package sqlite import ( "context" "database/sql" "database/sql/driver" "encoding/json" "errors" "fmt" "hash/maphash" "io" "runtime" "strings" ) var ( ErrDeprecated = errors.New("This function is deprecated by [database/sql/driver]") ErrAlreadyClosed = errors.Join(driver.ErrBadConn, errors.New("Already closed")) ErrBadColumn = errors.New("Bad column name or index") ) func init() { sql.Register("sqlite", Driver{}) } type Driver struct { lib *Library } // Open implements [driver.Driver]. func (d Driver) Open(name string) (driver.Conn, error) { return nil, ErrDeprecated } // OpenConnector implements [driver.DriverContext]. func (d Driver) OpenConnector(name string) (driver.Connector, error) { lib, err := Open() if err != nil { return nil, err } d.lib = lib return Connector{name, &d}, nil } type Connector struct { name string driver *Driver } // Connect implements [driver.Connector]. func (c Connector) Connect(context.Context) (driver.Conn, error) { var handle DbHandle errno := c.driver.lib.Open(c.name, &handle) if errno != Ok { return nil, errno } return Conn{ lib: c.driver.lib, handle: handle, seed: maphash.MakeSeed(), prepared: make(map[uint64]Stmt), }, nil } // Driver implements [driver.Connector]. func (c Connector) Driver() driver.Driver { return c.driver } type Conn struct { lib *Library handle DbHandle seed maphash.Seed prepared map[uint64]Stmt } // Begin implements [driver.Conn]. func (c Conn) Begin() (driver.Tx, error) { return nil, ErrDeprecated } // Close implements [driver.Conn]. func (c Conn) Close() error { if c.handle == nil { return ErrAlreadyClosed } errno := c.lib.Close(c.handle) if errno != Ok { return errno } c.handle = nil return nil } // Prepare implements [driver.Conn]. func (c Conn) Prepare(query string) (driver.Stmt, error) { return nil, ErrDeprecated } // PrepareContext implements [driver.ConnPrepareContext]. func (c Conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { if c.handle == nil { return nil, ErrAlreadyClosed } // Hash and check manually to avoid storing query strings h := maphash.String(c.seed, strings.TrimSpace(query)) stmt, ok := c.prepared[h] if ok { return stmt, nil } var stmtHandle StmtHandle errno := c.lib.Prepare(c.handle, query, len(query), &stmtHandle, nil) if errno != Ok { return nil, errno } stmt = Stmt{&c, stmtHandle} // Make sure that statements are fully cleaned up // https://pkg.go.dev/runtime#AddCleanup runtime.AddCleanup(&stmt, func(handle StmtHandle) { errno = c.lib.Stmt.Finalize(handle) if errno != Ok { panic(errno) } }, stmt.handle) c.prepared[h] = stmt return stmt, nil } type Tx struct { conn *Conn } // Commit implements [driver.Tx]. func (t Tx) Commit() error { errno := t.conn.lib.Exec(t.conn.handle, "COMMIT;", nil, nil, nil) if errno != Ok { return errno } return nil } // Rollback implements [driver.Tx]. func (t Tx) Rollback() error { errno := t.conn.lib.Exec(t.conn.handle, "ROLLBACK;", nil, nil, nil) if errno != Ok { return errno } return nil } // BeginTx implements [driver.ConnBeginTx]. func (c Conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { errno := c.lib.Exec(c.handle, "BEGIN;", nil, nil, nil) if errno != Ok { return nil, errno } return Tx{&c}, nil } type Stmt struct { conn *Conn handle StmtHandle } // Exec implements [driver.Stmt]. func (s Stmt) Exec(args []driver.Value) (driver.Result, error) { return nil, ErrDeprecated } // Query implements [driver.Stmt]. func (s Stmt) Query(args []driver.Value) (driver.Rows, error) { return nil, ErrDeprecated } type Result struct { count int64 last_id int64 } // LastInsertId implements [driver.Result]. func (r Result) LastInsertId() (int64, error) { return r.last_id, nil } // RowsAffected implements [driver.Result]. func (r Result) RowsAffected() (int64, error) { return r.count, nil } // ExecContext implements [driver.StmtExecContext]. func (s Stmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) { var lib = s.conn.lib err := s.bindArgs(ctx, args) if err != nil { return nil, err } // Eagerly performs the full query stepping for { errno := lib.Step(s.handle) switch errno { case Ok, Row: continue case Done: return Result{ count: lib.Changes(s.conn.handle), last_id: lib.LastId(s.conn.handle), }, nil default: return nil, errno } } } type Rows struct { stmt *Stmt } // Close implements [driver.Rows]. func (r Rows) Close() error { if r.stmt == nil { return ErrAlreadyClosed } r.stmt.Close() r.stmt = nil return nil } // Columns implements [driver.Rows]. func (r Rows) Columns() []string { lib := r.stmt.conn.lib count := lib.Stmt.Column.Count(r.stmt.handle) out := make([]string, count) for i := range count { str := lib.Stmt.Column.Name(r.stmt.handle, i) out = append(out, str) } return out } // Next implements [driver.Rows]. func (r Rows) Next(dest []driver.Value) error { lib := r.stmt.conn.lib handle := r.stmt.handle errno := lib.Step(handle) if errno == Done { return io.EOF } if errno != Ok { return errno } count := lib.Stmt.Column.Count(handle) for i := range count { dataType := lib.Stmt.Column.Type(handle, i) switch dataType { case Int: dest[i] = lib.Stmt.Column.Int(handle, i) case Double: dest[i] = lib.Stmt.Column.Double(handle, i) case Text: dest[i] = lib.Stmt.Column.Text(handle, i) case Blob: dest[i] = lib.Stmt.Column.Blob(handle, i) case Null: dest[i] = nil } } return nil } // QueryContext implements [driver.StmtQueryContext]. func (s Stmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) { err := s.bindArgs(ctx, args) if err != nil { return nil, err } return Rows{&s}, nil } func (s Stmt) bindArgs(ctx context.Context, args []driver.NamedValue) error { lib := s.conn.lib for _, arg := range args { // Handle deadline if ctx.Err() != nil { return ctx.Err() } index := arg.Ordinal if arg.Name != "" { index = lib.Stmt.Index(s.handle, arg.Name) if index == 0 { return ErrBadColumn } } if arg.Value == nil { lib.Stmt.Bind.Null(s.handle, index) continue } // See [Stmt.CheckNamedValue] for conversion process var errno ErrCode switch arg.Value.(type) { case int64: errno = lib.Stmt.Bind.Int(s.handle, index, arg.Value.(int64)) case float64: errno = lib.Stmt.Bind.Double(s.handle, index, arg.Value.(float64)) case string: str := arg.Value.(string) errno = lib.Stmt.Bind.Text(s.handle, index, str, len(str), Transient) case []byte: blob := arg.Value.([]byte) errno = lib.Stmt.Bind.Blob(s.handle, index, blob, len(blob), Transient) default: return fmt.Errorf("Unsupported value: %s", arg.Value) } if errno != Ok { return errno } } return nil } // Close implements [driver.Stmt]. func (s Stmt) Close() error { if s.handle == nil { return ErrAlreadyClosed } errno := s.conn.lib.Stmt.Reset(s.handle) if errno != Ok { return errno } errno = s.conn.lib.Stmt.Reset(s.handle) if errno != Ok { return errno } s.handle = nil return nil } // NumInput implements [driver.Stmt]. func (s Stmt) NumInput() int { return s.conn.lib.Stmt.Count(s.handle) } // CheckNamedValue implements [driver.NamedValueChecker] func (s Stmt) CheckNamedValue(arg *driver.NamedValue) error { switch v := arg.Value.(type) { // The types we don't need to convert case int64, float64, string, []byte: break case int8: arg.Value = int64(v) case int16: arg.Value = int64(v) case int32: arg.Value = int64(v) case uint: arg.Value = int64(v) case uint8: arg.Value = int64(v) case uint16: arg.Value = int64(v) case uint32: arg.Value = int64(v) case uint64: arg.Value = int64(v) case uintptr: arg.Value = int64(v) case float32: arg.Value = float64(v) default: // All else fails we use JSON data, err := json.Marshal(arg.Value) if err != nil { return err } arg.Value = data } return nil }