1
`, t) - } -} - -func Test_Mixin_NoArguments(t *testing.T) { - res, err := run(` - mixin a() - p Testing - - +a()`, nil) - - if err != nil { - t.Fatal(err.Error()) - } else { - expect(res, `Testing
`, t) - } -} - -func Test_Mixin_MultiArguments(t *testing.T) { - res, err := run(` - mixin a($a, $b, $c, $d) - p #{$a} #{$b} #{$c} #{$d} - - +a("a", "b", "c", A)`, map[string]int{"A": 2}) - - if err != nil { - t.Fatal(err.Error()) - } else { - expect(res, `a b c 2
`, t) - } -} - -func Test_ClassName(t *testing.T) { - res, err := run(`div.test - p.test1.test2 - [class=$] - .test3`, "test4") - - if err != nil { - t.Fatal(err.Error()) - } else { - expect(res, `This is C
", t) -} - -func Failing_Test_CompileDir(t *testing.T) { - tmpl, err := CompileDir("samples/", DefaultDirOptions, DefaultOptions) - - // Test Compilation - if err != nil { - t.Fatal(err.Error()) - } - - // Make sure files are added to map correctly - val1, ok := tmpl["basic"] - if ok != true || val1 == nil { - t.Fatal("CompileDir, template not found.") - } - val2, ok := tmpl["inherit"] - if ok != true || val2 == nil { - t.Fatal("CompileDir, template not found.") - } - val3, ok := tmpl["compiledir_test/basic"] - if ok != true || val3 == nil { - t.Fatal("CompileDir, template not found.") - } - val4, ok := tmpl["compiledir_test/compiledir_test/basic"] - if ok != true || val4 == nil { - t.Fatal("CompileDir, template not found.") - } - - // Make sure file parsing is the same - var doc1, doc2 bytes.Buffer - val1.Execute(&doc1, nil) - val4.Execute(&doc2, nil) - expect(doc1.String(), doc2.String(), t) - - // Check against CompileFile - compilefile, err := CompileFile("samples/basic.amber", DefaultOptions) - if err != nil { - t.Fatal(err.Error()) - } - var doc3 bytes.Buffer - compilefile.Execute(&doc3, nil) - expect(doc1.String(), doc3.String(), t) - expect(doc2.String(), doc3.String(), t) - -} - -func Benchmark_Parse(b *testing.B) { - code := ` - !!! 5 - html - head - title Test Title - body - nav#mainNav[data-foo="bar"] - div#content - div.left - div.center - block center - p Main Content - .long ? somevar && someothervar - div.right` - - for i := 0; i < b.N; i++ { - cmp := New() - cmp.Parse(code) - } -} - -func Benchmark_Compile(b *testing.B) { - b.StopTimer() - - code := ` - !!! 5 - html - head - title Test Title - body - nav#mainNav[data-foo="bar"] - div#content - div.left - div.center - block center - p Main Content - .long ? somevar && someothervar - div.right` - - cmp := New() - cmp.Parse(code) - - b.StartTimer() - - for i := 0; i < b.N; i++ { - cmp.CompileString() - } -} - -func expect(cur, expected string, t *testing.T) { - if cur != expected { - t.Fatalf("Expected {%s} got {%s}.", expected, cur) - } -} - -func run(tpl string, data interface{}) (string, error) { - t, err := Compile(tpl, Options{false, false}) - if err != nil { - return "", err - } - var buf bytes.Buffer - if err = t.Execute(&buf, data); err != nil { - return "", err - } - return strings.TrimSpace(buf.String()), nil -} diff --git a/vendor/github.com/eknkc/amber/amberc/cli.go b/vendor/github.com/eknkc/amber/amberc/cli.go deleted file mode 100644 index 4ce316336..000000000 --- a/vendor/github.com/eknkc/amber/amberc/cli.go +++ /dev/null @@ -1,48 +0,0 @@ -package main - -import ( - "flag" - "fmt" - amber "github.com/eknkc/amber" - "os" -) - -var prettyPrint bool -var lineNumbers bool - -func init() { - flag.BoolVar(&prettyPrint, "prettyprint", true, "Use pretty indentation in output html.") - flag.BoolVar(&prettyPrint, "pp", true, "Use pretty indentation in output html.") - - flag.BoolVar(&lineNumbers, "linenos", true, "Enable debugging information in output html.") - flag.BoolVar(&lineNumbers, "ln", true, "Enable debugging information in output html.") - - flag.Parse() -} - -func main() { - input := flag.Arg(0) - - if len(input) == 0 { - fmt.Fprintln(os.Stderr, "Please provide an input file. (amberc input.amber)") - os.Exit(1) - } - - cmp := amber.New() - cmp.PrettyPrint = prettyPrint - cmp.LineNumbers = lineNumbers - - err := cmp.ParseFile(input) - - if err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } - - err = cmp.CompileWriter(os.Stdout) - - if err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } -} diff --git a/vendor/github.com/eknkc/amber/samples/basic.amber b/vendor/github.com/eknkc/amber/samples/basic.amber deleted file mode 100644 index 96f73271b..000000000 --- a/vendor/github.com/eknkc/amber/samples/basic.amber +++ /dev/null @@ -1,28 +0,0 @@ -!!! 5 -html - head - title Hello - - meta[name="description"][value="This is a sample"] - - script[type="text/javascript"] - var hw = "Hello World!" - alert(hw) - - style[type="text/css"] - body { - background: maroon; - color: white - } - - body - header#mainHeader - ul - li.active - a[href="/"] Main Page - [title="Main Page"] - - footer - | Hey - br - | There diff --git a/vendor/github.com/eknkc/amber/samples/compiledir_test/basic.amber b/vendor/github.com/eknkc/amber/samples/compiledir_test/basic.amber deleted file mode 100644 index 96f73271b..000000000 --- a/vendor/github.com/eknkc/amber/samples/compiledir_test/basic.amber +++ /dev/null @@ -1,28 +0,0 @@ -!!! 5 -html - head - title Hello - - meta[name="description"][value="This is a sample"] - - script[type="text/javascript"] - var hw = "Hello World!" - alert(hw) - - style[type="text/css"] - body { - background: maroon; - color: white - } - - body - header#mainHeader - ul - li.active - a[href="/"] Main Page - [title="Main Page"] - - footer - | Hey - br - | There diff --git a/vendor/github.com/eknkc/amber/samples/compiledir_test/compiledir_test/basic.amber b/vendor/github.com/eknkc/amber/samples/compiledir_test/compiledir_test/basic.amber deleted file mode 100644 index 96f73271b..000000000 --- a/vendor/github.com/eknkc/amber/samples/compiledir_test/compiledir_test/basic.amber +++ /dev/null @@ -1,28 +0,0 @@ -!!! 5 -html - head - title Hello - - meta[name="description"][value="This is a sample"] - - script[type="text/javascript"] - var hw = "Hello World!" - alert(hw) - - style[type="text/css"] - body { - background: maroon; - color: white - } - - body - header#mainHeader - ul - li.active - a[href="/"] Main Page - [title="Main Page"] - - footer - | Hey - br - | There diff --git a/vendor/github.com/eknkc/amber/samples/inherit.amber b/vendor/github.com/eknkc/amber/samples/inherit.amber deleted file mode 100644 index afb38bb60..000000000 --- a/vendor/github.com/eknkc/amber/samples/inherit.amber +++ /dev/null @@ -1,11 +0,0 @@ -extends inherit.master.amber - -block append meta - meta[name="keywords"][content="These are added by the child template"] - -block menu - li Item 1 - li Item 2 - -block content - p Content from child template diff --git a/vendor/github.com/eknkc/amber/samples/inherit.master.amber b/vendor/github.com/eknkc/amber/samples/inherit.master.amber deleted file mode 100644 index 66cf82cd7..000000000 --- a/vendor/github.com/eknkc/amber/samples/inherit.master.amber +++ /dev/null @@ -1,16 +0,0 @@ -!!! transitional -html - head - title Hello - - block meta - meta[name="description"][value="This is a sample"] - - body - header#mainHeader - ul - block menu - - div#content - block content - diff --git a/vendor/github.com/eknkc/amber/samples/multilevel.inheritance.a.amber b/vendor/github.com/eknkc/amber/samples/multilevel.inheritance.a.amber deleted file mode 100644 index 2e2c45ac4..000000000 --- a/vendor/github.com/eknkc/amber/samples/multilevel.inheritance.a.amber +++ /dev/null @@ -1,2 +0,0 @@ -block overwriteme - p This is A diff --git a/vendor/github.com/eknkc/amber/samples/multilevel.inheritance.b.amber b/vendor/github.com/eknkc/amber/samples/multilevel.inheritance.b.amber deleted file mode 100644 index 23b699f52..000000000 --- a/vendor/github.com/eknkc/amber/samples/multilevel.inheritance.b.amber +++ /dev/null @@ -1,4 +0,0 @@ -extends multilevel.inheritance.a.amber - -block overwriteme - p This is B diff --git a/vendor/github.com/eknkc/amber/samples/multilevel.inheritance.c.amber b/vendor/github.com/eknkc/amber/samples/multilevel.inheritance.c.amber deleted file mode 100644 index 3cce2ee93..000000000 --- a/vendor/github.com/eknkc/amber/samples/multilevel.inheritance.c.amber +++ /dev/null @@ -1,4 +0,0 @@ -extends multilevel.inheritance.b.amber - -block overwriteme - p This is C diff --git a/vendor/github.com/elazarl/go-bindata-assetfs/go-bindata-assetfs/main.go b/vendor/github.com/elazarl/go-bindata-assetfs/go-bindata-assetfs/main.go deleted file mode 100644 index a5b2b5eef..000000000 --- a/vendor/github.com/elazarl/go-bindata-assetfs/go-bindata-assetfs/main.go +++ /dev/null @@ -1,97 +0,0 @@ -package main - -import ( - "bufio" - "bytes" - "flag" - "fmt" - "os" - "os/exec" - "strings" -) - -const bindatafile = "bindata.go" - -func isDebug(args []string) bool { - flagset := flag.NewFlagSet("", flag.ContinueOnError) - debug := flagset.Bool("debug", false, "") - debugArgs := make([]string, 0) - for _, arg := range args { - if strings.HasPrefix(arg, "-debug") { - debugArgs = append(debugArgs, arg) - } - } - flagset.Parse(debugArgs) - if debug == nil { - return false - } - return *debug -} - -func main() { - if _, err := exec.LookPath("go-bindata"); err != nil { - fmt.Println("Cannot find go-bindata executable in path") - fmt.Println("Maybe you need: go get github.com/elazarl/go-bindata-assetfs/...") - os.Exit(1) - } - cmd := exec.Command("go-bindata", os.Args[1:]...) - cmd.Stdin = os.Stdin - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - if err := cmd.Run(); err != nil { - os.Exit(1) - } - in, err := os.Open(bindatafile) - if err != nil { - fmt.Fprintln(os.Stderr, "Cannot read", bindatafile, err) - return - } - out, err := os.Create("bindata_assetfs.go") - if err != nil { - fmt.Fprintln(os.Stderr, "Cannot write 'bindata_assetfs.go'", err) - return - } - debug := isDebug(os.Args[1:]) - r := bufio.NewReader(in) - done := false - for line, isPrefix, err := r.ReadLine(); err == nil; line, isPrefix, err = r.ReadLine() { - if !isPrefix { - line = append(line, '\n') - } - if _, err := out.Write(line); err != nil { - fmt.Fprintln(os.Stderr, "Cannot write to 'bindata_assetfs.go'", err) - return - } - if !done && !isPrefix && bytes.HasPrefix(line, []byte("import (")) { - if debug { - fmt.Fprintln(out, "\t\"net/http\"") - } else { - fmt.Fprintln(out, "\t\"github.com/elazarl/go-bindata-assetfs\"") - } - done = true - } - } - if debug { - fmt.Fprintln(out, ` -func assetFS() http.FileSystem { - for k := range _bintree.Children { - return http.Dir(k) - } - panic("unreachable") -}`) - } else { - fmt.Fprintln(out, ` -func assetFS() *assetfs.AssetFS { - for k := range _bintree.Children { - return &assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: k} - } - panic("unreachable") -}`) - } - // Close files BEFORE remove calls (don't use defer). - in.Close() - out.Close() - if err := os.Remove(bindatafile); err != nil { - fmt.Fprintln(os.Stderr, "Cannot remove", bindatafile, err) - } -} diff --git a/vendor/github.com/dustin/go-broadcast/LICENSE b/vendor/github.com/franela/goblin/LICENSE similarity index 94% rename from vendor/github.com/dustin/go-broadcast/LICENSE rename to vendor/github.com/franela/goblin/LICENSE index b01ef8026..b2d652206 100644 --- a/vendor/github.com/dustin/go-broadcast/LICENSE +++ b/vendor/github.com/franela/goblin/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2013 Dustin Sallings +Copyright (c) 2013 Marcos Lilljedahl and Jonathan Leibiusky Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/github.com/franela/goblin/Makefile b/vendor/github.com/franela/goblin/Makefile new file mode 100644 index 000000000..66763dc8c --- /dev/null +++ b/vendor/github.com/franela/goblin/Makefile @@ -0,0 +1,3 @@ +export GOPATH=$(shell pwd) +test: + go test -v diff --git a/vendor/github.com/franela/goblin/README.md b/vendor/github.com/franela/goblin/README.md new file mode 100644 index 000000000..d9f847e10 --- /dev/null +++ b/vendor/github.com/franela/goblin/README.md @@ -0,0 +1,141 @@ +[](https://travis-ci.org/franela/goblin) +Goblin +====== + + + +A [Mocha](http://visionmedia.github.io/mocha/) like BDD testing framework for Go + +No extensive documentation nor complicated steps to get it running + +Run tests as usual with `go test` + +Colorful reports and beautiful syntax + + +Why Goblin? +----------- + +Inspired by the flexibility and simplicity of Node BDD and frustrated by the +rigorousness of Go way of testing, we wanted to bring a new tool to +write self-describing and comprehensive code. + + + +What do I get with it? +---------------------- + +- Preserve the exact same syntax and behaviour as Node's Mocha +- Nest as many `Describe` and `It` blocks as you want +- Use `Before`, `BeforeEach`, `After` and `AfterEach` for setup and teardown your tests +- No need to remember confusing parameters in `Describe` and `It` blocks +- Use a declarative and expressive language to write your tests +- Plug different assertion libraries ([Gomega](https://github.com/onsi/gomega) supported so far) +- Skip your tests the same way as you would do in Mocha +- Automatic terminal support for colored outputs +- Two line setup is all you need to get up running + + + +How do I use it? +---------------- + +Since ```go test``` is not currently extensive, you will have to hook Goblin to it. You do that by +adding a single test method in your test file. All your goblin tests will be implemented inside this function. + +```go +package foobar + +import ( + "testing" + . "github.com/franela/goblin" +) + +func Test(t *testing.T) { + g := Goblin(t) + g.Describe("Numbers", func() { + g.It("Should add two numbers ", func() { + g.Assert(1+1).Equal(2) + }) + g.It("Should match equal numbers", func() { + g.Assert(2).Equal(4) + }) + g.It("Should substract two numbers") + }) +} +``` + +Ouput will be something like: + + + +Nice and easy, right? + +Can I do asynchronous tests? +---------------------------- + +Yes! Goblin will help you to test asynchronous things, like goroutines, etc. You just need to add a ```done``` parameter to the handler function of your ```It```. This handler function should be called when your test passes. + +```go + ... + g.Describe("Numbers", func() { + g.It("Should add two numbers asynchronously", func(done Done) { + go func() { + g.Assert(1+1).Equal(2) + done() + }() + }) + }) + ... +``` + +Goblin will wait for the ```done``` call, a ```Fail``` call or any false assertion. + +How do I use it with Gomega? +---------------------------- + +Gomega is a nice assertion framework. But it doesn't provide a nice way to hook it to testing frameworks. It should just panic instead of requiring a fail function. There is an issue about that [here](https://github.com/onsi/gomega/issues/5). +While this is being discussed and hopefully fixed, the way to use Gomega with Goblin is: + +```go +package foobar + +import ( + "testing" + . "github.com/franela/goblin" + . "github.com/onsi/gomega" +) + +func Test(t *testing.T) { + g := Goblin(t) + + //special hook for gomega + RegisterFailHandler(func(m string, _ ...int) { g.Fail(m) }) + + g.Describe("lala", func() { + g.It("lslslslsls", func() { + Expect(1).To(Equal(10)) + }) + }) +} +``` + + +FAQ: +---- + +### How do I run specific tests? + +If `-goblin.run=$REGES` is supplied to the `go test` command then only tests that match the supplied regex will run + + +TODO: +----- + +We do have a couple of [issues](https://github.com/franela/goblin/issues) pending we'll be addressing soon. But feel free to +contribute and send us PRs (with tests please :smile:). + +Contributions: +------------ + +Special thanks to [Leandro Reox](https://github.com/leandroreox) (Leitan) for the goblin logo. diff --git a/vendor/github.com/franela/goblin/assertions.go b/vendor/github.com/franela/goblin/assertions.go new file mode 100644 index 000000000..5ccae7daf --- /dev/null +++ b/vendor/github.com/franela/goblin/assertions.go @@ -0,0 +1,59 @@ +package goblin + +import ( + "fmt" + "reflect" + "strings" +) + +type Assertion struct { + src interface{} + fail func(interface{}) +} + +func objectsAreEqual(a, b interface{}) bool { + if reflect.TypeOf(a) != reflect.TypeOf(b) { + return false + } + + if reflect.DeepEqual(a, b) { + return true + } + + if fmt.Sprintf("%#v", a) == fmt.Sprintf("%#v", b) { + return true + } + + return false +} + +func formatMessages(messages ...string) string { + if len(messages) > 0 { + return ", " + strings.Join(messages, " ") + } + return "" +} + +func (a *Assertion) Eql(dst interface{}) { + a.Equal(dst) +} + +func (a *Assertion) Equal(dst interface{}) { + if !objectsAreEqual(a.src, dst) { + a.fail(fmt.Sprintf("%#v %s %#v", a.src, "does not equal", dst)) + } +} + +func (a *Assertion) IsTrue(messages ...string) { + if !objectsAreEqual(a.src, true) { + message := fmt.Sprintf("%v %s%s", a.src, "expected false to be truthy", formatMessages(messages...)) + a.fail(message) + } +} + +func (a *Assertion) IsFalse(messages ...string) { + if !objectsAreEqual(a.src, false) { + message := fmt.Sprintf("%v %s%s", a.src, "expected true to be falsey", formatMessages(messages...)) + a.fail(message) + } +} diff --git a/vendor/github.com/franela/goblin/goblin.go b/vendor/github.com/franela/goblin/goblin.go new file mode 100644 index 000000000..e029548bc --- /dev/null +++ b/vendor/github.com/franela/goblin/goblin.go @@ -0,0 +1,294 @@ +package goblin + +import ( + "flag" + "fmt" + "regexp" + "runtime" + "sync" + "testing" + "time" +) + +type Done func(error ...interface{}) + +type Runnable interface { + run(*G) bool +} + +func (g *G) Describe(name string, h func()) { + d := &Describe{name: name, h: h, parent: g.parent} + + if d.parent != nil { + d.parent.children = append(d.parent.children, Runnable(d)) + } + + g.parent = d + + h() + + g.parent = d.parent + + if g.parent == nil && d.hasTests { + g.reporter.begin() + if d.run(g) { + g.t.Fail() + } + g.reporter.end() + } +} + +type Describe struct { + name string + h func() + children []Runnable + befores []func() + afters []func() + afterEach []func() + beforeEach []func() + hasTests bool + parent *Describe +} + +func (d *Describe) runBeforeEach() { + if d.parent != nil { + d.parent.runBeforeEach() + } + + for _, b := range d.beforeEach { + b() + } +} + +func (d *Describe) runAfterEach() { + + if d.parent != nil { + d.parent.runAfterEach() + } + + for _, a := range d.afterEach { + a() + } +} + +func (d *Describe) run(g *G) bool { + failed := false + if d.hasTests { + g.reporter.beginDescribe(d.name) + + for _, b := range d.befores { + b() + } + + for _, r := range d.children { + if r.run(g) { + failed = true + } + } + + for _, a := range d.afters { + a() + } + + g.reporter.endDescribe() + } + + return failed +} + +type Failure struct { + stack []string + testName string + message string +} + +type It struct { + h interface{} + name string + parent *Describe + failure *Failure + reporter Reporter + isAsync bool +} + +func (it *It) run(g *G) bool { + g.currentIt = it + + if it.h == nil { + g.reporter.itIsPending(it.name) + return false + } + //TODO: should handle errors for beforeEach + it.parent.runBeforeEach() + + runIt(g, it.h) + + it.parent.runAfterEach() + + failed := false + if it.failure != nil { + failed = true + } + + if failed { + g.reporter.itFailed(it.name) + g.reporter.failure(it.failure) + } else { + g.reporter.itPassed(it.name) + } + return failed +} + +func (it *It) failed(msg string, stack []string) { + it.failure = &Failure{stack: stack, message: msg, testName: it.parent.name + " " + it.name} +} + +func parseFlags() { + //Flag parsing + flag.Parse() + if *regexParam != "" { + runRegex = regexp.MustCompile(*regexParam) + } else { + runRegex = nil + } +} + +var timeout = flag.Duration("goblin.timeout", 5*time.Second, "Sets default timeouts for all tests") +var isTty = flag.Bool("goblin.tty", true, "Sets the default output format (color / monochrome)") +var regexParam = flag.String("goblin.run", "", "Runs only tests which match the supplied regex") +var runRegex *regexp.Regexp + +func init() { + parseFlags() +} + +func Goblin(t *testing.T, arguments ...string) *G { + g := &G{t: t, timeout: *timeout} + var fancy TextFancier + if *isTty { + fancy = &TerminalFancier{} + } else { + fancy = &Monochrome{} + } + + g.reporter = Reporter(&DetailedReporter{fancy: fancy}) + return g +} + +func runIt(g *G, h interface{}) { + defer timeTrack(time.Now(), g) + g.mutex.Lock() + g.timedOut = false + g.mutex.Unlock() + g.shouldContinue = make(chan bool) + if call, ok := h.(func()); ok { + // the test is synchronous + go func(c chan bool) { call(); c <- true }(g.shouldContinue) + } else if call, ok := h.(func(Done)); ok { + doneCalled := 0 + go func(c chan bool) { + call(func(msg ...interface{}) { + if len(msg) > 0 { + g.Fail(msg) + } else { + doneCalled++ + if doneCalled > 1 { + g.Fail("Done called multiple times") + } + c <- true + } + }) + }(g.shouldContinue) + } else { + panic("Not implemented.") + } + select { + case <-g.shouldContinue: + case <-time.After(g.timeout): + //Set to nil as it shouldn't continue + g.shouldContinue = nil + g.timedOut = true + g.Fail("Test exceeded " + fmt.Sprintf("%s", g.timeout)) + } +} + +type G struct { + t *testing.T + parent *Describe + currentIt *It + timeout time.Duration + reporter Reporter + timedOut bool + shouldContinue chan bool + mutex sync.Mutex +} + +func (g *G) SetReporter(r Reporter) { + g.reporter = r +} + +func (g *G) It(name string, h ...interface{}) { + if matchesRegex(name) { + it := &It{name: name, parent: g.parent, reporter: g.reporter} + notifyParents(g.parent) + if len(h) > 0 { + it.h = h[0] + } + g.parent.children = append(g.parent.children, Runnable(it)) + } +} + +func matchesRegex(value string) bool { + if runRegex != nil { + return runRegex.MatchString(value) + } + return true +} + +func notifyParents(d *Describe) { + d.hasTests = true + if d.parent != nil { + notifyParents(d.parent) + } +} + +func (g *G) Before(h func()) { + g.parent.befores = append(g.parent.befores, h) +} + +func (g *G) BeforeEach(h func()) { + g.parent.beforeEach = append(g.parent.beforeEach, h) +} + +func (g *G) After(h func()) { + g.parent.afters = append(g.parent.afters, h) +} + +func (g *G) AfterEach(h func()) { + g.parent.afterEach = append(g.parent.afterEach, h) +} + +func (g *G) Assert(src interface{}) *Assertion { + return &Assertion{src: src, fail: g.Fail} +} + +func timeTrack(start time.Time, g *G) { + g.reporter.itTook(time.Since(start)) +} + +func (g *G) Fail(error interface{}) { + //Skips 7 stacks due to the functions between the stack and the test + stack := ResolveStack(4) + message := fmt.Sprintf("%v", error) + g.currentIt.failed(message, stack) + if g.shouldContinue != nil { + g.shouldContinue <- true + } + g.mutex.Lock() + defer g.mutex.Unlock() + if !g.timedOut { + //Stop test function execution + runtime.Goexit() + } + +} diff --git a/vendor/github.com/franela/goblin/goblin_logo.jpg b/vendor/github.com/franela/goblin/goblin_logo.jpg new file mode 100644 index 000000000..44534f297 Binary files /dev/null and b/vendor/github.com/franela/goblin/goblin_logo.jpg differ diff --git a/vendor/github.com/franela/goblin/goblin_output.png b/vendor/github.com/franela/goblin/goblin_output.png new file mode 100644 index 000000000..be3c9ea7a Binary files /dev/null and b/vendor/github.com/franela/goblin/goblin_output.png differ diff --git a/vendor/github.com/franela/goblin/mono_reporter.go b/vendor/github.com/franela/goblin/mono_reporter.go new file mode 100644 index 000000000..04d6e5e3a --- /dev/null +++ b/vendor/github.com/franela/goblin/mono_reporter.go @@ -0,0 +1,26 @@ +package goblin + +import () + +type Monochrome struct { +} + +func (self *Monochrome) Red(text string) string { + return "!" + text +} + +func (self *Monochrome) Gray(text string) string { + return text +} + +func (self *Monochrome) Cyan(text string) string { + return text +} + +func (self *Monochrome) WithCheck(text string) string { + return ">>>" + text +} + +func (self *Monochrome) Green(text string) string { + return text +} diff --git a/vendor/github.com/franela/goblin/reporting.go b/vendor/github.com/franela/goblin/reporting.go new file mode 100644 index 000000000..1d67d662d --- /dev/null +++ b/vendor/github.com/franela/goblin/reporting.go @@ -0,0 +1,137 @@ +package goblin + +import ( + "fmt" + "strconv" + "strings" + "time" +) + +type Reporter interface { + beginDescribe(string) + endDescribe() + begin() + end() + failure(*Failure) + itTook(time.Duration) + itFailed(string) + itPassed(string) + itIsPending(string) +} + +type TextFancier interface { + Red(text string) string + Gray(text string) string + Cyan(text string) string + Green(text string) string + WithCheck(text string) string +} + +type DetailedReporter struct { + level, failed, passed, pending int + failures []*Failure + executionTime, totalExecutionTime time.Duration + fancy TextFancier +} + +func (r *DetailedReporter) SetTextFancier(f TextFancier) { + r.fancy = f +} + +type TerminalFancier struct { +} + +func (self *TerminalFancier) Red(text string) string { + return "\033[31m" + text + "\033[0m" +} + +func (self *TerminalFancier) Gray(text string) string { + return "\033[90m" + text + "\033[0m" +} + +func (self *TerminalFancier) Cyan(text string) string { + return "\033[36m" + text + "\033[0m" +} + +func (self *TerminalFancier) Green(text string) string { + return "\033[32m" + text + "\033[0m" +} + +func (self *TerminalFancier) WithCheck(text string) string { + return "\033[32m\u2713\033[0m " + text +} + +func (r *DetailedReporter) getSpace() string { + return strings.Repeat(" ", (r.level+1)*2) +} + +func (r *DetailedReporter) failure(failure *Failure) { + r.failures = append(r.failures, failure) +} + +func (r *DetailedReporter) print(text string) { + fmt.Printf("%v%v\n", r.getSpace(), text) +} + +func (r *DetailedReporter) printWithCheck(text string) { + fmt.Printf("%v%v\n", r.getSpace(), r.fancy.WithCheck(text)) +} + +func (r *DetailedReporter) beginDescribe(name string) { + fmt.Println("") + r.print(name) + r.level++ +} + +func (r *DetailedReporter) endDescribe() { + r.level-- +} + +func (r *DetailedReporter) itTook(duration time.Duration) { + r.executionTime = duration + r.totalExecutionTime += duration +} + +func (r *DetailedReporter) itFailed(name string) { + r.failed++ + r.print(r.fancy.Red(strconv.Itoa(r.failed) + ") " + name)) +} + +func (r *DetailedReporter) itPassed(name string) { + r.passed++ + r.printWithCheck(r.fancy.Gray(name)) +} + +func (r *DetailedReporter) itIsPending(name string) { + r.pending++ + r.print(r.fancy.Cyan("- " + name)) +} + +func (r *DetailedReporter) begin() { +} + +func (r *DetailedReporter) end() { + comp := fmt.Sprintf("%d tests complete", r.passed) + t := fmt.Sprintf("(%d ms)", r.totalExecutionTime/time.Millisecond) + + //fmt.Printf("\n\n \033[32m%d tests complete\033[0m \033[90m(%d ms)\033[0m\n", r.passed, r.totalExecutionTime/time.Millisecond) + fmt.Printf("\n\n %v %v\n", r.fancy.Green(comp), r.fancy.Gray(t)) + + if r.pending > 0 { + pend := fmt.Sprintf("%d test(s) pending", r.pending) + fmt.Printf(" %v\n\n", r.fancy.Cyan(pend)) + } + + if len(r.failures) > 0 { + fmt.Printf("%s \n\n", r.fancy.Red(fmt.Sprintf(" %d tests failed:", len(r.failures)))) + + } + + for i, failure := range r.failures { + fmt.Printf(" %d) %s:\n\n", i+1, failure.testName) + fmt.Printf(" %s\n", r.fancy.Red(failure.message)) + for _, stackItem := range failure.stack { + fmt.Printf(" %s\n", r.fancy.Gray(stackItem)) + } + } +} diff --git a/vendor/github.com/franela/goblin/resolver.go b/vendor/github.com/franela/goblin/resolver.go new file mode 100644 index 000000000..125fcec9c --- /dev/null +++ b/vendor/github.com/franela/goblin/resolver.go @@ -0,0 +1,21 @@ +package goblin + +import ( + "runtime/debug" + "strings" +) + +func ResolveStack(skip int) []string { + return cleanStack(debug.Stack(), skip) +} + +func cleanStack(stack []byte, skip int) []string { + arrayStack := strings.Split(string(stack), "\n") + var finalStack []string + for i := skip; i < len(arrayStack); i++ { + if strings.Contains(arrayStack[i], ".go") { + finalStack = append(finalStack, arrayStack[i]) + } + } + return finalStack +} diff --git a/vendor/github.com/getsentry/raven-go/Dockerfile.test b/vendor/github.com/getsentry/raven-go/Dockerfile.test deleted file mode 100644 index e0aa037b1..000000000 --- a/vendor/github.com/getsentry/raven-go/Dockerfile.test +++ /dev/null @@ -1,11 +0,0 @@ -FROM golang:1.4 - -RUN mkdir -p /go/src/github.com/getsentry/raven-go -WORKDIR /go/src/github.com/getsentry/raven-go -ENV GOPATH /go - -RUN go install -race std && go get golang.org/x/tools/cmd/cover - -COPY . /go/src/github.com/getsentry/raven-go - -CMD ["./runtests.sh"] diff --git a/vendor/github.com/getsentry/raven-go/README.md b/vendor/github.com/getsentry/raven-go/README.md deleted file mode 100644 index a5373ce87..000000000 --- a/vendor/github.com/getsentry/raven-go/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# raven [](https://travis-ci.org/getsentry/raven-go) - -raven is a Go client for the [Sentry](https://github.com/getsentry/sentry) -event/error logging system. - -[**Documentation**](http://godoc.org/github.com/getsentry/raven-go). - -## Installation - -```text -go get github.com/getsentry/raven-go -``` diff --git a/vendor/github.com/getsentry/raven-go/client.go b/vendor/github.com/getsentry/raven-go/client.go deleted file mode 100644 index f514c7456..000000000 --- a/vendor/github.com/getsentry/raven-go/client.go +++ /dev/null @@ -1,683 +0,0 @@ -// Package raven implements a client for the Sentry error logging service. -package raven - -import ( - "bytes" - "compress/zlib" - "crypto/rand" - "encoding/base64" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "os" - "runtime" - "strings" - "sync" - "time" -) - -const ( - userAgent = "raven-go/1.0" - timestampFormat = `"2006-01-02T15:04:05"` -) - -var ( - ErrPacketDropped = errors.New("raven: packet dropped") - ErrUnableToUnmarshalJSON = errors.New("raven: unable to unmarshal JSON") - ErrMissingUser = errors.New("raven: dsn missing public key and/or password") - ErrMissingPrivateKey = errors.New("raven: dsn missing private key") - ErrMissingProjectID = errors.New("raven: dsn missing project id") -) - -type Severity string - -// http://docs.python.org/2/howto/logging.html#logging-levels -const ( - DEBUG = Severity("debug") - INFO = Severity("info") - WARNING = Severity("warning") - ERROR = Severity("error") - FATAL = Severity("fatal") -) - -type Timestamp time.Time - -func (t Timestamp) MarshalJSON() ([]byte, error) { - return []byte(time.Time(t).UTC().Format(timestampFormat)), nil -} - -func (timestamp *Timestamp) UnmarshalJSON(data []byte) error { - t, err := time.Parse(timestampFormat, string(data)) - if err != nil { - return err - } - - *timestamp = Timestamp(t) - return nil -} - -// An Interface is a Sentry interface that will be serialized as JSON. -// It must implement json.Marshaler or use json struct tags. -type Interface interface { - // The Sentry class name. Example: sentry.interfaces.Stacktrace - Class() string -} - -type Culpriter interface { - Culprit() string -} - -type Transport interface { - Send(url, authHeader string, packet *Packet) error -} - -type outgoingPacket struct { - packet *Packet - ch chan error -} - -type Tag struct { - Key string - Value string -} - -type Tags []Tag - -func (tag *Tag) MarshalJSON() ([]byte, error) { - return json.Marshal([2]string{tag.Key, tag.Value}) -} - -func (t *Tag) UnmarshalJSON(data []byte) error { - var tag [2]string - if err := json.Unmarshal(data, &tag); err != nil { - return err - } - *t = Tag{tag[0], tag[1]} - return nil -} - -func (t *Tags) UnmarshalJSON(data []byte) error { - var tags []Tag - - switch data[0] { - case '[': - // Unmarshal into []Tag - if err := json.Unmarshal(data, &tags); err != nil { - return err - } - case '{': - // Unmarshal into map[string]string - tagMap := make(map[string]string) - if err := json.Unmarshal(data, &tagMap); err != nil { - return err - } - - // Convert to []Tag - for k, v := range tagMap { - tags = append(tags, Tag{k, v}) - } - default: - return ErrUnableToUnmarshalJSON - } - - *t = tags - return nil -} - -// http://sentry.readthedocs.org/en/latest/developer/client/index.html#building-the-json-packet -type Packet struct { - // Required - Message string `json:"message"` - - // Required, set automatically by Client.Send/Report via Packet.Init if blank - EventID string `json:"event_id"` - Project string `json:"project"` - Timestamp Timestamp `json:"timestamp"` - Level Severity `json:"level"` - Logger string `json:"logger"` - - // Optional - Platform string `json:"platform,omitempty"` - Culprit string `json:"culprit,omitempty"` - ServerName string `json:"server_name,omitempty"` - Release string `json:"release,omitempty"` - Tags Tags `json:"tags,omitempty"` - Modules []map[string]string `json:"modules,omitempty"` - Extra map[string]interface{} `json:"extra,omitempty"` - - Interfaces []Interface `json:"-"` -} - -// NewPacket constructs a packet with the specified message and interfaces. -func NewPacket(message string, interfaces ...Interface) *Packet { - extra := map[string]interface{}{ - "runtime.Version": runtime.Version(), - "runtime.NumCPU": runtime.NumCPU(), - "runtime.GOMAXPROCS": runtime.GOMAXPROCS(0), // 0 just returns the current value - "runtime.NumGoroutine": runtime.NumGoroutine(), - } - return &Packet{ - Message: message, - Interfaces: interfaces, - Extra: extra, - } -} - -// Init initializes required fields in a packet. It is typically called by -// Client.Send/Report automatically. -func (packet *Packet) Init(project string) error { - if packet.Project == "" { - packet.Project = project - } - if packet.EventID == "" { - var err error - packet.EventID, err = uuid() - if err != nil { - return err - } - } - if time.Time(packet.Timestamp).IsZero() { - packet.Timestamp = Timestamp(time.Now()) - } - if packet.Level == "" { - packet.Level = ERROR - } - if packet.Logger == "" { - packet.Logger = "root" - } - if packet.ServerName == "" { - packet.ServerName = hostname - } - if packet.Platform == "" { - packet.Platform = "go" - } - - if packet.Culprit == "" { - for _, inter := range packet.Interfaces { - if c, ok := inter.(Culpriter); ok { - packet.Culprit = c.Culprit() - if packet.Culprit != "" { - break - } - } - } - } - - return nil -} - -func (packet *Packet) AddTags(tags map[string]string) { - for k, v := range tags { - packet.Tags = append(packet.Tags, Tag{k, v}) - } -} - -func uuid() (string, error) { - id := make([]byte, 16) - _, err := io.ReadFull(rand.Reader, id) - if err != nil { - return "", err - } - id[6] &= 0x0F // clear version - id[6] |= 0x40 // set version to 4 (random uuid) - id[8] &= 0x3F // clear variant - id[8] |= 0x80 // set to IETF variant - return hex.EncodeToString(id), nil -} - -func (packet *Packet) JSON() []byte { - packetJSON, _ := json.Marshal(packet) - - interfaces := make(map[string]Interface, len(packet.Interfaces)) - for _, inter := range packet.Interfaces { - interfaces[inter.Class()] = inter - } - - if len(interfaces) > 0 { - interfaceJSON, _ := json.Marshal(interfaces) - packetJSON[len(packetJSON)-1] = ',' - packetJSON = append(packetJSON, interfaceJSON[1:]...) - } - - return packetJSON -} - -type context struct { - user *User - http *Http - tags map[string]string -} - -func (c *context) SetUser(u *User) { c.user = u } -func (c *context) SetHttp(h *Http) { c.http = h } -func (c *context) SetTags(t map[string]string) { - if c.tags == nil { - c.tags = make(map[string]string) - } - for k, v := range t { - c.tags[k] = v - } -} -func (c *context) Clear() { - c.user = nil - c.http = nil - c.tags = nil -} - -// Return a list of interfaces to be used in appending with the rest -func (c *context) interfaces() []Interface { - len, i := 0, 0 - if c.user != nil { - len++ - } - if c.http != nil { - len++ - } - interfaces := make([]Interface, len) - if c.user != nil { - interfaces[i] = c.user - i++ - } - if c.http != nil { - interfaces[i] = c.http - i++ - } - return interfaces -} - -// The maximum number of packets that will be buffered waiting to be delivered. -// Packets will be dropped if the buffer is full. Used by NewClient. -var MaxQueueBuffer = 100 - -func newClient(tags map[string]string) *Client { - client := &Client{ - Transport: &HTTPTransport{}, - Tags: tags, - context: &context{}, - queue: make(chan *outgoingPacket, MaxQueueBuffer), - } - go client.worker() - client.SetDSN(os.Getenv("SENTRY_DSN")) - return client -} - -// New constructs a new Sentry client instance -func New(dsn string) (*Client, error) { - client := newClient(nil) - return client, client.SetDSN(dsn) -} - -// NewWithTags constructs a new Sentry client instance with default tags. -func NewWithTags(dsn string, tags map[string]string) (*Client, error) { - client := newClient(tags) - return client, client.SetDSN(dsn) -} - -// NewClient constructs a Sentry client and spawns a background goroutine to -// handle packets sent by Client.Report. -// -// Deprecated: use New and NewWithTags instead -func NewClient(dsn string, tags map[string]string) (*Client, error) { - client := newClient(tags) - return client, client.SetDSN(dsn) -} - -// Client encapsulates a connection to a Sentry server. It must be initialized -// by calling NewClient. Modification of fields concurrently with Send or after -// calling Report for the first time is not thread-safe. -type Client struct { - Tags map[string]string - - Transport Transport - - // DropHandler is called when a packet is dropped because the buffer is full. - DropHandler func(*Packet) - - // Context that will get appending to all packets - context *context - - mu sync.RWMutex - url string - projectID string - authHeader string - release string - queue chan *outgoingPacket - - // A WaitGroup to keep track of all currently in-progress captures - // This is intended to be used with Client.Wait() to assure that - // all messages have been transported before exiting the process. - wg sync.WaitGroup -} - -// Initialize a default *Client instance -var DefaultClient = newClient(nil) - -// SetDSN updates a client with a new DSN. It safe to call after and -// concurrently with calls to Report and Send. -func (client *Client) SetDSN(dsn string) error { - if dsn == "" { - return nil - } - - client.mu.Lock() - defer client.mu.Unlock() - - uri, err := url.Parse(dsn) - if err != nil { - return err - } - - if uri.User == nil { - return ErrMissingUser - } - publicKey := uri.User.Username() - secretKey, ok := uri.User.Password() - if !ok { - return ErrMissingPrivateKey - } - uri.User = nil - - if idx := strings.LastIndex(uri.Path, "/"); idx != -1 { - client.projectID = uri.Path[idx+1:] - uri.Path = uri.Path[:idx+1] + "api/" + client.projectID + "/store/" - } - if client.projectID == "" { - return ErrMissingProjectID - } - - client.url = uri.String() - - client.authHeader = fmt.Sprintf("Sentry sentry_version=4, sentry_key=%s, sentry_secret=%s", publicKey, secretKey) - - return nil -} - -// Sets the DSN for the default *Client instance -func SetDSN(dsn string) error { return DefaultClient.SetDSN(dsn) } - -// SetRelease sets the "release" tag. -func (client *Client) SetRelease(release string) { - client.mu.Lock() - defer client.mu.Unlock() - client.release = release -} - -// SetRelease sets the "release" tag on the default *Client -func SetRelease(release string) { DefaultClient.SetRelease(release) } - -func (client *Client) worker() { - for outgoingPacket := range client.queue { - - client.mu.RLock() - url, authHeader := client.url, client.authHeader - client.mu.RUnlock() - - outgoingPacket.ch <- client.Transport.Send(url, authHeader, outgoingPacket.packet) - client.wg.Done() - } -} - -// Capture asynchronously delivers a packet to the Sentry server. It is a no-op -// when client is nil. A channel is provided if it is important to check for a -// send's success. -func (client *Client) Capture(packet *Packet, captureTags map[string]string) (eventID string, ch chan error) { - if client == nil { - return - } - - // Keep track of all running Captures so that we can wait for them all to finish - // *Must* call client.wg.Done() on any path that indicates that an event was - // finished being acted upon, whether success or failure - client.wg.Add(1) - - ch = make(chan error, 1) - - // Merge capture tags and client tags - packet.AddTags(captureTags) - packet.AddTags(client.Tags) - packet.AddTags(client.context.tags) - - // Initialize any required packet fields - client.mu.RLock() - projectID := client.projectID - release := client.release - client.mu.RUnlock() - - err := packet.Init(projectID) - if err != nil { - ch <- err - client.wg.Done() - return - } - packet.Release = release - - outgoingPacket := &outgoingPacket{packet, ch} - - select { - case client.queue <- outgoingPacket: - default: - // Send would block, drop the packet - if client.DropHandler != nil { - client.DropHandler(packet) - } - ch <- ErrPacketDropped - client.wg.Done() - } - - return packet.EventID, ch -} - -// Capture asynchronously delivers a packet to the Sentry server with the default *Client. -// It is a no-op when client is nil. A channel is provided if it is important to check for a -// send's success. -func Capture(packet *Packet, captureTags map[string]string) (eventID string, ch chan error) { - return DefaultClient.Capture(packet, captureTags) -} - -// CaptureMessage formats and delivers a string message to the Sentry server. -func (client *Client) CaptureMessage(message string, tags map[string]string, interfaces ...Interface) string { - if client == nil { - return "" - } - - packet := NewPacket(message, append(append(interfaces, client.context.interfaces()...), &Message{message, nil})...) - eventID, _ := client.Capture(packet, tags) - - return eventID -} - -// CaptureMessage formats and delivers a string message to the Sentry server with the default *Client -func CaptureMessage(message string, tags map[string]string, interfaces ...Interface) string { - return DefaultClient.CaptureMessage(message, tags, interfaces...) -} - -// CaptureMessageAndWait is identical to CaptureMessage except it blocks and waits for the message to be sent. -func (client *Client) CaptureMessageAndWait(message string, tags map[string]string, interfaces ...Interface) string { - if client == nil { - return "" - } - - packet := NewPacket(message, append(append(interfaces, client.context.interfaces()...), &Message{message, nil})...) - eventID, ch := client.Capture(packet, tags) - <-ch - - return eventID -} - -// CaptureMessageAndWait is identical to CaptureMessage except it blocks and waits for the message to be sent. -func CaptureMessageAndWait(message string, tags map[string]string, interfaces ...Interface) string { - return DefaultClient.CaptureMessageAndWait(message, tags, interfaces...) -} - -// CaptureErrors formats and delivers an error to the Sentry server. -// Adds a stacktrace to the packet, excluding the call to this method. -func (client *Client) CaptureError(err error, tags map[string]string, interfaces ...Interface) string { - if client == nil { - return "" - } - - packet := NewPacket(err.Error(), append(append(interfaces, client.context.interfaces()...), NewException(err, NewStacktrace(1, 3, nil)))...) - eventID, _ := client.Capture(packet, tags) - - return eventID -} - -// CaptureErrors formats and delivers an error to the Sentry server using the default *Client. -// Adds a stacktrace to the packet, excluding the call to this method. -func CaptureError(err error, tags map[string]string, interfaces ...Interface) string { - return DefaultClient.CaptureError(err, tags, interfaces...) -} - -// CaptureErrorAndWait is identical to CaptureError, except it blocks and assures that the event was sent -func (client *Client) CaptureErrorAndWait(err error, tags map[string]string, interfaces ...Interface) string { - if client == nil { - return "" - } - - packet := NewPacket(err.Error(), append(append(interfaces, client.context.interfaces()...), NewException(err, NewStacktrace(1, 3, nil)))...) - eventID, ch := client.Capture(packet, tags) - <-ch - - return eventID -} - -// CaptureErrorAndWait is identical to CaptureError, except it blocks and assures that the event was sent -func CaptureErrorAndWait(err error, tags map[string]string, interfaces ...Interface) string { - return DefaultClient.CaptureErrorAndWait(err, tags, interfaces...) -} - -// CapturePanic calls f and then recovers and reports a panic to the Sentry server if it occurs. -func (client *Client) CapturePanic(f func(), tags map[string]string, interfaces ...Interface) { - // Note: This doesn't need to check for client, because we still want to go through the defer/recover path - // Down the line, Capture will be noop'd, so while this does a _tiny_ bit of overhead constructing the - // *Packet just to be thrown away, this should not be the normal case. Could be refactored to - // be completely noop though if we cared. - defer func() { - var packet *Packet - switch rval := recover().(type) { - case nil: - return - case error: - packet = NewPacket(rval.Error(), append(append(interfaces, client.context.interfaces()...), NewException(rval, NewStacktrace(2, 3, nil)))...) - default: - rvalStr := fmt.Sprint(rval) - packet = NewPacket(rvalStr, append(append(interfaces, client.context.interfaces()...), NewException(errors.New(rvalStr), NewStacktrace(2, 3, nil)))...) - } - - client.Capture(packet, tags) - }() - - f() -} - -// CapturePanic calls f and then recovers and reports a panic to the Sentry server if it occurs. -func CapturePanic(f func(), tags map[string]string, interfaces ...Interface) { - DefaultClient.CapturePanic(f, tags, interfaces...) -} - -func (client *Client) Close() { - close(client.queue) -} - -func Close() { DefaultClient.Close() } - -// Wait blocks and waits for all events to finish being sent to Sentry server -func (client *Client) Wait() { - client.wg.Wait() -} - -// Wait blocks and waits for all events to finish being sent to Sentry server -func Wait() { DefaultClient.Wait() } - -func (client *Client) URL() string { - client.mu.RLock() - defer client.mu.RUnlock() - - return client.url -} - -func URL() string { return DefaultClient.URL() } - -func (client *Client) ProjectID() string { - client.mu.RLock() - defer client.mu.RUnlock() - - return client.projectID -} - -func ProjectID() string { return DefaultClient.ProjectID() } - -func (client *Client) Release() string { - client.mu.RLock() - defer client.mu.RUnlock() - - return client.release -} - -func Release() string { return DefaultClient.Release() } - -func (c *Client) SetUserContext(u *User) { c.context.SetUser(u) } -func (c *Client) SetHttpContext(h *Http) { c.context.SetHttp(h) } -func (c *Client) SetTagsContext(t map[string]string) { c.context.SetTags(t) } -func (c *Client) ClearContext() { c.context.Clear() } - -func SetUserContext(u *User) { DefaultClient.SetUserContext(u) } -func SetHttpContext(h *Http) { DefaultClient.SetHttpContext(h) } -func SetTagsContext(t map[string]string) { DefaultClient.SetTagsContext(t) } -func ClearContext() { DefaultClient.ClearContext() } - -// HTTPTransport is the default transport, delivering packets to Sentry via the -// HTTP API. -type HTTPTransport struct { - Http http.Client -} - -func (t *HTTPTransport) Send(url, authHeader string, packet *Packet) error { - if url == "" { - return nil - } - - body, contentType := serializedPacket(packet) - req, _ := http.NewRequest("POST", url, body) - req.Header.Set("X-Sentry-Auth", authHeader) - req.Header.Set("User-Agent", userAgent) - req.Header.Set("Content-Type", contentType) - res, err := t.Http.Do(req) - if err != nil { - return err - } - io.Copy(ioutil.Discard, res.Body) - res.Body.Close() - if res.StatusCode != 200 { - return fmt.Errorf("raven: got http status %d", res.StatusCode) - } - return nil -} - -func serializedPacket(packet *Packet) (r io.Reader, contentType string) { - packetJSON := packet.JSON() - - // Only deflate/base64 the packet if it is bigger than 1KB, as there is - // overhead. - if len(packetJSON) > 1000 { - buf := &bytes.Buffer{} - b64 := base64.NewEncoder(base64.StdEncoding, buf) - deflate, _ := zlib.NewWriterLevel(b64, zlib.BestCompression) - deflate.Write(packetJSON) - deflate.Close() - b64.Close() - return buf, "application/octet-stream" - } - return bytes.NewReader(packetJSON), "application/json" -} - -var hostname string - -func init() { - hostname, _ = os.Hostname() -} diff --git a/vendor/github.com/getsentry/raven-go/client_test.go b/vendor/github.com/getsentry/raven-go/client_test.go deleted file mode 100644 index 632c8d4a0..000000000 --- a/vendor/github.com/getsentry/raven-go/client_test.go +++ /dev/null @@ -1,150 +0,0 @@ -package raven - -import ( - "encoding/json" - "reflect" - "testing" - "time" -) - -type testInterface struct{} - -func (t *testInterface) Class() string { return "sentry.interfaces.Test" } -func (t *testInterface) Culprit() string { return "codez" } - -func TestPacketJSON(t *testing.T) { - packet := &Packet{ - Project: "1", - EventID: "2", - Platform: "linux", - Culprit: "caused_by", - ServerName: "host1", - Release: "721e41770371db95eee98ca2707686226b993eda", - Message: "test", - Timestamp: Timestamp(time.Date(2000, 01, 01, 0, 0, 0, 0, time.UTC)), - Level: ERROR, - Logger: "com.getsentry.raven-go.logger-test-packet-json", - Tags: []Tag{Tag{"foo", "bar"}}, - Interfaces: []Interface{&Message{Message: "foo"}}, - } - - packet.AddTags(map[string]string{"foo": "foo"}) - packet.AddTags(map[string]string{"baz": "buzz"}) - - expected := `{"message":"test","event_id":"2","project":"1","timestamp":"2000-01-01T00:00:00","level":"error","logger":"com.getsentry.raven-go.logger-test-packet-json","platform":"linux","culprit":"caused_by","server_name":"host1","release":"721e41770371db95eee98ca2707686226b993eda","tags":[["foo","bar"],["foo","foo"],["baz","buzz"]],"logentry":{"message":"foo"}}` - actual := string(packet.JSON()) - - if actual != expected { - t.Errorf("incorrect json; got %s, want %s", actual, expected) - } -} - -func TestPacketInit(t *testing.T) { - packet := &Packet{Message: "a", Interfaces: []Interface{&testInterface{}}} - packet.Init("foo") - - if packet.Project != "foo" { - t.Error("incorrect Project:", packet.Project) - } - if packet.Culprit != "codez" { - t.Error("incorrect Culprit:", packet.Culprit) - } - if packet.ServerName == "" { - t.Errorf("ServerName should not be empty") - } - if packet.Level != ERROR { - t.Errorf("incorrect Level: got %d, want %d", packet.Level, ERROR) - } - if packet.Logger != "root" { - t.Errorf("incorrect Logger: got %s, want %s", packet.Logger, "root") - } - if time.Time(packet.Timestamp).IsZero() { - t.Error("Timestamp is zero") - } - if len(packet.EventID) != 32 { - t.Error("incorrect EventID:", packet.EventID) - } -} - -func TestSetDSN(t *testing.T) { - client := &Client{} - client.SetDSN("https://u:p@example.com/sentry/1") - - if client.url != "https://example.com/sentry/api/1/store/" { - t.Error("incorrect url:", client.url) - } - if client.projectID != "1" { - t.Error("incorrect projectID:", client.projectID) - } - if client.authHeader != "Sentry sentry_version=4, sentry_key=u, sentry_secret=p" { - t.Error("incorrect authHeader:", client.authHeader) - } -} - -func TestUnmarshalTag(t *testing.T) { - actual := new(Tag) - if err := json.Unmarshal([]byte(`["foo","bar"]`), actual); err != nil { - t.Fatal("unable to decode JSON:", err) - } - - expected := &Tag{Key: "foo", Value: "bar"} - if !reflect.DeepEqual(actual, expected) { - t.Errorf("incorrect Tag: wanted '%+v' and got '%+v'", expected, actual) - } -} - -func TestUnmarshalTags(t *testing.T) { - tests := []struct { - Input string - Expected Tags - }{ - { - `{"foo":"bar"}`, - Tags{Tag{Key: "foo", Value: "bar"}}, - }, - { - `[["foo","bar"],["bar","baz"]]`, - Tags{Tag{Key: "foo", Value: "bar"}, Tag{Key: "bar", Value: "baz"}}, - }, - } - - for _, test := range tests { - var actual Tags - if err := json.Unmarshal([]byte(test.Input), &actual); err != nil { - t.Fatal("unable to decode JSON:", err) - } - - if !reflect.DeepEqual(actual, test.Expected) { - t.Errorf("incorrect Tags: wanted '%+v' and got '%+v'", test.Expected, actual) - } - } -} - -func TestMarshalTimestamp(t *testing.T) { - timestamp := Timestamp(time.Date(2000, 01, 02, 03, 04, 05, 0, time.UTC)) - expected := `"2000-01-02T03:04:05"` - - actual, err := json.Marshal(timestamp) - if err != nil { - t.Error(err) - } - - if string(actual) != expected { - t.Errorf("incorrect string; got %s, want %s", actual, expected) - } -} - -func TestUnmarshalTimestamp(t *testing.T) { - timestamp := `"2000-01-02T03:04:05"` - expected := Timestamp(time.Date(2000, 01, 02, 03, 04, 05, 0, time.UTC)) - - var actual Timestamp - err := json.Unmarshal([]byte(timestamp), &actual) - if err != nil { - t.Error(err) - } - - if actual != expected { - t.Errorf("incorrect string; got %s, want %s", actual, expected) - } -} diff --git a/vendor/github.com/getsentry/raven-go/docs/Makefile b/vendor/github.com/getsentry/raven-go/docs/Makefile deleted file mode 100644 index 60f8b8439..000000000 --- a/vendor/github.com/getsentry/raven-go/docs/Makefile +++ /dev/null @@ -1,153 +0,0 @@ -# Makefile for Sphinx documentation -# - -# You can set these variables from the command line. -SPHINXOPTS = -SPHINXBUILD = sphinx-build -PAPER = -BUILDDIR = _build - -# Internal variables. -PAPEROPT_a4 = -D latex_paper_size=a4 -PAPEROPT_letter = -D latex_paper_size=letter -ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . -# the i18n builder cannot share the environment and doctrees with the others -I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . - -.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext - -help: - @echo "Please use \`make
+
[](https://travis-ci.org/gin-gonic/gin)
[](https://coveralls.io/r/gin-gonic/gin?branch=master)
[](https://godoc.org/github.com/gin-gonic/gin)
@@ -12,7 +12,7 @@ Gin is a web framework written in Golang. It features a martini-like API with mu

-```
+```sh
$ cat test.go
```
```go
@@ -23,9 +23,11 @@ import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
- c.String(200, "pong")
+ c.JSON(200, gin.H{
+ "message": "hello world",
+ })
})
- r.Run(":8080") // listen and serve on 0.0.0.0:8080
+ r.Run() // listen and server on 0.0.0.0:8080
}
```
@@ -84,7 +86,7 @@ BenchmarkZeus_GithubAll | 2000 | 944234 | 300688 | 2648
1. Download and install it:
```sh
-go get github.com/gin-gonic/gin
+$ go get github.com/gin-gonic/gin
```
2. Import it in your code:
@@ -110,8 +112,10 @@ func main() {
router.HEAD("/someHead", head)
router.OPTIONS("/someOptions", options)
- // Listen and server on 0.0.0.0:8080
- router.Run(":8080")
+ // By default it serves on :8080 unless a
+ // PORT environment variable was defined.
+ router.Run()
+ // router.Run.Run(":3000") for a hard coded port
}
```
@@ -128,7 +132,7 @@ func main() {
})
// However, this one will match /user/john/ and also /user/john/send
- // If no other routers match /user/john, it will redirect to /user/join/
+ // If no other routers match /user/john, it will redirect to /user/john/
router.GET("/user/:name/*action", func(c *gin.Context) {
name := c.Param("name")
action := c.Param("action")
@@ -143,17 +147,17 @@ func main() {
#### Querystring parameters
```go
func main() {
- router := gin.Default()
+ router := gin.Default()
- // Query string parameters are parsed using the existing underlying request object.
- // The request responds to a url matching: /welcome?firstname=Jane&lastname=Doe
- router.GET("/welcome", func(c *gin.Context) {
- firstname := c.DefaultQuery("firstname", "Guest")
- lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")
+ // Query string parameters are parsed using the existing underlying request object.
+ // The request responds to a url matching: /welcome?firstname=Jane&lastname=Doe
+ router.GET("/welcome", func(c *gin.Context) {
+ firstname := c.DefaultQuery("firstname", "Guest")
+ lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")
- c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
- })
- router.Run(":8080")
+ c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
+ })
+ router.Run(":8080")
}
```
@@ -161,18 +165,19 @@ func main() {
```go
func main() {
- router := gin.Default()
+ router := gin.Default()
- router.POST("/form_post", func(c *gin.Context) {
- message := c.PostForm("message")
- nick := c.DefaultPostForm("nick", "anonymous")
+ router.POST("/form_post", func(c *gin.Context) {
+ message := c.PostForm("message")
+ nick := c.DefaultPostForm("nick", "anonymous")
- c.JSON(200, gin.H{
- "status": "posted",
- "message": message,
- })
- })
- router.Run(":8080")
+ c.JSON(200, gin.H{
+ "status": "posted",
+ "message": message,
+ "nick": nick,
+ })
+ })
+ router.Run(":8080")
}
```
@@ -190,19 +195,20 @@ func main() {
router := gin.Default()
router.POST("/post", func(c *gin.Context) {
- id := c.Query("id")
- page := c.DefaultQuery("id", "0")
- name := c.PostForm("name")
- message := c.PostForm("message")
- fmt.Println("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
+ id := c.Query("id")
+ page := c.DefaultQuery("page", "0")
+ name := c.PostForm("name")
+ message := c.PostForm("message")
+
+ fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
})
router.Run(":8080")
}
```
```
-id: 1234; page: 0; name: manu; message: this_is_great
+id: 1234; page: 1; name: manu; message: this_is_great
```
@@ -301,30 +307,30 @@ type Login struct {
func main() {
router := gin.Default()
- // Example for binding JSON ({"user": "manu", "password": "123"})
+ // Example for binding JSON ({"user": "manu", "password": "123"})
router.POST("/loginJSON", func(c *gin.Context) {
var json Login
- if c.BindJSON(&json) == nil {
- if json.User == "manu" && json.Password == "123" {
- c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
- } else {
- c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
- }
- }
+ if c.BindJSON(&json) == nil {
+ if json.User == "manu" && json.Password == "123" {
+ c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
+ } else {
+ c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
+ }
+ }
})
- // Example for binding a HTML form (user=manu&password=123)
- router.POST("/loginForm", func(c *gin.Context) {
- var form Login
- // This will infer what binder to use depending on the content-type header.
- if c.Bind(&form) == nil {
- if form.User == "manu" && form.Password == "123" {
- c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
- } else {
- c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
- }
- }
- })
+ // Example for binding a HTML form (user=manu&password=123)
+ router.POST("/loginForm", func(c *gin.Context) {
+ var form Login
+ // This will infer what binder to use depending on the content-type header.
+ if c.Bind(&form) == nil {
+ if form.User == "manu" && form.Password == "123" {
+ c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
+ } else {
+ c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
+ }
+ }
+ })
// Listen and server on 0.0.0.0:8080
router.Run(":8080")
@@ -353,21 +359,21 @@ func main() {
// c.BindWith(&form, binding.Form)
// or you can simply use autobinding with Bind method:
var form LoginForm
- // in this case proper binding will be automatically selected
+ // in this case proper binding will be automatically selected
if c.Bind(&form) == nil {
- if form.User == "user" && form.Password == "password" {
- c.JSON(200, gin.H{"status": "you are logged in"})
- } else {
- c.JSON(401, gin.H{"status": "unauthorized"})
- }
- }
+ if form.User == "user" && form.Password == "password" {
+ c.JSON(200, gin.H{"status": "you are logged in"})
+ } else {
+ c.JSON(401, gin.H{"status": "unauthorized"})
+ }
+ }
})
router.Run(":8080")
}
```
Test it with:
-```bash
+```sh
$ curl -v --form user=user --form password=password http://localhost:8080/login
```
@@ -411,13 +417,13 @@ func main() {
```go
func main() {
- router := gin.Default()
- router.Static("/assets", "./assets")
- router.StaticFS("/more_static", http.Dir("my_file_system"))
- router.StaticFile("/favicon.ico", "./resources/favicon.ico")
+ router := gin.Default()
+ router.Static("/assets", "./assets")
+ router.StaticFS("/more_static", http.Dir("my_file_system"))
+ router.StaticFile("/favicon.ico", "./resources/favicon.ico")
- // Listen and server on 0.0.0.0:8080
- router.Run(":8080")
+ // Listen and server on 0.0.0.0:8080
+ router.Run(":8080")
}
```
@@ -438,11 +444,53 @@ func main() {
router.Run(":8080")
}
```
+templates/index.tmpl
```html
+
+ Using posts/index.tmpl
+{{ end }} +``` +templates/users/index.tmpl +```html +{{ define "users/index.tmpl" }} +Using users/index.tmpl
+ +{{ end }} ``` You can also use your own html template render @@ -559,17 +607,16 @@ func main() { r.GET("/long_async", func(c *gin.Context) { // create copy to be used inside the goroutine - c_cp := c.Copy() + cCp := c.Copy() go func() { // simulate a long task with time.Sleep(). 5 seconds time.Sleep(5 * time.Second) // note than you are using the copied context "c_cp", IMPORTANT - log.Println("Done! in path " + c_cp.Request.URL.Path) + log.Println("Done! in path " + cCp.Request.URL.Path) }() }) - r.GET("/long_sync", func(c *gin.Context) { // simulate a long task with time.Sleep(). 5 seconds time.Sleep(5 * time.Second) @@ -578,8 +625,8 @@ func main() { log.Println("Done! in path " + c.Request.URL.Path) }) - // Listen and server on 0.0.0.0:8080 - r.Run(":8080") + // Listen and server on 0.0.0.0:8080 + r.Run(":8080") } ``` @@ -609,3 +656,22 @@ func main() { s.ListenAndServe() } ``` + +#### Graceful restart or stop + +Do you want to graceful restart or stop your web server? +There be some ways. + +We can using fvbock/endless to replace the default ListenAndServe + +Refer the issue for more details: + +https://github.com/gin-gonic/gin/issues/296 + +```go +router := gin.Default() +router.GET("/", handler) +// [...] +endless.ListenAndServe(":4242", router) + +``` diff --git a/vendor/github.com/gin-gonic/gin/auth.go b/vendor/github.com/gin-gonic/gin/auth.go index ab4e35d76..125e659f2 100644 --- a/vendor/github.com/gin-gonic/gin/auth.go +++ b/vendor/github.com/gin-gonic/gin/auth.go @@ -65,14 +65,10 @@ func BasicAuth(accounts Accounts) HandlerFunc { } func processAccounts(accounts Accounts) authPairs { - if len(accounts) == 0 { - panic("Empty list of authorized credentials") - } + assert1(len(accounts) > 0, "Empty list of authorized credentials") pairs := make(authPairs, 0, len(accounts)) for user, password := range accounts { - if len(user) == 0 { - panic("User can not be empty") - } + assert1(len(user) > 0, "User can not be empty") value := authorizationHeader(user, password) pairs = append(pairs, authPair{ Value: value, diff --git a/vendor/github.com/gin-gonic/gin/auth_test.go b/vendor/github.com/gin-gonic/gin/auth_test.go deleted file mode 100644 index b22d9ced6..000000000 --- a/vendor/github.com/gin-gonic/gin/auth_test.go +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "encoding/base64" - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestBasicAuth(t *testing.T) { - pairs := processAccounts(Accounts{ - "admin": "password", - "foo": "bar", - "bar": "foo", - }) - - assert.Len(t, pairs, 3) - assert.Contains(t, pairs, authPair{ - User: "bar", - Value: "Basic YmFyOmZvbw==", - }) - assert.Contains(t, pairs, authPair{ - User: "foo", - Value: "Basic Zm9vOmJhcg==", - }) - assert.Contains(t, pairs, authPair{ - User: "admin", - Value: "Basic YWRtaW46cGFzc3dvcmQ=", - }) -} - -func TestBasicAuthFails(t *testing.T) { - assert.Panics(t, func() { processAccounts(nil) }) - assert.Panics(t, func() { - processAccounts(Accounts{ - "": "password", - "foo": "bar", - }) - }) -} - -func TestBasicAuthSearchCredential(t *testing.T) { - pairs := processAccounts(Accounts{ - "admin": "password", - "foo": "bar", - "bar": "foo", - }) - - user, found := pairs.searchCredential(authorizationHeader("admin", "password")) - assert.Equal(t, user, "admin") - assert.True(t, found) - - user, found = pairs.searchCredential(authorizationHeader("foo", "bar")) - assert.Equal(t, user, "foo") - assert.True(t, found) - - user, found = pairs.searchCredential(authorizationHeader("bar", "foo")) - assert.Equal(t, user, "bar") - assert.True(t, found) - - user, found = pairs.searchCredential(authorizationHeader("admins", "password")) - assert.Empty(t, user) - assert.False(t, found) - - user, found = pairs.searchCredential(authorizationHeader("foo", "bar ")) - assert.Empty(t, user) - assert.False(t, found) - - user, found = pairs.searchCredential("") - assert.Empty(t, user) - assert.False(t, found) -} - -func TestBasicAuthAuthorizationHeader(t *testing.T) { - assert.Equal(t, authorizationHeader("admin", "password"), "Basic YWRtaW46cGFzc3dvcmQ=") -} - -func TestBasicAuthSecureCompare(t *testing.T) { - assert.True(t, secureCompare("1234567890", "1234567890")) - assert.False(t, secureCompare("123456789", "1234567890")) - assert.False(t, secureCompare("12345678900", "1234567890")) - assert.False(t, secureCompare("1234567891", "1234567890")) -} - -func TestBasicAuthSucceed(t *testing.T) { - accounts := Accounts{"admin": "password"} - router := New() - router.Use(BasicAuth(accounts)) - router.GET("/login", func(c *Context) { - c.String(200, c.MustGet(AuthUserKey).(string)) - }) - - w := httptest.NewRecorder() - req, _ := http.NewRequest("GET", "/login", nil) - req.Header.Set("Authorization", authorizationHeader("admin", "password")) - router.ServeHTTP(w, req) - - assert.Equal(t, w.Code, 200) - assert.Equal(t, w.Body.String(), "admin") -} - -func TestBasicAuth401(t *testing.T) { - called := false - accounts := Accounts{"foo": "bar"} - router := New() - router.Use(BasicAuth(accounts)) - router.GET("/login", func(c *Context) { - called = true - c.String(200, c.MustGet(AuthUserKey).(string)) - }) - - w := httptest.NewRecorder() - req, _ := http.NewRequest("GET", "/login", nil) - req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password"))) - router.ServeHTTP(w, req) - - assert.False(t, called) - assert.Equal(t, w.Code, 401) - assert.Equal(t, w.HeaderMap.Get("WWW-Authenticate"), "Basic realm=\"Authorization Required\"") -} - -func TestBasicAuth401WithCustomRealm(t *testing.T) { - called := false - accounts := Accounts{"foo": "bar"} - router := New() - router.Use(BasicAuthForRealm(accounts, "My Custom \"Realm\"")) - router.GET("/login", func(c *Context) { - called = true - c.String(200, c.MustGet(AuthUserKey).(string)) - }) - - w := httptest.NewRecorder() - req, _ := http.NewRequest("GET", "/login", nil) - req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password"))) - router.ServeHTTP(w, req) - - assert.False(t, called) - assert.Equal(t, w.Code, 401) - assert.Equal(t, w.HeaderMap.Get("WWW-Authenticate"), "Basic realm=\"My Custom \\\"Realm\\\"\"") -} diff --git a/vendor/github.com/gin-gonic/gin/benchmarks_test.go b/vendor/github.com/gin-gonic/gin/benchmarks_test.go deleted file mode 100644 index 8a1c91a96..000000000 --- a/vendor/github.com/gin-gonic/gin/benchmarks_test.go +++ /dev/null @@ -1,157 +0,0 @@ -package gin - -import ( - "html/template" - "net/http" - "testing" -) - -func BenchmarkOneRoute(B *testing.B) { - router := New() - router.GET("/ping", func(c *Context) {}) - runRequest(B, router, "GET", "/ping") -} - -func BenchmarkRecoveryMiddleware(B *testing.B) { - router := New() - router.Use(Recovery()) - router.GET("/", func(c *Context) {}) - runRequest(B, router, "GET", "/") -} - -func BenchmarkLoggerMiddleware(B *testing.B) { - router := New() - router.Use(LoggerWithWriter(newMockWriter())) - router.GET("/", func(c *Context) {}) - runRequest(B, router, "GET", "/") -} - -func BenchmarkManyHandlers(B *testing.B) { - router := New() - router.Use(Recovery(), LoggerWithWriter(newMockWriter())) - router.Use(func(c *Context) {}) - router.Use(func(c *Context) {}) - router.GET("/ping", func(c *Context) {}) - runRequest(B, router, "GET", "/ping") -} - -func Benchmark5Params(B *testing.B) { - DefaultWriter = newMockWriter() - router := New() - router.Use(func(c *Context) {}) - router.GET("/param/:param1/:params2/:param3/:param4/:param5", func(c *Context) {}) - runRequest(B, router, "GET", "/param/path/to/parameter/john/12345") -} - -func BenchmarkOneRouteJSON(B *testing.B) { - router := New() - data := struct { - Status string `json:"status"` - }{"ok"} - router.GET("/json", func(c *Context) { - c.JSON(200, data) - }) - runRequest(B, router, "GET", "/json") -} - -var htmlContentType = []string{"text/html; charset=utf-8"} - -func BenchmarkOneRouteHTML(B *testing.B) { - router := New() - t := template.Must(template.New("index").Parse(` -)^ ** -** The table above makes reference to standard C library functions atoi() -** and atof(). SQLite does not really use these functions. It has its -** own equivalent internal routines. The atoi() and atof() names are -** used in the table for brevity and because they are familiar to most -** C programmers. -** ** Note that when type conversions occur, pointers returned by prior ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or ** sqlite3_column_text16() may be invalidated. @@ -4006,7 +4267,7 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); ** of conversion are done in place when it is possible, but sometimes they ** are not possible and in those cases prior pointers are invalidated. ** -** The safest and easiest to remember policy is to invoke these routines +** The safest policy is to invoke these routines ** in one of the following ways: ** **@@ -257,9 +360,9 @@ extern "C" { ** See also: [sqlite_version()] and [sqlite_source_id()]. */ SQLITE_API const char sqlite3_version[] = SQLITE_VERSION; -SQLITE_API const char *sqlite3_libversion(void); -SQLITE_API const char *sqlite3_sourceid(void); -SQLITE_API int sqlite3_libversion_number(void); +SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void); +SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void); +SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void); /* ** CAPI3REF: Run-Time Library Compilation Options Diagnostics @@ -284,8 +387,8 @@ SQLITE_API int sqlite3_libversion_number(void); ** [sqlite_compileoption_get()] and the [compile_options pragma]. */ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS -SQLITE_API int sqlite3_compileoption_used(const char *zOptName); -SQLITE_API const char *sqlite3_compileoption_get(int N); +SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName); +SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N); #endif /* @@ -316,7 +419,7 @@ SQLITE_API const char *sqlite3_compileoption_get(int N); ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but ** can be fully or partially disabled using a call to [sqlite3_config()] ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], -** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the +** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the ** sqlite3_threadsafe() function shows only the compile-time setting of ** thread safety, not any run-time changes to that setting made by ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe() @@ -324,7 +427,7 @@ SQLITE_API const char *sqlite3_compileoption_get(int N); ** ** See the [threading mode] documentation for additional information. */ -SQLITE_API int sqlite3_threadsafe(void); +SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void); /* ** CAPI3REF: Database Connection Handle @@ -381,10 +484,11 @@ typedef sqlite_uint64 sqlite3_uint64; /* ** CAPI3REF: Closing A Database Connection +** DESTRUCTOR: sqlite3 ** ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors ** for the [sqlite3] object. -** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if +** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if ** the [sqlite3] object is successfully destroyed and all associated ** resources are deallocated. ** @@ -392,7 +496,7 @@ typedef sqlite_uint64 sqlite3_uint64; ** statements or unfinished sqlite3_backup objects then sqlite3_close() ** will leave the database connection open and return [SQLITE_BUSY]. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements -** and unfinished sqlite3_backups, then the database connection becomes +** and/or unfinished sqlite3_backups, then the database connection becomes ** an unusable "zombie" which will automatically be deallocated when the ** last prepared statement is finalized or the last sqlite3_backup is ** finished. The sqlite3_close_v2() interface is intended for use with @@ -405,7 +509,7 @@ typedef sqlite_uint64 sqlite3_uint64; ** with the [sqlite3] object prior to attempting to close the object. ^If ** sqlite3_close_v2() is called on a [database connection] that still has ** outstanding [prepared statements], [BLOB handles], and/or -** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation +** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation ** of resources is deferred until all [prepared statements], [BLOB handles], ** and [sqlite3_backup] objects are also destroyed. ** @@ -420,8 +524,8 @@ typedef sqlite_uint64 sqlite3_uint64; ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer ** argument is a harmless no-op. */ -SQLITE_API int sqlite3_close(sqlite3*); -SQLITE_API int sqlite3_close_v2(sqlite3*); +SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3*); +SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3*); /* ** The type for a callback function. @@ -432,6 +536,7 @@ typedef int (*sqlite3_callback)(void*,int,char**, char**); /* ** CAPI3REF: One-Step Query Execution Interface +** METHOD: sqlite3 ** ** The sqlite3_exec() interface is a convenience wrapper around ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()], @@ -483,7 +588,7 @@ typedef int (*sqlite3_callback)(void*,int,char**, char**); ** Restrictions: ** **-**
*/ -SQLITE_API int sqlite3_exec( +SQLITE_API int SQLITE_STDCALL sqlite3_exec( sqlite3*, /* An open database */ const char *sql, /* SQL to be evaluated */ int (*callback)(void*,int,char**,char**), /* Callback function */ @@ -501,16 +606,14 @@ SQLITE_API int sqlite3_exec( /* ** CAPI3REF: Result Codes -** KEYWORDS: SQLITE_OK {error code} {error codes} -** KEYWORDS: {result code} {result codes} +** KEYWORDS: {result code definitions} ** ** Many SQLite functions return an integer result code from the set shown ** here in order to indicate success or failure. ** ** New error codes may be added in future versions of SQLite. ** -** See also: [SQLITE_IOERR_READ | extended result codes], -** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes]. +** See also: [extended result code definitions] */ #define SQLITE_OK 0 /* Successful result */ /* beginning-of-error-codes */ @@ -548,26 +651,19 @@ SQLITE_API int sqlite3_exec( /* ** CAPI3REF: Extended Result Codes -** KEYWORDS: {extended error code} {extended error codes} -** KEYWORDS: {extended result code} {extended result codes} +** KEYWORDS: {extended result code definitions} ** -** In its default configuration, SQLite API routines return one of 26 integer -** [SQLITE_OK | result codes]. However, experience has shown that many of +** In its default configuration, SQLite API routines return one of 30 integer +** [result codes]. However, experience has shown that many of ** these result codes are too coarse-grained. They do not provide as ** much information about problems as programmers might like. In an effort to ** address this, newer versions of SQLite (version 3.3.8 and later) include ** support for additional result codes that provide more detailed information -** about errors. The extended result codes are enabled or disabled +** about errors. These [extended result codes] are enabled or disabled ** on a per database connection basis using the -** [sqlite3_extended_result_codes()] API. -** -** Some of the available extended result codes are listed here. -** One may expect the number of extended result codes will increase -** over time. Software that uses extended result codes should expect -** to see new result codes in future releases of SQLite. -** -** The SQLITE_OK result code will never be extended. It will always -** be exactly zero. +** [sqlite3_extended_result_codes()] API. Or, the extended code for +** the most recent error can be obtained using +** [sqlite3_extended_errcode()]. */ #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) @@ -595,6 +691,8 @@ SQLITE_API int sqlite3_exec( #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8)) #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8)) #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8)) +#define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8)) +#define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8)) #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8)) @@ -621,6 +719,7 @@ SQLITE_API int sqlite3_exec( #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8)) #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8)) #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8)) +#define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8)) /* ** CAPI3REF: Flags For File Open Operations @@ -800,7 +899,7 @@ struct sqlite3_file { ** locking strategy (for example to use dot-file locks), to inquire ** about the status of a lock, or to break stale locks. The SQLite ** core reserves all opcodes less than 100 for its own use. -** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. +** A [file control opcodes | list of opcodes] less than 100 is available. ** Applications that define a custom xFileControl method should use opcodes ** greater than 100 to avoid conflicts. VFS implementations should ** return [SQLITE_NOTFOUND] for file control opcodes that they do not @@ -873,19 +972,22 @@ struct sqlite3_io_methods { /* ** CAPI3REF: Standard File Control Opcodes +** KEYWORDS: {file control opcodes} {file control opcode} ** ** These integer constants are opcodes for the xFileControl method ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] ** interface. ** +**- The application must insure that the 1st parameter to sqlite3_exec() +**
- The application must ensure that the 1st parameter to sqlite3_exec() ** is a valid and open [database connection]. **
- The application must not close the [database connection] specified by ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running. @@ -491,7 +596,7 @@ typedef int (*sqlite3_callback)(void*,int,char**, char**); ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running. **
+**
** ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as -** was given no the corresponding lock. +** was given on the corresponding lock. ** ** The xShmLock method can transition between unlocked and SHARED or ** between unlocked and EXCLUSIVE. It cannot transition between SHARED @@ -1440,10 +1584,10 @@ struct sqlite3_vfs { ** must return [SQLITE_OK] on success and some other [error code] upon ** failure. */ -SQLITE_API int sqlite3_initialize(void); -SQLITE_API int sqlite3_shutdown(void); -SQLITE_API int sqlite3_os_init(void); -SQLITE_API int sqlite3_os_end(void); +SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void); +SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void); +SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void); +SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void); /* ** CAPI3REF: Configuring The SQLite Library @@ -1454,9 +1598,11 @@ SQLITE_API int sqlite3_os_end(void); ** applications and so this routine is usually not necessary. It is ** provided to support rare applications with unusual needs. ** -** The sqlite3_config() interface is not threadsafe. The application -** must insure that no other SQLite interfaces are invoked by other -** threads while sqlite3_config() is running. Furthermore, sqlite3_config() +** The sqlite3_config() interface is not threadsafe. The application +** must ensure that no other SQLite interfaces are invoked by other +** threads while sqlite3_config() is running. +** +** The sqlite3_config() interface ** may only be invoked prior to library initialization using ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before @@ -1474,10 +1620,11 @@ SQLITE_API int sqlite3_os_end(void); ** ^If the option is unknown or SQLite is unable to set the option ** then this routine returns a non-zero [error code]. */ -SQLITE_API int sqlite3_config(int, ...); +SQLITE_API int SQLITE_CDECL sqlite3_config(int, ...); /* ** CAPI3REF: Configure database connections +** METHOD: sqlite3 ** ** The sqlite3_db_config() interface is used to make configuration ** changes to a [database connection]. The interface is similar to @@ -1492,7 +1639,7 @@ SQLITE_API int sqlite3_config(int, ...); ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if ** the call is considered successful. */ -SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); +SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3*, int op, ...); /* ** CAPI3REF: Memory Allocation Routines @@ -1626,31 +1773,33 @@ struct sqlite3_mem_methods { ** SQLITE_CONFIG_SERIALIZED configuration option. ** ** [[SQLITE_CONFIG_MALLOC]]- [[SQLITE_FCNTL_LOCKSTATE]] ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This ** opcode causes the xFileControl method to write the current state of ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) ** into an integer that the pArg argument points to. This capability -** is used during testing and only needs to be supported when SQLITE_TEST -** is defined. -**
+** is used during testing and is only available when the SQLITE_TEST +** compile-time option is used. +** **
*/ #define SQLITE_FCNTL_LOCKSTATE 1 -#define SQLITE_GET_LOCKPROXYFILE 2 -#define SQLITE_SET_LOCKPROXYFILE 3 -#define SQLITE_LAST_ERRNO 4 +#define SQLITE_FCNTL_GET_LOCKPROXYFILE 2 +#define SQLITE_FCNTL_SET_LOCKPROXYFILE 3 +#define SQLITE_FCNTL_LAST_ERRNO 4 #define SQLITE_FCNTL_SIZE_HINT 5 #define SQLITE_FCNTL_CHUNK_SIZE 6 #define SQLITE_FCNTL_FILE_POINTER 7 @@ -1092,6 +1225,17 @@ struct sqlite3_io_methods { #define SQLITE_FCNTL_SYNC 21 #define SQLITE_FCNTL_COMMIT_PHASETWO 22 #define SQLITE_FCNTL_WIN32_SET_HANDLE 23 +#define SQLITE_FCNTL_WAL_BLOCK 24 +#define SQLITE_FCNTL_ZIPVFS 25 +#define SQLITE_FCNTL_RBU 26 +#define SQLITE_FCNTL_VFS_POINTER 27 +#define SQLITE_FCNTL_JOURNAL_POINTER 28 + +/* deprecated names */ +#define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE +#define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE +#define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO + /* ** CAPI3REF: Mutex Handle @@ -1343,7 +1487,7 @@ struct sqlite3_vfs { **- [[SQLITE_FCNTL_SIZE_HINT]] ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS ** layer a hint of how large the database file will grow to be during the @@ -906,8 +1008,13 @@ struct sqlite3_io_methods { **
- [[SQLITE_FCNTL_FILE_POINTER]] ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer ** to the [sqlite3_file] object associated with a particular database -** connection. See the [sqlite3_file_control()] documentation for -** additional information. +** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER]. +** +**
- [[SQLITE_FCNTL_JOURNAL_POINTER]] +** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer +** to the [sqlite3_file] object associated with the journal file (either +** the [rollback journal] or the [write-ahead log]) for a particular database +** connection. See also [SQLITE_FCNTL_FILE_POINTER]. ** **
- [[SQLITE_FCNTL_SYNC_OMITTED]] ** No longer in use. @@ -994,6 +1101,15 @@ struct sqlite3_io_methods { ** pointer in case this file-control is not implemented. This file-control ** is intended for diagnostic use only. ** +**
- [[SQLITE_FCNTL_VFS_POINTER]] +** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level +** [VFSes] currently in use. ^(The argument X in +** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be +** of type "[sqlite3_vfs] **". This opcodes will set *X +** to a pointer to the top-level VFS.)^ +** ^When there are multiple VFS shims in the stack, this opcode finds the +** upper-most shim only. +** **
- [[SQLITE_FCNTL_PRAGMA]] ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] ** file control is sent to the open [sqlite3_file] object corresponding @@ -1010,7 +1126,9 @@ struct sqlite3_io_methods { ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA] ** file control returns [SQLITE_OK], then the parser assumes that the ** VFS has handled the PRAGMA itself and the parser generates a no-op -** prepared statement. ^If the [SQLITE_FCNTL_PRAGMA] file control returns +** prepared statement if result string is NULL, or that returns a copy +** of the result string if the string is non-NULL. +** ^If the [SQLITE_FCNTL_PRAGMA] file control returns ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means ** that the VFS encountered an error while handling the [PRAGMA] and the ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA] @@ -1068,12 +1186,27 @@ struct sqlite3_io_methods { ** pointed to by the pArg argument. This capability is used during testing ** and only needs to be supported when SQLITE_TEST is defined. ** +**
- [[SQLITE_FCNTL_WAL_BLOCK]] +** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might +** be advantageous to block on the next WAL lock if the lock is not immediately +** available. The WAL subsystem issues this signal during rare +** circumstances in order to fix a problem with priority inversion. +** Applications should not use this file-control. +** +**
- [[SQLITE_FCNTL_ZIPVFS]] +** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other +** VFS should return SQLITE_NOTFOUND for this opcode. +** +**
- [[SQLITE_FCNTL_RBU]] +** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by +** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for +** this opcode. **
SQLITE_CONFIG_MALLOC -**^(This option takes a single argument which is a pointer to an -** instance of the [sqlite3_mem_methods] structure. The argument specifies +** ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is +** a pointer to an instance of the [sqlite3_mem_methods] structure. +** The argument specifies ** alternative low-level memory allocation routines to be used in place of ** the memory allocation routines built into SQLite.)^ ^SQLite makes ** its own private copy of the content of the [sqlite3_mem_methods] structure ** before the [sqlite3_config()] call returns. ** ** [[SQLITE_CONFIG_GETMALLOC]]SQLITE_CONFIG_GETMALLOC -**^(This option takes a single argument which is a pointer to an -** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods] +** ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which +** is a pointer to an instance of the [sqlite3_mem_methods] structure. +** The [sqlite3_mem_methods] ** structure is filled with the currently defined memory allocation routines.)^ ** This option can be used to overload the default memory allocation ** routines with a wrapper that simulations memory allocation failure or ** tracks memory usage, for example. ** ** [[SQLITE_CONFIG_MEMSTATUS]]SQLITE_CONFIG_MEMSTATUS -**^This option takes single argument of type int, interpreted as a -** boolean, which enables or disables the collection of memory allocation -** statistics. ^(When memory allocation statistics are disabled, the -** following SQLite interfaces become non-operational: +** ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int, +** interpreted as a boolean, which enables or disables the collection of +** memory allocation statistics. ^(When memory allocation statistics are +** disabled, the following SQLite interfaces become non-operational: ** ** ** [[SQLITE_CONFIG_SCRATCH]]**
)^ ** ^Memory allocation statistics are enabled by default unless SQLite is ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory @@ -1658,53 +1807,72 @@ struct sqlite3_mem_methods { **- [sqlite3_memory_used()] **
- [sqlite3_memory_highwater()] **
- [sqlite3_soft_heap_limit64()] -**
- [sqlite3_status()] +**
- [sqlite3_status64()] **
SQLITE_CONFIG_SCRATCH -**^This option specifies a static memory buffer that SQLite can use for -** scratch memory. There are three arguments: A pointer an 8-byte +** ** ** [[SQLITE_CONFIG_PAGECACHE]]^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer +** that SQLite can use for scratch memory. ^(There are three arguments +** to SQLITE_CONFIG_SCRATCH: A pointer an 8-byte ** aligned memory buffer from which the scratch allocations will be ** drawn, the size of each scratch allocation (sz), -** and the maximum number of scratch allocations (N). The sz -** argument must be a multiple of 16. +** and the maximum number of scratch allocations (N).)^ ** The first argument must be a pointer to an 8-byte aligned buffer ** of at least sz*N bytes of memory. -** ^SQLite will use no more than two scratch buffers per thread. So -** N should be set to twice the expected maximum number of threads. -** ^SQLite will never require a scratch buffer that is more than 6 -** times the database page size. ^If SQLite needs needs additional +** ^SQLite will not use more than one scratch buffers per thread. +** ^SQLite will never request a scratch buffer that is more than 6 +** times the database page size. +** ^If SQLite needs needs additional ** scratch memory beyond what is provided by this configuration option, then -** [sqlite3_malloc()] will be used to obtain the memory needed. +** [sqlite3_malloc()] will be used to obtain the memory needed.+** ^When the application provides any amount of scratch memory using +** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large +** [sqlite3_malloc|heap allocations]. +** This can help [Robson proof|prevent memory allocation failures] due to heap +** fragmentation in low-memory embedded systems. +**
SQLITE_CONFIG_PAGECACHE -**^This option specifies a static memory buffer that SQLite can use for -** the database page cache with the default page cache implementation. -** This configuration should not be used if an application-define page -** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option. -** There are three arguments to this option: A pointer to 8-byte aligned -** memory, the size of each page buffer (sz), and the number of pages (N). +** ** ** [[SQLITE_CONFIG_HEAP]]^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool +** that SQLite can use for the database page cache with the default page +** cache implementation. +** This configuration option is a no-op if an application-define page +** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2]. +** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to +** 8-byte aligned memory (pMem), the size of each page cache line (sz), +** and the number of cache lines (N). ** The sz argument should be the size of the largest database page -** (a power of two between 512 and 32768) plus a little extra for each -** page header. ^The page header size is 20 to 40 bytes depending on -** the host architecture. ^It is harmless, apart from the wasted memory, -** to make sz a little too large. The first -** argument should point to an allocation of at least sz*N bytes of memory. -** ^SQLite will use the memory provided by the first argument to satisfy its -** memory needs for the first N pages that it adds to cache. ^If additional -** page cache memory is needed beyond what is provided by this option, then -** SQLite goes to [sqlite3_malloc()] for the additional storage space. -** The pointer in the first argument must -** be aligned to an 8-byte boundary or subsequent behavior of SQLite -** will be undefined. +** (a power of two between 512 and 65536) plus some extra bytes for each +** page header. ^The number of extra bytes needed by the page header +** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ]. +** ^It is harmless, apart from the wasted memory, +** for the sz parameter to be larger than necessary. The pMem +** argument must be either a NULL pointer or a pointer to an 8-byte +** aligned block of memory of at least sz*N bytes, otherwise +** subsequent behavior is undefined. +** ^When pMem is not NULL, SQLite will strive to use the memory provided +** to satisfy page cache needs, falling back to [sqlite3_malloc()] if +** a page cache line is larger than sz bytes or if all of the pMem buffer +** is exhausted. +** ^If pMem is NULL and N is non-zero, then each database connection +** does an initial bulk allocation for page cache memory +** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or +** of -1024*N bytes if N is negative, . ^If additional +** page cache memory is needed beyond what is provided by the initial +** allocation, then SQLite goes to [sqlite3_malloc()] separately for each +** additional cache line.SQLITE_CONFIG_HEAP -**^This option specifies a static memory buffer that SQLite will use -** for all of its dynamic memory allocation needs beyond those provided -** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE]. -** There are three arguments: An 8-byte aligned pointer to the memory, +** ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer +** that SQLite will use for all of its dynamic memory allocation needs +** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and +** [SQLITE_CONFIG_PAGECACHE]. +** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled +** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns +** [SQLITE_ERROR] if invoked otherwise. +** ^There are three arguments to SQLITE_CONFIG_HEAP: +** An 8-byte aligned pointer to the memory, ** the number of bytes in the memory buffer, and the minimum allocation size. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts ** to using its default memory allocator (the system malloc() implementation), ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the -** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or -** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory +** memory pointer is not NULL then the alternative memory ** allocator is engaged to handle all of SQLites memory allocation needs. ** The first pointer (the memory pointer) must be aligned to an 8-byte ** boundary or subsequent behavior of SQLite will be undefined. @@ -1712,11 +1880,11 @@ struct sqlite3_mem_methods { ** for the minimum allocation size are 2**5 through 2**8. ** ** [[SQLITE_CONFIG_MUTEX]]SQLITE_CONFIG_MUTEX -**^(This option takes a single argument which is a pointer to an -** instance of the [sqlite3_mutex_methods] structure. The argument specifies -** alternative low-level mutex routines to be used in place -** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the -** content of the [sqlite3_mutex_methods] structure before the call to +** ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a +** pointer to an instance of the [sqlite3_mutex_methods] structure. +** The argument specifies alternative low-level mutex routines to be used +** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of +** the content of the [sqlite3_mutex_methods] structure before the call to ** [sqlite3_config()] returns. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** the entire mutexing subsystem is omitted from the build and hence calls to @@ -1724,8 +1892,8 @@ struct sqlite3_mem_methods { ** return [SQLITE_ERROR]. ** ** [[SQLITE_CONFIG_GETMUTEX]]SQLITE_CONFIG_GETMUTEX -**^(This option takes a single argument which is a pointer to an -** instance of the [sqlite3_mutex_methods] structure. The +** ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which +** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The ** [sqlite3_mutex_methods] ** structure is filled with the currently defined mutex routines.)^ ** This option can be used to overload the default mutex allocation @@ -1737,25 +1905,25 @@ struct sqlite3_mem_methods { ** return [SQLITE_ERROR]. ** ** [[SQLITE_CONFIG_LOOKASIDE]]SQLITE_CONFIG_LOOKASIDE -**^(This option takes two arguments that determine the default -** memory allocation for the lookaside memory allocator on each -** [database connection]. The first argument is the +** ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine +** the default size of lookaside memory on each [database connection]. +** The first argument is the ** size of each lookaside buffer slot and the second is the number of -** slots allocated to each database connection.)^ ^(This option sets the -** default lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE] -** verb to [sqlite3_db_config()] can be used to change the lookaside +** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE +** sets the default lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE] +** option to [sqlite3_db_config()] can be used to change the lookaside ** configuration on individual connections.)^ ** ** [[SQLITE_CONFIG_PCACHE2]]SQLITE_CONFIG_PCACHE2 -**^(This option takes a single argument which is a pointer to -** an [sqlite3_pcache_methods2] object. This object specifies the interface -** to a custom page cache implementation.)^ ^SQLite makes a copy of the -** object and uses it for page cache memory allocations. +**^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is +** a pointer to an [sqlite3_pcache_methods2] object. This object specifies +** the interface to a custom page cache implementation.)^ +** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object. ** ** [[SQLITE_CONFIG_GETPCACHE2]]SQLITE_CONFIG_GETPCACHE2 -**^(This option takes a single argument which is a pointer to an -** [sqlite3_pcache_methods2] object. SQLite copies of the current -** page cache implementation into that object.)^ +**^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which +** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of +** the current page cache implementation into that object.)^ ** ** [[SQLITE_CONFIG_LOG]]SQLITE_CONFIG_LOG **The SQLITE_CONFIG_LOG option is used to configure the SQLite @@ -1778,10 +1946,11 @@ struct sqlite3_mem_methods { ** function must be threadsafe. ** ** [[SQLITE_CONFIG_URI]]SQLITE_CONFIG_URI -** ^(This option takes a single argument of type int. If non-zero, then -** URI handling is globally enabled. If the parameter is zero, then URI handling -** is globally disabled.)^ ^If URI handling is globally enabled, all filenames -** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or +** ^(The SQLITE_CONFIG_URI option takes a single argument of type int. +** If non-zero, then URI handling is globally enabled. If the parameter is zero, +** then URI handling is globally disabled.)^ ^If URI handling is globally +** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()], +** [sqlite3_open16()] or ** specified as part of [ATTACH] commands are interpreted as URIs, regardless ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database ** connection is opened. ^If it is globally disabled, filenames are @@ -1791,9 +1960,10 @@ struct sqlite3_mem_methods { ** [SQLITE_USE_URI] symbol defined.)^ ** ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] SQLITE_CONFIG_COVERING_INDEX_SCAN -** ^This option takes a single integer argument which is interpreted as -** a boolean in order to enable or disable the use of covering indices for -** full table scans in the query optimizer. ^The default setting is determined +** ^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer +** argument which is interpreted as a boolean in order to enable or disable +** the use of covering indices for full table scans in the query optimizer. +** ^The default setting is determined ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on" ** if that compile-time option is omitted. ** The ability to disable the use of covering indices for full table scans @@ -1833,18 +2003,37 @@ struct sqlite3_mem_methods { ** ^The default setting can be overridden by each database connection using ** either the [PRAGMA mmap_size] command, or by using the ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size -** cannot be changed at run-time. Nor may the maximum allowed mmap size -** exceed the compile-time maximum mmap size set by the +** will be silently truncated if necessary so that it does not exceed the +** compile-time maximum mmap size set by the ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^ ** ^If either argument to this option is negative, then that argument is ** changed to its compile-time default. ** ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]] ** SQLITE_CONFIG_WIN32_HEAPSIZE -** ^This option is only available if SQLite is compiled for Windows -** with the [SQLITE_WIN32_MALLOC] pre-processor macro defined. -** SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value +** ^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is +** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro +** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value ** that specifies the maximum size of the created heap. +** +** [[SQLITE_CONFIG_PCACHE_HDRSZ]] +** SQLITE_CONFIG_PCACHE_HDRSZ +** ^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which +** is a pointer to an integer and writes into that integer the number of extra +** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE]. +** The amount of extra space required can change depending on the compiler, +** target platform, and SQLite version. +** +** [[SQLITE_CONFIG_PMASZ]] +** SQLITE_CONFIG_PMASZ +** ^The SQLITE_CONFIG_PMASZ option takes a single parameter which +** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded +** sorter to that integer. The default minimum PMA Size is set by the +** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched +** to help with sort operations when multithreaded sorting +** is enabled (using the [PRAGMA threads] command) and the amount of content +** to be sorted exceeds the page size times the minimum of the +** [PRAGMA cache_size] setting and this value. ** */ #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ @@ -1870,6 +2059,8 @@ struct sqlite3_mem_methods { #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */ #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */ #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */ +#define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */ +#define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */ /* ** CAPI3REF: Database Connection Configuration Options @@ -1936,15 +2127,17 @@ struct sqlite3_mem_methods { /* ** CAPI3REF: Enable Or Disable Extended Result Codes +** METHOD: sqlite3 ** ** ^The sqlite3_extended_result_codes() routine enables or disables the ** [extended result codes] feature of SQLite. ^The extended result ** codes are disabled by default for historical compatibility. */ -SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); +SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3*, int onoff); /* ** CAPI3REF: Last Insert Rowid +** METHOD: sqlite3 ** ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables) ** has a unique 64-bit signed @@ -1992,52 +2185,51 @@ SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); ** unpredictable and might not equal either the old or the new ** last insert [rowid]. */ -SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); +SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3*); /* ** CAPI3REF: Count The Number Of Rows Modified +** METHOD: sqlite3 ** -** ^This function returns the number of database rows that were changed -** or inserted or deleted by the most recently completed SQL statement -** on the [database connection] specified by the first parameter. -** ^(Only changes that are directly specified by the [INSERT], [UPDATE], -** or [DELETE] statement are counted. Auxiliary changes caused by -** triggers or [foreign key actions] are not counted.)^ Use the -** [sqlite3_total_changes()] function to find the total number of changes -** including changes caused by triggers and foreign key actions. +** ^This function returns the number of rows modified, inserted or +** deleted by the most recently completed INSERT, UPDATE or DELETE +** statement on the database connection specified by the only parameter. +** ^Executing any other type of SQL statement does not modify the value +** returned by this function. ** -** ^Changes to a view that are simulated by an [INSTEAD OF trigger] -** are not counted. Only real table changes are counted. +** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are +** considered - auxiliary changes caused by [CREATE TRIGGER | triggers], +** [foreign key actions] or [REPLACE] constraint resolution are not counted. +** +** Changes to a view that are intercepted by +** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value +** returned by sqlite3_changes() immediately after an INSERT, UPDATE or +** DELETE statement run on a view is always zero. Only changes made to real +** tables are counted. ** -** ^(A "row change" is a change to a single row of a single table -** caused by an INSERT, DELETE, or UPDATE statement. Rows that -** are changed as side effects of [REPLACE] constraint resolution, -** rollback, ABORT processing, [DROP TABLE], or by any other -** mechanisms do not count as direct row changes.)^ -** -** A "trigger context" is a scope of execution that begins and -** ends with the script of a [CREATE TRIGGER | trigger]. -** Most SQL statements are -** evaluated outside of any trigger. This is the "top level" -** trigger context. If a trigger fires from the top level, a -** new trigger context is entered for the duration of that one -** trigger. Subtriggers create subcontexts for their duration. -** -** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does -** not create a new trigger context. -** -** ^This function returns the number of direct row changes in the -** most recent INSERT, UPDATE, or DELETE statement within the same -** trigger context. -** -** ^Thus, when called from the top level, this function returns the -** number of changes in the most recent INSERT, UPDATE, or DELETE -** that also occurred at the top level. ^(Within the body of a trigger, -** the sqlite3_changes() interface can be called to find the number of -** changes in the most recently completed INSERT, UPDATE, or DELETE -** statement within the body of the same trigger. -** However, the number returned does not include changes -** caused by subtriggers since those have their own context.)^ +** Things are more complicated if the sqlite3_changes() function is +** executed while a trigger program is running. This may happen if the +** program uses the [changes() SQL function], or if some other callback +** function invokes sqlite3_changes() directly. Essentially: +** +** +**
+** +** ^This means that if the changes() SQL function (or similar) is used +** by the first INSERT, UPDATE or DELETE statement within a trigger, it +** returns the value as set when the calling statement began executing. +** ^If it is used by the second or subsequent such statement within a trigger +** program, the value returned reflects the number of rows modified by the +** previous INSERT, UPDATE or DELETE statement within the same trigger. ** ** See also the [sqlite3_total_changes()] interface, the ** [count_changes pragma], and the [changes() SQL function]. @@ -2046,25 +2238,23 @@ SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); ** while [sqlite3_changes()] is running then the value returned ** is unpredictable and not meaningful. */ -SQLITE_API int sqlite3_changes(sqlite3*); +SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3*); /* ** CAPI3REF: Total Number Of Rows Modified +** METHOD: sqlite3 ** -** ^This function returns the number of row changes caused by [INSERT], -** [UPDATE] or [DELETE] statements since the [database connection] was opened. -** ^(The count returned by sqlite3_total_changes() includes all changes -** from all [CREATE TRIGGER | trigger] contexts and changes made by -** [foreign key actions]. However, -** the count does not include changes used to implement [REPLACE] constraints, -** do rollbacks or ABORT processing, or [DROP TABLE] processing. The -** count does not include rows of views that fire an [INSTEAD OF trigger], -** though if the INSTEAD OF trigger makes changes of its own, those changes -** are counted.)^ -** ^The sqlite3_total_changes() function counts the changes as soon as -** the statement that makes them is completed (when the statement handle -** is passed to [sqlite3_reset()] or [sqlite3_finalize()]). -** +** ^This function returns the total number of rows inserted, modified or +** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed +** since the database connection was opened, including those executed as +** part of trigger programs. ^Executing any other type of SQL statement +** does not affect the value returned by sqlite3_total_changes(). +** +** ^Changes made as part of [foreign key actions] are included in the +** count, but those made as part of REPLACE constraint resolution are +** not. ^Changes to a view that are intercepted by INSTEAD OF triggers +** are not counted. +** ** See also the [sqlite3_changes()] interface, the ** [count_changes pragma], and the [total_changes() SQL function]. ** @@ -2072,10 +2262,11 @@ SQLITE_API int sqlite3_changes(sqlite3*); ** while [sqlite3_total_changes()] is running then the value ** returned is unpredictable and not meaningful. */ -SQLITE_API int sqlite3_total_changes(sqlite3*); +SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3*); /* ** CAPI3REF: Interrupt A Long-Running Query +** METHOD: sqlite3 ** ** ^This function causes any pending database operation to abort and ** return at its earliest opportunity. This routine is typically @@ -2111,7 +2302,7 @@ SQLITE_API int sqlite3_total_changes(sqlite3*); ** If the database connection closes while [sqlite3_interrupt()] ** is running then bad things will likely happen. */ -SQLITE_API void sqlite3_interrupt(sqlite3*); +SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3*); /* ** CAPI3REF: Determine If An SQL Statement Is Complete @@ -2146,33 +2337,41 @@ SQLITE_API void sqlite3_interrupt(sqlite3*); ** The input to [sqlite3_complete16()] must be a zero-terminated ** UTF-16 string in native byte order. */ -SQLITE_API int sqlite3_complete(const char *sql); -SQLITE_API int sqlite3_complete16(const void *sql); +SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *sql); +SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *sql); /* ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors +** KEYWORDS: {busy-handler callback} {busy handler} +** METHOD: sqlite3 ** -** ^This routine sets a callback function that might be invoked whenever -** an attempt is made to open a database table that another thread -** or process has locked. +** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X +** that might be invoked with argument P whenever +** an attempt is made to access a database table associated with +** [database connection] D when another thread +** or process has the table locked. +** The sqlite3_busy_handler() interface is used to implement +** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout]. ** -** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] +** ^If the busy callback is NULL, then [SQLITE_BUSY] ** is returned immediately upon encountering the lock. ^If the busy callback ** is not NULL, then the callback might be invoked with two arguments. ** ** ^The first argument to the busy handler is a copy of the void* pointer which ** is the third argument to sqlite3_busy_handler(). ^The second argument to ** the busy handler callback is the number of times that the busy handler has -** been invoked for this locking event. ^If the +** been invoked previously for the same locking event. ^If the ** busy callback returns 0, then no additional attempts are made to -** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. +** access the database and [SQLITE_BUSY] is returned +** to the application. ** ^If the callback returns non-zero, then another attempt -** is made to open the database for reading and the cycle repeats. +** is made to access the database and the cycle repeats. ** ** The presence of a busy handler does not guarantee that it will be invoked ** when there is lock contention. ^If SQLite determines that invoking the busy ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY] -** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler. +** to the application instead of invoking the +** busy handler. ** Consider a scenario where one process is holding a read lock that ** it is trying to promote to a reserved lock and ** a second process is holding a reserved lock that it is trying @@ -2186,57 +2385,48 @@ SQLITE_API int sqlite3_complete16(const void *sql); ** ** ^The default busy callback is NULL. ** -** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] -** when SQLite is in the middle of a large transaction where all the -** changes will not fit into the in-memory cache. SQLite will -** already hold a RESERVED lock on the database file, but it needs -** to promote this lock to EXCLUSIVE so that it can spill cache -** pages into the database file without harm to concurrent -** readers. ^If it is unable to promote the lock, then the in-memory -** cache will be left in an inconsistent state and so the error -** code is promoted from the relatively benign [SQLITE_BUSY] to -** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion -** forces an automatic rollback of the changes. See the -** -** CorruptionFollowingBusyError wiki page for a discussion of why -** this is important. -** ** ^(There can only be a single busy handler defined for each ** [database connection]. Setting a new busy handler clears any ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()] -** will also set or clear the busy handler. +** or evaluating [PRAGMA busy_timeout=N] will change the +** busy handler and thus clear any previously set busy handler. ** ** The busy callback should not take any actions which modify the -** database connection that invoked the busy handler. Any such actions +** database connection that invoked the busy handler. In other words, +** the busy handler is not reentrant. Any such actions ** result in undefined behavior. ** ** A busy handler must not close the database connection ** or [prepared statement] that invoked the busy handler. */ -SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); +SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); /* ** CAPI3REF: Set A Busy Timeout +** METHOD: sqlite3 ** ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps ** for a specified amount of time when a table is locked. ^The handler ** will sleep multiple times until at least "ms" milliseconds of sleeping ** have accumulated. ^After at least "ms" milliseconds of sleeping, ** the handler returns 0 which causes [sqlite3_step()] to return -** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. +** [SQLITE_BUSY]. ** ** ^Calling this routine with an argument less than or equal to zero ** turns off all busy handlers. ** ** ^(There can only be a single busy handler for a particular -** [database connection] any any given moment. If another busy handler +** [database connection] at any given moment. If another busy handler ** was defined (using [sqlite3_busy_handler()]) prior to calling ** this routine, that other busy handler is cleared.)^ +** +** See also: [PRAGMA busy_timeout] */ -SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); +SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3*, int ms); /* ** CAPI3REF: Convenience Routines For Running Queries +** METHOD: sqlite3 ** ** This is a legacy interface that is preserved for backwards compatibility. ** Use of this interface is not recommended. @@ -2307,7 +2497,7 @@ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); ** reflected in subsequent calls to [sqlite3_errcode()] or ** [sqlite3_errmsg()]. */ -SQLITE_API int sqlite3_get_table( +SQLITE_API int SQLITE_STDCALL sqlite3_get_table( sqlite3 *db, /* An open database */ const char *zSql, /* SQL to be evaluated */ char ***pazResult, /* Results of the query */ @@ -2315,13 +2505,17 @@ SQLITE_API int sqlite3_get_table( int *pnColumn, /* Number of result columns written here */ char **pzErrmsg /* Error msg written here */ ); -SQLITE_API void sqlite3_free_table(char **result); +SQLITE_API void SQLITE_STDCALL sqlite3_free_table(char **result); /* ** CAPI3REF: Formatted String Printing Functions ** ** These routines are work-alikes of the "printf()" family of functions ** from the standard C library. +** These routines understand most of the common K&R formatting options, +** plus some additional non-standard formats, detailed below. +** Note that some of the more obscure formatting options from recent +** C-library standards are omitted from this implementation. ** ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their ** results into memory obtained from [sqlite3_malloc()]. @@ -2354,7 +2548,7 @@ SQLITE_API void sqlite3_free_table(char **result); ** These routines all implement some additional formatting ** options that are useful for constructing SQL statements. ** All of the usual printf() formatting options apply. In addition, there -** is are "%q", "%Q", and "%z" options. +** is are "%q", "%Q", "%w" and "%z" options. ** ** ^(The %q option works like %s in that it substitutes a nul-terminated ** string from the argument list. But %q also doubles every '\'' character. @@ -2407,14 +2601,20 @@ SQLITE_API void sqlite3_free_table(char **result); ** The code above will render a correct SQL statement in the zSQL ** variable even if the zText variable is a NULL pointer. ** +** ^(The "%w" formatting option is like "%q" except that it expects to +** be contained within double-quotes instead of single quotes, and it +** escapes the double-quote character instead of the single-quote +** character.)^ The "%w" formatting option is intended for safely inserting +** table and column names into a constructed SQL statement. +** ** ^(The "%z" formatting option works like "%s" but with the ** addition that after the string has been read and copied into ** the result, [sqlite3_free()] is called on the input string.)^ */ -SQLITE_API char *sqlite3_mprintf(const char*,...); -SQLITE_API char *sqlite3_vmprintf(const char*, va_list); -SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...); -SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); +SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char*,...); +SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char*, va_list); +SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int,char*,const char*, ...); +SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int,char*,const char*, va_list); /* ** CAPI3REF: Memory Allocation Subsystem @@ -2431,6 +2631,10 @@ SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns ** a NULL pointer. ** +** ^The sqlite3_malloc64(N) routine works just like +** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead +** of a signed 32-bit integer. +** ** ^Calling sqlite3_free() with a pointer previously returned ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so ** that it might be reused. ^The sqlite3_free() routine is @@ -2442,24 +2646,38 @@ SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); ** might result if sqlite3_free() is called with a non-NULL pointer that ** was not obtained from sqlite3_malloc() or sqlite3_realloc(). ** -** ^(The sqlite3_realloc() interface attempts to resize a -** prior memory allocation to be at least N bytes, where N is the -** second parameter. The memory allocation to be resized is the first -** parameter.)^ ^ If the first parameter to sqlite3_realloc() +** ^The sqlite3_realloc(X,N) interface attempts to resize a +** prior memory allocation X to be at least N bytes. +** ^If the X parameter to sqlite3_realloc(X,N) ** is a NULL pointer then its behavior is identical to calling -** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc(). -** ^If the second parameter to sqlite3_realloc() is zero or +** sqlite3_malloc(N). +** ^If the N parameter to sqlite3_realloc(X,N) is zero or ** negative then the behavior is exactly the same as calling -** sqlite3_free(P) where P is the first parameter to sqlite3_realloc(). -** ^sqlite3_realloc() returns a pointer to a memory allocation -** of at least N bytes in size or NULL if sufficient memory is unavailable. +** sqlite3_free(X). +** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation +** of at least N bytes in size or NULL if insufficient memory is available. ** ^If M is the size of the prior allocation, then min(N,M) bytes ** of the prior allocation are copied into the beginning of buffer returned -** by sqlite3_realloc() and the prior allocation is freed. -** ^If sqlite3_realloc() returns NULL, then the prior allocation -** is not freed. +** by sqlite3_realloc(X,N) and the prior allocation is freed. +** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the +** prior allocation is not freed. ** -** ^The memory returned by sqlite3_malloc() and sqlite3_realloc() +** ^The sqlite3_realloc64(X,N) interfaces works the same as +** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead +** of a 32-bit signed integer. +** +** ^If X is a memory allocation previously obtained from sqlite3_malloc(), +** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then +** sqlite3_msize(X) returns the size of that memory allocation in bytes. +** ^The value returned by sqlite3_msize(X) might be larger than the number +** of bytes requested when X was allocated. ^If X is a NULL pointer then +** sqlite3_msize(X) returns zero. If X points to something that is not +** the beginning of memory allocation, or if it points to a formerly +** valid memory allocation that has now been freed, then the behavior +** of sqlite3_msize(X) is undefined and possibly harmful. +** +** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(), +** sqlite3_malloc64(), and sqlite3_realloc64() ** is always aligned to at least an 8 byte boundary, or to a ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time ** option is used. @@ -2486,9 +2704,12 @@ SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); ** a block of memory after it has been released using ** [sqlite3_free()] or [sqlite3_realloc()]. */ -SQLITE_API void *sqlite3_malloc(int); -SQLITE_API void *sqlite3_realloc(void*, int); -SQLITE_API void sqlite3_free(void*); +SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int); +SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64); +SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void*, int); +SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void*, sqlite3_uint64); +SQLITE_API void SQLITE_STDCALL sqlite3_free(void*); +SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void*); /* ** CAPI3REF: Memory Allocator Statistics @@ -2513,8 +2734,8 @@ SQLITE_API void sqlite3_free(void*); ** by [sqlite3_memory_highwater(1)] is the high-water mark ** prior to the reset. */ -SQLITE_API sqlite3_int64 sqlite3_memory_used(void); -SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); +SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void); +SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag); /* ** CAPI3REF: Pseudo-Random Number Generator @@ -2526,20 +2747,22 @@ SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); ** applications to access the same PRNG for other purposes. ** ** ^A call to this routine stores N bytes of randomness into buffer P. -** ^If N is less than one, then P can be a NULL pointer. +** ^The P parameter can be a NULL pointer. ** ** ^If this routine has not been previously called or if the previous -** call had N less than one, then the PRNG is seeded using randomness -** obtained from the xRandomness method of the default [sqlite3_vfs] object. -** ^If the previous call to this routine had an N of 1 or more then -** the pseudo-randomness is generated +** call had N less than one or a NULL pointer for P, then the PRNG is +** seeded using randomness obtained from the xRandomness method of +** the default [sqlite3_vfs] object. +** ^If the previous call to this routine had an N of 1 or more and a +** non-NULL P then the pseudo-randomness is generated ** internally and without recourse to the [sqlite3_vfs] xRandomness ** method. */ -SQLITE_API void sqlite3_randomness(int N, void *P); +SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *P); /* ** CAPI3REF: Compile-Time Authorization Callbacks +** METHOD: sqlite3 ** ** ^This routine registers an authorizer callback with a particular ** [database connection], supplied in the first argument. @@ -2618,7 +2841,7 @@ SQLITE_API void sqlite3_randomness(int N, void *P); ** as stated in the previous paragraph, sqlite3_step() invokes ** sqlite3_prepare_v2() to reprepare a statement after a schema change. */ -SQLITE_API int sqlite3_set_authorizer( +SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer( sqlite3*, int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), void *pUserData @@ -2633,8 +2856,8 @@ SQLITE_API int sqlite3_set_authorizer( ** [sqlite3_set_authorizer | authorizer documentation] for additional ** information. ** -** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code] -** from the [sqlite3_vtab_on_conflict()] interface. +** Note that SQLITE_IGNORE is also used as a [conflict resolution mode] +** returned from the [sqlite3_vtab_on_conflict()] interface. */ #define SQLITE_DENY 1 /* Abort the SQL statement with an error */ #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ @@ -2696,6 +2919,7 @@ SQLITE_API int sqlite3_set_authorizer( /* ** CAPI3REF: Tracing And Profiling Functions +** METHOD: sqlite3 ** ** These routines register callback functions that can be used for ** tracing and profiling the execution of SQL statements. @@ -2722,12 +2946,13 @@ SQLITE_API int sqlite3_set_authorizer( ** sqlite3_profile() function is considered experimental and is ** subject to change in future versions of SQLite. */ -SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); -SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*, +SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); +SQLITE_API SQLITE_EXPERIMENTAL void *SQLITE_STDCALL sqlite3_profile(sqlite3*, void(*xProfile)(void*,const char*,sqlite3_uint64), void*); /* ** CAPI3REF: Query Progress Callbacks +** METHOD: sqlite3 ** ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback ** function X to be invoked periodically during long running calls to @@ -2757,10 +2982,11 @@ SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*, ** database connections for the meaning of "modify" in this paragraph. ** */ -SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); +SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); /* ** CAPI3REF: Opening A New Database Connection +** CONSTRUCTOR: sqlite3 ** ** ^These routines open an SQLite database file as specified by the ** filename argument. ^The filename argument is interpreted as UTF-8 for @@ -2775,9 +3001,9 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); ** an English language description of the error following a failure of any ** of the sqlite3_open() routines. ** -** ^The default encoding for the database will be UTF-8 if -** sqlite3_open() or sqlite3_open_v2() is called and -** UTF-16 in the native byte order if sqlite3_open16() is used. +** ^The default encoding will be UTF-8 for databases created using +** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases +** created using sqlite3_open16() will be UTF-16 in the native byte order. ** ** Whether or not an error occurs when it is opened, resources ** associated with the [database connection] handle should be released by @@ -2865,13 +3091,14 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); ** then it is interpreted as an absolute path. ^If the path does not begin ** with a '/' (meaning that the authority section is omitted from the URI) ** then the path is interpreted as a relative path. -** ^On windows, the first component of an absolute path -** is a drive specification (e.g. "C:"). +** ^(On windows, the first component of an absolute path +** is a drive specification (e.g. "C:").)^ ** ** [[core URI query parameters]] ** The query component of a URI may contain parameters that are interpreted ** either by SQLite itself, or by a [VFS | custom VFS implementation]. -** SQLite interprets the following three query parameters: +** SQLite and its built-in [VFSes] interpret the +** following query parameters: ** **- ^(Before entering a trigger program the value returned by +** sqlite3_changes() function is saved. After the trigger program +** has finished, the original value is restored.)^ +** +**
- ^(Within a trigger program each INSERT, UPDATE and DELETE +** statement sets the value returned by sqlite3_changes() +** upon completion as normal. Of course, this value will not include +** any changes performed by sub-triggers, as the sqlite3_changes() +** value will be saved and restored after each sub-trigger has run.)^ +**
**
- vfs: ^The "vfs" parameter may be used to specify the name of @@ -2906,11 +3133,9 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); ** a URI filename, its value overrides any behavior requested by setting ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag. ** -**
- psow: ^The psow parameter may be "true" (or "on" or "yes" or -** "1") or "false" (or "off" or "no" or "0") to indicate that the +**
- psow: ^The psow parameter indicates whether or not the ** [powersafe overwrite] property does or does not apply to the -** storage media on which the database file resides. ^The psow query -** parameter only works for the built-in unix and Windows VFSes. +** storage media on which the database file resides. ** **
- nolock: ^The nolock parameter is a boolean query parameter ** which if set disables file locking in rollback journal modes. This @@ -2986,15 +3211,15 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); ** ** See also: [sqlite3_temp_directory] */ -SQLITE_API int sqlite3_open( +SQLITE_API int SQLITE_STDCALL sqlite3_open( const char *filename, /* Database filename (UTF-8) */ sqlite3 **ppDb /* OUT: SQLite db handle */ ); -SQLITE_API int sqlite3_open16( +SQLITE_API int SQLITE_STDCALL sqlite3_open16( const void *filename, /* Database filename (UTF-16) */ sqlite3 **ppDb /* OUT: SQLite db handle */ ); -SQLITE_API int sqlite3_open_v2( +SQLITE_API int SQLITE_STDCALL sqlite3_open_v2( const char *filename, /* Database filename (UTF-8) */ sqlite3 **ppDb, /* OUT: SQLite db handle */ int flags, /* Flags */ @@ -3040,19 +3265,22 @@ SQLITE_API int sqlite3_open_v2( ** VFS method, then the behavior of this routine is undefined and probably ** undesirable. */ -SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam); -SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault); -SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64); +SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam); +SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault); +SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(const char*, const char*, sqlite3_int64); /* ** CAPI3REF: Error Codes And Messages +** METHOD: sqlite3 ** -** ^The sqlite3_errcode() interface returns the numeric [result code] or -** [extended result code] for the most recent failed sqlite3_* API call -** associated with a [database connection]. If a prior API call failed -** but the most recent API call succeeded, the return value from -** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode() +** ^If the most recent sqlite3_* API call associated with +** [database connection] D failed, then the sqlite3_errcode(D) interface +** returns the numeric [result code] or [extended result code] for that +** API call. +** If the most recent API call was successful, +** then the return value from sqlite3_errcode() is undefined. +** ^The sqlite3_extended_errcode() ** interface is the same except that it always returns the ** [extended result code] even when extended result codes are ** disabled. @@ -3083,40 +3311,41 @@ SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int ** was invoked incorrectly by the application. In that case, the ** error code and message may or may not be set. */ -SQLITE_API int sqlite3_errcode(sqlite3 *db); -SQLITE_API int sqlite3_extended_errcode(sqlite3 *db); -SQLITE_API const char *sqlite3_errmsg(sqlite3*); -SQLITE_API const void *sqlite3_errmsg16(sqlite3*); -SQLITE_API const char *sqlite3_errstr(int); +SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db); +SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db); +SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3*); +SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3*); +SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int); /* -** CAPI3REF: SQL Statement Object +** CAPI3REF: Prepared Statement Object ** KEYWORDS: {prepared statement} {prepared statements} ** -** An instance of this object represents a single SQL statement. -** This object is variously known as a "prepared statement" or a -** "compiled SQL statement" or simply as a "statement". +** An instance of this object represents a single SQL statement that +** has been compiled into binary form and is ready to be evaluated. ** -** The life of a statement object goes something like this: +** Think of each SQL statement as a separate computer program. The +** original SQL text is source code. A prepared statement object +** is the compiled object code. All SQL must be converted into a +** prepared statement before it can be run. +** +** The life-cycle of a prepared statement object usually goes like this: ** **
** */ -SQLITE_API int sqlite3_prepare( +SQLITE_API int SQLITE_STDCALL sqlite3_prepare( sqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const char **pzTail /* OUT: Pointer to unused portion of zSql */ ); -SQLITE_API int sqlite3_prepare_v2( +SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2( sqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const char **pzTail /* OUT: Pointer to unused portion of zSql */ ); -SQLITE_API int sqlite3_prepare16( +SQLITE_API int SQLITE_STDCALL sqlite3_prepare16( sqlite3 *db, /* Database handle */ const void *zSql, /* SQL statement, UTF-16 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const void **pzTail /* OUT: Pointer to unused portion of zSql */ ); -SQLITE_API int sqlite3_prepare16_v2( +SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2( sqlite3 *db, /* Database handle */ const void *zSql, /* SQL statement, UTF-16 encoded */ int nByte, /* Maximum length of zSql in bytes. */ @@ -3332,15 +3566,17 @@ SQLITE_API int sqlite3_prepare16_v2( /* ** CAPI3REF: Retrieving Statement SQL +** METHOD: sqlite3_stmt ** ** ^This interface can be used to retrieve a saved copy of the original ** SQL text used to create a [prepared statement] if that statement was ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()]. */ -SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); +SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt); /* ** CAPI3REF: Determine If An SQL Statement Writes The Database +** METHOD: sqlite3_stmt ** ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if ** and only if the [prepared statement] X makes no direct changes to @@ -3368,14 +3604,16 @@ SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); ** change the configuration of a database connection, they do not make ** changes to the content of the database files on disk. */ -SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt); +SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt); /* ** CAPI3REF: Determine If A Prepared Statement Has Been Reset +** METHOD: sqlite3_stmt ** ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the ** [prepared statement] S has been stepped at least once using -** [sqlite3_step(S)] but has not run to completion and/or has not +** [sqlite3_step(S)] but has neither run to completion (returned +** [SQLITE_DONE] from [sqlite3_step(S)]) nor ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S) ** interface returns false if S is a NULL pointer. If S is not a ** NULL pointer and is not a pointer to a valid [prepared statement] @@ -3387,7 +3625,7 @@ SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt); ** for example, in diagnostic routines to search for prepared ** statements that are holding a transaction open. */ -SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*); +SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt*); /* ** CAPI3REF: Dynamically Typed Value Object @@ -3402,7 +3640,9 @@ SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*); ** Some interfaces require a protected sqlite3_value. Other interfaces ** will accept either a protected or an unprotected sqlite3_value. ** Every interface that accepts sqlite3_value arguments specifies -** whether or not it requires a protected sqlite3_value. +** whether or not it requires a protected sqlite3_value. The +** [sqlite3_value_dup()] interface can be used to construct a new +** protected sqlite3_value from an unprotected sqlite3_value. ** ** The terms "protected" and "unprotected" refer to whether or not ** a mutex is held. An internal mutex is held for a protected @@ -3446,6 +3686,7 @@ typedef struct sqlite3_context sqlite3_context; ** CAPI3REF: Binding Values To Prepared Statements ** KEYWORDS: {host parameter} {host parameters} {host parameter name} ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} +** METHOD: sqlite3_stmt ** ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants, ** literals may be replaced by a [parameter] that matches one of following @@ -3492,18 +3733,18 @@ typedef struct sqlite3_context sqlite3_context; ** If the fourth parameter to sqlite3_bind_blob() is negative, then ** the behavior is undefined. ** If a non-negative fourth parameter is provided to sqlite3_bind_text() -** or sqlite3_bind_text16() then that parameter must be the byte offset +** or sqlite3_bind_text16() or sqlite3_bind_text64() then +** that parameter must be the byte offset ** where the NUL terminator would occur assuming the string were NUL ** terminated. If any NUL characters occur at byte offsets less than ** the value of the fourth parameter then the resulting string value will ** contain embedded NULs. The result of expressions involving strings ** with embedded NULs is undefined. ** -** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and -** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or +** ^The fifth argument to the BLOB and string binding interfaces +** is a destructor used to dispose of the BLOB or ** string after SQLite has finished with it. ^The destructor is called -** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(), -** sqlite3_bind_text(), or sqlite3_bind_text16() fails. +** to dispose of the BLOB or string even if the call to bind API fails. ** ^If the fifth argument is ** the special value [SQLITE_STATIC], then SQLite assumes that the ** information is in static, unmanaged space and does not need to be freed. @@ -3511,6 +3752,14 @@ typedef struct sqlite3_context sqlite3_context; ** SQLite makes its own private copy of the data immediately, before ** the sqlite3_bind_*() routine returns. ** +** ^The sixth argument to sqlite3_bind_text64() must be one of +** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE] +** to specify the encoding of the text in the third parameter. If +** the sixth argument to sqlite3_bind_text64() is not one of the +** allowed values shown above, or if the text encoding is different +** from the encoding specified by the sixth parameter, then the behavior +** is undefined. +** ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory ** (just an integer to hold its size) while it is being processed. @@ -3531,24 +3780,33 @@ typedef struct sqlite3_context sqlite3_context; ** ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an ** [error code] if anything goes wrong. +** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB +** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or +** [SQLITE_MAX_LENGTH]. ** ^[SQLITE_RANGE] is returned if the parameter ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails. ** ** See also: [sqlite3_bind_parameter_count()], ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. */ -SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); -SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double); -SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int); -SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); -SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int); -SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*)); -SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); -SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); -SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); +SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); +SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64, + void(*)(void*)); +SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt*, int, double); +SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt*, int, int); +SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); +SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt*, int); +SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*)); +SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); +SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64, + void(*)(void*), unsigned char encoding); +SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); +SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); +SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64); /* ** CAPI3REF: Number Of SQL Parameters +** METHOD: sqlite3_stmt ** ** ^This routine can be used to find the number of [SQL parameters] ** in a [prepared statement]. SQL parameters are tokens of the @@ -3565,10 +3823,11 @@ SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); ** [sqlite3_bind_parameter_name()], and ** [sqlite3_bind_parameter_index()]. */ -SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); +SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt*); /* ** CAPI3REF: Name Of A Host Parameter +** METHOD: sqlite3_stmt ** ** ^The sqlite3_bind_parameter_name(P,N) interface returns ** the name of the N-th [SQL parameter] in the [prepared statement] P. @@ -3592,10 +3851,11 @@ SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); ** [sqlite3_bind_parameter_count()], and ** [sqlite3_bind_parameter_index()]. */ -SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); +SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt*, int); /* ** CAPI3REF: Index Of A Parameter With A Given Name +** METHOD: sqlite3_stmt ** ** ^Return the index of an SQL parameter given its name. ^The ** index value returned is suitable for use as the second @@ -3606,21 +3866,23 @@ SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); ** ** See also: [sqlite3_bind_blob|sqlite3_bind()], ** [sqlite3_bind_parameter_count()], and -** [sqlite3_bind_parameter_index()]. +** [sqlite3_bind_parameter_name()]. */ -SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); +SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); /* ** CAPI3REF: Reset All Bindings On A Prepared Statement +** METHOD: sqlite3_stmt ** ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset ** the [sqlite3_bind_blob | bindings] on a [prepared statement]. ** ^Use this routine to reset all host parameters to NULL. */ -SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); +SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt*); /* ** CAPI3REF: Number Of Columns In A Result Set +** METHOD: sqlite3_stmt ** ** ^Return the number of columns in the result set returned by the ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL @@ -3628,10 +3890,11 @@ SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); ** ** See also: [sqlite3_data_count()] */ -SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); +SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt); /* ** CAPI3REF: Column Names In A Result Set +** METHOD: sqlite3_stmt ** ** ^These routines return the name assigned to a particular column ** in the result set of a [SELECT] statement. ^The sqlite3_column_name() @@ -3656,11 +3919,12 @@ SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); ** then the name of the column is unspecified and may change from ** one release of SQLite to the next. */ -SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N); -SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); +SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt*, int N); +SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt*, int N); /* ** CAPI3REF: Source Of Data In A Query Result +** METHOD: sqlite3_stmt ** ** ^These routines provide a means to determine the database, table, and ** table column that is the origin of a particular result column in @@ -3704,15 +3968,16 @@ SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); ** for the same [prepared statement] and result column ** at the same time then the results are undefined. */ -SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int); -SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); -SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int); -SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); -SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int); -SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); +SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt*,int); +SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt*,int); +SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt*,int); +SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt*,int); +SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt*,int); +SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt*,int); /* ** CAPI3REF: Declared Datatype Of A Query Result +** METHOD: sqlite3_stmt ** ** ^(The first parameter is a [prepared statement]. ** If this statement is a [SELECT] statement and the Nth column of the @@ -3740,11 +4005,12 @@ SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); ** is associated with individual values, not with the containers ** used to hold those values. */ -SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int); -SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); +SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt*,int); +SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt*,int); /* ** CAPI3REF: Evaluate An SQL Statement +** METHOD: sqlite3_stmt ** ** After a [prepared statement] has been prepared using either ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy @@ -3820,10 +4086,11 @@ SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); ** then the more specific [error codes] are returned directly ** by sqlite3_step(). The use of the "v2" interface is recommended. */ -SQLITE_API int sqlite3_step(sqlite3_stmt*); +SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt*); /* ** CAPI3REF: Number of columns in a result set +** METHOD: sqlite3_stmt ** ** ^The sqlite3_data_count(P) interface returns the number of columns in the ** current row of the result set of [prepared statement] P. @@ -3840,7 +4107,7 @@ SQLITE_API int sqlite3_step(sqlite3_stmt*); ** ** See also: [sqlite3_column_count()] */ -SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); +SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt); /* ** CAPI3REF: Fundamental Datatypes @@ -3877,8 +4144,7 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); /* ** CAPI3REF: Result Values From A Query ** KEYWORDS: {column access functions} -** -** These routines form the "result set" interface. +** METHOD: sqlite3_stmt ** ** ^These routines return information about a single column of the current ** result row of a query. ^In every case the first argument is a pointer @@ -3939,13 +4205,14 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); ** even empty strings, are always zero-terminated. ^The return ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer. ** -** ^The object returned by [sqlite3_column_value()] is an -** [unprotected sqlite3_value] object. An unprotected sqlite3_value object -** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()]. +** Warning: ^The object returned by [sqlite3_column_value()] is an +** [unprotected sqlite3_value] object. In a multithreaded environment, +** an unprotected sqlite3_value object may only be used safely with +** [sqlite3_bind_value()] and [sqlite3_result_value()]. ** If the [unprotected sqlite3_value] object returned by ** [sqlite3_column_value()] is used in any other way, including calls ** to routines like [sqlite3_value_int()], [sqlite3_value_text()], -** or [sqlite3_value_bytes()], then the behavior is undefined. +** or [sqlite3_value_bytes()], the behavior is not threadsafe. ** ** These routines attempt to convert the value where appropriate. ^For ** example, if the internal representation is FLOAT and a text result @@ -3976,12 +4243,6 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); ** **-**
-** -** Refer to documentation on individual methods above for additional -** information. */ typedef struct sqlite3_stmt sqlite3_stmt; /* ** CAPI3REF: Run-time Limits +** METHOD: sqlite3 ** ** ^(This interface allows the size of various constructs to be limited ** on a connection by connection basis. The first parameter is the @@ -3154,7 +3383,7 @@ typedef struct sqlite3_stmt sqlite3_stmt; ** ** New run-time limit categories may be added in future releases. */ -SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); +SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3*, int id, int newVal); /* ** CAPI3REF: Run-Time Limit Categories @@ -3206,6 +3435,10 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); ** ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(- Create the object using [sqlite3_prepare_v2()] or a related -** function. -**
- Bind values to [host parameters] using the sqlite3_bind_*() +**
- Create the prepared statement object using [sqlite3_prepare_v2()]. +**
- Bind values to [parameters] using the sqlite3_bind_*() ** interfaces. **
- Run the SQL by calling [sqlite3_step()] one or more times. -**
- Reset the statement using [sqlite3_reset()] then go back +**
- Reset the prepared statement using [sqlite3_reset()] then go back ** to step 2. Do this zero or more times. **
- Destroy the object using [sqlite3_finalize()]. **
- SQLITE_LIMIT_TRIGGER_DEPTH
**- The maximum depth of recursion for triggers.
)^ +** +** [[SQLITE_LIMIT_WORKER_THREADS]] ^(- SQLITE_LIMIT_WORKER_THREADS
+**- The maximum number of auxiliary worker threads that a single +** [prepared statement] may start.
)^ ** */ #define SQLITE_LIMIT_LENGTH 0 @@ -3219,10 +3452,13 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8 #define SQLITE_LIMIT_VARIABLE_NUMBER 9 #define SQLITE_LIMIT_TRIGGER_DEPTH 10 +#define SQLITE_LIMIT_WORKER_THREADS 11 /* ** CAPI3REF: Compiling An SQL Statement ** KEYWORDS: {SQL statement compiler} +** METHOD: sqlite3 +** CONSTRUCTOR: sqlite3_stmt ** ** To execute an SQL query, it must first be compiled into a byte-code ** program using one of these routines. @@ -3236,16 +3472,14 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2() ** use UTF-16. ** -** ^If the nByte argument is less than zero, then zSql is read up to the -** first zero terminator. ^If nByte is non-negative, then it is the maximum -** number of bytes read from zSql. ^When nByte is non-negative, the -** zSql string ends at either the first '\000' or '\u0000' character or -** the nByte-th byte, whichever comes first. If the caller knows -** that the supplied string is nul-terminated, then there is a small -** performance advantage to be gained by passing an nByte parameter that -** is equal to the number of bytes in the input string including -** the nul-terminator bytes as this saves SQLite from having to -** make a copy of the input string. +** ^If the nByte argument is negative, then zSql is read up to the +** first zero terminator. ^If nByte is positive, then it is the +** number of bytes read from zSql. ^If nByte is zero, then no prepared +** statement is generated. +** If the caller knows that the supplied string is nul-terminated, then +** there is a small performance advantage to passing an nByte parameter that +** is the number of bytes in the input string including +** the nul-terminator. ** ** ^If pzTail is not NULL then *pzTail is made to point to the first byte ** past the end of the first SQL statement in zSql. These routines only @@ -3301,28 +3535,28 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); **
** data type: "INTEGER" @@ -5250,15 +5613,11 @@ SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N); ** auto increment: 0 **)^ ** -** ^(This function may load one or more schemas from database files. If an -** error occurs during this process, or if the requested table or column -** cannot be found, an [error code] is returned and an error message left -** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^ -** -** ^This API is only available if the library was compiled with the -** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined. +** ^This function causes all database schemas to be read from disk and +** parsed, if that has not already been done, and returns an error if +** any errors are encountered while loading the schema. */ -SQLITE_API int sqlite3_table_column_metadata( +SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata( sqlite3 *db, /* Connection handle */ const char *zDbName, /* Database name or NULL */ const char *zTableName, /* Table name */ @@ -5272,6 +5631,7 @@ SQLITE_API int sqlite3_table_column_metadata( /* ** CAPI3REF: Load An Extension +** METHOD: sqlite3 ** ** ^This interface loads an SQLite extension library from the named file. ** @@ -5304,7 +5664,7 @@ SQLITE_API int sqlite3_table_column_metadata( ** ** See also the [load_extension() SQL function]. */ -SQLITE_API int sqlite3_load_extension( +SQLITE_API int SQLITE_STDCALL sqlite3_load_extension( sqlite3 *db, /* Load the extension into this database connection */ const char *zFile, /* Name of the shared library containing extension */ const char *zProc, /* Entry point. Derived from zFile if 0 */ @@ -5313,6 +5673,7 @@ SQLITE_API int sqlite3_load_extension( /* ** CAPI3REF: Enable Or Disable Extension Loading +** METHOD: sqlite3 ** ** ^So as not to open security holes in older applications that are ** unprepared to deal with [extension loading], and as a means of disabling @@ -5324,7 +5685,7 @@ SQLITE_API int sqlite3_load_extension( ** to turn extension loading on and call it with onoff==0 to turn ** it back off again. */ -SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); +SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff); /* ** CAPI3REF: Automatically Load Statically Linked Extensions @@ -5362,7 +5723,7 @@ SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); ** See also: [sqlite3_reset_auto_extension()] ** and [sqlite3_cancel_auto_extension()] */ -SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void)); +SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void (*xEntryPoint)(void)); /* ** CAPI3REF: Cancel Automatic Extension Loading @@ -5374,7 +5735,7 @@ SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void)); ** unregistered and it returns 0 if X was not on the list of initialization ** routines. */ -SQLITE_API int sqlite3_cancel_auto_extension(void (*xEntryPoint)(void)); +SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void (*xEntryPoint)(void)); /* ** CAPI3REF: Reset Automatic Extension Loading @@ -5382,7 +5743,7 @@ SQLITE_API int sqlite3_cancel_auto_extension(void (*xEntryPoint)(void)); ** ^This interface disables all automatic extensions previously ** registered using [sqlite3_auto_extension()]. */ -SQLITE_API void sqlite3_reset_auto_extension(void); +SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void); /* ** The interface to the virtual-table mechanism is currently considered @@ -5484,6 +5845,17 @@ struct sqlite3_module { ** ^Information about the ORDER BY clause is stored in aOrderBy[]. ** ^Each term of aOrderBy records a column of the ORDER BY clause. ** +** The colUsed field indicates which columns of the virtual table may be +** required by the current scan. Virtual table columns are numbered from +** zero in the order in which they appear within the CREATE TABLE statement +** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62), +** the corresponding bit is set within the colUsed mask if the column may be +** required by SQLite. If the table has at least 64 columns and any column +** to the right of the first 63 is required, then bit 63 of colUsed is also +** set. In other words, column iCol may be required if the expression +** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to +** non-zero. +** ** The [xBestIndex] method must fill aConstraintUsage[] with information ** about what parameters to pass to xFilter. ^If argvIndex>0 then ** the right-hand side of the corresponding aConstraint[] is evaluated @@ -5509,13 +5881,31 @@ struct sqlite3_module { ** ^The estimatedRows value is an estimate of the number of rows that ** will be returned by the strategy. ** +** The xBestIndex method may optionally populate the idxFlags field with a +** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag - +** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite +** assumes that the strategy may visit at most one row. +** +** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then +** SQLite also assumes that if a call to the xUpdate() method is made as +** part of the same statement to delete or update a virtual table row and the +** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback +** any database changes. In other words, if the xUpdate() returns +** SQLITE_CONSTRAINT, the database contents must be exactly as they were +** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not +** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by +** the xUpdate method are automatically rolled back by SQLite. +** ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info ** structure for SQLite version 3.8.2. If a virtual table extension is ** used with an SQLite version earlier than 3.8.2, the results of attempting ** to read or write the estimatedRows field are undefined (but are likely ** to included crashing the application). The estimatedRows field should ** therefore only be used if [sqlite3_libversion_number()] returns a -** value greater than or equal to 3008002. +** value greater than or equal to 3008002. Similarly, the idxFlags field +** was added for version 3.9.0. It may therefore only be used if +** sqlite3_libversion_number() returns a value greater than or equal to +** 3009000. */ struct sqlite3_index_info { /* Inputs */ @@ -5543,8 +5933,17 @@ struct sqlite3_index_info { double estimatedCost; /* Estimated cost of using this index */ /* Fields below are only available in SQLite 3.8.2 and later */ sqlite3_int64 estimatedRows; /* Estimated number of rows returned */ + /* Fields below are only available in SQLite 3.9.0 and later */ + int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */ + /* Fields below are only available in SQLite 3.10.0 and later */ + sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */ }; +/* +** CAPI3REF: Virtual Table Scan Flags +*/ +#define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */ + /* ** CAPI3REF: Virtual Table Constraint Operator Codes ** @@ -5553,15 +5952,19 @@ struct sqlite3_index_info { ** an operator that is part of a constraint term in the wHERE clause of ** a query that uses a [virtual table]. */ -#define SQLITE_INDEX_CONSTRAINT_EQ 2 -#define SQLITE_INDEX_CONSTRAINT_GT 4 -#define SQLITE_INDEX_CONSTRAINT_LE 8 -#define SQLITE_INDEX_CONSTRAINT_LT 16 -#define SQLITE_INDEX_CONSTRAINT_GE 32 -#define SQLITE_INDEX_CONSTRAINT_MATCH 64 +#define SQLITE_INDEX_CONSTRAINT_EQ 2 +#define SQLITE_INDEX_CONSTRAINT_GT 4 +#define SQLITE_INDEX_CONSTRAINT_LE 8 +#define SQLITE_INDEX_CONSTRAINT_LT 16 +#define SQLITE_INDEX_CONSTRAINT_GE 32 +#define SQLITE_INDEX_CONSTRAINT_MATCH 64 +#define SQLITE_INDEX_CONSTRAINT_LIKE 65 +#define SQLITE_INDEX_CONSTRAINT_GLOB 66 +#define SQLITE_INDEX_CONSTRAINT_REGEXP 67 /* ** CAPI3REF: Register A Virtual Table Implementation +** METHOD: sqlite3 ** ** ^These routines are used to register a new [virtual table module] name. ** ^Module names must be registered before @@ -5585,13 +5988,13 @@ struct sqlite3_index_info { ** interface is equivalent to sqlite3_create_module_v2() with a NULL ** destructor. */ -SQLITE_API int sqlite3_create_module( +SQLITE_API int SQLITE_STDCALL sqlite3_create_module( sqlite3 *db, /* SQLite connection to register module with */ const char *zName, /* Name of the module */ const sqlite3_module *p, /* Methods for the module */ void *pClientData /* Client data for xCreate/xConnect */ ); -SQLITE_API int sqlite3_create_module_v2( +SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2( sqlite3 *db, /* SQLite connection to register module with */ const char *zName, /* Name of the module */ const sqlite3_module *p, /* Methods for the module */ @@ -5619,7 +6022,7 @@ SQLITE_API int sqlite3_create_module_v2( */ struct sqlite3_vtab { const sqlite3_module *pModule; /* The module for this virtual table */ - int nRef; /* NO LONGER USED */ + int nRef; /* Number of open cursors */ char *zErrMsg; /* Error message from sqlite3_mprintf() */ /* Virtual table implementations will typically add additional fields */ }; @@ -5654,10 +6057,11 @@ struct sqlite3_vtab_cursor { ** to declare the format (the names and datatypes of the columns) of ** the virtual tables they implement. */ -SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL); +SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3*, const char *zSQL); /* ** CAPI3REF: Overload A Function For A Virtual Table +** METHOD: sqlite3 ** ** ^(Virtual tables can provide alternative implementations of functions ** using the [xFindFunction] method of the [virtual table module]. @@ -5672,7 +6076,7 @@ SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL); ** purpose is to be a placeholder function that can be overloaded ** by a [virtual table]. */ -SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); +SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); /* ** The interface to the virtual-table mechanism defined above (back up @@ -5700,6 +6104,8 @@ typedef struct sqlite3_blob sqlite3_blob; /* ** CAPI3REF: Open A BLOB For Incremental I/O +** METHOD: sqlite3 +** CONSTRUCTOR: sqlite3_blob ** ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located ** in row iRow, column zColumn, table zTable in database zDb; @@ -5709,26 +6115,42 @@ typedef struct sqlite3_blob sqlite3_blob; ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow; ** )^ ** +** ^(Parameter zDb is not the filename that contains the database, but +** rather the symbolic name of the database. For attached databases, this is +** the name that appears after the AS keyword in the [ATTACH] statement. +** For the main database file, the database name is "main". For TEMP +** tables, the database name is "temp".)^ +** ** ^If the flags parameter is non-zero, then the BLOB is opened for read -** and write access. ^If it is zero, the BLOB is opened for read access. -** ^It is not possible to open a column that is part of an index or primary -** key for writing. ^If [foreign key constraints] are enabled, it is -** not possible to open a column that is part of a [child key] for writing. +** and write access. ^If the flags parameter is zero, the BLOB is opened for +** read-only access. ** -** ^Note that the database name is not the filename that contains -** the database but rather the symbolic name of the database that -** appears after the AS keyword when the database is connected using [ATTACH]. -** ^For the main database file, the database name is "main". -** ^For TEMP tables, the database name is "temp". +** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored +** in *ppBlob. Otherwise an [error code] is returned and, unless the error +** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided +** the API is not misused, it is always safe to call [sqlite3_blob_close()] +** on *ppBlob after this function it returns. +** +** This function fails with SQLITE_ERROR if any of the following are true: +**