poad 2.75.2 → 2.76.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/global/start.js +1 -1
- package/package.json +1 -1
- package/project/cli.js +2 -0
- package/project/deploy.js +85 -26
- package/project/migrate.js +7 -3
- package/project/pull.js +4 -0
- package/project/push.js +4 -0
- package/test/cloud.test.js +55 -2
- package/test/data-loss.test.js +112 -0
- package/test/project-sync.test.js +297 -0
- package/utils/banner.js +2 -0
- package/utils/cloud/db.js +6 -7
- package/utils/data-loss.js +600 -0
- package/utils/help-details.js +61 -7
- package/utils/migrate-run.js +32 -1
- package/utils/migrations.js +29 -3
- package/utils/project-sync/code.js +122 -0
- package/utils/project-sync/pg.js +130 -0
- package/utils/project-sync/plan.js +436 -0
- package/utils/project-sync/run.js +769 -0
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
// poad push / poad pull : tout ce qui se décide sans réseau ni base (testé seul).
|
|
2
|
+
//
|
|
3
|
+
// parts --only / --skip / --tables → parties et tables visées
|
|
4
|
+
// inventaire requête SQL qui décrit une base (tables du projet, colonnes, clés, séquences, migrations,
|
|
5
|
+
// comptes, noms des variables et credentials) en un JSON : jamais une valeur
|
|
6
|
+
// structure tables de la source face à la cible : copiables, absentes, différentes
|
|
7
|
+
// différence empreintes « md5(clé) md5(ligne) » des deux côtés → ajoutées, remplacées, supprimées, identiques
|
|
8
|
+
// transfert script bash lancé dans le conteneur de l'engine local : psql source | psql cible, une transaction
|
|
9
|
+
// secrets requête qui, lue à la source, écrit les instructions à rejouer dans la cible (valeurs dans le flux seulement)
|
|
10
|
+
'use strict';
|
|
11
|
+
|
|
12
|
+
const PARTS = ['code', 'base', 'auth', 's3', 'refs'];
|
|
13
|
+
/** Ordre d'exécution : la structure (code) d'abord, puis les données, références, fichiers, secrets */
|
|
14
|
+
const ORDER = ['code', 'base', 'auth', 'refs', 's3', 'secrets'];
|
|
15
|
+
const ALIASES = { db: 'base', data: 'base', database: 'base', storage: 's3', files: 's3', references: 'refs', ref: 'refs', reference: 'refs', migrations: 'code', accounts: 'auth', users: 'auth' };
|
|
16
|
+
|
|
17
|
+
// Schémas de l'engine : jamais copiés (même liste que branch-copy-from-prod de poad.io, plus poad_api)
|
|
18
|
+
const SYSTEM_SCHEMAS = ['information_schema', 'auth', 'storage', 'extensions', 'graphql', 'graphql_public', 'realtime', '_realtime', 'vault', 'pgsodium', 'pgsodium_masks', 'net', 'cron', 'supabase_functions', 'supabase_migrations', 'pgbouncer', '_logs', 'logs', '_poad', 'poad', 'poad_api', 'poad_migrations', 'poad_options', 'queries', '_analytics', 'topology', 'tiger', 'tiger_data', 'ai', 'mcp', 'flows', 'functions', 'history'];
|
|
19
|
+
|
|
20
|
+
// Comptes : tables reprises telles quelles (dans cet ordre), colonnes de jetons vidées sur la cible et hors de l'empreinte
|
|
21
|
+
const AUTH_TABLES = ['users', 'identities', 'mfa_factors'];
|
|
22
|
+
const AUTH_CLOSED = ['mfa_amr_claims', 'mfa_challenges', 'refresh_tokens', 'sessions', 'flow_state'];
|
|
23
|
+
const AUTH_TOKENS = ['confirmation_token', 'recovery_token', 'email_change_token', 'email_change_token_new', 'email_change_token_current', 'reauthentication_token', 'phone_change_token'];
|
|
24
|
+
|
|
25
|
+
/** Au-delà (lignes estimées ou octets), une table n'est pas comparée ligne à ligne : comptes seuls */
|
|
26
|
+
const DIFF_MAX_ROWS = 200000;
|
|
27
|
+
const DIFF_MAX_BYTES = 256 * 1024 * 1024;
|
|
28
|
+
|
|
29
|
+
class PlanError extends Error {}
|
|
30
|
+
|
|
31
|
+
const ident = (s) => `"${String(s).replace(/"/g, '""')}"`;
|
|
32
|
+
const lit = (s) => `'${String(s).replace(/'/g, "''")}'`;
|
|
33
|
+
const qname = (schema, name) => `${ident(schema)}.${ident(name)}`;
|
|
34
|
+
/** Une chaîne entre apostrophes pour bash */
|
|
35
|
+
const shq = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
36
|
+
|
|
37
|
+
/** --only, --skip, --tables, --with-secrets → { parts: [...], tables: [...] | null, secrets } */
|
|
38
|
+
function parseParts({ only, skip, tables, withSecrets } = {}) {
|
|
39
|
+
const list = (v, opt) =>
|
|
40
|
+
String(v)
|
|
41
|
+
.split(',')
|
|
42
|
+
.map((x) => x.trim().toLowerCase())
|
|
43
|
+
.filter(Boolean)
|
|
44
|
+
.map((x) => {
|
|
45
|
+
const p = ALIASES[x] || x;
|
|
46
|
+
if (p === 'secrets') throw new PlanError(`${opt} secrets: secrets are copied only with --with-secrets`);
|
|
47
|
+
if (!PARTS.includes(p)) throw new PlanError(`${opt} ${x}: unknown part (code, base, auth, s3, refs)`);
|
|
48
|
+
return p;
|
|
49
|
+
});
|
|
50
|
+
if (only !== undefined && skip !== undefined) throw new PlanError('--only and --skip: choose one');
|
|
51
|
+
let parts = PARTS.slice();
|
|
52
|
+
if (only !== undefined) {
|
|
53
|
+
const o = list(only, '--only');
|
|
54
|
+
if (!o.length) throw new PlanError('--only needs at least one part (code, base, auth, s3, refs)');
|
|
55
|
+
parts = PARTS.filter((p) => o.includes(p));
|
|
56
|
+
}
|
|
57
|
+
if (skip !== undefined) {
|
|
58
|
+
const s = list(skip, '--skip');
|
|
59
|
+
parts = parts.filter((p) => !s.includes(p));
|
|
60
|
+
}
|
|
61
|
+
let tl = null;
|
|
62
|
+
if (tables !== undefined) {
|
|
63
|
+
tl = [];
|
|
64
|
+
for (const t of String(tables).split(',').map((x) => x.trim()).filter(Boolean)) {
|
|
65
|
+
const m = /^(?:([A-Za-z_][A-Za-z0-9_$]{0,62})\.)?([A-Za-z_][A-Za-z0-9_$]{0,62})$/.exec(t);
|
|
66
|
+
if (!m) throw new PlanError(`--tables ${t}: expected table or schema.table`);
|
|
67
|
+
tl.push(`${m[1] || 'public'}.${m[2]}`);
|
|
68
|
+
}
|
|
69
|
+
if (!tl.length) throw new PlanError('--tables needs at least one table');
|
|
70
|
+
if (!parts.includes('base')) throw new PlanError('--tables chooses tables of the base part, which is left out here');
|
|
71
|
+
}
|
|
72
|
+
if (withSecrets) parts.push('secrets');
|
|
73
|
+
if (!parts.length) throw new PlanError('No part left to copy.');
|
|
74
|
+
return { parts: ORDER.filter((p) => parts.includes(p)), tables: tl };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Requête : quels objets facultatifs existent (avant l'inventaire) */
|
|
78
|
+
const PROBE_SQL = `select json_build_object(
|
|
79
|
+
'history', to_regclass('poad_migrations.history') is not null,
|
|
80
|
+
'variables', to_regclass('_poad.variables') is not null,
|
|
81
|
+
'credentials', to_regclass('_poad.credentials') is not null and to_regclass('_poad.credential_uses') is not null,
|
|
82
|
+
'vault', to_regclass('vault.decrypted_secrets') is not null,
|
|
83
|
+
'auth', (select coalesce(json_agg(c.relname order by c.relname), '[]') from pg_class c join pg_namespace n on n.oid = c.relnamespace where n.nspname = 'auth' and c.relkind = 'r')
|
|
84
|
+
)`;
|
|
85
|
+
|
|
86
|
+
const userSchemasWhere = (alias = 'n') => `${alias}.nspname !~ '^(pg_|_timescaledb|timescaledb_)' and ${alias}.nspname not in (${SYSTEM_SCHEMAS.map(lit).join(', ')})`;
|
|
87
|
+
|
|
88
|
+
const columnsJson = (rel) =>
|
|
89
|
+
`(select coalesce(json_agg(json_build_object('name', a.attname, 'type', format_type(a.atttypid, a.atttypmod), 'generated', a.attgenerated <> '', 'notnull', a.attnotnull, 'default', a.atthasdef or a.attidentity <> '') order by a.attnum), '[]') from pg_attribute a where a.attrelid = ${rel} and a.attnum > 0 and not a.attisdropped)`;
|
|
90
|
+
|
|
91
|
+
/** Inventaire d'une base, en un JSON (aucune valeur de ligne, aucun secret : des noms, des tailles, des comptes) */
|
|
92
|
+
function inventorySql(probe = {}) {
|
|
93
|
+
const auth = (probe.auth || []).filter((t) => AUTH_TABLES.includes(t) || AUTH_CLOSED.includes(t));
|
|
94
|
+
return `select json_build_object(
|
|
95
|
+
'tables', (select coalesce(json_agg(json_build_object(
|
|
96
|
+
'schema', n.nspname, 'name', c.relname,
|
|
97
|
+
'columns', ${columnsJson('c.oid')},
|
|
98
|
+
'pk', (select json_agg(a.attname order by array_position(i.indkey::int2[], a.attnum)) from pg_index i join pg_attribute a on a.attrelid = i.indrelid and a.attnum = any(i.indkey) where i.indrelid = c.oid and i.indisprimary),
|
|
99
|
+
'estimate', greatest(c.reltuples, 0)::bigint,
|
|
100
|
+
'bytes', pg_total_relation_size(c.oid),
|
|
101
|
+
'refs', (select coalesce(json_agg(distinct rn.nspname || '.' || rc.relname), '[]') from pg_constraint k join pg_class rc on rc.oid = k.confrelid join pg_namespace rn on rn.oid = rc.relnamespace where k.conrelid = c.oid and k.contype = 'f')
|
|
102
|
+
) order by n.nspname, c.relname), '[]')
|
|
103
|
+
from pg_class c join pg_namespace n on n.oid = c.relnamespace
|
|
104
|
+
where c.relkind = 'r' and ${userSchemasWhere('n')}
|
|
105
|
+
and not exists (select 1 from pg_depend d where d.classid = 'pg_class'::regclass and d.objid = c.oid and d.deptype = 'e')),
|
|
106
|
+
'sequences', (select coalesce(json_agg(json_build_object('schema', s.schemaname, 'name', s.sequencename, 'last', s.last_value,
|
|
107
|
+
'owner', (select tn.nspname || '.' || tc.relname from pg_depend d join pg_class tc on tc.oid = d.refobjid join pg_namespace tn on tn.oid = tc.relnamespace
|
|
108
|
+
where d.classid = 'pg_class'::regclass and d.objid = (quote_ident(s.schemaname) || '.' || quote_ident(s.sequencename))::regclass and d.refclassid = 'pg_class'::regclass and d.deptype in ('a', 'i') limit 1)
|
|
109
|
+
) order by s.schemaname, s.sequencename), '[]') from pg_sequences s join pg_namespace n on n.nspname = s.schemaname where ${userSchemasWhere('n')}),
|
|
110
|
+
'migrations', ${probe.history ? `(select coalesce(json_agg(version order by version), '[]') from poad_migrations.history)` : `'[]'::json`},
|
|
111
|
+
'auth', json_build_object(${auth.length ? auth.map((t) => `${lit(t)}, json_build_object('rows', (select count(*) from auth.${ident(t)}), 'bytes', pg_total_relation_size('auth.${ident(t)}'), 'columns', ${columnsJson(`'auth.${ident(t)}'::regclass`)}, 'pk', (select json_agg(a.attname order by array_position(i.indkey::int2[], a.attnum)) from pg_index i join pg_attribute a on a.attrelid = i.indrelid and a.attnum = any(i.indkey) where i.indrelid = 'auth.${ident(t)}'::regclass and i.indisprimary))`).join(', ') : ''}),
|
|
112
|
+
'variables', ${probe.variables ? `(select coalesce(json_agg(name || case when app = '' then '' else '@' || app end order by name, app), '[]') from _poad.variables where value is not null)` : `'[]'::json`},
|
|
113
|
+
'credentials', ${probe.credentials ? `(select coalesce(json_agg(c.name order by c.name), '[]') from _poad.credentials c where not exists (select 1 from _poad.credential_uses u where u.credential = c.name and u.slot like 'storage.%'))` : `'[]'::json`},
|
|
114
|
+
'storage_credentials', ${probe.credentials ? `(select coalesce(json_agg(distinct u.credential), '[]') from _poad.credential_uses u where u.slot like 'storage.%')` : `'[]'::json`}
|
|
115
|
+
)`;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const keyOf = (t) => `${t.schema}.${t.name}`;
|
|
119
|
+
|
|
120
|
+
/** Types comparables : sans les modificateurs qui ne changent pas la copie (varchar(255) ≈ varchar(300)) */
|
|
121
|
+
const sameType = (a, b) => a === b;
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Tables de la source face à la cible.
|
|
125
|
+
* exclude : tables gérées ailleurs (magasin de références) ; only : --tables
|
|
126
|
+
* Rend { tables: [{ key, schema, name, columns, pk, bytes, estimate, refs, target: { bytes, estimate } }],
|
|
127
|
+
* blocked: [{ key, reason }], excluded: [{ key, reason }], unknown: [--tables absentes de la source],
|
|
128
|
+
* extra: [tables de la cible absentes de la source (gardées telles quelles)] }
|
|
129
|
+
*/
|
|
130
|
+
function compareTables(src = [], dst = [], { exclude = [], only = null } = {}) {
|
|
131
|
+
const byKey = new Map(dst.map((t) => [keyOf(t), t]));
|
|
132
|
+
const out = { tables: [], blocked: [], excluded: [], unknown: [], extra: [] };
|
|
133
|
+
const srcKeys = new Set(src.map(keyOf));
|
|
134
|
+
if (only) out.unknown = only.filter((k) => !srcKeys.has(k));
|
|
135
|
+
for (const t of src) {
|
|
136
|
+
const key = keyOf(t);
|
|
137
|
+
if (only && !only.includes(key)) continue;
|
|
138
|
+
if (exclude.includes(key)) {
|
|
139
|
+
out.excluded.push({ key, reason: 'reference' });
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
const d = byKey.get(key);
|
|
143
|
+
if (!d) {
|
|
144
|
+
out.blocked.push({ key, reason: 'missing', detail: 'table missing on the target' });
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
const cols = (t.columns || []).filter((c) => !c.generated);
|
|
148
|
+
const dcols = new Map((d.columns || []).map((c) => [c.name, c]));
|
|
149
|
+
const problems = [];
|
|
150
|
+
for (const c of cols) {
|
|
151
|
+
const x = dcols.get(c.name);
|
|
152
|
+
if (!x) problems.push(`column ${c.name} missing on the target`);
|
|
153
|
+
else if (x.generated) problems.push(`column ${c.name} is generated on the target`);
|
|
154
|
+
else if (!sameType(c.type, x.type)) problems.push(`column ${c.name}: ${c.type} here, ${x.type} on the target`);
|
|
155
|
+
}
|
|
156
|
+
const names = new Set(cols.map((c) => c.name));
|
|
157
|
+
for (const x of d.columns || []) if (!names.has(x.name) && !x.generated && x.notnull && !x.default) problems.push(`column ${x.name} (not null, no default) only on the target`);
|
|
158
|
+
if (problems.length) {
|
|
159
|
+
out.blocked.push({ key, reason: 'differs', detail: problems.join('; ') });
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
out.tables.push({ key, schema: t.schema, name: t.name, columns: cols.map((c) => c.name), pk: Array.isArray(t.pk) && t.pk.length ? t.pk : null, bytes: Number(t.bytes) || 0, estimate: Number(t.estimate) || 0, refs: t.refs || [], target: { bytes: Number(d.bytes) || 0, estimate: Number(d.estimate) || 0 } });
|
|
163
|
+
}
|
|
164
|
+
if (!only) for (const d of dst) if (!srcKeys.has(keyOf(d)) && !exclude.includes(keyOf(d))) out.extra.push(keyOf(d));
|
|
165
|
+
return out;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Migrations : celles de la source absentes de la cible (et l'inverse) */
|
|
169
|
+
function compareMigrations(src = [], dst = []) {
|
|
170
|
+
const d = new Set(dst);
|
|
171
|
+
const s = new Set(src);
|
|
172
|
+
return { missing: src.filter((v) => !d.has(v)), extra: dst.filter((v) => !s.has(v)) };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** La table est-elle comparée ligne à ligne ? */
|
|
176
|
+
const diffable = (t) => (t.estimate <= DIFF_MAX_ROWS && t.bytes <= DIFF_MAX_BYTES) || t.bytes <= 8 * 1024 * 1024;
|
|
177
|
+
|
|
178
|
+
/** Requête des empreintes d'une table : une ligne « md5(clé) md5(ligne) » (sans clé : md5(ligne) seul) */
|
|
179
|
+
function hashSql(t, { blank = [] } = {}) {
|
|
180
|
+
const cols = t.columns.map((c) => (blank.includes(c) ? `null::text` : ident(c)));
|
|
181
|
+
const row = `md5(row(${cols.join(', ')})::text)`;
|
|
182
|
+
const q = qname(t.schema, t.name);
|
|
183
|
+
return t.pk ? `select md5(row(${t.pk.map(ident).join(', ')})::text) || ' ' || ${row} from ${q}` : `select ${row} from ${q}`;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const countSql = (t) => `select count(*) from ${qname(t.schema, t.name)}`;
|
|
187
|
+
|
|
188
|
+
/** Différence de deux listes d'empreintes (texte de psql -tA) → { added, replaced, deleted, unchanged, rows, target_rows } */
|
|
189
|
+
function diffHashes(srcText, dstText, hasPk) {
|
|
190
|
+
const lines = (s) => String(s || '').split('\n').filter(Boolean);
|
|
191
|
+
const a = lines(srcText);
|
|
192
|
+
const b = lines(dstText);
|
|
193
|
+
if (hasPk) {
|
|
194
|
+
const m = new Map();
|
|
195
|
+
for (const l of b) {
|
|
196
|
+
const i = l.indexOf(' ');
|
|
197
|
+
m.set(l.slice(0, i), l.slice(i + 1));
|
|
198
|
+
}
|
|
199
|
+
let added = 0;
|
|
200
|
+
let replaced = 0;
|
|
201
|
+
let unchanged = 0;
|
|
202
|
+
for (const l of a) {
|
|
203
|
+
const i = l.indexOf(' ');
|
|
204
|
+
const k = l.slice(0, i);
|
|
205
|
+
if (!m.has(k)) added++;
|
|
206
|
+
else {
|
|
207
|
+
if (m.get(k) === l.slice(i + 1)) unchanged++;
|
|
208
|
+
else replaced++;
|
|
209
|
+
m.delete(k);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return { added, replaced, deleted: m.size, unchanged, rows: a.length, target_rows: b.length, exact: true };
|
|
213
|
+
}
|
|
214
|
+
// Sans clé primaire : multiensembles d'empreintes
|
|
215
|
+
const m = new Map();
|
|
216
|
+
for (const h of b) m.set(h, (m.get(h) || 0) + 1);
|
|
217
|
+
let added = 0;
|
|
218
|
+
let unchanged = 0;
|
|
219
|
+
for (const h of a) {
|
|
220
|
+
const n = m.get(h) || 0;
|
|
221
|
+
if (n > 0) {
|
|
222
|
+
unchanged++;
|
|
223
|
+
m.set(h, n - 1);
|
|
224
|
+
} else added++;
|
|
225
|
+
}
|
|
226
|
+
let deleted = 0;
|
|
227
|
+
for (const n of m.values()) deleted += n;
|
|
228
|
+
return { added, replaced: 0, deleted, unchanged, rows: a.length, target_rows: b.length, exact: true };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Une table à réécrire ? (comptes seuls : toujours, sauf deux tables vides) */
|
|
232
|
+
const changed = (d) => (d.exact ? d.added + d.replaced + d.deleted > 0 : d.rows + d.target_rows > 0);
|
|
233
|
+
|
|
234
|
+
/** Réserve du journal de la base pendant un chargement (comme le magasin de références de poad.io) */
|
|
235
|
+
const walReserve = (limit) => Math.max(64 * 1024 ** 2, Math.floor((Number(limit) || 0) / 4 / 1024 ** 2) * 1024 ** 2);
|
|
236
|
+
|
|
237
|
+
/** La copie tient-elle : octets de la source + 10 %, et la réserve du journal, dans la place libre ? */
|
|
238
|
+
function fits(need, space) {
|
|
239
|
+
if (!space || !Number.isFinite(space.limit) || !Number.isFinite(space.used)) return { known: false, ok: true };
|
|
240
|
+
const reserve = space.reserve !== undefined ? space.reserve : walReserve(space.limit);
|
|
241
|
+
const free = space.limit - space.used;
|
|
242
|
+
const required = Math.ceil(need * 1.1 + reserve);
|
|
243
|
+
return { known: true, ok: required <= free, required, free, reserve, limit: space.limit };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Script bash du transfert des données (base et comptes), lancé dans le conteneur de l'engine local.
|
|
248
|
+
* srcFn / dstFn commandes psql vers la source / la cible
|
|
249
|
+
* tables [{ schema, name, columns }] dans l'ordre de chargement
|
|
250
|
+
* clear instructions de remise à zéro de la cible (avant les COPY), dans la transaction
|
|
251
|
+
* after instructions après les COPY (jetons vidés…)
|
|
252
|
+
* sequences requête lue à la source qui écrit les setval à rejouer
|
|
253
|
+
* La source est lue en UNE session, dans une transaction en lecture seule « repeatable read » : un instantané
|
|
254
|
+
* cohérent de toutes les tables, même si la source change pendant la copie. Elle écrit elle-même le flux de la
|
|
255
|
+
* cible (« COPY … FROM stdin; », les lignes, « \. ») ; la cible l'exécute en une transaction (ON_ERROR_STOP).
|
|
256
|
+
* Repères sur la sortie d'erreur : « @@poad start <i> <ms> », « @@poad done <ms> <code> ».
|
|
257
|
+
*/
|
|
258
|
+
function transferScript({ srcFn, dstFn, tables = [], clear = [], after = [], sequences = null, replica = true }) {
|
|
259
|
+
const lines = ['set -o pipefail', `srcs() { ${srcFn} "$@"; }`, `dst() { ${dstFn} "$@"; }`, 'ms() { date +%s%3N; }', '{'];
|
|
260
|
+
const emit = (sql) => lines.push(` printf '%s\\n' ${shq(sql)}`);
|
|
261
|
+
// \echo de psql : apostrophes doublées, barres obliques inverses doublées
|
|
262
|
+
const echo = (text) => `\\echo '${String(text).replace(/\\/g, '\\\\').replace(/'/g, "''")}'`;
|
|
263
|
+
emit('begin;');
|
|
264
|
+
emit("set local lock_timeout = '30s';");
|
|
265
|
+
emit('set local statement_timeout = 0;');
|
|
266
|
+
if (replica) emit('set local session_replication_role = replica;');
|
|
267
|
+
for (const s of clear) emit(s);
|
|
268
|
+
const src = ['begin isolation level repeatable read read only;'];
|
|
269
|
+
tables.forEach((t, i) => {
|
|
270
|
+
const cols = t.columns.map(ident).join(', ');
|
|
271
|
+
const q = qname(t.schema, t.name);
|
|
272
|
+
src.push(`\\! echo "@@poad start ${i} $(date +%s%3N)" >&2`);
|
|
273
|
+
src.push(echo(`COPY ${q} (${cols}) FROM stdin;`));
|
|
274
|
+
src.push(`COPY (select ${cols} from ${q}) TO STDOUT;`);
|
|
275
|
+
src.push(echo('\\.'));
|
|
276
|
+
});
|
|
277
|
+
if (sequences) src.push(`${sequences};`);
|
|
278
|
+
src.push('commit;');
|
|
279
|
+
lines.push(' srcs -v ON_ERROR_STOP=1 -tA -f - <<\'POAD_SRC_EOF\' || exit 3', ...src, 'POAD_SRC_EOF');
|
|
280
|
+
for (const s of after) emit(s);
|
|
281
|
+
emit('commit;');
|
|
282
|
+
// Statistiques à jour pour le planificateur (hors transaction ; un échec ici ne défait rien)
|
|
283
|
+
if (tables.length) emit('\\set ON_ERROR_STOP 0');
|
|
284
|
+
if (tables.length) emit(`analyze ${tables.map((t) => qname(t.schema, t.name)).join(', ')};`);
|
|
285
|
+
lines.push('} | dst -v ON_ERROR_STOP=1 > /dev/null', 'rc=$?', 'echo "@@poad done $(ms) $rc" >&2', 'exit $rc');
|
|
286
|
+
return lines.join('\n') + '\n';
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Requête lue à la source : les setval des séquences à rejouer sur la cible */
|
|
290
|
+
function sequencesSql(seqs = []) {
|
|
291
|
+
if (!seqs.length) return null;
|
|
292
|
+
return `select format('select setval(%L, %s, %s);', quote_ident(schemaname) || '.' || quote_ident(sequencename), coalesce(last_value, start_value), case when last_value is null then 'false' else 'true' end) from pg_sequences where (schemaname, sequencename) in (${seqs.map((s) => `(${lit(s.schema)}, ${lit(s.name)})`).join(', ')})`;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Séquences à recaler : celles des tables copiées ; toutes celles du projet quand toute la base est copiée */
|
|
296
|
+
function sequencesFor(srcSeqs = [], dstSeqs = [], copied = [], { all = false } = {}) {
|
|
297
|
+
const there = new Map(dstSeqs.map((s) => [`${s.schema}.${s.name}`, s]));
|
|
298
|
+
const keys = new Set(copied);
|
|
299
|
+
// Déjà à la même valeur sur la cible : rien à recaler
|
|
300
|
+
return srcSeqs.filter((s) => {
|
|
301
|
+
const d = there.get(`${s.schema}.${s.name}`);
|
|
302
|
+
return d && (s.owner ? keys.has(s.owner) : all) && String(d.last ?? '') !== String(s.last ?? '');
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Comptes : tables de auth reprises (colonnes communes aux deux côtés), colonnes perdues (seulement à la
|
|
308
|
+
* source), et instructions de remise à zéro de la cible.
|
|
309
|
+
*/
|
|
310
|
+
function authPlan(src = {}, dst = {}) {
|
|
311
|
+
const tables = [];
|
|
312
|
+
const dropped = [];
|
|
313
|
+
for (const name of AUTH_TABLES) {
|
|
314
|
+
const s = src[name];
|
|
315
|
+
const d = dst[name];
|
|
316
|
+
if (!s || !d) continue;
|
|
317
|
+
const there = new Map((d.columns || []).map((c) => [c.name, c]));
|
|
318
|
+
const cols = (s.columns || []).filter((c) => !c.generated && there.has(c.name) && !there.get(c.name).generated).map((c) => c.name);
|
|
319
|
+
for (const c of s.columns || []) if (!there.has(c.name)) dropped.push(`auth.${name}.${c.name}`);
|
|
320
|
+
tables.push({ schema: 'auth', name, key: `auth.${name}`, columns: cols, pk: Array.isArray(s.pk) && s.pk.length ? s.pk : null, rows: Number(s.rows) || 0, bytes: Number(s.bytes) || 0, target: { rows: Number(d.rows) || 0, bytes: Number(d.bytes) || 0 }, blank: AUTH_TOKENS.filter((c) => cols.includes(c)) });
|
|
321
|
+
}
|
|
322
|
+
// Remise à zéro : ce qui dépend des comptes d'abord (sessions, jetons, facteurs), puis les comptes
|
|
323
|
+
const clear = [...AUTH_CLOSED.filter((t) => dst[t]), ...tables.map((t) => t.name).reverse()].map((t) => `delete from auth.${ident(t)};`);
|
|
324
|
+
const after = tables
|
|
325
|
+
.filter((t) => t.blank.length)
|
|
326
|
+
.map((t) => `update auth.${ident(t.name)} set ${t.blank.map((c) => `${ident(c)} = ''`).join(', ')} where ${t.blank.map((c) => `${ident(c)} <> ''`).join(' or ')};`);
|
|
327
|
+
return { tables, dropped, clear, after, closed: AUTH_CLOSED.filter((t) => dst[t]) };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* Secrets : requête lue à la source qui écrit les instructions à rejouer dans la cible, en une transaction.
|
|
332
|
+
* Variables : la valeur propre de l'engine (value) ; les défauts viennent du code. Credentials : tous sauf ceux du
|
|
333
|
+
* Stockage (chaque environnement garde le sien), champs, usages et valeurs du coffre. Rien de la cible n'est lu.
|
|
334
|
+
* La sortie porte des valeurs : elle ne va que dans le tube vers la cible, jamais à l'écran ni au journal.
|
|
335
|
+
*/
|
|
336
|
+
function secretsSql(probe = {}, { targetStorage = [] } = {}) {
|
|
337
|
+
const q = ["select 'begin;'"];
|
|
338
|
+
if (probe.variables) {
|
|
339
|
+
q.push("select 'update _poad.variables set value = null where value is not null;'");
|
|
340
|
+
q.push("select format('insert into _poad.variables (name, app, value, fallback, description) values (%L, %L, %L, %L, %L) on conflict (name, app) do update set value = excluded.value;', name, app, value, fallback, description) from _poad.variables where value is not null");
|
|
341
|
+
}
|
|
342
|
+
if (probe.credentials && probe.vault) {
|
|
343
|
+
const keep = `array[${targetStorage.map(lit).join(', ')}]::text[]`;
|
|
344
|
+
const srcStorage = "(select coalesce(array_agg(distinct credential), '{}') from _poad.credential_uses where slot like 'storage.%')::text[]";
|
|
345
|
+
// Sur la cible : ses credentials du Stockage restent ; le reste est remplacé par ceux de la source
|
|
346
|
+
q.push(`select format('delete from _poad.credential_uses where slot not like %L; delete from vault.secrets where name like %L and not (split_part(name, %L, 2) = any(%L::text[])); delete from _poad.credentials where not (name = any(%L::text[]));', 'storage.%', 'credential.%', '.', ${keep}, ${keep})`);
|
|
347
|
+
q.push(`select format('insert into _poad.credentials (name, type, label, params, secrets) values (%L, %L, %L, %L::jsonb, %L::text[]) on conflict (name) do nothing;', name, type, label, params, secrets) from _poad.credentials where not (name = any(${srcStorage})) and not (name = any(${keep}))`);
|
|
348
|
+
q.push(`select format('select vault.create_secret(%L, %L, %L);', decrypted_secret, name, coalesce(description, '')) from vault.decrypted_secrets where name like 'credential.%' and not (split_part(name, '.', 2) = any(${srcStorage})) and not (split_part(name, '.', 2) = any(${keep}))`);
|
|
349
|
+
q.push(`select format('insert into _poad.credential_uses (slot, credential) values (%L, %L) on conflict (slot) do nothing;', slot, credential) from _poad.credential_uses where slot not like 'storage.%' and not (credential = any(${keep})) and not (credential = any(${srcStorage}))`);
|
|
350
|
+
}
|
|
351
|
+
q.push("select 'commit;'");
|
|
352
|
+
return q;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** Script bash des secrets : la sortie de la source va dans la cible ; aucune sortie, aucune erreur gardée */
|
|
356
|
+
function secretsScript({ srcFn, dstFn, queries }) {
|
|
357
|
+
return [
|
|
358
|
+
'set -o pipefail',
|
|
359
|
+
`src() { ${srcFn} "$@" < /dev/null; }`,
|
|
360
|
+
`dst() { ${dstFn} "$@"; }`,
|
|
361
|
+
// Source arrêtée à la première erreur : la cible ne reçoit jamais « commit; » et annule tout
|
|
362
|
+
`src -v ON_ERROR_STOP=1 -tA ${queries.map((x) => `-c ${shq(x)}`).join(' ')} 2> /dev/null | dst -v ON_ERROR_STOP=1 > /dev/null 2>&1`,
|
|
363
|
+
'rc=$?',
|
|
364
|
+
'echo "@@poad done 0 $rc" >&2',
|
|
365
|
+
'exit $rc',
|
|
366
|
+
].join('\n') + '\n';
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** Taille lisible */
|
|
370
|
+
const size = (n) => {
|
|
371
|
+
const v = Number(n) || 0;
|
|
372
|
+
if (v < 1024) return `${v} B`;
|
|
373
|
+
if (v < 1024 ** 2) return `${(v / 1024).toFixed(1)} KB`;
|
|
374
|
+
if (v < 1024 ** 3) return `${(v / 1024 ** 2).toFixed(1)} MB`;
|
|
375
|
+
return `${(v / 1024 ** 3).toFixed(2)} GB`;
|
|
376
|
+
};
|
|
377
|
+
|
|
378
|
+
/** Repères du script (sortie d'erreur) → { tables: { i: { start, bytes } }, done, rc, errors: [lignes] } */
|
|
379
|
+
function parseMarkers(text) {
|
|
380
|
+
const out = { tables: {}, done: null, rc: null, errors: [] };
|
|
381
|
+
for (const l of String(text || '').split('\n')) {
|
|
382
|
+
const m = /^@@poad (start|bytes|done) (\d+) (-?\d+)\s*$/.exec(l.trim());
|
|
383
|
+
if (!m) {
|
|
384
|
+
if (l.trim()) out.errors.push(l.trim());
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
const [, kind, a, b] = m;
|
|
388
|
+
if (kind === 'done') {
|
|
389
|
+
out.done = Number(a);
|
|
390
|
+
out.rc = Number(b);
|
|
391
|
+
} else (out.tables[a] = out.tables[a] || {})[kind] = Number(b);
|
|
392
|
+
}
|
|
393
|
+
return out;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** Erreur de psql montrable : la ligne ERROR seulement (jamais CONTEXT, qui cite des lignes), bornée */
|
|
397
|
+
function errorLine(errors = []) {
|
|
398
|
+
const e = errors.find((l) => /^(psql:.*)?ERROR:/.test(l) || /\bERROR:/.test(l)) || errors.find((l) => /FATAL|could not|failed|refused/i.test(l)) || errors[0] || '';
|
|
399
|
+
return e.replace(/^psql:[^:]*:\d+: /, '').slice(0, 300);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
module.exports = {
|
|
403
|
+
PARTS,
|
|
404
|
+
ORDER,
|
|
405
|
+
SYSTEM_SCHEMAS,
|
|
406
|
+
AUTH_TABLES,
|
|
407
|
+
AUTH_CLOSED,
|
|
408
|
+
AUTH_TOKENS,
|
|
409
|
+
DIFF_MAX_ROWS,
|
|
410
|
+
PlanError,
|
|
411
|
+
ident,
|
|
412
|
+
lit,
|
|
413
|
+
qname,
|
|
414
|
+
shq,
|
|
415
|
+
parseParts,
|
|
416
|
+
PROBE_SQL,
|
|
417
|
+
inventorySql,
|
|
418
|
+
compareTables,
|
|
419
|
+
compareMigrations,
|
|
420
|
+
diffable,
|
|
421
|
+
hashSql,
|
|
422
|
+
countSql,
|
|
423
|
+
diffHashes,
|
|
424
|
+
changed,
|
|
425
|
+
walReserve,
|
|
426
|
+
fits,
|
|
427
|
+
transferScript,
|
|
428
|
+
sequencesSql,
|
|
429
|
+
sequencesFor,
|
|
430
|
+
authPlan,
|
|
431
|
+
secretsSql,
|
|
432
|
+
secretsScript,
|
|
433
|
+
size,
|
|
434
|
+
parseMarkers,
|
|
435
|
+
errorLine,
|
|
436
|
+
};
|