poad 2.51.0 → 2.53.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.51.0",
3
+ "version": "2.53.0",
4
4
  "engine": "0.28.0",
5
5
  "runner": "0.2.0",
6
6
  "main": "index.js",
package/project/cli.js CHANGED
@@ -23,6 +23,15 @@ module.exports = {
23
23
  url: 'Connection string of the poad.io database (password masked, copied to the clipboard; --show-password to print it)',
24
24
  pull: 'Schema of the poad.io database into a new local migration (pg_dump --schema-only, never overwrites)',
25
25
  },
26
+ seed: {
27
+ description: 'Seeds and heavy reference tables on poad.io: stored outside git and the project volume (S3, encrypted by poad); no local folder needed with --project',
28
+ inspect: 'What a .sql or .csv file holds, table by table and column by column, before sending anything: rows, volume share of each column, value sizes, heavy columns, estimated size in the database: seed inspect <file> [--fields a,b | --exclude c]',
29
+ push: 'Convert a .sql (INSERT, COPY) or .csv file and send each table: seed push <file> [--fields a,b | --exclude c] [--table schema.table] [--mode seed|reference] [--load] [--env <name>]',
30
+ ls: 'Seeds of the project: mode, size, what each environment has loaded, store quota',
31
+ load: 'Load seeds into an environment (--env, else the git branch, else main) or into the local engine (--local): seed load [table…] [--reference] [--force]',
32
+ mode: 'seed (development data, never into production without --force) or reference (loaded everywhere): seed mode <table> seed|reference',
33
+ rm: 'Remove a seed from poad.io (the table keeps its rows): seed rm <table> [--yes]',
34
+ },
26
35
  link: 'Link this project to a poad.io project: [cloud] project = "<id>" in poad/config.toml (no secret): link [<id>]',
27
36
  unlink: 'Remove the link to poad.io from poad/config.toml (nothing changes on poad.io)',
28
37
  env: {
@@ -0,0 +1,18 @@
1
+ // poad seed : aide des commandes du magasin de seeds
2
+ module.exports = async () => {
3
+ const chalk = require('chalk-v2');
4
+ const c = (s) => chalk.cyanBright(s);
5
+ console.log(`${chalk.bold(' Usage :')}`);
6
+ console.log(' ');
7
+ console.log(` ${c('poad seed inspect <file>')} What the file holds, column by column, and its weight: nothing is sent`);
8
+ console.log(` ${c('poad seed push <file>')} Convert a .sql (INSERT, COPY) or .csv file and send each table to poad.io`);
9
+ console.log(` ${c('poad seed ls')} Seeds of the project, their mode and what each environment has loaded`);
10
+ console.log(` ${c('poad seed load [table…]')} Load seeds into an environment (--env), or into the local engine (--local)`);
11
+ console.log(` ${c('poad seed mode <table> seed|reference')}`);
12
+ console.log(` ${c('poad seed rm <table>')} Remove a seed from the store (the table keeps its rows)`);
13
+ console.log(' ');
14
+ console.log(chalk.grey(' Data lives on poad.io (S3), outside git and outside the project volume, encrypted by poad.'));
15
+ console.log(chalk.grey(' seed: development data, never loaded into production unless --force; reference: loaded everywhere.'));
16
+ console.log(chalk.grey(' No local folder needed: --project <id> targets a project created in the console.'));
17
+ console.log(' ');
18
+ };
@@ -0,0 +1,45 @@
1
+ // poad seed inspect <fichier> [--fields a,b | --exclude c] [--table schéma.table] [--format sql|csv] [--json]
2
+ // Ce que contient le fichier, table par table et colonne par colonne, avant tout envoi :
3
+ // lignes, volume, part de chaque colonne, taille des valeurs, colonnes lourdes, place
4
+ // estimée dans la base. Rien n'est envoyé ni écrit ; aucune connexion à poad.io.
5
+ module.exports = (args, raw) =>
6
+ require('../../utils/cloud/cli').run(raw, { values: ['table', 'format', 'fields', 'exclude'] }, async ({ opts, positionals, out }) => {
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const api = require('../../utils/cloud/api');
10
+ const S = require('../../utils/seed/run');
11
+ const { tableReport, fmt } = require('../../utils/seed/report');
12
+ const { chalk } = out;
13
+ const file = positionals[0];
14
+ if (!file) throw api.usageError('poad seed inspect <file.sql|file.csv> [--fields a,b | --exclude c]');
15
+ if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw api.usageError(`${file}: no such file`);
16
+ const t0 = Date.now();
17
+ let last = 0;
18
+ const conv = await S.convertFile(file, {
19
+ format: opts.format,
20
+ table: opts.table,
21
+ fields: opts.fields,
22
+ exclude: opts.exclude,
23
+ write: false,
24
+ onProgress: (read, total) => {
25
+ if (!out.json && process.stderr.isTTY && Date.now() - last > 250) {
26
+ last = Date.now();
27
+ process.stderr.write(`\r ${chalk.grey('reading')} ${path.basename(file)} ${Math.floor((read / total) * 100)}% `);
28
+ }
29
+ },
30
+ });
31
+ if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
32
+ const tables = conv.tables.map((t) => ({ ...t.stats, dropped: t.dropped }));
33
+ out.result({ file: path.basename(file), tables, skipped: conv.skipped, mutations: conv.mutations });
34
+ if (out.json) return;
35
+ if (!tables.length) return out.log(chalk.yellowBright(` ${path.basename(file)}: no data found (INSERT … VALUES, COPY … FROM stdin, or CSV rows).`));
36
+ out.log(chalk.grey(` ${path.basename(file)} read in ${((Date.now() - t0) / 1000).toFixed(1)} s, nothing sent`));
37
+ for (const t of tables) {
38
+ out.log('');
39
+ for (const l of tableReport(t, chalk, { dropped: t.dropped })) out.log(` ${l}`);
40
+ }
41
+ const total = tables.reduce((n, t) => n + t.db_bytes, 0);
42
+ out.log('');
43
+ out.log(` ${chalk.bold('Total')} ≈ ${fmt(total)} in the database once loaded (estimate: rows, values and indexes)`);
44
+ out.log(chalk.grey(` Send it: poad seed push ${path.basename(file)}${opts.fields ? ` --fields ${opts.fields}` : opts.exclude ? ` --exclude ${opts.exclude}` : ''}`));
45
+ });
@@ -0,0 +1,50 @@
1
+ // poad seed load [table…] [--env <branche>] [--reference] [--force] [--project <id>] [--json]
2
+ // poad seed load [table…] --local : dans l'engine Docker du projet de ce dossier
3
+ // Sans table : toutes celles du registre (--reference : seulement les références).
4
+ module.exports = (args, raw) =>
5
+ require('../../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['local', 'force', 'reference'] }, async ({ opts, positionals, out }) => {
6
+ const api = require('../../utils/cloud/api');
7
+ const cli = require('../../utils/cloud/cli');
8
+ const { parseTarget } = require('../../utils/seed/convert');
9
+ const S = require('../../utils/seed/run');
10
+ const { chalk } = out;
11
+ const targets = positionals.map((t) => {
12
+ const v = parseTarget(t);
13
+ if (!v) throw api.usageError(`"${t}" is not schema.table`);
14
+ return v;
15
+ });
16
+ const { id, root } = cli.targetProject(opts);
17
+ if (!opts.local) {
18
+ const branches = require('../../utils/cloud/branches');
19
+ const env = await branches.resolve(id, { wanted: opts.env, root });
20
+ const { startAndWait } = require('./push');
21
+ const l = await startAndWait(id, env.branch, targets.length ? targets : undefined, opts, out);
22
+ out.result({ project: id, load: l });
23
+ return l.status === 'failed' ? api.EXIT.failed : 0;
24
+ }
25
+ // Engine local : le projet de ce dossier, démarré
26
+ if (!root) throw api.usageError('--local: run it inside the poad project folder (poad start first).');
27
+ const { readConfig } = require('../../utils/config');
28
+ const { isDockerExist } = require('../../utils/docker');
29
+ const config = readConfig(root);
30
+ if (!(await isDockerExist(config.project_uuid))) throw api.usageError('The local project is not started: "poad start".');
31
+ const list = await api.call('GET', `v1/projects/${api.enc(id)}/seeds`, { what: 'seeds' });
32
+ let items = list.items;
33
+ if (targets.length) {
34
+ const missing = targets.filter((t) => !items.some((s) => s.target === t));
35
+ if (missing.length) throw api.usageError(`unknown seed: ${missing.join(', ')} ("poad seed ls")`);
36
+ items = items.filter((s) => targets.includes(s.target));
37
+ } else if (opts.reference) items = items.filter((s) => s.mode === 'reference');
38
+ if (!items.length) throw api.usageError('No seed to load ("poad seed ls").');
39
+ const A = require('../../utils/seed/apply');
40
+ const order = A.loadOrder(items.map((s) => s.target), await S.localEdges(config.project_uuid));
41
+ const results = [];
42
+ for (const target of order) {
43
+ const t0 = Date.now();
44
+ const d = await api.call('POST', `v1/projects/${api.enc(id)}/seeds/download`, { body: { target }, what: `seed ${target}` });
45
+ const r = await S.loadLocal(config.project_uuid, d);
46
+ out.log(`${chalk.greenBright('✔')} ${target} loaded locally: ${r.written} rows written, ${r.deleted} removed (${((Date.now() - t0) / 1000).toFixed(1)} s)`);
47
+ results.push({ target, ...r });
48
+ }
49
+ out.result({ project: id, local: true, tables: results });
50
+ });
@@ -0,0 +1,27 @@
1
+ // poad seed ls [--project <id>] [--json] : registre des seeds, quota, ce que chaque environnement a chargé
2
+ module.exports = (args, raw) =>
3
+ require('../../utils/cloud/cli').run(raw, { values: ['project'] }, async ({ opts, out }) => {
4
+ const api = require('../../utils/cloud/api');
5
+ const cli = require('../../utils/cloud/cli');
6
+ const { fmt } = require('../../utils/seed/run');
7
+ const { chalk } = out;
8
+ const { id } = cli.targetProject(opts);
9
+ const r = await api.call('GET', `v1/projects/${api.enc(id)}/seeds`, { what: 'seeds' });
10
+ out.result({ project: id, ...r });
11
+ if (out.json) return;
12
+ if (!r.store) out.log(chalk.yellowBright(' The seed store is not configured on this poad.io instance.'));
13
+ out.log(` Store: ${fmt(r.quota.used)} used of ${fmt(r.quota.limit)} (account quota, outside the project volume)`);
14
+ if (!r.items.length) return out.log(chalk.grey(' No seed yet: poad seed push <file.sql|file.csv>'));
15
+ const envs = Object.keys(r.applied);
16
+ out.log('');
17
+ for (const s of r.items) {
18
+ const state = envs.map((e) => {
19
+ const a = r.applied[e][s.target];
20
+ return a ? (a.sha256 === s.sha256 ? chalk.greenBright(`${e} ✔`) : chalk.yellowBright(`${e} outdated`)) : null;
21
+ }).filter(Boolean);
22
+ out.log(` ${chalk.bold(s.target)} ${s.mode === 'reference' ? chalk.magentaBright('reference') : chalk.cyanBright('seed')} ${s.rows} rows ${fmt(s.stored_bytes)} ${chalk.grey(s.source || '')}`);
23
+ out.log(` ${state.length ? state.join(' ') : chalk.grey('not loaded anywhere yet')}`);
24
+ }
25
+ const last = r.loads[0];
26
+ if (last) out.log(chalk.grey(`\n Last load: ${last.branch}, ${last.status}${last.error ? ` (${last.error})` : ''}, ${new Date(last.started_at).toLocaleString()}`));
27
+ });
@@ -0,0 +1,14 @@
1
+ // poad seed mode <table> seed|reference [--project <id>] [--json]
2
+ module.exports = (args, raw) =>
3
+ require('../../utils/cloud/cli').run(raw, { values: ['project'] }, async ({ opts, positionals, out }) => {
4
+ const api = require('../../utils/cloud/api');
5
+ const cli = require('../../utils/cloud/cli');
6
+ const { parseTarget } = require('../../utils/seed/convert');
7
+ const [t, mode] = positionals;
8
+ const target = parseTarget(t || '');
9
+ if (!target || !['seed', 'reference'].includes(mode)) throw api.usageError('poad seed mode <schema.table> seed|reference');
10
+ const { id } = cli.targetProject(opts);
11
+ const r = await api.call('POST', `v1/projects/${api.enc(id)}/seeds/mode`, { body: { target, mode }, what: `seed ${target}` });
12
+ out.result({ project: id, ...r });
13
+ out.log(`${out.chalk.greenBright('✔')} ${target}: ${mode}${mode === 'reference' ? ' (loaded everywhere, production included)' : ' (development data: never loaded into production without --force)'}`);
14
+ });
@@ -0,0 +1,109 @@
1
+ // poad seed push <fichier> [--table schéma.table] [--format sql|csv] [--mode seed|reference]
2
+ // [--load] [--env <branche>] [--force] [--project <id>] [--json]
3
+ // Convertit le fichier (une entrée par table), chiffre chaque table et l'envoie
4
+ // au magasin de poad.io par URL signée, puis l'inscrit au registre du projet.
5
+ // --load : la charge aussitôt dans l'environnement visé (--env, sinon la branche git, sinon main).
6
+ module.exports = (args, raw) =>
7
+ require('../../utils/cloud/cli').run(raw, { values: ['table', 'format', 'mode', 'env', 'project', 'fields', 'exclude'], flags: ['load', 'force', 'yes'] }, async ({ opts, positionals, out }) => {
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const api = require('../../utils/cloud/api');
11
+ const cli = require('../../utils/cloud/cli');
12
+ const S = require('../../utils/seed/run');
13
+ const { chalk } = out;
14
+ const file = positionals[0];
15
+ if (!file) throw api.usageError('poad seed push <file.sql|file.csv> [--table schema.table] [--mode seed|reference]');
16
+ if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw api.usageError(`${file}: no such file`);
17
+ const mode = opts.mode || 'seed';
18
+ if (!['seed', 'reference'].includes(mode)) throw api.usageError('--mode is seed or reference');
19
+ if (opts.format && !['sql', 'csv'].includes(opts.format)) throw api.usageError('--format is sql or csv');
20
+ const { id, root } = cli.targetProject(opts);
21
+ api.requireToken();
22
+ const dir = S.tmpDir();
23
+ try {
24
+ // 1. Conversion
25
+ const t0 = Date.now();
26
+ let last = 0;
27
+ const conv = await S.convertFile(file, {
28
+ format: opts.format,
29
+ table: opts.table,
30
+ fields: opts.fields,
31
+ exclude: opts.exclude,
32
+ dir,
33
+ onProgress: (read, total) => {
34
+ if (!out.json && process.stderr.isTTY && Date.now() - last > 250) {
35
+ last = Date.now();
36
+ process.stderr.write(`\r ${chalk.grey('reading')} ${path.basename(file)} ${Math.floor((read / total) * 100)}% `);
37
+ }
38
+ },
39
+ });
40
+ if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
41
+ if (!conv.tables.length) throw new api.CloudError(`${path.basename(file)}: no data found (INSERT … VALUES, COPY … FROM stdin, or CSV rows)`, { code: 'seed_empty' });
42
+ out.log(`${chalk.greenBright('✔')} ${path.basename(file)} read in ${((Date.now() - t0) / 1000).toFixed(1)} s: ${conv.tables.map((t) => `${t.target} (${t.rows} rows, ≈ ${S.fmt(t.stats.db_bytes)} in the database)`).join(', ')}`);
43
+ for (const t of conv.tables) {
44
+ if (t.dropped.length) out.log(chalk.grey(` ${t.target}: left out ${t.dropped.join(', ')}`));
45
+ if (t.stats.heavy.length) out.log(chalk.yellowBright(` ${t.target}: heavy column(s) ${t.stats.heavy.map((h) => `${h.column} (${Math.round(h.share * 100)} %)`).join(', ')}; "poad seed inspect ${path.basename(file)}" shows the detail, --exclude leaves them out`));
46
+ }
47
+ const skipped = Object.entries(conv.skipped).filter(([w]) => !['SET', 'BEGIN', 'COMMIT', 'END', 'SELECT'].includes(w));
48
+ if (skipped.length) out.log(chalk.grey(` Ignored, not data: ${skipped.map(([w, n]) => `${n} ${w}`).join(', ')} (structure goes through migrations).`));
49
+ if (conv.mutations) out.log(chalk.yellowBright(` ${conv.mutations} UPDATE/DELETE statement(s) ignored: a seed only carries rows; apply them as a migration if they matter.`));
50
+ // 2. Envoi, table par table
51
+ const results = [];
52
+ for (const t of conv.tables) {
53
+ let shown = 0;
54
+ const r = await S.pushTable(id, t, {
55
+ mode,
56
+ source: path.basename(file),
57
+ onProgress: (done, total) => {
58
+ if (!out.json && process.stderr.isTTY && Date.now() - shown > 250) {
59
+ shown = Date.now();
60
+ process.stderr.write(`\r ${chalk.grey('sending')} ${t.target} ${S.fmt(done)} / ${S.fmt(total)} `);
61
+ }
62
+ },
63
+ });
64
+ if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
65
+ out.log(`${chalk.greenBright('✔')} ${chalk.bold(t.target)} ${r.uploaded ? `sent (${S.fmt(r.stored)} encrypted)` : 'unchanged content: nothing to send'}, mode ${mode}${r.replaced ? ', replaces the previous version' : ''}`);
66
+ results.push({ target: t.target, rows: t.rows, sha256: t.sha256, uploaded: r.uploaded, stored_bytes: r.stored, db_bytes: t.stats.db_bytes, mode });
67
+ }
68
+ // 3. Chargement facultatif
69
+ let load = null;
70
+ if (opts.load) {
71
+ const branches = require('../../utils/cloud/branches');
72
+ const env = await branches.resolve(id, { wanted: opts.env, root });
73
+ load = await startAndWait(id, env.branch, results.map((r) => r.target), opts, out);
74
+ } else out.log(chalk.grey(` Load it: poad seed load ${results.map((r) => r.target).join(' ')}${opts.env ? ` --env ${opts.env}` : ''} (or poad seed load --local)`));
75
+ out.result({ project: id, tables: results, load });
76
+ return load && load.status === 'failed' ? api.EXIT.failed : 0;
77
+ } finally {
78
+ fs.rmSync(dir, { recursive: true, force: true });
79
+ }
80
+ });
81
+
82
+ /** Lance un chargement hébergé et suit ses étapes */
83
+ async function startAndWait(id, branch, targets, opts, out) {
84
+ const api = require('../../utils/cloud/api');
85
+ const S = require('../../utils/seed/run');
86
+ const { chalk } = out;
87
+ let started;
88
+ try {
89
+ started = await api.call('POST', `v1/projects/${api.enc(id)}/seeds/load`, { body: { branch, targets, force: Boolean(opts.force), ...(opts.reference ? { only: 'reference' } : {}) }, what: 'seed load' });
90
+ } catch (e) {
91
+ if (e.code === 'seed_in_production') throw new api.CloudError(`${e.message}\n Development data into production: add --force if that is what you want.`, { code: e.code, exit: api.EXIT.confirm });
92
+ throw e;
93
+ }
94
+ out.log(chalk.grey(` Loading into ${branch} (${started.targets.length} table(s))…`));
95
+ const done = new Set();
96
+ const l = await S.waitLoad(id, started.load_id, {
97
+ onStep: (st) => {
98
+ for (const s of st.steps) {
99
+ if (done.has(s.target) || !['done', 'failed'].includes(s.status)) continue;
100
+ done.add(s.target);
101
+ if (s.status === 'done') out.log(`${chalk.greenBright('✔')} ${s.target} loaded into ${branch}: ${s.written} rows written, ${s.deleted} removed (${(s.duration_ms / 1000).toFixed(1)} s)`);
102
+ else out.log(`${chalk.redBright('✖')} ${s.target}: ${s.error}`);
103
+ }
104
+ },
105
+ });
106
+ if (l.status === 'failed') out.log(chalk.grey(' Nothing was half-loaded: each table is all or nothing.'));
107
+ return l;
108
+ }
109
+ module.exports.startAndWait = startAndWait;
@@ -0,0 +1,14 @@
1
+ // poad seed rm <table> [--yes] [--project <id>] [--json] : retire le seed du magasin (la table garde ses lignes)
2
+ module.exports = (args, raw) =>
3
+ require('../../utils/cloud/cli').run(raw, { values: ['project'], flags: ['yes'] }, async ({ opts, positionals, out }) => {
4
+ const api = require('../../utils/cloud/api');
5
+ const cli = require('../../utils/cloud/cli');
6
+ const { parseTarget } = require('../../utils/seed/convert');
7
+ const target = parseTarget(positionals[0] || '');
8
+ if (!target) throw api.usageError('poad seed rm <schema.table>');
9
+ const { id } = cli.targetProject(opts);
10
+ await cli.confirm(`Remove the seed of ${target} from poad.io? The table keeps its rows; the stored file is deleted.`, { yes: opts.yes, json: out.json });
11
+ const r = await api.call('POST', `v1/projects/${api.enc(id)}/seeds/delete`, { body: { target }, what: `seed ${target}` });
12
+ out.result({ project: id, ...r });
13
+ out.log(`${out.chalk.greenBright('✔')} seed of ${target} removed`);
14
+ });
@@ -0,0 +1,168 @@
1
+ // poad seed : conversion SQL/CSV -> COPY, paquets chiffrés, script de chargement
2
+ const test = require('node:test');
3
+ const assert = require('node:assert');
4
+ const crypto = require('crypto');
5
+ const fs = require('fs');
6
+ const os = require('os');
7
+ const path = require('path');
8
+ const zlib = require('zlib');
9
+ const { pipeline } = require('stream/promises');
10
+ const { SqlSource, CsvSource, ConvertError, copyEscape, parseTarget } = require('../utils/seed/convert');
11
+ const { TableSink, encryptFile, decryptStream } = require('../utils/seed/pack');
12
+ const A = require('../utils/seed/apply');
13
+
14
+ const sql = (text, chunk = 0) => {
15
+ const rows = [];
16
+ const s = new SqlSource({ onRow: (t, c, v) => rows.push({ t, c, l: v.map(copyEscape).join('\t') }) });
17
+ if (chunk) for (let i = 0; i < text.length; i += chunk) s.push(text.slice(i, i + chunk));
18
+ else s.push(text);
19
+ s.end();
20
+ return { rows, skipped: s.skipped, mutations: s.mutations };
21
+ };
22
+
23
+ test('INSERT multi-lignes, guillemets, NULL, conversions, nom sans schéma', () => {
24
+ const r = sql(`-- dump
25
+ SET x = 1;
26
+ INSERT INTO "departement" ("id","nom","geom") VALUES
27
+ ( 1,'Ain','0106AB' ), (2, 'Côtes-d''Armor', NULL),(3,'a;b', '2024-01-19'::timestamp without time zone);
28
+ COMMIT;`);
29
+ assert.deepStrictEqual(r.rows.map((x) => x.l), ['1\tAin\t0106AB', "2\tCôtes-d'Armor\t\\N", '3\ta;b\t2024-01-19']);
30
+ assert.strictEqual(r.rows[0].t, 'public.departement');
31
+ assert.deepStrictEqual(r.rows[0].c, ['id', 'nom', 'geom']);
32
+ assert.deepStrictEqual(r.skipped, { SET: 1, COMMIT: 1 });
33
+ });
34
+
35
+ test('le même résultat quel que soit le découpage en morceaux', () => {
36
+ const text = `INSERT INTO public.t (a, b) VALUES (E'x\\'y\\\\z', 'p''q'), (-1.5e3, $$d;'$$);\nCOPY public.u (a) FROM stdin;\nl1\\tx\nl2\n\\.\nINSERT INTO t VALUES (true, false);`;
37
+ const whole = sql(text);
38
+ for (const n of [1, 2, 3, 5, 7, 13]) assert.deepStrictEqual(sql(text, n).rows, whole.rows, `morceaux de ${n}`);
39
+ assert.deepStrictEqual(whole.rows.map((x) => x.l), ["x'y\\\\z\tp'q", "-1.5e3\td;'", 'l1\\tx', 'l2', 'true\tfalse']);
40
+ assert.strictEqual(whole.rows[4].c, null);
41
+ });
42
+
43
+ test('échappement COPY : barre oblique, fin de ligne, tabulation', () => {
44
+ assert.strictEqual(copyEscape('a\\b\nc\td\re'), 'a\\\\b\\nc\\td\\re');
45
+ assert.strictEqual(copyEscape(null), '\\N');
46
+ });
47
+
48
+ test('refus explicites : fonction, DEFAULT, INSERT … SELECT, nombre de valeurs', () => {
49
+ assert.throws(() => sql(`INSERT INTO t (g) VALUES (ST_GeomFromText('POINT(0 0)', 4326));`), /not a plain value.*line 1.*public\.t/);
50
+ assert.throws(() => sql(`INSERT INTO t (a) VALUES (DEFAULT);`), /DEFAULT/);
51
+ assert.throws(() => sql(`INSERT INTO t (a) SELECT 1;`), /INSERT … SELECT/);
52
+ assert.throws(() => sql(`INSERT INTO t (a, b) VALUES (1);`), /1 values for 2 columns/);
53
+ assert.throws(() => sql(`COPY t FROM '/etc/passwd';`), /FROM stdin/);
54
+ assert.ok(new ConvertError('x') instanceof Error);
55
+ });
56
+
57
+ test('UPDATE et DELETE sont comptés à part (des données qu’un seed ne rejoue pas)', () => {
58
+ const r = sql(`UPDATE t SET a = 1; DELETE FROM t; CREATE TABLE x (a int);`);
59
+ assert.strictEqual(r.mutations, 2);
60
+ assert.strictEqual(r.skipped.CREATE, 1);
61
+ });
62
+
63
+ test('CSV : en-tête, « ; », guillemets, vide = NULL, "" = chaîne vide', () => {
64
+ const rows = [];
65
+ const c = new CsvSource({ target: 'public.t', onRow: (t, cols, v) => rows.push({ cols, l: v.map(copyEscape).join('\t') }) });
66
+ const text = 'id;nom;note\r\n1;"a;""b""";\r\n2;"multi\nligne";""\n';
67
+ for (let i = 0; i < text.length; i += 4) c.push(text.slice(i, i + 4));
68
+ c.end();
69
+ assert.deepStrictEqual(rows[0].cols, ['id', 'nom', 'note']);
70
+ assert.deepStrictEqual(rows.map((r) => r.l), ['1\ta;"b"\t\\N', '2\tmulti\\nligne\t']);
71
+ });
72
+
73
+ test('nom de table tapé', () => {
74
+ assert.strictEqual(parseTarget('commune'), 'public.commune');
75
+ assert.strictEqual(parseTarget('Ref.Commune'), 'ref.commune');
76
+ assert.strictEqual(parseTarget('"Ref"."Commune"'), 'Ref.Commune');
77
+ assert.strictEqual(parseTarget('a.b.c'), null);
78
+ assert.strictEqual(parseTarget('x;drop'), null);
79
+ });
80
+
81
+ test('paquet : gzip + chiffrement, aller-retour, altération et troncature détectées', async () => {
82
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-seed-'));
83
+ const sink = new TableSink(path.join(dir, 't.gz'));
84
+ const lines = [];
85
+ for (let i = 0; i < 60000; i++) {
86
+ const l = `${i}\t${crypto.randomBytes(24).toString('hex')}`;
87
+ lines.push(l);
88
+ sink.row(l);
89
+ }
90
+ const r = await sink.close();
91
+ const plain = Buffer.from(lines.join('\n') + '\n');
92
+ assert.strictEqual(r.rows, 60000);
93
+ assert.strictEqual(r.plainBytes, plain.length);
94
+ assert.strictEqual(r.sha256, crypto.createHash('sha256').update(plain).digest('hex'));
95
+ const key = crypto.randomBytes(32);
96
+ await encryptFile(r.file, path.join(dir, 't.psd'), key);
97
+ const back = async (file, k = key) => {
98
+ const parts = [];
99
+ await pipeline(fs.createReadStream(file, { highWaterMark: 7777 }), decryptStream(k), zlib.createGunzip(), async function* (src) {
100
+ for await (const c of src) parts.push(c);
101
+ });
102
+ return Buffer.concat(parts);
103
+ };
104
+ assert.ok((await back(path.join(dir, 't.psd'))).equals(plain));
105
+ const enc = fs.readFileSync(path.join(dir, 't.psd'));
106
+ assert.ok(enc.length > 1024 * 1024, 'plusieurs blocs');
107
+ await assert.rejects(back(path.join(dir, 't.psd'), crypto.randomBytes(32)), /altered/);
108
+ const flipped = Buffer.from(enc);
109
+ flipped[100] ^= 1;
110
+ fs.writeFileSync(path.join(dir, 'f.psd'), flipped);
111
+ await assert.rejects(back(path.join(dir, 'f.psd')), /altered/);
112
+ // Coupé après le premier bloc : le dernier manque
113
+ const first = 4 + 32 + enc.readUInt32BE(4 + 12);
114
+ fs.writeFileSync(path.join(dir, 'c.psd'), enc.subarray(0, first));
115
+ await assert.rejects(back(path.join(dir, 'c.psd')), /truncated|altered/);
116
+ fs.rmSync(dir, { recursive: true, force: true });
117
+ });
118
+
119
+ test('script de chargement : noms entre guillemets, colonnes, avis lu', () => {
120
+ const h = A.head('public.Commune', ['id', 'n"om']);
121
+ assert.match(h, /create temp table _poad_seed on commit drop as select "id", "n""om" from "public"\."Commune" with no data;/);
122
+ assert.match(h, /\\set poad_into '"public"\."Commune"'/);
123
+ assert.match(h, /\ncopy :poad_into \("id", "n""om"\) from stdin;\n$/, 'le COPY précède immédiatement les données');
124
+ const t = A.tail('public.Commune', ['id', "o'k"]);
125
+ assert.match(t, /^\\\.\n/);
126
+ assert.match(t, /array\['id', 'o''k'\]::text\[\]/);
127
+ assert.match(A.tail('public.t', null), /cols text\[\] := null::text\[\]/);
128
+ assert.deepStrictEqual(A.parseNotice('NOTICE: poad-seed commune written=34945 deleted=2'), { table: 'commune', written: 34945, deleted: 2 });
129
+ });
130
+
131
+ test('ordre de chargement : une table après celles qu’elle référence', () => {
132
+ const order = A.loadOrder(['public.commune', 'public.region', 'public.departement'], ['commune|departement', 'departement|region', 'observation|commune']);
133
+ assert.deepStrictEqual(order, ['public.region', 'public.departement', 'public.commune']);
134
+ });
135
+
136
+ test('inspection : part du volume, valeurs lourdes quel que soit leur type (texte, binaire, géométrie)', () => {
137
+ const { TableStats } = require('../utils/seed/inspect');
138
+ const t = new TableStats('public.doc', ['id', 'code', 'roman', 'video', 'geom', 'n']);
139
+ for (let i = 0; i < 20; i++) t.add([String(i + 1), '0' + (i % 9), 'mot '.repeat(i * 3000), i % 2 ? '\\x' + 'ab'.repeat(40000) : null, '0106000020E6100000' + '00'.repeat(60), '1.5e3']);
140
+ const v = t.view();
141
+ const col = (n) => v.columns.find((c) => c.name === n);
142
+ assert.strictEqual(col('id').type, 'int');
143
+ assert.strictEqual(col('code').type, 'text', 'un code avec un zéro devant reste du texte');
144
+ assert.strictEqual(col('video').type, 'binary');
145
+ assert.strictEqual(col('video').max_value_bytes, 40000);
146
+ assert.strictEqual(col('geom').type, 'geometry');
147
+ assert.deepStrictEqual({ type: col('geom').geometry.type, srid: col('geom').geometry.srid }, { type: 'MultiPolygon', srid: 4326 });
148
+ assert.strictEqual(col('n').type, 'numeric');
149
+ assert.ok(col('roman').heavy && col('video').heavy && !col('id').heavy);
150
+ assert.deepStrictEqual(v.heavy.map((h) => h.column), ['roman', 'video']);
151
+ assert.ok(v.db_bytes > 0);
152
+ });
153
+
154
+ test('choix des colonnes : --fields, --exclude, par table, erreurs lisibles', () => {
155
+ const { columnPicker } = require('../utils/seed/inspect');
156
+ assert.strictEqual(columnPicker({}).pick('public.t', null), null);
157
+ const ex = columnPicker({ exclude: 'geom' });
158
+ assert.deepStrictEqual(ex.pick('public.commune', ['id', 'nom', 'geom']), [0, 1]);
159
+ assert.strictEqual(ex.pick('public.region', ['id', 'nom']), null);
160
+ assert.deepStrictEqual(ex.check(), []);
161
+ const f = columnPicker({ fields: 'commune.id,nom,typo' });
162
+ assert.deepStrictEqual(f.pick('public.commune', ['id', 'nom', 'geom']), [0, 1]);
163
+ assert.deepStrictEqual(f.pick('public.region', ['id', 'nom']), [1]);
164
+ assert.deepStrictEqual(f.check(), ['typo']);
165
+ assert.throws(() => columnPicker({ fields: 'a', exclude: 'b' }), /cannot be combined/);
166
+ assert.throws(() => columnPicker({ exclude: 'x' }).pick('public.t', null), /does not name its columns/);
167
+ assert.throws(() => columnPicker({ fields: 'zz' }).pick('public.t', ['a']), /no column left/);
168
+ });
@@ -0,0 +1,155 @@
1
+ // Script psql qui charge le contenu COPY d'une table dans sa table cible.
2
+ // Même texte que deploy/cloud/control/seed-apply.mjs de poad-site (chargement
3
+ // des projets hébergés) : à garder identiques.
4
+ //
5
+ // En une transaction. Table vide (premier chargement) : COPY directement dans
6
+ // la table (pas de copie temporaire : la place n'est prise qu'une fois). Sinon :
7
+ // table temporaire du même type, COPY, puis
8
+ // - avec clé primaire : les lignes absentes du contenu sont supprimées, les
9
+ // autres insérées ou mises à jour (ON CONFLICT) : les lignes des autres
10
+ // tables qui y renvoient restent valides ;
11
+ // - sans clé primaire : la table est vidée puis remplie ;
12
+ // - les séquences (serial, identity) repartent après le plus grand identifiant.
13
+ // Une suppression refusée par une clé étrangère annule tout, avec le message de
14
+ // PostgreSQL : rien n'est chargé à moitié.
15
+ 'use strict';
16
+
17
+ const quoteIdent = (s) => `"${String(s).replace(/"/g, '""')}"`;
18
+ const quoteLiteral = (s) => `'${String(s).replace(/'/g, "''")}'`;
19
+
20
+ /** « schéma.table » du registre vers un nom SQL entre guillemets */
21
+ function sqlName(target) {
22
+ const i = target.indexOf('.');
23
+ return `${quoteIdent(target.slice(0, i))}.${quoteIdent(target.slice(i + 1))}`;
24
+ }
25
+
26
+ /**
27
+ * Début du script (avant les lignes de données). Table vide (premier chargement) :
28
+ * COPY directement dans la table, sans copie temporaire, ce qui évite d'occuper deux
29
+ * fois la place au pic. Sinon : table temporaire puis fusion (voir tail).
30
+ */
31
+ function head(target, columns) {
32
+ const t = sqlName(target);
33
+ const cols = columns && columns.length ? columns.map(quoteIdent).join(', ') : '*';
34
+ const copyCols = columns && columns.length ? ` (${columns.map(quoteIdent).join(', ')})` : '';
35
+ return [
36
+ '\\set ON_ERROR_STOP on',
37
+ 'set client_min_messages = notice;',
38
+ 'begin;',
39
+ 'set local statement_timeout = 0;',
40
+ "set local lock_timeout = '60s';",
41
+ `select not exists (select 1 from ${t} limit 1) as poad_empty \\gset`,
42
+ // Le COPY doit précéder immédiatement les données : la destination est choisie avant, dans une variable
43
+ '\\if :poad_empty',
44
+ `\\set poad_into '${t.replace(/'/g, "\\'")}'`,
45
+ '\\else',
46
+ `create temp table _poad_seed on commit drop as select ${cols} from ${t} with no data;`,
47
+ '\\set poad_into _poad_seed',
48
+ '\\endif',
49
+ `copy :poad_into${copyCols} from stdin;`,
50
+ '',
51
+ ].join('\n');
52
+ }
53
+
54
+ /** Séquences (serial, identity) : elles repartent après le plus grand identifiant */
55
+ const SEQUENCES = ` for s in select a.attname::text as col, pg_get_serial_sequence(t::text, a.attname) as seq
56
+ from pg_attribute a where a.attrelid = t and a.attnum > 0 and not a.attisdropped loop
57
+ if s.seq is not null then
58
+ execute format('select setval(%L, coalesce((select max(%I) from %s), 0) + 1, false)', s.seq, s.col, t);
59
+ end if;
60
+ end loop;`;
61
+
62
+ /** Fin du script (après les lignes de données) */
63
+ function tail(target, columns) {
64
+ const arr = columns && columns.length ? `array[${columns.map(quoteLiteral).join(', ')}]::text[]` : 'null::text[]';
65
+ const reg = `${quoteLiteral(sqlName(target))}::regclass`;
66
+ return `\\.
67
+ \\if :poad_empty
68
+ do $poad$
69
+ declare
70
+ t regclass := ${reg};
71
+ n bigint;
72
+ s record;
73
+ begin
74
+ execute format('select count(*) from %s', t) into n;
75
+ ${SEQUENCES}
76
+ raise notice 'poad-seed % written=% deleted=0', t, n;
77
+ end
78
+ $poad$;
79
+ \\else
80
+ do $poad$
81
+ declare
82
+ t regclass := ${reg};
83
+ cols text[] := ${arr};
84
+ pk text[];
85
+ collist text;
86
+ setlist text;
87
+ n bigint := 0;
88
+ d bigint := 0;
89
+ s record;
90
+ begin
91
+ if cols is null then
92
+ select array_agg(attname::text order by attnum) into cols
93
+ from pg_attribute where attrelid = '_poad_seed'::regclass and attnum > 0 and not attisdropped;
94
+ end if;
95
+ select array_agg(a.attname::text order by array_position(i.indkey::int2[], a.attnum)) into pk
96
+ from pg_index i join pg_attribute a on a.attrelid = i.indrelid and a.attnum = any(i.indkey)
97
+ where i.indrelid = t and i.indisprimary;
98
+ collist := (select string_agg(quote_ident(c), ', ') from unnest(cols) c);
99
+ if pk is null or not (pk <@ cols) then
100
+ execute format('delete from %s', t);
101
+ get diagnostics d = row_count;
102
+ execute format('insert into %s (%s) overriding system value select %s from _poad_seed', t, collist, collist);
103
+ else
104
+ execute format('delete from %s x where not exists (select 1 from _poad_seed s where %s)', t,
105
+ (select string_agg(format('s.%1$I is not distinct from x.%1$I', c), ' and ') from unnest(pk) c));
106
+ get diagnostics d = row_count;
107
+ setlist := (select string_agg(format('%1$I = excluded.%1$I', c), ', ') from unnest(cols) c where c <> all (pk));
108
+ execute format('insert into %s (%s) overriding system value select %s from _poad_seed on conflict (%s) do %s', t, collist, collist,
109
+ (select string_agg(quote_ident(c), ', ') from unnest(pk) c),
110
+ case when setlist is null then 'nothing' else 'update set ' || setlist end);
111
+ end if;
112
+ get diagnostics n = row_count;
113
+ ${SEQUENCES}
114
+ raise notice 'poad-seed % written=% deleted=%', t, n, d;
115
+ end
116
+ $poad$;
117
+ \\endif
118
+ commit;
119
+ `;
120
+ }
121
+
122
+ /** Ligne « poad-seed … written=N deleted=M » de la sortie de psql */
123
+ function parseNotice(text) {
124
+ const m = /poad-seed (\S+) written=(\d+) deleted=(\d+)/.exec(String(text || ''));
125
+ return m ? { table: m[1], written: Number(m[2]), deleted: Number(m[3]) } : null;
126
+ }
127
+
128
+ /** Requête des dépendances (clés étrangères) entre tables, pour l'ordre de chargement */
129
+ const FK_SQL = "select conrelid::regclass::text || '|' || confrelid::regclass::text from pg_constraint where contype = 'f' and conrelid <> confrelid";
130
+
131
+ /** Ordre de chargement : une table après celles qu'elle référence (registre : schéma.table) */
132
+ function loadOrder(targets, edges) {
133
+ const norm = (s) => s.replace(/"/g, '');
134
+ const key = (t) => (t.includes('.') ? t : `public.${t}`);
135
+ const set = new Set(targets);
136
+ const deps = new Map(targets.map((t) => [t, new Set()]));
137
+ for (const line of edges) {
138
+ const [from, to] = String(line).split('|').map((x) => key(norm(x.trim())));
139
+ if (set.has(from) && set.has(to)) deps.get(from).add(to);
140
+ }
141
+ const out = [];
142
+ const state = new Map();
143
+ const visit = (t) => {
144
+ if (state.get(t) === 2) return;
145
+ if (state.get(t) === 1) return; // cycle : l'ordre donné l'emporte
146
+ state.set(t, 1);
147
+ for (const d of deps.get(t)) visit(d);
148
+ state.set(t, 2);
149
+ out.push(t);
150
+ };
151
+ for (const t of targets) visit(t);
152
+ return out;
153
+ }
154
+
155
+ module.exports = { head, tail, parseNotice, sqlName, quoteIdent, loadOrder, FK_SQL };