poad 2.69.0 → 2.71.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.
@@ -0,0 +1,283 @@
1
+ // Copie de infra/services/meta/src/capture.ts (compilée en CommonJS) : garder
2
+ // les deux identiques, la console et poad db diff capturent pareil.
3
+ "use strict";
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.suggestName = exports.countItems = exports.capture = exports.describeEntry = exports.splitIdentity = exports.shortOf = exports.isRoutineStatement = exports.splitStatements = void 0;
6
+ // Ce qu'une migration tirée du journal emporte vraiment.
7
+ //
8
+ // Le journal note le texte envoyé par le client : un script entier de l'éditeur
9
+ // SQL (42 fonctions dont une seule modifiée) arrive en une entrée de 2 000 lignes
10
+ // qui cite 42 fonctions. Postgres signale un CREATE OR REPLACE même quand rien ne
11
+ // change.
12
+ //
13
+ // Pour les fonctions et procédures, ce n'est donc plus le texte qui part dans la
14
+ // migration, mais la différence du catalogue (poad_migrations.routine_changes(),
15
+ // engine 0.69.0) : formes canoniques (pg_get_functiondef, droits, commentaire,
16
+ // propriétaire), surcharges distinguées par leur signature complète.
17
+ // - une entrée qui cite des routines est découpée en instructions ; celles qui
18
+ // portent sur une routine (create/alter/drop function, comment on function,
19
+ // grant/revoke on function…) sont retirées, le reste (le « résidu ») est gardé
20
+ // tel quel ;
21
+ // - les entrées qui citent les mêmes routines forment un groupe (une unité de
22
+ // l'écran Migrations) ; sa dernière entrée porte le SQL de la différence ;
23
+ // - rien de changé : l'unité est « sans effet », il n'y a rien à écrire.
24
+ // Les entrées antérieures à la référence (routinesSince) gardent leur texte.
25
+ //
26
+ // Même code dans le CLI (utils/capture.js) : poad db diff fait pareil.
27
+ const compact_1 = require("./compact");
28
+ // ------------------------------------------------------------ découpage
29
+ /** Découpe un script SQL en instructions (chaînes, identifiants, $tag$…$tag$, commentaires). null : script mal formé. Pure. */
30
+ const splitStatements = (text) => {
31
+ const out = [];
32
+ let start = 0;
33
+ let i = 0;
34
+ const n = text.length;
35
+ while (i < n) {
36
+ const c = text[i];
37
+ const next = text[i + 1];
38
+ if (c === '-' && next === '-') {
39
+ const e = text.indexOf('\n', i);
40
+ i = e < 0 ? n : e + 1;
41
+ }
42
+ else if (c === '/' && next === '*') {
43
+ let depth = 1;
44
+ i += 2;
45
+ while (i < n && depth) {
46
+ if (text[i] === '/' && text[i + 1] === '*')
47
+ (depth++, (i += 2));
48
+ else if (text[i] === '*' && text[i + 1] === '/')
49
+ (depth--, (i += 2));
50
+ else
51
+ i++;
52
+ }
53
+ if (depth)
54
+ return null;
55
+ }
56
+ else if (c === "'" || c === '"') {
57
+ // E'…' : antislash échappé
58
+ const escapes = c === "'" && /[eE]/.test(text[i - 1] ?? '') && !/[\w$]/.test(text[i - 2] ?? '');
59
+ i++;
60
+ for (;;) {
61
+ if (i >= n)
62
+ return null;
63
+ if (escapes && text[i] === '\\')
64
+ i += 2;
65
+ else if (text[i] === c && text[i + 1] === c)
66
+ i += 2;
67
+ else if (text[i] === c)
68
+ break;
69
+ else
70
+ i++;
71
+ }
72
+ i++;
73
+ }
74
+ else if (c === '$' && !/[\w$]/.test(text[i - 1] ?? '')) {
75
+ const m = /^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(text.slice(i, i + 64));
76
+ if (!m) {
77
+ i++;
78
+ continue;
79
+ }
80
+ const end = text.indexOf(m[0], i + m[0].length);
81
+ if (end < 0)
82
+ return null;
83
+ i = end + m[0].length;
84
+ }
85
+ else if (c === ';') {
86
+ out.push(text.slice(start, i + 1));
87
+ start = ++i;
88
+ }
89
+ else
90
+ i++;
91
+ }
92
+ out.push(text.slice(start));
93
+ return out.map((s) => s.trim()).filter((s) => s && !/^;?$/.test(stripComments(s).trim()));
94
+ };
95
+ exports.splitStatements = splitStatements;
96
+ const stripComments = (s) => s.replace(/^(?:\s*(?:--[^\n]*\n?|\/\*[\s\S]*?\*\/))*/, '');
97
+ const ROUTINE_STATEMENT = /^\s*(?:create\s+(?:or\s+replace\s+)?(?:function|procedure)\b|(?:alter|drop)\s+(?:function|procedure|routine)\b|comment\s+on\s+(?:function|procedure|routine)\b|(?:grant|revoke)\b[^;]*?\bon\s+(?:function|procedure|routine)\b)/i;
98
+ /** L'instruction porte-t-elle sur une routine (create/alter/drop function, comment, grant/revoke on function) ? Pure. */
99
+ const isRoutineStatement = (stmt) => ROUTINE_STATEMENT.test(stripComments(stmt));
100
+ exports.isRoutineStatement = isRoutineStatement;
101
+ // ------------------------------------------------------------ description
102
+ const KINDS = ['schema', 'extension', 'table', 'view', 'materialized view', 'foreign table', 'type', 'domain', 'function', 'procedure', 'aggregate', 'trigger', 'policy', 'publication', 'index', 'sequence'];
103
+ const kindOf = (command) => /^(?:CREATE|ALTER|DROP)\s+(.+)$/i.exec(command.trim())?.[1]?.toLowerCase() ?? null;
104
+ /** public.f(pg_catalog.text) → public.f ; « p on public.t » reste tel quel. Pure. */
105
+ const shortOf = (identity) => identity.split('(')[0];
106
+ exports.shortOf = shortOf;
107
+ /** Schéma et nom d'une identité (public.todos, "Mon schéma".t, « p on public.t » → p). Pure. */
108
+ const splitIdentity = (identity) => {
109
+ const head = (0, exports.shortOf)(identity).split(' on ')[0];
110
+ const parts = (head.match(/"(?:[^"]|"")+"|[^.]+/g) ?? [head]).map((p) => p.replace(/^"|"$/g, '').replace(/""/g, '"'));
111
+ return parts.length > 1 ? { schema: parts[0], name: parts[parts.length - 1] } : { schema: '', name: parts[0] };
112
+ };
113
+ exports.splitIdentity = splitIdentity;
114
+ const escapeRe = (t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
115
+ /** L'objet principal d'une entrée du journal, lisible (type, nom, motif). Pure. */
116
+ const describeEntry = (e, objects = e.objects.filter((o) => Boolean(o))) => {
117
+ const rank = (k) => (k && KINDS.includes(k) ? KINDS.indexOf(k) : KINDS.length);
118
+ const main = [...e.commands].sort((a, b) => rank(kindOf(a)) - rank(kindOf(b)))[0] ?? '';
119
+ const verb = main.split(/\s+/)[0].toUpperCase();
120
+ if (!objects.length)
121
+ return null;
122
+ const named = objects.find((o) => new RegExp(`(^|[^\\w$])"?${escapeRe((0, exports.splitIdentity)(o).name)}"?($|[^\\w$])`, 'i').test(e.statement));
123
+ const object = named ?? objects[0];
124
+ const type = kindOf(main) ?? (verb === 'GRANT' || verb === 'REVOKE' ? 'grants' : verb === 'COMMENT' ? 'comment' : 'object');
125
+ const change = verb === 'DROP' ? 'dropped' : verb === 'CREATE' && !/^\s*create\s+or\s+replace\b/i.test(stripComments(e.statement)) ? 'created' : 'modified';
126
+ return { type, ...(0, exports.splitIdentity)(object), change };
127
+ };
128
+ exports.describeEntry = describeEntry;
129
+ /** a, b, c et 47 autres. Pure. */
130
+ const shortList = (xs, max = 3) => (xs.length <= max ? xs.join(', ') : `${xs.slice(0, max).join(', ')} et ${xs.length - max} autres`);
131
+ // ------------------------------------------------------------ capture
132
+ /**
133
+ * Unités de l'écran Migrations (et de poad db diff) et SQL effectif de chaque entrée. Pure.
134
+ * known : identités des routines (actuelles et de la référence), pour reconnaître les objets du journal
135
+ * since : id du journal à partir duquel la référence vaut (null : engine sans référence, texte gardé partout)
136
+ */
137
+ const capture = (entries, changes, known, since) => {
138
+ const knownFull = new Set(known);
139
+ const knownShort = new Set(known.map(exports.shortOf));
140
+ const isRoutineObj = (e, o) => knownFull.has(o) || knownShort.has(o) || (o.includes('(') && e.commands.some((c) => /^(CREATE|ALTER|DROP) (FUNCTION|PROCEDURE|ROUTINE)$/i.test(c)));
141
+ const sql = new Map();
142
+ const routineEntries = [];
143
+ const normal = [];
144
+ for (const e of entries) {
145
+ const objs = e.objects.filter((o) => Boolean(o));
146
+ const routines = since === null || e.id <= since ? [] : objs.filter((o) => isRoutineObj(e, o));
147
+ const parts = routines.length ? (0, exports.splitStatements)(e.statement) : null;
148
+ if (!parts) {
149
+ normal.push(e);
150
+ continue;
151
+ }
152
+ routineEntries.push({ e, routines: routines.map(exports.shortOf), residue: parts.filter((p) => !(0, exports.isRoutineStatement)(p)), others: objs.filter((o) => !routines.includes(o)) });
153
+ }
154
+ // Groupes : entrées qui citent une même routine (par schéma.nom : les surcharges vont ensemble)
155
+ const parent = routineEntries.map((_, i) => i);
156
+ const find = (i) => (parent[i] === i ? i : (parent[i] = find(parent[i])));
157
+ const owner = new Map();
158
+ routineEntries.forEach((r, i) => {
159
+ for (const k of r.routines) {
160
+ const j = owner.get(k);
161
+ if (j === undefined)
162
+ owner.set(k, i);
163
+ else
164
+ parent[find(i)] = find(j);
165
+ }
166
+ });
167
+ const groups = new Map();
168
+ routineEntries.forEach((r, i) => groups.set(find(i), [...(groups.get(find(i)) ?? []), r]));
169
+ const units = [];
170
+ for (const g of groups.values()) {
171
+ const names = new Set(g.flatMap((r) => r.routines));
172
+ const rows = changes.filter((c) => names.has((0, exports.shortOf)(c.identity)));
173
+ const ids = g.map((r) => r.e.id);
174
+ const last = ids[ids.length - 1];
175
+ const keep = [];
176
+ for (const r of g) {
177
+ const own = r.residue.map((s) => s.replace(/;?\s*$/, ';'));
178
+ if (r.e.id === last)
179
+ own.push(...rows.map((c) => c.sql));
180
+ const text = own.join('\n\n');
181
+ sql.set(r.e.id, text);
182
+ if (text.trim())
183
+ keep.push(r.e.id);
184
+ }
185
+ const items = rows.map((c) => ({ type: c.kind, schema: c.schema_name, name: c.name, change: c.change, aspects: c.aspects, identity: c.identity, lines: c.sql.split('\n').length }));
186
+ for (const r of g)
187
+ if (r.residue.length) {
188
+ const d = (0, exports.describeEntry)({ ...r.e, statement: r.residue.join('\n') }, r.others);
189
+ if (d)
190
+ items.push(d);
191
+ }
192
+ units.push({
193
+ ids,
194
+ keep,
195
+ kind: 'routine',
196
+ target: shortList([...names].map((n) => (0, exports.splitIdentity)(n).name)),
197
+ effect: !keep.length ? 'none' : ids.length === 1 ? 'one' : 'merged',
198
+ // Groupe de plusieurs entrées : ce qu'il en reste (« 2 objets changés »)
199
+ result: ids.length > 1 && items.length ? `${items.length} objet${items.length > 1 ? 's' : ''} changé${items.length > 1 ? 's' : ''}` : null,
200
+ items,
201
+ at: keep[keep.length - 1] ?? last,
202
+ });
203
+ }
204
+ const byId = new Map(entries.map((e) => [e.id, e]));
205
+ for (const u of (0, compact_1.compact)(normal)) {
206
+ const items = u.keep.map((id) => (0, exports.describeEntry)(byId.get(id))).filter((x) => Boolean(x));
207
+ for (const id of u.ids)
208
+ sql.set(id, u.keep.includes(id) ? String(byId.get(id).statement).trim().replace(/;?\s*$/, ';') : '');
209
+ units.push({ ...u, items, at: u.keep[u.keep.length - 1] ?? u.ids[u.ids.length - 1] });
210
+ }
211
+ const sorted = units.sort((a, b) => a.at - b.at).map(({ at: _at, ...u }) => u);
212
+ return { units: sorted, sql };
213
+ };
214
+ exports.capture = capture;
215
+ /** Objets d'une sélection, comptés par type et motif (journal migration_captured). Pure. */
216
+ const countItems = (items) => {
217
+ const byType = {};
218
+ const byChange = {};
219
+ for (const i of items) {
220
+ byType[i.type] = (byType[i.type] ?? 0) + 1;
221
+ byChange[i.change] = (byChange[i.change] ?? 0) + 1;
222
+ }
223
+ return { objects: items.length, by_type: byType, by_change: byChange };
224
+ };
225
+ exports.countItems = countItems;
226
+ // ------------------------------------------------------------ nom
227
+ const VERB = { created: 'cree', modified: 'modifie', dropped: 'supprime' };
228
+ const TYPE = {
229
+ function: ['', 'fonctions'],
230
+ procedure: ['procedure', 'procedures'],
231
+ table: ['table', 'tables'],
232
+ view: ['vue', 'vues'],
233
+ 'materialized view': ['vue_materialisee', 'vues_materialisees'],
234
+ 'foreign table': ['table_distante', 'tables_distantes'],
235
+ index: ['index', 'index'],
236
+ policy: ['politique', 'politiques'],
237
+ extension: ['extension', 'extensions'],
238
+ schema: ['schema', 'schemas'],
239
+ type: ['type', 'types'],
240
+ domain: ['domaine', 'domaines'],
241
+ trigger: ['declencheur', 'declencheurs'],
242
+ sequence: ['sequence', 'sequences'],
243
+ grants: ['droits', 'droits'],
244
+ comment: ['commentaire', 'commentaires'],
245
+ };
246
+ const snake = (s) => s
247
+ .normalize('NFD')
248
+ .replace(/[̀-ͯ]/g, '')
249
+ .replace(/[^A-Za-z0-9]+/g, '_')
250
+ .replace(/^_+|_+$/g, '')
251
+ .toLowerCase();
252
+ /** Tronque à max caractères sans couper un mot (sauf s'il est seul). Pure. */
253
+ const cut = (s, max) => {
254
+ if (s.length <= max)
255
+ return s;
256
+ const at = s.lastIndexOf('_', max);
257
+ return (at > 10 ? s.slice(0, at) : s.slice(0, max)).replace(/_+$/, '');
258
+ };
259
+ /**
260
+ * Nom proposé d'après ce qui a changé (jamais d'après les premiers objets vus) : modifie_observation_enregistrer,
261
+ * cree_table_releves, supprime_mx_calcul_07, modifie_droits_auteur_invitable, modifie_3_fonctions, modifie_5_objets.
262
+ * snake_case, sans schéma public ni pg_catalog, 60 caractères au plus. Pure.
263
+ */
264
+ const suggestName = (items, max = 60) => {
265
+ if (!items.length)
266
+ return '';
267
+ const changes = new Set(items.map((i) => i.change));
268
+ const verb = changes.size === 1 ? VERB[items[0].change] : 'modifie';
269
+ const label = (i) => (i.schema && i.schema !== 'public' ? `${i.schema}_${i.name}` : i.name);
270
+ const names = new Set(items.map(label));
271
+ const types = new Set(items.map((i) => i.type));
272
+ if (names.size === 1) {
273
+ const i = items[0];
274
+ // Seulement les droits ou le commentaire d'une fonction : dit tel quel
275
+ const only = items.length === 1 && i.change === 'modified' && i.aspects?.length === 1 && i.aspects[0] !== 'definition' ? { grants: 'droits', comment: 'commentaire', owner: 'proprietaire' }[i.aspects[0]] : '';
276
+ const word = only || (TYPE[i.type]?.[0] ?? snake(i.type));
277
+ const over = items.length > 1 && types.size === 1 ? `_${items.length}_surcharges` : '';
278
+ return cut(snake([verb, word, label(i)].filter(Boolean).join('_')) + over, max);
279
+ }
280
+ const plural = types.size === 1 ? (TYPE[[...types][0]]?.[1] ?? 'objets') : 'objets';
281
+ return cut(snake(`${verb}_${items.length}_${plural}`), max);
282
+ };
283
+ exports.suggestName = suggestName;
@@ -19,7 +19,7 @@ const fs = require('fs');
19
19
  const path = require('path');
20
20
  const zlib = require('zlib');
21
21
 
22
- const DIRS = ['migrations', 'queries', 'auth', 'storage', 'functions', 'flows', 'api', 'reference', 'sources', 'variables', 'types'];
22
+ const DIRS = ['migrations', 'queries', 'auth', 'storage', 'functions', 'flows', 'api', 'reference', 'sources', 'connections', 'variables', 'types'];
23
23
  const FILES = ['seed.sql', 'config.toml'];
24
24
  const NEVER = [/^secrets\.toml$/i, /^\.env$/i, /^\.env\..*/i, /^\.DS_Store$/, /^Thumbs\.db$/i, /^desktop\.ini$/i, /~$/, /\.swp$/];
25
25
  const SKIP_DIRS = new Set(['node_modules', '.git', 'data', 'backups', '.cache']);
@@ -0,0 +1,30 @@
1
+ // Service de sortie de l'engine (poad-egress, engine 0.69.0+) : [egress] de poad/config.toml
2
+ //
3
+ // [egress]
4
+ // mode = "free" # défaut en local : tout hôte public ; "declared" : allow et les hôtes des connexions seulement
5
+ // allow = ["api.github.com", "*.data.gouv.fr"]
6
+ //
7
+ // Les adresses internes sont toujours refusées, quel que soit le mode.
8
+ const MODES = ['free', 'declared'];
9
+ const HOST_RE = /^(\*\.)?[a-z0-9]([a-z0-9-]{0,62}\.)*[a-z0-9-]{1,63}$/i;
10
+
11
+ /** Réglage [egress] lu et vérifié : { mode, allow } ou { error }. Pure. */
12
+ const settings = (config) => {
13
+ const e = (config && config.egress) || {};
14
+ const mode = e.mode === undefined ? 'free' : String(e.mode);
15
+ if (!MODES.includes(mode)) return { error: `[egress] mode: "free" or "declared" (got "${mode}")` };
16
+ const allow = e.allow === undefined ? [] : Array.isArray(e.allow) ? e.allow.map(String) : null;
17
+ if (!allow) return { error: '[egress] allow: a list of host names, like ["api.github.com", "*.data.gouv.fr"]' };
18
+ const bad = allow.find((h) => !HOST_RE.test(h));
19
+ if (bad) return { error: `[egress] allow: "${bad}" is not a host name` };
20
+ return { mode, allow };
21
+ };
22
+
23
+ /** Variables de l'engine ; un réglage invalide : mode declared sans liste (sûr), le message est donné par start */
24
+ const engineEnv = (config) => {
25
+ const s = settings(config);
26
+ if (s.error) return ['EGRESS_MODE=declared'];
27
+ return [`EGRESS_MODE=${s.mode}`, ...(s.allow.length ? [`EGRESS_ALLOW=${s.allow.join(',')}`] : [])];
28
+ };
29
+
30
+ module.exports = { settings, engineEnv, MODES };
@@ -97,7 +97,7 @@ const sheets = {
97
97
  logs: {
98
98
  usage: ['poad logs [service …] [<filter>=<value> …] [-f] [--json]'],
99
99
  text: [
100
- 'Unified logs of the project (every service, the project functions and flow steps), the latest 100 lines by default. Services: gateway, data, auth, storage, meta, functions, flows, postgres, logs, engine, mailpit, keycloak, valkey, ai.',
100
+ 'Unified logs of the project (every service, the project functions and flow steps), the latest 100 lines by default. Services: gateway, data, auth, storage, meta, functions, flows, postgres, files (remote tables, engine 0.68.0+), egress (every outbound call: connection, host, path without query, status, duration, engine 0.69.0+; filters connection= host=), logs, engine, mailpit, keycloak, valkey, ai.',
101
101
  ],
102
102
  options: [
103
103
  ['level=warn', 'warn, error and fatal'],
@@ -144,14 +144,17 @@ const sheets = {
144
144
  notes: ['Structure created by the file lands in the change journal: "poad db diff <name>" writes it as a migration. Logs: poad logs meta event=sql_import (never a value of the file).'],
145
145
  },
146
146
  'db diff': {
147
- usage: ['poad db diff', 'poad db diff <name>', 'poad db diff --discard', 'poad db diff --json'],
147
+ usage: ['poad db diff', 'poad db diff <name>', 'poad db diff --save', 'poad db diff --discard', 'poad db diff --json'],
148
148
  text: [
149
149
  'Structure changes made outside the migrations (console SQL, psql, a tool), noted by the change journal of the engine (0.11.0+).',
150
150
  'First a summary, one object per line: + added, ~ changed (with the column added, removed, renamed or changed when it can be read), - removed, · no net effect (created then dropped…); then the SQL of each change, as it will be written.',
151
+ 'Functions and procedures (engine 0.69.0+): only those that really changed, compared with the catalogue (definition, privileges, comment, owner; overloads told apart by their full signature). A script replayed as is writes nothing.',
152
+ 'A name is suggested from what changed (modifie_observation_enregistrer, cree_table_releves, modifie_3_fonctions). Logs: poad logs cli event=migration_captured.',
151
153
  ],
152
154
  options: [
153
155
  ['(nothing)', 'summary, then the SQL'],
154
156
  ['<name>', 'write them to poad/migrations/<timestamp>_<name>.sql (already applied here: not replayed), then the summary of what it holds'],
157
+ ['--save', 'same as <name>, with the suggested name'],
155
158
  ['--discard', 'forget them (they stay in the database)'],
156
159
  ['--json', 'entries, groups, SQL and the summary (summary: change, kind, object, others, detail)'],
157
160
  ],
@@ -287,7 +290,7 @@ const sheets = {
287
290
  notes: ['Their logs: poad logs flow=<name>, poad logs run=<id>'],
288
291
  },
289
292
  source: {
290
- usage: ['poad source ls [--json]', 'poad source refresh <name> [--force] [--detach]', 'poad source import <file> [--table <table>] [--name <source>] [--key <col,…> | --key-generated uuid|identity|hash] [--existing] [--format …] [--root <path>] [--sheet <name|n>] [--header <row|none>] [--records <path>] [--expand-until <YYYY-MM-DD>] [--kinds wpt,rte,trk] [--detach]', 'poad source link <table> --host <host> --database <db> --remote <schema.table> --credential <name> [--port <port>] [--sslmode require|verify-full|disable] [--columns <col,…>]', 'poad source link <table> --url <https://…> | --storage <bucket>/<path> [--format csv|json|jsonl|geojson|parquet] [--delimiter <c>] [--no-header] [--encoding utf-8|latin-1|utf-16] [--root <a.b>] [--columns <col,…>]', 'poad source test <name>', 'poad source pull <name> [--force] [--stdout]', 'poad source ls | refresh | import | link | test | pull … --env <name> [--project <id>]'],
293
+ usage: ['poad source ls [--json]', 'poad source refresh <name> [--force] [--detach]', 'poad source import <file> [--table <table>] [--name <source>] [--key <col,…> | --key-generated uuid|identity|hash] [--existing] [--format …] [--root <path>] [--sheet <name|n>] [--header <row|none>] [--records <path>] [--expand-until <YYYY-MM-DD>] [--kinds wpt,rte,trk] [--detach]', 'poad source link <table> --host <host> --database <db> --remote <schema.table> --credential <name> [--port <port>] [--sslmode require|verify-full|disable] [--columns <col,…>]', 'poad source link <table> --url <https://…> | --storage <bucket>/<path> [--format csv|json|jsonl|geojson|parquet|topojson|ics|xlsx|ods|xml|kml|kmz|gpx|shapefile|gpkg|fgb] [--sheet <name|n>] [--layer <name>] [--records <path>] [--delimiter <c>] [--no-header] [--encoding utf-8|latin-1|utf-16] [--root <a.b>] [--columns <col,…>]', 'poad source test <name>', 'poad source expose <name> [--roles authenticated,anon] [--filter <sql>] [--rate 30/min] [--max-rows 100]', 'poad source unexpose <name>', 'poad source relate <name> <column> <schema.table.column> [--name <relation>]', 'poad source unrelate <name> <column>', 'poad source retain <name> <90d|off> [--column <date column>]', 'poad source pull <name> [--force] [--stdout]', 'poad source ls | refresh | import | link | test | pull … --env <name> [--project <id>]'],
291
294
  text: [
292
295
  'Sources of the project: tables kept up to date from a URL (JSON, GeoJSON, CSV, JSONL, ICS calendar, XLSX or ODS spreadsheet, XML such as RSS or Atom, KML, KMZ or GPX), declared in poad/sources/<name>.yaml (engine 0.64.0+; from engine 0.65.0 a source created by poad is named after its table). The engine creates the table with a migration of poad/migrations (read-only for the application, readable through the API with api: true) and a generated flow source-<name> that fills it: download, read, deposit, apply (upsert by key, removals under a guard).',
293
296
  'With --env or --project, the commands act on the project hosted on poad.io (session of poad login, owner only) instead of the local engine: poad.io gives an access of 15 minutes, never shown. Locally, the service_role key of the project, never shown.',
@@ -298,11 +301,16 @@ const sheets = {
298
301
  ['import <file>', 'load a CSV, JSON, GeoJSON, JSONL, ICS, XLSX, ODS, XML, KML, KMZ or GPX file (.gz accepted, no size limit) into a table: the file goes to the system bucket poad-sources (resumable upload when the storage offers it), the engine reads a sample, proposes the columns and a key, declares an imported source (origin kind: upload) and loads it, streamed; a source is named after its table (poad/sources/<table>.yaml); the source already exists: a new version, same path, then the load. --table <name> (default: the file name; cleaned: lowercase, accents removed, spaces → _, leading digit → t_), --name <source> (kept for compatibility: an existing source of that name gets a new version, otherwise ignored), --key <col,…>, --existing (load into an existing table), --format and --root when the guess is wrong. ICS, XLSX, ODS, XML, KML, KMZ and GPX are read by the source-read step itself (engine with meta 1.43.0): --sheet <name or position> and --header <row, or none> for a spreadsheet (default: the first sheet that has rows, first row with two cells or more), --records <path> for XML (channel/item; RSS and Atom are found alone), --expand-until <YYYY-MM-DD> for a calendar (one row per occurrence of repeated events instead of one row per event), --kinds wpt,rte,trk for GPX; what the reader chose is written in the declaration (origin.<format>)'],
299
302
  ['--key-generated <kind>', 'import, new table without a natural key: poad adds an id column first, key: { generated: <kind> } in the declaration. uuid (gen_random_uuid()) or identity (sequential bigint): each new version replaces the whole table content in one transaction (the API never sees it empty), under the deletion guard on the net row loss; hash: SHA-256 of the row values, an unchanged row keeps its id (a modified row is removed then added)'],
300
303
  ['link <table>', 'a linked table (mode virtual, engine 0.66.0+): a table of another PostgreSQL database read on every query through a foreign table (postgres_fdw), nothing copied. The engine checks the host (internal addresses refused: private network, localhost, link-local, the engine), connects read-only with the credential (a "Database login" of the vault: user and password, never on the command line), proposes the columns of --remote <schema.table> (--columns keeps some of them, remote names), then writes poad/sources/<table>.yaml and the migration of the foreign table. Private: never served by the API'],
301
- ['link <table> --url | --storage', 'a remote table over a file (mode virtual, engine 0.67.0+): a CSV, JSON (array, --root for where the rows are), JSON-L, GeoJSON (geometry as PostGIS geometry) or Parquet file (.gz accepted) read by DuckDB inside Postgres (duckdb_fdw) on every query, nothing copied: select, where, join with the tables of the project, aggregates; filters are pushed to the file reader. --url <https://…> (internal addresses refused: private network, localhost, link-local, NAT64, the engine, another poad project; no credential, no secret in the address) or --storage <bucket>/<path> (an object of the project storage, local or S3). The engine reads a sample, proposes the columns (--columns keeps some of them, field names), then writes poad/sources/<table>.yaml and the migration of the foreign table. Private: never served by the API'],
304
+ ['link <table> --url | --storage', 'a remote table over a file (mode virtual, engine 0.67.0+): a CSV, JSON (array, --root for where the rows are), JSON-L, GeoJSON (geometry as PostGIS geometry) or Parquet file (.gz accepted) read by poad-files inside Postgres (file_fdw, engine 0.68.0; DuckDB in 0.67.0) on every query, nothing copied: select, where, join with the tables of the project, aggregates; filters are pushed to the file reader. --url <https://…> (internal addresses refused: private network, localhost, link-local, NAT64, the engine, another poad project; no credential, no secret in the address) or --storage <bucket>/<path> (an object of the project storage, local or S3). The engine reads a sample, proposes the columns (--columns keeps some of them, field names), then writes poad/sources/<table>.yaml and the migration of the foreign table. Private: never served by the API Separator, header, encoding, decimal comma and dd/mm/yyyy dates are detected and written to the declaration; --delimiter, --no-header and --encoding only override the detection. A ZIP archive holding one file is read as that file (entry: in the declaration when it holds several).'],
302
305
  ['test <name>', 'a linked or remote table: check the address again, reattach it and read one row through Postgres (duration, location without its query string); exit code 1 if it cannot be read'],
306
+ ['expose <name>', 'engine 0.69.0+: serve a linked or remote table through the data API, on purpose (by default it is refused, 403 not_exposed): poad puts a protected view (security_barrier, security_invoker), read only, granted to --roles only (authenticated by default; anon only if you say so), with --filter as its row filter (an SQL condition written like an RLS policy, checked by Postgres before anything is written), a rate limit per caller (--rate, 60/min by default: 429 and Retry-After beyond) and a page cap (--max-rows, 100 by default). Nothing is copied: the data never counts in the quota. Writes api: in poad/sources/<name>.yaml'],
307
+ ['unexpose <name>', 'stop serving it: back to 403 not_exposed'],
308
+ ['relate <name> <column> <target>', 'declare a relation (any source): <column> of the source points at schema.table.column (a table, a view or another source). The data API uses it like a foreign key, both ways: include=["commune"] from the source, include=["<source table>"] from the target. RLS and the filter of a remote table still apply'],
309
+ ['retain <name> <duration>', 'a copied source (synchronized, imported): keep its copy for a while. With --column, rows older than the duration by that date column are purged; without, the copy is emptied once its last successful sync is older than the duration. off removes it. Checked every hour, logged as source_purge'],
303
310
  ['pull <name>', 'write the declaration of a source into poad/sources/<name>.yaml: with --env, a source created in the console of poad.io (kept in the project database); commit it, then poad deploy'],
304
311
  ['--force', 'refresh: lift the deletion guard (safety.maxDeletePercent) for this run: the source is right even though many rows go away; pull: replace an existing poad/sources/<name>.yaml'],
305
312
  ['--stdout', 'pull: print the declaration instead of writing the file'],
313
+ ['--roles, --filter, --rate, --max-rows', 'expose: also --filtre, --debit, --pagination (the keys of the YAML); --no-filter removes the filter'],
306
314
  ['--detach (or --no-wait)', 'print the run id only, without following it'],
307
315
  ['--json', 'ls: the sources as JSON'],
308
316
  ['--env <name>', 'an environment of the linked poad.io project (main: production)'],
package/utils/logline.js CHANGED
@@ -5,8 +5,8 @@ const LEVELS = ['debug', 'info', 'warn', 'error', 'fatal'];
5
5
 
6
6
  // Options de filtre → attribut de la ligne (attrs). Mêmes noms et même sens
7
7
  // que les paramètres de /logs/v1 (services/logs/src/api.ts de l'infra).
8
- const ATTR_OPTIONS = { flow: 'flow', step: 'step', function: 'function', tool: 'tool', outcome: 'outcome', provider: 'provider', model: 'model', event: 'event', table: 'table', channel: 'channel', front: 'front', page: 'page', source: 'source_name', upload: 'upload_id', bucket: 'bucket' };
9
- const EXAMPLES = { flow: 'demo-flux', step: 'appel', function: 'demo-stats', tool: 'select_rows', outcome: 'refused', provider: 'anthropic', model: 'claude-opus-5-5', event: 'ai_default_model_changed', table: 'notes', channel: 'notes', front: 'k3x9q2m7a1bc', page: 'accueil', source: 'communes', upload: '0b8e8f7e-1b2c-4d5e-8f90-123456789abc', bucket: 'documents' };
8
+ const ATTR_OPTIONS = { flow: 'flow', step: 'step', function: 'function', tool: 'tool', outcome: 'outcome', provider: 'provider', model: 'model', event: 'event', table: 'table', channel: 'channel', front: 'front', page: 'page', source: 'source_name', upload: 'upload_id', bucket: 'bucket', connection: 'connection', host: 'host' };
9
+ const EXAMPLES = { flow: 'demo-flux', step: 'appel', function: 'demo-stats', tool: 'select_rows', outcome: 'refused', provider: 'anthropic', model: 'claude-opus-5-5', event: 'ai_default_model_changed', table: 'notes', channel: 'notes', front: 'k3x9q2m7a1bc', page: 'accueil', source: 'communes', upload: '0b8e8f7e-1b2c-4d5e-8f90-123456789abc', bucket: 'documents', connection: 'sncf', host: 'api.sncf.com' };
10
10
  // Identifiant d'exécution (UUID) entier, ou son début : 8 caractères au moins
11
11
  const RUN_RE = /^[0-9a-f-]{8,36}$/;
12
12
 
@@ -241,22 +241,43 @@ async function snapshot(client) {
241
241
  if (await hasJournal(client)) await client.query('select poad_migrations.snapshot()');
242
242
  }
243
243
 
244
- /** Changements non enregistrés : { supported, entries, units, upTo, drift, sql } (sql : regroupé) */
244
+ /** Différence des routines (engine 0.69.0) : changements, identités connues, début de la référence */
245
+ async function routineCapture(client) {
246
+ const ok = (await client.query("select to_regprocedure('poad_migrations.routine_changes()') is not null as ok")).rows[0].ok;
247
+ if (!ok) return { changes: [], known: [], since: null };
248
+ const s = (await client.query('select routines_since from poad_migrations.state where id = 1')).rows[0];
249
+ if (!s || s.routines_since === null) return { changes: [], known: [], since: null };
250
+ const changes = (await client.query('select identity, schema_name, name, kind, change, aspects, sql from poad_migrations.routine_changes() order by ord, identity')).rows;
251
+ const known = (await client.query('select identity from poad_migrations.routine_state() union select identity from poad_migrations.routines')).rows.map((r) => r.identity);
252
+ return { changes, known, since: Number(s.routines_since) };
253
+ }
254
+
255
+ /**
256
+ * Changements non enregistrés : { supported, entries, units, upTo, drift, sql, items, suggested_name }.
257
+ * Fonctions et procédures : la différence du catalogue, pas le texte envoyé (utils/capture.js, engine 0.69.0) ;
258
+ * le reste : effet net par objet (utils/compact.js). sql : regroupé.
259
+ */
245
260
  async function changes(client) {
246
261
  if (!(await hasJournal(client))) return { supported: false, entries: [], upTo: null, drift: false, sql: '' };
247
262
  const { rows } = await client.query('select id, at, statement, commands, objects, role_name, application from poad_migrations.journal order by id');
248
263
  const st = (await client.query('select poad_migrations.status() as s')).rows[0].s || {};
249
- // Effet net par objet (extension activée puis désactivée…) : utils/compact.js
250
- const entries = rows.map((r) => ({ ...r, id: Number(r.id) }));
251
- const units = require('./compact').compact(entries);
264
+ const capture = require('./capture');
265
+ const routines = await routineCapture(client);
266
+ const raw = rows.map((r) => ({ ...r, id: Number(r.id) }));
267
+ const { units, sql: effective } = capture.capture(raw, routines.changes, routines.known, routines.since);
268
+ const entries = raw.map((e) => ({ ...e, sql: effective.get(e.id) || '' }));
252
269
  const kept = new Set(units.flatMap((u) => u.keep));
270
+ const items = units.flatMap((u) => (u.keep.length ? u.items : []));
253
271
  return {
254
272
  supported: true,
255
273
  entries,
256
274
  units,
257
275
  upTo: entries.length ? entries[entries.length - 1].id : null,
258
276
  drift: Boolean(st.drift) && rows.length === 0,
259
- sql: entries.filter((r) => kept.has(r.id)).map((r) => String(r.statement).trim().replace(/;?\s*$/, ';')).join('\n\n'),
277
+ routines: routines.since !== null,
278
+ sql: entries.filter((r) => kept.has(r.id) && r.sql.trim()).map((r) => r.sql).join('\n\n'),
279
+ items,
280
+ suggested_name: capture.suggestName(items),
260
281
  };
261
282
  }
262
283
 
@@ -265,7 +286,7 @@ async function changes(client) {
265
286
  * déjà dans la base) : fichier, historique, journal vidé jusqu'à upTo,
266
287
  * empreinte. Renvoie le chemin du fichier.
267
288
  */
268
- async function saveChanges(root, client, name, sql, upTo) {
289
+ async function saveChanges(root, client, name, sql, upTo, items = []) {
269
290
  const file = create(root, name);
270
291
  const content = fs.readFileSync(file, 'utf-8').replace('Appliquée une seule fois', 'Changements de structure enregistrés par poad db diff (déjà appliqués à la base locale). Appliquée une seule fois') + sql.trim() + '\n';
271
292
  const m = FILE_RE.exec(path.basename(file));
@@ -284,6 +305,13 @@ async function saveChanges(root, client, name, sql, upTo) {
284
305
  fs.rmSync(file, { force: true });
285
306
  throw err;
286
307
  }
308
+ // Puits de logs : migration_captured, avec le nombre d'objets par type (jamais de SQL ni de secret)
309
+ const counts = require('./capture').countItems(items);
310
+ await client
311
+ .query("insert into _logs.entries (ts, level, service, msg, attrs) values (now(), 'info', 'cli', 'migration enregistrée depuis le journal', $1::jsonb)", [
312
+ JSON.stringify({ event: 'migration_captured', migration: `poad/migrations/${path.basename(file)}`, ...counts, lines: content.split('\n').length, via: 'poad db diff' }),
313
+ ])
314
+ .catch(() => {});
287
315
  return file;
288
316
  }
289
317