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