File
Blob: util/sqlite/sqlite.go
| 1 | // Package sqlite opens the SQLite driver with Specter's per-connection memory limit. |
| 2 | package sqlite |
| 3 | |
| 4 | import ( |
| 5 | "context" |
| 6 | "database/sql" |
| 7 | "database/sql/driver" |
| 8 | "errors" |
| 9 | |
| 10 | "github.com/ncruces/go-sqlite3" |
| 11 | sqlitedriver "github.com/ncruces/go-sqlite3/driver" |
| 12 | ) |
| 13 | |
| 14 | const MaxMemory = 64 << 20 |
| 15 | |
| 16 | // Open applies the memory limit and optional setup to every physical connection, |
| 17 | // including replacements opened by database/sql's background goroutine. |
| 18 | func Open(dsn string, setup func(*sqlite3.Conn) error) (*sql.DB, error) { |
| 19 | c, err := (&sqlitedriver.SQLite{}).OpenConnector(dsn) |
| 20 | if err != nil { |
| 21 | return nil, err |
| 22 | } |
| 23 | return sql.OpenDB(connector{Connector: c, setup: setup}), nil |
| 24 | } |
| 25 | |
| 26 | type connector struct { |
| 27 | driver.Connector |
| 28 | setup func(*sqlite3.Conn) error |
| 29 | } |
| 30 | |
| 31 | func (c connector) Connect(ctx context.Context) (driver.Conn, error) { |
| 32 | conn, err := c.Connector.Connect(sqlite3.WithMaxMemory(ctx, MaxMemory)) |
| 33 | if err != nil { |
| 34 | return nil, err |
| 35 | } |
| 36 | if c.setup != nil { |
| 37 | raw := conn.(sqlitedriver.Conn).Raw() |
| 38 | previous := raw.SetInterrupt(ctx) |
| 39 | err = c.setup(raw) |
| 40 | raw.SetInterrupt(previous) |
| 41 | if err != nil { |
| 42 | return nil, errors.Join(err, conn.Close()) |
| 43 | } |
| 44 | } |
| 45 | return conn, nil |
| 46 | } |