@pgpmjs/diff 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 +23 -0
- package/README.md +81 -0
- package/diff-source.d.ts +47 -0
- package/diff-source.js +150 -0
- package/esm/diff-source.js +109 -0
- package/esm/index.js +1 -0
- package/index.d.ts +2 -0
- package/index.js +9 -0
- package/package.json +50 -0
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,81 @@
|
|
|
1
|
+
# @pgpmjs/diff
|
|
2
|
+
|
|
3
|
+
`pgpm diff` engine: identity-keyed semantic schema diff between any two SQL sources โ pgpm modules, SQL dumps, or live databases (dumped via `pg_dump` by the CLI).
|
|
4
|
+
|
|
5
|
+
Every side normalizes to the same `DiffInputChange[]` seam consumed by the semantic diff driver in `@pgpmjs/transform`, so the comparison is source- and dial-invariant. `deltaChangesToRows` lifts the resulting deltas back onto deployable `PgpmRow`s.
|
|
6
|
+
|
|
7
|
+
Used by the `pgpm diff` CLI command (`pgpm/cli`). Sibling front doors: `@pgpmjs/export` (live database), `@pgpmjs/import` (dumps).
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Education and Tutorials
|
|
12
|
+
|
|
13
|
+
1. ๐ [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
|
|
14
|
+
Get started with modular databases in minutes. Install prerequisites and deploy your first module.
|
|
15
|
+
|
|
16
|
+
2. ๐ฆ [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
|
|
17
|
+
Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
|
|
18
|
+
|
|
19
|
+
3. โ๏ธ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
|
|
20
|
+
Master the workflow for adding, organizing, and managing database changes with pgpm.
|
|
21
|
+
|
|
22
|
+
4. ๐งช [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
|
|
23
|
+
Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
|
|
24
|
+
|
|
25
|
+
5. โก [Supabase Testing](https://constructive.io/learn/supabase)
|
|
26
|
+
Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
|
|
27
|
+
|
|
28
|
+
6. ๐ง [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
|
|
29
|
+
Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
|
|
30
|
+
|
|
31
|
+
7. ๐ง [Troubleshooting](https://constructive.io/learn/troubleshooting)
|
|
32
|
+
Common issues and solutions for pgpm, PostgreSQL, and testing.
|
|
33
|
+
|
|
34
|
+
## Related Constructive Tooling
|
|
35
|
+
|
|
36
|
+
### ๐ฆ Package Management
|
|
37
|
+
|
|
38
|
+
* [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.
|
|
39
|
+
|
|
40
|
+
### ๐งช Testing
|
|
41
|
+
|
|
42
|
+
* [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.
|
|
43
|
+
* [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.
|
|
44
|
+
* [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.
|
|
45
|
+
* [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.
|
|
46
|
+
* [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.
|
|
47
|
+
* [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.
|
|
48
|
+
|
|
49
|
+
### ๐ง Parsing & AST
|
|
50
|
+
|
|
51
|
+
* [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **๐ SQL conversion engine** that interprets and converts PostgreSQL syntax.
|
|
52
|
+
* [libpg-query-node](https://www.npmjs.com/package/libpg-query): **๐ Node.js bindings** for `libpg_query`, converting SQL into parse trees.
|
|
53
|
+
* [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.
|
|
54
|
+
* [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **๐ท๏ธ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
|
|
55
|
+
* [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **๐ Type definitions** for PostgreSQL AST nodes in TypeScript.
|
|
56
|
+
* [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **๐ ๏ธ AST utilities** for constructing and transforming PostgreSQL syntax trees.
|
|
57
|
+
|
|
58
|
+
### ๐ Documentation & Skills
|
|
59
|
+
|
|
60
|
+
* [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.
|
|
61
|
+
|
|
62
|
+
Install skills for AI coding agents:
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
# All platform skills (security, blueprints, codegen, billing, etc.)
|
|
66
|
+
npx skills add constructive-io/constructive-skills
|
|
67
|
+
|
|
68
|
+
# Individual repo skills (pgpm, testing, CLI, search, etc.)
|
|
69
|
+
npx skills add https://github.com/constructive-io/constructive --skill pgpm
|
|
70
|
+
npx skills add https://github.com/constructive-io/constructive --skill constructive-testing
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Credits
|
|
74
|
+
|
|
75
|
+
**๐ 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).**
|
|
76
|
+
|
|
77
|
+
## Disclaimer
|
|
78
|
+
|
|
79
|
+
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
80
|
+
|
|
81
|
+
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.
|
package/diff-source.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Input ingestion + migration emission for `pgpm diff`.
|
|
3
|
+
*
|
|
4
|
+
* A diff side can be a pgpm module directory, a raw .sql file, or a live
|
|
5
|
+
* database (handled by the CLI via pg_dump; the dump text lands here through
|
|
6
|
+
* {@link sqlToDiffChanges}). Every side normalizes to the same
|
|
7
|
+
* `DiffInputChange[]` seam the semantic diff driver consumes, so the
|
|
8
|
+
* comparison is source- and dial-invariant.
|
|
9
|
+
*/
|
|
10
|
+
import { PgpmRow } from '@pgpmjs/ast';
|
|
11
|
+
import type { DiffInputChange, SemanticDeltaChange } from '@pgpmjs/transform';
|
|
12
|
+
/** What a diff side spec resolves to. */
|
|
13
|
+
export type DiffSideKind = 'module' | 'sql' | 'database';
|
|
14
|
+
/** A diff side normalized to the semantic diff driver's input seam. */
|
|
15
|
+
export interface DiffSide {
|
|
16
|
+
kind: DiffSideKind;
|
|
17
|
+
/** Human-readable label for messages (module name, file, db). */
|
|
18
|
+
label: string;
|
|
19
|
+
changes: DiffInputChange[];
|
|
20
|
+
warnings: string[];
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Classify a side spec: `db:<name>` or a postgres:// / postgresql://
|
|
24
|
+
* connection string is a live database; a directory containing pgpm.plan is
|
|
25
|
+
* a module; an existing file is raw SQL.
|
|
26
|
+
*/
|
|
27
|
+
export declare const resolveDiffSideKind: (spec: string) => DiffSideKind;
|
|
28
|
+
/**
|
|
29
|
+
* Strip the pg_dump session preamble (SET/set_config, psql meta-commands)
|
|
30
|
+
* so the remaining text is pure DDL the classifier understands. Only whole
|
|
31
|
+
* lines are stripped โ SET clauses inside function bodies are untouched.
|
|
32
|
+
*/
|
|
33
|
+
export declare const stripDumpPreamble: (sql: string) => string;
|
|
34
|
+
/** Wrap raw SQL text (a .sql file or a schema dump) as a single diff change. */
|
|
35
|
+
export declare const sqlToDiffChanges: (sql: string, name: string) => DiffInputChange[];
|
|
36
|
+
/**
|
|
37
|
+
* Load an on-disk diff side (module directory or .sql file). Live databases
|
|
38
|
+
* are dumped by the caller and fed through {@link sqlToDiffChanges}.
|
|
39
|
+
*/
|
|
40
|
+
export declare const loadDiffSideFromDisk: (spec: string) => DiffSide;
|
|
41
|
+
/**
|
|
42
|
+
* Convert the semantic diff's delta changes into writable pgpm rows.
|
|
43
|
+
* Plan order is the delta order (drops first, then creates/alters); when two
|
|
44
|
+
* changes derive the same spec path, later occurrences get the alteration
|
|
45
|
+
* convention (`alterationPathFor`), with the parent added to their deps.
|
|
46
|
+
*/
|
|
47
|
+
export declare const deltaChangesToRows: (changes: SemanticDeltaChange[]) => PgpmRow[];
|
package/diff-source.js
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
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.deltaChangesToRows = exports.loadDiffSideFromDisk = exports.sqlToDiffChanges = exports.stripDumpPreamble = exports.resolveDiffSideKind = void 0;
|
|
37
|
+
const naming_spec_1 = require("@pgpmjs/naming-spec");
|
|
38
|
+
const transform_1 = require("@pgpmjs/transform");
|
|
39
|
+
const fs = __importStar(require("fs"));
|
|
40
|
+
const path = __importStar(require("path"));
|
|
41
|
+
/**
|
|
42
|
+
* Classify a side spec: `db:<name>` or a postgres:// / postgresql://
|
|
43
|
+
* connection string is a live database; a directory containing pgpm.plan is
|
|
44
|
+
* a module; an existing file is raw SQL.
|
|
45
|
+
*/
|
|
46
|
+
const resolveDiffSideKind = (spec) => {
|
|
47
|
+
if (/^postgres(ql)?:\/\//.test(spec) || spec.startsWith('db:'))
|
|
48
|
+
return 'database';
|
|
49
|
+
const resolved = path.resolve(spec);
|
|
50
|
+
if (fs.existsSync(resolved)) {
|
|
51
|
+
if (fs.statSync(resolved).isDirectory()) {
|
|
52
|
+
if (fs.existsSync(path.join(resolved, 'pgpm.plan')))
|
|
53
|
+
return 'module';
|
|
54
|
+
throw new Error(`${spec}: directory has no pgpm.plan (not a pgpm module)`);
|
|
55
|
+
}
|
|
56
|
+
return 'sql';
|
|
57
|
+
}
|
|
58
|
+
throw new Error(`${spec}: not a module directory, .sql file, db:<name>, or connection string`);
|
|
59
|
+
};
|
|
60
|
+
exports.resolveDiffSideKind = resolveDiffSideKind;
|
|
61
|
+
/** Lines pg_dump emits that carry no schema content. */
|
|
62
|
+
const DUMP_NOISE = [
|
|
63
|
+
/^\\/, // psql meta-commands (\connect, \restrict, ...)
|
|
64
|
+
/^SET\s+[\w.]+\s*(=|TO)\s*[^;]*;?\s*$/i, // session SET preamble
|
|
65
|
+
/^SELECT\s+pg_catalog\.set_config\(/i
|
|
66
|
+
];
|
|
67
|
+
/**
|
|
68
|
+
* Strip the pg_dump session preamble (SET/set_config, psql meta-commands)
|
|
69
|
+
* so the remaining text is pure DDL the classifier understands. Only whole
|
|
70
|
+
* lines are stripped โ SET clauses inside function bodies are untouched.
|
|
71
|
+
*/
|
|
72
|
+
const stripDumpPreamble = (sql) => sql
|
|
73
|
+
.split('\n')
|
|
74
|
+
.filter(line => !DUMP_NOISE.some(re => re.test(line.trim())))
|
|
75
|
+
.join('\n')
|
|
76
|
+
.trim();
|
|
77
|
+
exports.stripDumpPreamble = stripDumpPreamble;
|
|
78
|
+
/** Wrap raw SQL text (a .sql file or a schema dump) as a single diff change. */
|
|
79
|
+
const sqlToDiffChanges = (sql, name) => [
|
|
80
|
+
{
|
|
81
|
+
name,
|
|
82
|
+
dependencies: [],
|
|
83
|
+
deploy: (0, exports.stripDumpPreamble)((0, transform_1.stripTransactionWrapper)(sql))
|
|
84
|
+
}
|
|
85
|
+
];
|
|
86
|
+
exports.sqlToDiffChanges = sqlToDiffChanges;
|
|
87
|
+
/**
|
|
88
|
+
* Load an on-disk diff side (module directory or .sql file). Live databases
|
|
89
|
+
* are dumped by the caller and fed through {@link sqlToDiffChanges}.
|
|
90
|
+
*/
|
|
91
|
+
const loadDiffSideFromDisk = (spec) => {
|
|
92
|
+
const kind = (0, exports.resolveDiffSideKind)(spec);
|
|
93
|
+
if (kind === 'database') {
|
|
94
|
+
throw new Error(`${spec}: live database sides must be dumped by the caller`);
|
|
95
|
+
}
|
|
96
|
+
const resolved = path.resolve(spec);
|
|
97
|
+
if (kind === 'module') {
|
|
98
|
+
const source = (0, transform_1.loadModuleSource)(resolved);
|
|
99
|
+
return {
|
|
100
|
+
kind,
|
|
101
|
+
label: source.name,
|
|
102
|
+
changes: source.changes.map(change => ({
|
|
103
|
+
name: change.name,
|
|
104
|
+
dependencies: change.dependencies,
|
|
105
|
+
deploy: change.deploy
|
|
106
|
+
})),
|
|
107
|
+
warnings: source.warnings
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
kind,
|
|
112
|
+
label: path.basename(resolved),
|
|
113
|
+
changes: (0, exports.sqlToDiffChanges)(fs.readFileSync(resolved, 'utf-8'), path.basename(resolved, '.sql')),
|
|
114
|
+
warnings: []
|
|
115
|
+
};
|
|
116
|
+
};
|
|
117
|
+
exports.loadDiffSideFromDisk = loadDiffSideFromDisk;
|
|
118
|
+
/**
|
|
119
|
+
* Convert the semantic diff's delta changes into writable pgpm rows.
|
|
120
|
+
* Plan order is the delta order (drops first, then creates/alters); when two
|
|
121
|
+
* changes derive the same spec path, later occurrences get the alteration
|
|
122
|
+
* convention (`alterationPathFor`), with the parent added to their deps.
|
|
123
|
+
*/
|
|
124
|
+
const deltaChangesToRows = (changes) => {
|
|
125
|
+
const counters = new Map();
|
|
126
|
+
const taken = new Set();
|
|
127
|
+
return changes.map(change => {
|
|
128
|
+
let deploy = change.name;
|
|
129
|
+
const deps = [...change.dependencies];
|
|
130
|
+
if (taken.has(deploy)) {
|
|
131
|
+
let n = (counters.get(change.name) ?? 0) + 1;
|
|
132
|
+
while (taken.has((0, naming_spec_1.alterationPathFor)(change.name, n)))
|
|
133
|
+
n++;
|
|
134
|
+
counters.set(change.name, n);
|
|
135
|
+
deploy = (0, naming_spec_1.alterationPathFor)(change.name, n);
|
|
136
|
+
if (!deps.includes(change.name))
|
|
137
|
+
deps.push(change.name);
|
|
138
|
+
}
|
|
139
|
+
taken.add(deploy);
|
|
140
|
+
return {
|
|
141
|
+
name: deploy,
|
|
142
|
+
deploy,
|
|
143
|
+
deps: deps.filter(dep => taken.has(dep) && dep !== deploy),
|
|
144
|
+
content: change.deploy,
|
|
145
|
+
revert: change.revert,
|
|
146
|
+
verify: change.verify
|
|
147
|
+
};
|
|
148
|
+
});
|
|
149
|
+
};
|
|
150
|
+
exports.deltaChangesToRows = deltaChangesToRows;
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { alterationPathFor } from '@pgpmjs/naming-spec';
|
|
2
|
+
import { loadModuleSource, stripTransactionWrapper } from '@pgpmjs/transform';
|
|
3
|
+
import * as fs from 'fs';
|
|
4
|
+
import * as path from 'path';
|
|
5
|
+
/**
|
|
6
|
+
* Classify a side spec: `db:<name>` or a postgres:// / postgresql://
|
|
7
|
+
* connection string is a live database; a directory containing pgpm.plan is
|
|
8
|
+
* a module; an existing file is raw SQL.
|
|
9
|
+
*/
|
|
10
|
+
export const resolveDiffSideKind = (spec) => {
|
|
11
|
+
if (/^postgres(ql)?:\/\//.test(spec) || spec.startsWith('db:'))
|
|
12
|
+
return 'database';
|
|
13
|
+
const resolved = path.resolve(spec);
|
|
14
|
+
if (fs.existsSync(resolved)) {
|
|
15
|
+
if (fs.statSync(resolved).isDirectory()) {
|
|
16
|
+
if (fs.existsSync(path.join(resolved, 'pgpm.plan')))
|
|
17
|
+
return 'module';
|
|
18
|
+
throw new Error(`${spec}: directory has no pgpm.plan (not a pgpm module)`);
|
|
19
|
+
}
|
|
20
|
+
return 'sql';
|
|
21
|
+
}
|
|
22
|
+
throw new Error(`${spec}: not a module directory, .sql file, db:<name>, or connection string`);
|
|
23
|
+
};
|
|
24
|
+
/** Lines pg_dump emits that carry no schema content. */
|
|
25
|
+
const DUMP_NOISE = [
|
|
26
|
+
/^\\/, // psql meta-commands (\connect, \restrict, ...)
|
|
27
|
+
/^SET\s+[\w.]+\s*(=|TO)\s*[^;]*;?\s*$/i, // session SET preamble
|
|
28
|
+
/^SELECT\s+pg_catalog\.set_config\(/i
|
|
29
|
+
];
|
|
30
|
+
/**
|
|
31
|
+
* Strip the pg_dump session preamble (SET/set_config, psql meta-commands)
|
|
32
|
+
* so the remaining text is pure DDL the classifier understands. Only whole
|
|
33
|
+
* lines are stripped โ SET clauses inside function bodies are untouched.
|
|
34
|
+
*/
|
|
35
|
+
export const stripDumpPreamble = (sql) => sql
|
|
36
|
+
.split('\n')
|
|
37
|
+
.filter(line => !DUMP_NOISE.some(re => re.test(line.trim())))
|
|
38
|
+
.join('\n')
|
|
39
|
+
.trim();
|
|
40
|
+
/** Wrap raw SQL text (a .sql file or a schema dump) as a single diff change. */
|
|
41
|
+
export const sqlToDiffChanges = (sql, name) => [
|
|
42
|
+
{
|
|
43
|
+
name,
|
|
44
|
+
dependencies: [],
|
|
45
|
+
deploy: stripDumpPreamble(stripTransactionWrapper(sql))
|
|
46
|
+
}
|
|
47
|
+
];
|
|
48
|
+
/**
|
|
49
|
+
* Load an on-disk diff side (module directory or .sql file). Live databases
|
|
50
|
+
* are dumped by the caller and fed through {@link sqlToDiffChanges}.
|
|
51
|
+
*/
|
|
52
|
+
export const loadDiffSideFromDisk = (spec) => {
|
|
53
|
+
const kind = resolveDiffSideKind(spec);
|
|
54
|
+
if (kind === 'database') {
|
|
55
|
+
throw new Error(`${spec}: live database sides must be dumped by the caller`);
|
|
56
|
+
}
|
|
57
|
+
const resolved = path.resolve(spec);
|
|
58
|
+
if (kind === 'module') {
|
|
59
|
+
const source = loadModuleSource(resolved);
|
|
60
|
+
return {
|
|
61
|
+
kind,
|
|
62
|
+
label: source.name,
|
|
63
|
+
changes: source.changes.map(change => ({
|
|
64
|
+
name: change.name,
|
|
65
|
+
dependencies: change.dependencies,
|
|
66
|
+
deploy: change.deploy
|
|
67
|
+
})),
|
|
68
|
+
warnings: source.warnings
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
kind,
|
|
73
|
+
label: path.basename(resolved),
|
|
74
|
+
changes: sqlToDiffChanges(fs.readFileSync(resolved, 'utf-8'), path.basename(resolved, '.sql')),
|
|
75
|
+
warnings: []
|
|
76
|
+
};
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* Convert the semantic diff's delta changes into writable pgpm rows.
|
|
80
|
+
* Plan order is the delta order (drops first, then creates/alters); when two
|
|
81
|
+
* changes derive the same spec path, later occurrences get the alteration
|
|
82
|
+
* convention (`alterationPathFor`), with the parent added to their deps.
|
|
83
|
+
*/
|
|
84
|
+
export const deltaChangesToRows = (changes) => {
|
|
85
|
+
const counters = new Map();
|
|
86
|
+
const taken = new Set();
|
|
87
|
+
return changes.map(change => {
|
|
88
|
+
let deploy = change.name;
|
|
89
|
+
const deps = [...change.dependencies];
|
|
90
|
+
if (taken.has(deploy)) {
|
|
91
|
+
let n = (counters.get(change.name) ?? 0) + 1;
|
|
92
|
+
while (taken.has(alterationPathFor(change.name, n)))
|
|
93
|
+
n++;
|
|
94
|
+
counters.set(change.name, n);
|
|
95
|
+
deploy = alterationPathFor(change.name, n);
|
|
96
|
+
if (!deps.includes(change.name))
|
|
97
|
+
deps.push(change.name);
|
|
98
|
+
}
|
|
99
|
+
taken.add(deploy);
|
|
100
|
+
return {
|
|
101
|
+
name: deploy,
|
|
102
|
+
deploy,
|
|
103
|
+
deps: deps.filter(dep => taken.has(dep) && dep !== deploy),
|
|
104
|
+
content: change.deploy,
|
|
105
|
+
revert: change.revert,
|
|
106
|
+
verify: change.verify
|
|
107
|
+
};
|
|
108
|
+
});
|
|
109
|
+
};
|
package/esm/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { deltaChangesToRows, loadDiffSideFromDisk, resolveDiffSideKind, sqlToDiffChanges, stripDumpPreamble } from './diff-source';
|
package/index.d.ts
ADDED
package/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.stripDumpPreamble = exports.sqlToDiffChanges = exports.resolveDiffSideKind = exports.loadDiffSideFromDisk = exports.deltaChangesToRows = void 0;
|
|
4
|
+
var diff_source_1 = require("./diff-source");
|
|
5
|
+
Object.defineProperty(exports, "deltaChangesToRows", { enumerable: true, get: function () { return diff_source_1.deltaChangesToRows; } });
|
|
6
|
+
Object.defineProperty(exports, "loadDiffSideFromDisk", { enumerable: true, get: function () { return diff_source_1.loadDiffSideFromDisk; } });
|
|
7
|
+
Object.defineProperty(exports, "resolveDiffSideKind", { enumerable: true, get: function () { return diff_source_1.resolveDiffSideKind; } });
|
|
8
|
+
Object.defineProperty(exports, "sqlToDiffChanges", { enumerable: true, get: function () { return diff_source_1.sqlToDiffChanges; } });
|
|
9
|
+
Object.defineProperty(exports, "stripDumpPreamble", { enumerable: true, get: function () { return diff_source_1.stripDumpPreamble; } });
|
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@pgpmjs/diff",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"author": "Constructive <developers@constructive.io>",
|
|
5
|
+
"description": "pgpm diff โ identity-keyed semantic schema diff between pgpm modules, SQL dumps, and live databases",
|
|
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
|
+
"diff",
|
|
38
|
+
"schema",
|
|
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
|
+
}
|