poad 2.21.0 → 2.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.21.0",
4
- "engine": "0.11.2",
3
+ "version": "2.23.0",
4
+ "engine": "0.13.0",
5
5
  "main": "index.js",
6
6
  "license": "MIT",
7
7
  "bin": {
@@ -44,16 +44,25 @@ module.exports = async (args = {}) => {
44
44
  return console.log(`${chalk.greenBright('✔')} ${c.entries.length} change(s) forgotten ${chalk.grey('(still in the database)')}.`);
45
45
  }
46
46
  if (!name) {
47
- console.log(chalk.bold(`${c.entries.length} structure change(s) not in a migration`));
47
+ const byId = new Map(c.entries.map((e) => [e.id, e]));
48
+ console.log(chalk.bold(`${c.units.length} structure change(s) not in a migration`));
48
49
  console.log(' ');
49
- for (const e of c.entries) {
50
+ for (const u of c.units) {
51
+ const e = byId.get(u.keep.length ? u.keep[u.keep.length - 1] : u.ids[u.ids.length - 1]);
50
52
  const when = new Date(e.at).toLocaleString();
51
- console.log(chalk.grey(`-- ${when} · ${e.role_name}${e.application ? ' · ' + e.application : ''} · ${(e.commands || []).join(', ')}`));
52
- console.log(String(e.statement).trim().replace(/;?\s*$/, ';'));
53
+ const group = u.effect === 'merged' ? chalk.cyanBright(` · ${u.ids.length} changes → ${u.result}`) : u.effect === 'none' ? chalk.yellowBright(` · ${u.ids.length} changes, no effect`) : '';
54
+ console.log(chalk.grey(`-- ${when} · ${e.role_name}${e.application ? ' · ' + e.application : ''} · ${(e.commands || []).join(', ')}`) + group);
55
+ if (u.effect === 'none') console.log(chalk.grey(`-- ${u.target}: nothing to write`));
56
+ for (const id of u.keep) console.log(String(byId.get(id).statement).trim().replace(/;?\s*$/, ';'));
53
57
  console.log(' ');
54
58
  }
55
59
  return console.log(chalk.grey(' "poad db diff <name>" writes them to poad/migrations (not replayed); "poad db diff --discard" forgets them.'));
56
60
  }
61
+ if (!c.sql.trim()) {
62
+ // Que des changements qui s'annulent : rien à écrire
63
+ await migrations.discardChanges(client, c.upTo);
64
+ return console.log(`${chalk.greenBright('✔')} ${c.entries.length} change(s) with no net effect: nothing to write, journal cleared.`);
65
+ }
57
66
  const file = await migrations.saveChanges(root, client, name, c.sql, c.upTo);
58
67
  console.log(`${chalk.greenBright('✔')} ${chalk.bold(path.relative(process.cwd(), file))} ${chalk.grey(`(${c.entries.length} change(s), already applied here)`)}`);
59
68
  console.log(chalk.grey(' Review it, then commit it with your branch.'));
@@ -0,0 +1,132 @@
1
+ // Copie de infra/services/meta/src/compact.ts (compilée en CommonJS) : garder
2
+ // les deux identiques, la console et poad db diff regroupent pareil.
3
+ "use strict";
4
+ // Regroupement des changements du journal avant d'en faire une migration.
5
+ //
6
+ // Pour les objets qui n'ont qu'un état (présent / absent, activé / désactivé),
7
+ // une suite de changements se résume à son effet net :
8
+ // extension activer, désactiver, activer -> le dernier create
9
+ // activer, désactiver -> sans effet
10
+ // RLS d'une table enable, disable, enable -> le dernier enable
11
+ // enable, disable -> sans effet
12
+ // politique, index create, alter, drop -> sans effet
13
+ // drop, create -> drop puis create (remplacement)
14
+ // create, alter -> gardés tels quels
15
+ // Tout le reste (tables, colonnes, fonctions, renommages…) est gardé tel quel,
16
+ // dans l'ordre : deviner y ferait perdre une intention ou des données.
17
+ //
18
+ // Un changement n'est regroupé que s'il ne touche qu'un objet, et un groupe
19
+ // n'est résumé que si rien ne s'intercale entre ses entrées (sauf des
20
+ // politiques ou du RLS, dont rien ne dépend) : activer vector, créer une table
21
+ // qui l'utilise, la supprimer, désactiver vector garde tout, sinon la table
22
+ // serait créée sans son extension. Les entrées
23
+ // écartées (superseded) restent dans le journal jusqu'à ce que la migration
24
+ // les emporte (ids) ; seules celles de keep écrivent du SQL.
25
+ //
26
+ // Même code dans le CLI (utils/compact.js) : poad db diff regroupe pareil.
27
+ Object.defineProperty(exports, "__esModule", { value: true });
28
+ exports.compact = exports.classify = void 0;
29
+ // Interrupteurs API et Temps réel de la console : leurs formes exactes seulement
30
+ // (un GRANT partiel écrit à la main reste tel quel)
31
+ const API_ON_RE = /^\s*grant\s+select,\s*insert,\s*update,\s*delete\s+on\s+table\s+(.+?)\s+to\s+anon,\s*authenticated\s*;?\s*$/is;
32
+ const API_OFF_RE = /^\s*revoke\s+all\s+on\s+table\s+(.+?)\s+from\s+anon,\s*authenticated\s*;?\s*$/is;
33
+ const RLS_RE = /^\s*alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?(.+?)\s+(enable|disable)\s+row\s+level\s+security\s*;?\s*$/is;
34
+ /** Objet unique et opération d'une entrée, ou null si elle n'est pas regroupable */
35
+ const classify = (e) => {
36
+ const objs = e.objects.filter((o) => Boolean(o));
37
+ if (e.commands.length !== 1 || objs.length !== 1)
38
+ return null;
39
+ const [cmd] = e.commands;
40
+ const target = objs[0];
41
+ const by = {
42
+ 'CREATE EXTENSION': ['extension', 'on'],
43
+ 'DROP EXTENSION': ['extension', 'off'],
44
+ 'CREATE POLICY': ['policy', 'on'],
45
+ 'ALTER POLICY': ['policy', 'alter'],
46
+ 'DROP POLICY': ['policy', 'off'],
47
+ 'CREATE INDEX': ['index', 'on'],
48
+ 'DROP INDEX': ['index', 'off'],
49
+ };
50
+ if (by[cmd])
51
+ return { kind: by[cmd][0], target, op: by[cmd][1] };
52
+ if (cmd === 'ALTER PUBLICATION')
53
+ return { kind: 'realtime', target, op: 'on' };
54
+ if (cmd === 'DROP PUBLICATION RELATION')
55
+ return { kind: 'realtime', target, op: 'off' };
56
+ if (cmd === 'GRANT' && API_ON_RE.test(e.statement))
57
+ return { kind: 'api', target, op: 'on' };
58
+ if (cmd === 'REVOKE' && API_OFF_RE.test(e.statement))
59
+ return { kind: 'api', target, op: 'off' };
60
+ if (cmd === 'ALTER TABLE') {
61
+ const m = RLS_RE.exec(e.statement);
62
+ if (m)
63
+ return { kind: 'rls', target, op: m[2].toLowerCase() === 'enable' ? 'on' : 'off' };
64
+ }
65
+ return null;
66
+ };
67
+ exports.classify = classify;
68
+ const RESULT = {
69
+ extension: ['activée', 'désactivée'],
70
+ rls: ['RLS activé', 'RLS désactivé'],
71
+ api: ['publiée dans l’API', 'retirée de l’API'],
72
+ realtime: ['temps réel activé', 'temps réel désactivé'],
73
+ policy: ['créée', 'supprimée'],
74
+ index: ['créé', 'supprimé'],
75
+ };
76
+ /** Effet net d'une suite d'opérations sur un même objet */
77
+ const net = (kind, items) => {
78
+ const ops = items.map((i) => i.op);
79
+ const before = ops[0] === 'on' ? 'off' : 'on'; // create : l'objet n'existait pas
80
+ const after = ops.at(-1) === 'off' ? 'off' : 'on';
81
+ const lastOff = ops.lastIndexOf('off');
82
+ const lastOn = ops.lastIndexOf('on');
83
+ const stateOnly = kind === 'extension' || kind === 'rls' || kind === 'api' || kind === 'realtime';
84
+ let keep;
85
+ if (before === 'off' && after === 'off')
86
+ keep = [];
87
+ else if (before === 'off')
88
+ keep = items.slice(lastOn).map((i) => i.id); // le dernier create et ce qui le suit
89
+ else if (after === 'off')
90
+ keep = [items[lastOff].id]; // un seul drop
91
+ else if (lastOff < 0)
92
+ keep = items.map((i) => i.id); // que des alter
93
+ else if (stateOnly)
94
+ keep = []; // désactivé puis réactivé : comme avant
95
+ else
96
+ keep = items.slice(lastOff).map((i) => i.id); // remplacement : drop puis create
97
+ const effect = items.length === 1 ? 'one' : keep.length ? 'merged' : 'none';
98
+ return { keep, effect, result: effect === 'merged' ? RESULT[kind][after === 'on' ? 0 : 1] : null };
99
+ };
100
+ /** Unités à présenter, dans l'ordre du journal (position de leur dernière entrée gardée) */
101
+ const compact = (entries) => {
102
+ const groups = new Map();
103
+ const units = [];
104
+ for (const e of entries) {
105
+ const c = (0, exports.classify)(e);
106
+ if (!c) {
107
+ units.push({ ids: [e.id], keep: [e.id], kind: null, target: null, effect: 'one', result: null, at: e.id });
108
+ continue;
109
+ }
110
+ const key = `${c.kind}:${c.target}`;
111
+ const g = groups.get(key) ?? { kind: c.kind, target: c.target, items: [] };
112
+ g.items.push({ id: e.id, op: c.op });
113
+ groups.set(key, g);
114
+ }
115
+ const kindOf = new Map(entries.map((e) => [e.id, (0, exports.classify)(e)?.kind ?? null]));
116
+ for (const g of groups.values()) {
117
+ const ids = g.items.map((i) => i.id);
118
+ const mine = new Set(ids);
119
+ const between = entries.filter((e) => e.id > ids[0] && e.id < ids.at(-1) && !mine.has(e.id));
120
+ const free = between.every((e) => ['policy', 'rls', 'api', 'realtime'].includes(kindOf.get(e.id) ?? ''));
121
+ if (!free) {
122
+ // Des changements dépendent peut-être des états intermédiaires : tout est gardé
123
+ for (const id of ids)
124
+ units.push({ ids: [id], keep: [id], kind: g.kind, target: g.target, effect: 'one', result: null, at: id });
125
+ continue;
126
+ }
127
+ const n = net(g.kind, g.items);
128
+ units.push({ ids, keep: n.keep, kind: g.kind, target: g.target, effect: n.effect, result: n.result, at: n.keep.at(-1) ?? ids.at(-1) });
129
+ }
130
+ return units.sort((a, b) => a.at - b.at).map(({ at: _at, ...u }) => u);
131
+ };
132
+ exports.compact = compact;
@@ -233,17 +233,22 @@ async function snapshot(client) {
233
233
  if (await hasJournal(client)) await client.query('select poad_migrations.snapshot()');
234
234
  }
235
235
 
236
- /** Changements non enregistrés : { supported, entries, upTo, drift, sql } */
236
+ /** Changements non enregistrés : { supported, entries, units, upTo, drift, sql } (sql : regroupé) */
237
237
  async function changes(client) {
238
238
  if (!(await hasJournal(client))) return { supported: false, entries: [], upTo: null, drift: false, sql: '' };
239
239
  const { rows } = await client.query('select id, at, statement, commands, objects, role_name, application from poad_migrations.journal order by id');
240
240
  const st = (await client.query('select poad_migrations.status() as s')).rows[0].s || {};
241
+ // Effet net par objet (extension activée puis désactivée…) : utils/compact.js
242
+ const entries = rows.map((r) => ({ ...r, id: Number(r.id) }));
243
+ const units = require('./compact').compact(entries);
244
+ const kept = new Set(units.flatMap((u) => u.keep));
241
245
  return {
242
246
  supported: true,
243
- entries: rows,
244
- upTo: rows.length ? Number(rows[rows.length - 1].id) : null,
247
+ entries,
248
+ units,
249
+ upTo: entries.length ? entries[entries.length - 1].id : null,
245
250
  drift: Boolean(st.drift) && rows.length === 0,
246
- sql: rows.map((r) => String(r.statement).trim().replace(/;?\s*$/, ';')).join('\n\n'),
251
+ sql: entries.filter((r) => kept.has(r.id)).map((r) => String(r.statement).trim().replace(/;?\s*$/, ';')).join('\n\n'),
247
252
  };
248
253
  }
249
254