@pgpmjs/import 0.1.1

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/esm/import.js ADDED
@@ -0,0 +1,547 @@
1
+ import { pathFor } from '@pgpmjs/naming-spec';
2
+ import { classifyStatements, loadModule, regenerateScripts, restructureExportRows } from '@pgpmjs/transform';
3
+ import { copyBlockToInsert, copyTargetOf } from './dump-source';
4
+ export const MISC_CHANGE_PATH = 'misc/statements';
5
+ const stringVal = (node) => typeof node?.String?.sval === 'string' ? node.String.sval : null;
6
+ const namesOf = (nodes) => (nodes ?? []).map(stringVal).filter((s) => s !== null);
7
+ const hostKey = (schema, name) => `${schema ?? ''}.${name}`;
8
+ const keyOfParts = (parts) => {
9
+ if (parts.length === 0)
10
+ return null;
11
+ if (parts.length === 1)
12
+ return hostKey(null, parts[0]);
13
+ return hostKey(parts[0], parts[1]);
14
+ };
15
+ /** Comment object types whose name parts end with a sub-object segment. */
16
+ const COMMENT_SUBOBJECT_TYPES = new Set([
17
+ 'OBJECT_COLUMN',
18
+ 'OBJECT_TRIGGER',
19
+ 'OBJECT_POLICY',
20
+ 'OBJECT_RULE',
21
+ 'OBJECT_TABCONSTRAINT'
22
+ ]);
23
+ /** Resolve the host object a COMMENT statement targets. */
24
+ const commentHostOf = (stmt) => {
25
+ const comment = stmt.CommentStmt;
26
+ if (!comment)
27
+ return null;
28
+ const { objtype, object } = comment;
29
+ if (!object)
30
+ return null;
31
+ if (object.String)
32
+ return hostKey(null, object.String.sval);
33
+ if (object.TypeName)
34
+ return keyOfParts(namesOf(object.TypeName.names));
35
+ if (object.ObjectWithArgs)
36
+ return keyOfParts(namesOf(object.ObjectWithArgs.objname));
37
+ if (object.List) {
38
+ let parts = namesOf(object.List.items);
39
+ if (COMMENT_SUBOBJECT_TYPES.has(objtype))
40
+ parts = parts.slice(0, -1);
41
+ return keyOfParts(parts);
42
+ }
43
+ return null;
44
+ };
45
+ /** Resolve the host object an ALTER ... OWNER TO statement targets. */
46
+ const ownerHostOf = (stmt) => {
47
+ const alter = stmt.AlterOwnerStmt;
48
+ if (!alter?.object)
49
+ return null;
50
+ const { object } = alter;
51
+ if (object.String)
52
+ return hostKey(null, object.String.sval);
53
+ if (object.TypeName)
54
+ return keyOfParts(namesOf(object.TypeName.names));
55
+ if (object.ObjectWithArgs)
56
+ return keyOfParts(namesOf(object.ObjectWithArgs.objname));
57
+ if (object.List)
58
+ return keyOfParts(namesOf(object.List.items));
59
+ return null;
60
+ };
61
+ /** Resolve the host object a GRANT/REVOKE statement targets. */
62
+ const grantHostOf = (stmt) => {
63
+ const grant = stmt.GrantStmt;
64
+ if (!grant?.objects?.length)
65
+ return null;
66
+ const first = grant.objects[0];
67
+ if (first.String)
68
+ return hostKey(null, first.String.sval);
69
+ if (first.RangeVar) {
70
+ return hostKey(first.RangeVar.schemaname ?? null, first.RangeVar.relname);
71
+ }
72
+ if (first.ObjectWithArgs)
73
+ return keyOfParts(namesOf(first.ObjectWithArgs.objname));
74
+ return null;
75
+ };
76
+ /**
77
+ * `ALTER SEQUENCE ... OWNED BY table.column` must ride the *table* change:
78
+ * the serial table's default already depends on the sequence, so attaching
79
+ * OWNED BY to the sequence change would create a cycle.
80
+ */
81
+ const sequenceOwnedByHostOf = (stmt) => {
82
+ const options = stmt.AlterSeqStmt?.options ?? [];
83
+ for (const opt of options) {
84
+ if (opt?.DefElem?.defname !== 'owned_by')
85
+ continue;
86
+ const parts = namesOf(opt.DefElem.arg?.List?.items);
87
+ if (parts.length >= 2)
88
+ return keyOfParts(parts.slice(0, -1));
89
+ }
90
+ return null;
91
+ };
92
+ /** The host object a rider statement (no creates) attaches to, if resolvable. */
93
+ const riderHostOf = (facts) => {
94
+ if (facts.references.length > 0) {
95
+ const ref = facts.references[0];
96
+ return hostKey(ref.schema, ref.name);
97
+ }
98
+ if (!facts.stmt)
99
+ return null;
100
+ if (facts.nodeTag === 'CommentStmt')
101
+ return commentHostOf(facts.stmt);
102
+ if (facts.nodeTag === 'GrantStmt')
103
+ return grantHostOf(facts.stmt);
104
+ if (facts.nodeTag === 'AlterOwnerStmt')
105
+ return ownerHostOf(facts.stmt);
106
+ return null;
107
+ };
108
+ /**
109
+ * Order a change's statements creates-first (stable): granularity folding
110
+ * can re-emit a folded CREATE after riders (grants, owners, comments) that
111
+ * were originally adjacent to the unfolded one.
112
+ */
113
+ const reorderChangeStatements = (content) => {
114
+ const facts = classifyStatements(content);
115
+ if (facts.length < 2)
116
+ return content;
117
+ const isCreate = (f) => !f.nodeTag.startsWith('Alter') && f.nodeTag !== 'GrantStmt' && f.nodeTag !== 'CommentStmt';
118
+ const creates = facts.filter(isCreate);
119
+ const riders = facts.filter(f => !isCreate(f));
120
+ const ordered = [...creates, ...riders];
121
+ if (ordered.every((f, i) => f === facts[i]))
122
+ return content;
123
+ return ordered.map(f => statementText(content, f)).join('\n\n') + '\n';
124
+ };
125
+ /**
126
+ * Order a revert's statements drops-last (stable), mirroring the deploy
127
+ * reorder: REVOKEs and other inverses must run before the host object is
128
+ * dropped. Non-statement note lines (e.g. "-- revert not derivable") are
129
+ * preserved at the end.
130
+ */
131
+ const reorderRevertStatements = (content) => {
132
+ const facts = classifyStatements(content);
133
+ if (facts.length < 2)
134
+ return content;
135
+ const isDrop = (f) => f.nodeTag.startsWith('Drop');
136
+ const ordered = [...facts.filter(f => !isDrop(f)), ...facts.filter(isDrop)];
137
+ if (ordered.every((f, i) => f === facts[i]))
138
+ return content;
139
+ let leftover = content;
140
+ for (const f of facts) {
141
+ leftover = leftover.replace(content.slice(f.span.start, f.span.start + f.span.len), '');
142
+ }
143
+ const notes = leftover
144
+ .split('\n')
145
+ .map(line => line.trim())
146
+ .filter(line => line.startsWith('--'));
147
+ return [...ordered.map(f => statementText(content, f)), ...notes].join('\n\n') + '\n';
148
+ };
149
+ const SET_CONFIG = /^SELECT\s+(pg_catalog\.)?set_config\s*\(/i;
150
+ const SETVAL = /^SELECT\s+(pg_catalog\.)?setval\s*\(\s*'([^']+)'/i;
151
+ const isPreamble = (facts, text) => facts.nodeTag === 'VariableSetStmt' ||
152
+ (facts.nodeTag === 'SelectStmt' && SET_CONFIG.test(text));
153
+ const statementText = (sql, facts) => {
154
+ const text = sql.slice(facts.span.start, facts.span.start + facts.span.len).trim();
155
+ return text.endsWith(';') ? text : `${text};`;
156
+ };
157
+ const seedVerify = (schema, name) => {
158
+ const target = schema ? `${schema}.${name}` : name;
159
+ return [
160
+ 'DO $$ BEGIN',
161
+ ` IF NOT EXISTS (SELECT 1 FROM ${target}) THEN`,
162
+ ` RAISE EXCEPTION 'no seed rows in ${target}';`,
163
+ ' END IF;',
164
+ 'END $$;'
165
+ ].join('\n');
166
+ };
167
+ const seedRevert = (schema, name) => {
168
+ const target = schema ? `${schema}.${name}` : name;
169
+ return `DELETE FROM ${target};`;
170
+ };
171
+ /**
172
+ * Stable topological sort by intra-module deps: pg_dump orders objects
173
+ * alphabetically (orders before users), but pgpm deploys in plan order, so
174
+ * prerequisites must be written first.
175
+ */
176
+ const sortRowsByDeps = (rows) => {
177
+ const byName = new Map(rows.map(row => [row.deploy, row]));
178
+ const sorted = [];
179
+ const state = new Map();
180
+ const visit = (row) => {
181
+ const mark = state.get(row.deploy);
182
+ if (mark === 'done')
183
+ return;
184
+ if (mark === 'visiting')
185
+ return; // cycle: keep input order
186
+ state.set(row.deploy, 'visiting');
187
+ for (const dep of row.deps ?? []) {
188
+ const depRow = byName.get(dep);
189
+ if (depRow)
190
+ visit(depRow);
191
+ }
192
+ state.set(row.deploy, 'done');
193
+ sorted.push(row);
194
+ };
195
+ for (const row of rows)
196
+ visit(row);
197
+ return sorted;
198
+ };
199
+ const CREATED_RELATION = /CREATE\s+(?:TABLE|SEQUENCE)\s+(?:IF\s+NOT\s+EXISTS\s+)?([\w."]+)/gi;
200
+ const RELATION_REFS = [
201
+ /OWNED\s+BY\s+([\w."]+)\.[\w"]+\s*;/gi,
202
+ /nextval\((?:CAST\()?'([^']+)'/g,
203
+ /ALTER\s+TABLE\s+(?:ONLY\s+)?(?:IF\s+EXISTS\s+)?([\w."]+)/gi,
204
+ /COMMENT\s+ON\s+TABLE\s+([\w."]+)/gi,
205
+ /GRANT\s+[^;]*?\s+ON\s+(?:TABLE\s+)?([\w."]+)\s+TO\s/gi
206
+ ];
207
+ const normalizeQualname = (raw) => raw.replace(/"/g, '').replace(/::regclass$/, '');
208
+ /**
209
+ * Re-link intra-package deps that only exist in statement *text* — riders
210
+ * (`ALTER TABLE`, `GRANT`, `COMMENT ON`, `OWNED BY`) and serial
211
+ * `nextval('seq')` defaults referencing a relation created by another row —
212
+ * after a pass (like partitioning) that regrouped statements and rebuilt
213
+ * dependencies from the statement graph alone. Deps that would create a
214
+ * cycle are dropped so the emitted plan stays deployable. Mutates `deps`
215
+ * and returns the rows re-sorted so prerequisites deploy first.
216
+ */
217
+ export const linkTextualDeps = (rows) => {
218
+ const byQualname = new Map();
219
+ for (const row of rows) {
220
+ CREATED_RELATION.lastIndex = 0;
221
+ let match;
222
+ while ((match = CREATED_RELATION.exec(row.content)) !== null) {
223
+ byQualname.set(normalizeQualname(match[1]), row);
224
+ }
225
+ }
226
+ for (const row of rows) {
227
+ for (const pattern of RELATION_REFS) {
228
+ pattern.lastIndex = 0;
229
+ let match;
230
+ while ((match = pattern.exec(row.content)) !== null) {
231
+ const targetRow = byQualname.get(normalizeQualname(match[1]));
232
+ if (!targetRow || targetRow === row)
233
+ continue;
234
+ row.deps = row.deps ?? [];
235
+ if (!row.deps.includes(targetRow.deploy))
236
+ row.deps.push(targetRow.deploy);
237
+ }
238
+ }
239
+ }
240
+ // Drop back-edges: a dep pointing at a row that transitively depends on
241
+ // this one would make the plan unsatisfiable.
242
+ const byName = new Map(rows.map(row => [row.deploy, row]));
243
+ const state = new Map();
244
+ const prune = (row) => {
245
+ if (state.get(row.deploy))
246
+ return;
247
+ state.set(row.deploy, 'visiting');
248
+ row.deps = (row.deps ?? []).filter(dep => {
249
+ const depRow = byName.get(dep);
250
+ if (!depRow)
251
+ return true;
252
+ if (state.get(depRow.deploy) === 'visiting')
253
+ return false;
254
+ prune(depRow);
255
+ return true;
256
+ });
257
+ state.set(row.deploy, 'done');
258
+ };
259
+ for (const row of rows)
260
+ prune(row);
261
+ return sortRowsByDeps(rows);
262
+ };
263
+ /**
264
+ * Classify a preprocessed dump and restructure it into pgpm change rows at
265
+ * the requested granularity. Requires nothing beyond the `DumpSource` —
266
+ * `loadModule()` is awaited internally.
267
+ */
268
+ export const importDumpRows = async (source, options = {}) => {
269
+ await loadModule();
270
+ const granularity = options.granularity ?? 'object';
271
+ const style = options.naming ?? 'directory';
272
+ const withData = options.withData ?? false;
273
+ const warnings = [...source.warnings];
274
+ const controlRequires = [];
275
+ const miscTexts = [];
276
+ const dataUnits = [];
277
+ let skippedPreamble = source.metaCommands.length;
278
+ let skippedData = 0;
279
+ const facts = classifyStatements(source.sql);
280
+ // Main statements (those creating/targeting an object) in dump order, with
281
+ // per-statement rider buckets so riders re-attach right after their host.
282
+ const mainTexts = [];
283
+ const riderBuckets = [];
284
+ const lastIndexOfKey = new Map();
285
+ const pendingRiders = [];
286
+ const ownedSequences = [];
287
+ for (const f of facts) {
288
+ const text = statementText(source.sql, f);
289
+ if (isPreamble(f, text)) {
290
+ skippedPreamble++;
291
+ continue;
292
+ }
293
+ if (f.kind === 'extension' && f.extension?.action === 'create') {
294
+ if (!controlRequires.includes(f.extension.name)) {
295
+ controlRequires.push(f.extension.name);
296
+ }
297
+ continue;
298
+ }
299
+ const setval = f.nodeTag === 'SelectStmt' ? SETVAL.exec(text) : null;
300
+ if (setval) {
301
+ if (!withData) {
302
+ skippedData++;
303
+ continue;
304
+ }
305
+ // setval is sequence state (data): ride the sequence's change.
306
+ const parts = setval[2].split('.');
307
+ const host = parts.length > 1
308
+ ? hostKey(parts[0], parts.slice(1).join('.'))
309
+ : hostKey(null, parts[0]);
310
+ pendingRiders.push({ text, host, nodeTag: 'SelectStmt (setval)' });
311
+ continue;
312
+ }
313
+ if (f.kind === 'seed_dml') {
314
+ const target = f.creates[0];
315
+ if (!withData) {
316
+ skippedData++;
317
+ continue;
318
+ }
319
+ dataUnits.push({
320
+ key: hostKey(target?.schema ?? null, target?.name ?? 'unknown'),
321
+ identity: {
322
+ kind: 'seed_dml',
323
+ schema: target?.schema ?? null,
324
+ name: 'seed',
325
+ table: target?.name ?? 'unknown'
326
+ },
327
+ sql: text
328
+ });
329
+ continue;
330
+ }
331
+ // `ALTER SEQUENCE ... OWNED BY table.column` is held out of the
332
+ // restructure (grouping would fold it into the sequence change, whose
333
+ // serial table depends on the sequence — a cycle) and appended to the
334
+ // table's change afterwards.
335
+ if (f.nodeTag === 'AlterSeqStmt' && f.stmt) {
336
+ const ownedBy = sequenceOwnedByHostOf(f.stmt);
337
+ if (ownedBy !== null) {
338
+ const seq = f.stmt.AlterSeqStmt?.sequence;
339
+ ownedSequences.push({
340
+ schema: seq?.schemaname ?? null,
341
+ name: seq?.relname ?? '',
342
+ tableKey: ownedBy,
343
+ text
344
+ });
345
+ continue;
346
+ }
347
+ }
348
+ if (f.creates.length > 0) {
349
+ // pg_dump emits ALTERs (late FKs, owners, defaults) far from their
350
+ // CREATE; repositioning them right after it keeps each group's
351
+ // statements in a deployable order at every granularity.
352
+ const hostIndex = f.nodeTag.startsWith('Alter')
353
+ ? lastIndexOfKey.get(hostKey(f.creates[0].schema, f.creates[0].name))
354
+ : undefined;
355
+ if (hostIndex !== undefined) {
356
+ riderBuckets[hostIndex].push(text);
357
+ continue;
358
+ }
359
+ const index = mainTexts.length;
360
+ mainTexts.push(text);
361
+ riderBuckets.push([]);
362
+ for (const created of f.creates) {
363
+ lastIndexOfKey.set(hostKey(created.schema, created.name), index);
364
+ }
365
+ continue;
366
+ }
367
+ const host = riderHostOf(f);
368
+ if (host !== null) {
369
+ pendingRiders.push({ text, host, nodeTag: f.nodeTag });
370
+ continue;
371
+ }
372
+ miscTexts.push(text);
373
+ warnings.push(`unclassifiable statement (${f.nodeTag}) placed in ${MISC_CHANGE_PATH}: ${text.split('\n')[0]}`);
374
+ }
375
+ for (const rider of pendingRiders) {
376
+ const index = lastIndexOfKey.get(rider.host);
377
+ if (index !== undefined) {
378
+ riderBuckets[index].push(rider.text);
379
+ }
380
+ else {
381
+ miscTexts.push(rider.text);
382
+ warnings.push(`${rider.nodeTag} targets an object not created in this dump — placed in ${MISC_CHANGE_PATH}: ${rider.text.split('\n')[0]}`);
383
+ }
384
+ }
385
+ // COPY data blocks (extracted pre-parse) become seed data too.
386
+ for (const block of source.copyBlocks) {
387
+ if (!withData) {
388
+ skippedData++;
389
+ continue;
390
+ }
391
+ const insert = copyBlockToInsert(block);
392
+ if (!insert)
393
+ continue;
394
+ const target = copyTargetOf(block);
395
+ dataUnits.push({
396
+ key: hostKey(target.schema, target.name),
397
+ identity: { kind: 'seed_dml', schema: target.schema, name: 'seed', table: target.name },
398
+ sql: insert
399
+ });
400
+ }
401
+ if (!withData && skippedData > 0) {
402
+ warnings.push(`${skippedData} data statement(s) skipped (pass --with-data to import them as seed fixtures)`);
403
+ }
404
+ // Reassemble the program with riders adjacent to their hosts, and
405
+ // restructure through the shared dials pipeline.
406
+ const program = mainTexts
407
+ .flatMap((text, i) => [text, ...riderBuckets[i]])
408
+ .join('\n\n');
409
+ const restructured = await restructureExportRows(program.trim()
410
+ ? [{ name: 'import/dump', deploy: 'import/dump', deps: [], content: program }]
411
+ : [], granularity, { naming: style });
412
+ warnings.push(...restructured.warnings);
413
+ const rows = [];
414
+ if (miscTexts.length > 0) {
415
+ const miscSql = miscTexts.join('\n\n');
416
+ const scripts = regenerateScripts(miscSql);
417
+ warnings.push(...scripts.revert.warnings.map(w => `${MISC_CHANGE_PATH}: ${w}`));
418
+ warnings.push(...scripts.verify.warnings.map(w => `${MISC_CHANGE_PATH}: ${w}`));
419
+ rows.push({
420
+ name: MISC_CHANGE_PATH,
421
+ deploy: MISC_CHANGE_PATH,
422
+ deps: [],
423
+ content: miscSql,
424
+ revert: scripts.revert.sql,
425
+ verify: scripts.verify.sql
426
+ });
427
+ }
428
+ rows.push(...restructured.rows.map(row => ({
429
+ ...row,
430
+ content: reorderChangeStatements(row.content),
431
+ revert: reorderRevertStatements(row.revert)
432
+ })));
433
+ // Seed fixture changes, one per table, after the schema changes.
434
+ const seedsByTable = new Map();
435
+ for (const unit of dataUnits) {
436
+ const existing = seedsByTable.get(unit.key);
437
+ if (existing)
438
+ existing.push(unit);
439
+ else
440
+ seedsByTable.set(unit.key, [unit]);
441
+ }
442
+ const taken = new Set(rows.map(row => row.deploy));
443
+ const seedPathByTablePath = new Map();
444
+ for (const units of seedsByTable.values()) {
445
+ const { identity } = units[0];
446
+ let deploy = pathFor(identity, { style });
447
+ while (taken.has(deploy))
448
+ deploy = `${deploy}_`;
449
+ taken.add(deploy);
450
+ const tablePath = pathFor({ kind: 'table', schema: identity.schema, name: identity.table }, { style });
451
+ seedPathByTablePath.set(tablePath, deploy);
452
+ rows.push({
453
+ name: deploy,
454
+ deploy,
455
+ deps: rows.some(row => row.deploy === tablePath) ? [tablePath] : [],
456
+ content: units.map(unit => unit.sql).join('\n\n'),
457
+ revert: seedRevert(identity.schema, identity.table),
458
+ verify: seedVerify(identity.schema, identity.table)
459
+ });
460
+ }
461
+ // Seeds must respect FKs: if table B depends on table A and both have
462
+ // seeds, seed(B) also depends on seed(A).
463
+ for (const [tablePath, seedPath] of seedPathByTablePath) {
464
+ const tableRow = rows.find(row => row.deploy === tablePath);
465
+ const seedRow = rows.find(row => row.deploy === seedPath);
466
+ for (const dep of tableRow?.deps ?? []) {
467
+ const depSeed = seedPathByTablePath.get(dep);
468
+ if (depSeed && !seedRow.deps.includes(depSeed)) {
469
+ seedRow.deps.push(depSeed);
470
+ }
471
+ }
472
+ }
473
+ // Re-attach OWNED BY to the owning table's change; the sequence's own
474
+ // revert must then tolerate the sequence being dropped with the table.
475
+ for (const seq of ownedSequences) {
476
+ if (!seq.name)
477
+ continue;
478
+ const [tableSchema, ...tableRest] = seq.tableKey.split('.');
479
+ const tablePath = pathFor({ kind: 'table', schema: tableSchema || null, name: tableRest.join('.') }, { style });
480
+ const tableRow = rows.find(r => r.deploy === tablePath);
481
+ const seqPath = pathFor({ kind: 'sequence', schema: seq.schema, name: seq.name }, { style });
482
+ const seqRow = rows.find(r => r.deploy === seqPath);
483
+ if (tableRow) {
484
+ tableRow.content = `${tableRow.content.trimEnd()}\n\n${seq.text}`;
485
+ if (seqRow) {
486
+ tableRow.deps = tableRow.deps ?? [];
487
+ if (!tableRow.deps.includes(seqPath))
488
+ tableRow.deps.push(seqPath);
489
+ }
490
+ }
491
+ else {
492
+ const miscRow = rows.find(r => r.deploy === MISC_CHANGE_PATH);
493
+ if (miscRow) {
494
+ miscRow.content = `${miscRow.content.trimEnd()}\n\n${seq.text}`;
495
+ }
496
+ else {
497
+ rows.push({
498
+ name: MISC_CHANGE_PATH,
499
+ deploy: MISC_CHANGE_PATH,
500
+ deps: [],
501
+ content: seq.text,
502
+ revert: '',
503
+ verify: ''
504
+ });
505
+ }
506
+ warnings.push(`AlterSeqStmt OWNED BY targets a table not created in this dump — placed in ${MISC_CHANGE_PATH}: ${seq.text.split('\n')[0]}`);
507
+ }
508
+ if (seqRow && tableRow) {
509
+ const target = seq.schema ? `${seq.schema}.${seq.name}` : seq.name;
510
+ seqRow.revert = `DROP SEQUENCE IF EXISTS ${target};`;
511
+ }
512
+ }
513
+ // pg_dump wires serial columns via `SET DEFAULT nextval('...')` — a plain
514
+ // string the statement graph cannot see, so add the sequence dep here.
515
+ const NEXTVAL = /nextval\((?:CAST\()?'([^']+)'/g;
516
+ const rowsByPath = new Map(rows.map(row => [row.deploy, row]));
517
+ for (const row of rows) {
518
+ NEXTVAL.lastIndex = 0;
519
+ let match;
520
+ while ((match = NEXTVAL.exec(row.content)) !== null) {
521
+ const parts = match[1].replace(/::regclass$/, '').split('.');
522
+ const seqPath = pathFor({
523
+ kind: 'sequence',
524
+ schema: parts.length > 1 ? parts[0] : null,
525
+ name: parts.length > 1 ? parts.slice(1).join('.') : parts[0]
526
+ }, { style });
527
+ if (seqPath !== row.deploy && rowsByPath.has(seqPath)) {
528
+ row.deps = row.deps ?? [];
529
+ if (!row.deps.includes(seqPath))
530
+ row.deps.push(seqPath);
531
+ }
532
+ }
533
+ }
534
+ const orderedRows = sortRowsByDeps(rows);
535
+ return {
536
+ rows: orderedRows,
537
+ controlRequires,
538
+ warnings,
539
+ summary: {
540
+ statements: facts.length + source.copyBlocks.length + source.metaCommands.length,
541
+ changes: orderedRows.length,
542
+ skippedPreamble,
543
+ skippedData: withData ? 0 : skippedData,
544
+ misc: miscTexts.length
545
+ }
546
+ };
547
+ };
package/esm/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { copyBlockToInsert, copyTargetOf, dumpCompatibilityWarnings, loadDumpSource, preprocessDumpText } from './dump-source';
2
+ export { importDumpRows, linkTextualDeps, MISC_CHANGE_PATH } from './import';
package/import.d.ts ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * `pgpm import` driver: pgpm-itize an arbitrary SQL dump.
3
+ *
4
+ * A preprocessed dump (`DumpSource`) is classified statement-by-statement,
5
+ * dump noise is filtered, riders (grants/comments/ownership) are re-attached
6
+ * to their host objects, and the result is routed through the shared dials
7
+ * pipeline (`restructureExportRows`): spec-derived change paths
8
+ * (`identityOf` + `pathFor`, collisions via `alterationPathFor`),
9
+ * graph-derived `requires`, generated revert/verify.
10
+ *
11
+ * Dump-specific handling:
12
+ * - `SET ...` / `SELECT set_config(...)` preamble statements are skipped;
13
+ * - `CREATE EXTENSION` statements become `.control` requires (pgpm owns
14
+ * extension creation at deploy time);
15
+ * - `COPY ... FROM stdin` blocks and `INSERT`s are skipped by default with a
16
+ * warning; `withData` emits them as seed fixture changes (COPY data is
17
+ * converted to INSERTs so it deploys through the pg driver);
18
+ * - statements that classify to no object and attach to no host (roles,
19
+ * default privileges, ...) land in a `misc/statements` change, first in
20
+ * the plan, with a warning — never dropped silently.
21
+ */
22
+ import { PgpmRow } from '@pgpmjs/ast';
23
+ import { PathStyle } from '@pgpmjs/naming-spec';
24
+ import { ExportGranularity } from '@pgpmjs/transform';
25
+ import { DumpSource } from './dump-source';
26
+ export declare const MISC_CHANGE_PATH = "misc/statements";
27
+ export interface ImportDumpRowsOptions {
28
+ /** Granularity dial (default: `object`). */
29
+ granularity?: ExportGranularity;
30
+ /** Naming spec path style (default: `directory`). */
31
+ naming?: PathStyle;
32
+ /** Emit data statements (COPY blocks, INSERTs) as seed fixture changes. */
33
+ withData?: boolean;
34
+ }
35
+ export interface ImportDumpSummary {
36
+ /** Total statements seen (parsed statements + COPY data blocks). */
37
+ statements: number;
38
+ /** Changes emitted. */
39
+ changes: number;
40
+ /** Preamble statements skipped (SET / set_config / psql meta-commands). */
41
+ skippedPreamble: number;
42
+ /** Data statements skipped (only when `withData` is off). */
43
+ skippedData: number;
44
+ /** Statements placed in the misc/ change. */
45
+ misc: number;
46
+ }
47
+ export interface ImportDumpRowsResult {
48
+ /** Changes in deploy order, ready for plan/file emission. */
49
+ rows: PgpmRow[];
50
+ /** Extension names from `CREATE EXTENSION`, for the module's `.control`. */
51
+ controlRequires: string[];
52
+ warnings: string[];
53
+ summary: ImportDumpSummary;
54
+ }
55
+ /**
56
+ * Re-link intra-package deps that only exist in statement *text* — riders
57
+ * (`ALTER TABLE`, `GRANT`, `COMMENT ON`, `OWNED BY`) and serial
58
+ * `nextval('seq')` defaults referencing a relation created by another row —
59
+ * after a pass (like partitioning) that regrouped statements and rebuilt
60
+ * dependencies from the statement graph alone. Deps that would create a
61
+ * cycle are dropped so the emitted plan stays deployable. Mutates `deps`
62
+ * and returns the rows re-sorted so prerequisites deploy first.
63
+ */
64
+ export declare const linkTextualDeps: (rows: PgpmRow[]) => PgpmRow[];
65
+ /**
66
+ * Classify a preprocessed dump and restructure it into pgpm change rows at
67
+ * the requested granularity. Requires nothing beyond the `DumpSource` —
68
+ * `loadModule()` is awaited internally.
69
+ */
70
+ export declare const importDumpRows: (source: DumpSource, options?: ImportDumpRowsOptions) => Promise<ImportDumpRowsResult>;