@broberg/db-sdk 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +283 -25
- package/dist/index.d.ts +32 -55
- package/dist/index.js +174 -17
- package/dist/index.js.map +1 -1
- package/dist/switchable/index.d.ts +506 -0
- package/dist/switchable/index.js +965 -0
- package/dist/switchable/index.js.map +1 -0
- package/dist/types-9Y21zZWt.d.ts +114 -0
- package/package.json +19 -5
package/README.md
CHANGED
|
@@ -1,12 +1,21 @@
|
|
|
1
1
|
# @broberg/db-sdk
|
|
2
2
|
|
|
3
|
-
The
|
|
4
|
-
|
|
5
|
-
play as [`@broberg/ai-sdk`](https://www.npmjs.com/package/@broberg/ai-sdk), for
|
|
6
|
-
the data layer.
|
|
3
|
+
The broberg.ai fleet's shared **database client** — one thin facade over two
|
|
4
|
+
transports:
|
|
7
5
|
|
|
8
|
-
|
|
9
|
-
|
|
6
|
+
| Transport | For | Env default |
|
|
7
|
+
|---|---|---|
|
|
8
|
+
| `libsql` (default) | Turso / libSQL, local `file:` databases | `TURSO_DATABASE_URL`, `TURSO_AUTH_TOKEN` |
|
|
9
|
+
| `postgres` | PostgreSQL, including Supabase | `DATABASE_URL` |
|
|
10
|
+
|
|
11
|
+
`createClient()` returns the same `DbClient` from both, so switching transport is
|
|
12
|
+
a change at the call to `createClient` — **for the connection.**
|
|
13
|
+
|
|
14
|
+
> **The SQL is not translated.** libSQL takes `?` placeholders, Postgres takes
|
|
15
|
+
> `$1`, and the two dialects differ in DDL, functions and `PRAGMA`. The facade
|
|
16
|
+
> passes your SQL through untouched: rewriting `?` into `$1` would also rewrite a
|
|
17
|
+
> `?` inside a string literal or a JSON operator. Moving an app between
|
|
18
|
+
> transports means moving its SQL too.
|
|
10
19
|
|
|
11
20
|
## Install
|
|
12
21
|
|
|
@@ -20,41 +29,290 @@ bun add @broberg/db-sdk
|
|
|
20
29
|
```ts
|
|
21
30
|
import { createClient, createReplica, health } from '@broberg/db-sdk';
|
|
22
31
|
|
|
23
|
-
//
|
|
32
|
+
// Turso (reads TURSO_DATABASE_URL + TURSO_AUTH_TOKEN)
|
|
33
|
+
const db = createClient();
|
|
34
|
+
|
|
35
|
+
// Postgres / Supabase (reads DATABASE_URL)
|
|
36
|
+
const pg = createClient({ backend: 'postgres' });
|
|
37
|
+
|
|
38
|
+
await pg.execute({ sql: 'insert into notes (id, body) values ($1, $2)', args: [1, 'hej'] });
|
|
39
|
+
const { rows } = await pg.execute('select id, body from notes');
|
|
40
|
+
// rows: [{ id: 1, body: 'hej' }]
|
|
41
|
+
|
|
42
|
+
// Several statements in ONE transaction — all apply or none do.
|
|
43
|
+
await db.batch([
|
|
44
|
+
{ sql: 'delete from s where edge = ?', args: ['m1'] },
|
|
45
|
+
{ sql: 'insert into s (edge, name) values (?, ?)', args: ['m1', 'x'] },
|
|
46
|
+
], 'write');
|
|
47
|
+
|
|
48
|
+
await health(pg); // { ok: true, transport: 'postgres', version: '16.4' }
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
`health()` reports the transport that **answered** — read it there rather than
|
|
52
|
+
inferring it from your own config.
|
|
53
|
+
|
|
54
|
+
### The escape hatch
|
|
55
|
+
|
|
56
|
+
`client.raw` is the underlying driver's own client, typed per transport, for
|
|
57
|
+
anything the facade does not cover:
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
const pg = createClient({ backend: 'postgres' });
|
|
61
|
+
await pg.raw.listen('events', (payload) => { /* … */ }); // postgres.js
|
|
62
|
+
|
|
24
63
|
const db = createClient();
|
|
25
|
-
await
|
|
64
|
+
await db.raw.executeMultiple(script); // @libsql/client
|
|
65
|
+
```
|
|
26
66
|
|
|
27
|
-
|
|
67
|
+
### Embedded replicas (libSQL only)
|
|
68
|
+
|
|
69
|
+
A local SQLite file kept in sync with a remote Turso primary. There is no
|
|
70
|
+
Postgres counterpart, and the config type says so — `backend: 'postgres'` on a
|
|
71
|
+
`ReplicaConfig` is a compile error.
|
|
72
|
+
|
|
73
|
+
```ts
|
|
28
74
|
const edge = createReplica({ path: '/data/buddy.db', syncIntervalSeconds: 30 });
|
|
29
|
-
// reads hit the local file at SQLite speed; writes forward to the primary
|
|
30
75
|
await edge.sync(); // or rely on the interval
|
|
31
76
|
```
|
|
32
77
|
|
|
33
|
-
|
|
78
|
+
### Supabase
|
|
79
|
+
|
|
80
|
+
Use the pooler connection string as `DATABASE_URL`. Prepared statements are
|
|
81
|
+
**always off** in the Postgres transport, because of what they do to Supabase's
|
|
82
|
+
transaction-mode pooler (port 6543). Measured 23 Sep 2026 against a real
|
|
83
|
+
Supabase project (eu-north-1), 40 concurrent queries with prepared statements ON:
|
|
84
|
+
|
|
85
|
+
| Route | Result |
|
|
86
|
+
|---|---|
|
|
87
|
+
| transaction pooler, 6543 | **hung** after 5–8 answers — no error, 3 runs of 3 |
|
|
88
|
+
| session pooler | 40/40 |
|
|
89
|
+
| direct, 5432 | 40/40 |
|
|
90
|
+
|
|
91
|
+
**Reproduced on 24 Sep 2026 on a self-hosted Supabase** (CLI 2.117.0, Supavisor
|
|
92
|
+
2.9.12, transaction mode): prepared statements ON hung 2 runs of 2 (one also
|
|
93
|
+
threw driver-internal errors), OFF answered 40/40, and a direct connection
|
|
94
|
+
answered 40/40 either way. So it is the transaction pooler (Supavisor) itself,
|
|
95
|
+
not a quirk of Supabase's cloud.
|
|
96
|
+
|
|
97
|
+
It does not fail — it **hangs**, and only under concurrency, so a sequential
|
|
98
|
+
test and a local Postgres both stay green. The contract suite has a case for
|
|
99
|
+
it — 60 concurrent queries through a transaction pooler against a 90-second
|
|
100
|
+
deadline, red with `HUNG` when prepared statements are turned back on — but it
|
|
101
|
+
runs only when `DB_SDK_TEST_PG_POOLER_URL` points at a real pooler. **CI does
|
|
102
|
+
not have one today**, so the guard in CI is the configuration test
|
|
103
|
+
(`prepare: false`), not the behavioural one.
|
|
104
|
+
|
|
105
|
+
Keep the service-role connection string on the server. Supabase auth belongs in
|
|
106
|
+
`@broberg/auth`, storage in `@broberg/media`; this package is the SQL connection
|
|
107
|
+
only.
|
|
108
|
+
|
|
109
|
+
### ORM
|
|
110
|
+
|
|
111
|
+
The ORM stays in the consumer. Drizzle takes the **driver's** client, so hand it
|
|
112
|
+
`raw`:
|
|
34
113
|
|
|
35
114
|
```ts
|
|
36
|
-
import { drizzle } from 'drizzle-orm/
|
|
37
|
-
|
|
38
|
-
const orm = drizzle(createClient(), { schema });
|
|
115
|
+
import { drizzle } from 'drizzle-orm/postgres-js';
|
|
116
|
+
const orm = drizzle(createClient({ backend: 'postgres' }).raw, { schema });
|
|
39
117
|
```
|
|
40
118
|
|
|
41
119
|
## API
|
|
42
120
|
|
|
43
|
-
| Export | Signature |
|
|
121
|
+
| Export | Signature |
|
|
122
|
+
|---|---|
|
|
123
|
+
| `createClient` | `(cfg?: LibsqlConfig) => DbClient<LibsqlClient>` · `(cfg: PostgresConfig) => DbClient<Sql>` |
|
|
124
|
+
| `createReplica` | `(cfg: ReplicaConfig) => ReplicaClient` — libSQL only |
|
|
125
|
+
| `health` | `(client) => Promise<{ ok, transport, version }>` — throws if unreachable |
|
|
126
|
+
|
|
127
|
+
`DbClient`: `transport`, `raw`, `execute(stmt)`, `batch(stmts, mode?)`, `close()`.
|
|
128
|
+
A statement is `string` or `{ sql, args? }`. A result is
|
|
129
|
+
`{ rows, columns, rowsAffected }`, with rows as plain objects keyed by column.
|
|
130
|
+
|
|
131
|
+
**Values are the driver's own — the facade unifies the shape, not the types.**
|
|
132
|
+
Measured on the same query:
|
|
133
|
+
|
|
134
|
+
| SQL value | libsql | postgres |
|
|
44
135
|
|---|---|---|
|
|
45
|
-
| `
|
|
46
|
-
| `
|
|
47
|
-
| `
|
|
136
|
+
| `count(*)`, `bigint` | `number` | **`string`** (`'1'`) |
|
|
137
|
+
| `numeric` / `1.5` literal | `number` | **`string`** (`'1.5'`) |
|
|
138
|
+
| `integer` | `number` | `number` |
|
|
139
|
+
| `timestamptz` | `string` | `Date` |
|
|
140
|
+
| `jsonb` | `string` | parsed object |
|
|
141
|
+
|
|
142
|
+
Postgres returns int8 and numeric as strings because a JS number cannot hold an
|
|
143
|
+
int8 above 2^53, and the facade does not convert them for the same reason —
|
|
144
|
+
a silent precision loss is worse than a visible string. Wrap with `Number(...)`
|
|
145
|
+
where you know the range is safe. The contract suite pins these, so a driver
|
|
146
|
+
changing them turns it red.
|
|
147
|
+
|
|
148
|
+
`batch` modes are `'write'` and `'deferred'`. There is **no `'read'` mode**: a
|
|
149
|
+
libSQL read batch against a local file was measured executing an INSERT that
|
|
150
|
+
Postgres refused, and a read-only promise that holds on one transport only is not
|
|
151
|
+
one the facade can make.
|
|
48
152
|
|
|
49
|
-
|
|
153
|
+
## node-postgres (`pg`)
|
|
50
154
|
|
|
51
|
-
|
|
155
|
+
```ts
|
|
156
|
+
const db = createClient({ backend: 'pg', url: process.env.DATABASE_URL }); // or { backend: 'pg', pool: myPgPool }
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
The same facade over `pg.Pool` — for a stack that needs a pg pool (Better Auth's
|
|
160
|
+
kysely dialect does). `pg` is an optional peer dependency: install it yourself,
|
|
161
|
+
or pass your own `pool` and the package never imports it. The contract suite
|
|
162
|
+
runs against it unchanged (components-F085.6).
|
|
163
|
+
|
|
164
|
+
## Instant switch (`@broberg/db-sdk/switchable`) — Postgres, 0.3.0+
|
|
165
|
+
|
|
166
|
+
For a dual-DB app (primary + reserve replica, D-444126): one client that moves
|
|
167
|
+
to the other database **while the process runs**, a fence that makes the
|
|
168
|
+
database you are NOT on refuse writes, and the way back without loss. Ported
|
|
169
|
+
from broberg-id (F084.149/.153/.154); components-F085.5.
|
|
170
|
+
|
|
171
|
+
```ts
|
|
172
|
+
import { createClient } from '@broberg/db-sdk';
|
|
173
|
+
import { createSwitchable } from '@broberg/db-sdk/switchable';
|
|
174
|
+
|
|
175
|
+
const primary = createClient({ backend: 'postgres', url: process.env.DATABASE_URL });
|
|
176
|
+
const db = createSwitchable(primary, 'primary'); // use `db` everywhere — execute(), batch() AND db.raw
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
**The switch itself is NOT something to do by hand.** It is an ordered
|
|
180
|
+
sequence with a way back at every step, run across every machine — broberg-id's
|
|
181
|
+
`src/db-switch-cli.ts`, whose port into this package is the next step of
|
|
182
|
+
F085.5. Until then, read the order here, not as a recipe:
|
|
183
|
+
|
|
184
|
+
1. Preconditions: the fence is installed on both sides and covers every table;
|
|
185
|
+
the target is `locked`, the current side `open`. Otherwise stop.
|
|
186
|
+
2. To the reserve: a marker row through the replication stream proves it is alive.
|
|
187
|
+
3. `hold(ms)` on every machine. **Any machine not drained (`ok: false`) → abort.**
|
|
188
|
+
4. To the reserve: a second marker must arrive (everything written before the
|
|
189
|
+
hold is there), then `alter subscription … disable`, then
|
|
190
|
+
`captureBaseline(reserve)` — while everything is held.
|
|
191
|
+
5. `setFence(target, 'open')` — nobody writes yet, everyone holds.
|
|
192
|
+
6. `point(target)` on every machine, then `release()` on every machine.
|
|
193
|
+
7. `setFence(old, 'locked')` — also if a machine did not confirm: a machine
|
|
194
|
+
left on the old side is exactly the one that must fail loudly.
|
|
195
|
+
|
|
196
|
+
**Abort** (any step before 6 fails): `release()` on the old side everywhere
|
|
197
|
+
(the machine-side control does this itself if the orchestrator vanishes),
|
|
198
|
+
re-lock the target if step 5 ran, and re-enable the subscription if step 4 ran.
|
|
199
|
+
The way back to the primary is the same with `reconcile(reserve, primary,
|
|
200
|
+
{ apply: true })` before the hold (most rows) and again under it (the rest).
|
|
201
|
+
|
|
202
|
+
- **Either driver.** `createSwitchable(createClient({ backend: 'pg', … }))` gives a `.raw` that is a stand-in `pg.Pool` — `query` and `connect()` wait out a hold and count as running (a client until its `release()`, once) — so Better Auth and your own pool code follow the switch. Both sides must use the same driver.
|
|
203
|
+
- **`.raw` follows the switch.** `db.raw` is a stand-in `Sql`: `` sql`…` ``,
|
|
204
|
+
`sql.unsafe()`, `sql.begin()` and `sql.reserve()` all reach the side that is
|
|
205
|
+
active when they run, after any hold. Query modifiers and fragments work as
|
|
206
|
+
usual; a cursor or `forEach` counts as running until it ends. `sql.notify()`
|
|
207
|
+
waits out a hold too; `sql.listen()` stays on the side it was called on. If a
|
|
208
|
+
postgres.js upgrade moves the internals this relies on, creating the client
|
|
209
|
+
throws — it never runs quietly on the wrong side (postgres.js is pinned
|
|
210
|
+
`~3.4.9`).
|
|
211
|
+
- **The fence lives in the database** (a per-statement trigger), so it covers
|
|
212
|
+
every path in: `execute()`, `.raw`, migrations, psql. Call `installFence`
|
|
213
|
+
after every migration — it fences new tables and never changes the state.
|
|
214
|
+
Replication passes through a locked subscriber — initial copy, INSERT,
|
|
215
|
+
UPDATE, DELETE (measured in CI).
|
|
216
|
+
- **The way back:** `captureBaseline(reserve)` at the switch;
|
|
217
|
+
`reconcile(reserve, primary, { apply })` before switching back copies what
|
|
218
|
+
changed in the reserve and reports — never overwrites — a row the primary
|
|
219
|
+
changed on its own.
|
|
220
|
+
- Names default to `dbFence` / `db_sdk.fence_bypass` / schema `dbSwitch`; BID
|
|
221
|
+
passes its own (`bidFence`, `bid.fence_bypass`, `bidSwitch`).
|
|
222
|
+
|
|
223
|
+
**Per-machine control (`createSwitchControl`).** The HTTP door an orchestrator
|
|
224
|
+
moves each process by — `POST /db/prepare|hold|point|release|abort`, `GET
|
|
225
|
+
/db/status`, Bearer = `switchToken(sharedSecret, context)`. `point` is refused
|
|
226
|
+
(409) unless the target was prepared AND the machine holds. If the orchestrator
|
|
227
|
+
disappears, a holding machine aborts by itself after 2 × the hold — back to
|
|
228
|
+
the side from before, never alone on the new one. Serve it where only your
|
|
229
|
+
own machines reach it (BID: Fly's private network); which URLs and TLS the
|
|
230
|
+
targets use stays in your app:
|
|
231
|
+
|
|
232
|
+
```ts
|
|
233
|
+
const handle = createSwitchControl({
|
|
234
|
+
switchable: db,
|
|
235
|
+
secret: process.env.APP_SECRET!,
|
|
236
|
+
targets: {
|
|
237
|
+
primary: { label: 'supabase', open: () => createClient({ backend: 'postgres', url: PRIMARY_URL }) },
|
|
238
|
+
reserve: { label: 'upcloud', open: () => createClient({ backend: 'postgres', url: RESERVE_URL }) },
|
|
239
|
+
},
|
|
240
|
+
});
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
`emergencyGate()` is BID's guard for a switch without the primary: never
|
|
244
|
+
without an explicit accept of data loss, and refused while the primary answers.
|
|
245
|
+
|
|
246
|
+
**Orchestration (`orchestrateSwitch`).** BID's switch order as one call, over
|
|
247
|
+
every machine: fence preconditions → probe through the stream → prepare →
|
|
248
|
+
hold (an undrained machine ABORTS) → marker → subscription off → baseline →
|
|
249
|
+
unfence target → point → release → fence the old side. Any failure before
|
|
250
|
+
release aborts on all machines: back to the old side, target re-fenced,
|
|
251
|
+
subscription re-enabled. The way home (`to: 'primary'`) copies the reserve's
|
|
252
|
+
writes first; conflicts stop it unless `skipConflicts`. Emergency
|
|
253
|
+
(`primaryDown`) needs `acceptDataLoss` and is refused while the primary answers.
|
|
254
|
+
Machines are `{ id, call }` — `httpMachine(id, baseUrl, switchToken(secret))`
|
|
255
|
+
for plain HTTP; finding them and setting secrets afterwards stays in the app.
|
|
256
|
+
Tested with three in-process machines, two servers and real replication,
|
|
257
|
+
including the faults BID injects in production (`fault: 'replication' | 'point'`).
|
|
258
|
+
|
|
259
|
+
**Is the reserve alive? (`reserveHealth`, `watchReserve`).** Read from the
|
|
260
|
+
PRIMARY's replication slot (a dead reserve is exactly what it must report):
|
|
261
|
+
`missing | inactive | lost | stale | lagging | unreadable`, never «ok» when it
|
|
262
|
+
could not look. Serve it on its own route (BID: `/health/reserve`), never your
|
|
263
|
+
readiness check — a dead reserve must not take logins down. `watchReserve` is
|
|
264
|
+
the pure alarm hook: unhealthy ≥ 10 min in a row → one incident per episode
|
|
265
|
+
(the id carries the episode start); a failed reserve migration
|
|
266
|
+
(`noteReserveMigration`) alarms at once. You keep the state and send the alarm.
|
|
267
|
+
|
|
268
|
+
**The reserve reconnects itself (`runGuard`, `liveDeps`).** When the
|
|
269
|
+
reserve's provider gives it a new public address (UpCloud maintenance did, twice),
|
|
270
|
+
the primary's allow-list keeps it out and the slot dies. The guard — run from
|
|
271
|
+
CI, never the app (the primary's token is account-wide) — confirms the slot is
|
|
272
|
+
really unhealthy (a blink is not a state), finds the reserve's current address,
|
|
273
|
+
ADDS it (never removes), reads the list back until it took effect, and waits for
|
|
274
|
+
the slot. Outcomes: `healthy | not-network | already-allowed | fixed |
|
|
275
|
+
still-down | needs-rebuild`. `liveDeps` is UpCloud + Supabase; another pair of
|
|
276
|
+
providers is another `GuardDeps`.
|
|
277
|
+
|
|
278
|
+
The CI workflow for the guard, the replication setup and the runbook are a
|
|
279
|
+
Discovery playbook, not package code.
|
|
280
|
+
|
|
281
|
+
## Migrating from 0.1.x
|
|
282
|
+
|
|
283
|
+
`createClient()` used to return `@libsql/client`'s own `Client`. It now returns
|
|
284
|
+
`DbClient`. What changed for a caller:
|
|
285
|
+
|
|
286
|
+
- `execute(string | { sql, args })` and `batch(stmts, 'write')` — **unchanged**.
|
|
287
|
+
- `rows[i]['column']` — unchanged. Positional access `rows[i][0]` is gone: rows
|
|
288
|
+
are plain objects now.
|
|
289
|
+
- `lastInsertRowid` — gone from the facade (it is a SQLite concept). Use
|
|
290
|
+
`client.raw.execute(...)`, or `returning id`.
|
|
291
|
+
- Anything else on the libSQL client (`executeMultiple`, `transaction`, `sync`):
|
|
292
|
+
reach it via `client.raw`.
|
|
293
|
+
- **Drizzle:** `drizzle(createClient(), { schema })` — the pattern this README
|
|
294
|
+
used to show — no longer works, because drizzle wants the driver's client.
|
|
295
|
+
Write `drizzle(createClient().raw, { schema })`. Measured working for both
|
|
296
|
+
transports (`drizzle-orm/libsql` and `drizzle-orm/postgres-js`).
|
|
297
|
+
- `type Client` still exists as a deprecated alias of `DbClient`.
|
|
298
|
+
|
|
299
|
+
buddy (`apps/server`), the one known 0.1.x consumer, typechecks and passes its own
|
|
300
|
+
db-sdk test against this version with no source changes.
|
|
301
|
+
|
|
302
|
+
## Tests
|
|
303
|
+
|
|
304
|
+
```bash
|
|
305
|
+
DB_SDK_TEST_PG_URL=postgres://… bun test
|
|
306
|
+
```
|
|
52
307
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
308
|
+
One contract suite runs the **same** cases against libSQL (a local file), a
|
|
309
|
+
**real** Postgres, and — when `DB_SDK_TEST_PG_POOLER_URL` is set — a real
|
|
310
|
+
Supabase transaction pooler. Without `DB_SDK_TEST_PG_URL` the suite fails rather than
|
|
311
|
+
skipping Postgres — a skipped transport reads as a green one. The switch tests
|
|
312
|
+
need a SECOND server at `DB_SDK_TEST_PG_URL_2` (two databases on one server hid
|
|
313
|
+
a cancel going to the wrong server). CI starts two Postgres 17 servers with
|
|
314
|
+
`wal_level=logical` and sets `DB_SDK_TEST_REQUIRE_LOGICAL=1`, so the replication
|
|
315
|
+
tests cannot be skipped there.
|
|
58
316
|
|
|
59
317
|
## License
|
|
60
318
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,68 +1,45 @@
|
|
|
1
|
+
import { L as LibsqlConfig, D as DbClient, P as PostgresConfig, a as PgConfig, R as ReplicaConfig, b as ReplicaClient, H as Health } from './types-9Y21zZWt.js';
|
|
2
|
+
export { B as BatchMode, C as Client, c as DbConfig, d as DbResult, e as Row, S as Statement, T as Transport } from './types-9Y21zZWt.js';
|
|
3
|
+
import { Pool } from 'pg';
|
|
1
4
|
import { Client } from '@libsql/client';
|
|
2
|
-
export { Client
|
|
3
|
-
|
|
4
|
-
|
|
5
|
+
export { Client as LibsqlClient } from '@libsql/client';
|
|
6
|
+
import { Sql } from 'postgres';
|
|
7
|
+
export { Sql } from 'postgres';
|
|
5
8
|
|
|
6
9
|
/**
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
+
* @broberg/db-sdk — the broberg.ai fleet's shared database client.
|
|
11
|
+
*
|
|
12
|
+
* One facade over two transports: libSQL/Turso and PostgreSQL (Supabase
|
|
13
|
+
* included). `createClient` returns the same `DbClient` from both, so switching
|
|
14
|
+
* transport is a config change at the call to `createClient` — for the
|
|
15
|
+
* CONNECTION. The SQL itself is passed through untouched: libSQL takes `?`,
|
|
16
|
+
* Postgres takes `$1`, and the facade does not translate between them.
|
|
17
|
+
*
|
|
18
|
+
* Intentionally THIN: a client, an embedded-replica client (libSQL only), and a
|
|
19
|
+
* health probe. ORM, schema and migrations stay in the consumer.
|
|
10
20
|
*/
|
|
11
|
-
type Backend = 'libsql';
|
|
12
|
-
/** Connection config for a remote database. Falls back to env. */
|
|
13
|
-
interface DbConfig {
|
|
14
|
-
/** `libsql://…` (remote) or `file:…` (local). Default: `$TURSO_DATABASE_URL`. */
|
|
15
|
-
url?: string;
|
|
16
|
-
/** Auth token. Default: `$TURSO_AUTH_TOKEN`. */
|
|
17
|
-
authToken?: string;
|
|
18
|
-
/** Transport backend. Default `libsql`. */
|
|
19
|
-
backend?: Backend;
|
|
20
|
-
}
|
|
21
|
-
/** Embedded-replica config: a local file kept in sync with a remote primary. */
|
|
22
|
-
interface ReplicaConfig {
|
|
23
|
-
/** Local file path for the replica DB (e.g. `/data/buddy.db`). */
|
|
24
|
-
path: string;
|
|
25
|
-
/** Remote primary to sync from. Default: `$TURSO_DATABASE_URL`. */
|
|
26
|
-
syncUrl?: string;
|
|
27
|
-
/** Auth token for the remote. Default: `$TURSO_AUTH_TOKEN`. */
|
|
28
|
-
authToken?: string;
|
|
29
|
-
/** Auto-sync interval in seconds. Omit to sync manually via `client.sync()`. */
|
|
30
|
-
syncIntervalSeconds?: number;
|
|
31
|
-
/** Transport backend. Default `libsql` (embedded replicas are libSQL-specific). */
|
|
32
|
-
backend?: Backend;
|
|
33
|
-
}
|
|
34
21
|
|
|
35
22
|
/**
|
|
36
|
-
*
|
|
23
|
+
* Create a client against a REMOTE database.
|
|
37
24
|
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
* transports, limits and observability — the same play as `@broberg/ai-sdk`.
|
|
41
|
-
*
|
|
42
|
-
* Turso/libSQL is the only transport implemented today (Buddy Cloud, F067, is
|
|
43
|
-
* the pilot consumer); `postgres` / `supabase` are planned behind the same
|
|
44
|
-
* `createClient` / `createReplica` surface (see `Backend`). Intentionally THIN:
|
|
45
|
-
* a remote client, an embedded-replica client, and a health probe. ORM stays in
|
|
46
|
-
* the consumer (`drizzle(createClient(), { schema })`).
|
|
25
|
+
* - libSQL/Turso (default): reads `TURSO_DATABASE_URL` + `TURSO_AUTH_TOKEN`.
|
|
26
|
+
* - `{ backend: 'postgres' }`: reads `DATABASE_URL`.
|
|
47
27
|
*/
|
|
48
|
-
|
|
28
|
+
declare function createClient(cfg?: LibsqlConfig): DbClient<Client>;
|
|
29
|
+
declare function createClient(cfg: PostgresConfig): DbClient<Sql>;
|
|
30
|
+
declare function createClient(cfg: PgConfig): DbClient<Pool>;
|
|
49
31
|
/**
|
|
50
|
-
* Create
|
|
51
|
-
*
|
|
52
|
-
* `
|
|
32
|
+
* Create an EMBEDDED REPLICA: a local SQLite file kept in sync with a remote
|
|
33
|
+
* Turso primary. Reads hit the local file; writes forward to the primary;
|
|
34
|
+
* `sync()` (or `syncIntervalSeconds`) pulls the latest. libSQL only — there is
|
|
35
|
+
* no Postgres counterpart, and the config type says so.
|
|
53
36
|
*/
|
|
54
|
-
declare function
|
|
37
|
+
declare function createReplica(cfg: ReplicaConfig): ReplicaClient;
|
|
55
38
|
/**
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
* how F067 edge daemons read fleet state fast and tolerate a cloud blip.
|
|
39
|
+
* Liveness + version probe. Asks the transport itself and reports which one
|
|
40
|
+
* answered — read `transport` here rather than inferring it from your config.
|
|
41
|
+
* Throws if the database cannot be reached.
|
|
60
42
|
*/
|
|
61
|
-
declare function
|
|
62
|
-
/** Liveness + SQLite version probe — handy for health endpoints. */
|
|
63
|
-
declare function health(client: Client): Promise<{
|
|
64
|
-
ok: boolean;
|
|
65
|
-
version: string;
|
|
66
|
-
}>;
|
|
43
|
+
declare function health(client: DbClient): Promise<Health>;
|
|
67
44
|
|
|
68
|
-
export {
|
|
45
|
+
export { DbClient, Health, LibsqlConfig, PgConfig, PostgresConfig, ReplicaClient, ReplicaConfig, createClient, createReplica, health };
|
package/dist/index.js
CHANGED
|
@@ -1,49 +1,206 @@
|
|
|
1
|
+
// src/backends/pg.ts
|
|
2
|
+
import { createRequire } from "module";
|
|
3
|
+
function parts(stmt) {
|
|
4
|
+
if (typeof stmt === "string") return [stmt, []];
|
|
5
|
+
return [stmt.sql, [...stmt.args ?? []]];
|
|
6
|
+
}
|
|
7
|
+
function toResult(res) {
|
|
8
|
+
const r = Array.isArray(res) ? res[res.length - 1] : res;
|
|
9
|
+
const columns = (r.fields ?? []).map((f) => f.name);
|
|
10
|
+
const rows = (r.rows ?? []).map((x) => ({ ...x }));
|
|
11
|
+
const isRead = r.command === "SELECT";
|
|
12
|
+
return { rows, columns, rowsAffected: isRead ? 0 : r.rowCount ?? 0 };
|
|
13
|
+
}
|
|
14
|
+
function loadPool(url, max) {
|
|
15
|
+
let pg;
|
|
16
|
+
try {
|
|
17
|
+
pg = createRequire(import.meta.url)("pg");
|
|
18
|
+
} catch {
|
|
19
|
+
throw new Error("@broberg/db-sdk: backend 'pg' needs the 'pg' package \u2014 npm i pg (or pass your own `pool`)");
|
|
20
|
+
}
|
|
21
|
+
return new pg.Pool({ connectionString: url, max });
|
|
22
|
+
}
|
|
23
|
+
function pgClient(cfg) {
|
|
24
|
+
let pool;
|
|
25
|
+
if (cfg.pool) pool = cfg.pool;
|
|
26
|
+
else {
|
|
27
|
+
const url = cfg.url ?? process.env.DATABASE_URL;
|
|
28
|
+
if (!url) throw new Error("@broberg/db-sdk: missing database url \u2014 set DATABASE_URL, pass url, or pass your own pool");
|
|
29
|
+
pool = loadPool(url, cfg.max);
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
transport: "postgres",
|
|
33
|
+
raw: pool,
|
|
34
|
+
async execute(stmt) {
|
|
35
|
+
const [text, args] = parts(stmt);
|
|
36
|
+
return toResult(await pool.query(text, args));
|
|
37
|
+
},
|
|
38
|
+
async batch(stmts) {
|
|
39
|
+
const client = await pool.connect();
|
|
40
|
+
try {
|
|
41
|
+
await client.query("begin");
|
|
42
|
+
const out = [];
|
|
43
|
+
for (const s of stmts) {
|
|
44
|
+
const [text, args] = parts(s);
|
|
45
|
+
out.push(toResult(await client.query(text, args)));
|
|
46
|
+
}
|
|
47
|
+
await client.query("commit");
|
|
48
|
+
return out;
|
|
49
|
+
} catch (e) {
|
|
50
|
+
try {
|
|
51
|
+
await client.query("rollback");
|
|
52
|
+
} catch (rb) {
|
|
53
|
+
e.rollbackError = rb;
|
|
54
|
+
}
|
|
55
|
+
throw e;
|
|
56
|
+
} finally {
|
|
57
|
+
client.release();
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
async close() {
|
|
61
|
+
if (!pool.ended) await pool.end();
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
1
66
|
// src/backends/libsql.ts
|
|
2
67
|
import { createClient as createLibsqlClient } from "@libsql/client";
|
|
3
68
|
function requireUrl(url, what) {
|
|
4
69
|
if (!url) {
|
|
5
|
-
throw new Error(
|
|
6
|
-
`@broberg/db-sdk: missing ${what} \u2014 set TURSO_DATABASE_URL or pass it explicitly`
|
|
7
|
-
);
|
|
70
|
+
throw new Error(`@broberg/db-sdk: missing ${what} \u2014 set TURSO_DATABASE_URL or pass it explicitly`);
|
|
8
71
|
}
|
|
9
72
|
return url;
|
|
10
73
|
}
|
|
74
|
+
function toLibsql(stmt) {
|
|
75
|
+
if (typeof stmt === "string") return stmt;
|
|
76
|
+
return { sql: stmt.sql, args: stmt.args ?? [] };
|
|
77
|
+
}
|
|
78
|
+
function toResult2(rs) {
|
|
79
|
+
const rows = rs.rows.map((r) => {
|
|
80
|
+
const row = {};
|
|
81
|
+
rs.columns.forEach((c, i) => {
|
|
82
|
+
row[c] = r[i];
|
|
83
|
+
});
|
|
84
|
+
return row;
|
|
85
|
+
});
|
|
86
|
+
return { rows, columns: [...rs.columns], rowsAffected: rs.rowsAffected };
|
|
87
|
+
}
|
|
88
|
+
function wrap(raw) {
|
|
89
|
+
return {
|
|
90
|
+
transport: "libsql",
|
|
91
|
+
raw,
|
|
92
|
+
async execute(stmt) {
|
|
93
|
+
return toResult2(await raw.execute(toLibsql(stmt)));
|
|
94
|
+
},
|
|
95
|
+
async batch(stmts, mode = "deferred") {
|
|
96
|
+
const results = await raw.batch(stmts.map(toLibsql), mode);
|
|
97
|
+
return results.map(toResult2);
|
|
98
|
+
},
|
|
99
|
+
async close() {
|
|
100
|
+
raw.close();
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
}
|
|
11
104
|
function libsqlClient(cfg) {
|
|
12
105
|
const url = requireUrl(cfg.url ?? process.env.TURSO_DATABASE_URL, "database url");
|
|
13
106
|
const authToken = cfg.authToken ?? process.env.TURSO_AUTH_TOKEN;
|
|
14
|
-
return createLibsqlClient({ url, authToken });
|
|
107
|
+
return wrap(createLibsqlClient({ url, authToken }));
|
|
15
108
|
}
|
|
16
109
|
function libsqlReplica(cfg) {
|
|
17
110
|
const syncUrl = requireUrl(cfg.syncUrl ?? process.env.TURSO_DATABASE_URL, "sync url");
|
|
18
111
|
const authToken = cfg.authToken ?? process.env.TURSO_AUTH_TOKEN;
|
|
19
|
-
|
|
112
|
+
const raw = createLibsqlClient({
|
|
20
113
|
url: `file:${cfg.path}`,
|
|
21
114
|
syncUrl,
|
|
22
115
|
authToken,
|
|
23
116
|
syncInterval: cfg.syncIntervalSeconds
|
|
24
117
|
});
|
|
118
|
+
return {
|
|
119
|
+
...wrap(raw),
|
|
120
|
+
async sync() {
|
|
121
|
+
await raw.sync();
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
async function libsqlVersion(raw) {
|
|
126
|
+
const res = await raw.execute("select sqlite_version() as v");
|
|
127
|
+
return String(res.rows[0]?.v ?? "unknown");
|
|
25
128
|
}
|
|
26
129
|
|
|
27
|
-
// src/
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
);
|
|
130
|
+
// src/backends/postgres.ts
|
|
131
|
+
import postgres from "postgres";
|
|
132
|
+
var PG_OPTIONS = { prepare: false };
|
|
133
|
+
function toResult3(res) {
|
|
134
|
+
const columns = (res.columns ?? []).map((c) => c.name);
|
|
135
|
+
const rows = Array.from(res, (r) => ({ ...r }));
|
|
136
|
+
const isRead = res.command === "SELECT";
|
|
137
|
+
return { rows, columns, rowsAffected: isRead ? 0 : res.count ?? 0 };
|
|
138
|
+
}
|
|
139
|
+
function parts2(stmt) {
|
|
140
|
+
if (typeof stmt === "string") return [stmt, []];
|
|
141
|
+
return [stmt.sql, [...stmt.args ?? []]];
|
|
142
|
+
}
|
|
143
|
+
function run(sql, stmt) {
|
|
144
|
+
const [text, args] = parts2(stmt);
|
|
145
|
+
return sql.unsafe(text, args, PG_OPTIONS);
|
|
146
|
+
}
|
|
147
|
+
function postgresClient(cfg) {
|
|
148
|
+
const url = cfg.url ?? process.env.DATABASE_URL;
|
|
149
|
+
if (!url) {
|
|
150
|
+
throw new Error("@broberg/db-sdk: missing database url \u2014 set DATABASE_URL or pass it explicitly");
|
|
151
|
+
}
|
|
152
|
+
const raw = postgres(url, { ...PG_OPTIONS, max: cfg.max, onnotice: () => {
|
|
153
|
+
} });
|
|
154
|
+
return {
|
|
155
|
+
transport: "postgres",
|
|
156
|
+
raw,
|
|
157
|
+
async execute(stmt) {
|
|
158
|
+
return toResult3(await run(raw, stmt));
|
|
159
|
+
},
|
|
160
|
+
// Postgres has no write-lock-up-front mode, so both BatchModes begin a
|
|
161
|
+
// plain transaction and the mode argument is not read.
|
|
162
|
+
async batch(stmts) {
|
|
163
|
+
const results = await raw.begin(async (tx) => {
|
|
164
|
+
const out = [];
|
|
165
|
+
for (const s of stmts) out.push(toResult3(await run(tx, s)));
|
|
166
|
+
return out;
|
|
167
|
+
});
|
|
168
|
+
return results;
|
|
169
|
+
},
|
|
170
|
+
async close() {
|
|
171
|
+
await raw.end();
|
|
172
|
+
}
|
|
173
|
+
};
|
|
32
174
|
}
|
|
175
|
+
async function postgresVersion(raw) {
|
|
176
|
+
const [row] = await raw.unsafe("show server_version", [], PG_OPTIONS);
|
|
177
|
+
return String(row?.server_version ?? "unknown");
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// src/index.ts
|
|
33
181
|
function createClient(cfg = {}) {
|
|
34
182
|
const backend = cfg.backend ?? "libsql";
|
|
35
|
-
if (backend === "
|
|
36
|
-
|
|
183
|
+
if (cfg.backend === "postgres") return postgresClient(cfg);
|
|
184
|
+
if (cfg.backend === "pg") return pgClient(cfg);
|
|
185
|
+
if (cfg.backend === void 0 || cfg.backend === "libsql") return libsqlClient(cfg);
|
|
186
|
+
throw new Error(`@broberg/db-sdk: unknown backend '${backend}' \u2014 expected 'libsql', 'postgres' or 'pg'`);
|
|
37
187
|
}
|
|
38
188
|
function createReplica(cfg) {
|
|
39
189
|
const backend = cfg.backend ?? "libsql";
|
|
40
|
-
if (backend
|
|
41
|
-
|
|
190
|
+
if (backend !== "libsql") {
|
|
191
|
+
throw new Error(`@broberg/db-sdk: embedded replicas are libSQL-only, got backend '${backend}'`);
|
|
192
|
+
}
|
|
193
|
+
return libsqlReplica(cfg);
|
|
42
194
|
}
|
|
43
195
|
async function health(client) {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
196
|
+
if (client.transport === "postgres") {
|
|
197
|
+
if (typeof client.raw !== "function") {
|
|
198
|
+
const r = await client.execute("show server_version");
|
|
199
|
+
return { ok: true, transport: "postgres", version: String(r.rows[0]?.server_version ?? "unknown") };
|
|
200
|
+
}
|
|
201
|
+
return { ok: true, transport: "postgres", version: await postgresVersion(client.raw) };
|
|
202
|
+
}
|
|
203
|
+
return { ok: true, transport: "libsql", version: await libsqlVersion(client.raw) };
|
|
47
204
|
}
|
|
48
205
|
export {
|
|
49
206
|
createClient,
|