doc.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. // Copyright (c) 2018 David Crawshaw <david@zentus.com>
  2. //
  3. // Permission to use, copy, modify, and distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. /*
  15. Package sqlite provides a Go interface to SQLite 3.
  16. The semantics of this package are deliberately close to the
  17. SQLite3 C API, so it is helpful to be familiar with
  18. http://www.sqlite.org/c3ref/intro.html.
  19. An SQLite connection is represented by a *sqlite.Conn.
  20. Connections cannot be used concurrently.
  21. A typical Go program will create a pool of connections
  22. (using Open to create a *sqlitex.Pool) so goroutines can
  23. borrow a connection while they need to talk to the database.
  24. This package assumes SQLite will be used concurrently by the
  25. process through several connections, so the build options for
  26. SQLite enable multi-threading and the shared cache:
  27. https://www.sqlite.org/sharedcache.html
  28. The implementation automatically handles shared cache locking,
  29. see the documentation on Stmt.Step for details.
  30. The optional SQLite3 compiled in are: FTS5, RTree, JSON1, Session, GeoPoly
  31. This is not a database/sql driver.
  32. # Statement Caching
  33. Statements are prepared with the Prepare and PrepareTransient methods.
  34. When using Prepare, statements are keyed inside a connection by the
  35. original query string used to create them. This means long-running
  36. high-performance code paths can write:
  37. stmt, err := conn.Prepare("SELECT ...")
  38. After all the connections in a pool have been warmed up by passing
  39. through one of these Prepare calls, subsequent calls are simply a
  40. map lookup that returns an existing statement.
  41. # Streaming Blobs
  42. The sqlite package supports the SQLite incremental I/O interface for
  43. streaming blob data into and out of the the database without loading
  44. the entire blob into a single []byte.
  45. (This is important when working either with very large blobs, or
  46. more commonly, a large number of moderate-sized blobs concurrently.)
  47. To write a blob, first use an INSERT statement to set the size of the
  48. blob and assign a rowid:
  49. "INSERT INTO blobs (myblob) VALUES (?);"
  50. Use BindZeroBlob or SetZeroBlob to set the size of myblob.
  51. Then you can open the blob with:
  52. b, err := conn.OpenBlob("", "blobs", "myblob", conn.LastInsertRowID(), true)
  53. # Deadlines and Cancellation
  54. Every connection can have a done channel associated with it using
  55. the SetInterrupt method. This is typically the channel returned by
  56. a context.Context Done method.
  57. For example, a timeout can be associated with a connection session:
  58. ctx := context.WithTimeout(context.Background(), 100*time.Millisecond)
  59. conn.SetInterrupt(ctx.Done())
  60. As database connections are long-lived, the SetInterrupt method can
  61. be called multiple times to reset the associated lifetime.
  62. When using pools, the shorthand for associating a context with a
  63. connection is:
  64. conn := dbpool.Get(ctx)
  65. if conn == nil {
  66. // ... handle error
  67. }
  68. defer dbpool.Put(c)
  69. # Transactions
  70. SQLite transactions have to be managed manually with this package
  71. by directly calling BEGIN / COMMIT / ROLLBACK or
  72. SAVEPOINT / RELEASE/ ROLLBACK. The sqlitex has a Savepoint
  73. function that helps automate this.
  74. # A typical HTTP Handler
  75. Using a Pool to execute SQL in a concurrent HTTP handler.
  76. var dbpool *sqlitex.Pool
  77. func main() {
  78. var err error
  79. dbpool, err = sqlitex.Open("file:memory:?mode=memory", 0, 10)
  80. if err != nil {
  81. log.Fatal(err)
  82. }
  83. http.HandleFunc("/", handle)
  84. log.Fatal(http.ListenAndServe(":8080", nil))
  85. }
  86. func handle(w http.ResponseWriter, r *http.Request) {
  87. conn := dbpool.Get(r.Context())
  88. if conn == nil {
  89. return
  90. }
  91. defer dbpool.Put(conn)
  92. stmt := conn.Prep("SELECT foo FROM footable WHERE id = $id;")
  93. stmt.SetText("$id", "_user_id_")
  94. for {
  95. if hasRow, err := stmt.Step(); err != nil {
  96. // ... handle error
  97. } else if !hasRow {
  98. break
  99. }
  100. foo := stmt.GetText("foo")
  101. // ... use foo
  102. }
  103. }
  104. For helper functions that make some kinds of statements easier to
  105. write see the sqlitex package.
  106. */
  107. package sqlite // import "github.com/go-llsqlite/crawshaw"