@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/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
4
+ Copyright (c) 2025 Constructive <developers@constructive.io>
5
+ Copyright (c) 2020-present, Interweb, Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,82 @@
1
+ # @pgpmjs/import
2
+
3
+ `pgpm import` engine: pgpm-itize arbitrary SQL dumps (plain `pg_dump` output or raw `.sql` files) through the dials pipeline.
4
+
5
+ - `dump-source` β€” preprocess dump text: strip psql backslash commands, extract `COPY ... FROM stdin` blocks, convert COPY data to INSERTs.
6
+ - `import` β€” `importDumpRows`: classify statements, attach riders (grants/comments/ownership) to their host objects, route through the shared restructure seam (`@pgpmjs/transform`), and emit deployable `PgpmRow`s with generated revert/verify.
7
+
8
+ Used by the `pgpm import` CLI command (`pgpm/cli`). Sibling front doors: `@pgpmjs/export` (live database), `@pgpmjs/diff` (semantic diff).
9
+
10
+ ---
11
+
12
+ ## Education and Tutorials
13
+
14
+ 1. πŸš€ [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
15
+ Get started with modular databases in minutes. Install prerequisites and deploy your first module.
16
+
17
+ 2. πŸ“¦ [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
18
+ Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
19
+
20
+ 3. ✏️ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
21
+ Master the workflow for adding, organizing, and managing database changes with pgpm.
22
+
23
+ 4. πŸ§ͺ [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
24
+ Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
25
+
26
+ 5. ⚑ [Supabase Testing](https://constructive.io/learn/supabase)
27
+ Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
28
+
29
+ 6. πŸ’§ [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
30
+ Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
31
+
32
+ 7. πŸ”§ [Troubleshooting](https://constructive.io/learn/troubleshooting)
33
+ Common issues and solutions for pgpm, PostgreSQL, and testing.
34
+
35
+ ## Related Constructive Tooling
36
+
37
+ ### πŸ“¦ Package Management
38
+
39
+ * [pgpm](https://github.com/constructive-io/constructive/tree/main/pgpm/pgpm): **πŸ–₯️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
40
+
41
+ ### πŸ§ͺ Testing
42
+
43
+ * [pgsql-test](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-test): **πŸ“Š Isolated testing environments** with per-test transaction rollbacksβ€”ideal for integration tests, complex migrations, and RLS simulation.
44
+ * [pglite-test](https://github.com/constructive-io/constructive/tree/main/postgres/pglite-test): **πŸͺΆ Drop-in pgsql-test replacement backed by PGlite** β€” in-process Postgres, no server required, instance-per-suite isolation.
45
+ * [pgsql-seed](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-seed): **🌱 PostgreSQL seeding utilities** for CSV, JSON, SQL data loading, and pgpm deployment.
46
+ * [supabase-test](https://github.com/constructive-io/constructive/tree/main/postgres/supabase-test): **πŸ§ͺ Supabase-native test harness** preconfigured for the local Supabase stackβ€”per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
47
+ * [graphile-test](https://github.com/constructive-io/constructive/tree/main/graphile/graphile-test): **πŸ” Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
48
+ * [pg-query-context](https://github.com/constructive-io/constructive/tree/main/postgres/pg-query-context): **πŸ”’ Session context injection** to add session-local context (e.g., `SET LOCAL`) into queriesβ€”ideal for setting `role`, `jwt.claims`, and other session settings.
49
+
50
+ ### 🧠 Parsing & AST
51
+
52
+ * [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **πŸ”„ SQL conversion engine** that interprets and converts PostgreSQL syntax.
53
+ * [libpg-query-node](https://www.npmjs.com/package/libpg-query): **πŸŒ‰ Node.js bindings** for `libpg_query`, converting SQL into parse trees.
54
+ * [pg-proto-parser](https://www.npmjs.com/package/pg-proto-parser): **πŸ“¦ Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
55
+ * [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
56
+ * [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **πŸ“ Type definitions** for PostgreSQL AST nodes in TypeScript.
57
+ * [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **πŸ› οΈ AST utilities** for constructing and transforming PostgreSQL syntax trees.
58
+
59
+ ### πŸ“š Documentation & Skills
60
+
61
+ * [constructive-skills](https://github.com/constructive-io/constructive-skills): **πŸ“– Platform documentation and AI agent skills** β€” feature catalog, blueprint reference, SDK guides (i18n, billing, limits, events, uploads, security, entities, search, AI), and deployment guides.
62
+
63
+ Install skills for AI coding agents:
64
+
65
+ ```bash
66
+ # All platform skills (security, blueprints, codegen, billing, etc.)
67
+ npx skills add constructive-io/constructive-skills
68
+
69
+ # Individual repo skills (pgpm, testing, CLI, search, etc.)
70
+ npx skills add https://github.com/constructive-io/constructive --skill pgpm
71
+ npx skills add https://github.com/constructive-io/constructive --skill constructive-testing
72
+ ```
73
+
74
+ ## Credits
75
+
76
+ **πŸ›  Built by the [Constructive](https://constructive.io) team β€” creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
77
+
78
+ ## Disclaimer
79
+
80
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
81
+
82
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
@@ -0,0 +1,54 @@
1
+ /** A `COPY ... FROM stdin;` block captured verbatim from the dump. */
2
+ export interface CopyBlock {
3
+ /** The COPY statement line (without the data). */
4
+ statement: string;
5
+ /** Raw data lines between the statement and the terminating `\.`. */
6
+ dataLines: string[];
7
+ }
8
+ /** A dump loaded and preprocessed into parseable SQL + data blocks. */
9
+ export interface DumpSource {
10
+ /** Files the SQL was read from, in concatenation order. */
11
+ files: string[];
12
+ /** Parseable SQL: the dump minus meta-commands and COPY data blocks. */
13
+ sql: string;
14
+ /** COPY data blocks, in dump order. */
15
+ copyBlocks: CopyBlock[];
16
+ /** psql backslash meta-commands that were stripped, verbatim. */
17
+ metaCommands: string[];
18
+ /** Non-fatal notes. */
19
+ warnings: string[];
20
+ }
21
+ /**
22
+ * Preprocess raw dump text: strip psql meta-commands, extract
23
+ * `COPY ... FROM stdin;` data blocks (through their terminating `\.`), and
24
+ * return the remaining SQL, which is parseable as a whole.
25
+ */
26
+ export declare const preprocessDumpText: (text: string) => Omit<DumpSource, "files">;
27
+ /**
28
+ * Load a dump from a .sql file or a directory of .sql files. Directory
29
+ * inputs are concatenated in sorted (lexicographic) filename order β€” name
30
+ * files accordingly (e.g. `001-schema.sql`, `002-data.sql`).
31
+ */
32
+ export declare const loadDumpSource: (inputPath: string) => DumpSource;
33
+ /**
34
+ * Loud compatibility warnings for dump constructs we handle only best-effort
35
+ * because they are not SQL and cannot go through the real parser: COPY stdin
36
+ * data blocks and non-preamble psql meta-commands. The reliable path is to
37
+ * hand `pgpm import` pure parseable SQL.
38
+ */
39
+ export declare const dumpCompatibilityWarnings: (source: Pick<DumpSource, "copyBlocks" | "metaCommands">) => string[];
40
+ /** The parsed target of a COPY statement. */
41
+ export interface CopyTarget {
42
+ schema: string | null;
43
+ name: string;
44
+ /** Raw column list between the parens, or null when omitted. */
45
+ columns: string | null;
46
+ }
47
+ /** Parse the table (and column list) a COPY block targets. */
48
+ export declare const copyTargetOf: (block: CopyBlock) => CopyTarget;
49
+ /**
50
+ * Convert a COPY block to an equivalent multi-row INSERT statement, so the
51
+ * data can be deployed through the pg driver (which cannot stream
52
+ * `COPY ... FROM stdin` inline data).
53
+ */
54
+ export declare const copyBlockToInsert: (block: CopyBlock) => string;
package/dump-source.js ADDED
@@ -0,0 +1,247 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.copyBlockToInsert = exports.copyTargetOf = exports.dumpCompatibilityWarnings = exports.loadDumpSource = exports.preprocessDumpText = void 0;
37
+ /**
38
+ * Dump ingestion for `pgpm import`: turn a `pg_dump` output file (or a
39
+ * directory of .sql files, concatenated in sorted order) into parseable SQL
40
+ * plus extracted data blocks. This is the file/dump front door of the "ingest
41
+ * anything -> classified unit set" seam (`loadModuleSource` is the module
42
+ * front door).
43
+ *
44
+ * Text-level preprocessing handles the two things libpg_query cannot parse:
45
+ * - psql backslash meta-commands (`\connect`, `\restrict`, ...) β€” stripped
46
+ * and reported;
47
+ * - `COPY ... FROM stdin;` data blocks β€” captured as a unit including the
48
+ * terminating `\.` so they can be re-emitted as seed fixtures.
49
+ *
50
+ * The scanner tracks dollar-quoted strings so function bodies containing
51
+ * backslash-prefixed lines are left untouched.
52
+ */
53
+ const fs = __importStar(require("fs"));
54
+ const path = __importStar(require("path"));
55
+ const COPY_FROM_STDIN = /^COPY\s.+\bFROM\s+stdin\s*;\s*$/i;
56
+ const DOLLAR_TAG = /\$[A-Za-z_][A-Za-z_0-9]*\$|\$\$/g;
57
+ /** Advance the dollar-quote state across one line; returns the open tag or null. */
58
+ const trackDollarQuotes = (line, openTag) => {
59
+ let tag = openTag;
60
+ DOLLAR_TAG.lastIndex = 0;
61
+ let match;
62
+ while ((match = DOLLAR_TAG.exec(line)) !== null) {
63
+ if (tag === null) {
64
+ tag = match[0];
65
+ }
66
+ else if (match[0] === tag) {
67
+ tag = null;
68
+ }
69
+ }
70
+ return tag;
71
+ };
72
+ /**
73
+ * Preprocess raw dump text: strip psql meta-commands, extract
74
+ * `COPY ... FROM stdin;` data blocks (through their terminating `\.`), and
75
+ * return the remaining SQL, which is parseable as a whole.
76
+ */
77
+ const preprocessDumpText = (text) => {
78
+ const sqlLines = [];
79
+ const copyBlocks = [];
80
+ const metaCommands = [];
81
+ const warnings = [];
82
+ let openTag = null;
83
+ let copy = null;
84
+ for (const line of text.split('\n')) {
85
+ if (copy) {
86
+ if (line === '\\.') {
87
+ copyBlocks.push(copy);
88
+ copy = null;
89
+ }
90
+ else {
91
+ copy.dataLines.push(line);
92
+ }
93
+ continue;
94
+ }
95
+ if (openTag === null) {
96
+ const trimmed = line.trimStart();
97
+ if (trimmed.startsWith('\\')) {
98
+ metaCommands.push(trimmed);
99
+ continue;
100
+ }
101
+ if (COPY_FROM_STDIN.test(trimmed)) {
102
+ copy = { statement: trimmed, dataLines: [] };
103
+ continue;
104
+ }
105
+ }
106
+ openTag = trackDollarQuotes(line, openTag);
107
+ sqlLines.push(line);
108
+ }
109
+ if (copy) {
110
+ warnings.push(`COPY block "${copy.statement}" is missing its terminating \\. β€” its data was kept but may be truncated`);
111
+ copyBlocks.push(copy);
112
+ }
113
+ return { sql: sqlLines.join('\n'), copyBlocks, metaCommands, warnings };
114
+ };
115
+ exports.preprocessDumpText = preprocessDumpText;
116
+ /**
117
+ * Load a dump from a .sql file or a directory of .sql files. Directory
118
+ * inputs are concatenated in sorted (lexicographic) filename order β€” name
119
+ * files accordingly (e.g. `001-schema.sql`, `002-data.sql`).
120
+ */
121
+ const loadDumpSource = (inputPath) => {
122
+ const resolved = path.resolve(inputPath);
123
+ const stat = fs.statSync(resolved);
124
+ let files;
125
+ if (stat.isDirectory()) {
126
+ files = fs
127
+ .readdirSync(resolved)
128
+ .filter(f => f.endsWith('.sql'))
129
+ .sort((a, b) => a.localeCompare(b))
130
+ .map(f => path.join(resolved, f));
131
+ if (files.length === 0) {
132
+ throw new Error(`No .sql files found in directory: ${resolved}`);
133
+ }
134
+ }
135
+ else {
136
+ files = [resolved];
137
+ }
138
+ const text = files.map(f => fs.readFileSync(f, 'utf-8')).join('\n');
139
+ return { files, ...(0, exports.preprocessDumpText)(text) };
140
+ };
141
+ exports.loadDumpSource = loadDumpSource;
142
+ /** psql meta-commands pg_dump always emits as preamble β€” expected noise. */
143
+ const EXPECTED_META = /^\\(restrict|unrestrict|connect)\b/;
144
+ /**
145
+ * Loud compatibility warnings for dump constructs we handle only best-effort
146
+ * because they are not SQL and cannot go through the real parser: COPY stdin
147
+ * data blocks and non-preamble psql meta-commands. The reliable path is to
148
+ * hand `pgpm import` pure parseable SQL.
149
+ */
150
+ const dumpCompatibilityWarnings = (source) => {
151
+ const warnings = [];
152
+ if (source.copyBlocks.length > 0) {
153
+ warnings.push(`dump contains ${source.copyBlocks.length} COPY ... FROM stdin data block(s). ` +
154
+ `COPY data is NOT SQL and is handled by a best-effort text scanner β€” data could be missed or truncated. ` +
155
+ `For a guaranteed import, re-dump with:\n` +
156
+ ` pg_dump --schema-only (schema only; recommended)\n` +
157
+ ` pg_dump --inserts (data as parseable INSERT statements, for --with-data)`);
158
+ }
159
+ const unexpected = source.metaCommands.filter(cmd => !EXPECTED_META.test(cmd));
160
+ if (unexpected.length > 0) {
161
+ warnings.push(`dump contains ${unexpected.length} psql meta-command(s) beyond the standard pg_dump preamble ` +
162
+ `(e.g. ${unexpected[0].split(/\s/)[0]}). These are client-side psql commands, not SQL β€” they are stripped ` +
163
+ `and will NOT be part of the module. Feed pgpm import plain SQL (e.g. pg_dump output), not psql scripts.`);
164
+ }
165
+ return warnings;
166
+ };
167
+ exports.dumpCompatibilityWarnings = dumpCompatibilityWarnings;
168
+ const COPY_TARGET = /^COPY\s+(.+?)(?:\s*\(([^)]*)\))?\s+FROM\s+stdin\s*;\s*$/i;
169
+ /** Parse the table (and column list) a COPY block targets. */
170
+ const copyTargetOf = (block) => {
171
+ const match = COPY_TARGET.exec(block.statement.trim());
172
+ if (!match) {
173
+ throw new Error(`Unrecognized COPY statement: ${block.statement}`);
174
+ }
175
+ const target = match[1].trim();
176
+ const columns = match[2]?.trim() || null;
177
+ const unquote = (s) => s.startsWith('"') && s.endsWith('"') ? s.slice(1, -1).replace(/""/g, '"') : s;
178
+ const parts = target.split('.').map(unquote);
179
+ return parts.length > 1
180
+ ? { schema: parts[0], name: parts.slice(1).join('.'), columns }
181
+ : { schema: null, name: target, columns };
182
+ };
183
+ exports.copyTargetOf = copyTargetOf;
184
+ /** Decode one field of COPY text-format data (`\N` handled by the caller). */
185
+ const decodeCopyField = (field) => {
186
+ let out = '';
187
+ for (let i = 0; i < field.length; i++) {
188
+ const ch = field[i];
189
+ if (ch !== '\\') {
190
+ out += ch;
191
+ continue;
192
+ }
193
+ const next = field[++i];
194
+ switch (next) {
195
+ case 'b':
196
+ out += '\b';
197
+ break;
198
+ case 'f':
199
+ out += '\f';
200
+ break;
201
+ case 'n':
202
+ out += '\n';
203
+ break;
204
+ case 'r':
205
+ out += '\r';
206
+ break;
207
+ case 't':
208
+ out += '\t';
209
+ break;
210
+ case 'v':
211
+ out += '\v';
212
+ break;
213
+ case undefined:
214
+ out += '\\';
215
+ break;
216
+ default: out += next;
217
+ }
218
+ }
219
+ return out;
220
+ };
221
+ const quoteLiteral = (value) => `'${value.replace(/'/g, "''")}'`;
222
+ /**
223
+ * Convert a COPY block to an equivalent multi-row INSERT statement, so the
224
+ * data can be deployed through the pg driver (which cannot stream
225
+ * `COPY ... FROM stdin` inline data).
226
+ */
227
+ const copyBlockToInsert = (block) => {
228
+ const match = COPY_TARGET.exec(block.statement.trim());
229
+ if (!match) {
230
+ throw new Error(`Unrecognized COPY statement: ${block.statement}`);
231
+ }
232
+ const target = match[1].trim();
233
+ const columns = match[2]?.trim();
234
+ const rows = block.dataLines
235
+ .filter(line => line.length > 0)
236
+ .map(line => {
237
+ const values = line
238
+ .split('\t')
239
+ .map(field => (field === '\\N' ? 'NULL' : quoteLiteral(decodeCopyField(field))));
240
+ return `(${values.join(', ')})`;
241
+ });
242
+ if (rows.length === 0)
243
+ return '';
244
+ const columnList = columns ? ` (${columns})` : '';
245
+ return `INSERT INTO ${target}${columnList} VALUES\n ${rows.join(',\n ')};`;
246
+ };
247
+ exports.copyBlockToInsert = copyBlockToInsert;
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Dump ingestion for `pgpm import`: turn a `pg_dump` output file (or a
3
+ * directory of .sql files, concatenated in sorted order) into parseable SQL
4
+ * plus extracted data blocks. This is the file/dump front door of the "ingest
5
+ * anything -> classified unit set" seam (`loadModuleSource` is the module
6
+ * front door).
7
+ *
8
+ * Text-level preprocessing handles the two things libpg_query cannot parse:
9
+ * - psql backslash meta-commands (`\connect`, `\restrict`, ...) β€” stripped
10
+ * and reported;
11
+ * - `COPY ... FROM stdin;` data blocks β€” captured as a unit including the
12
+ * terminating `\.` so they can be re-emitted as seed fixtures.
13
+ *
14
+ * The scanner tracks dollar-quoted strings so function bodies containing
15
+ * backslash-prefixed lines are left untouched.
16
+ */
17
+ import * as fs from 'fs';
18
+ import * as path from 'path';
19
+ const COPY_FROM_STDIN = /^COPY\s.+\bFROM\s+stdin\s*;\s*$/i;
20
+ const DOLLAR_TAG = /\$[A-Za-z_][A-Za-z_0-9]*\$|\$\$/g;
21
+ /** Advance the dollar-quote state across one line; returns the open tag or null. */
22
+ const trackDollarQuotes = (line, openTag) => {
23
+ let tag = openTag;
24
+ DOLLAR_TAG.lastIndex = 0;
25
+ let match;
26
+ while ((match = DOLLAR_TAG.exec(line)) !== null) {
27
+ if (tag === null) {
28
+ tag = match[0];
29
+ }
30
+ else if (match[0] === tag) {
31
+ tag = null;
32
+ }
33
+ }
34
+ return tag;
35
+ };
36
+ /**
37
+ * Preprocess raw dump text: strip psql meta-commands, extract
38
+ * `COPY ... FROM stdin;` data blocks (through their terminating `\.`), and
39
+ * return the remaining SQL, which is parseable as a whole.
40
+ */
41
+ export const preprocessDumpText = (text) => {
42
+ const sqlLines = [];
43
+ const copyBlocks = [];
44
+ const metaCommands = [];
45
+ const warnings = [];
46
+ let openTag = null;
47
+ let copy = null;
48
+ for (const line of text.split('\n')) {
49
+ if (copy) {
50
+ if (line === '\\.') {
51
+ copyBlocks.push(copy);
52
+ copy = null;
53
+ }
54
+ else {
55
+ copy.dataLines.push(line);
56
+ }
57
+ continue;
58
+ }
59
+ if (openTag === null) {
60
+ const trimmed = line.trimStart();
61
+ if (trimmed.startsWith('\\')) {
62
+ metaCommands.push(trimmed);
63
+ continue;
64
+ }
65
+ if (COPY_FROM_STDIN.test(trimmed)) {
66
+ copy = { statement: trimmed, dataLines: [] };
67
+ continue;
68
+ }
69
+ }
70
+ openTag = trackDollarQuotes(line, openTag);
71
+ sqlLines.push(line);
72
+ }
73
+ if (copy) {
74
+ warnings.push(`COPY block "${copy.statement}" is missing its terminating \\. β€” its data was kept but may be truncated`);
75
+ copyBlocks.push(copy);
76
+ }
77
+ return { sql: sqlLines.join('\n'), copyBlocks, metaCommands, warnings };
78
+ };
79
+ /**
80
+ * Load a dump from a .sql file or a directory of .sql files. Directory
81
+ * inputs are concatenated in sorted (lexicographic) filename order β€” name
82
+ * files accordingly (e.g. `001-schema.sql`, `002-data.sql`).
83
+ */
84
+ export const loadDumpSource = (inputPath) => {
85
+ const resolved = path.resolve(inputPath);
86
+ const stat = fs.statSync(resolved);
87
+ let files;
88
+ if (stat.isDirectory()) {
89
+ files = fs
90
+ .readdirSync(resolved)
91
+ .filter(f => f.endsWith('.sql'))
92
+ .sort((a, b) => a.localeCompare(b))
93
+ .map(f => path.join(resolved, f));
94
+ if (files.length === 0) {
95
+ throw new Error(`No .sql files found in directory: ${resolved}`);
96
+ }
97
+ }
98
+ else {
99
+ files = [resolved];
100
+ }
101
+ const text = files.map(f => fs.readFileSync(f, 'utf-8')).join('\n');
102
+ return { files, ...preprocessDumpText(text) };
103
+ };
104
+ /** psql meta-commands pg_dump always emits as preamble β€” expected noise. */
105
+ const EXPECTED_META = /^\\(restrict|unrestrict|connect)\b/;
106
+ /**
107
+ * Loud compatibility warnings for dump constructs we handle only best-effort
108
+ * because they are not SQL and cannot go through the real parser: COPY stdin
109
+ * data blocks and non-preamble psql meta-commands. The reliable path is to
110
+ * hand `pgpm import` pure parseable SQL.
111
+ */
112
+ export const dumpCompatibilityWarnings = (source) => {
113
+ const warnings = [];
114
+ if (source.copyBlocks.length > 0) {
115
+ warnings.push(`dump contains ${source.copyBlocks.length} COPY ... FROM stdin data block(s). ` +
116
+ `COPY data is NOT SQL and is handled by a best-effort text scanner β€” data could be missed or truncated. ` +
117
+ `For a guaranteed import, re-dump with:\n` +
118
+ ` pg_dump --schema-only (schema only; recommended)\n` +
119
+ ` pg_dump --inserts (data as parseable INSERT statements, for --with-data)`);
120
+ }
121
+ const unexpected = source.metaCommands.filter(cmd => !EXPECTED_META.test(cmd));
122
+ if (unexpected.length > 0) {
123
+ warnings.push(`dump contains ${unexpected.length} psql meta-command(s) beyond the standard pg_dump preamble ` +
124
+ `(e.g. ${unexpected[0].split(/\s/)[0]}). These are client-side psql commands, not SQL β€” they are stripped ` +
125
+ `and will NOT be part of the module. Feed pgpm import plain SQL (e.g. pg_dump output), not psql scripts.`);
126
+ }
127
+ return warnings;
128
+ };
129
+ const COPY_TARGET = /^COPY\s+(.+?)(?:\s*\(([^)]*)\))?\s+FROM\s+stdin\s*;\s*$/i;
130
+ /** Parse the table (and column list) a COPY block targets. */
131
+ export const copyTargetOf = (block) => {
132
+ const match = COPY_TARGET.exec(block.statement.trim());
133
+ if (!match) {
134
+ throw new Error(`Unrecognized COPY statement: ${block.statement}`);
135
+ }
136
+ const target = match[1].trim();
137
+ const columns = match[2]?.trim() || null;
138
+ const unquote = (s) => s.startsWith('"') && s.endsWith('"') ? s.slice(1, -1).replace(/""/g, '"') : s;
139
+ const parts = target.split('.').map(unquote);
140
+ return parts.length > 1
141
+ ? { schema: parts[0], name: parts.slice(1).join('.'), columns }
142
+ : { schema: null, name: target, columns };
143
+ };
144
+ /** Decode one field of COPY text-format data (`\N` handled by the caller). */
145
+ const decodeCopyField = (field) => {
146
+ let out = '';
147
+ for (let i = 0; i < field.length; i++) {
148
+ const ch = field[i];
149
+ if (ch !== '\\') {
150
+ out += ch;
151
+ continue;
152
+ }
153
+ const next = field[++i];
154
+ switch (next) {
155
+ case 'b':
156
+ out += '\b';
157
+ break;
158
+ case 'f':
159
+ out += '\f';
160
+ break;
161
+ case 'n':
162
+ out += '\n';
163
+ break;
164
+ case 'r':
165
+ out += '\r';
166
+ break;
167
+ case 't':
168
+ out += '\t';
169
+ break;
170
+ case 'v':
171
+ out += '\v';
172
+ break;
173
+ case undefined:
174
+ out += '\\';
175
+ break;
176
+ default: out += next;
177
+ }
178
+ }
179
+ return out;
180
+ };
181
+ const quoteLiteral = (value) => `'${value.replace(/'/g, "''")}'`;
182
+ /**
183
+ * Convert a COPY block to an equivalent multi-row INSERT statement, so the
184
+ * data can be deployed through the pg driver (which cannot stream
185
+ * `COPY ... FROM stdin` inline data).
186
+ */
187
+ export const copyBlockToInsert = (block) => {
188
+ const match = COPY_TARGET.exec(block.statement.trim());
189
+ if (!match) {
190
+ throw new Error(`Unrecognized COPY statement: ${block.statement}`);
191
+ }
192
+ const target = match[1].trim();
193
+ const columns = match[2]?.trim();
194
+ const rows = block.dataLines
195
+ .filter(line => line.length > 0)
196
+ .map(line => {
197
+ const values = line
198
+ .split('\t')
199
+ .map(field => (field === '\\N' ? 'NULL' : quoteLiteral(decodeCopyField(field))));
200
+ return `(${values.join(', ')})`;
201
+ });
202
+ if (rows.length === 0)
203
+ return '';
204
+ const columnList = columns ? ` (${columns})` : '';
205
+ return `INSERT INTO ${target}${columnList} VALUES\n ${rows.join(',\n ')};`;
206
+ };