You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1029 lines
25 KiB

  1. // Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>.
  2. //
  3. // Use of this source code is governed by an MIT-style
  4. // license that can be found in the LICENSE file.
  5. package sqlite3
  6. /*
  7. #cgo CFLAGS: -std=gnu99
  8. #cgo CFLAGS: -DSQLITE_ENABLE_RTREE -DSQLITE_THREADSAFE=1
  9. #cgo CFLAGS: -DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_FTS3_PARENTHESIS -DSQLITE_ENABLE_FTS4_UNICODE61
  10. #cgo CFLAGS: -DSQLITE_TRACE_SIZE_LIMIT=15
  11. #cgo CFLAGS: -DSQLITE_DISABLE_INTRINSIC
  12. #cgo CFLAGS: -Wno-deprecated-declarations
  13. #ifndef USE_LIBSQLITE3
  14. #include <sqlite3-binding.h>
  15. #else
  16. #include <sqlite3.h>
  17. #endif
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #ifdef __CYGWIN__
  21. # include <errno.h>
  22. #endif
  23. #ifndef SQLITE_OPEN_READWRITE
  24. # define SQLITE_OPEN_READWRITE 0
  25. #endif
  26. #ifndef SQLITE_OPEN_FULLMUTEX
  27. # define SQLITE_OPEN_FULLMUTEX 0
  28. #endif
  29. #ifndef SQLITE_DETERMINISTIC
  30. # define SQLITE_DETERMINISTIC 0
  31. #endif
  32. static int
  33. _sqlite3_open_v2(const char *filename, sqlite3 **ppDb, int flags, const char *zVfs) {
  34. #ifdef SQLITE_OPEN_URI
  35. return sqlite3_open_v2(filename, ppDb, flags | SQLITE_OPEN_URI, zVfs);
  36. #else
  37. return sqlite3_open_v2(filename, ppDb, flags, zVfs);
  38. #endif
  39. }
  40. static int
  41. _sqlite3_bind_text(sqlite3_stmt *stmt, int n, char *p, int np) {
  42. return sqlite3_bind_text(stmt, n, p, np, SQLITE_TRANSIENT);
  43. }
  44. static int
  45. _sqlite3_bind_blob(sqlite3_stmt *stmt, int n, void *p, int np) {
  46. return sqlite3_bind_blob(stmt, n, p, np, SQLITE_TRANSIENT);
  47. }
  48. #include <stdio.h>
  49. #include <stdint.h>
  50. static int
  51. _sqlite3_exec(sqlite3* db, const char* pcmd, long long* rowid, long long* changes)
  52. {
  53. int rv = sqlite3_exec(db, pcmd, 0, 0, 0);
  54. *rowid = (long long) sqlite3_last_insert_rowid(db);
  55. *changes = (long long) sqlite3_changes(db);
  56. return rv;
  57. }
  58. static int
  59. _sqlite3_step(sqlite3_stmt* stmt, long long* rowid, long long* changes)
  60. {
  61. int rv = sqlite3_step(stmt);
  62. sqlite3* db = sqlite3_db_handle(stmt);
  63. *rowid = (long long) sqlite3_last_insert_rowid(db);
  64. *changes = (long long) sqlite3_changes(db);
  65. return rv;
  66. }
  67. void _sqlite3_result_text(sqlite3_context* ctx, const char* s) {
  68. sqlite3_result_text(ctx, s, -1, &free);
  69. }
  70. void _sqlite3_result_blob(sqlite3_context* ctx, const void* b, int l) {
  71. sqlite3_result_blob(ctx, b, l, SQLITE_TRANSIENT);
  72. }
  73. int _sqlite3_create_function(
  74. sqlite3 *db,
  75. const char *zFunctionName,
  76. int nArg,
  77. int eTextRep,
  78. uintptr_t pApp,
  79. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  80. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  81. void (*xFinal)(sqlite3_context*)
  82. ) {
  83. return sqlite3_create_function(db, zFunctionName, nArg, eTextRep, (void*) pApp, xFunc, xStep, xFinal);
  84. }
  85. void callbackTrampoline(sqlite3_context*, int, sqlite3_value**);
  86. */
  87. import "C"
  88. import (
  89. "database/sql"
  90. "database/sql/driver"
  91. "errors"
  92. "fmt"
  93. "io"
  94. "net/url"
  95. "reflect"
  96. "runtime"
  97. "strconv"
  98. "strings"
  99. "sync"
  100. "time"
  101. "unsafe"
  102. "golang.org/x/net/context"
  103. )
  104. // SQLiteTimestampFormats is timestamp formats understood by both this module
  105. // and SQLite. The first format in the slice will be used when saving time
  106. // values into the database. When parsing a string from a timestamp or datetime
  107. // column, the formats are tried in order.
  108. var SQLiteTimestampFormats = []string{
  109. // By default, store timestamps with whatever timezone they come with.
  110. // When parsed, they will be returned with the same timezone.
  111. "2006-01-02 15:04:05.999999999-07:00",
  112. "2006-01-02T15:04:05.999999999-07:00",
  113. "2006-01-02 15:04:05.999999999",
  114. "2006-01-02T15:04:05.999999999",
  115. "2006-01-02 15:04:05",
  116. "2006-01-02T15:04:05",
  117. "2006-01-02 15:04",
  118. "2006-01-02T15:04",
  119. "2006-01-02",
  120. }
  121. func init() {
  122. sql.Register("sqlite3", &SQLiteDriver{})
  123. }
  124. // Version returns SQLite library version information.
  125. func Version() (libVersion string, libVersionNumber int, sourceID string) {
  126. libVersion = C.GoString(C.sqlite3_libversion())
  127. libVersionNumber = int(C.sqlite3_libversion_number())
  128. sourceID = C.GoString(C.sqlite3_sourceid())
  129. return libVersion, libVersionNumber, sourceID
  130. }
  131. // SQLiteDriver implement sql.Driver.
  132. type SQLiteDriver struct {
  133. Extensions []string
  134. ConnectHook func(*SQLiteConn) error
  135. }
  136. // SQLiteConn implement sql.Conn.
  137. type SQLiteConn struct {
  138. dbMu sync.Mutex
  139. db *C.sqlite3
  140. loc *time.Location
  141. txlock string
  142. funcs []*functionInfo
  143. aggregators []*aggInfo
  144. }
  145. // SQLiteTx implemen sql.Tx.
  146. type SQLiteTx struct {
  147. c *SQLiteConn
  148. }
  149. // SQLiteStmt implement sql.Stmt.
  150. type SQLiteStmt struct {
  151. c *SQLiteConn
  152. s *C.sqlite3_stmt
  153. t string
  154. closed bool
  155. cls bool
  156. }
  157. // SQLiteResult implement sql.Result.
  158. type SQLiteResult struct {
  159. id int64
  160. changes int64
  161. }
  162. // SQLiteRows implement sql.Rows.
  163. type SQLiteRows struct {
  164. s *SQLiteStmt
  165. nc int
  166. cols []string
  167. decltype []string
  168. cls bool
  169. done chan struct{}
  170. }
  171. type functionInfo struct {
  172. f reflect.Value
  173. argConverters []callbackArgConverter
  174. variadicConverter callbackArgConverter
  175. retConverter callbackRetConverter
  176. }
  177. func (fi *functionInfo) Call(ctx *C.sqlite3_context, argv []*C.sqlite3_value) {
  178. args, err := callbackConvertArgs(argv, fi.argConverters, fi.variadicConverter)
  179. if err != nil {
  180. callbackError(ctx, err)
  181. return
  182. }
  183. ret := fi.f.Call(args)
  184. if len(ret) == 2 && ret[1].Interface() != nil {
  185. callbackError(ctx, ret[1].Interface().(error))
  186. return
  187. }
  188. err = fi.retConverter(ctx, ret[0])
  189. if err != nil {
  190. callbackError(ctx, err)
  191. return
  192. }
  193. }
  194. type aggInfo struct {
  195. constructor reflect.Value
  196. // Active aggregator objects for aggregations in flight. The
  197. // aggregators are indexed by a counter stored in the aggregation
  198. // user data space provided by sqlite.
  199. active map[int64]reflect.Value
  200. next int64
  201. stepArgConverters []callbackArgConverter
  202. stepVariadicConverter callbackArgConverter
  203. doneRetConverter callbackRetConverter
  204. }
  205. func (ai *aggInfo) agg(ctx *C.sqlite3_context) (int64, reflect.Value, error) {
  206. aggIdx := (*int64)(C.sqlite3_aggregate_context(ctx, C.int(8)))
  207. if *aggIdx == 0 {
  208. *aggIdx = ai.next
  209. ret := ai.constructor.Call(nil)
  210. if len(ret) == 2 && ret[1].Interface() != nil {
  211. return 0, reflect.Value{}, ret[1].Interface().(error)
  212. }
  213. if ret[0].IsNil() {
  214. return 0, reflect.Value{}, errors.New("aggregator constructor returned nil state")
  215. }
  216. ai.next++
  217. ai.active[*aggIdx] = ret[0]
  218. }
  219. return *aggIdx, ai.active[*aggIdx], nil
  220. }
  221. func (ai *aggInfo) Step(ctx *C.sqlite3_context, argv []*C.sqlite3_value) {
  222. _, agg, err := ai.agg(ctx)
  223. if err != nil {
  224. callbackError(ctx, err)
  225. return
  226. }
  227. args, err := callbackConvertArgs(argv, ai.stepArgConverters, ai.stepVariadicConverter)
  228. if err != nil {
  229. callbackError(ctx, err)
  230. return
  231. }
  232. ret := agg.MethodByName("Step").Call(args)
  233. if len(ret) == 1 && ret[0].Interface() != nil {
  234. callbackError(ctx, ret[0].Interface().(error))
  235. return
  236. }
  237. }
  238. func (ai *aggInfo) Done(ctx *C.sqlite3_context) {
  239. idx, agg, err := ai.agg(ctx)
  240. if err != nil {
  241. callbackError(ctx, err)
  242. return
  243. }
  244. defer func() { delete(ai.active, idx) }()
  245. ret := agg.MethodByName("Done").Call(nil)
  246. if len(ret) == 2 && ret[1].Interface() != nil {
  247. callbackError(ctx, ret[1].Interface().(error))
  248. return
  249. }
  250. err = ai.doneRetConverter(ctx, ret[0])
  251. if err != nil {
  252. callbackError(ctx, err)
  253. return
  254. }
  255. }
  256. // Commit transaction.
  257. func (tx *SQLiteTx) Commit() error {
  258. _, err := tx.c.exec(context.Background(), "COMMIT", nil)
  259. if err != nil && err.(Error).Code == C.SQLITE_BUSY {
  260. // sqlite3 will leave the transaction open in this scenario.
  261. // However, database/sql considers the transaction complete once we
  262. // return from Commit() - we must clean up to honour its semantics.
  263. tx.c.exec(context.Background(), "ROLLBACK", nil)
  264. }
  265. return err
  266. }
  267. // Rollback transaction.
  268. func (tx *SQLiteTx) Rollback() error {
  269. _, err := tx.c.exec(context.Background(), "ROLLBACK", nil)
  270. return err
  271. }
  272. // RegisterFunc makes a Go function available as a SQLite function.
  273. //
  274. // The Go function can have arguments of the following types: any
  275. // numeric type except complex, bool, []byte, string and
  276. // interface{}. interface{} arguments are given the direct translation
  277. // of the SQLite data type: int64 for INTEGER, float64 for FLOAT,
  278. // []byte for BLOB, string for TEXT.
  279. //
  280. // The function can additionally be variadic, as long as the type of
  281. // the variadic argument is one of the above.
  282. //
  283. // If pure is true. SQLite will assume that the function's return
  284. // value depends only on its inputs, and make more aggressive
  285. // optimizations in its queries.
  286. //
  287. // See _example/go_custom_funcs for a detailed example.
  288. func (c *SQLiteConn) RegisterFunc(name string, impl interface{}, pure bool) error {
  289. var fi functionInfo
  290. fi.f = reflect.ValueOf(impl)
  291. t := fi.f.Type()
  292. if t.Kind() != reflect.Func {
  293. return errors.New("Non-function passed to RegisterFunc")
  294. }
  295. if t.NumOut() != 1 && t.NumOut() != 2 {
  296. return errors.New("SQLite functions must return 1 or 2 values")
  297. }
  298. if t.NumOut() == 2 && !t.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
  299. return errors.New("Second return value of SQLite function must be error")
  300. }
  301. numArgs := t.NumIn()
  302. if t.IsVariadic() {
  303. numArgs--
  304. }
  305. for i := 0; i < numArgs; i++ {
  306. conv, err := callbackArg(t.In(i))
  307. if err != nil {
  308. return err
  309. }
  310. fi.argConverters = append(fi.argConverters, conv)
  311. }
  312. if t.IsVariadic() {
  313. conv, err := callbackArg(t.In(numArgs).Elem())
  314. if err != nil {
  315. return err
  316. }
  317. fi.variadicConverter = conv
  318. // Pass -1 to sqlite so that it allows any number of
  319. // arguments. The call helper verifies that the minimum number
  320. // of arguments is present for variadic functions.
  321. numArgs = -1
  322. }
  323. conv, err := callbackRet(t.Out(0))
  324. if err != nil {
  325. return err
  326. }
  327. fi.retConverter = conv
  328. // fi must outlast the database connection, or we'll have dangling pointers.
  329. c.funcs = append(c.funcs, &fi)
  330. cname := C.CString(name)
  331. defer C.free(unsafe.Pointer(cname))
  332. opts := C.SQLITE_UTF8
  333. if pure {
  334. opts |= C.SQLITE_DETERMINISTIC
  335. }
  336. rv := sqlite3CreateFunction(c.db, cname, C.int(numArgs), C.int(opts), newHandle(c, &fi), C.callbackTrampoline, nil, nil)
  337. if rv != C.SQLITE_OK {
  338. return c.lastError()
  339. }
  340. return nil
  341. }
  342. func sqlite3CreateFunction(db *C.sqlite3, zFunctionName *C.char, nArg C.int, eTextRep C.int, pApp uintptr, xFunc unsafe.Pointer, xStep unsafe.Pointer, xFinal unsafe.Pointer) C.int {
  343. return C._sqlite3_create_function(db, zFunctionName, nArg, eTextRep, C.uintptr_t(pApp), (*[0]byte)(unsafe.Pointer(xFunc)), (*[0]byte)(unsafe.Pointer(xStep)), (*[0]byte)(unsafe.Pointer(xFinal)))
  344. }
  345. // AutoCommit return which currently auto commit or not.
  346. func (c *SQLiteConn) AutoCommit() bool {
  347. return int(C.sqlite3_get_autocommit(c.db)) != 0
  348. }
  349. func (c *SQLiteConn) lastError() error {
  350. return lastError(c.db)
  351. }
  352. func lastError(db *C.sqlite3) error {
  353. rv := C.sqlite3_errcode(db)
  354. if rv == C.SQLITE_OK {
  355. return nil
  356. }
  357. return Error{
  358. Code: ErrNo(rv),
  359. ExtendedCode: ErrNoExtended(C.sqlite3_extended_errcode(db)),
  360. err: C.GoString(C.sqlite3_errmsg(db)),
  361. }
  362. }
  363. // Exec implements Execer.
  364. func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, error) {
  365. list := make([]namedValue, len(args))
  366. for i, v := range args {
  367. list[i] = namedValue{
  368. Ordinal: i + 1,
  369. Value: v,
  370. }
  371. }
  372. return c.exec(context.Background(), query, list)
  373. }
  374. func (c *SQLiteConn) exec(ctx context.Context, query string, args []namedValue) (driver.Result, error) {
  375. start := 0
  376. for {
  377. s, err := c.prepare(ctx, query)
  378. if err != nil {
  379. return nil, err
  380. }
  381. var res driver.Result
  382. if s.(*SQLiteStmt).s != nil {
  383. na := s.NumInput()
  384. if len(args) < na {
  385. s.Close()
  386. return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args))
  387. }
  388. for i := 0; i < na; i++ {
  389. args[i].Ordinal -= start
  390. }
  391. res, err = s.(*SQLiteStmt).exec(ctx, args[:na])
  392. if err != nil && err != driver.ErrSkip {
  393. s.Close()
  394. return nil, err
  395. }
  396. args = args[na:]
  397. start += na
  398. }
  399. tail := s.(*SQLiteStmt).t
  400. s.Close()
  401. if tail == "" {
  402. return res, nil
  403. }
  404. query = tail
  405. }
  406. }
  407. type namedValue struct {
  408. Name string
  409. Ordinal int
  410. Value driver.Value
  411. }
  412. // Query implements Queryer.
  413. func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error) {
  414. list := make([]namedValue, len(args))
  415. for i, v := range args {
  416. list[i] = namedValue{
  417. Ordinal: i + 1,
  418. Value: v,
  419. }
  420. }
  421. return c.query(context.Background(), query, list)
  422. }
  423. func (c *SQLiteConn) query(ctx context.Context, query string, args []namedValue) (driver.Rows, error) {
  424. start := 0
  425. for {
  426. s, err := c.prepare(ctx, query)
  427. if err != nil {
  428. return nil, err
  429. }
  430. s.(*SQLiteStmt).cls = true
  431. na := s.NumInput()
  432. if len(args) < na {
  433. return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args))
  434. }
  435. for i := 0; i < na; i++ {
  436. args[i].Ordinal -= start
  437. }
  438. rows, err := s.(*SQLiteStmt).query(ctx, args[:na])
  439. if err != nil && err != driver.ErrSkip {
  440. s.Close()
  441. return rows, err
  442. }
  443. args = args[na:]
  444. start += na
  445. tail := s.(*SQLiteStmt).t
  446. if tail == "" {
  447. return rows, nil
  448. }
  449. rows.Close()
  450. s.Close()
  451. query = tail
  452. }
  453. }
  454. // Begin transaction.
  455. func (c *SQLiteConn) Begin() (driver.Tx, error) {
  456. return c.begin(context.Background())
  457. }
  458. func (c *SQLiteConn) begin(ctx context.Context) (driver.Tx, error) {
  459. if _, err := c.exec(ctx, c.txlock, nil); err != nil {
  460. return nil, err
  461. }
  462. return &SQLiteTx{c}, nil
  463. }
  464. func errorString(err Error) string {
  465. return C.GoString(C.sqlite3_errstr(C.int(err.Code)))
  466. }
  467. // Open database and return a new connection.
  468. // You can specify a DSN string using a URI as the filename.
  469. // test.db
  470. // file:test.db?cache=shared&mode=memory
  471. // :memory:
  472. // file::memory:
  473. // go-sqlite3 adds the following query parameters to those used by SQLite:
  474. // _loc=XXX
  475. // Specify location of time format. It's possible to specify "auto".
  476. // _busy_timeout=XXX
  477. // Specify value for sqlite3_busy_timeout.
  478. // _txlock=XXX
  479. // Specify locking behavior for transactions. XXX can be "immediate",
  480. // "deferred", "exclusive".
  481. // _foreign_keys=X
  482. // Enable or disable enforcement of foreign keys. X can be 1 or 0.
  483. func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
  484. if C.sqlite3_threadsafe() == 0 {
  485. return nil, errors.New("sqlite library was not compiled for thread-safe operation")
  486. }
  487. var loc *time.Location
  488. txlock := "BEGIN"
  489. busyTimeout := 5000
  490. foreignKeys := -1
  491. pos := strings.IndexRune(dsn, '?')
  492. if pos >= 1 {
  493. params, err := url.ParseQuery(dsn[pos+1:])
  494. if err != nil {
  495. return nil, err
  496. }
  497. // _loc
  498. if val := params.Get("_loc"); val != "" {
  499. if val == "auto" {
  500. loc = time.Local
  501. } else {
  502. loc, err = time.LoadLocation(val)
  503. if err != nil {
  504. return nil, fmt.Errorf("Invalid _loc: %v: %v", val, err)
  505. }
  506. }
  507. }
  508. // _busy_timeout
  509. if val := params.Get("_busy_timeout"); val != "" {
  510. iv, err := strconv.ParseInt(val, 10, 64)
  511. if err != nil {
  512. return nil, fmt.Errorf("Invalid _busy_timeout: %v: %v", val, err)
  513. }
  514. busyTimeout = int(iv)
  515. }
  516. // _txlock
  517. if val := params.Get("_txlock"); val != "" {
  518. switch val {
  519. case "immediate":
  520. txlock = "BEGIN IMMEDIATE"
  521. case "exclusive":
  522. txlock = "BEGIN EXCLUSIVE"
  523. case "deferred":
  524. txlock = "BEGIN"
  525. default:
  526. return nil, fmt.Errorf("Invalid _txlock: %v", val)
  527. }
  528. }
  529. // _foreign_keys
  530. if val := params.Get("_foreign_keys"); val != "" {
  531. switch val {
  532. case "1":
  533. foreignKeys = 1
  534. case "0":
  535. foreignKeys = 0
  536. default:
  537. return nil, fmt.Errorf("Invalid _foreign_keys: %v", val)
  538. }
  539. }
  540. if !strings.HasPrefix(dsn, "file:") {
  541. dsn = dsn[:pos]
  542. }
  543. }
  544. var db *C.sqlite3
  545. name := C.CString(dsn)
  546. defer C.free(unsafe.Pointer(name))
  547. rv := C._sqlite3_open_v2(name, &db,
  548. C.SQLITE_OPEN_FULLMUTEX|
  549. C.SQLITE_OPEN_READWRITE|
  550. C.SQLITE_OPEN_CREATE,
  551. nil)
  552. if rv != 0 {
  553. return nil, Error{Code: ErrNo(rv)}
  554. }
  555. if db == nil {
  556. return nil, errors.New("sqlite succeeded without returning a database")
  557. }
  558. rv = C.sqlite3_busy_timeout(db, C.int(busyTimeout))
  559. if rv != C.SQLITE_OK {
  560. C.sqlite3_close_v2(db)
  561. return nil, Error{Code: ErrNo(rv)}
  562. }
  563. exec := func(s string) error {
  564. cs := C.CString(s)
  565. rv := C.sqlite3_exec(db, cs, nil, nil, nil)
  566. C.free(unsafe.Pointer(cs))
  567. if rv != C.SQLITE_OK {
  568. return lastError(db)
  569. }
  570. return nil
  571. }
  572. if foreignKeys == 0 {
  573. if err := exec("PRAGMA foreign_keys = OFF;"); err != nil {
  574. C.sqlite3_close_v2(db)
  575. return nil, err
  576. }
  577. } else if foreignKeys == 1 {
  578. if err := exec("PRAGMA foreign_keys = ON;"); err != nil {
  579. C.sqlite3_close_v2(db)
  580. return nil, err
  581. }
  582. }
  583. conn := &SQLiteConn{db: db, loc: loc, txlock: txlock}
  584. if len(d.Extensions) > 0 {
  585. if err := conn.loadExtensions(d.Extensions); err != nil {
  586. conn.Close()
  587. return nil, err
  588. }
  589. }
  590. if d.ConnectHook != nil {
  591. if err := d.ConnectHook(conn); err != nil {
  592. conn.Close()
  593. return nil, err
  594. }
  595. }
  596. runtime.SetFinalizer(conn, (*SQLiteConn).Close)
  597. return conn, nil
  598. }
  599. // Close the connection.
  600. func (c *SQLiteConn) Close() error {
  601. rv := C.sqlite3_close_v2(c.db)
  602. if rv != C.SQLITE_OK {
  603. return c.lastError()
  604. }
  605. deleteHandles(c)
  606. c.dbMu.Lock()
  607. c.db = nil
  608. c.dbMu.Unlock()
  609. runtime.SetFinalizer(c, nil)
  610. return nil
  611. }
  612. func (c *SQLiteConn) dbConnOpen() bool {
  613. if c == nil {
  614. return false
  615. }
  616. c.dbMu.Lock()
  617. defer c.dbMu.Unlock()
  618. return c.db != nil
  619. }
  620. // Prepare the query string. Return a new statement.
  621. func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error) {
  622. return c.prepare(context.Background(), query)
  623. }
  624. func (c *SQLiteConn) prepare(ctx context.Context, query string) (driver.Stmt, error) {
  625. pquery := C.CString(query)
  626. defer C.free(unsafe.Pointer(pquery))
  627. var s *C.sqlite3_stmt
  628. var tail *C.char
  629. rv := C.sqlite3_prepare_v2(c.db, pquery, -1, &s, &tail)
  630. if rv != C.SQLITE_OK {
  631. return nil, c.lastError()
  632. }
  633. var t string
  634. if tail != nil && *tail != '\000' {
  635. t = strings.TrimSpace(C.GoString(tail))
  636. }
  637. ss := &SQLiteStmt{c: c, s: s, t: t}
  638. runtime.SetFinalizer(ss, (*SQLiteStmt).Close)
  639. return ss, nil
  640. }
  641. // Close the statement.
  642. func (s *SQLiteStmt) Close() error {
  643. if s.closed {
  644. return nil
  645. }
  646. s.closed = true
  647. if !s.c.dbConnOpen() {
  648. return errors.New("sqlite statement with already closed database connection")
  649. }
  650. rv := C.sqlite3_finalize(s.s)
  651. if rv != C.SQLITE_OK {
  652. return s.c.lastError()
  653. }
  654. runtime.SetFinalizer(s, nil)
  655. return nil
  656. }
  657. // NumInput return a number of parameters.
  658. func (s *SQLiteStmt) NumInput() int {
  659. return int(C.sqlite3_bind_parameter_count(s.s))
  660. }
  661. type bindArg struct {
  662. n int
  663. v driver.Value
  664. }
  665. var placeHolder = []byte{0}
  666. func (s *SQLiteStmt) bind(args []namedValue) error {
  667. rv := C.sqlite3_reset(s.s)
  668. if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
  669. return s.c.lastError()
  670. }
  671. for i, v := range args {
  672. if v.Name != "" {
  673. cname := C.CString(":" + v.Name)
  674. args[i].Ordinal = int(C.sqlite3_bind_parameter_index(s.s, cname))
  675. C.free(unsafe.Pointer(cname))
  676. }
  677. }
  678. for _, arg := range args {
  679. n := C.int(arg.Ordinal)
  680. switch v := arg.Value.(type) {
  681. case nil:
  682. rv = C.sqlite3_bind_null(s.s, n)
  683. case string:
  684. if len(v) == 0 {
  685. rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&placeHolder[0])), C.int(0))
  686. } else {
  687. b := []byte(v)
  688. rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b)))
  689. }
  690. case int64:
  691. rv = C.sqlite3_bind_int64(s.s, n, C.sqlite3_int64(v))
  692. case bool:
  693. if bool(v) {
  694. rv = C.sqlite3_bind_int(s.s, n, 1)
  695. } else {
  696. rv = C.sqlite3_bind_int(s.s, n, 0)
  697. }
  698. case float64:
  699. rv = C.sqlite3_bind_double(s.s, n, C.double(v))
  700. case []byte:
  701. if len(v) == 0 {
  702. v = placeHolder
  703. }
  704. rv = C._sqlite3_bind_blob(s.s, n, unsafe.Pointer(&v[0]), C.int(len(v)))
  705. case time.Time:
  706. b := []byte(v.Format(SQLiteTimestampFormats[0]))
  707. rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b)))
  708. }
  709. if rv != C.SQLITE_OK {
  710. return s.c.lastError()
  711. }
  712. }
  713. return nil
  714. }
  715. // Query the statement with arguments. Return records.
  716. func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error) {
  717. list := make([]namedValue, len(args))
  718. for i, v := range args {
  719. list[i] = namedValue{
  720. Ordinal: i + 1,
  721. Value: v,
  722. }
  723. }
  724. return s.query(context.Background(), list)
  725. }
  726. func (s *SQLiteStmt) query(ctx context.Context, args []namedValue) (driver.Rows, error) {
  727. if err := s.bind(args); err != nil {
  728. return nil, err
  729. }
  730. rows := &SQLiteRows{
  731. s: s,
  732. nc: int(C.sqlite3_column_count(s.s)),
  733. cols: nil,
  734. decltype: nil,
  735. cls: s.cls,
  736. done: make(chan struct{}),
  737. }
  738. go func(db *C.sqlite3) {
  739. select {
  740. case <-ctx.Done():
  741. select {
  742. case <-rows.done:
  743. default:
  744. C.sqlite3_interrupt(db)
  745. rows.Close()
  746. }
  747. case <-rows.done:
  748. }
  749. }(s.c.db)
  750. return rows, nil
  751. }
  752. // LastInsertId teturn last inserted ID.
  753. func (r *SQLiteResult) LastInsertId() (int64, error) {
  754. return r.id, nil
  755. }
  756. // RowsAffected return how many rows affected.
  757. func (r *SQLiteResult) RowsAffected() (int64, error) {
  758. return r.changes, nil
  759. }
  760. // Exec execute the statement with arguments. Return result object.
  761. func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error) {
  762. list := make([]namedValue, len(args))
  763. for i, v := range args {
  764. list[i] = namedValue{
  765. Ordinal: i + 1,
  766. Value: v,
  767. }
  768. }
  769. return s.exec(context.Background(), list)
  770. }
  771. func (s *SQLiteStmt) exec(ctx context.Context, args []namedValue) (driver.Result, error) {
  772. if err := s.bind(args); err != nil {
  773. C.sqlite3_reset(s.s)
  774. C.sqlite3_clear_bindings(s.s)
  775. return nil, err
  776. }
  777. done := make(chan struct{})
  778. defer close(done)
  779. go func(db *C.sqlite3) {
  780. select {
  781. case <-ctx.Done():
  782. C.sqlite3_interrupt(db)
  783. case <-done:
  784. }
  785. }(s.c.db)
  786. var rowid, changes C.longlong
  787. rv := C._sqlite3_step(s.s, &rowid, &changes)
  788. if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
  789. err := s.c.lastError()
  790. C.sqlite3_reset(s.s)
  791. C.sqlite3_clear_bindings(s.s)
  792. return nil, err
  793. }
  794. return &SQLiteResult{id: int64(rowid), changes: int64(changes)}, nil
  795. }
  796. // Close the rows.
  797. func (rc *SQLiteRows) Close() error {
  798. if rc.s.closed {
  799. return nil
  800. }
  801. if rc.done != nil {
  802. close(rc.done)
  803. }
  804. if rc.cls {
  805. return rc.s.Close()
  806. }
  807. rv := C.sqlite3_reset(rc.s.s)
  808. if rv != C.SQLITE_OK {
  809. return rc.s.c.lastError()
  810. }
  811. return nil
  812. }
  813. // Columns return column names.
  814. func (rc *SQLiteRows) Columns() []string {
  815. if rc.nc != len(rc.cols) {
  816. rc.cols = make([]string, rc.nc)
  817. for i := 0; i < rc.nc; i++ {
  818. rc.cols[i] = C.GoString(C.sqlite3_column_name(rc.s.s, C.int(i)))
  819. }
  820. }
  821. return rc.cols
  822. }
  823. // DeclTypes return column types.
  824. func (rc *SQLiteRows) DeclTypes() []string {
  825. if rc.decltype == nil {
  826. rc.decltype = make([]string, rc.nc)
  827. for i := 0; i < rc.nc; i++ {
  828. rc.decltype[i] = strings.ToLower(C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i))))
  829. }
  830. }
  831. return rc.decltype
  832. }
  833. // Next move cursor to next.
  834. func (rc *SQLiteRows) Next(dest []driver.Value) error {
  835. rv := C.sqlite3_step(rc.s.s)
  836. if rv == C.SQLITE_DONE {
  837. return io.EOF
  838. }
  839. if rv != C.SQLITE_ROW {
  840. rv = C.sqlite3_reset(rc.s.s)
  841. if rv != C.SQLITE_OK {
  842. return rc.s.c.lastError()
  843. }
  844. return nil
  845. }
  846. rc.DeclTypes()
  847. for i := range dest {
  848. switch C.sqlite3_column_type(rc.s.s, C.int(i)) {
  849. case C.SQLITE_INTEGER:
  850. val := int64(C.sqlite3_column_int64(rc.s.s, C.int(i)))
  851. switch rc.decltype[i] {
  852. case "timestamp", "datetime", "date":
  853. var t time.Time
  854. // Assume a millisecond unix timestamp if it's 13 digits -- too
  855. // large to be a reasonable timestamp in seconds.
  856. if val > 1e12 || val < -1e12 {
  857. val *= int64(time.Millisecond) // convert ms to nsec
  858. t = time.Unix(0, val)
  859. } else {
  860. t = time.Unix(val, 0)
  861. }
  862. t = t.UTC()
  863. if rc.s.c.loc != nil {
  864. t = t.In(rc.s.c.loc)
  865. }
  866. dest[i] = t
  867. case "boolean":
  868. dest[i] = val > 0
  869. default:
  870. dest[i] = val
  871. }
  872. case C.SQLITE_FLOAT:
  873. dest[i] = float64(C.sqlite3_column_double(rc.s.s, C.int(i)))
  874. case C.SQLITE_BLOB:
  875. p := C.sqlite3_column_blob(rc.s.s, C.int(i))
  876. if p == nil {
  877. dest[i] = nil
  878. continue
  879. }
  880. n := int(C.sqlite3_column_bytes(rc.s.s, C.int(i)))
  881. switch dest[i].(type) {
  882. case sql.RawBytes:
  883. dest[i] = (*[1 << 30]byte)(unsafe.Pointer(p))[0:n]
  884. default:
  885. slice := make([]byte, n)
  886. copy(slice[:], (*[1 << 30]byte)(unsafe.Pointer(p))[0:n])
  887. dest[i] = slice
  888. }
  889. case C.SQLITE_NULL:
  890. dest[i] = nil
  891. case C.SQLITE_TEXT:
  892. var err error
  893. var timeVal time.Time
  894. n := int(C.sqlite3_column_bytes(rc.s.s, C.int(i)))
  895. s := C.GoStringN((*C.char)(unsafe.Pointer(C.sqlite3_column_text(rc.s.s, C.int(i)))), C.int(n))
  896. switch rc.decltype[i] {
  897. case "timestamp", "datetime", "date":
  898. var t time.Time
  899. s = strings.TrimSuffix(s, "Z")
  900. for _, format := range SQLiteTimestampFormats {
  901. if timeVal, err = time.ParseInLocation(format, s, time.UTC); err == nil {
  902. t = timeVal
  903. break
  904. }
  905. }
  906. if err != nil {
  907. // The column is a time value, so return the zero time on parse failure.
  908. t = time.Time{}
  909. }
  910. if rc.s.c.loc != nil {
  911. t = t.In(rc.s.c.loc)
  912. }
  913. dest[i] = t
  914. default:
  915. dest[i] = []byte(s)
  916. }
  917. }
  918. }
  919. return nil
  920. }