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.

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