poad 2.74.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/package.json +1 -1
- package/project/cli.js +2 -2
- package/project/deploy.js +39 -2
- package/project/migrate-cloud.js +184 -0
- package/project/migrate.js +12 -1
- package/project/migration-pull.js +159 -0
- package/project/migration.js +7 -2
- package/test/cloud.test.js +161 -0
- package/utils/help-details.js +8 -4
package/package.json
CHANGED
package/project/cli.js
CHANGED
|
@@ -71,8 +71,8 @@ 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',
|
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) =>
|
|
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
|
|
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;
|
|
@@ -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 };
|
package/project/migrate.js
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
// poad migrate : applique les migrations en attente de poad/migrations
|
|
2
|
-
|
|
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');
|
|
@@ -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;
|
package/project/migration.js
CHANGED
|
@@ -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
|
};
|
package/test/cloud.test.js
CHANGED
|
@@ -96,8 +96,17 @@ function fakeCloud(t, behaviour = {}) {
|
|
|
96
96
|
return send(res, 200, { removed: branch });
|
|
97
97
|
}
|
|
98
98
|
if (req.method === 'POST' && (m[2] === '/clone' || m[2] === '/sync')) return send(res, 200, { name: branch, status: 'active', status_detail: 'copie depuis la production : measure', credentials_with_values: ['claude'] });
|
|
99
|
+
// Migrations de l'environnement (control/server.mjs, migrationsOfBranch) : ?sql=0 la liste, ?versions= le SQL
|
|
100
|
+
if (req.method === 'GET' && m[2] === '/migrations') {
|
|
101
|
+
const all = (behaviour.migrations && behaviour.migrations[branch]) || [];
|
|
102
|
+
const only = url.searchParams.get('versions');
|
|
103
|
+
const withSql = url.searchParams.get('sql') !== '0';
|
|
104
|
+
const list = all.filter((x) => !only || only.split(',').includes(x.version)).map(({ sql, ...x }) => (withSql && sql !== undefined ? { ...x, sql } : x));
|
|
105
|
+
return send(res, 200, { project: id, branch, migrations: list });
|
|
106
|
+
}
|
|
99
107
|
if (req.method === 'POST' && m[2] === '/deploy') {
|
|
100
108
|
const dry = req.headers['x-poad-dry-run'] === '1';
|
|
109
|
+
if (behaviour.refuse) return send(res, 200, { deploy_id: 'dr', outcome: 'refused', dry_run: dry, migrations_applied: [], migrations_pending: [], errors: [behaviour.refuse] });
|
|
101
110
|
if (behaviour.async) {
|
|
102
111
|
state.deploys.d1 = 0;
|
|
103
112
|
// La forme réelle de poad.io (control/server.mjs, deployView) : outcome, migrations_applied…
|
|
@@ -617,3 +626,155 @@ test('options : valeur manquante et option inconnue -> code 2', async (t) => {
|
|
|
617
626
|
assert.strictEqual(jsonOf(u).error.code, 'usage');
|
|
618
627
|
});
|
|
619
628
|
|
|
629
|
+
|
|
630
|
+
// --- Migrations écrites sur poad.io : deploy refusé, migration pull, migrate list, migrate renumber ------------
|
|
631
|
+
|
|
632
|
+
const sha256 = (s) => require('crypto').createHash('sha256').update(s).digest('hex');
|
|
633
|
+
const INIT_SQL = 'create table todo (id serial primary key);\n';
|
|
634
|
+
const NOTES_SQL = '-- ajoute_notes\n-- Écrite par la console poad.\n\ncreate table notes (id int);\n';
|
|
635
|
+
const IDX_SQL = 'create index on notes (id);\n';
|
|
636
|
+
const remoteMigrations = () => ({
|
|
637
|
+
main: [
|
|
638
|
+
{ version: '20261101000000', name: 'init', file: '20261101000000_init.sql', checksum: sha256(INIT_SQL), applied_at: '2026-11-01T00:00:00Z', applied: true, source: 'history', sql: INIT_SQL },
|
|
639
|
+
{ version: '20261203101500', name: 'ajoute_notes', file: '20261203101500_ajoute_notes.sql', checksum: sha256(NOTES_SQL), applied_at: '2026-12-03T10:15:00Z', applied: true, source: 'history', sql: NOTES_SQL },
|
|
640
|
+
{ version: '20261204080000', name: 'index_notes', file: '20261204080000_index_notes.sql', checksum: null, applied_at: null, applied: false, source: 'folder', sql: IDX_SQL },
|
|
641
|
+
],
|
|
642
|
+
dev: [{ version: '20261101000000', name: 'init', file: '20261101000000_init.sql', checksum: sha256(INIT_SQL), applied_at: '2026-11-01T00:00:00Z', applied: true, source: 'history', sql: INIT_SQL }],
|
|
643
|
+
});
|
|
644
|
+
|
|
645
|
+
test('deploy refusé (migrations manquantes) : lesquelles, avec nom et date, et la commande ; --dry-run --json garde versions et missing', async (t) => {
|
|
646
|
+
const box = sandbox(t);
|
|
647
|
+
const refuse = {
|
|
648
|
+
code: 'migrations_missing',
|
|
649
|
+
message: 'migrations applied on poad.io are missing from the folder: bring them back with poad migration pull, commit them, then deploy again',
|
|
650
|
+
versions: ['20261203101500'],
|
|
651
|
+
missing: [{ version: '20261203101500', name: 'ajoute_notes', file: '20261203101500_ajoute_notes.sql', applied_at: '2026-12-03T10:15:00Z' }],
|
|
652
|
+
};
|
|
653
|
+
const cloud = await fakeCloud(t, { refuse });
|
|
654
|
+
await login(box, cloud);
|
|
655
|
+
await poad(box, cloud.api, ['link', PID]);
|
|
656
|
+
const dry = await poad(box, cloud.api, ['deploy', '--dry-run']);
|
|
657
|
+
assert.strictEqual(dry.status, 5, dry.all);
|
|
658
|
+
assert.match(dry.stdout, /20261203101500_ajoute_notes\.sql\s+applied 2026-12-03 10:15 UTC/);
|
|
659
|
+
assert.match(dry.stdout, /poad migration pull(?! --env)/);
|
|
660
|
+
const j = await poad(box, cloud.api, ['deploy', '--dry-run', '--json', '--env', 'main']);
|
|
661
|
+
const o = jsonOf(j);
|
|
662
|
+
assert.deepStrictEqual(o.migrations.errors[0].versions, ['20261203101500']);
|
|
663
|
+
assert.strictEqual(o.migrations.errors[0].missing[0].file, '20261203101500_ajoute_notes.sql');
|
|
664
|
+
assert.deepStrictEqual(o.missing_migrations.map((m) => m.version), ['20261203101500']);
|
|
665
|
+
assert.deepStrictEqual(o.fix, ['poad migration pull --env main']);
|
|
666
|
+
// poad.io d'avant (versions seules) : listées quand même
|
|
667
|
+
const old = await fakeCloud(t, { refuse: { code: 'migrations_missing', message: 'missing', versions: ['20261203101500'] } });
|
|
668
|
+
await login(box, old);
|
|
669
|
+
const r = await poad(box, old.api, ['deploy', '--env', 'dev']);
|
|
670
|
+
assert.match(r.stdout, /20261203101500 \(name unknown\)/);
|
|
671
|
+
assert.match(r.stdout, /poad migration pull --env dev/);
|
|
672
|
+
});
|
|
673
|
+
|
|
674
|
+
test('deploy refusé (hors d’ordre) : la renumérotation proposée, rien de forcé', async (t) => {
|
|
675
|
+
const box = sandbox(t);
|
|
676
|
+
const cloud = await fakeCloud(t, { refuse: { code: 'migrations_out_of_order', message: 'pending migrations are older than the last applied one: rename them after it', files: ['20261101000000_init.sql'] } });
|
|
677
|
+
await login(box, cloud);
|
|
678
|
+
await poad(box, cloud.api, ['link', PID]);
|
|
679
|
+
const r = await poad(box, cloud.api, ['deploy', '--env', 'dev', '--json']);
|
|
680
|
+
assert.strictEqual(r.status, 5, r.all);
|
|
681
|
+
assert.deepStrictEqual(jsonOf(r).fix, ['poad migrate renumber 20261101000000 --env dev']);
|
|
682
|
+
const text = await poad(box, cloud.api, ['deploy', '--env', 'dev']);
|
|
683
|
+
assert.match(text.stdout, /poad migrate renumber 20261101000000 --env dev/);
|
|
684
|
+
assert.ok(!cloud.requests.some((q) => q.headers['x-poad-force']), 'aucun forçage');
|
|
685
|
+
});
|
|
686
|
+
|
|
687
|
+
test('migration pull : nom, version et contenu exacts, jamais d’écrasement, conflit dit (code 5) ; migrate pull alias', async (t) => {
|
|
688
|
+
const box = sandbox(t);
|
|
689
|
+
const cloud = await fakeCloud(t, { migrations: remoteMigrations() });
|
|
690
|
+
await login(box, cloud);
|
|
691
|
+
await poad(box, cloud.api, ['link', PID]);
|
|
692
|
+
const mdir = path.join(box.poad, 'migrations');
|
|
693
|
+
|
|
694
|
+
const dry = await poad(box, cloud.api, ['migration', 'pull', '--dry-run', '--json']);
|
|
695
|
+
assert.strictEqual(dry.status, 0, dry.all);
|
|
696
|
+
assert.deepStrictEqual(jsonOf(dry).pull.map((m) => m.file), ['20261203101500_ajoute_notes.sql', '20261204080000_index_notes.sql']);
|
|
697
|
+
assert.deepStrictEqual(fs.readdirSync(mdir), ['20261101000000_init.sql']);
|
|
698
|
+
|
|
699
|
+
// Hors terminal sans --yes : rien d'écrit
|
|
700
|
+
const ask = await poad(box, cloud.api, ['migration', 'pull']);
|
|
701
|
+
assert.strictEqual(ask.status, 4, ask.all);
|
|
702
|
+
assert.match(ask.stdout, /↓ 20261203101500_ajoute_notes\.sql\s+applied 2026-12-03 10:15 UTC/);
|
|
703
|
+
assert.match(ask.stdout, /↓ 20261204080000_index_notes\.sql\s+written on poad\.io, not applied yet/);
|
|
704
|
+
|
|
705
|
+
const r = await poad(box, cloud.api, ['migrate', 'pull', '--yes', '--json']);
|
|
706
|
+
assert.strictEqual(r.status, 0, r.all);
|
|
707
|
+
const o = jsonOf(r);
|
|
708
|
+
assert.deepStrictEqual(o.written.map((w) => w.file), ['20261203101500_ajoute_notes.sql', '20261204080000_index_notes.sql']);
|
|
709
|
+
assert.strictEqual(fs.readFileSync(path.join(mdir, '20261203101500_ajoute_notes.sql'), 'utf8'), NOTES_SQL);
|
|
710
|
+
assert.strictEqual(fs.readFileSync(path.join(mdir, '20261204080000_index_notes.sql'), 'utf8'), IDX_SQL);
|
|
711
|
+
const reqs = cloud.requests.filter((q) => q.route.endsWith('/migrations'));
|
|
712
|
+
assert.ok(reqs.every((q) => q.route === `v1/projects/${PID}/branches/main/migrations`));
|
|
713
|
+
assert.ok(reqs.some((q) => q.query.versions === '20261203101500,20261204080000'));
|
|
714
|
+
assert.ok(!r.all.includes(TOKEN));
|
|
715
|
+
|
|
716
|
+
const again = await poad(box, cloud.api, ['migration', 'pull', '--yes']);
|
|
717
|
+
assert.strictEqual(again.status, 0, again.all);
|
|
718
|
+
assert.match(again.stdout, /Nothing to pull/);
|
|
719
|
+
|
|
720
|
+
// Une version déjà prise ici sous un autre nom : conflit, rien d'écrasé
|
|
721
|
+
fs.rmSync(path.join(mdir, '20261203101500_ajoute_notes.sql'));
|
|
722
|
+
fs.writeFileSync(path.join(mdir, '20261203101500_mien.sql'), 'select 1;\n');
|
|
723
|
+
const c = await poad(box, cloud.api, ['migration', 'pull', '--yes', '--json']);
|
|
724
|
+
assert.strictEqual(c.status, 5, c.all);
|
|
725
|
+
assert.deepStrictEqual(jsonOf(c).conflicts, [{ version: '20261203101500', file: '20261203101500_ajoute_notes.sql', local: '20261203101500_mien.sql' }]);
|
|
726
|
+
assert.strictEqual(fs.readFileSync(path.join(mdir, '20261203101500_mien.sql'), 'utf8'), 'select 1;\n');
|
|
727
|
+
assert.ok(!fs.existsSync(path.join(mdir, '20261203101500_ajoute_notes.sql')));
|
|
728
|
+
});
|
|
729
|
+
|
|
730
|
+
test('migration pull : SQL introuvable ou somme fausse là-haut, refusé (code 5) avec poad db pull en recours', async (t) => {
|
|
731
|
+
const box = sandbox(t);
|
|
732
|
+
const m = remoteMigrations();
|
|
733
|
+
m.main[1] = { ...m.main[1], sql: 'tampered;\n' };
|
|
734
|
+
m.main.push({ version: '20261204090000', name: 'perdue', file: '20261204090000_perdue.sql', checksum: 'x', applied_at: '2026-12-04T09:00:00Z', applied: true, source: null, problem: 'sql_unavailable' });
|
|
735
|
+
const cloud = await fakeCloud(t, { migrations: m });
|
|
736
|
+
await login(box, cloud);
|
|
737
|
+
await poad(box, cloud.api, ['link', PID]);
|
|
738
|
+
const r = await poad(box, cloud.api, ['migration', 'pull', '--yes', '--json']);
|
|
739
|
+
assert.strictEqual(r.status, 5, r.all);
|
|
740
|
+
const o = jsonOf(r);
|
|
741
|
+
assert.deepStrictEqual(o.written.map((w) => w.file), ['20261204080000_index_notes.sql']);
|
|
742
|
+
assert.deepStrictEqual(o.unavailable.map((u) => [u.version, u.problem]).sort(), [['20261203101500', 'checksum_mismatch'], ['20261204090000', 'sql_unavailable']]);
|
|
743
|
+
assert.ok(!fs.existsSync(path.join(box.poad, 'migrations', '20261203101500_ajoute_notes.sql')));
|
|
744
|
+
const text = await poad(box, cloud.api, ['migration', 'pull', '--yes']);
|
|
745
|
+
assert.match(text.stdout, /poad db pull/);
|
|
746
|
+
});
|
|
747
|
+
|
|
748
|
+
test('migrate list : dossier face à poad.io (appliquée, en attente, manquante, hors d’ordre) ; migrate renumber', async (t) => {
|
|
749
|
+
const box = sandbox(t);
|
|
750
|
+
const cloud = await fakeCloud(t, { migrations: remoteMigrations() });
|
|
751
|
+
await login(box, cloud);
|
|
752
|
+
await poad(box, cloud.api, ['link', PID]);
|
|
753
|
+
const mdir = path.join(box.poad, 'migrations');
|
|
754
|
+
fs.writeFileSync(path.join(mdir, '20261202000000_vieille.sql'), 'select 2;\n');
|
|
755
|
+
fs.writeFileSync(path.join(mdir, '20991231000000_future.sql'), 'select 3;\n');
|
|
756
|
+
const r = await poad(box, cloud.api, ['migrate', 'list', '--json']);
|
|
757
|
+
assert.strictEqual(r.status, 0, r.all);
|
|
758
|
+
const states = Object.fromEntries(jsonOf(r).migrations.map((m) => [m.version, m.state]));
|
|
759
|
+
assert.deepStrictEqual(states, { 20261101000000: 'applied', 20261202000000: 'out_of_order', 20261203101500: 'missing', 20261204080000: 'remote_pending', 20991231000000: 'pending' });
|
|
760
|
+
assert.strictEqual(jsonOf(r).migrations.find((m) => m.version === '20261203101500').applied_at, '2026-12-03T10:15:00Z');
|
|
761
|
+
const text = await poad(box, cloud.api, ['migration', 'list', '--env', 'main']);
|
|
762
|
+
assert.match(text.stdout, /poad migration pull --env main/);
|
|
763
|
+
assert.match(text.stdout, /poad migrate renumber 20261202000000 --env main/);
|
|
764
|
+
|
|
765
|
+
// Appliquée sur un environnement : jamais renumérotée
|
|
766
|
+
const applied = await poad(box, cloud.api, ['migrate', 'renumber', '20261101000000', '--yes']);
|
|
767
|
+
assert.strictEqual(applied.status, 5, applied.all);
|
|
768
|
+
assert.match(applied.stderr, /already applied on main/);
|
|
769
|
+
assert.ok(fs.existsSync(path.join(mdir, '20261101000000_init.sql')));
|
|
770
|
+
|
|
771
|
+
const ren = await poad(box, cloud.api, ['migrate', 'renumber', '20261202000000_vieille.sql', '--yes', '--json']);
|
|
772
|
+
assert.strictEqual(ren.status, 0, ren.all);
|
|
773
|
+
const o = jsonOf(ren);
|
|
774
|
+
assert.strictEqual(o.from, '20261202000000_vieille.sql');
|
|
775
|
+
assert.ok(o.version > '20991231000000', `après la dernière du dossier et de poad.io : ${o.version}`);
|
|
776
|
+
assert.strictEqual(fs.readFileSync(path.join(mdir, o.to), 'utf8'), 'select 2;\n');
|
|
777
|
+
assert.ok(!fs.existsSync(path.join(mdir, '20261202000000_vieille.sql')));
|
|
778
|
+
const unknown = await poad(box, cloud.api, ['migrate', 'renumber', '20200101000000', '--yes']);
|
|
779
|
+
assert.strictEqual(unknown.status, 2, unknown.all);
|
|
780
|
+
});
|
package/utils/help-details.js
CHANGED
|
@@ -328,7 +328,7 @@ const sheets = {
|
|
|
328
328
|
],
|
|
329
329
|
},
|
|
330
330
|
migrate: {
|
|
331
|
-
usage: ['poad migrate', 'poad migrate --force-reference', 'poad migrate --json'],
|
|
331
|
+
usage: ['poad migrate', 'poad migrate --force-reference', 'poad migrate --json', 'poad migrate list [--env <name>] [--json]', 'poad migrate pull [--env <name>] [--yes] [--dry-run] [--json]', 'poad migrate renumber <version|file> [--env <name>] [--yes] [--json]'],
|
|
332
332
|
text: [
|
|
333
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
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).',
|
|
@@ -336,15 +336,19 @@ const sheets = {
|
|
|
336
336
|
options: [
|
|
337
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
338
|
['--json', 'one JSON object: applied, failed, pending, api_exposure (items with reason, roles, fix, created), unprotected tables'],
|
|
339
|
+
['list', 'poad/migrations against an environment of poad.io (--env, else the git branch, else main; the local engine when the project is not linked): applied on both sides, pending here, missing here, written on poad.io without being applied, same version under another name, changed since applied, older than the last one applied (poad deploy refuses it); with version, name and date'],
|
|
340
|
+
['pull', 'same as poad migration pull'],
|
|
341
|
+
['renumber <version>', 'give a pending migration a version after the last one of the environment and of the folder (the file is renamed, its SQL is unchanged) when poad deploy refuses it as out of order. Refused when it is applied on any environment of poad.io; applied on the local engine only: the local history follows. Logs: poad logs cli event=migration_renumbered'],
|
|
339
342
|
],
|
|
340
343
|
},
|
|
341
344
|
migration: {
|
|
342
|
-
usage: ['poad migration new <name>', 'poad migration list'],
|
|
345
|
+
usage: ['poad migration new <name>', 'poad migration list [--env <name>]', 'poad migration pull [--env <name>] [--yes] [--dry-run] [--json]'],
|
|
343
346
|
options: [
|
|
344
347
|
['new <name>', 'create poad/migrations/<timestamp>_<name>.sql'],
|
|
345
|
-
['list', 'applied and pending migrations'],
|
|
348
|
+
['list', 'applied and pending migrations of the local engine; with --env <name>: against poad.io (as poad migrate list)'],
|
|
349
|
+
['pull', 'write into poad/migrations the migrations of a poad.io environment missing from the folder (--env, else the git branch, else main): those written there by the console, the MCP or the assistant, applied (their exact SQL from the migration history) or not yet applied. Each keeps its exact version, name and content (sha256 of the history checked); an existing file is never overwritten: a version already used here under another name is a conflict, said and left alone. Then commit them and poad deploy. Exit code 5 when one could not be pulled'],
|
|
346
350
|
],
|
|
347
|
-
notes: ['poad migrate applies the pending ones (poad start does it too).'],
|
|
351
|
+
notes: ['poad migrate applies the pending ones (poad start does it too).', 'poad deploy refuses while a migration applied on poad.io is missing from the folder: it lists them (version, name, date) and gives the poad migration pull command, --dry-run included.', 'Logs, never any SQL: poad logs cli event=migrations_pulled --env <name> (written by poad.io: versions and files).'],
|
|
348
352
|
},
|
|
349
353
|
kc: {
|
|
350
354
|
usage: ['poad kc', 'poad kc export'],
|