poad 2.51.0 → 2.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,673 @@
1
+ // Conversion d'un fichier de données en contenu COPY (format texte de
2
+ // PostgreSQL), une table à la fois : c'est le format unique du magasin de
3
+ // seeds, quel que soit ce que le développeur apporte.
4
+ //
5
+ // .sql INSERT INTO … [(colonnes)] VALUES (…), (…); (pg_dump --inserts,
6
+ // --column-inserts, Valentina, DBeaver…) et blocs COPY … FROM stdin
7
+ // (pg_dump par défaut). Le reste (SET, BEGIN, CREATE…) est ignoré et
8
+ // compté : la structure passe par les migrations.
9
+ // .csv une ligne d'en-tête (noms des colonnes), séparateur « , » ou « ; »
10
+ //
11
+ // Aucune valeur n'est interprétée : une chaîne reste une chaîne (géométrie
12
+ // en EWKB hexadécimal, JSON, date…), c'est PostgreSQL qui la convertit au
13
+ // chargement dans le type de la colonne. Ce qui ne peut pas devenir une
14
+ // valeur littérale (appel de fonction, DEFAULT, ARRAY[…]) est refusé avec la
15
+ // ligne et la table en cause.
16
+ 'use strict';
17
+
18
+ class ConvertError extends Error {
19
+ constructor(message, { line, table } = {}) {
20
+ super(line ? `${message} (line ${line}${table ? `, table ${table}` : ''})` : message);
21
+ this.code = 'seed_convert';
22
+ this.line = line;
23
+ this.table = table;
24
+ }
25
+ }
26
+
27
+ // --- Identifiants -----------------------------------------------------------
28
+
29
+ /** « schéma.table » d'un nom tapé : guillemets retirés, minuscules sinon, public par défaut */
30
+ function qualify(parts) {
31
+ const ids = parts.map((p) => (p.quoted ? p.name : p.name.toLowerCase()));
32
+ if (ids.length === 1) return { schema: 'public', table: ids[0] };
33
+ if (ids.length === 2) return { schema: ids[0], table: ids[1] };
34
+ return { schema: ids[ids.length - 2], table: ids[ids.length - 1] };
35
+ }
36
+ const targetOf = (q) => `${q.schema}.${q.table}`;
37
+
38
+ /** Lit « a.b », « "A"."b" », « public.t » à partir de s[i] ; { parts, end } */
39
+ function readName(s, i) {
40
+ const parts = [];
41
+ for (;;) {
42
+ i = skipSpace(s, i);
43
+ if (s[i] === '"') {
44
+ let j = i + 1;
45
+ let name = '';
46
+ for (;;) {
47
+ const k = s.indexOf('"', j);
48
+ if (k < 0) return null;
49
+ name += s.slice(j, k);
50
+ if (s[k + 1] === '"') {
51
+ name += '"';
52
+ j = k + 2;
53
+ continue;
54
+ }
55
+ i = k + 1;
56
+ break;
57
+ }
58
+ parts.push({ name, quoted: true });
59
+ } else {
60
+ const m = /^[A-Za-z_\u0080-￿][A-Za-z0-9_$\u0080-￿]*/.exec(s.slice(i, i + 200));
61
+ if (!m) return null;
62
+ parts.push({ name: m[0], quoted: false });
63
+ i += m[0].length;
64
+ }
65
+ const j = skipSpace(s, i);
66
+ if (s[j] === '.') {
67
+ i = j + 1;
68
+ continue;
69
+ }
70
+ return { parts, end: i };
71
+ }
72
+ }
73
+
74
+ /** Saute espaces et commentaires (-- … et /* … *\/) */
75
+ function skipSpace(s, i) {
76
+ for (;;) {
77
+ while (i < s.length && (s[i] === ' ' || s[i] === '\n' || s[i] === '\t' || s[i] === '\r' || s[i] === '\f')) i++;
78
+ if (s[i] === '-' && s[i + 1] === '-') {
79
+ const k = s.indexOf('\n', i);
80
+ i = k < 0 ? s.length : k + 1;
81
+ continue;
82
+ }
83
+ if (s[i] === '/' && s[i + 1] === '*') {
84
+ const k = s.indexOf('*/', i + 2);
85
+ i = k < 0 ? s.length : k + 2;
86
+ continue;
87
+ }
88
+ return i;
89
+ }
90
+ }
91
+
92
+ /** Liste « (a, "B", c) » ; { cols, end } */
93
+ function readColumns(s, i) {
94
+ i = skipSpace(s, i);
95
+ if (s[i] !== '(') return null;
96
+ i++;
97
+ const cols = [];
98
+ for (;;) {
99
+ const n = readName(s, i);
100
+ if (!n || n.parts.length !== 1) return null;
101
+ cols.push(n.parts[0].quoted ? n.parts[0].name : n.parts[0].name.toLowerCase());
102
+ i = skipSpace(s, n.end);
103
+ if (s[i] === ',') {
104
+ i++;
105
+ continue;
106
+ }
107
+ if (s[i] === ')') return { cols, end: i + 1 };
108
+ return null;
109
+ }
110
+ }
111
+
112
+ // --- Valeurs vers COPY texte --------------------------------------------------
113
+
114
+ /** Échappement du format texte de COPY */
115
+ function copyEscape(v) {
116
+ if (v === null) return '\\N';
117
+ let out = '';
118
+ let last = 0;
119
+ for (let i = 0; i < v.length; i++) {
120
+ const c = v.charCodeAt(i);
121
+ let r = null;
122
+ if (c === 92) r = '\\\\';
123
+ else if (c === 10) r = '\\n';
124
+ else if (c === 13) r = '\\r';
125
+ else if (c === 9) r = '\\t';
126
+ if (r) {
127
+ out += v.slice(last, i) + r;
128
+ last = i + 1;
129
+ }
130
+ }
131
+ return last === 0 ? v : out + v.slice(last);
132
+ }
133
+
134
+ const E_ESCAPES = { n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', '\\': '\\', "'": "'", '"': '"' };
135
+
136
+ /**
137
+ * Lit une valeur littérale à partir de s[i] : { value (chaîne ou null), end }.
138
+ * Les conversions « ::type » sont ignorées (PostgreSQL convertit au chargement).
139
+ */
140
+ function readValue(s, i, ctx) {
141
+ i = skipSpace(s, i);
142
+ let value;
143
+ const c = s[i];
144
+ if (c === "'" || ((c === 'E' || c === 'e') && s[i + 1] === "'")) {
145
+ const escaped = c !== "'";
146
+ let j = escaped ? i + 2 : i + 1;
147
+ let v = '';
148
+ for (;;) {
149
+ const q = s.indexOf("'", j);
150
+ if (q < 0) throw new ConvertError('unterminated string', ctx);
151
+ let piece = s.slice(j, q);
152
+ if (escaped && piece.includes('\\')) {
153
+ // Un « \' » ne ferme pas la chaîne : on reprend après
154
+ let backslashes = 0;
155
+ for (let k = q - 1; k >= j && s[k] === '\\'; k--) backslashes++;
156
+ if (backslashes % 2 === 1) {
157
+ v += unescapeE(piece.slice(0, -1)) + "'";
158
+ j = q + 1;
159
+ continue;
160
+ }
161
+ piece = unescapeE(piece);
162
+ }
163
+ v += piece;
164
+ if (s[q + 1] === "'") {
165
+ v += "'";
166
+ j = q + 2;
167
+ continue;
168
+ }
169
+ i = q + 1;
170
+ break;
171
+ }
172
+ value = v;
173
+ } else if (c === '$') {
174
+ const m = /^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(s.slice(i, i + 70));
175
+ if (!m) throw new ConvertError('unexpected "$"', ctx);
176
+ const k = s.indexOf(m[0], i + m[0].length);
177
+ if (k < 0) throw new ConvertError('unterminated dollar-quoted string', ctx);
178
+ value = s.slice(i + m[0].length, k);
179
+ i = k + m[0].length;
180
+ } else {
181
+ const m = /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?/.exec(s.slice(i, i + 400));
182
+ if (m) {
183
+ value = m[0].startsWith('+') ? m[0].slice(1) : m[0];
184
+ i += m[0].length;
185
+ } else {
186
+ const w = /^[A-Za-z_][A-Za-z0-9_]*/.exec(s.slice(i, i + 64));
187
+ if (!w) throw new ConvertError(`unexpected "${s.slice(i, i + 12)}" in VALUES`, ctx);
188
+ const word = w[0].toLowerCase();
189
+ const after = skipSpace(s, i + w[0].length);
190
+ if (s[after] === '(' || s[after] === '[') {
191
+ throw new ConvertError(`${w[0]}(…) is not a plain value: only literal values can be seeded (convert it in the source, or load this table another way)`, ctx);
192
+ }
193
+ if (word === 'null') value = null;
194
+ else if (word === 'true' || word === 'false') value = word;
195
+ else if (word === 'default') throw new ConvertError('DEFAULT is not supported in a seed: give the value, or leave the column out of the column list', ctx);
196
+ else throw new ConvertError(`unexpected word "${w[0]}" in VALUES`, ctx);
197
+ i += w[0].length;
198
+ }
199
+ }
200
+ // Conversions : 'x'::type, ::character varying(255), ::timestamp without time zone, ::int[]
201
+ for (;;) {
202
+ const j = skipSpace(s, i);
203
+ if (s[j] !== ':' || s[j + 1] !== ':') return { value, end: i };
204
+ const m = /^::\s*(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_.]*)(?:\s+(?:without|with|time|zone|varying|precision)\b)*(?:\s*\([^)]*\))?(?:\s*\[\])*/i.exec(s.slice(j, j + 200));
205
+ if (!m) throw new ConvertError('unreadable type cast', ctx);
206
+ i = j + m[0].length;
207
+ }
208
+ }
209
+
210
+ function unescapeE(piece) {
211
+ return piece.replace(/\\(x[0-9A-Fa-f]{1,2}|[0-7]{1,3}|.)/gs, (_, e) => {
212
+ if (e[0] === 'x' && e.length > 1) return String.fromCharCode(parseInt(e.slice(1), 16));
213
+ if (/^[0-7]+$/.test(e)) return String.fromCharCode(parseInt(e, 8));
214
+ return E_ESCAPES[e] ?? e;
215
+ });
216
+ }
217
+
218
+ // --- Fichier SQL --------------------------------------------------------------
219
+
220
+ /**
221
+ * Analyseur SQL par morceaux. Pour chaque ligne de données :
222
+ * onRow(target, columns|null, copyLine)
223
+ * Les instructions entières (hors données COPY) sont découpées au « ; » hors
224
+ * chaînes, identifiants entre guillemets, commentaires et $$…$$.
225
+ */
226
+ class SqlSource {
227
+ constructor({ onRow, maxStatement = 768 * 1024 * 1024 } = {}) {
228
+ this.onRow = onRow;
229
+ this.maxStatement = maxStatement;
230
+ this.buf = '';
231
+ this.pos = 0; // jusqu'où buf a été parcouru sans trouver de fin d'instruction
232
+ this.state = null; // null | "'" | '"' | '--' | '/*' | '$tag$' | 'E'
233
+ this.line = 1; // ligne du début de buf
234
+ this.copy = null; // { target, columns } pendant les données d'un COPY
235
+ this.skipped = {}; // instructions ignorées, par mot de tête
236
+ this.mutations = 0; // UPDATE/DELETE/TRUNCATE ignorés (données qu'un seed ne sait pas rejouer)
237
+ }
238
+
239
+ push(chunk) {
240
+ this.buf += chunk;
241
+ this.drain(false);
242
+ }
243
+
244
+ end() {
245
+ this.drain(true);
246
+ if (this.copy) throw new ConvertError('COPY data not terminated by "\\."', { line: this.line, table: this.copy.target });
247
+ const rest = this.buf.slice(skipSpace(this.buf, 0));
248
+ if (rest) this.statement(rest);
249
+ this.buf = '';
250
+ }
251
+
252
+ drain(final) {
253
+ for (;;) {
254
+ if (this.copy) {
255
+ if (!this.copyData(final)) return;
256
+ continue;
257
+ }
258
+ const end = this.findEnd();
259
+ if (end < 0) {
260
+ if (this.buf.length > this.maxStatement) throw new ConvertError('statement too large (over 768 MB)', { line: this.line });
261
+ return;
262
+ }
263
+ const text = this.buf.slice(0, end);
264
+ this.buf = this.buf.slice(end + 1);
265
+ this.pos = 0;
266
+ const startLine = this.line;
267
+ this.statement(text, startLine);
268
+ this.line += countLines(text) + 0;
269
+ // le « ; » lui-même n'ajoute pas de ligne
270
+ }
271
+ }
272
+
273
+ /** Index du « ; » qui termine l'instruction en tête de buf, ou -1 */
274
+ findEnd() {
275
+ const s = this.buf;
276
+ let i = this.pos;
277
+ let st = this.state;
278
+ while (i < s.length) {
279
+ if (st === null) {
280
+ // Saut rapide jusqu'au prochain caractère qui compte
281
+ const m = /[;'"\-/$]|[Ee](?=')/g;
282
+ m.lastIndex = i;
283
+ const r = m.exec(s);
284
+ if (!r) {
285
+ // Un E en fin de morceau peut ouvrir une chaîne E'…' : on attend le caractère suivant
286
+ i = s.length > i && /[Ee]/.test(s[s.length - 1]) ? s.length - 1 : s.length;
287
+ break;
288
+ }
289
+ i = r.index;
290
+ const c = s[i];
291
+ if (c === ';') {
292
+ this.state = null;
293
+ return i;
294
+ }
295
+ if (c === "'") (st = "'"), i++;
296
+ else if (c === 'E' || c === 'e') {
297
+ // E'…' seulement si E n'est pas la fin d'un mot
298
+ const prev = s[i - 1];
299
+ if (i > 0 && /[A-Za-z0-9_]/.test(prev)) i++;
300
+ else (st = 'E'), (i += 2);
301
+ } else if (c === '"') (st = '"'), i++;
302
+ else if (c === '-') {
303
+ if (s[i + 1] === '-') (st = '--'), (i += 2);
304
+ else if (i + 1 >= s.length) break;
305
+ else i++;
306
+ } else if (c === '/') {
307
+ if (s[i + 1] === '*') (st = '/*'), (i += 2);
308
+ else if (i + 1 >= s.length) break;
309
+ else i++;
310
+ } else if (c === '$') {
311
+ const t = /^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(s.slice(i, i + 70));
312
+ if (t && !/[A-Za-z0-9_]/.test(s[i - 1] || '')) (st = t[0]), (i += t[0].length);
313
+ else if (!t && s.length - i < 70 && /^\$[A-Za-z0-9_]*$/.test(s.slice(i))) break;
314
+ else i++;
315
+ }
316
+ } else if (st === "'") {
317
+ const q = s.indexOf("'", i);
318
+ if (q < 0) {
319
+ i = s.length;
320
+ break;
321
+ }
322
+ if (q + 1 >= s.length) {
323
+ i = q;
324
+ break;
325
+ }
326
+ if (s[q + 1] === "'") i = q + 2;
327
+ else (st = null), (i = q + 1);
328
+ } else if (st === 'E') {
329
+ const q = /\\.|''|'/gs;
330
+ q.lastIndex = i;
331
+ let r;
332
+ let done = false;
333
+ while ((r = q.exec(s))) {
334
+ if (r[0] === "'") {
335
+ if (r.index + 1 >= s.length) {
336
+ i = r.index;
337
+ done = 'wait';
338
+ break;
339
+ }
340
+ st = null;
341
+ i = r.index + 1;
342
+ done = true;
343
+ break;
344
+ }
345
+ if (r[0].length === 2 && r.index + 2 > s.length) break;
346
+ }
347
+ if (done === 'wait') break;
348
+ if (!done) {
349
+ // reprendre au dernier « \ » incomplet éventuel
350
+ i = s.endsWith('\\') ? s.length - 1 : s.length;
351
+ break;
352
+ }
353
+ } else if (st === '"') {
354
+ const q = s.indexOf('"', i);
355
+ if (q < 0) {
356
+ i = s.length;
357
+ break;
358
+ }
359
+ if (q + 1 >= s.length) {
360
+ i = q;
361
+ break;
362
+ }
363
+ if (s[q + 1] === '"') i = q + 2;
364
+ else (st = null), (i = q + 1);
365
+ } else if (st === '--') {
366
+ const q = s.indexOf('\n', i);
367
+ if (q < 0) {
368
+ i = s.length;
369
+ break;
370
+ }
371
+ st = null;
372
+ i = q + 1;
373
+ } else if (st === '/*') {
374
+ const q = s.indexOf('*/', i);
375
+ if (q < 0) {
376
+ i = Math.max(i, s.length - 1);
377
+ break;
378
+ }
379
+ st = null;
380
+ i = q + 2;
381
+ } else {
382
+ const q = s.indexOf(st, i);
383
+ if (q < 0) {
384
+ i = Math.max(i, s.length - st.length + 1);
385
+ break;
386
+ }
387
+ i = q + st.length;
388
+ st = null;
389
+ }
390
+ }
391
+ this.pos = i;
392
+ this.state = st;
393
+ return -1;
394
+ }
395
+
396
+ statement(text, line = this.line) {
397
+ let i = skipSpace(text, 0);
398
+ if (i >= text.length) return;
399
+ const lineAt = line + countLines(text.slice(0, i));
400
+ const head = /^[A-Za-z]+/.exec(text.slice(i, i + 20));
401
+ const word = head ? head[0].toUpperCase() : '?';
402
+ if (word === 'INSERT') return this.insert(text, i + 6, lineAt);
403
+ if (word === 'COPY') return this.copyStart(text, i + 4, lineAt);
404
+ if (word === 'UPDATE' || word === 'DELETE' || word === 'TRUNCATE' || word === 'MERGE') this.mutations++;
405
+ this.skipped[word] = (this.skipped[word] || 0) + 1;
406
+ }
407
+
408
+ insert(s, i, line) {
409
+ i = skipSpace(s, i);
410
+ if (!/^INTO\b/i.test(s.slice(i, i + 5))) throw new ConvertError('INSERT without INTO', { line });
411
+ const n = readName(s, i + 4);
412
+ if (!n) throw new ConvertError('unreadable table name after INSERT INTO', { line });
413
+ const target = targetOf(qualify(n.parts));
414
+ const ctx = { line, table: target };
415
+ i = skipSpace(s, n.end);
416
+ let columns = null;
417
+ if (s[i] === '(') {
418
+ const c = readColumns(s, i);
419
+ if (!c) throw new ConvertError('unreadable column list', ctx);
420
+ columns = c.cols;
421
+ i = skipSpace(s, c.end);
422
+ }
423
+ if (/^OVERRIDING\s+(SYSTEM|USER)\s+VALUE\b/i.test(s.slice(i, i + 40))) i = skipSpace(s, i + /^OVERRIDING\s+\w+\s+VALUE/i.exec(s.slice(i, i + 40))[0].length);
424
+ if (!/^VALUES\b/i.test(s.slice(i, i + 7))) {
425
+ throw new ConvertError(/^SELECT\b/i.test(s.slice(i, i + 7)) ? 'INSERT … SELECT is not data: it can only run against a database' : 'INSERT without VALUES', ctx);
426
+ }
427
+ i += 6;
428
+ for (;;) {
429
+ i = skipSpace(s, i);
430
+ if (s[i] !== '(') throw new ConvertError('"(" expected in VALUES', ctx);
431
+ i++;
432
+ const vals = [];
433
+ for (;;) {
434
+ const v = readValue(s, i, ctx);
435
+ vals.push(copyEscape(v.value));
436
+ i = skipSpace(s, v.end);
437
+ if (s[i] === ',') {
438
+ i++;
439
+ continue;
440
+ }
441
+ if (s[i] === ')') {
442
+ i++;
443
+ break;
444
+ }
445
+ throw new ConvertError(`"," or ")" expected in VALUES, found "${s.slice(i, i + 10)}"`, ctx);
446
+ }
447
+ if (columns && vals.length !== columns.length) throw new ConvertError(`${vals.length} values for ${columns.length} columns`, ctx);
448
+ this.onRow(target, columns, vals.join('\t'));
449
+ i = skipSpace(s, i);
450
+ if (s[i] === ',') {
451
+ i++;
452
+ continue;
453
+ }
454
+ if (i >= s.length) return;
455
+ if (/^ON\s+CONFLICT\b/i.test(s.slice(i, i + 20))) return; // le chargement fait déjà la mise à jour
456
+ if (/^RETURNING\b/i.test(s.slice(i, i + 10))) return;
457
+ throw new ConvertError(`unexpected "${s.slice(i, i + 16)}" after VALUES`, ctx);
458
+ }
459
+ }
460
+
461
+ copyStart(s, i, line) {
462
+ const n = readName(s, i);
463
+ if (!n) throw new ConvertError('unreadable table name after COPY', { line });
464
+ const target = targetOf(qualify(n.parts));
465
+ i = skipSpace(s, n.end);
466
+ let columns = null;
467
+ if (s[i] === '(') {
468
+ const c = readColumns(s, i);
469
+ if (!c) throw new ConvertError('unreadable column list', { line, table: target });
470
+ columns = c.cols;
471
+ i = skipSpace(s, c.end);
472
+ }
473
+ const rest = s.slice(i).replace(/\s+/g, ' ').trim();
474
+ if (!/^FROM stdin$/i.test(rest)) {
475
+ throw new ConvertError(`only "COPY … FROM stdin" in text format is supported (found "${rest.slice(0, 40)}")`, { line, table: target });
476
+ }
477
+ // Les données commencent après la fin de ligne qui suit le « ; »
478
+ this.copy = { target, columns, started: false };
479
+ }
480
+
481
+ /** Lignes de données d'un COPY jusqu'à « \. » ; false s'il faut plus de texte */
482
+ copyData(final) {
483
+ let s = this.buf;
484
+ if (!this.copy.started) {
485
+ const nl = s.indexOf('\n');
486
+ if (nl < 0) return final ? ((this.buf = ''), false) : false;
487
+ s = s.slice(nl + 1);
488
+ this.line += 1;
489
+ this.copy.started = true;
490
+ }
491
+ let i = 0;
492
+ for (;;) {
493
+ const nl = s.indexOf('\n', i);
494
+ if (nl < 0) {
495
+ if (final && i < s.length) throw new ConvertError('COPY data not terminated by "\\."', { line: this.line, table: this.copy.target });
496
+ this.buf = s.slice(i);
497
+ this.pos = 0;
498
+ return false;
499
+ }
500
+ let row = s.slice(i, nl);
501
+ if (row.endsWith('\r')) row = row.slice(0, -1);
502
+ i = nl + 1;
503
+ this.line++;
504
+ if (row === '\\.') {
505
+ this.copy = null;
506
+ this.buf = s.slice(i);
507
+ this.pos = 0;
508
+ this.state = null;
509
+ return true;
510
+ }
511
+ this.onRow(this.copy.target, this.copy.columns, row);
512
+ }
513
+ }
514
+ }
515
+
516
+ function countLines(s) {
517
+ let n = 0;
518
+ for (let i = s.indexOf('\n'); i >= 0; i = s.indexOf('\n', i + 1)) n++;
519
+ return n;
520
+ }
521
+
522
+ // --- Fichier CSV --------------------------------------------------------------
523
+
524
+ /**
525
+ * CSV (RFC 4180) vers COPY texte : première ligne = noms des colonnes.
526
+ * Champ vide sans guillemets = NULL, "" = chaîne vide (comme COPY … CSV).
527
+ */
528
+ class CsvSource {
529
+ constructor({ target, onRow, delimiter } = {}) {
530
+ this.target = target;
531
+ this.onRow = onRow;
532
+ this.delimiter = delimiter || null;
533
+ this.columns = null;
534
+ this.buf = '';
535
+ this.line = 1;
536
+ this.field = '';
537
+ this.quotedField = false;
538
+ this.inQuote = false;
539
+ this.record = [];
540
+ this.started = false;
541
+ }
542
+
543
+ push(chunk) {
544
+ if (!this.started) {
545
+ if (chunk.charCodeAt(0) === 0xfeff) chunk = chunk.slice(1);
546
+ this.started = true;
547
+ }
548
+ if (!this.delimiter) {
549
+ const firstLine = (this.buf + chunk).split('\n')[0];
550
+ if (!(this.buf + chunk).includes('\n') && chunk.length) {
551
+ this.buf += chunk;
552
+ return;
553
+ }
554
+ this.delimiter = (firstLine.match(/;/g) || []).length > (firstLine.match(/,/g) || []).length ? ';' : (firstLine.match(/\t/g) || []).length > (firstLine.match(/,/g) || []).length ? '\t' : ',';
555
+ chunk = this.buf + chunk;
556
+ this.buf = '';
557
+ }
558
+ this.scan(chunk);
559
+ }
560
+
561
+ scan(s) {
562
+ const d = this.delimiter;
563
+ let i = 0;
564
+ while (i < s.length) {
565
+ const c = s[i];
566
+ if (this.pendingQuote) {
567
+ // « " » en fin du morceau précédent : « "" » (guillemet) ou fin du champ entre guillemets
568
+ this.pendingQuote = false;
569
+ if (c === '"') {
570
+ this.field += '"';
571
+ i++;
572
+ continue;
573
+ }
574
+ this.inQuote = false;
575
+ continue;
576
+ }
577
+ if (this.inQuote) {
578
+ if (c === '"') {
579
+ if (i + 1 >= s.length) {
580
+ this.pendingQuote = true;
581
+ i++;
582
+ continue;
583
+ }
584
+ if (s[i + 1] === '"') {
585
+ this.field += '"';
586
+ i += 2;
587
+ continue;
588
+ }
589
+ this.inQuote = false;
590
+ i++;
591
+ continue;
592
+ }
593
+ const q = s.indexOf('"', i);
594
+ const piece = q < 0 ? s.slice(i) : s.slice(i, q);
595
+ this.field += piece;
596
+ for (let k = piece.indexOf('\n'); k >= 0; k = piece.indexOf('\n', k + 1)) this.line++;
597
+ i = q < 0 ? s.length : q;
598
+ continue;
599
+ }
600
+ if (c === '"' && this.field === '' && !this.quotedField) {
601
+ this.inQuote = true;
602
+ this.quotedField = true;
603
+ i++;
604
+ } else if (c === d) {
605
+ this.pushField();
606
+ i++;
607
+ } else if (c === '\n') {
608
+ this.pushField();
609
+ this.endRecord();
610
+ this.line++;
611
+ i++;
612
+ } else if (c === '\r') {
613
+ i++;
614
+ } else {
615
+ // morceau sans caractère spécial
616
+ let j = i + 1;
617
+ while (j < s.length && s[j] !== d && s[j] !== '\n' && s[j] !== '\r' && s[j] !== '"') j++;
618
+ this.field += s.slice(i, j);
619
+ i = j;
620
+ }
621
+ }
622
+ }
623
+
624
+ pushField() {
625
+ this.record.push(this.quotedField || this.field !== '' ? this.field : null);
626
+ this.field = '';
627
+ this.quotedField = false;
628
+ }
629
+
630
+ endRecord() {
631
+ const r = this.record;
632
+ this.record = [];
633
+ if (r.length === 1 && r[0] === null) return; // ligne vide
634
+ if (!this.columns) {
635
+ const cols = r.map((c) => String(c ?? '').trim());
636
+ if (cols.some((c) => !c)) throw new ConvertError('the CSV header has an empty column name', { line: this.line, table: this.target });
637
+ const seen = new Set();
638
+ for (const c of cols) {
639
+ if (seen.has(c)) throw new ConvertError(`column "${c}" appears twice in the CSV header`, { line: this.line, table: this.target });
640
+ seen.add(c);
641
+ }
642
+ this.columns = cols;
643
+ return;
644
+ }
645
+ 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.map(copyEscape).join('\t'));
647
+ }
648
+
649
+ end() {
650
+ if (!this.delimiter && this.buf) {
651
+ const b = this.buf;
652
+ this.buf = '';
653
+ this.delimiter = ',';
654
+ this.scan(b);
655
+ }
656
+ if (this.pendingQuote) (this.pendingQuote = false), (this.inQuote = false);
657
+ if (this.inQuote) throw new ConvertError('unterminated quoted field', { line: this.line, table: this.target });
658
+ if (this.field !== '' || this.record.length || this.quotedField) {
659
+ this.pushField();
660
+ this.endRecord();
661
+ }
662
+ if (!this.columns) throw new ConvertError('empty CSV file', { table: this.target });
663
+ }
664
+ }
665
+
666
+ /** « schéma.table » tapé (--table) vers la forme du registre */
667
+ function parseTarget(text) {
668
+ const n = readName(String(text || ''), 0);
669
+ if (!n || n.end !== String(text).length || n.parts.length > 2) return null;
670
+ return targetOf(qualify(n.parts));
671
+ }
672
+
673
+ module.exports = { SqlSource, CsvSource, ConvertError, copyEscape, parseTarget, qualify, targetOf, readValue };