@otwdesign/db-core 1.4.1 → 1.5.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.
Files changed (62) hide show
  1. package/README.md +38 -0
  2. package/dist/backup/api.js +2 -33
  3. package/dist/backup/api.js.map +1 -1
  4. package/dist/body.d.ts +17 -0
  5. package/dist/body.js +88 -0
  6. package/dist/body.js.map +1 -0
  7. package/dist/browser.d.ts +1 -0
  8. package/dist/drivers/mysql-connection.d.ts +101 -0
  9. package/dist/drivers/mysql-connection.js +204 -0
  10. package/dist/drivers/mysql-connection.js.map +1 -0
  11. package/dist/drivers/mysql-import.d.ts +22 -0
  12. package/dist/drivers/mysql-import.js +688 -0
  13. package/dist/drivers/mysql-import.js.map +1 -0
  14. package/dist/drivers/mysql.d.ts +11 -1
  15. package/dist/drivers/mysql.js +87 -97
  16. package/dist/drivers/mysql.js.map +1 -1
  17. package/dist/errors.d.ts +4 -0
  18. package/dist/errors.js.map +1 -1
  19. package/dist/handler.d.ts +31 -0
  20. package/dist/handler.js +93 -9
  21. package/dist/handler.js.map +1 -1
  22. package/dist/import/api.d.ts +65 -0
  23. package/dist/import/api.js +1282 -0
  24. package/dist/import/api.js.map +1 -0
  25. package/dist/import/audit.d.ts +47 -0
  26. package/dist/import/audit.js +434 -0
  27. package/dist/import/audit.js.map +1 -0
  28. package/dist/import/charsets.d.ts +25 -0
  29. package/dist/import/charsets.js +39 -0
  30. package/dist/import/charsets.js.map +1 -0
  31. package/dist/import/frames.d.ts +26 -0
  32. package/dist/import/frames.js +158 -0
  33. package/dist/import/frames.js.map +1 -0
  34. package/dist/import/grants.d.ts +26 -0
  35. package/dist/import/grants.js +122 -0
  36. package/dist/import/grants.js.map +1 -0
  37. package/dist/import/protocol.d.ts +462 -0
  38. package/dist/import/protocol.js +72 -0
  39. package/dist/import/protocol.js.map +1 -0
  40. package/dist/import/shared.d.ts +3 -0
  41. package/dist/import/shared.js +9 -0
  42. package/dist/import/shared.js.map +1 -0
  43. package/dist/index.d.ts +1 -0
  44. package/dist/types.d.ts +308 -2
  45. package/package.json +7 -2
  46. package/src/backup/api.ts +2 -33
  47. package/src/body.ts +94 -0
  48. package/src/browser.ts +24 -0
  49. package/src/drivers/mysql-connection.ts +282 -0
  50. package/src/drivers/mysql-import.ts +769 -0
  51. package/src/drivers/mysql.ts +96 -107
  52. package/src/errors.ts +2 -0
  53. package/src/handler.ts +126 -8
  54. package/src/import/api.ts +1530 -0
  55. package/src/import/audit.ts +467 -0
  56. package/src/import/charsets.ts +46 -0
  57. package/src/import/frames.ts +191 -0
  58. package/src/import/grants.ts +117 -0
  59. package/src/import/protocol.ts +540 -0
  60. package/src/import/shared.ts +8 -0
  61. package/src/index.ts +24 -0
  62. package/src/types.ts +319 -2
@@ -0,0 +1,688 @@
1
+ import { ConnectionError, DbAdminError, QueryError } from "../errors.js";
2
+ import { READ_ALIKE, READ_ALIKE_IN_ASCII } from "../import/charsets.js";
3
+ import { backtick, serverOf } from "./mysql.js";
4
+ import { connectionOptions, killQuery, watchStatement, } from "./mysql-connection.js";
5
+ import { whole } from "./sql.js";
6
+ /*
7
+ * One import's connection to MySQL or MariaDB: the file's statements, one a round trip, on a
8
+ * session that is the file's alone from its first statement to its last. Loaded when the first
9
+ * import opens.
10
+ *
11
+ * What the session is after a statement is never read from the statement's text. The server
12
+ * says it: whether a transaction is open with every answer, and the rest (the sql_mode, with
13
+ * NO_BACKSLASH_ESCAPES and ANSI_QUOTES or without, the character set statements are read in, and
14
+ * the database selected) when it is asked, which is whenever an answer says the session changed,
15
+ * or could not say. An answer that says nothing is taken for "nothing changed" only on a
16
+ * connection that has shown it does say, for each way a file can set a setting: on any other,
17
+ * MariaDB's among them, the server is asked after every statement.
18
+ */
19
+ /** The URL's options an import's connection takes. Where and who are the URL's own parts. */
20
+ const URL_OPTIONS = new Set(['ssl', 'socketPath', 'connectTimeout']);
21
+ /** The answer to two statements sent as one, from a connection that runs one at a time. */
22
+ const SYNTAX_ERROR = 1064;
23
+ /** "Query was empty": the statement is nothing on this server. */
24
+ const EMPTY_QUERY = 1065;
25
+ /** "Got a packet bigger than 'max_allowed_packet' bytes", after which the server hangs up. */
26
+ const PACKET_TOO_LARGE = 1153;
27
+ /**
28
+ * "This version of MySQL doesn't yet support …": the server's number for what it does not take,
29
+ * and the nearest to a statement an import does not send.
30
+ */
31
+ const NOT_SUPPORTED = 1235;
32
+ /** What a statement's packet holds beside its text, at most: the command, and two counts. */
33
+ const PACKET_HEAD = 3;
34
+ /**
35
+ * The most a statement's packet holds here, in bytes, whatever the server takes: four short of
36
+ * what one packet of the protocol does (16 MiB less one). mysql2 (3.24.6) sends an empty packet
37
+ * after one that comes closer than that, which the server reads as the next statement, and it
38
+ * answers "Got packets out of order" to everything after. Anything longer goes as several
39
+ * packets, which no import needs: the API takes 4 MiB of statements at most in one request.
40
+ */
41
+ const PACKET_MOST = 0xffffff - 4;
42
+ /**
43
+ * The server's status with every OK: a transaction is open. The status has a bit for
44
+ * NO_BACKSLASH_ESCAPES too (0x0200), which is not read: the server sets it where a SET sql_mode
45
+ * runs and leaves it when a routine that ran one returns and its caller's mode is put back, so
46
+ * from then on it is wrong with every answer.
47
+ */
48
+ const IN_TRANSACTION = 0x0001;
49
+ /** Something of the session changed with this statement, as far as the server reports it. */
50
+ const SESSION_CHANGED = 0x4000;
51
+ /**
52
+ * How long a statement that was told to stop has to answer, from when its kill was answered or
53
+ * given up on, before its connection is closed under it; and how long the rollback at the end
54
+ * has.
55
+ */
56
+ const REPLY_MS = 120_000;
57
+ /** The time limit of the connection's own statements, which ask and change nothing. */
58
+ const OWN_MS = 30_000;
59
+ /** How long the server has to hang up after the goodbye. */
60
+ const GOODBYE_MS = 5_000;
61
+ /** How long an import may sit unused, unless whoever opens it says: 5 minutes. */
62
+ const IDLE_MS = 300_000;
63
+ /** What the server keeps an unused connection for beyond that, in seconds. */
64
+ const IDLE_MARGIN_S = 60;
65
+ /** The longest wait_timeout a server takes, in seconds: a year. */
66
+ const WAIT_MOST_S = 31_536_000;
67
+ /** The longest wait a timer keeps, in milliseconds: past it, it fires at once. */
68
+ const TIMER_MOST_MS = 2 ** 31 - 1;
69
+ /**
70
+ * What the server reports of the session with each answer: that something of it changed, which
71
+ * database is selected, and the settings in the list. Each of the two tells when the other is
72
+ * turned off: the list names the switch of the report of changes, and the report of changes
73
+ * tells of any change to the list, or to the report of the database. So a file can't turn one
74
+ * off unseen. The rest of the list is what a file's statements are read by: sql_mode,
75
+ * autocommit, and the character set, which mysql2 follows (see `#answer`) and which decides
76
+ * what is sent (see `#misread`).
77
+ */
78
+ const REPORTS = [
79
+ 'session_track_schema = ON',
80
+ 'session_track_state_change = ON',
81
+ "session_track_system_variables = 'sql_mode,character_set_client,autocommit,session_track_state_change'",
82
+ ].join(', ');
83
+ /**
84
+ * Sets a setting of the list to what it is, in each way a file can name one: nothing of the
85
+ * session changes, and the server reports the setting as changed all the same, wherever it
86
+ * reports that way at all.
87
+ *
88
+ * The settings above say what the server would report, not whether it does. It reports only to a
89
+ * client it granted that at the handshake (CLIENT_SESSION_TRACK), which a proxy in between may
90
+ * not pass on: every SET above still succeeds then and reads back as set, and no answer ever
91
+ * says the session changed. And it may report some ways and not others: MariaDB (11.4) does not
92
+ * report a SET that names each of its settings as @@name, whether plain, in a comment for
93
+ * versions, prepared or in an EXECUTE IMMEDIATE. So a report of each way has to be seen to arrive.
94
+ */
95
+ const PROOFS = [
96
+ 'SET SESSION sql_mode = @@SESSION.sql_mode',
97
+ 'SET sql_mode = @@SESSION.sql_mode',
98
+ 'SET @@SESSION.sql_mode = @@SESSION.sql_mode',
99
+ 'SET @@sql_mode = @@SESSION.sql_mode',
100
+ ];
101
+ /** A character beyond ASCII. */
102
+ const BEYOND_ASCII = /\P{ASCII}/u;
103
+ /**
104
+ * The connection's character set once more, by name: the server then gives the session its own
105
+ * collation for utf8mb4, as the `mysql` client's has. The handshake names a collation by number,
106
+ * and no number is every server's own; mysql2's is utf8mb4_unicode_ci. Under that one, a file
107
+ * with no SET NAMES of its own has its variables and routines made in another collation than
108
+ * its columns, and a `WHERE name = @name` is refused as an illegal mix of the two (1267).
109
+ */
110
+ const NAMES = 'SET NAMES utf8mb4';
111
+ /**
112
+ * A question of the connection's own, answered with one row whatever the session has set for
113
+ * its SELECTs. Each value as bytes: a file may ask for its results in any character set, and
114
+ * bytes are sent as they are. Its own LIMIT comes before the session's sql_select_limit, which
115
+ * at 0 would leave it no row.
116
+ */
117
+ const question = (values) => `SELECT ${values.map((value) => `CAST(${value} AS BINARY)`).join(', ')} LIMIT 1`;
118
+ /** The session as only asking tells it, and the reports as they are now. */
119
+ const ASK = question([
120
+ '@@SESSION.sql_mode',
121
+ 'DATABASE()',
122
+ '@@SESSION.character_set_client',
123
+ '@@SESSION.session_track_system_variables',
124
+ '@@SESSION.session_track_state_change',
125
+ '@@SESSION.session_track_schema',
126
+ ]);
127
+ /** The connection as it opened. */
128
+ const OPENED = question([
129
+ 'CONNECTION_ID()',
130
+ 'VERSION()',
131
+ '@@SESSION.max_allowed_packet',
132
+ '@@SESSION.wait_timeout',
133
+ ]);
134
+ const STUCK = 'The statement did not stop when it was asked to, so the import’s connection was closed under it. Whether it finished is not known.';
135
+ const KILL_UNANSWERED = 'A request to stop a statement got no answer and could still stop a later one, so the import’s connection was closed.';
136
+ /**
137
+ * One connection's settings for an import of the server at `url`. Not the driver's own (see
138
+ * `connectionOptions`): a file must run as it would in the `mysql` client, so nothing of the URL
139
+ * that changes how statements are read or sent gets through, its character set, flags and time
140
+ * zone among them.
141
+ */
142
+ export function importOptions(url) {
143
+ // mysql2 reads mysql:// addresses; mariadb:// is the same thing.
144
+ const address = new URL(url.replace(/^mariadb:/i, 'mysql:'));
145
+ for (const key of [...address.searchParams.keys()]) {
146
+ if (!URL_OPTIONS.has(key))
147
+ address.searchParams.delete(key);
148
+ }
149
+ return {
150
+ uri: address.href,
151
+ // One statement a query, whoever asked otherwise: mysql2 drops a flag taken away. And as the
152
+ // `mysql` client connects: a function's name stays a name before a space, rows changed are
153
+ // counted and not rows matched, and the server can't ask this process for a file.
154
+ flags: ['-MULTI_STATEMENTS', '-IGNORE_SPACE', '-FOUND_ROWS', '-LOCAL_FILES'],
155
+ // For its character set, the wire's. The session's collation is set as it opens (see NAMES).
156
+ charset: 'UTF8MB4_UNICODE_CI',
157
+ connectAttributes: { program_name: 'otw-db' },
158
+ };
159
+ }
160
+ /**
161
+ * Opens one import's connection to the server at `url`, with `mysql` as mysql2. It answers once
162
+ * the connection has proved it runs one statement a query, and the server reports its session.
163
+ *
164
+ * `idleMs` is how long the import may sit unused between statements: the server is asked to keep
165
+ * the connection a minute longer than that, where it would drop it sooner. `closed` is called
166
+ * once, when the connection has gone, however it went.
167
+ */
168
+ export async function openImporter(mysql, url, { idleMs = IDLE_MS, closed = () => { } } = {}) {
169
+ const keepS = Math.min(Math.ceil(idleMs / 1_000) + IDLE_MARGIN_S, WAIT_MOST_S);
170
+ if (!(idleMs > 0) || !Number.isSafeInteger(keepS)) {
171
+ throw new DbAdminError(`${idleMs} isn't a time in milliseconds.`, 400, 'bad-request');
172
+ }
173
+ let core;
174
+ try {
175
+ const connection = await mysql.createConnection(importOptions(url));
176
+ // The connection underneath takes a statement without a callback; the promise one doesn't.
177
+ core = connection.connection;
178
+ }
179
+ catch (error) {
180
+ throw new ConnectionError(`Could not connect to MySQL: ${error.message}`);
181
+ }
182
+ const kill = (thread) => killQuery(mysql, connectionOptions(url), thread);
183
+ const importer = new MySqlImporter(core, kill, closed);
184
+ await importer.open(keepS);
185
+ return importer;
186
+ }
187
+ class MySqlImporter {
188
+ #target;
189
+ #core;
190
+ /** KILL QUERY for this connection, on one of its own. */
191
+ #kill;
192
+ /** Told once, when the connection has gone, however it went. */
193
+ #closed;
194
+ /** The character set its text goes over the wire in, as the connection opened: utf8mb4. */
195
+ #wire;
196
+ /** The session's max_allowed_packet, in bytes. */
197
+ #packet = 0;
198
+ /** The session as last asked; its character set none known, under which none is sent. */
199
+ #session = {
200
+ inTransaction: false,
201
+ noBackslashEscapes: false,
202
+ ansiQuotes: false,
203
+ database: null,
204
+ characterSet: '',
205
+ };
206
+ /** The server's reports of the session as they were set. */
207
+ #reports = '';
208
+ /**
209
+ * An answer that reports no change means none: the reports were seen to arrive on this
210
+ * connection for each way of setting a setting, and are still set as they were. Otherwise
211
+ * every statement is asked after.
212
+ */
213
+ #reported = false;
214
+ /** The watch on the file's last statement: what `stop()` stops, while that one runs. */
215
+ #stoppable = null;
216
+ /** A statement of the file's was sent and has not answered. */
217
+ #unanswered = false;
218
+ /** What runs now: a statement and all that is asked after it. */
219
+ #running = null;
220
+ /** `end()` was called: from then on nothing of the file's starts. */
221
+ #ended = false;
222
+ #ending = null;
223
+ /** Why the connection is of no more use, once it is. */
224
+ #gone = null;
225
+ /** The same, when it went other than by `end()`. */
226
+ #lost = null;
227
+ /** The connection went under a statement of the file's: whether that one finished is not known. */
228
+ #doubt = false;
229
+ #listeners = [];
230
+ /**
231
+ * Whoever waits on a statement's answer, to be told when the connection goes and no answer
232
+ * can come. Each is here only while it waits: an import has statements by the million, and
233
+ * what one of them left behind would be kept for all of them.
234
+ */
235
+ #waiting = new Set();
236
+ constructor(core, kill, closed) {
237
+ this.#core = core;
238
+ this.#kill = kill;
239
+ this.#closed = closed;
240
+ this.#wire = core.config.charsetNumber;
241
+ // mysql2 tells the connection, and not the statement, of a connection that went under a
242
+ // statement sent without a callback; and with no listener, that error is the process's end.
243
+ core.on('error', (error) => {
244
+ this.#lose(new ConnectionError(`The import’s connection was lost: ${error.message}`));
245
+ });
246
+ }
247
+ get target() {
248
+ return this.#target;
249
+ }
250
+ /**
251
+ * Proves the connection runs one statement a query, gives its session the server's own
252
+ * collation, has the server keep it for `keepS` seconds unused and report its session, sees
253
+ * whether those reports arrive for each way of setting a setting, and reads where it is. A
254
+ * connection that fails any of it is closed; one whose reports do not all arrive is asked
255
+ * after every statement instead.
256
+ */
257
+ async open(keepS) {
258
+ // No kill can be sent for these: the connection's id isn't known before they answer.
259
+ const late = setTimeout(() => this.#lose(new ConnectionError(`MySQL did not answer within ${OWN_MS} ms.`)), OWN_MS);
260
+ try {
261
+ const two = await this.#answer('DO 0; DO 0');
262
+ if (two.error?.errno !== SYNTAX_ERROR) {
263
+ throw new DbAdminError('This connection would run two statements sent as one, so no import can use it. Nothing of the file was sent.', 500, 'unsafe-connection');
264
+ }
265
+ const send = (sql, row) => this.#answer(sql, row);
266
+ const [thread, version, packet, wait] = await this.#one(OPENED, 4, send);
267
+ const names = await this.#answer(NAMES);
268
+ if (names.error)
269
+ throw refused(names.error);
270
+ const longer = Number(wait) < keepS ? `, wait_timeout = ${whole(keepS)}` : '';
271
+ const set = await this.#answer(`SET SESSION ${REPORTS}${longer}`);
272
+ if (set.error)
273
+ throw refused(set.error);
274
+ const proofs = [];
275
+ for (const proof of PROOFS)
276
+ proofs.push(await this.#answer(proof));
277
+ const { sqlMode, reports, ...session } = await this.#ask(send);
278
+ this.#reports = reports;
279
+ this.#reported = proofs.every(sessionChanged);
280
+ this.#packet = whole(Number(packet));
281
+ this.#session = { inTransaction: inTransaction(set.status), ...session };
282
+ this.#target = { ...serverOf(version ?? ''), thread: whole(Number(thread)), sqlMode };
283
+ }
284
+ catch (error) {
285
+ this.#lose(error);
286
+ throw error;
287
+ }
288
+ finally {
289
+ clearTimeout(late);
290
+ }
291
+ }
292
+ use(database) {
293
+ return this.#alone(async () => {
294
+ const reply = await this.#statement(`USE ${backtick(database)}`, OWN_MS);
295
+ if (reply.error)
296
+ throw refused(reply.error);
297
+ return this.#after(reply);
298
+ });
299
+ }
300
+ run(sql, { timeoutMs }) {
301
+ return this.#alone(async () => {
302
+ const limit = timeLimit(timeoutMs);
303
+ const unsent = this.#tooLong(sql) ?? this.#misread(sql);
304
+ if (unsent)
305
+ return { error: unsent };
306
+ const reply = await this.#statement(sql, limit, { ofFile: true });
307
+ const nothing = reply.error?.errno === EMPTY_QUERY;
308
+ if (reply.error && !nothing)
309
+ return { error: reply.error };
310
+ const done = { affected: reply.affected, warnings: reply.warnings, rows: reply.rows };
311
+ // The server has answered for it. That stands whatever comes of the connection after: a
312
+ // statement that ran and is not counted would be run again.
313
+ const session = await this.#sessionAfter(reply, nothing);
314
+ return session ? { ...done, ...session } : { ...done, lost: this.#gone };
315
+ });
316
+ }
317
+ /**
318
+ * The session after a statement of the file's that ran: null when the connection went before
319
+ * it could say. `nothing` is a statement with nothing to run, so nothing changed: the session
320
+ * is as its last statement left it, while there is one.
321
+ */
322
+ async #sessionAfter(reply, nothing) {
323
+ if (nothing)
324
+ return this.#gone ? null : this.#session;
325
+ try {
326
+ return await this.#after(reply);
327
+ }
328
+ catch (error) {
329
+ if (error !== this.#gone)
330
+ throw error;
331
+ return null;
332
+ }
333
+ }
334
+ state() {
335
+ // An error carries no status, and on MariaDB what the statement changed before it failed is
336
+ // reported with no later answer either: so the server is asked.
337
+ return this.#alone(async () => this.#after(await this.#nothing(), true));
338
+ }
339
+ async stop() {
340
+ await this.#stoppable?.stop('cancel');
341
+ }
342
+ end() {
343
+ this.#ended = true;
344
+ this.#ending ??= this.#close();
345
+ return this.#ending;
346
+ }
347
+ onLost(listener) {
348
+ if (this.#lost)
349
+ tell(listener, this.#lost);
350
+ else if (!this.#gone)
351
+ this.#listeners.push(listener);
352
+ }
353
+ /**
354
+ * One thing at a time on the connection, a statement with all that is asked after it. While it
355
+ * lasts a kill may be on its way, which would land on whatever else was sent.
356
+ */
357
+ #alone(work) {
358
+ if (this.#ended) {
359
+ return Promise.reject(new DbAdminError('The import has ended.', 409, 'conflict'));
360
+ }
361
+ if (this.#gone)
362
+ return Promise.reject(this.#gone);
363
+ if (this.#running) {
364
+ return Promise.reject(new DbAdminError('The import’s connection is busy.', 409, 'conflict'));
365
+ }
366
+ const running = work().finally(() => (this.#running = null));
367
+ this.#running = running;
368
+ return running;
369
+ }
370
+ /**
371
+ * The server's error for a statement that would cost the connection, with nothing sent: one
372
+ * the server would hang up on, or one whose packet mysql2 would not send as it is.
373
+ */
374
+ #tooLong(sql) {
375
+ // The server takes a packet shorter than max_allowed_packet, the statement's head included.
376
+ const taken = this.#packet - PACKET_HEAD - 1;
377
+ const sent = PACKET_MOST - PACKET_HEAD;
378
+ const bytes = Buffer.byteLength(sql, 'utf8');
379
+ if (bytes <= Math.min(taken, sent))
380
+ return null;
381
+ const most = taken <= sent
382
+ ? `this server takes ${taken} at most in one statement (its max_allowed_packet is ${this.#packet})`
383
+ : `an import sends ${sent} at most in one statement`;
384
+ return {
385
+ errno: PACKET_TOO_LARGE,
386
+ code: '08S01',
387
+ message: `The statement is ${bytes} bytes, and ${most}.`,
388
+ unsent: true,
389
+ };
390
+ }
391
+ /**
392
+ * The import's no to a statement the server would read otherwise than the browser cut and
393
+ * checked it, with nothing sent: the person would have agreed to one statement, and the server
394
+ * run another. The character set the session reads it in is the one the server last said.
395
+ */
396
+ #misread(sql) {
397
+ const set = this.#session.characterSet;
398
+ if (READ_ALIKE.has(set))
399
+ return null;
400
+ const ascii = READ_ALIKE_IN_ASCII.has(set);
401
+ if (ascii && !BEYOND_ASCII.test(sql))
402
+ return null;
403
+ const why = ascii
404
+ ? `The statement holds text beyond ASCII, and the session reads statements as ${set}, as the file set it. Read as ${set}, the bytes of that text are other characters than this import read, and the server could end a string or a name where this import did not.`
405
+ : `The session reads statements as ${set}, as the file set it, and in that set the server may not read even ASCII as this import does: it could end a string or a name where this import did not.`;
406
+ return {
407
+ errno: NOT_SUPPORTED,
408
+ code: '42000',
409
+ message: `${why} So the statement was not sent: have the file set utf8mb4 first (SET NAMES utf8mb4).`,
410
+ unsent: true,
411
+ };
412
+ }
413
+ /**
414
+ * One statement, sent and watched. Past `timeoutMs`, or at a `stop()` when it is the file's, it
415
+ * is sent a KILL QUERY; once that kill has been answered or given up on, the statement has two
416
+ * minutes for an answer of its own, and then the connection is closed under it. It answers
417
+ * only once the kill has been answered too, so none is left on its way to whatever is sent
418
+ * next; a kill that got no answer may still come, and costs the connection.
419
+ *
420
+ * It rejects only when the statement got no answer. The answer of one that did is given even
421
+ * when the connection has gone since, for that kill or for anything else: `#after` then has
422
+ * no session to tell.
423
+ */
424
+ async #statement(sql, timeoutMs, { ofFile = false, row } = {}) {
425
+ const watch = watchStatement({ threadId: this.target.thread, destroy: () => this.#lose(new ConnectionError(STUCK)) }, { timeoutMs, graceMs: REPLY_MS, graceFrom: 'answer', kill: this.#kill });
426
+ if (ofFile)
427
+ this.#stoppable = watch;
428
+ this.#unanswered = ofFile;
429
+ try {
430
+ const reply = await this.#answer(sql, row);
431
+ watch.end();
432
+ if ((await watch.settled()) === 'unanswered')
433
+ this.#lose(new ConnectionError(KILL_UNANSWERED));
434
+ return reply;
435
+ }
436
+ finally {
437
+ watch.end();
438
+ }
439
+ }
440
+ /**
441
+ * One statement's answer, or the reason the connection can give none: whichever came first.
442
+ * It settles where the answer arrives, so an answer and the end of the connection read from
443
+ * the network in one go are heard in that order.
444
+ *
445
+ * `sql` is sent as it is, as one query: no values, so a `?` or a `:name` is the file's own.
446
+ * Rows are counted as they arrive and let go: only a question of the connection's own has a
447
+ * `row` to hand them to.
448
+ */
449
+ #answer(sql, row) {
450
+ if (this.#gone)
451
+ return Promise.reject(this.#gone);
452
+ // mysql2 takes up the character set the server reports for the session, and would send the
453
+ // text after a SET NAMES latin1 as latin1. The file's bytes are UTF-8 whatever it has set,
454
+ // as they are when the `mysql` client reads it: the server is to make of them what it would.
455
+ this.#core.config.charsetNumber = this.#wire;
456
+ return new Promise((resolve, reject) => {
457
+ const reply = { affected: 0, warnings: 0, rows: 0 };
458
+ let failure;
459
+ // Told by `#lose` while it waits. Not through a promise that lasts as long as the
460
+ // connection: each wait on one of those is kept until it settles, which is at the end.
461
+ this.#waiting.add(reject);
462
+ // Said here, where it arrives, and not by whoever waits for it: the next packet of the
463
+ // same read may be the connection's end, and that leaves no statement in doubt.
464
+ const answered = (answer) => {
465
+ this.#unanswered = false;
466
+ this.#waiting.delete(reject);
467
+ resolve(answer);
468
+ };
469
+ const failed = (error) => reject(this.#lose(error));
470
+ try {
471
+ // No callback: with one, mysql2 keeps every row until the statement has ended.
472
+ const query = this.#core.query({
473
+ sql,
474
+ rowsAsArray: true,
475
+ typeCast: false,
476
+ namedPlaceholders: false,
477
+ });
478
+ query.on('fields', (fields) => {
479
+ if (fields)
480
+ delete reply.status;
481
+ });
482
+ query.on('result', (result) => {
483
+ if (Array.isArray(result)) {
484
+ reply.rows++;
485
+ return row?.(result);
486
+ }
487
+ const ok = result;
488
+ reply.status = ok.serverStatus;
489
+ reply.affected = ok.affectedRows;
490
+ reply.warnings = ok.warningStatus;
491
+ });
492
+ query.on('error', (error) => (failure = error));
493
+ query.on('end', () => {
494
+ if (!failure)
495
+ return answered(reply);
496
+ const error = serverError(failure);
497
+ if (error)
498
+ return answered({ ...reply, error });
499
+ // Not the server's answer, so nothing says the connection can still be used.
500
+ failed(new ConnectionError(`The import’s connection failed: ${failure.message}`));
501
+ });
502
+ }
503
+ catch (error) {
504
+ failed(error);
505
+ }
506
+ });
507
+ }
508
+ /**
509
+ * The session after a statement that ran, as the server says it. What is asked for it runs on
510
+ * the file's session, between two of the file's statements, and is not nothing there. The
511
+ * file's next statement then reads of the question, and not of the file's own last one:
512
+ * ROW_COUNT() is -1 and FOUND_ROWS() is 1, on both servers, and on MySQL the list SHOW
513
+ * WARNINGS reads is empty. MariaDB keeps that list, through a statement that reads no table.
514
+ * The `DO 0` sent first, where an answer came without its status, changes none of this.
515
+ *
516
+ * No way of asking leaves the three as they were (MySQL 8.4, MariaDB 11.4). What the session
517
+ * is comes only as rows, and an answer with rows puts ROW_COUNT() at -1, as one without puts
518
+ * it at what its own statement changed; a SELECT sets FOUND_ROWS(); and on MySQL every
519
+ * statement empties the list but those that read it. Of those, GET DIAGNOSTICS leaves all
520
+ * three, and it tells nothing of the session.
521
+ *
522
+ * So these read as in the `mysql` client only where nothing is asked: after a statement of the
523
+ * file's that ran, returned no rows and changed nothing of the session, on a connection whose
524
+ * reports are trusted (see PROOFS), which MariaDB's are not. One the server refused is asked
525
+ * after as well, by `state()`, before the file's next statement is sent.
526
+ */
527
+ async #after(reply, ask = false) {
528
+ // The statement was answered and the connection went all the same, for its kill.
529
+ if (this.#gone)
530
+ throw this.#gone;
531
+ // Rows end without the status an OK carries, and without a word on what changed.
532
+ const hidden = reply.status === undefined;
533
+ const status = reply.status ?? (await this.#nothing()).status;
534
+ const open = inTransaction(status);
535
+ const changed = ask || hidden || !this.#reported || sessionChanged(reply);
536
+ // The sql_mode is as it was last asked: nothing an answer carries says it better.
537
+ if (!changed)
538
+ return (this.#session = { ...this.#session, inTransaction: open });
539
+ const { reports, ...asked } = await this.#ask((sql, row) => this.#statement(sql, OWN_MS, { row }));
540
+ // Once a file has changed what the server reports, every statement is asked after.
541
+ this.#reported &&= reports === this.#reports;
542
+ const { noBackslashEscapes, ansiQuotes, database, characterSet } = asked;
543
+ return (this.#session = {
544
+ inTransaction: open,
545
+ noBackslashEscapes,
546
+ ansiQuotes,
547
+ database,
548
+ characterSet,
549
+ });
550
+ }
551
+ /** A statement that does nothing, for the status its OK carries. */
552
+ async #nothing() {
553
+ const reply = await this.#statement('DO 0', OWN_MS);
554
+ if (reply.status === undefined)
555
+ throw this.#unknown(reply.error?.message);
556
+ return reply;
557
+ }
558
+ /**
559
+ * What only asking tells: the sql_mode whole, with NO_BACKSLASH_ESCAPES and ANSI_QUOTES or
560
+ * without; the database selected; the character set statements are read in; and what the
561
+ * server reports of the session now.
562
+ */
563
+ async #ask(send) {
564
+ const [sqlMode, database, client, ...reports] = await this.#one(ASK, 6, send);
565
+ const modes = (sqlMode ?? '').split(',');
566
+ return {
567
+ sqlMode: sqlMode ?? '',
568
+ noBackslashEscapes: modes.includes('NO_BACKSLASH_ESCAPES'),
569
+ ansiQuotes: modes.includes('ANSI_QUOTES'),
570
+ database: database ?? null,
571
+ characterSet: client ?? '',
572
+ reports: reports.join('\n'),
573
+ };
574
+ }
575
+ /** The one row of `count` values a question of the connection's own is answered with, as text. */
576
+ async #one(sql, count, send) {
577
+ const rows = [];
578
+ const reply = await send(sql, (values) => rows.push(values));
579
+ if (rows.length !== 1 || rows[0].length !== count)
580
+ throw this.#unknown(reply.error?.message);
581
+ return rows[0].map((value) => (value === null ? null : value.toString('utf8')));
582
+ }
583
+ /** The session's state can't be had, so nothing more can be split for it or sent to it. */
584
+ #unknown(why = 'it gave no answer') {
585
+ return this.#lose(new ConnectionError(`The import’s connection could not say what state its session is in (${why}), so it was closed.`));
586
+ }
587
+ /**
588
+ * The connection is of no more use: it is closed, whatever waits on it is told, and the
589
+ * listeners are, unless the import was ending anyway. The first reason is the one kept.
590
+ */
591
+ #lose(error) {
592
+ if (this.#gone)
593
+ return this.#gone;
594
+ this.#gone = error;
595
+ this.#doubt = this.#unanswered;
596
+ this.#core.destroy();
597
+ for (const told of this.#waiting)
598
+ told(error);
599
+ this.#waiting.clear();
600
+ this.#closed();
601
+ if (this.#ended)
602
+ return error;
603
+ this.#lost = error;
604
+ for (const listener of this.#listeners.splice(0))
605
+ tell(listener, error);
606
+ return error;
607
+ }
608
+ /**
609
+ * Stops what runs and waits for it, kill and all; then rolls back what the file left open, as
610
+ * the server says is open then, and says goodbye.
611
+ *
612
+ * Only a rollback the server took is called one. A connection that went first, or one closed
613
+ * on a rollback the server refused, has its transaction `abandoned`: nothing here says
614
+ * whether one was still open by then, and the server keeps one kind after its connection, an
615
+ * XA transaction already prepared.
616
+ */
617
+ async #close() {
618
+ const running = this.#running;
619
+ await this.#stoppable?.stop('cancel');
620
+ await running?.catch(() => { });
621
+ try {
622
+ const open = inTransaction((await this.#nothing()).status);
623
+ if (open) {
624
+ const undone = await this.#statement('ROLLBACK', REPLY_MS);
625
+ // The server's no, as inside an XA transaction, which only its own statements end.
626
+ if (undone.error)
627
+ throw this.#lose(new ConnectionError(undone.error.message));
628
+ }
629
+ await this.#goodbye();
630
+ return { transaction: open ? 'rolled-back' : 'none', inDoubt: false };
631
+ }
632
+ catch (error) {
633
+ if (error !== this.#gone)
634
+ throw error;
635
+ return { transaction: 'abandoned', inDoubt: this.#doubt };
636
+ }
637
+ finally {
638
+ this.#lose(new ConnectionError('The import has ended.'));
639
+ }
640
+ }
641
+ /** QUIT, and the server's own hanging up heard: its thread is going by then. */
642
+ #goodbye() {
643
+ return new Promise((resolve) => {
644
+ const late = setTimeout(resolve, GOODBYE_MS);
645
+ this.#core.once('end', () => {
646
+ clearTimeout(late);
647
+ resolve();
648
+ });
649
+ this.#core.end();
650
+ });
651
+ }
652
+ }
653
+ /** Whether a statement's answer came with the server's word that the session changed. */
654
+ function sessionChanged({ status = 0 }) {
655
+ return (status & SESSION_CHANGED) !== 0;
656
+ }
657
+ /** Whether the status with an OK says a transaction is open. */
658
+ function inTransaction(status) {
659
+ return (status & IN_TRANSACTION) !== 0;
660
+ }
661
+ /** The server's no to a statement, which leaves the connection as it was; null for anything else. */
662
+ function serverError({ errno, sqlState, sqlMessage, message, code, fatal }) {
663
+ if (!Number.isInteger(errno) || fatal)
664
+ return null;
665
+ // The message comes in the character set the file asked its results in, and may not read.
666
+ return { errno: errno, code: sqlState ?? 'HY000', message: sqlMessage || message || code || '' };
667
+ }
668
+ /** The server's no, for a statement of the importer's own that whoever asked must hear of. */
669
+ function refused({ errno, code, message }) {
670
+ return new QueryError(message, code, { errno });
671
+ }
672
+ /** A statement's time limit as a timer can keep it: a whole number of milliseconds, 24 days at most. */
673
+ function timeLimit(timeoutMs) {
674
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > TIMER_MOST_MS) {
675
+ throw new DbAdminError(`${timeoutMs} isn't a time limit in milliseconds.`, 400, 'bad-request');
676
+ }
677
+ return timeoutMs;
678
+ }
679
+ /** A listener of someone else's, called so that nothing it throws gets out. */
680
+ function tell(listener, error) {
681
+ try {
682
+ listener(error);
683
+ }
684
+ catch (failure) {
685
+ console.error('otw-db: an import’s listener failed', failure);
686
+ }
687
+ }
688
+ //# sourceMappingURL=mysql-import.js.map