poad 2.75.1 → 2.75.3
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 +15 -1
- package/package.json +1 -1
- package/project/db/reset.js +35 -0
- package/project/deploy.js +85 -26
- package/project/functions.js +4 -47
- package/project/migrate.js +7 -3
- package/test/cloud.test.js +50 -0
- package/test/data-loss.test.js +112 -0
- package/test/db-reset.test.js +20 -0
- package/test/function-types.test.js +51 -0
- package/utils/data-loss.js +600 -0
- package/utils/function-types.js +98 -0
- package/utils/help-details.js +8 -4
- package/utils/migrate-run.js +32 -1
- package/utils/migrations.js +29 -3
|
@@ -0,0 +1,600 @@
|
|
|
1
|
+
// Avertissement « à la Prisma » avant d'appliquer des migrations : quelles instructions des migrations en attente
|
|
2
|
+
// perdent des données (ou cassent les clients de l'API), et combien de lignes elles touchent vraiment sur la base.
|
|
3
|
+
//
|
|
4
|
+
// Même fichier, identique, dans le CLI (cli/utils/data-loss.js : poad migrate, poad start, poad db reset) et dans
|
|
5
|
+
// poad.io (deploy/cloud/control/data-loss.cjs : push.sh, poad deploy). Garder les deux copies identiques.
|
|
6
|
+
//
|
|
7
|
+
// 1. analyze(batch) : lecture des migrations en attente, jamais exécutées. Un lexer ôte commentaires (-- et /* */
|
|
8
|
+
// imbriqués), chaînes ('…', E'…', $tag$…$tag$ : corps des fonctions et blocs DO) et identifiants entre guillemets,
|
|
9
|
+
// découpe en instructions (BEGIN ATOMIC compris), puis repère : DROP TABLE, DROP COLUMN, ALTER COLUMN … TYPE,
|
|
10
|
+
// TRUNCATE, DELETE (sans WHERE, ou filtré), DROP SCHEMA, RENAME TABLE / COLUMN, DROP VIEW / FUNCTION.
|
|
11
|
+
// Renommages suivis dans le lot (la cible est cherchée sous son nom d'avant) ; vue ou fonction recréée dans le
|
|
12
|
+
// lot : rien à dire.
|
|
13
|
+
// 2. checks(findings) : une requête en lecture seule par constat (existence, lignes comptées avec une borne,
|
|
14
|
+
// valeurs non nulles d'une colonne, droits d'anon / authenticated) et sa solution de repli sur les estimations
|
|
15
|
+
// du catalogue (reltuples, pg_stats.null_frac) si le comptage dépasse son délai. Jouées par runChecks (client
|
|
16
|
+
// pg, CLI) ou par script() + parseOutput() (psql dans le pod de l'engine, poad.io).
|
|
17
|
+
// 3. decide(findings, results, { production, accepted }) : silence (cible absente — créée par le lot —, vide,
|
|
18
|
+
// table étrangère, conversion sans perte, vue / fonction hors API ou recréée), avertissement, ou confirmation
|
|
19
|
+
// (production, perte de données) ; message lisible et ligne de journal sans aucune valeur de données.
|
|
20
|
+
'use strict';
|
|
21
|
+
|
|
22
|
+
const CAP = 100000; // lignes comptées au plus par cible ; au-delà, estimation du catalogue
|
|
23
|
+
const MAX_FINDINGS = 60;
|
|
24
|
+
|
|
25
|
+
// ------------------------------------------------------------------ lexer
|
|
26
|
+
const WORD_START = /[A-Za-z_\u0080-]/;
|
|
27
|
+
const WORD = /[A-Za-z0-9_$\u0080-]/;
|
|
28
|
+
|
|
29
|
+
/** Jetons d'un script SQL : { k: 'w' (mot, v en minuscules) | 'id' (identifiant entre guillemets) | 's' (chaîne) | 'n' | 'p' (ponctuation), v, s, e } */
|
|
30
|
+
function tokenize(sql) {
|
|
31
|
+
const out = [];
|
|
32
|
+
const n = sql.length;
|
|
33
|
+
let i = 0;
|
|
34
|
+
while (i < n) {
|
|
35
|
+
const c = sql[i];
|
|
36
|
+
const d = sql[i + 1];
|
|
37
|
+
if (c === ' ' || c === '\t' || c === '\n' || c === '\r' || c === '\f') {
|
|
38
|
+
i++;
|
|
39
|
+
} else if (c === '-' && d === '-') {
|
|
40
|
+
const e = sql.indexOf('\n', i);
|
|
41
|
+
i = e < 0 ? n : e + 1;
|
|
42
|
+
} else if (c === '/' && d === '*') {
|
|
43
|
+
let depth = 1;
|
|
44
|
+
i += 2;
|
|
45
|
+
while (i < n && depth) {
|
|
46
|
+
if (sql[i] === '/' && sql[i + 1] === '*') (depth++, (i += 2));
|
|
47
|
+
else if (sql[i] === '*' && sql[i + 1] === '/') (depth--, (i += 2));
|
|
48
|
+
else i++;
|
|
49
|
+
}
|
|
50
|
+
} else if (c === "'") {
|
|
51
|
+
// E'…' : antislash échappé (le mot E qui précède, collé, est absorbé dans la chaîne)
|
|
52
|
+
const prev = out[out.length - 1];
|
|
53
|
+
const escapes = prev && prev.k === 'w' && prev.e === i && /^[eE]$/.test(sql.slice(prev.s, prev.e));
|
|
54
|
+
const s = escapes ? prev.s : i;
|
|
55
|
+
if (escapes) out.pop();
|
|
56
|
+
i++;
|
|
57
|
+
while (i < n) {
|
|
58
|
+
if (escapes && sql[i] === '\\') i += 2;
|
|
59
|
+
else if (sql[i] === "'" && sql[i + 1] === "'") i += 2;
|
|
60
|
+
else if (sql[i] === "'") break;
|
|
61
|
+
else i++;
|
|
62
|
+
}
|
|
63
|
+
i = Math.min(n, i + 1);
|
|
64
|
+
out.push({ k: 's', v: '', s, e: i });
|
|
65
|
+
} else if (c === '"') {
|
|
66
|
+
const s = i;
|
|
67
|
+
let v = '';
|
|
68
|
+
i++;
|
|
69
|
+
while (i < n) {
|
|
70
|
+
if (sql[i] === '"' && sql[i + 1] === '"') (v += '"', (i += 2));
|
|
71
|
+
else if (sql[i] === '"') break;
|
|
72
|
+
else v += sql[i++];
|
|
73
|
+
}
|
|
74
|
+
i = Math.min(n, i + 1);
|
|
75
|
+
out.push({ k: 'id', v, s, e: i });
|
|
76
|
+
} else if (c === '$' && /[A-Za-z_\u0080-$]/.test(d || '')) {
|
|
77
|
+
const m = /^\$([A-Za-z_\u0080-][A-Za-z0-9_\u0080-]*)?\$/.exec(sql.slice(i, i + 80));
|
|
78
|
+
if (!m) {
|
|
79
|
+
out.push({ k: 'p', v: c, s: i, e: ++i });
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const tag = m[0];
|
|
83
|
+
const end = sql.indexOf(tag, i + tag.length);
|
|
84
|
+
const s = i;
|
|
85
|
+
i = end < 0 ? n : end + tag.length;
|
|
86
|
+
out.push({ k: 's', v: '', s, e: i });
|
|
87
|
+
} else if (WORD_START.test(c)) {
|
|
88
|
+
const s = i;
|
|
89
|
+
while (i < n && WORD.test(sql[i])) i++;
|
|
90
|
+
out.push({ k: 'w', v: sql.slice(s, i).toLowerCase(), s, e: i });
|
|
91
|
+
} else if (/[0-9]/.test(c) || (c === '.' && /[0-9]/.test(d || ''))) {
|
|
92
|
+
const s = i;
|
|
93
|
+
while (i < n && /[0-9.eE_]/.test(sql[i])) i++;
|
|
94
|
+
out.push({ k: 'n', v: sql.slice(s, i), s, e: i });
|
|
95
|
+
} else {
|
|
96
|
+
out.push({ k: 'p', v: c, s: i, e: ++i });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Instructions : listes de jetons, coupées aux « ; » (sauf dans un corps BEGIN ATOMIC … END) */
|
|
103
|
+
function statements(tokens) {
|
|
104
|
+
const out = [];
|
|
105
|
+
let cur = [];
|
|
106
|
+
let atomic = 0; // profondeur dans BEGIN ATOMIC (CASE … END compris)
|
|
107
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
108
|
+
const t = tokens[i];
|
|
109
|
+
if (t.k === 'p' && t.v === ';' && !atomic) {
|
|
110
|
+
if (cur.length) out.push(cur);
|
|
111
|
+
cur = [];
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
if (t.k === 'w') {
|
|
115
|
+
if (t.v === 'begin' && tokens[i + 1] && tokens[i + 1].k === 'w' && tokens[i + 1].v === 'atomic') atomic++;
|
|
116
|
+
else if (atomic && t.v === 'case') atomic++;
|
|
117
|
+
else if (atomic && t.v === 'end') atomic--;
|
|
118
|
+
}
|
|
119
|
+
cur.push(t);
|
|
120
|
+
}
|
|
121
|
+
if (cur.length) out.push(cur);
|
|
122
|
+
return out;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// ------------------------------------------------------------------ lecture des instructions
|
|
126
|
+
const isName = (t) => t && (t.k === 'id' || t.k === 'w');
|
|
127
|
+
const nameOf = (t) => (t.k === 'id' ? t.v : t.v);
|
|
128
|
+
|
|
129
|
+
/** Nom qualifié à partir de toks[i] : { parts, next } ou null */
|
|
130
|
+
function qualified(toks, i) {
|
|
131
|
+
if (!isName(toks[i])) return null;
|
|
132
|
+
const parts = [nameOf(toks[i])];
|
|
133
|
+
let j = i + 1;
|
|
134
|
+
while (toks[j] && toks[j].k === 'p' && toks[j].v === '.' && isName(toks[j + 1])) {
|
|
135
|
+
parts.push(nameOf(toks[j + 1]));
|
|
136
|
+
j += 2;
|
|
137
|
+
}
|
|
138
|
+
return { parts, next: j };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const tableOf = (parts) => (parts.length >= 2 ? { schema: parts[parts.length - 2], table: parts[parts.length - 1] } : { schema: 'public', table: parts[0] });
|
|
142
|
+
|
|
143
|
+
/** Sauts : [IF EXISTS] */
|
|
144
|
+
const skipIfExists = (toks, j) => (w(toks[j], 'if') && w(toks[j + 1], 'exists') ? j + 2 : j);
|
|
145
|
+
const w = (t, ...words) => Boolean(t && t.k === 'w' && words.includes(t.v));
|
|
146
|
+
|
|
147
|
+
/** Parenthèses équilibrées à partir de toks[j] = '(' : index après ')' */
|
|
148
|
+
function skipParens(toks, j) {
|
|
149
|
+
let depth = 0;
|
|
150
|
+
for (; j < toks.length; j++) {
|
|
151
|
+
if (toks[j].k === 'p' && toks[j].v === '(') depth++;
|
|
152
|
+
else if (toks[j].k === 'p' && toks[j].v === ')' && --depth === 0) return j + 1;
|
|
153
|
+
}
|
|
154
|
+
return j;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Morceaux séparés par des virgules au niveau 0 */
|
|
158
|
+
function splitTop(toks, from) {
|
|
159
|
+
const parts = [];
|
|
160
|
+
let cur = [];
|
|
161
|
+
let depth = 0;
|
|
162
|
+
for (let j = from; j < toks.length; j++) {
|
|
163
|
+
const t = toks[j];
|
|
164
|
+
if (t.k === 'p' && t.v === '(') depth++;
|
|
165
|
+
else if (t.k === 'p' && t.v === ')') depth--;
|
|
166
|
+
if (t.k === 'p' && t.v === ',' && depth === 0) {
|
|
167
|
+
parts.push(cur);
|
|
168
|
+
cur = [];
|
|
169
|
+
} else cur.push(t);
|
|
170
|
+
}
|
|
171
|
+
if (cur.length) parts.push(cur);
|
|
172
|
+
return parts;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Texte de l'instruction tel qu'écrit, sans les commentaires, sur une ligne, borné */
|
|
176
|
+
function textOf(sql, toks, max = 240) {
|
|
177
|
+
let s = '';
|
|
178
|
+
let prev = null;
|
|
179
|
+
for (const t of toks) {
|
|
180
|
+
const raw = sql.slice(t.s, t.e).replace(/\s+/g, ' ');
|
|
181
|
+
// Espacement de la source : collé s'il l'était, une espace sinon (commentaires et retours à la ligne ôtés)
|
|
182
|
+
const tight = prev && prev.e === t.s;
|
|
183
|
+
s += (prev && !tight ? ' ' : '') + raw;
|
|
184
|
+
prev = t;
|
|
185
|
+
}
|
|
186
|
+
return s.length > max ? `${s.slice(0, max - 1)}…` : s;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const lineAt = (sql, pos) => sql.slice(0, pos).split('\n').length;
|
|
190
|
+
|
|
191
|
+
/** Instructions destructrices d'un fichier : [{ kind, schema, table, column?, ... }] (noms tels qu'écrits) */
|
|
192
|
+
function parseStatement(toks) {
|
|
193
|
+
const found = [];
|
|
194
|
+
const t0 = toks[0];
|
|
195
|
+
if (!t0 || t0.k !== 'w') return found;
|
|
196
|
+
// DROP TABLE | SCHEMA | VIEW | MATERIALIZED VIEW | FUNCTION | PROCEDURE [IF EXISTS] nom[, …] [CASCADE]
|
|
197
|
+
if (t0.v === 'drop') {
|
|
198
|
+
let j = 1;
|
|
199
|
+
let kind = null;
|
|
200
|
+
if (w(toks[j], 'table')) (kind = 'drop_table'), j++;
|
|
201
|
+
else if (w(toks[j], 'schema')) (kind = 'drop_schema'), j++;
|
|
202
|
+
else if (w(toks[j], 'view')) (kind = 'drop_view'), j++;
|
|
203
|
+
else if (w(toks[j], 'materialized') && w(toks[j + 1], 'view')) (kind = 'drop_view'), (j += 2);
|
|
204
|
+
else if (w(toks[j], 'function', 'procedure')) (kind = 'drop_function'), j++;
|
|
205
|
+
if (!kind) return found;
|
|
206
|
+
j = skipIfExists(toks, j);
|
|
207
|
+
const cascade = toks.some((t) => w(t, 'cascade'));
|
|
208
|
+
for (const part of splitTop(toks, j)) {
|
|
209
|
+
const q = qualified(part, 0);
|
|
210
|
+
if (!q) continue;
|
|
211
|
+
if (kind === 'drop_schema') found.push({ kind, schema: q.parts[q.parts.length - 1], cascade });
|
|
212
|
+
else found.push({ kind, ...tableOf(q.parts), cascade });
|
|
213
|
+
}
|
|
214
|
+
return found;
|
|
215
|
+
}
|
|
216
|
+
// TRUNCATE [TABLE] [ONLY] nom [*][, …]
|
|
217
|
+
if (t0.v === 'truncate') {
|
|
218
|
+
let j = w(toks[1], 'table') ? 2 : 1;
|
|
219
|
+
for (const part of splitTop(toks, j)) {
|
|
220
|
+
const k = w(part[0], 'only') ? 1 : 0;
|
|
221
|
+
const q = qualified(part, k);
|
|
222
|
+
if (q && !w(part[k], 'restart', 'continue', 'cascade', 'restrict')) found.push({ kind: 'truncate', ...tableOf(q.parts) });
|
|
223
|
+
}
|
|
224
|
+
return found;
|
|
225
|
+
}
|
|
226
|
+
// [WITH …] DELETE FROM [ONLY] nom … [WHERE …]
|
|
227
|
+
if (t0.v === 'delete' || t0.v === 'with') {
|
|
228
|
+
for (let j = 0; j < toks.length - 1; j++) {
|
|
229
|
+
if (!(w(toks[j], 'delete') && w(toks[j + 1], 'from'))) continue;
|
|
230
|
+
let k = j + 2;
|
|
231
|
+
if (w(toks[k], 'only')) k++;
|
|
232
|
+
const q = qualified(toks, k);
|
|
233
|
+
if (!q) continue;
|
|
234
|
+
// WHERE au même niveau de parenthèses que le DELETE
|
|
235
|
+
let depth = 0;
|
|
236
|
+
let filtered = false;
|
|
237
|
+
for (let m = q.next; m < toks.length; m++) {
|
|
238
|
+
const t = toks[m];
|
|
239
|
+
if (t.k === 'p' && t.v === '(') depth++;
|
|
240
|
+
else if (t.k === 'p' && t.v === ')') {
|
|
241
|
+
if (--depth < 0) break;
|
|
242
|
+
} else if (depth === 0 && w(t, 'where')) {
|
|
243
|
+
filtered = true;
|
|
244
|
+
break;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
found.push({ kind: filtered ? 'delete_where' : 'delete', ...tableOf(q.parts) });
|
|
248
|
+
}
|
|
249
|
+
return found;
|
|
250
|
+
}
|
|
251
|
+
// ALTER TABLE [IF EXISTS] [ONLY] nom action[, …]
|
|
252
|
+
if (t0.v === 'alter' && w(toks[1], 'table')) {
|
|
253
|
+
let j = skipIfExists(toks, 2);
|
|
254
|
+
if (w(toks[j], 'only')) j++;
|
|
255
|
+
const q = qualified(toks, j);
|
|
256
|
+
if (!q) return found;
|
|
257
|
+
const target = tableOf(q.parts);
|
|
258
|
+
j = q.next;
|
|
259
|
+
if (toks[j] && toks[j].k === 'p' && toks[j].v === '*') j++;
|
|
260
|
+
for (const a of splitTop(toks, j)) {
|
|
261
|
+
if (w(a[0], 'rename')) {
|
|
262
|
+
if (w(a[1], 'to') && isName(a[2])) found.push({ kind: 'rename_table', ...target, to: nameOf(a[2]) });
|
|
263
|
+
else if (w(a[1], 'constraint')) continue;
|
|
264
|
+
else {
|
|
265
|
+
let k = w(a[1], 'column') ? 2 : 1;
|
|
266
|
+
if (isName(a[k]) && w(a[k + 1], 'to') && isName(a[k + 2])) found.push({ kind: 'rename_column', ...target, column: nameOf(a[k]), to: nameOf(a[k + 2]) });
|
|
267
|
+
}
|
|
268
|
+
} else if (w(a[0], 'drop')) {
|
|
269
|
+
let k = 1;
|
|
270
|
+
if (w(a[k], 'column')) k++;
|
|
271
|
+
else if (w(a[k], 'constraint')) continue;
|
|
272
|
+
k = skipIfExists(a, k);
|
|
273
|
+
if (isName(a[k])) found.push({ kind: 'drop_column', ...target, column: nameOf(a[k]) });
|
|
274
|
+
} else if (w(a[0], 'alter')) {
|
|
275
|
+
let k = 1;
|
|
276
|
+
if (w(a[k], 'column')) k++;
|
|
277
|
+
if (!isName(a[k])) continue;
|
|
278
|
+
const column = nameOf(a[k]);
|
|
279
|
+
k++;
|
|
280
|
+
if (w(a[k], 'set') && w(a[k + 1], 'data') && w(a[k + 2], 'type')) k += 3;
|
|
281
|
+
else if (w(a[k], 'type')) k++;
|
|
282
|
+
else continue;
|
|
283
|
+
const typeToks = [];
|
|
284
|
+
for (; k < a.length && !w(a[k], 'using', 'collate'); k++) typeToks.push(a[k]);
|
|
285
|
+
found.push({ kind: 'alter_type', ...target, column, typeToks });
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return found;
|
|
289
|
+
}
|
|
290
|
+
return found;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** Objets créés par une instruction (vue, fonction, table) : pour « recréé dans le lot » */
|
|
294
|
+
function createdBy(toks) {
|
|
295
|
+
if (!w(toks[0], 'create')) return null;
|
|
296
|
+
let j = 1;
|
|
297
|
+
if (w(toks[j], 'or') && w(toks[j + 1], 'replace')) j += 2;
|
|
298
|
+
while (w(toks[j], 'temp', 'temporary', 'unlogged', 'recursive', 'secure')) j++;
|
|
299
|
+
let type = null;
|
|
300
|
+
if (w(toks[j], 'view')) (type = 'view'), j++;
|
|
301
|
+
else if (w(toks[j], 'materialized') && w(toks[j + 1], 'view')) (type = 'view'), (j += 2);
|
|
302
|
+
else if (w(toks[j], 'function', 'procedure')) (type = 'function'), j++;
|
|
303
|
+
else if (w(toks[j], 'table')) (type = 'table'), j++;
|
|
304
|
+
if (!type) return null;
|
|
305
|
+
if (w(toks[j], 'if') && w(toks[j + 1], 'not') && w(toks[j + 2], 'exists')) j += 3;
|
|
306
|
+
const q = qualified(toks, j);
|
|
307
|
+
return q ? { type, ...tableOf(q.parts) } : null;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const key = (...p) => p.map((x) => String(x)).join('\u0000');
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* Lot de migrations en attente, dans l'ordre : [{ file, sql }]. Rend les constats :
|
|
314
|
+
* [{ file, line, statement, kind, schema, table, column?, to?, type?, db: { schema, table, column? }, recreated? }]
|
|
315
|
+
* db : le nom de la cible sur la base avant le lot (renommages du lot suivis).
|
|
316
|
+
*/
|
|
317
|
+
function analyze(batch) {
|
|
318
|
+
const findings = [];
|
|
319
|
+
const tableAlias = new Map(); // nom après renommage dans le lot → nom sur la base
|
|
320
|
+
const columnAlias = new Map();
|
|
321
|
+
const created = []; // { type, schema, table, at }
|
|
322
|
+
let at = 0;
|
|
323
|
+
for (const m of batch) {
|
|
324
|
+
const sql = String(m.sql || '');
|
|
325
|
+
let toks;
|
|
326
|
+
try {
|
|
327
|
+
toks = tokenize(sql);
|
|
328
|
+
} catch {
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
for (const st of statements(toks)) {
|
|
332
|
+
at++;
|
|
333
|
+
const c = createdBy(st);
|
|
334
|
+
if (c) created.push({ ...c, at });
|
|
335
|
+
for (const f of parseStatement(st)) {
|
|
336
|
+
const dbTable = f.table !== undefined ? tableAlias.get(key(f.schema, f.table)) || { schema: f.schema, table: f.table } : null;
|
|
337
|
+
const dbColumn = f.column !== undefined ? columnAlias.get(key(dbTable.schema, dbTable.table, f.column)) || f.column : undefined;
|
|
338
|
+
const item = {
|
|
339
|
+
file: m.file,
|
|
340
|
+
line: lineAt(sql, st[0].s),
|
|
341
|
+
statement: textOf(sql, st),
|
|
342
|
+
kind: f.kind,
|
|
343
|
+
schema: f.schema,
|
|
344
|
+
...(f.table !== undefined ? { table: f.table } : {}),
|
|
345
|
+
...(f.column !== undefined ? { column: f.column } : {}),
|
|
346
|
+
...(f.to !== undefined ? { to: f.to } : {}),
|
|
347
|
+
...(f.typeToks ? { type: textOf(sql, f.typeToks, 80) } : {}),
|
|
348
|
+
...(f.cascade ? { cascade: true } : {}),
|
|
349
|
+
db: f.kind === 'drop_schema' ? { schema: f.schema } : { ...dbTable, ...(dbColumn !== undefined ? { column: dbColumn } : {}) },
|
|
350
|
+
at,
|
|
351
|
+
};
|
|
352
|
+
findings.push(item);
|
|
353
|
+
if (f.kind === 'rename_table') tableAlias.set(key(f.schema, f.to), dbTable);
|
|
354
|
+
if (f.kind === 'rename_column') columnAlias.set(key(dbTable.schema, dbTable.table, f.to), dbColumn);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
// Vue ou fonction supprimée puis recréée plus loin dans le lot (drop view if exists x; create view x …)
|
|
359
|
+
for (const f of findings) {
|
|
360
|
+
if (f.kind !== 'drop_view' && f.kind !== 'drop_function') continue;
|
|
361
|
+
const type = f.kind === 'drop_view' ? 'view' : 'function';
|
|
362
|
+
if (created.some((c) => c.type === type && c.schema === f.schema && c.table === f.table && c.at > f.at)) f.recreated = true;
|
|
363
|
+
}
|
|
364
|
+
return findings.map(({ at: _at, ...f }) => f).slice(0, 500);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// ------------------------------------------------------------------ requêtes sur la base (lecture seule)
|
|
368
|
+
const lit = (s) => `'${String(s).replace(/'/g, "''")}'`;
|
|
369
|
+
const regclass = (s, t) => `to_regclass(format('%I.%I', ${lit(s)}, ${lit(t)}))`;
|
|
370
|
+
const countXml = (inner) => `(xpath('/row/n/text()', query_to_xml(${inner}, false, true, '')))[1]::text::bigint`;
|
|
371
|
+
|
|
372
|
+
/** Requête (exacte) et repli (estimations) d'un constat ; une ligne de JSON chacune */
|
|
373
|
+
function checkOf(f) {
|
|
374
|
+
const { schema, table, column } = f.db;
|
|
375
|
+
if (f.kind === 'drop_schema') {
|
|
376
|
+
const tables = `from pg_class c join pg_namespace n on n.oid = c.relnamespace where n.nspname = ${lit(schema)} and c.relkind in ('r', 'p')`;
|
|
377
|
+
return {
|
|
378
|
+
sql: `select json_build_object('exists', exists (select 1 from pg_namespace where nspname = ${lit(schema)}), 'tables', (select count(*) ${tables}), 'rows', (select coalesce(sum(${countXml(`format('select count(*) as n from (select 1 from %I.%I limit ${CAP + 1}) s', n.nspname, c.relname)`)}), 0) ${tables}))::text`,
|
|
379
|
+
fallback: `select json_build_object('exists', exists (select 1 from pg_namespace where nspname = ${lit(schema)}), 'tables', (select count(*) ${tables}), 'rows', (select coalesce(sum(greatest(c.reltuples, 0)), 0)::bigint ${tables}), 'approx', true)::text`,
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
if (f.kind === 'drop_view') {
|
|
383
|
+
return {
|
|
384
|
+
sql: `select json_build_object('exists', c.oid is not null, 'relkind', c.relkind, 'api', coalesce(has_table_privilege('anon', c.oid, 'select') or has_table_privilege('authenticated', c.oid, 'select'), false))::text from (select ${regclass(schema, table)}::oid as oid) r left join pg_class c on c.oid = r.oid`,
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
if (f.kind === 'drop_function') {
|
|
388
|
+
return {
|
|
389
|
+
sql: `select json_build_object('exists', count(p.oid) > 0, 'api', coalesce(bool_or(has_function_privilege('anon', p.oid, 'execute') or has_function_privilege('authenticated', p.oid, 'execute')), false))::text from pg_proc p join pg_namespace n on n.oid = p.pronamespace where n.nspname = ${lit(schema)} and p.proname = ${lit(table)}`,
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
const rel = `from (select ${regclass(schema, table)}::oid as oid) r left join pg_class c on c.oid = r.oid`;
|
|
393
|
+
const plain = `c.relkind in ('r', 'p')`;
|
|
394
|
+
if (column !== undefined) {
|
|
395
|
+
const att = `(select a.attname from pg_attribute a where a.attrelid = c.oid and a.attname = ${lit(column)} and a.attnum > 0 and not a.attisdropped)`;
|
|
396
|
+
const typ = `(select format_type(a.atttypid, a.atttypmod) from pg_attribute a where a.attrelid = c.oid and a.attname = ${lit(column)} and a.attnum > 0 and not a.attisdropped)`;
|
|
397
|
+
const exact = countXml(`format('select count(*) as n from (select 1 from %I.%I where %I is not null limit ${CAP + 1}) s', ${lit(schema)}, ${lit(table)}, ${lit(column)})`);
|
|
398
|
+
return {
|
|
399
|
+
sql: `select json_build_object('exists', c.oid is not null, 'relkind', c.relkind, 'column', ${att} is not null, 'type', ${typ}, 'rows', case when ${plain} and ${att} is not null then ${exact} end, 'estimate', greatest(c.reltuples, 0)::bigint, 'api', coalesce(has_table_privilege('anon', c.oid, 'select') or has_table_privilege('authenticated', c.oid, 'select'), false))::text ${rel}`,
|
|
400
|
+
fallback: `select json_build_object('exists', c.oid is not null, 'relkind', c.relkind, 'column', ${att} is not null, 'type', ${typ}, 'rows', case when ${plain} and ${att} is not null then (greatest(c.reltuples, 0) * (1 - coalesce((select s.null_frac from pg_stats s where s.schemaname = ${lit(schema)} and s.tablename = ${lit(table)} and s.attname = ${lit(column)}), 0)))::bigint end, 'approx', true, 'api', coalesce(has_table_privilege('anon', c.oid, 'select') or has_table_privilege('authenticated', c.oid, 'select'), false))::text ${rel}`,
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
const exact = countXml(`format('select count(*) as n from (select 1 from %I.%I limit ${CAP + 1}) s', ${lit(schema)}, ${lit(table)})`);
|
|
404
|
+
return {
|
|
405
|
+
sql: `select json_build_object('exists', c.oid is not null, 'relkind', c.relkind, 'rows', case when ${plain} then ${exact} end, 'estimate', greatest(c.reltuples, 0)::bigint, 'api', coalesce(has_table_privilege('anon', c.oid, 'select') or has_table_privilege('authenticated', c.oid, 'select'), false))::text ${rel}`,
|
|
406
|
+
fallback: `select json_build_object('exists', c.oid is not null, 'relkind', c.relkind, 'rows', case when ${plain} then greatest(c.reltuples, 0)::bigint end, 'approx', true, 'api', coalesce(has_table_privilege('anon', c.oid, 'select') or has_table_privilege('authenticated', c.oid, 'select'), false))::text ${rel}`,
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
const checks = (findings) => findings.slice(0, MAX_FINDINGS).map(checkOf);
|
|
411
|
+
|
|
412
|
+
const TX = ["begin transaction read only", "set local statement_timeout = '3s'", "set local lock_timeout = '1s'"];
|
|
413
|
+
|
|
414
|
+
/** Résultat d'un constat : l'exact, sinon le repli (marqué approx), sinon null (inconnu) */
|
|
415
|
+
function merge(exact, fallback) {
|
|
416
|
+
if (exact) {
|
|
417
|
+
const r = { ...exact };
|
|
418
|
+
// Au-delà de la borne : l'estimation du catalogue si elle est plus grande
|
|
419
|
+
if (typeof r.rows === 'number' && r.rows > CAP) (r.rows = Math.max(r.rows, Number(r.estimate) || 0)), (r.approx = true);
|
|
420
|
+
return r;
|
|
421
|
+
}
|
|
422
|
+
return fallback ? { ...fallback, approx: true } : null;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** Client pg (CLI) : chaque requête dans un point de sauvegarde, la transaction en lecture seule annulée à la fin */
|
|
426
|
+
async function runChecks(client, list) {
|
|
427
|
+
const out = [];
|
|
428
|
+
if (!list.length) return out;
|
|
429
|
+
for (const q of TX) await client.query(q);
|
|
430
|
+
try {
|
|
431
|
+
for (const c of list) {
|
|
432
|
+
const one = async (sql) => {
|
|
433
|
+
if (!sql) return null;
|
|
434
|
+
await client.query('savepoint poad_dl');
|
|
435
|
+
try {
|
|
436
|
+
const { rows } = await client.query(sql);
|
|
437
|
+
await client.query('release savepoint poad_dl');
|
|
438
|
+
return JSON.parse(Object.values(rows[0] || {})[0] || 'null');
|
|
439
|
+
} catch {
|
|
440
|
+
await client.query('rollback to savepoint poad_dl').catch(() => {});
|
|
441
|
+
return null;
|
|
442
|
+
}
|
|
443
|
+
};
|
|
444
|
+
const exact = await one(c.sql);
|
|
445
|
+
out.push(merge(exact, exact ? null : await one(c.fallback)));
|
|
446
|
+
}
|
|
447
|
+
} finally {
|
|
448
|
+
await client.query('rollback').catch(() => {});
|
|
449
|
+
}
|
|
450
|
+
return out;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/** Script psql (poad.io : psql -X -qtA -v ON_ERROR_STOP=0 -f -) : lignes « <i> e|f <json> » */
|
|
454
|
+
function script(list) {
|
|
455
|
+
const lines = [...TX.map((q) => `${q};`)];
|
|
456
|
+
list.forEach((c, i) => {
|
|
457
|
+
lines.push('savepoint poad_dl;', `select '${i} e ' || (${c.sql});`, 'rollback to savepoint poad_dl;');
|
|
458
|
+
if (c.fallback) lines.push(`select '${i} f ' || (${c.fallback});`, 'rollback to savepoint poad_dl;');
|
|
459
|
+
});
|
|
460
|
+
lines.push('rollback;');
|
|
461
|
+
return lines.join('\n') + '\n';
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
function parseOutput(text, count) {
|
|
465
|
+
const e = new Array(count).fill(null);
|
|
466
|
+
const f = new Array(count).fill(null);
|
|
467
|
+
for (const line of String(text || '').split('\n')) {
|
|
468
|
+
const m = /^(\d+) ([ef]) (\{.*\})\s*$/.exec(line);
|
|
469
|
+
if (!m || Number(m[1]) >= count) continue;
|
|
470
|
+
try {
|
|
471
|
+
(m[2] === 'e' ? e : f)[Number(m[1])] = JSON.parse(m[3]);
|
|
472
|
+
} catch {
|
|
473
|
+
/* ligne illisible : inconnu */
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
return e.map((x, i) => merge(x, x ? null : f[i]));
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// ------------------------------------------------------------------ décision
|
|
480
|
+
const LOSS = new Set(['drop_table', 'drop_column', 'alter_type', 'truncate', 'delete', 'drop_schema']);
|
|
481
|
+
const LABEL = { drop_table: 'DROP TABLE', drop_column: 'DROP COLUMN', alter_type: 'ALTER COLUMN', truncate: 'TRUNCATE', delete: 'DELETE FROM', delete_where: 'DELETE FROM', drop_schema: 'DROP SCHEMA', rename_table: 'RENAME TABLE', rename_column: 'RENAME COLUMN', drop_view: 'DROP VIEW', drop_function: 'DROP FUNCTION' };
|
|
482
|
+
|
|
483
|
+
const ALIASES = { int: 'integer', int4: 'integer', int8: 'bigint', int2: 'smallint', float8: 'double precision', float4: 'real', float: 'double precision', bool: 'boolean', varchar: 'character varying', char: 'character', timestamptz: 'timestamp with time zone', timestamp: 'timestamp without time zone', timetz: 'time with time zone', time: 'time without time zone', decimal: 'numeric' };
|
|
484
|
+
function normType(s) {
|
|
485
|
+
let t = String(s || '').toLowerCase().replace(/\s+/g, ' ').replace(/\s*\(\s*/g, '(').replace(/\s*,\s*/g, ',').replace(/\s*\)/g, ')').replace(/^pg_catalog\./, '').trim();
|
|
486
|
+
const m = /^([a-z0-9_ ]+?)(\([0-9,]+\))?(\[\])?$/.exec(t);
|
|
487
|
+
if (!m) return t;
|
|
488
|
+
return (ALIASES[m[1]] || m[1]) + (m[2] || '') + (m[3] || '');
|
|
489
|
+
}
|
|
490
|
+
/** Conversion qui ne peut rien perdre (vers text, élargissement d'entier, de varchar…) */
|
|
491
|
+
function safeConversion(from, to) {
|
|
492
|
+
const a = normType(from);
|
|
493
|
+
const b = normType(to);
|
|
494
|
+
if (!a || !b) return false;
|
|
495
|
+
if (a === b) return true;
|
|
496
|
+
if (b === 'text' || b === 'character varying' || b === 'citext') return !a.endsWith('[]');
|
|
497
|
+
const INTS = ['smallint', 'integer', 'bigint'];
|
|
498
|
+
if (INTS.includes(a) && INTS.includes(b)) return INTS.indexOf(b) >= INTS.indexOf(a);
|
|
499
|
+
if (INTS.includes(a) && b === 'numeric') return true;
|
|
500
|
+
if (a === 'real' && b === 'double precision') return true;
|
|
501
|
+
const va = /^character varying\((\d+)\)$/.exec(a);
|
|
502
|
+
const vb = /^character varying\((\d+)\)$/.exec(b);
|
|
503
|
+
if (va && vb) return Number(vb[1]) >= Number(va[1]);
|
|
504
|
+
if (a === 'json' && b === 'jsonb') return true;
|
|
505
|
+
if (a === 'timestamp without time zone' && b === 'timestamp with time zone') return true;
|
|
506
|
+
return false;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
const targetOf = (f) => (f.kind === 'drop_schema' ? f.schema : `${f.schema}.${f.table}${f.column !== undefined ? `.${f.column}` : ''}`);
|
|
510
|
+
const fmt = (n, approx) => `${approx ? '~' : ''}${Number(n).toLocaleString('en-US')}`;
|
|
511
|
+
|
|
512
|
+
/** Phrase lisible (anglais, comme le reste du CLI), sans valeur de données */
|
|
513
|
+
function describe(f, r) {
|
|
514
|
+
const rows = r && typeof r.rows === 'number' ? r.rows : null;
|
|
515
|
+
const n = rows === null ? null : fmt(rows, r.approx);
|
|
516
|
+
const unknown = 'row count unknown (the count timed out): data may be lost';
|
|
517
|
+
const head = `${LABEL[f.kind]} ${targetOf(f)}`;
|
|
518
|
+
switch (f.kind) {
|
|
519
|
+
case 'drop_table':
|
|
520
|
+
case 'truncate':
|
|
521
|
+
case 'delete':
|
|
522
|
+
return `${head}${f.kind === 'delete' ? ' (no WHERE)' : ''} — ${n === null ? unknown : `${n} row(s) will be lost`}`;
|
|
523
|
+
case 'delete_where':
|
|
524
|
+
return `${head} WHERE … — up to ${n === null ? '?' : n} row(s) (the filter is not evaluated)`;
|
|
525
|
+
case 'drop_column':
|
|
526
|
+
return `${head} — ${n === null ? unknown : `${n} non-null value(s) will be lost`}`;
|
|
527
|
+
case 'alter_type':
|
|
528
|
+
return `${head} TYPE ${f.type} — ${n === null ? unknown : `${n} non-null value(s) converted from ${(r && r.type) || '?'}: loss or failure possible`}`;
|
|
529
|
+
case 'drop_schema':
|
|
530
|
+
return `${head}${f.cascade ? ' CASCADE' : ''} — ${n === null ? unknown : `${(r && r.tables) || 0} table(s), ${n} row(s) will be lost`}`;
|
|
531
|
+
case 'rename_table':
|
|
532
|
+
return `${head} TO ${f.to} — API clients using ${f.table} break (${n === null ? '?' : n} row(s) kept)`;
|
|
533
|
+
case 'rename_column':
|
|
534
|
+
return `${head} TO ${f.to} — API clients using ${f.column} break (values kept)`;
|
|
535
|
+
default:
|
|
536
|
+
return `${head} — served by the API to anon or authenticated: its clients break`;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/**
|
|
541
|
+
* Décision par constat. production : environnement main de poad.io (jamais en local) ; accepted :
|
|
542
|
+
* --allow-destructive / confirmation donnée. Rend [{ ...constat, target, rows, approx, loss, decision, reason, message }] ;
|
|
543
|
+
* decision : silent | warn | confirm (production, perte, pas encore acceptée) | accepted.
|
|
544
|
+
*/
|
|
545
|
+
function decide(findings, results, { production = false, accepted = false, exposedSchemas = ['public'] } = {}) {
|
|
546
|
+
return findings.map((f, i) => {
|
|
547
|
+
const r = i < MAX_FINDINGS ? results[i] || null : null;
|
|
548
|
+
const target = targetOf(f);
|
|
549
|
+
const base = { file: f.file, line: f.line, statement: f.statement, kind: f.kind, target, rows: r && typeof r.rows === 'number' ? r.rows : null, approx: Boolean(r && r.approx), loss: LOSS.has(f.kind) };
|
|
550
|
+
const silent = (reason) => ({ ...base, decision: 'silent', reason, message: null });
|
|
551
|
+
if (r && r.exists === false) return silent('target_absent');
|
|
552
|
+
if (f.recreated) return silent('recreated_in_batch');
|
|
553
|
+
if (f.kind === 'drop_view' || f.kind === 'drop_function') {
|
|
554
|
+
if (!exposedSchemas.includes(f.schema)) return silent('not_exposed');
|
|
555
|
+
if (r && !r.api) return silent('not_exposed');
|
|
556
|
+
} else if (f.kind !== 'drop_schema') {
|
|
557
|
+
if (r && r.relkind && !['r', 'p'].includes(r.relkind)) return silent(r.relkind === 'f' ? 'foreign_table' : 'not_a_table');
|
|
558
|
+
if (f.column !== undefined && r && r.column === false) return silent('target_absent');
|
|
559
|
+
}
|
|
560
|
+
if (f.kind === 'alter_type' && r && r.type && safeConversion(r.type, f.type)) return silent('lossless_conversion');
|
|
561
|
+
if (['rename_table', 'rename_column'].includes(f.kind) && !exposedSchemas.includes(f.schema)) return silent('not_exposed');
|
|
562
|
+
if (LOSS.has(f.kind) || f.kind === 'delete_where') if (base.rows === 0) return silent('empty');
|
|
563
|
+
const message = describe(f, r);
|
|
564
|
+
if (!base.loss) return { ...base, decision: 'warn', reason: 'api_clients', message };
|
|
565
|
+
const reason = base.rows === null ? 'count_unknown' : 'rows';
|
|
566
|
+
if (!production) return { ...base, decision: 'warn', reason, message };
|
|
567
|
+
return { ...base, decision: accepted ? 'accepted' : 'confirm', reason, message };
|
|
568
|
+
});
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/** Constats montrés (et rendus en JSON) : ceux qui ne sont pas silencieux */
|
|
572
|
+
const visible = (decided) => decided.filter((d) => d.decision !== 'silent');
|
|
573
|
+
|
|
574
|
+
/** Champ data_loss de --json : { file, statement, target, rows, kind } (+ line, approx, decision, message) */
|
|
575
|
+
const jsonOf = (decided) => visible(decided).map((d) => ({ file: d.file, line: d.line, statement: d.statement, target: d.target, rows: d.rows, approx: d.approx, kind: d.kind, loss: d.loss, decision: d.decision, message: d.message }));
|
|
576
|
+
|
|
577
|
+
/** Attributs de la ligne de journal (event=migration_data_loss_check) : jamais d'instruction, de valeur ni de secret */
|
|
578
|
+
function logAttrs(d, extra = {}) {
|
|
579
|
+
const [schema, table, column] = d.target.split('.');
|
|
580
|
+
return {
|
|
581
|
+
event: 'migration_data_loss_check',
|
|
582
|
+
file: `poad/migrations/${d.file}`,
|
|
583
|
+
kind: d.kind,
|
|
584
|
+
target: d.target,
|
|
585
|
+
schema,
|
|
586
|
+
...(table ? { table } : {}),
|
|
587
|
+
...(column ? { column } : {}),
|
|
588
|
+
rows: d.rows,
|
|
589
|
+
approx: d.approx,
|
|
590
|
+
loss: d.loss,
|
|
591
|
+
decision: d.decision,
|
|
592
|
+
reason: d.reason,
|
|
593
|
+
...extra,
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
const levelOf = (d) => (d.decision === 'silent' ? 'debug' : 'warn');
|
|
598
|
+
const logMsg = (d) => `data loss check: ${LABEL[d.kind]} ${d.target}: ${d.decision}${d.rows !== null && d.decision !== 'silent' ? ` (${fmt(d.rows, d.approx)} row(s))` : d.decision === 'silent' ? ` (${d.reason})` : ''}`;
|
|
599
|
+
|
|
600
|
+
module.exports = { CAP, tokenize, statements, analyze, checks, runChecks, script, parseOutput, decide, visible, jsonOf, logAttrs, levelOf, logMsg, safeConversion, normType, LOSS };
|