@persql/sdk 0.1.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/dist/cli.cjs ADDED
@@ -0,0 +1,1827 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ // src/cli.ts
5
+ var import_promises = require("fs/promises");
6
+
7
+ // src/local.ts
8
+ var PROPOSAL_TTL_DEFAULT_SEC = 600;
9
+ var PROPOSAL_TTL_MAX_SEC = 3600;
10
+ function newLocalProposalId() {
11
+ const buf = new Uint8Array(8);
12
+ crypto.getRandomValues(buf);
13
+ let hex = "";
14
+ for (const b of buf) hex += b.toString(16).padStart(2, "0");
15
+ return `pmut_local_${hex}`;
16
+ }
17
+ var LocalDriver = class {
18
+ constructor(path) {
19
+ this.path = path;
20
+ }
21
+ db = null;
22
+ proposals = /* @__PURE__ */ new Map();
23
+ async open() {
24
+ if (this.db) return this.db;
25
+ const moduleName = "better-sqlite3";
26
+ let mod;
27
+ try {
28
+ mod = await import(moduleName);
29
+ } catch {
30
+ throw new Error(
31
+ "PerSQL local mode requires the `better-sqlite3` peer dep. Install with `npm i -D better-sqlite3` (or pnpm/yarn equivalent)."
32
+ );
33
+ }
34
+ const m = mod;
35
+ const Ctor = m.default ?? mod;
36
+ this.db = new Ctor(this.path);
37
+ this.db.pragma("foreign_keys = ON");
38
+ return this.db;
39
+ }
40
+ async query(sql, params) {
41
+ const db = await this.open();
42
+ return runOne(db, sql, params);
43
+ }
44
+ async batch(statements, transaction) {
45
+ const db = await this.open();
46
+ const exec = () => statements.map((s) => runOne(db, s.sql, s.params ?? []));
47
+ if (transaction) return db.transaction(exec)();
48
+ return exec();
49
+ }
50
+ async tables() {
51
+ const db = await this.open();
52
+ const rows = runOne(
53
+ db,
54
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name",
55
+ []
56
+ ).rows;
57
+ return rows.map(([name]) => {
58
+ const c = runOne(db, `SELECT COUNT(*) FROM "${name.replace(/"/g, '""')}"`, []).rows[0];
59
+ return { name, rowCount: Number(c?.[0] ?? 0) };
60
+ });
61
+ }
62
+ async explain(sql, params) {
63
+ const db = await this.open();
64
+ const r = runOne(db, `EXPLAIN QUERY PLAN ${sql}`, params);
65
+ return r.rows.map((row) => ({
66
+ id: Number(row[0]),
67
+ parent: Number(row[1]),
68
+ detail: String(row[3])
69
+ }));
70
+ }
71
+ async propose(sql, params, ttlSec) {
72
+ const db = await this.open();
73
+ const planRaw = runOne(db, `EXPLAIN QUERY PLAN ${sql}`, params).rows;
74
+ const plan = planRaw;
75
+ const ttl = Math.min(
76
+ Math.max(1, Math.floor(ttlSec ?? PROPOSAL_TTL_DEFAULT_SEC)),
77
+ PROPOSAL_TTL_MAX_SEC
78
+ );
79
+ const expiresAt = Date.now() + ttl * 1e3;
80
+ const executionToken = newLocalProposalId();
81
+ this.proposals.set(executionToken, { sql, params, expiresAt });
82
+ this.gcProposals();
83
+ return {
84
+ sql,
85
+ plan,
86
+ estimatedAffectedRows: null,
87
+ executionToken,
88
+ expiresAt: new Date(expiresAt).toISOString(),
89
+ action: actionForSql(sql)
90
+ };
91
+ }
92
+ async apply(executionToken) {
93
+ const rec = this.proposals.get(executionToken);
94
+ if (!rec) {
95
+ throw new Error(
96
+ "PerSQL: executionToken is unknown, expired, or already redeemed"
97
+ );
98
+ }
99
+ this.proposals.delete(executionToken);
100
+ if (rec.expiresAt < Date.now()) {
101
+ throw new Error("PerSQL: executionToken has expired");
102
+ }
103
+ return this.query(rec.sql, rec.params);
104
+ }
105
+ gcProposals() {
106
+ const now = Date.now();
107
+ for (const [k, v] of this.proposals) {
108
+ if (v.expiresAt < now) this.proposals.delete(k);
109
+ }
110
+ }
111
+ close() {
112
+ if (this.db) {
113
+ try {
114
+ this.db.close();
115
+ } catch {
116
+ }
117
+ this.db = null;
118
+ }
119
+ }
120
+ };
121
+ function actionForSql(sql) {
122
+ const head = sql.trim().slice(0, 24).toLowerCase();
123
+ if (head.startsWith("create") || head.startsWith("drop") || head.startsWith("alter")) {
124
+ return "admin";
125
+ }
126
+ if (head.startsWith("insert") || head.startsWith("update") || head.startsWith("delete") || head.startsWith("replace")) {
127
+ return "write";
128
+ }
129
+ return "read";
130
+ }
131
+ function runOne(db, sql, params) {
132
+ const stmt = db.prepare(sql);
133
+ if (stmt.reader) {
134
+ const cols = stmt.columns().map((c) => c.name);
135
+ const rows = stmt.raw(true).all(...params);
136
+ return { columns: cols, rows, rowsRead: rows.length, rowsWritten: 0 };
137
+ }
138
+ const info = stmt.run(...params);
139
+ return { columns: [], rows: [], rowsRead: 0, rowsWritten: info.changes ?? 0 };
140
+ }
141
+
142
+ // src/index.ts
143
+ var PerSQLError = class extends Error {
144
+ status;
145
+ // Set on /v1/query and /v1/batch failures with a parsed envelope
146
+ // (kind, table, column, hint, etc.) so callers can branch on
147
+ // `error.detail.kind` instead of string-matching the message.
148
+ detail;
149
+ constructor(status, message, detail) {
150
+ super(message);
151
+ this.name = "PerSQLError";
152
+ this.status = status;
153
+ this.detail = detail;
154
+ }
155
+ };
156
+ var RateLimitError = class extends PerSQLError {
157
+ retryAfterSeconds;
158
+ constructor(retryAfterSeconds, message = "Rate limit exceeded") {
159
+ super(429, message);
160
+ this.name = "RateLimitError";
161
+ this.retryAfterSeconds = retryAfterSeconds;
162
+ }
163
+ };
164
+ var ApprovalRequiredError = class extends PerSQLError {
165
+ approvalToken;
166
+ approvalUrl;
167
+ hits;
168
+ expiresAt;
169
+ constructor(opts) {
170
+ super(403, opts.message);
171
+ this.name = "ApprovalRequiredError";
172
+ this.approvalToken = opts.approvalToken;
173
+ this.approvalUrl = opts.approvalUrl;
174
+ this.hits = opts.hits;
175
+ this.expiresAt = opts.expiresAt;
176
+ }
177
+ };
178
+ var PerSQL = class _PerSQL {
179
+ /** @internal — exposed read-only so PerSQLDatabase can build URLs. */
180
+ token;
181
+ /** @internal — same. */
182
+ baseURL;
183
+ /** @internal — set when running in local mode. */
184
+ local;
185
+ _fetch;
186
+ constructor(opts) {
187
+ if (opts.local) {
188
+ this.local = new LocalDriver(opts.local);
189
+ this.token = "";
190
+ this.baseURL = "";
191
+ this._fetch = opts.fetch ?? globalThis.fetch?.bind(globalThis);
192
+ return;
193
+ }
194
+ if (!opts.token) {
195
+ throw new Error(
196
+ 'PerSQL: token is required (or pass { local: ":memory:" } for tests)'
197
+ );
198
+ }
199
+ this.local = null;
200
+ this.token = opts.token;
201
+ this.baseURL = (opts.baseURL ?? "https://api.persql.com").replace(/\/$/, "");
202
+ this._fetch = opts.fetch ?? globalThis.fetch.bind(globalThis);
203
+ }
204
+ /** Close the local SQLite connection (no-op in HTTP mode). */
205
+ close() {
206
+ this.local?.close();
207
+ }
208
+ /**
209
+ * Redeem a handoff token (`phand_…`) for a regular PerSQL client
210
+ * scoped to the handed-off (database, branch, role). Single use:
211
+ * the handoff token is consumed by the call.
212
+ *
213
+ * Common pattern — agent A pins a branch and hands the token to
214
+ * agent B; agent B does:
215
+ *
216
+ * const persql = await PerSQL.fromHandoff(handoffToken);
217
+ * const db = persql.database(persql.handedOff!.namespaceSlug, persql.handedOff!.databaseSlug);
218
+ */
219
+ static async fromHandoff(handoffToken, opts = {}) {
220
+ const baseURL = (opts.baseURL ?? "https://api.persql.com").replace(/\/$/, "");
221
+ const fetcher = opts.fetch ?? globalThis.fetch.bind(globalThis);
222
+ const res = await fetcher(`${baseURL}/v1/handoff/claim`, {
223
+ method: "POST",
224
+ headers: { "Content-Type": "application/json" },
225
+ body: JSON.stringify({ token: handoffToken, name: opts.name })
226
+ });
227
+ const envelope = await res.json().catch(() => null);
228
+ if (!res.ok || !envelope?.success || !envelope.data) {
229
+ throw new PerSQLError(
230
+ res.status,
231
+ envelope?.error ?? `Handoff claim failed (${res.status})`
232
+ );
233
+ }
234
+ const { plaintext, ...handedOff } = envelope.data;
235
+ const client = new _PerSQL({ token: plaintext, baseURL, fetch: opts.fetch });
236
+ return Object.assign(client, { handedOff });
237
+ }
238
+ database(a, b) {
239
+ if (b !== void 0) return new PerSQLDatabase(this, a, b);
240
+ const [ns, slug] = a.split("/");
241
+ if (!ns || !slug) {
242
+ throw new Error('PerSQL: database path must be "<namespace>/<slug>"');
243
+ }
244
+ return new PerSQLDatabase(this, ns, slug);
245
+ }
246
+ /** @internal */
247
+ async request(method, path, body, headers) {
248
+ const res = await this._fetch(`${this.baseURL}${path}`, {
249
+ method,
250
+ headers: {
251
+ Authorization: `Bearer ${this.token}`,
252
+ "Content-Type": "application/json",
253
+ ...headers ?? {}
254
+ },
255
+ body: body !== void 0 ? JSON.stringify(body) : void 0
256
+ });
257
+ if (res.status === 429) {
258
+ const retryAfter = Number(res.headers.get("retry-after") ?? "60");
259
+ throw new RateLimitError(retryAfter);
260
+ }
261
+ let envelope = null;
262
+ try {
263
+ envelope = await res.json();
264
+ } catch {
265
+ }
266
+ if (!res.ok || !envelope?.success) {
267
+ const message = envelope?.error ?? `Request failed (${res.status})`;
268
+ if (res.status === 403 && envelope?.approvalToken && envelope?.approvalUrl && envelope?.expiresAt) {
269
+ throw new ApprovalRequiredError({
270
+ message,
271
+ approvalToken: envelope.approvalToken,
272
+ approvalUrl: envelope.approvalUrl,
273
+ hits: envelope.hits ?? [],
274
+ expiresAt: envelope.expiresAt
275
+ });
276
+ }
277
+ throw new PerSQLError(res.status, message, envelope?.errorDetail);
278
+ }
279
+ return envelope.data;
280
+ }
281
+ /** @internal — raw upload (e.g. blob PUT) returning the ApiResponse data. */
282
+ async requestRaw(method, path, body, contentType) {
283
+ const res = await this._fetch(`${this.baseURL}${path}`, {
284
+ method,
285
+ headers: {
286
+ Authorization: `Bearer ${this.token}`,
287
+ "Content-Type": contentType ?? "application/octet-stream"
288
+ },
289
+ body,
290
+ // @ts-expect-error — duplex is required by Node fetch for streaming bodies
291
+ duplex: "half"
292
+ });
293
+ if (res.status === 429) {
294
+ const retryAfter = Number(res.headers.get("retry-after") ?? "60");
295
+ throw new RateLimitError(retryAfter);
296
+ }
297
+ let envelope = null;
298
+ try {
299
+ envelope = await res.json();
300
+ } catch {
301
+ }
302
+ if (!res.ok || !envelope?.success) {
303
+ const message = envelope?.error ?? `Request failed (${res.status})`;
304
+ throw new PerSQLError(res.status, message, envelope?.errorDetail);
305
+ }
306
+ return envelope.data;
307
+ }
308
+ /** @internal — raw fetch returning the underlying Response (used by blob GET). */
309
+ fetchRaw(method, path) {
310
+ return this._fetch(`${this.baseURL}${path}`, {
311
+ method,
312
+ headers: { Authorization: `Bearer ${this.token}` }
313
+ });
314
+ }
315
+ };
316
+ var PerSQLDatabase = class {
317
+ constructor(client, namespace, slug) {
318
+ this.client = client;
319
+ this.namespace = namespace;
320
+ this.slug = slug;
321
+ }
322
+ /** Run a single SQL statement. */
323
+ async query(sql, params = [], options = {}) {
324
+ if (this.client.local) {
325
+ const raw2 = await this.client.local.query(sql, params);
326
+ return { ...raw2, data: rowsToObjects(raw2.columns, raw2.rows) };
327
+ }
328
+ const headers = {};
329
+ if (options.idempotencyKey) headers["Idempotency-Key"] = options.idempotencyKey;
330
+ if (options.planKey) headers["Plan-Key"] = options.planKey;
331
+ if (options.planStep) headers["Plan-Step"] = options.planStep;
332
+ const raw = await this.client.request(
333
+ "POST",
334
+ `/v1/db/${this.namespace}/${this.slug}/query`,
335
+ { sql, params },
336
+ headers
337
+ );
338
+ return {
339
+ ...raw,
340
+ data: rowsToObjects(raw.columns, raw.rows)
341
+ };
342
+ }
343
+ /** Run multiple statements in one round-trip, optionally in a transaction. */
344
+ async batch(statements, options = {}) {
345
+ if (this.client.local) {
346
+ const raw2 = await this.client.local.batch(
347
+ statements,
348
+ options.transaction ?? false
349
+ );
350
+ return raw2.map((r) => ({ ...r, data: rowsToObjects(r.columns, r.rows) }));
351
+ }
352
+ const headers = {};
353
+ if (options.idempotencyKey) headers["Idempotency-Key"] = options.idempotencyKey;
354
+ if (options.planKey) headers["Plan-Key"] = options.planKey;
355
+ if (options.planStep) headers["Plan-Step"] = options.planStep;
356
+ const raw = await this.client.request(
357
+ "POST",
358
+ `/v1/db/${this.namespace}/${this.slug}/batch`,
359
+ { statements, transaction: options.transaction ?? false },
360
+ headers
361
+ );
362
+ return raw.map((r) => ({ ...r, data: rowsToObjects(r.columns, r.rows) }));
363
+ }
364
+ /** Convenience for a transactional batch. */
365
+ transaction(statements, options = {}) {
366
+ return this.batch(statements, { ...options, transaction: true });
367
+ }
368
+ /**
369
+ * Engine telemetry — recent /v1/query and /v1/batch calls issued
370
+ * against this database. Backed by the in-DO `_persql_meta_query_log`
371
+ * table; 7-day retention. Useful for agents that need to replay
372
+ * what they (or another agent) did, audit cost, or stream a live
373
+ * tail via `db.subscribe`.
374
+ */
375
+ async queryLog(opts = {}) {
376
+ if (this.client.local) {
377
+ throw new Error("PerSQL: queryLog is not available in local mode.");
378
+ }
379
+ const qs = new URLSearchParams();
380
+ if (opts.since) {
381
+ qs.set(
382
+ "since",
383
+ typeof opts.since === "string" ? opts.since : opts.since.toISOString()
384
+ );
385
+ }
386
+ if (opts.until) {
387
+ qs.set(
388
+ "until",
389
+ typeof opts.until === "string" ? opts.until : opts.until.toISOString()
390
+ );
391
+ }
392
+ if (opts.tokenId) qs.set("tokenId", opts.tokenId);
393
+ if (opts.status) qs.set("status", opts.status);
394
+ if (opts.cursor) qs.set("cursor", opts.cursor);
395
+ if (opts.pageSize) qs.set("pageSize", String(opts.pageSize));
396
+ const tail = qs.toString() ? `?${qs.toString()}` : "";
397
+ const res = await this.client.fetchRaw(
398
+ "GET",
399
+ `/v1/db/${this.namespace}/${this.slug}/queries${tail}`
400
+ );
401
+ const body = await res.json();
402
+ if (!res.ok || !body.success) {
403
+ throw new PerSQLError(res.status, body.error ?? `Request failed (${res.status})`);
404
+ }
405
+ return { data: body.data ?? [], nextCursor: body.nextCursor ?? null };
406
+ }
407
+ /**
408
+ * Returns a structured description of the database — columns, FK
409
+ * graph, and any human-/AI-authored docs persisted via
410
+ * `db.describe(...)`. The shape is designed for direct injection
411
+ * into an LLM prompt: one round-trip and the agent has everything
412
+ * it needs to write correct SQL.
413
+ */
414
+ async describe() {
415
+ if (this.client.local) {
416
+ throw new Error(
417
+ "PerSQL: describe is not available in local mode (yet)."
418
+ );
419
+ }
420
+ return this.client.request(
421
+ "GET",
422
+ `/v1/db/${this.namespace}/${this.slug}/describe`
423
+ );
424
+ }
425
+ /**
426
+ * Persist semantic descriptions for the database / tables / columns.
427
+ * Pass any subset — only the fields you set are updated. Requires
428
+ * an admin-role token because docs change how every other client
429
+ * (and every agent) interprets the schema.
430
+ */
431
+ async setDescription(input) {
432
+ if (this.client.local) {
433
+ throw new Error("PerSQL: setDescription is not available in local mode.");
434
+ }
435
+ return this.client.request(
436
+ "PUT",
437
+ `/v1/db/${this.namespace}/${this.slug}/describe`,
438
+ input
439
+ );
440
+ }
441
+ /**
442
+ * Natural-language ranked search across table names, column names,
443
+ * and any descriptions you've stored via `setDescription`. Use this
444
+ * before writing SQL when you don't know the schema cold — one call
445
+ * narrows a 200-table DB down to the handful that match the intent.
446
+ */
447
+ async search(query, opts = {}) {
448
+ if (this.client.local) {
449
+ throw new Error("PerSQL: search is not available in local mode.");
450
+ }
451
+ const qs = new URLSearchParams({ q: query });
452
+ if (opts.limit) qs.set("limit", String(opts.limit));
453
+ return this.client.request(
454
+ "GET",
455
+ `/v1/db/${this.namespace}/${this.slug}/search?${qs.toString()}`
456
+ );
457
+ }
458
+ /**
459
+ * Lints the schema for issues that hurt LLM consumption: missing
460
+ * primary keys, ambiguous column names ("data", "value"), unindexed
461
+ * foreign keys, etc. Pure read-only analysis — emits suggestions
462
+ * for the agent to act on, never modifies the schema itself.
463
+ */
464
+ async doctor() {
465
+ if (this.client.local) {
466
+ throw new Error("PerSQL: doctor is not available in local mode.");
467
+ }
468
+ return this.client.request(
469
+ "GET",
470
+ `/v1/db/${this.namespace}/${this.slug}/doctor`
471
+ );
472
+ }
473
+ /** List user-defined tables in this database. */
474
+ async tables() {
475
+ if (this.client.local) return this.client.local.tables();
476
+ return this.client.request(
477
+ "GET",
478
+ `/v1/db/${this.namespace}/${this.slug}/tables`
479
+ );
480
+ }
481
+ /**
482
+ * Returns SQLite's `EXPLAIN QUERY PLAN` output for the given SQL.
483
+ * Read-only — does not execute the statement.
484
+ */
485
+ async explain(sql, params = []) {
486
+ if (this.client.local) return this.client.local.explain(sql, params);
487
+ return this.client.request("POST", `/v1/db/${this.namespace}/${this.slug}/explain`, { sql, params });
488
+ }
489
+ /**
490
+ * Introspect the database schema. Returns one entry per user table
491
+ * with column definitions, suitable for codegen tools (the
492
+ * `persql-codegen` CLI uses this to emit Drizzle schema files).
493
+ */
494
+ async schema() {
495
+ const tables = await this.tables();
496
+ const out = { tables: [] };
497
+ for (const t of tables) {
498
+ const r = await this.query(`PRAGMA table_info("${t.name.replace(/"/g, '""')}")`);
499
+ out.tables.push({
500
+ name: t.name,
501
+ columns: r.data.map((c) => ({
502
+ name: c.name,
503
+ type: c.type,
504
+ notNull: !!c.notnull,
505
+ primaryKey: !!c.pk,
506
+ default: c.dflt_value === null ? null : String(c.dflt_value)
507
+ }))
508
+ });
509
+ }
510
+ return out;
511
+ }
512
+ /**
513
+ * Per-database semantic search via Cloudflare Vectorize. Use
514
+ * `vectors.upsert` to embed and store rows; `vectors.query` to
515
+ * retrieve the most similar by free text. Embeddings are computed
516
+ * server-side using bge-base-en-v1.5 (768 dim, cosine distance).
517
+ */
518
+ get vectors() {
519
+ if (this.client.local) {
520
+ throw new Error(
521
+ "PerSQL: vectors require Cloudflare Vectorize and Workers AI \u2014 not available in local mode. Use a server-mode token (psql_live_/psql_test_) to call vectors.upsert/query/delete."
522
+ );
523
+ }
524
+ return new PerSQLVectors(this.client, this.namespace, this.slug);
525
+ }
526
+ /**
527
+ * Manage preview/PR-style branches of this database. Each branch is
528
+ * its own DO with its own SQLite file; create-or-reset by ref is
529
+ * idempotent (PUT semantics) so CI pipelines can call it on every
530
+ * build. Requires an admin-role bearer token for create / delete /
531
+ * merge; list is open to any role.
532
+ */
533
+ get branches() {
534
+ if (this.client.local) {
535
+ throw new Error(
536
+ "PerSQL: branches model fork-by-Durable-Object \u2014 not available in local mode. Use a server-mode token to call branches.upsert/claim/merge, or stub branch isolation in tests by spinning up multiple `new PerSQL({ local: ':memory:' })` instances."
537
+ );
538
+ }
539
+ return new PerSQLBranches(this.client, this.namespace, this.slug);
540
+ }
541
+ /**
542
+ * Redeem an approval that was minted when a write hit a
543
+ * `require_approval` rule. Throws `ApprovalRequiredError` until a
544
+ * namespace member decides; on approve, runs the original SQL.
545
+ */
546
+ get approvals() {
547
+ if (this.client.local) {
548
+ throw new Error(
549
+ "PerSQL: approvals require a server-side approval gate \u2014 not available in local mode. Local mode runs every statement immediately; use a server-mode token if you need the require_approval rule."
550
+ );
551
+ }
552
+ return new PerSQLApprovals(this.client, this.namespace, this.slug);
553
+ }
554
+ /**
555
+ * Pre-flight a write before running it. `propose()` validates the
556
+ * SQL via EXPLAIN, estimates affected rows, and returns a single-use
557
+ * `executionToken` to redeem with `apply()`. Use this when an agent
558
+ * (or its parent / a human) should review a mutation before it runs.
559
+ * Works in both HTTP and local modes — local mode keeps the
560
+ * executionToken in-process.
561
+ */
562
+ get proposals() {
563
+ return new PerSQLProposals(this.client, this.namespace, this.slug);
564
+ }
565
+ /**
566
+ * Per-database BLOB storage backed by R2. Use this for anything
567
+ * larger than a SQLite cell (images, PDFs, model weights). Each
568
+ * database has its own private namespace; keys may be hierarchical
569
+ * (`avatars/2025/foo.jpg`) but never start with `/`.
570
+ */
571
+ get blob() {
572
+ if (this.client.local) {
573
+ throw new Error(
574
+ "PerSQL: blob storage is backed by R2 \u2014 not available in local mode. Use a server-mode token, or store blobs in your test fixtures directly."
575
+ );
576
+ }
577
+ return new PerSQLBlob(this.client, this.namespace, this.slug);
578
+ }
579
+ /**
580
+ * Subscribe to row-changes via WebSocket — the SQL equivalent of
581
+ * Postgres `LISTEN`. The callback fires once per write that
582
+ * matches the table filter. Returns an `unsubscribe` function;
583
+ * call it to close the socket.
584
+ *
585
+ * ```ts
586
+ * const off = db.subscribe({
587
+ * tables: ["orders"],
588
+ * onChange: (e) => console.log(e.kind, e.table),
589
+ * });
590
+ * // …later
591
+ * off();
592
+ * ```
593
+ *
594
+ * Authentication uses the `persql.bearer.<token>` sub-protocol so
595
+ * the token doesn't leak via URL logs. In environments without
596
+ * sub-protocol support (some serverless WebSocket clients), the
597
+ * fallback `?token=` query string is also accepted by the
598
+ * server.
599
+ */
600
+ subscribe(options) {
601
+ if (this.client.local) {
602
+ throw new Error(
603
+ "PerSQL: subscribe requires the DO's WebSocket fan-out \u2014 not available in local mode. Use a server-mode token to call subscribe()."
604
+ );
605
+ }
606
+ const baseHttp = this.client.baseURL;
607
+ const wsBase = baseHttp.replace(/^http/, "ws");
608
+ const tablesParam = options.tables && options.tables.length > 0 ? `?tables=${encodeURIComponent(options.tables.join(","))}` : "";
609
+ const url = `${wsBase}/v1/db/${this.namespace}/${this.slug}/subscribe${tablesParam}`;
610
+ const ws = new WebSocket(url, [`persql.bearer.${this.client.token}`]);
611
+ let closed = false;
612
+ ws.addEventListener("message", (ev) => {
613
+ try {
614
+ const msg = JSON.parse(String(ev.data));
615
+ if (msg.type === "change" && msg.table && msg.kind) {
616
+ options.onChange({ table: msg.table, kind: msg.kind });
617
+ } else if (msg.type === "error") {
618
+ options.onError?.(new Error(msg.message ?? "Subscription error"));
619
+ } else if (msg.type === "subscribed") {
620
+ options.onReady?.(msg.tables ?? "*");
621
+ }
622
+ } catch {
623
+ }
624
+ });
625
+ ws.addEventListener("error", () => {
626
+ options.onError?.(new Error("WebSocket error"));
627
+ });
628
+ ws.addEventListener("close", () => {
629
+ if (!closed) options.onClose?.();
630
+ });
631
+ return () => {
632
+ closed = true;
633
+ try {
634
+ ws.close();
635
+ } catch {
636
+ }
637
+ };
638
+ }
639
+ /**
640
+ * Returns the callback shape `drizzle-orm/sqlite-proxy` expects.
641
+ * Pair with `drizzle()` from that module to get a typed,
642
+ * fluent ORM client over the PerSQL HTTP API:
643
+ *
644
+ * ```ts
645
+ * import { drizzle } from "drizzle-orm/sqlite-proxy";
646
+ * import { PerSQL } from "@persql/sdk";
647
+ *
648
+ * const persql = new PerSQL({ token });
649
+ * const db = drizzle(persql.database("acme/orders").driver());
650
+ * ```
651
+ *
652
+ * Drizzle's `prepare` interface maps onto our `query` /
653
+ * `batch`; `method` tells us how to shape the rows.
654
+ */
655
+ driver() {
656
+ const callback = async (sql, params, method) => {
657
+ const result = await this.query(sql, params ?? []);
658
+ if (method === "values" || method === "get") {
659
+ return { rows: result.rows[0] ?? [] };
660
+ }
661
+ return { rows: result.rows };
662
+ };
663
+ return callback;
664
+ }
665
+ /**
666
+ * Returns a tool definition for use with Anthropic / OpenAI / function-calling
667
+ * agents. Pair it with `runTool` to execute the call.
668
+ */
669
+ asTool(name = "persql_query") {
670
+ return {
671
+ anthropic: {
672
+ name,
673
+ description: `Run a SQL query against the PerSQL database "${this.namespace}/${this.slug}". Returns up to 1000 rows. Use parameter binding (?) to avoid injection.`,
674
+ input_schema: {
675
+ type: "object",
676
+ properties: {
677
+ sql: { type: "string", description: "SQLite SQL statement" },
678
+ params: {
679
+ type: "array",
680
+ items: {},
681
+ description: "Positional parameters for the SQL statement"
682
+ }
683
+ },
684
+ required: ["sql"]
685
+ }
686
+ },
687
+ openai: {
688
+ type: "function",
689
+ function: {
690
+ name,
691
+ description: `Run a SQL query against the PerSQL database "${this.namespace}/${this.slug}".`,
692
+ parameters: {
693
+ type: "object",
694
+ properties: {
695
+ sql: { type: "string" },
696
+ params: { type: "array", items: {} }
697
+ },
698
+ required: ["sql"]
699
+ }
700
+ }
701
+ }
702
+ };
703
+ }
704
+ /**
705
+ * Executes a tool-call payload returned from the model. Pair with `asTool`.
706
+ */
707
+ runTool(input) {
708
+ return this.query(input.sql, input.params ?? []);
709
+ }
710
+ /**
711
+ * Generate a *bundle* of typed tools — one per table — instead of one
712
+ * generic `query` tool. Agents perform dramatically better with narrow
713
+ * typed surfaces than they do with one fat SQL function. Each table
714
+ * gets:
715
+ * - `select_<table>(where?, limit?, orderBy?)` — typed column filter
716
+ * - `count_<table>(where?)` — quick row count
717
+ * - `describe_<table>()` — columns, row count, foreign keys
718
+ * Plus a fallback `sql_query(sql, params)` for anything the typed
719
+ * tools can't express.
720
+ *
721
+ * The returned `run(name, input)` dispatcher executes whichever tool
722
+ * the model invoked. Format the tools for the LLM via the
723
+ * `anthropic` or `openai` arrays (matches the shapes of `asTool`).
724
+ *
725
+ * ```ts
726
+ * const tools = await db.asTools();
727
+ * const reply = await anthropic.messages.create({
728
+ * model: "claude-opus-4-7",
729
+ * tools: tools.anthropic,
730
+ * messages: [...],
731
+ * });
732
+ * for (const block of reply.content) {
733
+ * if (block.type === "tool_use") {
734
+ * const result = await tools.run(block.name, block.input);
735
+ * }
736
+ * }
737
+ * ```
738
+ */
739
+ async asTools() {
740
+ const schema = await this.schema();
741
+ const anthropic = [];
742
+ const openai = [];
743
+ for (const t of schema.tables) {
744
+ const safe = sanitizeToolPart(t.name);
745
+ const columnList = t.columns.map((c) => `${c.name} ${c.type}${c.notNull ? " NOT NULL" : ""}${c.primaryKey ? " PRIMARY KEY" : ""}`).join(", ");
746
+ const whereProps = {};
747
+ for (const c of t.columns) {
748
+ whereProps[c.name] = {
749
+ type: ["string", "number", "boolean", "null"],
750
+ description: `Equality filter on ${t.name}.${c.name} (${c.type})`
751
+ };
752
+ }
753
+ const selectName = `select_${safe}`;
754
+ const selectDesc = `Read rows from ${t.name}. Columns: ${columnList}. Use \`where\` for equality predicates, \`orderBy\` to sort, \`limit\` to bound the result (default 100, max 1000).`;
755
+ const selectInput = {
756
+ type: "object",
757
+ properties: {
758
+ where: {
759
+ type: "object",
760
+ description: "Equality filter \u2014 keys are column names, values are scalars.",
761
+ properties: whereProps,
762
+ additionalProperties: false
763
+ },
764
+ orderBy: {
765
+ type: "string",
766
+ description: "Column name optionally followed by ASC/DESC."
767
+ },
768
+ limit: {
769
+ type: "integer",
770
+ minimum: 1,
771
+ maximum: 1e3,
772
+ default: 100
773
+ }
774
+ },
775
+ additionalProperties: false
776
+ };
777
+ anthropic.push({ name: selectName, description: selectDesc, input_schema: selectInput });
778
+ openai.push({
779
+ type: "function",
780
+ function: { name: selectName, description: selectDesc, parameters: selectInput }
781
+ });
782
+ const countName = `count_${safe}`;
783
+ const countDesc = `Count rows in ${t.name}, optionally filtered by equality on any column.`;
784
+ const countInput = {
785
+ type: "object",
786
+ properties: {
787
+ where: {
788
+ type: "object",
789
+ properties: whereProps,
790
+ additionalProperties: false
791
+ }
792
+ },
793
+ additionalProperties: false
794
+ };
795
+ anthropic.push({ name: countName, description: countDesc, input_schema: countInput });
796
+ openai.push({
797
+ type: "function",
798
+ function: { name: countName, description: countDesc, parameters: countInput }
799
+ });
800
+ const descName = `describe_${safe}`;
801
+ const descDesc = `Return columns, row count, and foreign keys for ${t.name}.`;
802
+ const descInput = {
803
+ type: "object",
804
+ properties: {},
805
+ additionalProperties: false
806
+ };
807
+ anthropic.push({ name: descName, description: descDesc, input_schema: descInput });
808
+ openai.push({
809
+ type: "function",
810
+ function: { name: descName, description: descDesc, parameters: descInput }
811
+ });
812
+ const valueProps = {};
813
+ const requiredForInsert = [];
814
+ for (const c of t.columns) {
815
+ valueProps[c.name] = {
816
+ type: ["string", "number", "boolean", "null"],
817
+ description: `${t.name}.${c.name} (${c.type})${c.notNull ? " NOT NULL" : ""}`
818
+ };
819
+ if (c.notNull && !c.primaryKey) {
820
+ requiredForInsert.push(c.name);
821
+ }
822
+ }
823
+ const insertName = `insert_${safe}`;
824
+ const insertDesc = `Insert one row into ${t.name}. Provide column values in \`values\`. Required (NOT NULL): ${requiredForInsert.join(", ") || "(none)"}.`;
825
+ const insertInput = {
826
+ type: "object",
827
+ properties: {
828
+ values: {
829
+ type: "object",
830
+ description: "Column \u2192 value map for the new row.",
831
+ properties: valueProps,
832
+ required: requiredForInsert,
833
+ additionalProperties: false
834
+ }
835
+ },
836
+ required: ["values"],
837
+ additionalProperties: false
838
+ };
839
+ anthropic.push({ name: insertName, description: insertDesc, input_schema: insertInput });
840
+ openai.push({
841
+ type: "function",
842
+ function: { name: insertName, description: insertDesc, parameters: insertInput }
843
+ });
844
+ const updateName = `update_${safe}`;
845
+ const updateDesc = `Update rows in ${t.name} matching \`where\` (equality on any column) with the columns provided in \`set\`. Both must be non-empty \u2014 to clear the filter use \`sql_query\`.`;
846
+ const updateInput = {
847
+ type: "object",
848
+ properties: {
849
+ where: {
850
+ type: "object",
851
+ properties: whereProps,
852
+ additionalProperties: false
853
+ },
854
+ set: {
855
+ type: "object",
856
+ properties: valueProps,
857
+ additionalProperties: false
858
+ }
859
+ },
860
+ required: ["where", "set"],
861
+ additionalProperties: false
862
+ };
863
+ anthropic.push({ name: updateName, description: updateDesc, input_schema: updateInput });
864
+ openai.push({
865
+ type: "function",
866
+ function: { name: updateName, description: updateDesc, parameters: updateInput }
867
+ });
868
+ const deleteName = `delete_${safe}`;
869
+ const deleteDesc = `Delete rows from ${t.name} matching \`where\`. \`where\` must be non-empty \u2014 to truncate use \`sql_query\` with an explicit DELETE.`;
870
+ const deleteInput = {
871
+ type: "object",
872
+ properties: {
873
+ where: {
874
+ type: "object",
875
+ properties: whereProps,
876
+ additionalProperties: false
877
+ }
878
+ },
879
+ required: ["where"],
880
+ additionalProperties: false
881
+ };
882
+ anthropic.push({ name: deleteName, description: deleteDesc, input_schema: deleteInput });
883
+ openai.push({
884
+ type: "function",
885
+ function: { name: deleteName, description: deleteDesc, parameters: deleteInput }
886
+ });
887
+ }
888
+ const sqlName = "sql_query";
889
+ const sqlDesc = `Run an arbitrary parameterised SQL statement against the PerSQL database "${this.namespace}/${this.slug}". Prefer the table-specific select_/count_/describe_ tools when they fit; fall back to this for joins, aggregates, or DDL.`;
890
+ const sqlInput = {
891
+ type: "object",
892
+ properties: {
893
+ sql: { type: "string" },
894
+ params: { type: "array", items: {} }
895
+ },
896
+ required: ["sql"],
897
+ additionalProperties: false
898
+ };
899
+ anthropic.push({ name: sqlName, description: sqlDesc, input_schema: sqlInput });
900
+ openai.push({
901
+ type: "function",
902
+ function: { name: sqlName, description: sqlDesc, parameters: sqlInput }
903
+ });
904
+ const describeDbName = "describe_database";
905
+ const describeDbDesc = `Return the full schema graph plus stored semantic descriptions for "${this.namespace}/${this.slug}". Call this FIRST on any unfamiliar database \u2014 it includes table descriptions, column docs, and foreign keys in one shot, sized to JSON-stringify into a system prompt.`;
906
+ const describeDbInput = {
907
+ type: "object",
908
+ properties: {},
909
+ additionalProperties: false
910
+ };
911
+ anthropic.push({
912
+ name: describeDbName,
913
+ description: describeDbDesc,
914
+ input_schema: describeDbInput
915
+ });
916
+ openai.push({
917
+ type: "function",
918
+ function: {
919
+ name: describeDbName,
920
+ description: describeDbDesc,
921
+ parameters: describeDbInput
922
+ }
923
+ });
924
+ const searchSchemaName = "search_schema";
925
+ const searchSchemaDesc = `Natural-language ranked search across table names, column names, and stored descriptions. Use this when you have a goal ("billing addresses", "abandoned carts") but don't know which table holds it.`;
926
+ const searchSchemaInput = {
927
+ type: "object",
928
+ properties: {
929
+ q: {
930
+ type: "string",
931
+ description: "Free-text query \u2014 table/column/description tokens are matched."
932
+ },
933
+ limit: {
934
+ type: "integer",
935
+ minimum: 1,
936
+ maximum: 100,
937
+ default: 25
938
+ }
939
+ },
940
+ required: ["q"],
941
+ additionalProperties: false
942
+ };
943
+ anthropic.push({
944
+ name: searchSchemaName,
945
+ description: searchSchemaDesc,
946
+ input_schema: searchSchemaInput
947
+ });
948
+ openai.push({
949
+ type: "function",
950
+ function: {
951
+ name: searchSchemaName,
952
+ description: searchSchemaDesc,
953
+ parameters: searchSchemaInput
954
+ }
955
+ });
956
+ const doctorName = "schema_doctor";
957
+ const doctorDesc = `Lint the schema for LLM-hostile patterns \u2014 missing primary keys, ambiguous column names, unindexed foreign keys. Read-only; useful before generating SQL so you know what the schema gets wrong.`;
958
+ const doctorInput = {
959
+ type: "object",
960
+ properties: {},
961
+ additionalProperties: false
962
+ };
963
+ anthropic.push({
964
+ name: doctorName,
965
+ description: doctorDesc,
966
+ input_schema: doctorInput
967
+ });
968
+ openai.push({
969
+ type: "function",
970
+ function: {
971
+ name: doctorName,
972
+ description: doctorDesc,
973
+ parameters: doctorInput
974
+ }
975
+ });
976
+ const proposeName = "propose_mutation";
977
+ const proposeDesc = `Pre-flight a SQL write \u2014 EXPLAIN-validate, estimate affected rows, and return a single-use executionToken. Nothing is mutated until apply_mutation is called with that token. Use for any UPDATE/DELETE that isn't tightly scoped to a single PK, or any INSERT batch you want to verify.`;
978
+ const proposeInput = {
979
+ type: "object",
980
+ properties: {
981
+ sql: { type: "string", description: "SQLite SQL statement." },
982
+ params: { type: "array", items: {} },
983
+ ttlSec: {
984
+ type: "integer",
985
+ minimum: 30,
986
+ maximum: 3600,
987
+ description: "Token TTL in seconds. Default 600 (10 min)."
988
+ }
989
+ },
990
+ required: ["sql"],
991
+ additionalProperties: false
992
+ };
993
+ anthropic.push({
994
+ name: proposeName,
995
+ description: proposeDesc,
996
+ input_schema: proposeInput
997
+ });
998
+ openai.push({
999
+ type: "function",
1000
+ function: {
1001
+ name: proposeName,
1002
+ description: proposeDesc,
1003
+ parameters: proposeInput
1004
+ }
1005
+ });
1006
+ const applyName = "apply_mutation";
1007
+ const applyDesc = `Redeem an executionToken returned by propose_mutation. Single-use \u2014 calling twice fails. The actual write runs through the same auto-snapshot + query-log + pricing pipeline as a normal SQL call.`;
1008
+ const applyInput = {
1009
+ type: "object",
1010
+ properties: {
1011
+ executionToken: {
1012
+ type: "string",
1013
+ description: "pmut_\u2026 token from propose_mutation."
1014
+ }
1015
+ },
1016
+ required: ["executionToken"],
1017
+ additionalProperties: false
1018
+ };
1019
+ anthropic.push({
1020
+ name: applyName,
1021
+ description: applyDesc,
1022
+ input_schema: applyInput
1023
+ });
1024
+ openai.push({
1025
+ type: "function",
1026
+ function: {
1027
+ name: applyName,
1028
+ description: applyDesc,
1029
+ parameters: applyInput
1030
+ }
1031
+ });
1032
+ const queryLogName = "recent_queries";
1033
+ const queryLogDesc = `Recent /query and /batch calls against this database \u2014 durations, errors, statement counts. Use to debug a failed write you just made, or to spot N+1 patterns in your own behavior.`;
1034
+ const queryLogInput = {
1035
+ type: "object",
1036
+ properties: {
1037
+ since: {
1038
+ type: "string",
1039
+ description: "ISO timestamp lower bound."
1040
+ },
1041
+ status: {
1042
+ type: "string",
1043
+ enum: ["ok", "error"]
1044
+ },
1045
+ pageSize: {
1046
+ type: "integer",
1047
+ minimum: 1,
1048
+ maximum: 200,
1049
+ default: 50
1050
+ }
1051
+ },
1052
+ additionalProperties: false
1053
+ };
1054
+ anthropic.push({
1055
+ name: queryLogName,
1056
+ description: queryLogDesc,
1057
+ input_schema: queryLogInput
1058
+ });
1059
+ openai.push({
1060
+ type: "function",
1061
+ function: {
1062
+ name: queryLogName,
1063
+ description: queryLogDesc,
1064
+ parameters: queryLogInput
1065
+ }
1066
+ });
1067
+ const dbRef = `"${this.namespace}/${this.slug}"`;
1068
+ const branchesList = "branches_list";
1069
+ const branchesListInput = {
1070
+ type: "object",
1071
+ properties: {},
1072
+ additionalProperties: false
1073
+ };
1074
+ const branchesListDesc = `List preview branches of ${dbRef}. Each branch is its own SQLite database forked from the parent at create time.`;
1075
+ anthropic.push({
1076
+ name: branchesList,
1077
+ description: branchesListDesc,
1078
+ input_schema: branchesListInput
1079
+ });
1080
+ openai.push({
1081
+ type: "function",
1082
+ function: {
1083
+ name: branchesList,
1084
+ description: branchesListDesc,
1085
+ parameters: branchesListInput
1086
+ }
1087
+ });
1088
+ const branchesCreate = "branches_create";
1089
+ const branchesCreateInput = {
1090
+ type: "object",
1091
+ properties: {
1092
+ ref: {
1093
+ type: "string",
1094
+ description: "Stable identifier for the branch (e.g. 'pr-42' or 'agent-run-7c2f'). PUT semantics \u2014 the same ref re-runs as a reset from the parent's current state."
1095
+ },
1096
+ name: {
1097
+ type: "string",
1098
+ description: "Optional human-readable name."
1099
+ },
1100
+ ttlDays: {
1101
+ type: ["integer", "null"],
1102
+ minimum: 1,
1103
+ maximum: 30,
1104
+ description: "Auto-delete after N days (1..30). Use for ephemeral / scratch experiments."
1105
+ }
1106
+ },
1107
+ required: ["ref"],
1108
+ additionalProperties: false
1109
+ };
1110
+ const branchesCreateDesc = `Create-or-reset a branch of ${dbRef} keyed by ref. Idempotent: repeat the same ref to refresh from the current parent. Requires an admin-role token.`;
1111
+ anthropic.push({
1112
+ name: branchesCreate,
1113
+ description: branchesCreateDesc,
1114
+ input_schema: branchesCreateInput
1115
+ });
1116
+ openai.push({
1117
+ type: "function",
1118
+ function: {
1119
+ name: branchesCreate,
1120
+ description: branchesCreateDesc,
1121
+ parameters: branchesCreateInput
1122
+ }
1123
+ });
1124
+ const branchesDelete = "branches_delete";
1125
+ const branchesDeleteInput = {
1126
+ type: "object",
1127
+ properties: {
1128
+ ref: { type: "string", description: "The branch ref to delete." }
1129
+ },
1130
+ required: ["ref"],
1131
+ additionalProperties: false
1132
+ };
1133
+ const branchesDeleteDesc = `Delete a branch of ${dbRef}. Removes the branch's database and all of its data. Requires an admin-role token.`;
1134
+ anthropic.push({
1135
+ name: branchesDelete,
1136
+ description: branchesDeleteDesc,
1137
+ input_schema: branchesDeleteInput
1138
+ });
1139
+ openai.push({
1140
+ type: "function",
1141
+ function: {
1142
+ name: branchesDelete,
1143
+ description: branchesDeleteDesc,
1144
+ parameters: branchesDeleteInput
1145
+ }
1146
+ });
1147
+ const branchesMergeInput = {
1148
+ type: "object",
1149
+ properties: {
1150
+ ref: { type: "string", description: "The branch ref to apply." },
1151
+ mode: {
1152
+ type: "string",
1153
+ enum: ["schema", "promote"],
1154
+ description: "schema (default): apply the DDL delta \u2014 adds, plus replaces for views/triggers/indexes. Refuses table-shape changes. promote: replace the parent's full contents with the branch's (the parent keeps its identity)."
1155
+ },
1156
+ dropRemoved: {
1157
+ type: "boolean",
1158
+ description: "Schema mode only \u2014 also drop objects present in the parent but absent in the branch."
1159
+ }
1160
+ },
1161
+ required: ["ref"],
1162
+ additionalProperties: false
1163
+ };
1164
+ const branchesPreview = "branches_preview_merge";
1165
+ const branchesPreviewDesc = `Preview merging a branch of ${dbRef} back into its parent \u2014 returns the plan (added/changed/removed objects) without writing. Use this before branches_merge to show the user what will happen.`;
1166
+ anthropic.push({
1167
+ name: branchesPreview,
1168
+ description: branchesPreviewDesc,
1169
+ input_schema: branchesMergeInput
1170
+ });
1171
+ openai.push({
1172
+ type: "function",
1173
+ function: {
1174
+ name: branchesPreview,
1175
+ description: branchesPreviewDesc,
1176
+ parameters: branchesMergeInput
1177
+ }
1178
+ });
1179
+ const claimBranchName = "claim_branch";
1180
+ const claimBranchDesc = `One-shot lease: create a fresh branch of ${dbRef} AND mint a scoped psql_live_ token in the same call. Use this when delegating work to a sub-agent \u2014 return the token to the sub-agent, walk away, and the branch + token both expire when the lease ends. Requires an admin-role token.`;
1181
+ const claimBranchInput = {
1182
+ type: "object",
1183
+ properties: {
1184
+ purpose: {
1185
+ type: "string",
1186
+ description: "Free-text label baked into the auto-generated branch ref (e.g. 'agent-run-fix-issue-742')."
1187
+ },
1188
+ ttlSec: {
1189
+ type: "integer",
1190
+ minimum: 60,
1191
+ maximum: 60 * 60 * 24 * 30,
1192
+ description: "Lease duration in seconds. Default 3600 (1 hour)."
1193
+ },
1194
+ role: {
1195
+ type: "string",
1196
+ enum: ["read", "write", "admin"],
1197
+ description: "Role for the minted token. Default 'write'."
1198
+ }
1199
+ },
1200
+ additionalProperties: false
1201
+ };
1202
+ anthropic.push({
1203
+ name: claimBranchName,
1204
+ description: claimBranchDesc,
1205
+ input_schema: claimBranchInput
1206
+ });
1207
+ openai.push({
1208
+ type: "function",
1209
+ function: {
1210
+ name: claimBranchName,
1211
+ description: claimBranchDesc,
1212
+ parameters: claimBranchInput
1213
+ }
1214
+ });
1215
+ const branchesMerge = "branches_merge";
1216
+ const branchesMergeDesc = `Apply a branch back into ${dbRef}. Auto-snapshots the parent first (rollback via /restore with the returned snapshotId). Requires an admin-role token.`;
1217
+ anthropic.push({
1218
+ name: branchesMerge,
1219
+ description: branchesMergeDesc,
1220
+ input_schema: branchesMergeInput
1221
+ });
1222
+ openai.push({
1223
+ type: "function",
1224
+ function: {
1225
+ name: branchesMerge,
1226
+ description: branchesMergeDesc,
1227
+ parameters: branchesMergeInput
1228
+ }
1229
+ });
1230
+ const tableBySafe = /* @__PURE__ */ new Map();
1231
+ for (const t of schema.tables) tableBySafe.set(sanitizeToolPart(t.name), t);
1232
+ const run = async (name, input = {}) => {
1233
+ if (name === sqlName) {
1234
+ const sql = String(input.sql ?? "");
1235
+ const params2 = Array.isArray(input.params) ? input.params : [];
1236
+ return this.query(sql, params2);
1237
+ }
1238
+ if (name === describeDbName) {
1239
+ return this.describe();
1240
+ }
1241
+ if (name === searchSchemaName) {
1242
+ const q = String(input.q ?? "");
1243
+ if (!q) throw new Error("q is required");
1244
+ const limit2 = typeof input.limit === "number" ? input.limit : void 0;
1245
+ return this.search(q, limit2 !== void 0 ? { limit: limit2 } : {});
1246
+ }
1247
+ if (name === doctorName) {
1248
+ return this.doctor();
1249
+ }
1250
+ if (name === proposeName) {
1251
+ const sql = String(input.sql ?? "");
1252
+ if (!sql) throw new Error("sql is required");
1253
+ const params2 = Array.isArray(input.params) ? input.params : void 0;
1254
+ const ttlSec = typeof input.ttlSec === "number" ? input.ttlSec : void 0;
1255
+ return this.proposals.propose(sql, {
1256
+ params: params2,
1257
+ ttlSec
1258
+ });
1259
+ }
1260
+ if (name === applyName) {
1261
+ const token = String(input.executionToken ?? "");
1262
+ if (!token) throw new Error("executionToken is required");
1263
+ return this.proposals.apply(token);
1264
+ }
1265
+ if (name === queryLogName) {
1266
+ const opts = {};
1267
+ if (typeof input.since === "string") opts.since = input.since;
1268
+ if (input.status === "ok" || input.status === "error")
1269
+ opts.status = input.status;
1270
+ if (typeof input.pageSize === "number") opts.pageSize = input.pageSize;
1271
+ return this.queryLog(opts);
1272
+ }
1273
+ if (name === claimBranchName) {
1274
+ const opts = {};
1275
+ if (typeof input.purpose === "string") opts.purpose = input.purpose;
1276
+ if (typeof input.ttlSec === "number") opts.ttlSec = input.ttlSec;
1277
+ if (input.role === "read" || input.role === "write" || input.role === "admin")
1278
+ opts.role = input.role;
1279
+ return this.branches.claim(opts);
1280
+ }
1281
+ if (name === branchesList) {
1282
+ return this.branches.list();
1283
+ }
1284
+ if (name === branchesCreate) {
1285
+ const ref = String(input.ref ?? "");
1286
+ if (!ref) throw new Error("ref is required");
1287
+ const ttl = input.ttlDays;
1288
+ return this.branches.upsert(ref, {
1289
+ name: typeof input.name === "string" ? input.name : void 0,
1290
+ ttlDays: typeof ttl === "number" ? ttl : ttl === null ? null : void 0
1291
+ });
1292
+ }
1293
+ if (name === branchesDelete) {
1294
+ const ref = String(input.ref ?? "");
1295
+ if (!ref) throw new Error("ref is required");
1296
+ return this.branches.delete(ref);
1297
+ }
1298
+ if (name === branchesPreview || name === branchesMerge) {
1299
+ const ref = String(input.ref ?? "");
1300
+ if (!ref) throw new Error("ref is required");
1301
+ const mode = input.mode === "promote" ? "promote" : "schema";
1302
+ return this.branches.merge(ref, {
1303
+ mode,
1304
+ preview: name === branchesPreview,
1305
+ dropRemoved: input.dropRemoved === true
1306
+ });
1307
+ }
1308
+ const m = name.match(/^(select|count|describe|insert|update|delete)_(.+)$/);
1309
+ if (!m) throw new Error(`Unknown tool: ${name}`);
1310
+ const [, op, tableSafe] = m;
1311
+ const t = tableBySafe.get(tableSafe);
1312
+ if (!t) throw new Error(`Unknown table for tool ${name}`);
1313
+ const ident = quoteIdent(t.name);
1314
+ const colSetForT = new Set(t.columns.map((c) => c.name));
1315
+ if (op === "insert") {
1316
+ const values = input.values ?? {};
1317
+ const cols = Object.keys(values);
1318
+ if (cols.length === 0) throw new Error("values must be non-empty");
1319
+ for (const k of cols) {
1320
+ if (!colSetForT.has(k)) throw new Error(`Unknown column: ${k}`);
1321
+ }
1322
+ const placeholders = cols.map(() => "?").join(", ");
1323
+ const colSql = cols.map(quoteIdent).join(", ");
1324
+ return this.query(
1325
+ `INSERT INTO ${ident} (${colSql}) VALUES (${placeholders})`,
1326
+ cols.map((c) => values[c])
1327
+ );
1328
+ }
1329
+ if (op === "update") {
1330
+ const where2 = input.where ?? {};
1331
+ const setObj = input.set ?? {};
1332
+ const setKeys = Object.keys(setObj);
1333
+ const whereKeys = Object.keys(where2);
1334
+ if (setKeys.length === 0) throw new Error("set must be non-empty");
1335
+ if (whereKeys.length === 0)
1336
+ throw new Error("where must be non-empty \u2014 use sql_query for unfiltered updates");
1337
+ for (const k of [...setKeys, ...whereKeys]) {
1338
+ if (!colSetForT.has(k)) throw new Error(`Unknown column: ${k}`);
1339
+ }
1340
+ const setSql = setKeys.map((k) => `${quoteIdent(k)} = ?`).join(", ");
1341
+ const whereSqlParts = [];
1342
+ const whereParams = [];
1343
+ for (const k of whereKeys) {
1344
+ const v = where2[k];
1345
+ if (v === null) {
1346
+ whereSqlParts.push(`${quoteIdent(k)} IS NULL`);
1347
+ } else {
1348
+ whereSqlParts.push(`${quoteIdent(k)} = ?`);
1349
+ whereParams.push(v);
1350
+ }
1351
+ }
1352
+ return this.query(
1353
+ `UPDATE ${ident} SET ${setSql} WHERE ${whereSqlParts.join(" AND ")}`,
1354
+ [...setKeys.map((k) => setObj[k]), ...whereParams]
1355
+ );
1356
+ }
1357
+ if (op === "delete") {
1358
+ const where2 = input.where ?? {};
1359
+ const whereKeys = Object.keys(where2);
1360
+ if (whereKeys.length === 0)
1361
+ throw new Error("where must be non-empty \u2014 use sql_query for unfiltered deletes");
1362
+ for (const k of whereKeys) {
1363
+ if (!colSetForT.has(k)) throw new Error(`Unknown column: ${k}`);
1364
+ }
1365
+ const whereSqlParts = [];
1366
+ const whereParams = [];
1367
+ for (const k of whereKeys) {
1368
+ const v = where2[k];
1369
+ if (v === null) {
1370
+ whereSqlParts.push(`${quoteIdent(k)} IS NULL`);
1371
+ } else {
1372
+ whereSqlParts.push(`${quoteIdent(k)} = ?`);
1373
+ whereParams.push(v);
1374
+ }
1375
+ }
1376
+ return this.query(
1377
+ `DELETE FROM ${ident} WHERE ${whereSqlParts.join(" AND ")}`,
1378
+ whereParams
1379
+ );
1380
+ }
1381
+ if (op === "describe") {
1382
+ const [info, fks, count] = await Promise.all([
1383
+ this.query(`PRAGMA table_info(${ident})`),
1384
+ this.query(`PRAGMA foreign_key_list(${ident})`),
1385
+ this.query(`SELECT COUNT(*) AS n FROM ${ident}`)
1386
+ ]);
1387
+ return {
1388
+ table: t.name,
1389
+ rowCount: Number(count.rows[0]?.[0] ?? 0),
1390
+ columns: info.data,
1391
+ foreignKeys: fks.data
1392
+ };
1393
+ }
1394
+ const where = input.where ?? {};
1395
+ const colSet = new Set(t.columns.map((c) => c.name));
1396
+ const clauses = [];
1397
+ const params = [];
1398
+ for (const [k, v] of Object.entries(where)) {
1399
+ if (!colSet.has(k)) throw new Error(`Unknown column: ${k}`);
1400
+ if (v === null) {
1401
+ clauses.push(`${quoteIdent(k)} IS NULL`);
1402
+ } else {
1403
+ clauses.push(`${quoteIdent(k)} = ?`);
1404
+ params.push(v);
1405
+ }
1406
+ }
1407
+ const whereSql = clauses.length ? ` WHERE ${clauses.join(" AND ")}` : "";
1408
+ if (op === "count") {
1409
+ const r2 = await this.query(`SELECT COUNT(*) AS n FROM ${ident}${whereSql}`, params);
1410
+ return { count: Number(r2.rows[0]?.[0] ?? 0) };
1411
+ }
1412
+ const limit = Math.min(1e3, Math.max(1, Number(input.limit ?? 100)));
1413
+ let orderSql = "";
1414
+ if (typeof input.orderBy === "string" && input.orderBy.trim()) {
1415
+ const ob = input.orderBy.trim();
1416
+ const obMatch = ob.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(asc|desc)?$/i);
1417
+ if (!obMatch) throw new Error("orderBy must be `<col>` or `<col> ASC|DESC`");
1418
+ const [, col, dir] = obMatch;
1419
+ if (!colSet.has(col)) throw new Error(`Unknown column: ${col}`);
1420
+ orderSql = ` ORDER BY ${quoteIdent(col)} ${(dir ?? "ASC").toUpperCase()}`;
1421
+ }
1422
+ const r = await this.query(
1423
+ `SELECT * FROM ${ident}${whereSql}${orderSql} LIMIT ${limit}`,
1424
+ params
1425
+ );
1426
+ return r;
1427
+ };
1428
+ const aiSdk = () => {
1429
+ const out = {};
1430
+ for (const t of anthropic) {
1431
+ out[t.name] = {
1432
+ description: t.description,
1433
+ inputSchema: t.input_schema,
1434
+ execute: (input) => run(t.name, input)
1435
+ };
1436
+ }
1437
+ return out;
1438
+ };
1439
+ const mastra = () => {
1440
+ const out = {};
1441
+ for (const t of anthropic) {
1442
+ out[t.name] = {
1443
+ id: t.name,
1444
+ description: t.description,
1445
+ inputSchema: t.input_schema,
1446
+ execute: ({ context }) => run(t.name, context)
1447
+ };
1448
+ }
1449
+ return out;
1450
+ };
1451
+ const langchain = () => anthropic.map((t) => ({
1452
+ name: t.name,
1453
+ description: t.description,
1454
+ schema: t.input_schema,
1455
+ invoke: (input) => run(t.name, input)
1456
+ }));
1457
+ const openaiAgents = () => anthropic.map((t) => ({
1458
+ type: "function",
1459
+ name: t.name,
1460
+ description: t.description,
1461
+ parameters: t.input_schema,
1462
+ invoke: (input) => run(t.name, input)
1463
+ }));
1464
+ return { anthropic, openai, run, aiSdk, mastra, langchain, openaiAgents };
1465
+ }
1466
+ };
1467
+ function sanitizeToolPart(s) {
1468
+ return s.replace(/[^A-Za-z0-9_]/g, "_");
1469
+ }
1470
+ function quoteIdent(s) {
1471
+ return `"${s.replace(/"/g, '""')}"`;
1472
+ }
1473
+ var PerSQLBlob = class {
1474
+ constructor(client, namespace, slug) {
1475
+ this.client = client;
1476
+ this.namespace = namespace;
1477
+ this.slug = slug;
1478
+ }
1479
+ /** Upload a blob. Body can be ArrayBuffer, Blob, ReadableStream, or string. */
1480
+ async put(key, body, opts = {}) {
1481
+ const path = `/v1/db/${this.namespace}/${this.slug}/blobs/${encodeBlobKey(key)}`;
1482
+ return this.client.requestRaw(
1483
+ "PUT",
1484
+ path,
1485
+ body,
1486
+ opts.contentType
1487
+ );
1488
+ }
1489
+ /** Fetch a blob. Returns null if missing. */
1490
+ async get(key) {
1491
+ const path = `/v1/db/${this.namespace}/${this.slug}/blobs/${encodeBlobKey(key)}`;
1492
+ const res = await this.client.fetchRaw("GET", path);
1493
+ if (res.status === 404) return null;
1494
+ if (!res.ok) {
1495
+ throw new PerSQLError(res.status, `Blob fetch failed (${res.status})`);
1496
+ }
1497
+ return res;
1498
+ }
1499
+ /** Delete a blob. */
1500
+ async delete(key) {
1501
+ const path = `/v1/db/${this.namespace}/${this.slug}/blobs/${encodeBlobKey(key)}`;
1502
+ await this.client.request("DELETE", path);
1503
+ }
1504
+ /** List blobs by prefix. */
1505
+ async list(opts = {}) {
1506
+ const params = new URLSearchParams();
1507
+ if (opts.prefix) params.set("prefix", opts.prefix);
1508
+ if (opts.cursor) params.set("cursor", opts.cursor);
1509
+ if (opts.limit) params.set("limit", String(opts.limit));
1510
+ const qs = params.toString();
1511
+ const path = `/v1/db/${this.namespace}/${this.slug}/blobs` + (qs ? `?${qs}` : "");
1512
+ return this.client.request("GET", path);
1513
+ }
1514
+ };
1515
+ function encodeBlobKey(key) {
1516
+ return key.split("/").map(encodeURIComponent).join("/");
1517
+ }
1518
+ var PerSQLVectors = class {
1519
+ constructor(client, namespace, slug) {
1520
+ this.client = client;
1521
+ this.namespace = namespace;
1522
+ this.slug = slug;
1523
+ }
1524
+ /** Embed and upsert up to 100 items in one call. */
1525
+ async upsert(items) {
1526
+ return this.client.request(
1527
+ "POST",
1528
+ `/v1/db/${this.namespace}/${this.slug}/vectors`,
1529
+ { items }
1530
+ );
1531
+ }
1532
+ /** Top-K nearest neighbours by free-text query. */
1533
+ async query(text, opts = {}) {
1534
+ return this.client.request(
1535
+ "POST",
1536
+ `/v1/db/${this.namespace}/${this.slug}/vectors/query`,
1537
+ { query: text, topK: opts.topK, filter: opts.filter }
1538
+ );
1539
+ }
1540
+ /** Delete vectors by id. Up to 1000 ids per call. */
1541
+ async delete(ids) {
1542
+ return this.client.request(
1543
+ "DELETE",
1544
+ `/v1/db/${this.namespace}/${this.slug}/vectors`,
1545
+ { ids }
1546
+ );
1547
+ }
1548
+ };
1549
+ var PerSQLApprovals = class {
1550
+ constructor(client, namespace, slug) {
1551
+ this.client = client;
1552
+ this.namespace = namespace;
1553
+ this.slug = slug;
1554
+ }
1555
+ /**
1556
+ * Redeem an approved approvalToken. The bearer must be the same one
1557
+ * that minted it, and the request must target the same database.
1558
+ * Returns the result of the originally-blocked query or batch.
1559
+ */
1560
+ async redeem(approvalToken) {
1561
+ const raw = await this.client.request("POST", `/v1/db/${this.namespace}/${this.slug}/redeem_approval`, {
1562
+ approvalToken
1563
+ });
1564
+ if (Array.isArray(raw)) {
1565
+ return raw.map((r) => ({
1566
+ ...r,
1567
+ data: rowsToObjects(r.columns, r.rows)
1568
+ }));
1569
+ }
1570
+ return { ...raw, data: rowsToObjects(raw.columns, raw.rows) };
1571
+ }
1572
+ };
1573
+ var PerSQLProposals = class {
1574
+ constructor(client, namespace, slug) {
1575
+ this.client = client;
1576
+ this.namespace = namespace;
1577
+ this.slug = slug;
1578
+ }
1579
+ /**
1580
+ * Pre-flight an SQL statement. EXPLAIN-validates, estimates affected
1581
+ * rows, and returns a single-use `executionToken` valid for 10 min
1582
+ * (override with `ttlSec`, max 1 hour). Nothing is mutated until
1583
+ * `apply()` is called.
1584
+ */
1585
+ async propose(sql, opts = {}) {
1586
+ if (this.client.local) {
1587
+ return this.client.local.propose(sql, opts.params ?? [], opts.ttlSec);
1588
+ }
1589
+ return this.client.request(
1590
+ "POST",
1591
+ `/v1/db/${this.namespace}/${this.slug}/propose`,
1592
+ {
1593
+ sql,
1594
+ params: opts.params ?? [],
1595
+ ttlSec: opts.ttlSec
1596
+ }
1597
+ );
1598
+ }
1599
+ /**
1600
+ * Redeem an `executionToken` from `propose()`. Single-use — calling
1601
+ * twice with the same token throws 404. The token is also pinned to
1602
+ * the originating bearer + database; cross-token redemption throws
1603
+ * 403.
1604
+ */
1605
+ async apply(executionToken) {
1606
+ if (this.client.local) {
1607
+ const raw2 = await this.client.local.apply(executionToken);
1608
+ return { ...raw2, data: rowsToObjects(raw2.columns, raw2.rows) };
1609
+ }
1610
+ const raw = await this.client.request("POST", `/v1/db/${this.namespace}/${this.slug}/apply`, { executionToken });
1611
+ return {
1612
+ ...raw,
1613
+ data: rowsToObjects(raw.columns, raw.rows)
1614
+ };
1615
+ }
1616
+ };
1617
+ var PerSQLBranches = class {
1618
+ constructor(client, namespace, slug) {
1619
+ this.client = client;
1620
+ this.namespace = namespace;
1621
+ this.slug = slug;
1622
+ }
1623
+ /**
1624
+ * One-shot lease — create or reset a branch with a TTL and mint a
1625
+ * scoped token in the same call. Use at the start of an agent run
1626
+ * instead of chaining create + token mint.
1627
+ */
1628
+ async claim(opts = {}) {
1629
+ return this.client.request(
1630
+ "POST",
1631
+ `/v1/db/${this.namespace}/${this.slug}/claim_branch`,
1632
+ opts
1633
+ );
1634
+ }
1635
+ /** List branches of this database. Any-role token. */
1636
+ async list(opts = {}) {
1637
+ const qs = new URLSearchParams();
1638
+ if (opts.cursor) qs.set("cursor", opts.cursor);
1639
+ if (opts.pageSize) qs.set("pageSize", String(opts.pageSize));
1640
+ const tail = qs.toString() ? `?${qs.toString()}` : "";
1641
+ const res = await this.client.fetchRaw(
1642
+ "GET",
1643
+ `/v1/db/${this.namespace}/${this.slug}/branches${tail}`
1644
+ );
1645
+ const body = await res.json();
1646
+ if (!res.ok || !body.success) {
1647
+ throw new PerSQLError(res.status, body.error ?? `Request failed (${res.status})`);
1648
+ }
1649
+ return { data: body.data ?? [], nextCursor: body.nextCursor ?? null };
1650
+ }
1651
+ /**
1652
+ * Create-or-reset a branch by ref. Idempotent: re-PUTting the same
1653
+ * ref refreshes the branch from the parent's current state.
1654
+ * Requires an admin-role token.
1655
+ */
1656
+ async upsert(ref, opts = {}) {
1657
+ return this.client.request(
1658
+ "PUT",
1659
+ `/v1/db/${this.namespace}/${this.slug}/branches/${encodeURIComponent(ref)}`,
1660
+ {
1661
+ name: opts.name,
1662
+ region: opts.region,
1663
+ ttlDays: opts.ttlDays ?? null
1664
+ }
1665
+ );
1666
+ }
1667
+ /** Delete a branch by ref. Requires an admin-role token. */
1668
+ async delete(ref) {
1669
+ return this.client.request(
1670
+ "DELETE",
1671
+ `/v1/db/${this.namespace}/${this.slug}/branches/${encodeURIComponent(ref)}`
1672
+ );
1673
+ }
1674
+ /**
1675
+ * Apply a branch back into its parent. `preview: true` returns the
1676
+ * plan without writing. Requires an admin-role token.
1677
+ */
1678
+ async merge(ref, opts = {}) {
1679
+ return this.client.request(
1680
+ "POST",
1681
+ `/v1/db/${this.namespace}/${this.slug}/branches/${encodeURIComponent(ref)}/merge`,
1682
+ {
1683
+ mode: opts.mode ?? "schema",
1684
+ preview: opts.preview === true,
1685
+ dropRemoved: opts.dropRemoved === true,
1686
+ snapshot: opts.snapshot !== false
1687
+ }
1688
+ );
1689
+ }
1690
+ /** Convenience for `merge(ref, { preview: true, ...opts })`. */
1691
+ preview(ref, opts = {}) {
1692
+ return this.merge(ref, { ...opts, preview: true });
1693
+ }
1694
+ /**
1695
+ * Mint a single-use handoff token for this branch. The receiving
1696
+ * agent calls `PerSQL.fromHandoff(token)` to redeem it for a
1697
+ * regular bearer token scoped to exactly this (database, branch,
1698
+ * role) — the agent that minted the handoff never has to share
1699
+ * its own token. Single-use, ≤24h TTL.
1700
+ */
1701
+ async pin(ref, opts = {}) {
1702
+ return this.client.request(
1703
+ "POST",
1704
+ `/v1/db/${this.namespace}/${this.slug}/branches/${encodeURIComponent(ref)}/pin`,
1705
+ { role: opts.role ?? "write", ttlSec: opts.ttlSec }
1706
+ );
1707
+ }
1708
+ /**
1709
+ * Render the branch's schema delta as a committable SQL migration.
1710
+ * Read-only. Returns `{ name, sql, plan, summary }` — `name` is a
1711
+ * timestamped filename (`YYYYMMDDHHMMSS_branch_<ref>.sql`) safe to
1712
+ * write to disk; `sql` is the migration body wrapped in a single
1713
+ * BEGIN/COMMIT.
1714
+ */
1715
+ async migration(ref, opts = {}) {
1716
+ return this.client.request(
1717
+ "POST",
1718
+ `/v1/db/${this.namespace}/${this.slug}/branches/${encodeURIComponent(ref)}/migration`,
1719
+ { dropRemoved: opts.dropRemoved === true }
1720
+ );
1721
+ }
1722
+ };
1723
+ function rowsToObjects(columns, rows) {
1724
+ return rows.map((r) => {
1725
+ const obj = {};
1726
+ for (let i = 0; i < columns.length; i++) obj[columns[i]] = r[i];
1727
+ return obj;
1728
+ });
1729
+ }
1730
+
1731
+ // src/cli.ts
1732
+ function parseArgs() {
1733
+ const argv = process.argv.slice(2);
1734
+ const m = {};
1735
+ for (let i = 0; i < argv.length; i++) {
1736
+ const a = argv[i];
1737
+ if (a === "--db") m.db = argv[++i] ?? "";
1738
+ else if (a === "--out") m.out = argv[++i] ?? "";
1739
+ else if (a === "--base-url") m.baseURL = argv[++i] ?? "";
1740
+ else if (a === "--help" || a === "-h") {
1741
+ process.stdout.write(
1742
+ "Usage: persql-codegen --db <ns/slug> --out <file.ts> [--base-url <url>]\n"
1743
+ );
1744
+ process.exit(0);
1745
+ }
1746
+ }
1747
+ if (!m.db || !m.out) {
1748
+ process.stderr.write("persql-codegen: --db and --out are required\n");
1749
+ process.exit(1);
1750
+ }
1751
+ return m;
1752
+ }
1753
+ function camel(s) {
1754
+ return s.replace(/[^a-zA-Z0-9_]+/g, "_").replace(/_([a-z])/g, (_, c) => c.toUpperCase()).replace(/^[A-Z]/, (c) => c.toLowerCase());
1755
+ }
1756
+ function emitColumn(col) {
1757
+ const t = col.type.toUpperCase();
1758
+ let drizzle;
1759
+ if (t.includes("INT")) {
1760
+ drizzle = `integer("${col.name}")`;
1761
+ } else if (t.includes("REAL") || t.includes("FLOA") || t.includes("DOUB")) {
1762
+ drizzle = `real("${col.name}")`;
1763
+ } else if (t.includes("BLOB")) {
1764
+ drizzle = `blob("${col.name}")`;
1765
+ } else if (t.includes("CHAR") || t.includes("TEXT") || t.includes("CLOB")) {
1766
+ drizzle = `text("${col.name}")`;
1767
+ } else {
1768
+ drizzle = `text("${col.name}")`;
1769
+ }
1770
+ if (col.primaryKey) drizzle += ".primaryKey()";
1771
+ if (col.notNull && !col.primaryKey) drizzle += ".notNull()";
1772
+ if (col.default !== null) drizzle += `.default(${JSON.stringify(col.default)})`;
1773
+ return ` ${camel(col.name)}: ${drizzle},`;
1774
+ }
1775
+ async function main() {
1776
+ const args = parseArgs();
1777
+ const token = process.env.PERSQL_TOKEN;
1778
+ if (!token) {
1779
+ process.stderr.write(
1780
+ "persql-codegen: PERSQL_TOKEN env var is required (psql_live_\u2026)\n"
1781
+ );
1782
+ process.exit(1);
1783
+ }
1784
+ const persql = new PerSQL({
1785
+ token,
1786
+ baseURL: args.baseURL ?? "https://api.persql.com"
1787
+ });
1788
+ const db = persql.database(args.db);
1789
+ const schema = await db.schema();
1790
+ const types = /* @__PURE__ */ new Set();
1791
+ const tables = [];
1792
+ for (const t of schema.tables) {
1793
+ if (t.columns.length === 0) continue;
1794
+ for (const c of t.columns) {
1795
+ const tt = c.type.toUpperCase();
1796
+ if (tt.includes("INT")) types.add("integer");
1797
+ else if (tt.includes("REAL") || tt.includes("FLOA") || tt.includes("DOUB"))
1798
+ types.add("real");
1799
+ else if (tt.includes("BLOB")) types.add("blob");
1800
+ else types.add("text");
1801
+ }
1802
+ const cols = t.columns.map(emitColumn).join("\n");
1803
+ tables.push(
1804
+ `export const ${camel(t.name)} = sqliteTable("${t.name}", {
1805
+ ${cols}
1806
+ });`
1807
+ );
1808
+ }
1809
+ const importList = ["sqliteTable", ...types].join(", ");
1810
+ const out = `// Generated by @persql/sdk codegen on ${(/* @__PURE__ */ new Date()).toISOString()}.
1811
+ // Re-run \`npx persql-codegen\` after schema changes.
1812
+
1813
+ import { ${importList} } from "drizzle-orm/sqlite-core";
1814
+
1815
+ ` + tables.join("\n\n") + "\n";
1816
+ await (0, import_promises.writeFile)(args.out, out, "utf8");
1817
+ process.stdout.write(
1818
+ `Wrote ${schema.tables.length} table${schema.tables.length === 1 ? "" : "s"} to ${args.out}
1819
+ `
1820
+ );
1821
+ }
1822
+ main().catch((e) => {
1823
+ process.stderr.write(`persql-codegen: ${e.message}
1824
+ `);
1825
+ process.exit(1);
1826
+ });
1827
+ //# sourceMappingURL=cli.cjs.map