poad 2.52.0 → 2.54.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 +14 -6
- package/project/ref/index.js +17 -0
- package/project/ref/inspect.js +45 -0
- package/project/ref/load.js +50 -0
- package/project/ref/ls.js +27 -0
- package/project/ref/push.js +108 -0
- package/project/ref/rm.js +14 -0
- package/project/seed/index.js +2 -17
- package/project/seed/inspect.js +2 -0
- package/project/seed/load.js +2 -50
- package/project/seed/ls.js +2 -27
- package/project/seed/push.js +2 -103
- package/project/seed/rm.js +2 -14
- package/test/seed.test.js +45 -3
- package/utils/seed/apply.js +42 -11
- package/utils/seed/convert.js +21 -7
- package/utils/seed/inspect.js +236 -0
- package/utils/seed/report.js +37 -0
- package/utils/seed/run.js +40 -19
- package/project/seed/mode.js +0 -14
package/package.json
CHANGED
package/project/cli.js
CHANGED
|
@@ -23,13 +23,21 @@ 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
|
+
ref: {
|
|
27
|
+
description: 'Heavy reference tables (municipalities, code lists…) stored on poad.io, outside git and the project volume (S3, encrypted by poad), loaded everywhere; 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: ref inspect <file> [--fields a,b | --exclude c]',
|
|
29
|
+
push: 'Send each table of a .sql (INSERT, COPY) or .csv file as a reference table: ref push <file> [--fields a,b | --exclude c] [--table schema.table] [--load] [--env <name>]',
|
|
30
|
+
ls: 'Reference tables stored on poad.io: size, columns left out, what each environment has loaded, store quota',
|
|
31
|
+
load: 'Load reference tables into an environment (--env, else the git branch, else main) or into the local engine (--local): ref load [table…]',
|
|
32
|
+
rm: 'Remove a reference table from poad.io (the table keeps its rows): ref rm <table> [--yes]',
|
|
33
|
+
},
|
|
26
34
|
seed: {
|
|
27
|
-
description: '
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
rm: '
|
|
35
|
+
description: 'Old name of poad ref (the store keeps reference tables only)',
|
|
36
|
+
inspect: 'Same as poad ref inspect',
|
|
37
|
+
push: 'Same as poad ref push',
|
|
38
|
+
ls: 'Same as poad ref ls',
|
|
39
|
+
load: 'Same as poad ref load',
|
|
40
|
+
rm: 'Same as poad ref rm',
|
|
33
41
|
},
|
|
34
42
|
link: 'Link this project to a poad.io project: [cloud] project = "<id>" in poad/config.toml (no secret): link [<id>]',
|
|
35
43
|
unlink: 'Remove the link to poad.io from poad/config.toml (nothing changes on poad.io)',
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// poad ref : aide des commandes des tables de référence lourdes (magasin de poad.io)
|
|
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 ref inspect <file>')} What the file holds, column by column, and its weight: nothing is sent`);
|
|
8
|
+
console.log(` ${c('poad ref push <file>')} Send each table of a .sql (INSERT, COPY) or .csv file as a reference table`);
|
|
9
|
+
console.log(` ${c('poad ref ls')} Reference tables stored on poad.io, and what each environment has loaded`);
|
|
10
|
+
console.log(` ${c('poad ref load [table…]')} Load them into an environment (--env), or into the local engine (--local)`);
|
|
11
|
+
console.log(` ${c('poad ref rm <table>')} Remove a reference from poad.io (the table keeps its rows)`);
|
|
12
|
+
console.log(' ');
|
|
13
|
+
console.log(chalk.grey(' Reference tables (municipalities, code lists…) are part of the project and are loaded everywhere,'));
|
|
14
|
+
console.log(chalk.grey(' production included. Heavy ones live on poad.io (S3, encrypted by poad), outside git and the project volume.'));
|
|
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,45 @@
|
|
|
1
|
+
// poad ref 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 ref 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 ref push ${path.basename(file)}${opts.fields ? ` --fields ${opts.fields}` : opts.exclude ? ` --exclude ${opts.exclude}` : ''}`));
|
|
45
|
+
});
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// poad ref load [table…] [--env <branche>] [--project <id>] [--json]
|
|
2
|
+
// poad ref 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'] }, 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: 'references' });
|
|
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 reference: ${missing.join(', ')} ("poad ref ls")`);
|
|
36
|
+
items = items.filter((s) => targets.includes(s.target));
|
|
37
|
+
}
|
|
38
|
+
if (!items.length) throw api.usageError('No reference to load ("poad ref 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: `reference ${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 ref ls [--project <id>] [--json] : registre des références, 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: 'references' });
|
|
10
|
+
out.result({ project: id, ...r });
|
|
11
|
+
if (out.json) return;
|
|
12
|
+
if (!r.store) out.log(chalk.yellowBright(' The reference 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 reference stored yet: poad ref inspect <file>, then poad ref push <file>'));
|
|
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.rows} rows ${fmt(s.stored_bytes)} stored${s.db_bytes ? `, ≈ ${fmt(s.db_bytes)} in the database` : ''} ${chalk.grey(s.source || '')}${s.dropped && s.dropped.length ? chalk.grey(` without ${s.dropped.join(', ')}`) : ''}`);
|
|
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,108 @@
|
|
|
1
|
+
// poad ref push <fichier> [--fields a,b | --exclude c] [--table schéma.table] [--format sql|csv]
|
|
2
|
+
// [--load] [--env <branche>] [--project <id>] [--json]
|
|
3
|
+
// Tables de référence lourdes (communes, nomenclatures…) : convertit le fichier (une entrée par
|
|
4
|
+
// table), chiffre chaque table, l'envoie au magasin de poad.io par URL signée et l'inscrit au registre
|
|
5
|
+
// du projet. Une référence se charge partout, production comprise.
|
|
6
|
+
// --load : la charge aussitôt dans l'environnement visé (--env, sinon la branche git, sinon main).
|
|
7
|
+
module.exports = (args, raw) =>
|
|
8
|
+
require('../../utils/cloud/cli').run(raw, { values: ['table', 'format', 'env', 'project', 'fields', 'exclude'], flags: ['load', 'yes'] }, async ({ opts, positionals, out }) => {
|
|
9
|
+
const fs = require('fs');
|
|
10
|
+
const path = require('path');
|
|
11
|
+
const api = require('../../utils/cloud/api');
|
|
12
|
+
const cli = require('../../utils/cloud/cli');
|
|
13
|
+
const S = require('../../utils/seed/run');
|
|
14
|
+
const { chalk } = out;
|
|
15
|
+
const file = positionals[0];
|
|
16
|
+
if (!file) throw api.usageError('poad ref push <file.sql|file.csv> [--fields a,b | --exclude c] [--table schema.table]');
|
|
17
|
+
if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw api.usageError(`${file}: no such file`);
|
|
18
|
+
const mode = '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 ref 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 reference 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'}${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 ref load ${results.map((r) => r.target).join(' ')}${opts.env ? ` --env ${opts.env}` : ''} (or poad ref 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 }, what: 'reference load' });
|
|
90
|
+
} catch (e) {
|
|
91
|
+
throw e;
|
|
92
|
+
}
|
|
93
|
+
out.log(chalk.grey(` Loading into ${branch} (${started.targets.length} table(s))…`));
|
|
94
|
+
const done = new Set();
|
|
95
|
+
const l = await S.waitLoad(id, started.load_id, {
|
|
96
|
+
onStep: (st) => {
|
|
97
|
+
for (const s of st.steps) {
|
|
98
|
+
if (done.has(s.target) || !['done', 'failed'].includes(s.status)) continue;
|
|
99
|
+
done.add(s.target);
|
|
100
|
+
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)`);
|
|
101
|
+
else out.log(`${chalk.redBright('✖')} ${s.target}: ${s.error}`);
|
|
102
|
+
}
|
|
103
|
+
},
|
|
104
|
+
});
|
|
105
|
+
if (l.status === 'failed') out.log(chalk.grey(' Nothing was half-loaded: each table is all or nothing.'));
|
|
106
|
+
return l;
|
|
107
|
+
}
|
|
108
|
+
module.exports.startAndWait = startAndWait;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// poad ref rm <table> [--yes] [--project <id>] [--json] : retire la référence 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 ref rm <schema.table>');
|
|
9
|
+
const { id } = cli.targetProject(opts);
|
|
10
|
+
await cli.confirm(`Remove the reference ${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: `reference ${target}` });
|
|
12
|
+
out.result({ project: id, ...r });
|
|
13
|
+
out.log(`${out.chalk.greenBright('✔')} reference ${target} removed`);
|
|
14
|
+
});
|
package/project/seed/index.js
CHANGED
|
@@ -1,17 +1,2 @@
|
|
|
1
|
-
// poad
|
|
2
|
-
module.exports =
|
|
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
|
-
};
|
|
1
|
+
// Ancien nom de poad ref (le magasin ne garde que des tables de référence)
|
|
2
|
+
module.exports = require('../ref/index');
|
package/project/seed/load.js
CHANGED
|
@@ -1,50 +1,2 @@
|
|
|
1
|
-
// poad
|
|
2
|
-
|
|
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
|
-
});
|
|
1
|
+
// Ancien nom de poad ref (le magasin ne garde que des tables de référence)
|
|
2
|
+
module.exports = require('../ref/load');
|
package/project/seed/ls.js
CHANGED
|
@@ -1,27 +1,2 @@
|
|
|
1
|
-
//
|
|
2
|
-
module.exports = (
|
|
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
|
-
});
|
|
1
|
+
// Ancien nom de poad ref (le magasin ne garde que des tables de référence)
|
|
2
|
+
module.exports = require('../ref/ls');
|
package/project/seed/push.js
CHANGED
|
@@ -1,103 +1,2 @@
|
|
|
1
|
-
// poad
|
|
2
|
-
|
|
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;
|
|
1
|
+
// Ancien nom de poad ref (le magasin ne garde que des tables de référence)
|
|
2
|
+
module.exports = require('../ref/push');
|
package/project/seed/rm.js
CHANGED
|
@@ -1,14 +1,2 @@
|
|
|
1
|
-
//
|
|
2
|
-
module.exports = (
|
|
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
|
-
});
|
|
1
|
+
// Ancien nom de poad ref (le magasin ne garde que des tables de référence)
|
|
2
|
+
module.exports = require('../ref/rm');
|
package/test/seed.test.js
CHANGED
|
@@ -13,7 +13,7 @@ const A = require('../utils/seed/apply');
|
|
|
13
13
|
|
|
14
14
|
const sql = (text, chunk = 0) => {
|
|
15
15
|
const rows = [];
|
|
16
|
-
const s = new SqlSource({ onRow: (t, c,
|
|
16
|
+
const s = new SqlSource({ onRow: (t, c, v) => rows.push({ t, c, l: v.map(copyEscape).join('\t') }) });
|
|
17
17
|
if (chunk) for (let i = 0; i < text.length; i += chunk) s.push(text.slice(i, i + chunk));
|
|
18
18
|
else s.push(text);
|
|
19
19
|
s.end();
|
|
@@ -62,7 +62,7 @@ test('UPDATE et DELETE sont comptés à part (des données qu’un seed ne rejou
|
|
|
62
62
|
|
|
63
63
|
test('CSV : en-tête, « ; », guillemets, vide = NULL, "" = chaîne vide', () => {
|
|
64
64
|
const rows = [];
|
|
65
|
-
const c = new CsvSource({ target: 'public.t', onRow: (t, cols,
|
|
65
|
+
const c = new CsvSource({ target: 'public.t', onRow: (t, cols, v) => rows.push({ cols, l: v.map(copyEscape).join('\t') }) });
|
|
66
66
|
const text = 'id;nom;note\r\n1;"a;""b""";\r\n2;"multi\nligne";""\n';
|
|
67
67
|
for (let i = 0; i < text.length; i += 4) c.push(text.slice(i, i + 4));
|
|
68
68
|
c.end();
|
|
@@ -119,7 +119,8 @@ test('paquet : gzip + chiffrement, aller-retour, altération et troncature déte
|
|
|
119
119
|
test('script de chargement : noms entre guillemets, colonnes, avis lu', () => {
|
|
120
120
|
const h = A.head('public.Commune', ['id', 'n"om']);
|
|
121
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,
|
|
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');
|
|
123
124
|
const t = A.tail('public.Commune', ['id', "o'k"]);
|
|
124
125
|
assert.match(t, /^\\\.\n/);
|
|
125
126
|
assert.match(t, /array\['id', 'o''k'\]::text\[\]/);
|
|
@@ -131,3 +132,44 @@ test('ordre de chargement : une table après celles qu’elle référence', () =
|
|
|
131
132
|
const order = A.loadOrder(['public.commune', 'public.region', 'public.departement'], ['commune|departement', 'departement|region', 'observation|commune']);
|
|
132
133
|
assert.deepStrictEqual(order, ['public.region', 'public.departement', 'public.commune']);
|
|
133
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
|
+
});
|
|
169
|
+
|
|
170
|
+
test('inspection : une petite table n’a pas de colonne lourde', () => {
|
|
171
|
+
const { TableStats } = require('../utils/seed/inspect');
|
|
172
|
+
const t = new TableStats('public.t', ['id', 'nom']);
|
|
173
|
+
t.add(['1', 'a']);
|
|
174
|
+
assert.deepStrictEqual(t.view().heavy, []);
|
|
175
|
+
});
|
package/utils/seed/apply.js
CHANGED
|
@@ -2,7 +2,9 @@
|
|
|
2
2
|
// Même texte que deploy/cloud/control/seed-apply.mjs de poad-site (chargement
|
|
3
3
|
// des projets hébergés) : à garder identiques.
|
|
4
4
|
//
|
|
5
|
-
// En une transaction
|
|
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
|
|
6
8
|
// - avec clé primaire : les lignes absentes du contenu sont supprimées, les
|
|
7
9
|
// autres insérées ou mises à jour (ON CONFLICT) : les lignes des autres
|
|
8
10
|
// tables qui y renvoient restent valides ;
|
|
@@ -21,7 +23,11 @@ function sqlName(target) {
|
|
|
21
23
|
return `${quoteIdent(target.slice(0, i))}.${quoteIdent(target.slice(i + 1))}`;
|
|
22
24
|
}
|
|
23
25
|
|
|
24
|
-
/**
|
|
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
|
+
*/
|
|
25
31
|
function head(target, columns) {
|
|
26
32
|
const t = sqlName(target);
|
|
27
33
|
const cols = columns && columns.length ? columns.map(quoteIdent).join(', ') : '*';
|
|
@@ -30,21 +36,50 @@ function head(target, columns) {
|
|
|
30
36
|
'\\set ON_ERROR_STOP on',
|
|
31
37
|
'set client_min_messages = notice;',
|
|
32
38
|
'begin;',
|
|
33
|
-
|
|
39
|
+
'set local statement_timeout = 0;',
|
|
34
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',
|
|
35
46
|
`create temp table _poad_seed on commit drop as select ${cols} from ${t} with no data;`,
|
|
36
|
-
|
|
47
|
+
'\\set poad_into _poad_seed',
|
|
48
|
+
'\\endif',
|
|
49
|
+
`copy :poad_into${copyCols} from stdin;`,
|
|
37
50
|
'',
|
|
38
51
|
].join('\n');
|
|
39
52
|
}
|
|
40
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
|
+
|
|
41
62
|
/** Fin du script (après les lignes de données) */
|
|
42
63
|
function tail(target, columns) {
|
|
43
64
|
const arr = columns && columns.length ? `array[${columns.map(quoteLiteral).join(', ')}]::text[]` : 'null::text[]';
|
|
65
|
+
const reg = `${quoteLiteral(sqlName(target))}::regclass`;
|
|
44
66
|
return `\\.
|
|
67
|
+
\\if :poad_empty
|
|
45
68
|
do $poad$
|
|
46
69
|
declare
|
|
47
|
-
t regclass := ${
|
|
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};
|
|
48
83
|
cols text[] := ${arr};
|
|
49
84
|
pk text[];
|
|
50
85
|
collist text;
|
|
@@ -75,15 +110,11 @@ begin
|
|
|
75
110
|
case when setlist is null then 'nothing' else 'update set ' || setlist end);
|
|
76
111
|
end if;
|
|
77
112
|
get diagnostics n = row_count;
|
|
78
|
-
|
|
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;
|
|
113
|
+
${SEQUENCES}
|
|
84
114
|
raise notice 'poad-seed % written=% deleted=%', t, n, d;
|
|
85
115
|
end
|
|
86
116
|
$poad$;
|
|
117
|
+
\\endif
|
|
87
118
|
commit;
|
|
88
119
|
`;
|
|
89
120
|
}
|
package/utils/seed/convert.js
CHANGED
|
@@ -109,7 +109,21 @@ function readColumns(s, i) {
|
|
|
109
109
|
}
|
|
110
110
|
}
|
|
111
111
|
|
|
112
|
-
// --- Valeurs vers COPY texte
|
|
112
|
+
// --- Valeurs vers COPY texte (et retour) -----------------------------------------
|
|
113
|
+
|
|
114
|
+
const COPY_UNESCAPE = { b: '\b', f: '\f', n: '\n', r: '\r', t: '\t', v: '\v', '\\': '\\' };
|
|
115
|
+
/** Une ligne de données COPY (format texte) -> valeurs brutes ; \N = null */
|
|
116
|
+
function splitCopy(line) {
|
|
117
|
+
return line.split('\t').map((f) => {
|
|
118
|
+
if (f === '\\N') return null;
|
|
119
|
+
if (!f.includes('\\')) return f;
|
|
120
|
+
return f.replace(/\\(x[0-9A-Fa-f]{1,2}|[0-7]{1,3}|.)/g, (_, e) => {
|
|
121
|
+
if (e[0] === 'x' && e.length > 1) return String.fromCharCode(parseInt(e.slice(1), 16));
|
|
122
|
+
if (/^[0-7]+$/.test(e)) return String.fromCharCode(parseInt(e, 8));
|
|
123
|
+
return COPY_UNESCAPE[e] ?? e;
|
|
124
|
+
});
|
|
125
|
+
});
|
|
126
|
+
}
|
|
113
127
|
|
|
114
128
|
/** Échappement du format texte de COPY */
|
|
115
129
|
function copyEscape(v) {
|
|
@@ -219,7 +233,7 @@ function unescapeE(piece) {
|
|
|
219
233
|
|
|
220
234
|
/**
|
|
221
235
|
* Analyseur SQL par morceaux. Pour chaque ligne de données :
|
|
222
|
-
* onRow(target, columns|null,
|
|
236
|
+
* onRow(target, columns|null, values) values : chaînes brutes ou null (non échappées)
|
|
223
237
|
* Les instructions entières (hors données COPY) sont découpées au « ; » hors
|
|
224
238
|
* chaînes, identifiants entre guillemets, commentaires et $$…$$.
|
|
225
239
|
*/
|
|
@@ -432,7 +446,7 @@ class SqlSource {
|
|
|
432
446
|
const vals = [];
|
|
433
447
|
for (;;) {
|
|
434
448
|
const v = readValue(s, i, ctx);
|
|
435
|
-
vals.push(
|
|
449
|
+
vals.push(v.value);
|
|
436
450
|
i = skipSpace(s, v.end);
|
|
437
451
|
if (s[i] === ',') {
|
|
438
452
|
i++;
|
|
@@ -445,7 +459,7 @@ class SqlSource {
|
|
|
445
459
|
throw new ConvertError(`"," or ")" expected in VALUES, found "${s.slice(i, i + 10)}"`, ctx);
|
|
446
460
|
}
|
|
447
461
|
if (columns && vals.length !== columns.length) throw new ConvertError(`${vals.length} values for ${columns.length} columns`, ctx);
|
|
448
|
-
this.onRow(target, columns, vals
|
|
462
|
+
this.onRow(target, columns, vals);
|
|
449
463
|
i = skipSpace(s, i);
|
|
450
464
|
if (s[i] === ',') {
|
|
451
465
|
i++;
|
|
@@ -508,7 +522,7 @@ class SqlSource {
|
|
|
508
522
|
this.state = null;
|
|
509
523
|
return true;
|
|
510
524
|
}
|
|
511
|
-
this.onRow(this.copy.target, this.copy.columns, row);
|
|
525
|
+
this.onRow(this.copy.target, this.copy.columns, splitCopy(row));
|
|
512
526
|
}
|
|
513
527
|
}
|
|
514
528
|
}
|
|
@@ -643,7 +657,7 @@ class CsvSource {
|
|
|
643
657
|
return;
|
|
644
658
|
}
|
|
645
659
|
if (r.length !== this.columns.length) throw new ConvertError(`${r.length} fields for ${this.columns.length} columns`, { line: this.line, table: this.target });
|
|
646
|
-
this.onRow(this.target, this.columns, r
|
|
660
|
+
this.onRow(this.target, this.columns, r);
|
|
647
661
|
}
|
|
648
662
|
|
|
649
663
|
end() {
|
|
@@ -670,4 +684,4 @@ function parseTarget(text) {
|
|
|
670
684
|
return targetOf(qualify(n.parts));
|
|
671
685
|
}
|
|
672
686
|
|
|
673
|
-
module.exports = { SqlSource, CsvSource, ConvertError, copyEscape, parseTarget, qualify, targetOf, readValue };
|
|
687
|
+
module.exports = { SqlSource, CsvSource, ConvertError, copyEscape, splitCopy, parseTarget, qualify, targetOf, readValue };
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
// Seed inspector : ce que contient un fichier de données, colonne par colonne,
|
|
2
|
+
// avant tout envoi. L'essentiel est la VOLUMÉTRIE, quelle que soit la nature de
|
|
3
|
+
// la donnée (géométrie, long texte, binaire d'une image ou d'une vidéo, JSON) :
|
|
4
|
+
// part du volume de chaque colonne, taille moyenne et maximale d'une valeur,
|
|
5
|
+
// colonnes lourdes signalées. Le type deviné ne sert qu'à estimer la place que
|
|
6
|
+
// la table prendra dans la base (PostgreSQL), index compris.
|
|
7
|
+
// Tout est calculé sur le poste, en un passage, sans rien garder en mémoire
|
|
8
|
+
// d'autre que des compteurs.
|
|
9
|
+
'use strict';
|
|
10
|
+
|
|
11
|
+
const GEOM_TYPES = { 1: 'Point', 2: 'LineString', 3: 'Polygon', 4: 'MultiPoint', 5: 'MultiLineString', 6: 'MultiPolygon', 7: 'GeometryCollection' };
|
|
12
|
+
|
|
13
|
+
/** En-tête EWKB (hexadécimal) : { type, srid } ou null */
|
|
14
|
+
function ewkbHeader(hex) {
|
|
15
|
+
if (hex.length < 10 || hex.length % 2 || !/^0[01]/.test(hex)) return null;
|
|
16
|
+
const little = hex[1] === '1';
|
|
17
|
+
const u32 = (at) => {
|
|
18
|
+
const b = hex.slice(at, at + 8);
|
|
19
|
+
if (b.length < 8 || !/^[0-9A-Fa-f]{8}$/.test(b)) return null;
|
|
20
|
+
const bytes = b.match(/../g).map((x) => parseInt(x, 16));
|
|
21
|
+
const v = little ? bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24) : (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3];
|
|
22
|
+
return v >>> 0;
|
|
23
|
+
};
|
|
24
|
+
const t = u32(2);
|
|
25
|
+
if (t === null) return null;
|
|
26
|
+
const base = t & 0xffff;
|
|
27
|
+
const type = GEOM_TYPES[base % 1000];
|
|
28
|
+
if (!type) return null;
|
|
29
|
+
const hasSrid = (t & 0x20000000) !== 0;
|
|
30
|
+
const dims = 2 + ((t & 0x80000000) !== 0 ? 1 : 0) + ((t & 0x40000000) !== 0 ? 1 : 0);
|
|
31
|
+
const srid = hasSrid ? u32(10) : null;
|
|
32
|
+
return { type, srid, dims };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const RE = {
|
|
36
|
+
int: /^-?(0|[1-9]\d{0,17})$/,
|
|
37
|
+
numeric: /^-?((0|[1-9]\d{0,39})(\.\d{0,40})?|\.\d{1,40})([eE][-+]?\d{1,3})?$/,
|
|
38
|
+
bool: /^(t|f|true|false)$/i,
|
|
39
|
+
uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
|
|
40
|
+
date: /^\d{4}-\d{2}-\d{2}$/,
|
|
41
|
+
timestamp: /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(:\d{2}(\.\d+)?)?([+-]\d{2}(:?\d{2})?|Z)?$/,
|
|
42
|
+
hex: /^[0-9A-Fa-f]+$/,
|
|
43
|
+
};
|
|
44
|
+
// Du plus précis au plus général ; une valeur qui ne correspond pas élimine le type
|
|
45
|
+
const ORDER = ['bool', 'int', 'numeric', 'uuid', 'date', 'timestamp', 'binary', 'geometry', 'json', 'text'];
|
|
46
|
+
/** Une valeur au-delà de cette taille rend la colonne « lourde », quelle que soit sa part */
|
|
47
|
+
const HEAVY_VALUE = 32 * 1024;
|
|
48
|
+
/** En dessous, une table est trop petite pour qu'une colonne y soit « lourde » par sa seule part */
|
|
49
|
+
const HEAVY_TABLE = 1024 * 1024;
|
|
50
|
+
|
|
51
|
+
class ColumnStats {
|
|
52
|
+
constructor(name) {
|
|
53
|
+
this.name = name;
|
|
54
|
+
this.values = 0;
|
|
55
|
+
this.nulls = 0;
|
|
56
|
+
this.bytes = 0; // octets du contenu en clair (COPY)
|
|
57
|
+
this.maxLen = 0;
|
|
58
|
+
this.sample = null;
|
|
59
|
+
this.types = new Set(ORDER);
|
|
60
|
+
this.intBig = false;
|
|
61
|
+
this.geom = null; // { type, srid, dims, points }
|
|
62
|
+
this.geomPoints = 0;
|
|
63
|
+
this.geomCount = 0;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
add(v) {
|
|
67
|
+
this.values++;
|
|
68
|
+
if (v === null) {
|
|
69
|
+
this.nulls++;
|
|
70
|
+
this.bytes += 2;
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const len = v.length;
|
|
74
|
+
this.bytes += len + 1;
|
|
75
|
+
if (len > this.maxLen) this.maxLen = len;
|
|
76
|
+
if (this.sample === null && len) this.sample = v;
|
|
77
|
+
const t = this.types;
|
|
78
|
+
if (t.size > 1) {
|
|
79
|
+
if (t.has('bool') && !RE.bool.test(v)) t.delete('bool');
|
|
80
|
+
if (t.has('int')) {
|
|
81
|
+
if (!RE.int.test(v)) t.delete('int');
|
|
82
|
+
else if (Math.abs(Number(v)) > 2147483647) this.intBig = true;
|
|
83
|
+
}
|
|
84
|
+
if (t.has('numeric') && !RE.numeric.test(v)) t.delete('numeric');
|
|
85
|
+
if (t.has('uuid') && !RE.uuid.test(v)) t.delete('uuid');
|
|
86
|
+
if (t.has('date') && !RE.date.test(v)) t.delete('date');
|
|
87
|
+
if (t.has('timestamp') && !RE.timestamp.test(v)) t.delete('timestamp');
|
|
88
|
+
if (t.has('json') && !/^\s*[[{]/.test(v)) t.delete('json');
|
|
89
|
+
// bytea en hexadécimal (\x…) : un binaire (image, vidéo, PDF…)
|
|
90
|
+
if (t.has('binary') && !(v.startsWith('\\x') && (len - 2) % 2 === 0 && RE.hex.test(v.slice(2)))) t.delete('binary');
|
|
91
|
+
if (t.has('geometry')) {
|
|
92
|
+
const h = len >= 18 && len < 64 * 1024 * 1024 && RE.hex.test(v) ? ewkbHeader(v) : null;
|
|
93
|
+
if (!h) t.delete('geometry');
|
|
94
|
+
else {
|
|
95
|
+
if (!this.geom) this.geom = { type: h.type, srid: h.srid, dims: h.dims };
|
|
96
|
+
else if (this.geom.type !== h.type) this.geom.type = 'Geometry';
|
|
97
|
+
// Points : (octets - en-têtes) / (8 octets par coordonnée × dimensions), en gros
|
|
98
|
+
this.geomPoints += Math.max(1, Math.round((len / 2 - 9) / (8 * h.dims)));
|
|
99
|
+
this.geomCount++;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Type deviné : le plus précis qui a résisté à toutes les valeurs (vide : inconnu) */
|
|
106
|
+
type() {
|
|
107
|
+
if (this.values === this.nulls) return 'unknown';
|
|
108
|
+
for (const k of ORDER) if (this.types.has(k)) return k === 'int' && this.intBig ? 'bigint' : k;
|
|
109
|
+
return 'text';
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Octets estimés dans la base pour ce contenu (sans en-têtes de ligne) */
|
|
113
|
+
dbBytes() {
|
|
114
|
+
const filled = this.values - this.nulls;
|
|
115
|
+
const avg = filled ? (this.bytes - this.nulls * 2) / filled - 1 : 0;
|
|
116
|
+
const per = {
|
|
117
|
+
bool: 1,
|
|
118
|
+
int: 4,
|
|
119
|
+
bigint: 8,
|
|
120
|
+
numeric: Math.max(5, Math.ceil(avg / 2) + 3),
|
|
121
|
+
uuid: 16,
|
|
122
|
+
date: 4,
|
|
123
|
+
timestamp: 8,
|
|
124
|
+
geometry: avg / 2 + 8,
|
|
125
|
+
binary: (avg - 2) / 2 + 4,
|
|
126
|
+
json: avg + 4,
|
|
127
|
+
text: avg + (avg > 126 ? 4 : 1),
|
|
128
|
+
unknown: 0,
|
|
129
|
+
}[this.type()];
|
|
130
|
+
return Math.round(filled * per);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
view(totalBytes) {
|
|
134
|
+
const type = this.type();
|
|
135
|
+
const filled = this.values - this.nulls;
|
|
136
|
+
// Taille d'une valeur telle qu'elle sera stockée (un hexadécimal compte pour moitié)
|
|
137
|
+
const half = type === 'geometry' || type === 'binary';
|
|
138
|
+
const prefix = type === 'binary' ? 2 : 0; // « \x » d'un bytea
|
|
139
|
+
const avgValue = filled ? ((this.bytes - this.nulls * 2) / filled - 1 - prefix) / (half ? 2 : 1) : 0;
|
|
140
|
+
const maxValue = (this.maxLen - prefix) / (half ? 2 : 1);
|
|
141
|
+
return {
|
|
142
|
+
name: this.name,
|
|
143
|
+
type,
|
|
144
|
+
nulls: this.values ? this.nulls / this.values : 0,
|
|
145
|
+
plain_bytes: this.bytes,
|
|
146
|
+
share: totalBytes ? this.bytes / totalBytes : 0,
|
|
147
|
+
avg_value_bytes: Math.round(avgValue),
|
|
148
|
+
max_value_bytes: Math.round(maxValue),
|
|
149
|
+
// Lourde : une valeur au-delà de 32 Kio, ou plus de la moitié d'une table qui pèse (1 Mio) ; une petite table n'a pas de colonne lourde
|
|
150
|
+
heavy: maxValue >= HEAVY_VALUE || ((totalBytes ? this.bytes / totalBytes : 0) >= 0.5 && this.bytes >= HEAVY_TABLE),
|
|
151
|
+
max_length: this.maxLen,
|
|
152
|
+
sample: this.sample === null ? null : this.sample.length > 60 ? `${this.sample.slice(0, 57)}…` : this.sample,
|
|
153
|
+
db_bytes: this.dbBytes(),
|
|
154
|
+
...(type === 'geometry' && this.geom ? { geometry: { ...this.geom, avg_points: Math.round(this.geomPoints / Math.max(1, this.geomCount)) } } : {}),
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Statistiques d'une table, alimentées ligne par ligne */
|
|
160
|
+
class TableStats {
|
|
161
|
+
constructor(target, columns) {
|
|
162
|
+
this.target = target;
|
|
163
|
+
this.columns = columns;
|
|
164
|
+
this.rows = 0;
|
|
165
|
+
this.cols = null;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
add(values) {
|
|
169
|
+
if (!this.cols) this.cols = values.map((_, i) => new ColumnStats(this.columns ? this.columns[i] : `#${i + 1}`));
|
|
170
|
+
this.rows++;
|
|
171
|
+
for (let i = 0; i < values.length; i++) this.cols[i] && this.cols[i].add(values[i]);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
view() {
|
|
175
|
+
const cols = this.cols || [];
|
|
176
|
+
const plain = cols.reduce((n, c) => n + c.bytes, 0);
|
|
177
|
+
const columns = cols.map((c) => c.view(plain));
|
|
178
|
+
// Ligne : en-tête (24 octets) + alignement ; index : clé primaire supposée (≈ 20 o/ligne), index spatial (≈ 60 o/ligne)
|
|
179
|
+
const data = columns.reduce((n, c) => n + c.db_bytes, 0) + this.rows * 28;
|
|
180
|
+
const indexes = this.rows * 20 + columns.filter((c) => c.type === 'geometry').length * this.rows * 60;
|
|
181
|
+
const heavy = columns.filter((c) => c.heavy).sort((a, b) => b.share - a.share);
|
|
182
|
+
return {
|
|
183
|
+
target: this.target,
|
|
184
|
+
named_columns: Boolean(this.columns),
|
|
185
|
+
rows: this.rows,
|
|
186
|
+
plain_bytes: plain,
|
|
187
|
+
db_bytes: Math.round((data + indexes) * 1.1),
|
|
188
|
+
columns,
|
|
189
|
+
heavy: heavy.map((c) => ({ column: c.name, share: c.share, type: c.type, max_value_bytes: c.max_value_bytes })),
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Sélection de colonnes (--fields, --exclude) : « col » s'applique à toute table qui l'a,
|
|
196
|
+
* « table.col » ou « schéma.table.col » à une seule. Renvoie pick(target, columns) ->
|
|
197
|
+
* indices gardés (null : toutes), et check() qui signale ce qui n'a rien désigné.
|
|
198
|
+
*/
|
|
199
|
+
function columnPicker({ fields, exclude } = {}) {
|
|
200
|
+
const parse = (s) =>
|
|
201
|
+
String(s || '')
|
|
202
|
+
.split(',')
|
|
203
|
+
.map((x) => x.trim())
|
|
204
|
+
.filter(Boolean);
|
|
205
|
+
const keep = parse(fields);
|
|
206
|
+
const drop = parse(exclude);
|
|
207
|
+
if (!keep.length && !drop.length) return { active: false, pick: () => null, check: () => [] };
|
|
208
|
+
if (keep.length && drop.length) throw new Error('--fields and --exclude cannot be combined: keep a list, or remove one');
|
|
209
|
+
const used = new Set();
|
|
210
|
+
const matches = (spec, target, col) => {
|
|
211
|
+
const parts = spec.split('.');
|
|
212
|
+
if (parts.length === 1) return parts[0] === col;
|
|
213
|
+
const [t, c] = [parts.slice(0, -1).join('.'), parts[parts.length - 1]];
|
|
214
|
+
return c === col && (target === t || target.endsWith(`.${t}`));
|
|
215
|
+
};
|
|
216
|
+
return {
|
|
217
|
+
active: true,
|
|
218
|
+
pick(target, columns) {
|
|
219
|
+
if (!columns) throw new Error(`${target}: the file does not name its columns (INSERT without a column list): --fields and --exclude need names`);
|
|
220
|
+
const idx = [];
|
|
221
|
+
columns.forEach((col, i) => {
|
|
222
|
+
const hitKeep = keep.find((s) => matches(s, target, col));
|
|
223
|
+
const hitDrop = drop.find((s) => matches(s, target, col));
|
|
224
|
+
if (hitKeep) used.add(hitKeep);
|
|
225
|
+
if (hitDrop) used.add(hitDrop);
|
|
226
|
+
if (keep.length ? hitKeep : !hitDrop) idx.push(i);
|
|
227
|
+
});
|
|
228
|
+
if (!idx.length) throw new Error(`${target}: no column left after --fields/--exclude`);
|
|
229
|
+
return idx.length === columns.length ? null : idx;
|
|
230
|
+
},
|
|
231
|
+
/** Ce qui n'a désigné aucune colonne (faute de frappe) */
|
|
232
|
+
check: () => [...keep, ...drop].filter((s) => !used.has(s)),
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
module.exports = { ColumnStats, TableStats, columnPicker, ewkbHeader };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// Affichage d'une inspection (poad seed inspect, et résumé de poad seed push)
|
|
2
|
+
'use strict';
|
|
3
|
+
const fmt = (n) => (n >= 1024 ** 3 ? `${(n / 1024 ** 3).toFixed(2)} GB` : n >= 1024 ** 2 ? `${(n / 1024 ** 2).toFixed(1)} MB` : n >= 1024 ? `${Math.round(n / 1024)} KB` : `${n} B`);
|
|
4
|
+
const pct = (x) => (x >= 0.995 ? '100 %' : x < 0.005 && x > 0 ? '<1 %' : `${Math.round(x * 100)} %`);
|
|
5
|
+
const pad = (s, n) => {
|
|
6
|
+
const t = String(s);
|
|
7
|
+
return t.length >= n ? t : t + ' '.repeat(n - t.length);
|
|
8
|
+
};
|
|
9
|
+
const lpad = (s, n) => {
|
|
10
|
+
const t = String(s);
|
|
11
|
+
return t.length >= n ? t : ' '.repeat(n - t.length) + t;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
/** Lignes d'une table inspectée (sans couleur si chalk absent) */
|
|
15
|
+
function tableReport(st, chalk, { dropped = [] } = {}) {
|
|
16
|
+
const c = chalk || { bold: (x) => x, grey: (x) => x, yellowBright: (x) => x, cyanBright: (x) => x };
|
|
17
|
+
const out = [];
|
|
18
|
+
out.push(`${c.bold(st.target)} ${st.rows.toLocaleString('en-US')} rows ${fmt(st.plain_bytes)} as text ≈ ${fmt(st.db_bytes)} in the database`);
|
|
19
|
+
if (dropped.length) out.push(c.grey(` left out: ${dropped.join(', ')}`));
|
|
20
|
+
const w = Math.max(6, ...st.columns.map((x) => x.name.length)) + 2;
|
|
21
|
+
out.push(c.grey(` ${pad('column', w)}${pad('type', 11)}${lpad('empty', 7)}${lpad('volume', 9)}${lpad('avg value', 12)}${lpad('max value', 12)} sample`));
|
|
22
|
+
for (const col of st.columns) {
|
|
23
|
+
const extra = col.geometry ? ` ${col.geometry.type}${col.geometry.srid ? `, SRID ${col.geometry.srid}` : ''}, ~${col.geometry.avg_points} points` : '';
|
|
24
|
+
const sample = col.type === 'binary' || col.type === 'geometry' ? extra.trim() : col.sample === null ? '' : JSON.stringify(col.sample);
|
|
25
|
+
const line = ` ${pad(col.name, w)}${pad(col.type, 11)}${lpad(pct(col.nulls), 7)}${lpad(pct(col.share), 9)}${lpad(fmt(col.avg_value_bytes), 12)}${lpad(fmt(col.max_value_bytes), 12)} ${sample}`;
|
|
26
|
+
out.push(col.heavy ? c.yellowBright(line) : line);
|
|
27
|
+
}
|
|
28
|
+
if (st.heavy.length) {
|
|
29
|
+
const names = st.heavy.map((h) => h.column);
|
|
30
|
+
out.push(c.yellowBright(` ⚠ heavy: ${st.heavy.map((h) => `${h.column} (${pct(h.share)} of the volume, up to ${fmt(h.max_value_bytes)} per value)`).join(', ')}`));
|
|
31
|
+
out.push(c.grey(` leave it out: --exclude ${names.join(',')} or keep only what you need: --fields <a,b,…>`));
|
|
32
|
+
}
|
|
33
|
+
if (!st.named_columns) out.push(c.grey(' The file does not name its columns (INSERT without a column list): --fields and --exclude are not available.'));
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
module.exports = { tableReport, fmt, pct };
|
package/utils/seed/run.js
CHANGED
|
@@ -14,29 +14,45 @@ const A = require('./apply');
|
|
|
14
14
|
const fmt = (n) => (n >= 1024 ** 3 ? `${(n / 1024 ** 3).toFixed(2)} GB` : n >= 1024 ** 2 ? `${(n / 1024 ** 2).toFixed(1)} MB` : `${Math.max(1, Math.round(n / 1024))} KB`);
|
|
15
15
|
|
|
16
16
|
/**
|
|
17
|
-
* Fichier -> une entrée par table : { target, columns, rows, sha256, plainBytes, file (gzip) }.
|
|
17
|
+
* Fichier -> une entrée par table : { target, columns, rows, sha256, plainBytes, file (gzip), stats }.
|
|
18
18
|
* format : sql | csv (sinon d'après l'extension) ; table : obligatoire en CSV (sinon le nom du fichier).
|
|
19
|
+
* fields / exclude : colonnes gardées ou écartées (voir inspect.columnPicker).
|
|
20
|
+
* write: false : inspection seule (rien n'est écrit) ; les statistiques sont toujours calculées.
|
|
19
21
|
*/
|
|
20
|
-
async function convertFile(file, { format, table, dir, onProgress } = {}) {
|
|
22
|
+
async function convertFile(file, { format, table, dir, onProgress, fields, exclude, write = true } = {}) {
|
|
23
|
+
const { TableStats, columnPicker } = require('./inspect');
|
|
24
|
+
const { copyEscape } = require('./convert');
|
|
21
25
|
const ext = path.extname(file).toLowerCase();
|
|
22
26
|
const kind = format || (ext === '.csv' || ext === '.tsv' ? 'csv' : ext === '.sql' ? 'sql' : null);
|
|
23
27
|
if (!kind) throw api.usageError(`${path.basename(file)}: unknown format (.sql or .csv), or pass --format sql|csv`);
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
28
|
+
let picker;
|
|
29
|
+
try {
|
|
30
|
+
picker = columnPicker({ fields, exclude });
|
|
31
|
+
} catch (e) {
|
|
32
|
+
throw api.usageError(e.message);
|
|
33
|
+
}
|
|
34
|
+
// Par table : colonnes d'origine, indices gardés, colonnes gardées, statistiques, fichier
|
|
35
|
+
const tablesBy = new Map();
|
|
36
|
+
const onRow = (target, cols, values) => {
|
|
37
|
+
let t = tablesBy.get(target);
|
|
38
|
+
if (!t) {
|
|
39
|
+
let keep = null;
|
|
40
|
+
try {
|
|
41
|
+
keep = picker.pick(target, cols);
|
|
42
|
+
} catch (e) {
|
|
43
|
+
throw api.usageError(e.message);
|
|
36
44
|
}
|
|
45
|
+
const kept = cols && keep ? keep.map((i) => cols[i]) : cols;
|
|
46
|
+
t = { cols, keep, kept, stats: new TableStats(target, kept), sink: write ? new TableSink(path.join(dir, `${tablesBy.size}.copy.gz`)) : null };
|
|
47
|
+
tablesBy.set(target, t);
|
|
48
|
+
} else if (JSON.stringify(t.cols) !== JSON.stringify(cols)) {
|
|
49
|
+
throw api.usageError(`${target}: rows with different column lists in the same file (split the file, or give every INSERT the same columns)`);
|
|
37
50
|
}
|
|
38
|
-
|
|
51
|
+
const v = t.keep ? t.keep.map((i) => values[i]) : values;
|
|
52
|
+
t.stats.add(v);
|
|
53
|
+
if (t.sink) t.sink.row(v.map(copyEscape).join('\t'));
|
|
39
54
|
};
|
|
55
|
+
const sinks = { values: () => [...tablesBy.values()].map((t) => t.sink).filter(Boolean) };
|
|
40
56
|
let source;
|
|
41
57
|
if (kind === 'csv') {
|
|
42
58
|
const target = table ? parseTarget(table) : parseTarget(path.basename(file, path.extname(file)));
|
|
@@ -53,10 +69,12 @@ async function convertFile(file, { format, table, dir, onProgress } = {}) {
|
|
|
53
69
|
onProgress && onProgress(read, total);
|
|
54
70
|
}
|
|
55
71
|
source.end();
|
|
72
|
+
const unused = picker.check();
|
|
73
|
+
if (unused.length) throw api.usageError(`--fields/--exclude: no column matches ${unused.join(', ')}`);
|
|
56
74
|
const tables = [];
|
|
57
|
-
for (const [target,
|
|
58
|
-
const r = await
|
|
59
|
-
tables.push({ target, columns:
|
|
75
|
+
for (const [target, t] of tablesBy) {
|
|
76
|
+
const r = t.sink ? await t.sink.close() : null;
|
|
77
|
+
tables.push({ target, columns: t.kept, rows: t.stats.rows, sha256: r && r.sha256, plainBytes: r && r.plainBytes, file: r && r.file, stats: t.stats.view(), dropped: t.cols && t.keep ? t.cols.filter((_, i) => !t.keep.includes(i)) : [] });
|
|
60
78
|
}
|
|
61
79
|
// Une seule table en SQL et --table donné : il la renomme
|
|
62
80
|
if (kind === 'sql' && table) {
|
|
@@ -64,6 +82,7 @@ async function convertFile(file, { format, table, dir, onProgress } = {}) {
|
|
|
64
82
|
if (!t) throw api.usageError(`--table: "${table}" is not schema.table`);
|
|
65
83
|
if (tables.length !== 1) throw api.usageError(`--table renames a single table; the file has ${tables.length}: ${tables.map((x) => x.target).join(', ')}`);
|
|
66
84
|
tables[0].target = t;
|
|
85
|
+
tables[0].stats.target = t;
|
|
67
86
|
}
|
|
68
87
|
return { tables, skipped: source.skipped || {}, mutations: source.mutations || 0 };
|
|
69
88
|
}
|
|
@@ -80,7 +99,9 @@ async function pushTable(id, t, { mode, source, onProgress }) {
|
|
|
80
99
|
body: { target: t.target, sha256: t.sha256, plain_bytes: t.plainBytes, stored_bytes: stored },
|
|
81
100
|
what: `seed ${t.target}`,
|
|
82
101
|
});
|
|
83
|
-
|
|
102
|
+
// Ce que l'inspection a mesuré part avec le seed (jamais de valeur des données : pas d'exemple)
|
|
103
|
+
const stats = t.stats ? t.stats.columns.map(({ name, type, share, avg_value_bytes, max_value_bytes, nulls, heavy }) => ({ name, type, share, avg_value_bytes, max_value_bytes, nulls, heavy })) : undefined;
|
|
104
|
+
let commit = { target: t.target, sha256: t.sha256, mode, rows: t.rows, columns: t.columns, source, db_bytes: t.stats ? t.stats.db_bytes : undefined, stats, dropped: t.dropped };
|
|
84
105
|
if (!prep.exists) {
|
|
85
106
|
const written = await encryptFile(t.file, enc, key(prep.key));
|
|
86
107
|
if (written !== stored) throw new api.CloudError(`internal: encrypted size ${written} differs from ${stored}`);
|
package/project/seed/mode.js
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
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
|
-
});
|