poad 2.51.0 → 2.52.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 +1 -1
- package/project/cli.js +8 -0
- package/project/seed/index.js +17 -0
- package/project/seed/load.js +50 -0
- package/project/seed/ls.js +27 -0
- package/project/seed/mode.js +14 -0
- package/project/seed/push.js +103 -0
- package/project/seed/rm.js +14 -0
- package/test/seed.test.js +133 -0
- package/utils/seed/apply.js +124 -0
- package/utils/seed/convert.js +673 -0
- package/utils/seed/pack.js +179 -0
- package/utils/seed/run.js +193 -0
package/package.json
CHANGED
package/project/cli.js
CHANGED
|
@@ -23,6 +23,14 @@ 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
|
+
push: 'Convert a .sql (INSERT, COPY) or .csv file and send each table: seed push <file> [--table schema.table] [--mode seed|reference] [--load] [--env <name>]',
|
|
29
|
+
ls: 'Seeds of the project: mode, size, what each environment has loaded, store quota',
|
|
30
|
+
load: 'Load seeds into an environment (--env, else the git branch, else main) or into the local engine (--local): seed load [table…] [--reference] [--force]',
|
|
31
|
+
mode: 'seed (development data, never into production without --force) or reference (loaded everywhere): seed mode <table> seed|reference',
|
|
32
|
+
rm: 'Remove a seed from poad.io (the table keeps its rows): seed rm <table> [--yes]',
|
|
33
|
+
},
|
|
26
34
|
link: 'Link this project to a poad.io project: [cloud] project = "<id>" in poad/config.toml (no secret): link [<id>]',
|
|
27
35
|
unlink: 'Remove the link to poad.io from poad/config.toml (nothing changes on poad.io)',
|
|
28
36
|
env: {
|
|
@@ -0,0 +1,17 @@
|
|
|
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 push <file>')} Convert a .sql (INSERT, COPY) or .csv file and send each table to poad.io`);
|
|
8
|
+
console.log(` ${c('poad seed ls')} Seeds of the project, their mode and what each environment has loaded`);
|
|
9
|
+
console.log(` ${c('poad seed load [table…]')} Load seeds into an environment (--env), or into the local engine (--local)`);
|
|
10
|
+
console.log(` ${c('poad seed mode <table> seed|reference')}`);
|
|
11
|
+
console.log(` ${c('poad seed rm <table>')} Remove a seed from the store (the table keeps its rows)`);
|
|
12
|
+
console.log(' ');
|
|
13
|
+
console.log(chalk.grey(' Data lives on poad.io (S3), outside git and outside the project volume, encrypted by poad.'));
|
|
14
|
+
console.log(chalk.grey(' seed: development data, never loaded into production unless --force; reference: loaded everywhere.'));
|
|
15
|
+
console.log(chalk.grey(' No local folder needed: --project <id> targets a project created in the console.'));
|
|
16
|
+
console.log(' ');
|
|
17
|
+
};
|
|
@@ -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,103 @@
|
|
|
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'], 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
|
+
dir,
|
|
31
|
+
onProgress: (read, total) => {
|
|
32
|
+
if (!out.json && process.stderr.isTTY && Date.now() - last > 250) {
|
|
33
|
+
last = Date.now();
|
|
34
|
+
process.stderr.write(`\r ${chalk.grey('reading')} ${path.basename(file)} ${Math.floor((read / total) * 100)}% `);
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
});
|
|
38
|
+
if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
|
|
39
|
+
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' });
|
|
40
|
+
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)`).join(', ')}`);
|
|
41
|
+
const skipped = Object.entries(conv.skipped).filter(([w]) => !['SET', 'BEGIN', 'COMMIT', 'END', 'SELECT'].includes(w));
|
|
42
|
+
if (skipped.length) out.log(chalk.grey(` Ignored, not data: ${skipped.map(([w, n]) => `${n} ${w}`).join(', ')} (structure goes through migrations).`));
|
|
43
|
+
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.`));
|
|
44
|
+
// 2. Envoi, table par table
|
|
45
|
+
const results = [];
|
|
46
|
+
for (const t of conv.tables) {
|
|
47
|
+
let shown = 0;
|
|
48
|
+
const r = await S.pushTable(id, t, {
|
|
49
|
+
mode,
|
|
50
|
+
source: path.basename(file),
|
|
51
|
+
onProgress: (done, total) => {
|
|
52
|
+
if (!out.json && process.stderr.isTTY && Date.now() - shown > 250) {
|
|
53
|
+
shown = Date.now();
|
|
54
|
+
process.stderr.write(`\r ${chalk.grey('sending')} ${t.target} ${S.fmt(done)} / ${S.fmt(total)} `);
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
|
|
59
|
+
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' : ''}`);
|
|
60
|
+
results.push({ target: t.target, rows: t.rows, sha256: t.sha256, uploaded: r.uploaded, stored_bytes: r.stored, mode });
|
|
61
|
+
}
|
|
62
|
+
// 3. Chargement facultatif
|
|
63
|
+
let load = null;
|
|
64
|
+
if (opts.load) {
|
|
65
|
+
const branches = require('../../utils/cloud/branches');
|
|
66
|
+
const env = await branches.resolve(id, { wanted: opts.env, root });
|
|
67
|
+
load = await startAndWait(id, env.branch, results.map((r) => r.target), opts, out);
|
|
68
|
+
} 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)`));
|
|
69
|
+
out.result({ project: id, tables: results, load });
|
|
70
|
+
return load && load.status === 'failed' ? api.EXIT.failed : 0;
|
|
71
|
+
} finally {
|
|
72
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
/** Lance un chargement hébergé et suit ses étapes */
|
|
77
|
+
async function startAndWait(id, branch, targets, opts, out) {
|
|
78
|
+
const api = require('../../utils/cloud/api');
|
|
79
|
+
const S = require('../../utils/seed/run');
|
|
80
|
+
const { chalk } = out;
|
|
81
|
+
let started;
|
|
82
|
+
try {
|
|
83
|
+
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' });
|
|
84
|
+
} catch (e) {
|
|
85
|
+
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 });
|
|
86
|
+
throw e;
|
|
87
|
+
}
|
|
88
|
+
out.log(chalk.grey(` Loading into ${branch} (${started.targets.length} table(s))…`));
|
|
89
|
+
const done = new Set();
|
|
90
|
+
const l = await S.waitLoad(id, started.load_id, {
|
|
91
|
+
onStep: (st) => {
|
|
92
|
+
for (const s of st.steps) {
|
|
93
|
+
if (done.has(s.target) || !['done', 'failed'].includes(s.status)) continue;
|
|
94
|
+
done.add(s.target);
|
|
95
|
+
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)`);
|
|
96
|
+
else out.log(`${chalk.redBright('✖')} ${s.target}: ${s.error}`);
|
|
97
|
+
}
|
|
98
|
+
},
|
|
99
|
+
});
|
|
100
|
+
if (l.status === 'failed') out.log(chalk.grey(' Nothing was half-loaded: each table is all or nothing.'));
|
|
101
|
+
return l;
|
|
102
|
+
}
|
|
103
|
+
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,133 @@
|
|
|
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, l) => rows.push({ t, c, l }) });
|
|
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, l) => rows.push({ cols, l }) });
|
|
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, /copy _poad_seed \("id", "n""om"\) from stdin;/);
|
|
123
|
+
const t = A.tail('public.Commune', ['id', "o'k"]);
|
|
124
|
+
assert.match(t, /^\\\.\n/);
|
|
125
|
+
assert.match(t, /array\['id', 'o''k'\]::text\[\]/);
|
|
126
|
+
assert.match(A.tail('public.t', null), /cols text\[\] := null::text\[\]/);
|
|
127
|
+
assert.deepStrictEqual(A.parseNotice('NOTICE: poad-seed commune written=34945 deleted=2'), { table: 'commune', written: 34945, deleted: 2 });
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
test('ordre de chargement : une table après celles qu’elle référence', () => {
|
|
131
|
+
const order = A.loadOrder(['public.commune', 'public.region', 'public.departement'], ['commune|departement', 'departement|region', 'observation|commune']);
|
|
132
|
+
assert.deepStrictEqual(order, ['public.region', 'public.departement', 'public.commune']);
|
|
133
|
+
});
|
|
@@ -0,0 +1,124 @@
|
|
|
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 temporaire du même type, COPY, puis
|
|
6
|
+
// - avec clé primaire : les lignes absentes du contenu sont supprimées, les
|
|
7
|
+
// autres insérées ou mises à jour (ON CONFLICT) : les lignes des autres
|
|
8
|
+
// tables qui y renvoient restent valides ;
|
|
9
|
+
// - sans clé primaire : la table est vidée puis remplie ;
|
|
10
|
+
// - les séquences (serial, identity) repartent après le plus grand identifiant.
|
|
11
|
+
// Une suppression refusée par une clé étrangère annule tout, avec le message de
|
|
12
|
+
// PostgreSQL : rien n'est chargé à moitié.
|
|
13
|
+
'use strict';
|
|
14
|
+
|
|
15
|
+
const quoteIdent = (s) => `"${String(s).replace(/"/g, '""')}"`;
|
|
16
|
+
const quoteLiteral = (s) => `'${String(s).replace(/'/g, "''")}'`;
|
|
17
|
+
|
|
18
|
+
/** « schéma.table » du registre vers un nom SQL entre guillemets */
|
|
19
|
+
function sqlName(target) {
|
|
20
|
+
const i = target.indexOf('.');
|
|
21
|
+
return `${quoteIdent(target.slice(0, i))}.${quoteIdent(target.slice(i + 1))}`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Début du script (avant les lignes de données) */
|
|
25
|
+
function head(target, columns) {
|
|
26
|
+
const t = sqlName(target);
|
|
27
|
+
const cols = columns && columns.length ? columns.map(quoteIdent).join(', ') : '*';
|
|
28
|
+
const copyCols = columns && columns.length ? ` (${columns.map(quoteIdent).join(', ')})` : '';
|
|
29
|
+
return [
|
|
30
|
+
'\\set ON_ERROR_STOP on',
|
|
31
|
+
'set client_min_messages = notice;',
|
|
32
|
+
'begin;',
|
|
33
|
+
"set local statement_timeout = 0;",
|
|
34
|
+
"set local lock_timeout = '60s';",
|
|
35
|
+
`create temp table _poad_seed on commit drop as select ${cols} from ${t} with no data;`,
|
|
36
|
+
`copy _poad_seed${copyCols} from stdin;`,
|
|
37
|
+
'',
|
|
38
|
+
].join('\n');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Fin du script (après les lignes de données) */
|
|
42
|
+
function tail(target, columns) {
|
|
43
|
+
const arr = columns && columns.length ? `array[${columns.map(quoteLiteral).join(', ')}]::text[]` : 'null::text[]';
|
|
44
|
+
return `\\.
|
|
45
|
+
do $poad$
|
|
46
|
+
declare
|
|
47
|
+
t regclass := ${quoteLiteral(sqlName(target))}::regclass;
|
|
48
|
+
cols text[] := ${arr};
|
|
49
|
+
pk text[];
|
|
50
|
+
collist text;
|
|
51
|
+
setlist text;
|
|
52
|
+
n bigint := 0;
|
|
53
|
+
d bigint := 0;
|
|
54
|
+
s record;
|
|
55
|
+
begin
|
|
56
|
+
if cols is null then
|
|
57
|
+
select array_agg(attname::text order by attnum) into cols
|
|
58
|
+
from pg_attribute where attrelid = '_poad_seed'::regclass and attnum > 0 and not attisdropped;
|
|
59
|
+
end if;
|
|
60
|
+
select array_agg(a.attname::text order by array_position(i.indkey::int2[], a.attnum)) into pk
|
|
61
|
+
from pg_index i join pg_attribute a on a.attrelid = i.indrelid and a.attnum = any(i.indkey)
|
|
62
|
+
where i.indrelid = t and i.indisprimary;
|
|
63
|
+
collist := (select string_agg(quote_ident(c), ', ') from unnest(cols) c);
|
|
64
|
+
if pk is null or not (pk <@ cols) then
|
|
65
|
+
execute format('delete from %s', t);
|
|
66
|
+
get diagnostics d = row_count;
|
|
67
|
+
execute format('insert into %s (%s) overriding system value select %s from _poad_seed', t, collist, collist);
|
|
68
|
+
else
|
|
69
|
+
execute format('delete from %s x where not exists (select 1 from _poad_seed s where %s)', t,
|
|
70
|
+
(select string_agg(format('s.%1$I is not distinct from x.%1$I', c), ' and ') from unnest(pk) c));
|
|
71
|
+
get diagnostics d = row_count;
|
|
72
|
+
setlist := (select string_agg(format('%1$I = excluded.%1$I', c), ', ') from unnest(cols) c where c <> all (pk));
|
|
73
|
+
execute format('insert into %s (%s) overriding system value select %s from _poad_seed on conflict (%s) do %s', t, collist, collist,
|
|
74
|
+
(select string_agg(quote_ident(c), ', ') from unnest(pk) c),
|
|
75
|
+
case when setlist is null then 'nothing' else 'update set ' || setlist end);
|
|
76
|
+
end if;
|
|
77
|
+
get diagnostics n = row_count;
|
|
78
|
+
for s in select a.attname::text as col, pg_get_serial_sequence(t::text, a.attname) as seq
|
|
79
|
+
from pg_attribute a where a.attrelid = t and a.attnum > 0 and not a.attisdropped loop
|
|
80
|
+
if s.seq is not null then
|
|
81
|
+
execute format('select setval(%L, coalesce((select max(%I) from %s), 0) + 1, false)', s.seq, s.col, t);
|
|
82
|
+
end if;
|
|
83
|
+
end loop;
|
|
84
|
+
raise notice 'poad-seed % written=% deleted=%', t, n, d;
|
|
85
|
+
end
|
|
86
|
+
$poad$;
|
|
87
|
+
commit;
|
|
88
|
+
`;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Ligne « poad-seed … written=N deleted=M » de la sortie de psql */
|
|
92
|
+
function parseNotice(text) {
|
|
93
|
+
const m = /poad-seed (\S+) written=(\d+) deleted=(\d+)/.exec(String(text || ''));
|
|
94
|
+
return m ? { table: m[1], written: Number(m[2]), deleted: Number(m[3]) } : null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Requête des dépendances (clés étrangères) entre tables, pour l'ordre de chargement */
|
|
98
|
+
const FK_SQL = "select conrelid::regclass::text || '|' || confrelid::regclass::text from pg_constraint where contype = 'f' and conrelid <> confrelid";
|
|
99
|
+
|
|
100
|
+
/** Ordre de chargement : une table après celles qu'elle référence (registre : schéma.table) */
|
|
101
|
+
function loadOrder(targets, edges) {
|
|
102
|
+
const norm = (s) => s.replace(/"/g, '');
|
|
103
|
+
const key = (t) => (t.includes('.') ? t : `public.${t}`);
|
|
104
|
+
const set = new Set(targets);
|
|
105
|
+
const deps = new Map(targets.map((t) => [t, new Set()]));
|
|
106
|
+
for (const line of edges) {
|
|
107
|
+
const [from, to] = String(line).split('|').map((x) => key(norm(x.trim())));
|
|
108
|
+
if (set.has(from) && set.has(to)) deps.get(from).add(to);
|
|
109
|
+
}
|
|
110
|
+
const out = [];
|
|
111
|
+
const state = new Map();
|
|
112
|
+
const visit = (t) => {
|
|
113
|
+
if (state.get(t) === 2) return;
|
|
114
|
+
if (state.get(t) === 1) return; // cycle : l'ordre donné l'emporte
|
|
115
|
+
state.set(t, 1);
|
|
116
|
+
for (const d of deps.get(t)) visit(d);
|
|
117
|
+
state.set(t, 2);
|
|
118
|
+
out.push(t);
|
|
119
|
+
};
|
|
120
|
+
for (const t of targets) visit(t);
|
|
121
|
+
return out;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
module.exports = { head, tail, parseNotice, sqlName, quoteIdent, loadOrder, FK_SQL };
|