poad 2.52.0 → 2.53.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/project/cli.js +2 -1
- package/project/seed/index.js +1 -0
- package/project/seed/inspect.js +45 -0
- package/project/seed/push.js +9 -3
- package/test/seed.test.js +38 -3
- package/utils/seed/apply.js +42 -11
- package/utils/seed/convert.js +21 -7
- package/utils/seed/inspect.js +233 -0
- package/utils/seed/report.js +37 -0
- package/utils/seed/run.js +40 -19
package/package.json
CHANGED
package/project/cli.js
CHANGED
|
@@ -25,7 +25,8 @@ module.exports = {
|
|
|
25
25
|
},
|
|
26
26
|
seed: {
|
|
27
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
|
-
|
|
28
|
+
inspect: 'What a .sql or .csv file holds, table by table and column by column, before sending anything: rows, volume share of each column, value sizes, heavy columns, estimated size in the database: seed inspect <file> [--fields a,b | --exclude c]',
|
|
29
|
+
push: 'Convert a .sql (INSERT, COPY) or .csv file and send each table: seed push <file> [--fields a,b | --exclude c] [--table schema.table] [--mode seed|reference] [--load] [--env <name>]',
|
|
29
30
|
ls: 'Seeds of the project: mode, size, what each environment has loaded, store quota',
|
|
30
31
|
load: 'Load seeds into an environment (--env, else the git branch, else main) or into the local engine (--local): seed load [table…] [--reference] [--force]',
|
|
31
32
|
mode: 'seed (development data, never into production without --force) or reference (loaded everywhere): seed mode <table> seed|reference',
|
package/project/seed/index.js
CHANGED
|
@@ -4,6 +4,7 @@ module.exports = async () => {
|
|
|
4
4
|
const c = (s) => chalk.cyanBright(s);
|
|
5
5
|
console.log(`${chalk.bold(' Usage :')}`);
|
|
6
6
|
console.log(' ');
|
|
7
|
+
console.log(` ${c('poad seed inspect <file>')} What the file holds, column by column, and its weight: nothing is sent`);
|
|
7
8
|
console.log(` ${c('poad seed push <file>')} Convert a .sql (INSERT, COPY) or .csv file and send each table to poad.io`);
|
|
8
9
|
console.log(` ${c('poad seed ls')} Seeds of the project, their mode and what each environment has loaded`);
|
|
9
10
|
console.log(` ${c('poad seed load [table…]')} Load seeds into an environment (--env), or into the local engine (--local)`);
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// poad seed inspect <fichier> [--fields a,b | --exclude c] [--table schéma.table] [--format sql|csv] [--json]
|
|
2
|
+
// Ce que contient le fichier, table par table et colonne par colonne, avant tout envoi :
|
|
3
|
+
// lignes, volume, part de chaque colonne, taille des valeurs, colonnes lourdes, place
|
|
4
|
+
// estimée dans la base. Rien n'est envoyé ni écrit ; aucune connexion à poad.io.
|
|
5
|
+
module.exports = (args, raw) =>
|
|
6
|
+
require('../../utils/cloud/cli').run(raw, { values: ['table', 'format', 'fields', 'exclude'] }, async ({ opts, positionals, out }) => {
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
const api = require('../../utils/cloud/api');
|
|
10
|
+
const S = require('../../utils/seed/run');
|
|
11
|
+
const { tableReport, fmt } = require('../../utils/seed/report');
|
|
12
|
+
const { chalk } = out;
|
|
13
|
+
const file = positionals[0];
|
|
14
|
+
if (!file) throw api.usageError('poad seed inspect <file.sql|file.csv> [--fields a,b | --exclude c]');
|
|
15
|
+
if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw api.usageError(`${file}: no such file`);
|
|
16
|
+
const t0 = Date.now();
|
|
17
|
+
let last = 0;
|
|
18
|
+
const conv = await S.convertFile(file, {
|
|
19
|
+
format: opts.format,
|
|
20
|
+
table: opts.table,
|
|
21
|
+
fields: opts.fields,
|
|
22
|
+
exclude: opts.exclude,
|
|
23
|
+
write: false,
|
|
24
|
+
onProgress: (read, total) => {
|
|
25
|
+
if (!out.json && process.stderr.isTTY && Date.now() - last > 250) {
|
|
26
|
+
last = Date.now();
|
|
27
|
+
process.stderr.write(`\r ${chalk.grey('reading')} ${path.basename(file)} ${Math.floor((read / total) * 100)}% `);
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
});
|
|
31
|
+
if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
|
|
32
|
+
const tables = conv.tables.map((t) => ({ ...t.stats, dropped: t.dropped }));
|
|
33
|
+
out.result({ file: path.basename(file), tables, skipped: conv.skipped, mutations: conv.mutations });
|
|
34
|
+
if (out.json) return;
|
|
35
|
+
if (!tables.length) return out.log(chalk.yellowBright(` ${path.basename(file)}: no data found (INSERT … VALUES, COPY … FROM stdin, or CSV rows).`));
|
|
36
|
+
out.log(chalk.grey(` ${path.basename(file)} read in ${((Date.now() - t0) / 1000).toFixed(1)} s, nothing sent`));
|
|
37
|
+
for (const t of tables) {
|
|
38
|
+
out.log('');
|
|
39
|
+
for (const l of tableReport(t, chalk, { dropped: t.dropped })) out.log(` ${l}`);
|
|
40
|
+
}
|
|
41
|
+
const total = tables.reduce((n, t) => n + t.db_bytes, 0);
|
|
42
|
+
out.log('');
|
|
43
|
+
out.log(` ${chalk.bold('Total')} ≈ ${fmt(total)} in the database once loaded (estimate: rows, values and indexes)`);
|
|
44
|
+
out.log(chalk.grey(` Send it: poad seed push ${path.basename(file)}${opts.fields ? ` --fields ${opts.fields}` : opts.exclude ? ` --exclude ${opts.exclude}` : ''}`));
|
|
45
|
+
});
|
package/project/seed/push.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// au magasin de poad.io par URL signée, puis l'inscrit au registre du projet.
|
|
5
5
|
// --load : la charge aussitôt dans l'environnement visé (--env, sinon la branche git, sinon main).
|
|
6
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 }) => {
|
|
7
|
+
require('../../utils/cloud/cli').run(raw, { values: ['table', 'format', 'mode', 'env', 'project', 'fields', 'exclude'], flags: ['load', 'force', 'yes'] }, async ({ opts, positionals, out }) => {
|
|
8
8
|
const fs = require('fs');
|
|
9
9
|
const path = require('path');
|
|
10
10
|
const api = require('../../utils/cloud/api');
|
|
@@ -27,6 +27,8 @@ module.exports = (args, raw) =>
|
|
|
27
27
|
const conv = await S.convertFile(file, {
|
|
28
28
|
format: opts.format,
|
|
29
29
|
table: opts.table,
|
|
30
|
+
fields: opts.fields,
|
|
31
|
+
exclude: opts.exclude,
|
|
30
32
|
dir,
|
|
31
33
|
onProgress: (read, total) => {
|
|
32
34
|
if (!out.json && process.stderr.isTTY && Date.now() - last > 250) {
|
|
@@ -37,7 +39,11 @@ module.exports = (args, raw) =>
|
|
|
37
39
|
});
|
|
38
40
|
if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
|
|
39
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' });
|
|
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(', ')}`);
|
|
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
|
+
}
|
|
41
47
|
const skipped = Object.entries(conv.skipped).filter(([w]) => !['SET', 'BEGIN', 'COMMIT', 'END', 'SELECT'].includes(w));
|
|
42
48
|
if (skipped.length) out.log(chalk.grey(` Ignored, not data: ${skipped.map(([w, n]) => `${n} ${w}`).join(', ')} (structure goes through migrations).`));
|
|
43
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.`));
|
|
@@ -57,7 +63,7 @@ module.exports = (args, raw) =>
|
|
|
57
63
|
});
|
|
58
64
|
if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
|
|
59
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' : ''}`);
|
|
60
|
-
results.push({ target: t.target, rows: t.rows, sha256: t.sha256, uploaded: r.uploaded, stored_bytes: r.stored, mode });
|
|
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 });
|
|
61
67
|
}
|
|
62
68
|
// 3. Chargement facultatif
|
|
63
69
|
let load = null;
|
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,37 @@ 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
|
+
});
|
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,233 @@
|
|
|
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
|
+
|
|
49
|
+
class ColumnStats {
|
|
50
|
+
constructor(name) {
|
|
51
|
+
this.name = name;
|
|
52
|
+
this.values = 0;
|
|
53
|
+
this.nulls = 0;
|
|
54
|
+
this.bytes = 0; // octets du contenu en clair (COPY)
|
|
55
|
+
this.maxLen = 0;
|
|
56
|
+
this.sample = null;
|
|
57
|
+
this.types = new Set(ORDER);
|
|
58
|
+
this.intBig = false;
|
|
59
|
+
this.geom = null; // { type, srid, dims, points }
|
|
60
|
+
this.geomPoints = 0;
|
|
61
|
+
this.geomCount = 0;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
add(v) {
|
|
65
|
+
this.values++;
|
|
66
|
+
if (v === null) {
|
|
67
|
+
this.nulls++;
|
|
68
|
+
this.bytes += 2;
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
const len = v.length;
|
|
72
|
+
this.bytes += len + 1;
|
|
73
|
+
if (len > this.maxLen) this.maxLen = len;
|
|
74
|
+
if (this.sample === null && len) this.sample = v;
|
|
75
|
+
const t = this.types;
|
|
76
|
+
if (t.size > 1) {
|
|
77
|
+
if (t.has('bool') && !RE.bool.test(v)) t.delete('bool');
|
|
78
|
+
if (t.has('int')) {
|
|
79
|
+
if (!RE.int.test(v)) t.delete('int');
|
|
80
|
+
else if (Math.abs(Number(v)) > 2147483647) this.intBig = true;
|
|
81
|
+
}
|
|
82
|
+
if (t.has('numeric') && !RE.numeric.test(v)) t.delete('numeric');
|
|
83
|
+
if (t.has('uuid') && !RE.uuid.test(v)) t.delete('uuid');
|
|
84
|
+
if (t.has('date') && !RE.date.test(v)) t.delete('date');
|
|
85
|
+
if (t.has('timestamp') && !RE.timestamp.test(v)) t.delete('timestamp');
|
|
86
|
+
if (t.has('json') && !/^\s*[[{]/.test(v)) t.delete('json');
|
|
87
|
+
// bytea en hexadécimal (\x…) : un binaire (image, vidéo, PDF…)
|
|
88
|
+
if (t.has('binary') && !(v.startsWith('\\x') && (len - 2) % 2 === 0 && RE.hex.test(v.slice(2)))) t.delete('binary');
|
|
89
|
+
if (t.has('geometry')) {
|
|
90
|
+
const h = len >= 18 && len < 64 * 1024 * 1024 && RE.hex.test(v) ? ewkbHeader(v) : null;
|
|
91
|
+
if (!h) t.delete('geometry');
|
|
92
|
+
else {
|
|
93
|
+
if (!this.geom) this.geom = { type: h.type, srid: h.srid, dims: h.dims };
|
|
94
|
+
else if (this.geom.type !== h.type) this.geom.type = 'Geometry';
|
|
95
|
+
// Points : (octets - en-têtes) / (8 octets par coordonnée × dimensions), en gros
|
|
96
|
+
this.geomPoints += Math.max(1, Math.round((len / 2 - 9) / (8 * h.dims)));
|
|
97
|
+
this.geomCount++;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Type deviné : le plus précis qui a résisté à toutes les valeurs (vide : inconnu) */
|
|
104
|
+
type() {
|
|
105
|
+
if (this.values === this.nulls) return 'unknown';
|
|
106
|
+
for (const k of ORDER) if (this.types.has(k)) return k === 'int' && this.intBig ? 'bigint' : k;
|
|
107
|
+
return 'text';
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Octets estimés dans la base pour ce contenu (sans en-têtes de ligne) */
|
|
111
|
+
dbBytes() {
|
|
112
|
+
const filled = this.values - this.nulls;
|
|
113
|
+
const avg = filled ? (this.bytes - this.nulls * 2) / filled - 1 : 0;
|
|
114
|
+
const per = {
|
|
115
|
+
bool: 1,
|
|
116
|
+
int: 4,
|
|
117
|
+
bigint: 8,
|
|
118
|
+
numeric: Math.max(5, Math.ceil(avg / 2) + 3),
|
|
119
|
+
uuid: 16,
|
|
120
|
+
date: 4,
|
|
121
|
+
timestamp: 8,
|
|
122
|
+
geometry: avg / 2 + 8,
|
|
123
|
+
binary: (avg - 2) / 2 + 4,
|
|
124
|
+
json: avg + 4,
|
|
125
|
+
text: avg + (avg > 126 ? 4 : 1),
|
|
126
|
+
unknown: 0,
|
|
127
|
+
}[this.type()];
|
|
128
|
+
return Math.round(filled * per);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
view(totalBytes) {
|
|
132
|
+
const type = this.type();
|
|
133
|
+
const filled = this.values - this.nulls;
|
|
134
|
+
// Taille d'une valeur telle qu'elle sera stockée (un hexadécimal compte pour moitié)
|
|
135
|
+
const half = type === 'geometry' || type === 'binary';
|
|
136
|
+
const prefix = type === 'binary' ? 2 : 0; // « \x » d'un bytea
|
|
137
|
+
const avgValue = filled ? ((this.bytes - this.nulls * 2) / filled - 1 - prefix) / (half ? 2 : 1) : 0;
|
|
138
|
+
const maxValue = (this.maxLen - prefix) / (half ? 2 : 1);
|
|
139
|
+
return {
|
|
140
|
+
name: this.name,
|
|
141
|
+
type,
|
|
142
|
+
nulls: this.values ? this.nulls / this.values : 0,
|
|
143
|
+
plain_bytes: this.bytes,
|
|
144
|
+
share: totalBytes ? this.bytes / totalBytes : 0,
|
|
145
|
+
avg_value_bytes: Math.round(avgValue),
|
|
146
|
+
max_value_bytes: Math.round(maxValue),
|
|
147
|
+
heavy: (totalBytes ? this.bytes / totalBytes : 0) >= 0.5 || maxValue >= HEAVY_VALUE,
|
|
148
|
+
max_length: this.maxLen,
|
|
149
|
+
sample: this.sample === null ? null : this.sample.length > 60 ? `${this.sample.slice(0, 57)}…` : this.sample,
|
|
150
|
+
db_bytes: this.dbBytes(),
|
|
151
|
+
...(type === 'geometry' && this.geom ? { geometry: { ...this.geom, avg_points: Math.round(this.geomPoints / Math.max(1, this.geomCount)) } } : {}),
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Statistiques d'une table, alimentées ligne par ligne */
|
|
157
|
+
class TableStats {
|
|
158
|
+
constructor(target, columns) {
|
|
159
|
+
this.target = target;
|
|
160
|
+
this.columns = columns;
|
|
161
|
+
this.rows = 0;
|
|
162
|
+
this.cols = null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
add(values) {
|
|
166
|
+
if (!this.cols) this.cols = values.map((_, i) => new ColumnStats(this.columns ? this.columns[i] : `#${i + 1}`));
|
|
167
|
+
this.rows++;
|
|
168
|
+
for (let i = 0; i < values.length; i++) this.cols[i] && this.cols[i].add(values[i]);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
view() {
|
|
172
|
+
const cols = this.cols || [];
|
|
173
|
+
const plain = cols.reduce((n, c) => n + c.bytes, 0);
|
|
174
|
+
const columns = cols.map((c) => c.view(plain));
|
|
175
|
+
// Ligne : en-tête (24 octets) + alignement ; index : clé primaire supposée (≈ 20 o/ligne), index spatial (≈ 60 o/ligne)
|
|
176
|
+
const data = columns.reduce((n, c) => n + c.db_bytes, 0) + this.rows * 28;
|
|
177
|
+
const indexes = this.rows * 20 + columns.filter((c) => c.type === 'geometry').length * this.rows * 60;
|
|
178
|
+
const heavy = columns.filter((c) => c.heavy).sort((a, b) => b.share - a.share);
|
|
179
|
+
return {
|
|
180
|
+
target: this.target,
|
|
181
|
+
named_columns: Boolean(this.columns),
|
|
182
|
+
rows: this.rows,
|
|
183
|
+
plain_bytes: plain,
|
|
184
|
+
db_bytes: Math.round((data + indexes) * 1.1),
|
|
185
|
+
columns,
|
|
186
|
+
heavy: heavy.map((c) => ({ column: c.name, share: c.share, type: c.type, max_value_bytes: c.max_value_bytes })),
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Sélection de colonnes (--fields, --exclude) : « col » s'applique à toute table qui l'a,
|
|
193
|
+
* « table.col » ou « schéma.table.col » à une seule. Renvoie pick(target, columns) ->
|
|
194
|
+
* indices gardés (null : toutes), et check() qui signale ce qui n'a rien désigné.
|
|
195
|
+
*/
|
|
196
|
+
function columnPicker({ fields, exclude } = {}) {
|
|
197
|
+
const parse = (s) =>
|
|
198
|
+
String(s || '')
|
|
199
|
+
.split(',')
|
|
200
|
+
.map((x) => x.trim())
|
|
201
|
+
.filter(Boolean);
|
|
202
|
+
const keep = parse(fields);
|
|
203
|
+
const drop = parse(exclude);
|
|
204
|
+
if (!keep.length && !drop.length) return { active: false, pick: () => null, check: () => [] };
|
|
205
|
+
if (keep.length && drop.length) throw new Error('--fields and --exclude cannot be combined: keep a list, or remove one');
|
|
206
|
+
const used = new Set();
|
|
207
|
+
const matches = (spec, target, col) => {
|
|
208
|
+
const parts = spec.split('.');
|
|
209
|
+
if (parts.length === 1) return parts[0] === col;
|
|
210
|
+
const [t, c] = [parts.slice(0, -1).join('.'), parts[parts.length - 1]];
|
|
211
|
+
return c === col && (target === t || target.endsWith(`.${t}`));
|
|
212
|
+
};
|
|
213
|
+
return {
|
|
214
|
+
active: true,
|
|
215
|
+
pick(target, columns) {
|
|
216
|
+
if (!columns) throw new Error(`${target}: the file does not name its columns (INSERT without a column list): --fields and --exclude need names`);
|
|
217
|
+
const idx = [];
|
|
218
|
+
columns.forEach((col, i) => {
|
|
219
|
+
const hitKeep = keep.find((s) => matches(s, target, col));
|
|
220
|
+
const hitDrop = drop.find((s) => matches(s, target, col));
|
|
221
|
+
if (hitKeep) used.add(hitKeep);
|
|
222
|
+
if (hitDrop) used.add(hitDrop);
|
|
223
|
+
if (keep.length ? hitKeep : !hitDrop) idx.push(i);
|
|
224
|
+
});
|
|
225
|
+
if (!idx.length) throw new Error(`${target}: no column left after --fields/--exclude`);
|
|
226
|
+
return idx.length === columns.length ? null : idx;
|
|
227
|
+
},
|
|
228
|
+
/** Ce qui n'a désigné aucune colonne (faute de frappe) */
|
|
229
|
+
check: () => [...keep, ...drop].filter((s) => !used.has(s)),
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
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}`);
|