@pgpmjs/slice 0.2.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/LICENSE +23 -0
- package/README.md +112 -0
- package/closure.d.ts +34 -0
- package/closure.js +124 -0
- package/esm/closure.js +120 -0
- package/esm/index.js +5 -0
- package/esm/output.js +117 -0
- package/esm/refs.js +36 -0
- package/esm/slice.js +520 -0
- package/esm/types.js +1 -0
- package/index.d.ts +5 -0
- package/index.js +21 -0
- package/output.d.ts +22 -0
- package/output.js +124 -0
- package/package.json +51 -0
- package/refs.d.ts +43 -0
- package/refs.js +41 -0
- package/slice.d.ts +59 -0
- package/slice.js +536 -0
- package/types.d.ts +204 -0
- package/types.js +2 -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,112 @@
|
|
|
1
|
+
# @pgpmjs/slice
|
|
2
|
+
|
|
3
|
+
PGPM plan slicing: split a monolithic pgpm plan into independently deployable packages.
|
|
4
|
+
|
|
5
|
+
- **`slicePlan`** — assign changes to packages via explicit lists or glob **pattern strategies** (`minimatch`), preserving plan order, tags, and cross-package `requires` validation.
|
|
6
|
+
- **Opt-in AST dependency closure** — a cherry-picked slice (`closure: true`) automatically pulls in its TRUE transitive dependencies, discovered from the deploy SQL itself via [`@pgpmjs/transform`](../transform)'s `classifyStatements`: function calls (including inside PL/pgSQL bodies), table/view/type references, and FK targets — even when not declared in plan `requires` headers. The result includes a full report of what was auto-included and why (`requires` vs `ast`), plus `dynamicSqlChanges` and `unresolvedReferences`.
|
|
7
|
+
- **`writeSliceResult` / `generatePlanContent`** — write sliced packages back out as pgpm module trees.
|
|
8
|
+
|
|
9
|
+
## Installation
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @pgpmjs/slice
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Usage
|
|
16
|
+
|
|
17
|
+
```typescript
|
|
18
|
+
import { loadModule, slicePlan, writeSliceResult } from '@pgpmjs/slice';
|
|
19
|
+
|
|
20
|
+
await loadModule(); // WASM parser init — required before closure-enabled slicing
|
|
21
|
+
|
|
22
|
+
const result = slicePlan(plan, {
|
|
23
|
+
strategy: {
|
|
24
|
+
type: 'pattern',
|
|
25
|
+
slices: [
|
|
26
|
+
{ package: 'api', patterns: ['schemas/api/**'], closure: true }
|
|
27
|
+
]
|
|
28
|
+
},
|
|
29
|
+
closure: { moduleDir } // where deploy/ scripts live
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
// result.closure => {
|
|
33
|
+
// autoIncluded: [{ change, package, requiredBy, reason: 'requires' | 'ast', ref? }],
|
|
34
|
+
// dynamicSqlChanges,
|
|
35
|
+
// unresolvedReferences
|
|
36
|
+
// }
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Default behavior (no `closure`) is unchanged from the classic slicer: dependency edges come only from declared plan `requires` headers.
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
## Education and Tutorials
|
|
44
|
+
|
|
45
|
+
1. 🚀 [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
|
|
46
|
+
Get started with modular databases in minutes. Install prerequisites and deploy your first module.
|
|
47
|
+
|
|
48
|
+
2. 📦 [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
|
|
49
|
+
Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
|
|
50
|
+
|
|
51
|
+
3. ✏️ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
|
|
52
|
+
Master the workflow for adding, organizing, and managing database changes with pgpm.
|
|
53
|
+
|
|
54
|
+
4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
|
|
55
|
+
Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
|
|
56
|
+
|
|
57
|
+
5. ⚡ [Supabase Testing](https://constructive.io/learn/supabase)
|
|
58
|
+
Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
|
|
59
|
+
|
|
60
|
+
6. 💧 [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
|
|
61
|
+
Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
|
|
62
|
+
|
|
63
|
+
7. 🔧 [Troubleshooting](https://constructive.io/learn/troubleshooting)
|
|
64
|
+
Common issues and solutions for pgpm, PostgreSQL, and testing.
|
|
65
|
+
|
|
66
|
+
## Related Constructive Tooling
|
|
67
|
+
|
|
68
|
+
### 📦 Package Management
|
|
69
|
+
|
|
70
|
+
* [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.
|
|
71
|
+
|
|
72
|
+
### 🧪 Testing
|
|
73
|
+
|
|
74
|
+
* [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.
|
|
75
|
+
* [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.
|
|
76
|
+
* [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.
|
|
77
|
+
* [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.
|
|
78
|
+
* [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.
|
|
79
|
+
|
|
80
|
+
### 🧠 Parsing & AST
|
|
81
|
+
|
|
82
|
+
* [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
|
|
83
|
+
* [libpg-query-node](https://www.npmjs.com/package/libpg-query): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
|
|
84
|
+
* [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.
|
|
85
|
+
* [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
|
|
86
|
+
* [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
|
|
87
|
+
* [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
|
|
88
|
+
|
|
89
|
+
### 📚 Documentation & Skills
|
|
90
|
+
|
|
91
|
+
* [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.
|
|
92
|
+
|
|
93
|
+
Install skills for AI coding agents:
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
# All platform skills (security, blueprints, codegen, billing, etc.)
|
|
97
|
+
npx skills add constructive-io/constructive-skills
|
|
98
|
+
|
|
99
|
+
# Individual repo skills (pgpm, testing, CLI, search, etc.)
|
|
100
|
+
npx skills add https://github.com/constructive-io/constructive --skill pgpm
|
|
101
|
+
npx skills add https://github.com/constructive-io/constructive --skill constructive-testing
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Credits
|
|
105
|
+
|
|
106
|
+
**🛠 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).**
|
|
107
|
+
|
|
108
|
+
## Disclaimer
|
|
109
|
+
|
|
110
|
+
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
111
|
+
|
|
112
|
+
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/closure.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { ClosureReport, DependencyGraph, PatternStrategy } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* AST-discovered dependency edges between plan changes.
|
|
4
|
+
*/
|
|
5
|
+
export interface AstEdges {
|
|
6
|
+
/** change -> (dependency change -> the referenced object that links them) */
|
|
7
|
+
edges: Map<string, Map<string, string>>;
|
|
8
|
+
/** Changes whose PL/pgSQL bodies execute dynamic SQL (edges incomplete). */
|
|
9
|
+
dynamicSqlChanges: string[];
|
|
10
|
+
/** Schema-qualified references no change in the plan produces. */
|
|
11
|
+
unresolvedReferences: {
|
|
12
|
+
change: string;
|
|
13
|
+
ref: string;
|
|
14
|
+
}[];
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Parse each change's deploy SQL and derive dependency edges from the
|
|
18
|
+
* schema-qualified objects it references, mapped back to the plan change that
|
|
19
|
+
* creates each object. Only edges between plan-known changes are produced —
|
|
20
|
+
* references to objects created outside the plan (installed modules,
|
|
21
|
+
* extensions) are reported as unresolved instead.
|
|
22
|
+
*/
|
|
23
|
+
export declare function buildAstEdges(graph: DependencyGraph, moduleDir: string): AstEdges;
|
|
24
|
+
/**
|
|
25
|
+
* Expand the packages of closure-enabled pattern slices to cover the
|
|
26
|
+
* transitive dependency closure of their seed changes.
|
|
27
|
+
*
|
|
28
|
+
* The closure follows declared plan `requires` edges plus AST-discovered
|
|
29
|
+
* edges. Only changes currently assigned to the default package are pulled in
|
|
30
|
+
* — a dependency that another explicit slice claimed stays where it is and
|
|
31
|
+
* remains an ordinary cross-package dependency. Mutates `assignments` in
|
|
32
|
+
* place and returns a report of every auto-included change and why.
|
|
33
|
+
*/
|
|
34
|
+
export declare function expandClosures(assignments: Map<string, Set<string>>, graph: DependencyGraph, astEdges: AstEdges, strategy: PatternStrategy, defaultPackage: string): ClosureReport;
|
package/closure.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildAstEdges = buildAstEdges;
|
|
4
|
+
exports.expandClosures = expandClosures;
|
|
5
|
+
const fs_1 = require("fs");
|
|
6
|
+
const path_1 = require("path");
|
|
7
|
+
const refs_1 = require("./refs");
|
|
8
|
+
function objectKey(schema, name) {
|
|
9
|
+
return `${schema ?? ''}\u0000${name}`;
|
|
10
|
+
}
|
|
11
|
+
function refLabel(schema, name) {
|
|
12
|
+
return schema ? `${schema}.${name}` : name;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Parse each change's deploy SQL and derive dependency edges from the
|
|
16
|
+
* schema-qualified objects it references, mapped back to the plan change that
|
|
17
|
+
* creates each object. Only edges between plan-known changes are produced —
|
|
18
|
+
* references to objects created outside the plan (installed modules,
|
|
19
|
+
* extensions) are reported as unresolved instead.
|
|
20
|
+
*/
|
|
21
|
+
function buildAstEdges(graph, moduleDir) {
|
|
22
|
+
const facts = new Map();
|
|
23
|
+
for (const changeName of graph.nodes.keys()) {
|
|
24
|
+
const deployPath = (0, path_1.join)(moduleDir, 'deploy', `${changeName}.sql`);
|
|
25
|
+
if (!(0, fs_1.existsSync)(deployPath))
|
|
26
|
+
continue;
|
|
27
|
+
facts.set(changeName, (0, refs_1.extractSqlFacts)((0, fs_1.readFileSync)(deployPath, 'utf-8')));
|
|
28
|
+
}
|
|
29
|
+
// Producer index in plan order: first change creating an object wins.
|
|
30
|
+
const producerByObject = new Map();
|
|
31
|
+
for (const change of graph.plan.changes) {
|
|
32
|
+
const f = facts.get(change.name);
|
|
33
|
+
if (!f)
|
|
34
|
+
continue;
|
|
35
|
+
for (const c of f.creates) {
|
|
36
|
+
const key = objectKey(c.schema, c.name);
|
|
37
|
+
if (!producerByObject.has(key))
|
|
38
|
+
producerByObject.set(key, change.name);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const edges = new Map();
|
|
42
|
+
const dynamicSqlChanges = [];
|
|
43
|
+
const unresolvedReferences = [];
|
|
44
|
+
for (const [changeName, f] of facts) {
|
|
45
|
+
if (f.dynamicSql)
|
|
46
|
+
dynamicSqlChanges.push(changeName);
|
|
47
|
+
for (const r of f.references) {
|
|
48
|
+
const producer = producerByObject.get(objectKey(r.schema, r.name));
|
|
49
|
+
if (!producer) {
|
|
50
|
+
unresolvedReferences.push({ change: changeName, ref: refLabel(r.schema, r.name) });
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (producer === changeName)
|
|
54
|
+
continue;
|
|
55
|
+
if (!edges.has(changeName))
|
|
56
|
+
edges.set(changeName, new Map());
|
|
57
|
+
const deps = edges.get(changeName);
|
|
58
|
+
if (!deps.has(producer))
|
|
59
|
+
deps.set(producer, refLabel(r.schema, r.name));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return { edges, dynamicSqlChanges, unresolvedReferences };
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Expand the packages of closure-enabled pattern slices to cover the
|
|
66
|
+
* transitive dependency closure of their seed changes.
|
|
67
|
+
*
|
|
68
|
+
* The closure follows declared plan `requires` edges plus AST-discovered
|
|
69
|
+
* edges. Only changes currently assigned to the default package are pulled in
|
|
70
|
+
* — a dependency that another explicit slice claimed stays where it is and
|
|
71
|
+
* remains an ordinary cross-package dependency. Mutates `assignments` in
|
|
72
|
+
* place and returns a report of every auto-included change and why.
|
|
73
|
+
*/
|
|
74
|
+
function expandClosures(assignments, graph, astEdges, strategy, defaultPackage) {
|
|
75
|
+
const autoIncluded = [];
|
|
76
|
+
const defaultChanges = assignments.get(defaultPackage) ?? new Set();
|
|
77
|
+
for (const slice of strategy.slices) {
|
|
78
|
+
if (!slice.closure)
|
|
79
|
+
continue;
|
|
80
|
+
const pkgChanges = assignments.get(slice.packageName);
|
|
81
|
+
if (!pkgChanges || pkgChanges.size === 0)
|
|
82
|
+
continue;
|
|
83
|
+
const queue = [...pkgChanges];
|
|
84
|
+
const seen = new Set(queue);
|
|
85
|
+
while (queue.length > 0) {
|
|
86
|
+
const current = queue.shift();
|
|
87
|
+
const pull = (dep, reason, ref) => {
|
|
88
|
+
if (seen.has(dep))
|
|
89
|
+
return;
|
|
90
|
+
seen.add(dep);
|
|
91
|
+
if (pkgChanges.has(dep)) {
|
|
92
|
+
queue.push(dep);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
// A dependency claimed by another explicit slice stays where it is
|
|
96
|
+
// and remains an ordinary cross-package dependency.
|
|
97
|
+
if (!defaultChanges.has(dep))
|
|
98
|
+
return;
|
|
99
|
+
defaultChanges.delete(dep);
|
|
100
|
+
pkgChanges.add(dep);
|
|
101
|
+
queue.push(dep);
|
|
102
|
+
autoIncluded.push({
|
|
103
|
+
change: dep,
|
|
104
|
+
package: slice.packageName,
|
|
105
|
+
requiredBy: current,
|
|
106
|
+
reason,
|
|
107
|
+
...(ref ? { ref } : {})
|
|
108
|
+
});
|
|
109
|
+
};
|
|
110
|
+
for (const dep of graph.edges.get(current) ?? []) {
|
|
111
|
+
if (graph.nodes.has(dep))
|
|
112
|
+
pull(dep, 'requires');
|
|
113
|
+
}
|
|
114
|
+
for (const [dep, ref] of astEdges.edges.get(current) ?? []) {
|
|
115
|
+
pull(dep, 'ast', ref);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return {
|
|
120
|
+
autoIncluded,
|
|
121
|
+
dynamicSqlChanges: astEdges.dynamicSqlChanges,
|
|
122
|
+
unresolvedReferences: astEdges.unresolvedReferences
|
|
123
|
+
};
|
|
124
|
+
}
|
package/esm/closure.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'fs';
|
|
2
|
+
import { join } from 'path';
|
|
3
|
+
import { extractSqlFacts } from './refs';
|
|
4
|
+
function objectKey(schema, name) {
|
|
5
|
+
return `${schema ?? ''}\u0000${name}`;
|
|
6
|
+
}
|
|
7
|
+
function refLabel(schema, name) {
|
|
8
|
+
return schema ? `${schema}.${name}` : name;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Parse each change's deploy SQL and derive dependency edges from the
|
|
12
|
+
* schema-qualified objects it references, mapped back to the plan change that
|
|
13
|
+
* creates each object. Only edges between plan-known changes are produced —
|
|
14
|
+
* references to objects created outside the plan (installed modules,
|
|
15
|
+
* extensions) are reported as unresolved instead.
|
|
16
|
+
*/
|
|
17
|
+
export function buildAstEdges(graph, moduleDir) {
|
|
18
|
+
const facts = new Map();
|
|
19
|
+
for (const changeName of graph.nodes.keys()) {
|
|
20
|
+
const deployPath = join(moduleDir, 'deploy', `${changeName}.sql`);
|
|
21
|
+
if (!existsSync(deployPath))
|
|
22
|
+
continue;
|
|
23
|
+
facts.set(changeName, extractSqlFacts(readFileSync(deployPath, 'utf-8')));
|
|
24
|
+
}
|
|
25
|
+
// Producer index in plan order: first change creating an object wins.
|
|
26
|
+
const producerByObject = new Map();
|
|
27
|
+
for (const change of graph.plan.changes) {
|
|
28
|
+
const f = facts.get(change.name);
|
|
29
|
+
if (!f)
|
|
30
|
+
continue;
|
|
31
|
+
for (const c of f.creates) {
|
|
32
|
+
const key = objectKey(c.schema, c.name);
|
|
33
|
+
if (!producerByObject.has(key))
|
|
34
|
+
producerByObject.set(key, change.name);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
const edges = new Map();
|
|
38
|
+
const dynamicSqlChanges = [];
|
|
39
|
+
const unresolvedReferences = [];
|
|
40
|
+
for (const [changeName, f] of facts) {
|
|
41
|
+
if (f.dynamicSql)
|
|
42
|
+
dynamicSqlChanges.push(changeName);
|
|
43
|
+
for (const r of f.references) {
|
|
44
|
+
const producer = producerByObject.get(objectKey(r.schema, r.name));
|
|
45
|
+
if (!producer) {
|
|
46
|
+
unresolvedReferences.push({ change: changeName, ref: refLabel(r.schema, r.name) });
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (producer === changeName)
|
|
50
|
+
continue;
|
|
51
|
+
if (!edges.has(changeName))
|
|
52
|
+
edges.set(changeName, new Map());
|
|
53
|
+
const deps = edges.get(changeName);
|
|
54
|
+
if (!deps.has(producer))
|
|
55
|
+
deps.set(producer, refLabel(r.schema, r.name));
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return { edges, dynamicSqlChanges, unresolvedReferences };
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Expand the packages of closure-enabled pattern slices to cover the
|
|
62
|
+
* transitive dependency closure of their seed changes.
|
|
63
|
+
*
|
|
64
|
+
* The closure follows declared plan `requires` edges plus AST-discovered
|
|
65
|
+
* edges. Only changes currently assigned to the default package are pulled in
|
|
66
|
+
* — a dependency that another explicit slice claimed stays where it is and
|
|
67
|
+
* remains an ordinary cross-package dependency. Mutates `assignments` in
|
|
68
|
+
* place and returns a report of every auto-included change and why.
|
|
69
|
+
*/
|
|
70
|
+
export function expandClosures(assignments, graph, astEdges, strategy, defaultPackage) {
|
|
71
|
+
const autoIncluded = [];
|
|
72
|
+
const defaultChanges = assignments.get(defaultPackage) ?? new Set();
|
|
73
|
+
for (const slice of strategy.slices) {
|
|
74
|
+
if (!slice.closure)
|
|
75
|
+
continue;
|
|
76
|
+
const pkgChanges = assignments.get(slice.packageName);
|
|
77
|
+
if (!pkgChanges || pkgChanges.size === 0)
|
|
78
|
+
continue;
|
|
79
|
+
const queue = [...pkgChanges];
|
|
80
|
+
const seen = new Set(queue);
|
|
81
|
+
while (queue.length > 0) {
|
|
82
|
+
const current = queue.shift();
|
|
83
|
+
const pull = (dep, reason, ref) => {
|
|
84
|
+
if (seen.has(dep))
|
|
85
|
+
return;
|
|
86
|
+
seen.add(dep);
|
|
87
|
+
if (pkgChanges.has(dep)) {
|
|
88
|
+
queue.push(dep);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
// A dependency claimed by another explicit slice stays where it is
|
|
92
|
+
// and remains an ordinary cross-package dependency.
|
|
93
|
+
if (!defaultChanges.has(dep))
|
|
94
|
+
return;
|
|
95
|
+
defaultChanges.delete(dep);
|
|
96
|
+
pkgChanges.add(dep);
|
|
97
|
+
queue.push(dep);
|
|
98
|
+
autoIncluded.push({
|
|
99
|
+
change: dep,
|
|
100
|
+
package: slice.packageName,
|
|
101
|
+
requiredBy: current,
|
|
102
|
+
reason,
|
|
103
|
+
...(ref ? { ref } : {})
|
|
104
|
+
});
|
|
105
|
+
};
|
|
106
|
+
for (const dep of graph.edges.get(current) ?? []) {
|
|
107
|
+
if (graph.nodes.has(dep))
|
|
108
|
+
pull(dep, 'requires');
|
|
109
|
+
}
|
|
110
|
+
for (const [dep, ref] of astEdges.edges.get(current) ?? []) {
|
|
111
|
+
pull(dep, 'ast', ref);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return {
|
|
116
|
+
autoIncluded,
|
|
117
|
+
dynamicSqlChanges: astEdges.dynamicSqlChanges,
|
|
118
|
+
unresolvedReferences: astEdges.unresolvedReferences
|
|
119
|
+
};
|
|
120
|
+
}
|
package/esm/index.js
ADDED
package/esm/output.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
/**
|
|
4
|
+
* Write sliced packages to disk
|
|
5
|
+
*/
|
|
6
|
+
export function writeSliceResult(result, options) {
|
|
7
|
+
const { outputDir, overwrite = false, copySourceFiles = false, sourceDir } = options;
|
|
8
|
+
// Create output directory
|
|
9
|
+
fs.mkdirSync(outputDir, { recursive: true });
|
|
10
|
+
// Write each package
|
|
11
|
+
for (const pkg of result.packages) {
|
|
12
|
+
writePackage(pkg, outputDir, overwrite, copySourceFiles, sourceDir);
|
|
13
|
+
}
|
|
14
|
+
// Write workspace manifest
|
|
15
|
+
const manifestPath = path.join(outputDir, 'pgpm-workspace.json');
|
|
16
|
+
const manifestContent = JSON.stringify({
|
|
17
|
+
packages: result.workspace.packages.map(p => `packages/${p}`),
|
|
18
|
+
slicing: {
|
|
19
|
+
deployOrder: result.workspace.deployOrder,
|
|
20
|
+
dependencies: result.workspace.dependencies
|
|
21
|
+
},
|
|
22
|
+
stats: result.stats
|
|
23
|
+
}, null, 2);
|
|
24
|
+
fs.writeFileSync(manifestPath, manifestContent);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Write a single package to disk
|
|
28
|
+
*/
|
|
29
|
+
function writePackage(pkg, outputDir, overwrite, copySourceFiles, sourceDir) {
|
|
30
|
+
const pkgDir = path.join(outputDir, 'packages', pkg.name);
|
|
31
|
+
// Check if package already exists
|
|
32
|
+
if (fs.existsSync(pkgDir) && !overwrite) {
|
|
33
|
+
throw new Error(`Package directory already exists: ${pkgDir}. Use --overwrite to replace.`);
|
|
34
|
+
}
|
|
35
|
+
// Create package directory structure
|
|
36
|
+
fs.mkdirSync(pkgDir, { recursive: true });
|
|
37
|
+
fs.mkdirSync(path.join(pkgDir, 'deploy'), { recursive: true });
|
|
38
|
+
fs.mkdirSync(path.join(pkgDir, 'revert'), { recursive: true });
|
|
39
|
+
fs.mkdirSync(path.join(pkgDir, 'verify'), { recursive: true });
|
|
40
|
+
// Write plan file
|
|
41
|
+
fs.writeFileSync(path.join(pkgDir, 'pgpm.plan'), pkg.planContent);
|
|
42
|
+
// Write control file
|
|
43
|
+
fs.writeFileSync(path.join(pkgDir, `${pkg.name}.control`), pkg.controlContent);
|
|
44
|
+
// Copy SQL files if requested
|
|
45
|
+
if (copySourceFiles && sourceDir) {
|
|
46
|
+
for (const change of pkg.changes) {
|
|
47
|
+
copyChangeFiles(change.name, sourceDir, pkgDir);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Copy deploy/revert/verify SQL files for a change
|
|
53
|
+
*/
|
|
54
|
+
function copyChangeFiles(changeName, sourceDir, targetDir) {
|
|
55
|
+
const types = ['deploy', 'revert', 'verify'];
|
|
56
|
+
for (const type of types) {
|
|
57
|
+
const sourceFile = path.join(sourceDir, type, `${changeName}.sql`);
|
|
58
|
+
const targetFile = path.join(targetDir, type, `${changeName}.sql`);
|
|
59
|
+
if (fs.existsSync(sourceFile)) {
|
|
60
|
+
// Create target directory if needed
|
|
61
|
+
const targetSubDir = path.dirname(targetFile);
|
|
62
|
+
fs.mkdirSync(targetSubDir, { recursive: true });
|
|
63
|
+
// Copy file
|
|
64
|
+
fs.copyFileSync(sourceFile, targetFile);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Generate a dry-run report of what would be created
|
|
70
|
+
*/
|
|
71
|
+
export function generateDryRunReport(result) {
|
|
72
|
+
const lines = [];
|
|
73
|
+
lines.push('=== PGPM Slice Dry Run Report ===\n');
|
|
74
|
+
// Statistics
|
|
75
|
+
lines.push('Statistics:');
|
|
76
|
+
lines.push(` Total changes: ${result.stats.totalChanges}`);
|
|
77
|
+
lines.push(` Packages to create: ${result.stats.packagesCreated}`);
|
|
78
|
+
lines.push(` Internal edges: ${result.stats.internalEdges}`);
|
|
79
|
+
lines.push(` Cross-package edges: ${result.stats.crossPackageEdges}`);
|
|
80
|
+
lines.push(` Cross-package ratio: ${(result.stats.crossPackageRatio * 100).toFixed(1)}%`);
|
|
81
|
+
lines.push('');
|
|
82
|
+
// Warnings
|
|
83
|
+
if (result.warnings.length > 0) {
|
|
84
|
+
lines.push('Warnings:');
|
|
85
|
+
for (const warning of result.warnings) {
|
|
86
|
+
lines.push(` [${warning.type}] ${warning.message}`);
|
|
87
|
+
if (warning.suggestedAction) {
|
|
88
|
+
lines.push(` Suggestion: ${warning.suggestedAction}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
lines.push('');
|
|
92
|
+
}
|
|
93
|
+
// Deploy order
|
|
94
|
+
lines.push('Deploy Order:');
|
|
95
|
+
for (let i = 0; i < result.workspace.deployOrder.length; i++) {
|
|
96
|
+
const pkg = result.workspace.deployOrder[i];
|
|
97
|
+
const deps = result.workspace.dependencies[pkg] || [];
|
|
98
|
+
const depStr = deps.length > 0 ? ` (depends on: ${deps.join(', ')})` : '';
|
|
99
|
+
lines.push(` ${i + 1}. ${pkg}${depStr}`);
|
|
100
|
+
}
|
|
101
|
+
lines.push('');
|
|
102
|
+
// Package details
|
|
103
|
+
lines.push('Packages:');
|
|
104
|
+
for (const pkg of result.packages) {
|
|
105
|
+
lines.push(`\n ${pkg.name}/`);
|
|
106
|
+
lines.push(` Changes: ${pkg.changes.length}`);
|
|
107
|
+
lines.push(` Dependencies: ${pkg.packageDependencies.join(', ') || 'none'}`);
|
|
108
|
+
lines.push(' Contents:');
|
|
109
|
+
for (const change of pkg.changes.slice(0, 5)) {
|
|
110
|
+
lines.push(` - ${change.name}`);
|
|
111
|
+
}
|
|
112
|
+
if (pkg.changes.length > 5) {
|
|
113
|
+
lines.push(` ... and ${pkg.changes.length - 5} more`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return lines.join('\n');
|
|
117
|
+
}
|
package/esm/refs.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { classifyStatements } from '@pgpmjs/transform';
|
|
2
|
+
/**
|
|
3
|
+
* The parser runs on a WASM build of the real PostgreSQL parser; callers must
|
|
4
|
+
* `await loadModule()` once before any synchronous extraction/slicing call.
|
|
5
|
+
*/
|
|
6
|
+
export { loadModule } from 'plpgsql-parser';
|
|
7
|
+
function pushUnique(list, r) {
|
|
8
|
+
if (list.some(x => x.schema === r.schema && x.name === r.name))
|
|
9
|
+
return;
|
|
10
|
+
list.push(r);
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Extract created objects and schema-qualified references from a SQL script,
|
|
14
|
+
* including references reached inside PL/pgSQL function bodies (which are
|
|
15
|
+
* opaque strings in `CREATE FUNCTION` and invisible to a plain SQL parse).
|
|
16
|
+
*
|
|
17
|
+
* Aggregates `@pgsql/transform`'s per-statement `classifyStatements` facts to
|
|
18
|
+
* the change level: references satisfied by objects the same change creates
|
|
19
|
+
* (in any statement) are dropped.
|
|
20
|
+
*/
|
|
21
|
+
export function extractSqlFacts(sql) {
|
|
22
|
+
const facts = { creates: [], references: [], dynamicSql: false };
|
|
23
|
+
for (const stmt of classifyStatements(sql)) {
|
|
24
|
+
for (const c of stmt.creates) {
|
|
25
|
+
pushUnique(facts.creates, { schema: c.schema, name: c.name });
|
|
26
|
+
}
|
|
27
|
+
for (const r of stmt.references) {
|
|
28
|
+
pushUnique(facts.references, { schema: r.schema, name: r.name });
|
|
29
|
+
}
|
|
30
|
+
if (stmt.dynamicSql)
|
|
31
|
+
facts.dynamicSql = true;
|
|
32
|
+
}
|
|
33
|
+
// A change does not depend on objects it creates itself.
|
|
34
|
+
facts.references = facts.references.filter(r => !facts.creates.some(c => c.schema === r.schema && c.name === r.name));
|
|
35
|
+
return facts;
|
|
36
|
+
}
|