sqlite.go 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409
  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 (
  19. "bytes"
  20. "fmt"
  21. "strings"
  22. "sync"
  23. "time"
  24. "unsafe"
  25. "modernc.org/libc"
  26. "modernc.org/libc/sys/types"
  27. lib "modernc.org/sqlite/lib"
  28. )
  29. // Version is the SQLite version in the format "X.Y.Z" where X is the major
  30. // version number (always 3), Y is the minor version number, and Z is the
  31. // release number.
  32. const Version = lib.SQLITE_VERSION
  33. // VersionNumber is an integer with the value (X*1000000 + Y*1000 + Z) where X
  34. // is the major version number (always 3), Y is the minor version number, and Z
  35. // is the release number.
  36. const VersionNumber = lib.SQLITE_VERSION_NUMBER
  37. // Conn is an open connection to an SQLite3 database.
  38. //
  39. // A Conn can only be used by goroutine at a time.
  40. type Conn struct {
  41. tls *libc.TLS
  42. conn uintptr
  43. stmts map[string]*Stmt // query -> prepared statement
  44. closed bool
  45. cancelCh chan struct{}
  46. doneCh <-chan struct{}
  47. unlockNote uintptr
  48. file string
  49. line int
  50. }
  51. const ptrSize = types.Size_t(unsafe.Sizeof(uintptr(0)))
  52. // OpenConn opens a single SQLite database connection with the given flags.
  53. // No flags or a value of 0 defaults to the following:
  54. //
  55. // - [OpenReadWrite]
  56. // - [OpenCreate]
  57. // - [OpenWAL]
  58. // - [OpenURI]
  59. //
  60. // https://www.sqlite.org/c3ref/open.html
  61. func OpenConn(path string, flags ...OpenFlags) (*Conn, error) {
  62. var openFlags OpenFlags
  63. for _, f := range flags {
  64. openFlags |= f
  65. }
  66. if openFlags == 0 {
  67. openFlags = OpenReadWrite | OpenCreate | OpenWAL | OpenURI
  68. }
  69. c, err := openConn(path, openFlags&^(OpenWAL|OpenFullMutex)|OpenNoMutex)
  70. if err != nil {
  71. return nil, err
  72. }
  73. // Disable double-quoted string literals.
  74. varArgs := libc.NewVaList(int32(0), uintptr(0))
  75. if varArgs == 0 {
  76. c.Close()
  77. return nil, fmt.Errorf("sqlite: open %q: cannot allocate memory", path)
  78. }
  79. defer libc.Xfree(c.tls, varArgs)
  80. res := ResultCode(lib.Xsqlite3_db_config(
  81. c.tls,
  82. c.conn,
  83. lib.SQLITE_DBCONFIG_DQS_DDL,
  84. varArgs,
  85. ))
  86. if err := res.ToError(); err != nil {
  87. // Making error opaque because it's not part of the primary connection
  88. // opening and reflects an internal error.
  89. c.Close()
  90. return nil, fmt.Errorf("sqlite: open %q: disable double-quoted string literals: %v", path, err)
  91. }
  92. res = ResultCode(lib.Xsqlite3_db_config(
  93. c.tls,
  94. c.conn,
  95. lib.SQLITE_DBCONFIG_DQS_DML,
  96. varArgs,
  97. ))
  98. if err := res.ToError(); err != nil {
  99. // Making error opaque because it's not part of the primary connection
  100. // opening and reflects an internal error.
  101. c.Close()
  102. return nil, fmt.Errorf("sqlite: open %q: disable double-quoted string literals: %v", path, err)
  103. }
  104. if openFlags&OpenWAL != 0 {
  105. // Set timeout for enabling WAL.
  106. // See https://github.com/crawshaw/sqlite/pull/113 for details.
  107. // TODO(maybe): Pass in Context to OpenConn?
  108. c.SetBusyTimeout(10 * time.Second)
  109. stmt, _, err := c.PrepareTransient("PRAGMA journal_mode=wal;")
  110. if err != nil {
  111. c.Close()
  112. return nil, fmt.Errorf("sqlite: open %q: %w", path, err)
  113. }
  114. _, err = stmt.Step()
  115. stmt.Finalize()
  116. if err != nil {
  117. c.Close()
  118. return nil, fmt.Errorf("sqlite: open %q: enable wal: %w", path, err)
  119. }
  120. }
  121. c.SetBlockOnBusy()
  122. return c, nil
  123. }
  124. var allConns struct {
  125. mu sync.RWMutex
  126. table map[uintptr]*Conn
  127. }
  128. func openConn(path string, openFlags OpenFlags) (_ *Conn, err error) {
  129. tls := libc.NewTLS()
  130. defer func() {
  131. if err != nil {
  132. tls.Close()
  133. }
  134. }()
  135. unlockNote, err := allocUnlockNote(tls)
  136. if err != nil {
  137. return nil, fmt.Errorf("sqlite: open %q: %w", path, err)
  138. }
  139. defer func() {
  140. if err != nil {
  141. libc.Xfree(tls, unlockNote)
  142. }
  143. }()
  144. cpath, err := libc.CString(path)
  145. if err != nil {
  146. return nil, fmt.Errorf("sqlite: open %q: %w", path, err)
  147. }
  148. defer libc.Xfree(tls, cpath)
  149. connPtr, err := malloc(tls, ptrSize)
  150. if err != nil {
  151. return nil, fmt.Errorf("sqlite: open %q: %w", path, err)
  152. }
  153. defer libc.Xfree(tls, connPtr)
  154. res := ResultCode(lib.Xsqlite3_open_v2(tls, cpath, connPtr, int32(openFlags), 0))
  155. c := &Conn{
  156. tls: tls,
  157. conn: *(*uintptr)(unsafe.Pointer(connPtr)),
  158. stmts: make(map[string]*Stmt),
  159. unlockNote: unlockNote,
  160. }
  161. if c.conn == 0 {
  162. // Not enough memory to allocate the sqlite3 object.
  163. return nil, fmt.Errorf("sqlite: open %q: %w", path, sqliteError{res})
  164. }
  165. if res != ResultOK {
  166. // sqlite3_open_v2 may still return a sqlite3* just so we can extract the error.
  167. extres := ResultCode(lib.Xsqlite3_extended_errcode(tls, c.conn))
  168. if extres != 0 {
  169. res = extres
  170. }
  171. lib.Xsqlite3_close_v2(tls, c.conn)
  172. return nil, fmt.Errorf("sqlite: open %q: %w", path, sqliteError{res})
  173. }
  174. lib.Xsqlite3_extended_result_codes(tls, c.conn, 1)
  175. allConns.mu.Lock()
  176. if allConns.table == nil {
  177. allConns.table = make(map[uintptr]*Conn)
  178. }
  179. allConns.table[c.conn] = c
  180. allConns.mu.Unlock()
  181. return c, nil
  182. }
  183. // Close closes the database connection using sqlite3_close and finalizes
  184. // persistent prepared statements. https://www.sqlite.org/c3ref/close.html
  185. func (c *Conn) Close() error {
  186. if c == nil {
  187. return fmt.Errorf("sqlite: close: nil connection")
  188. }
  189. c.cancelInterrupt()
  190. c.closed = true
  191. for _, stmt := range c.stmts {
  192. stmt.Finalize()
  193. }
  194. res := ResultCode(lib.Xsqlite3_close(c.tls, c.conn))
  195. libc.Xfree(c.tls, c.unlockNote)
  196. c.unlockNote = 0
  197. c.tls.Close()
  198. c.tls = nil
  199. c.releaseAuthorizer()
  200. busyHandlers.Delete(c.conn)
  201. allConns.mu.Lock()
  202. delete(allConns.table, c.conn)
  203. allConns.mu.Unlock()
  204. if !res.IsSuccess() {
  205. return fmt.Errorf("sqlite: close: %w", sqliteError{res})
  206. }
  207. return nil
  208. }
  209. // AutocommitEnabled reports whether conn is in autocommit mode.
  210. // https://sqlite.org/c3ref/get_autocommit.html
  211. func (c *Conn) AutocommitEnabled() bool {
  212. if c == nil {
  213. return false
  214. }
  215. return lib.Xsqlite3_get_autocommit(c.tls, c.conn) != 0
  216. }
  217. // CheckReset reports whether any statement on this connection is in the process
  218. // of returning results.
  219. func (c *Conn) CheckReset() string {
  220. if c != nil {
  221. for _, stmt := range c.stmts {
  222. if stmt.lastHasRow {
  223. return stmt.query
  224. }
  225. }
  226. }
  227. return ""
  228. }
  229. // SetInterrupt assigns a channel to control connection execution lifetime.
  230. //
  231. // When doneCh is closed, the connection uses sqlite3_interrupt to
  232. // stop long-running queries and cancels any *Stmt.Step calls that
  233. // are blocked waiting for the database write lock.
  234. //
  235. // Subsequent uses of the connection will return SQLITE_INTERRUPT
  236. // errors until doneCh is reset with a subsequent call to SetInterrupt.
  237. //
  238. // Any busy statements at the time SetInterrupt is called will be reset.
  239. //
  240. // SetInterrupt returns the old doneCh assigned to the connection.
  241. func (c *Conn) SetInterrupt(doneCh <-chan struct{}) (oldDoneCh <-chan struct{}) {
  242. if c == nil {
  243. return nil
  244. }
  245. if c.closed {
  246. panic("sqlite.Conn is closed")
  247. }
  248. oldDoneCh = c.doneCh
  249. c.cancelInterrupt()
  250. c.doneCh = doneCh
  251. for _, stmt := range c.stmts {
  252. if stmt.lastHasRow {
  253. stmt.Reset()
  254. }
  255. }
  256. if doneCh == nil {
  257. return oldDoneCh
  258. }
  259. cancelCh := make(chan struct{})
  260. c.cancelCh = cancelCh
  261. go func() {
  262. select {
  263. case <-doneCh:
  264. lib.Xsqlite3_interrupt(c.tls, c.conn)
  265. fireUnlockNote(c.tls, c.unlockNote)
  266. <-cancelCh
  267. cancelCh <- struct{}{}
  268. case <-cancelCh:
  269. cancelCh <- struct{}{}
  270. }
  271. }()
  272. return oldDoneCh
  273. }
  274. // SetBusyTimeout sets a busy handler that sleeps for up to d to acquire a lock.
  275. // Passing a non-positive value will turn off all busy handlers.
  276. //
  277. // By default, connections are opened with SetBlockOnBusy,
  278. // with the assumption that programs use SetInterrupt to control timeouts.
  279. //
  280. // https://www.sqlite.org/c3ref/busy_timeout.html
  281. func (c *Conn) SetBusyTimeout(d time.Duration) {
  282. if c != nil {
  283. lib.Xsqlite3_busy_timeout(c.tls, c.conn, int32(d/time.Millisecond))
  284. busyHandlers.Delete(c.conn)
  285. }
  286. }
  287. // SetBlockOnBusy sets a busy handler that waits to acquire a lock
  288. // until the connection is interrupted (see SetInterrupt).
  289. //
  290. // By default, connections are opened with SetBlockOnBusy,
  291. // with the assumption that programs use SetInterrupt to control timeouts.
  292. //
  293. // https://www.sqlite.org/c3ref/busy_handler.html
  294. func (c *Conn) SetBlockOnBusy() {
  295. if c == nil {
  296. return
  297. }
  298. c.setBusyHandler(func(count int) bool {
  299. if count >= len(busyDelays) {
  300. count = len(busyDelays) - 1
  301. }
  302. t := time.NewTimer(busyDelays[count])
  303. defer t.Stop()
  304. select {
  305. case <-t.C:
  306. return true
  307. case <-c.doneCh:
  308. // ^ Assuming that doneCh won't be set by SetInterrupt concurrently
  309. // with other operations.
  310. return false
  311. }
  312. })
  313. }
  314. var busyDelays = [...]time.Duration{
  315. 1 * time.Second,
  316. 2 * time.Second,
  317. 5 * time.Second,
  318. 10 * time.Second,
  319. 15 * time.Second,
  320. 20 * time.Second,
  321. 25 * time.Second,
  322. 25 * time.Second,
  323. 25 * time.Second,
  324. 50 * time.Second,
  325. 50 * time.Second,
  326. 100 * time.Second,
  327. }
  328. var busyHandlers sync.Map // sqlite3* -> func(int) bool
  329. func (c *Conn) setBusyHandler(handler func(count int) bool) {
  330. if c == nil {
  331. return
  332. }
  333. if handler == nil {
  334. lib.Xsqlite3_busy_handler(c.tls, c.conn, 0, 0)
  335. busyHandlers.Delete(c.conn)
  336. return
  337. }
  338. busyHandlers.Store(c.conn, handler)
  339. xBusy := cFuncPointer(busyHandlerCallback)
  340. lib.Xsqlite3_busy_handler(c.tls, c.conn, xBusy, c.conn)
  341. }
  342. func busyHandlerCallback(tls *libc.TLS, pArg uintptr, count int32) int32 {
  343. val, _ := busyHandlers.Load(pArg)
  344. if val == nil {
  345. return 0
  346. }
  347. f := val.(func(int) bool)
  348. if !f(int(count)) {
  349. return 0
  350. }
  351. return 1
  352. }
  353. func (c *Conn) interrupted() error {
  354. select {
  355. case <-c.doneCh:
  356. return sqliteError{ResultInterrupt}
  357. default:
  358. return nil
  359. }
  360. }
  361. func (c *Conn) cancelInterrupt() {
  362. if c.cancelCh != nil {
  363. c.cancelCh <- struct{}{}
  364. <-c.cancelCh
  365. c.cancelCh = nil
  366. }
  367. }
  368. // Prep returns a persistent SQL statement.
  369. //
  370. // Any error in preparation will panic.
  371. //
  372. // Persistent prepared statements are cached by the query
  373. // string in a Conn. If Finalize is not called, then subsequent
  374. // calls to Prepare will return the same statement.
  375. //
  376. // https://www.sqlite.org/c3ref/prepare.html
  377. func (c *Conn) Prep(query string) *Stmt {
  378. stmt, err := c.Prepare(query)
  379. if err != nil {
  380. if ErrCode(err) == ResultInterrupt {
  381. return &Stmt{
  382. conn: c,
  383. query: query,
  384. colNames: make(map[string]int),
  385. prepInterrupt: true,
  386. }
  387. }
  388. panic(err)
  389. }
  390. return stmt
  391. }
  392. // Prepare prepares a persistent SQL statement.
  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. // If the query has any unprocessed trailing bytes, Prepare
  399. // returns an error.
  400. //
  401. // https://www.sqlite.org/c3ref/prepare.html
  402. func (c *Conn) Prepare(query string) (*Stmt, error) {
  403. if c == nil {
  404. return nil, fmt.Errorf("sqlite: prepare %q: nil connection", query)
  405. }
  406. if stmt := c.stmts[query]; stmt != nil {
  407. if err := stmt.Reset(); err != nil {
  408. return nil, err
  409. }
  410. if err := stmt.ClearBindings(); err != nil {
  411. return nil, err
  412. }
  413. return stmt, nil
  414. }
  415. stmt, trailingBytes, err := c.prepare(query, lib.SQLITE_PREPARE_PERSISTENT)
  416. if err != nil {
  417. return nil, fmt.Errorf("sqlite: prepare %q: %w", query, err)
  418. }
  419. if trailingBytes != 0 {
  420. stmt.Finalize()
  421. return nil, fmt.Errorf("sqlite: prepare %q: statement has trailing bytes", query)
  422. }
  423. c.stmts[query] = stmt
  424. return stmt, nil
  425. }
  426. // PrepareTransient prepares an SQL statement that is not cached by
  427. // the Conn. Subsequent calls with the same query will create new Stmts.
  428. // Finalize must be called by the caller once done with the Stmt.
  429. //
  430. // The number of trailing bytes not consumed from query is returned.
  431. //
  432. // To run a sequence of queries once as part of a script,
  433. // the sqlitex package provides an ExecScript function built on this.
  434. //
  435. // https://www.sqlite.org/c3ref/prepare.html
  436. func (c *Conn) PrepareTransient(query string) (stmt *Stmt, trailingBytes int, err error) {
  437. if c == nil {
  438. return nil, 0, fmt.Errorf("sqlite: prepare %q: nil connection", query)
  439. }
  440. // TODO(soon)
  441. // if stmt != nil {
  442. // runtime.SetFinalizer(stmt, func(stmt *Stmt) {
  443. // if stmt.conn != nil {
  444. // panic("open *sqlite.Stmt \"" + query + "\" garbage collected, call Finalize")
  445. // }
  446. // })
  447. // }
  448. return c.prepare(query, 0)
  449. }
  450. func (c *Conn) prepare(query string, flags uint32) (*Stmt, int, error) {
  451. if err := c.interrupted(); err != nil {
  452. return nil, 0, err
  453. }
  454. cquery, err := libc.CString(query)
  455. if err != nil {
  456. return nil, 0, err
  457. }
  458. defer libc.Xfree(c.tls, cquery)
  459. ctrailingPtr, err := malloc(c.tls, ptrSize)
  460. if err != nil {
  461. return nil, 0, err
  462. }
  463. defer libc.Xfree(c.tls, ctrailingPtr)
  464. stmtPtr, err := malloc(c.tls, ptrSize)
  465. if err != nil {
  466. return nil, 0, err
  467. }
  468. defer libc.Xfree(c.tls, stmtPtr)
  469. res := ResultCode(lib.Xsqlite3_prepare_v3(c.tls, c.conn, cquery, -1, flags, stmtPtr, ctrailingPtr))
  470. if err := c.extreserr(res); err != nil {
  471. return nil, 0, err
  472. }
  473. ctrailing := *(*uintptr)(unsafe.Pointer(ctrailingPtr))
  474. trailingBytes := len(query) - int(ctrailing-cquery)
  475. stmt := &Stmt{
  476. conn: c,
  477. query: query,
  478. stmt: *(*uintptr)(unsafe.Pointer(stmtPtr)),
  479. }
  480. stmt.bindNames = make([]string, lib.Xsqlite3_bind_parameter_count(c.tls, stmt.stmt))
  481. for i := range stmt.bindNames {
  482. cname := lib.Xsqlite3_bind_parameter_name(c.tls, stmt.stmt, int32(i+1))
  483. if cname != 0 {
  484. stmt.bindNames[i] = libc.GoString(cname)
  485. }
  486. }
  487. colCount := int(lib.Xsqlite3_column_count(c.tls, stmt.stmt))
  488. stmt.colNames = make(map[string]int, colCount)
  489. for i := 0; i < colCount; i++ {
  490. cname := lib.Xsqlite3_column_name(c.tls, stmt.stmt, int32(i))
  491. if cname != 0 {
  492. stmt.colNames[libc.GoString(cname)] = i
  493. }
  494. }
  495. return stmt, trailingBytes, nil
  496. }
  497. // Changes reports the number of rows affected by the most recent statement.
  498. //
  499. // https://www.sqlite.org/c3ref/changes.html
  500. func (c *Conn) Changes() int {
  501. if c == nil {
  502. return 0
  503. }
  504. return int(lib.Xsqlite3_changes(c.tls, c.conn))
  505. }
  506. // LastInsertRowID reports the rowid of the most recently successful INSERT.
  507. //
  508. // https://www.sqlite.org/c3ref/last_insert_rowid.html
  509. func (c *Conn) LastInsertRowID() int64 {
  510. if c == nil {
  511. return 0
  512. }
  513. return lib.Xsqlite3_last_insert_rowid(c.tls, c.conn)
  514. }
  515. // Serialize serializes the database with the given name (e.g. "main" or "temp").
  516. func (c *Conn) Serialize(dbName string) ([]byte, error) {
  517. if c == nil {
  518. return nil, fmt.Errorf("sqlite: serialize %q: nil connection", dbName)
  519. }
  520. zSchema, cleanup, err := cDBName(dbName)
  521. if err != nil {
  522. return nil, fmt.Errorf("sqlite: serialize %q: %v", dbName, err)
  523. }
  524. defer cleanup()
  525. piSize := lib.Xsqlite3_malloc(c.tls, int32(unsafe.Sizeof(int64(0))))
  526. if piSize == 0 {
  527. return nil, fmt.Errorf("sqlite: serialize %q: memory allocation failure", dbName)
  528. }
  529. defer lib.Xsqlite3_free(c.tls, piSize)
  530. // Optimization: avoid copying if possible.
  531. p := lib.Xsqlite3_serialize(c.tls, c.conn, zSchema, piSize, lib.SQLITE_SERIALIZE_NOCOPY)
  532. if p == 0 {
  533. // Optimization impossible. Have SQLite allocate memory.
  534. p = lib.Xsqlite3_serialize(c.tls, c.conn, zSchema, piSize, 0)
  535. if p == 0 {
  536. return nil, fmt.Errorf("sqlite: serialize %q: unable to serialize", dbName)
  537. }
  538. defer lib.Xsqlite3_free(c.tls, p)
  539. }
  540. // Copy data into a Go byte slice.
  541. n := *(*int64)(unsafe.Pointer(piSize))
  542. goCopy := make([]byte, n)
  543. copy(goCopy, libc.GoBytes(p, int(n)))
  544. return goCopy, nil
  545. }
  546. // Deserialize disconnects the database with the given name (e.g. "main")
  547. // and reopens it as an in-memory database based on the serialized data.
  548. // The database name must already exist.
  549. // It is not possible to deserialize into the TEMP database.
  550. func (c *Conn) Deserialize(dbName string, data []byte) error {
  551. if c == nil {
  552. return fmt.Errorf("sqlite: deserialize to %q: nil connection", dbName)
  553. }
  554. zSchema, cleanup, err := cDBName(dbName)
  555. if err != nil {
  556. return fmt.Errorf("sqlite: deserialize to %q: %v", dbName, err)
  557. }
  558. defer cleanup()
  559. n := int64(len(data))
  560. pData := lib.Xsqlite3_malloc64(c.tls, uint64(n))
  561. if pData == 0 {
  562. return fmt.Errorf("sqlite: deserialize to %q: memory allocation failure", dbName)
  563. }
  564. copy(libc.GoBytes(pData, len(data)), data)
  565. res := ResultCode(lib.Xsqlite3_deserialize(c.tls, c.conn, zSchema, pData, n, n, lib.SQLITE_DESERIALIZE_FREEONCLOSE|lib.SQLITE_DESERIALIZE_RESIZEABLE))
  566. if !res.IsSuccess() {
  567. return fmt.Errorf("sqlite: deserialize to %q: %w", dbName, res.ToError())
  568. }
  569. return nil
  570. }
  571. // extreserr asks SQLite for a string explaining the error.
  572. // Only called for errors that are probably program bugs.
  573. func (c *Conn) extreserr(res ResultCode) error {
  574. if res.IsSuccess() {
  575. return nil
  576. }
  577. if msg := libc.GoString(lib.Xsqlite3_errmsg(c.tls, c.conn)); msg != "" {
  578. return fmt.Errorf("%w: %s", res.ToError(), msg)
  579. }
  580. return res.ToError()
  581. }
  582. // Stmt is an SQLite3 prepared statement.
  583. //
  584. // A Stmt is attached to a particular Conn
  585. // (and that Conn can only be used by a single goroutine).
  586. //
  587. // When a Stmt is no longer needed it should be cleaned up
  588. // by calling the Finalize method.
  589. type Stmt struct {
  590. conn *Conn
  591. stmt uintptr
  592. query string
  593. bindNames []string
  594. colNames map[string]int
  595. bindErr error
  596. prepInterrupt bool // set if Prep was interrupted
  597. lastHasRow bool // last bool returned by Step
  598. }
  599. func (stmt *Stmt) interrupted() error {
  600. if stmt.prepInterrupt {
  601. return sqliteError{ResultInterrupt}
  602. }
  603. return stmt.conn.interrupted()
  604. }
  605. // Finalize deletes a prepared statement.
  606. //
  607. // Be sure to always call Finalize when done with
  608. // a statement created using PrepareTransient.
  609. //
  610. // Do not call Finalize on a prepared statement that
  611. // you intend to prepare again in the future.
  612. //
  613. // https://www.sqlite.org/c3ref/finalize.html
  614. func (stmt *Stmt) Finalize() error {
  615. if ptr := stmt.conn.stmts[stmt.query]; ptr == stmt {
  616. delete(stmt.conn.stmts, stmt.query)
  617. }
  618. res := ResultCode(lib.Xsqlite3_finalize(stmt.conn.tls, stmt.stmt))
  619. stmt.conn = nil
  620. if err := res.ToError(); err != nil {
  621. return fmt.Errorf("sqlite: finalize: %w", err)
  622. }
  623. return nil
  624. }
  625. // Reset resets a prepared statement so it can be executed again.
  626. //
  627. // Note that any parameter values bound to the statement are retained.
  628. // To clear bound values, call ClearBindings.
  629. //
  630. // https://www.sqlite.org/c3ref/reset.html
  631. func (stmt *Stmt) Reset() error {
  632. stmt.lastHasRow = false
  633. var res ResultCode
  634. for {
  635. res = ResultCode(lib.Xsqlite3_reset(stmt.conn.tls, stmt.stmt))
  636. if res != ResultLockedSharedCache {
  637. break
  638. }
  639. // An SQLITE_LOCKED_SHAREDCACHE error has been seen from sqlite3_reset
  640. // in the wild, but so far has eluded exact test case replication.
  641. // TODO: write a test for this.
  642. if res := waitForUnlockNotify(stmt.conn.tls, stmt.conn.conn, stmt.conn.unlockNote); res != ResultOK {
  643. return fmt.Errorf("sqlite: reset: %w", stmt.conn.extreserr(res))
  644. }
  645. }
  646. if err := stmt.conn.extreserr(res); err != nil {
  647. return fmt.Errorf("sqlite: reset: %w", err)
  648. }
  649. return nil
  650. }
  651. // ClearBindings clears all bound parameter values on a statement.
  652. //
  653. // https://www.sqlite.org/c3ref/clear_bindings.html
  654. func (stmt *Stmt) ClearBindings() error {
  655. if err := stmt.interrupted(); err != nil {
  656. return fmt.Errorf("sqlite: clear bindings: %w", err)
  657. }
  658. res := ResultCode(lib.Xsqlite3_clear_bindings(stmt.conn.tls, stmt.stmt))
  659. if err := res.ToError(); err != nil {
  660. return fmt.Errorf("sqlite: clear bindings: %w", err)
  661. }
  662. return nil
  663. }
  664. // Step moves through the statement cursor using sqlite3_step.
  665. //
  666. // If a row of data is available, rowReturned is reported as true.
  667. // If the statement has reached the end of the available data then
  668. // rowReturned is false. Thus the status codes SQLITE_ROW and
  669. // SQLITE_DONE are reported by the rowReturned bool, and all other
  670. // non-OK status codes are reported as an error.
  671. //
  672. // If an error value is returned, then the statement has been reset.
  673. //
  674. // https://www.sqlite.org/c3ref/step.html
  675. //
  676. // # Shared cache
  677. //
  678. // As multiple writers are common in multi-threaded programs,
  679. // this Step method uses sqlite3_unlock_notify to handle any
  680. // SQLITE_LOCKED errors.
  681. //
  682. // Without the shared cache, SQLite will block for
  683. // several seconds while trying to acquire the write lock.
  684. // With the shared cache, it returns SQLITE_LOCKED immediately
  685. // if the write lock is held by another connection in this process.
  686. // Dealing with this correctly makes for an unpleasant programming
  687. // experience, so this package does it automatically by blocking
  688. // Step until the write lock is relinquished.
  689. //
  690. // This means Step can block for a very long time.
  691. // Use SetInterrupt to control how long Step will block.
  692. //
  693. // For far more details, see:
  694. //
  695. // http://www.sqlite.org/unlock_notify.html
  696. func (stmt *Stmt) Step() (rowReturned bool, err error) {
  697. if stmt.bindErr != nil {
  698. err = stmt.bindErr
  699. stmt.bindErr = nil
  700. stmt.Reset()
  701. return false, fmt.Errorf("sqlite: step: %w", err)
  702. }
  703. rowReturned, err = stmt.step()
  704. stmt.lastHasRow = rowReturned
  705. if err != nil {
  706. lib.Xsqlite3_reset(stmt.conn.tls, stmt.stmt)
  707. return rowReturned, fmt.Errorf("sqlite: step: %w", err)
  708. }
  709. return rowReturned, nil
  710. }
  711. func (stmt *Stmt) step() (bool, error) {
  712. for {
  713. if err := stmt.interrupted(); err != nil {
  714. return false, err
  715. }
  716. switch res := ResultCode(lib.Xsqlite3_step(stmt.conn.tls, stmt.stmt)); res.ToPrimary() {
  717. case ResultLocked:
  718. if res != ResultLockedSharedCache {
  719. // don't call waitForUnlockNotify as it might deadlock, see:
  720. // https://github.com/crawshaw/sqlite/issues/6
  721. return false, stmt.conn.extreserr(res)
  722. }
  723. if res := waitForUnlockNotify(stmt.conn.tls, stmt.conn.conn, stmt.conn.unlockNote); !res.IsSuccess() {
  724. return false, stmt.conn.extreserr(res)
  725. }
  726. lib.Xsqlite3_reset(stmt.conn.tls, stmt.stmt)
  727. // loop
  728. case ResultRow:
  729. return true, nil
  730. case ResultDone:
  731. return false, nil
  732. case ResultInterrupt:
  733. // TODO: embed some of these errors into the stmt for zero-alloc errors?
  734. return false, res.ToError()
  735. default:
  736. return false, stmt.conn.extreserr(res)
  737. }
  738. }
  739. }
  740. func (stmt *Stmt) handleBindErr(prefix string, res ResultCode) {
  741. if stmt.bindErr == nil && !res.IsSuccess() {
  742. stmt.bindErr = fmt.Errorf("%s: %w", prefix, res.ToError())
  743. }
  744. }
  745. // DataCount returns the number of columns in the current row of the result
  746. // set of prepared statement.
  747. //
  748. // https://sqlite.org/c3ref/data_count.html
  749. func (stmt *Stmt) DataCount() int {
  750. return int(lib.Xsqlite3_data_count(stmt.conn.tls, stmt.stmt))
  751. }
  752. // ColumnCount returns the number of columns in the result set returned by the
  753. // prepared statement.
  754. //
  755. // https://sqlite.org/c3ref/column_count.html
  756. func (stmt *Stmt) ColumnCount() int {
  757. return int(lib.Xsqlite3_column_count(stmt.conn.tls, stmt.stmt))
  758. }
  759. // ColumnName returns the name assigned to a particular column in the result
  760. // set of a SELECT statement.
  761. //
  762. // https://sqlite.org/c3ref/column_name.html
  763. func (stmt *Stmt) ColumnName(col int) string {
  764. return libc.GoString(lib.Xsqlite3_column_name(stmt.conn.tls, stmt.stmt, int32(col)))
  765. }
  766. // BindParamCount reports the number of parameters in stmt.
  767. //
  768. // https://www.sqlite.org/c3ref/bind_parameter_count.html
  769. func (stmt *Stmt) BindParamCount() int {
  770. if stmt.stmt == 0 {
  771. return 0
  772. }
  773. return len(stmt.bindNames)
  774. }
  775. // BindParamName returns the name of parameter or the empty string if the
  776. // parameter is nameless or i is out of range.
  777. //
  778. // Parameters indices start at 1.
  779. //
  780. // https://www.sqlite.org/c3ref/bind_parameter_name.html
  781. func (stmt *Stmt) BindParamName(i int) string {
  782. i-- // map from 1-based to 0-based
  783. if i < 0 || i >= len(stmt.bindNames) {
  784. return ""
  785. }
  786. return stmt.bindNames[i]
  787. }
  788. // BindInt64 binds value to a numbered stmt parameter.
  789. //
  790. // Parameter indices start at 1.
  791. //
  792. // https://www.sqlite.org/c3ref/bind_blob.html
  793. func (stmt *Stmt) BindInt64(param int, value int64) {
  794. if stmt.stmt == 0 {
  795. return
  796. }
  797. res := ResultCode(lib.Xsqlite3_bind_int64(stmt.conn.tls, stmt.stmt, int32(param), value))
  798. stmt.handleBindErr("bind int64", res)
  799. }
  800. // BindBool binds value (as an integer 0 or 1) to a numbered stmt parameter.
  801. //
  802. // Parameter indices start at 1.
  803. //
  804. // https://www.sqlite.org/c3ref/bind_blob.html
  805. func (stmt *Stmt) BindBool(param int, value bool) {
  806. if stmt.stmt == 0 {
  807. return
  808. }
  809. v := int64(0)
  810. if value {
  811. v = 1
  812. }
  813. res := ResultCode(lib.Xsqlite3_bind_int64(stmt.conn.tls, stmt.stmt, int32(param), v))
  814. stmt.handleBindErr("bind bool", res)
  815. }
  816. var emptyCString = mustCString("")
  817. const sqliteStatic uintptr = 0
  818. // BindBytes binds value to a numbered stmt parameter.
  819. //
  820. // In-memory copies of value are made using this interface.
  821. // For large blobs, consider using the streaming Blob object.
  822. //
  823. // Parameter indices start at 1.
  824. //
  825. // https://www.sqlite.org/c3ref/bind_blob.html
  826. func (stmt *Stmt) BindBytes(param int, value []byte) {
  827. if stmt.stmt == 0 {
  828. return
  829. }
  830. if len(value) == 0 {
  831. res := ResultCode(lib.Xsqlite3_bind_blob(stmt.conn.tls, stmt.stmt, int32(param), emptyCString, 0, sqliteStatic))
  832. stmt.handleBindErr("bind bytes", res)
  833. return
  834. }
  835. v, err := malloc(stmt.conn.tls, types.Size_t(len(value)))
  836. if err != nil {
  837. if stmt.bindErr == nil {
  838. stmt.bindErr = fmt.Errorf("bind bytes: %w", err)
  839. }
  840. return
  841. }
  842. for i, b := range value {
  843. *(*byte)(unsafe.Pointer(v + uintptr(i))) = b
  844. }
  845. res := ResultCode(lib.Xsqlite3_bind_blob(stmt.conn.tls, stmt.stmt, int32(param), v, int32(len(value)), freeFuncPtr))
  846. stmt.handleBindErr("bind bytes", res)
  847. }
  848. var freeFuncPtr = cFuncPointer(libc.Xfree)
  849. // BindText binds value to a numbered stmt parameter.
  850. //
  851. // Parameter indices start at 1.
  852. //
  853. // https://www.sqlite.org/c3ref/bind_blob.html
  854. func (stmt *Stmt) BindText(param int, value string) {
  855. if stmt.stmt == 0 {
  856. return
  857. }
  858. allocSize := types.Size_t(len(value))
  859. if allocSize == 0 {
  860. allocSize = 1
  861. }
  862. v, err := malloc(stmt.conn.tls, allocSize)
  863. if err != nil {
  864. if stmt.bindErr == nil {
  865. stmt.bindErr = fmt.Errorf("bind text: %w", err)
  866. }
  867. return
  868. }
  869. for i := 0; i < len(value); i++ {
  870. *(*byte)(unsafe.Pointer(v + uintptr(i))) = value[i]
  871. }
  872. res := ResultCode(lib.Xsqlite3_bind_text(stmt.conn.tls, stmt.stmt, int32(param), v, int32(len(value)), freeFuncPtr))
  873. stmt.handleBindErr("bind text", res)
  874. }
  875. // BindFloat binds value to a numbered stmt parameter.
  876. //
  877. // Parameter indices start at 1.
  878. //
  879. // https://www.sqlite.org/c3ref/bind_blob.html
  880. func (stmt *Stmt) BindFloat(param int, value float64) {
  881. if stmt.stmt == 0 {
  882. return
  883. }
  884. res := ResultCode(lib.Xsqlite3_bind_double(stmt.conn.tls, stmt.stmt, int32(param), value))
  885. stmt.handleBindErr("bind float", res)
  886. }
  887. // BindNull binds an SQL NULL value to a numbered stmt parameter.
  888. //
  889. // Parameter indices start at 1.
  890. //
  891. // https://www.sqlite.org/c3ref/bind_blob.html
  892. func (stmt *Stmt) BindNull(param int) {
  893. if stmt.stmt == 0 {
  894. return
  895. }
  896. res := ResultCode(lib.Xsqlite3_bind_null(stmt.conn.tls, stmt.stmt, int32(param)))
  897. stmt.handleBindErr("bind null", res)
  898. }
  899. // BindZeroBlob binds a blob of zeros of length len to a numbered stmt parameter.
  900. //
  901. // Parameter indices start at 1.
  902. //
  903. // https://www.sqlite.org/c3ref/bind_blob.html
  904. func (stmt *Stmt) BindZeroBlob(param int, len int64) {
  905. if stmt.stmt == 0 {
  906. return
  907. }
  908. res := ResultCode(lib.Xsqlite3_bind_zeroblob64(stmt.conn.tls, stmt.stmt, int32(param), uint64(len)))
  909. stmt.handleBindErr("bind zero blob", res)
  910. }
  911. func (stmt *Stmt) findBindName(prefix string, param string) int {
  912. for i, name := range stmt.bindNames {
  913. if name == param {
  914. return i + 1 // 1-based indices
  915. }
  916. }
  917. if stmt.bindErr == nil {
  918. stmt.bindErr = fmt.Errorf("%s: unknown parameter: %s", prefix, param)
  919. }
  920. return 0
  921. }
  922. // SetInt64 binds an int64 to a parameter using a column name.
  923. func (stmt *Stmt) SetInt64(param string, value int64) {
  924. stmt.BindInt64(stmt.findBindName("SetInt64", param), value)
  925. }
  926. // SetBool binds a value (as a 0 or 1) to a parameter using a column name.
  927. func (stmt *Stmt) SetBool(param string, value bool) {
  928. stmt.BindBool(stmt.findBindName("SetBool", param), value)
  929. }
  930. // SetBytes binds bytes to a parameter using a column name.
  931. // An invalid parameter name will cause the call to Step to return an error.
  932. func (stmt *Stmt) SetBytes(param string, value []byte) {
  933. stmt.BindBytes(stmt.findBindName("SetBytes", param), value)
  934. }
  935. // SetText binds text to a parameter using a column name.
  936. // An invalid parameter name will cause the call to Step to return an error.
  937. func (stmt *Stmt) SetText(param string, value string) {
  938. stmt.BindText(stmt.findBindName("SetText", param), value)
  939. }
  940. // SetFloat binds a float64 to a parameter using a column name.
  941. // An invalid parameter name will cause the call to Step to return an error.
  942. func (stmt *Stmt) SetFloat(param string, value float64) {
  943. stmt.BindFloat(stmt.findBindName("SetFloat", param), value)
  944. }
  945. // SetNull binds a null to a parameter using a column name.
  946. // An invalid parameter name will cause the call to Step to return an error.
  947. func (stmt *Stmt) SetNull(param string) {
  948. stmt.BindNull(stmt.findBindName("SetNull", param))
  949. }
  950. // SetZeroBlob binds a zero blob of length len to a parameter using a column name.
  951. // An invalid parameter name will cause the call to Step to return an error.
  952. func (stmt *Stmt) SetZeroBlob(param string, len int64) {
  953. stmt.BindZeroBlob(stmt.findBindName("SetZeroBlob", param), len)
  954. }
  955. // ColumnInt returns a query result value as an int.
  956. //
  957. // Note: this method calls sqlite3_column_int64 and then converts the
  958. // resulting 64-bits to an int.
  959. //
  960. // Column indices start at 0.
  961. //
  962. // https://www.sqlite.org/c3ref/column_blob.html
  963. func (stmt *Stmt) ColumnInt(col int) int {
  964. return int(stmt.ColumnInt64(col))
  965. }
  966. // ColumnInt32 returns a query result value as an int32.
  967. //
  968. // Column indices start at 0.
  969. //
  970. // https://www.sqlite.org/c3ref/column_blob.html
  971. func (stmt *Stmt) ColumnInt32(col int) int32 {
  972. return lib.Xsqlite3_column_int(stmt.conn.tls, stmt.stmt, int32(col))
  973. }
  974. // ColumnInt64 returns a query result value as an int64.
  975. //
  976. // Column indices start at 0.
  977. //
  978. // https://www.sqlite.org/c3ref/column_blob.html
  979. func (stmt *Stmt) ColumnInt64(col int) int64 {
  980. return lib.Xsqlite3_column_int64(stmt.conn.tls, stmt.stmt, int32(col))
  981. }
  982. // ColumnBool reports whether a query result value is non-zero.
  983. //
  984. // Column indices start at 0.
  985. //
  986. // https://www.sqlite.org/c3ref/column_blob.html
  987. func (stmt *Stmt) ColumnBool(col int) bool {
  988. return stmt.ColumnInt64(col) != 0
  989. }
  990. // ColumnBytes reads a query result into buf.
  991. // It reports the number of bytes read.
  992. //
  993. // Column indices start at 0.
  994. //
  995. // https://www.sqlite.org/c3ref/column_blob.html
  996. func (stmt *Stmt) ColumnBytes(col int, buf []byte) int {
  997. return copy(buf, stmt.columnBytes(col))
  998. }
  999. // ColumnReader creates a byte reader for a query result column.
  1000. //
  1001. // The reader directly references C-managed memory that stops
  1002. // being valid as soon as the statement row resets.
  1003. func (stmt *Stmt) ColumnReader(col int) *bytes.Reader {
  1004. // Load the C memory directly into the Reader.
  1005. // There is no exported method that lets it escape.
  1006. return bytes.NewReader(stmt.columnBytes(col))
  1007. }
  1008. func (stmt *Stmt) columnBytes(col int) []byte {
  1009. p := lib.Xsqlite3_column_blob(stmt.conn.tls, stmt.stmt, int32(col))
  1010. if p == 0 {
  1011. return nil
  1012. }
  1013. n := stmt.ColumnLen(col)
  1014. return libc.GoBytes(p, n)
  1015. }
  1016. // ColumnType are codes for each of the SQLite fundamental datatypes:
  1017. //
  1018. // - 64-bit signed integer
  1019. // - 64-bit IEEE floating point number
  1020. // - string
  1021. // - BLOB
  1022. // - NULL
  1023. //
  1024. // https://www.sqlite.org/c3ref/c_blob.html
  1025. type ColumnType int
  1026. // Data types.
  1027. const (
  1028. TypeInteger ColumnType = lib.SQLITE_INTEGER
  1029. TypeFloat ColumnType = lib.SQLITE_FLOAT
  1030. TypeText ColumnType = lib.SQLITE_TEXT
  1031. TypeBlob ColumnType = lib.SQLITE_BLOB
  1032. TypeNull ColumnType = lib.SQLITE_NULL
  1033. )
  1034. // String returns the SQLite constant name of the type.
  1035. func (t ColumnType) String() string {
  1036. switch t {
  1037. case TypeInteger:
  1038. return "SQLITE_INTEGER"
  1039. case TypeFloat:
  1040. return "SQLITE_FLOAT"
  1041. case TypeText:
  1042. return "SQLITE_TEXT"
  1043. case TypeBlob:
  1044. return "SQLITE_BLOB"
  1045. case TypeNull:
  1046. return "SQLITE_NULL"
  1047. default:
  1048. return "<unknown sqlite datatype>"
  1049. }
  1050. }
  1051. // ColumnType returns the datatype code for the initial data
  1052. // type of the result column. The returned value is one of:
  1053. //
  1054. // - SQLITE_INTEGER
  1055. // - SQLITE_FLOAT
  1056. // - SQLITE_TEXT
  1057. // - SQLITE_BLOB
  1058. // - SQLITE_NULL
  1059. //
  1060. // Column indices start at 0.
  1061. //
  1062. // https://www.sqlite.org/c3ref/column_blob.html
  1063. func (stmt *Stmt) ColumnType(col int) ColumnType {
  1064. return ColumnType(lib.Xsqlite3_column_type(stmt.conn.tls, stmt.stmt, int32(col)))
  1065. }
  1066. // ColumnText returns a query result as a string.
  1067. //
  1068. // Column indices start at 0.
  1069. //
  1070. // https://www.sqlite.org/c3ref/column_blob.html
  1071. func (stmt *Stmt) ColumnText(col int) string {
  1072. n := stmt.ColumnLen(col)
  1073. return goStringN(lib.Xsqlite3_column_text(stmt.conn.tls, stmt.stmt, int32(col)), n)
  1074. }
  1075. // ColumnFloat returns a query result as a float64.
  1076. //
  1077. // Column indices start at 0.
  1078. //
  1079. // https://www.sqlite.org/c3ref/column_blob.html
  1080. func (stmt *Stmt) ColumnFloat(col int) float64 {
  1081. return lib.Xsqlite3_column_double(stmt.conn.tls, stmt.stmt, int32(col))
  1082. }
  1083. // ColumnLen returns the number of bytes in a query result.
  1084. //
  1085. // Column indices start at 0.
  1086. //
  1087. // https://www.sqlite.org/c3ref/column_blob.html
  1088. func (stmt *Stmt) ColumnLen(col int) int {
  1089. return int(lib.Xsqlite3_column_bytes(stmt.conn.tls, stmt.stmt, int32(col)))
  1090. }
  1091. func (stmt *Stmt) ColumnDatabaseName(col int) string {
  1092. return libc.GoString(lib.Xsqlite3_column_database_name(stmt.conn.tls, stmt.stmt, int32(col)))
  1093. }
  1094. func (stmt *Stmt) ColumnTableName(col int) string {
  1095. return libc.GoString(lib.Xsqlite3_column_table_name(stmt.conn.tls, stmt.stmt, int32(col)))
  1096. }
  1097. // ColumnIndex returns the index of the column with the given name.
  1098. //
  1099. // If there is no column with the given name ColumnIndex returns -1.
  1100. func (stmt *Stmt) ColumnIndex(colName string) int {
  1101. col, found := stmt.colNames[colName]
  1102. if !found {
  1103. return -1
  1104. }
  1105. return col
  1106. }
  1107. // GetInt64 returns a query result value for colName as an int64.
  1108. func (stmt *Stmt) GetInt64(colName string) int64 {
  1109. col, found := stmt.colNames[colName]
  1110. if !found {
  1111. return 0
  1112. }
  1113. return stmt.ColumnInt64(col)
  1114. }
  1115. // GetBool reports whether the query result value for colName is non-zero.
  1116. func (stmt *Stmt) GetBool(colName string) bool {
  1117. return stmt.GetInt64(colName) != 0
  1118. }
  1119. // GetBytes reads a query result for colName into buf.
  1120. // It reports the number of bytes read.
  1121. func (stmt *Stmt) GetBytes(colName string, buf []byte) int {
  1122. col, found := stmt.colNames[colName]
  1123. if !found {
  1124. return 0
  1125. }
  1126. return stmt.ColumnBytes(col, buf)
  1127. }
  1128. // GetReader creates a byte reader for colName.
  1129. //
  1130. // The reader directly references C-managed memory that stops
  1131. // being valid as soon as the statement row resets.
  1132. func (stmt *Stmt) GetReader(colName string) *bytes.Reader {
  1133. col, found := stmt.colNames[colName]
  1134. if !found {
  1135. return bytes.NewReader(nil)
  1136. }
  1137. return stmt.ColumnReader(col)
  1138. }
  1139. // GetText returns a query result value for colName as a string.
  1140. func (stmt *Stmt) GetText(colName string) string {
  1141. col, found := stmt.colNames[colName]
  1142. if !found {
  1143. return ""
  1144. }
  1145. return stmt.ColumnText(col)
  1146. }
  1147. // GetFloat returns a query result value for colName as a float64.
  1148. func (stmt *Stmt) GetFloat(colName string) float64 {
  1149. col, found := stmt.colNames[colName]
  1150. if !found {
  1151. return 0
  1152. }
  1153. return stmt.ColumnFloat(col)
  1154. }
  1155. // GetLen returns the number of bytes in a query result for colName.
  1156. func (stmt *Stmt) GetLen(colName string) int {
  1157. col, found := stmt.colNames[colName]
  1158. if !found {
  1159. return 0
  1160. }
  1161. return stmt.ColumnLen(col)
  1162. }
  1163. func malloc(tls *libc.TLS, n types.Size_t) (uintptr, error) {
  1164. p := libc.Xmalloc(tls, n)
  1165. if p == 0 {
  1166. return 0, fmt.Errorf("out of memory")
  1167. }
  1168. return p, nil
  1169. }
  1170. func mustCString(s string) uintptr {
  1171. p, err := libc.CString(s)
  1172. if err != nil {
  1173. panic(err)
  1174. }
  1175. return p
  1176. }
  1177. func goStringN(s uintptr, n int) string {
  1178. if s == 0 {
  1179. return ""
  1180. }
  1181. var buf strings.Builder
  1182. buf.Grow(n)
  1183. for i := 0; i < n; i++ {
  1184. buf.WriteByte(*(*byte)(unsafe.Pointer(s)))
  1185. s++
  1186. }
  1187. return buf.String()
  1188. }
  1189. // cFuncPointer converts a function defined by a function declaration to a C pointer.
  1190. // The result of using cFuncPointer on closures is undefined.
  1191. func cFuncPointer[T any](f T) uintptr {
  1192. // This assumes the memory representation described in https://golang.org/s/go11func.
  1193. //
  1194. // cFuncPointer does its conversion by doing the following in order:
  1195. // 1) Create a Go struct containing a pointer to a pointer to
  1196. // the function. It is assumed that the pointer to the function will be
  1197. // stored in the read-only data section and thus will not move.
  1198. // 2) Convert the pointer to the Go struct to a pointer to uintptr through
  1199. // unsafe.Pointer. This is permitted via Rule #1 of unsafe.Pointer.
  1200. // 3) Dereference the pointer to uintptr to obtain the function value as a
  1201. // uintptr. This is safe as long as function values are passed as pointers.
  1202. return *(*uintptr)(unsafe.Pointer(&struct{ f T }{f}))
  1203. }
  1204. // Limit is a category of performance limits.
  1205. //
  1206. // https://sqlite.org/c3ref/c_limit_attached.html
  1207. type Limit int32
  1208. // Limit categories.
  1209. const (
  1210. LimitLength Limit = lib.SQLITE_LIMIT_LENGTH
  1211. LimitSQLLength Limit = lib.SQLITE_LIMIT_SQL_LENGTH
  1212. LimitColumn Limit = lib.SQLITE_LIMIT_COLUMN
  1213. LimitExprDepth Limit = lib.SQLITE_LIMIT_EXPR_DEPTH
  1214. LimitCompoundSelect Limit = lib.SQLITE_LIMIT_COMPOUND_SELECT
  1215. LimitVDBEOp Limit = lib.SQLITE_LIMIT_VDBE_OP
  1216. LimitFunctionArg Limit = lib.SQLITE_LIMIT_FUNCTION_ARG
  1217. LimitAttached Limit = lib.SQLITE_LIMIT_ATTACHED
  1218. LimitLikePatternLength Limit = lib.SQLITE_LIMIT_LIKE_PATTERN_LENGTH
  1219. LimitVariableNumber Limit = lib.SQLITE_LIMIT_VARIABLE_NUMBER
  1220. LimitTriggerDepth Limit = lib.SQLITE_LIMIT_TRIGGER_DEPTH
  1221. LimitWorkerThreads Limit = lib.SQLITE_LIMIT_WORKER_THREADS
  1222. )
  1223. // String returns the limit's C constant name.
  1224. func (limit Limit) String() string {
  1225. switch limit {
  1226. case LimitLength:
  1227. return "SQLITE_LIMIT_LENGTH"
  1228. case LimitSQLLength:
  1229. return "SQLITE_LIMIT_SQL_LENGTH"
  1230. case LimitColumn:
  1231. return "SQLITE_LIMIT_COLUMN"
  1232. case LimitExprDepth:
  1233. return "SQLITE_LIMIT_EXPR_DEPTH"
  1234. case LimitCompoundSelect:
  1235. return "SQLITE_LIMIT_COMPOUND_SELECT"
  1236. case LimitVDBEOp:
  1237. return "SQLITE_LIMIT_VDBE_OP"
  1238. case LimitFunctionArg:
  1239. return "SQLITE_LIMIT_FUNCTION_ARG"
  1240. case LimitAttached:
  1241. return "SQLITE_LIMIT_ATTACHED"
  1242. case LimitLikePatternLength:
  1243. return "SQLITE_LIMIT_LIKE_PATTERN_LENGTH"
  1244. case LimitVariableNumber:
  1245. return "SQLITE_LIMIT_VARIABLE_NUMBER"
  1246. case LimitTriggerDepth:
  1247. return "SQLITE_LIMIT_TRIGGER_DEPTH"
  1248. case LimitWorkerThreads:
  1249. return "SQLITE_LIMIT_WORKER_THREADS"
  1250. default:
  1251. return fmt.Sprintf("Limit(%d)", int32(limit))
  1252. }
  1253. }
  1254. // Limit sets a runtime limit on the connection. The the previous value of the
  1255. // limit is returned. Pass a negative value to check the limit without changing
  1256. // it.
  1257. //
  1258. // https://sqlite.org/c3ref/limit.html
  1259. func (c *Conn) Limit(id Limit, value int32) int32 {
  1260. if c == nil {
  1261. return 0
  1262. }
  1263. return lib.Xsqlite3_limit(c.tls, c.conn, int32(id), int32(value))
  1264. }
  1265. // SetDefensive sets the "defensive" flag for a database connection. When the
  1266. // defensive flag is enabled, language features that allow ordinary SQL to
  1267. // deliberately corrupt the database file are disabled. The disabled features
  1268. // include but are not limited to the following:
  1269. //
  1270. // - The PRAGMA writable_schema=ON statement.
  1271. // - The PRAGMA journal_mode=OFF statement.
  1272. // - Writes to the sqlite_dbpage virtual table.
  1273. // - Direct writes to shadow tables.
  1274. func (c *Conn) SetDefensive(enabled bool) error {
  1275. if c == nil {
  1276. return fmt.Errorf("sqlite: set defensive=%t: nil connection", enabled)
  1277. }
  1278. enabledInt := int32(0)
  1279. if enabled {
  1280. enabledInt = 1
  1281. }
  1282. varArgs := libc.NewVaList(enabledInt)
  1283. if varArgs == 0 {
  1284. return fmt.Errorf("sqlite: set defensive=%t: cannot allocate memory", enabled)
  1285. }
  1286. defer libc.Xfree(c.tls, varArgs)
  1287. res := ResultCode(lib.Xsqlite3_db_config(
  1288. c.tls,
  1289. c.conn,
  1290. lib.SQLITE_DBCONFIG_DEFENSIVE,
  1291. varArgs,
  1292. ))
  1293. if err := res.ToError(); err != nil {
  1294. return fmt.Errorf("sqlite: set defensive=%t: %w", enabled, err)
  1295. }
  1296. return nil
  1297. }