sqlite3.go 18 KB

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