poad 2.53.0 → 2.54.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/project/cli.js +14 -7
- package/project/ref/index.js +17 -0
- package/project/ref/inspect.js +45 -0
- package/project/ref/load.js +51 -0
- package/project/ref/ls.js +27 -0
- package/project/ref/push.js +111 -0
- package/project/ref/rm.js +14 -0
- package/project/seed/index.js +2 -18
- package/project/seed/inspect.js +2 -45
- package/project/seed/load.js +2 -50
- package/project/seed/ls.js +2 -27
- package/project/seed/push.js +2 -109
- package/project/seed/rm.js +2 -14
- package/test/seed.test.js +7 -0
- package/utils/seed/apply.js +16 -4
- package/utils/seed/inspect.js +4 -1
- package/utils/seed/run.js +2 -1
- package/project/seed/mode.js +0 -14
package/package.json
CHANGED
package/project/cli.js
CHANGED
|
@@ -23,14 +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
|
-
inspect: '
|
|
29
|
-
push: '
|
|
30
|
-
ls: '
|
|
31
|
-
load: '
|
|
32
|
-
|
|
33
|
-
rm: 'Remove a seed from poad.io (the table keeps its rows): seed rm <table> [--yes]',
|
|
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',
|
|
34
41
|
},
|
|
35
42
|
link: 'Link this project to a poad.io project: [cloud] project = "<id>" in poad/config.toml (no secret): link [<id>]',
|
|
36
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,51 @@
|
|
|
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
|
+
for (const w of r.warnings || []) out.log(chalk.yellowBright(` ⚠ ${w}`));
|
|
48
|
+
results.push({ target, ...r });
|
|
49
|
+
}
|
|
50
|
+
out.result({ project: id, local: true, tables: results });
|
|
51
|
+
});
|
|
@@ -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,111 @@
|
|
|
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') {
|
|
101
|
+
out.log(`${chalk.greenBright('✔')} ${s.target} loaded into ${branch}: ${s.written} rows written, ${s.deleted} removed (${(s.duration_ms / 1000).toFixed(1)} s)`);
|
|
102
|
+
for (const w of s.warnings || []) out.log(chalk.yellowBright(` ⚠ ${w}`));
|
|
103
|
+
}
|
|
104
|
+
else out.log(`${chalk.redBright('✖')} ${s.target}: ${s.error}`);
|
|
105
|
+
}
|
|
106
|
+
},
|
|
107
|
+
});
|
|
108
|
+
if (l.status === 'failed') out.log(chalk.grey(' Nothing was half-loaded: each table is all or nothing.'));
|
|
109
|
+
return l;
|
|
110
|
+
}
|
|
111
|
+
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,18 +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 inspect <file>')} What the file holds, column by column, and its weight: nothing is sent`);
|
|
8
|
-
console.log(` ${c('poad seed push <file>')} Convert a .sql (INSERT, COPY) or .csv file and send each table to poad.io`);
|
|
9
|
-
console.log(` ${c('poad seed ls')} Seeds of the project, their mode and what each environment has loaded`);
|
|
10
|
-
console.log(` ${c('poad seed load [table…]')} Load seeds into an environment (--env), or into the local engine (--local)`);
|
|
11
|
-
console.log(` ${c('poad seed mode <table> seed|reference')}`);
|
|
12
|
-
console.log(` ${c('poad seed rm <table>')} Remove a seed from the store (the table keeps its rows)`);
|
|
13
|
-
console.log(' ');
|
|
14
|
-
console.log(chalk.grey(' Data lives on poad.io (S3), outside git and outside the project volume, encrypted by poad.'));
|
|
15
|
-
console.log(chalk.grey(' seed: development data, never loaded into production unless --force; reference: loaded everywhere.'));
|
|
16
|
-
console.log(chalk.grey(' No local folder needed: --project <id> targets a project created in the console.'));
|
|
17
|
-
console.log(' ');
|
|
18
|
-
};
|
|
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/inspect.js
CHANGED
|
@@ -1,45 +1,2 @@
|
|
|
1
|
-
//
|
|
2
|
-
|
|
3
|
-
// lignes, volume, part de chaque colonne, taille des valeurs, colonnes lourdes, place
|
|
4
|
-
// estimée dans la base. Rien n'est envoyé ni écrit ; aucune connexion à poad.io.
|
|
5
|
-
module.exports = (args, raw) =>
|
|
6
|
-
require('../../utils/cloud/cli').run(raw, { values: ['table', 'format', 'fields', 'exclude'] }, async ({ opts, positionals, out }) => {
|
|
7
|
-
const fs = require('fs');
|
|
8
|
-
const path = require('path');
|
|
9
|
-
const api = require('../../utils/cloud/api');
|
|
10
|
-
const S = require('../../utils/seed/run');
|
|
11
|
-
const { tableReport, fmt } = require('../../utils/seed/report');
|
|
12
|
-
const { chalk } = out;
|
|
13
|
-
const file = positionals[0];
|
|
14
|
-
if (!file) throw api.usageError('poad seed inspect <file.sql|file.csv> [--fields a,b | --exclude c]');
|
|
15
|
-
if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw api.usageError(`${file}: no such file`);
|
|
16
|
-
const t0 = Date.now();
|
|
17
|
-
let last = 0;
|
|
18
|
-
const conv = await S.convertFile(file, {
|
|
19
|
-
format: opts.format,
|
|
20
|
-
table: opts.table,
|
|
21
|
-
fields: opts.fields,
|
|
22
|
-
exclude: opts.exclude,
|
|
23
|
-
write: false,
|
|
24
|
-
onProgress: (read, total) => {
|
|
25
|
-
if (!out.json && process.stderr.isTTY && Date.now() - last > 250) {
|
|
26
|
-
last = Date.now();
|
|
27
|
-
process.stderr.write(`\r ${chalk.grey('reading')} ${path.basename(file)} ${Math.floor((read / total) * 100)}% `);
|
|
28
|
-
}
|
|
29
|
-
},
|
|
30
|
-
});
|
|
31
|
-
if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
|
|
32
|
-
const tables = conv.tables.map((t) => ({ ...t.stats, dropped: t.dropped }));
|
|
33
|
-
out.result({ file: path.basename(file), tables, skipped: conv.skipped, mutations: conv.mutations });
|
|
34
|
-
if (out.json) return;
|
|
35
|
-
if (!tables.length) return out.log(chalk.yellowBright(` ${path.basename(file)}: no data found (INSERT … VALUES, COPY … FROM stdin, or CSV rows).`));
|
|
36
|
-
out.log(chalk.grey(` ${path.basename(file)} read in ${((Date.now() - t0) / 1000).toFixed(1)} s, nothing sent`));
|
|
37
|
-
for (const t of tables) {
|
|
38
|
-
out.log('');
|
|
39
|
-
for (const l of tableReport(t, chalk, { dropped: t.dropped })) out.log(` ${l}`);
|
|
40
|
-
}
|
|
41
|
-
const total = tables.reduce((n, t) => n + t.db_bytes, 0);
|
|
42
|
-
out.log('');
|
|
43
|
-
out.log(` ${chalk.bold('Total')} ≈ ${fmt(total)} in the database once loaded (estimate: rows, values and indexes)`);
|
|
44
|
-
out.log(chalk.grey(` Send it: poad seed push ${path.basename(file)}${opts.fields ? ` --fields ${opts.fields}` : opts.exclude ? ` --exclude ${opts.exclude}` : ''}`));
|
|
45
|
-
});
|
|
1
|
+
// Ancien nom de poad ref (le magasin ne garde que des tables de référence)
|
|
2
|
+
module.exports = require('../ref/inspect');
|
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,109 +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', 'fields', 'exclude'], flags: ['load', 'force', 'yes'] }, async ({ opts, positionals, out }) => {
|
|
8
|
-
const fs = require('fs');
|
|
9
|
-
const path = require('path');
|
|
10
|
-
const api = require('../../utils/cloud/api');
|
|
11
|
-
const cli = require('../../utils/cloud/cli');
|
|
12
|
-
const S = require('../../utils/seed/run');
|
|
13
|
-
const { chalk } = out;
|
|
14
|
-
const file = positionals[0];
|
|
15
|
-
if (!file) throw api.usageError('poad seed push <file.sql|file.csv> [--table schema.table] [--mode seed|reference]');
|
|
16
|
-
if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw api.usageError(`${file}: no such file`);
|
|
17
|
-
const mode = opts.mode || 'seed';
|
|
18
|
-
if (!['seed', 'reference'].includes(mode)) throw api.usageError('--mode is seed or reference');
|
|
19
|
-
if (opts.format && !['sql', 'csv'].includes(opts.format)) throw api.usageError('--format is sql or csv');
|
|
20
|
-
const { id, root } = cli.targetProject(opts);
|
|
21
|
-
api.requireToken();
|
|
22
|
-
const dir = S.tmpDir();
|
|
23
|
-
try {
|
|
24
|
-
// 1. Conversion
|
|
25
|
-
const t0 = Date.now();
|
|
26
|
-
let last = 0;
|
|
27
|
-
const conv = await S.convertFile(file, {
|
|
28
|
-
format: opts.format,
|
|
29
|
-
table: opts.table,
|
|
30
|
-
fields: opts.fields,
|
|
31
|
-
exclude: opts.exclude,
|
|
32
|
-
dir,
|
|
33
|
-
onProgress: (read, total) => {
|
|
34
|
-
if (!out.json && process.stderr.isTTY && Date.now() - last > 250) {
|
|
35
|
-
last = Date.now();
|
|
36
|
-
process.stderr.write(`\r ${chalk.grey('reading')} ${path.basename(file)} ${Math.floor((read / total) * 100)}% `);
|
|
37
|
-
}
|
|
38
|
-
},
|
|
39
|
-
});
|
|
40
|
-
if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
|
|
41
|
-
if (!conv.tables.length) throw new api.CloudError(`${path.basename(file)}: no data found (INSERT … VALUES, COPY … FROM stdin, or CSV rows)`, { code: 'seed_empty' });
|
|
42
|
-
out.log(`${chalk.greenBright('✔')} ${path.basename(file)} read in ${((Date.now() - t0) / 1000).toFixed(1)} s: ${conv.tables.map((t) => `${t.target} (${t.rows} rows, ≈ ${S.fmt(t.stats.db_bytes)} in the database)`).join(', ')}`);
|
|
43
|
-
for (const t of conv.tables) {
|
|
44
|
-
if (t.dropped.length) out.log(chalk.grey(` ${t.target}: left out ${t.dropped.join(', ')}`));
|
|
45
|
-
if (t.stats.heavy.length) out.log(chalk.yellowBright(` ${t.target}: heavy column(s) ${t.stats.heavy.map((h) => `${h.column} (${Math.round(h.share * 100)} %)`).join(', ')}; "poad seed inspect ${path.basename(file)}" shows the detail, --exclude leaves them out`));
|
|
46
|
-
}
|
|
47
|
-
const skipped = Object.entries(conv.skipped).filter(([w]) => !['SET', 'BEGIN', 'COMMIT', 'END', 'SELECT'].includes(w));
|
|
48
|
-
if (skipped.length) out.log(chalk.grey(` Ignored, not data: ${skipped.map(([w, n]) => `${n} ${w}`).join(', ')} (structure goes through migrations).`));
|
|
49
|
-
if (conv.mutations) out.log(chalk.yellowBright(` ${conv.mutations} UPDATE/DELETE statement(s) ignored: a seed only carries rows; apply them as a migration if they matter.`));
|
|
50
|
-
// 2. Envoi, table par table
|
|
51
|
-
const results = [];
|
|
52
|
-
for (const t of conv.tables) {
|
|
53
|
-
let shown = 0;
|
|
54
|
-
const r = await S.pushTable(id, t, {
|
|
55
|
-
mode,
|
|
56
|
-
source: path.basename(file),
|
|
57
|
-
onProgress: (done, total) => {
|
|
58
|
-
if (!out.json && process.stderr.isTTY && Date.now() - shown > 250) {
|
|
59
|
-
shown = Date.now();
|
|
60
|
-
process.stderr.write(`\r ${chalk.grey('sending')} ${t.target} ${S.fmt(done)} / ${S.fmt(total)} `);
|
|
61
|
-
}
|
|
62
|
-
},
|
|
63
|
-
});
|
|
64
|
-
if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
|
|
65
|
-
out.log(`${chalk.greenBright('✔')} ${chalk.bold(t.target)} ${r.uploaded ? `sent (${S.fmt(r.stored)} encrypted)` : 'unchanged content: nothing to send'}, mode ${mode}${r.replaced ? ', replaces the previous version' : ''}`);
|
|
66
|
-
results.push({ target: t.target, rows: t.rows, sha256: t.sha256, uploaded: r.uploaded, stored_bytes: r.stored, db_bytes: t.stats.db_bytes, mode });
|
|
67
|
-
}
|
|
68
|
-
// 3. Chargement facultatif
|
|
69
|
-
let load = null;
|
|
70
|
-
if (opts.load) {
|
|
71
|
-
const branches = require('../../utils/cloud/branches');
|
|
72
|
-
const env = await branches.resolve(id, { wanted: opts.env, root });
|
|
73
|
-
load = await startAndWait(id, env.branch, results.map((r) => r.target), opts, out);
|
|
74
|
-
} else out.log(chalk.grey(` Load it: poad seed load ${results.map((r) => r.target).join(' ')}${opts.env ? ` --env ${opts.env}` : ''} (or poad seed load --local)`));
|
|
75
|
-
out.result({ project: id, tables: results, load });
|
|
76
|
-
return load && load.status === 'failed' ? api.EXIT.failed : 0;
|
|
77
|
-
} finally {
|
|
78
|
-
fs.rmSync(dir, { recursive: true, force: true });
|
|
79
|
-
}
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
/** Lance un chargement hébergé et suit ses étapes */
|
|
83
|
-
async function startAndWait(id, branch, targets, opts, out) {
|
|
84
|
-
const api = require('../../utils/cloud/api');
|
|
85
|
-
const S = require('../../utils/seed/run');
|
|
86
|
-
const { chalk } = out;
|
|
87
|
-
let started;
|
|
88
|
-
try {
|
|
89
|
-
started = await api.call('POST', `v1/projects/${api.enc(id)}/seeds/load`, { body: { branch, targets, force: Boolean(opts.force), ...(opts.reference ? { only: 'reference' } : {}) }, what: 'seed load' });
|
|
90
|
-
} catch (e) {
|
|
91
|
-
if (e.code === 'seed_in_production') throw new api.CloudError(`${e.message}\n Development data into production: add --force if that is what you want.`, { code: e.code, exit: api.EXIT.confirm });
|
|
92
|
-
throw e;
|
|
93
|
-
}
|
|
94
|
-
out.log(chalk.grey(` Loading into ${branch} (${started.targets.length} table(s))…`));
|
|
95
|
-
const done = new Set();
|
|
96
|
-
const l = await S.waitLoad(id, started.load_id, {
|
|
97
|
-
onStep: (st) => {
|
|
98
|
-
for (const s of st.steps) {
|
|
99
|
-
if (done.has(s.target) || !['done', 'failed'].includes(s.status)) continue;
|
|
100
|
-
done.add(s.target);
|
|
101
|
-
if (s.status === 'done') out.log(`${chalk.greenBright('✔')} ${s.target} loaded into ${branch}: ${s.written} rows written, ${s.deleted} removed (${(s.duration_ms / 1000).toFixed(1)} s)`);
|
|
102
|
-
else out.log(`${chalk.redBright('✖')} ${s.target}: ${s.error}`);
|
|
103
|
-
}
|
|
104
|
-
},
|
|
105
|
-
});
|
|
106
|
-
if (l.status === 'failed') out.log(chalk.grey(' Nothing was half-loaded: each table is all or nothing.'));
|
|
107
|
-
return l;
|
|
108
|
-
}
|
|
109
|
-
module.exports.startAndWait = startAndWait;
|
|
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
|
@@ -166,3 +166,10 @@ test('choix des colonnes : --fields, --exclude, par table, erreurs lisibles', ()
|
|
|
166
166
|
assert.throws(() => columnPicker({ exclude: 'x' }).pick('public.t', null), /does not name its columns/);
|
|
167
167
|
assert.throws(() => columnPicker({ fields: 'zz' }).pick('public.t', ['a']), /no column left/);
|
|
168
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
|
@@ -51,11 +51,23 @@ function head(target, columns) {
|
|
|
51
51
|
].join('\n');
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
/**
|
|
55
|
-
|
|
54
|
+
/**
|
|
55
|
+
* Séquences (serial, identity) des colonnes ENTIÈRES : elles repartent après le plus grand identifiant.
|
|
56
|
+
* Une séquence attachée à une colonne d'un autre type (héritage d'un ancien schéma) est laissée telle
|
|
57
|
+
* quelle, avec un avertissement qui la nomme ; un échec de recalage n'annule pas le chargement.
|
|
58
|
+
*/
|
|
59
|
+
const SEQUENCES = ` for s in select a.attname::text as col, pg_get_serial_sequence(t::text, a.attname) as seq, a.atttypid in ('int2'::regtype, 'int4'::regtype, 'int8'::regtype) as whole
|
|
56
60
|
from pg_attribute a where a.attrelid = t and a.attnum > 0 and not a.attisdropped loop
|
|
57
|
-
if s.seq is
|
|
58
|
-
|
|
61
|
+
if s.seq is null then
|
|
62
|
+
continue;
|
|
63
|
+
elsif not s.whole then
|
|
64
|
+
raise warning 'poad-seed séquence % non recalée : colonne %.% non entière', s.seq, t, s.col;
|
|
65
|
+
else
|
|
66
|
+
begin
|
|
67
|
+
execute format('select setval(%L, coalesce((select max(%I) from %s), 0) + 1, false)', s.seq, s.col, t);
|
|
68
|
+
exception when others then
|
|
69
|
+
raise warning 'poad-seed séquence % non recalée : %', s.seq, sqlerrm;
|
|
70
|
+
end;
|
|
59
71
|
end if;
|
|
60
72
|
end loop;`;
|
|
61
73
|
|
package/utils/seed/inspect.js
CHANGED
|
@@ -45,6 +45,8 @@ const RE = {
|
|
|
45
45
|
const ORDER = ['bool', 'int', 'numeric', 'uuid', 'date', 'timestamp', 'binary', 'geometry', 'json', 'text'];
|
|
46
46
|
/** Une valeur au-delà de cette taille rend la colonne « lourde », quelle que soit sa part */
|
|
47
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;
|
|
48
50
|
|
|
49
51
|
class ColumnStats {
|
|
50
52
|
constructor(name) {
|
|
@@ -144,7 +146,8 @@ class ColumnStats {
|
|
|
144
146
|
share: totalBytes ? this.bytes / totalBytes : 0,
|
|
145
147
|
avg_value_bytes: Math.round(avgValue),
|
|
146
148
|
max_value_bytes: Math.round(maxValue),
|
|
147
|
-
|
|
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),
|
|
148
151
|
max_length: this.maxLen,
|
|
149
152
|
sample: this.sample === null ? null : this.sample.length > 60 ? `${this.sample.slice(0, 57)}…` : this.sample,
|
|
150
153
|
db_bytes: this.dbBytes(),
|
package/utils/seed/run.js
CHANGED
|
@@ -197,7 +197,8 @@ async function loadLocal(container, d, { database } = {}) {
|
|
|
197
197
|
const detail = lines.find((l) => /^DETAIL:/.test(l));
|
|
198
198
|
throw new api.CloudError(`${d.target}: ${e}${detail ? ` — ${detail.replace(/^DETAIL:\s+/, '')}` : ''}`, { code: 'seed_load_failed' });
|
|
199
199
|
}
|
|
200
|
-
|
|
200
|
+
const warnings = out.split('\n').filter((l) => /WARNING:.*poad-seed/.test(l)).map((l) => l.replace(/^.*WARNING:\s+([0-9A-Z]{5}:\s+)?poad-seed\s+/, ''));
|
|
201
|
+
return { ...(A.parseNotice(out) || { written: null, deleted: null }), warnings };
|
|
201
202
|
}
|
|
202
203
|
|
|
203
204
|
/** Dépendances entre tables de l'engine local (ordre de chargement) */
|
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
|
-
});
|