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