sqlite.go 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343
  1. // Copyright (c) 2018 David Crawshaw <david@zentus.com>
  2. // Copyright (c) 2021 Ross Light <ross@zombiezen.com>
  3. //
  4. // Permission to use, copy, modify, and distribute this software for any
  5. // purpose with or without fee is hereby granted, provided that the above
  6. // copyright notice and this permission notice appear in all copies.
  7. //
  8. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. //
  16. // SPDX-License-Identifier: ISC
  17. package sqlite
  18. import "C"
  19. import (
  20. "bytes"
  21. "runtime"
  22. "sync"
  23. "time"
  24. "unsafe"
  25. "github.com/anacrolix/chansync"
  26. )
  27. /*
  28. // !!! UPDATE THE Makefile WITH THESE DEFINES !!!
  29. #cgo CFLAGS: -DSQLITE_THREADSAFE=2
  30. #cgo CFLAGS: -DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1
  31. #cgo CFLAGS: -DSQLITE_ENABLE_UNLOCK_NOTIFY
  32. #cgo CFLAGS: -DSQLITE_ENABLE_FTS5
  33. #cgo CFLAGS: -DSQLITE_ENABLE_RTREE
  34. #cgo CFLAGS: -DSQLITE_LIKE_DOESNT_MATCH_BLOBS
  35. #cgo CFLAGS: -DSQLITE_OMIT_DEPRECATED
  36. #cgo CFLAGS: -DSQLITE_ENABLE_JSON1
  37. #cgo CFLAGS: -DSQLITE_ENABLE_SESSION
  38. #cgo CFLAGS: -DSQLITE_ENABLE_SNAPSHOT
  39. #cgo CFLAGS: -DSQLITE_ENABLE_PREUPDATE_HOOK
  40. #cgo CFLAGS: -DSQLITE_USE_ALLOCA
  41. #cgo CFLAGS: -DSQLITE_ENABLE_COLUMN_METADATA
  42. #cgo CFLAGS: -DHAVE_USLEEP=1
  43. #cgo CFLAGS: -DSQLITE_DQS=0
  44. #cgo CFLAGS: -DSQLITE_ENABLE_GEOPOLY
  45. #cgo CFLAGS: -DSQLITE_DIRECT_OVERFLOW_READ
  46. #cgo windows LDFLAGS: -lwinpthread
  47. #cgo linux LDFLAGS: -ldl -lm
  48. #cgo linux CFLAGS: -std=c99
  49. #cgo openbsd LDFLAGS: -lm
  50. #cgo openbsd CFLAGS: -std=c99
  51. #cgo freebsd LDFLAGS: -lm
  52. #cgo freebsd CFLAGS: -std=c99
  53. // !!! UPDATE THE Makefile WITH THESE DEFINES !!!
  54. #include <blocking_step.h>
  55. #include <sqlite3.h>
  56. #include <stdlib.h>
  57. #include <string.h>
  58. #include "wrappers.h"
  59. // Use a helper function here to avoid the cgo pointer detection
  60. // logic treating SQLITE_TRANSIENT as a Go pointer.
  61. static int transient_bind_blob(sqlite3_stmt* stmt, int col, unsigned char* p, int n) {
  62. return sqlite3_bind_blob(stmt, col, p, n, SQLITE_TRANSIENT);
  63. }
  64. static void enable_logging() {
  65. sqlite3_config(SQLITE_CONFIG_LOG, c_log_fn, NULL);
  66. }
  67. static int db_config_onoff(sqlite3* db, int op, int onoff) {
  68. return sqlite3_db_config(db, op, onoff, NULL);
  69. }
  70. */
  71. import "C"
  72. // Conn is an open connection to an SQLite3 database.
  73. //
  74. // A Conn can only be used by goroutine at a time.
  75. type Conn struct {
  76. conn *C.sqlite3
  77. stmts map[string]*Stmt // query -> prepared statement
  78. authorizer int // authorizer ID or -1
  79. closed bool
  80. count int // shared variable to help the race detector find Conn misuse
  81. cancelCh chan struct{}
  82. tracer Tracer
  83. doneCh <-chan struct{}
  84. unlockNote *C.unlock_note
  85. // This flag is set to on if the Go busy handler is invoked (enabled with BlockOnBusy). It
  86. // should be okay to clear it between calls to sqlite (it's also concurrent safe anyway).
  87. BlockedOnBusy chansync.Flag
  88. }
  89. func (me *Conn) CSqliteObject() *C.sqlite3 {
  90. return me.conn
  91. }
  92. // sqlitex_pool is used by sqlitex.Open to tell OpenConn that there is
  93. // one more layer in the stack calls before reaching a user function.
  94. const sqlitex_pool = OpenFlags(0x01000000)
  95. // OpenConn opens a single SQLite database connection with the given flags.
  96. //
  97. // No flags or a value of 0 defaults to OpenFlagsDefault which includes the
  98. // following:
  99. //
  100. // SQLITE_OPEN_READWRITE
  101. // SQLITE_OPEN_CREATE
  102. // SQLITE_OPEN_WAL
  103. // SQLITE_OPEN_URI
  104. // SQLITE_OPEN_NOMUTEX
  105. //
  106. // https://www.sqlite.org/c3ref/open.html
  107. func OpenConn(path string, flags ...OpenFlags) (*Conn, error) {
  108. return openConn(path, flags...)
  109. }
  110. func openConn(path string, flags ...OpenFlags) (*Conn, error) {
  111. sqliteInit.Do(sqliteInitFn)
  112. var openFlags OpenFlags
  113. for _, f := range flags {
  114. openFlags |= f
  115. }
  116. if openFlags == 0 {
  117. openFlags = OpenFlagsDefault
  118. }
  119. conn := &Conn{
  120. stmts: make(map[string]*Stmt),
  121. authorizer: -1,
  122. // A pointer to unlockNote is retained by C,
  123. // so we allocate it on the C heap.
  124. unlockNote: C.unlock_note_alloc(),
  125. }
  126. cpath := C.CString(path)
  127. defer C.free(unsafe.Pointer(cpath))
  128. stackCallerLayers := 2 // caller of OpenConn or Open
  129. if openFlags&sqlitex_pool != 0 {
  130. stackCallerLayers = 3 // caller of sqlitex.Open
  131. }
  132. openFlags &^= sqlitex_pool
  133. res := C.sqlite3_open_v2(cpath, &conn.conn, C.int(openFlags), nil)
  134. if res != 0 {
  135. extres := C.sqlite3_extended_errcode(conn.conn)
  136. if extres != 0 {
  137. res = extres
  138. }
  139. C.sqlite3_close_v2(conn.conn)
  140. return nil, reserr("OpenConn", path, "", res)
  141. }
  142. C.sqlite3_extended_result_codes(conn.conn, 1)
  143. // TODO: only if Debug ?
  144. _, file, line, _ := runtime.Caller(stackCallerLayers)
  145. runtime.SetFinalizer(conn, func(conn *Conn) {
  146. if !conn.closed {
  147. var buf [20]byte
  148. panic(file + ":" + string(itoa(buf[:], int64(line))) + ": *sqlite.Conn for " + path + " garbage collected, call Close method")
  149. }
  150. })
  151. if openFlags&SQLITE_OPEN_WAL != 0 {
  152. // Set timeout for enabling WAL.
  153. // See https://github.com/crawshaw/sqlite/pull/113 for details.
  154. // TODO(maybe): Pass in Context to OpenConn?
  155. conn.SetBusyTimeout(10 * time.Second)
  156. stmt, _, err := conn.PrepareTransient("PRAGMA journal_mode=wal;")
  157. if err != nil {
  158. conn.Close()
  159. return nil, err
  160. }
  161. defer stmt.Finalize()
  162. if _, err := stmt.Step(); err != nil {
  163. conn.Close()
  164. return nil, err
  165. }
  166. }
  167. conn.SetBlockOnBusy()
  168. return conn, nil
  169. }
  170. // Close closes the database connection using sqlite3_close and finalizes
  171. // persistent prepared statements. https://www.sqlite.org/c3ref/close.html
  172. func (conn *Conn) Close() error {
  173. conn.cancelInterrupt()
  174. conn.closed = true
  175. for _, stmt := range conn.stmts {
  176. stmt.Finalize()
  177. }
  178. res := C.sqlite3_close(conn.conn)
  179. C.unlock_note_free(conn.unlockNote)
  180. conn.unlockNote = nil
  181. conn.releaseAuthorizer()
  182. return reserr("Conn.Close", "", "", res)
  183. }
  184. func (conn *Conn) GetAutocommit() bool {
  185. return int(C.sqlite3_get_autocommit(conn.conn)) != 0
  186. }
  187. const (
  188. SQLITE_DBCONFIG_DQS_DML = C.int(C.SQLITE_DBCONFIG_DQS_DML)
  189. SQLITE_DBCONFIG_DQS_DDL = C.int(C.SQLITE_DBCONFIG_DQS_DDL)
  190. )
  191. // EnableDoubleQuotedStringLiterals allows fine grained control over whether
  192. // double quoted string literals are accepted in Data Manipulation Language or
  193. // Data Definition Language queries.
  194. //
  195. // By default DQS is disabled since double quotes should indicate an identifier.
  196. //
  197. // https://sqlite.org/quirks.html#dblquote
  198. func (conn *Conn) EnableDoubleQuotedStringLiterals(dml, ddl bool) error {
  199. var enable C.int
  200. if dml {
  201. enable = 1
  202. }
  203. res := C.db_config_onoff(conn.conn, SQLITE_DBCONFIG_DQS_DML, enable)
  204. if res != 0 {
  205. return reserr("Conn.EnableDoubleQuotedStringLiterals", "", "", res)
  206. }
  207. enable = 0
  208. if ddl {
  209. enable = 1
  210. }
  211. res = C.db_config_onoff(conn.conn, SQLITE_DBCONFIG_DQS_DDL, enable)
  212. if res != 0 {
  213. return reserr("Conn.EnableDoubleQuotedStringLiterals", "", "", res)
  214. }
  215. return nil
  216. }
  217. // CheckReset reports whether any statement on this connection is in the process
  218. // of returning results.
  219. func (conn *Conn) CheckReset() string {
  220. for _, stmt := range conn.stmts {
  221. if stmt.lastHasRow {
  222. return stmt.query
  223. }
  224. }
  225. return ""
  226. }
  227. type Tracer interface {
  228. NewTask(name string) TracerTask
  229. Push(name string)
  230. Pop()
  231. }
  232. type TracerTask interface {
  233. StartRegion(regionType string)
  234. EndRegion()
  235. End()
  236. }
  237. func (conn *Conn) Tracer() Tracer {
  238. return conn.tracer
  239. }
  240. func (conn *Conn) SetTracer(tracer Tracer) {
  241. conn.tracer = tracer
  242. }
  243. // SetInterrupt assigns a channel to control connection execution lifetime.
  244. //
  245. // When doneCh is closed, the connection uses sqlite3_interrupt to
  246. // stop long-running queries and cancels any *Stmt.Step calls that
  247. // are blocked waiting for the database write lock.
  248. //
  249. // Subsequent uses of the connection will return SQLITE_INTERRUPT
  250. // errors until doneCh is reset with a subsequent call to SetInterrupt.
  251. //
  252. // Typically, doneCh is provided by the Done method on a context.Context.
  253. // For example, a timeout can be associated with a connection session:
  254. //
  255. // ctx := context.WithTimeout(context.Background(), 100*time.Millisecond)
  256. // conn.SetInterrupt(ctx.Done())
  257. //
  258. // Any busy statements at the time SetInterrupt is called will be reset.
  259. //
  260. // SetInterrupt returns the old doneCh assigned to the connection.
  261. func (conn *Conn) SetInterrupt(doneCh <-chan struct{}) (oldDoneCh <-chan struct{}) {
  262. if conn.closed {
  263. panic("sqlite.Conn is closed")
  264. }
  265. oldDoneCh = conn.doneCh
  266. conn.cancelInterrupt()
  267. conn.doneCh = doneCh
  268. for _, stmt := range conn.stmts {
  269. if stmt.lastHasRow {
  270. stmt.Reset()
  271. }
  272. }
  273. if doneCh == nil {
  274. return oldDoneCh
  275. }
  276. cancelCh := make(chan struct{})
  277. conn.cancelCh = cancelCh
  278. go func() {
  279. select {
  280. case <-doneCh:
  281. C.sqlite3_interrupt(conn.conn)
  282. C.unlock_note_fire(conn.unlockNote)
  283. <-cancelCh
  284. cancelCh <- struct{}{}
  285. case <-cancelCh:
  286. cancelCh <- struct{}{}
  287. }
  288. }()
  289. return oldDoneCh
  290. }
  291. // SetBusyTimeout sets a busy handler that sleeps for up to d to acquire a lock.
  292. //
  293. // By default, a large busy timeout (10s) is set on the assumption that
  294. // Go programs use a context object via SetInterrupt to control timeouts.
  295. //
  296. // https://www.sqlite.org/c3ref/busy_timeout.html
  297. func (conn *Conn) SetBusyTimeout(d time.Duration) {
  298. C.sqlite3_busy_timeout(conn.conn, C.int(d/time.Millisecond))
  299. busyHandlers.Delete(conn.conn)
  300. }
  301. // SetBlockOnBusy sets a busy handler that waits to acquire a lock
  302. // until the connection is interrupted (see SetInterrupt).
  303. //
  304. // By default, connections are opened with SetBlockOnBusy,
  305. // with the assumption that programs use SetInterrupt to control timeouts.
  306. //
  307. // https://www.sqlite.org/c3ref/busy_handler.html
  308. func (c *Conn) SetBlockOnBusy() {
  309. if c == nil {
  310. return
  311. }
  312. c.setBusyHandler(func(count int) bool {
  313. c.BlockedOnBusy.Set()
  314. delay := getDelayForCount(sqliteMsDelays[:], count)
  315. t := time.NewTimer(time.Duration(delay) * time.Millisecond)
  316. defer t.Stop()
  317. select {
  318. case <-t.C:
  319. return true
  320. case <-c.doneCh:
  321. // ^ Assuming that doneCh won't be set by SetInterrupt concurrently
  322. // with other operations.
  323. return false
  324. }
  325. })
  326. }
  327. func getDelayForCount[T any](delays []T, count int) T {
  328. if count >= len(delays) {
  329. count = len(delays) - 1
  330. }
  331. return delays[count]
  332. }
  333. // These are the delays from sqliteDefaultBusyCallback
  334. var sqliteMsDelays = [...]uint8{1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100}
  335. // These are the delays that zombiezen uses. I'm not sure why they're so big.
  336. var zombiezenBusyDelays = [...]time.Duration{
  337. 1 * time.Second,
  338. 2 * time.Second,
  339. 5 * time.Second,
  340. 10 * time.Second,
  341. 15 * time.Second,
  342. 20 * time.Second,
  343. 25 * time.Second,
  344. 25 * time.Second,
  345. 25 * time.Second,
  346. 50 * time.Second,
  347. 50 * time.Second,
  348. 100 * time.Second,
  349. }
  350. var busyHandlers sync.Map // sqlite3* -> func(int) bool
  351. func (c *Conn) setBusyHandler(handler func(count int) bool) {
  352. if c == nil {
  353. return
  354. }
  355. if handler == nil {
  356. C.sqlite3_busy_handler(c.conn, nil, nil)
  357. busyHandlers.Delete(c.conn)
  358. return
  359. }
  360. busyHandlers.Store(c.conn, handler)
  361. C.sqlite3_busy_handler(c.conn, (*[0]byte)(C.c_goBusyHandlerCallback), unsafe.Pointer(c.conn))
  362. }
  363. //export goBusyHandlerCallback
  364. func goBusyHandlerCallback(pArg unsafe.Pointer, count C.int) C.int {
  365. val, _ := busyHandlers.Load((*C.sqlite3)(pArg))
  366. if val == nil {
  367. return 0
  368. }
  369. f := val.(func(int) bool)
  370. if !f(int(count)) {
  371. return 0
  372. }
  373. return 1
  374. }
  375. func (conn *Conn) interrupted(loc, query string) error {
  376. select {
  377. case <-conn.doneCh:
  378. return reserr(loc, query, "", C.SQLITE_INTERRUPT)
  379. default:
  380. return nil
  381. }
  382. }
  383. func (conn *Conn) cancelInterrupt() {
  384. if conn.cancelCh != nil {
  385. conn.cancelCh <- struct{}{}
  386. <-conn.cancelCh
  387. conn.cancelCh = nil
  388. }
  389. }
  390. // Prep returns a persistent SQL statement.
  391. //
  392. // Any error in preparation will panic.
  393. //
  394. // Persistent prepared statements are cached by the query
  395. // string in a Conn. If Finalize is not called, then subsequent
  396. // calls to Prepare will return the same statement.
  397. //
  398. // https://www.sqlite.org/c3ref/prepare.html
  399. func (conn *Conn) Prep(query string) *Stmt {
  400. stmt, err := conn.Prepare(query)
  401. if err != nil {
  402. if ErrCode(err) == SQLITE_INTERRUPT {
  403. return &Stmt{
  404. conn: conn,
  405. query: query,
  406. colNames: make(map[string]int),
  407. prepInterrupt: true,
  408. }
  409. }
  410. panic(err)
  411. }
  412. return stmt
  413. }
  414. // Prepare prepares a persistent SQL statement.
  415. //
  416. // Persistent prepared statements are cached by the query
  417. // string in a Conn. If Finalize is not called, then subsequent
  418. // calls to Prepare will return the same statement.
  419. //
  420. // If the query has any unprocessed trailing bytes, Prepare
  421. // returns an error.
  422. //
  423. // https://www.sqlite.org/c3ref/prepare.html
  424. func (conn *Conn) Prepare(query string) (*Stmt, error) {
  425. if stmt := conn.stmts[query]; stmt != nil {
  426. if err := stmt.Reset(); err != nil {
  427. return nil, err
  428. }
  429. if err := stmt.ClearBindings(); err != nil {
  430. return nil, err
  431. }
  432. if conn.tracer != nil {
  433. // TODO: is query too long for a task name?
  434. // should we use trace.Log instead?
  435. stmt.tracerTask = conn.tracer.NewTask(query)
  436. }
  437. return stmt, nil
  438. }
  439. stmt, trailingBytes, err := conn.prepare(query, C.SQLITE_PREPARE_PERSISTENT)
  440. if err != nil {
  441. return nil, err
  442. }
  443. if trailingBytes != 0 {
  444. stmt.Finalize()
  445. return nil, reserr("Conn.Prepare", query, "statement has trailing bytes", C.SQLITE_ERROR)
  446. }
  447. conn.stmts[query] = stmt
  448. if conn.tracer != nil {
  449. stmt.tracerTask = conn.tracer.NewTask(query)
  450. }
  451. return stmt, nil
  452. }
  453. // PrepareTransient prepares an SQL statement that is not cached by
  454. // the Conn. Subsequent calls with the same query will create new Stmts.
  455. // Finalize must be called by the caller once done with the Stmt.
  456. //
  457. // The number of trailing bytes not consumed from query is returned.
  458. //
  459. // To run a sequence of queries once as part of a script,
  460. // the sqlitex package provides an ExecScript function built on this.
  461. //
  462. // https://www.sqlite.org/c3ref/prepare.html
  463. func (conn *Conn) PrepareTransient(query string) (stmt *Stmt, trailingBytes int, err error) {
  464. stmt, trailingBytes, err = conn.prepare(query, 0)
  465. if stmt != nil {
  466. runtime.SetFinalizer(stmt, func(stmt *Stmt) {
  467. if stmt.conn != nil {
  468. panic("open *sqlite.Stmt \"" + query + "\" garbage collected, call Finalize")
  469. }
  470. })
  471. }
  472. return stmt, trailingBytes, err
  473. }
  474. func (conn *Conn) prepare(query string, flags C.uint) (*Stmt, int, error) {
  475. conn.count++
  476. if err := conn.interrupted("Conn.Prepare", query); err != nil {
  477. return nil, 0, err
  478. }
  479. stmt := &Stmt{
  480. conn: conn,
  481. query: query,
  482. colNames: make(map[string]int),
  483. }
  484. cquery := C.CString(query)
  485. defer C.free(unsafe.Pointer(cquery))
  486. var ctrailing *C.char
  487. res := C.sqlite3_prepare_v3(conn.conn, cquery, -1, flags, &stmt.stmt, &ctrailing)
  488. if err := conn.extreserr("Conn.Prepare", query, res); err != nil {
  489. return nil, 0, err
  490. }
  491. trailingBytes := int(C.strlen(ctrailing))
  492. bindCount := int(C.sqlite3_bind_parameter_count(stmt.stmt))
  493. stmt.bindNames = make([]string, bindCount)
  494. stmt.bindIndex = make(map[string]int, bindCount)
  495. for i := range stmt.bindNames {
  496. cname := C.sqlite3_bind_parameter_name(stmt.stmt, C.int(i+1))
  497. if cname != nil {
  498. name := C.GoString(cname)
  499. stmt.bindNames[i] = name
  500. stmt.bindIndex[name] = i + 1
  501. }
  502. }
  503. for i, count := 0, int(C.sqlite3_column_count(stmt.stmt)); i < count; i++ {
  504. cname := C.sqlite3_column_name(stmt.stmt, C.int(i))
  505. if cname != nil {
  506. stmt.colNames[C.GoString(cname)] = i
  507. }
  508. }
  509. return stmt, trailingBytes, nil
  510. }
  511. // Changes reports the number of rows affected by the most recent statement.
  512. //
  513. // https://www.sqlite.org/c3ref/changes.html
  514. func (conn *Conn) Changes() int {
  515. conn.count++
  516. return int(C.sqlite3_changes(conn.conn))
  517. }
  518. // LastInsertRowID reports the rowid of the most recently successful INSERT.
  519. //
  520. // https://www.sqlite.org/c3ref/last_insert_rowid.html
  521. func (conn *Conn) LastInsertRowID() int64 {
  522. conn.count++
  523. return int64(C.sqlite3_last_insert_rowid(conn.conn))
  524. }
  525. // extreserr asks SQLite for a string explaining the error.
  526. // Only called for errors that are probably program bugs.
  527. func (conn *Conn) extreserr(loc, query string, res C.int) error {
  528. msg := ""
  529. switch res {
  530. case C.SQLITE_OK, C.SQLITE_ROW, C.SQLITE_DONE:
  531. return nil
  532. default:
  533. msg = C.GoString(C.sqlite3_errmsg(conn.conn))
  534. }
  535. return reserr(loc, query, msg, res)
  536. }
  537. func (conn *Conn) reserr(loc, query string, res C.int) error {
  538. switch res {
  539. case C.SQLITE_OK, C.SQLITE_ROW, C.SQLITE_DONE:
  540. return nil
  541. }
  542. // TODO
  543. /*extres := C.sqlite3_extended_errcode(conn.conn)
  544. if extres != 0 {
  545. res = extres
  546. }*/
  547. return reserr(loc, query, "", res)
  548. }
  549. func reserr(loc, query, msg string, res C.int) error {
  550. if res != 0 {
  551. return Error{
  552. Code: ErrorCode(res),
  553. Loc: loc,
  554. Query: query,
  555. Msg: msg,
  556. }
  557. }
  558. return nil
  559. }
  560. // Stmt is an SQLite3 prepared statement.
  561. //
  562. // A Stmt is attached to a particular Conn
  563. // (and that Conn can only be used by a single goroutine).
  564. //
  565. // When a Stmt is no longer needed it should be cleaned up
  566. // by calling the Finalize method.
  567. type Stmt struct {
  568. conn *Conn
  569. stmt *C.sqlite3_stmt
  570. query string
  571. bindNames []string
  572. bindIndex map[string]int
  573. colNames map[string]int
  574. bindErr error
  575. prepInterrupt bool // set if Prep was interrupted
  576. lastHasRow bool // last bool returned by Step
  577. tracerTask TracerTask
  578. }
  579. func (stmt *Stmt) interrupted(loc string) error {
  580. loc = "Stmt." + loc
  581. if stmt.prepInterrupt {
  582. return reserr(loc, stmt.query, "", C.SQLITE_INTERRUPT)
  583. }
  584. return stmt.conn.interrupted(loc, stmt.query)
  585. }
  586. // Finalize deletes a prepared statement.
  587. //
  588. // Be sure to always call Finalize when done with
  589. // a statement created using PrepareTransient.
  590. //
  591. // Do not call Finalize on a prepared statement that
  592. // you intend to prepare again in the future.
  593. //
  594. // https://www.sqlite.org/c3ref/finalize.html
  595. func (stmt *Stmt) Finalize() error {
  596. stmt.conn.count++
  597. if ptr := stmt.conn.stmts[stmt.query]; ptr == stmt {
  598. delete(stmt.conn.stmts, stmt.query)
  599. }
  600. res := C.sqlite3_finalize(stmt.stmt)
  601. stmt.conn = nil
  602. return stmt.conn.reserr("Stmt.Finalize", stmt.query, res)
  603. }
  604. // Reset resets a prepared statement so it can be executed again.
  605. //
  606. // Note that any parameter values bound to the statement are retained.
  607. // To clear bound values, call ClearBindings.
  608. //
  609. // https://www.sqlite.org/c3ref/reset.html
  610. func (stmt *Stmt) Reset() error {
  611. stmt.conn.count++
  612. stmt.lastHasRow = false
  613. var res C.int
  614. for {
  615. res = C.sqlite3_reset(stmt.stmt)
  616. if res != C.SQLITE_LOCKED_SHAREDCACHE {
  617. break
  618. }
  619. // An SQLITE_LOCKED_SHAREDCACHE error has been seen from sqlite3_reset
  620. // in the wild, but so far has eluded exact test case replication.
  621. // TODO: write a test for this.
  622. if res := C.wait_for_unlock_notify(stmt.conn.conn, stmt.conn.unlockNote); res != C.SQLITE_OK {
  623. return stmt.conn.extreserr("Stmt.Reset(Wait)", stmt.query, res)
  624. }
  625. }
  626. return stmt.conn.extreserr("Stmt.Reset", stmt.query, res)
  627. }
  628. // ClearBindings clears all bound parameter values on a statement.
  629. //
  630. // https://www.sqlite.org/c3ref/clear_bindings.html
  631. func (stmt *Stmt) ClearBindings() error {
  632. stmt.conn.count++
  633. if err := stmt.interrupted("ClearBindings"); err != nil {
  634. return err
  635. }
  636. res := C.sqlite3_clear_bindings(stmt.stmt)
  637. return stmt.conn.reserr("Stmt.ClearBindings", stmt.query, res)
  638. }
  639. // Step moves through the statement cursor using sqlite3_step.
  640. //
  641. // If a row of data is available, rowReturned is reported as true.
  642. // If the statement has reached the end of the available data then
  643. // rowReturned is false. Thus the status codes SQLITE_ROW and
  644. // SQLITE_DONE are reported by the rowReturned bool, and all other
  645. // non-OK status codes are reported as an error.
  646. //
  647. // If an error value is returned, then the statement has been reset.
  648. //
  649. // https://www.sqlite.org/c3ref/step.html
  650. //
  651. // # Shared cache
  652. //
  653. // As the sqlite package enables shared cache mode by default
  654. // and multiple writers are common in multi-threaded programs,
  655. // this Step method uses sqlite3_unlock_notify to handle any
  656. // SQLITE_LOCKED errors.
  657. //
  658. // Without the shared cache, SQLite will block for
  659. // several seconds while trying to acquire the write lock.
  660. // With the shared cache, it returns SQLITE_LOCKED immediately
  661. // if the write lock is held by another connection in this process.
  662. // Dealing with this correctly makes for an unpleasant programming
  663. // experience, so this package does it automatically by blocking
  664. // Step until the write lock is relinquished.
  665. //
  666. // This means Step can block for a very long time.
  667. // Use SetInterrupt to control how long Step will block.
  668. //
  669. // For far more details, see:
  670. //
  671. // http://www.sqlite.org/unlock_notify.html
  672. func (stmt *Stmt) Step() (rowReturned bool, err error) {
  673. if stmt.bindErr != nil {
  674. err = stmt.bindErr
  675. stmt.bindErr = nil
  676. stmt.Reset()
  677. return false, err
  678. }
  679. if stmt.tracerTask != nil {
  680. stmt.tracerTask.StartRegion("Step")
  681. }
  682. rowReturned, err = stmt.step()
  683. if stmt.tracerTask != nil {
  684. stmt.tracerTask.EndRegion()
  685. if !rowReturned {
  686. stmt.tracerTask.End()
  687. stmt.tracerTask = nil
  688. }
  689. }
  690. if err != nil {
  691. C.sqlite3_reset(stmt.stmt)
  692. }
  693. stmt.lastHasRow = rowReturned
  694. return rowReturned, err
  695. }
  696. func (stmt *Stmt) step() (bool, error) {
  697. for {
  698. stmt.conn.count++
  699. if err := stmt.interrupted("Step"); err != nil {
  700. return false, err
  701. }
  702. switch res := C.sqlite3_step(stmt.stmt); uint8(res) { // reduce to non-extended error code
  703. case C.SQLITE_LOCKED:
  704. if res != C.SQLITE_LOCKED_SHAREDCACHE {
  705. // don't call wait_for_unlock_notify as it might deadlock, see:
  706. // https://github.com/crawshaw/sqlite/issues/6
  707. return false, stmt.conn.extreserr("Stmt.Step", stmt.query, res)
  708. }
  709. if res := C.wait_for_unlock_notify(stmt.conn.conn, stmt.conn.unlockNote); res != C.SQLITE_OK {
  710. return false, stmt.conn.extreserr("Stmt.Step(Wait)", stmt.query, res)
  711. }
  712. C.sqlite3_reset(stmt.stmt)
  713. // loop
  714. case C.SQLITE_ROW:
  715. return true, nil
  716. case C.SQLITE_DONE:
  717. return false, nil
  718. case C.SQLITE_INTERRUPT:
  719. // TODO: embed some of these errors into the stmt for zero-alloc errors?
  720. return false, stmt.conn.reserr("Stmt.Step", stmt.query, res)
  721. default:
  722. return false, stmt.conn.extreserr("Stmt.Step", stmt.query, res)
  723. }
  724. }
  725. }
  726. func (stmt *Stmt) handleBindErr(loc string, res C.int) {
  727. if stmt.bindErr == nil {
  728. stmt.bindErr = stmt.conn.reserr("Stmt."+loc, stmt.query, res)
  729. }
  730. }
  731. func (stmt *Stmt) findBindName(loc string, param string) int {
  732. pos := stmt.bindIndex[param]
  733. if pos == 0 && stmt.bindErr == nil {
  734. stmt.bindErr = reserr("Stmt."+loc, stmt.query, "unknown parameter: "+param, C.SQLITE_ERROR)
  735. }
  736. return pos
  737. }
  738. // DataCount returns the number of columns in the current row of the result
  739. // set of prepared statement.
  740. //
  741. // https://sqlite.org/c3ref/data_count.html
  742. func (stmt *Stmt) DataCount() int {
  743. return int(C.sqlite3_data_count(stmt.stmt))
  744. }
  745. // ColumnCount returns the number of columns in the result set returned by the
  746. // prepared statement.
  747. //
  748. // https://sqlite.org/c3ref/column_count.html
  749. func (stmt *Stmt) ColumnCount() int {
  750. return int(C.sqlite3_column_count(stmt.stmt))
  751. }
  752. // ColumnName returns the name assigned to a particular column in the result
  753. // set of a SELECT statement.
  754. //
  755. // https://sqlite.org/c3ref/column_name.html
  756. func (stmt *Stmt) ColumnName(col int) string {
  757. return C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_name(stmt.stmt, C.int(col)))))
  758. }
  759. // BindParamCount reports the number of parameters in stmt.
  760. //
  761. // https://www.sqlite.org/c3ref/bind_parameter_count.html
  762. func (stmt *Stmt) BindParamCount() int {
  763. if stmt.stmt == nil {
  764. return 0
  765. }
  766. return len(stmt.bindNames)
  767. }
  768. // BindParamName returns the name of parameter or the empty string if the
  769. // parameter is nameless or i is out of range.
  770. //
  771. // Parameters indices start at 1.
  772. //
  773. // https://www.sqlite.org/c3ref/bind_parameter_name.html
  774. func (stmt *Stmt) BindParamName(param int) string {
  775. param-- // map from 1-based to 0-based
  776. if param < 0 || param >= len(stmt.bindNames) {
  777. return ""
  778. }
  779. return stmt.bindNames[param]
  780. }
  781. // BindInt64 binds value to a numbered stmt parameter.
  782. //
  783. // Parameter indices start at 1.
  784. //
  785. // https://www.sqlite.org/c3ref/bind_blob.html
  786. func (stmt *Stmt) BindInt64(param int, value int64) {
  787. if stmt.stmt == nil {
  788. return
  789. }
  790. res := C.sqlite3_bind_int64(stmt.stmt, C.int(param), C.sqlite3_int64(value))
  791. stmt.handleBindErr("BindInt64", res)
  792. }
  793. // BindBool binds value (as an integer 0 or 1) to a numbered stmt parameter.
  794. //
  795. // Parameter indices start at 1.
  796. //
  797. // https://www.sqlite.org/c3ref/bind_blob.html
  798. func (stmt *Stmt) BindBool(param int, value bool) {
  799. if stmt.stmt == nil {
  800. return
  801. }
  802. v := 0
  803. if value {
  804. v = 1
  805. }
  806. res := C.sqlite3_bind_int64(stmt.stmt, C.int(param), C.sqlite3_int64(v))
  807. stmt.handleBindErr("BindBool", res)
  808. }
  809. // BindBytes binds value to a numbered stmt parameter.
  810. //
  811. // If value is a nil slice, an SQL NULL value will be bound.
  812. //
  813. // In-memory copies of value are made using this interface.
  814. // For large blobs, consider using the streaming Blob object.
  815. //
  816. // Parameter indices start at 1.
  817. //
  818. // https://www.sqlite.org/c3ref/bind_blob.html
  819. func (stmt *Stmt) BindBytes(param int, value []byte) {
  820. if stmt.stmt == nil {
  821. return
  822. }
  823. var res C.int
  824. switch {
  825. case value == nil:
  826. res = C.sqlite3_bind_null(stmt.stmt, C.int(param))
  827. case len(value) == 0:
  828. res = C.sqlite3_bind_zeroblob(stmt.stmt, C.int(param), C.int(0))
  829. default:
  830. v := (*C.uchar)(unsafe.Pointer(&value[0]))
  831. res = C.transient_bind_blob(stmt.stmt, C.int(param), v, C.int(len(value)))
  832. runtime.KeepAlive(value) // Ensure that value is not GC'd during the above C call.
  833. }
  834. stmt.handleBindErr("BindBytes", res)
  835. }
  836. var emptyCstr = C.CString("")
  837. // BindText binds value to a numbered stmt parameter.
  838. //
  839. // Parameter indices start at 1.
  840. //
  841. // https://www.sqlite.org/c3ref/bind_blob.html
  842. func (stmt *Stmt) BindText(param int, value string) {
  843. if stmt.stmt == nil {
  844. return
  845. }
  846. var v *C.char
  847. var free *[0]byte
  848. if len(value) == 0 {
  849. v = emptyCstr
  850. } else {
  851. v = C.CString(value)
  852. free = (*[0]byte)(C.cfree)
  853. }
  854. res := C.sqlite3_bind_text(stmt.stmt, C.int(param), v, C.int(len(value)), free)
  855. stmt.handleBindErr("BindText", res)
  856. }
  857. // BindFloat binds value to a numbered stmt parameter.
  858. //
  859. // Parameter indices start at 1.
  860. //
  861. // https://www.sqlite.org/c3ref/bind_blob.html
  862. func (stmt *Stmt) BindFloat(param int, value float64) {
  863. if stmt.stmt == nil {
  864. return
  865. }
  866. res := C.sqlite3_bind_double(stmt.stmt, C.int(param), C.double(value))
  867. stmt.handleBindErr("BindFloat", res)
  868. }
  869. // BindNull binds an SQL NULL value to a numbered stmt parameter.
  870. //
  871. // Parameter indices start at 1.
  872. //
  873. // https://www.sqlite.org/c3ref/bind_blob.html
  874. func (stmt *Stmt) BindNull(param int) {
  875. if stmt.stmt == nil {
  876. return
  877. }
  878. res := C.sqlite3_bind_null(stmt.stmt, C.int(param))
  879. stmt.handleBindErr("BindNull", res)
  880. }
  881. // BindZeroBlob binds a blob of zeros of length len to a numbered stmt
  882. // parameter.
  883. //
  884. // Parameter indices start at 1.
  885. //
  886. // https://www.sqlite.org/c3ref/bind_blob.html
  887. func (stmt *Stmt) BindZeroBlob(param int, len int64) {
  888. if stmt.stmt == nil {
  889. return
  890. }
  891. res := C.sqlite3_bind_zeroblob64(stmt.stmt, C.int(param), C.sqlite3_uint64(len))
  892. stmt.handleBindErr("BindZeroBlob", res)
  893. }
  894. // SetInt64 binds an int64 to a parameter using a column name.
  895. func (stmt *Stmt) SetInt64(param string, value int64) {
  896. stmt.BindInt64(stmt.findBindName("SetInt64", param), value)
  897. }
  898. // SetBool binds a value (as a 0 or 1) to a parameter using a column name.
  899. func (stmt *Stmt) SetBool(param string, value bool) {
  900. stmt.BindBool(stmt.findBindName("SetBool", param), value)
  901. }
  902. // SetBytes binds bytes to a parameter using a column name.
  903. //
  904. // If value is a nil slice, an SQL NULL value will be bound.
  905. //
  906. // An invalid parameter name will cause the call to Step to return an error.
  907. func (stmt *Stmt) SetBytes(param string, value []byte) {
  908. stmt.BindBytes(stmt.findBindName("SetBytes", param), value)
  909. }
  910. // SetText binds text to a parameter using a column name.
  911. // An invalid parameter name will cause the call to Step to return an error.
  912. func (stmt *Stmt) SetText(param string, value string) {
  913. stmt.BindText(stmt.findBindName("SetText", param), value)
  914. }
  915. // SetFloat binds a float64 to a parameter using a column name.
  916. // An invalid parameter name will cause the call to Step to return an error.
  917. func (stmt *Stmt) SetFloat(param string, value float64) {
  918. stmt.BindFloat(stmt.findBindName("SetFloat", param), value)
  919. }
  920. // SetNull binds a null to a parameter using a column name.
  921. // An invalid parameter name will cause the call to Step to return an error.
  922. func (stmt *Stmt) SetNull(param string) {
  923. stmt.BindNull(stmt.findBindName("SetNull", param))
  924. }
  925. // SetZeroBlob binds a zero blob of length len to a parameter using a column name.
  926. // An invalid parameter name will cause the call to Step to return an error.
  927. func (stmt *Stmt) SetZeroBlob(param string, len int64) {
  928. stmt.BindZeroBlob(stmt.findBindName("SetZeroBlob", param), len)
  929. }
  930. // ColumnInt returns a query result value as an int.
  931. //
  932. // Note: this method calls sqlite3_column_int64 and then converts the
  933. // resulting 64-bits to an int.
  934. //
  935. // Column indices start at 0.
  936. //
  937. // https://www.sqlite.org/c3ref/column_blob.html
  938. func (stmt *Stmt) ColumnInt(col int) int {
  939. return int(stmt.ColumnInt64(col))
  940. }
  941. // ColumnInt32 returns a query result value as an int32.
  942. //
  943. // Column indices start at 0.
  944. //
  945. // https://www.sqlite.org/c3ref/column_blob.html
  946. func (stmt *Stmt) ColumnInt32(col int) int32 {
  947. return int32(C.sqlite3_column_int(stmt.stmt, C.int(col)))
  948. }
  949. // ColumnInt64 returns a query result value as an int64.
  950. //
  951. // Column indices start at 0.
  952. //
  953. // https://www.sqlite.org/c3ref/column_blob.html
  954. func (stmt *Stmt) ColumnInt64(col int) int64 {
  955. return int64(C.sqlite3_column_int64(stmt.stmt, C.int(col)))
  956. }
  957. // ColumnBytes reads a query result into buf.
  958. // It reports the number of bytes read.
  959. //
  960. // Column indices start at 0.
  961. //
  962. // https://www.sqlite.org/c3ref/column_blob.html
  963. func (stmt *Stmt) ColumnBytes(col int, buf []byte) int {
  964. return copy(buf, stmt.columnBytes(col))
  965. }
  966. func (stmt *Stmt) ColumnViewBytes(col int) []byte {
  967. return stmt.columnBytes(col)
  968. }
  969. // ColumnReader creates a byte reader for a query result column.
  970. //
  971. // The reader directly references C-managed memory that stops
  972. // being valid as soon as the statement row resets.
  973. func (stmt *Stmt) ColumnReader(col int) *bytes.Reader {
  974. // Load the C memory directly into the Reader.
  975. // There is no exported method that lets it escape.
  976. return bytes.NewReader(stmt.columnBytes(col))
  977. }
  978. func (stmt *Stmt) columnBytes(col int) []byte {
  979. p := C.sqlite3_column_blob(stmt.stmt, C.int(col))
  980. if p == nil {
  981. return nil
  982. }
  983. n := stmt.ColumnLen(col)
  984. slice := struct {
  985. data unsafe.Pointer
  986. len int
  987. cap int
  988. }{
  989. data: unsafe.Pointer(p),
  990. len: n,
  991. cap: n,
  992. }
  993. return *(*[]byte)(unsafe.Pointer(&slice))
  994. }
  995. // ColumnType are codes for each of the SQLite fundamental datatypes:
  996. //
  997. // 64-bit signed integer
  998. // 64-bit IEEE floating point number
  999. // string
  1000. // BLOB
  1001. // NULL
  1002. //
  1003. // https://www.sqlite.org/c3ref/c_blob.html
  1004. type ColumnType int
  1005. const (
  1006. SQLITE_INTEGER = ColumnType(C.SQLITE_INTEGER)
  1007. SQLITE_FLOAT = ColumnType(C.SQLITE_FLOAT)
  1008. SQLITE_TEXT = ColumnType(C.SQLITE3_TEXT)
  1009. SQLITE_BLOB = ColumnType(C.SQLITE_BLOB)
  1010. SQLITE_NULL = ColumnType(C.SQLITE_NULL)
  1011. )
  1012. func (t ColumnType) String() string {
  1013. switch t {
  1014. case SQLITE_INTEGER:
  1015. return "SQLITE_INTEGER"
  1016. case SQLITE_FLOAT:
  1017. return "SQLITE_FLOAT"
  1018. case SQLITE_TEXT:
  1019. return "SQLITE_TEXT"
  1020. case SQLITE_BLOB:
  1021. return "SQLITE_BLOB"
  1022. case SQLITE_NULL:
  1023. return "SQLITE_NULL"
  1024. default:
  1025. return "<unknown sqlite datatype>"
  1026. }
  1027. }
  1028. // ColumnType returns the datatype code for the initial data
  1029. // type of the result column. The returned value is one of:
  1030. //
  1031. // SQLITE_INTEGER
  1032. // SQLITE_FLOAT
  1033. // SQLITE_TEXT
  1034. // SQLITE_BLOB
  1035. // SQLITE_NULL
  1036. //
  1037. // Column indices start at 0.
  1038. //
  1039. // https://www.sqlite.org/c3ref/column_blob.html
  1040. func (stmt *Stmt) ColumnType(col int) ColumnType {
  1041. return ColumnType(C.sqlite3_column_type(stmt.stmt, C.int(col)))
  1042. }
  1043. // ColumnText returns a query result as a string.
  1044. //
  1045. // Column indices start at 0.
  1046. //
  1047. // https://www.sqlite.org/c3ref/column_blob.html
  1048. func (stmt *Stmt) ColumnText(col int) string {
  1049. n := stmt.ColumnLen(col)
  1050. return C.GoStringN((*C.char)(unsafe.Pointer(C.sqlite3_column_text(stmt.stmt, C.int(col)))), C.int(n))
  1051. }
  1052. // ColumnFloat returns a query result as a float64.
  1053. //
  1054. // Column indices start at 0.
  1055. //
  1056. // https://www.sqlite.org/c3ref/column_blob.html
  1057. func (stmt *Stmt) ColumnFloat(col int) float64 {
  1058. return float64(C.sqlite3_column_double(stmt.stmt, C.int(col)))
  1059. }
  1060. // ColumnLen returns the number of bytes in a query result.
  1061. //
  1062. // Column indices start at 0.
  1063. //
  1064. // https://www.sqlite.org/c3ref/column_blob.html
  1065. func (stmt *Stmt) ColumnLen(col int) int {
  1066. return int(C.sqlite3_column_bytes(stmt.stmt, C.int(col)))
  1067. }
  1068. func (stmt *Stmt) ColumnDatabaseName(col int) string {
  1069. return C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_database_name(stmt.stmt, C.int(col)))))
  1070. }
  1071. func (stmt *Stmt) ColumnTableName(col int) string {
  1072. return C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_table_name(stmt.stmt, C.int(col)))))
  1073. }
  1074. // ColumnIndex returns the index of the column with the given name.
  1075. //
  1076. // If there is no column with the given name ColumnIndex returns -1.
  1077. func (stmt *Stmt) ColumnIndex(colName string) int {
  1078. col, found := stmt.colNames[colName]
  1079. if !found {
  1080. return -1
  1081. }
  1082. return col
  1083. }
  1084. // GetType returns a query result type for colName
  1085. func (stmt *Stmt) GetType(colName string) ColumnType {
  1086. col, found := stmt.colNames[colName]
  1087. if !found {
  1088. return SQLITE_NULL
  1089. }
  1090. return stmt.ColumnType(col)
  1091. }
  1092. // GetInt64 returns a query result value for colName as an int64.
  1093. func (stmt *Stmt) GetInt64(colName string) int64 {
  1094. col, found := stmt.colNames[colName]
  1095. if !found {
  1096. return 0
  1097. }
  1098. return stmt.ColumnInt64(col)
  1099. }
  1100. // GetBytes reads a query result for colName into buf.
  1101. // It reports the number of bytes read.
  1102. func (stmt *Stmt) GetBytes(colName string, buf []byte) int {
  1103. col, found := stmt.colNames[colName]
  1104. if !found {
  1105. return 0
  1106. }
  1107. return stmt.ColumnBytes(col, buf)
  1108. }
  1109. // GetReader creates a byte reader for colName.
  1110. //
  1111. // The reader directly references C-managed memory that stops
  1112. // being valid as soon as the statement row resets.
  1113. func (stmt *Stmt) GetReader(colName string) *bytes.Reader {
  1114. col, found := stmt.colNames[colName]
  1115. if !found {
  1116. return bytes.NewReader(nil)
  1117. }
  1118. return stmt.ColumnReader(col)
  1119. }
  1120. // GetText returns a query result value for colName as a string.
  1121. func (stmt *Stmt) GetText(colName string) string {
  1122. col, found := stmt.colNames[colName]
  1123. if !found {
  1124. return ""
  1125. }
  1126. return stmt.ColumnText(col)
  1127. }
  1128. // GetFloat returns a query result value for colName as a float64.
  1129. func (stmt *Stmt) GetFloat(colName string) float64 {
  1130. col, found := stmt.colNames[colName]
  1131. if !found {
  1132. return 0
  1133. }
  1134. return stmt.ColumnFloat(col)
  1135. }
  1136. // GetLen returns the number of bytes in a query result for colName.
  1137. func (stmt *Stmt) GetLen(colName string) int {
  1138. col, found := stmt.colNames[colName]
  1139. if !found {
  1140. return 0
  1141. }
  1142. return stmt.ColumnLen(col)
  1143. }
  1144. // Limit is a category of performance limits.
  1145. //
  1146. // https://sqlite.org/c3ref/c_limit_attached.html
  1147. type Limit int
  1148. // Limit categories.
  1149. const (
  1150. SQLITE_LIMIT_LENGTH = Limit(C.SQLITE_LIMIT_LENGTH)
  1151. SQLITE_LIMIT_SQL_LENGTH = Limit(C.SQLITE_LIMIT_SQL_LENGTH)
  1152. SQLITE_LIMIT_COLUMN = Limit(C.SQLITE_LIMIT_COLUMN)
  1153. SQLITE_LIMIT_EXPR_DEPTH = Limit(C.SQLITE_LIMIT_EXPR_DEPTH)
  1154. SQLITE_LIMIT_COMPOUND_SELECT = Limit(C.SQLITE_LIMIT_COMPOUND_SELECT)
  1155. SQLITE_LIMIT_VDBE_OP = Limit(C.SQLITE_LIMIT_VDBE_OP)
  1156. SQLITE_LIMIT_FUNCTION_ARG = Limit(C.SQLITE_LIMIT_FUNCTION_ARG)
  1157. SQLITE_LIMIT_ATTACHED = Limit(C.SQLITE_LIMIT_ATTACHED)
  1158. SQLITE_LIMIT_LIKE_PATTERN_LENGTH = Limit(C.SQLITE_LIMIT_LIKE_PATTERN_LENGTH)
  1159. SQLITE_LIMIT_VARIABLE_NUMBER = Limit(C.SQLITE_LIMIT_VARIABLE_NUMBER)
  1160. SQLITE_LIMIT_TRIGGER_DEPTH = Limit(C.SQLITE_LIMIT_TRIGGER_DEPTH)
  1161. SQLITE_LIMIT_WORKER_THREADS = Limit(C.SQLITE_LIMIT_WORKER_THREADS)
  1162. )
  1163. // String returns the limit's C constant name.
  1164. func (limit Limit) String() string {
  1165. switch limit {
  1166. default:
  1167. var buf [20]byte
  1168. return "SQLITE_UNKNOWN_LIMIT(" + string(itoa(buf[:], int64(limit))) + ")"
  1169. case SQLITE_LIMIT_LENGTH:
  1170. return "SQLITE_LIMIT_LENGTH"
  1171. case SQLITE_LIMIT_SQL_LENGTH:
  1172. return "SQLITE_LIMIT_SQL_LENGTH"
  1173. case SQLITE_LIMIT_COLUMN:
  1174. return "SQLITE_LIMIT_COLUMN"
  1175. case SQLITE_LIMIT_EXPR_DEPTH:
  1176. return "SQLITE_LIMIT_EXPR_DEPTH"
  1177. case SQLITE_LIMIT_COMPOUND_SELECT:
  1178. return "SQLITE_LIMIT_COMPOUND_SELECT"
  1179. case SQLITE_LIMIT_VDBE_OP:
  1180. return "SQLITE_LIMIT_VDBE_OP"
  1181. case SQLITE_LIMIT_FUNCTION_ARG:
  1182. return "SQLITE_LIMIT_FUNCTION_ARG"
  1183. case SQLITE_LIMIT_ATTACHED:
  1184. return "SQLITE_LIMIT_ATTACHED"
  1185. case SQLITE_LIMIT_LIKE_PATTERN_LENGTH:
  1186. return "SQLITE_LIMIT_LIKE_PATTERN_LENGTH"
  1187. case SQLITE_LIMIT_VARIABLE_NUMBER:
  1188. return "SQLITE_LIMIT_VARIABLE_NUMBER"
  1189. case SQLITE_LIMIT_TRIGGER_DEPTH:
  1190. return "SQLITE_LIMIT_TRIGGER_DEPTH"
  1191. case SQLITE_LIMIT_WORKER_THREADS:
  1192. return "SQLITE_LIMIT_WORKER_THREADS"
  1193. }
  1194. }
  1195. // Limit sets a runtime limit on the connection. The the previous value of the
  1196. // limit is returned. Pass a negative value to check the limit without changing
  1197. // it.
  1198. //
  1199. // https://sqlite.org/c3ref/limit.html
  1200. func (conn *Conn) Limit(id Limit, value int) int {
  1201. return int(C.sqlite3_limit(conn.conn, C.int(id), C.int(value)))
  1202. }
  1203. var (
  1204. sqliteInit sync.Once
  1205. )
  1206. func sqliteInitFn() {
  1207. if Logger != nil {
  1208. C.enable_logging()
  1209. }
  1210. }
  1211. //export go_log_fn
  1212. func go_log_fn(_ unsafe.Pointer, code C.int, msg *C.char) {
  1213. var msgBytes []byte
  1214. if msg != nil {
  1215. str := C.GoString(msg) // TODO: do not copy msg.
  1216. msgBytes = []byte(str)
  1217. }
  1218. Logger(ErrorCode(code), msgBytes)
  1219. }
  1220. // Logger is written to by SQLite.
  1221. // The Logger must be set before any connection is opened.
  1222. // The msg slice is only valid for the duration of the call.
  1223. //
  1224. // It is very noisy.
  1225. var Logger func(code ErrorCode, msg []byte)