poad 2.75.2 → 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 CHANGED
@@ -247,7 +247,7 @@ module.exports = async (args = {}) => {
247
247
  process.exitCode = 1;
248
248
  } else {
249
249
  waiting.stop();
250
- const migrated = migrate ? await require('../utils/migrate-run')(root, config, { quietWhenNone: false }) : true;
250
+ const migrated = migrate ? await require('../utils/migrate-run')(root, config, { quietWhenNone: false, via: 'poad start' }) : true;
251
251
  // Code de sortie 1 si une migration ou le seed échoue (scripts, CI)
252
252
  if (!migrated) process.exitCode = 1;
253
253
  if (hasReference && migrated && !(await reference.sync(root, config))) process.exitCode = 1;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.75.2",
3
+ "version": "2.75.3",
4
4
  "engine": "0.28.0",
5
5
  "runner": "0.5.0",
6
6
  "main": "index.js",
package/project/deploy.js CHANGED
@@ -1,4 +1,4 @@
1
- // poad deploy [--env <branche>] [--dry-run] [--yes] [--json]
1
+ // poad deploy [--env <branche>] [--dry-run] [--yes] [--allow-destructive | --accept-data-loss] [--json]
2
2
  //
3
3
  // Envoie le dossier poad/ (liste blanche, sans aucun secret : utils/cloud/bundle.js)
4
4
  // à l'environnement du projet poad.io lié :
@@ -6,15 +6,21 @@
6
6
  // x-poad-sha commit git courant, si poad/ n'a aucun changement non commité
7
7
  // x-poad-dry-run 1 avec --dry-run : le serveur dit ce qu'il ferait, rien ne change
8
8
  // réponse : { deploy_id?, status?, migrations: { applied, pending, errors }, warnings }
9
- // warnings : migrations qui perdent des données (drop table, truncate…), signalées, jamais refusées
9
+ // x-poad-allow-destructive 1 avec --allow-destructive (ou après confirmation) : la production applique des
10
+ // migrations qui perdent des données
11
+ // warnings : migrations appliquées modifiées depuis… (et, pour les anciens CLI, le résumé des pertes de données)
12
+ // data_loss : [{ file, line, statement, target, rows, kind, decision, message }] (poad.io 0.70+) : ce que les
13
+ // migrations en attente perdent vraiment, compté sur la base de l'environnement (utils/data-loss.js) ; silence
14
+ // quand la cible est créée par le même déploiement ou vide. Production : refus destructive_migrations sans
15
+ // x-poad-allow-destructive, avant toute écriture ; dans un terminal, le CLI demande et relance avec l'en-tête.
10
16
  // api_exposure : fonctions et vues que l'API ne sert pas à anon ni à authenticated (SECURITY DEFINER, vues
11
17
  // sans security_invoker, vues matérialisées), dans la base et dans les migrations en attente, avec ce que
12
18
  // l'engine de l'environnement en fait et le correctif de chacune (poad.io 0.66.0+), jamais bloquant
13
19
  // asynchrone (deploy_id et état non terminé) : GET …/deploys/:deploy_id jusqu'à la fin
14
20
  //
15
21
  // Production (main) : résumé puis confirmation, sauf --yes (obligatoire hors
16
- // terminal). Codes de sortie : 0 déployé, 5 déploiement en échec (erreurs de
17
- // migration), 4 confirmation manquante, 3 session, 2 usage, 1 autre erreur.
22
+ // terminal ; --yes n'accepte pas une perte de données). Codes de sortie : 0 déployé, 5 déploiement en échec
23
+ // (erreurs de migration), 4 confirmation manquante (ou perte de données refusée), 3 session, 2 usage, 1 autre erreur.
18
24
  const DONE = ['succeeded', 'success', 'refused', 'done', 'deployed', 'completed', 'ok', 'failed', 'error', 'cancelled', 'canceled'];
19
25
  const FAILED = ['failed', 'error', 'cancelled', 'canceled', 'refused'];
20
26
 
@@ -67,13 +73,25 @@ function summarize(d = {}) {
67
73
  dry_run: Boolean(d.dry_run),
68
74
  migrations: { applied: names(m.applied), pending: names(m.pending), errors },
69
75
  message: typeof d.message === 'string' ? d.message : null,
70
- // Signalé, jamais bloquant : migrations qui perdent des données (drop table, truncate…)
71
- warnings: (Array.isArray(d.warnings) ? d.warnings : []).map((w) => ({ message: String((w && w.message) || ''), files: Array.isArray(w && w.files) ? w.files.map(String) : [] })),
76
+ // Signalé, jamais bloquant : migrations appliquées modifiées, résumé des pertes de données (code data_loss)
77
+ warnings: (Array.isArray(d.warnings) ? d.warnings : []).map((w) => ({ message: String((w && w.message) || ''), files: Array.isArray(w && w.files) ? w.files.map(String) : [], ...(w && typeof w.code === 'string' ? { code: w.code } : {}) })),
78
+ data_loss: dataLossOf(d.data_loss),
79
+ refused: errors.some((e) => e.code === 'destructive_migrations') ? 'destructive_migrations' : null,
72
80
  failed: errors.length > 0 || FAILED.includes(status),
73
81
  api_exposure: exposureOf(d.api_exposure),
74
82
  };
75
83
  }
76
84
 
85
+ /** Pertes de données rendues par poad.io, ramenées aux champs connus (textes bornés) */
86
+ function dataLossOf(list) {
87
+ if (!Array.isArray(list)) return [];
88
+ const str = (v, n) => (typeof v === 'string' ? v.slice(0, n) : null);
89
+ return list
90
+ .filter((x) => x && typeof x.file === 'string' && typeof x.kind === 'string')
91
+ .slice(0, 200)
92
+ .map((x) => ({ file: str(x.file, 200), line: Number.isInteger(x.line) ? x.line : null, statement: str(x.statement, 300), target: str(x.target, 200), rows: typeof x.rows === 'number' ? x.rows : null, approx: Boolean(x.approx), kind: str(x.kind, 40), loss: Boolean(x.loss), decision: str(x.decision, 20), message: str(x.message, 400) }));
93
+ }
94
+
77
95
  /** Avertissement de l'API (poad.io) ramené à la règle du CLI (utils/api-exposure) : textes en anglais */
78
96
  function exposureOf(x) {
79
97
  if (!x || typeof x !== 'object' || !Array.isArray(x.items)) return null;
@@ -101,7 +119,7 @@ function gitState(dir) {
101
119
  }
102
120
 
103
121
  module.exports = (args, raw) =>
104
- require('../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['dry-run', 'allow-destructive'] }, async ({ opts, out }) => {
122
+ require('../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['dry-run', 'allow-destructive', 'accept-data-loss'] }, async ({ opts, out }) => {
105
123
  const path = require('path');
106
124
  const api = require('../utils/cloud/api');
107
125
  const cli = require('../utils/cloud/cli');
@@ -118,7 +136,9 @@ module.exports = (args, raw) =>
118
136
  // Tables de référence trop lourdes pour git : hors de l'archive, envoyées au magasin de références
119
137
  const large = refStore.largeFiles(poadDir);
120
138
  const ignored = refStore.ensureGitignore(poadDir, large);
121
- // --allow-destructive : accepté, sans effet (poad.io signale les migrations qui perdent des données, sans refuser)
139
+ // --allow-destructive (alias --accept-data-loss) : la production applique sans demander les migrations qui
140
+ // perdent des données ; sans lui, poad.io refuse (avant toute écriture) et le CLI demande dans un terminal
141
+ let allowLoss = Boolean(opts['allow-destructive'] || opts['accept-data-loss']);
122
142
 
123
143
  const env = await branches.resolve(id, { wanted: opts.env, root });
124
144
  let b;
@@ -158,22 +178,55 @@ module.exports = (args, raw) =>
158
178
  const route = `v1/projects/${api.enc(id)}/branches/${api.enc(env.branch)}`;
159
179
  // --env des commandes proposées : omis quand poad deploy l'aurait aussi omis (production par défaut)
160
180
  const where = env.source === 'option' || !env.production ? ` --env ${env.branch}` : '';
161
- const headers = {};
162
- if (sha) headers['x-poad-sha'] = sha;
163
- if (dryRun) headers['x-poad-dry-run'] = '1';
164
- let result = summarize(await api.call('POST', `${route}/deploy`, { body: b.tgz, contentType: 'application/gzip', headers, what: 'deploy', timeout: 300000 }));
165
-
166
- // Déploiement asynchrone : suivi jusqu'à son terme
167
- if (result.deploy_id && result.status && !DONE.includes(result.status)) {
168
- const started = Date.now();
169
- let last = result.status;
170
- out.log(chalk.grey(` deploy ${result.deploy_id}: ${last}…`));
171
- while (!DONE.includes(result.status)) {
172
- if (Date.now() - started > 15 * 60 * 1000) throw new api.CloudError(`Deploy ${result.deploy_id} still ${result.status} after 15 min: follow it on poad.io.`, { code: 'timeout' });
173
- await new Promise((r) => setTimeout(r, Number(process.env.POAD_DEPLOY_POLL_MS) || 2000));
174
- const next = summarize(await api.call('GET', `${route}/deploys/${api.enc(result.deploy_id)}`, { what: 'deploy status' }));
175
- result = { ...next, deploy_id: next.deploy_id || result.deploy_id };
176
- if (result.status !== last) out.log(chalk.grey(` deploy ${result.deploy_id}: ${(last = result.status)}`));
181
+ const send = async () => {
182
+ const headers = {};
183
+ if (sha) headers['x-poad-sha'] = sha;
184
+ if (dryRun) headers['x-poad-dry-run'] = '1';
185
+ if (allowLoss) headers['x-poad-allow-destructive'] = '1';
186
+ let r = summarize(await api.call('POST', `${route}/deploy`, { body: b.tgz, contentType: 'application/gzip', headers, what: 'deploy', timeout: 300000 }));
187
+ // Déploiement asynchrone : suivi jusqu'à son terme
188
+ if (r.deploy_id && r.status && !DONE.includes(r.status)) {
189
+ const started = Date.now();
190
+ let last = r.status;
191
+ out.log(chalk.grey(` deploy ${r.deploy_id}: ${last}…`));
192
+ while (!DONE.includes(r.status)) {
193
+ if (Date.now() - started > 15 * 60 * 1000) throw new api.CloudError(`Deploy ${r.deploy_id} still ${r.status} after 15 min: follow it on poad.io.`, { code: 'timeout' });
194
+ await new Promise((res) => setTimeout(res, Number(process.env.POAD_DEPLOY_POLL_MS) || 2000));
195
+ const next = summarize(await api.call('GET', `${route}/deploys/${api.enc(r.deploy_id)}`, { what: 'deploy status' }));
196
+ r = { ...next, deploy_id: next.deploy_id || r.deploy_id };
197
+ if (r.status !== last) out.log(chalk.grey(` deploy ${r.deploy_id}: ${(last = r.status)}`));
198
+ }
199
+ }
200
+ return r;
201
+ };
202
+ let result = await send();
203
+ const lossLines = (r) => require('../utils/migrate-run').dataLossLines(r.data_loss, chalk, { production: env.production });
204
+
205
+ // Production : des migrations perdent des données, poad.io a refusé avant toute écriture. Dans un terminal :
206
+ // ce qui serait perdu, puis la question ; oui : même envoi avec x-poad-allow-destructive. Sinon : refus (code 4).
207
+ let lossRefused = false;
208
+ let lossShown = false;
209
+ if (result.refused === 'destructive_migrations' && !allowLoss && !dryRun) {
210
+ out.log(' ');
211
+ for (const l of lossLines(result)) out.log(l);
212
+ lossShown = true;
213
+ const lost = result.data_loss.filter((d) => d.loss && d.decision === 'confirm');
214
+ const total = lost.reduce((n, d) => n + (d.rows || 0), 0);
215
+ if (cli.interactive() && !out.json) {
216
+ const { confirm: ask } = require('@inquirer/prompts');
217
+ out.log(' ');
218
+ const ok = await ask({ message: `Apply anyway on production (${env.branch})? ${lost.length} statement(s), ${total.toLocaleString('en-US')}${lost.some((d) => d.approx || d.rows === null) ? '+' : ''} row(s) or value(s) lost (a backup is taken first).`, default: false }).catch(() => false);
219
+ if (ok) {
220
+ allowLoss = true;
221
+ result = await send();
222
+ } else {
223
+ out.log(chalk.grey(' Cancelled: nothing was changed.'));
224
+ lossRefused = true;
225
+ }
226
+ } else {
227
+ out.log(chalk.redBright(' Refused: these migrations lose data on production. Nothing was changed.'));
228
+ out.log(chalk.grey(' Run poad deploy in a terminal to confirm, or add --allow-destructive.'));
229
+ lossRefused = true;
177
230
  }
178
231
  }
179
232
 
@@ -182,12 +235,17 @@ module.exports = (args, raw) =>
182
235
  for (const n of m.applied) out.log(` ${chalk.greenBright('✔')} ${n}`);
183
236
  for (const n of m.pending) out.log(` ${chalk.yellow('○')} ${n} ${chalk.grey(dryRun ? '(would be applied)' : '(pending)')}`);
184
237
  for (const e of m.errors) {
238
+ // Refus pour pertes de données : déjà détaillé (et demandé) plus haut
239
+ if (e.code === 'destructive_migrations' && result.data_loss.length) continue;
185
240
  out.log(` ${chalk.redBright('✕')} ${e.migration ? chalk.bold(e.migration) + ': ' : ''}${e.message}`);
186
241
  // Refus : lesquelles ; migrations manquantes ou hors d'ordre : la commande qui lève le refus
187
242
  for (const f of e.files || []) out.log(` ${chalk.yellow(f)}`);
188
243
  for (const l of refusalLines(e, { env: env.branch, where, chalk })) out.log(l);
189
244
  }
245
+ // Pertes de données (sauf si déjà montrées avec le refus) : fichier, instruction, nombre de lignes
246
+ if (!result.refused && !lossShown) for (const l of lossLines(result)) out.log(l);
190
247
  for (const w of result.warnings || []) {
248
+ if (w.code === 'data_loss' && result.data_loss.length) continue;
191
249
  out.log(` ${chalk.yellowBright('⚠')} ${w.message}`);
192
250
  for (const f of w.files) out.log(` ${chalk.yellow(f)}`);
193
251
  }
@@ -202,7 +260,8 @@ module.exports = (args, raw) =>
202
260
  }
203
261
 
204
262
  out.log(' ');
205
- if (result.failed) out.log(chalk.redBright(` Deploy failed${references && references.failed ? ': a reference table could not be loaded' : result.message ? `: ${result.message}` : ''}.`));
263
+ if (lossRefused) out.log(chalk.redBright(' Deploy refused: pending migrations lose data on production.'));
264
+ else if (result.failed) out.log(chalk.redBright(` Deploy failed${references && references.failed ? ': a reference table could not be loaded' : result.message ? `: ${result.message}` : ''}.`));
206
265
  else if (dryRun && large.length) out.log(`${chalk.greenBright('✔')} Dry run: nothing changed on ${env.branch}. ${large.map((f) => f.target).join(', ')} would go to the reference store, then be loaded.`);
207
266
  else if (dryRun) out.log(`${chalk.greenBright('✔')} Dry run: nothing changed on ${env.branch}.`);
208
267
  else out.log(`${chalk.greenBright('✔')} Deployed to ${env.branch}${result.deploy_id ? chalk.grey(` (${result.deploy_id})`) : ''}.`);
@@ -225,7 +284,7 @@ module.exports = (args, raw) =>
225
284
  large_references: large.map((f) => ({ path: `poad/${f.rel}`, bytes: f.size, target: f.target })),
226
285
  references,
227
286
  });
228
- return result.failed ? api.EXIT.failed : 0;
287
+ return lossRefused ? api.EXIT.confirm : result.failed ? api.EXIT.failed : 0;
229
288
  });
230
289
 
231
290
  module.exports.summarize = summarize;
@@ -1,4 +1,5 @@
1
- // poad migrate : applique les migrations en attente de poad/migrations
1
+ // poad migrate [--dry-run] [--json] : applique les migrations en attente de poad/migrations (avant : ce qu'elles
2
+ // perdent sur la base, utils/data-loss.js, avertissement seulement en local)
2
3
  // poad migrate pull | list | renumber : poad/migrations face à poad.io (migration-pull.js, migrate-cloud.js)
3
4
  module.exports = async (args, raw = []) => {
4
5
  if (raw[0] === 'pull') return require('./migration-pull')(raw.slice(1));
@@ -30,10 +31,13 @@ module.exports = async (args, raw = []) => {
30
31
  let ok;
31
32
  let refOk = true;
32
33
  try {
33
- ok = await require('../utils/migrate-run')(root, config, { report, exposureList: true });
34
+ // --dry-run : migrations en attente et ce qu'elles perdraient (comptées sur la base), rien d'appliqué
35
+ const dryRun = process.argv.includes('--dry-run');
36
+ ok = await require('../utils/migrate-run')(root, config, { report, exposureList: true, dryRun });
37
+ if (dryRun) report.dry_run = true;
34
38
  // Tables de référence : après les migrations, quand leur structure est à jour
35
39
  // --force-reference : le fichier fait foi même s'il retire beaucoup de lignes (garde-fou de l'engine passé)
36
- if (ok) refOk = await require('../utils/reference').sync(root, config, { force: process.argv.includes('--force-reference') });
40
+ if (ok && !dryRun) refOk = await require('../utils/reference').sync(root, config, { force: process.argv.includes('--force-reference') });
37
41
  } finally {
38
42
  console.log = log;
39
43
  }
@@ -107,6 +107,15 @@ function fakeCloud(t, behaviour = {}) {
107
107
  if (req.method === 'POST' && m[2] === '/deploy') {
108
108
  const dry = req.headers['x-poad-dry-run'] === '1';
109
109
  if (behaviour.refuse) return send(res, 200, { deploy_id: 'dr', outcome: 'refused', dry_run: dry, migrations_applied: [], migrations_pending: [], errors: [behaviour.refuse] });
110
+ // Pertes de données (push.sh, control/data-loss.cjs) : production refusée sans x-poad-allow-destructive
111
+ if (behaviour.dataLoss) {
112
+ const prod = branch === 'main';
113
+ const allow = req.headers['x-poad-allow-destructive'] === '1';
114
+ const item = (decision) => ({ file: '20261204212826_sans_fichier.sql', line: 2, statement: 'alter table public.documents drop column fichier', target: 'public.documents.fichier', rows: 1240, approx: false, kind: 'drop_column', loss: true, decision, message: 'DROP COLUMN public.documents.fichier — 1,240 non-null value(s) will be lost' });
115
+ const summary = { message: 'pending migrations lose data or break API clients', files: ['20261204212826_sans_fichier.sql'], code: 'data_loss' };
116
+ if (prod && !allow && !dry) return send(res, 200, { deploy_id: 'dl', outcome: 'refused', migrations_applied: [], migrations_pending: ['20261204212826_sans_fichier.sql'], errors: [{ code: 'destructive_migrations', message: 'pending migrations lose data on production', files: ['20261204212826_sans_fichier.sql'] }], warnings: [], data_loss: [item('confirm')] });
117
+ return send(res, 200, { deploy_id: 'dl', outcome: 'success', dry_run: dry, migrations_applied: dry ? [] : ['20261204212826_sans_fichier.sql'], migrations_pending: dry ? ['20261204212826_sans_fichier.sql'] : [], errors: [], warnings: [summary], data_loss: [item(!prod ? 'warn' : allow ? 'accepted' : 'confirm')] });
118
+ }
110
119
  if (behaviour.async) {
111
120
  state.deploys.d1 = 0;
112
121
  // La forme réelle de poad.io (control/server.mjs, deployView) : outcome, migrations_applied…
@@ -827,3 +836,44 @@ test('pendingToRenumber : pure', () => {
827
836
  assert.deepStrictEqual(pendingToRenumber([l('20261109000000'), l('20261101000000'), l('20261111000000')], remote).map((m) => m.version), ['20261101000000', '20261109000000', '20261111000000']);
828
837
  assert.deepStrictEqual(pendingToRenumber([l('20261101000000')], []), []);
829
838
  });
839
+
840
+ test('deploy : pertes de données (à la Prisma) : recette avertie ; production refusée hors terminal (code 4), --allow-destructive passe ; --json data_loss', async (t) => {
841
+ const box = sandbox(t);
842
+ const cloud = await fakeCloud(t, { dataLoss: true });
843
+ await login(box, cloud);
844
+ await poad(box, cloud.api, ['link', PID]);
845
+ git(box.app, 'commit', '-qam', 'link');
846
+
847
+ // Recette : avertissement avec fichier, instruction et nombre ; jamais de question
848
+ const dev = await poad(box, cloud.api, ['deploy', '--env', 'dev']);
849
+ assert.strictEqual(dev.status, 0, dev.all);
850
+ assert.match(dev.stdout, /20261204212826_sans_fichier\.sql:2\s+DROP COLUMN public\.documents\.fichier — 1,240 non-null value\(s\) will be lost/);
851
+ assert.match(dev.stdout, /alter table public\.documents drop column fichier/);
852
+ assert.doesNotMatch(dev.stdout, /pending migrations lose data or break API clients\n/, 'résumé des anciens CLI remplacé par le détail');
853
+
854
+ // Production, hors terminal, --yes : refus (--yes n'accepte pas une perte de données), rien appliqué
855
+ const refused = await poad(box, cloud.api, ['deploy', '--yes']);
856
+ assert.strictEqual(refused.status, 4, refused.all);
857
+ assert.match(refused.stdout, /1,240 non-null value\(s\) will be lost/);
858
+ assert.match(refused.stdout, /--allow-destructive/);
859
+ assert.match(refused.stdout, /Deploy refused/);
860
+ assert.strictEqual(cloud.requests.filter((q) => q.route.endsWith('/main/deploy')).length, 1, 'un seul envoi');
861
+
862
+ const j = jsonOf(await poad(box, cloud.api, ['deploy', '--yes', '--json']));
863
+ assert.strictEqual(j.refused, 'destructive_migrations');
864
+ assert.deepStrictEqual(Object.fromEntries(['file', 'statement', 'target', 'rows', 'kind'].map((k) => [k, j.data_loss[0][k]])), { file: '20261204212826_sans_fichier.sql', statement: 'alter table public.documents drop column fichier', target: 'public.documents.fichier', rows: 1240, kind: 'drop_column' });
865
+
866
+ // --dry-run : la même chose, sans refus ni envoi de l'en-tête
867
+ const dry = await poad(box, cloud.api, ['deploy', '--dry-run']);
868
+ assert.strictEqual(dry.status, 0, dry.all);
869
+ assert.match(dry.stdout, /1,240 non-null value\(s\) will be lost/);
870
+ assert.match(dry.stdout, /data is lost only after a confirmation/);
871
+
872
+ // --allow-destructive (ou --accept-data-loss) : l'en-tête part, déployé
873
+ for (const flag of ['--allow-destructive', '--accept-data-loss']) {
874
+ const ok = await poad(box, cloud.api, ['deploy', '--yes', flag]);
875
+ assert.strictEqual(ok.status, 0, ok.all);
876
+ assert.strictEqual(cloud.requests.filter((q) => q.route.endsWith('/main/deploy')).at(-1).headers['x-poad-allow-destructive'], '1');
877
+ assert.match(ok.stdout, /Deployed to main/);
878
+ }
879
+ });
@@ -0,0 +1,112 @@
1
+ // Avertissement à la Prisma (utils/data-loss.js) : lecture des migrations, décision. Sans base : les résultats
2
+ // des requêtes sont donnés à la main (le comptage réel est essayé sur un projet jetable, poad migrate).
3
+ const test = require('node:test');
4
+ const assert = require('node:assert');
5
+ const dl = require('../utils/data-loss');
6
+
7
+ const kinds = (sql) => dl.analyze([{ file: '20261204212826_x.sql', sql }]).map((f) => `${f.kind} ${f.schema}${f.table ? '.' + f.table : ''}${f.column ? '.' + f.column : ''}`);
8
+
9
+ test('commentaires, chaînes et corps de fonctions ($$, BEGIN ATOMIC) ignorés', () => {
10
+ const sql = `-- drop table a;
11
+ /* drop table b; /* imbriqué */ truncate c; */
12
+ create function f() returns void language plpgsql as $$ begin drop table z; delete from w; end $$;
13
+ create function g() returns void language plpgsql as $body$ begin execute 'truncate q'; end $body$;
14
+ do $x$ begin alter table t drop column c; end $x$;
15
+ select 'drop table k', E'it\\'s; drop table j', "drop table";
16
+ create function h() returns int language sql begin atomic select case when true then 1 end; delete from inatomic; end;
17
+ drop table vraie;`;
18
+ assert.deepStrictEqual(kinds(sql), ['drop_table public.vraie']);
19
+ });
20
+
21
+ test('instructions repérées avec leur cible', () => {
22
+ const sql = `ALTER TABLE public.documents DROP COLUMN fichier, ADD COLUMN x int DEFAULT f(1, 2), ALTER COLUMN n TYPE numeric(5,2) USING n::numeric;
23
+ alter table t drop constraint k, alter column c drop default, alter column d set not null;
24
+ truncate table a, only s.b restart identity;
25
+ delete from logs; delete from s.l2 where id in (select id from z);
26
+ with d as (delete from old returning *) select 1;
27
+ drop table if exists t1, "Mixte".T2 cascade; drop schema arch cascade;
28
+ alter table x rename column a to b; alter table x rename to y; alter table x rename constraint k to l;
29
+ drop view if exists v1; drop function g(int, text);`;
30
+ assert.deepStrictEqual(kinds(sql), [
31
+ 'drop_column public.documents.fichier',
32
+ 'alter_type public.documents.n',
33
+ 'truncate public.a',
34
+ 'truncate s.b',
35
+ 'delete public.logs',
36
+ 'delete_where s.l2',
37
+ 'delete public.old',
38
+ 'drop_table public.t1',
39
+ 'drop_table Mixte.t2',
40
+ 'drop_schema arch',
41
+ 'rename_column public.x.a',
42
+ 'rename_table public.x',
43
+ 'drop_view public.v1',
44
+ 'drop_function public.g',
45
+ ]);
46
+ const [f] = dl.analyze([{ file: 'a.sql', sql: '\n\nalter table documents\n drop column fichier; -- fin' }]);
47
+ assert.strictEqual(f.line, 3);
48
+ assert.strictEqual(f.statement, 'alter table documents drop column fichier');
49
+ });
50
+
51
+ test('renommage dans le lot : la cible est cherchée sous son nom sur la base ; vue recréée : silence', () => {
52
+ const f = dl.analyze([
53
+ { file: '1.sql', sql: 'alter table old_name rename to new_name;' },
54
+ { file: '2.sql', sql: 'alter table new_name drop column c; drop view if exists v; create or replace view v as select 1;' },
55
+ ]);
56
+ assert.deepStrictEqual(f[1].db, { schema: 'public', table: 'old_name', column: 'c' });
57
+ assert.strictEqual(f[2].recreated, true);
58
+ });
59
+
60
+ const one = (sql, result, opts) => {
61
+ const findings = dl.analyze([{ file: '20261204212826_x.sql', sql }]);
62
+ return dl.decide(findings, [result], opts)[0];
63
+ };
64
+
65
+ test('décision : base neuve (cible absente) et table vide : silence', () => {
66
+ assert.strictEqual(one('drop table documents;', { exists: false }).decision, 'silent');
67
+ assert.strictEqual(one('drop table documents;', { exists: false }, { production: true }).reason, 'target_absent');
68
+ assert.strictEqual(one('alter table documents drop column fichier;', { exists: true, relkind: 'r', column: true, rows: 0 }, { production: true }).decision, 'silent');
69
+ assert.strictEqual(one('alter table documents drop column fichier;', { exists: true, relkind: 'r', column: false, rows: null }).reason, 'target_absent');
70
+ assert.strictEqual(one('drop table ft;', { exists: true, relkind: 'f', rows: null }).reason, 'foreign_table');
71
+ });
72
+
73
+ test('décision : table pleine + DROP COLUMN : avertissement avec le nombre ; production : confirmation ; acceptée', () => {
74
+ const r = { exists: true, relkind: 'r', column: true, rows: 1240 };
75
+ const w = one('alter table public.documents drop column fichier;', r);
76
+ assert.strictEqual(w.decision, 'warn');
77
+ assert.strictEqual(w.message, 'DROP COLUMN public.documents.fichier — 1,240 non-null value(s) will be lost');
78
+ assert.strictEqual(one('alter table public.documents drop column fichier;', r, { production: true }).decision, 'confirm');
79
+ assert.strictEqual(one('alter table public.documents drop column fichier;', r, { production: true, accepted: true }).decision, 'accepted');
80
+ // Comptage impossible (délai) : prudence, comme une perte
81
+ assert.strictEqual(one('truncate documents;', null, { production: true }).decision, 'confirm');
82
+ // JSON : { file, statement, target, rows, kind }
83
+ const [j] = dl.jsonOf([w]);
84
+ assert.deepStrictEqual([j.file, j.statement, j.target, j.rows, j.kind], ['20261204212826_x.sql', 'alter table public.documents drop column fichier', 'public.documents.fichier', 1240, 'drop_column']);
85
+ });
86
+
87
+ test('décision : conversions sans perte, renommages et vues hors API', () => {
88
+ assert.strictEqual(one('alter table t alter column c type text;', { exists: true, relkind: 'r', column: true, rows: 5, type: 'character varying(20)' }).reason, 'lossless_conversion');
89
+ assert.strictEqual(one('alter table t alter column c type bigint;', { exists: true, relkind: 'r', column: true, rows: 5, type: 'integer' }).reason, 'lossless_conversion');
90
+ assert.strictEqual(one('alter table t alter column c type integer;', { exists: true, relkind: 'r', column: true, rows: 5, type: 'text' }, { production: true }).decision, 'confirm');
91
+ const ren = one('alter table t rename column a to b;', { exists: true, relkind: 'r', column: true, rows: 5 }, { production: true });
92
+ assert.deepStrictEqual([ren.decision, ren.loss], ['warn', false]);
93
+ assert.strictEqual(one('drop view v;', { exists: true, relkind: 'v', api: false }).reason, 'not_exposed');
94
+ assert.strictEqual(one('drop view v;', { exists: true, relkind: 'v', api: true }).decision, 'warn');
95
+ assert.strictEqual(one('drop view private.v;', { exists: true, relkind: 'v', api: true }).reason, 'not_exposed');
96
+ });
97
+
98
+ test('script psql et lecture de sa sortie ; ligne de journal sans instruction', () => {
99
+ const findings = dl.analyze([{ file: 'x.sql', sql: "alter table documents drop column fichier; delete from notes where body = 'secret';" }]);
100
+ const s = dl.script(dl.checks(findings));
101
+ assert.match(s, /^begin transaction read only;/);
102
+ assert.match(s, /statement_timeout = '3s'/);
103
+ assert.doesNotMatch(s, /secret/);
104
+ const res = dl.parseOutput('0 e {"exists":true,"relkind":"r","column":true,"rows":3}\n1 f {"exists":true,"relkind":"r","rows":7}\n', 2);
105
+ assert.strictEqual(res[0].rows, 3);
106
+ assert.deepStrictEqual([res[1].rows, res[1].approx], [7, true]);
107
+ const d = dl.decide(findings, res);
108
+ const a = dl.logAttrs(d[1]);
109
+ assert.strictEqual(a.event, 'migration_data_loss_check');
110
+ assert.strictEqual(a.target, 'public.notes');
111
+ assert.doesNotMatch(JSON.stringify(a) + dl.logMsg(d[1]), /secret|body/);
112
+ });
@@ -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 };
@@ -328,14 +328,16 @@ const sheets = {
328
328
  ],
329
329
  },
330
330
  migrate: {
331
- usage: ['poad migrate', 'poad migrate --force-reference', 'poad migrate --json', 'poad migrate list [--env <name>] [--json]', 'poad migrate pull [--env <name>] [--yes] [--dry-run] [--json]', 'poad migrate renumber <version|file> [--env <name>] [--yes] [--json]', 'poad migrate renumber --pending [--env <name>] [--yes] [--json]'],
331
+ usage: ['poad migrate', 'poad migrate --dry-run', 'poad migrate --force-reference', 'poad migrate --json', 'poad migrate list [--env <name>] [--json]', 'poad migrate pull [--env <name>] [--yes] [--dry-run] [--json]', 'poad migrate renumber <version|file> [--env <name>] [--yes] [--json]', 'poad migrate renumber --pending [--env <name>] [--yes] [--json]'],
332
332
  text: [
333
333
  'Apply pending migrations of poad/migrations and named queries of poad/queries, then the reference tables of poad/reference (the file is the source of truth).',
334
+ 'Before applying, reads the pending migrations (never run for this) and counts on the database what they would lose: DROP TABLE, DROP COLUMN (non-null values), ALTER COLUMN … TYPE, TRUNCATE, DELETE, DROP SCHEMA, and what breaks API clients (RENAME TABLE / COLUMN, DROP VIEW / FUNCTION served to anon or authenticated). Silent when the target does not exist yet (created by the same batch) or is empty; otherwise a warning with file, statement and number of rows. Locally a warning only (poad deploy asks to confirm on production). Logs: poad logs cli event=migration_data_loss_check.',
334
335
  'Then warns (never blocks) about functions and views granted to anon or authenticated that the API does not serve them (403 not_exposed: SECURITY DEFINER functions, views without security_invoker, materialized views), each with its fix; the ones a migration just created also go to the log sink (poad logs cli event=api_exposure).',
335
336
  ],
336
337
  options: [
338
+ ['--dry-run', 'the pending migrations and the data they would lose (counted on the database), nothing applied'],
337
339
  ['--force-reference', 'also apply a reference file that would remove many rows: an empty file for a table that has rows, or more than 20% of its rows (refused otherwise, nothing removed)'],
338
- ['--json', 'one JSON object: applied, failed, pending, api_exposure (items with reason, roles, fix, created), unprotected tables'],
340
+ ['--json', 'one JSON object: applied, failed, pending, data_loss ([{ file, line, statement, target, rows, kind, decision }]), api_exposure (items with reason, roles, fix, created), unprotected tables'],
339
341
  ['list', 'poad/migrations against an environment of poad.io (--env, else the git branch, else main; the local engine when the project is not linked): applied on both sides, pending here, missing here, written on poad.io without being applied, same version under another name, changed since applied, older than the last one applied (poad deploy refuses it); with version, name and date'],
340
342
  ['pull', 'same as poad migration pull'],
341
343
  ['renumber <version>', 'give a pending migration a version after the last one of the environment and of the folder (the file is renamed, its SQL is unchanged) when poad deploy refuses it as out of order. Refused when it is applied on any environment of poad.io; applied on the local engine only: the local history follows. Logs: poad logs cli event=migration_renumbered'],
@@ -482,7 +484,7 @@ Object.assign(sheets, {
482
484
  notes: [EXIT_NOTE],
483
485
  },
484
486
  deploy: {
485
- usage: ['poad deploy [--env <name>] [--dry-run] [--yes] [--json]'],
487
+ usage: ['poad deploy [--env <name>] [--dry-run] [--yes] [--allow-destructive] [--json]'],
486
488
  text: [
487
489
  'Send the poad/ folder to an environment of the linked poad.io project, which applies its pending migrations and loads its functions, flows, API, auth and storage settings.',
488
490
  'Sent: migrations, auth, storage, functions, flows, api, reference, variables (defaults, no secret), types, credentials/manifest.json (names and types only, never values), seed.sql, config.toml (without any secret key). Never sent: poad/secrets.toml, .env files, data/, backups/, node_modules, symbolic links. If a value of poad/secrets.toml appears in a file to send, nothing is sent.',
@@ -490,11 +492,13 @@ Object.assign(sheets, {
490
492
  options: [
491
493
  ['--env <name>', 'the environment (default: the current git branch if it exists on poad.io, else main)'],
492
494
  ['--dry-run', 'poad.io says what it would do (migrations to apply), nothing changes'],
493
- ['--yes', 'no question for production (required outside a terminal)'],
495
+ ['--yes', 'no question for production (required outside a terminal); does not accept a data loss'],
496
+ ['--allow-destructive', 'production: apply migrations that lose data without asking (required outside a terminal when they do); alias --accept-data-loss'],
494
497
  PROJECT_OPT,
495
498
  JSON_OPT,
496
499
  ],
497
500
  notes: [
501
+ 'Before applying, poad.io counts on the database of the environment what the pending migrations would lose (DROP TABLE, DROP COLUMN, ALTER COLUMN … TYPE, TRUNCATE, DELETE, DROP SCHEMA; RENAME and DROP VIEW / FUNCTION served by the API break clients): nothing is said when the target is created by the same deploy or is empty; otherwise file, statement and number of rows (data_loss in --json, --dry-run included). Production: a loss of data needs a confirmation in a terminal, or --allow-destructive; refused otherwise (exit code 4), nothing changed. Other environments: a warning.',
498
502
  'Production (main): a summary, then a confirmation (none for --dry-run, which changes nothing). Uncommitted changes in poad/: a warning, and no commit id is sent (the commit id is sent when poad/ is clean).',
499
503
  EXIT_NOTE,
500
504
  ],
@@ -2,7 +2,7 @@
2
2
  const path = require('path');
3
3
 
4
4
  // report : objet rempli pour --json (applied, failed, api_exposure, unprotected, queries)
5
- module.exports = async (root, config, { quietWhenNone = false, report = null, exposureList = false } = {}) => {
5
+ module.exports = async (root, config, { quietWhenNone = false, report = null, exposureList = false, dryRun = false, via = 'poad migrate' } = {}) => {
6
6
  const chalk = require('chalk-v2');
7
7
  const migrations = require('./migrations');
8
8
  const rel = (p) => path.relative(process.cwd(), p);
@@ -10,6 +10,12 @@ module.exports = async (root, config, { quietWhenNone = false, report = null, ex
10
10
  let result;
11
11
  try {
12
12
  result = await migrations.migrate(root, config, {
13
+ dryRun,
14
+ via,
15
+ // Avant la première migration appliquée : ce qui sera perdu (silence si la cible est absente ou vide)
16
+ onDataLoss: (list) => {
17
+ for (const l of dataLossLines(list, chalk, { local: true })) console.log(l);
18
+ },
13
19
  onApply: (m) => console.log(`${chalk.greenBright('✔')} ${chalk.bold(m.file)}`),
14
20
  });
15
21
  } catch (err) {
@@ -19,6 +25,7 @@ module.exports = async (root, config, { quietWhenNone = false, report = null, ex
19
25
  const { applied, failed, state } = result;
20
26
  if (report) {
21
27
  Object.assign(report, {
28
+ data_loss: require('./data-loss').jsonOf(result.dataLoss || []),
22
29
  applied: applied.map((m) => m.file),
23
30
  failed: failed ? { file: failed.migration.file, message: failed.message } : null,
24
31
  pending: state.pending.filter((m) => !applied.includes(m)).map((m) => m.file),
@@ -28,6 +35,11 @@ module.exports = async (root, config, { quietWhenNone = false, report = null, ex
28
35
  });
29
36
  }
30
37
 
38
+ if (dryRun) {
39
+ for (const m of state.pending) console.log(` ${chalk.yellow('○')} ${m.file} ${chalk.grey('(would be applied)')}`);
40
+ console.log(state.pending.length ? chalk.bold(` Dry run: ${state.pending.length} pending migration(s), nothing applied.`) : chalk.grey(` Database up to date (${state.list.length} migration(s)).`));
41
+ return true;
42
+ }
31
43
  for (const m of state.changed) {
32
44
  console.log(chalk.yellowBright(` ${m.file} changed after it was applied: it is not replayed. Write a new migration instead.`));
33
45
  }
@@ -69,3 +81,22 @@ module.exports = async (root, config, { quietWhenNone = false, report = null, ex
69
81
  for (const l of require('./api-exposure').migrateLines(result.apiExposure, chalk, { full: exposureList || applied.length > 0 })) console.log(l);
70
82
  return qr.errors.length === 0;
71
83
  };
84
+
85
+ /**
86
+ * Lignes d'avertissement des pertes de données (utils/data-loss.js), partagées avec poad deploy :
87
+ * « ⚠ fichier:ligne DROP COLUMN public.t.c — 1,240 non-null value(s) will be lost », puis l'instruction.
88
+ * local : la base du poste (avertissement seul) ; sinon le mot de la décision de poad.io.
89
+ */
90
+ function dataLossLines(list, chalk, { local = false, production = false } = {}) {
91
+ const shown = (list || []).filter((d) => d && d.decision !== 'silent' && d.message);
92
+ if (!shown.length) return [];
93
+ const out = [`${chalk.yellowBright('⚠')} ${chalk.bold('Pending migrations lose data or break API clients:')}`];
94
+ for (const d of shown) {
95
+ out.push(` ${chalk.yellow(`${d.file}${d.line ? `:${d.line}` : ''}`)} ${d.loss ? chalk.yellowBright(d.message) : d.message}`);
96
+ if (d.statement) out.push(chalk.grey(` ${d.statement}`));
97
+ }
98
+ if (local) out.push(chalk.grey(' Local database: applied anyway. On the production of poad.io, poad deploy asks to confirm (or --allow-destructive).'));
99
+ else if (production && shown.some((d) => d.decision === 'confirm')) out.push(chalk.grey(' Production: data is lost only after a confirmation (terminal) or with --allow-destructive.'));
100
+ return out;
101
+ }
102
+ module.exports.dataLossLines = dataLossLines;
@@ -137,12 +137,17 @@ function lineOf(sql, position) {
137
137
  * transaction est annulée, les suivantes ne sont pas tentées).
138
138
  * Renvoie { applied: [...], failed: { migration, message } | null, state }.
139
139
  */
140
- async function migrate(root, config, { onApply } = {}) {
140
+ async function migrate(root, config, { onApply, onDataLoss, dryRun = false, via = 'poad migrate' } = {}) {
141
141
  const client = await connect(config);
142
142
  const applied = [];
143
143
  try {
144
144
  await client.query('select pg_advisory_lock($1)', [LOCK_ID]);
145
145
  const state = await status(root, client);
146
+ // Avant d'appliquer : ce que les migrations en attente perdent vraiment sur cette base (utils/data-loss.js).
147
+ // En local, un avertissement seulement (la confirmation est pour la production de poad.io, poad deploy).
148
+ const dataLoss = state.pending.length ? await dataLossCheck(client, state.pending, config, dryRun ? `${via} --dry-run` : via) : [];
149
+ if (onDataLoss) onDataLoss(dataLoss);
150
+ if (dryRun) return { applied, failed: null, state, dataLoss, dryRun: true };
146
151
  // Ce que l'API ne sert pas à anon ni à authenticated alors qu'ils en ont le droit, avant les migrations : ce
147
152
  // qu'elles font apparaître est signalé et va au puits de logs (event=api_exposure)
148
153
  const exposure = require('./api-exposure');
@@ -159,7 +164,7 @@ async function migrate(root, config, { onApply } = {}) {
159
164
  } catch (err) {
160
165
  await client.query('rollback').catch(() => {});
161
166
  const where = err.position ? ` (line ${lineOf(m.sql, err.position)})` : '';
162
- return { applied, failed: { migration: m, message: `${err.message}${where}` }, state };
167
+ return { applied, failed: { migration: m, message: `${err.message}${where}` }, state, dataLoss };
163
168
  }
164
169
  }
165
170
  // Empreinte de la structure après les migrations (journal des changements)
@@ -170,13 +175,34 @@ async function migrate(root, config, { onApply } = {}) {
170
175
  const unprotected = await unprotectedTables(client, exposedSchemas(config));
171
176
  const apiExposure = exposure.afterMigrate({ engine: config.engine, before, after: await exposure.query(client, exposedSchemas(config)) });
172
177
  if (apiExposure.created.length) await logApiExposure(client, apiExposure, applied);
173
- return { applied, failed: null, state, queries, unprotected, apiExposure };
178
+ return { applied, failed: null, state, queries, unprotected, apiExposure, dataLoss };
174
179
  } finally {
175
180
  await client.query('select pg_advisory_unlock($1)', [LOCK_ID]).catch(() => {});
176
181
  await client.end().catch(() => {});
177
182
  }
178
183
  }
179
184
 
185
+ /**
186
+ * Pertes de données des migrations en attente, comptées sur la base locale (lecture seule, délai court). Une ligne
187
+ * par constat dans le puits (service cli, event=migration_data_loss_check ; debug quand rien n'est perdu) : fichier,
188
+ * genre, cible, nombre de lignes, décision ; jamais d'instruction ni de valeur. Une erreur ici ne bloque jamais.
189
+ */
190
+ async function dataLossCheck(client, pending, config, via) {
191
+ const dl = require('./data-loss');
192
+ try {
193
+ const findings = dl.analyze(pending.map((m) => ({ file: m.file, sql: m.sql })));
194
+ if (!findings.length) return [];
195
+ const results = await dl.runChecks(client, dl.checks(findings));
196
+ const decided = dl.decide(findings, results, { production: false, exposedSchemas: exposedSchemas(config) });
197
+ const rows = decided.map((d) => [dl.levelOf(d), dl.logMsg(d), JSON.stringify(dl.logAttrs(d, { via, env: 'local' }))]);
198
+ for (const r of rows) await client.query("insert into _logs.entries (ts, level, service, msg, attrs) values (now(), $1, 'cli', $2, $3::jsonb)", r).catch(() => {});
199
+ return decided;
200
+ } catch {
201
+ await client.query('rollback').catch(() => {});
202
+ return [];
203
+ }
204
+ }
205
+
180
206
  /**
181
207
  * Puits de logs (service cli, event=api_exposure) : une migration vient de créer des fonctions ou vues accordées à
182
208
  * anon ou authenticated que l'API ne leur sert pas. Noms et raisons seulement, jamais de SQL ni de secret.