@pgpmjs/core 7.22.0 → 7.23.0
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/diff/index.d.ts +2 -0
- package/diff/index.js +18 -0
- package/diff/ledger.d.ts +74 -0
- package/diff/ledger.js +142 -0
- package/diff/sides.d.ts +42 -0
- package/diff/sides.js +128 -0
- package/dump/pg-dump.d.ts +68 -0
- package/dump/pg-dump.js +106 -0
- package/esm/diff/index.js +2 -0
- package/esm/diff/ledger.js +101 -0
- package/esm/diff/sides.js +87 -0
- package/esm/dump/pg-dump.js +99 -0
- package/esm/index.js +4 -1
- package/esm/migrate/client.js +42 -0
- package/esm/utils/database-spec.js +29 -0
- package/index.d.ts +5 -1
- package/index.js +5 -1
- package/migrate/client.d.ts +22 -0
- package/migrate/client.js +42 -0
- package/package.json +15 -14
- package/utils/database-spec.d.ts +18 -0
- package/utils/database-spec.js +35 -0
package/diff/index.d.ts
ADDED
package/diff/index.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./ledger"), exports);
|
|
18
|
+
__exportStar(require("./sides"), exports);
|
package/diff/ledger.d.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ledger-aware reconciliation: relate a plan-bearing diff side to a live
|
|
3
|
+
* database's `pgpm_migrate` ledger.
|
|
4
|
+
*
|
|
5
|
+
* Two independent judgements are combined here. Name/hash classification
|
|
6
|
+
* (`classifyAgainstLedger`) says what the ledger literally records. Semantic
|
|
7
|
+
* coverage (`coverChanges`) says which of a side's changes the other side's
|
|
8
|
+
* catalog already satisfies — which is what survives a regenerated plan
|
|
9
|
+
* whose changes were renamed, regrouped, or reordered. A change that is
|
|
10
|
+
* `pending` by name but `satisfied` semantically is exactly what a backfill
|
|
11
|
+
* should record without re-executing.
|
|
12
|
+
*/
|
|
13
|
+
import type { BackfillSelection, LedgerBackfillEntry, LedgerChangeRecord, LedgerClassification, PlanChangeRef } from '@pgpmjs/diff';
|
|
14
|
+
import type { ChangeCoverage, DiffInputChange, ModuleSource, SemanticDiffResult } from '@pgpmjs/transform';
|
|
15
|
+
import type { PgConfig } from 'pg-env';
|
|
16
|
+
/**
|
|
17
|
+
* Candidate hashes for every plan entry of a set of modules: the raw content
|
|
18
|
+
* hash (what `pgpm deploy` records by default) and the AST hash (what
|
|
19
|
+
* `DEPLOYMENT_HASH_METHOD=ast` records — formatting- and comment-proof). A
|
|
20
|
+
* ledger row matches the plan entry when it recorded either.
|
|
21
|
+
*/
|
|
22
|
+
export declare const planChangeRefs: (modules: ModuleSource[]) => Promise<PlanChangeRef[]>;
|
|
23
|
+
/** Read a database's `pgpm_migrate` ledger as a snapshot, in deploy order. */
|
|
24
|
+
export declare const readLedgerSnapshot: (config: PgConfig) => Promise<LedgerChangeRecord[]>;
|
|
25
|
+
/** A plan-vs-ledger reconciliation, with the backfill it implies. */
|
|
26
|
+
export interface LedgerReport extends BackfillSelection {
|
|
27
|
+
classification: LedgerClassification;
|
|
28
|
+
coverage: ChangeCoverage[];
|
|
29
|
+
/** Backfill script for {@link BackfillSelection.entries}, when non-empty. */
|
|
30
|
+
backfillSql?: string;
|
|
31
|
+
}
|
|
32
|
+
export interface LedgerReportOptions {
|
|
33
|
+
/** Database whose ledger is the deployment cursor (`db:<name>` or a DSN). */
|
|
34
|
+
config: PgConfig;
|
|
35
|
+
/** The plan-bearing side: a workspace or module directory. */
|
|
36
|
+
spec: string;
|
|
37
|
+
cwd?: string;
|
|
38
|
+
/** That side's changes, as flattened for the diff. */
|
|
39
|
+
changes: DiffInputChange[];
|
|
40
|
+
/** The semantic diff of the two sides, for coverage. */
|
|
41
|
+
diff: SemanticDiffResult;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Build the reconciliation report: classify the side's plan against the
|
|
45
|
+
* ledger, compute semantic coverage against the diff, and emit the backfill
|
|
46
|
+
* for entries that are unrecorded but already satisfied, so a subsequent
|
|
47
|
+
* `pgpm deploy` executes only the genuine delta.
|
|
48
|
+
*/
|
|
49
|
+
export declare const buildLedgerReport: (options: LedgerReportOptions) => Promise<LedgerReport>;
|
|
50
|
+
/**
|
|
51
|
+
* Every plan entry of a set of modules as a backfill row, in plan order — the
|
|
52
|
+
* whole plan, not the satisfied subset. This is the "baseline" input: a
|
|
53
|
+
* database that already carries a plan's schema (e.g. one imported from a
|
|
54
|
+
* dump, or one adopted from outside pgpm) can record the entire plan as
|
|
55
|
+
* deployed without re-executing any DDL. Entries with no candidate hash
|
|
56
|
+
* (deploy script missing) are skipped, mirroring {@link selectBackfillEntries}.
|
|
57
|
+
*/
|
|
58
|
+
export declare const baselineBackfillEntries: (modules: ModuleSource[]) => Promise<LedgerBackfillEntry[]>;
|
|
59
|
+
/** A whole-plan baseline backfill for a plan-bearing side. */
|
|
60
|
+
export interface BaselineBackfill {
|
|
61
|
+
/** Backfill rows for every plan entry, in plan order. */
|
|
62
|
+
entries: LedgerBackfillEntry[];
|
|
63
|
+
/** Idempotent log-only backfill script for {@link entries}. */
|
|
64
|
+
backfillSql: string;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Build a whole-plan baseline backfill for a workspace or module directory:
|
|
68
|
+
* record every change as already deployed, log-only, so a `pgpm deploy`
|
|
69
|
+
* afterward is a no-op and the database is adopted at the plan's head. The
|
|
70
|
+
* target database must already have the `pgpm_migrate` schema
|
|
71
|
+
* (`pgpm migrate init` or any prior deploy creates it, and applying the
|
|
72
|
+
* baseline through `PgpmMigrate.deploy({ logOnly: true })` initializes it).
|
|
73
|
+
*/
|
|
74
|
+
export declare const buildBaselineBackfill: (spec: string, cwd?: string) => Promise<BaselineBackfill>;
|
package/diff/ledger.js
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
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.buildBaselineBackfill = exports.baselineBackfillEntries = exports.buildLedgerReport = exports.readLedgerSnapshot = exports.planChangeRefs = void 0;
|
|
37
|
+
const diff_1 = require("@pgpmjs/diff");
|
|
38
|
+
const transform_1 = require("@pgpmjs/transform");
|
|
39
|
+
const fs = __importStar(require("fs"));
|
|
40
|
+
const path = __importStar(require("path"));
|
|
41
|
+
const client_1 = require("../migrate/client");
|
|
42
|
+
const hash_1 = require("../migrate/utils/hash");
|
|
43
|
+
const sides_1 = require("./sides");
|
|
44
|
+
/**
|
|
45
|
+
* Candidate hashes for every plan entry of a set of modules: the raw content
|
|
46
|
+
* hash (what `pgpm deploy` records by default) and the AST hash (what
|
|
47
|
+
* `DEPLOYMENT_HASH_METHOD=ast` records — formatting- and comment-proof). A
|
|
48
|
+
* ledger row matches the plan entry when it recorded either.
|
|
49
|
+
*/
|
|
50
|
+
const planChangeRefs = async (modules) => {
|
|
51
|
+
const refs = [];
|
|
52
|
+
for (const mod of modules) {
|
|
53
|
+
for (const change of mod.changes) {
|
|
54
|
+
const deployPath = path.join(mod.modulePath, 'deploy', `${change.name}.sql`);
|
|
55
|
+
const hashes = [];
|
|
56
|
+
if (fs.existsSync(deployPath)) {
|
|
57
|
+
hashes.push((0, hash_1.hashString)(fs.readFileSync(deployPath, 'utf-8')));
|
|
58
|
+
hashes.push(await (0, hash_1.hashSqlFile)(deployPath));
|
|
59
|
+
}
|
|
60
|
+
refs.push({
|
|
61
|
+
package: mod.name,
|
|
62
|
+
name: change.name,
|
|
63
|
+
hashes,
|
|
64
|
+
dependencies: change.dependencies
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return refs;
|
|
69
|
+
};
|
|
70
|
+
exports.planChangeRefs = planChangeRefs;
|
|
71
|
+
/** Read a database's `pgpm_migrate` ledger as a snapshot, in deploy order. */
|
|
72
|
+
const readLedgerSnapshot = async (config) => {
|
|
73
|
+
const rows = await new client_1.PgpmMigrate(config).readDeployedState();
|
|
74
|
+
return rows.map(row => ({
|
|
75
|
+
package: row.package,
|
|
76
|
+
changeName: row.changeName,
|
|
77
|
+
scriptHash: row.scriptHash,
|
|
78
|
+
deployedAt: row.deployedAt,
|
|
79
|
+
requires: row.requires
|
|
80
|
+
}));
|
|
81
|
+
};
|
|
82
|
+
exports.readLedgerSnapshot = readLedgerSnapshot;
|
|
83
|
+
/**
|
|
84
|
+
* Build the reconciliation report: classify the side's plan against the
|
|
85
|
+
* ledger, compute semantic coverage against the diff, and emit the backfill
|
|
86
|
+
* for entries that are unrecorded but already satisfied, so a subsequent
|
|
87
|
+
* `pgpm deploy` executes only the genuine delta.
|
|
88
|
+
*/
|
|
89
|
+
const buildLedgerReport = async (options) => {
|
|
90
|
+
const modules = await (0, sides_1.loadPlanSideModules)(options.spec, options.cwd);
|
|
91
|
+
const refs = await (0, exports.planChangeRefs)(modules);
|
|
92
|
+
const ledger = await (0, exports.readLedgerSnapshot)(options.config);
|
|
93
|
+
const classification = (0, diff_1.classifyAgainstLedger)(refs, ledger);
|
|
94
|
+
const coverage = (0, transform_1.coverChanges)(options.changes, options.diff);
|
|
95
|
+
const selection = (0, diff_1.selectBackfillEntries)(refs, classification, coverage);
|
|
96
|
+
return {
|
|
97
|
+
...selection,
|
|
98
|
+
classification,
|
|
99
|
+
coverage,
|
|
100
|
+
backfillSql: selection.entries.length > 0 ? (0, diff_1.emitLedgerBackfill)(selection.entries) : undefined
|
|
101
|
+
};
|
|
102
|
+
};
|
|
103
|
+
exports.buildLedgerReport = buildLedgerReport;
|
|
104
|
+
/**
|
|
105
|
+
* Every plan entry of a set of modules as a backfill row, in plan order — the
|
|
106
|
+
* whole plan, not the satisfied subset. This is the "baseline" input: a
|
|
107
|
+
* database that already carries a plan's schema (e.g. one imported from a
|
|
108
|
+
* dump, or one adopted from outside pgpm) can record the entire plan as
|
|
109
|
+
* deployed without re-executing any DDL. Entries with no candidate hash
|
|
110
|
+
* (deploy script missing) are skipped, mirroring {@link selectBackfillEntries}.
|
|
111
|
+
*/
|
|
112
|
+
const baselineBackfillEntries = async (modules) => {
|
|
113
|
+
const refs = await (0, exports.planChangeRefs)(modules);
|
|
114
|
+
const entries = [];
|
|
115
|
+
for (const ref of refs) {
|
|
116
|
+
const scriptHash = ref.hashes[0];
|
|
117
|
+
if (!scriptHash)
|
|
118
|
+
continue;
|
|
119
|
+
entries.push({
|
|
120
|
+
package: ref.package,
|
|
121
|
+
changeName: ref.name,
|
|
122
|
+
scriptHash,
|
|
123
|
+
requires: ref.dependencies
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
return entries;
|
|
127
|
+
};
|
|
128
|
+
exports.baselineBackfillEntries = baselineBackfillEntries;
|
|
129
|
+
/**
|
|
130
|
+
* Build a whole-plan baseline backfill for a workspace or module directory:
|
|
131
|
+
* record every change as already deployed, log-only, so a `pgpm deploy`
|
|
132
|
+
* afterward is a no-op and the database is adopted at the plan's head. The
|
|
133
|
+
* target database must already have the `pgpm_migrate` schema
|
|
134
|
+
* (`pgpm migrate init` or any prior deploy creates it, and applying the
|
|
135
|
+
* baseline through `PgpmMigrate.deploy({ logOnly: true })` initializes it).
|
|
136
|
+
*/
|
|
137
|
+
const buildBaselineBackfill = async (spec, cwd) => {
|
|
138
|
+
const modules = await (0, sides_1.loadPlanSideModules)(spec, cwd);
|
|
139
|
+
const entries = await (0, exports.baselineBackfillEntries)(modules);
|
|
140
|
+
return { entries, backfillSql: (0, diff_1.emitLedgerBackfill)(entries) };
|
|
141
|
+
};
|
|
142
|
+
exports.buildBaselineBackfill = buildBaselineBackfill;
|
package/diff/sides.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Diff-side loading: turn a side spec — module directory, workspace
|
|
3
|
+
* directory, .sql file, or live database — into the single
|
|
4
|
+
* `DiffInputChange[]` seam the semantic diff consumes.
|
|
5
|
+
*
|
|
6
|
+
* `@pgpmjs/diff` owns the pure normalizations (classification, flattening,
|
|
7
|
+
* SQL wrapping); this module supplies the I/O they need and that only core
|
|
8
|
+
* has: workspace module-map resolution (`PgpmPackage`) and `pg_dump`.
|
|
9
|
+
*/
|
|
10
|
+
import type { DiffSide } from '@pgpmjs/diff';
|
|
11
|
+
import type { ModuleSource } from '@pgpmjs/transform';
|
|
12
|
+
/** A workspace's local modules, loaded in dependency order. */
|
|
13
|
+
export interface WorkspaceModuleSources {
|
|
14
|
+
modules: ModuleSource[];
|
|
15
|
+
warnings: string[];
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Load every local module of a pgpm workspace as a `ModuleSource`, in
|
|
19
|
+
* cross-module dependency order.
|
|
20
|
+
*
|
|
21
|
+
* Ordering and membership come from the same resolver `deploy`/`verify`/
|
|
22
|
+
* `revert` use (`resolveWorkspaceExtensionDependencies`), so a workspace
|
|
23
|
+
* flattens the way it deploys. External extensions (installed Postgres
|
|
24
|
+
* extensions rather than local modules) are not authored schema and are
|
|
25
|
+
* skipped, as are modules without a plan (proxy / apply-spec modules).
|
|
26
|
+
*/
|
|
27
|
+
export declare const loadWorkspaceModuleSources: (workspaceDir: string) => Promise<WorkspaceModuleSources>;
|
|
28
|
+
/** Load a pgpm workspace directory as a flattened diff side. */
|
|
29
|
+
export declare const loadWorkspaceSide: (workspaceDir: string) => Promise<DiffSide>;
|
|
30
|
+
/** Load a live database's schema as a diff side (via `pg_dump`). */
|
|
31
|
+
export declare const loadDatabaseSide: (spec: string) => Promise<DiffSide>;
|
|
32
|
+
/**
|
|
33
|
+
* Load any diff side. Databases are dumped, workspaces are resolved and
|
|
34
|
+
* flattened, and modules / .sql files are read by `@pgpmjs/diff`.
|
|
35
|
+
*/
|
|
36
|
+
export declare const loadDiffSide: (spec: string, cwd?: string) => Promise<DiffSide>;
|
|
37
|
+
/**
|
|
38
|
+
* The modules behind a plan-bearing side: every local module for a
|
|
39
|
+
* workspace, or the single module for a module directory. Used by ledger
|
|
40
|
+
* classification, which needs plan entries rather than flattened changes.
|
|
41
|
+
*/
|
|
42
|
+
export declare const loadPlanSideModules: (spec: string, cwd?: string) => Promise<ModuleSource[]>;
|
package/diff/sides.js
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
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.loadPlanSideModules = exports.loadDiffSide = exports.loadDatabaseSide = exports.loadWorkspaceSide = exports.loadWorkspaceModuleSources = void 0;
|
|
37
|
+
const diff_1 = require("@pgpmjs/diff");
|
|
38
|
+
const transform_1 = require("@pgpmjs/transform");
|
|
39
|
+
const fs = __importStar(require("fs"));
|
|
40
|
+
const path = __importStar(require("path"));
|
|
41
|
+
const pgpm_1 = require("../core/class/pgpm");
|
|
42
|
+
const pg_dump_1 = require("../dump/pg-dump");
|
|
43
|
+
const database_spec_1 = require("../utils/database-spec");
|
|
44
|
+
/**
|
|
45
|
+
* Load every local module of a pgpm workspace as a `ModuleSource`, in
|
|
46
|
+
* cross-module dependency order.
|
|
47
|
+
*
|
|
48
|
+
* Ordering and membership come from the same resolver `deploy`/`verify`/
|
|
49
|
+
* `revert` use (`resolveWorkspaceExtensionDependencies`), so a workspace
|
|
50
|
+
* flattens the way it deploys. External extensions (installed Postgres
|
|
51
|
+
* extensions rather than local modules) are not authored schema and are
|
|
52
|
+
* skipped, as are modules without a plan (proxy / apply-spec modules).
|
|
53
|
+
*/
|
|
54
|
+
const loadWorkspaceModuleSources = async (workspaceDir) => {
|
|
55
|
+
const pkg = new pgpm_1.PgpmPackage(path.resolve(workspaceDir));
|
|
56
|
+
const workspacePath = pkg.getWorkspacePath();
|
|
57
|
+
if (!workspacePath) {
|
|
58
|
+
throw new Error(`${workspaceDir}: not a pgpm workspace (no pgpm.json / pgpm.config.js)`);
|
|
59
|
+
}
|
|
60
|
+
const moduleMap = pkg.getModuleMap();
|
|
61
|
+
const { resolved, external } = await pkg.resolveWorkspaceExtensionDependencies();
|
|
62
|
+
const warnings = [];
|
|
63
|
+
const modules = [];
|
|
64
|
+
for (const name of resolved) {
|
|
65
|
+
if (external.includes(name))
|
|
66
|
+
continue;
|
|
67
|
+
const entry = moduleMap[name];
|
|
68
|
+
if (!entry) {
|
|
69
|
+
warnings.push(`${name}: resolved module is not in the workspace module map; skipped`);
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
const moduleDir = path.resolve(workspacePath, entry.path);
|
|
73
|
+
if (!fs.existsSync(path.join(moduleDir, 'pgpm.plan'))) {
|
|
74
|
+
warnings.push(`${name}: no pgpm.plan (proxy or apply-spec module); skipped`);
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
const source = (0, transform_1.loadModuleSource)(moduleDir);
|
|
78
|
+
warnings.push(...source.warnings.map(w => `${name}: ${w}`));
|
|
79
|
+
modules.push(source);
|
|
80
|
+
}
|
|
81
|
+
return { modules, warnings };
|
|
82
|
+
};
|
|
83
|
+
exports.loadWorkspaceModuleSources = loadWorkspaceModuleSources;
|
|
84
|
+
/** Load a pgpm workspace directory as a flattened diff side. */
|
|
85
|
+
const loadWorkspaceSide = async (workspaceDir) => {
|
|
86
|
+
const resolved = path.resolve(workspaceDir);
|
|
87
|
+
const { modules, warnings } = await (0, exports.loadWorkspaceModuleSources)(resolved);
|
|
88
|
+
return {
|
|
89
|
+
kind: 'workspace',
|
|
90
|
+
label: path.basename(resolved),
|
|
91
|
+
changes: (0, diff_1.workspaceModulesToDiffChanges)(modules),
|
|
92
|
+
warnings
|
|
93
|
+
};
|
|
94
|
+
};
|
|
95
|
+
exports.loadWorkspaceSide = loadWorkspaceSide;
|
|
96
|
+
/** Load a live database's schema as a diff side (via `pg_dump`). */
|
|
97
|
+
const loadDatabaseSide = async (spec) => {
|
|
98
|
+
const label = (0, database_spec_1.databaseSpecLabel)(spec);
|
|
99
|
+
const sql = await (0, pg_dump_1.dumpSchemaForComparison)((0, database_spec_1.resolveDatabaseSpec)(spec));
|
|
100
|
+
return { kind: 'database', label, changes: (0, diff_1.sqlToDiffChanges)(sql, label), warnings: [] };
|
|
101
|
+
};
|
|
102
|
+
exports.loadDatabaseSide = loadDatabaseSide;
|
|
103
|
+
/**
|
|
104
|
+
* Load any diff side. Databases are dumped, workspaces are resolved and
|
|
105
|
+
* flattened, and modules / .sql files are read by `@pgpmjs/diff`.
|
|
106
|
+
*/
|
|
107
|
+
const loadDiffSide = async (spec, cwd = process.cwd()) => {
|
|
108
|
+
if ((0, database_spec_1.isDatabaseSpec)(spec))
|
|
109
|
+
return (0, exports.loadDatabaseSide)(spec);
|
|
110
|
+
const resolved = path.resolve(cwd, spec);
|
|
111
|
+
if ((0, diff_1.resolveDiffSideKind)(resolved) === 'workspace')
|
|
112
|
+
return (0, exports.loadWorkspaceSide)(resolved);
|
|
113
|
+
return (0, diff_1.loadDiffSideFromDisk)(resolved);
|
|
114
|
+
};
|
|
115
|
+
exports.loadDiffSide = loadDiffSide;
|
|
116
|
+
/**
|
|
117
|
+
* The modules behind a plan-bearing side: every local module for a
|
|
118
|
+
* workspace, or the single module for a module directory. Used by ledger
|
|
119
|
+
* classification, which needs plan entries rather than flattened changes.
|
|
120
|
+
*/
|
|
121
|
+
const loadPlanSideModules = async (spec, cwd = process.cwd()) => {
|
|
122
|
+
const resolved = path.resolve(cwd, spec);
|
|
123
|
+
if ((0, diff_1.resolveDiffSideKind)(resolved) === 'workspace') {
|
|
124
|
+
return (await (0, exports.loadWorkspaceModuleSources)(resolved)).modules;
|
|
125
|
+
}
|
|
126
|
+
return [(0, transform_1.loadModuleSource)(resolved)];
|
|
127
|
+
};
|
|
128
|
+
exports.loadPlanSideModules = loadPlanSideModules;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type { PgConfig } from 'pg-env';
|
|
2
|
+
/**
|
|
3
|
+
* Schemas that record deployment history rather than authored schema.
|
|
4
|
+
* Excluded when dumping a database for comparison: two databases with the
|
|
5
|
+
* same schema but different migration histories are the same schema.
|
|
6
|
+
*/
|
|
7
|
+
export declare const LEDGER_SCHEMAS: readonly ["pgpm_migrate", "sqitch"];
|
|
8
|
+
/** How to invoke `pg_dump` and what to ask it for. */
|
|
9
|
+
export interface PgDumpOptions {
|
|
10
|
+
/** Connection. Its `database` is passed explicitly, not just via PG* env. */
|
|
11
|
+
config: PgConfig;
|
|
12
|
+
/** Schema definitions only, no data. */
|
|
13
|
+
schemaOnly?: boolean;
|
|
14
|
+
/** Data only, no schema definitions. */
|
|
15
|
+
dataOnly?: boolean;
|
|
16
|
+
/** Emit data as INSERT statements instead of COPY. */
|
|
17
|
+
inserts?: boolean;
|
|
18
|
+
/** Emit data as INSERT statements naming every column. */
|
|
19
|
+
columnInserts?: boolean;
|
|
20
|
+
/** Omit ownership commands (default: true). */
|
|
21
|
+
noOwner?: boolean;
|
|
22
|
+
/** Omit GRANT/REVOKE commands. */
|
|
23
|
+
noPrivileges?: boolean;
|
|
24
|
+
/** Output format (default: plain). */
|
|
25
|
+
format?: 'plain' | 'custom' | 'directory' | 'tar';
|
|
26
|
+
/** Restrict to these schemas. */
|
|
27
|
+
schemas?: string[];
|
|
28
|
+
/** Skip these schemas (see {@link LEDGER_SCHEMAS}). */
|
|
29
|
+
excludeSchemas?: string[];
|
|
30
|
+
/** Restrict to these tables. */
|
|
31
|
+
tables?: string[];
|
|
32
|
+
/** Skip these tables. */
|
|
33
|
+
excludeTables?: string[];
|
|
34
|
+
/** Write the dump here. When unset, the dump is returned as a string. */
|
|
35
|
+
file?: string;
|
|
36
|
+
/** Flags appended verbatim, for anything not modelled above. */
|
|
37
|
+
extraArgs?: string[];
|
|
38
|
+
/**
|
|
39
|
+
* The `pg_dump` command to run, as argv (e.g.
|
|
40
|
+
* `['docker', 'exec', '-e', 'PGUSER=postgres', 'pg', 'pg_dump']`).
|
|
41
|
+
* Defaults to {@link resolvePgDumpCommand}.
|
|
42
|
+
*/
|
|
43
|
+
command?: string[];
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The `pg_dump` argv to use, resolved by the typed env layer
|
|
47
|
+
* ({@link getPgClientCommand}): honors `PGPM_PG_DUMP` / `PGPM_PG_CLIENT_PREFIX`
|
|
48
|
+
* so an older/absent local client can be pointed at a version-matched one,
|
|
49
|
+
* including inside a container. Tool location only; connection still comes
|
|
50
|
+
* from `pg-env`.
|
|
51
|
+
*/
|
|
52
|
+
export declare const resolvePgDumpCommand: () => string[];
|
|
53
|
+
/** Assemble `pg_dump` flags from options (exported for testing/inspection). */
|
|
54
|
+
export declare const buildPgDumpArgs: (options: PgDumpOptions) => string[];
|
|
55
|
+
/**
|
|
56
|
+
* Run `pg_dump`. Returns the dump text, or an empty string when `file` was
|
|
57
|
+
* given (pg_dump wrote it directly).
|
|
58
|
+
*/
|
|
59
|
+
export declare const pgDump: (options: PgDumpOptions) => Promise<string>;
|
|
60
|
+
/**
|
|
61
|
+
* Dump a database's schema for comparison: definitions only, no ownership,
|
|
62
|
+
* and without the migration-history schemas (which are the ledger, not the
|
|
63
|
+
* schema under comparison — read those with `PgpmMigrate.readDeployedState`).
|
|
64
|
+
*/
|
|
65
|
+
export declare const dumpSchemaForComparison: (config: PgConfig, options?: {
|
|
66
|
+
excludeSchemas?: string[];
|
|
67
|
+
command?: string[];
|
|
68
|
+
}) => Promise<string>;
|
package/dump/pg-dump.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.dumpSchemaForComparison = exports.pgDump = exports.buildPgDumpArgs = exports.resolvePgDumpCommand = exports.LEDGER_SCHEMAS = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* `pg_dump` as a typed core operation.
|
|
6
|
+
*
|
|
7
|
+
* Both `pgpm dump` (write a file) and `pgpm diff` (capture a schema for
|
|
8
|
+
* comparison) need the same process plumbing — connection env, flag
|
|
9
|
+
* assembly, error translation — so it lives here rather than being
|
|
10
|
+
* re-spawned per command.
|
|
11
|
+
*/
|
|
12
|
+
const child_process_1 = require("child_process");
|
|
13
|
+
const pg_env_1 = require("pg-env");
|
|
14
|
+
/**
|
|
15
|
+
* Schemas that record deployment history rather than authored schema.
|
|
16
|
+
* Excluded when dumping a database for comparison: two databases with the
|
|
17
|
+
* same schema but different migration histories are the same schema.
|
|
18
|
+
*/
|
|
19
|
+
exports.LEDGER_SCHEMAS = ['pgpm_migrate', 'sqitch'];
|
|
20
|
+
/**
|
|
21
|
+
* The `pg_dump` argv to use, resolved by the typed env layer
|
|
22
|
+
* ({@link getPgClientCommand}): honors `PGPM_PG_DUMP` / `PGPM_PG_CLIENT_PREFIX`
|
|
23
|
+
* so an older/absent local client can be pointed at a version-matched one,
|
|
24
|
+
* including inside a container. Tool location only; connection still comes
|
|
25
|
+
* from `pg-env`.
|
|
26
|
+
*/
|
|
27
|
+
const resolvePgDumpCommand = () => (0, pg_env_1.getPgClientCommand)('pg_dump');
|
|
28
|
+
exports.resolvePgDumpCommand = resolvePgDumpCommand;
|
|
29
|
+
/** Assemble `pg_dump` flags from options (exported for testing/inspection). */
|
|
30
|
+
const buildPgDumpArgs = (options) => {
|
|
31
|
+
const args = [];
|
|
32
|
+
if (options.format)
|
|
33
|
+
args.push(`--format=${options.format}`);
|
|
34
|
+
if (options.schemaOnly)
|
|
35
|
+
args.push('--schema-only');
|
|
36
|
+
if (options.dataOnly)
|
|
37
|
+
args.push('--data-only');
|
|
38
|
+
if (options.inserts)
|
|
39
|
+
args.push('--inserts');
|
|
40
|
+
if (options.columnInserts)
|
|
41
|
+
args.push('--column-inserts');
|
|
42
|
+
if (options.noOwner !== false)
|
|
43
|
+
args.push('--no-owner');
|
|
44
|
+
if (options.noPrivileges)
|
|
45
|
+
args.push('--no-privileges');
|
|
46
|
+
for (const schema of options.schemas ?? [])
|
|
47
|
+
args.push(`--schema=${schema}`);
|
|
48
|
+
for (const schema of options.excludeSchemas ?? [])
|
|
49
|
+
args.push(`--exclude-schema=${schema}`);
|
|
50
|
+
for (const table of options.tables ?? [])
|
|
51
|
+
args.push(`--table=${table}`);
|
|
52
|
+
for (const table of options.excludeTables ?? [])
|
|
53
|
+
args.push(`--exclude-table=${table}`);
|
|
54
|
+
if (options.file)
|
|
55
|
+
args.push('--file', options.file);
|
|
56
|
+
args.push(...(options.extraArgs ?? []));
|
|
57
|
+
// Pass the database explicitly rather than relying solely on PGDATABASE:
|
|
58
|
+
// a wrapped command (e.g. `docker exec`) does not inherit the host's env.
|
|
59
|
+
args.push('--dbname', options.config.database);
|
|
60
|
+
return args;
|
|
61
|
+
};
|
|
62
|
+
exports.buildPgDumpArgs = buildPgDumpArgs;
|
|
63
|
+
/**
|
|
64
|
+
* Run `pg_dump`. Returns the dump text, or an empty string when `file` was
|
|
65
|
+
* given (pg_dump wrote it directly).
|
|
66
|
+
*/
|
|
67
|
+
const pgDump = async (options) => {
|
|
68
|
+
const [cmd, ...prefixArgs] = options.command ?? (0, exports.resolvePgDumpCommand)();
|
|
69
|
+
const args = [...prefixArgs, ...(0, exports.buildPgDumpArgs)(options)];
|
|
70
|
+
const env = (0, pg_env_1.getSpawnEnvWithPg)(options.config);
|
|
71
|
+
return new Promise((resolve, reject) => {
|
|
72
|
+
const child = (0, child_process_1.spawn)(cmd, args, { env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
73
|
+
let out = '';
|
|
74
|
+
let err = '';
|
|
75
|
+
child.stdout.on('data', chunk => { out += chunk; });
|
|
76
|
+
child.stderr.on('data', chunk => { err += chunk; });
|
|
77
|
+
child.on('error', (e) => {
|
|
78
|
+
if (e.code === 'ENOENT') {
|
|
79
|
+
reject(new Error(`${cmd} not found; ensure PostgreSQL client tools are installed and in PATH, ` +
|
|
80
|
+
'or set PGPM_PG_DUMP / PGPM_PG_CLIENT_PREFIX to a version-matched pg_dump command'));
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
reject(e);
|
|
84
|
+
});
|
|
85
|
+
child.on('close', code => {
|
|
86
|
+
if (code === 0)
|
|
87
|
+
resolve(out);
|
|
88
|
+
else
|
|
89
|
+
reject(new Error(`pg_dump exited with code ${code}: ${err.trim()}`));
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
};
|
|
93
|
+
exports.pgDump = pgDump;
|
|
94
|
+
/**
|
|
95
|
+
* Dump a database's schema for comparison: definitions only, no ownership,
|
|
96
|
+
* and without the migration-history schemas (which are the ledger, not the
|
|
97
|
+
* schema under comparison — read those with `PgpmMigrate.readDeployedState`).
|
|
98
|
+
*/
|
|
99
|
+
const dumpSchemaForComparison = async (config, options = {}) => (0, exports.pgDump)({
|
|
100
|
+
config,
|
|
101
|
+
schemaOnly: true,
|
|
102
|
+
noOwner: true,
|
|
103
|
+
excludeSchemas: [...exports.LEDGER_SCHEMAS, ...(options.excludeSchemas ?? [])],
|
|
104
|
+
...(options.command ? { command: options.command } : {})
|
|
105
|
+
});
|
|
106
|
+
exports.dumpSchemaForComparison = dumpSchemaForComparison;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { classifyAgainstLedger, emitLedgerBackfill, selectBackfillEntries } from '@pgpmjs/diff';
|
|
2
|
+
import { coverChanges } from '@pgpmjs/transform';
|
|
3
|
+
import * as fs from 'fs';
|
|
4
|
+
import * as path from 'path';
|
|
5
|
+
import { PgpmMigrate } from '../migrate/client';
|
|
6
|
+
import { hashSqlFile, hashString } from '../migrate/utils/hash';
|
|
7
|
+
import { loadPlanSideModules } from './sides';
|
|
8
|
+
/**
|
|
9
|
+
* Candidate hashes for every plan entry of a set of modules: the raw content
|
|
10
|
+
* hash (what `pgpm deploy` records by default) and the AST hash (what
|
|
11
|
+
* `DEPLOYMENT_HASH_METHOD=ast` records — formatting- and comment-proof). A
|
|
12
|
+
* ledger row matches the plan entry when it recorded either.
|
|
13
|
+
*/
|
|
14
|
+
export const planChangeRefs = async (modules) => {
|
|
15
|
+
const refs = [];
|
|
16
|
+
for (const mod of modules) {
|
|
17
|
+
for (const change of mod.changes) {
|
|
18
|
+
const deployPath = path.join(mod.modulePath, 'deploy', `${change.name}.sql`);
|
|
19
|
+
const hashes = [];
|
|
20
|
+
if (fs.existsSync(deployPath)) {
|
|
21
|
+
hashes.push(hashString(fs.readFileSync(deployPath, 'utf-8')));
|
|
22
|
+
hashes.push(await hashSqlFile(deployPath));
|
|
23
|
+
}
|
|
24
|
+
refs.push({
|
|
25
|
+
package: mod.name,
|
|
26
|
+
name: change.name,
|
|
27
|
+
hashes,
|
|
28
|
+
dependencies: change.dependencies
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return refs;
|
|
33
|
+
};
|
|
34
|
+
/** Read a database's `pgpm_migrate` ledger as a snapshot, in deploy order. */
|
|
35
|
+
export const readLedgerSnapshot = async (config) => {
|
|
36
|
+
const rows = await new PgpmMigrate(config).readDeployedState();
|
|
37
|
+
return rows.map(row => ({
|
|
38
|
+
package: row.package,
|
|
39
|
+
changeName: row.changeName,
|
|
40
|
+
scriptHash: row.scriptHash,
|
|
41
|
+
deployedAt: row.deployedAt,
|
|
42
|
+
requires: row.requires
|
|
43
|
+
}));
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Build the reconciliation report: classify the side's plan against the
|
|
47
|
+
* ledger, compute semantic coverage against the diff, and emit the backfill
|
|
48
|
+
* for entries that are unrecorded but already satisfied, so a subsequent
|
|
49
|
+
* `pgpm deploy` executes only the genuine delta.
|
|
50
|
+
*/
|
|
51
|
+
export const buildLedgerReport = async (options) => {
|
|
52
|
+
const modules = await loadPlanSideModules(options.spec, options.cwd);
|
|
53
|
+
const refs = await planChangeRefs(modules);
|
|
54
|
+
const ledger = await readLedgerSnapshot(options.config);
|
|
55
|
+
const classification = classifyAgainstLedger(refs, ledger);
|
|
56
|
+
const coverage = coverChanges(options.changes, options.diff);
|
|
57
|
+
const selection = selectBackfillEntries(refs, classification, coverage);
|
|
58
|
+
return {
|
|
59
|
+
...selection,
|
|
60
|
+
classification,
|
|
61
|
+
coverage,
|
|
62
|
+
backfillSql: selection.entries.length > 0 ? emitLedgerBackfill(selection.entries) : undefined
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* Every plan entry of a set of modules as a backfill row, in plan order — the
|
|
67
|
+
* whole plan, not the satisfied subset. This is the "baseline" input: a
|
|
68
|
+
* database that already carries a plan's schema (e.g. one imported from a
|
|
69
|
+
* dump, or one adopted from outside pgpm) can record the entire plan as
|
|
70
|
+
* deployed without re-executing any DDL. Entries with no candidate hash
|
|
71
|
+
* (deploy script missing) are skipped, mirroring {@link selectBackfillEntries}.
|
|
72
|
+
*/
|
|
73
|
+
export const baselineBackfillEntries = async (modules) => {
|
|
74
|
+
const refs = await planChangeRefs(modules);
|
|
75
|
+
const entries = [];
|
|
76
|
+
for (const ref of refs) {
|
|
77
|
+
const scriptHash = ref.hashes[0];
|
|
78
|
+
if (!scriptHash)
|
|
79
|
+
continue;
|
|
80
|
+
entries.push({
|
|
81
|
+
package: ref.package,
|
|
82
|
+
changeName: ref.name,
|
|
83
|
+
scriptHash,
|
|
84
|
+
requires: ref.dependencies
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
return entries;
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* Build a whole-plan baseline backfill for a workspace or module directory:
|
|
91
|
+
* record every change as already deployed, log-only, so a `pgpm deploy`
|
|
92
|
+
* afterward is a no-op and the database is adopted at the plan's head. The
|
|
93
|
+
* target database must already have the `pgpm_migrate` schema
|
|
94
|
+
* (`pgpm migrate init` or any prior deploy creates it, and applying the
|
|
95
|
+
* baseline through `PgpmMigrate.deploy({ logOnly: true })` initializes it).
|
|
96
|
+
*/
|
|
97
|
+
export const buildBaselineBackfill = async (spec, cwd) => {
|
|
98
|
+
const modules = await loadPlanSideModules(spec, cwd);
|
|
99
|
+
const entries = await baselineBackfillEntries(modules);
|
|
100
|
+
return { entries, backfillSql: emitLedgerBackfill(entries) };
|
|
101
|
+
};
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { loadDiffSideFromDisk, resolveDiffSideKind, sqlToDiffChanges, workspaceModulesToDiffChanges } from '@pgpmjs/diff';
|
|
2
|
+
import { loadModuleSource } from '@pgpmjs/transform';
|
|
3
|
+
import * as fs from 'fs';
|
|
4
|
+
import * as path from 'path';
|
|
5
|
+
import { PgpmPackage } from '../core/class/pgpm';
|
|
6
|
+
import { dumpSchemaForComparison } from '../dump/pg-dump';
|
|
7
|
+
import { databaseSpecLabel, isDatabaseSpec, resolveDatabaseSpec } from '../utils/database-spec';
|
|
8
|
+
/**
|
|
9
|
+
* Load every local module of a pgpm workspace as a `ModuleSource`, in
|
|
10
|
+
* cross-module dependency order.
|
|
11
|
+
*
|
|
12
|
+
* Ordering and membership come from the same resolver `deploy`/`verify`/
|
|
13
|
+
* `revert` use (`resolveWorkspaceExtensionDependencies`), so a workspace
|
|
14
|
+
* flattens the way it deploys. External extensions (installed Postgres
|
|
15
|
+
* extensions rather than local modules) are not authored schema and are
|
|
16
|
+
* skipped, as are modules without a plan (proxy / apply-spec modules).
|
|
17
|
+
*/
|
|
18
|
+
export const loadWorkspaceModuleSources = async (workspaceDir) => {
|
|
19
|
+
const pkg = new PgpmPackage(path.resolve(workspaceDir));
|
|
20
|
+
const workspacePath = pkg.getWorkspacePath();
|
|
21
|
+
if (!workspacePath) {
|
|
22
|
+
throw new Error(`${workspaceDir}: not a pgpm workspace (no pgpm.json / pgpm.config.js)`);
|
|
23
|
+
}
|
|
24
|
+
const moduleMap = pkg.getModuleMap();
|
|
25
|
+
const { resolved, external } = await pkg.resolveWorkspaceExtensionDependencies();
|
|
26
|
+
const warnings = [];
|
|
27
|
+
const modules = [];
|
|
28
|
+
for (const name of resolved) {
|
|
29
|
+
if (external.includes(name))
|
|
30
|
+
continue;
|
|
31
|
+
const entry = moduleMap[name];
|
|
32
|
+
if (!entry) {
|
|
33
|
+
warnings.push(`${name}: resolved module is not in the workspace module map; skipped`);
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
const moduleDir = path.resolve(workspacePath, entry.path);
|
|
37
|
+
if (!fs.existsSync(path.join(moduleDir, 'pgpm.plan'))) {
|
|
38
|
+
warnings.push(`${name}: no pgpm.plan (proxy or apply-spec module); skipped`);
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
const source = loadModuleSource(moduleDir);
|
|
42
|
+
warnings.push(...source.warnings.map(w => `${name}: ${w}`));
|
|
43
|
+
modules.push(source);
|
|
44
|
+
}
|
|
45
|
+
return { modules, warnings };
|
|
46
|
+
};
|
|
47
|
+
/** Load a pgpm workspace directory as a flattened diff side. */
|
|
48
|
+
export const loadWorkspaceSide = async (workspaceDir) => {
|
|
49
|
+
const resolved = path.resolve(workspaceDir);
|
|
50
|
+
const { modules, warnings } = await loadWorkspaceModuleSources(resolved);
|
|
51
|
+
return {
|
|
52
|
+
kind: 'workspace',
|
|
53
|
+
label: path.basename(resolved),
|
|
54
|
+
changes: workspaceModulesToDiffChanges(modules),
|
|
55
|
+
warnings
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
/** Load a live database's schema as a diff side (via `pg_dump`). */
|
|
59
|
+
export const loadDatabaseSide = async (spec) => {
|
|
60
|
+
const label = databaseSpecLabel(spec);
|
|
61
|
+
const sql = await dumpSchemaForComparison(resolveDatabaseSpec(spec));
|
|
62
|
+
return { kind: 'database', label, changes: sqlToDiffChanges(sql, label), warnings: [] };
|
|
63
|
+
};
|
|
64
|
+
/**
|
|
65
|
+
* Load any diff side. Databases are dumped, workspaces are resolved and
|
|
66
|
+
* flattened, and modules / .sql files are read by `@pgpmjs/diff`.
|
|
67
|
+
*/
|
|
68
|
+
export const loadDiffSide = async (spec, cwd = process.cwd()) => {
|
|
69
|
+
if (isDatabaseSpec(spec))
|
|
70
|
+
return loadDatabaseSide(spec);
|
|
71
|
+
const resolved = path.resolve(cwd, spec);
|
|
72
|
+
if (resolveDiffSideKind(resolved) === 'workspace')
|
|
73
|
+
return loadWorkspaceSide(resolved);
|
|
74
|
+
return loadDiffSideFromDisk(resolved);
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* The modules behind a plan-bearing side: every local module for a
|
|
78
|
+
* workspace, or the single module for a module directory. Used by ledger
|
|
79
|
+
* classification, which needs plan entries rather than flattened changes.
|
|
80
|
+
*/
|
|
81
|
+
export const loadPlanSideModules = async (spec, cwd = process.cwd()) => {
|
|
82
|
+
const resolved = path.resolve(cwd, spec);
|
|
83
|
+
if (resolveDiffSideKind(resolved) === 'workspace') {
|
|
84
|
+
return (await loadWorkspaceModuleSources(resolved)).modules;
|
|
85
|
+
}
|
|
86
|
+
return [loadModuleSource(resolved)];
|
|
87
|
+
};
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `pg_dump` as a typed core operation.
|
|
3
|
+
*
|
|
4
|
+
* Both `pgpm dump` (write a file) and `pgpm diff` (capture a schema for
|
|
5
|
+
* comparison) need the same process plumbing — connection env, flag
|
|
6
|
+
* assembly, error translation — so it lives here rather than being
|
|
7
|
+
* re-spawned per command.
|
|
8
|
+
*/
|
|
9
|
+
import { spawn } from 'child_process';
|
|
10
|
+
import { getPgClientCommand, getSpawnEnvWithPg } from 'pg-env';
|
|
11
|
+
/**
|
|
12
|
+
* Schemas that record deployment history rather than authored schema.
|
|
13
|
+
* Excluded when dumping a database for comparison: two databases with the
|
|
14
|
+
* same schema but different migration histories are the same schema.
|
|
15
|
+
*/
|
|
16
|
+
export const LEDGER_SCHEMAS = ['pgpm_migrate', 'sqitch'];
|
|
17
|
+
/**
|
|
18
|
+
* The `pg_dump` argv to use, resolved by the typed env layer
|
|
19
|
+
* ({@link getPgClientCommand}): honors `PGPM_PG_DUMP` / `PGPM_PG_CLIENT_PREFIX`
|
|
20
|
+
* so an older/absent local client can be pointed at a version-matched one,
|
|
21
|
+
* including inside a container. Tool location only; connection still comes
|
|
22
|
+
* from `pg-env`.
|
|
23
|
+
*/
|
|
24
|
+
export const resolvePgDumpCommand = () => getPgClientCommand('pg_dump');
|
|
25
|
+
/** Assemble `pg_dump` flags from options (exported for testing/inspection). */
|
|
26
|
+
export const buildPgDumpArgs = (options) => {
|
|
27
|
+
const args = [];
|
|
28
|
+
if (options.format)
|
|
29
|
+
args.push(`--format=${options.format}`);
|
|
30
|
+
if (options.schemaOnly)
|
|
31
|
+
args.push('--schema-only');
|
|
32
|
+
if (options.dataOnly)
|
|
33
|
+
args.push('--data-only');
|
|
34
|
+
if (options.inserts)
|
|
35
|
+
args.push('--inserts');
|
|
36
|
+
if (options.columnInserts)
|
|
37
|
+
args.push('--column-inserts');
|
|
38
|
+
if (options.noOwner !== false)
|
|
39
|
+
args.push('--no-owner');
|
|
40
|
+
if (options.noPrivileges)
|
|
41
|
+
args.push('--no-privileges');
|
|
42
|
+
for (const schema of options.schemas ?? [])
|
|
43
|
+
args.push(`--schema=${schema}`);
|
|
44
|
+
for (const schema of options.excludeSchemas ?? [])
|
|
45
|
+
args.push(`--exclude-schema=${schema}`);
|
|
46
|
+
for (const table of options.tables ?? [])
|
|
47
|
+
args.push(`--table=${table}`);
|
|
48
|
+
for (const table of options.excludeTables ?? [])
|
|
49
|
+
args.push(`--exclude-table=${table}`);
|
|
50
|
+
if (options.file)
|
|
51
|
+
args.push('--file', options.file);
|
|
52
|
+
args.push(...(options.extraArgs ?? []));
|
|
53
|
+
// Pass the database explicitly rather than relying solely on PGDATABASE:
|
|
54
|
+
// a wrapped command (e.g. `docker exec`) does not inherit the host's env.
|
|
55
|
+
args.push('--dbname', options.config.database);
|
|
56
|
+
return args;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Run `pg_dump`. Returns the dump text, or an empty string when `file` was
|
|
60
|
+
* given (pg_dump wrote it directly).
|
|
61
|
+
*/
|
|
62
|
+
export const pgDump = async (options) => {
|
|
63
|
+
const [cmd, ...prefixArgs] = options.command ?? resolvePgDumpCommand();
|
|
64
|
+
const args = [...prefixArgs, ...buildPgDumpArgs(options)];
|
|
65
|
+
const env = getSpawnEnvWithPg(options.config);
|
|
66
|
+
return new Promise((resolve, reject) => {
|
|
67
|
+
const child = spawn(cmd, args, { env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
68
|
+
let out = '';
|
|
69
|
+
let err = '';
|
|
70
|
+
child.stdout.on('data', chunk => { out += chunk; });
|
|
71
|
+
child.stderr.on('data', chunk => { err += chunk; });
|
|
72
|
+
child.on('error', (e) => {
|
|
73
|
+
if (e.code === 'ENOENT') {
|
|
74
|
+
reject(new Error(`${cmd} not found; ensure PostgreSQL client tools are installed and in PATH, ` +
|
|
75
|
+
'or set PGPM_PG_DUMP / PGPM_PG_CLIENT_PREFIX to a version-matched pg_dump command'));
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
reject(e);
|
|
79
|
+
});
|
|
80
|
+
child.on('close', code => {
|
|
81
|
+
if (code === 0)
|
|
82
|
+
resolve(out);
|
|
83
|
+
else
|
|
84
|
+
reject(new Error(`pg_dump exited with code ${code}: ${err.trim()}`));
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* Dump a database's schema for comparison: definitions only, no ownership,
|
|
90
|
+
* and without the migration-history schemas (which are the ledger, not the
|
|
91
|
+
* schema under comparison — read those with `PgpmMigrate.readDeployedState`).
|
|
92
|
+
*/
|
|
93
|
+
export const dumpSchemaForComparison = async (config, options = {}) => pgDump({
|
|
94
|
+
config,
|
|
95
|
+
schemaOnly: true,
|
|
96
|
+
noOwner: true,
|
|
97
|
+
excludeSchemas: [...LEDGER_SCHEMAS, ...(options.excludeSchemas ?? [])],
|
|
98
|
+
...(options.command ? { command: options.command } : {})
|
|
99
|
+
});
|
package/esm/index.js
CHANGED
|
@@ -2,6 +2,8 @@ export * from './core/boilerplate-scanner';
|
|
|
2
2
|
export * from './core/boilerplate-types';
|
|
3
3
|
export * from './core/class/pgpm';
|
|
4
4
|
export * from './core/template-scaffold';
|
|
5
|
+
export * from './diff';
|
|
6
|
+
export * from './dump/pg-dump';
|
|
5
7
|
export * from './extensions';
|
|
6
8
|
export * from './modules/modules';
|
|
7
9
|
export * from './packaging/check';
|
|
@@ -20,10 +22,11 @@ export * from './bundle';
|
|
|
20
22
|
export { PgpmInit } from './init/client';
|
|
21
23
|
export { cleanSql } from './migrate/clean';
|
|
22
24
|
export { PgpmMigrate } from './migrate/client';
|
|
23
|
-
export { hashFile, hashString } from './migrate/utils/hash';
|
|
25
|
+
export { hashFile, hashSqlFile, hashString } from './migrate/utils/hash';
|
|
24
26
|
export { executeQuery, withTransaction } from './migrate/utils/transaction';
|
|
25
27
|
export * from './refactor';
|
|
26
28
|
export * from './roles';
|
|
29
|
+
export * from './utils/database-spec';
|
|
27
30
|
export { parseAuthor } from '@pgpmjs/ast';
|
|
28
31
|
export * from '@pgpmjs/ast/files';
|
|
29
32
|
export * from '@pgpmjs/ast/module';
|
package/esm/migrate/client.js
CHANGED
|
@@ -545,6 +545,48 @@ export class PgpmMigrate {
|
|
|
545
545
|
throw error;
|
|
546
546
|
}
|
|
547
547
|
}
|
|
548
|
+
/**
|
|
549
|
+
* Read the whole `pgpm_migrate` ledger as an ordered snapshot: every
|
|
550
|
+
* recorded change with its script hash and its recorded requires, in
|
|
551
|
+
* deploy order. This is the deployment cursor a ledger-aware diff reads —
|
|
552
|
+
* what the database believes it has executed, independent of what its
|
|
553
|
+
* catalog currently looks like.
|
|
554
|
+
*
|
|
555
|
+
* Returns an empty array when the database has no ledger (never deployed
|
|
556
|
+
* through pgpm).
|
|
557
|
+
*/
|
|
558
|
+
async readDeployedState() {
|
|
559
|
+
try {
|
|
560
|
+
const result = await this.pool.query(`
|
|
561
|
+
SELECT
|
|
562
|
+
c.package,
|
|
563
|
+
c.change_name,
|
|
564
|
+
c.script_hash,
|
|
565
|
+
c.deployed_at,
|
|
566
|
+
COALESCE(
|
|
567
|
+
(SELECT array_agg(d.requires ORDER BY d.requires)
|
|
568
|
+
FROM pgpm_migrate.dependencies d
|
|
569
|
+
WHERE d.change_id = c.change_id),
|
|
570
|
+
ARRAY[]::TEXT[]
|
|
571
|
+
) AS requires
|
|
572
|
+
FROM pgpm_migrate.changes c
|
|
573
|
+
ORDER BY c.deployed_at ASC, c.change_name ASC
|
|
574
|
+
`);
|
|
575
|
+
return result.rows.map((row) => ({
|
|
576
|
+
package: row.package,
|
|
577
|
+
changeName: row.change_name,
|
|
578
|
+
scriptHash: row.script_hash,
|
|
579
|
+
deployedAt: row.deployed_at ? new Date(row.deployed_at) : undefined,
|
|
580
|
+
requires: row.requires ?? []
|
|
581
|
+
}));
|
|
582
|
+
}
|
|
583
|
+
catch (error) {
|
|
584
|
+
// No pgpm_migrate schema/table: nothing has been deployed through pgpm.
|
|
585
|
+
if (error.code === '42P01' || error.code === '3F000')
|
|
586
|
+
return [];
|
|
587
|
+
throw error;
|
|
588
|
+
}
|
|
589
|
+
}
|
|
548
590
|
/**
|
|
549
591
|
* Get dependencies for a change
|
|
550
592
|
*/
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { getPgEnvOptions } from 'pg-env';
|
|
2
|
+
const DB_PREFIX = 'db:';
|
|
3
|
+
const DSN_PREFIX = /^postgres(ql)?:\/\//;
|
|
4
|
+
/** True when a spec names a live database rather than an on-disk path. */
|
|
5
|
+
export const isDatabaseSpec = (spec) => DSN_PREFIX.test(spec) || spec.startsWith(DB_PREFIX);
|
|
6
|
+
/** Display label for a database spec: the database name for `db:<name>`. */
|
|
7
|
+
export const databaseSpecLabel = (spec) => spec.startsWith(DB_PREFIX) ? spec.slice(DB_PREFIX.length) : spec;
|
|
8
|
+
/**
|
|
9
|
+
* Resolve a database spec to a `PgConfig`. `db:<name>` takes only the
|
|
10
|
+
* database name from the spec; a connection string overrides each part it
|
|
11
|
+
* specifies. Everything unspecified falls back to the environment.
|
|
12
|
+
*/
|
|
13
|
+
export const resolveDatabaseSpec = (spec) => {
|
|
14
|
+
if (spec.startsWith(DB_PREFIX)) {
|
|
15
|
+
return getPgEnvOptions({ database: spec.slice(DB_PREFIX.length) });
|
|
16
|
+
}
|
|
17
|
+
if (!DSN_PREFIX.test(spec)) {
|
|
18
|
+
return getPgEnvOptions({ database: spec });
|
|
19
|
+
}
|
|
20
|
+
const url = new URL(spec);
|
|
21
|
+
const database = url.pathname.replace(/^\//, '');
|
|
22
|
+
return getPgEnvOptions({
|
|
23
|
+
...(url.hostname && { host: url.hostname }),
|
|
24
|
+
...(url.port && { port: Number(url.port) }),
|
|
25
|
+
...(url.username && { user: decodeURIComponent(url.username) }),
|
|
26
|
+
...(url.password && { password: decodeURIComponent(url.password) }),
|
|
27
|
+
...(database && { database: decodeURIComponent(database) })
|
|
28
|
+
});
|
|
29
|
+
};
|
package/index.d.ts
CHANGED
|
@@ -2,6 +2,8 @@ export * from './core/boilerplate-scanner';
|
|
|
2
2
|
export * from './core/boilerplate-types';
|
|
3
3
|
export * from './core/class/pgpm';
|
|
4
4
|
export * from './core/template-scaffold';
|
|
5
|
+
export * from './diff';
|
|
6
|
+
export * from './dump/pg-dump';
|
|
5
7
|
export * from './extensions';
|
|
6
8
|
export * from './modules/modules';
|
|
7
9
|
export * from './packaging/check';
|
|
@@ -18,12 +20,14 @@ export * from './apply';
|
|
|
18
20
|
export * from './bundle';
|
|
19
21
|
export { PgpmInit } from './init/client';
|
|
20
22
|
export { cleanSql } from './migrate/clean';
|
|
23
|
+
export type { DeployedChangeRecord } from './migrate/client';
|
|
21
24
|
export { PgpmMigrate } from './migrate/client';
|
|
22
25
|
export { DeployOptions, DeployResult, MigrateChange, MigratePlanFile, RevertOptions, RevertResult, StatusResult, VerifyOptions, VerifyResult } from './migrate/types';
|
|
23
|
-
export { hashFile, hashString } from './migrate/utils/hash';
|
|
26
|
+
export { hashFile, hashSqlFile, hashString } from './migrate/utils/hash';
|
|
24
27
|
export { executeQuery, TransactionContext, TransactionOptions, withTransaction } from './migrate/utils/transaction';
|
|
25
28
|
export * from './refactor';
|
|
26
29
|
export * from './roles';
|
|
30
|
+
export * from './utils/database-spec';
|
|
27
31
|
export { parseAuthor } from '@pgpmjs/ast';
|
|
28
32
|
export * from '@pgpmjs/ast/files';
|
|
29
33
|
export * from '@pgpmjs/ast/module';
|
package/index.js
CHANGED
|
@@ -14,11 +14,13 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.parseAuthor = exports.withTransaction = exports.executeQuery = exports.hashString = exports.hashFile = exports.PgpmMigrate = exports.cleanSql = exports.PgpmInit = void 0;
|
|
17
|
+
exports.parseAuthor = exports.withTransaction = exports.executeQuery = exports.hashString = exports.hashSqlFile = exports.hashFile = exports.PgpmMigrate = exports.cleanSql = exports.PgpmInit = void 0;
|
|
18
18
|
__exportStar(require("./core/boilerplate-scanner"), exports);
|
|
19
19
|
__exportStar(require("./core/boilerplate-types"), exports);
|
|
20
20
|
__exportStar(require("./core/class/pgpm"), exports);
|
|
21
21
|
__exportStar(require("./core/template-scaffold"), exports);
|
|
22
|
+
__exportStar(require("./diff"), exports);
|
|
23
|
+
__exportStar(require("./dump/pg-dump"), exports);
|
|
22
24
|
__exportStar(require("./extensions"), exports);
|
|
23
25
|
__exportStar(require("./modules/modules"), exports);
|
|
24
26
|
__exportStar(require("./packaging/check"), exports);
|
|
@@ -42,12 +44,14 @@ var client_2 = require("./migrate/client");
|
|
|
42
44
|
Object.defineProperty(exports, "PgpmMigrate", { enumerable: true, get: function () { return client_2.PgpmMigrate; } });
|
|
43
45
|
var hash_1 = require("./migrate/utils/hash");
|
|
44
46
|
Object.defineProperty(exports, "hashFile", { enumerable: true, get: function () { return hash_1.hashFile; } });
|
|
47
|
+
Object.defineProperty(exports, "hashSqlFile", { enumerable: true, get: function () { return hash_1.hashSqlFile; } });
|
|
45
48
|
Object.defineProperty(exports, "hashString", { enumerable: true, get: function () { return hash_1.hashString; } });
|
|
46
49
|
var transaction_1 = require("./migrate/utils/transaction");
|
|
47
50
|
Object.defineProperty(exports, "executeQuery", { enumerable: true, get: function () { return transaction_1.executeQuery; } });
|
|
48
51
|
Object.defineProperty(exports, "withTransaction", { enumerable: true, get: function () { return transaction_1.withTransaction; } });
|
|
49
52
|
__exportStar(require("./refactor"), exports);
|
|
50
53
|
__exportStar(require("./roles"), exports);
|
|
54
|
+
__exportStar(require("./utils/database-spec"), exports);
|
|
51
55
|
var ast_1 = require("@pgpmjs/ast");
|
|
52
56
|
Object.defineProperty(exports, "parseAuthor", { enumerable: true, get: function () { return ast_1.parseAuthor; } });
|
|
53
57
|
__exportStar(require("@pgpmjs/ast/files"), exports);
|
package/migrate/client.d.ts
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
import { PgConfig } from 'pg-env';
|
|
2
2
|
import { DeployOptions, DeployResult, RevertOptions, RevertResult, StatusResult, VerifyOptions, VerifyResult } from './types';
|
|
3
3
|
export type HashMethod = 'content' | 'ast';
|
|
4
|
+
/**
|
|
5
|
+
* One `pgpm_migrate` ledger row: a change the database records as deployed,
|
|
6
|
+
* with the script hash it was deployed from and its recorded requires.
|
|
7
|
+
*/
|
|
8
|
+
export interface DeployedChangeRecord {
|
|
9
|
+
package: string;
|
|
10
|
+
changeName: string;
|
|
11
|
+
scriptHash: string;
|
|
12
|
+
deployedAt?: Date;
|
|
13
|
+
requires: string[];
|
|
14
|
+
}
|
|
4
15
|
export interface PgpmMigrateOptions {
|
|
5
16
|
/**
|
|
6
17
|
* Hash method for SQL files:
|
|
@@ -69,6 +80,17 @@ export declare class PgpmMigrate {
|
|
|
69
80
|
* Get all deployed changes for a project
|
|
70
81
|
*/
|
|
71
82
|
getDeployedChanges(targetDatabase: string, packageName: string): Promise<any[]>;
|
|
83
|
+
/**
|
|
84
|
+
* Read the whole `pgpm_migrate` ledger as an ordered snapshot: every
|
|
85
|
+
* recorded change with its script hash and its recorded requires, in
|
|
86
|
+
* deploy order. This is the deployment cursor a ledger-aware diff reads —
|
|
87
|
+
* what the database believes it has executed, independent of what its
|
|
88
|
+
* catalog currently looks like.
|
|
89
|
+
*
|
|
90
|
+
* Returns an empty array when the database has no ledger (never deployed
|
|
91
|
+
* through pgpm).
|
|
92
|
+
*/
|
|
93
|
+
readDeployedState(): Promise<DeployedChangeRecord[]>;
|
|
72
94
|
/**
|
|
73
95
|
* Get dependencies for a change
|
|
74
96
|
*/
|
package/migrate/client.js
CHANGED
|
@@ -548,6 +548,48 @@ class PgpmMigrate {
|
|
|
548
548
|
throw error;
|
|
549
549
|
}
|
|
550
550
|
}
|
|
551
|
+
/**
|
|
552
|
+
* Read the whole `pgpm_migrate` ledger as an ordered snapshot: every
|
|
553
|
+
* recorded change with its script hash and its recorded requires, in
|
|
554
|
+
* deploy order. This is the deployment cursor a ledger-aware diff reads —
|
|
555
|
+
* what the database believes it has executed, independent of what its
|
|
556
|
+
* catalog currently looks like.
|
|
557
|
+
*
|
|
558
|
+
* Returns an empty array when the database has no ledger (never deployed
|
|
559
|
+
* through pgpm).
|
|
560
|
+
*/
|
|
561
|
+
async readDeployedState() {
|
|
562
|
+
try {
|
|
563
|
+
const result = await this.pool.query(`
|
|
564
|
+
SELECT
|
|
565
|
+
c.package,
|
|
566
|
+
c.change_name,
|
|
567
|
+
c.script_hash,
|
|
568
|
+
c.deployed_at,
|
|
569
|
+
COALESCE(
|
|
570
|
+
(SELECT array_agg(d.requires ORDER BY d.requires)
|
|
571
|
+
FROM pgpm_migrate.dependencies d
|
|
572
|
+
WHERE d.change_id = c.change_id),
|
|
573
|
+
ARRAY[]::TEXT[]
|
|
574
|
+
) AS requires
|
|
575
|
+
FROM pgpm_migrate.changes c
|
|
576
|
+
ORDER BY c.deployed_at ASC, c.change_name ASC
|
|
577
|
+
`);
|
|
578
|
+
return result.rows.map((row) => ({
|
|
579
|
+
package: row.package,
|
|
580
|
+
changeName: row.change_name,
|
|
581
|
+
scriptHash: row.script_hash,
|
|
582
|
+
deployedAt: row.deployed_at ? new Date(row.deployed_at) : undefined,
|
|
583
|
+
requires: row.requires ?? []
|
|
584
|
+
}));
|
|
585
|
+
}
|
|
586
|
+
catch (error) {
|
|
587
|
+
// No pgpm_migrate schema/table: nothing has been deployed through pgpm.
|
|
588
|
+
if (error.code === '42P01' || error.code === '3F000')
|
|
589
|
+
return [];
|
|
590
|
+
throw error;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
551
593
|
/**
|
|
552
594
|
* Get dependencies for a change
|
|
553
595
|
*/
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pgpmjs/core",
|
|
3
|
-
"version": "7.
|
|
3
|
+
"version": "7.23.0",
|
|
4
4
|
"author": "Constructive <developers@constructive.io>",
|
|
5
5
|
"description": "PGPM Package and Migration Tools",
|
|
6
6
|
"main": "index.js",
|
|
@@ -48,24 +48,25 @@
|
|
|
48
48
|
"makage": "^0.3.0"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@pgpmjs/ast": "^0.11.
|
|
52
|
-
"@pgpmjs/bundle": "^0.14.
|
|
53
|
-
"@pgpmjs/
|
|
51
|
+
"@pgpmjs/ast": "^0.11.1",
|
|
52
|
+
"@pgpmjs/bundle": "^0.14.1",
|
|
53
|
+
"@pgpmjs/diff": "^0.3.0",
|
|
54
|
+
"@pgpmjs/env": "^2.41.1",
|
|
54
55
|
"@pgpmjs/logger": "^2.24.0",
|
|
55
|
-
"@pgpmjs/server-utils": "^3.25.
|
|
56
|
-
"@pgpmjs/slice": "^0.14.
|
|
57
|
-
"@pgpmjs/transform": "^0.
|
|
58
|
-
"@pgpmjs/types": "^2.50.
|
|
59
|
-
"csv-to-pg": "^4.10.
|
|
56
|
+
"@pgpmjs/server-utils": "^3.25.1",
|
|
57
|
+
"@pgpmjs/slice": "^0.14.1",
|
|
58
|
+
"@pgpmjs/transform": "^0.22.0",
|
|
59
|
+
"@pgpmjs/types": "^2.50.1",
|
|
60
|
+
"csv-to-pg": "^4.10.1",
|
|
60
61
|
"genomic": "^5.6.2",
|
|
61
62
|
"glob": "^13.0.6",
|
|
62
63
|
"parse-package-name": "^1.0.0",
|
|
63
64
|
"pg": "^8.21.0",
|
|
64
|
-
"pg-cache": "^3.25.
|
|
65
|
-
"pg-env": "^1.
|
|
66
|
-
"pgsql-deparser": "^18.3.
|
|
67
|
-
"pgsql-parser": "^18.2.
|
|
65
|
+
"pg-cache": "^3.25.1",
|
|
66
|
+
"pg-env": "^1.29.0",
|
|
67
|
+
"pgsql-deparser": "^18.3.3",
|
|
68
|
+
"pgsql-parser": "^18.2.3",
|
|
68
69
|
"yanse": "^0.2.1"
|
|
69
70
|
},
|
|
70
|
-
"gitHead": "
|
|
71
|
+
"gitHead": "6da0705f8aa49d62dc2defb8b135b71674611483"
|
|
71
72
|
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Live-database specs: the `db:<name>` shorthand and postgres:// connection
|
|
3
|
+
* strings that commands accept wherever a database can stand in for a path.
|
|
4
|
+
*
|
|
5
|
+
* Resolution goes through `pg-env`, so host/port/user/password come from the
|
|
6
|
+
* usual layered configuration and a spec only overrides what it names.
|
|
7
|
+
*/
|
|
8
|
+
import type { PgConfig } from 'pg-env';
|
|
9
|
+
/** True when a spec names a live database rather than an on-disk path. */
|
|
10
|
+
export declare const isDatabaseSpec: (spec: string) => boolean;
|
|
11
|
+
/** Display label for a database spec: the database name for `db:<name>`. */
|
|
12
|
+
export declare const databaseSpecLabel: (spec: string) => string;
|
|
13
|
+
/**
|
|
14
|
+
* Resolve a database spec to a `PgConfig`. `db:<name>` takes only the
|
|
15
|
+
* database name from the spec; a connection string overrides each part it
|
|
16
|
+
* specifies. Everything unspecified falls back to the environment.
|
|
17
|
+
*/
|
|
18
|
+
export declare const resolveDatabaseSpec: (spec: string) => PgConfig;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.resolveDatabaseSpec = exports.databaseSpecLabel = exports.isDatabaseSpec = void 0;
|
|
4
|
+
const pg_env_1 = require("pg-env");
|
|
5
|
+
const DB_PREFIX = 'db:';
|
|
6
|
+
const DSN_PREFIX = /^postgres(ql)?:\/\//;
|
|
7
|
+
/** True when a spec names a live database rather than an on-disk path. */
|
|
8
|
+
const isDatabaseSpec = (spec) => DSN_PREFIX.test(spec) || spec.startsWith(DB_PREFIX);
|
|
9
|
+
exports.isDatabaseSpec = isDatabaseSpec;
|
|
10
|
+
/** Display label for a database spec: the database name for `db:<name>`. */
|
|
11
|
+
const databaseSpecLabel = (spec) => spec.startsWith(DB_PREFIX) ? spec.slice(DB_PREFIX.length) : spec;
|
|
12
|
+
exports.databaseSpecLabel = databaseSpecLabel;
|
|
13
|
+
/**
|
|
14
|
+
* Resolve a database spec to a `PgConfig`. `db:<name>` takes only the
|
|
15
|
+
* database name from the spec; a connection string overrides each part it
|
|
16
|
+
* specifies. Everything unspecified falls back to the environment.
|
|
17
|
+
*/
|
|
18
|
+
const resolveDatabaseSpec = (spec) => {
|
|
19
|
+
if (spec.startsWith(DB_PREFIX)) {
|
|
20
|
+
return (0, pg_env_1.getPgEnvOptions)({ database: spec.slice(DB_PREFIX.length) });
|
|
21
|
+
}
|
|
22
|
+
if (!DSN_PREFIX.test(spec)) {
|
|
23
|
+
return (0, pg_env_1.getPgEnvOptions)({ database: spec });
|
|
24
|
+
}
|
|
25
|
+
const url = new URL(spec);
|
|
26
|
+
const database = url.pathname.replace(/^\//, '');
|
|
27
|
+
return (0, pg_env_1.getPgEnvOptions)({
|
|
28
|
+
...(url.hostname && { host: url.hostname }),
|
|
29
|
+
...(url.port && { port: Number(url.port) }),
|
|
30
|
+
...(url.username && { user: decodeURIComponent(url.username) }),
|
|
31
|
+
...(url.password && { password: decodeURIComponent(url.password) }),
|
|
32
|
+
...(database && { database: decodeURIComponent(database) })
|
|
33
|
+
});
|
|
34
|
+
};
|
|
35
|
+
exports.resolveDatabaseSpec = resolveDatabaseSpec;
|