gitlab.com/CoiaPrant/sqlite3@v1.19.1/sqlite.go (about) 1 // Copyright 2017 The Sqlite Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 //go:generate go run generator.go -full-path-comments 6 7 package sqlite // import "gitlab.com/CoiaPrant/sqlite3" 8 9 import ( 10 "context" 11 "database/sql" 12 "database/sql/driver" 13 "fmt" 14 "io" 15 "math" 16 "net/url" 17 "reflect" 18 "strconv" 19 "strings" 20 "sync" 21 "sync/atomic" 22 "time" 23 "unsafe" 24 25 "modernc.org/libc" 26 "modernc.org/libc/sys/types" 27 sqlite3 "gitlab.com/CoiaPrant/sqlite3/lib" 28 ) 29 30 var ( 31 _ driver.Conn = (*conn)(nil) 32 _ driver.Driver = (*Driver)(nil) 33 //lint:ignore SA1019 TODO implement ExecerContext 34 _ driver.Execer = (*conn)(nil) 35 //lint:ignore SA1019 TODO implement QueryerContext 36 _ driver.Queryer = (*conn)(nil) 37 _ driver.Result = (*result)(nil) 38 _ driver.Rows = (*rows)(nil) 39 _ driver.RowsColumnTypeDatabaseTypeName = (*rows)(nil) 40 _ driver.RowsColumnTypeLength = (*rows)(nil) 41 _ driver.RowsColumnTypeNullable = (*rows)(nil) 42 _ driver.RowsColumnTypePrecisionScale = (*rows)(nil) 43 _ driver.RowsColumnTypeScanType = (*rows)(nil) 44 _ driver.Stmt = (*stmt)(nil) 45 _ driver.Tx = (*tx)(nil) 46 _ error = (*Error)(nil) 47 ) 48 49 const ( 50 driverName = "sqlite3" 51 ptrSize = unsafe.Sizeof(uintptr(0)) 52 sqliteLockedSharedcache = sqlite3.SQLITE_LOCKED | (1 << 8) 53 ) 54 55 // Error represents sqlite library error code. 56 type Error struct { 57 msg string 58 code int 59 } 60 61 // Error implements error. 62 func (e *Error) Error() string { return e.msg } 63 64 // Code returns the sqlite result code for this error. 65 func (e *Error) Code() int { return e.code } 66 67 var ( 68 // ErrorCodeString maps Error.Code() to its string representation. 69 ErrorCodeString = map[int]string{ 70 sqlite3.SQLITE_ABORT: "Callback routine requested an abort (SQLITE_ABORT)", 71 sqlite3.SQLITE_AUTH: "Authorization denied (SQLITE_AUTH)", 72 sqlite3.SQLITE_BUSY: "The database file is locked (SQLITE_BUSY)", 73 sqlite3.SQLITE_CANTOPEN: "Unable to open the database file (SQLITE_CANTOPEN)", 74 sqlite3.SQLITE_CONSTRAINT: "Abort due to constraint violation (SQLITE_CONSTRAINT)", 75 sqlite3.SQLITE_CORRUPT: "The database disk image is malformed (SQLITE_CORRUPT)", 76 sqlite3.SQLITE_DONE: "sqlite3_step() has finished executing (SQLITE_DONE)", 77 sqlite3.SQLITE_EMPTY: "Internal use only (SQLITE_EMPTY)", 78 sqlite3.SQLITE_ERROR: "Generic error (SQLITE_ERROR)", 79 sqlite3.SQLITE_FORMAT: "Not used (SQLITE_FORMAT)", 80 sqlite3.SQLITE_FULL: "Insertion failed because database is full (SQLITE_FULL)", 81 sqlite3.SQLITE_INTERNAL: "Internal logic error in SQLite (SQLITE_INTERNAL)", 82 sqlite3.SQLITE_INTERRUPT: "Operation terminated by sqlite3_interrupt()(SQLITE_INTERRUPT)", 83 sqlite3.SQLITE_IOERR | (1 << 8): "(SQLITE_IOERR_READ)", 84 sqlite3.SQLITE_IOERR | (10 << 8): "(SQLITE_IOERR_DELETE)", 85 sqlite3.SQLITE_IOERR | (11 << 8): "(SQLITE_IOERR_BLOCKED)", 86 sqlite3.SQLITE_IOERR | (12 << 8): "(SQLITE_IOERR_NOMEM)", 87 sqlite3.SQLITE_IOERR | (13 << 8): "(SQLITE_IOERR_ACCESS)", 88 sqlite3.SQLITE_IOERR | (14 << 8): "(SQLITE_IOERR_CHECKRESERVEDLOCK)", 89 sqlite3.SQLITE_IOERR | (15 << 8): "(SQLITE_IOERR_LOCK)", 90 sqlite3.SQLITE_IOERR | (16 << 8): "(SQLITE_IOERR_CLOSE)", 91 sqlite3.SQLITE_IOERR | (17 << 8): "(SQLITE_IOERR_DIR_CLOSE)", 92 sqlite3.SQLITE_IOERR | (2 << 8): "(SQLITE_IOERR_SHORT_READ)", 93 sqlite3.SQLITE_IOERR | (3 << 8): "(SQLITE_IOERR_WRITE)", 94 sqlite3.SQLITE_IOERR | (4 << 8): "(SQLITE_IOERR_FSYNC)", 95 sqlite3.SQLITE_IOERR | (5 << 8): "(SQLITE_IOERR_DIR_FSYNC)", 96 sqlite3.SQLITE_IOERR | (6 << 8): "(SQLITE_IOERR_TRUNCATE)", 97 sqlite3.SQLITE_IOERR | (7 << 8): "(SQLITE_IOERR_FSTAT)", 98 sqlite3.SQLITE_IOERR | (8 << 8): "(SQLITE_IOERR_UNLOCK)", 99 sqlite3.SQLITE_IOERR | (9 << 8): "(SQLITE_IOERR_RDLOCK)", 100 sqlite3.SQLITE_IOERR: "Some kind of disk I/O error occurred (SQLITE_IOERR)", 101 sqlite3.SQLITE_LOCKED | (1 << 8): "(SQLITE_LOCKED_SHAREDCACHE)", 102 sqlite3.SQLITE_LOCKED: "A table in the database is locked (SQLITE_LOCKED)", 103 sqlite3.SQLITE_MISMATCH: "Data type mismatch (SQLITE_MISMATCH)", 104 sqlite3.SQLITE_MISUSE: "Library used incorrectly (SQLITE_MISUSE)", 105 sqlite3.SQLITE_NOLFS: "Uses OS features not supported on host (SQLITE_NOLFS)", 106 sqlite3.SQLITE_NOMEM: "A malloc() failed (SQLITE_NOMEM)", 107 sqlite3.SQLITE_NOTADB: "File opened that is not a database file (SQLITE_NOTADB)", 108 sqlite3.SQLITE_NOTFOUND: "Unknown opcode in sqlite3_file_control() (SQLITE_NOTFOUND)", 109 sqlite3.SQLITE_NOTICE: "Notifications from sqlite3_log() (SQLITE_NOTICE)", 110 sqlite3.SQLITE_PERM: "Access permission denied (SQLITE_PERM)", 111 sqlite3.SQLITE_PROTOCOL: "Database lock protocol error (SQLITE_PROTOCOL)", 112 sqlite3.SQLITE_RANGE: "2nd parameter to sqlite3_bind out of range (SQLITE_RANGE)", 113 sqlite3.SQLITE_READONLY: "Attempt to write a readonly database (SQLITE_READONLY)", 114 sqlite3.SQLITE_ROW: "sqlite3_step() has another row ready (SQLITE_ROW)", 115 sqlite3.SQLITE_SCHEMA: "The database schema changed (SQLITE_SCHEMA)", 116 sqlite3.SQLITE_TOOBIG: "String or BLOB exceeds size limit (SQLITE_TOOBIG)", 117 sqlite3.SQLITE_WARNING: "Warnings from sqlite3_log() (SQLITE_WARNING)", 118 } 119 ) 120 121 func init() { 122 sql.Register(driverName, newDriver()) 123 } 124 125 type result struct { 126 lastInsertID int64 127 rowsAffected int 128 } 129 130 func newResult(c *conn) (_ *result, err error) { 131 r := &result{} 132 if r.rowsAffected, err = c.changes(); err != nil { 133 return nil, err 134 } 135 136 if r.lastInsertID, err = c.lastInsertRowID(); err != nil { 137 return nil, err 138 } 139 140 return r, nil 141 } 142 143 // LastInsertId returns the database's auto-generated ID after, for example, an 144 // INSERT into a table with primary key. 145 func (r *result) LastInsertId() (int64, error) { 146 if r == nil { 147 return 0, nil 148 } 149 150 return r.lastInsertID, nil 151 } 152 153 // RowsAffected returns the number of rows affected by the query. 154 func (r *result) RowsAffected() (int64, error) { 155 if r == nil { 156 return 0, nil 157 } 158 159 return int64(r.rowsAffected), nil 160 } 161 162 type rows struct { 163 allocs []uintptr 164 c *conn 165 columns []string 166 pstmt uintptr 167 168 doStep bool 169 empty bool 170 } 171 172 func newRows(c *conn, pstmt uintptr, allocs []uintptr, empty bool) (r *rows, err error) { 173 r = &rows{c: c, pstmt: pstmt, allocs: allocs, empty: empty} 174 175 defer func() { 176 if err != nil { 177 r.Close() 178 r = nil 179 } 180 }() 181 182 n, err := c.columnCount(pstmt) 183 if err != nil { 184 return nil, err 185 } 186 187 r.columns = make([]string, n) 188 for i := range r.columns { 189 if r.columns[i], err = r.c.columnName(pstmt, i); err != nil { 190 return nil, err 191 } 192 } 193 194 return r, nil 195 } 196 197 // Close closes the rows iterator. 198 func (r *rows) Close() (err error) { 199 for _, v := range r.allocs { 200 r.c.free(v) 201 } 202 r.allocs = nil 203 return r.c.finalize(r.pstmt) 204 } 205 206 // Columns returns the names of the columns. The number of columns of the 207 // result is inferred from the length of the slice. If a particular column name 208 // isn't known, an empty string should be returned for that entry. 209 func (r *rows) Columns() (c []string) { 210 return r.columns 211 } 212 213 // Next is called to populate the next row of data into the provided slice. The 214 // provided slice will be the same size as the Columns() are wide. 215 // 216 // Next should return io.EOF when there are no more rows. 217 func (r *rows) Next(dest []driver.Value) (err error) { 218 if r.empty { 219 return io.EOF 220 } 221 222 rc := sqlite3.SQLITE_ROW 223 if r.doStep { 224 if rc, err = r.c.step(r.pstmt); err != nil { 225 return err 226 } 227 } 228 229 r.doStep = true 230 switch rc { 231 case sqlite3.SQLITE_ROW: 232 if g, e := len(dest), len(r.columns); g != e { 233 return fmt.Errorf("sqlite: Next: have %v destination values, expected %v", g, e) 234 } 235 236 for i := range dest { 237 ct, err := r.c.columnType(r.pstmt, i) 238 if err != nil { 239 return err 240 } 241 242 switch ct { 243 case sqlite3.SQLITE_INTEGER: 244 v, err := r.c.columnInt64(r.pstmt, i) 245 if err != nil { 246 return err 247 } 248 249 dest[i] = v 250 case sqlite3.SQLITE_FLOAT: 251 v, err := r.c.columnDouble(r.pstmt, i) 252 if err != nil { 253 return err 254 } 255 256 dest[i] = v 257 case sqlite3.SQLITE_TEXT: 258 v, err := r.c.columnText(r.pstmt, i) 259 if err != nil { 260 return err 261 } 262 263 switch r.ColumnTypeDatabaseTypeName(i) { 264 case "DATE", "DATETIME", "TIMESTAMP": 265 dest[i], _ = r.c.parseTime(v) 266 default: 267 dest[i] = v 268 } 269 case sqlite3.SQLITE_BLOB: 270 v, err := r.c.columnBlob(r.pstmt, i) 271 if err != nil { 272 return err 273 } 274 275 dest[i] = v 276 case sqlite3.SQLITE_NULL: 277 dest[i] = nil 278 default: 279 return fmt.Errorf("internal error: rc %d", rc) 280 } 281 } 282 return nil 283 case sqlite3.SQLITE_DONE: 284 return io.EOF 285 default: 286 return r.c.errstr(int32(rc)) 287 } 288 } 289 290 // Inspired by mattn/go-sqlite3: https://github.com/mattn/go-sqlite3/blob/ab91e934/sqlite3.go#L210-L226 291 // 292 // These time.Parse formats handle formats 1 through 7 listed at https://www.sqlite.org/lang_datefunc.html. 293 var parseTimeFormats = []string{ 294 "2006-01-02 15:04:05.999999999-07:00", 295 "2006-01-02T15:04:05.999999999-07:00", 296 "2006-01-02 15:04:05.999999999", 297 "2006-01-02T15:04:05.999999999", 298 "2006-01-02 15:04", 299 "2006-01-02T15:04", 300 "2006-01-02", 301 } 302 303 // Attempt to parse s as a time. Return (s, false) if s is not 304 // recognized as a valid time encoding. 305 func (c *conn) parseTime(s string) (interface{}, bool) { 306 if v, ok := c.parseTimeString(s, strings.Index(s, "m=")); ok { 307 return v, true 308 } 309 310 ts := strings.TrimSuffix(s, "Z") 311 312 for _, f := range parseTimeFormats { 313 t, err := time.Parse(f, ts) 314 if err == nil { 315 return t, true 316 } 317 } 318 319 return s, false 320 } 321 322 // Attempt to parse s as a time string produced by t.String(). If x > 0 it's 323 // the index of substring "m=" within s. Return (s, false) if s is 324 // not recognized as a valid time encoding. 325 func (c *conn) parseTimeString(s0 string, x int) (interface{}, bool) { 326 s := s0 327 if x > 0 { 328 s = s[:x] // "2006-01-02 15:04:05.999999999 -0700 MST m=+9999" -> "2006-01-02 15:04:05.999999999 -0700 MST " 329 } 330 s = strings.TrimSpace(s) 331 if t, err := time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", s); err == nil { 332 return t, true 333 } 334 335 return s0, false 336 } 337 338 // writeTimeFormats are the names and formats supported 339 // by the `_time_format` DSN query param. 340 var writeTimeFormats = map[string]string{ 341 "sqlite": parseTimeFormats[0], 342 } 343 344 func (c *conn) formatTime(t time.Time) string { 345 // Before configurable write time formats were supported, 346 // time.Time.String was used. Maintain that default to 347 // keep existing driver users formatting times the same. 348 if c.writeTimeFormat == "" { 349 return t.String() 350 } 351 return t.Format(c.writeTimeFormat) 352 } 353 354 // RowsColumnTypeDatabaseTypeName may be implemented by Rows. It should return 355 // the database system type name without the length. Type names should be 356 // uppercase. Examples of returned types: "VARCHAR", "NVARCHAR", "VARCHAR2", 357 // "CHAR", "TEXT", "DECIMAL", "SMALLINT", "INT", "BIGINT", "BOOL", "[]BIGINT", 358 // "JSONB", "XML", "TIMESTAMP". 359 func (r *rows) ColumnTypeDatabaseTypeName(index int) string { 360 return strings.ToUpper(r.c.columnDeclType(r.pstmt, index)) 361 } 362 363 // RowsColumnTypeLength may be implemented by Rows. It should return the length 364 // of the column type if the column is a variable length type. If the column is 365 // not a variable length type ok should return false. If length is not limited 366 // other than system limits, it should return math.MaxInt64. The following are 367 // examples of returned values for various types: 368 // 369 // TEXT (math.MaxInt64, true) 370 // varchar(10) (10, true) 371 // nvarchar(10) (10, true) 372 // decimal (0, false) 373 // int (0, false) 374 // bytea(30) (30, true) 375 func (r *rows) ColumnTypeLength(index int) (length int64, ok bool) { 376 t, err := r.c.columnType(r.pstmt, index) 377 if err != nil { 378 return 0, false 379 } 380 381 switch t { 382 case sqlite3.SQLITE_INTEGER: 383 return 0, false 384 case sqlite3.SQLITE_FLOAT: 385 return 0, false 386 case sqlite3.SQLITE_TEXT: 387 return math.MaxInt64, true 388 case sqlite3.SQLITE_BLOB: 389 return math.MaxInt64, true 390 case sqlite3.SQLITE_NULL: 391 return 0, false 392 default: 393 return 0, false 394 } 395 } 396 397 // RowsColumnTypeNullable may be implemented by Rows. The nullable value should 398 // be true if it is known the column may be null, or false if the column is 399 // known to be not nullable. If the column nullability is unknown, ok should be 400 // false. 401 func (r *rows) ColumnTypeNullable(index int) (nullable, ok bool) { 402 return true, true 403 } 404 405 // RowsColumnTypePrecisionScale may be implemented by Rows. It should return 406 // the precision and scale for decimal types. If not applicable, ok should be 407 // false. The following are examples of returned values for various types: 408 // 409 // decimal(38, 4) (38, 4, true) 410 // int (0, 0, false) 411 // decimal (math.MaxInt64, math.MaxInt64, true) 412 func (r *rows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool) { 413 return 0, 0, false 414 } 415 416 // RowsColumnTypeScanType may be implemented by Rows. It should return the 417 // value type that can be used to scan types into. For example, the database 418 // column type "bigint" this should return "reflect.TypeOf(int64(0))". 419 func (r *rows) ColumnTypeScanType(index int) reflect.Type { 420 t, err := r.c.columnType(r.pstmt, index) 421 if err != nil { 422 return reflect.TypeOf("") 423 } 424 425 switch t { 426 case sqlite3.SQLITE_INTEGER: 427 switch strings.ToLower(r.c.columnDeclType(r.pstmt, index)) { 428 case "boolean": 429 return reflect.TypeOf(false) 430 case "date", "datetime", "time", "timestamp": 431 return reflect.TypeOf(time.Time{}) 432 default: 433 return reflect.TypeOf(int64(0)) 434 } 435 case sqlite3.SQLITE_FLOAT: 436 return reflect.TypeOf(float64(0)) 437 case sqlite3.SQLITE_TEXT: 438 return reflect.TypeOf("") 439 case sqlite3.SQLITE_BLOB: 440 return reflect.SliceOf(reflect.TypeOf([]byte{})) 441 case sqlite3.SQLITE_NULL: 442 return reflect.TypeOf(nil) 443 default: 444 return reflect.TypeOf("") 445 } 446 } 447 448 type stmt struct { 449 c *conn 450 psql uintptr 451 } 452 453 func newStmt(c *conn, sql string) (*stmt, error) { 454 p, err := libc.CString(sql) 455 if err != nil { 456 return nil, err 457 } 458 stm := stmt{c: c, psql: p} 459 460 return &stm, nil 461 } 462 463 // Close closes the statement. 464 // 465 // As of Go 1.1, a Stmt will not be closed if it's in use by any queries. 466 func (s *stmt) Close() (err error) { 467 s.c.free(s.psql) 468 s.psql = 0 469 return nil 470 } 471 472 // Exec executes a query that doesn't return rows, such as an INSERT or UPDATE. 473 // 474 // 475 // Deprecated: Drivers should implement StmtExecContext instead (or 476 // additionally). 477 func (s *stmt) Exec(args []driver.Value) (driver.Result, error) { //TODO StmtExecContext 478 return s.exec(context.Background(), toNamedValues(args)) 479 } 480 481 // toNamedValues converts []driver.Value to []driver.NamedValue 482 func toNamedValues(vals []driver.Value) (r []driver.NamedValue) { 483 r = make([]driver.NamedValue, len(vals)) 484 for i, val := range vals { 485 r[i] = driver.NamedValue{Value: val, Ordinal: i + 1} 486 } 487 return r 488 } 489 490 func (s *stmt) exec(ctx context.Context, args []driver.NamedValue) (r driver.Result, err error) { 491 var pstmt uintptr 492 var done int32 493 if ctx != nil && ctx.Done() != nil { 494 defer interruptOnDone(ctx, s.c, &done)() 495 } 496 497 for psql := s.psql; *(*byte)(unsafe.Pointer(psql)) != 0 && atomic.LoadInt32(&done) == 0; { 498 if pstmt, err = s.c.prepareV2(&psql); err != nil { 499 return nil, err 500 } 501 502 if pstmt == 0 { 503 continue 504 } 505 err = func() (err error) { 506 n, err := s.c.bindParameterCount(pstmt) 507 if err != nil { 508 return err 509 } 510 511 if n != 0 { 512 allocs, err := s.c.bind(pstmt, n, args) 513 if err != nil { 514 return err 515 } 516 517 if len(allocs) != 0 { 518 defer func() { 519 for _, v := range allocs { 520 s.c.free(v) 521 } 522 }() 523 } 524 } 525 526 rc, err := s.c.step(pstmt) 527 if err != nil { 528 return err 529 } 530 531 switch rc & 0xff { 532 case sqlite3.SQLITE_DONE, sqlite3.SQLITE_ROW: 533 // nop 534 default: 535 return s.c.errstr(int32(rc)) 536 } 537 538 return nil 539 }() 540 541 if e := s.c.finalize(pstmt); e != nil && err == nil { 542 err = e 543 } 544 545 if err != nil { 546 return nil, err 547 } 548 } 549 return newResult(s.c) 550 } 551 552 // NumInput returns the number of placeholder parameters. 553 // 554 // If NumInput returns >= 0, the sql package will sanity check argument counts 555 // from callers and return errors to the caller before the statement's Exec or 556 // Query methods are called. 557 // 558 // NumInput may also return -1, if the driver doesn't know its number of 559 // placeholders. In that case, the sql package will not sanity check Exec or 560 // Query argument counts. 561 func (s *stmt) NumInput() (n int) { 562 return -1 563 } 564 565 // Query executes a query that may return rows, such as a 566 // SELECT. 567 // 568 // Deprecated: Drivers should implement StmtQueryContext instead (or 569 // additionally). 570 func (s *stmt) Query(args []driver.Value) (driver.Rows, error) { //TODO StmtQueryContext 571 return s.query(context.Background(), toNamedValues(args)) 572 } 573 574 func (s *stmt) query(ctx context.Context, args []driver.NamedValue) (r driver.Rows, err error) { 575 var pstmt uintptr 576 var done int32 577 if ctx != nil && ctx.Done() != nil { 578 defer interruptOnDone(ctx, s.c, &done)() 579 } 580 581 var allocs []uintptr 582 for psql := s.psql; *(*byte)(unsafe.Pointer(psql)) != 0 && atomic.LoadInt32(&done) == 0; { 583 if pstmt, err = s.c.prepareV2(&psql); err != nil { 584 return nil, err 585 } 586 587 if pstmt == 0 { 588 continue 589 } 590 591 err = func() (err error) { 592 n, err := s.c.bindParameterCount(pstmt) 593 if err != nil { 594 return err 595 } 596 597 if n != 0 { 598 if allocs, err = s.c.bind(pstmt, n, args); err != nil { 599 return err 600 } 601 } 602 603 rc, err := s.c.step(pstmt) 604 if err != nil { 605 return err 606 } 607 608 switch rc & 0xff { 609 case sqlite3.SQLITE_ROW: 610 if r != nil { 611 r.Close() 612 } 613 if r, err = newRows(s.c, pstmt, allocs, false); err != nil { 614 return err 615 } 616 617 pstmt = 0 618 return nil 619 case sqlite3.SQLITE_DONE: 620 if r == nil { 621 if r, err = newRows(s.c, pstmt, allocs, true); err != nil { 622 return err 623 } 624 pstmt = 0 625 return nil 626 } 627 628 // nop 629 default: 630 return s.c.errstr(int32(rc)) 631 } 632 633 if *(*byte)(unsafe.Pointer(psql)) == 0 { 634 if r != nil { 635 r.Close() 636 } 637 if r, err = newRows(s.c, pstmt, allocs, true); err != nil { 638 return err 639 } 640 641 pstmt = 0 642 } 643 return nil 644 }() 645 if e := s.c.finalize(pstmt); e != nil && err == nil { 646 err = e 647 } 648 649 if err != nil { 650 return nil, err 651 } 652 } 653 return r, err 654 } 655 656 type tx struct { 657 c *conn 658 } 659 660 func newTx(c *conn) (*tx, error) { 661 r := &tx{c: c} 662 var sql string 663 if c.beginMode != "" { 664 sql = "begin " + c.beginMode 665 } else { 666 sql = "begin" 667 } 668 if err := r.exec(context.Background(), sql); err != nil { 669 return nil, err 670 } 671 672 return r, nil 673 } 674 675 // Commit implements driver.Tx. 676 func (t *tx) Commit() (err error) { 677 return t.exec(context.Background(), "commit") 678 } 679 680 // Rollback implements driver.Tx. 681 func (t *tx) Rollback() (err error) { 682 return t.exec(context.Background(), "rollback") 683 } 684 685 func (t *tx) exec(ctx context.Context, sql string) (err error) { 686 psql, err := libc.CString(sql) 687 if err != nil { 688 return err 689 } 690 691 defer t.c.free(psql) 692 //TODO use t.conn.ExecContext() instead 693 694 if ctx != nil && ctx.Done() != nil { 695 defer interruptOnDone(ctx, t.c, nil)() 696 } 697 698 if rc := sqlite3.Xsqlite3_exec(t.c.tls, t.c.db, psql, 0, 0, 0); rc != sqlite3.SQLITE_OK { 699 return t.c.errstr(rc) 700 } 701 702 return nil 703 } 704 705 // interruptOnDone sets up a goroutine to interrupt the provided db when the 706 // context is canceled, and returns a function the caller must defer so it 707 // doesn't interrupt after the caller finishes. 708 func interruptOnDone( 709 ctx context.Context, 710 c *conn, 711 done *int32, 712 ) func() { 713 if done == nil { 714 var d int32 715 done = &d 716 } 717 718 donech := make(chan struct{}) 719 720 go func() { 721 select { 722 case <-ctx.Done(): 723 // don't call interrupt if we were already done: it indicates that this 724 // call to exec is no longer running and we would be interrupting 725 // nothing, or even possibly an unrelated later call to exec. 726 if atomic.AddInt32(done, 1) == 1 { 727 c.interrupt(c.db) 728 } 729 case <-donech: 730 } 731 }() 732 733 // the caller is expected to defer this function 734 return func() { 735 // set the done flag so that a context cancellation right after the caller 736 // returns doesn't trigger a call to interrupt for some other statement. 737 atomic.AddInt32(done, 1) 738 close(donech) 739 } 740 } 741 742 type conn struct { 743 db uintptr // *sqlite3.Xsqlite3 744 tls *libc.TLS 745 746 // Context handling can cause conn.Close and conn.interrupt to be invoked 747 // concurrently. 748 sync.Mutex 749 750 writeTimeFormat string 751 beginMode string 752 } 753 754 func newConn(dsn string) (*conn, error) { 755 var query string 756 757 // Parse the query parameters from the dsn and them from the dsn if not prefixed by file: 758 // https://github.com/mattn/go-sqlite3/blob/3392062c729d77820afc1f5cae3427f0de39e954/sqlite3.go#L1046 759 // https://github.com/mattn/go-sqlite3/blob/3392062c729d77820afc1f5cae3427f0de39e954/sqlite3.go#L1383 760 pos := strings.IndexRune(dsn, '?') 761 if pos >= 1 { 762 query = dsn[pos+1:] 763 if !strings.HasPrefix(dsn, "file:") { 764 dsn = dsn[:pos] 765 } 766 } 767 768 c := &conn{tls: libc.NewTLS()} 769 db, err := c.openV2( 770 dsn, 771 sqlite3.SQLITE_OPEN_READWRITE|sqlite3.SQLITE_OPEN_CREATE| 772 sqlite3.SQLITE_OPEN_FULLMUTEX| 773 sqlite3.SQLITE_OPEN_URI, 774 ) 775 if err != nil { 776 return nil, err 777 } 778 779 c.db = db 780 if err = c.extendedResultCodes(true); err != nil { 781 c.Close() 782 return nil, err 783 } 784 785 if err = applyQueryParams(c, query); err != nil { 786 c.Close() 787 return nil, err 788 } 789 790 return c, nil 791 } 792 793 func applyQueryParams(c *conn, query string) error { 794 q, err := url.ParseQuery(query) 795 if err != nil { 796 return err 797 } 798 799 for _, v := range q["_pragma"] { 800 cmd := "pragma " + v 801 _, err := c.exec(context.Background(), cmd, nil) 802 if err != nil { 803 return err 804 } 805 } 806 807 if v := q.Get("_time_format"); v != "" { 808 f, ok := writeTimeFormats[v] 809 if !ok { 810 return fmt.Errorf("unknown _time_format %q", v) 811 } 812 c.writeTimeFormat = f 813 return nil 814 } 815 816 if v := q.Get("_txlock"); v != "" { 817 lower := strings.ToLower(v) 818 if lower != "deferred" && lower != "immediate" && lower != "exclusive" { 819 return fmt.Errorf("unknown _txlock %q", v) 820 } 821 c.beginMode = v 822 } 823 824 return nil 825 } 826 827 // const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); 828 func (c *conn) columnBlob(pstmt uintptr, iCol int) (v []byte, err error) { 829 p := sqlite3.Xsqlite3_column_blob(c.tls, pstmt, int32(iCol)) 830 len, err := c.columnBytes(pstmt, iCol) 831 if err != nil { 832 return nil, err 833 } 834 835 if p == 0 || len == 0 { 836 return nil, nil 837 } 838 839 v = make([]byte, len) 840 copy(v, (*libc.RawMem)(unsafe.Pointer(p))[:len:len]) 841 return v, nil 842 } 843 844 // int sqlite3_column_bytes(sqlite3_stmt*, int iCol); 845 func (c *conn) columnBytes(pstmt uintptr, iCol int) (_ int, err error) { 846 v := sqlite3.Xsqlite3_column_bytes(c.tls, pstmt, int32(iCol)) 847 return int(v), nil 848 } 849 850 // const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); 851 func (c *conn) columnText(pstmt uintptr, iCol int) (v string, err error) { 852 p := sqlite3.Xsqlite3_column_text(c.tls, pstmt, int32(iCol)) 853 len, err := c.columnBytes(pstmt, iCol) 854 if err != nil { 855 return "", err 856 } 857 858 if p == 0 || len == 0 { 859 return "", nil 860 } 861 862 b := make([]byte, len) 863 copy(b, (*libc.RawMem)(unsafe.Pointer(p))[:len:len]) 864 return string(b), nil 865 } 866 867 // double sqlite3_column_double(sqlite3_stmt*, int iCol); 868 func (c *conn) columnDouble(pstmt uintptr, iCol int) (v float64, err error) { 869 v = sqlite3.Xsqlite3_column_double(c.tls, pstmt, int32(iCol)) 870 return v, nil 871 } 872 873 // sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); 874 func (c *conn) columnInt64(pstmt uintptr, iCol int) (v int64, err error) { 875 v = sqlite3.Xsqlite3_column_int64(c.tls, pstmt, int32(iCol)) 876 return v, nil 877 } 878 879 // int sqlite3_column_type(sqlite3_stmt*, int iCol); 880 func (c *conn) columnType(pstmt uintptr, iCol int) (_ int, err error) { 881 v := sqlite3.Xsqlite3_column_type(c.tls, pstmt, int32(iCol)) 882 return int(v), nil 883 } 884 885 // const char *sqlite3_column_decltype(sqlite3_stmt*,int); 886 func (c *conn) columnDeclType(pstmt uintptr, iCol int) string { 887 return libc.GoString(sqlite3.Xsqlite3_column_decltype(c.tls, pstmt, int32(iCol))) 888 } 889 890 // const char *sqlite3_column_name(sqlite3_stmt*, int N); 891 func (c *conn) columnName(pstmt uintptr, n int) (string, error) { 892 p := sqlite3.Xsqlite3_column_name(c.tls, pstmt, int32(n)) 893 return libc.GoString(p), nil 894 } 895 896 // int sqlite3_column_count(sqlite3_stmt *pStmt); 897 func (c *conn) columnCount(pstmt uintptr) (_ int, err error) { 898 v := sqlite3.Xsqlite3_column_count(c.tls, pstmt) 899 return int(v), nil 900 } 901 902 // sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); 903 func (c *conn) lastInsertRowID() (v int64, _ error) { 904 return sqlite3.Xsqlite3_last_insert_rowid(c.tls, c.db), nil 905 } 906 907 // int sqlite3_changes(sqlite3*); 908 func (c *conn) changes() (int, error) { 909 v := sqlite3.Xsqlite3_changes(c.tls, c.db) 910 return int(v), nil 911 } 912 913 // int sqlite3_step(sqlite3_stmt*); 914 func (c *conn) step(pstmt uintptr) (int, error) { 915 for { 916 switch rc := sqlite3.Xsqlite3_step(c.tls, pstmt); rc { 917 case sqliteLockedSharedcache: 918 if err := c.retry(pstmt); err != nil { 919 return sqlite3.SQLITE_LOCKED, err 920 } 921 case 922 sqlite3.SQLITE_DONE, 923 sqlite3.SQLITE_ROW: 924 925 return int(rc), nil 926 default: 927 return int(rc), c.errstr(rc) 928 } 929 } 930 } 931 932 func (c *conn) retry(pstmt uintptr) error { 933 mu := mutexAlloc(c.tls) 934 (*mutex)(unsafe.Pointer(mu)).Lock() 935 rc := sqlite3.Xsqlite3_unlock_notify( 936 c.tls, 937 c.db, 938 *(*uintptr)(unsafe.Pointer(&struct { 939 f func(*libc.TLS, uintptr, int32) 940 }{unlockNotify})), 941 mu, 942 ) 943 if rc == sqlite3.SQLITE_LOCKED { // Deadlock, see https://www.sqlite.org/c3ref/unlock_notify.html 944 (*mutex)(unsafe.Pointer(mu)).Unlock() 945 mutexFree(c.tls, mu) 946 return c.errstr(rc) 947 } 948 949 (*mutex)(unsafe.Pointer(mu)).Lock() 950 (*mutex)(unsafe.Pointer(mu)).Unlock() 951 mutexFree(c.tls, mu) 952 if pstmt != 0 { 953 sqlite3.Xsqlite3_reset(c.tls, pstmt) 954 } 955 return nil 956 } 957 958 func unlockNotify(t *libc.TLS, ppArg uintptr, nArg int32) { 959 for i := int32(0); i < nArg; i++ { 960 mu := *(*uintptr)(unsafe.Pointer(ppArg)) 961 (*mutex)(unsafe.Pointer(mu)).Unlock() 962 ppArg += ptrSize 963 } 964 } 965 966 func (c *conn) bind(pstmt uintptr, n int, args []driver.NamedValue) (allocs []uintptr, err error) { 967 defer func() { 968 if err == nil { 969 return 970 } 971 972 for _, v := range allocs { 973 c.free(v) 974 } 975 allocs = nil 976 }() 977 978 for i := 1; i <= n; i++ { 979 name, err := c.bindParameterName(pstmt, i) 980 if err != nil { 981 return allocs, err 982 } 983 984 var found bool 985 var v driver.NamedValue 986 for _, v = range args { 987 if name != "" { 988 // For ?NNN and $NNN params, match if NNN == v.Ordinal. 989 // 990 // Supporting this for $NNN is a special case that makes eg 991 // `select $1, $2, $3 ...` work without needing to use 992 // sql.Named. 993 if (name[0] == '?' || name[0] == '$') && name[1:] == strconv.Itoa(v.Ordinal) { 994 found = true 995 break 996 } 997 998 // sqlite supports '$', '@' and ':' prefixes for string 999 // identifiers and '?' for numeric, so we cannot 1000 // combine different prefixes with the same name 1001 // because `database/sql` requires variable names 1002 // to start with a letter 1003 if name[1:] == v.Name[:] { 1004 found = true 1005 break 1006 } 1007 } else { 1008 if v.Ordinal == i { 1009 found = true 1010 break 1011 } 1012 } 1013 } 1014 1015 if !found { 1016 if name != "" { 1017 return allocs, fmt.Errorf("missing named argument %q", name[1:]) 1018 } 1019 1020 return allocs, fmt.Errorf("missing argument with index %d", i) 1021 } 1022 1023 var p uintptr 1024 switch x := v.Value.(type) { 1025 case int64: 1026 if err := c.bindInt64(pstmt, i, x); err != nil { 1027 return allocs, err 1028 } 1029 case float64: 1030 if err := c.bindDouble(pstmt, i, x); err != nil { 1031 return allocs, err 1032 } 1033 case bool: 1034 v := 0 1035 if x { 1036 v = 1 1037 } 1038 if err := c.bindInt(pstmt, i, v); err != nil { 1039 return allocs, err 1040 } 1041 case []byte: 1042 if p, err = c.bindBlob(pstmt, i, x); err != nil { 1043 return allocs, err 1044 } 1045 case string: 1046 if p, err = c.bindText(pstmt, i, x); err != nil { 1047 return allocs, err 1048 } 1049 case time.Time: 1050 if p, err = c.bindText(pstmt, i, c.formatTime(x)); err != nil { 1051 return allocs, err 1052 } 1053 case nil: 1054 if p, err = c.bindNull(pstmt, i); err != nil { 1055 return allocs, err 1056 } 1057 default: 1058 return allocs, fmt.Errorf("sqlite: invalid driver.Value type %T", x) 1059 } 1060 if p != 0 { 1061 allocs = append(allocs, p) 1062 } 1063 } 1064 return allocs, nil 1065 } 1066 1067 // int sqlite3_bind_null(sqlite3_stmt*, int); 1068 func (c *conn) bindNull(pstmt uintptr, idx1 int) (uintptr, error) { 1069 if rc := sqlite3.Xsqlite3_bind_null(c.tls, pstmt, int32(idx1)); rc != sqlite3.SQLITE_OK { 1070 return 0, c.errstr(rc) 1071 } 1072 1073 return 0, nil 1074 } 1075 1076 // int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*)); 1077 func (c *conn) bindText(pstmt uintptr, idx1 int, value string) (uintptr, error) { 1078 p, err := libc.CString(value) 1079 if err != nil { 1080 return 0, err 1081 } 1082 1083 if rc := sqlite3.Xsqlite3_bind_text(c.tls, pstmt, int32(idx1), p, int32(len(value)), 0); rc != sqlite3.SQLITE_OK { 1084 c.free(p) 1085 return 0, c.errstr(rc) 1086 } 1087 1088 return p, nil 1089 } 1090 1091 // int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); 1092 func (c *conn) bindBlob(pstmt uintptr, idx1 int, value []byte) (uintptr, error) { 1093 if value != nil && len(value) == 0 { 1094 if rc := sqlite3.Xsqlite3_bind_zeroblob(c.tls, pstmt, int32(idx1), 0); rc != sqlite3.SQLITE_OK { 1095 return 0, c.errstr(rc) 1096 } 1097 return 0, nil 1098 } 1099 1100 p, err := c.malloc(len(value)) 1101 if err != nil { 1102 return 0, err 1103 } 1104 if len(value) != 0 { 1105 copy((*libc.RawMem)(unsafe.Pointer(p))[:len(value):len(value)], value) 1106 } 1107 if rc := sqlite3.Xsqlite3_bind_blob(c.tls, pstmt, int32(idx1), p, int32(len(value)), 0); rc != sqlite3.SQLITE_OK { 1108 c.free(p) 1109 return 0, c.errstr(rc) 1110 } 1111 1112 return p, nil 1113 } 1114 1115 // int sqlite3_bind_int(sqlite3_stmt*, int, int); 1116 func (c *conn) bindInt(pstmt uintptr, idx1, value int) (err error) { 1117 if rc := sqlite3.Xsqlite3_bind_int(c.tls, pstmt, int32(idx1), int32(value)); rc != sqlite3.SQLITE_OK { 1118 return c.errstr(rc) 1119 } 1120 1121 return nil 1122 } 1123 1124 // int sqlite3_bind_double(sqlite3_stmt*, int, double); 1125 func (c *conn) bindDouble(pstmt uintptr, idx1 int, value float64) (err error) { 1126 if rc := sqlite3.Xsqlite3_bind_double(c.tls, pstmt, int32(idx1), value); rc != 0 { 1127 return c.errstr(rc) 1128 } 1129 1130 return nil 1131 } 1132 1133 // int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); 1134 func (c *conn) bindInt64(pstmt uintptr, idx1 int, value int64) (err error) { 1135 if rc := sqlite3.Xsqlite3_bind_int64(c.tls, pstmt, int32(idx1), value); rc != sqlite3.SQLITE_OK { 1136 return c.errstr(rc) 1137 } 1138 1139 return nil 1140 } 1141 1142 // const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); 1143 func (c *conn) bindParameterName(pstmt uintptr, i int) (string, error) { 1144 p := sqlite3.Xsqlite3_bind_parameter_name(c.tls, pstmt, int32(i)) 1145 return libc.GoString(p), nil 1146 } 1147 1148 // int sqlite3_bind_parameter_count(sqlite3_stmt*); 1149 func (c *conn) bindParameterCount(pstmt uintptr) (_ int, err error) { 1150 r := sqlite3.Xsqlite3_bind_parameter_count(c.tls, pstmt) 1151 return int(r), nil 1152 } 1153 1154 // int sqlite3_finalize(sqlite3_stmt *pStmt); 1155 func (c *conn) finalize(pstmt uintptr) error { 1156 if rc := sqlite3.Xsqlite3_finalize(c.tls, pstmt); rc != sqlite3.SQLITE_OK { 1157 return c.errstr(rc) 1158 } 1159 1160 return nil 1161 } 1162 1163 // int sqlite3_prepare_v2( 1164 // sqlite3 *db, /* Database handle */ 1165 // const char *zSql, /* SQL statement, UTF-8 encoded */ 1166 // int nByte, /* Maximum length of zSql in bytes. */ 1167 // sqlite3_stmt **ppStmt, /* OUT: Statement handle */ 1168 // const char **pzTail /* OUT: Pointer to unused portion of zSql */ 1169 // ); 1170 func (c *conn) prepareV2(zSQL *uintptr) (pstmt uintptr, err error) { 1171 var ppstmt, pptail uintptr 1172 1173 defer func() { 1174 c.free(ppstmt) 1175 c.free(pptail) 1176 }() 1177 1178 if ppstmt, err = c.malloc(int(ptrSize)); err != nil { 1179 return 0, err 1180 } 1181 1182 if pptail, err = c.malloc(int(ptrSize)); err != nil { 1183 return 0, err 1184 } 1185 1186 for { 1187 switch rc := sqlite3.Xsqlite3_prepare_v2(c.tls, c.db, *zSQL, -1, ppstmt, pptail); rc { 1188 case sqlite3.SQLITE_OK: 1189 *zSQL = *(*uintptr)(unsafe.Pointer(pptail)) 1190 return *(*uintptr)(unsafe.Pointer(ppstmt)), nil 1191 case sqliteLockedSharedcache: 1192 if err := c.retry(0); err != nil { 1193 return 0, err 1194 } 1195 default: 1196 return 0, c.errstr(rc) 1197 } 1198 } 1199 } 1200 1201 // void sqlite3_interrupt(sqlite3*); 1202 func (c *conn) interrupt(pdb uintptr) (err error) { 1203 c.Lock() // Defend against race with .Close invoked by context handling. 1204 1205 defer c.Unlock() 1206 1207 if c.tls != nil { 1208 sqlite3.Xsqlite3_interrupt(c.tls, pdb) 1209 } 1210 return nil 1211 } 1212 1213 // int sqlite3_extended_result_codes(sqlite3*, int onoff); 1214 func (c *conn) extendedResultCodes(on bool) error { 1215 if rc := sqlite3.Xsqlite3_extended_result_codes(c.tls, c.db, libc.Bool32(on)); rc != sqlite3.SQLITE_OK { 1216 return c.errstr(rc) 1217 } 1218 1219 return nil 1220 } 1221 1222 // int sqlite3_open_v2( 1223 // const char *filename, /* Database filename (UTF-8) */ 1224 // sqlite3 **ppDb, /* OUT: SQLite db handle */ 1225 // int flags, /* Flags */ 1226 // const char *zVfs /* Name of VFS module to use */ 1227 // ); 1228 func (c *conn) openV2(name string, flags int32) (uintptr, error) { 1229 var p, s uintptr 1230 1231 defer func() { 1232 if p != 0 { 1233 c.free(p) 1234 } 1235 if s != 0 { 1236 c.free(s) 1237 } 1238 }() 1239 1240 p, err := c.malloc(int(ptrSize)) 1241 if err != nil { 1242 return 0, err 1243 } 1244 1245 if s, err = libc.CString(name); err != nil { 1246 return 0, err 1247 } 1248 1249 if rc := sqlite3.Xsqlite3_open_v2(c.tls, s, p, flags, 0); rc != sqlite3.SQLITE_OK { 1250 return 0, c.errstr(rc) 1251 } 1252 1253 return *(*uintptr)(unsafe.Pointer(p)), nil 1254 } 1255 1256 func (c *conn) malloc(n int) (uintptr, error) { 1257 if p := libc.Xmalloc(c.tls, types.Size_t(n)); p != 0 || n == 0 { 1258 return p, nil 1259 } 1260 1261 return 0, fmt.Errorf("sqlite: cannot allocate %d bytes of memory", n) 1262 } 1263 1264 func (c *conn) free(p uintptr) { 1265 if p != 0 { 1266 libc.Xfree(c.tls, p) 1267 } 1268 } 1269 1270 // const char *sqlite3_errstr(int); 1271 func (c *conn) errstr(rc int32) error { 1272 p := sqlite3.Xsqlite3_errstr(c.tls, rc) 1273 str := libc.GoString(p) 1274 p = sqlite3.Xsqlite3_errmsg(c.tls, c.db) 1275 var s string 1276 if rc == sqlite3.SQLITE_BUSY { 1277 s = " (SQLITE_BUSY)" 1278 } 1279 switch msg := libc.GoString(p); { 1280 case msg == str: 1281 return &Error{msg: fmt.Sprintf("%s (%v)%s", str, rc, s), code: int(rc)} 1282 default: 1283 return &Error{msg: fmt.Sprintf("%s: %s (%v)%s", str, msg, rc, s), code: int(rc)} 1284 } 1285 } 1286 1287 // Begin starts a transaction. 1288 // 1289 // Deprecated: Drivers should implement ConnBeginTx instead (or additionally). 1290 func (c *conn) Begin() (driver.Tx, error) { 1291 return c.begin(context.Background(), driver.TxOptions{}) 1292 } 1293 1294 func (c *conn) begin(ctx context.Context, opts driver.TxOptions) (t driver.Tx, err error) { 1295 return newTx(c) 1296 } 1297 1298 // Close invalidates and potentially stops any current prepared statements and 1299 // transactions, marking this connection as no longer in use. 1300 // 1301 // Because the sql package maintains a free pool of connections and only calls 1302 // Close when there's a surplus of idle connections, it shouldn't be necessary 1303 // for drivers to do their own connection caching. 1304 func (c *conn) Close() error { 1305 c.Lock() // Defend against race with .interrupt invoked by context handling. 1306 1307 defer c.Unlock() 1308 1309 if c.db != 0 { 1310 if err := c.closeV2(c.db); err != nil { 1311 return err 1312 } 1313 1314 c.db = 0 1315 } 1316 1317 if c.tls != nil { 1318 c.tls.Close() 1319 c.tls = nil 1320 } 1321 return nil 1322 } 1323 1324 // int sqlite3_close_v2(sqlite3*); 1325 func (c *conn) closeV2(db uintptr) error { 1326 if rc := sqlite3.Xsqlite3_close_v2(c.tls, db); rc != sqlite3.SQLITE_OK { 1327 return c.errstr(rc) 1328 } 1329 1330 return nil 1331 } 1332 1333 type userDefinedFunction struct { 1334 zFuncName uintptr 1335 nArg int32 1336 eTextRep int32 1337 xFunc func(*libc.TLS, uintptr, int32, uintptr) 1338 1339 freeOnce sync.Once 1340 } 1341 1342 func (c *conn) createFunctionInternal(fun *userDefinedFunction) error { 1343 if rc := sqlite3.Xsqlite3_create_function( 1344 c.tls, 1345 c.db, 1346 fun.zFuncName, 1347 fun.nArg, 1348 fun.eTextRep, 1349 0, 1350 *(*uintptr)(unsafe.Pointer(&fun.xFunc)), 1351 0, 1352 0, 1353 ); rc != sqlite3.SQLITE_OK { 1354 return c.errstr(rc) 1355 } 1356 return nil 1357 } 1358 1359 // Execer is an optional interface that may be implemented by a Conn. 1360 // 1361 // If a Conn does not implement Execer, the sql package's DB.Exec will first 1362 // prepare a query, execute the statement, and then close the statement. 1363 // 1364 // Exec may return ErrSkip. 1365 // 1366 // Deprecated: Drivers should implement ExecerContext instead. 1367 func (c *conn) Exec(query string, args []driver.Value) (driver.Result, error) { 1368 return c.exec(context.Background(), query, toNamedValues(args)) 1369 } 1370 1371 func (c *conn) exec(ctx context.Context, query string, args []driver.NamedValue) (r driver.Result, err error) { 1372 s, err := c.prepare(ctx, query) 1373 if err != nil { 1374 return nil, err 1375 } 1376 1377 defer func() { 1378 if err2 := s.Close(); err2 != nil && err == nil { 1379 err = err2 1380 } 1381 }() 1382 1383 return s.(*stmt).exec(ctx, args) 1384 } 1385 1386 // Prepare returns a prepared statement, bound to this connection. 1387 func (c *conn) Prepare(query string) (driver.Stmt, error) { 1388 return c.prepare(context.Background(), query) 1389 } 1390 1391 func (c *conn) prepare(ctx context.Context, query string) (s driver.Stmt, err error) { 1392 //TODO use ctx 1393 return newStmt(c, query) 1394 } 1395 1396 // Queryer is an optional interface that may be implemented by a Conn. 1397 // 1398 // If a Conn does not implement Queryer, the sql package's DB.Query will first 1399 // prepare a query, execute the statement, and then close the statement. 1400 // 1401 // Query may return ErrSkip. 1402 // 1403 // Deprecated: Drivers should implement QueryerContext instead. 1404 func (c *conn) Query(query string, args []driver.Value) (driver.Rows, error) { 1405 return c.query(context.Background(), query, toNamedValues(args)) 1406 } 1407 1408 func (c *conn) query(ctx context.Context, query string, args []driver.NamedValue) (r driver.Rows, err error) { 1409 s, err := c.prepare(ctx, query) 1410 if err != nil { 1411 return nil, err 1412 } 1413 1414 defer func() { 1415 if err2 := s.Close(); err2 != nil && err == nil { 1416 err = err2 1417 } 1418 }() 1419 1420 return s.(*stmt).query(ctx, args) 1421 } 1422 1423 // Driver implements database/sql/driver.Driver. 1424 type Driver struct { 1425 // user defined functions that are added to every new connection on Open 1426 udfs map[string]*userDefinedFunction 1427 } 1428 1429 var d = &Driver{udfs: make(map[string]*userDefinedFunction)} 1430 1431 func newDriver() *Driver { return d } 1432 1433 // Open returns a new connection to the database. The name is a string in a 1434 // driver-specific format. 1435 // 1436 // Open may return a cached connection (one previously closed), but doing so is 1437 // unnecessary; the sql package maintains a pool of idle connections for 1438 // efficient re-use. 1439 // 1440 // The returned connection is only used by one goroutine at a time. 1441 // 1442 // If name contains a '?', what follows is treated as a query string. This 1443 // driver supports the following query parameters: 1444 // 1445 // _pragma: Each value will be run as a "PRAGMA ..." statement (with the PRAGMA 1446 // keyword added for you). May be specified more than once. Example: 1447 // "_pragma=foreign_keys(1)" will enable foreign key enforcement. More 1448 // information on supported PRAGMAs is available from the SQLite documentation: 1449 // https://www.sqlite.org/pragma.html 1450 // 1451 // _time_format: The name of a format to use when writing time values to the 1452 // database. Currently the only supported value is "sqlite", which corresponds 1453 // to format 7 from https://www.sqlite.org/lang_datefunc.html#time_values, 1454 // including the timezone specifier. If this parameter is not specified, then 1455 // the default String() format will be used. 1456 // 1457 // _txlock: The locking behavior to use when beginning a transaction. May be 1458 // "deferred", "immediate", or "exclusive" (case insensitive). The default is to 1459 // not specify one, which SQLite maps to "deferred". More information is 1460 // available at 1461 // https://www.sqlite.org/lang_transaction.html#deferred_immediate_and_exclusive_transactions 1462 func (d *Driver) Open(name string) (driver.Conn, error) { 1463 c, err := newConn(name) 1464 if err != nil { 1465 return nil, err 1466 } 1467 1468 for _, udf := range d.udfs { 1469 if err = c.createFunctionInternal(udf); err != nil { 1470 c.Close() 1471 return nil, err 1472 } 1473 } 1474 return c, nil 1475 } 1476 1477 // FunctionContext represents the context user defined functions execute in. 1478 // Fields and/or methods of this type may get addedd in the future. 1479 type FunctionContext struct{} 1480 1481 const sqliteValPtrSize = unsafe.Sizeof(&sqlite3.Sqlite3_value{}) 1482 1483 // RegisterScalarFunction registers a scalar function named zFuncName with nArg 1484 // arguments. Passing -1 for nArg indicates the function is variadic. 1485 // 1486 // The new function will be available to all new connections opened after 1487 // executing RegisterScalarFunction. 1488 func RegisterScalarFunction( 1489 zFuncName string, 1490 nArg int32, 1491 xFunc func(ctx *FunctionContext, args []driver.Value) (driver.Value, error), 1492 ) error { 1493 return registerScalarFunction(zFuncName, nArg, sqlite3.SQLITE_UTF8, xFunc) 1494 } 1495 1496 // MustRegisterScalarFunction is like RegisterScalarFunction but panics on 1497 // error. 1498 func MustRegisterScalarFunction( 1499 zFuncName string, 1500 nArg int32, 1501 xFunc func(ctx *FunctionContext, args []driver.Value) (driver.Value, error), 1502 ) { 1503 if err := RegisterScalarFunction(zFuncName, nArg, xFunc); err != nil { 1504 panic(err) 1505 } 1506 } 1507 1508 // MustRegisterDeterministicScalarFunction is like 1509 // RegisterDeterministicScalarFunction but panics on error. 1510 func MustRegisterDeterministicScalarFunction( 1511 zFuncName string, 1512 nArg int32, 1513 xFunc func(ctx *FunctionContext, args []driver.Value) (driver.Value, error), 1514 ) { 1515 if err := RegisterDeterministicScalarFunction(zFuncName, nArg, xFunc); err != nil { 1516 panic(err) 1517 } 1518 } 1519 1520 // RegisterDeterministicScalarFunction registers a deterministic scalar 1521 // function named zFuncName with nArg arguments. Passing -1 for nArg indicates 1522 // the function is variadic. A deterministic function means that the function 1523 // always gives the same output when the input parameters are the same. 1524 // 1525 // The new function will be available to all new connections opened after 1526 // executing RegisterDeterministicScalarFunction. 1527 func RegisterDeterministicScalarFunction( 1528 zFuncName string, 1529 nArg int32, 1530 xFunc func(ctx *FunctionContext, args []driver.Value) (driver.Value, error), 1531 ) error { 1532 return registerScalarFunction(zFuncName, nArg, sqlite3.SQLITE_UTF8|sqlite3.SQLITE_DETERMINISTIC, xFunc) 1533 } 1534 1535 func registerScalarFunction( 1536 zFuncName string, 1537 nArg int32, 1538 eTextRep int32, 1539 xFunc func(ctx *FunctionContext, args []driver.Value) (driver.Value, error), 1540 ) error { 1541 1542 if _, ok := d.udfs[zFuncName]; ok { 1543 return fmt.Errorf("a function named %q is already registered", zFuncName) 1544 } 1545 1546 // dont free, functions registered on the driver live as long as the program 1547 name, err := libc.CString(zFuncName) 1548 if err != nil { 1549 return err 1550 } 1551 1552 udf := &userDefinedFunction{ 1553 zFuncName: name, 1554 nArg: nArg, 1555 eTextRep: eTextRep, 1556 xFunc: func(tls *libc.TLS, ctx uintptr, argc int32, argv uintptr) { 1557 setErrorResult := func(res error) { 1558 errmsg, cerr := libc.CString(res.Error()) 1559 if cerr != nil { 1560 panic(cerr) 1561 } 1562 defer libc.Xfree(tls, errmsg) 1563 sqlite3.Xsqlite3_result_error(tls, ctx, errmsg, -1) 1564 sqlite3.Xsqlite3_result_error_code(tls, ctx, sqlite3.SQLITE_ERROR) 1565 } 1566 1567 args := make([]driver.Value, argc) 1568 for i := int32(0); i < argc; i++ { 1569 valPtr := *(*uintptr)(unsafe.Pointer(argv + uintptr(i)*sqliteValPtrSize)) 1570 1571 switch valType := sqlite3.Xsqlite3_value_type(tls, valPtr); valType { 1572 case sqlite3.SQLITE_TEXT: 1573 args[i] = libc.GoString(sqlite3.Xsqlite3_value_text(tls, valPtr)) 1574 case sqlite3.SQLITE_INTEGER: 1575 args[i] = sqlite3.Xsqlite3_value_int64(tls, valPtr) 1576 case sqlite3.SQLITE_FLOAT: 1577 args[i] = sqlite3.Xsqlite3_value_double(tls, valPtr) 1578 case sqlite3.SQLITE_NULL: 1579 args[i] = nil 1580 case sqlite3.SQLITE_BLOB: 1581 size := sqlite3.Xsqlite3_value_bytes(tls, valPtr) 1582 blobPtr := sqlite3.Xsqlite3_value_blob(tls, valPtr) 1583 v := make([]byte, size) 1584 copy(v, (*libc.RawMem)(unsafe.Pointer(blobPtr))[:size:size]) 1585 args[i] = v 1586 default: 1587 panic(fmt.Sprintf("unexpected argument type %q passed by sqlite", valType)) 1588 } 1589 } 1590 1591 res, err := xFunc(&FunctionContext{}, args) 1592 if err != nil { 1593 setErrorResult(err) 1594 return 1595 } 1596 1597 switch resTyped := res.(type) { 1598 case nil: 1599 sqlite3.Xsqlite3_result_null(tls, ctx) 1600 case int64: 1601 sqlite3.Xsqlite3_result_int64(tls, ctx, resTyped) 1602 case float64: 1603 sqlite3.Xsqlite3_result_double(tls, ctx, resTyped) 1604 case bool: 1605 sqlite3.Xsqlite3_result_int(tls, ctx, libc.Bool32(resTyped)) 1606 case time.Time: 1607 sqlite3.Xsqlite3_result_int64(tls, ctx, resTyped.Unix()) 1608 case string: 1609 size := int32(len(resTyped)) 1610 cstr, err := libc.CString(resTyped) 1611 if err != nil { 1612 panic(err) 1613 } 1614 defer libc.Xfree(tls, cstr) 1615 sqlite3.Xsqlite3_result_text(tls, ctx, cstr, size, sqlite3.SQLITE_TRANSIENT) 1616 case []byte: 1617 size := int32(len(resTyped)) 1618 if size == 0 { 1619 sqlite3.Xsqlite3_result_zeroblob(tls, ctx, 0) 1620 return 1621 } 1622 p := libc.Xmalloc(tls, types.Size_t(size)) 1623 if p == 0 { 1624 panic(fmt.Sprintf("unable to allocate space for blob: %d", size)) 1625 } 1626 defer libc.Xfree(tls, p) 1627 copy((*libc.RawMem)(unsafe.Pointer(p))[:size:size], resTyped) 1628 1629 sqlite3.Xsqlite3_result_blob(tls, ctx, p, size, sqlite3.SQLITE_TRANSIENT) 1630 default: 1631 setErrorResult(fmt.Errorf("function did not return a valid driver.Value: %T", resTyped)) 1632 return 1633 } 1634 }, 1635 } 1636 d.udfs[zFuncName] = udf 1637 1638 return nil 1639 }