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