@profullstack/sh1pt-migrate 0.0.0-stage → 0.1.15

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.
Files changed (78) hide show
  1. package/README.md +133 -2
  2. package/dist/apply.d.ts +65 -0
  3. package/dist/apply.d.ts.map +1 -0
  4. package/dist/apply.js +143 -0
  5. package/dist/apply.js.map +1 -0
  6. package/dist/engines/files.d.ts +37 -0
  7. package/dist/engines/files.d.ts.map +1 -0
  8. package/dist/engines/files.js +137 -0
  9. package/dist/engines/files.js.map +1 -0
  10. package/dist/engines/index.d.ts +20 -0
  11. package/dist/engines/index.d.ts.map +1 -0
  12. package/dist/engines/index.js +35 -0
  13. package/dist/engines/index.js.map +1 -0
  14. package/dist/engines/mysql.d.ts +17 -0
  15. package/dist/engines/mysql.d.ts.map +1 -0
  16. package/dist/engines/mysql.js +171 -0
  17. package/dist/engines/mysql.js.map +1 -0
  18. package/dist/engines/object-storage.d.ts +42 -0
  19. package/dist/engines/object-storage.d.ts.map +1 -0
  20. package/dist/engines/object-storage.js +197 -0
  21. package/dist/engines/object-storage.js.map +1 -0
  22. package/dist/engines/postgres.d.ts +34 -0
  23. package/dist/engines/postgres.d.ts.map +1 -0
  24. package/dist/engines/postgres.js +309 -0
  25. package/dist/engines/postgres.js.map +1 -0
  26. package/dist/engines/redis.d.ts +3 -0
  27. package/dist/engines/redis.d.ts.map +1 -0
  28. package/dist/engines/redis.js +87 -0
  29. package/dist/engines/redis.js.map +1 -0
  30. package/dist/engines/sqlite.d.ts +3 -0
  31. package/dist/engines/sqlite.d.ts.map +1 -0
  32. package/dist/engines/sqlite.js +113 -0
  33. package/dist/engines/sqlite.js.map +1 -0
  34. package/dist/exec.d.ts +31 -0
  35. package/dist/exec.d.ts.map +1 -0
  36. package/dist/exec.js +119 -0
  37. package/dist/exec.js.map +1 -0
  38. package/dist/index.d.ts +35 -0
  39. package/dist/index.d.ts.map +1 -0
  40. package/dist/index.js +31 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/plan.d.ts +115 -0
  43. package/dist/plan.d.ts.map +1 -0
  44. package/dist/plan.js +339 -0
  45. package/dist/plan.js.map +1 -0
  46. package/dist/platforms/index.d.ts +29 -0
  47. package/dist/platforms/index.d.ts.map +1 -0
  48. package/dist/platforms/index.js +51 -0
  49. package/dist/platforms/index.js.map +1 -0
  50. package/dist/platforms/managed.d.ts +41 -0
  51. package/dist/platforms/managed.d.ts.map +1 -0
  52. package/dist/platforms/managed.js +163 -0
  53. package/dist/platforms/managed.js.map +1 -0
  54. package/dist/platforms/railway.d.ts +29 -0
  55. package/dist/platforms/railway.d.ts.map +1 -0
  56. package/dist/platforms/railway.js +135 -0
  57. package/dist/platforms/railway.js.map +1 -0
  58. package/dist/platforms/ssh.d.ts +56 -0
  59. package/dist/platforms/ssh.d.ts.map +1 -0
  60. package/dist/platforms/ssh.js +151 -0
  61. package/dist/platforms/ssh.js.map +1 -0
  62. package/dist/platforms/supabase.d.ts +57 -0
  63. package/dist/platforms/supabase.d.ts.map +1 -0
  64. package/dist/platforms/supabase.js +102 -0
  65. package/dist/platforms/supabase.js.map +1 -0
  66. package/dist/staging.d.ts +27 -0
  67. package/dist/staging.d.ts.map +1 -0
  68. package/dist/staging.js +98 -0
  69. package/dist/staging.js.map +1 -0
  70. package/dist/transforms.d.ts +113 -0
  71. package/dist/transforms.d.ts.map +1 -0
  72. package/dist/transforms.js +179 -0
  73. package/dist/transforms.js.map +1 -0
  74. package/dist/types.d.ts +238 -0
  75. package/dist/types.d.ts.map +1 -0
  76. package/dist/types.js +79 -0
  77. package/dist/types.js.map +1 -0
  78. package/package.json +33 -4
@@ -0,0 +1,309 @@
1
+ import { quoteIdent, quoteLiteral } from '../transforms.js';
2
+ /**
3
+ * Moving a Postgres database.
4
+ *
5
+ * Supabase, Neon, Railway, RDS and a Postgres in a container on a dedicated
6
+ * box are all this engine. That is the point of splitting platforms from
7
+ * engines: the vendor decides where the connection string comes from, and this
8
+ * decides what to do with it.
9
+ *
10
+ * ## Why the custom format, and why not --clean
11
+ *
12
+ * `pg_dump -Fc` (custom) rather than plain SQL, because it is the only format
13
+ * `pg_restore` can parallelise and selectively restore, and because a 4.7 GB
14
+ * plain-text dump is unusable when one table fails. `--no-owner` and
15
+ * `--no-acl`, because the roles on a managed provider do not exist on the
16
+ * destination and a dump that tries to `ALTER OWNER TO supabase_admin` fails
17
+ * on every object.
18
+ *
19
+ * `--clean` is deliberately NOT passed. It would make a re-run idempotent,
20
+ * which sounds desirable, but it means a restore aimed at the wrong database
21
+ * silently drops what is there. A migration tool should not be one typo away
22
+ * from deleting production; an existing non-empty target is refused instead.
23
+ *
24
+ * ## The extension problem
25
+ *
26
+ * A dump records `CREATE EXTENSION pg_cron`, but an extension is a server
27
+ * feature, not data: if the destination image does not ship it, the restore
28
+ * fails partway, having already written some tables. Extensions are therefore
29
+ * read during inventory and surfaced as quirks so the planner warns before
30
+ * anything runs.
31
+ */
32
+ const DUMP = 'dump.pgc';
33
+ /** Read the DSN off a resource, failing loudly rather than connecting to a default. */
34
+ function dsn(r) {
35
+ const url = r.connection.url;
36
+ if (!url)
37
+ throw new Error(`postgres resource '${r.name}' has no connection.url`);
38
+ return url.reveal();
39
+ }
40
+ /**
41
+ * Postgres credentials go in the environment, never in argv.
42
+ *
43
+ * `ps` is world-readable on a normal box, so a password spliced into a command
44
+ * line is visible to every other user for as long as the dump runs — which for
45
+ * a migration is hours.
46
+ *
47
+ * These are libpq's own variables, which `pg_dump`, `pg_restore` and `psql`
48
+ * all read directly. That matters more than it looks: `exec` runs commands
49
+ * without a shell, so there is nothing to expand a `$VAR` written into an
50
+ * argument. Passing the connection through the environment is not merely
51
+ * tidier here, it is the only thing that works.
52
+ */
53
+ export function pgEnv(r) {
54
+ const raw = dsn(r);
55
+ let u;
56
+ try {
57
+ u = new URL(raw);
58
+ }
59
+ catch {
60
+ throw new Error(`postgres resource '${r.name}' has a connection.url that is not a URL`);
61
+ }
62
+ const env = {};
63
+ if (u.hostname)
64
+ env.PGHOST = decodeURIComponent(u.hostname);
65
+ if (u.port)
66
+ env.PGPORT = u.port;
67
+ if (u.username)
68
+ env.PGUSER = decodeURIComponent(u.username);
69
+ if (u.password)
70
+ env.PGPASSWORD = decodeURIComponent(u.password);
71
+ const database = u.pathname.replace(/^\//, '');
72
+ if (database)
73
+ env.PGDATABASE = decodeURIComponent(database);
74
+ // Managed providers almost universally require TLS, and libpq's default of
75
+ // `prefer` silently falls back to plaintext where it is not enforced.
76
+ env.PGSSLMODE = u.searchParams.get('sslmode') ?? 'require';
77
+ return env;
78
+ }
79
+ /**
80
+ * The timestamp column the delta sync keys on.
81
+ *
82
+ * This ends up interpolated into SQL, and it comes from a resource's metadata,
83
+ * which comes from a config file a person edits — so it is checked against a
84
+ * plain identifier rather than trusted. `psql -c` would happily run a second
85
+ * statement smuggled in here, against the production database the migration is
86
+ * reading from.
87
+ */
88
+ export function deltaColumn(r) {
89
+ const raw = r.metadata?.deltaColumns ?? 'created_at';
90
+ if (!/^[a-z_][a-z0-9_]*$/i.test(raw)) {
91
+ throw new Error(`'${raw}' is not a valid column name for the delta sync of '${r.name}'. Use a plain identifier.`);
92
+ }
93
+ return raw;
94
+ }
95
+ export const postgresEngine = {
96
+ kind: 'postgres',
97
+ requires: ['pg_dump', 'pg_restore', 'psql'],
98
+ async export(ctx, from) {
99
+ const path = `${from.id}/${DUMP}`;
100
+ ctx.log(`pg_dump ${from.name} → ${path}`);
101
+ if (ctx.dryRun) {
102
+ return [{ resourceId: from.id, kind: 'postgres', path }];
103
+ }
104
+ await ctx.exec('pg_dump', [
105
+ '--format=custom',
106
+ '--no-owner',
107
+ '--no-acl',
108
+ // Compresses inside the custom format; the wire is usually the
109
+ // bottleneck on a cloud-to-anywhere move, not the CPU.
110
+ '--compress=6',
111
+ '--file',
112
+ `${ctx.staging.dir}/${path}`,
113
+ ], { env: pgEnv(from), timeoutMs: 6 * 60 * 60 * 1000 });
114
+ const artifact = { resourceId: from.id, kind: 'postgres', path };
115
+ await ctx.staging.record(artifact);
116
+ return [artifact];
117
+ },
118
+ async import(ctx, to, artifacts) {
119
+ const dump = artifacts.find((a) => a.kind === 'postgres');
120
+ if (!dump)
121
+ throw new Error(`no postgres dump staged for '${to.name}'`);
122
+ if (ctx.dryRun) {
123
+ ctx.log(`would pg_restore into ${to.name}`);
124
+ return;
125
+ }
126
+ // Refuse to write into a database that already has user tables. Without
127
+ // this, re-running a half-finished migration against the wrong target is
128
+ // indistinguishable from the intended one until the duplicate-key errors
129
+ // start, by which point the restore is half applied.
130
+ const existing = await ctx.exec('psql', [
131
+ '--tuples-only',
132
+ '--no-align',
133
+ '--command',
134
+ "select count(*) from information_schema.tables where table_schema not in ('pg_catalog','information_schema')",
135
+ ], { env: pgEnv(to), check: false });
136
+ const tableCount = Number.parseInt(existing.stdout.trim(), 10);
137
+ if (Number.isFinite(tableCount) && tableCount > 0) {
138
+ throw new Error(`target database '${to.name}' already has ${tableCount} table(s). Refusing to restore over it — drop and recreate the database, or point at an empty one.`);
139
+ }
140
+ ctx.log(`pg_restore → ${to.name}`);
141
+ const res = await ctx.exec('pg_restore', [
142
+ '--no-owner',
143
+ '--no-acl',
144
+ // Parallel restore. Indexes dominate a large restore and they are
145
+ // perfectly parallel.
146
+ '--jobs=4',
147
+ // Keep going so ONE failed object (a missing extension, a role that
148
+ // does not exist) does not abandon a multi-hour restore. Errors are
149
+ // counted and surfaced below rather than swallowed.
150
+ '--exit-on-error=false',
151
+ `${ctx.staging.dir}/${dump.path}`,
152
+ ], { env: pgEnv(to), check: false, timeoutMs: 6 * 60 * 60 * 1000 });
153
+ if (res.code !== 0) {
154
+ const errors = res.stderr
155
+ .split('\n')
156
+ .filter((l) => l.includes('error:'))
157
+ .slice(0, 10);
158
+ ctx.log(`pg_restore finished with errors (${errors.length} shown):\n${errors.join('\n')}`, 'warn');
159
+ // A restore that produced errors is not automatically a failed
160
+ // migration — a missing extension on a replica, for instance — but it is
161
+ // never something to pass over silently.
162
+ if (errors.some((e) => /could not|does not exist|permission denied/i.test(e))) {
163
+ throw new Error(`pg_restore into '${to.name}' reported errors that will leave the database incomplete. First: ${errors[0] ?? 'unknown'}`);
164
+ }
165
+ }
166
+ },
167
+ /**
168
+ * Re-copy rows written during the bulk dump.
169
+ *
170
+ * There is no general delta for Postgres without logical replication, and
171
+ * standing up a replication slot against a managed provider mid-migration is
172
+ * its own project. What works in practice, and what the crawlproof migration
173
+ * actually did, is narrower: for tables that carry a timestamp column, copy
174
+ * the rows newer than the dump. That covers append-heavy tables (events,
175
+ * impressions, logs) which are exactly the ones that keep being written
176
+ * while a long dump runs.
177
+ *
178
+ * It does NOT cover updates to old rows or deletes. The planner says so, and
179
+ * the honest use of this is: freeze writes to anything that mutates history,
180
+ * and let the append-only tables catch up.
181
+ */
182
+ async delta(ctx, from, since) {
183
+ const columns = deltaColumn(from);
184
+ const path = `${from.id}/delta-${since.toISOString().replace(/[:.]/g, '')}.sql`;
185
+ ctx.log(`delta for ${from.name} on ${columns} since ${since.toISOString()}`);
186
+ if (ctx.dryRun)
187
+ return [{ resourceId: from.id, kind: 'postgres', path }];
188
+ /*
189
+ * Find tables that actually have the timestamp column rather than assuming
190
+ * a schema. A table without one cannot be delta'd and is reported.
191
+ *
192
+ * Schema and table come back as separate fields rather than pre-joined
193
+ * with a dot, so each can be quoted independently below. Joining them here
194
+ * would make `public.user` a string that cannot be quoted correctly —
195
+ * quoting the whole thing gives `"public.user"`, a single identifier with
196
+ * a dot in its name, which is a different table that does not exist.
197
+ */
198
+ const found = await ctx.exec('psql', [
199
+ '--tuples-only',
200
+ '--no-align',
201
+ '--field-separator=|',
202
+ '--command',
203
+ `select table_schema, table_name from information_schema.columns
204
+ where column_name = ${quoteLiteral(columns)}
205
+ and table_schema not in ('pg_catalog','information_schema')
206
+ order by 1, 2`,
207
+ ], { env: pgEnv(from) });
208
+ const tables = found.stdout
209
+ .split('\n')
210
+ .map((l) => l.trim())
211
+ .filter(Boolean)
212
+ .map((l) => {
213
+ const [schema, table] = l.split('|');
214
+ return schema && table ? { schema, table } : undefined;
215
+ })
216
+ .filter((t) => Boolean(t));
217
+ if (!tables.length) {
218
+ ctx.log(`no table has a '${columns}' column; nothing can be delta-synced`, 'warn');
219
+ return [];
220
+ }
221
+ const artifacts = [];
222
+ for (const { schema, table } of tables) {
223
+ const label = `${schema}.${table}`;
224
+ const out = `${from.id}/delta-${label.replace(/[^\w]/g, '_')}.csv`;
225
+ /*
226
+ * Every identifier is quoted. These names come from information_schema
227
+ * so they are real tables rather than attacker input, but a table called
228
+ * `user` or `order` is a reserved word and an unquoted reference to it is
229
+ * a syntax error partway through a cutover — and a name containing a
230
+ * quote or a space simply does not parse. Quoting costs nothing and
231
+ * removes the class.
232
+ */
233
+ await ctx.exec('psql', [
234
+ '--command',
235
+ `\\copy (select * from ${quoteIdent(schema)}.${quoteIdent(table)} where ${quoteIdent(columns)} > ${quoteLiteral(since.toISOString())}) to ${quoteLiteral(`${ctx.staging.dir}/${out}`)} with csv header`,
236
+ ], { env: pgEnv(from) });
237
+ const artifact = {
238
+ resourceId: from.id,
239
+ kind: 'postgres',
240
+ path: out,
241
+ metadata: { table: label, mode: 'delta-csv' },
242
+ };
243
+ await ctx.staging.record(artifact);
244
+ artifacts.push(artifact);
245
+ }
246
+ return artifacts;
247
+ },
248
+ /**
249
+ * Compare row counts per table.
250
+ *
251
+ * Not a checksum — comparing 4.7 GB twice over the wire costs as much as the
252
+ * migration did. Row counts per table catch the failures that actually
253
+ * happen: a table that restored empty, a restore that stopped partway.
254
+ */
255
+ async verify(ctx, from, to) {
256
+ if (ctx.dryRun)
257
+ return { ok: true, checks: ['dry run: not compared'], problems: [] };
258
+ const countsQuery = `select table_schema||'.'||table_name as t,
259
+ (xpath('/row/c/text()', query_to_xml(format('select count(*) as c from %I.%I', table_schema, table_name), false, true, '')))[1]::text::bigint as n
260
+ from information_schema.tables
261
+ where table_type = 'BASE TABLE' and table_schema not in ('pg_catalog','information_schema')
262
+ order by 1`;
263
+ const read = async (r) => {
264
+ const res = await ctx.exec('psql', ['--tuples-only', '--no-align', '--field-separator=|', '--command', countsQuery], { env: pgEnv(r) });
265
+ const map = new Map();
266
+ for (const line of res.stdout.split('\n')) {
267
+ const [t, n] = line.split('|');
268
+ if (t && n !== undefined)
269
+ map.set(t.trim(), Number.parseInt(n, 10));
270
+ }
271
+ return map;
272
+ };
273
+ const [a, b] = await Promise.all([read(from), read(to)]);
274
+ const checks = [];
275
+ const problems = [];
276
+ for (const [table, sourceCount] of a) {
277
+ const targetCount = b.get(table);
278
+ if (targetCount === undefined) {
279
+ problems.push(`${table}: missing on the target`);
280
+ continue;
281
+ }
282
+ checks.push(`${table}: ${sourceCount} → ${targetCount}`);
283
+ // The target may legitimately have MORE rows once it is live and the
284
+ // source is frozen; fewer is always wrong.
285
+ if (targetCount < sourceCount) {
286
+ problems.push(`${table}: ${sourceCount} rows on the source, ${targetCount} on the target`);
287
+ }
288
+ }
289
+ for (const table of b.keys()) {
290
+ if (!a.has(table))
291
+ checks.push(`${table}: target only`);
292
+ }
293
+ return { ok: problems.length === 0, checks, problems };
294
+ },
295
+ };
296
+ /**
297
+ * The extensions a database uses, for the inventory's quirks.
298
+ *
299
+ * Exported so a platform can call it while building its inventory: the
300
+ * platform knows the DSN, this knows the question worth asking.
301
+ */
302
+ export async function postgresExtensions(ctx, r) {
303
+ const res = await ctx.exec('psql', ['--tuples-only', '--no-align', '--command',
304
+ "select extname from pg_extension where extname not in ('plpgsql') order by 1"], { env: pgEnv(r), check: false });
305
+ if (res.code !== 0)
306
+ return [];
307
+ return res.stdout.split('\n').map((l) => l.trim()).filter(Boolean);
308
+ }
309
+ //# sourceMappingURL=postgres.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres.js","sourceRoot":"","sources":["../../src/engines/postgres.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAG5D;;;;;;;;;;;;;;;;;;;;;;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KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IAC9B,OAAO,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;AACrE,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { Engine } from '../types.js';
2
+ export declare const redisEngine: Engine;
3
+ //# sourceMappingURL=redis.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redis.d.ts","sourceRoot":"","sources":["../../src/engines/redis.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAY,MAAM,EAAyC,MAAM,aAAa,CAAC;AAiC3F,eAAO,MAAM,WAAW,EAAE,MAgEzB,CAAC"}
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Moving a Redis.
3
+ *
4
+ * Usually you should not. Redis is a cache far more often than it is a
5
+ * database, and the right migration for a cache is an empty one: point the new
6
+ * app at a new Redis and let it fill. Copying a cache moves stale entries and
7
+ * costs downtime for data that is worthless by definition.
8
+ *
9
+ * It is here because sometimes it is not a cache — a BullMQ queue with jobs
10
+ * waiting in it, a session store where copying nothing logs every user out.
11
+ * Those are real, so the engine exists, and the planner surfaces the question
12
+ * rather than deciding for you.
13
+ *
14
+ * There is no delta. A key written during the copy is simply missed, which is
15
+ * exactly why queues and sessions want the source stopped first. The planner
16
+ * warns about that because `delta` is absent.
17
+ */
18
+ const DUMP = 'dump.rdb';
19
+ function redisArgs(r) {
20
+ const url = r.connection.url?.reveal();
21
+ if (!url)
22
+ throw new Error(`redis resource '${r.name}' has no connection.url`);
23
+ // redis-cli takes the whole URL, and unlike libpq there is no environment
24
+ // variable for it. The password is therefore visible in `ps` for as long as
25
+ // the command runs, which for --rdb is the length of the copy. Nothing can
26
+ // be done about that from here beyond keeping the window short; it is noted
27
+ // so nobody assumes otherwise.
28
+ return ['-u', url];
29
+ }
30
+ export const redisEngine = {
31
+ kind: 'redis',
32
+ requires: ['redis-cli'],
33
+ async export(ctx, from) {
34
+ const path = `${from.id}/${DUMP}`;
35
+ ctx.log(`redis --rdb ${from.name}`);
36
+ if (ctx.dryRun)
37
+ return [{ resourceId: from.id, kind: 'redis', path }];
38
+ // --rdb asks the server for a full sync and writes the RDB the replica
39
+ // would have received, which is consistent at a point in time. Reading
40
+ // keys with SCAN+DUMP instead is not: keys move under you as you walk.
41
+ await ctx.exec('redis-cli', [...redisArgs(from), '--rdb', `${ctx.staging.dir}/${path}`], {
42
+ timeoutMs: 2 * 60 * 60 * 1000,
43
+ });
44
+ const artifact = { resourceId: from.id, kind: 'redis', path };
45
+ await ctx.staging.record(artifact);
46
+ return [artifact];
47
+ },
48
+ /**
49
+ * There is no supported way to push an RDB into a running managed Redis, so
50
+ * this refuses rather than pretending.
51
+ *
52
+ * A self-hosted target takes the file directly: stop the server, drop the
53
+ * RDB in its data directory, start it. That is a host operation rather than
54
+ * a client one, so it is surfaced as an instruction instead of being done
55
+ * badly over the wire.
56
+ */
57
+ async import(ctx, to, artifacts) {
58
+ const dump = artifacts.find((a) => a.kind === 'redis');
59
+ if (!dump)
60
+ throw new Error(`no redis dump staged for '${to.name}'`);
61
+ const dataDir = to.connection.dataDir?.reveal();
62
+ if (!dataDir) {
63
+ throw new Error(`Redis cannot be loaded over the wire. Copy ${dump.path} to the target's data directory as dump.rdb while the server is stopped, then start it. Set connection.dataDir on the target to have this done for you.`);
64
+ }
65
+ if (ctx.dryRun) {
66
+ ctx.log(`would place ${dump.path} at ${dataDir}/dump.rdb`);
67
+ return;
68
+ }
69
+ await ctx.exec('cp', [`${ctx.staging.dir}/${dump.path}`, `${dataDir}/dump.rdb`]);
70
+ ctx.log(`placed dump.rdb in ${dataDir}; restart the target Redis to load it`, 'warn');
71
+ },
72
+ async verify(ctx, from, to) {
73
+ if (ctx.dryRun)
74
+ return { ok: true, checks: ['dry run: not compared'], problems: [] };
75
+ const size = async (r) => {
76
+ const res = await ctx.exec('redis-cli', [...redisArgs(r), 'dbsize'], { check: false });
77
+ return Number.parseInt(res.stdout.trim(), 10) || 0;
78
+ };
79
+ const [a, b] = await Promise.all([size(from), size(to)]);
80
+ return {
81
+ ok: b >= a,
82
+ checks: [`keys: ${a} → ${b}`],
83
+ problems: b < a ? [`${a - b} key(s) missing on the target`] : [],
84
+ };
85
+ },
86
+ };
87
+ //# sourceMappingURL=redis.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redis.js","sourceRoot":"","sources":["../../src/engines/redis.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;GAgBG;AAEH,MAAM,IAAI,GAAG,UAAU,CAAC;AAExB,SAAS,SAAS,CAAC,CAAW;IAC5B,MAAM,GAAG,GAAG,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,CAAC;IACvC,IAAI,CAAC,GAAG;QAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC,IAAI,yBAAyB,CAAC,CAAC;IAC9E,0EAA0E;IAC1E,4EAA4E;IAC5E,2EAA2E;IAC3E,4EAA4E;IAC5E,+BAA+B;IAC/B,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;AACrB,CAAC;AAED,MAAM,CAAC,MAAM,WAAW,GAAW;IACjC,IAAI,EAAE,OAAO;IACb,QAAQ,EAAE,CAAC,WAAW,CAAC;IAEvB,KAAK,CAAC,MAAM,CAAC,GAAkB,EAAE,IAAc;QAC7C,MAAM,IAAI,GAAG,GAAG,IAAI,CAAC,EAAE,IAAI,IAAI,EAAE,CAAC;QAClC,GAAG,CAAC,GAAG,CAAC,eAAe,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;QACpC,IAAI,GAAG,CAAC,MAAM;YAAE,OAAO,CAAC,EAAE,UAAU,EAAE,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;QAEtE,uEAAuE;QACvE,uEAA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.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite.d.ts","sourceRoot":"","sources":["../../src/engines/sqlite.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAY,MAAM,EAAyC,MAAM,aAAa,CAAC;AAsC3F,eAAO,MAAM,YAAY,EAAE,MAmF1B,CAAC"}
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Moving a SQLite or libSQL database.
3
+ *
4
+ * Turso is libSQL, which is SQLite with a server in front, and a local
5
+ * `app.db` is SQLite with nothing in front. Both dump to the same SQL text,
6
+ * which is why they are one engine — and why Turso→dedicated and
7
+ * dedicated→Turso are the same code path.
8
+ *
9
+ * The dump is plain SQL rather than a file copy. Copying the file works for a
10
+ * local database and not at all for a hosted one, and a SQLite file copied
11
+ * while something is writing to it is a corrupt file rather than an error. The
12
+ * text dump is slower and always correct.
13
+ *
14
+ * Note the `.dump` output includes `PRAGMA foreign_keys=OFF` and wraps in a
15
+ * transaction on its own, which is what lets the rows load in whatever order
16
+ * the dump emitted them.
17
+ */
18
+ const DUMP = 'dump.sql';
19
+ /** Turso's CLI talks to a named database; plain SQLite takes a file path. */
20
+ function isTurso(r) {
21
+ return Boolean(r.connection.tursoDatabase) || r.metadata?.platform === 'turso';
22
+ }
23
+ function tursoEnv(r) {
24
+ const token = r.connection.authToken?.reveal();
25
+ return token ? { TURSO_API_TOKEN: token } : {};
26
+ }
27
+ function filePath(r) {
28
+ const p = r.connection.path?.reveal();
29
+ if (!p)
30
+ throw new Error(`sqlite resource '${r.name}' has no connection.path`);
31
+ return p;
32
+ }
33
+ export const sqliteEngine = {
34
+ kind: 'sqlite',
35
+ /*
36
+ * `sqlite3` only. Which binary is needed actually depends on the resource —
37
+ * a Turso database is reached with `turso`, a file with `sqlite3` — but
38
+ * `requires` is a property of the engine, not of one side of one migration.
39
+ * Declaring the union would block a file-to-file move on a missing Turso CLI
40
+ * nobody needs, so the Turso side is checked at the point of use instead and
41
+ * fails with a message naming the binary.
42
+ */
43
+ requires: ['sqlite3'],
44
+ async export(ctx, from) {
45
+ const path = `${from.id}/${DUMP}`;
46
+ ctx.log(`dumping ${from.name} → ${path}`);
47
+ if (ctx.dryRun)
48
+ return [{ resourceId: from.id, kind: 'sqlite', path }];
49
+ const out = `${ctx.staging.dir}/${path}`;
50
+ if (isTurso(from)) {
51
+ const db = from.connection.tursoDatabase.reveal();
52
+ await ctx.exec('turso', ['db', 'shell', db, '.dump'], {
53
+ env: tursoEnv(from),
54
+ timeoutMs: 2 * 60 * 60 * 1000,
55
+ stdoutFile: out,
56
+ });
57
+ }
58
+ else {
59
+ await ctx.exec('sqlite3', [filePath(from), '.dump'], {
60
+ timeoutMs: 2 * 60 * 60 * 1000,
61
+ stdoutFile: out,
62
+ });
63
+ }
64
+ const artifact = { resourceId: from.id, kind: 'sqlite', path };
65
+ await ctx.staging.record(artifact);
66
+ return [artifact];
67
+ },
68
+ async import(ctx, to, artifacts) {
69
+ const dump = artifacts.find((a) => a.kind === 'sqlite');
70
+ if (!dump)
71
+ throw new Error(`no sqlite dump staged for '${to.name}'`);
72
+ if (ctx.dryRun) {
73
+ ctx.log(`would load ${dump.path} into ${to.name}`);
74
+ return;
75
+ }
76
+ const file = `${ctx.staging.dir}/${dump.path}`;
77
+ if (isTurso(to)) {
78
+ const db = to.connection.tursoDatabase.reveal();
79
+ await ctx.exec('turso', ['db', 'shell', db], {
80
+ env: tursoEnv(to),
81
+ timeoutMs: 2 * 60 * 60 * 1000,
82
+ stdinFile: file,
83
+ });
84
+ }
85
+ else {
86
+ await ctx.exec('sqlite3', [filePath(to), `.read ${file}`], {
87
+ timeoutMs: 2 * 60 * 60 * 1000,
88
+ });
89
+ }
90
+ },
91
+ async verify(ctx, from, to) {
92
+ if (ctx.dryRun)
93
+ return { ok: true, checks: ['dry run: not compared'], problems: [] };
94
+ const countTables = async (r) => {
95
+ const sql = "select name from sqlite_master where type='table' and name not like 'sqlite_%' order by 1";
96
+ const res = isTurso(r)
97
+ ? await ctx.exec('turso', ['db', 'shell', r.connection.tursoDatabase.reveal(), sql], {
98
+ env: tursoEnv(r),
99
+ check: false,
100
+ })
101
+ : await ctx.exec('sqlite3', [filePath(r), sql], { check: false });
102
+ return res.stdout.split('\n').map((l) => l.trim()).filter(Boolean);
103
+ };
104
+ const [a, b] = await Promise.all([countTables(from), countTables(to)]);
105
+ const missing = a.filter((t) => !b.includes(t));
106
+ return {
107
+ ok: missing.length === 0,
108
+ checks: [`tables: ${a.length} → ${b.length}`],
109
+ problems: missing.map((t) => `${t}: missing on the target`),
110
+ };
111
+ },
112
+ };
113
+ //# sourceMappingURL=sqlite.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite.js","sourceRoot":"","sources":["../../src/engines/sqlite.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;GAgBG;AAEH,MAAM,IAAI,GAAG,UAAU,CAAC;AAExB,6EAA6E;AAC7E,SAAS,OAAO,CAAC,CAAW;IAC1B,OAAO,OAAO,CAAC,CAAC,CAAC,UAAU,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,QAAQ,KAAK,OAAO,CAAC;AACjF,CAAC;AAED,SAAS,QAAQ,CAAC,CAAW;IAC3B,MAAM,KAAK,GAAG,CAAC,CAAC,UAAU,CAAC,SAAS,EAAE,MAAM,EAAE,CAAC;IAC/C,OAAO,KAAK,CAAC,CAAC,CAAC,EAAE,eAAe,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;AACjD,CAAC;AAED,SAAS,QAAQ,CAAC,CAAW;IAC3B,MAAM,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC;IACtC,IAAI,CAAC,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC,IAAI,0BAA0B,CAAC,CAAC;IAC9E,OAAO,CAAC,CAAC;AACX,CAAC;AAED,MAAM,CAAC,MAAM,YAAY,GAAW;IAClC,IAAI,E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,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;QAChD,OAAO;YACL,EAAE,EAAE,OAAO,CAAC,MAAM,KAAK,CAAC;YACxB,MAAM,EAAE,CAAC,WAAW,CAAC,CAAC,MAAM,MAAM,CAAC,CAAC,MAAM,EAAE,CAAC;YAC7C,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,yBAAyB,CAAC;SAC5D,CAAC;IACJ,CAAC;CACF,CAAC"}
package/dist/exec.d.ts ADDED
@@ -0,0 +1,31 @@
1
+ import type { ExecOptions, ExecResult } from './types.js';
2
+ /**
3
+ * Running an external command.
4
+ *
5
+ * The real implementation behind the `exec` every engine receives. It is
6
+ * injected rather than imported so the engines can be tested without any of
7
+ * the tools installed, and so a dry run can be genuinely inert.
8
+ *
9
+ * `spawn` without a shell, always. Engines build argument arrays from
10
+ * connection strings, bucket names and paths, all of which come from config a
11
+ * person edits — running those through a shell would make a bucket named
12
+ * `; rm -rf /` a working attack and a path with a space a silent bug. The
13
+ * cost is that `>` and `<` do not work, which is why redirection is an option
14
+ * rather than a character in the argument list.
15
+ */
16
+ export declare function createExec(opts?: {
17
+ log?: (msg: string) => void;
18
+ }): (cmd: string, args: string[], options?: ExecOptions) => Promise<ExecResult>;
19
+ /**
20
+ * An exec that records instead of running, for `--dry-run`.
21
+ *
22
+ * A dry run has to be genuinely inert: the point is to be safe to run against
23
+ * production, and an engine that shells out "just to look" is not.
24
+ */
25
+ export declare function recordingExec(recorded?: string[][]): {
26
+ exec: (cmd: string, args: string[]) => Promise<ExecResult>;
27
+ recorded: string[][];
28
+ };
29
+ /** Which of these binaries are on PATH, for the planner's preflight check. */
30
+ export declare function availableBinaries(names: string[]): Promise<Set<string>>;
31
+ //# sourceMappingURL=exec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exec.d.ts","sourceRoot":"","sources":["../src/exec.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE1D;;;;;;;;;;;;;GAaG;AACH,wBAAgB,UAAU,CAAC,IAAI,GAAE;IAAE,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAA;CAAO,IAEjE,KAAK,MAAM,EACX,MAAM,MAAM,EAAE,EACd,UAAS,WAAgB,KACxB,OAAO,CAAC,UAAU,CAAC,CA6EvB;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,QAAQ,GAAE,MAAM,EAAE,EAAO;gBAC5B,MAAM,QAAQ,MAAM,EAAE,KAAG,OAAO,CAAC,UAAU,CAAC;;EAKtE;AAED,8EAA8E;AAC9E,wBAAsB,iBAAiB,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAc7E"}