poad 2.73.0 → 2.74.1

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,354 @@
1
+ // poad transform ls modèles (poad/transforms/<nom>.sql), état, dernier passage
2
+ // poad transform new <nom> [--table|--view] [--from <table>] crée poad/transforms/<nom>.sql avec un en-tête minimal
3
+ // poad transform check relit tous les modèles : en-têtes, requêtes, graphe, cycles ; ne change rien
4
+ // poad transform run [<sélecteur>…] [--changed] [--detach] lance un passage et le suit (tout par défaut) ;
5
+ // sélecteurs : nom, nom+ (et son aval), +nom (et son amont)
6
+ // poad transform preview <nom> [--limit 20] premières lignes, calculées dans une transaction annulée
7
+ // poad transform graph lignage en texte (amont → aval)
8
+ // poad transform pull <nom> [--force] [--stdout] rapatrie un modèle saisi dans la console de poad.io (--env)
9
+ //
10
+ // Une transformation est une requête select dans poad/transforms/<nom>.sql (en-tête YAML en commentaire) :
11
+ // l'engine (0.72.0+, meta /meta/v1/transforms) en tire une vue (security_invoker) ou une table recalculée,
12
+ // dans l'ordre de leurs dépendances (déduites du SQL). Journaux : poad logs transform model=<nom>.
13
+ //
14
+ // --env <environnement> et --project <id> : le projet hébergé sur poad.io (comme poad source).
15
+ const flows = require('./flows');
16
+
17
+ const NAME_RE = /^[a-z_][a-z0-9_]{0,62}$/; // meta, transforms.ts : TRANSFORM_NAME_RE
18
+ const SELECTOR_RE = /^\+?[a-z_][a-z0-9_]{0,62}\+?$/;
19
+ const POLL_MS = 700;
20
+ const TIMEOUT_MS = 30000;
21
+ const USAGE =
22
+ 'Usage: poad transform ls | new <name> [--table|--view] [--from <table>] | check | run [<selector>…] [--changed] [--detach] | preview <name> [--limit <n>] | graph | pull <name> [--force] [--stdout], and --env <name> | --project <id> for poad.io';
23
+
24
+ /** Engine 0.72.0 ou plus (suffixe de lot accepté). Pure. */
25
+ const supportsTransforms = (config) => {
26
+ const [major, minor] = String((config && config.engine) || '').split('.').map((x) => parseInt(x, 10));
27
+ return major > 0 || minor >= 72;
28
+ };
29
+
30
+ const MAT = { view: 'view', table: 'table' };
31
+
32
+ /** Texte d'un nouveau modèle (même forme que meta : transforms.ts newModelText). Pure. */
33
+ const newModelText = ({ materialized = 'view', from = null } = {}) => ['/* ---', `materialized: ${materialized}`, 'api: false', '--- */', 'select *', `from ${from || 'ma_table'}`, ''].join('\n');
34
+
35
+ const duration = (ms) => (ms === null || ms === undefined ? '' : ms < 1000 ? `${ms} ms` : `${(ms / 1000).toFixed(1)} s`);
36
+ const count = (n) => (typeof n === 'number' && Number.isFinite(n) ? n.toLocaleString('en-US') : '?');
37
+
38
+ /** Lignes d'un modèle pour ls. Pure (chalk passé). */
39
+ const modelLines = (m, chalk) => {
40
+ const out = [];
41
+ const head = `${chalk.bold(m.name)} ${chalk.grey(`${m.materialized || '?'}${m.schema && m.schema !== 'public' ? ` ${m.schema}` : ''}${m.api ? `, API (${m.lecture})` : ''}${m.stored === 'console' ? ', not in git (poad transform pull)' : ''}`)}`;
42
+ out.push(head);
43
+ if (!m.valid) {
44
+ for (const p of (m.problems || []).slice(0, 5)) out.push(chalk.redBright(` ${m.file}${p.line ? `:${p.line}` : ''} ${p.message}`));
45
+ return out;
46
+ }
47
+ for (const w of (m.warnings || []).slice(0, 3)) out.push(chalk.yellowBright(` ${m.file}${w.line ? `:${w.line}` : ''} ${w.message}`));
48
+ const r = m.last_run;
49
+ if (!r) out.push(chalk.grey(' never built'));
50
+ else if (r.status === 'ok') out.push(` ${chalk.greenBright('ok')}${r.rows !== null && r.rows !== undefined ? chalk.grey(` ${count(r.rows)} row(s)`) : ''}${chalk.grey(` ${duration(r.duration_ms)} ${new Date(r.at).toLocaleString()}`)}`);
51
+ else if (r.status === 'skipped') out.push(` ${chalk.yellowBright('skipped')}${chalk.grey(` ${r.because} failed`)}`);
52
+ else out.push(` ${chalk.redBright(r.status)} ${r.error ? `${r.error.message}${r.error.line ? chalk.grey(` (${m.file}:${r.error.line})`) : ''}` : ''}`);
53
+ if (m.stale && r && r.status === 'ok') out.push(chalk.yellowBright(' changed since its last build: poad transform run ' + m.name));
54
+ if (m.upstream && m.upstream.length) out.push(chalk.grey(` reads ${m.upstream.join(', ')}`));
55
+ return out;
56
+ };
57
+
58
+ /** Lignage en texte : chaque modèle, ce qu'il lit (modèles et tables). Pure. */
59
+ const graphLines = (list, chalk) => {
60
+ const byName = new Map(list.models.map((m) => [m.name, m]));
61
+ const out = [];
62
+ for (const n of list.order || []) {
63
+ const m = byName.get(n);
64
+ const ins = [...(m.reads || []).map((r) => chalk.cyan(r)), ...(m.upstream || [])];
65
+ out.push(`${ins.length ? ins.join(', ') : chalk.grey('(nothing)')} ${chalk.grey('→')} ${chalk.bold(n)} ${chalk.grey(`(${m.materialized})`)}`);
66
+ }
67
+ for (const m of list.models.filter((x) => !x.valid)) out.push(chalk.redBright(`${m.name}: ${(m.problems[0] || {}).message || 'invalid'}`));
68
+ return out;
69
+ };
70
+
71
+ /** Ligne d'un modèle dans le suivi d'un passage. Pure. */
72
+ const runModelLine = (x, chalk) => {
73
+ if (x.status === 'ok') return `${chalk.greenBright('✔')} ${chalk.bold(x.model)} ${chalk.grey(`${x.materialized}${x.rows !== null && x.rows !== undefined ? `, ${count(x.rows)} row(s)` : ''}, ${duration(x.duration_ms)}`)}`;
74
+ if (x.status === 'skipped') return `${chalk.yellowBright('-')} ${chalk.bold(x.model)} ${chalk.grey(`skipped: ${x.because} failed`)}`;
75
+ return `${chalk.redBright('✖')} ${chalk.bold(x.model)} ${chalk.redBright(x.error_message || x.status)}${x.error_line ? chalk.grey(` (line ${x.error_line}${x.error_col ? `, column ${x.error_col}` : ''})`) : ''}`;
76
+ };
77
+
78
+ /**
79
+ * deps (tests) : started(config), fetch, sleep(ms), cwd, cloudTarget(opts).
80
+ */
81
+ const main = async (args = {}, raw, deps = {}) => {
82
+ const chalk = require('chalk-v2');
83
+ const path = require('path');
84
+ const fs = require('fs');
85
+ const { findPoadDir } = require('../utils/findpoad');
86
+ const { readConfig } = require('../utils/config');
87
+ const cwd = deps.cwd || process.cwd();
88
+ const doFetch = deps.fetch || fetch;
89
+ const sleep = deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
90
+ const started = deps.started || ((config) => require('../utils/docker').isDockerExist(config.project_uuid));
91
+ const cloudTarget = deps.cloudTarget || ((opts) => require('../utils/storage').cloudTarget(opts));
92
+ const fail = (message, code = 1) => {
93
+ process.exitCode = code;
94
+ console.log(chalk.redBright(message));
95
+ };
96
+
97
+ const typed = flows.cloudOptions(Array.isArray(raw) ? raw.map(String) : Object.keys(args));
98
+ if (typed.error) return fail(`poad transform: ${typed.error}.`, 2);
99
+ const json = typed.words.includes('--json');
100
+ const words = typed.words.filter((w) => w !== '--json');
101
+ const command = words[0] || 'ls';
102
+ const rest = words.slice(1);
103
+ const cloud = Boolean(typed.env || typed.project);
104
+ const where = cloud ? ` ${[typed.env ? `--env ${typed.env}` : '', typed.project ? `--project ${typed.project}` : ''].filter(Boolean).join(' ')}` : '';
105
+ const root = findPoadDir(cwd);
106
+ if (!root && !(cloud && typed.project)) return fail(cloud ? 'Not in a poad project folder: cd into one, or pass --project <id>.' : 'You are not in a poad project directory.');
107
+ const dir = root ? path.join(path.dirname(root), 'transforms') : null;
108
+
109
+ // ------------------------------------------------------------------ new (fichier seulement, sans engine)
110
+ if (command === 'new') {
111
+ let name = null;
112
+ let materialized = 'view';
113
+ let from = null;
114
+ for (let i = 0; i < rest.length; i++) {
115
+ const w = rest[i];
116
+ if (w === '--table') materialized = 'table';
117
+ else if (w === '--view') materialized = 'view';
118
+ else if (w === '--from') {
119
+ from = rest[++i];
120
+ if (!from || !/^([a-z_][a-z0-9_]{0,62}\.)?[a-z_][a-z0-9_]{0,62}$/.test(from)) return fail('--from <table>: a table name (schema.table accepted).', 2);
121
+ } else if (w.startsWith('-')) return fail(`poad transform new: unknown option ${w}.`, 2);
122
+ else if (name === null) name = w;
123
+ else return fail(`poad transform new: one model at a time ("${w}").`, 2);
124
+ }
125
+ if (!name) return fail('Usage: poad transform new <name> [--table|--view] [--from <table>]', 2);
126
+ if (!NAME_RE.test(name)) return fail(`"${name}" is not a model name: the name of its table or view (a-z, 0-9 and "_", a letter or "_" first).`, 2);
127
+ if (cloud) return fail('poad transform new writes a file of this folder: drop --env, then "poad deploy".', 2);
128
+ const file = path.join(dir, `${name}.sql`);
129
+ if (fs.existsSync(file)) return fail(`poad/transforms/${name}.sql already exists.`);
130
+ fs.mkdirSync(dir, { recursive: true });
131
+ fs.writeFileSync(file, newModelText({ materialized: MAT[materialized], from }));
132
+ console.log(`${chalk.greenBright('✔')} poad/transforms/${name}.sql ${chalk.grey(`(${materialized}${from ? `, from ${from}` : ''})`)}`);
133
+ return console.log(chalk.grey(` Write its select, then: poad transform run ${name}`));
134
+ }
135
+
136
+ /** Engine visé, prêt à répondre, ou null (message affiché) */
137
+ const ready = async () => {
138
+ if (cloud) {
139
+ try {
140
+ const t = await cloudTarget({ env: typed.env, project: typed.project });
141
+ return { base: t.base, key: t.key, apikey: t.apikey || t.key, label: t.label, cloud: true, renew: t.renew, expires: t.renew && t.renew.first ? Date.parse(t.renew.first) : null };
142
+ } catch (err) {
143
+ return fail((err && err.message) || String(err), (err && err.exit) || 1) || null;
144
+ }
145
+ }
146
+ const config = readConfig(root);
147
+ if (!supportsTransforms(config)) return fail(`Transformations need engine 0.72.0 or later (this project uses ${config.engine}): "poad upgrade".`) || null;
148
+ if (!(await started(config))) return fail('The project is not started: run "poad start".') || null;
149
+ const key = config.auth.service;
150
+ return { base: `http://localhost:${config.web.port}`, key, apikey: key, label: 'local engine', cloud: false };
151
+ };
152
+ const fresh = async (t) => {
153
+ if (!t.renew || !t.expires || t.expires - Date.now() > 60000) return;
154
+ const n = await t.renew.next();
155
+ Object.assign(t, { key: n.token, apikey: n.anon_key || t.apikey, expires: Date.parse(n.expires_at) });
156
+ };
157
+ class TransformError extends Error {}
158
+ const call = async (t, method, route, body) => {
159
+ try {
160
+ await fresh(t);
161
+ } catch (err) {
162
+ throw new TransformError(`poad.io gave no new access: ${(err && err.message) || err}`);
163
+ }
164
+ let res;
165
+ try {
166
+ res = await doFetch(`${t.base}${route}`, {
167
+ method,
168
+ headers: { apikey: t.apikey, authorization: `Bearer ${t.key}`, 'x-poad-by': 'cli', ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
169
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
170
+ signal: AbortSignal.timeout(TIMEOUT_MS),
171
+ });
172
+ } catch (err) {
173
+ const timedOut = err && (err.name === 'TimeoutError' || err.name === 'AbortError');
174
+ const who = t.cloud ? t.label : 'The engine';
175
+ throw new TransformError(timedOut ? `${who} did not answer within ${TIMEOUT_MS / 1000} s (${t.base}).` : `${who} does not answer on ${t.base}: ${(err && err.cause && err.cause.message) || (err && err.message) || err}`);
176
+ }
177
+ const data = await res.json().catch(() => null);
178
+ if (res.status >= 200 && res.status < 300) return data || {};
179
+ const error = data && data.error && typeof data.error === 'object' ? data.error : null;
180
+ if (error && error.message) {
181
+ const e = new TransformError(`${error.message}${error.hint ? ` (${error.hint})` : ''}`);
182
+ e.problems = data.problems;
183
+ throw e;
184
+ }
185
+ if (res.status === 404) throw new TransformError(`${t.cloud ? t.label : 'The engine'} has no transformations API (HTTP 404): engine 0.72.0 or later is needed.`);
186
+ if (res.status === 401 || res.status === 403) throw new TransformError(t.cloud ? `${t.label} refused the access (HTTP ${res.status}): "poad login" again.` : `the engine refused the service_role key (HTTP ${res.status})`);
187
+ throw new TransformError(`HTTP ${res.status}`);
188
+ };
189
+ const guard = async (fn) => {
190
+ try {
191
+ return await fn();
192
+ } catch (err) {
193
+ if (!(err instanceof TransformError)) throw err;
194
+ fail(err.message);
195
+ return undefined;
196
+ }
197
+ };
198
+
199
+ // ------------------------------------------------------------------ ls, check, graph
200
+ if (command === 'ls' || command === 'list' || command === 'check' || command === 'graph') {
201
+ if (rest.length) return fail(`poad transform ${command}: no argument expected ("${rest[0]}").`, 2);
202
+ const t = await ready();
203
+ if (!t) return;
204
+ const list = await guard(() => call(t, 'GET', '/meta/v1/transforms'));
205
+ if (!list) return;
206
+ if (json) return console.log(JSON.stringify(command === 'check' ? { valid: list.models.every((m) => m.valid), models: list.models.map((m) => ({ name: m.name, file: m.file, valid: m.valid, problems: m.problems, warnings: m.warnings })) } : list, null, 2));
207
+ if (!list.available && !list.models.length) return console.log(chalk.grey(`No poad/transforms folder in ${cloud ? t.label : 'this engine'}: "poad transform new <name>".`));
208
+ if (!list.models.length) return console.log(chalk.grey('No transformation yet: "poad transform new <name>" writes poad/transforms/<name>.sql.'));
209
+ if (command === 'graph') {
210
+ for (const line of graphLines(list, chalk)) console.log(line);
211
+ return;
212
+ }
213
+ if (command === 'check') {
214
+ const bad = list.models.filter((m) => !m.valid);
215
+ for (const m of list.models) {
216
+ if (m.valid) console.log(`${chalk.greenBright('✔')} ${m.file}${m.upstream.length ? chalk.grey(` reads ${m.upstream.join(', ')}`) : ''}`);
217
+ else for (const p of m.problems) console.log(`${chalk.redBright('✖')} ${m.file}${p.line ? `:${p.line}${p.col ? `:${p.col}` : ''}` : ''} ${p.message}`);
218
+ for (const w of m.warnings || []) console.log(`${chalk.yellowBright('⚠')} ${m.file}${w.line ? `:${w.line}` : ''} ${w.message}`);
219
+ }
220
+ console.log(' ');
221
+ if (bad.length) {
222
+ process.exitCode = 1;
223
+ return console.log(chalk.redBright(`${bad.length} of ${list.models.length} model(s) invalid.`));
224
+ }
225
+ return console.log(`${chalk.greenBright('✔')} ${list.models.length} model(s), order: ${list.order.join(' → ')}`);
226
+ }
227
+ for (const m of list.models) {
228
+ for (const line of modelLines(m, chalk)) console.log(line);
229
+ console.log(' ');
230
+ }
231
+ if (list.running) console.log(chalk.cyan(`A run is in progress: ${list.running}`));
232
+ return console.log(chalk.grey(`Logs: poad logs transform${where} · one model: poad logs transform model=<name>${where}`));
233
+ }
234
+
235
+ // ------------------------------------------------------------------ run
236
+ if (command === 'run') {
237
+ let detach = false;
238
+ let changed = false;
239
+ const selection = [];
240
+ for (const w of rest) {
241
+ if (w === '--detach') detach = true;
242
+ else if (w === '--changed') changed = true;
243
+ else if (w === '--full') continue; // étape 5 (incrémental) : sans effet pour view et table
244
+ else if (w.startsWith('-')) return fail(`poad transform run: unknown option ${w}.`, 2);
245
+ else if (!SELECTOR_RE.test(w)) return fail(`"${w}" is not a selector: name, name+ (and what reads it), +name (and what it reads).`, 2);
246
+ else selection.push(w);
247
+ }
248
+ if (changed && selection.length) return fail('--changed or selectors, not both.', 2);
249
+ const t = await ready();
250
+ if (!t) return;
251
+ const body = changed ? { trigger: 'manual', stale: true } : { trigger: 'manual', ...(selection.length ? { selection } : {}) };
252
+ const q = await guard(() => call(t, 'POST', '/meta/v1/transforms/run', body));
253
+ if (!q) return;
254
+ let runId = q.run_id;
255
+ if (detach) return console.log(runId || `queued ${q.queued}`);
256
+ return follow(t, runId, q.queued);
257
+ }
258
+
259
+ /** Suit un passage jusqu'à sa fin, modèle par modèle */
260
+ async function follow(t, runId, queuedId) {
261
+ for (let i = 0; !runId && i < 7200; i++) {
262
+ if (i === 1) console.log(chalk.grey(' Waiting for the run in progress to finish…'));
263
+ await sleep(POLL_MS);
264
+ const q = await guard(() => call(t, 'GET', `/meta/v1/transforms/queue/${queuedId}`));
265
+ if (!q) return;
266
+ runId = q.run_id;
267
+ }
268
+ console.log(chalk.grey(`run ${runId}${cloud ? ` ${t.label}` : ''}`));
269
+ const shown = new Set();
270
+ let view = null;
271
+ for (;;) {
272
+ view = await guard(() => call(t, 'GET', `/meta/v1/transforms/runs/${runId}`));
273
+ if (!view) return;
274
+ for (const x of view.models || []) {
275
+ if (shown.has(x.model) || x.status === 'running') continue;
276
+ shown.add(x.model);
277
+ console.log(runModelLine(x, chalk));
278
+ }
279
+ if (view.status !== 'running') break;
280
+ await sleep(POLL_MS);
281
+ }
282
+ console.log(' ');
283
+ if (view.status === 'empty') return console.log(chalk.grey('Nothing to build (no model, or nothing changed).'));
284
+ const line = `${view.ok} built, ${view.failed} failed, ${view.skipped} skipped${view.duration_ms !== null ? ` in ${duration(view.duration_ms)}` : ''}`;
285
+ if (view.status === 'ok') return console.log(`${chalk.greenBright('completed')} ${chalk.grey(line)}`);
286
+ process.exitCode = 1;
287
+ console.log(`${chalk.redBright(view.status)} ${chalk.grey(line)}`);
288
+ console.log(chalk.grey(` Details: poad logs transform run=${runId.slice(0, 8)}${where}`));
289
+ }
290
+
291
+ // ------------------------------------------------------------------ preview
292
+ if (command === 'preview') {
293
+ let name = null;
294
+ let limit = 20;
295
+ for (let i = 0; i < rest.length; i++) {
296
+ const w = rest[i];
297
+ if (w === '--limit') {
298
+ limit = Number(rest[++i]);
299
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) return fail('--limit: 1 to 100.', 2);
300
+ } else if (w.startsWith('-')) return fail(`poad transform preview: unknown option ${w}.`, 2);
301
+ else if (name === null) name = w;
302
+ else return fail('poad transform preview: one model at a time.', 2);
303
+ }
304
+ if (!name || !NAME_RE.test(name)) return fail('Usage: poad transform preview <name> [--limit <n>]', 2);
305
+ const t = await ready();
306
+ if (!t) return;
307
+ const p = await guard(() => call(t, 'POST', '/meta/v1/transforms/preview', { name, limit }));
308
+ if (!p) return;
309
+ if (json) return console.log(JSON.stringify(p, null, 2));
310
+ const cols = p.columns.map((c) => c.name);
311
+ const cell = (v) => (v === null || v === undefined ? 'null' : typeof v === 'object' ? JSON.stringify(v) : String(v)).replace(/\s+/g, ' ').slice(0, 40);
312
+ const widths = cols.map((c) => Math.max(c.length, ...p.rows.map((r) => cell(r[c]).length)));
313
+ console.log(chalk.bold(cols.map((c, i) => c.padEnd(widths[i])).join(' ')));
314
+ console.log(chalk.grey(p.columns.map((c, i) => c.type.padEnd(widths[i]).slice(0, widths[i])).join(' ')));
315
+ for (const r of p.rows) console.log(cols.map((c, i) => cell(r[c]).padEnd(widths[i])).join(' '));
316
+ return console.log(chalk.grey(`${p.rows.length} row(s)${p.truncated ? ' shown, more exist' : ''}, ${duration(p.duration_ms)}; nothing was written`));
317
+ }
318
+
319
+ // ------------------------------------------------------------------ pull
320
+ if (command === 'pull') {
321
+ let name = null;
322
+ let force = false;
323
+ let toStdout = false;
324
+ for (const w of rest) {
325
+ if (w === '--force' || w === '-f') force = true;
326
+ else if (w === '--stdout') toStdout = true;
327
+ else if (w.startsWith('-')) return fail(`poad transform pull: unknown option ${w}.`, 2);
328
+ else if (name === null) name = w;
329
+ else return fail(`poad transform pull: one model at a time ("${w}").`, 2);
330
+ }
331
+ if (!name) return fail('Usage: poad transform pull <name> [--force] [--stdout] --env <name> ("poad transform ls --env <name>" lists them).', 2);
332
+ if (!NAME_RE.test(name)) return fail(`"${name}" is not a model name.`, 2);
333
+ if (!root && !toStdout) return fail('Not in a poad project folder: cd into one, or pass --stdout.');
334
+ const target = root ? path.join(dir, `${name}.sql`) : null;
335
+ if (target && !toStdout && !force && fs.existsSync(target)) return fail(`poad/transforms/${name}.sql already exists: --force replaces it (check "git diff" afterwards), or --stdout prints it.`);
336
+ const t = await ready();
337
+ if (!t) return;
338
+ const got = await guard(() => call(t, 'GET', `/meta/v1/transforms/${encodeURIComponent(name)}/sql`));
339
+ if (!got) return;
340
+ if (typeof got.text !== 'string' || !got.text.trim()) return fail('The engine gave no model text.');
341
+ const text = got.text.endsWith('\n') ? got.text : `${got.text}\n`;
342
+ if (toStdout) return process.stdout.write(text);
343
+ fs.mkdirSync(path.dirname(target), { recursive: true });
344
+ fs.writeFileSync(target, text);
345
+ console.log(`${chalk.greenBright('✔')} poad/transforms/${name}.sql ${chalk.grey(`from ${cloud ? t.label : 'the local engine'}${got.stored === 'console' ? ', created in the console' : ''}`)}`);
346
+ if (got.stored === 'console' && cloud) console.log(chalk.grey(` Commit it, then "poad deploy${where}": the deployed file then wins over the console copy.`));
347
+ return;
348
+ }
349
+
350
+ fail(USAGE, 2);
351
+ };
352
+
353
+ module.exports = (args, raw) => main(args, raw);
354
+ Object.assign(module.exports, { main, supportsTransforms, newModelText, modelLines, graphLines, runModelLine, NAME_RE, SELECTOR_RE });
@@ -0,0 +1,2 @@
1
+ // poad transforms … : alias de poad transform …
2
+ module.exports = require('./transform');
@@ -28,7 +28,7 @@ test('poad upgrade 0.62 → 0.66 : perdues pour anon et authenticated, correctif
28
28
  assert.equal(x.items[1].fix, 'alter view public.stats set (security_invoker = true);');
29
29
  const out = exposure.lines(x, chalk).join('\n');
30
30
  assert.match(out, /With engine 0\.66\.0, the API no longer serves 2 function\(s\) or view\(s\) to anon or authenticated/);
31
- assert.match(out, /alter function est_admin\(uuid\) security invoker;/);
31
+ assert.match(out, /alter function public\.est_admin\(uuid\) security invoker;/);
32
32
  assert.match(out, /public\.stats .*authenticated/);
33
33
  });
34
34
 
@@ -58,3 +58,40 @@ test('la requête est la même que celle de poad.io (api-exposure.sql)', () => {
58
58
  assert.match(sql, /security_invoker=true/);
59
59
  assert.match(sql, /c\.relkind = 'm'/);
60
60
  });
61
+
62
+ test('poad migrate : seuls les objets accordés et non servis, nouveaux marqués, correctif « private + INVOKER »', () => {
63
+ const x = exposure.afterMigrate({ engine: '0.71.0', before: [view], after: [definer, view] });
64
+ assert.equal(x.count, 2);
65
+ assert.deepEqual(x.created, ['public.est_admin']);
66
+ assert.equal(x.items.find((i) => i.name === 'est_admin').created, true);
67
+ assert.equal(x.items.find((i) => i.name === 'stats').created, false);
68
+ const fix = x.items.find((i) => i.name === 'est_admin').fix;
69
+ assert.match(fix, /alter function public\.est_admin\(uuid\) security invoker;/);
70
+ assert.match(fix, /private\.est_admin \(SECURITY DEFINER, revoke execute from anon, authenticated\)/);
71
+ assert.match(fix, /public\.est_admin as a SECURITY INVOKER function that checks auth\.uid\(\)/);
72
+ const out = exposure.migrateLines(x, chalk).join('\n');
73
+ assert.match(out, /2 function\(s\) or view\(s\) granted to anon or authenticated are not served to them by the API/);
74
+ assert.match(out, /public\.est_admin \(new\)/);
75
+ assert.match(out, /granted to anon, authenticated/);
76
+ assert.match(out, /fix: alter view public\.stats set \(security_invoker = true\);/);
77
+ // Rappel d'une ligne quand rien n'a été appliqué (poad start)
78
+ assert.equal(exposure.migrateLines(x, chalk, { full: false }).length, 1);
79
+ });
80
+
81
+ test('poad migrate : rien avant 0.64.0 (l’API les servait), rien sans objet, base illisible : rien', () => {
82
+ assert.equal(exposure.afterMigrate({ engine: '0.62.0', before: [], after: [definer] }).count, 0);
83
+ assert.deepEqual(exposure.migrateLines(exposure.afterMigrate({ engine: '0.71.0', before: [], after: [] }), chalk), []);
84
+ assert.equal(exposure.afterMigrate({ engine: '0.71.0', before: null, after: null }).count, 0);
85
+ // Liste d'avant inconnue (rien d'appliqué) : aucun objet n'est dit nouveau
86
+ assert.deepEqual(exposure.afterMigrate({ engine: '0.71.0', before: null, after: [definer] }).created, []);
87
+ });
88
+
89
+ test('query : même requête que api-exposure.sql, sans les lignes psql, schémas en paramètre', async () => {
90
+ let seen;
91
+ const client = { query: async (text, params) => ((seen = { text, params }), { rows: [{ text: JSON.stringify({ schemas: ['public'], items: [definer] }) }] }) };
92
+ assert.deepEqual(await exposure.query(client, ['public', 'api', 'x;drop']), [definer]);
93
+ assert.doesNotMatch(seen.text, /default_transaction_read_only|\\set|:'schemas'/);
94
+ assert.match(seen.text, /string_to_array\(\$1, ','\)/);
95
+ assert.deepEqual(seen.params, ['public,api']);
96
+ assert.equal(await exposure.query({ query: async () => { throw new Error('role "anon" does not exist'); } }, ['public']), null);
97
+ });
@@ -96,8 +96,17 @@ function fakeCloud(t, behaviour = {}) {
96
96
  return send(res, 200, { removed: branch });
97
97
  }
98
98
  if (req.method === 'POST' && (m[2] === '/clone' || m[2] === '/sync')) return send(res, 200, { name: branch, status: 'active', status_detail: 'copie depuis la production : measure', credentials_with_values: ['claude'] });
99
+ // Migrations de l'environnement (control/server.mjs, migrationsOfBranch) : ?sql=0 la liste, ?versions= le SQL
100
+ if (req.method === 'GET' && m[2] === '/migrations') {
101
+ const all = (behaviour.migrations && behaviour.migrations[branch]) || [];
102
+ const only = url.searchParams.get('versions');
103
+ const withSql = url.searchParams.get('sql') !== '0';
104
+ const list = all.filter((x) => !only || only.split(',').includes(x.version)).map(({ sql, ...x }) => (withSql && sql !== undefined ? { ...x, sql } : x));
105
+ return send(res, 200, { project: id, branch, migrations: list });
106
+ }
99
107
  if (req.method === 'POST' && m[2] === '/deploy') {
100
108
  const dry = req.headers['x-poad-dry-run'] === '1';
109
+ if (behaviour.refuse) return send(res, 200, { deploy_id: 'dr', outcome: 'refused', dry_run: dry, migrations_applied: [], migrations_pending: [], errors: [behaviour.refuse] });
101
110
  if (behaviour.async) {
102
111
  state.deploys.d1 = 0;
103
112
  // La forme réelle de poad.io (control/server.mjs, deployView) : outcome, migrations_applied…
@@ -617,3 +626,155 @@ test('options : valeur manquante et option inconnue -> code 2', async (t) => {
617
626
  assert.strictEqual(jsonOf(u).error.code, 'usage');
618
627
  });
619
628
 
629
+
630
+ // --- Migrations écrites sur poad.io : deploy refusé, migration pull, migrate list, migrate renumber ------------
631
+
632
+ const sha256 = (s) => require('crypto').createHash('sha256').update(s).digest('hex');
633
+ const INIT_SQL = 'create table todo (id serial primary key);\n';
634
+ const NOTES_SQL = '-- ajoute_notes\n-- Écrite par la console poad.\n\ncreate table notes (id int);\n';
635
+ const IDX_SQL = 'create index on notes (id);\n';
636
+ const remoteMigrations = () => ({
637
+ main: [
638
+ { version: '20261101000000', name: 'init', file: '20261101000000_init.sql', checksum: sha256(INIT_SQL), applied_at: '2026-11-01T00:00:00Z', applied: true, source: 'history', sql: INIT_SQL },
639
+ { version: '20261203101500', name: 'ajoute_notes', file: '20261203101500_ajoute_notes.sql', checksum: sha256(NOTES_SQL), applied_at: '2026-12-03T10:15:00Z', applied: true, source: 'history', sql: NOTES_SQL },
640
+ { version: '20261204080000', name: 'index_notes', file: '20261204080000_index_notes.sql', checksum: null, applied_at: null, applied: false, source: 'folder', sql: IDX_SQL },
641
+ ],
642
+ dev: [{ version: '20261101000000', name: 'init', file: '20261101000000_init.sql', checksum: sha256(INIT_SQL), applied_at: '2026-11-01T00:00:00Z', applied: true, source: 'history', sql: INIT_SQL }],
643
+ });
644
+
645
+ test('deploy refusé (migrations manquantes) : lesquelles, avec nom et date, et la commande ; --dry-run --json garde versions et missing', async (t) => {
646
+ const box = sandbox(t);
647
+ const refuse = {
648
+ code: 'migrations_missing',
649
+ message: 'migrations applied on poad.io are missing from the folder: bring them back with poad migration pull, commit them, then deploy again',
650
+ versions: ['20261203101500'],
651
+ missing: [{ version: '20261203101500', name: 'ajoute_notes', file: '20261203101500_ajoute_notes.sql', applied_at: '2026-12-03T10:15:00Z' }],
652
+ };
653
+ const cloud = await fakeCloud(t, { refuse });
654
+ await login(box, cloud);
655
+ await poad(box, cloud.api, ['link', PID]);
656
+ const dry = await poad(box, cloud.api, ['deploy', '--dry-run']);
657
+ assert.strictEqual(dry.status, 5, dry.all);
658
+ assert.match(dry.stdout, /20261203101500_ajoute_notes\.sql\s+applied 2026-12-03 10:15 UTC/);
659
+ assert.match(dry.stdout, /poad migration pull(?! --env)/);
660
+ const j = await poad(box, cloud.api, ['deploy', '--dry-run', '--json', '--env', 'main']);
661
+ const o = jsonOf(j);
662
+ assert.deepStrictEqual(o.migrations.errors[0].versions, ['20261203101500']);
663
+ assert.strictEqual(o.migrations.errors[0].missing[0].file, '20261203101500_ajoute_notes.sql');
664
+ assert.deepStrictEqual(o.missing_migrations.map((m) => m.version), ['20261203101500']);
665
+ assert.deepStrictEqual(o.fix, ['poad migration pull --env main']);
666
+ // poad.io d'avant (versions seules) : listées quand même
667
+ const old = await fakeCloud(t, { refuse: { code: 'migrations_missing', message: 'missing', versions: ['20261203101500'] } });
668
+ await login(box, old);
669
+ const r = await poad(box, old.api, ['deploy', '--env', 'dev']);
670
+ assert.match(r.stdout, /20261203101500 \(name unknown\)/);
671
+ assert.match(r.stdout, /poad migration pull --env dev/);
672
+ });
673
+
674
+ test('deploy refusé (hors d’ordre) : la renumérotation proposée, rien de forcé', async (t) => {
675
+ const box = sandbox(t);
676
+ const cloud = await fakeCloud(t, { refuse: { code: 'migrations_out_of_order', message: 'pending migrations are older than the last applied one: rename them after it', files: ['20261101000000_init.sql'] } });
677
+ await login(box, cloud);
678
+ await poad(box, cloud.api, ['link', PID]);
679
+ const r = await poad(box, cloud.api, ['deploy', '--env', 'dev', '--json']);
680
+ assert.strictEqual(r.status, 5, r.all);
681
+ assert.deepStrictEqual(jsonOf(r).fix, ['poad migrate renumber 20261101000000 --env dev']);
682
+ const text = await poad(box, cloud.api, ['deploy', '--env', 'dev']);
683
+ assert.match(text.stdout, /poad migrate renumber 20261101000000 --env dev/);
684
+ assert.ok(!cloud.requests.some((q) => q.headers['x-poad-force']), 'aucun forçage');
685
+ });
686
+
687
+ test('migration pull : nom, version et contenu exacts, jamais d’écrasement, conflit dit (code 5) ; migrate pull alias', async (t) => {
688
+ const box = sandbox(t);
689
+ const cloud = await fakeCloud(t, { migrations: remoteMigrations() });
690
+ await login(box, cloud);
691
+ await poad(box, cloud.api, ['link', PID]);
692
+ const mdir = path.join(box.poad, 'migrations');
693
+
694
+ const dry = await poad(box, cloud.api, ['migration', 'pull', '--dry-run', '--json']);
695
+ assert.strictEqual(dry.status, 0, dry.all);
696
+ assert.deepStrictEqual(jsonOf(dry).pull.map((m) => m.file), ['20261203101500_ajoute_notes.sql', '20261204080000_index_notes.sql']);
697
+ assert.deepStrictEqual(fs.readdirSync(mdir), ['20261101000000_init.sql']);
698
+
699
+ // Hors terminal sans --yes : rien d'écrit
700
+ const ask = await poad(box, cloud.api, ['migration', 'pull']);
701
+ assert.strictEqual(ask.status, 4, ask.all);
702
+ assert.match(ask.stdout, /↓ 20261203101500_ajoute_notes\.sql\s+applied 2026-12-03 10:15 UTC/);
703
+ assert.match(ask.stdout, /↓ 20261204080000_index_notes\.sql\s+written on poad\.io, not applied yet/);
704
+
705
+ const r = await poad(box, cloud.api, ['migrate', 'pull', '--yes', '--json']);
706
+ assert.strictEqual(r.status, 0, r.all);
707
+ const o = jsonOf(r);
708
+ assert.deepStrictEqual(o.written.map((w) => w.file), ['20261203101500_ajoute_notes.sql', '20261204080000_index_notes.sql']);
709
+ assert.strictEqual(fs.readFileSync(path.join(mdir, '20261203101500_ajoute_notes.sql'), 'utf8'), NOTES_SQL);
710
+ assert.strictEqual(fs.readFileSync(path.join(mdir, '20261204080000_index_notes.sql'), 'utf8'), IDX_SQL);
711
+ const reqs = cloud.requests.filter((q) => q.route.endsWith('/migrations'));
712
+ assert.ok(reqs.every((q) => q.route === `v1/projects/${PID}/branches/main/migrations`));
713
+ assert.ok(reqs.some((q) => q.query.versions === '20261203101500,20261204080000'));
714
+ assert.ok(!r.all.includes(TOKEN));
715
+
716
+ const again = await poad(box, cloud.api, ['migration', 'pull', '--yes']);
717
+ assert.strictEqual(again.status, 0, again.all);
718
+ assert.match(again.stdout, /Nothing to pull/);
719
+
720
+ // Une version déjà prise ici sous un autre nom : conflit, rien d'écrasé
721
+ fs.rmSync(path.join(mdir, '20261203101500_ajoute_notes.sql'));
722
+ fs.writeFileSync(path.join(mdir, '20261203101500_mien.sql'), 'select 1;\n');
723
+ const c = await poad(box, cloud.api, ['migration', 'pull', '--yes', '--json']);
724
+ assert.strictEqual(c.status, 5, c.all);
725
+ assert.deepStrictEqual(jsonOf(c).conflicts, [{ version: '20261203101500', file: '20261203101500_ajoute_notes.sql', local: '20261203101500_mien.sql' }]);
726
+ assert.strictEqual(fs.readFileSync(path.join(mdir, '20261203101500_mien.sql'), 'utf8'), 'select 1;\n');
727
+ assert.ok(!fs.existsSync(path.join(mdir, '20261203101500_ajoute_notes.sql')));
728
+ });
729
+
730
+ test('migration pull : SQL introuvable ou somme fausse là-haut, refusé (code 5) avec poad db pull en recours', async (t) => {
731
+ const box = sandbox(t);
732
+ const m = remoteMigrations();
733
+ m.main[1] = { ...m.main[1], sql: 'tampered;\n' };
734
+ m.main.push({ version: '20261204090000', name: 'perdue', file: '20261204090000_perdue.sql', checksum: 'x', applied_at: '2026-12-04T09:00:00Z', applied: true, source: null, problem: 'sql_unavailable' });
735
+ const cloud = await fakeCloud(t, { migrations: m });
736
+ await login(box, cloud);
737
+ await poad(box, cloud.api, ['link', PID]);
738
+ const r = await poad(box, cloud.api, ['migration', 'pull', '--yes', '--json']);
739
+ assert.strictEqual(r.status, 5, r.all);
740
+ const o = jsonOf(r);
741
+ assert.deepStrictEqual(o.written.map((w) => w.file), ['20261204080000_index_notes.sql']);
742
+ assert.deepStrictEqual(o.unavailable.map((u) => [u.version, u.problem]).sort(), [['20261203101500', 'checksum_mismatch'], ['20261204090000', 'sql_unavailable']]);
743
+ assert.ok(!fs.existsSync(path.join(box.poad, 'migrations', '20261203101500_ajoute_notes.sql')));
744
+ const text = await poad(box, cloud.api, ['migration', 'pull', '--yes']);
745
+ assert.match(text.stdout, /poad db pull/);
746
+ });
747
+
748
+ test('migrate list : dossier face à poad.io (appliquée, en attente, manquante, hors d’ordre) ; migrate renumber', async (t) => {
749
+ const box = sandbox(t);
750
+ const cloud = await fakeCloud(t, { migrations: remoteMigrations() });
751
+ await login(box, cloud);
752
+ await poad(box, cloud.api, ['link', PID]);
753
+ const mdir = path.join(box.poad, 'migrations');
754
+ fs.writeFileSync(path.join(mdir, '20261202000000_vieille.sql'), 'select 2;\n');
755
+ fs.writeFileSync(path.join(mdir, '20991231000000_future.sql'), 'select 3;\n');
756
+ const r = await poad(box, cloud.api, ['migrate', 'list', '--json']);
757
+ assert.strictEqual(r.status, 0, r.all);
758
+ const states = Object.fromEntries(jsonOf(r).migrations.map((m) => [m.version, m.state]));
759
+ assert.deepStrictEqual(states, { 20261101000000: 'applied', 20261202000000: 'out_of_order', 20261203101500: 'missing', 20261204080000: 'remote_pending', 20991231000000: 'pending' });
760
+ assert.strictEqual(jsonOf(r).migrations.find((m) => m.version === '20261203101500').applied_at, '2026-12-03T10:15:00Z');
761
+ const text = await poad(box, cloud.api, ['migration', 'list', '--env', 'main']);
762
+ assert.match(text.stdout, /poad migration pull --env main/);
763
+ assert.match(text.stdout, /poad migrate renumber 20261202000000 --env main/);
764
+
765
+ // Appliquée sur un environnement : jamais renumérotée
766
+ const applied = await poad(box, cloud.api, ['migrate', 'renumber', '20261101000000', '--yes']);
767
+ assert.strictEqual(applied.status, 5, applied.all);
768
+ assert.match(applied.stderr, /already applied on main/);
769
+ assert.ok(fs.existsSync(path.join(mdir, '20261101000000_init.sql')));
770
+
771
+ const ren = await poad(box, cloud.api, ['migrate', 'renumber', '20261202000000_vieille.sql', '--yes', '--json']);
772
+ assert.strictEqual(ren.status, 0, ren.all);
773
+ const o = jsonOf(ren);
774
+ assert.strictEqual(o.from, '20261202000000_vieille.sql');
775
+ assert.ok(o.version > '20991231000000', `après la dernière du dossier et de poad.io : ${o.version}`);
776
+ assert.strictEqual(fs.readFileSync(path.join(mdir, o.to), 'utf8'), 'select 2;\n');
777
+ assert.ok(!fs.existsSync(path.join(mdir, '20261202000000_vieille.sql')));
778
+ const unknown = await poad(box, cloud.api, ['migrate', 'renumber', '20200101000000', '--yes']);
779
+ assert.strictEqual(unknown.status, 2, unknown.all);
780
+ });