Phase 9, part 2: one database layer for SQLite and Postgres
db.DB wraps database/sql for either database. The SQL stays SQLite's: on Postgres each statement's ? become $n and LIKE ignores case as SQLite's does, and the Postgres schema (postgres.sql, schema 29 as a whole) adds SQLite's instr, json_extract and two-argument max/min, and a nocase ICU collation. Needs Postgres 18. LastInsertId became db.Insert (RETURNING id), INSERT OR IGNORE became ON CONFLICT DO NOTHING, upserts qualify their columns, and three queries group by every column they use. SUPERMARKET_TEST_POSTGRES runs the test suite on Postgres, a new schema per test; all tests pass on both. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,257 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Dialect is which database a DB is.
|
||||
type Dialect int
|
||||
|
||||
const (
|
||||
// SQLite is the local edition's database: one file.
|
||||
SQLite Dialect = iota
|
||||
// Postgres is the server and multi-tenant editions' database.
|
||||
Postgres
|
||||
)
|
||||
|
||||
func (d Dialect) String() string {
|
||||
if d == Postgres {
|
||||
return "Postgres"
|
||||
}
|
||||
return "SQLite"
|
||||
}
|
||||
|
||||
// DB is the app's database. Its SQL is written for SQLite, with ? for
|
||||
// parameters; on Postgres each statement is adjusted on the way (see
|
||||
// rebind), and the schema adds the SQLite functions the app uses
|
||||
// (postgres.sql), so the same SQL runs on both.
|
||||
type DB struct {
|
||||
// SQL is the database itself, for what only works on one dialect
|
||||
// (SQLite's backups).
|
||||
SQL *sql.DB
|
||||
Dialect Dialect
|
||||
|
||||
closeHook func() error // tests on Postgres: drop the test's schema
|
||||
}
|
||||
|
||||
func (d *DB) query(q string) string {
|
||||
if d.Dialect == Postgres {
|
||||
return rebind(q)
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
func (d *DB) args(a []any) []any {
|
||||
if d.Dialect == Postgres {
|
||||
return pgArgs(a)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// Exec runs a statement.
|
||||
func (d *DB) Exec(q string, args ...any) (sql.Result, error) {
|
||||
return d.SQL.Exec(d.query(q), d.args(args)...)
|
||||
}
|
||||
|
||||
// Query runs a query that returns rows.
|
||||
func (d *DB) Query(q string, args ...any) (*sql.Rows, error) {
|
||||
return d.SQL.Query(d.query(q), d.args(args)...)
|
||||
}
|
||||
|
||||
// QueryRow runs a query that returns at most one row.
|
||||
func (d *DB) QueryRow(q string, args ...any) *sql.Row {
|
||||
return d.SQL.QueryRow(d.query(q), d.args(args)...)
|
||||
}
|
||||
|
||||
// Begin starts a transaction.
|
||||
func (d *DB) Begin() (*Tx, error) {
|
||||
tx, err := d.SQL.Begin()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Tx{tx: tx, d: d}, nil
|
||||
}
|
||||
|
||||
// Close closes the database.
|
||||
func (d *DB) Close() error {
|
||||
err := d.SQL.Close()
|
||||
if d.closeHook != nil {
|
||||
if herr := d.closeHook(); err == nil {
|
||||
err = herr
|
||||
}
|
||||
d.closeHook = nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Tx is a transaction.
|
||||
type Tx struct {
|
||||
tx *sql.Tx
|
||||
d *DB
|
||||
}
|
||||
|
||||
// Exec runs a statement in the transaction.
|
||||
func (t *Tx) Exec(q string, args ...any) (sql.Result, error) {
|
||||
return t.tx.Exec(t.d.query(q), t.d.args(args)...)
|
||||
}
|
||||
|
||||
// Query runs a query in the transaction.
|
||||
func (t *Tx) Query(q string, args ...any) (*sql.Rows, error) {
|
||||
return t.tx.Query(t.d.query(q), t.d.args(args)...)
|
||||
}
|
||||
|
||||
// QueryRow runs a one-row query in the transaction.
|
||||
func (t *Tx) QueryRow(q string, args ...any) *sql.Row {
|
||||
return t.tx.QueryRow(t.d.query(q), t.d.args(args)...)
|
||||
}
|
||||
|
||||
// Commit commits it.
|
||||
func (t *Tx) Commit() error { return t.tx.Commit() }
|
||||
|
||||
// Rollback abandons it.
|
||||
func (t *Tx) Rollback() error { return t.tx.Rollback() }
|
||||
|
||||
var rebound sync.Map // SQLite SQL → Postgres SQL
|
||||
|
||||
// rebind turns SQLite's SQL into Postgres': ? parameters become $1, $2…,
|
||||
// and LIKE ignores case as SQLite's does (x COLLATE nocase LIKE y).
|
||||
// Strings, quoted names and comments are left as they are.
|
||||
func rebind(q string) string {
|
||||
if v, ok := rebound.Load(q); ok {
|
||||
return v.(string)
|
||||
}
|
||||
var b strings.Builder
|
||||
b.Grow(len(q) + 16)
|
||||
n := 0
|
||||
lastWord, lastWordAt := "", 0 // the last keyword or name, and where it starts in b
|
||||
for i := 0; i < len(q); {
|
||||
c := q[i]
|
||||
switch {
|
||||
case c == '\'' || c == '"': // a string, or a quoted name
|
||||
j := i + 1
|
||||
for j < len(q) {
|
||||
if q[j] == c {
|
||||
if j+1 < len(q) && q[j+1] == c { // '' inside a string
|
||||
j += 2
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
j++
|
||||
}
|
||||
end := min(j+1, len(q))
|
||||
b.WriteString(q[i:end])
|
||||
i = end
|
||||
lastWord = ""
|
||||
case c == '-' && i+1 < len(q) && q[i+1] == '-': // a comment to the end of the line
|
||||
j := strings.IndexByte(q[i:], '\n')
|
||||
if j < 0 {
|
||||
j = len(q) - i
|
||||
}
|
||||
b.WriteString(q[i : i+j])
|
||||
i += j
|
||||
case c == '/' && i+1 < len(q) && q[i+1] == '*':
|
||||
j := strings.Index(q[i+2:], "*/")
|
||||
end := len(q)
|
||||
if j >= 0 {
|
||||
end = i + 2 + j + 2
|
||||
}
|
||||
b.WriteString(q[i:end])
|
||||
i = end
|
||||
case c == '?':
|
||||
n++
|
||||
b.WriteByte('$')
|
||||
b.WriteString(strconv.Itoa(n))
|
||||
i++
|
||||
lastWord = ""
|
||||
case isWordByte(c):
|
||||
j := i
|
||||
for j < len(q) && isWordByte(q[j]) {
|
||||
j++
|
||||
}
|
||||
word := q[i:j]
|
||||
if strings.EqualFold(word, "LIKE") {
|
||||
if strings.EqualFold(lastWord, "NOT") { // x NOT LIKE y → x COLLATE nocase NOT LIKE y
|
||||
s := b.String()
|
||||
b.Reset()
|
||||
b.WriteString(s[:lastWordAt])
|
||||
b.WriteString("COLLATE nocase ")
|
||||
b.WriteString(s[lastWordAt:])
|
||||
} else {
|
||||
b.WriteString("COLLATE nocase ")
|
||||
}
|
||||
}
|
||||
lastWord, lastWordAt = word, b.Len()
|
||||
b.WriteString(word)
|
||||
i = j
|
||||
default:
|
||||
b.WriteByte(c)
|
||||
i++
|
||||
if c != ' ' && c != '\t' && c != '\n' && c != '\r' {
|
||||
lastWord = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
out := b.String()
|
||||
rebound.Store(q, out)
|
||||
return out
|
||||
}
|
||||
|
||||
func isWordByte(c byte) bool {
|
||||
return c == '_' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c >= 0x80
|
||||
}
|
||||
|
||||
// timeFormat is how the SQLite driver writes a time.Time.
|
||||
const timeFormat = "2006-01-02 15:04:05.999999999-07:00"
|
||||
|
||||
// pgArgs gives Postgres parameters as SQLite would store them: booleans
|
||||
// as 0 and 1 (the schema keeps them in integer columns), and times as
|
||||
// the SQLite driver's text.
|
||||
func pgArgs(a []any) []any {
|
||||
var out []any
|
||||
for i, v := range a {
|
||||
var conv any
|
||||
switch x := v.(type) {
|
||||
case bool:
|
||||
conv = int64(0)
|
||||
if x {
|
||||
conv = int64(1)
|
||||
}
|
||||
case time.Time:
|
||||
conv = x.Format(timeFormat)
|
||||
case *time.Time:
|
||||
if x != nil {
|
||||
conv = x.Format(timeFormat)
|
||||
}
|
||||
default:
|
||||
continue
|
||||
}
|
||||
if out == nil {
|
||||
out = append([]any(nil), a...)
|
||||
}
|
||||
out[i] = conv
|
||||
}
|
||||
if out == nil {
|
||||
return a
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Insert runs an INSERT and returns the new row's id (RETURNING id, which
|
||||
// both databases support; Postgres' driver has no LastInsertId).
|
||||
func (d *DB) Insert(q string, args ...any) (int64, error) {
|
||||
var id int64
|
||||
err := d.QueryRow(q+" RETURNING id", args...).Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
// Insert runs an INSERT in the transaction and returns the new row's id.
|
||||
func (t *Tx) Insert(q string, args ...any) (int64, error) {
|
||||
var id int64
|
||||
err := t.QueryRow(q+" RETURNING id", args...).Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
Reference in New Issue
Block a user