1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
// Package sqlrite is a `database/sql`-compatible driver for the
// SQLRite embedded database engine.
//
// Usage:
//
// import (
// "database/sql"
// _ "github.com/joaoh82/rust_sqlite/sdk/go"
// )
//
// db, err := sql.Open("sqlrite", "foo.sqlrite")
// // or: sql.Open("sqlrite", ":memory:")
//
// All standard `database/sql` operations work — Exec, Query, QueryRow,
// transactions via Begin/Commit/Rollback on *sql.Tx. Rows are scanned
// into Go types via `rows.Scan(&id, &name, ...)`.
//
// # How it's wired
//
// This package is a thin cgo shim over the C FFI crate (sqlrite-ffi)
// at ../../sqlrite-ffi. At build time cgo compiles sqlrite.h (the
// cbindgen-generated header) and links the `libsqlrite_c` dynamic
// library. Phase 6i ships prebuilt `libsqlrite_c` tarballs (Linux
// x86_64/aarch64, macOS aarch64, Windows x86_64) on every release —
// see the GitHub Release at sdk/go/v<V>. Developers building from
// a repo clone need `cargo build --release -p sqlrite-ffi` first
// so the shared library exists locally.
//
// # Parameter binding
//
// Like the other SDKs, parameter binding isn't yet in the engine
// (deferred to Phase 5a.2). The driver accepts the `database/sql`
// signature for forward compat, but any non-empty args slice returns
// a clear error. Inline values into the SQL for the moment.
package sqlrite
/*
// Point cgo at the FFI crate's header + the cargo target dir. Paths
// are relative to this Go file (${SRCDIR}). Developers checking out
// the repo need to `cargo build --release -p sqlrite-ffi` once
// before `go test`. End users don't need the Rust toolchain — Phase
// 6i attaches per-platform `libsqlrite_c` tarballs to every Go
// release at `sdk/go/v<V>`; extract one and point `CGO_CFLAGS` /
// `CGO_LDFLAGS` at the unpacked include/ + lib/ dirs.
#cgo CFLAGS: -I${SRCDIR}/../../sqlrite-ffi/include
#cgo LDFLAGS: -L${SRCDIR}/../../target/release -lsqlrite_c
// Embed an rpath pointing at the cargo target dir so `go test` /
// `go run` find libsqlrite_c without any DYLD_LIBRARY_PATH dance.
// Production builds will replace this rpath with a location that
// matches where the library ships (e.g. /usr/local/lib).
#cgo linux LDFLAGS: -Wl,-rpath=${SRCDIR}/../../target/release
#cgo darwin LDFLAGS: -Wl,-rpath,${SRCDIR}/../../target/release
#include <stdlib.h>
#include "sqlrite.h"
*/
import "C"
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"path/filepath"
"sync"
"unsafe"
)
// ---------------------------------------------------------------------------
// Driver registration
// DriverName is the name callers pass to `sql.Open`.
const DriverName = "sqlrite"
func init()
type sqlriteDriver struct
// Open implements `driver.Driver`. `name` is the database path (or
// `":memory:"` for a transient in-memory DB, matching SQLite).
func (name string) (driver.Conn, error)
// OpenReadOnly is a package-level escape hatch — users who want a
// read-only handle can call this directly instead of going through
// `sql.Open`. The `database/sql` API doesn't carry a read-only flag
// through Open, so we offer this as a side door: internally it
// builds a `driver.Connector` that opens each new conn in read-
// only mode, then hands the resulting `*sql.DB` back to the caller.
func OpenReadOnly(name string) *sql.DB
type roConnector struct
// Connect matches driver.Connector. `context.Context` is accepted
// for the signature but unused — the engine has no cancellation
// hook yet.
func (_ context.Context) (driver.Conn, error)
func () driver.Driver
// ---------------------------------------------------------------------------
// Helpers
// lastError pulls the thread-local last-error string from the FFI.
// Returns an empty string if no error is pending.
func lastError() string
// Status is a Go-side alias for the C `SqlriteStatus` enum. cgo
// exposes the enum as `uint32` by default (rather than a named type),
// so we work in uint32 internally and compare against the exported
// constants below. The values match the C header byte-for-byte.
type Status uint32
const (
statusOk Status = 0
statusError Status = 1
statusInvalidArgument Status = 2
// Phase 11.7 — retryable-error codes the C FFI surfaces from
// `BEGIN CONCURRENT` commit conflicts. See `ErrBusy` /
// `ErrBusySnapshot` below for the Go-side sentinels callers
// match against.
statusBusy Status = 5
statusBusySnapshot Status = 6
statusDone Status = 101
statusRow Status = 102
)
// Phase 11.7 — retryable error sentinels exposed to Go callers.
// Match against them with `errors.Is(err, sqlrite.ErrBusy)` /
// `errors.Is(err, sqlrite.ErrBusySnapshot)` to drive a retry
// loop:
//
// for {
// tx, err := db.Begin()
// if err != nil { return err }
// // ... do work, then:
// err = tx.Commit()
// if err == nil { break }
// if errors.Is(err, sqlrite.ErrBusy) ||
// errors.Is(err, sqlrite.ErrBusySnapshot) {
// // tx was already rolled back by the engine
// continue
// }
// return err
// }
//
// Use [IsRetryable] for a kind-agnostic check.
var (
// ErrBusy is returned when a `BEGIN CONCURRENT` commit hits a
// row-level write-write conflict. The transaction has already
// been rolled back; the caller should retry the whole
// transaction with a fresh `BEGIN CONCURRENT`.
ErrBusy = errors.New("sqlrite: busy (write-write conflict; transaction rolled back, retry)")
// ErrBusySnapshot is returned when a `BEGIN CONCURRENT` read
// sees a row that has been superseded after the transaction's
// snapshot was taken. Same retry semantics as `ErrBusy`.
ErrBusySnapshot = errors.New("sqlrite: busy snapshot (snapshot stale; transaction rolled back, retry)")
)
// IsRetryable reports whether `err` chains an `ErrBusy` or
// `ErrBusySnapshot` and should therefore be retried by the
// caller. Use it instead of comparing against individual
// sentinels so a future retryable variant (e.g. lock-wait
// timeout) doesn't force a caller-side change.
func IsRetryable(err error) bool
// wrapErr returns a Go error when the status code is nonzero. Use
// after any `sqlrite_*` call that can fail.
//
// Phase 11.7 — retryable statuses surface as errors that wrap the
// matching sentinel (`ErrBusy` / `ErrBusySnapshot`) so callers can
// use `errors.Is` to branch their retry loops without parsing the
// message.
func wrapErr(status Status, op string) error
// cString converts a Go string into a C-allocated NUL-terminated
// copy the caller must `C.free`.
func cString(s string) *C.char
// isSelect is a coarse heuristic: trim leading whitespace/comments
// and check if the statement starts with `select`. Used to pick
// between `sqlrite_execute` (no rows) and `sqlrite_query` (rows).
// The engine also reports the statement type via its parser, but
// exposing that through the C FFI would add another round-trip per
// call — not worth it for this level of granularity.
func isSelect(sql string) bool
// eqFold is an ASCII-only case-insensitive compare — avoids the
// strings.ToLower allocation for this hot path.
func eqFold(a, b string) bool
// rejectParamsForNow is the uniform "we don't do parameter binding
// yet" response. Accepted: nil / empty. Anything else is an error.
func rejectParamsForNow(args []driver.Value) error
func rejectNamedParamsForNow(args []driver.NamedValue) error
// freeCString is a typed alias so call sites read cleanly.
func freeCString(p *C.char)
// ---------------------------------------------------------------------------
// Phase 11.11c — process-level path registry for file-backed siblings.
//
// The engine's `Connection::open` takes `flock(LOCK_EX)` on the WAL
// sidecar, so the *second* `sqlrite_open` for the same path in the
// same process would deadlock with itself. `database/sql` makes this
// easy to hit: a single `sql.DB`'s pool spins up additional `Conn`s
// on demand by calling `driver.Open` again, and applications routinely
// hold more than one `*sql.DB` against the same file.
//
// We thread every file-backed read-write `newConn` call through a
// process-level registry keyed by canonical absolute path. The first
// caller pays for a real `sqlrite_open` and the resulting handle is
// stashed as a hidden "primary" in the registry. Subsequent callers
// (within the same `sql.DB` pool or across instances) mint a sibling
// off that primary via `sqlrite_connect_sibling` — sharing the
// `Arc<Mutex<Database>>` underneath, so they all see the same tables
// and can each hold their own `BEGIN CONCURRENT`. The registry holds
// a refcount of outstanding siblings; when the last one closes, the
// registry closes the primary and drops the entry.
//
// **Scope (v0).** Read-only opens and `:memory:` opens skip the
// registry: a read-only open takes a shared lock that can coexist
// with other readers but conflicts with any writer in the same
// process, and `:memory:` databases are isolated by design.
// Cross-pool sharing for read-only handles is a future follow-up if
// anyone hits the use case.
//
// **Lock order.** Two locks are in play: each `*conn`'s `c.mu`, and
// the registry's `registryMu`. Acquisition order is always
// `c.mu` → `registryMu`, never the reverse. `newConn` only holds
// `registryMu`; `conn.Close` takes `c.mu` first, then `registryMu`.
type sharedEntry struct
var (
registryMu sync.Mutex
// canonical absolute path → entry.
pathRegistry = map[string]*sharedEntry
)
// canonicalPath returns the absolute, lexically-cleaned form of
// `name`. We use this as the registry key so two `sql.Open` calls
// with different relative paths but the same target resolve to the
// same entry. Symlinks are *not* resolved — `filepath.Abs` is
// path-syntactic only. Callers who want symlink-equality should
// pass an `os.EvalSymlinks`-ed path; for v0 that's their problem,
// not ours.
func canonicalPath(name string) (string, error)
// acquireSiblingHandle is the entry point newConn calls for
// file-backed read-write opens. Returns the sibling handle the
// caller should own + the canonical path the caller stashes on
// the `*conn` so Close can find the right entry.
func acquireSiblingHandle(name string) (*C.SqlriteConnection, string, error)
// releaseSiblingHandle is called from `conn.Close` for registered
// conns. Drops the refcount; when it hits zero, closes the hidden
// primary and removes the entry.
func releaseSiblingHandle(canonical string)
// registryHandleCount returns the number of outstanding siblings
// for `path` (canonicalized internally). Returns 0 for unknown
// paths. Used by the tests; not part of the public API.
//
//nolint:deadcode // exported via go:linkname-style for test access
func registryHandleCount(path string) int32