poad 2.73.0 → 2.74.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/global/start.js +9 -1
- package/package.json +1 -1
- package/project/cli.js +2 -0
- package/project/logs.js +6 -2
- package/project/migrate.js +17 -5
- package/project/transform.js +354 -0
- package/project/transforms.js +2 -0
- package/test/api-exposure.test.js +38 -1
- package/test/transform.test.js +177 -0
- package/utils/api-exposure/index.js +53 -2
- package/utils/cloud/bundle.js +2 -2
- package/utils/help-details.js +27 -3
- package/utils/logline.js +4 -2
- package/utils/migrate-run.js +15 -1
- package/utils/migrations.js +31 -1
- package/utils/transforms.js +64 -0
package/global/start.js
CHANGED
|
@@ -149,6 +149,8 @@ module.exports = async (args = {}) => {
|
|
|
149
149
|
// Sans cette variable, l'engine démarre en production.
|
|
150
150
|
'POAD_MODE=development',
|
|
151
151
|
'POAD_ENGINE_VERSION=' + config.engine,
|
|
152
|
+
// poad start / db reset construisent les transformations au démarrage (engine 0.72.0+) : meta n'en lance pas un second passage
|
|
153
|
+
'POAD_TRANSFORMS_BOOT=cli',
|
|
152
154
|
// Console d'administration sans mot de passe : seulement si les ports
|
|
153
155
|
// n'écoutent que sur cette machine
|
|
154
156
|
'POAD_CONSOLE=' + (require('../utils/ports').exposed(config) ? 'off' : 'local'),
|
|
@@ -189,7 +191,7 @@ module.exports = async (args = {}) => {
|
|
|
189
191
|
// poad/reference : contenu des tables de référence, un fichier par table
|
|
190
192
|
// poad/api : définitions de l'API publiée du projet, un fichier par version
|
|
191
193
|
// poad/sources : déclarations des sources (<nom>.yaml), lues par meta (engine 0.64.0+)
|
|
192
|
-
Binds: [path.dirname(root) + '/data:/data', `${ensureDir(path.join(path.dirname(root), 'migrations'))}:/project/migrations`, `${ensureDir(path.join(path.dirname(root), 'credentials'))}:/project/credentials`, `${ensureDir(path.join(path.dirname(root), 'functions'))}:/project/functions`, `${ensureDir(path.join(path.dirname(root), 'variables'))}:/project/variables`, `${ensureDir(path.join(path.dirname(root), 'types'))}:/project/types`, `${ensureDir(path.join(path.dirname(root), 'flows'))}:/project/flows`, `${ensureDir(path.join(path.dirname(root), 'auth'))}:/project/auth`, `${ensureDir(path.join(path.dirname(root), 'storage'))}:/project/storage`, `${ensureDir(path.join(path.dirname(root), 'reference'))}:/project/reference`, `${ensureDir(path.join(path.dirname(root), 'sources'))}:/project/sources`, `${ensureDir(path.join(path.dirname(root), 'connections'))}:/project/connections`, `${ensureDir(path.join(path.dirname(root), 'api'))}:/project/api`],
|
|
194
|
+
Binds: [path.dirname(root) + '/data:/data', `${ensureDir(path.join(path.dirname(root), 'migrations'))}:/project/migrations`, `${ensureDir(path.join(path.dirname(root), 'credentials'))}:/project/credentials`, `${ensureDir(path.join(path.dirname(root), 'functions'))}:/project/functions`, `${ensureDir(path.join(path.dirname(root), 'variables'))}:/project/variables`, `${ensureDir(path.join(path.dirname(root), 'types'))}:/project/types`, `${ensureDir(path.join(path.dirname(root), 'flows'))}:/project/flows`, `${ensureDir(path.join(path.dirname(root), 'auth'))}:/project/auth`, `${ensureDir(path.join(path.dirname(root), 'storage'))}:/project/storage`, `${ensureDir(path.join(path.dirname(root), 'reference'))}:/project/reference`, `${ensureDir(path.join(path.dirname(root), 'sources'))}:/project/sources`, `${ensureDir(path.join(path.dirname(root), 'transforms'))}:/project/transforms`, `${ensureDir(path.join(path.dirname(root), 'connections'))}:/project/connections`, `${ensureDir(path.join(path.dirname(root), 'api'))}:/project/api`],
|
|
193
195
|
// Services lancés sur la machine : joignables depuis l'engine, y
|
|
194
196
|
// compris sous Linux
|
|
195
197
|
ExtraHosts: ['host.docker.internal:host-gateway'],
|
|
@@ -240,6 +242,12 @@ module.exports = async (args = {}) => {
|
|
|
240
242
|
else if (seed && !(await runSeed(root, config))) process.exitCode = 1;
|
|
241
243
|
}
|
|
242
244
|
}
|
|
245
|
+
// Transformations (poad/transforms) : après le seed ; toutes sur une base neuve, sinon celles qui ont changé
|
|
246
|
+
const transforms = require('../utils/transforms');
|
|
247
|
+
if (transforms.hasModels(root) && !process.exitCode) {
|
|
248
|
+
const ready = migrate || seed || hasReference || ((await migrations.waitForDb(config)) && (await migrations.waitForServices(config)));
|
|
249
|
+
if (ready && !(await transforms.build(root, config, { fresh }))) process.exitCode = 1;
|
|
250
|
+
}
|
|
243
251
|
|
|
244
252
|
await finish();
|
|
245
253
|
};
|
package/package.json
CHANGED
package/project/cli.js
CHANGED
|
@@ -79,6 +79,8 @@ module.exports = {
|
|
|
79
79
|
flow: 'Alias of poad flows',
|
|
80
80
|
source: 'Sources of the project (tables kept up to date from a URL or an uploaded file, poad/sources/<name>.yaml, engine 0.64.0+): ls, refresh <name> [--force], import <file> [--table <t>], link <table> (linked table of another PostgreSQL database, or remote table over a CSV, JSON, JSON-L, GeoJSON or Parquet file: --url or --storage, engine 0.67.0+), test <name>, pull <name>; --env <name> for poad.io',
|
|
81
81
|
sources: 'Alias of poad source',
|
|
82
|
+
transform: 'Transformations (engine 0.72.0+): a select per file in poad/transforms/<name>.sql, built as a view or a table, in dependency order: ls, new <name>, check, run [<selector>…], preview <name>, graph, pull <name>; --env <name> for poad.io',
|
|
83
|
+
transforms: 'Alias of poad transform',
|
|
82
84
|
relation: 'Relations without a foreign key (engine 0.70.0+), between tables, views, remote and linked tables, nested in both directions by the API: ls [table], add <table.column> <table.column> [--name <n>], rm, suggest <table>, check <from> <to> (broken links); --env <name> for poad.io',
|
|
83
85
|
relations: 'Alias of poad relation',
|
|
84
86
|
connection: 'Named connections of the project (external services called through the egress service, poad/connections/<name>.yaml, engine 0.69.0+): ls, types [--provides tabular], add <name> --type <id> [--set key=value] (secrets from POAD_SECRET_<KEY>), add <name> --url <https://…> [--credential <c>], test <name>, rm <name> [--force]; --env <name> for poad.io',
|
package/project/logs.js
CHANGED
|
@@ -36,6 +36,8 @@
|
|
|
36
36
|
// envoi, event=storage.object.created
|
|
37
37
|
// poad logs data event=sync_pull device=<id> synchronisation d'une table synchronisée (engine 0.70+) :
|
|
38
38
|
// sync_pull, sync_push (data), sync_purge (meta), avec table= et device=
|
|
39
|
+
// poad logs transform model=ventes les transformations (engine 0.72+) : passages, modèles construits ou en
|
|
40
|
+
// échec ; run=<id>, event=model_failed, trigger=deploy ; transform=<nom> = model=<nom>
|
|
39
41
|
// poad logs limit=500 nombre de lignes (100 par défaut)
|
|
40
42
|
// poad logs -f | --follow suivi en direct
|
|
41
43
|
// poad logs --json une ligne JSON par entrée (pour jq)
|
|
@@ -99,7 +101,7 @@ module.exports = async (args = {}, raw = [], deps = {}) => {
|
|
|
99
101
|
const flag = (...names) => names.some((n) => args[n] === true);
|
|
100
102
|
const follow = flag('-f', '--follow', 'follow');
|
|
101
103
|
const asJson = flag('--json', 'json');
|
|
102
|
-
const services = Object.keys(args).filter((k) => args[k] === true && !OPTIONS.includes(k) && !k.startsWith('-'));
|
|
104
|
+
const services = Object.keys(args).filter((k) => args[k] === true && (!OPTIONS.includes(k) || SERVICE_WORDS.includes(k)) && !k.startsWith('-'));
|
|
103
105
|
const level = args.level ? String(args.level).toLowerCase() : null;
|
|
104
106
|
let since = null;
|
|
105
107
|
if (args.since) {
|
|
@@ -212,7 +214,7 @@ async function remoteLogs(typed, deps, chalk) {
|
|
|
212
214
|
if (!typed.project && !findPoadDir(deps.cwd || process.cwd())) return fail('Not in a poad project folder: cd into one, or pass --project <id>.');
|
|
213
215
|
const OPTIONS = optionNames(ATTR_OPTIONS);
|
|
214
216
|
const flag = (...names) => names.some((n) => args[n] === true);
|
|
215
|
-
const services = Object.keys(args).filter((k) => args[k] === true && !OPTIONS.includes(k) && !k.startsWith('-'));
|
|
217
|
+
const services = Object.keys(args).filter((k) => args[k] === true && (!OPTIONS.includes(k) || SERVICE_WORDS.includes(k)) && !k.startsWith('-'));
|
|
216
218
|
const q = remote.entriesParams(args, services);
|
|
217
219
|
if (q.error) return fail(q.error);
|
|
218
220
|
const asJson = flag('--json', 'json');
|
|
@@ -239,6 +241,8 @@ async function remoteLogs(typed, deps, chalk) {
|
|
|
239
241
|
}
|
|
240
242
|
|
|
241
243
|
/** Noms d'options reconnus (le reste, sans « - » devant, sont des services). Pure. */
|
|
244
|
+
/** Mots qui sont à la fois un service (poad logs transform) et une option (transform=<modèle>) */
|
|
245
|
+
const SERVICE_WORDS = ['transform'];
|
|
242
246
|
const optionNames = (ATTR_OPTIONS) => ['level', 'since', 'request', 'grep', 'limit', 'run', 'token', ...Object.keys(ATTR_OPTIONS), '-f', '--follow', 'follow', '--json', 'json'];
|
|
243
247
|
|
|
244
248
|
/**
|
package/project/migrate.js
CHANGED
|
@@ -11,9 +11,21 @@ module.exports = async () => {
|
|
|
11
11
|
if (!(await isDockerExist(config.project_uuid))) {
|
|
12
12
|
return console.log(chalk.redBright('The project is not started: run "poad start" (it applies pending migrations too).'));
|
|
13
13
|
}
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
14
|
+
// --json : une seule sortie, l'objet du passage (migrations appliquées, échec, api_exposure, tables sans RLS)
|
|
15
|
+
const json = process.argv.includes('--json');
|
|
16
|
+
const report = {};
|
|
17
|
+
const log = console.log;
|
|
18
|
+
if (json) console.log = () => {};
|
|
19
|
+
let ok;
|
|
20
|
+
let refOk = true;
|
|
21
|
+
try {
|
|
22
|
+
ok = await require('../utils/migrate-run')(root, config, { report, exposureList: true });
|
|
23
|
+
// Tables de référence : après les migrations, quand leur structure est à jour
|
|
24
|
+
// --force-reference : le fichier fait foi même s'il retire beaucoup de lignes (garde-fou de l'engine passé)
|
|
25
|
+
if (ok) refOk = await require('../utils/reference').sync(root, config, { force: process.argv.includes('--force-reference') });
|
|
26
|
+
} finally {
|
|
27
|
+
console.log = log;
|
|
28
|
+
}
|
|
29
|
+
if (!ok || !refOk) process.exitCode = 1;
|
|
30
|
+
if (json) console.log(JSON.stringify({ ok: Boolean(ok && refOk), ...report }, null, 2));
|
|
19
31
|
};
|
|
@@ -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 });
|
|
@@ -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
|
+
});
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// poad transform : ls, check, run (suivi), preview, new, pull ; filtre transform= de poad logs ;
|
|
2
|
+
// poad/transforms dans l'archive de poad deploy.
|
|
3
|
+
const test = require('node:test');
|
|
4
|
+
const assert = require('node:assert');
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const zlib = require('zlib');
|
|
8
|
+
const { tmpdir } = require('./helpers');
|
|
9
|
+
|
|
10
|
+
const transform = require('../project/transform');
|
|
11
|
+
const RUN = '7c2e1d90-4b3a-4f1e-8d2c-5a6b7c8d9e0f';
|
|
12
|
+
|
|
13
|
+
const LIST = {
|
|
14
|
+
available: true,
|
|
15
|
+
dir: 'poad/transforms',
|
|
16
|
+
store: 'file',
|
|
17
|
+
hosted: false,
|
|
18
|
+
running: null,
|
|
19
|
+
order: ['commandes_propres', 'ventes_par_mois'],
|
|
20
|
+
models: [
|
|
21
|
+
{ name: 'commandes_propres', file: 'poad/transforms/staging/commandes_propres.sql', stored: 'file', valid: true, problems: [], warnings: [], materialized: 'view', schema: 'staging', api: false, lecture: 'connectes', upstream: [], downstream: ['ventes_par_mois'], reads: ['public.commandes'], stale: false, last_run: { run_id: RUN, status: 'ok', rows: null, duration_ms: 7, at: '2026-12-04T10:00:00Z', error: null } },
|
|
22
|
+
{ name: 'ventes_par_mois', file: 'poad/transforms/ventes_par_mois.sql', stored: 'file', valid: true, problems: [], warnings: [], materialized: 'table', schema: 'public', api: true, lecture: 'connectes', upstream: ['commandes_propres'], downstream: [], reads: ['public.magasins'], stale: false, last_run: { run_id: RUN, status: 'failed', rows: null, duration_ms: 3, at: '2026-12-04T10:00:00Z', error: { code: '42703', message: 'column "x" does not exist', line: 9, col: 8 } } },
|
|
23
|
+
{ name: 'casse', file: 'poad/transforms/casse.sql', stored: 'file', valid: false, problems: [{ path: 'sql', message: 'cycle : casse → casse', line: 1 }], warnings: [], materialized: null, upstream: [], downstream: [], reads: [], stale: false, last_run: null },
|
|
24
|
+
],
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
function sandbox(t, { engine = '0.72.0' } = {}) {
|
|
28
|
+
const dir = tmpdir(t, 'poad-transform-');
|
|
29
|
+
const app = path.join(dir, 'app');
|
|
30
|
+
fs.mkdirSync(path.join(app, 'poad'), { recursive: true });
|
|
31
|
+
fs.writeFileSync(path.join(app, 'poad', 'config.toml'), `project_id = "demo"\nproject_uuid = "poad-transform-test-not-a-container"\nengine = "${engine}"\n[web]\nport = 1\n[db]\nport = 1\n`);
|
|
32
|
+
fs.writeFileSync(path.join(app, 'poad', 'secrets.toml'), '[auth]\nsecret = "LOCAL-SECRET-x"\nanon = "LOCAL-ANON-x"\nservice = "LOCAL-SERVICE-x"\nadmin = "LOCAL-ADMIN-x"\n');
|
|
33
|
+
return { dir, app };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Faux engine : rend des réponses selon le chemin ; garde les appels */
|
|
37
|
+
function fakeEngine(routes) {
|
|
38
|
+
const calls = [];
|
|
39
|
+
const fetchImpl = async (url, init = {}) => {
|
|
40
|
+
const u = new URL(url);
|
|
41
|
+
const body = init.body ? JSON.parse(init.body) : undefined;
|
|
42
|
+
calls.push({ method: init.method || 'GET', path: u.pathname, headers: init.headers, body });
|
|
43
|
+
const r = routes(init.method || 'GET', u.pathname, body, calls);
|
|
44
|
+
const [status, data] = r || [404, { error: { code: 'not_found', message: 'no route' } }];
|
|
45
|
+
return { status, ok: status >= 200 && status < 300, json: async () => data };
|
|
46
|
+
};
|
|
47
|
+
return { calls, fetchImpl };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const capture = async (fn) => {
|
|
51
|
+
const lines = [];
|
|
52
|
+
const log = console.log;
|
|
53
|
+
console.log = (...a) => lines.push(a.join(' '));
|
|
54
|
+
const before = process.exitCode;
|
|
55
|
+
process.exitCode = undefined;
|
|
56
|
+
try {
|
|
57
|
+
await fn();
|
|
58
|
+
} finally {
|
|
59
|
+
console.log = log;
|
|
60
|
+
}
|
|
61
|
+
const code = process.exitCode;
|
|
62
|
+
process.exitCode = before;
|
|
63
|
+
return { out: lines.join('\n').replace(/\x1b\[[0-9;]*m/g, ''), code };
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
test('ls : état, erreur située, modèle invalide, clé service_role et x-poad-by', async (t) => {
|
|
67
|
+
const box = sandbox(t);
|
|
68
|
+
const e = fakeEngine((m, p) => (m === 'GET' && p === '/meta/v1/transforms' ? [200, LIST] : null));
|
|
69
|
+
const r = await capture(() => transform.main({}, ['ls'], { cwd: box.app, fetch: e.fetchImpl, started: async () => true }));
|
|
70
|
+
assert.match(r.out, /commandes_propres {2}view staging/);
|
|
71
|
+
assert.match(r.out, /ventes_par_mois {2}table, API \(connectes\)/);
|
|
72
|
+
assert.match(r.out, /column "x" does not exist \(poad\/transforms\/ventes_par_mois.sql:9\)/);
|
|
73
|
+
assert.match(r.out, /casse.sql:1 {2}cycle : casse → casse/);
|
|
74
|
+
assert.strictEqual(e.calls[0].headers.authorization, 'Bearer LOCAL-SERVICE-x');
|
|
75
|
+
assert.strictEqual(e.calls[0].headers['x-poad-by'], 'cli');
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test('check : code 1 si un modèle est invalide', async (t) => {
|
|
79
|
+
const box = sandbox(t);
|
|
80
|
+
const e = fakeEngine((m, p) => (p === '/meta/v1/transforms' ? [200, LIST] : null));
|
|
81
|
+
const r = await capture(() => transform.main({}, ['check'], { cwd: box.app, fetch: e.fetchImpl, started: async () => true }));
|
|
82
|
+
assert.strictEqual(r.code, 1);
|
|
83
|
+
assert.match(r.out, /✖ poad\/transforms\/casse.sql:1 {2}cycle/);
|
|
84
|
+
assert.match(r.out, /1 of 3 model\(s\) invalid/);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test('run : sélecteurs envoyés, passage suivi modèle par modèle', async (t) => {
|
|
88
|
+
const box = sandbox(t);
|
|
89
|
+
let polls = 0;
|
|
90
|
+
const e = fakeEngine((m, p) => {
|
|
91
|
+
if (m === 'POST' && p === '/meta/v1/transforms/run') return [202, { queued: 4, run_id: RUN, waiting: false }];
|
|
92
|
+
if (m === 'GET' && p === `/meta/v1/transforms/runs/${RUN}`) {
|
|
93
|
+
polls++;
|
|
94
|
+
return [200, polls < 2 ? { status: 'running', models: [{ model: 'commandes_propres', status: 'ok', materialized: 'view', duration_ms: 7 }] } : { status: 'failed', ok: 1, failed: 1, skipped: 1, duration_ms: 40, models: [{ model: 'commandes_propres', status: 'ok', materialized: 'view', duration_ms: 7 }, { model: 'ventes_par_mois', status: 'failed', error_message: 'boom', error_line: 9, error_col: 8 }, { model: 'top', status: 'skipped', because: 'ventes_par_mois' }] }];
|
|
95
|
+
}
|
|
96
|
+
return null;
|
|
97
|
+
});
|
|
98
|
+
const r = await capture(() => transform.main({}, ['run', 'commandes_propres+'], { cwd: box.app, fetch: e.fetchImpl, started: async () => true, sleep: async () => {} }));
|
|
99
|
+
assert.deepStrictEqual(e.calls[0].body, { trigger: 'manual', selection: ['commandes_propres+'] });
|
|
100
|
+
assert.strictEqual(r.code, 1);
|
|
101
|
+
assert.match(r.out, /✔ commandes_propres {2}view, 7 ms/);
|
|
102
|
+
assert.match(r.out, /✖ ventes_par_mois {2}boom {2}\(line 9, column 8\)/);
|
|
103
|
+
assert.match(r.out, /- top {2}skipped: ventes_par_mois failed/);
|
|
104
|
+
assert.strictEqual((r.out.match(/commandes_propres {2}view/g) || []).length, 1);
|
|
105
|
+
assert.match(r.out, /poad logs transform run=7c2e1d90/);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test('run : sélecteur mal formé, engine trop ancien', async (t) => {
|
|
109
|
+
const box = sandbox(t);
|
|
110
|
+
let r = await capture(() => transform.main({}, ['run', 'Ventes!'], { cwd: box.app, fetch: async () => assert.fail('no call'), started: async () => true }));
|
|
111
|
+
assert.strictEqual(r.code, 2);
|
|
112
|
+
const old = sandbox(t, { engine: '0.71.0' });
|
|
113
|
+
r = await capture(() => transform.main({}, ['ls'], { cwd: old.app, fetch: async () => assert.fail('no call'), started: async () => true }));
|
|
114
|
+
assert.match(r.out, /engine 0.72.0 or later/);
|
|
115
|
+
assert.ok(transform.supportsTransforms({ engine: '0.72.0-transform' }));
|
|
116
|
+
assert.ok(!transform.supportsTransforms({ engine: '0.71.0' }));
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test('new : fichier avec un en-tête minimal, jamais écrasé', async (t) => {
|
|
120
|
+
const box = sandbox(t);
|
|
121
|
+
let r = await capture(() => transform.main({}, ['new', 'ventes', '--table', '--from', 'commandes'], { cwd: box.app }));
|
|
122
|
+
const file = path.join(box.app, 'poad', 'transforms', 'ventes.sql');
|
|
123
|
+
assert.strictEqual(fs.readFileSync(file, 'utf8'), '/* ---\nmaterialized: table\napi: false\n--- */\nselect *\nfrom commandes\n');
|
|
124
|
+
r = await capture(() => transform.main({}, ['new', 'ventes'], { cwd: box.app }));
|
|
125
|
+
assert.match(r.out, /already exists/);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
test('preview : tableau, rien d’écrit', async (t) => {
|
|
129
|
+
const box = sandbox(t);
|
|
130
|
+
const e = fakeEngine((m, p, b) => (p === '/meta/v1/transforms/preview' ? [200, { name: b.name, columns: [{ name: 'mois', type: 'date' }, { name: 'n', type: 'bigint' }], rows: [{ mois: '2026-09-01', n: 3 }], truncated: false, duration_ms: 4 }] : null));
|
|
131
|
+
const r = await capture(() => transform.main({}, ['preview', 'ventes_par_mois', '--limit', '5'], { cwd: box.app, fetch: e.fetchImpl, started: async () => true }));
|
|
132
|
+
assert.deepStrictEqual(e.calls[0].body, { name: 'ventes_par_mois', limit: 5 });
|
|
133
|
+
assert.match(r.out, /2026-09-01 {2}3/);
|
|
134
|
+
assert.match(r.out, /nothing was written/);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
test('pull : le texte gardé en base devient poad/transforms/<nom>.sql', async (t) => {
|
|
138
|
+
const box = sandbox(t);
|
|
139
|
+
const e = fakeEngine((m, p) => (p === '/meta/v1/transforms/ventes/sql' ? [200, { name: 'ventes', stored: 'console', text: 'select 1' }] : null));
|
|
140
|
+
await capture(() => transform.main({}, ['pull', 'ventes'], { cwd: box.app, fetch: e.fetchImpl, started: async () => true }));
|
|
141
|
+
assert.strictEqual(fs.readFileSync(path.join(box.app, 'poad', 'transforms', 'ventes.sql'), 'utf8'), 'select 1\n');
|
|
142
|
+
const r = await capture(() => transform.main({}, ['pull', 'ventes'], { cwd: box.app, fetch: e.fetchImpl, started: async () => true }));
|
|
143
|
+
assert.match(r.out, /already exists/);
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
test('poad logs : « transform » est un service, transform=<nom> filtre le modèle', () => {
|
|
147
|
+
const { attrConditions } = require('../utils/logline');
|
|
148
|
+
assert.deepStrictEqual(attrConditions({ transform: true }).conditions, []);
|
|
149
|
+
assert.deepStrictEqual(attrConditions({ transform: 'ventes' }).conditions, [["attrs->>'model' = ?", 'ventes']]);
|
|
150
|
+
assert.deepStrictEqual(attrConditions({ model: 'ventes' }).conditions, [["attrs->>'model' = ?", 'ventes']]);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
test('poad deploy : poad/transforms (sous-dossiers compris) est dans l’archive', (t) => {
|
|
154
|
+
const dir = tmpdir(t, 'poad-transform-bundle-');
|
|
155
|
+
fs.mkdirSync(path.join(dir, 'transforms', 'staging'), { recursive: true });
|
|
156
|
+
fs.writeFileSync(path.join(dir, 'config.toml'), 'project_id = "demo"\n');
|
|
157
|
+
fs.writeFileSync(path.join(dir, 'transforms', 'staging', 'a.sql'), 'select 1\n');
|
|
158
|
+
const bundle = require('../utils/cloud/bundle');
|
|
159
|
+
assert.ok(bundle.DIRS.includes('transforms'));
|
|
160
|
+
const { files } = bundle.build(dir);
|
|
161
|
+
assert.ok(files.some((f) => f.path === 'transforms/staging/a.sql'), JSON.stringify(files));
|
|
162
|
+
assert.ok(zlib.gunzipSync(bundle.build(dir).tgz).includes(Buffer.from('transforms/staging/a.sql')));
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
test('poad start : un dossier sans .sql ne demande rien à l’engine', (t) => {
|
|
166
|
+
const box = sandbox(t);
|
|
167
|
+
const { hasModels } = require('../utils/transforms');
|
|
168
|
+
// root : comme findPoadDir, un chemin dans poad/ (le dossier des modèles est à côté)
|
|
169
|
+
const poadDir = path.join(box.app, 'poad');
|
|
170
|
+
const root = path.join(poadDir, 'config.toml');
|
|
171
|
+
assert.strictEqual(hasModels(root), false);
|
|
172
|
+
fs.mkdirSync(path.join(poadDir, 'transforms', 'tests'), { recursive: true });
|
|
173
|
+
fs.writeFileSync(path.join(poadDir, 'transforms', 'tests', 'x.sql'), 'select 1');
|
|
174
|
+
assert.strictEqual(hasModels(root), false);
|
|
175
|
+
fs.writeFileSync(path.join(poadDir, 'transforms', 'a.sql'), 'select 1');
|
|
176
|
+
assert.strictEqual(hasModels(root), true);
|
|
177
|
+
});
|
|
@@ -39,7 +39,8 @@ const quote = (s) => (/^[a-z_][a-z0-9_]*$/.test(s) ? s : `"${String(s).replace(/
|
|
|
39
39
|
/** Le correctif qui sert de nouveau l'objet à anon et authenticated, sous RLS */
|
|
40
40
|
function fixFor(i) {
|
|
41
41
|
const id = `${quote(i.schema)}.${quote(i.name)}`;
|
|
42
|
-
if (i.reason === 'security_definer')
|
|
42
|
+
if (i.reason === 'security_definer')
|
|
43
|
+
return `alter function ${i.signature ? (/^[^(]*\./.test(i.signature) ? i.signature : `${quote(i.schema)}.${i.signature}`) : `${id}(…)`} security invoker; or, if it needs its owner's rights: move the body to private.${quote(i.name)} (SECURITY DEFINER, revoke execute from anon, authenticated) and keep ${id} as a SECURITY INVOKER function that checks auth.uid() and calls it`;
|
|
43
44
|
if (i.reason === 'view_owner_rights') return `alter view ${id} set (security_invoker = true);`;
|
|
44
45
|
return 'read it through a SECURITY INVOKER function that returns only allowed rows, or replace it with a table and policies';
|
|
45
46
|
}
|
|
@@ -75,6 +76,56 @@ function readLocal(container) {
|
|
|
75
76
|
}
|
|
76
77
|
}
|
|
77
78
|
|
|
79
|
+
/**
|
|
80
|
+
* La même requête, par une connexion pg déjà ouverte (poad migrate, poad start, poad db reset) : les lignes de
|
|
81
|
+
* psql (lecture seule, ON_ERROR_STOP) sont retirées, :'schemas' devient un paramètre. Renvoie les objets ; null si
|
|
82
|
+
* illisible (rôles anon / authenticated absents…).
|
|
83
|
+
*/
|
|
84
|
+
async function query(client, schemas) {
|
|
85
|
+
const text = fs
|
|
86
|
+
.readFileSync(path.join(__dirname, 'api-exposure.sql'), 'utf8')
|
|
87
|
+
.split('\n')
|
|
88
|
+
.filter((l) => !/^\s*(set default_transaction_read_only|\\set)\b/.test(l))
|
|
89
|
+
.join('\n')
|
|
90
|
+
.replace(":'schemas'", '$1');
|
|
91
|
+
try {
|
|
92
|
+
const { rows } = await client.query(text, [schemas.filter((s) => /^[A-Za-z0-9_]{1,63}$/.test(s)).join(',')]);
|
|
93
|
+
const o = JSON.parse(Object.values(rows[0] || {})[0] || 'null');
|
|
94
|
+
return o && Array.isArray(o.items) ? o.items : null;
|
|
95
|
+
} catch {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const keyOf = (i) => `${i.kind}:${i.schema}.${i.name}`;
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Après poad migrate : objets accordés à anon ou authenticated (GRANT EXECUTE / SELECT : le signal d'intention) que
|
|
104
|
+
* l'API de cet engine ne leur sert pas. before : la liste avant les migrations (null : inconnue) ; created : ceux que
|
|
105
|
+
* les migrations de ce passage ont fait apparaître. Rien à dire avant 0.64.0 (l'API les servait). Pure.
|
|
106
|
+
*/
|
|
107
|
+
function afterMigrate({ engine = null, before = null, after = null } = {}) {
|
|
108
|
+
if (!Array.isArray(after) || phaseOf(engine) === 'served') return { engine, count: 0, created: [], items: [] };
|
|
109
|
+
const had = new Set((before || []).map(keyOf));
|
|
110
|
+
const x = impact({ current: engine, target: engine, items: after });
|
|
111
|
+
const items = x.items.map((i) => ({ ...i, created: Array.isArray(before) && !had.has(keyOf(i)) }));
|
|
112
|
+
return { engine, phase: x.phase, count: items.length, created: items.filter((i) => i.created).map((i) => `${i.schema}.${i.name}`), items };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Lignes de poad migrate ; full : la liste (des migrations viennent d'être appliquées), sinon un rappel d'une ligne */
|
|
116
|
+
function migrateLines(x, chalk, { full = true, max = 20 } = {}) {
|
|
117
|
+
if (!x || !x.count) return [];
|
|
118
|
+
const n = `${x.count} function(s) or view(s)`;
|
|
119
|
+
if (!full) return [chalk.yellowBright(` ⚠ ${n} granted to anon or authenticated are not served to them by the API (403 not_exposed): "poad migrate --json" or the Migrations screen of the console list them with their fix.`)];
|
|
120
|
+
const out = [chalk.yellowBright(` ⚠ ${n} granted to anon or authenticated are not served to them by the API: they would bypass RLS, so a front end gets 403 not_exposed (service_role and SQL still work).`)];
|
|
121
|
+
for (const i of x.items.slice(0, max)) {
|
|
122
|
+
out.push(` ${chalk.bold(`${i.schema}.${i.name}`)}${i.created ? chalk.yellowBright(' (new)') : ''} ${chalk.grey(`(${i.why}; granted to ${i.roles.join(', ')})`)}`);
|
|
123
|
+
out.push(chalk.grey(` fix: ${i.fix}`));
|
|
124
|
+
}
|
|
125
|
+
if (x.items.length > max) out.push(chalk.grey(` … and ${x.items.length - max} more (poad migrate --json lists them all)`));
|
|
126
|
+
return out;
|
|
127
|
+
}
|
|
128
|
+
|
|
78
129
|
/** Lignes à montrer (poad deploy, poad upgrade) ; [] si rien à dire */
|
|
79
130
|
function lines(x, chalk, { max = 20 } = {}) {
|
|
80
131
|
if (!x || !x.count || !x.change || x.change === 'none') return [];
|
|
@@ -94,4 +145,4 @@ function lines(x, chalk, { max = 20 } = {}) {
|
|
|
94
145
|
return out;
|
|
95
146
|
}
|
|
96
147
|
|
|
97
|
-
module.exports = { HIDDEN_SINCE, SERVICE_ROLE_SINCE, phaseOf, fixFor, impact, readLocal, lines };
|
|
148
|
+
module.exports = { HIDDEN_SINCE, SERVICE_ROLE_SINCE, phaseOf, fixFor, impact, readLocal, lines, query, afterMigrate, migrateLines };
|
package/utils/cloud/bundle.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Archive de déploiement : le dossier poad/ en tar.gz, par liste blanche.
|
|
2
2
|
//
|
|
3
3
|
// Entrent (chemins relatifs à poad/, sans préfixe) :
|
|
4
|
-
// dossiers migrations queries auth storage functions flows api reference sources variables types
|
|
4
|
+
// dossiers migrations queries auth storage functions flows api reference sources transforms connections variables types
|
|
5
5
|
// credentials/manifest.json noms, types et usages des credentials, sans valeur
|
|
6
6
|
// (les valeurs restent dans le coffre de chaque engine)
|
|
7
7
|
// fichiers seed.sql, config.toml (sans aucune clé secrète : stripSecrets)
|
|
@@ -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', 'connections', 'variables', 'types'];
|
|
22
|
+
const DIRS = ['migrations', 'queries', 'auth', 'storage', 'functions', 'flows', 'api', 'reference', 'sources', 'transforms', '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']);
|
package/utils/help-details.js
CHANGED
|
@@ -328,9 +328,15 @@ const sheets = {
|
|
|
328
328
|
],
|
|
329
329
|
},
|
|
330
330
|
migrate: {
|
|
331
|
-
usage: ['poad migrate', 'poad migrate --force-reference'],
|
|
332
|
-
text: [
|
|
333
|
-
|
|
331
|
+
usage: ['poad migrate', 'poad migrate --force-reference', 'poad migrate --json'],
|
|
332
|
+
text: [
|
|
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
|
+
'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
|
+
options: [
|
|
337
|
+
['--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'],
|
|
339
|
+
],
|
|
334
340
|
},
|
|
335
341
|
migration: {
|
|
336
342
|
usage: ['poad migration new <name>', 'poad migration list'],
|
|
@@ -357,6 +363,24 @@ const alias = (of, name) => ({
|
|
|
357
363
|
sheets.function = alias('functions', 'function');
|
|
358
364
|
sheets.flow = alias('flows', 'flow');
|
|
359
365
|
sheets.sources = alias('source', 'sources');
|
|
366
|
+
sheets.transform = {
|
|
367
|
+
usage: ['poad transform ls [--json]', 'poad transform new <name> [--table|--view] [--from <table>]', 'poad transform check', 'poad transform run [<selector>…] [--changed] [--detach]', 'poad transform preview <name> [--limit <n>]', 'poad transform graph', 'poad transform pull <name> [--force] [--stdout] --env <name>'],
|
|
368
|
+
text: [
|
|
369
|
+
'Transformations (engine 0.72.0+): one select per file, poad/transforms/<name>.sql, with a YAML header in a comment (/* --- materialized: view|table, schema, api, lecture, depends_on, timeout --- */). poad builds it as a view (security_invoker) or a table recomputed in one transaction, in the order of their dependencies (read from the SQL: from, join; cycles refused).',
|
|
370
|
+
'The file is the declaration: the engine creates and reshapes the object, outside the migrations and "poad db diff" (marked poad:transform). Built at poad start, poad db reset and poad deploy when the file changed, or on demand. Not served by the API unless api: true.',
|
|
371
|
+
],
|
|
372
|
+
options: [
|
|
373
|
+
['ls', 'models, their last build (rows, duration, error with its line), what they read'],
|
|
374
|
+
['new <name>', 'write poad/transforms/<name>.sql with a minimal header (--table, --from <table>)'],
|
|
375
|
+
['check', 'read every model through the engine: header, query, graph, cycles; nothing is built (exit 1 if one is invalid)'],
|
|
376
|
+
['run [<selector>…]', 'build now and follow the run (all by default); name, name+ (and what reads it), +name (and what it reads); --changed: only what changed since its last build'],
|
|
377
|
+
['preview <name>', 'first rows, computed in a transaction rolled back (30 s at most)'],
|
|
378
|
+
['graph', 'lineage as text'],
|
|
379
|
+
['pull <name>', 'bring a model created in the poad.io console into poad/transforms (--env)'],
|
|
380
|
+
],
|
|
381
|
+
notes: ['Logs: poad logs transform (model=<name>, run=<id>, event=model_failed, trigger=manual|deploy|reset|start). Never a row value.'],
|
|
382
|
+
};
|
|
383
|
+
sheets.transforms = alias('transform', 'transforms');
|
|
360
384
|
sheets.relation = {
|
|
361
385
|
usage: ['poad relation ls [table] [--json]', 'poad relation add <table.column> <table.column> [--name <relation>]', 'poad relation rm <table.column> <table.column>', 'poad relation suggest <table>', 'poad relation check <table.column> <table.column>'],
|
|
362
386
|
text: [
|
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', object: 'object', trigger: 'trigger_kind', connection: 'connection', action: 'action', type: 'connection_type', host: 'host', user: 'user_id', device: 'device' };
|
|
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', object: 'releves/mars.csv', trigger: 'storage', connection: 'sncf', action: 'create_task', type: 'todoist', host: 'api.sncf.com', user: '4dbcaf19-7549-4c48-a3ad-f6bc173d3c48', device: 'alice-tel' };
|
|
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', object: 'object', trigger: 'trigger_kind', connection: 'connection', action: 'action', type: 'connection_type', host: 'host', user: 'user_id', device: 'device', transform: 'model' };
|
|
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', object: 'releves/mars.csv', trigger: 'storage', connection: 'sncf', action: 'create_task', type: 'todoist', host: 'api.sncf.com', user: '4dbcaf19-7549-4c48-a3ad-f6bc173d3c48', device: 'alice-tel', transform: 'ventes_par_mois' };
|
|
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
|
|
|
@@ -23,6 +23,8 @@ const attrConditions = (args = {}) => {
|
|
|
23
23
|
for (const [option, attr] of Object.entries(ATTR_OPTIONS)) {
|
|
24
24
|
const value = args[option];
|
|
25
25
|
if (value === undefined) continue;
|
|
26
|
+
// « poad logs transform » : le service, pas l'option transform=<modèle>
|
|
27
|
+
if (value === true && option === 'transform') continue;
|
|
26
28
|
if (value === true || value === '') return { error: `${option}=<${option === 'outcome' ? 'outcome' : 'name'}>: a value is expected, such as ${option}=${EXAMPLES[option]}` };
|
|
27
29
|
conditions.push([`attrs->>'${attr}' = ?`, String(value)]);
|
|
28
30
|
}
|
package/utils/migrate-run.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// Application des migrations avec affichage, partagée par poad migrate et poad start
|
|
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
6
|
const chalk = require('chalk-v2');
|
|
6
7
|
const migrations = require('./migrations');
|
|
7
8
|
const rel = (p) => path.relative(process.cwd(), p);
|
|
@@ -16,6 +17,16 @@ module.exports = async (root, config, { quietWhenNone = false } = {}) => {
|
|
|
16
17
|
return false;
|
|
17
18
|
}
|
|
18
19
|
const { applied, failed, state } = result;
|
|
20
|
+
if (report) {
|
|
21
|
+
Object.assign(report, {
|
|
22
|
+
applied: applied.map((m) => m.file),
|
|
23
|
+
failed: failed ? { file: failed.migration.file, message: failed.message } : null,
|
|
24
|
+
pending: state.pending.filter((m) => !applied.includes(m)).map((m) => m.file),
|
|
25
|
+
unprotected: result.unprotected || [],
|
|
26
|
+
queries: result.queries || null,
|
|
27
|
+
api_exposure: result.apiExposure || null,
|
|
28
|
+
});
|
|
29
|
+
}
|
|
19
30
|
|
|
20
31
|
for (const m of state.changed) {
|
|
21
32
|
console.log(chalk.yellowBright(` ${m.file} changed after it was applied: it is not replayed. Write a new migration instead.`));
|
|
@@ -53,5 +64,8 @@ module.exports = async (root, config, { quietWhenNone = false } = {}) => {
|
|
|
53
64
|
console.log(chalk.yellowBright(` ⚠ ${t.schema}.${t.name}: row level security is off, so ${who} can read${t.anon_write ? ' and change' : ''} every row.`));
|
|
54
65
|
console.log(chalk.grey(` alter table ${t.schema}.${t.name} enable row level security; (then add policies)`));
|
|
55
66
|
}
|
|
67
|
+
// Fonctions et vues accordées à anon ou authenticated que l'API ne leur sert pas (SECURITY DEFINER, vues sans
|
|
68
|
+
// security_invoker, vues matérialisées) : même règle que poad deploy et poad upgrade (utils/api-exposure)
|
|
69
|
+
for (const l of require('./api-exposure').migrateLines(result.apiExposure, chalk, { full: exposureList || applied.length > 0 })) console.log(l);
|
|
56
70
|
return qr.errors.length === 0;
|
|
57
71
|
};
|
package/utils/migrations.js
CHANGED
|
@@ -143,6 +143,10 @@ async function migrate(root, config, { onApply } = {}) {
|
|
|
143
143
|
try {
|
|
144
144
|
await client.query('select pg_advisory_lock($1)', [LOCK_ID]);
|
|
145
145
|
const state = await status(root, client);
|
|
146
|
+
// Ce que l'API ne sert pas à anon ni à authenticated alors qu'ils en ont le droit, avant les migrations : ce
|
|
147
|
+
// qu'elles font apparaître est signalé et va au puits de logs (event=api_exposure)
|
|
148
|
+
const exposure = require('./api-exposure');
|
|
149
|
+
const before = state.pending.length ? await exposure.query(client, exposedSchemas(config)) : null;
|
|
146
150
|
for (const m of state.pending) {
|
|
147
151
|
try {
|
|
148
152
|
await client.query('begin');
|
|
@@ -164,13 +168,39 @@ async function migrate(root, config, { onApply } = {}) {
|
|
|
164
168
|
// exposées sans RLS
|
|
165
169
|
const queries = await require('./queries').sync(root, client);
|
|
166
170
|
const unprotected = await unprotectedTables(client, exposedSchemas(config));
|
|
167
|
-
|
|
171
|
+
const apiExposure = exposure.afterMigrate({ engine: config.engine, before, after: await exposure.query(client, exposedSchemas(config)) });
|
|
172
|
+
if (apiExposure.created.length) await logApiExposure(client, apiExposure, applied);
|
|
173
|
+
return { applied, failed: null, state, queries, unprotected, apiExposure };
|
|
168
174
|
} finally {
|
|
169
175
|
await client.query('select pg_advisory_unlock($1)', [LOCK_ID]).catch(() => {});
|
|
170
176
|
await client.end().catch(() => {});
|
|
171
177
|
}
|
|
172
178
|
}
|
|
173
179
|
|
|
180
|
+
/**
|
|
181
|
+
* Puits de logs (service cli, event=api_exposure) : une migration vient de créer des fonctions ou vues accordées à
|
|
182
|
+
* anon ou authenticated que l'API ne leur sert pas. Noms et raisons seulement, jamais de SQL ni de secret.
|
|
183
|
+
*/
|
|
184
|
+
async function logApiExposure(client, x, applied) {
|
|
185
|
+
const created = x.items.filter((i) => i.created);
|
|
186
|
+
const attrs = {
|
|
187
|
+
event: 'api_exposure',
|
|
188
|
+
via: 'poad migrate',
|
|
189
|
+
migrations: applied.map((m) => `poad/migrations/${m.file}`).slice(-20),
|
|
190
|
+
api_hidden: created.length,
|
|
191
|
+
functions: created.filter((i) => i.kind === 'function').length,
|
|
192
|
+
views: created.filter((i) => i.kind !== 'function').length,
|
|
193
|
+
objects: created.slice(0, 40).map((i) => `${i.schema}.${i.name}`),
|
|
194
|
+
reasons: [...new Set(created.map((i) => i.reason))],
|
|
195
|
+
roles: [...new Set(created.flatMap((i) => i.roles))],
|
|
196
|
+
granted_total: x.count,
|
|
197
|
+
engine: x.engine || null,
|
|
198
|
+
fix: created.some((i) => i.reason === 'security_definer') ? 'public SECURITY INVOKER function that checks auth.uid() and calls a SECURITY DEFINER body in private (or alter function … security invoker)' : created[0].fix,
|
|
199
|
+
};
|
|
200
|
+
const msg = `API : ${created.length} fonction(s) ou vue(s) accordée(s) à anon ou authenticated mais non servie(s) (403 not_exposed) : ${attrs.objects.slice(0, 5).join(', ')}${created.length > 5 ? '…' : ''}`;
|
|
201
|
+
await client.query("insert into _logs.entries (ts, level, service, msg, attrs) values (now(), 'warn', 'cli', $1, $2::jsonb)", [msg, JSON.stringify(attrs)]).catch(() => {});
|
|
202
|
+
}
|
|
203
|
+
|
|
174
204
|
/** Schémas servis par /rest/v1 : [data] schemas de config.toml, public par défaut */
|
|
175
205
|
const exposedSchemas = (config) => {
|
|
176
206
|
const s = config.data && config.data.schemas;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// Transformations (poad/transforms, engine 0.72.0+) : après les migrations, les tables de référence et le seed de
|
|
2
|
+
// poad start (et donc de poad db reset), le CLI demande à l'engine de construire les modèles : tous sur une base
|
|
3
|
+
// neuve (le seed vient d'arriver), sinon ceux dont le fichier a changé depuis leur dernière construction. Le
|
|
4
|
+
// passage est suivi jusqu'à sa fin ; ses journaux sont dans poad logs transform.
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
|
|
8
|
+
const dir = (root) => path.join(path.dirname(root), 'transforms');
|
|
9
|
+
|
|
10
|
+
/** Le dossier contient-il au moins un modèle (.sql, sous-dossiers compris, sauf tests/) ? */
|
|
11
|
+
const hasModels = (root) => {
|
|
12
|
+
const walk = (d, depth) => {
|
|
13
|
+
let entries = [];
|
|
14
|
+
try {
|
|
15
|
+
entries = fs.readdirSync(d, { withFileTypes: true });
|
|
16
|
+
} catch {
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
return entries.some((e) => (e.isDirectory() ? !(depth === 0 && e.name === 'tests') && !e.name.startsWith('.') && depth < 6 && walk(path.join(d, e.name), depth + 1) : e.name.endsWith('.sql')));
|
|
20
|
+
};
|
|
21
|
+
return walk(dir(root), 0);
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/** Lance le passage et le suit ; rend false si un modèle a échoué */
|
|
25
|
+
const build = async (root, config, { fresh = false, fetchImpl = fetch, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) => {
|
|
26
|
+
const chalk = require('chalk-v2');
|
|
27
|
+
if (!hasModels(root)) return true;
|
|
28
|
+
if (!require('../project/transform').supportsTransforms(config)) {
|
|
29
|
+
console.log(chalk.yellowBright(` poad/transforms holds models, but engine ${config.engine} does not build them: "poad upgrade" (0.72.0+).`));
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
const base = `http://localhost:${config.web.port}/meta/v1/transforms`;
|
|
33
|
+
const headers = { apikey: config.auth.service, authorization: `Bearer ${config.auth.service}`, 'content-type': 'application/json', 'x-poad-by': 'cli' };
|
|
34
|
+
const call = async (method, route, body) => {
|
|
35
|
+
const res = await fetchImpl(`${base}${route}`, { method, headers, ...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(30000) });
|
|
36
|
+
const data = await res.json().catch(() => null);
|
|
37
|
+
if (!res.ok) throw new Error((data && data.error && data.error.message) || `HTTP ${res.status}`);
|
|
38
|
+
return data;
|
|
39
|
+
};
|
|
40
|
+
try {
|
|
41
|
+
const q = await call('POST', '/run', fresh ? { trigger: 'reset' } : { trigger: 'start', stale: true });
|
|
42
|
+
let runId = q.run_id;
|
|
43
|
+
for (let i = 0; !runId && i < 3600; i++) {
|
|
44
|
+
await sleep(500);
|
|
45
|
+
runId = (await call('GET', `/queue/${q.queued}`)).run_id;
|
|
46
|
+
}
|
|
47
|
+
let run;
|
|
48
|
+
for (let i = 0; i < 7200; i++) {
|
|
49
|
+
run = await call('GET', `/runs/${runId}`);
|
|
50
|
+
if (run.status !== 'running') break;
|
|
51
|
+
await sleep(500);
|
|
52
|
+
}
|
|
53
|
+
if (run.status === 'empty') return true;
|
|
54
|
+
for (const m of run.models.filter((x) => x.status !== 'ok')) console.log(chalk.yellowBright(` transform ${m.model}: ${m.status === 'skipped' ? `skipped (${m.because} failed)` : `${m.error_message}${m.error_line ? ` (line ${m.error_line})` : ''}`}`));
|
|
55
|
+
const line = `${run.ok} model(s) built${run.failed ? `, ${run.failed} failed` : ''}${run.skipped ? `, ${run.skipped} skipped` : ''} (${run.duration_ms} ms)`;
|
|
56
|
+
console.log(run.status === 'ok' ? `${chalk.greenBright('✔')} Transformations: ${chalk.grey(line)}` : chalk.yellowBright(` Transformations: ${line}: poad logs transform run=${runId.slice(0, 8)}`));
|
|
57
|
+
return run.status === 'ok';
|
|
58
|
+
} catch (err) {
|
|
59
|
+
console.log(chalk.yellowBright(` Transformations not built: ${err.message} ("poad transform run" later).`));
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
module.exports = { dir, hasModels, build };
|