@agentplat/postgres 0.2.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/README.md ADDED
@@ -0,0 +1,37 @@
1
+ # `@agentplat/postgres`
2
+
3
+ Shared PostgreSQL primitives for AgentPlat adapters. The package intentionally
4
+ depends only on `pg`: applications opt into AWS SDKs, secret sources and
5
+ deployment tooling themselves.
6
+
7
+ ```ts
8
+ import { checkPostgresPool, createPostgresPool } from '@agentplat/postgres';
9
+
10
+ const pool = createPostgresPool({
11
+ application_name: 'agentplat-orders',
12
+ max: 10,
13
+ ssl: { rejectUnauthorized: true, ca: rdsCaBundle },
14
+ password: () => currentRdsIamToken(),
15
+ });
16
+
17
+ const readiness = await checkPostgresPool(pool);
18
+ ```
19
+
20
+ `checkPostgresPool` runs `SELECT 1` and returns latency plus total, idle and
21
+ waiting connection counts. Do not expose database errors on a public endpoint;
22
+ map only `ok` to the external readiness response.
23
+
24
+ ## Versioned migrations
25
+
26
+ `runPostgresMigrations` stores package/application-scoped versions and SHA-256
27
+ checksums in `<schema>._agentplat_migrations`. It rejects missing, reordered or
28
+ edited applied migrations and serializes deploys with an advisory lock.
29
+
30
+ Rollback is deliberately one version at a time. It requires the observed
31
+ current version, an exact confirmation string, and `allowDataLoss: true` for a
32
+ destructive down migration. Back up and test restore before supplying those
33
+ values in production.
34
+
35
+ Schema identifiers use a strict portable subset and are always quoted. Use one
36
+ schema per application when several AgentPlat apps share one cluster, then keep
37
+ `tenant_id` as the isolation key inside each application schema.
@@ -0,0 +1,91 @@
1
+ import { Pool } from 'pg';
2
+ import type { PoolConfig } from 'pg';
3
+ export declare const defaultPostgresSchema = "public";
4
+ export interface PostgresPoolOptions extends PoolConfig {
5
+ /** Falls back to DATABASE_URL, then to pg's standard PG* variables. */
6
+ connectionString?: string;
7
+ }
8
+ /**
9
+ * Create a pg pool without adding an AWS SDK dependency.
10
+ *
11
+ * `pg` accepts TLS options through `ssl` and a password callback through
12
+ * `password`, which allows callers to supply short-lived RDS IAM tokens.
13
+ */
14
+ export declare function createPostgresPool(options?: PostgresPoolOptions): Pool;
15
+ export interface PostgresPoolHealth {
16
+ ok: boolean;
17
+ latencyMs: number;
18
+ pool: {
19
+ total: number;
20
+ idle: number;
21
+ waiting: number;
22
+ };
23
+ error?: {
24
+ name: string;
25
+ message: string;
26
+ code?: string;
27
+ };
28
+ }
29
+ export interface PostgresHealthOptions {
30
+ /** Per-query timeout. Defaults to 2 seconds. */
31
+ timeoutMs?: number;
32
+ }
33
+ /** Readiness check that exercises a checked-out connection and reports pool pressure. */
34
+ export declare function checkPostgresPool(pool: Pool, options?: PostgresHealthOptions): Promise<PostgresPoolHealth>;
35
+ /** Restrict identifiers so schema names can be safely interpolated in DDL. */
36
+ export declare function normalizePostgresIdentifier(value: string, label?: string): string;
37
+ export declare function quotePostgresIdentifier(value: string): string;
38
+ export declare function qualifyPostgresName(schema: string, object: string): string;
39
+ /** Replace the explicit schema token used by packaged migration SQL. */
40
+ export declare function renderPostgresSchema(sql: string, schema: string): string;
41
+ export interface PostgresMigration {
42
+ version: number;
43
+ name: string;
44
+ up: string;
45
+ down?: string;
46
+ /** Down SQL destroys or irreversibly rewrites application data. */
47
+ destructiveDown?: boolean;
48
+ /** Optional boolean `present` query for adopting a legacy, pre-ledger migration. */
49
+ adoptIf?: string;
50
+ }
51
+ export interface PostgresMigrationOptions {
52
+ applicationId: string;
53
+ schema?: string;
54
+ migrations: readonly PostgresMigration[];
55
+ /** Create the application schema if it is absent. Defaults to false. */
56
+ createSchema?: boolean;
57
+ }
58
+ export interface AppliedPostgresMigration {
59
+ applicationId: string;
60
+ version: number;
61
+ name: string;
62
+ checksum: string;
63
+ appliedAt: string;
64
+ }
65
+ export interface PostgresMigrationStatus {
66
+ schema: string;
67
+ applicationId: string;
68
+ currentVersion: number;
69
+ availableVersion: number;
70
+ pendingVersions: number[];
71
+ applied: AppliedPostgresMigration[];
72
+ }
73
+ export interface PostgresRollbackOptions extends PostgresMigrationOptions {
74
+ /** Version currently expected by the operator; prevents rolling back stale state. */
75
+ expectedCurrentVersion: number;
76
+ /** Exact value returned by `postgresRollbackConfirmation`. */
77
+ confirm: string;
78
+ /** Required when the selected down migration is marked destructive. */
79
+ allowDataLoss?: boolean;
80
+ }
81
+ /** Apply every pending migration under one schema/application-scoped advisory lock. */
82
+ export declare function runPostgresMigrations(pool: Pool, options: PostgresMigrationOptions): Promise<PostgresMigrationStatus>;
83
+ /** Inspect versions and checksums without applying a migration. */
84
+ export declare function getPostgresMigrationStatus(pool: Pool, options: PostgresMigrationOptions): Promise<PostgresMigrationStatus>;
85
+ /**
86
+ * Roll back exactly the current top migration after explicit state and data-loss checks.
87
+ * This intentionally cannot roll back several versions in one call.
88
+ */
89
+ export declare function rollbackPostgresMigration(pool: Pool, options: PostgresRollbackOptions): Promise<PostgresMigrationStatus>;
90
+ export declare function postgresRollbackConfirmation(applicationId: string, schema: string, version: number): string;
91
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,IAAI,CAAC;AAC1B,OAAO,KAAK,EAAc,UAAU,EAAkB,MAAM,IAAI,CAAC;AAEjE,eAAO,MAAM,qBAAqB,WAAW,CAAC;AAE9C,MAAM,WAAW,mBAAoB,SAAQ,UAAU;IACrD,uEAAuE;IACvE,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,GAAE,mBAAwB,GAAG,IAAI,CAM1E;AAED,MAAM,WAAW,kBAAkB;IACjC,EAAE,EAAE,OAAO,CAAC;IACZ,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI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E,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,wBAAwB;IACvC,aAAa,EAAE,MAAM,CAAC;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,uBAAuB;IACtC,MAAM,EAAE,MAAM,CAAC;IACf,aAAa,EAAE,MAAM,CAAC;IACtB,cAAc,EAAE,MAAM,CAAC;IACvB,gBAAgB,EAAE,MAAM,CAAC;IACzB,eAAe,EAAE,MAAM,EAAE,CAAC;IAC1B,OAAO,EAAE,wBAAwB,EAAE,CAAC;CACrC;AAED,MAAM,WAAW,uBAAwB,SAAQ,wBAAwB;IACvE,qFAAqF;IACrF,sBAAsB,EAAE,MAAM,CAAC;IAC/B,8DAA8D;IAC9D,OAAO,EAAE,MAAM,CAAC;IAChB,uEAAuE;IACvE,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAID,uFAAuF;AACvF,wBAAsB,qBAAqB,CACzC,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,wBAAwB,GAChC,OAAO,CAAC,uBAAuB,CAAC,CAoClC;AAED,mEAAmE;AACnE,wBAAsB,0BAA0B,CAC9C,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,wBAAwB,GAChC,OAAO,CAAC,uBAAuB,CAAC,CAgBlC;AAED;;;GAGG;AACH,wBAAsB,yBAAyB,CAC7C,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,uBAAuB,GAC/B,OAAO,CAAC,uBAAuB,CAAC,CAmDlC;AAED,wBAAgB,4BAA4B,CAC1C,aAAa,EAAE,MAAM,EACrB,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,GACd,MAAM,CAER"}
package/dist/index.js ADDED
@@ -0,0 +1,316 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { Pool } from 'pg';
3
+ export const defaultPostgresSchema = 'public';
4
+ /**
5
+ * Create a pg pool without adding an AWS SDK dependency.
6
+ *
7
+ * `pg` accepts TLS options through `ssl` and a password callback through
8
+ * `password`, which allows callers to supply short-lived RDS IAM tokens.
9
+ */
10
+ export function createPostgresPool(options = {}) {
11
+ const connectionString = options.connectionString ?? process.env.DATABASE_URL;
12
+ return new Pool({
13
+ ...options,
14
+ ...(connectionString ? { connectionString } : {}),
15
+ });
16
+ }
17
+ /** Readiness check that exercises a checked-out connection and reports pool pressure. */
18
+ export async function checkPostgresPool(pool, options = {}) {
19
+ const timeoutMs = positiveInteger(options.timeoutMs ?? 2_000, 'timeoutMs');
20
+ const startedAt = performance.now();
21
+ let client;
22
+ try {
23
+ client = await pool.connect();
24
+ await client.query(`SET statement_timeout TO ${timeoutMs}`);
25
+ await client.query('SELECT 1');
26
+ return health(pool, true, startedAt);
27
+ }
28
+ catch (error) {
29
+ const result = health(pool, false, startedAt);
30
+ result.error = safeError(error);
31
+ return result;
32
+ }
33
+ finally {
34
+ if (client) {
35
+ let resetError;
36
+ await client.query('RESET statement_timeout').catch((error) => {
37
+ resetError =
38
+ error instanceof Error ? error : new Error('Failed to reset timeout');
39
+ });
40
+ client.release(resetError);
41
+ }
42
+ }
43
+ }
44
+ function health(pool, ok, startedAt) {
45
+ return {
46
+ ok,
47
+ latencyMs: Math.max(0, Math.round(performance.now() - startedAt)),
48
+ pool: {
49
+ total: pool.totalCount,
50
+ idle: pool.idleCount,
51
+ waiting: pool.waitingCount,
52
+ },
53
+ };
54
+ }
55
+ function safeError(error) {
56
+ const value = error instanceof Error ? error : new Error(String(error));
57
+ const code = typeof error === 'object' && error !== null && 'code' in error
58
+ ? String(error.code)
59
+ : undefined;
60
+ return {
61
+ name: value.name,
62
+ message: value.message,
63
+ ...(code ? { code } : {}),
64
+ };
65
+ }
66
+ /** Restrict identifiers so schema names can be safely interpolated in DDL. */
67
+ export function normalizePostgresIdentifier(value, label = 'identifier') {
68
+ const normalized = value.trim();
69
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(normalized)) {
70
+ throw new TypeError(`${label} must start with a letter or underscore and contain only letters, numbers, and underscores`);
71
+ }
72
+ if (Buffer.byteLength(normalized, 'utf8') > 63) {
73
+ throw new RangeError(`${label} must be at most 63 UTF-8 bytes`);
74
+ }
75
+ return normalized;
76
+ }
77
+ export function quotePostgresIdentifier(value) {
78
+ return `"${normalizePostgresIdentifier(value)}"`;
79
+ }
80
+ export function qualifyPostgresName(schema, object) {
81
+ return `${quotePostgresIdentifier(schema)}.${quotePostgresIdentifier(object)}`;
82
+ }
83
+ /** Replace the explicit schema token used by packaged migration SQL. */
84
+ export function renderPostgresSchema(sql, schema) {
85
+ return sql.replaceAll('__AGENTPLAT_SCHEMA__', quotePostgresIdentifier(schema));
86
+ }
87
+ const ledgerName = '_agentplat_migrations';
88
+ /** Apply every pending migration under one schema/application-scoped advisory lock. */
89
+ export async function runPostgresMigrations(pool, options) {
90
+ const normalized = normalizeMigrationOptions(options);
91
+ return withMigrationLock(pool, normalized, async (client) => {
92
+ await ensureMigrationInfrastructure(client, normalized);
93
+ const applied = await readApplied(client, normalized);
94
+ verifyApplied(applied, normalized.migrations);
95
+ for (const migration of normalized.migrations.slice(applied.length)) {
96
+ await client.query('BEGIN');
97
+ try {
98
+ const adopted = migration.adoptIf
99
+ ? await shouldAdopt(client, migration.adoptIf, normalized.schema)
100
+ : false;
101
+ if (!adopted) {
102
+ await client.query(renderPostgresSchema(migration.up, normalized.schema));
103
+ }
104
+ await client.query(`INSERT INTO ${ledger(normalized.schema)}
105
+ (application_id, version, name, checksum)
106
+ VALUES ($1, $2, $3, $4)`, [
107
+ normalized.applicationId,
108
+ migration.version,
109
+ migration.name,
110
+ migrationChecksum(migration.up),
111
+ ]);
112
+ await client.query('COMMIT');
113
+ }
114
+ catch (error) {
115
+ await client.query('ROLLBACK').catch(() => undefined);
116
+ throw error;
117
+ }
118
+ }
119
+ return migrationStatus(client, normalized);
120
+ });
121
+ }
122
+ /** Inspect versions and checksums without applying a migration. */
123
+ export async function getPostgresMigrationStatus(pool, options) {
124
+ const normalized = normalizeMigrationOptions(options);
125
+ const client = await pool.connect();
126
+ try {
127
+ if (!(await schemaExists(client, normalized.schema))) {
128
+ return emptyStatus(normalized);
129
+ }
130
+ if (!(await ledgerExists(client, normalized.schema))) {
131
+ return emptyStatus(normalized);
132
+ }
133
+ const applied = await readApplied(client, normalized);
134
+ verifyApplied(applied, normalized.migrations);
135
+ return statusFrom(normalized, applied);
136
+ }
137
+ finally {
138
+ client.release();
139
+ }
140
+ }
141
+ /**
142
+ * Roll back exactly the current top migration after explicit state and data-loss checks.
143
+ * This intentionally cannot roll back several versions in one call.
144
+ */
145
+ export async function rollbackPostgresMigration(pool, options) {
146
+ const normalized = normalizeMigrationOptions(options);
147
+ positiveInteger(options.expectedCurrentVersion, 'expectedCurrentVersion');
148
+ const expectedConfirmation = postgresRollbackConfirmation(normalized.applicationId, normalized.schema, options.expectedCurrentVersion);
149
+ if (options.confirm !== expectedConfirmation) {
150
+ throw new Error(`Rollback confirmation does not match. Expected: ${expectedConfirmation}`);
151
+ }
152
+ return withMigrationLock(pool, normalized, async (client) => {
153
+ await ensureMigrationInfrastructure(client, normalized);
154
+ const applied = await readApplied(client, normalized);
155
+ verifyApplied(applied, normalized.migrations);
156
+ const current = applied.at(-1);
157
+ if (!current || current.version !== options.expectedCurrentVersion) {
158
+ throw new Error(`Database is at version ${current?.version ?? 0}, expected ${options.expectedCurrentVersion}`);
159
+ }
160
+ const migration = normalized.migrations.find((candidate) => candidate.version === current.version);
161
+ if (!migration?.down) {
162
+ throw new Error(`Migration ${current.version} has no down migration`);
163
+ }
164
+ if (migration.destructiveDown && options.allowDataLoss !== true) {
165
+ throw new Error(`Migration ${current.version} is destructive; set allowDataLoss only after backup and restore verification`);
166
+ }
167
+ await client.query('BEGIN');
168
+ try {
169
+ await client.query(renderPostgresSchema(migration.down, normalized.schema));
170
+ await client.query(`DELETE FROM ${ledger(normalized.schema)}
171
+ WHERE application_id = $1 AND version = $2`, [normalized.applicationId, migration.version]);
172
+ await client.query('COMMIT');
173
+ }
174
+ catch (error) {
175
+ await client.query('ROLLBACK').catch(() => undefined);
176
+ throw error;
177
+ }
178
+ return migrationStatus(client, normalized);
179
+ });
180
+ }
181
+ export function postgresRollbackConfirmation(applicationId, schema, version) {
182
+ return `ROLLBACK ${applicationId} VERSION ${version} FROM ${normalizePostgresIdentifier(schema, 'schema')}`;
183
+ }
184
+ function normalizeMigrationOptions(options) {
185
+ const applicationId = options.applicationId.trim();
186
+ if (!applicationId)
187
+ throw new TypeError('applicationId is required');
188
+ const schema = normalizePostgresIdentifier(options.schema ?? defaultPostgresSchema, 'schema');
189
+ const migrations = [...options.migrations].sort((left, right) => left.version - right.version);
190
+ migrations.forEach((migration, index) => {
191
+ if (migration.version !== index + 1) {
192
+ throw new Error('Migration versions must be contiguous and start at 1');
193
+ }
194
+ if (!migration.name.trim() || !migration.up.trim()) {
195
+ throw new Error(`Migration ${migration.version} requires name and up SQL`);
196
+ }
197
+ });
198
+ return {
199
+ applicationId,
200
+ schema,
201
+ migrations,
202
+ createSchema: options.createSchema === true,
203
+ };
204
+ }
205
+ async function withMigrationLock(pool, options, operation) {
206
+ const client = await pool.connect();
207
+ const lock = `agentplat:migrations:${options.schema}:${options.applicationId}`;
208
+ try {
209
+ await client.query('SELECT pg_advisory_lock(hashtext($1))', [lock]);
210
+ return await operation(client);
211
+ }
212
+ finally {
213
+ await client
214
+ .query('SELECT pg_advisory_unlock(hashtext($1))', [lock])
215
+ .catch(() => undefined);
216
+ client.release();
217
+ }
218
+ }
219
+ async function ensureMigrationInfrastructure(client, options) {
220
+ if (!(await schemaExists(client, options.schema))) {
221
+ if (!options.createSchema) {
222
+ throw new Error(`PostgreSQL schema "${options.schema}" does not exist; create it with the migration role or set createSchema`);
223
+ }
224
+ await client.query(`CREATE SCHEMA IF NOT EXISTS ${quotePostgresIdentifier(options.schema)}`);
225
+ }
226
+ await ensureLedger(client, options.schema);
227
+ }
228
+ async function schemaExists(client, schema) {
229
+ const result = await client.query('SELECT EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = $1) AS present', [schema]);
230
+ return result.rows[0]?.present === true;
231
+ }
232
+ async function ensureLedger(client, schema) {
233
+ await client.query(`CREATE TABLE IF NOT EXISTS ${ledger(schema)} (
234
+ application_id text NOT NULL,
235
+ version integer NOT NULL CHECK (version > 0),
236
+ name text NOT NULL,
237
+ checksum text NOT NULL,
238
+ applied_at timestamptz NOT NULL DEFAULT clock_timestamp(),
239
+ PRIMARY KEY (application_id, version),
240
+ UNIQUE (application_id, name)
241
+ )`);
242
+ }
243
+ async function ledgerExists(client, schema) {
244
+ const result = await client.query(`SELECT EXISTS (
245
+ SELECT 1
246
+ FROM pg_class class
247
+ JOIN pg_namespace namespace ON namespace.oid = class.relnamespace
248
+ WHERE namespace.nspname = $1 AND class.relname = $2
249
+ ) AS present`, [schema, ledgerName]);
250
+ return result.rows[0]?.present === true;
251
+ }
252
+ async function shouldAdopt(client, sql, schema) {
253
+ const result = await client.query(renderPostgresSchema(sql, schema));
254
+ return result.rows[0]?.present === true;
255
+ }
256
+ async function readApplied(client, options) {
257
+ const result = await client.query(`SELECT application_id, version, name, checksum, applied_at
258
+ FROM ${ledger(options.schema)}
259
+ WHERE application_id = $1
260
+ ORDER BY version`, [options.applicationId]);
261
+ return result.rows.map((row) => ({
262
+ applicationId: String(row.application_id),
263
+ version: Number(row.version),
264
+ name: String(row.name),
265
+ checksum: String(row.checksum),
266
+ appliedAt: row.applied_at instanceof Date
267
+ ? row.applied_at.toISOString()
268
+ : String(row.applied_at),
269
+ }));
270
+ }
271
+ function verifyApplied(applied, available) {
272
+ for (let index = 0; index < applied.length; index += 1) {
273
+ const record = applied[index];
274
+ const migration = available[index];
275
+ if (!migration || record.version !== migration.version) {
276
+ throw new Error(`Applied migration version ${record.version} is unavailable`);
277
+ }
278
+ if (record.name !== migration.name ||
279
+ record.checksum !== migrationChecksum(migration.up)) {
280
+ throw new Error(`Applied migration ${record.version} differs from packaged SQL; never edit an applied migration`);
281
+ }
282
+ }
283
+ }
284
+ async function migrationStatus(client, options) {
285
+ return statusFrom(options, await readApplied(client, options));
286
+ }
287
+ function statusFrom(options, applied) {
288
+ return {
289
+ schema: options.schema,
290
+ applicationId: options.applicationId,
291
+ currentVersion: applied.at(-1)?.version ?? 0,
292
+ availableVersion: options.migrations.at(-1)?.version ?? 0,
293
+ pendingVersions: options.migrations
294
+ .slice(applied.length)
295
+ .map((migration) => migration.version),
296
+ applied,
297
+ };
298
+ }
299
+ function emptyStatus(options) {
300
+ return statusFrom(options, []);
301
+ }
302
+ function ledger(schema) {
303
+ return qualifyPostgresName(schema, ledgerName);
304
+ }
305
+ function migrationChecksum(sql) {
306
+ return createHash('sha256')
307
+ .update(sql.replaceAll('\r\n', '\n'))
308
+ .digest('hex');
309
+ }
310
+ function positiveInteger(value, label) {
311
+ if (!Number.isInteger(value) || value <= 0) {
312
+ throw new RangeError(`${label} must be a positive integer`);
313
+ }
314
+ return value;
315
+ }
316
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,IAAI,EAAE,MAAM,IAAI,CAAC;AAG1B,MAAM,CAAC,MAAM,qBAAqB,GAAG,QAAQ,CAAC;AAO9C;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAAC,UAA+B,EAAE;IAClE,MAAM,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,IAAI,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC;IAC9E,OAAO,IAAI,IAAI,CAAC;QACd,GAAG,OAAO;QACV,GAAG,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,gBAAgB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAClD,CAAC,CAAC;AACL,CAAC;AAsBD,yFAAyF;AACzF,MAAM,CA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,CAAC;aACrB,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,OAAO,CAAC;QACxC,OAAO;KACR,CAAC;AACJ,CAAC;AAED,SAAS,WAAW,CAClB,OAAmC;IAEnC,OAAO,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;AACjC,CAAC;AAED,SAAS,MAAM,CAAC,MAAc;IAC5B,OAAO,mBAAmB,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;AACjD,CAAC;AAED,SAAS,iBAAiB,CAAC,GAAW;IACpC,OAAO,UAAU,CAAC,QAAQ,CAAC;SACxB,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;SACpC,MAAM,CAAC,KAAK,CAAC,CAAC;AACnB,CAAC;AAED,SAAS,eAAe,CAAC,KAAa,EAAE,KAAa;IACnD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,EAAE,CAAC;QAC3C,MAAM,IAAI,UAAU,CAAC,GAAG,KAAK,6BAA6B,CAAC,CAAC;IAC9D,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC"}
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@agentplat/postgres",
3
+ "version": "0.2.0-beta.11",
4
+ "description": "Shared PostgreSQL pool, health and migration primitives for AgentPlat adapters.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "sideEffects": false,
8
+ "main": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "README.md"
19
+ ],
20
+ "dependencies": {
21
+ "pg": "^8.13.1"
22
+ },
23
+ "devDependencies": {
24
+ "@types/node": "^20.10.0",
25
+ "@types/pg": "^8.11.10"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/Agentplat/agentplat.git",
33
+ "directory": "packages/postgres"
34
+ },
35
+ "scripts": {
36
+ "build": "tsc -p tsconfig.json",
37
+ "type-check": "tsc -p tsconfig.json --noEmit",
38
+ "clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\""
39
+ }
40
+ }