@forestfuture/active-record 0.0.0 → 0.7.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.
@@ -0,0 +1,939 @@
1
+ import { a as underscore } from "./epoch-storage-o2aoOH7H.mjs";
2
+ import { n as migrationSql, r as quotedName, t as generatedSchema } from "./for-adapters-Ch6CoHD4.mjs";
3
+ import { f as byVersion, l as parseJsonc, n as attributeName } from "./storage-override-CpbkdIqE.mjs";
4
+ import { createRequire } from "node:module";
5
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
6
+ import { basename, dirname, join } from "node:path";
7
+ import { randomUUID } from "node:crypto";
8
+ //#region cli/adapters/postgresql/config.ts
9
+ /** The table the runner records applied migrations in, left out of the schema. */
10
+ const migrationsTable = "schema_migrations";
11
+ /** The settings a database's entry may have, each a string. */
12
+ const stringSettings = [
13
+ "migrationsDir",
14
+ "url",
15
+ "remoteUrl",
16
+ "schemaUrl"
17
+ ];
18
+ /** Why a database's entry won't do, if it won't. */
19
+ function entryError(binding, entry) {
20
+ const wrong = stringSettings.find((key) => key in entry && typeof entry[key] !== "string");
21
+ return wrong === void 0 ? void 0 : `databases.${binding}.${wrong} isn't a string`;
22
+ }
23
+ /** An entry as a database: its binding, and its migrations' folder and table. */
24
+ function databaseOf(binding, entry) {
25
+ return {
26
+ binding,
27
+ migrationsDir: typeof entry.migrationsDir === "string" ? entry.migrationsDir : "migrations",
28
+ migrationsTable,
29
+ entry
30
+ };
31
+ }
32
+ /**
33
+ * The Postgres databases a project's `active-record.jsonc` declares, by binding:
34
+ * `{ "databases": { "HYPERDRIVE": { "adapter": "postgresql", "url": "postgres://localhost/shop" } } }`.
35
+ */
36
+ function readDatabases(project) {
37
+ const name = basename(project.file);
38
+ const entries = Object.entries(project.databases);
39
+ for (const [binding, entry] of entries) {
40
+ const error = entryError(binding, entry);
41
+ if (error !== void 0) return {
42
+ ok: false,
43
+ error: `${name}: ${error}`
44
+ };
45
+ }
46
+ return {
47
+ ok: true,
48
+ file: project.file,
49
+ dir: project.dir,
50
+ databases: entries.map(([binding, entry]) => databaseOf(binding, entry))
51
+ };
52
+ }
53
+ //#endregion
54
+ //#region cli/adapters/postgresql/wrangler.ts
55
+ const candidates = [
56
+ "wrangler.jsonc",
57
+ "wrangler.json",
58
+ "wrangler.toml"
59
+ ];
60
+ /** A TOML basic string's contents, its escapes decoded (`\\` → `\`, `é` → `é`). */
61
+ function basicString(body) {
62
+ return JSON.parse(`"${body.replace(/\\U([0-9a-fA-F]{8})/g, (_, hex) => {
63
+ return JSON.stringify(String.fromCodePoint(Number.parseInt(hex, 16))).slice(1, -1);
64
+ })}"`);
65
+ }
66
+ /** A TOML line's `key = "string"` as `[key, value]`, or undefined for any other line. */
67
+ function tomlPair(line) {
68
+ const pair = /^([\w-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|'([^']*)')/.exec(line);
69
+ if (pair === null) return void 0;
70
+ return [pair[1], pair[2] === void 0 ? pair[3] : basicString(pair[2])];
71
+ }
72
+ /** The `[[hyperdrive]]` tables of a wrangler.toml, each with its string keys: the ones read. */
73
+ function tomlHyperdrive(text) {
74
+ const tables = [];
75
+ let current;
76
+ for (const line of text.split("\n").map((each) => each.trim())) {
77
+ if (line.startsWith("[")) {
78
+ current = /^\[\[\s*hyperdrive\s*\]\](\s*#.*)?$/.test(line) ? {} : void 0;
79
+ if (current !== void 0) tables.push(current);
80
+ continue;
81
+ }
82
+ const pair = tomlPair(line);
83
+ if (current !== void 0 && pair !== void 0) current[pair[0]] = pair[1];
84
+ }
85
+ return tables;
86
+ }
87
+ /** The config's `hyperdrive` entries, as written, or why it can't be read. */
88
+ function entriesIn(file) {
89
+ const text = readFileSync(file, "utf8");
90
+ if (file.endsWith(".toml")) return tomlHyperdrive(text);
91
+ try {
92
+ const config = parseJsonc(text);
93
+ return Array.isArray(config.hyperdrive) ? config.hyperdrive : [];
94
+ } catch (error) {
95
+ return `${basename(file)} couldn't be read: ${error.message}`;
96
+ }
97
+ }
98
+ /** The Hyperdrive bindings in the Wrangler config in `dir`, if it has one, or why it can't be read. */
99
+ function hyperdriveIn(dir) {
100
+ const file = candidates.map((name) => join(dir, name)).find((path) => existsSync(path));
101
+ if (file === void 0) return void 0;
102
+ const entries = entriesIn(file);
103
+ if (typeof entries === "string") return entries;
104
+ return {
105
+ file,
106
+ bindings: entries.filter((entry) => typeof entry?.binding === "string")
107
+ };
108
+ }
109
+ //#endregion
110
+ //#region cli/adapters/postgresql/init.ts
111
+ /** The local database a project's folder suggests, named as Rails names it: `shop_development`. */
112
+ function guessedUrl(dir) {
113
+ return `postgres://localhost:5432/${basename(dir).toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "") || "app"}_development`;
114
+ }
115
+ /** A database's entry with a guessed local `url`, and a note naming it, with why it's a guess. */
116
+ function guessed(dir, binding, why = "") {
117
+ const url = guessedUrl(dir);
118
+ const note = `${binding}${why ? ` ${why}, so its` : "'s"} url is a guess (${url}); set it to your local database`;
119
+ return {
120
+ entry: { url },
121
+ note
122
+ };
123
+ }
124
+ /** A Hyperdrive binding's entry: its local connection string as the `url`, or a guess, noted. */
125
+ function entryOf(dir, file, binding) {
126
+ if (typeof binding.localConnectionString === "string") return { entry: { url: binding.localConnectionString } };
127
+ return guessed(dir, binding.binding, `has no localConnectionString in ${basename(file)}`);
128
+ }
129
+ /**
130
+ * The Postgres databases for `init`: each Hyperdrive binding in the Wrangler config in `dir`, or,
131
+ * when `--adapter` named PostgreSQL and there's none, `DATABASE_URL` with a guessed local database.
132
+ */
133
+ function init(dir, named) {
134
+ const found = hyperdriveIn(dir);
135
+ if (typeof found === "string") return found;
136
+ if (found !== void 0 && found.bindings.length > 0) {
137
+ const made = found.bindings.map((binding) => [binding.binding, entryOf(dir, found.file, binding)]);
138
+ return {
139
+ databases: Object.fromEntries(made.map(([binding, { entry }]) => [binding, entry])),
140
+ notes: Object.fromEntries(made.flatMap(([binding, { note }]) => note === void 0 ? [] : [[binding, note]]))
141
+ };
142
+ }
143
+ if (!named) return void 0;
144
+ const { entry, note } = guessed(dir, "DATABASE_URL");
145
+ return {
146
+ databases: { DATABASE_URL: entry },
147
+ notes: { DATABASE_URL: note }
148
+ };
149
+ }
150
+ //#endregion
151
+ //#region cli/adapters/postgresql/drivers.ts
152
+ /** Whether Node's error is for the package `name` itself missing, from `require` or `import`. */
153
+ function isMissing(error, name) {
154
+ const { code, message } = error;
155
+ return (code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") && String(message).includes(`'${name}'`);
156
+ }
157
+ /**
158
+ * `pg`, as the library's install has it (the app's own), loaded with `require` so a sync caller can
159
+ * use it; or what to install. A `pg` that fails for any other reason throws.
160
+ */
161
+ function pgDriver(load = createRequire(import.meta.url)) {
162
+ try {
163
+ return load("pg");
164
+ } catch (error) {
165
+ if (!isMissing(error, "pg")) throw error;
166
+ return "The PostgreSQL adapter needs pg, which isn't installed here: run `npm install pg`";
167
+ }
168
+ }
169
+ /** PGlite, which reads a schema in memory, as the library's install has it; or what to install. */
170
+ async function pgliteModule(load = () => import("@electric-sql/pglite")) {
171
+ try {
172
+ return await load();
173
+ } catch (error) {
174
+ if (!isMissing(error, "@electric-sql/pglite")) throw error;
175
+ return "Reading a PostgreSQL schema needs PGlite, which isn't installed here: run `npm install --save-dev @electric-sql/pglite`";
176
+ }
177
+ }
178
+ //#endregion
179
+ //#region cli/adapters/postgresql/urls.ts
180
+ /** `${NAME}`: a variable's value, put in its place. */
181
+ const variable = /\$\{(\w+)\}/g;
182
+ /**
183
+ * The connection string an entry's `setting` holds, with each `${NAME}` read from the environment;
184
+ * undefined when it has none, or why it can't be read. It's never printed: it can hold a password.
185
+ */
186
+ function connectionString(entry, setting) {
187
+ const value = entry?.[setting];
188
+ if (typeof value !== "string") return void 0;
189
+ const unset = [...value.matchAll(variable)].find(([, name]) => process.env[name] === void 0);
190
+ if (unset !== void 0) return { error: `The database's ${setting} names ${unset[0]}, which isn't set` };
191
+ return value.replaceAll(variable, (_, name) => process.env[name]);
192
+ }
193
+ /** The server and database `pg` connects to with a connection string, as it reads one; none when it can't. */
194
+ function parsed(url) {
195
+ const pg = pgDriver();
196
+ if (typeof pg === "string") return void 0;
197
+ try {
198
+ const client = new pg.Client({ connectionString: url });
199
+ return {
200
+ host: client.host,
201
+ database: client.database ?? client.user ?? "postgres"
202
+ };
203
+ } catch {
204
+ return;
205
+ }
206
+ }
207
+ /** Where a connection string points, for a person: its host (or socket folder), never its password. */
208
+ function hostOf(url) {
209
+ return parsed(url)?.host || "its server";
210
+ }
211
+ /** The database a connection string names, for a person to type: as `pg` reads it, its user's by default. */
212
+ function databaseNameOf(url) {
213
+ return parsed(url)?.database ?? "postgres";
214
+ }
215
+ //#endregion
216
+ //#region cli/adapters/postgresql/targets.ts
217
+ /** A database, named for a person: its binding, its database's name and its host. */
218
+ const described = (kind, binding, url) => `${kind} database ${binding} (${databaseNameOf(url)} on ${hostOf(url)})`;
219
+ /** The real database the entry's `remoteUrl` names, or why there's none. */
220
+ function remoteTarget(chosen) {
221
+ const reached = target(chosen, true);
222
+ if (typeof reached === "string") return reached;
223
+ return {
224
+ name: databaseNameOf(reached.url),
225
+ description: reached.description
226
+ };
227
+ }
228
+ /**
229
+ * The connection string a command uses, local or remote, and how it names the database; or why
230
+ * there's none, saying who needs it.
231
+ */
232
+ function target(chosen, remote, needs = "migrate needs") {
233
+ const setting = remote ? "remoteUrl" : "url";
234
+ const url = connectionString(chosen.entry, setting);
235
+ if (url === void 0) {
236
+ const need = remote ? "--remote needs" : `${needs} for the local database`;
237
+ return `${chosen.binding} has no ${setting} in ${basename(chosen.configFile)}, which ${need}`;
238
+ }
239
+ if (typeof url !== "string") return url.error;
240
+ return {
241
+ url,
242
+ description: described(remote ? "Remote" : "Local", chosen.binding, url)
243
+ };
244
+ }
245
+ //#endregion
246
+ //#region cli/adapters/postgresql/client.ts
247
+ /** A client on the connection string's database, connected, or the reason it couldn't be. */
248
+ async function connected(connectionString) {
249
+ const pg = pgDriver();
250
+ if (typeof pg === "string") return pg;
251
+ try {
252
+ const client = new pg.Client({
253
+ connectionString,
254
+ connectionTimeoutMillis: 1e4
255
+ });
256
+ client.on("error", () => {});
257
+ await client.connect();
258
+ return client;
259
+ } catch (error) {
260
+ return error.message;
261
+ }
262
+ }
263
+ //#endregion
264
+ //#region cli/adapters/postgresql/transaction-control.ts
265
+ /** Where a `--` comment starting at `index` ends: at the end of its line. */
266
+ function lineEnd(sql, index) {
267
+ const end = sql.indexOf("\n", index);
268
+ return end < 0 ? sql.length : end;
269
+ }
270
+ /** Where a `/* … *\/` comment starting at `index` ends. */
271
+ function blockEnd(sql, index) {
272
+ const end = sql.indexOf("*/", index + 2);
273
+ return end < 0 ? sql.length : end + 2;
274
+ }
275
+ /** Just past a quoted string or name starting at `index`: `''` doubles a quote, and `E'…'` escapes. */
276
+ function quoteEnd(sql, index, escapes) {
277
+ const quote = sql[index];
278
+ let at = index + 1;
279
+ while (at < sql.length) if (escapes && sql[at] === "\\") at += 2;
280
+ else if (sql[at] !== quote) at += 1;
281
+ else if (sql[at + 1] === quote) at += 2;
282
+ else return at + 1;
283
+ return sql.length;
284
+ }
285
+ /** Just past a dollar-quoted body (`$$ … $$`, `$body$ … $body$`) starting at `index`, if one does. */
286
+ function dollarEnd(sql, index) {
287
+ const tag = /^\$(?:[A-Za-z_]\w*)?\$/.exec(sql.slice(index))?.[0];
288
+ if (tag === void 0) return index;
289
+ const end = sql.indexOf(tag, index + tag.length);
290
+ return end < 0 ? sql.length : end + tag.length;
291
+ }
292
+ /** Whether a string starting at `index` is an escape string (`E'…'`). */
293
+ const escapeString = (sql, index) => /[eE]/.test(sql[index - 1] ?? "") && !/\w/.test(sql[index - 2] ?? "");
294
+ /** Where the quoted or commented text starting at `index` ends, or `index` when none starts there. */
295
+ function skipped(sql, index) {
296
+ if (sql.startsWith("--", index)) return lineEnd(sql, index);
297
+ if (sql.startsWith("/*", index)) return blockEnd(sql, index);
298
+ const char = sql[index];
299
+ if (char === "'") return quoteEnd(sql, index, escapeString(sql, index));
300
+ if (char === "\"") return quoteEnd(sql, index, false);
301
+ return char === "$" ? dollarEnd(sql, index) : index;
302
+ }
303
+ /** The SQL with what can't start a statement blanked out: strings, quoted names, comments, bodies. */
304
+ function blanked(sql) {
305
+ let out = "";
306
+ let index = 0;
307
+ while (index < sql.length) {
308
+ const end = skipped(sql, index);
309
+ out += end > index ? " " : sql[index];
310
+ index = Math.max(end, index + 1);
311
+ }
312
+ return out;
313
+ }
314
+ /** A statement that starts, ends or aborts a transaction; a savepoint nests inside one, so it's left out. */
315
+ const control = /^(begin|start\s+transaction|commit|end|abort|prepare\s+transaction|rollback(?!\s+(?:work\s+|transaction\s+)?to\b))\b/i;
316
+ /**
317
+ * The first statement in a migration that would start or end a transaction (`BEGIN`, `COMMIT`,
318
+ * `ROLLBACK`, …), as its keywords; undefined when there's none. Words in strings, quoted names,
319
+ * comments and function bodies (a plpgsql `BEGIN … END`) don't count.
320
+ */
321
+ function transactionControl(sql) {
322
+ for (const statement of blanked(sql).split(";")) {
323
+ const found = control.exec(statement.trim())?.[1];
324
+ if (found !== void 0) return found.toUpperCase().replaceAll(/\s+/g, " ");
325
+ }
326
+ }
327
+ /** Why `migrate` (and the schema, which refuses what it does) won't take these migrations, if it won't. */
328
+ function ownTransactions(migrations) {
329
+ for (const { name, sql } of migrations) {
330
+ const found = transactionControl(sql);
331
+ if (found !== void 0) return `${name} has its own ${found}; leave out BEGIN, COMMIT and ROLLBACK, since migrate runs each migration in a transaction of its own`;
332
+ }
333
+ }
334
+ //#endregion
335
+ //#region cli/adapters/postgresql/versions.ts
336
+ /**
337
+ * Each migration's version, by its file, in the order they're applied; or why one has none, or
338
+ * shares its version with another, which `migrate` and the schema both refuse.
339
+ */
340
+ function versionsOf(files) {
341
+ const versions = /* @__PURE__ */ new Map();
342
+ const seen = /* @__PURE__ */ new Map();
343
+ for (const file of [...files].sort(byVersion)) {
344
+ const digits = /^(\d+)/.exec(file)?.[1];
345
+ if (digits === void 0) return `${file} has no version: start its name with one, as the generators do (20261108090503_create_products.sql)`;
346
+ const version = BigInt(digits).toString();
347
+ const other = seen.get(version);
348
+ if (other !== void 0) return `${other} and ${file} have the same version, ${version}; give one a version of its own`;
349
+ seen.set(version, file);
350
+ versions.set(file, version);
351
+ }
352
+ return versions;
353
+ }
354
+ //#endregion
355
+ //#region cli/adapters/postgresql/runner.ts
356
+ /** The migrations folder's files in the order they're applied (by version), or why they can't be. */
357
+ function migrationFiles(dir) {
358
+ let names;
359
+ try {
360
+ names = readdirSync(dir).filter((name) => name.endsWith(".sql"));
361
+ } catch {
362
+ return `No migrations folder at ${dir}`;
363
+ }
364
+ const versions = versionsOf(names);
365
+ if (typeof versions === "string") return versions;
366
+ const files = [...versions].map(([file, version]) => ({
367
+ file,
368
+ version,
369
+ sql: readFileSync(join(dir, file), "utf8")
370
+ }));
371
+ return ownTransactions(files.map(({ file, sql }) => ({
372
+ name: file,
373
+ sql
374
+ }))) ?? files;
375
+ }
376
+ /** One lock per database and schema: a run while another holds it is refused, as Rails refuses it. */
377
+ const lock = `hashtext('active-record migrate ' || current_database() || '.' || current_schema())`;
378
+ /** The versions already applied, once the table that records them is there. */
379
+ async function appliedVersions(client) {
380
+ await client.query({ text: `CREATE TABLE IF NOT EXISTS ${migrationsTable} (version TEXT PRIMARY KEY)` });
381
+ const { rows } = await client.query({ text: `SELECT version FROM ${migrationsTable}` });
382
+ return new Set(rows.map((row) => String(row["version"])));
383
+ }
384
+ /** Applies one migration and records its version, in one transaction; why it failed, if it did. */
385
+ async function applyOne(client, { sql, version }) {
386
+ try {
387
+ await client.query({ text: "BEGIN" });
388
+ await client.query({ text: sql });
389
+ await client.query({
390
+ text: `INSERT INTO ${migrationsTable} (version) VALUES ($1)`,
391
+ values: [version]
392
+ });
393
+ await client.query({ text: "COMMIT" });
394
+ return;
395
+ } catch (error) {
396
+ await client.query({ text: "ROLLBACK" }).catch(() => {});
397
+ return error.message;
398
+ }
399
+ }
400
+ /** Applies the files not applied yet, saying each; false once one fails, and none after it run. */
401
+ async function applyPending(client, files, say) {
402
+ const applied = await appliedVersions(client).catch((error) => error);
403
+ if (applied instanceof Error) {
404
+ say(`Couldn't read ${migrationsTable}: ${applied.message}`);
405
+ return false;
406
+ }
407
+ const pending = files.filter((file) => !applied.has(file.version));
408
+ if (pending.length === 0) say("No migrations to apply");
409
+ for (const file of pending) {
410
+ const failure = await applyOne(client, file);
411
+ if (failure !== void 0) {
412
+ say(`${file.file} failed: ${failure}`);
413
+ return false;
414
+ }
415
+ say(`Applied ${file.file}`);
416
+ }
417
+ return true;
418
+ }
419
+ /**
420
+ * Applies the folder's pending migrations to the database `url` names, holding an advisory lock
421
+ * while it does. What it does goes to `say`; it resolves to the exit code.
422
+ */
423
+ async function runMigrations(url, files, say) {
424
+ const client = await connected(url);
425
+ if (typeof client === "string") {
426
+ say(`Couldn't connect to ${hostOf(url)}: ${client}`);
427
+ return 1;
428
+ }
429
+ try {
430
+ const { rows } = await client.query({ text: `SELECT pg_try_advisory_lock(${lock}) AS locked` });
431
+ if (rows[0]?.["locked"] !== true) {
432
+ say("Another migrate is running on this database; run it again once that one's done");
433
+ return 1;
434
+ }
435
+ return await applyPending(client, files, say) ? 0 : 1;
436
+ } catch (error) {
437
+ say(`Couldn't take the migrations' lock: ${error.message}`);
438
+ return 1;
439
+ } finally {
440
+ await client.end();
441
+ }
442
+ }
443
+ //#endregion
444
+ //#region cli/adapters/postgresql/migrate.ts
445
+ /** Applies the chosen database's pending migrations, locally or remotely; the exit code. */
446
+ async function migrate(_cwd, chosen, { remote }, io) {
447
+ const say = (line) => io.output(`${line}\n`);
448
+ const refused = (problem) => {
449
+ say(problem);
450
+ return 1;
451
+ };
452
+ const reached = target(chosen, remote);
453
+ if (typeof reached === "string") return refused(reached);
454
+ const files = migrationFiles(chosen.migrationsDir);
455
+ if (typeof files === "string") return refused(files);
456
+ say(reached.description);
457
+ return runMigrations(reached.url, files, say);
458
+ }
459
+ //#endregion
460
+ //#region cli/adapters/postgresql/migration.ts
461
+ /** Postgres's SQL for a generated migration. */
462
+ const postgres = {
463
+ reserved: new Set("all analyse analyze and any array as asc asymmetric authorization binary both case cast check collate collation column concurrently constraint create cross current_catalog current_date current_role current_schema current_time current_timestamp current_user default deferrable desc distinct do else end except false fetch for foreign freeze from full grant group having ilike in initially inner intersect into is isnull join lateral leading left like limit localtime localtimestamp natural not notnull null offset on only or order outer overlaps placing primary references returning right select session_user similar some symmetric system_user table tablesample then to trailing true union unique user using variadic verbose when where window with".split(" ")),
464
+ types: {
465
+ string: "TEXT",
466
+ integer: "BIGINT",
467
+ real: "DOUBLE PRECISION",
468
+ boolean: "BOOLEAN",
469
+ datetime: "TIMESTAMPTZ",
470
+ json: "JSONB"
471
+ },
472
+ key: (integerId) => integerId ? "id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY" : "id UUID PRIMARY KEY",
473
+ timestampType: "TIMESTAMPTZ",
474
+ guessedKeyType: "UUID",
475
+ dropColumn: (table, column) => `ALTER TABLE ${quotedName(postgres, table)} DROP COLUMN ${quotedName(postgres, column)};\n`
476
+ };
477
+ /** A migration's SQL, for Postgres, with a note for each key type it guessed. */
478
+ function migration(change) {
479
+ return migrationSql(change, postgres);
480
+ }
481
+ //#endregion
482
+ //#region cli/adapters/postgresql/open.ts
483
+ /**
484
+ * A Pool on the chosen database, for the project's `connect`: the `pg` this plugin imports is the
485
+ * one the project's PostgreSQL adapter imports, from the same install. It's ended when the console closes.
486
+ */
487
+ async function openDatabase(chosen, { remote }) {
488
+ const reached = target(chosen, remote, "the console needs");
489
+ if (typeof reached === "string") return reached;
490
+ const pg = pgDriver();
491
+ if (typeof pg === "string") return pg;
492
+ const pool = new pg.Pool({ connectionString: reached.url });
493
+ pool.on("error", () => {});
494
+ return {
495
+ binding: pool,
496
+ description: reached.description,
497
+ dispose: () => pool.end()
498
+ };
499
+ }
500
+ //#endregion
501
+ //#region cli/adapters/postgresql/catalog.ts
502
+ /** The current schema's own tables: ordinary and partitioned ones, not a partition or a view. */
503
+ const ownTables = `c.relnamespace = current_schema()::regnamespace
504
+ AND c.relkind IN ('r', 'p') AND NOT c.relispartition`;
505
+ const columnsQuery = `
506
+ SELECT c.relname AS "table", a.attname AS "name",
507
+ format_type(a.atttypid, a.atttypmod) AS "declared",
508
+ b.typname AS "base", b.typtype AS "kind", b.typcategory AS "category",
509
+ a.attnotnull AS "notNull", pg_get_expr(d.adbin, d.adrelid) AS "defaultValue",
510
+ COALESCE(a.attnum = ANY (k.conkey), false) AS "primaryKey"
511
+ FROM pg_class c
512
+ JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped
513
+ JOIN pg_type t ON t.oid = a.atttypid
514
+ JOIN pg_type b ON b.oid = CASE WHEN t.typtype = 'd' THEN t.typbasetype ELSE t.oid END
515
+ LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = a.attnum
516
+ LEFT JOIN pg_constraint k ON k.conrelid = c.oid AND k.contype = 'p'
517
+ WHERE ${ownTables}
518
+ ORDER BY c.relname, a.attnum`;
519
+ /** Each table's columns and constraints as one line of text, to tell when a migration changed it. */
520
+ const definitionsQuery = `
521
+ SELECT c.relname AS "table",
522
+ (SELECT string_agg(concat_ws(' ', a.attname, format_type(a.atttypid, a.atttypmod),
523
+ a.attnotnull, pg_get_expr(d.adbin, d.adrelid)), ', ' ORDER BY a.attnum)
524
+ FROM pg_attribute a
525
+ LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
526
+ WHERE a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped) || ' | ' ||
527
+ COALESCE((SELECT string_agg(pg_get_constraintdef(k.oid), ', ' ORDER BY k.conname)
528
+ FROM pg_constraint k WHERE k.conrelid = c.oid), '') AS "definition"
529
+ FROM pg_class c
530
+ WHERE ${ownTables}`;
531
+ /** Each table's definition, by name. */
532
+ async function definitions(query) {
533
+ const rows = await query(definitionsQuery);
534
+ return new Map(rows.map((row) => [String(row.table), String(row.definition)]));
535
+ }
536
+ /** Every column of the current schema's tables, by table, in column order. */
537
+ async function columnsByTable(query) {
538
+ const byTable = /* @__PURE__ */ new Map();
539
+ for (const row of await query(columnsQuery)) {
540
+ const column = row;
541
+ const columns = byTable.get(column.table) ?? [];
542
+ columns.push(column);
543
+ byTable.set(column.table, columns);
544
+ }
545
+ return byTable;
546
+ }
547
+ //#endregion
548
+ //#region cli/adapters/postgresql/conventions.ts
549
+ /** Each base type an attribute holds, by its catalog name. */
550
+ const attributeTypes = {
551
+ int2: "integer",
552
+ int4: "integer",
553
+ int8: "integer",
554
+ float4: "real",
555
+ float8: "real",
556
+ bool: "boolean",
557
+ date: "datetime",
558
+ timestamp: "datetime",
559
+ timestamptz: "datetime",
560
+ json: "json",
561
+ jsonb: "json",
562
+ text: "string",
563
+ varchar: "string",
564
+ bpchar: "string",
565
+ citext: "string",
566
+ uuid: "string",
567
+ name: "string"
568
+ };
569
+ /** Why a column's type can't be an attribute, if it can't. */
570
+ function refusal(column, where) {
571
+ if (column.category === "A") return `${where}: arrays (${column.declared}) aren't supported; use a jsonb column, or a table`;
572
+ if (column.base === "numeric") return `${where}: numeric loses precision as a number; store money as integer cents (${column.name}_cents BIGINT)`;
573
+ return column.base === "bytea" ? `${where}: bytea columns aren't supported yet (#20)` : void 0;
574
+ }
575
+ /** A column's attribute type, and a note when it's a string for want of a better one. */
576
+ function typeOf(column, where) {
577
+ const type = attributeTypes[column.base];
578
+ if (type !== void 0) return { type };
579
+ if (column.kind === "e") return { type: "string" };
580
+ return {
581
+ type: "string",
582
+ note: `${where}: is ${column.declared}, so it's read as a string; override it in its Model if it holds another type`
583
+ };
584
+ }
585
+ /** A cast Postgres adds to a default: `::text`, `::character varying(40)`, `::mood`. */
586
+ const casts = String.raw`(?:::[\w ."]+(?:\([\d, ]+\))?)*`;
587
+ /** A default's literal text, with its casts taken off: `'it''s'::text` → `it's`, `1.5` → `1.5`. */
588
+ function literalText(sql) {
589
+ const quoted = new RegExp(`^'((?:[^']|'')*)'${casts}$`).exec(sql);
590
+ if (quoted !== null) return quoted[1].replaceAll("''", "'");
591
+ return new RegExp(String.raw`^\(?(-?\d+(?:\.\d+)?|true|false)\)?${casts}$`, "i").exec(sql)?.[1];
592
+ }
593
+ /** A number, when JavaScript holds it exactly. */
594
+ function numberDefault(text, type) {
595
+ if (!/^-?\d+(\.\d+)?$/.test(text)) return void 0;
596
+ const number = Number(text);
597
+ return type === "integer" && !Number.isSafeInteger(number) ? void 0 : { literal: number };
598
+ }
599
+ /** JSON's value, or a date's text, when it parses. */
600
+ function parsedDefault(text, type) {
601
+ if (type === "datetime") return Number.isNaN(Date.parse(text)) ? void 0 : { date: text };
602
+ try {
603
+ return { literal: JSON.parse(text) };
604
+ } catch {
605
+ return;
606
+ }
607
+ }
608
+ /** A literal default as a value of the attribute's type; undefined for a function or anything else. */
609
+ function literalDefault(sql, type) {
610
+ const text = sql === null ? void 0 : literalText(sql.trim());
611
+ if (text === void 0) return void 0;
612
+ if (type === "boolean") return /^(true|false)$/i.test(text) ? { literal: /^true$/i.test(text) } : void 0;
613
+ if (type === "integer" || type === "real") return numberDefault(text, type);
614
+ return type === "string" ? { literal: text } : parsedDefault(text, type);
615
+ }
616
+ /** A column's spec: nullability, a mapped column name, and its default or a key made in code. */
617
+ function specOf(column, type, attribute) {
618
+ const spec = { type };
619
+ if (column.notNull || column.primaryKey) spec.null = false;
620
+ if (underscore(attribute) !== column.name) spec.column = column.name;
621
+ const defaultValue = literalDefault(column.defaultValue, type);
622
+ if (defaultValue !== void 0) spec.default = defaultValue;
623
+ else if (column.primaryKey && type === "string") spec.generateId = true;
624
+ return spec;
625
+ }
626
+ /** A column as an attribute: its type, nullability and literal default, or why it can't be one. */
627
+ function convert(column) {
628
+ const where = `${column.table}.${column.name}`;
629
+ const error = refusal(column, where);
630
+ if (error !== void 0) return {
631
+ ok: false,
632
+ error
633
+ };
634
+ const { type, note } = typeOf(column, where);
635
+ const attribute = attributeName(column.name);
636
+ const spec = specOf(column, type, attribute);
637
+ return note === void 0 ? {
638
+ ok: true,
639
+ attribute,
640
+ spec
641
+ } : {
642
+ ok: true,
643
+ attribute,
644
+ spec,
645
+ note
646
+ };
647
+ }
648
+ //#endregion
649
+ //#region cli/adapters/postgresql/extensions.ts
650
+ /** The contrib extensions PGlite has its own build of, by the module it exports each from. */
651
+ const contrib = new Set("amcheck auto_explain bloom btree_gin btree_gist citext cube dict_int dict_xsyn earthdistance file_fdw fuzzystrmatch hstore intarray isn lo ltree moddatetime pageinspect pg_buffercache pg_freespacemap pg_stat_statements pg_surgery pg_trgm pg_visibility pg_walinspect pgcrypto seg tablefunc tcn tsm_system_rows tsm_system_time unaccent uuid_ossp".split(" "));
652
+ /** `CREATE EXTENSION [IF NOT EXISTS] name`, its name quoted or not. */
653
+ const createExtension = /\bcreate\s+extension\s+(?:if\s+not\s+exists\s+)?(?:"([^"]+)"|([\w-]+))/gi;
654
+ /** The extensions the migrations create, by name, in the order they first appear. */
655
+ function extensionsIn(migrations) {
656
+ const names = migrations.flatMap(({ sql }) => [...sql.matchAll(createExtension)].map((match) => (match[1] ?? match[2]).toLowerCase()));
657
+ return [...new Set(names)];
658
+ }
659
+ /** The PGlite module an extension's build is in (`uuid-ossp` → `uuid_ossp`), if it has one. */
660
+ function moduleOf(name) {
661
+ const module = name.replaceAll("-", "_");
662
+ return contrib.has(module) ? module : void 0;
663
+ }
664
+ /** PGlite's builds of the extensions the migrations create, as its `extensions` option takes them. */
665
+ async function pgliteExtensions(migrations) {
666
+ const loaded = {};
667
+ for (const name of extensionsIn(migrations)) {
668
+ const module = moduleOf(name);
669
+ if (module === void 0) continue;
670
+ loaded[module] = (await import(`@electric-sql/pglite/contrib/${module}`))[module];
671
+ }
672
+ return loaded;
673
+ }
674
+ //#endregion
675
+ //#region cli/adapters/postgresql/server-schema.ts
676
+ /**
677
+ * The same server's connection string, for another database on it; undefined when Node can't read
678
+ * it as a URL (a socket's `postgres://app@/shop`), whose message would show it, password and all.
679
+ */
680
+ function urlForDatabase(url, name) {
681
+ try {
682
+ const target = new URL(url);
683
+ target.pathname = `/${name}`;
684
+ return target.toString();
685
+ } catch {
686
+ return;
687
+ }
688
+ }
689
+ /** Why the url can't name another database on its server. */
690
+ const unreadableUrl = "the database's schemaUrl can't be read as a URL; write it as postgres://user:password@host/database";
691
+ /** Drops the temporary database and ends the admin client, which ends even when the drop fails. */
692
+ async function dropped(admin, name) {
693
+ try {
694
+ await admin.query({ text: `DROP DATABASE IF EXISTS ${name} WITH (FORCE)` });
695
+ } finally {
696
+ await admin.end();
697
+ }
698
+ }
699
+ /** Creates the database, or says why it couldn't. */
700
+ async function created(admin, name) {
701
+ try {
702
+ await admin.query({ text: `CREATE DATABASE ${name}` });
703
+ return;
704
+ } catch (error) {
705
+ return error.message;
706
+ }
707
+ }
708
+ /** The signals a person stops a command with: Ctrl-C, and a terminal's or a process manager's. */
709
+ const stops = [
710
+ "SIGINT",
711
+ "SIGTERM",
712
+ "SIGHUP"
713
+ ];
714
+ /** Each temporary database there now, by its drop, which runs once however often it's called. */
715
+ const open = /* @__PURE__ */ new Set();
716
+ /** Drops every temporary database there, then stops the command as the signal would have. */
717
+ function onSignal(signal) {
718
+ for (const stop of stops) process.off(stop, onSignal);
719
+ Promise.allSettled([...open].map((drop) => drop())).finally(() => process.kill(process.pid, signal));
720
+ }
721
+ /**
722
+ * Keeps a temporary database's drop while it's there, so a signal that stops the command drops
723
+ * it first (every one, when several databases are read at once); returns the drop, run once.
724
+ */
725
+ function tracked(drop) {
726
+ let running;
727
+ const once = () => running ??= drop();
728
+ if (open.size === 0) for (const stop of stops) process.on(stop, onSignal);
729
+ open.add(once);
730
+ return async () => {
731
+ open.delete(once);
732
+ if (open.size === 0) for (const stop of stops) process.off(stop, onSignal);
733
+ await once();
734
+ };
735
+ }
736
+ /** Starts the one transaction the migrations run in, or says why it couldn't, ending the client. */
737
+ async function begun(client) {
738
+ try {
739
+ await client.query({ text: "BEGIN" });
740
+ return;
741
+ } catch (error) {
742
+ await client.end().catch(() => {});
743
+ return error.message;
744
+ }
745
+ }
746
+ /**
747
+ * A new, empty database on the server `url` names, which closing drops; or why there's none. The
748
+ * migrations then create their extensions there, as they would on the real database, in one
749
+ * transaction that closing rolls back.
750
+ */
751
+ async function temporaryDatabase(url) {
752
+ const name = `active_record_schema_${randomUUID().replaceAll("-", "")}`;
753
+ const target = urlForDatabase(url, name);
754
+ if (target === void 0) return unreadableUrl;
755
+ const admin = await connected(url);
756
+ if (typeof admin === "string") return admin;
757
+ const drop = tracked(() => dropped(admin, name));
758
+ const refusal = await created(admin, name);
759
+ if (refusal !== void 0) {
760
+ await drop().catch(() => {});
761
+ return refusal;
762
+ }
763
+ const client = await connected(target);
764
+ if (typeof client === "string") {
765
+ await drop();
766
+ return client;
767
+ }
768
+ const failure = await begun(client);
769
+ if (failure !== void 0) {
770
+ await drop();
771
+ return failure;
772
+ }
773
+ return {
774
+ exec: async (sql) => void await client.query({ text: sql }),
775
+ query: async (sql) => (await client.query({ text: sql })).rows,
776
+ close: async () => {
777
+ try {
778
+ await client.query({ text: "ROLLBACK" });
779
+ } finally {
780
+ await client.end().catch(() => {});
781
+ await drop();
782
+ }
783
+ }
784
+ };
785
+ }
786
+ //#endregion
787
+ //#region cli/adapters/postgresql/schema.ts
788
+ /**
789
+ * An in-memory PGlite, loaded when a schema is first read, with the extensions it has builds of;
790
+ * or what to install.
791
+ */
792
+ async function pglite(migrations) {
793
+ const loaded = await pgliteModule();
794
+ if (typeof loaded === "string") return loaded;
795
+ const lite = new loaded.PGlite({ extensions: await pgliteExtensions(migrations) });
796
+ return {
797
+ exec: async (sql) => void await lite.exec(sql),
798
+ query: async (sql) => (await lite.query(sql)).rows,
799
+ close: () => lite.close()
800
+ };
801
+ }
802
+ /**
803
+ * Applies the migrations in order, noting which one last changed each table's columns or
804
+ * constraints. A migration that fails is reported by its file name.
805
+ */
806
+ async function applied(scratch, migrations) {
807
+ const changedBy = /* @__PURE__ */ new Map();
808
+ let before = await definitions(scratch.query);
809
+ for (const { name, sql } of migrations) {
810
+ try {
811
+ await scratch.exec(sql);
812
+ } catch (error) {
813
+ const { message } = error;
814
+ const missing = /^extension "([^"]+)" is not available/.exec(message)?.[1];
815
+ return {
816
+ error: `${name}: ${message}`,
817
+ migration: name,
818
+ ...missing !== void 0 && { missing }
819
+ };
820
+ }
821
+ const after = await definitions(scratch.query);
822
+ for (const [table, definition] of after) if (before.get(table) !== definition) changedBy.set(table, name);
823
+ before = after;
824
+ }
825
+ return { changedBy };
826
+ }
827
+ /** The error for a table without a primary key, saying what Postgres's keys look like. */
828
+ const missingKey = (name) => `${name}: no primary key; Active Record needs one (id UUID PRIMARY KEY, or id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY)`;
829
+ /** The tables read from the migrations' database, but the runner's own. */
830
+ async function tablesIn(scratch, changedBy, ownTable) {
831
+ return [...await columnsByTable(scratch.query)].filter(([name]) => name !== ownTable).map(([name, columns]) => ({
832
+ name,
833
+ columns,
834
+ lastChangedBy: changedBy.get(name),
835
+ keyType: columns.find((column) => column.primaryKey)?.declared
836
+ }));
837
+ }
838
+ /** The schema the migrations make on `scratch`, which is closed afterwards, even when it fails. */
839
+ async function readOn(scratch, migrations, migrationsTable) {
840
+ const failed = (error) => ({
841
+ ok: false,
842
+ errors: [error.message]
843
+ });
844
+ const read = await readFrom(scratch, migrations, migrationsTable).catch(failed);
845
+ const closing = await scratch.close().then(() => void 0, failed);
846
+ if (closing === void 0) return read;
847
+ return {
848
+ ok: false,
849
+ errors: [..."errors" in read ? read.errors : [], ...closing.errors]
850
+ };
851
+ }
852
+ /** The schema the migrations make on `scratch`, or the extension it couldn't load. */
853
+ async function readFrom(scratch, migrations, migrationsTable) {
854
+ const result = await applied(scratch, migrations);
855
+ if ("error" in result) {
856
+ if (result.missing === void 0) return {
857
+ ok: false,
858
+ errors: [result.error]
859
+ };
860
+ return {
861
+ migration: result.migration,
862
+ missing: result.missing
863
+ };
864
+ }
865
+ const tables = await tablesIn(scratch, result.changedBy, migrationsTable);
866
+ return generatedSchema(tables, {
867
+ convert,
868
+ missingKey
869
+ });
870
+ }
871
+ /**
872
+ * The schema read on the server the database's `schemaUrl` names, in a database of its own, for
873
+ * migrations that need an extension PGlite can't load. It's never the database's `url`: a read
874
+ * shouldn't reach a server the app uses unless it's asked to.
875
+ */
876
+ async function readOnServer(migrations, options, { migration, missing }) {
877
+ const url = connectionString(options.entry, "schemaUrl");
878
+ if (url === void 0) return {
879
+ ok: false,
880
+ errors: [`${migration}: PGlite can't load the extension ${missing}; set the database's schemaUrl in active-record.jsonc to a Postgres server that has it, where the schema is read in a database of its own`]
881
+ };
882
+ if (typeof url !== "string") return {
883
+ ok: false,
884
+ errors: [url.error]
885
+ };
886
+ const server = await temporaryDatabase(url);
887
+ if (typeof server === "string") return {
888
+ ok: false,
889
+ errors: [`Couldn't read the schema on ${hostOf(url)}: ${server}`]
890
+ };
891
+ const read = await readOn(server, migrations, options.migrationsTable ?? "schema_migrations");
892
+ if (!("ok" in read)) return {
893
+ ok: false,
894
+ errors: [`${read.migration}: extension "${read.missing}" is not available`]
895
+ };
896
+ if (!read.ok) return read;
897
+ const note = `PGlite can't load the extension ${missing}, so the schema was read on ${hostOf(url)} in a database of its own`;
898
+ return {
899
+ ...read,
900
+ notes: [...read.notes, note]
901
+ };
902
+ }
903
+ /**
904
+ * The tables a project's migrations make: applied in order to an in-memory PGlite, then read from
905
+ * its catalog, in the current schema. Views, other schemas and the migrations table are left out.
906
+ * Migrations that need an extension PGlite can't load are read on the server `schemaUrl` names.
907
+ */
908
+ async function schemaOf(migrations, options = {}) {
909
+ const versions = versionsOf(migrations.map((migration) => migration.name));
910
+ const refusal = typeof versions === "string" ? versions : ownTransactions(migrations);
911
+ if (refusal !== void 0) return {
912
+ ok: false,
913
+ errors: [refusal]
914
+ };
915
+ const table = options.migrationsTable ?? "schema_migrations";
916
+ const scratch = await pglite(migrations);
917
+ if (typeof scratch === "string") return {
918
+ ok: false,
919
+ errors: [scratch]
920
+ };
921
+ const read = await readOn(scratch, migrations, table);
922
+ return "ok" in read ? read : readOnServer(migrations, options, read);
923
+ }
924
+ //#endregion
925
+ //#region cli/adapters/postgresql/plugin.ts
926
+ /** Postgres, as the command line sees it: `active-record.jsonc`'s databases, PGlite's schema, and `pg`. */
927
+ const cli = {
928
+ name: "postgresql",
929
+ init,
930
+ databases: readDatabases,
931
+ readSchema: schemaOf,
932
+ migration,
933
+ remote: (chosen) => remoteTarget(chosen),
934
+ stateFolder: ({ configFile }) => join(dirname(configFile), "node_modules/.cache/active-record"),
935
+ open: (_cwd, chosen, options) => openDatabase(chosen, options),
936
+ migrate
937
+ };
938
+ //#endregion
939
+ export { cli };