poad 2.50.0 → 2.52.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/global/start.js +13 -2
- package/package.json +1 -1
- package/project/cli.js +8 -0
- package/project/logs.js +2 -0
- package/project/seed/index.js +17 -0
- package/project/seed/load.js +50 -0
- package/project/seed/ls.js +27 -0
- package/project/seed/mode.js +14 -0
- package/project/seed/push.js +103 -0
- package/project/seed/rm.js +14 -0
- package/test/fronts.test.js +173 -0
- package/test/seed.test.js +133 -0
- package/utils/fronts.js +213 -0
- package/utils/logline.js +2 -2
- package/utils/report.js +12 -0
- package/utils/seed/apply.js +124 -0
- package/utils/seed/convert.js +673 -0
- package/utils/seed/pack.js +179 -0
- package/utils/seed/run.js +193 -0
- package/utils/tomlfile.js +3 -2
package/global/start.js
CHANGED
|
@@ -44,7 +44,7 @@ module.exports = async (args = {}) => {
|
|
|
44
44
|
require('../utils/console-services').write(root);
|
|
45
45
|
if (targets.length) await require('./run')({ services: targets.map((s) => s.id), quiet: true });
|
|
46
46
|
console.log(' ');
|
|
47
|
-
await require('../utils/report').printReport(root, require('../utils/config').loadConfig(root));
|
|
47
|
+
await require('../utils/report').printReport(root, require('../utils/config').loadConfig(root), { justStarted: true });
|
|
48
48
|
};
|
|
49
49
|
|
|
50
50
|
// --quiet : rien à dire ni à faire si le projet tourne déjà (bun start du front)
|
|
@@ -95,13 +95,21 @@ module.exports = async (args = {}) => {
|
|
|
95
95
|
await logs.ensureGelfPort(root, config);
|
|
96
96
|
if (mailpit) await mail.stopMailpit(docker, config);
|
|
97
97
|
const { reassignBusyPorts, describeMoves } = require('../utils/ports');
|
|
98
|
+
// Fronts (engine 0.46.0+) : un port par front, et une réserve pour ceux que la
|
|
99
|
+
// console crée pendant que le projet tourne (un port ne s'ajoute pas à un conteneur lancé)
|
|
100
|
+
const fronts = require('../utils/fronts');
|
|
101
|
+
const withFronts = fronts.supportsFronts(config);
|
|
102
|
+
if (withFronts) await fronts.ensureSpare(root, config);
|
|
98
103
|
const moved = await reassignBusyPorts(root, config, [
|
|
99
104
|
{ section: 'db', key: 'port', label: 'Database' },
|
|
100
105
|
{ section: 'web', key: 'port', label: 'API' },
|
|
101
106
|
...(mailpit ? [{ section: 'mail', key: 'port', label: 'Mailpit' }] : []),
|
|
102
107
|
{ section: 'logs', key: 'gelf_port', label: 'Logs collector', udp: true },
|
|
108
|
+
...(withFronts ? fronts.busyEntries(config) : []),
|
|
103
109
|
]);
|
|
110
|
+
if (withFronts) fronts.foldMoved(config);
|
|
104
111
|
describeMoves(moved).forEach((line) => console.log(chalk.yellowBright(` ${line}`)));
|
|
112
|
+
const frontPorts = withFronts ? fronts.bindings(config) : { exposed: {}, bindings: {} };
|
|
105
113
|
|
|
106
114
|
const progress = ora('Starting containers').start();
|
|
107
115
|
try {
|
|
@@ -144,14 +152,17 @@ module.exports = async (args = {}) => {
|
|
|
144
152
|
...gateway.engineEnv(config),
|
|
145
153
|
// Socle IA : [ai] de poad/config.toml (engine 0.30.0+ ; un engine plus ancien les ignore)
|
|
146
154
|
...aiSettings.env,
|
|
155
|
+
// Fronts : port de chacun, réserve, nom du projet (page « En construction »)
|
|
156
|
+
...(withFronts ? fronts.engineEnv(config) : []),
|
|
147
157
|
],
|
|
148
|
-
ExposedPorts: { '5432/tcp': {}, '8000/tcp': {}, ...gelf.exposed },
|
|
158
|
+
ExposedPorts: { '5432/tcp': {}, '8000/tcp': {}, ...gelf.exposed, ...frontPorts.exposed },
|
|
149
159
|
HostConfig: {
|
|
150
160
|
NetworkMode: net.NetworkMode,
|
|
151
161
|
PortBindings: {
|
|
152
162
|
'5432/tcp': [{ HostIp: require('../utils/ports').hostIp(config), HostPort: config.db.port.toString() }],
|
|
153
163
|
'8000/tcp': [{ HostIp: require('../utils/ports').hostIp(config), HostPort: config.web.port.toString() }],
|
|
154
164
|
...gelf.bindings,
|
|
165
|
+
...frontPorts.bindings,
|
|
155
166
|
},
|
|
156
167
|
// poad/migrations monté : la console y écrit les migrations qu'elle crée.
|
|
157
168
|
// poad/auth et poad/storage : manifestes versionnés des réglages d'auth et des buckets.
|
package/package.json
CHANGED
package/project/cli.js
CHANGED
|
@@ -23,6 +23,14 @@ module.exports = {
|
|
|
23
23
|
url: 'Connection string of the poad.io database (password masked, copied to the clipboard; --show-password to print it)',
|
|
24
24
|
pull: 'Schema of the poad.io database into a new local migration (pg_dump --schema-only, never overwrites)',
|
|
25
25
|
},
|
|
26
|
+
seed: {
|
|
27
|
+
description: 'Seeds and heavy reference tables on poad.io: stored outside git and the project volume (S3, encrypted by poad); no local folder needed with --project',
|
|
28
|
+
push: 'Convert a .sql (INSERT, COPY) or .csv file and send each table: seed push <file> [--table schema.table] [--mode seed|reference] [--load] [--env <name>]',
|
|
29
|
+
ls: 'Seeds of the project: mode, size, what each environment has loaded, store quota',
|
|
30
|
+
load: 'Load seeds into an environment (--env, else the git branch, else main) or into the local engine (--local): seed load [table…] [--reference] [--force]',
|
|
31
|
+
mode: 'seed (development data, never into production without --force) or reference (loaded everywhere): seed mode <table> seed|reference',
|
|
32
|
+
rm: 'Remove a seed from poad.io (the table keeps its rows): seed rm <table> [--yes]',
|
|
33
|
+
},
|
|
26
34
|
link: 'Link this project to a poad.io project: [cloud] project = "<id>" in poad/config.toml (no secret): link [<id>]',
|
|
27
35
|
unlink: 'Remove the link to poad.io from poad/config.toml (nothing changes on poad.io)',
|
|
28
36
|
env: {
|
package/project/logs.js
CHANGED
|
@@ -27,6 +27,8 @@
|
|
|
27
27
|
// poad logs data event=realtime_change les changements livrés (realtime_subscribed,
|
|
28
28
|
// realtime_unsubscribed, realtime_joined, realtime_left,
|
|
29
29
|
// realtime_closed, realtime_error, realtime_change_summary)
|
|
30
|
+
// poad logs app front=<id> un front dessiné dans poad (engine 0.46+) : le serveur du moteur
|
|
31
|
+
// et le navigateur (source=server|browser) ; page=<id> pour une page
|
|
30
32
|
// poad logs limit=500 nombre de lignes (100 par défaut)
|
|
31
33
|
// poad logs -f | --follow suivi en direct
|
|
32
34
|
// poad logs --json une ligne JSON par entrée (pour jq)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// poad seed : aide des commandes du magasin de seeds
|
|
2
|
+
module.exports = async () => {
|
|
3
|
+
const chalk = require('chalk-v2');
|
|
4
|
+
const c = (s) => chalk.cyanBright(s);
|
|
5
|
+
console.log(`${chalk.bold(' Usage :')}`);
|
|
6
|
+
console.log(' ');
|
|
7
|
+
console.log(` ${c('poad seed push <file>')} Convert a .sql (INSERT, COPY) or .csv file and send each table to poad.io`);
|
|
8
|
+
console.log(` ${c('poad seed ls')} Seeds of the project, their mode and what each environment has loaded`);
|
|
9
|
+
console.log(` ${c('poad seed load [table…]')} Load seeds into an environment (--env), or into the local engine (--local)`);
|
|
10
|
+
console.log(` ${c('poad seed mode <table> seed|reference')}`);
|
|
11
|
+
console.log(` ${c('poad seed rm <table>')} Remove a seed from the store (the table keeps its rows)`);
|
|
12
|
+
console.log(' ');
|
|
13
|
+
console.log(chalk.grey(' Data lives on poad.io (S3), outside git and outside the project volume, encrypted by poad.'));
|
|
14
|
+
console.log(chalk.grey(' seed: development data, never loaded into production unless --force; reference: loaded everywhere.'));
|
|
15
|
+
console.log(chalk.grey(' No local folder needed: --project <id> targets a project created in the console.'));
|
|
16
|
+
console.log(' ');
|
|
17
|
+
};
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// poad seed load [table…] [--env <branche>] [--reference] [--force] [--project <id>] [--json]
|
|
2
|
+
// poad seed load [table…] --local : dans l'engine Docker du projet de ce dossier
|
|
3
|
+
// Sans table : toutes celles du registre (--reference : seulement les références).
|
|
4
|
+
module.exports = (args, raw) =>
|
|
5
|
+
require('../../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['local', 'force', 'reference'] }, async ({ opts, positionals, out }) => {
|
|
6
|
+
const api = require('../../utils/cloud/api');
|
|
7
|
+
const cli = require('../../utils/cloud/cli');
|
|
8
|
+
const { parseTarget } = require('../../utils/seed/convert');
|
|
9
|
+
const S = require('../../utils/seed/run');
|
|
10
|
+
const { chalk } = out;
|
|
11
|
+
const targets = positionals.map((t) => {
|
|
12
|
+
const v = parseTarget(t);
|
|
13
|
+
if (!v) throw api.usageError(`"${t}" is not schema.table`);
|
|
14
|
+
return v;
|
|
15
|
+
});
|
|
16
|
+
const { id, root } = cli.targetProject(opts);
|
|
17
|
+
if (!opts.local) {
|
|
18
|
+
const branches = require('../../utils/cloud/branches');
|
|
19
|
+
const env = await branches.resolve(id, { wanted: opts.env, root });
|
|
20
|
+
const { startAndWait } = require('./push');
|
|
21
|
+
const l = await startAndWait(id, env.branch, targets.length ? targets : undefined, opts, out);
|
|
22
|
+
out.result({ project: id, load: l });
|
|
23
|
+
return l.status === 'failed' ? api.EXIT.failed : 0;
|
|
24
|
+
}
|
|
25
|
+
// Engine local : le projet de ce dossier, démarré
|
|
26
|
+
if (!root) throw api.usageError('--local: run it inside the poad project folder (poad start first).');
|
|
27
|
+
const { readConfig } = require('../../utils/config');
|
|
28
|
+
const { isDockerExist } = require('../../utils/docker');
|
|
29
|
+
const config = readConfig(root);
|
|
30
|
+
if (!(await isDockerExist(config.project_uuid))) throw api.usageError('The local project is not started: "poad start".');
|
|
31
|
+
const list = await api.call('GET', `v1/projects/${api.enc(id)}/seeds`, { what: 'seeds' });
|
|
32
|
+
let items = list.items;
|
|
33
|
+
if (targets.length) {
|
|
34
|
+
const missing = targets.filter((t) => !items.some((s) => s.target === t));
|
|
35
|
+
if (missing.length) throw api.usageError(`unknown seed: ${missing.join(', ')} ("poad seed ls")`);
|
|
36
|
+
items = items.filter((s) => targets.includes(s.target));
|
|
37
|
+
} else if (opts.reference) items = items.filter((s) => s.mode === 'reference');
|
|
38
|
+
if (!items.length) throw api.usageError('No seed to load ("poad seed ls").');
|
|
39
|
+
const A = require('../../utils/seed/apply');
|
|
40
|
+
const order = A.loadOrder(items.map((s) => s.target), await S.localEdges(config.project_uuid));
|
|
41
|
+
const results = [];
|
|
42
|
+
for (const target of order) {
|
|
43
|
+
const t0 = Date.now();
|
|
44
|
+
const d = await api.call('POST', `v1/projects/${api.enc(id)}/seeds/download`, { body: { target }, what: `seed ${target}` });
|
|
45
|
+
const r = await S.loadLocal(config.project_uuid, d);
|
|
46
|
+
out.log(`${chalk.greenBright('✔')} ${target} loaded locally: ${r.written} rows written, ${r.deleted} removed (${((Date.now() - t0) / 1000).toFixed(1)} s)`);
|
|
47
|
+
results.push({ target, ...r });
|
|
48
|
+
}
|
|
49
|
+
out.result({ project: id, local: true, tables: results });
|
|
50
|
+
});
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// poad seed ls [--project <id>] [--json] : registre des seeds, quota, ce que chaque environnement a chargé
|
|
2
|
+
module.exports = (args, raw) =>
|
|
3
|
+
require('../../utils/cloud/cli').run(raw, { values: ['project'] }, async ({ opts, out }) => {
|
|
4
|
+
const api = require('../../utils/cloud/api');
|
|
5
|
+
const cli = require('../../utils/cloud/cli');
|
|
6
|
+
const { fmt } = require('../../utils/seed/run');
|
|
7
|
+
const { chalk } = out;
|
|
8
|
+
const { id } = cli.targetProject(opts);
|
|
9
|
+
const r = await api.call('GET', `v1/projects/${api.enc(id)}/seeds`, { what: 'seeds' });
|
|
10
|
+
out.result({ project: id, ...r });
|
|
11
|
+
if (out.json) return;
|
|
12
|
+
if (!r.store) out.log(chalk.yellowBright(' The seed store is not configured on this poad.io instance.'));
|
|
13
|
+
out.log(` Store: ${fmt(r.quota.used)} used of ${fmt(r.quota.limit)} (account quota, outside the project volume)`);
|
|
14
|
+
if (!r.items.length) return out.log(chalk.grey(' No seed yet: poad seed push <file.sql|file.csv>'));
|
|
15
|
+
const envs = Object.keys(r.applied);
|
|
16
|
+
out.log('');
|
|
17
|
+
for (const s of r.items) {
|
|
18
|
+
const state = envs.map((e) => {
|
|
19
|
+
const a = r.applied[e][s.target];
|
|
20
|
+
return a ? (a.sha256 === s.sha256 ? chalk.greenBright(`${e} ✔`) : chalk.yellowBright(`${e} outdated`)) : null;
|
|
21
|
+
}).filter(Boolean);
|
|
22
|
+
out.log(` ${chalk.bold(s.target)} ${s.mode === 'reference' ? chalk.magentaBright('reference') : chalk.cyanBright('seed')} ${s.rows} rows ${fmt(s.stored_bytes)} ${chalk.grey(s.source || '')}`);
|
|
23
|
+
out.log(` ${state.length ? state.join(' ') : chalk.grey('not loaded anywhere yet')}`);
|
|
24
|
+
}
|
|
25
|
+
const last = r.loads[0];
|
|
26
|
+
if (last) out.log(chalk.grey(`\n Last load: ${last.branch}, ${last.status}${last.error ? ` (${last.error})` : ''}, ${new Date(last.started_at).toLocaleString()}`));
|
|
27
|
+
});
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// poad seed mode <table> seed|reference [--project <id>] [--json]
|
|
2
|
+
module.exports = (args, raw) =>
|
|
3
|
+
require('../../utils/cloud/cli').run(raw, { values: ['project'] }, async ({ opts, positionals, out }) => {
|
|
4
|
+
const api = require('../../utils/cloud/api');
|
|
5
|
+
const cli = require('../../utils/cloud/cli');
|
|
6
|
+
const { parseTarget } = require('../../utils/seed/convert');
|
|
7
|
+
const [t, mode] = positionals;
|
|
8
|
+
const target = parseTarget(t || '');
|
|
9
|
+
if (!target || !['seed', 'reference'].includes(mode)) throw api.usageError('poad seed mode <schema.table> seed|reference');
|
|
10
|
+
const { id } = cli.targetProject(opts);
|
|
11
|
+
const r = await api.call('POST', `v1/projects/${api.enc(id)}/seeds/mode`, { body: { target, mode }, what: `seed ${target}` });
|
|
12
|
+
out.result({ project: id, ...r });
|
|
13
|
+
out.log(`${out.chalk.greenBright('✔')} ${target}: ${mode}${mode === 'reference' ? ' (loaded everywhere, production included)' : ' (development data: never loaded into production without --force)'}`);
|
|
14
|
+
});
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// poad seed push <fichier> [--table schéma.table] [--format sql|csv] [--mode seed|reference]
|
|
2
|
+
// [--load] [--env <branche>] [--force] [--project <id>] [--json]
|
|
3
|
+
// Convertit le fichier (une entrée par table), chiffre chaque table et l'envoie
|
|
4
|
+
// au magasin de poad.io par URL signée, puis l'inscrit au registre du projet.
|
|
5
|
+
// --load : la charge aussitôt dans l'environnement visé (--env, sinon la branche git, sinon main).
|
|
6
|
+
module.exports = (args, raw) =>
|
|
7
|
+
require('../../utils/cloud/cli').run(raw, { values: ['table', 'format', 'mode', 'env', 'project'], flags: ['load', 'force', 'yes'] }, async ({ opts, positionals, out }) => {
|
|
8
|
+
const fs = require('fs');
|
|
9
|
+
const path = require('path');
|
|
10
|
+
const api = require('../../utils/cloud/api');
|
|
11
|
+
const cli = require('../../utils/cloud/cli');
|
|
12
|
+
const S = require('../../utils/seed/run');
|
|
13
|
+
const { chalk } = out;
|
|
14
|
+
const file = positionals[0];
|
|
15
|
+
if (!file) throw api.usageError('poad seed push <file.sql|file.csv> [--table schema.table] [--mode seed|reference]');
|
|
16
|
+
if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw api.usageError(`${file}: no such file`);
|
|
17
|
+
const mode = opts.mode || 'seed';
|
|
18
|
+
if (!['seed', 'reference'].includes(mode)) throw api.usageError('--mode is seed or reference');
|
|
19
|
+
if (opts.format && !['sql', 'csv'].includes(opts.format)) throw api.usageError('--format is sql or csv');
|
|
20
|
+
const { id, root } = cli.targetProject(opts);
|
|
21
|
+
api.requireToken();
|
|
22
|
+
const dir = S.tmpDir();
|
|
23
|
+
try {
|
|
24
|
+
// 1. Conversion
|
|
25
|
+
const t0 = Date.now();
|
|
26
|
+
let last = 0;
|
|
27
|
+
const conv = await S.convertFile(file, {
|
|
28
|
+
format: opts.format,
|
|
29
|
+
table: opts.table,
|
|
30
|
+
dir,
|
|
31
|
+
onProgress: (read, total) => {
|
|
32
|
+
if (!out.json && process.stderr.isTTY && Date.now() - last > 250) {
|
|
33
|
+
last = Date.now();
|
|
34
|
+
process.stderr.write(`\r ${chalk.grey('reading')} ${path.basename(file)} ${Math.floor((read / total) * 100)}% `);
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
});
|
|
38
|
+
if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
|
|
39
|
+
if (!conv.tables.length) throw new api.CloudError(`${path.basename(file)}: no data found (INSERT … VALUES, COPY … FROM stdin, or CSV rows)`, { code: 'seed_empty' });
|
|
40
|
+
out.log(`${chalk.greenBright('✔')} ${path.basename(file)} read in ${((Date.now() - t0) / 1000).toFixed(1)} s: ${conv.tables.map((t) => `${t.target} (${t.rows} rows)`).join(', ')}`);
|
|
41
|
+
const skipped = Object.entries(conv.skipped).filter(([w]) => !['SET', 'BEGIN', 'COMMIT', 'END', 'SELECT'].includes(w));
|
|
42
|
+
if (skipped.length) out.log(chalk.grey(` Ignored, not data: ${skipped.map(([w, n]) => `${n} ${w}`).join(', ')} (structure goes through migrations).`));
|
|
43
|
+
if (conv.mutations) out.log(chalk.yellowBright(` ${conv.mutations} UPDATE/DELETE statement(s) ignored: a seed only carries rows; apply them as a migration if they matter.`));
|
|
44
|
+
// 2. Envoi, table par table
|
|
45
|
+
const results = [];
|
|
46
|
+
for (const t of conv.tables) {
|
|
47
|
+
let shown = 0;
|
|
48
|
+
const r = await S.pushTable(id, t, {
|
|
49
|
+
mode,
|
|
50
|
+
source: path.basename(file),
|
|
51
|
+
onProgress: (done, total) => {
|
|
52
|
+
if (!out.json && process.stderr.isTTY && Date.now() - shown > 250) {
|
|
53
|
+
shown = Date.now();
|
|
54
|
+
process.stderr.write(`\r ${chalk.grey('sending')} ${t.target} ${S.fmt(done)} / ${S.fmt(total)} `);
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
|
|
59
|
+
out.log(`${chalk.greenBright('✔')} ${chalk.bold(t.target)} ${r.uploaded ? `sent (${S.fmt(r.stored)} encrypted)` : 'unchanged content: nothing to send'}, mode ${mode}${r.replaced ? ', replaces the previous version' : ''}`);
|
|
60
|
+
results.push({ target: t.target, rows: t.rows, sha256: t.sha256, uploaded: r.uploaded, stored_bytes: r.stored, mode });
|
|
61
|
+
}
|
|
62
|
+
// 3. Chargement facultatif
|
|
63
|
+
let load = null;
|
|
64
|
+
if (opts.load) {
|
|
65
|
+
const branches = require('../../utils/cloud/branches');
|
|
66
|
+
const env = await branches.resolve(id, { wanted: opts.env, root });
|
|
67
|
+
load = await startAndWait(id, env.branch, results.map((r) => r.target), opts, out);
|
|
68
|
+
} else out.log(chalk.grey(` Load it: poad seed load ${results.map((r) => r.target).join(' ')}${opts.env ? ` --env ${opts.env}` : ''} (or poad seed load --local)`));
|
|
69
|
+
out.result({ project: id, tables: results, load });
|
|
70
|
+
return load && load.status === 'failed' ? api.EXIT.failed : 0;
|
|
71
|
+
} finally {
|
|
72
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
/** Lance un chargement hébergé et suit ses étapes */
|
|
77
|
+
async function startAndWait(id, branch, targets, opts, out) {
|
|
78
|
+
const api = require('../../utils/cloud/api');
|
|
79
|
+
const S = require('../../utils/seed/run');
|
|
80
|
+
const { chalk } = out;
|
|
81
|
+
let started;
|
|
82
|
+
try {
|
|
83
|
+
started = await api.call('POST', `v1/projects/${api.enc(id)}/seeds/load`, { body: { branch, targets, force: Boolean(opts.force), ...(opts.reference ? { only: 'reference' } : {}) }, what: 'seed load' });
|
|
84
|
+
} catch (e) {
|
|
85
|
+
if (e.code === 'seed_in_production') throw new api.CloudError(`${e.message}\n Development data into production: add --force if that is what you want.`, { code: e.code, exit: api.EXIT.confirm });
|
|
86
|
+
throw e;
|
|
87
|
+
}
|
|
88
|
+
out.log(chalk.grey(` Loading into ${branch} (${started.targets.length} table(s))…`));
|
|
89
|
+
const done = new Set();
|
|
90
|
+
const l = await S.waitLoad(id, started.load_id, {
|
|
91
|
+
onStep: (st) => {
|
|
92
|
+
for (const s of st.steps) {
|
|
93
|
+
if (done.has(s.target) || !['done', 'failed'].includes(s.status)) continue;
|
|
94
|
+
done.add(s.target);
|
|
95
|
+
if (s.status === 'done') out.log(`${chalk.greenBright('✔')} ${s.target} loaded into ${branch}: ${s.written} rows written, ${s.deleted} removed (${(s.duration_ms / 1000).toFixed(1)} s)`);
|
|
96
|
+
else out.log(`${chalk.redBright('✖')} ${s.target}: ${s.error}`);
|
|
97
|
+
}
|
|
98
|
+
},
|
|
99
|
+
});
|
|
100
|
+
if (l.status === 'failed') out.log(chalk.grey(' Nothing was half-loaded: each table is all or nothing.'));
|
|
101
|
+
return l;
|
|
102
|
+
}
|
|
103
|
+
module.exports.startAndWait = startAndWait;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// poad seed rm <table> [--yes] [--project <id>] [--json] : retire le seed du magasin (la table garde ses lignes)
|
|
2
|
+
module.exports = (args, raw) =>
|
|
3
|
+
require('../../utils/cloud/cli').run(raw, { values: ['project'], flags: ['yes'] }, async ({ opts, positionals, out }) => {
|
|
4
|
+
const api = require('../../utils/cloud/api');
|
|
5
|
+
const cli = require('../../utils/cloud/cli');
|
|
6
|
+
const { parseTarget } = require('../../utils/seed/convert');
|
|
7
|
+
const target = parseTarget(positionals[0] || '');
|
|
8
|
+
if (!target) throw api.usageError('poad seed rm <schema.table>');
|
|
9
|
+
const { id } = cli.targetProject(opts);
|
|
10
|
+
await cli.confirm(`Remove the seed of ${target} from poad.io? The table keeps its rows; the stored file is deleted.`, { yes: opts.yes, json: out.json });
|
|
11
|
+
const r = await api.call('POST', `v1/projects/${api.enc(id)}/seeds/delete`, { body: { target }, what: `seed ${target}` });
|
|
12
|
+
out.result({ project: id, ...r });
|
|
13
|
+
out.log(`${out.chalk.greenBright('✔')} seed of ${target} removed`);
|
|
14
|
+
});
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// Fronts dessinés dans poad : un port par front dans poad/config.toml, réserve,
|
|
2
|
+
// variables et ports de l'engine, suivi des fronts créés depuis la console.
|
|
3
|
+
const { test } = require('node:test');
|
|
4
|
+
const assert = require('node:assert');
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
const os = require('os');
|
|
7
|
+
const path = require('path');
|
|
8
|
+
const toml = require('toml');
|
|
9
|
+
const fronts = require('../utils/fronts');
|
|
10
|
+
const { setInText, removeSectionInText } = require('../utils/tomlfile');
|
|
11
|
+
const { attrConditions } = require('../utils/logline');
|
|
12
|
+
|
|
13
|
+
const A = 'k3x9q2m7a1bc';
|
|
14
|
+
const B = 'zq8w7e6r5t4y';
|
|
15
|
+
|
|
16
|
+
const project = (text) => {
|
|
17
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-fronts-'));
|
|
18
|
+
const file = path.join(dir, 'config.toml');
|
|
19
|
+
fs.writeFileSync(file, text);
|
|
20
|
+
return file;
|
|
21
|
+
};
|
|
22
|
+
const parse = (file) => toml.parse(fs.readFileSync(file, 'utf-8'));
|
|
23
|
+
const BASE = 'project_id = "bdtheque"\nengine = "0.46.0"\n\n[db]\nport = 15432\n\n[web]\nport = 18000\n';
|
|
24
|
+
|
|
25
|
+
test('tomlfile : tableau sur une ligne, section imbriquée, retrait', () => {
|
|
26
|
+
let text = setInText(BASE, 'fronts', { spare_ports: [41001, 41002] });
|
|
27
|
+
text = setInText(text, `fronts.${A}`, { port: 41003 });
|
|
28
|
+
const c = toml.parse(text);
|
|
29
|
+
assert.deepStrictEqual(c.fronts.spare_ports, [41001, 41002]);
|
|
30
|
+
assert.strictEqual(c.fronts[A].port, 41003);
|
|
31
|
+
// La réserve se réécrit sans toucher à la section du front qui suit
|
|
32
|
+
text = setInText(text, 'fronts', { spare_ports: [41002] });
|
|
33
|
+
assert.match(text, /spare_ports = \[41002\]/);
|
|
34
|
+
assert.strictEqual(toml.parse(text).fronts[A].port, 41003);
|
|
35
|
+
text = removeSectionInText(text, `fronts.${A}`);
|
|
36
|
+
assert.strictEqual(toml.parse(text).fronts[A], undefined);
|
|
37
|
+
assert.strictEqual(toml.parse(text).web.port, 18000);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test('read : identifiants valides seulement, réserve sans doublon ni port de front', () => {
|
|
41
|
+
const s = fronts.read({ fronts: { spare_ports: [41001, 41001, 41003, 'x'], [A]: { port: 41003 }, 'Pas-un-id': { port: 41005 }, [B]: { port: 0 } } });
|
|
42
|
+
assert.deepStrictEqual(s.fronts, [{ id: A, port: 41003 }]);
|
|
43
|
+
assert.deepStrictEqual(s.spare, [41001]);
|
|
44
|
+
assert.deepStrictEqual(fronts.read({}), { fronts: [], spare: [] });
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test('ensureSpare : deux ports libres, jamais un port du projet, écrits dans config.toml', async () => {
|
|
48
|
+
const file = project(BASE);
|
|
49
|
+
const config = parse(file);
|
|
50
|
+
const offered = [18000, 15432, 41001, 41001, 41002];
|
|
51
|
+
const added = await fronts.ensureSpare(file, config, { findFreePorts: async () => [offered.shift()], isPortFree: async () => true });
|
|
52
|
+
assert.deepStrictEqual(added, [41001, 41002]);
|
|
53
|
+
assert.deepStrictEqual(parse(file).fronts.spare_ports, [41001, 41002]);
|
|
54
|
+
assert.deepStrictEqual(config.fronts.spare_ports, [41001, 41002]);
|
|
55
|
+
// Déjà complète : rien d'ajouté ; un port de réserve pris ailleurs est remplacé
|
|
56
|
+
assert.deepStrictEqual(await fronts.ensureSpare(file, config, { findFreePorts: async () => [41009], isPortFree: async () => true }), []);
|
|
57
|
+
const again = await fronts.ensureSpare(file, config, { findFreePorts: async () => [41009], isPortFree: async (p) => p !== 41001 });
|
|
58
|
+
assert.deepStrictEqual(again, [41009]);
|
|
59
|
+
assert.deepStrictEqual(parse(file).fronts.spare_ports, [41002, 41009]);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test('busyEntries et foldMoved : un port de front déplacé revient dans config.fronts', () => {
|
|
63
|
+
const config = { fronts: { spare_ports: [], [A]: { port: 41003 } } };
|
|
64
|
+
const entries = fronts.busyEntries(config);
|
|
65
|
+
assert.deepStrictEqual(entries, [{ section: `fronts.${A}`, key: 'port', label: `Front ${A}` }]);
|
|
66
|
+
config[`fronts.${A}`] = { port: 42000 }; // ce que fait reassignBusyPorts
|
|
67
|
+
fronts.foldMoved(config);
|
|
68
|
+
assert.strictEqual(config.fronts[A].port, 42000);
|
|
69
|
+
assert.strictEqual(config[`fronts.${A}`], undefined);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test('engineEnv et bindings : tous les ports vers 8100/tcp, même interface que les autres', () => {
|
|
73
|
+
const config = { project_id: 'bdtheque', web: { port: 18000 }, fronts: { spare_ports: [41001, 41002], [A]: { port: 41003 } } };
|
|
74
|
+
assert.deepStrictEqual(fronts.engineEnv(config), [`POAD_FRONT_PORTS=${A}=41003`, 'POAD_FRONT_SPARE_PORTS=41001,41002', 'POAD_PROJECT_NAME=bdtheque']);
|
|
75
|
+
const b = fronts.bindings(config);
|
|
76
|
+
assert.deepStrictEqual(b.exposed, { '8100/tcp': {} });
|
|
77
|
+
assert.deepStrictEqual(b.bindings['8100/tcp'], [
|
|
78
|
+
{ HostIp: '127.0.0.1', HostPort: '41003' },
|
|
79
|
+
{ HostIp: '127.0.0.1', HostPort: '41001' },
|
|
80
|
+
{ HostIp: '127.0.0.1', HostPort: '41002' },
|
|
81
|
+
]);
|
|
82
|
+
assert.strictEqual(fronts.bindings({ ...config, web: { port: 18000, expose: true } }).bindings['8100/tcp'][0].HostIp, '0.0.0.0');
|
|
83
|
+
assert.deepStrictEqual(fronts.bindings({}), { exposed: {}, bindings: {} });
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
test('supportsFronts : engine 0.46.0 et plus (0.45.0 publiée sans les fronts)', () => {
|
|
87
|
+
assert.strictEqual(fronts.supportsFronts({ engine: '0.44.2' }), false);
|
|
88
|
+
assert.strictEqual(fronts.supportsFronts({ engine: '0.45.0' }), false);
|
|
89
|
+
assert.strictEqual(fronts.supportsFronts({ engine: '0.46.0' }), true);
|
|
90
|
+
assert.strictEqual(fronts.supportsFronts({ engine: '1.0.0' }), true);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
const fakeFetch = (body, status = 200) => {
|
|
94
|
+
const calls = [];
|
|
95
|
+
const fn = async (url, init) => {
|
|
96
|
+
calls.push({ url, init });
|
|
97
|
+
return { ok: status < 400, status, json: async () => body };
|
|
98
|
+
};
|
|
99
|
+
fn.calls = calls;
|
|
100
|
+
return fn;
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
test('sync : un front créé depuis la console prend sa section, son port quitte la réserve ; un front supprimé part', async () => {
|
|
104
|
+
const file = project(`${BASE}\n[fronts]\nspare_ports = [41001, 41002]\n\n[fronts.${B}]\nport = 41000\n`);
|
|
105
|
+
const config = { ...parse(file), auth: { service: 'svc' } };
|
|
106
|
+
const fetchFn = fakeFetch([
|
|
107
|
+
{ id: A, name: 'Gestion', address: 'http://localhost:41001', port_pending: false },
|
|
108
|
+
{ id: 'abcdefghijkl', name: 'Sans port', address: null, port_pending: true },
|
|
109
|
+
]);
|
|
110
|
+
const out = await fronts.sync(file, config, fetchFn);
|
|
111
|
+
assert.strictEqual(fetchFn.calls[0].url, 'http://localhost:18000/meta/v1/fronts');
|
|
112
|
+
assert.strictEqual(fetchFn.calls[0].init.headers.authorization, 'Bearer svc');
|
|
113
|
+
const c = parse(file);
|
|
114
|
+
assert.strictEqual(c.fronts[A].port, 41001);
|
|
115
|
+
assert.deepStrictEqual(c.fronts.spare_ports, [41002]);
|
|
116
|
+
assert.strictEqual(c.fronts[B], undefined);
|
|
117
|
+
assert.deepStrictEqual(fronts.read(config), { fronts: [{ id: A, port: 41001 }], spare: [41002] });
|
|
118
|
+
assert.deepStrictEqual(out.fronts.map((f) => [f.name, f.address, f.port_pending]), [
|
|
119
|
+
['Gestion', 'http://localhost:41001', false],
|
|
120
|
+
['Sans port', null, true],
|
|
121
|
+
]);
|
|
122
|
+
const chalk = require('chalk-v2');
|
|
123
|
+
const lines = fronts.describe(config, out, chalk).join('\n');
|
|
124
|
+
assert.match(lines, /Front Gestion : .*http:\/\/localhost:41001/);
|
|
125
|
+
assert.match(lines, /Sans port : .*restart the project/);
|
|
126
|
+
assert.match(lines, /Spare front ports: 41002/);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
test('sync : meta absent (engine ancien, 404) ou injoignable : rien ne change', async () => {
|
|
130
|
+
const text = `${BASE}\n[fronts]\nspare_ports = [41001, 41002]\n`;
|
|
131
|
+
const file = project(text);
|
|
132
|
+
const config = { ...parse(file), auth: { service: 'svc' } };
|
|
133
|
+
assert.strictEqual(await fronts.sync(file, config, fakeFetch({ error: 'route inconnue' }, 404)), null);
|
|
134
|
+
assert.strictEqual(
|
|
135
|
+
await fronts.sync(file, config, async () => {
|
|
136
|
+
throw new Error('ECONNREFUSED');
|
|
137
|
+
}),
|
|
138
|
+
null,
|
|
139
|
+
);
|
|
140
|
+
assert.strictEqual(fs.readFileSync(file, 'utf-8'), text);
|
|
141
|
+
// Sans sync, l'affichage se rabat sur config.toml
|
|
142
|
+
assert.match(fronts.describe({ fronts: { [A]: { port: 41003 } } }, null, require('chalk-v2')).join('\n'), new RegExp(`Front ${A} : .*41003`));
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
test('portOf : seulement une adresse locale', () => {
|
|
146
|
+
assert.strictEqual(fronts.portOf('http://localhost:41001'), 41001);
|
|
147
|
+
assert.strictEqual(fronts.portOf('http://127.0.0.1:41001/'), 41001);
|
|
148
|
+
assert.strictEqual(fronts.portOf(`https://${A}.app.poad.io`), null);
|
|
149
|
+
assert.strictEqual(fronts.portOf(null), null);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
test('poad logs : front= et page= filtrent attrs', () => {
|
|
153
|
+
const r = attrConditions({ front: A, page: 'accueil' });
|
|
154
|
+
assert.deepStrictEqual(r.conditions, [
|
|
155
|
+
["attrs->>'front' = ?", A],
|
|
156
|
+
["attrs->>'page' = ?", 'accueil'],
|
|
157
|
+
]);
|
|
158
|
+
assert.match(attrConditions({ front: true }).error, /front=k3x9q2m7a1bc/);
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
test('fetchFronts : nouvel essai tant que la passerelle répond 502 juste après le démarrage, abandon sur 404', async () => {
|
|
162
|
+
const fronts = require('../utils/fronts');
|
|
163
|
+
const config = { web: { port: 1 }, auth: { service: 's' } };
|
|
164
|
+
let calls = 0;
|
|
165
|
+
const flaky = async () => (++calls < 3 ? { ok: false, status: 502 } : { ok: true, status: 200, json: async () => [{ id: 'abc123def456', name: 'Démo', address: 'http://localhost:41001' }] });
|
|
166
|
+
const list = await fronts.fetchFronts(config, flaky, { attempts: 5, delayMs: 1 });
|
|
167
|
+
require('node:assert').equal(calls, 3);
|
|
168
|
+
require('node:assert').equal(list[0].name, 'Démo');
|
|
169
|
+
calls = 0;
|
|
170
|
+
const gone = async () => (++calls, { ok: false, status: 404 });
|
|
171
|
+
require('node:assert').equal(await fronts.fetchFronts(config, gone, { attempts: 5, delayMs: 1 }), null);
|
|
172
|
+
require('node:assert').equal(calls, 1);
|
|
173
|
+
});
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// poad seed : conversion SQL/CSV -> COPY, paquets chiffrés, script de chargement
|
|
2
|
+
const test = require('node:test');
|
|
3
|
+
const assert = require('node:assert');
|
|
4
|
+
const crypto = require('crypto');
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
const os = require('os');
|
|
7
|
+
const path = require('path');
|
|
8
|
+
const zlib = require('zlib');
|
|
9
|
+
const { pipeline } = require('stream/promises');
|
|
10
|
+
const { SqlSource, CsvSource, ConvertError, copyEscape, parseTarget } = require('../utils/seed/convert');
|
|
11
|
+
const { TableSink, encryptFile, decryptStream } = require('../utils/seed/pack');
|
|
12
|
+
const A = require('../utils/seed/apply');
|
|
13
|
+
|
|
14
|
+
const sql = (text, chunk = 0) => {
|
|
15
|
+
const rows = [];
|
|
16
|
+
const s = new SqlSource({ onRow: (t, c, l) => rows.push({ t, c, l }) });
|
|
17
|
+
if (chunk) for (let i = 0; i < text.length; i += chunk) s.push(text.slice(i, i + chunk));
|
|
18
|
+
else s.push(text);
|
|
19
|
+
s.end();
|
|
20
|
+
return { rows, skipped: s.skipped, mutations: s.mutations };
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
test('INSERT multi-lignes, guillemets, NULL, conversions, nom sans schéma', () => {
|
|
24
|
+
const r = sql(`-- dump
|
|
25
|
+
SET x = 1;
|
|
26
|
+
INSERT INTO "departement" ("id","nom","geom") VALUES
|
|
27
|
+
( 1,'Ain','0106AB' ), (2, 'Côtes-d''Armor', NULL),(3,'a;b', '2024-01-19'::timestamp without time zone);
|
|
28
|
+
COMMIT;`);
|
|
29
|
+
assert.deepStrictEqual(r.rows.map((x) => x.l), ['1\tAin\t0106AB', "2\tCôtes-d'Armor\t\\N", '3\ta;b\t2024-01-19']);
|
|
30
|
+
assert.strictEqual(r.rows[0].t, 'public.departement');
|
|
31
|
+
assert.deepStrictEqual(r.rows[0].c, ['id', 'nom', 'geom']);
|
|
32
|
+
assert.deepStrictEqual(r.skipped, { SET: 1, COMMIT: 1 });
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test('le même résultat quel que soit le découpage en morceaux', () => {
|
|
36
|
+
const text = `INSERT INTO public.t (a, b) VALUES (E'x\\'y\\\\z', 'p''q'), (-1.5e3, $$d;'$$);\nCOPY public.u (a) FROM stdin;\nl1\\tx\nl2\n\\.\nINSERT INTO t VALUES (true, false);`;
|
|
37
|
+
const whole = sql(text);
|
|
38
|
+
for (const n of [1, 2, 3, 5, 7, 13]) assert.deepStrictEqual(sql(text, n).rows, whole.rows, `morceaux de ${n}`);
|
|
39
|
+
assert.deepStrictEqual(whole.rows.map((x) => x.l), ["x'y\\\\z\tp'q", "-1.5e3\td;'", 'l1\\tx', 'l2', 'true\tfalse']);
|
|
40
|
+
assert.strictEqual(whole.rows[4].c, null);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test('échappement COPY : barre oblique, fin de ligne, tabulation', () => {
|
|
44
|
+
assert.strictEqual(copyEscape('a\\b\nc\td\re'), 'a\\\\b\\nc\\td\\re');
|
|
45
|
+
assert.strictEqual(copyEscape(null), '\\N');
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test('refus explicites : fonction, DEFAULT, INSERT … SELECT, nombre de valeurs', () => {
|
|
49
|
+
assert.throws(() => sql(`INSERT INTO t (g) VALUES (ST_GeomFromText('POINT(0 0)', 4326));`), /not a plain value.*line 1.*public\.t/);
|
|
50
|
+
assert.throws(() => sql(`INSERT INTO t (a) VALUES (DEFAULT);`), /DEFAULT/);
|
|
51
|
+
assert.throws(() => sql(`INSERT INTO t (a) SELECT 1;`), /INSERT … SELECT/);
|
|
52
|
+
assert.throws(() => sql(`INSERT INTO t (a, b) VALUES (1);`), /1 values for 2 columns/);
|
|
53
|
+
assert.throws(() => sql(`COPY t FROM '/etc/passwd';`), /FROM stdin/);
|
|
54
|
+
assert.ok(new ConvertError('x') instanceof Error);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test('UPDATE et DELETE sont comptés à part (des données qu’un seed ne rejoue pas)', () => {
|
|
58
|
+
const r = sql(`UPDATE t SET a = 1; DELETE FROM t; CREATE TABLE x (a int);`);
|
|
59
|
+
assert.strictEqual(r.mutations, 2);
|
|
60
|
+
assert.strictEqual(r.skipped.CREATE, 1);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('CSV : en-tête, « ; », guillemets, vide = NULL, "" = chaîne vide', () => {
|
|
64
|
+
const rows = [];
|
|
65
|
+
const c = new CsvSource({ target: 'public.t', onRow: (t, cols, l) => rows.push({ cols, l }) });
|
|
66
|
+
const text = 'id;nom;note\r\n1;"a;""b""";\r\n2;"multi\nligne";""\n';
|
|
67
|
+
for (let i = 0; i < text.length; i += 4) c.push(text.slice(i, i + 4));
|
|
68
|
+
c.end();
|
|
69
|
+
assert.deepStrictEqual(rows[0].cols, ['id', 'nom', 'note']);
|
|
70
|
+
assert.deepStrictEqual(rows.map((r) => r.l), ['1\ta;"b"\t\\N', '2\tmulti\\nligne\t']);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test('nom de table tapé', () => {
|
|
74
|
+
assert.strictEqual(parseTarget('commune'), 'public.commune');
|
|
75
|
+
assert.strictEqual(parseTarget('Ref.Commune'), 'ref.commune');
|
|
76
|
+
assert.strictEqual(parseTarget('"Ref"."Commune"'), 'Ref.Commune');
|
|
77
|
+
assert.strictEqual(parseTarget('a.b.c'), null);
|
|
78
|
+
assert.strictEqual(parseTarget('x;drop'), null);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
test('paquet : gzip + chiffrement, aller-retour, altération et troncature détectées', async () => {
|
|
82
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-seed-'));
|
|
83
|
+
const sink = new TableSink(path.join(dir, 't.gz'));
|
|
84
|
+
const lines = [];
|
|
85
|
+
for (let i = 0; i < 60000; i++) {
|
|
86
|
+
const l = `${i}\t${crypto.randomBytes(24).toString('hex')}`;
|
|
87
|
+
lines.push(l);
|
|
88
|
+
sink.row(l);
|
|
89
|
+
}
|
|
90
|
+
const r = await sink.close();
|
|
91
|
+
const plain = Buffer.from(lines.join('\n') + '\n');
|
|
92
|
+
assert.strictEqual(r.rows, 60000);
|
|
93
|
+
assert.strictEqual(r.plainBytes, plain.length);
|
|
94
|
+
assert.strictEqual(r.sha256, crypto.createHash('sha256').update(plain).digest('hex'));
|
|
95
|
+
const key = crypto.randomBytes(32);
|
|
96
|
+
await encryptFile(r.file, path.join(dir, 't.psd'), key);
|
|
97
|
+
const back = async (file, k = key) => {
|
|
98
|
+
const parts = [];
|
|
99
|
+
await pipeline(fs.createReadStream(file, { highWaterMark: 7777 }), decryptStream(k), zlib.createGunzip(), async function* (src) {
|
|
100
|
+
for await (const c of src) parts.push(c);
|
|
101
|
+
});
|
|
102
|
+
return Buffer.concat(parts);
|
|
103
|
+
};
|
|
104
|
+
assert.ok((await back(path.join(dir, 't.psd'))).equals(plain));
|
|
105
|
+
const enc = fs.readFileSync(path.join(dir, 't.psd'));
|
|
106
|
+
assert.ok(enc.length > 1024 * 1024, 'plusieurs blocs');
|
|
107
|
+
await assert.rejects(back(path.join(dir, 't.psd'), crypto.randomBytes(32)), /altered/);
|
|
108
|
+
const flipped = Buffer.from(enc);
|
|
109
|
+
flipped[100] ^= 1;
|
|
110
|
+
fs.writeFileSync(path.join(dir, 'f.psd'), flipped);
|
|
111
|
+
await assert.rejects(back(path.join(dir, 'f.psd')), /altered/);
|
|
112
|
+
// Coupé après le premier bloc : le dernier manque
|
|
113
|
+
const first = 4 + 32 + enc.readUInt32BE(4 + 12);
|
|
114
|
+
fs.writeFileSync(path.join(dir, 'c.psd'), enc.subarray(0, first));
|
|
115
|
+
await assert.rejects(back(path.join(dir, 'c.psd')), /truncated|altered/);
|
|
116
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test('script de chargement : noms entre guillemets, colonnes, avis lu', () => {
|
|
120
|
+
const h = A.head('public.Commune', ['id', 'n"om']);
|
|
121
|
+
assert.match(h, /create temp table _poad_seed on commit drop as select "id", "n""om" from "public"\."Commune" with no data;/);
|
|
122
|
+
assert.match(h, /copy _poad_seed \("id", "n""om"\) from stdin;/);
|
|
123
|
+
const t = A.tail('public.Commune', ['id', "o'k"]);
|
|
124
|
+
assert.match(t, /^\\\.\n/);
|
|
125
|
+
assert.match(t, /array\['id', 'o''k'\]::text\[\]/);
|
|
126
|
+
assert.match(A.tail('public.t', null), /cols text\[\] := null::text\[\]/);
|
|
127
|
+
assert.deepStrictEqual(A.parseNotice('NOTICE: poad-seed commune written=34945 deleted=2'), { table: 'commune', written: 34945, deleted: 2 });
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
test('ordre de chargement : une table après celles qu’elle référence', () => {
|
|
131
|
+
const order = A.loadOrder(['public.commune', 'public.region', 'public.departement'], ['commune|departement', 'departement|region', 'observation|commune']);
|
|
132
|
+
assert.deepStrictEqual(order, ['public.region', 'public.departement', 'public.commune']);
|
|
133
|
+
});
|