Skip to content

Commit

Permalink
sqlite: implement driver.SessionResetter and driver.Validator
Browse files Browse the repository at this point in the history
These implementations enable us to maintain connections in database/sql
pools.

Fixes #70
  • Loading branch information
raggi committed May 26, 2023
1 parent 2d70ae2 commit ce94160
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
26 changes: 26 additions & 0 deletions sqlite.go
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,32 @@ func (c *conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, e
// Raw is so ConnInitFunc can cast to SQLConn.
func (c *conn) Raw(fn func(any) error) error { return fn(c) }

// ResetSession is called prior to executing a query on the connection
// if the connection has been used before. If the driver returns ErrBadConn
// the connection is discarded.
func (c *conn) ResetSession(ctx context.Context) error {
if c.txState != txStateNone {
return errors.New("cannot ResetSession on a connection with an active transaction")
}

// ensure that all prepared statements are reset and unbound
if c.stmts != nil {
for _, s := range c.stmts {
if err := s.resetAndClear(); err != nil {
return err
}
}
}

return nil
}

// IsValid is called prior to placing the connection into the
// connection pool. The connection will be discarded if false is returned.
func (c *conn) IsValid() bool {
return true
}

type readOnlyKey struct{}

// ReadOnly applies the query_only pragma to the connection.
Expand Down
7 changes: 7 additions & 0 deletions sqlite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ import (
"github.com/tailscale/sqlite/sqliteh"
)

// SessionResetter and Validator are required in order for conns to be returned
// to database/sql connection pools.
var (
_ driver.SessionResetter = (*conn)(nil)
_ driver.Validator = (*conn)(nil)
)

func TestOpenDB(t *testing.T) {
db := openTestDB(t)
var journalMode string
Expand Down

0 comments on commit ce94160

Please sign in to comment.