@pgpmjs/ast 0.1.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 +99 -0
- package/esm/files/extension/index.js +3 -0
- package/esm/files/extension/reader.js +79 -0
- package/esm/files/extension/writer.js +99 -0
- package/esm/files/index.js +6 -0
- package/esm/files/plan/generator.js +82 -0
- package/esm/files/plan/index.js +5 -0
- package/esm/files/plan/parser.js +297 -0
- package/esm/files/plan/validators.js +181 -0
- package/esm/files/plan/writer.js +142 -0
- package/esm/files/sql/header.js +259 -0
- package/esm/files/sql/index.js +2 -0
- package/esm/files/sql/writer.js +107 -0
- package/esm/files/sql-scripts/index.js +2 -0
- package/esm/files/sql-scripts/reader.js +19 -0
- package/esm/files/types/index.js +1 -0
- package/esm/files/types/package.js +1 -0
- package/esm/hash.js +9 -0
- package/esm/index.js +18 -0
- package/esm/module/index.js +12 -0
- package/esm/module/parse.js +27 -0
- package/esm/module/reader.js +64 -0
- package/esm/module/roundtrip.js +65 -0
- package/esm/module/types.js +1 -0
- package/esm/module/writer.js +45 -0
- package/esm/plan-rename.js +28 -0
- package/esm/utils/author.js +11 -0
- package/files/extension/index.d.ts +2 -0
- package/files/extension/index.js +19 -0
- package/files/extension/reader.d.ts +24 -0
- package/files/extension/reader.js +86 -0
- package/files/extension/writer.d.ts +48 -0
- package/files/extension/writer.js +107 -0
- package/files/index.d.ts +5 -0
- package/files/index.js +22 -0
- package/files/plan/generator.d.ts +23 -0
- package/files/plan/generator.js +90 -0
- package/files/plan/index.d.ts +4 -0
- package/files/plan/index.js +21 -0
- package/files/plan/parser.d.ts +28 -0
- package/files/plan/parser.js +304 -0
- package/files/plan/validators.d.ts +52 -0
- package/files/plan/validators.js +187 -0
- package/files/plan/writer.d.ts +27 -0
- package/files/plan/writer.js +152 -0
- package/files/sql/header.d.ts +114 -0
- package/files/sql/header.js +266 -0
- package/files/sql/index.d.ts +2 -0
- package/files/sql/index.js +18 -0
- package/files/sql/writer.d.ts +12 -0
- package/files/sql/writer.js +114 -0
- package/files/sql-scripts/index.d.ts +1 -0
- package/files/sql-scripts/index.js +18 -0
- package/files/sql-scripts/reader.d.ts +8 -0
- package/files/sql-scripts/reader.js +23 -0
- package/files/types/index.d.ts +46 -0
- package/files/types/index.js +17 -0
- package/files/types/package.d.ts +20 -0
- package/files/types/package.js +2 -0
- package/hash.d.ts +6 -0
- package/hash.js +12 -0
- package/index.d.ts +19 -0
- package/index.js +36 -0
- package/module/index.d.ts +12 -0
- package/module/index.js +28 -0
- package/module/parse.d.ts +23 -0
- package/module/parse.js +31 -0
- package/module/reader.d.ts +13 -0
- package/module/reader.js +67 -0
- package/module/roundtrip.d.ts +22 -0
- package/module/roundtrip.js +68 -0
- package/module/types.d.ts +72 -0
- package/module/types.js +2 -0
- package/module/writer.d.ts +30 -0
- package/module/writer.js +50 -0
- package/package.json +48 -0
- package/plan-rename.d.ts +8 -0
- package/plan-rename.js +31 -0
- package/utils/author.d.ts +5 -0
- package/utils/author.js +14 -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,99 @@
|
|
|
1
|
+
# @pgpmjs/ast
|
|
2
|
+
|
|
3
|
+
<p align="center" width="100%">
|
|
4
|
+
<img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
|
|
5
|
+
</p>
|
|
6
|
+
|
|
7
|
+
<p align="center" width="100%">
|
|
8
|
+
<a href="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml">
|
|
9
|
+
<img height="20" src="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml/badge.svg" />
|
|
10
|
+
</a>
|
|
11
|
+
<a href="https://github.com/constructive-io/constructive/blob/main/LICENSE"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
|
|
12
|
+
<a href="https://www.npmjs.com/package/@pgpmjs/ast"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/constructive?filename=pgpm%2Fast%2Fpackage.json"/></a>
|
|
13
|
+
</p>
|
|
14
|
+
|
|
15
|
+
The pgpm **module AST** — the plan/control/SQL-header parsers (`files/*`) and the
|
|
16
|
+
lossless module read/write layer (`module/*`) that composes them into a single typed
|
|
17
|
+
`PgpmModuleAst`.
|
|
18
|
+
|
|
19
|
+
- `readModule(dir)` / `parseModule(dir)` — parse a pgpm module directory into a typed AST.
|
|
20
|
+
- `writeModule(ast, { outDir })` / `deparseModule(ast)` — serialize the AST back to a
|
|
21
|
+
module (byte-lossless for modules read via `readModule`).
|
|
22
|
+
- `files/*` — the low-level parsers/writers everything else composes; no re-implementation.
|
|
23
|
+
|
|
24
|
+
This package is a pure leaf (no database, no deploy engine). `@pgpmjs/core` and the
|
|
25
|
+
migration-bundle artifact layer build on top of it. See the `pgpm-migration-bundle` skill
|
|
26
|
+
for how the bundle layer uses this AST.
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## Education and Tutorials
|
|
31
|
+
|
|
32
|
+
1. 🚀 [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
|
|
33
|
+
Get started with modular databases in minutes. Install prerequisites and deploy your first module.
|
|
34
|
+
|
|
35
|
+
2. 📦 [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
|
|
36
|
+
Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
|
|
37
|
+
|
|
38
|
+
3. ✏️ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
|
|
39
|
+
Master the workflow for adding, organizing, and managing database changes with pgpm.
|
|
40
|
+
|
|
41
|
+
4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
|
|
42
|
+
Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
|
|
43
|
+
|
|
44
|
+
5. ⚡ [Supabase Testing](https://constructive.io/learn/supabase)
|
|
45
|
+
Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
|
|
46
|
+
|
|
47
|
+
6. 💧 [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
|
|
48
|
+
Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
|
|
49
|
+
|
|
50
|
+
7. 🔧 [Troubleshooting](https://constructive.io/learn/troubleshooting)
|
|
51
|
+
Common issues and solutions for pgpm, PostgreSQL, and testing.
|
|
52
|
+
|
|
53
|
+
## Related Constructive Tooling
|
|
54
|
+
|
|
55
|
+
### 📦 Package Management
|
|
56
|
+
|
|
57
|
+
* [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.
|
|
58
|
+
|
|
59
|
+
### 🧪 Testing
|
|
60
|
+
|
|
61
|
+
* [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.
|
|
62
|
+
* [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.
|
|
63
|
+
* [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.
|
|
64
|
+
* [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.
|
|
65
|
+
* [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.
|
|
66
|
+
|
|
67
|
+
### 🧠 Parsing & AST
|
|
68
|
+
|
|
69
|
+
* [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
|
|
70
|
+
* [libpg-query-node](https://www.npmjs.com/package/libpg-query): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
|
|
71
|
+
* [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.
|
|
72
|
+
* [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
|
|
73
|
+
* [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
|
|
74
|
+
* [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
|
|
75
|
+
|
|
76
|
+
### 📚 Documentation & Skills
|
|
77
|
+
|
|
78
|
+
* [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.
|
|
79
|
+
|
|
80
|
+
Install skills for AI coding agents:
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
# All platform skills (security, blueprints, codegen, billing, etc.)
|
|
84
|
+
npx skills add constructive-io/constructive-skills
|
|
85
|
+
|
|
86
|
+
# Individual repo skills (pgpm, testing, CLI, search, etc.)
|
|
87
|
+
npx skills add https://github.com/constructive-io/constructive --skill pgpm
|
|
88
|
+
npx skills add https://github.com/constructive-io/constructive --skill constructive-testing
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Credits
|
|
92
|
+
|
|
93
|
+
**🛠 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).**
|
|
94
|
+
|
|
95
|
+
## Disclaimer
|
|
96
|
+
|
|
97
|
+
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
98
|
+
|
|
99
|
+
No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { readFileSync } from 'fs';
|
|
2
|
+
import { basename, dirname, relative } from 'path';
|
|
3
|
+
import { parsePlanFileSimple } from '../plan';
|
|
4
|
+
/**
|
|
5
|
+
* Parse a .control file and extract its metadata.
|
|
6
|
+
* https://www.postgresql.org/docs/current/extend-extensions.html
|
|
7
|
+
*/
|
|
8
|
+
export function parseControlFile(filePath, basePath) {
|
|
9
|
+
const contents = readFileSync(filePath, 'utf-8');
|
|
10
|
+
const key = basename(filePath).split('.control')[0];
|
|
11
|
+
const requires = contents
|
|
12
|
+
.split('\n')
|
|
13
|
+
.find((line) => /^requires/.test(line))
|
|
14
|
+
?.split('=')[1]
|
|
15
|
+
.split(',')
|
|
16
|
+
.map((req) => req.replace(/[\'\s]*/g, '').trim()) || [];
|
|
17
|
+
const version = contents
|
|
18
|
+
.split('\n')
|
|
19
|
+
.find((line) => /^default_version/.test(line))
|
|
20
|
+
?.split('=')[1]
|
|
21
|
+
.replace(/[\']*/g, '')
|
|
22
|
+
.trim() || '';
|
|
23
|
+
return {
|
|
24
|
+
path: dirname(relative(basePath, filePath)),
|
|
25
|
+
requires,
|
|
26
|
+
version,
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Parse the pgpm.plan file to get the extension name.
|
|
31
|
+
*/
|
|
32
|
+
export const getExtensionName = (packageDir) => {
|
|
33
|
+
const planPath = `${packageDir}/pgpm.plan`;
|
|
34
|
+
const plan = parsePlanFileSimple(planPath);
|
|
35
|
+
if (!plan.package) {
|
|
36
|
+
throw new Error('No package name found in pgpm.plan!');
|
|
37
|
+
}
|
|
38
|
+
return plan.package;
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Get detailed information about an extension in the specified directory.
|
|
42
|
+
*/
|
|
43
|
+
export const getExtensionInfo = (packageDir) => {
|
|
44
|
+
const pkgPath = `${packageDir}/package.json`;
|
|
45
|
+
const pkg = require(pkgPath);
|
|
46
|
+
const extname = getExtensionName(packageDir);
|
|
47
|
+
const version = pkg.version;
|
|
48
|
+
const Makefile = `${packageDir}/Makefile`;
|
|
49
|
+
const controlFile = `${packageDir}/${extname}.control`;
|
|
50
|
+
const sqlFile = `sql/${extname}--${version}.sql`;
|
|
51
|
+
return { extname, packageDir, version, Makefile, controlFile, sqlFile };
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* Get a list of extensions required by an extension from its control file.
|
|
55
|
+
* Returns an empty array if the file doesn't exist or has no requires line.
|
|
56
|
+
*/
|
|
57
|
+
export const getInstalledExtensions = (controlFilePath) => {
|
|
58
|
+
try {
|
|
59
|
+
const contents = readFileSync(controlFilePath, 'utf-8');
|
|
60
|
+
const match = contents.match(/^\s*requires\s*=\s*'([^']*)'/m);
|
|
61
|
+
if (!match) {
|
|
62
|
+
return [];
|
|
63
|
+
}
|
|
64
|
+
const requiresValue = match[1];
|
|
65
|
+
if (!requiresValue || requiresValue.trim() === '') {
|
|
66
|
+
return [];
|
|
67
|
+
}
|
|
68
|
+
return requiresValue
|
|
69
|
+
.split(',')
|
|
70
|
+
.map((ext) => ext.trim())
|
|
71
|
+
.filter((ext) => ext.length > 0);
|
|
72
|
+
}
|
|
73
|
+
catch (e) {
|
|
74
|
+
if (e.code === 'ENOENT') {
|
|
75
|
+
return [];
|
|
76
|
+
}
|
|
77
|
+
throw new Error(`Error reading control file at ${controlFilePath}: ${e.message}`);
|
|
78
|
+
}
|
|
79
|
+
};
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from 'fs';
|
|
2
|
+
import { getExtensionInfo } from './reader';
|
|
3
|
+
/**
|
|
4
|
+
* Write the Makefile for the extension.
|
|
5
|
+
*/
|
|
6
|
+
export const writeExtensionMakefile = (outputPath, extname, version) => {
|
|
7
|
+
const content = `EXTENSION = ${extname}
|
|
8
|
+
DATA = sql/${extname}--${version}.sql
|
|
9
|
+
|
|
10
|
+
PG_CONFIG = pg_config
|
|
11
|
+
PGXS := $(shell $(PG_CONFIG) --pgxs)
|
|
12
|
+
include $(PGXS)
|
|
13
|
+
`;
|
|
14
|
+
writeFileSync(outputPath, content);
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Generate content for a .control file
|
|
18
|
+
* https://www.postgresql.org/docs/current/extend-extensions.html
|
|
19
|
+
*/
|
|
20
|
+
export function generateControlFileContent(options) {
|
|
21
|
+
const { name, version, comment = `${name} extension`, requires = [], default_version = version, relocatable = false, superuser = false, schema, module_pathname } = options;
|
|
22
|
+
let content = `# ${name} extension
|
|
23
|
+
comment = '${comment}'
|
|
24
|
+
default_version = '${default_version}'
|
|
25
|
+
`;
|
|
26
|
+
if (module_pathname) {
|
|
27
|
+
content += `module_pathname = '${module_pathname}'\n`;
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
content += `module_pathname = '$libdir/${name}'\n`;
|
|
31
|
+
}
|
|
32
|
+
if (requires.length > 0) {
|
|
33
|
+
content += `requires = '${requires.join(',')}'\n`;
|
|
34
|
+
}
|
|
35
|
+
content += `relocatable = ${relocatable}
|
|
36
|
+
superuser = ${superuser}\n`;
|
|
37
|
+
if (schema) {
|
|
38
|
+
content += `schema = ${schema}\n`;
|
|
39
|
+
}
|
|
40
|
+
return content;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Update (or insert/remove) the `requires =` line of an existing .control file
|
|
44
|
+
* in place, preserving every other field and the file's formatting. Used when
|
|
45
|
+
* changing a module's dependencies after init (e.g. via `pgpm extension`) so
|
|
46
|
+
* hand-tuned fields (comment, schema, relocatable, module_pathname) survive.
|
|
47
|
+
*/
|
|
48
|
+
export function upsertRequiresLine(content, requires) {
|
|
49
|
+
const lines = content.split('\n');
|
|
50
|
+
const idx = lines.findIndex((line) => /^\s*requires\s*=/.test(line));
|
|
51
|
+
if (requires.length === 0) {
|
|
52
|
+
if (idx !== -1)
|
|
53
|
+
lines.splice(idx, 1);
|
|
54
|
+
return lines.join('\n');
|
|
55
|
+
}
|
|
56
|
+
const requiresLine = `requires = '${requires.join(',')}'`;
|
|
57
|
+
if (idx !== -1) {
|
|
58
|
+
lines[idx] = requiresLine;
|
|
59
|
+
return lines.join('\n');
|
|
60
|
+
}
|
|
61
|
+
// Insert to match generated ordering (before relocatable/superuser/schema).
|
|
62
|
+
const insertAt = lines.findIndex((line) => /^\s*(relocatable|superuser|schema)\s*=/.test(line));
|
|
63
|
+
if (insertAt !== -1) {
|
|
64
|
+
lines.splice(insertAt, 0, requiresLine);
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
lines.push(requiresLine);
|
|
68
|
+
}
|
|
69
|
+
return lines.join('\n');
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Write the control file for the extension.
|
|
73
|
+
* If the file already exists, only its `requires` line is updated so that any
|
|
74
|
+
* custom fields are preserved; otherwise a fresh file is generated.
|
|
75
|
+
*/
|
|
76
|
+
export const writeExtensionControlFile = (outputPath, extname, extensions, version) => {
|
|
77
|
+
if (existsSync(outputPath)) {
|
|
78
|
+
const existing = readFileSync(outputPath, 'utf-8');
|
|
79
|
+
writeFileSync(outputPath, upsertRequiresLine(existing, extensions));
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
const content = generateControlFileContent({
|
|
83
|
+
name: extname,
|
|
84
|
+
version,
|
|
85
|
+
requires: extensions
|
|
86
|
+
});
|
|
87
|
+
writeFileSync(outputPath, content);
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* Write control and Makefile for the extension with given data.
|
|
91
|
+
* If extInfo is not provided, it will be generated from packageDir.
|
|
92
|
+
*/
|
|
93
|
+
export const writeExtensions = (packageDir, extensions, extInfo) => {
|
|
94
|
+
// If extInfo is not provided, get it from packageDir
|
|
95
|
+
const info = extInfo || getExtensionInfo(packageDir);
|
|
96
|
+
const { controlFile, Makefile, extname, version } = info;
|
|
97
|
+
writeExtensionControlFile(controlFile, extname, extensions, version);
|
|
98
|
+
writeExtensionMakefile(Makefile, extname, version);
|
|
99
|
+
};
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
/**
|
|
3
|
+
* Fixed epoch timestamp used for deterministic plan generation.
|
|
4
|
+
* Can be overridden with the PGPM_FROZEN_TIME environment variable.
|
|
5
|
+
*/
|
|
6
|
+
const DEFAULT_FROZEN_TIME = '2017-08-11T08:11:51Z';
|
|
7
|
+
/**
|
|
8
|
+
* Get a UTC timestamp string from a Date object.
|
|
9
|
+
*/
|
|
10
|
+
function getUTCTimestamp(d) {
|
|
11
|
+
return (d.getUTCFullYear() +
|
|
12
|
+
'-' + String(d.getUTCMonth() + 1).padStart(2, '0') +
|
|
13
|
+
'-' + String(d.getUTCDate()).padStart(2, '0') +
|
|
14
|
+
'T' + String(d.getUTCHours()).padStart(2, '0') +
|
|
15
|
+
':' + String(d.getUTCMinutes()).padStart(2, '0') +
|
|
16
|
+
':' + String(d.getUTCSeconds()).padStart(2, '0') +
|
|
17
|
+
'Z');
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Get a timestamp for the plan file.
|
|
21
|
+
* Uses the PGPM_FROZEN_TIME env var if present, otherwise the fixed epoch.
|
|
22
|
+
*/
|
|
23
|
+
export function getNow() {
|
|
24
|
+
const frozen = process.env.PGPM_FROZEN_TIME;
|
|
25
|
+
if (frozen) {
|
|
26
|
+
return getUTCTimestamp(new Date(frozen));
|
|
27
|
+
}
|
|
28
|
+
return DEFAULT_FROZEN_TIME;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Sort dependencies by their order in the supplied plan, so prerequisites
|
|
32
|
+
* (parent migrations) appear before their dependents in the bracket.
|
|
33
|
+
* Internal dependencies are sorted by their plan index, and external
|
|
34
|
+
* dependencies (not in the plan) preserve their original order.
|
|
35
|
+
*/
|
|
36
|
+
const sortDependencies = (deps, order) => {
|
|
37
|
+
const originalOrder = new Map(deps.map((dep, index) => [dep, index]));
|
|
38
|
+
return [...deps].sort((a, b) => {
|
|
39
|
+
const aIndex = order.get(a);
|
|
40
|
+
const bIndex = order.get(b);
|
|
41
|
+
const aOriginal = originalOrder.get(a);
|
|
42
|
+
const bOriginal = originalOrder.get(b);
|
|
43
|
+
if (aIndex !== undefined && bIndex !== undefined)
|
|
44
|
+
return aIndex - bIndex || aOriginal - bOriginal;
|
|
45
|
+
if (aIndex !== undefined)
|
|
46
|
+
return -1;
|
|
47
|
+
if (bIndex !== undefined)
|
|
48
|
+
return 1;
|
|
49
|
+
return aOriginal - bOriginal;
|
|
50
|
+
});
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Generate a plan file content from structured data
|
|
54
|
+
*/
|
|
55
|
+
export function generatePlan(options) {
|
|
56
|
+
const { moduleName, uri, entries } = options;
|
|
57
|
+
const now = getNow();
|
|
58
|
+
const planfile = [
|
|
59
|
+
`%syntax-version=1.0.0`,
|
|
60
|
+
`%project=${moduleName}`,
|
|
61
|
+
`%uri=${uri || moduleName}`
|
|
62
|
+
];
|
|
63
|
+
// Build an order map from the entry list so brackets can be sorted by plan order
|
|
64
|
+
const entryOrder = new Map(entries.map((entry, index) => [entry.change, index]));
|
|
65
|
+
// Generate the plan entries
|
|
66
|
+
entries.forEach(entry => {
|
|
67
|
+
const deps = sortDependencies(entry.dependencies || [], entryOrder);
|
|
68
|
+
if (deps.length > 0) {
|
|
69
|
+
planfile.push(`${entry.change} [${deps.join(' ')}] ${now} constructive <constructive@5b0c196eeb62>${entry.comment ? ` # ${entry.comment}` : ''}`);
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
planfile.push(`${entry.change} ${now} constructive <constructive@5b0c196eeb62>${entry.comment ? ` # ${entry.comment}` : ''}`);
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
return planfile.join('\n');
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Write a generated plan file to disk
|
|
79
|
+
*/
|
|
80
|
+
export function writePlan(planPath, plan) {
|
|
81
|
+
fs.writeFileSync(planPath, plan);
|
|
82
|
+
}
|