@astratra/store-postgres 1.0.2 → 1.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 +1 -1
- package/README.md +24 -0
- package/package.json +2 -2
- package/src/index.d.ts +26 -0
- package/src/index.js +4 -3
- package/src/migrations.js +103 -0
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -84,6 +84,30 @@ const app = createSaasApp({
|
|
|
84
84
|
Les méthodes retournent toujours des objets JavaScript simples (jamais une
|
|
85
85
|
ligne `pg` brute) : `{ ...donnéesJSONB, id }`.
|
|
86
86
|
|
|
87
|
+
## Migrations
|
|
88
|
+
|
|
89
|
+
Pas un DSL, pas de CLI, pas d'introspection de schéma — un runner minimal
|
|
90
|
+
et honnête : tu lui donnes du SQL brut dans l'ordre, il applique une seule
|
|
91
|
+
fois chaque migration non encore vue (suivi par `id` dans une table de
|
|
92
|
+
suivi), chacune dans sa propre transaction, annulée en cas d'échec.
|
|
93
|
+
|
|
94
|
+
```js
|
|
95
|
+
const { createPostgresMigrationRunner } = require('@astratra/store-postgres');
|
|
96
|
+
|
|
97
|
+
const runner = createPostgresMigrationRunner({ pool });
|
|
98
|
+
|
|
99
|
+
await runner.run([
|
|
100
|
+
{ id: '2026-01-01-add-name', up: (client) => client.query('ALTER TABLE app_users ADD COLUMN name TEXT') },
|
|
101
|
+
{ id: '2026-01-15-index-role', up: (client) => client.query('CREATE INDEX IF NOT EXISTS app_users_role_idx ON app_users (role)') }
|
|
102
|
+
]);
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Rejoue `run()` avec la même liste (plus les nouvelles migrations ajoutées
|
|
106
|
+
au fil du temps) à chaque déploiement — les `id` déjà appliqués sont
|
|
107
|
+
ignorés. `appliedIds()` retourne l'historique. Pas de `down()` : ce runner
|
|
108
|
+
ne fait qu'avancer, un rollback de schéma se fait via une nouvelle migration
|
|
109
|
+
qui défait l'ancienne.
|
|
110
|
+
|
|
87
111
|
## Cycle de vie de connexion
|
|
88
112
|
|
|
89
113
|
Chemin recommandé : passer un `pool` déjà géré par l'application. Dans ce
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astratra/store-postgres",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "PostgreSQL persistence adapters for Astratra SaaS stores.",
|
|
5
5
|
"engines": {
|
|
6
|
-
"node": ">=
|
|
6
|
+
"node": ">=22"
|
|
7
7
|
},
|
|
8
8
|
"main": "src/index.js",
|
|
9
9
|
"types": "src/index.d.ts",
|
package/src/index.d.ts
CHANGED
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
export type Awaitable<T> = T | Promise<T>;
|
|
2
2
|
|
|
3
|
+
export interface PgClientLike {
|
|
4
|
+
query(text: string, values?: unknown[]): Promise<{ rows: any[] }>;
|
|
5
|
+
release(): void;
|
|
6
|
+
}
|
|
7
|
+
|
|
3
8
|
export interface PgPoolLike {
|
|
4
9
|
query(text: string, values?: unknown[]): Promise<{ rows: any[] }>;
|
|
10
|
+
connect(): Promise<PgClientLike>;
|
|
5
11
|
end(): Awaitable<void>;
|
|
6
12
|
}
|
|
7
13
|
|
|
@@ -60,3 +66,23 @@ export interface PostgresSettingsStore<TSettings extends object = Record<string,
|
|
|
60
66
|
|
|
61
67
|
export function createPostgresUsersStore<TUser extends PostgresUserBase = PostgresUser>(options: PostgresUsersStoreOptions): PostgresUsersStore<TUser>;
|
|
62
68
|
export function createPostgresSettingsStore<TSettings extends object = Record<string, unknown>>(options: PostgresSettingsStoreOptions): PostgresSettingsStore<TSettings>;
|
|
69
|
+
|
|
70
|
+
export interface PostgresMigration {
|
|
71
|
+
id: string;
|
|
72
|
+
up(client: PgClientLike): Awaitable<unknown>;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface PostgresMigrationRunnerOptions {
|
|
76
|
+
pool: PgPoolLike;
|
|
77
|
+
/** Defaults to "astratra_migrations". */
|
|
78
|
+
migrationsTable?: string;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface PostgresMigrationRunner {
|
|
82
|
+
/** IDs already recorded as applied, oldest first. */
|
|
83
|
+
appliedIds(): Promise<string[]>;
|
|
84
|
+
/** Runs whichever of the given migrations aren't applied yet, in order — each inside its own transaction, rolled back on failure. */
|
|
85
|
+
run(migrations: PostgresMigration[]): Promise<{ applied: string[] }>;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function createPostgresMigrationRunner(options: PostgresMigrationRunnerOptions): PostgresMigrationRunner;
|
package/src/index.js
CHANGED
|
@@ -6,8 +6,8 @@ const DEFAULT_SETTINGS_TABLE = 'astratra_settings';
|
|
|
6
6
|
function loadPg() {
|
|
7
7
|
try {
|
|
8
8
|
return require('pg');
|
|
9
|
-
} catch (
|
|
10
|
-
throw new Error('@astratra/store-postgres requires pg. Install pg or pass it from an app that already depends on it.');
|
|
9
|
+
} catch (error) {
|
|
10
|
+
throw new Error('@astratra/store-postgres requires pg. Install pg or pass it from an app that already depends on it.', { cause: error });
|
|
11
11
|
}
|
|
12
12
|
}
|
|
13
13
|
|
|
@@ -233,5 +233,6 @@ function createPostgresSettingsStore(options = {}) {
|
|
|
233
233
|
|
|
234
234
|
module.exports = {
|
|
235
235
|
createPostgresSettingsStore,
|
|
236
|
-
createPostgresUsersStore
|
|
236
|
+
createPostgresUsersStore,
|
|
237
|
+
...require('./migrations')
|
|
237
238
|
};
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
const DEFAULT_MIGRATIONS_TABLE = 'astratra_migrations';
|
|
2
|
+
|
|
3
|
+
function isValidIdentifier(name) {
|
|
4
|
+
return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name);
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
function assertValidIdentifier(name, label) {
|
|
8
|
+
if (!isValidIdentifier(name)) {
|
|
9
|
+
throw new Error(`@astratra/store-postgres: invalid ${label} "${name}".`);
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function assertMigrationsShape(migrations) {
|
|
14
|
+
if (!Array.isArray(migrations)) {
|
|
15
|
+
throw new Error('createPostgresMigrationRunner.run requires an array of migrations.');
|
|
16
|
+
}
|
|
17
|
+
const seen = new Set();
|
|
18
|
+
for (const migration of migrations) {
|
|
19
|
+
if (!migration || typeof migration.id !== 'string' || !migration.id) {
|
|
20
|
+
throw new Error('Every migration requires a non-empty string id.');
|
|
21
|
+
}
|
|
22
|
+
if (typeof migration.up !== 'function') {
|
|
23
|
+
throw new Error(`Migration "${migration.id}" requires an up(client) function.`);
|
|
24
|
+
}
|
|
25
|
+
if (seen.has(migration.id)) {
|
|
26
|
+
throw new Error(`Duplicate migration id "${migration.id}".`);
|
|
27
|
+
}
|
|
28
|
+
seen.add(migration.id);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* A minimal, honest migration runner — not a DSL, not a CLI, not schema
|
|
34
|
+
* introspection. It runs your plain SQL (or query calls) in order, once
|
|
35
|
+
* each, tracked by id in a ledger table. That is the whole feature: given
|
|
36
|
+
* an array of { id, up(client) }, apply whichever ids aren't in the ledger
|
|
37
|
+
* yet, each inside its own transaction, recording success before moving on.
|
|
38
|
+
*
|
|
39
|
+
* const runner = createPostgresMigrationRunner({ pool });
|
|
40
|
+
* await runner.run([
|
|
41
|
+
* { id: '2026-01-01-add-users-name', up: (client) => client.query('ALTER TABLE astratra_users ADD COLUMN name TEXT') }
|
|
42
|
+
* ]);
|
|
43
|
+
*/
|
|
44
|
+
function createPostgresMigrationRunner(options = {}) {
|
|
45
|
+
const { pool } = options;
|
|
46
|
+
if (!pool) {
|
|
47
|
+
throw new Error('createPostgresMigrationRunner requires options.pool.');
|
|
48
|
+
}
|
|
49
|
+
const table = options.migrationsTable || DEFAULT_MIGRATIONS_TABLE;
|
|
50
|
+
assertValidIdentifier(table, 'migrationsTable');
|
|
51
|
+
|
|
52
|
+
// Memoized (like the CRUD stores' own `ready` promise) so the DDL runs
|
|
53
|
+
// exactly once per runner instance — running "CREATE TABLE IF NOT
|
|
54
|
+
// EXISTS" redundantly is harmless against a real Postgres, but appliedIds()
|
|
55
|
+
// and run() both need the table to exist, and re-issuing the same DDL
|
|
56
|
+
// needlessly on every call is wasteful regardless of the target database.
|
|
57
|
+
const ledgerReady = pool.query(`
|
|
58
|
+
CREATE TABLE IF NOT EXISTS ${table} (
|
|
59
|
+
id TEXT PRIMARY KEY,
|
|
60
|
+
applied_at TEXT
|
|
61
|
+
)
|
|
62
|
+
`);
|
|
63
|
+
|
|
64
|
+
return {
|
|
65
|
+
async appliedIds() {
|
|
66
|
+
await ledgerReady;
|
|
67
|
+
const result = await pool.query(`SELECT id FROM ${table} ORDER BY applied_at ASC`);
|
|
68
|
+
return result.rows.map((row) => row.id);
|
|
69
|
+
},
|
|
70
|
+
|
|
71
|
+
async run(migrations) {
|
|
72
|
+
assertMigrationsShape(migrations);
|
|
73
|
+
await ledgerReady;
|
|
74
|
+
|
|
75
|
+
const alreadyApplied = new Set(await this.appliedIds());
|
|
76
|
+
const applied = [];
|
|
77
|
+
|
|
78
|
+
for (const migration of migrations) {
|
|
79
|
+
if (alreadyApplied.has(migration.id)) continue;
|
|
80
|
+
|
|
81
|
+
const client = await pool.connect();
|
|
82
|
+
try {
|
|
83
|
+
await client.query('BEGIN');
|
|
84
|
+
await migration.up(client);
|
|
85
|
+
await client.query(`INSERT INTO ${table} (id, applied_at) VALUES ($1, $2)`, [migration.id, new Date().toISOString()]);
|
|
86
|
+
await client.query('COMMIT');
|
|
87
|
+
applied.push(migration.id);
|
|
88
|
+
} catch (error) {
|
|
89
|
+
await client.query('ROLLBACK');
|
|
90
|
+
throw new Error(`Migration "${migration.id}" failed and was rolled back: ${error.message}`, { cause: error });
|
|
91
|
+
} finally {
|
|
92
|
+
client.release();
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return { applied };
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
module.exports = {
|
|
102
|
+
createPostgresMigrationRunner
|
|
103
|
+
};
|