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.
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.73.0",
3
+ "version": "2.74.1",
4
4
  "engine": "0.28.0",
5
5
  "runner": "0.5.0",
6
6
  "main": "index.js",
package/project/cli.js CHANGED
@@ -71,14 +71,16 @@ module.exports = {
71
71
  types: 'TypeScript types of the database for createClient<Database>() (out=src/types/database.ts, role=authenticated|anon|service_role)',
72
72
  env: 'TypeScript types of the public variables (PUBLIC_*) for poad.env (out=src/types/poad-env.ts)',
73
73
  },
74
- migrate: 'Apply pending migrations of poad/migrations and named queries of poad/queries (poad start does it too)',
75
- migration: 'Database migrations: migration new <name>, migration list',
74
+ migrate: 'Apply pending migrations of poad/migrations and named queries of poad/queries (poad start does it too); migrate list | pull | renumber <version> [--env <name>]: the folder against poad.io',
75
+ migration: 'Database migrations: migration new <name>, migration list [--env <name>], migration pull [--env <name>] (the migrations of poad.io missing from the folder)',
76
76
  functions: 'Functions of the project (JS/TS, served on /functions/v1/<name>): new, list, types',
77
77
  function: 'Alias of poad functions',
78
78
  flows: 'Flows of the project (automations in poad/flows/<name>.json, engine 0.18.0+, needs Valkey): new, list, run, runs, show, cancel; --env <name> for poad.io',
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/deploy.js CHANGED
@@ -20,7 +20,37 @@ const FAILED = ['failed', 'error', 'cancelled', 'canceled', 'refused'];
20
20
 
21
21
  const names = (list) => (Array.isArray(list) ? list : []).map((m) => (typeof m === 'string' ? m : m && (m.name || m.version || m.file || m.migration)) || '?');
22
22
  const errorsOf = (list) =>
23
- (Array.isArray(list) ? list : []).map((e) => (typeof e === 'string' ? { migration: null, message: e } : { migration: (e && (e.migration || e.name || e.version || e.file)) || null, message: String((e && (e.message || e.error)) || 'error'), code: (e && e.code) || null, files: Array.isArray(e && e.files) ? e.files.map(String) : [] }));
23
+ (Array.isArray(list) ? list : []).map((e) =>
24
+ typeof e === 'string'
25
+ ? { migration: null, message: e }
26
+ : {
27
+ migration: (e && (e.migration || e.name || e.version || e.file)) || null,
28
+ message: String((e && (e.message || e.error)) || 'error'),
29
+ code: (e && e.code) || null,
30
+ files: Array.isArray(e && e.files) ? e.files.map(String) : [],
31
+ // migrations_missing : versions (toujours) et missing (version, nom, fichier, date ; poad.io avec push.sh du 04/12/2026)
32
+ ...(Array.isArray(e && e.versions) ? { versions: e.versions.map(String) } : {}),
33
+ ...(Array.isArray(e && e.missing) ? { missing: e.missing.filter((m) => m && m.version).map((m) => ({ version: String(m.version), name: m.name || null, file: m.file || null, applied_at: m.applied_at || null })) } : {}),
34
+ },
35
+ );
36
+
37
+ const when = (at) => (typeof at === 'string' && at ? at.slice(0, 16).replace('T', ' ') + ' UTC' : null);
38
+
39
+ /** Lignes d'un refus de migrations (manquantes au dossier, hors d'ordre) avec la commande qui le lève. Pure. */
40
+ function refusalLines(e, { env, where, chalk }) {
41
+ const out = [];
42
+ if (e.code === 'migrations_missing') {
43
+ const list = e.missing && e.missing.length ? e.missing : (e.versions || []).map((v) => ({ version: v }));
44
+ out.push(` ${chalk.grey(`${list.length} migration(s) applied on ${env} and missing from poad/migrations:`)}`);
45
+ for (const m of list) out.push(` ${chalk.yellow(m.file || `${m.version} (name unknown)`)}${when(m.applied_at) ? chalk.grey(` applied ${when(m.applied_at)}`) : ''}`);
46
+ out.push(` ${chalk.grey('Bring them back, commit them, then deploy again:')} ${chalk.cyanBright(`poad migration pull${where}`)}`);
47
+ }
48
+ if (e.code === 'migrations_out_of_order') {
49
+ out.push(` ${chalk.grey(`Pending here, but older than the last migration applied on ${env}: they would run in a different order than locally. Nothing is forced; give each a version after the last one:`)}`);
50
+ for (const f of e.files || []) out.push(` ${chalk.cyanBright(`poad migrate renumber ${f.slice(0, 14)}${where}`)}`);
51
+ }
52
+ return out;
53
+ }
24
54
 
25
55
  /** Résultat d'un déploiement, ramené aux champs connus */
26
56
  function summarize(d = {}) {
@@ -125,6 +155,8 @@ module.exports = (args, raw) =>
125
155
  }
126
156
 
127
157
  const route = `v1/projects/${api.enc(id)}/branches/${api.enc(env.branch)}`;
158
+ // --env des commandes proposées : omis quand poad deploy l'aurait aussi omis (production par défaut)
159
+ const where = env.source === 'option' || !env.production ? ` --env ${env.branch}` : '';
128
160
  const headers = {};
129
161
  if (sha) headers['x-poad-sha'] = sha;
130
162
  if (dryRun) headers['x-poad-dry-run'] = '1';
@@ -150,8 +182,9 @@ module.exports = (args, raw) =>
150
182
  for (const n of m.pending) out.log(` ${chalk.yellow('○')} ${n} ${chalk.grey(dryRun ? '(would be applied)' : '(pending)')}`);
151
183
  for (const e of m.errors) {
152
184
  out.log(` ${chalk.redBright('✕')} ${e.migration ? chalk.bold(e.migration) + ': ' : ''}${e.message}`);
153
- // Refus pour migrations destructives : lesquelles, et comment confirmer
185
+ // Refus : lesquelles ; migrations manquantes ou hors d'ordre : la commande qui lève le refus
154
186
  for (const f of e.files || []) out.log(` ${chalk.yellow(f)}`);
187
+ for (const l of refusalLines(e, { env: env.branch, where, chalk })) out.log(l);
155
188
  }
156
189
  for (const w of result.warnings || []) {
157
190
  out.log(` ${chalk.yellowBright('⚠')} ${w.message}`);
@@ -185,6 +218,9 @@ module.exports = (args, raw) =>
185
218
  skipped: b.skipped,
186
219
  ...result,
187
220
  dry_run: dryRun,
221
+ // Ce qui lève un refus de migrations (poad migration pull, poad migrate renumber)
222
+ missing_migrations: result.migrations.errors.filter((e) => e.code === 'migrations_missing').flatMap((e) => (e.missing && e.missing.length ? e.missing : (e.versions || []).map((v) => ({ version: v, name: null, file: null, applied_at: null })))),
223
+ fix: result.migrations.errors.flatMap((e) => (e.code === 'migrations_missing' ? [`poad migration pull${where}`] : e.code === 'migrations_out_of_order' ? (e.files || []).map((f) => `poad migrate renumber ${f.slice(0, 14)}${where}`) : [])),
188
224
  large_references: large.map((f) => ({ path: `poad/${f.rel}`, bytes: f.size, target: f.target })),
189
225
  references,
190
226
  });
@@ -192,3 +228,4 @@ module.exports = (args, raw) =>
192
228
  });
193
229
 
194
230
  module.exports.summarize = summarize;
231
+ module.exports.refusalLines = refusalLines;
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
  /**
@@ -0,0 +1,184 @@
1
+ // poad migrate list [--env <nom>] [--project <id>] [--json]
2
+ // poad/migrations comparé à l'historique d'un environnement de poad.io : appliquée des deux côtés, en attente
3
+ // ici (le prochain poad deploy l'applique), manquante ici (poad migration pull), en attente là-haut (écrite
4
+ // sans être appliquée), conflit de version, modifiée depuis son application, hors d'ordre.
5
+ //
6
+ // poad migrate renumber <version|fichier> [--env <nom>] [--yes] [--json]
7
+ // donne à une migration en attente une version après la dernière de poad.io et du dossier (le fichier est
8
+ // renommé, son contenu ne change pas). Jamais une migration appliquée sur un environnement de poad.io ; si elle
9
+ // l'est sur l'engine local seulement, son historique local suit (même transaction que le renommage).
10
+ //
11
+ // Lecture : GET v1/projects/:id/branches/:branch/migrations?sql=0 (liste sans SQL).
12
+ const FILE_RE = /^(\d{14})_([A-Za-z0-9_-]{1,120})\.sql$/;
13
+
14
+ const when = (at) => (typeof at === 'string' && at ? at.slice(0, 16).replace('T', ' ') + ' UTC' : '');
15
+
16
+ /**
17
+ * État de chaque version, dossier contre poad.io. Pure.
18
+ * local : [{ version, name, file, checksum }] ; remote : [{ version, name, file, checksum, applied_at, applied }]
19
+ */
20
+ function compare(local = [], remote = []) {
21
+ const here = new Map(local.map((l) => [l.version, l]));
22
+ const there = new Map(remote.filter((r) => r && r.version).map((r) => [r.version, r]));
23
+ const lastApplied = [...there.values()].filter((r) => r.applied !== false).map((r) => r.version).sort().pop() || '';
24
+ const versions = [...new Set([...here.keys(), ...there.keys()])].sort();
25
+ return versions.map((version) => {
26
+ const l = here.get(version);
27
+ const r = there.get(version);
28
+ const row = { version, name: (l && l.name) || (r && r.name) || null, file: (l && l.file) || (r && r.file) || null, applied_at: (r && r.applied_at) || null };
29
+ if (l && r && r.file && l.file !== r.file) return { ...row, state: 'conflict', remote_file: r.file };
30
+ if (l && r && r.applied !== false) return { ...row, state: r.checksum && l.checksum !== r.checksum ? 'changed' : 'applied' };
31
+ if (l && r) return { ...row, state: 'pending_both' };
32
+ if (l) return { ...row, state: version < lastApplied ? 'out_of_order' : 'pending' };
33
+ if (r.applied === false) return { ...row, state: 'remote_pending' };
34
+ return { ...row, state: 'missing' };
35
+ });
36
+ }
37
+
38
+ const LABEL = {
39
+ applied: ['✔', 'greenBright', 'applied on both sides'],
40
+ changed: ['!', 'yellowBright', 'applied, the file changed since (not replayed: write a new migration)'],
41
+ pending: ['○', 'cyanBright', 'pending here: the next poad deploy applies it'],
42
+ pending_both: ['○', 'cyanBright', 'pending here and written on poad.io, not applied yet'],
43
+ out_of_order: ['✕', 'redBright', 'pending here but older than the last one applied on poad.io: poad deploy refuses it'],
44
+ missing: ['✕', 'redBright', 'applied on poad.io, missing here: poad deploy refuses'],
45
+ remote_pending: ['↓', 'yellowBright', 'written on poad.io, not applied, missing here'],
46
+ conflict: ['✕', 'redBright', 'same version, another name on poad.io'],
47
+ };
48
+
49
+ /** Version suivante : maintenant, sinon juste après la plus grande prise. Pure (now passé). */
50
+ function nextVersion(taken, now = new Date()) {
51
+ let v = Number(now.toISOString().replace(/[-:T]/g, '').slice(0, 14));
52
+ const max = Math.max(0, ...[...taken].map(Number).filter(Number.isFinite));
53
+ if (v <= max) v = max + 1;
54
+ while (taken.has(String(v))) v += 1;
55
+ return String(v);
56
+ }
57
+
58
+ async function remoteList(api, id, branch) {
59
+ const got = await api.call('GET', `v1/projects/${api.enc(id)}/branches/${api.enc(branch)}/migrations?sql=0`, { what: 'migrations' });
60
+ return Array.isArray(got && got.migrations) ? got.migrations : [];
61
+ }
62
+
63
+ const list = (raw) =>
64
+ require('../utils/cloud/cli').run(raw, { values: ['env', 'project'] }, async ({ opts, positionals, out }) => {
65
+ const api = require('../utils/cloud/api');
66
+ const cli = require('../utils/cloud/cli');
67
+ const branches = require('../utils/cloud/branches');
68
+ const migrations = require('../utils/migrations');
69
+ const { chalk } = out;
70
+ if (positionals.length) throw api.usageError('Usage: poad migrate list [--env <name>] [--json]');
71
+ const root = cli.projectRoot();
72
+ if (!root) throw api.usageError('Not in a poad project folder: cd into one.');
73
+ const { id } = cli.targetProject(opts);
74
+ const env = await branches.resolve(id, { wanted: opts.env, root });
75
+ const where = env.source === 'option' || !env.production ? ` --env ${env.branch}` : '';
76
+ const rows = compare(migrations.files(root).list, await remoteList(api, id, env.branch));
77
+ const count = (s) => rows.filter((r) => r.state === s).length;
78
+
79
+ out.log(` ${chalk.bold('Migrations')} ${cli.rel(migrations.dir(root))} ↔ ${chalk.white(id)} ${env.production ? chalk.magenta.bold(`${env.branch} (production)`) : chalk.cyan.bold(env.branch)}`);
80
+ out.log(' ');
81
+ for (const r of rows) {
82
+ const [mark, color, text] = LABEL[r.state];
83
+ out.log(` ${chalk[color](mark)} ${r.file || r.version} ${chalk.grey(`${text}${r.applied_at && r.state !== 'pending' ? `, ${when(r.applied_at)}` : ''}${r.remote_file ? ` (${r.remote_file})` : ''}`)}`);
84
+ }
85
+ if (!rows.length) out.log(chalk.grey(' None, here or on poad.io.'));
86
+ out.log(' ');
87
+ if (count('missing') || count('remote_pending')) out.log(` ${chalk.cyanBright(`poad migration pull${where}`)} ${chalk.grey('brings the missing ones into the folder.')}`);
88
+ for (const r of rows.filter((x) => x.state === 'out_of_order')) out.log(` ${chalk.cyanBright(`poad migrate renumber ${r.version}${where}`)} ${chalk.grey(`gives ${r.file} a version after the last one.`)}`);
89
+ if (count('pending') && !count('missing') && !count('out_of_order') && !count('conflict')) out.log(` ${chalk.cyanBright(`poad deploy${where}`)} ${chalk.grey(`applies the ${count('pending')} pending one(s).`)}`);
90
+ out.result({ project: id, env: env.branch, production: env.production, migrations: rows, counts: Object.fromEntries(Object.keys(LABEL).map((k) => [k, count(k)])) });
91
+ return 0;
92
+ });
93
+
94
+ const renumber = (raw) =>
95
+ require('../utils/cloud/cli').run(raw, { values: ['env', 'project'] }, async ({ opts, positionals, out }) => {
96
+ const fs = require('fs');
97
+ const path = require('path');
98
+ const api = require('../utils/cloud/api');
99
+ const cli = require('../utils/cloud/cli');
100
+ const branches = require('../utils/cloud/branches');
101
+ const migrations = require('../utils/migrations');
102
+ const { chalk } = out;
103
+ const usage = 'Usage: poad migrate renumber <version|file> [--env <name>] [--yes] [--json]';
104
+ if (positionals.length !== 1) throw api.usageError(usage);
105
+ const root = cli.projectRoot();
106
+ if (!root) throw api.usageError('Not in a poad project folder: cd into one.');
107
+ const wanted = path.basename(positionals[0]);
108
+ const local = migrations.files(root).list;
109
+ const m = local.find((l) => l.version === wanted || l.file === wanted);
110
+ if (!m) throw api.usageError(`No migration "${wanted}" in ${cli.rel(migrations.dir(root))} (a version of 14 digits, or a file name).`);
111
+ const { id } = cli.targetProject(opts);
112
+ const env = await branches.resolve(id, { wanted: opts.env, root });
113
+
114
+ // Appliquée nulle part sur poad.io : chaque environnement est lu ; un environnement illisible bloque
115
+ const all = await branches.list(id);
116
+ const taken = new Set(local.map((l) => l.version));
117
+ for (const b of all) {
118
+ let rows;
119
+ try {
120
+ rows = await remoteList(api, id, b.name);
121
+ } catch (err) {
122
+ throw new api.CloudError(`Cannot read the migrations of ${b.name} (${err.message}): nothing renamed. A migration is renumbered only once poad.io confirms it is applied nowhere; resume ${b.name} or try again.`, { code: 'environment_unreadable' });
123
+ }
124
+ const there = rows.find((r) => r.version === m.version);
125
+ if (there && there.applied !== false) {
126
+ throw new api.CloudError(`${m.file} is already applied on ${b.name}${there.applied_at ? ` (${when(there.applied_at)})` : ''}: its version stays. Nothing renamed.`, { code: 'already_applied', exit: api.EXIT.failed });
127
+ }
128
+ // Seulement la cible fixe la version : après tout ce qui y est appliqué ou écrit
129
+ if (b.name === env.branch) for (const r of rows) taken.add(r.version);
130
+ }
131
+ const version = nextVersion(taken);
132
+ const file = `${version}_${m.name}.sql`;
133
+ const target = path.join(migrations.dir(root), file);
134
+
135
+ // Engine local : appliquée là seulement, son historique suit le fichier
136
+ let client = null;
137
+ let localApplied = false;
138
+ try {
139
+ const { readConfig } = require('../utils/config');
140
+ const { isDockerExist } = require('../utils/docker');
141
+ const config = readConfig(root);
142
+ if (await isDockerExist(config.project_uuid)) {
143
+ client = await migrations.connect(config);
144
+ const r = await client.query("select 1 from poad_migrations.history where version = $1 and to_regclass('poad_migrations.history') is not null", [m.version]).catch(() => ({ rows: [] }));
145
+ localApplied = r.rows.length > 0;
146
+ }
147
+ } catch {
148
+ client = null;
149
+ }
150
+
151
+ out.log(` ${chalk.bold('Renumber')} ${m.file} → ${chalk.cyanBright(file)}`);
152
+ out.log(chalk.grey(` after the last migration of ${env.branch} and of the folder; applied on no environment of poad.io${localApplied ? '; the local history follows (applied on the local engine)' : ''}`));
153
+ try {
154
+ await cli.confirm(`Rename ${m.file} to ${file}?`, { yes: opts.yes, json: out.json });
155
+ if (fs.existsSync(target)) throw new api.CloudError(`${file} already exists: nothing renamed.`, { code: 'exists' });
156
+ if (localApplied) {
157
+ await client.query('begin');
158
+ await client.query('update poad_migrations.history set version = $1 where version = $2', [version, m.version]);
159
+ fs.renameSync(m.path, target);
160
+ await client.query('commit').catch(async (err) => {
161
+ fs.renameSync(target, m.path);
162
+ throw err;
163
+ });
164
+ } else {
165
+ fs.renameSync(m.path, target);
166
+ }
167
+ if (client) {
168
+ await client
169
+ .query("insert into _logs.entries (ts, level, service, msg, attrs) values (now(), 'info', 'cli', 'migration renumbered', $1::jsonb)", [JSON.stringify({ event: 'migration_renumbered', from: m.version, to: version, migration: `poad/migrations/${file}`, env: env.branch, local_history: localApplied })])
170
+ .catch(() => {});
171
+ }
172
+ } catch (err) {
173
+ if (client && localApplied) await client.query('rollback').catch(() => {});
174
+ throw err;
175
+ } finally {
176
+ if (client) await client.end().catch(() => {});
177
+ }
178
+ out.log(`${chalk.greenBright('✔')} ${cli.rel(target)}`);
179
+ out.log(chalk.grey(` Commit it, then "poad deploy${env.source === 'option' || !env.production ? ` --env ${env.branch}` : ''}".`));
180
+ out.result({ project: id, env: env.branch, from: m.file, to: file, version, local_history: localApplied });
181
+ return 0;
182
+ });
183
+
184
+ module.exports = { list, renumber, compare, nextVersion, FILE_RE };
@@ -1,5 +1,16 @@
1
1
  // poad migrate : applique les migrations en attente de poad/migrations
2
- module.exports = async () => {
2
+ // poad migrate pull | list | renumber : poad/migrations face à poad.io (migration-pull.js, migrate-cloud.js)
3
+ module.exports = async (args, raw = []) => {
4
+ if (raw[0] === 'pull') return require('./migration-pull')(raw.slice(1));
5
+ if (raw[0] === 'list') {
6
+ // Projet non lié et sans --env / --project : l'engine local (poad migration list)
7
+ const cli = require('../utils/cloud/cli');
8
+ const root = cli.projectRoot();
9
+ const remote = raw.slice(1).some((w) => /^(--?)?(env|project)(=|$)/.test(w)) || (root && cli.linkedId(root));
10
+ if (!remote) return require('./migration')({ list: true }, ['list']);
11
+ return require('./migrate-cloud').list(raw.slice(1));
12
+ }
13
+ if (raw[0] === 'renumber') return require('./migrate-cloud').renumber(raw.slice(1));
3
14
  const chalk = require('chalk-v2');
4
15
  const { findPoadDir } = require('../utils/findpoad');
5
16
  const { isDockerExist } = require('../utils/docker');
@@ -11,9 +22,21 @@ module.exports = async () => {
11
22
  if (!(await isDockerExist(config.project_uuid))) {
12
23
  return console.log(chalk.redBright('The project is not started: run "poad start" (it applies pending migrations too).'));
13
24
  }
14
- const ok = await require('../utils/migrate-run')(root, config);
15
- if (!ok) process.exitCode = 1;
16
- // Tables de référence : après les migrations, quand leur structure est à jour
17
- // --force-reference : le fichier fait foi même s'il retire beaucoup de lignes (garde-fou de l'engine passé)
18
- else if (!(await require('../utils/reference').sync(root, config, { force: process.argv.includes('--force-reference') }))) process.exitCode = 1;
25
+ // --json : une seule sortie, l'objet du passage (migrations appliquées, échec, api_exposure, tables sans RLS)
26
+ const json = process.argv.includes('--json');
27
+ const report = {};
28
+ const log = console.log;
29
+ if (json) console.log = () => {};
30
+ let ok;
31
+ let refOk = true;
32
+ try {
33
+ ok = await require('../utils/migrate-run')(root, config, { report, exposureList: true });
34
+ // Tables de référence : après les migrations, quand leur structure est à jour
35
+ // --force-reference : le fichier fait foi même s'il retire beaucoup de lignes (garde-fou de l'engine passé)
36
+ if (ok) refOk = await require('../utils/reference').sync(root, config, { force: process.argv.includes('--force-reference') });
37
+ } finally {
38
+ console.log = log;
39
+ }
40
+ if (!ok || !refOk) process.exitCode = 1;
41
+ if (json) console.log(JSON.stringify({ ok: Boolean(ok && refOk), ...report }, null, 2));
19
42
  };
@@ -0,0 +1,159 @@
1
+ // poad migration pull [--env <nom>] [--project <id>] [--yes] [--dry-run] [--json]
2
+ // (alias : poad migrate pull)
3
+ //
4
+ // Rapatrie dans poad/migrations les migrations d'un environnement de poad.io qui manquent au dossier : celles
5
+ // écrites là-haut par la console, le MCP ou l'assistant (appliquées, dans l'historique de la base), et celles
6
+ // écrites sans être appliquées (fichiers de /project/migrations de l'engine hébergé). poad deploy refuse tant
7
+ // qu'une migration appliquée manque au dossier (migrations_missing).
8
+ //
9
+ // GET v1/projects/:id/branches/:branch/migrations?sql=0 la liste (version, nom, date), sans SQL
10
+ // GET v1/projects/:id/branches/:branch/migrations?versions=a,b le SQL de celles qui manquent
11
+ //
12
+ // Chaque fichier garde son nom et sa version exacts (<version>_<nom>.sql) et son contenu exact (somme sha256 de
13
+ // l'historique vérifiée) ; jamais d'écrasement : une version déjà présente sous un autre nom est un conflit, dit
14
+ // et laissé tel quel. Journaux (sans SQL) : poad.io écrit event=migrations_pulled dans le puits du projet
15
+ // (poad logs cli event=migrations_pulled --env <nom>) et dans le sien.
16
+ //
17
+ // Codes de sortie : 0 rien à faire ou tout écrit, 5 une migration n'a pas pu être rapatriée (conflit, SQL
18
+ // introuvable là-haut), 4 confirmation manquante, 3 session, 2 usage, 1 autre erreur.
19
+ const FILE_RE = /^(\d{14})_([A-Za-z0-9_-]{1,120})\.sql$/;
20
+ const BATCH = 100;
21
+
22
+ /** Que faire de chaque migration de poad.io, d'après les fichiers du dossier. Pure. */
23
+ function planPull(remote = [], local = []) {
24
+ const byVersion = new Map(local.map((l) => [l.version, l]));
25
+ const plan = { pull: [], present: [], conflicts: [], unavailable: [] };
26
+ for (const m of remote) {
27
+ if (!m || typeof m.version !== 'string') continue;
28
+ const here = byVersion.get(m.version);
29
+ if (here && here.file === m.file) {
30
+ plan.present.push(m);
31
+ continue;
32
+ }
33
+ if (here) {
34
+ plan.conflicts.push({ ...m, local: here.file });
35
+ continue;
36
+ }
37
+ if (!m.file || !FILE_RE.test(m.file) || m.file.slice(0, 14) !== m.version) {
38
+ plan.unavailable.push({ ...m, problem: m.problem || 'invalid_name' });
39
+ continue;
40
+ }
41
+ if (m.problem) {
42
+ plan.unavailable.push(m);
43
+ continue;
44
+ }
45
+ plan.pull.push(m);
46
+ }
47
+ return plan;
48
+ }
49
+
50
+ const PROBLEMS = {
51
+ sql_unavailable: 'its SQL is not kept on poad.io (applied before engine 0.55, file lost)',
52
+ checksum_mismatch: 'the file on poad.io differs from what was applied',
53
+ invalid_name: 'its name is not <version>_<name>.sql',
54
+ };
55
+
56
+ const when = (at) => (typeof at === 'string' && at ? at.slice(0, 16).replace('T', ' ') + ' UTC' : null);
57
+
58
+ module.exports = (raw) =>
59
+ require('../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['dry-run'] }, async ({ opts, positionals, out }) => {
60
+ const fs = require('fs');
61
+ const path = require('path');
62
+ const crypto = require('crypto');
63
+ const api = require('../utils/cloud/api');
64
+ const cli = require('../utils/cloud/cli');
65
+ const branches = require('../utils/cloud/branches');
66
+ const migrations = require('../utils/migrations');
67
+ const { chalk } = out;
68
+
69
+ if (positionals.length) throw api.usageError(`poad migration pull: unexpected "${positionals[0]}". Usage: poad migration pull [--env <name>] [--yes] [--dry-run] [--json]`);
70
+ const root = cli.projectRoot();
71
+ if (!root) throw api.usageError('Not in a poad project folder: cd into one (the migrations are written to its poad/migrations).');
72
+ const { id } = cli.targetProject(opts);
73
+ const env = await branches.resolve(id, { wanted: opts.env, root });
74
+ const dir = migrations.dir(root);
75
+ const where = env.production && env.source !== 'option' ? '' : ` --env ${env.branch}`;
76
+ const route = `v1/projects/${api.enc(id)}/branches/${api.enc(env.branch)}/migrations`;
77
+
78
+ const listed = await api.call('GET', `${route}?sql=0`, { what: 'migrations' });
79
+ const remote = Array.isArray(listed && listed.migrations) ? listed.migrations : [];
80
+ const plan = planPull(remote, migrations.files(root).list);
81
+
82
+ out.log(` ${chalk.bold('Migrations of poad.io')} ${chalk.white(id)} → ${env.production ? chalk.magenta.bold(`${env.branch} (production)`) : chalk.cyan.bold(env.branch)}`);
83
+ out.log(chalk.grey(` ${remote.length} on poad.io, ${plan.present.length} already in ${cli.rel(dir)}`));
84
+ out.log(' ');
85
+ for (const m of plan.pull) out.log(` ${chalk.cyanBright('↓')} ${m.file}${chalk.grey(m.applied === false ? ' written on poad.io, not applied yet' : when(m.applied_at) ? ` applied ${when(m.applied_at)}` : '')}`);
86
+ for (const c of plan.conflicts) out.log(` ${chalk.redBright('✕')} ${c.file || c.version}: version ${c.version} is already used here by ${c.local}; nothing overwritten. Rename yours after the last migration of poad.io, then pull again.`);
87
+ for (const u of plan.unavailable) out.log(` ${chalk.redBright('✕')} ${u.file || u.version}: ${PROBLEMS[u.problem] || u.problem}. "poad db pull${where}" writes the real schema as a new migration instead.`);
88
+
89
+ const result = { project: id, env: env.branch, production: env.production, dir: cli.rel(dir), dry_run: Boolean(opts['dry-run']), written: [], present: plan.present.length, conflicts: plan.conflicts.map((c) => ({ version: c.version, file: c.file, local: c.local })), unavailable: plan.unavailable.map((u) => ({ version: u.version, file: u.file || null, problem: u.problem })) };
90
+ const failed = plan.conflicts.length + plan.unavailable.length > 0;
91
+
92
+ if (!plan.pull.length) {
93
+ if (!failed) out.log(`${chalk.greenBright('✔')} Nothing to pull: ${cli.rel(dir)} already has every migration of ${env.branch}.`);
94
+ out.log(' ');
95
+ out.result({ ...result, pull: [] });
96
+ return failed ? api.EXIT.failed : 0;
97
+ }
98
+ if (opts['dry-run']) {
99
+ out.log(' ');
100
+ out.log(`${chalk.greenBright('✔')} Dry run: ${plan.pull.length} migration(s) would be written; nothing changed.`);
101
+ out.log(' ');
102
+ out.result({ ...result, pull: plan.pull.map((m) => ({ version: m.version, file: m.file, applied: m.applied !== false, applied_at: m.applied_at || null })) });
103
+ return failed ? api.EXIT.failed : 0;
104
+ }
105
+ await cli.confirm(`Write ${plan.pull.length} migration(s) of ${env.branch} into ${cli.rel(dir)}?`, { yes: opts.yes, json: out.json });
106
+
107
+ fs.mkdirSync(dir, { recursive: true });
108
+ const wanted = new Map(plan.pull.map((m) => [m.version, m]));
109
+ const versions = [...wanted.keys()];
110
+ for (let i = 0; i < versions.length; i += BATCH) {
111
+ const got = await api.call('GET', `${route}?versions=${versions.slice(i, i + BATCH).join(',')}`, { what: 'migrations', timeout: 120000 });
112
+ for (const m of (got && got.migrations) || []) {
113
+ const asked = wanted.get(m && m.version);
114
+ if (!asked || m.file !== asked.file) continue;
115
+ wanted.delete(m.version);
116
+ if (m.problem || typeof m.sql !== 'string') {
117
+ result.unavailable.push({ version: m.version, file: m.file, problem: m.problem || 'sql_unavailable' });
118
+ out.log(` ${chalk.redBright('✕')} ${m.file}: ${PROBLEMS[m.problem || 'sql_unavailable']}.`);
119
+ continue;
120
+ }
121
+ // Le contenu exact de l'historique : sa somme fait foi
122
+ if (m.applied !== false && m.checksum && crypto.createHash('sha256').update(m.sql).digest('hex') !== m.checksum) {
123
+ result.unavailable.push({ version: m.version, file: m.file, problem: 'checksum_mismatch' });
124
+ out.log(` ${chalk.redBright('✕')} ${m.file}: ${PROBLEMS.checksum_mismatch}.`);
125
+ continue;
126
+ }
127
+ const target = path.join(dir, m.file);
128
+ try {
129
+ // wx : jamais d'écrasement, même d'un fichier apparu entre-temps
130
+ fs.writeFileSync(target, m.sql, { flag: 'wx' });
131
+ } catch (err) {
132
+ if (err.code !== 'EEXIST') throw err;
133
+ result.conflicts.push({ version: m.version, file: m.file, local: m.file });
134
+ out.log(` ${chalk.redBright('✕')} ${m.file}: already exists, left as it is.`);
135
+ continue;
136
+ }
137
+ result.written.push({ version: m.version, file: m.file, applied: m.applied !== false, applied_at: m.applied_at || null });
138
+ }
139
+ }
140
+ for (const [version, m] of wanted) {
141
+ result.unavailable.push({ version, file: m.file, problem: 'not_returned' });
142
+ out.log(` ${chalk.redBright('✕')} ${m.file}: not returned by poad.io, try again.`);
143
+ }
144
+
145
+ out.log(' ');
146
+ if (result.written.length) {
147
+ out.log(`${chalk.greenBright('✔')} ${result.written.length} migration(s) written to ${cli.rel(dir)}:`);
148
+ for (const w of result.written) out.log(` ${w.file}`);
149
+ out.log(chalk.grey(` Commit them (git add ${cli.rel(dir)} && git commit), then "poad deploy${where}".`));
150
+ if (result.written.some((w) => !w.applied)) out.log(chalk.grey(' Those not applied yet on poad.io are applied by that deploy.'));
151
+ }
152
+ const bad = result.conflicts.length + result.unavailable.length;
153
+ if (bad) out.log(chalk.redBright(` ${bad} migration(s) not pulled: poad deploy keeps refusing until they are in the folder.`));
154
+ out.log(' ');
155
+ out.result(result);
156
+ return bad ? api.EXIT.failed : 0;
157
+ });
158
+
159
+ module.exports.planPull = planPull;
@@ -1,7 +1,12 @@
1
1
  // poad migration new <nom> crée poad/migrations/<horodatage>_<nom>.sql
2
2
  // poad migration list migrations appliquées et en attente
3
3
  // (poad migrate applique celles en attente)
4
- module.exports = async (args = {}) => {
4
+ module.exports = async (args = {}, raw = []) => {
5
+ // poad migration pull : les migrations de poad.io qui manquent au dossier (migration-pull.js)
6
+ if (raw[0] === 'pull') return require('./migration-pull')(raw.slice(1));
7
+ // list --env / --project : le dossier face à poad.io (sans : l'engine local, plus bas)
8
+ if (raw[0] === 'list' && raw.slice(1).some((w) => /^(--?)?(env|project)(=|$)/.test(w))) return require('./migrate-cloud').list(raw.slice(1));
9
+ if (raw[0] === 'renumber') return require('./migrate-cloud').renumber(raw.slice(1));
5
10
  const chalk = require('chalk-v2');
6
11
  const path = require('path');
7
12
  const { findPoadDir } = require('../utils/findpoad');
@@ -58,5 +63,5 @@ module.exports = async (args = {}) => {
58
63
  return;
59
64
  }
60
65
 
61
- console.log(`${chalk.bold(' Usage :')} ${chalk.cyanBright('poad migration new <name>')} | ${chalk.cyanBright('poad migration list')} | ${chalk.cyanBright('poad migrate')}`);
66
+ console.log(`${chalk.bold(' Usage :')} ${chalk.cyanBright('poad migration new <name>')} | ${chalk.cyanBright('poad migration list [--env <name>]')} | ${chalk.cyanBright('poad migration pull [--env <name>]')} | ${chalk.cyanBright('poad migrate renumber <version>')} | ${chalk.cyanBright('poad migrate')}`);
62
67
  };