@spine-event-engine/storage-mysql 2.0.0-snapshot.24 → 2.0.0-snapshot.26

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 (51) hide show
  1. package/README.md +34 -26
  2. package/REFERENCE.md +47 -47
  3. package/dist/index.d.ts +1 -1
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js.map +1 -1
  6. package/dist/mysql/agent-history.d.ts +47 -8
  7. package/dist/mysql/agent-history.d.ts.map +1 -1
  8. package/dist/mysql/agent-history.js +85 -19
  9. package/dist/mysql/agent-history.js.map +1 -1
  10. package/dist/mysql/agent-transaction.d.ts +6 -0
  11. package/dist/mysql/agent-transaction.d.ts.map +1 -1
  12. package/dist/mysql/agent-transaction.js +15 -0
  13. package/dist/mysql/agent-transaction.js.map +1 -1
  14. package/dist/mysql/column-mapping.d.ts +1 -0
  15. package/dist/mysql/column-mapping.d.ts.map +1 -1
  16. package/dist/mysql/column-mapping.js +26 -3
  17. package/dist/mysql/column-mapping.js.map +1 -1
  18. package/dist/mysql/entity-history.d.ts +23 -6
  19. package/dist/mysql/entity-history.d.ts.map +1 -1
  20. package/dist/mysql/entity-history.js +210 -48
  21. package/dist/mysql/entity-history.js.map +1 -1
  22. package/dist/mysql/id-column.d.ts +7 -0
  23. package/dist/mysql/id-column.d.ts.map +1 -1
  24. package/dist/mysql/id-column.js +27 -3
  25. package/dist/mysql/id-column.js.map +1 -1
  26. package/dist/mysql/record-storage.d.ts +175 -34
  27. package/dist/mysql/record-storage.d.ts.map +1 -1
  28. package/dist/mysql/record-storage.js +317 -140
  29. package/dist/mysql/record-storage.js.map +1 -1
  30. package/dist/mysql/storage-factory.d.ts +284 -29
  31. package/dist/mysql/storage-factory.d.ts.map +1 -1
  32. package/dist/mysql/storage-factory.js +1226 -170
  33. package/dist/mysql/storage-factory.js.map +1 -1
  34. package/dist/mysql/table-resolver.d.ts +26 -1
  35. package/dist/mysql/table-resolver.d.ts.map +1 -1
  36. package/dist/mysql/table-resolver.js +69 -18
  37. package/dist/mysql/table-resolver.js.map +1 -1
  38. package/dist/mysql/table-spec.d.ts +0 -4
  39. package/dist/mysql/table-spec.d.ts.map +1 -1
  40. package/dist/mysql/table-spec.js +2 -34
  41. package/dist/mysql/table-spec.js.map +1 -1
  42. package/dist/mysql/testing.d.ts +8 -0
  43. package/dist/mysql/testing.d.ts.map +1 -1
  44. package/dist/mysql/testing.js +23 -2
  45. package/dist/mysql/testing.js.map +1 -1
  46. package/dist/tsconfig.tsbuildinfo +1 -1
  47. package/package.json +5 -6
  48. package/dist/mysql/agent-execution.d.ts +0 -276
  49. package/dist/mysql/agent-execution.d.ts.map +0 -1
  50. package/dist/mysql/agent-execution.js +0 -630
  51. package/dist/mysql/agent-execution.js.map +0 -1
@@ -13,7 +13,7 @@
13
13
  */
14
14
  import { fromBinary, ScalarType, toBinary } from "@bufbuild/protobuf";
15
15
  import { AsyncLocalStorage } from "node:async_hooks";
16
- import { StringifierRegistry } from "@spine-event-engine/core";
16
+ import { defaultStringifierRegistry, StringifierRegistry } from "@spine-event-engine/core";
17
17
  import { ColumnMappings, defaultQueryCandidateLimit, RecordQuery, RecordStorage, } from "@spine-event-engine/storage";
18
18
  import { resolvedMysqlTableSpec } from "./table-spec.js";
19
19
  import { MysqlStorageDataError, MysqlStorageOperationError, MysqlStorageSchemaError, mysqlError, } from "./errors.js";
@@ -31,6 +31,7 @@ export class MysqlRecordStorage extends RecordStorage {
31
31
  lifecycle;
32
32
  onClose;
33
33
  createOperation;
34
+ publicHandle;
34
35
  // prettier-ignore
35
36
  /**
36
37
  * Declares support for atomic compare-and-set operations.
@@ -57,7 +58,10 @@ export class MysqlRecordStorage extends RecordStorage {
57
58
  * @returns Resolves after table creation and inspection complete.
58
59
  */
59
60
  async prepare() {
60
- await this.using(() => Promise.resolve());
61
+ if (this.lifecycle.prepare !== undefined)
62
+ await this.lifecycle.prepare();
63
+ else
64
+ await this.using(() => Promise.resolve());
61
65
  }
62
66
  /**
63
67
  * Reads a bounded package-local native history page.
@@ -85,55 +89,9 @@ export class MysqlRecordStorage extends RecordStorage {
85
89
  * @returns Completion after the native index definition is checked.
86
90
  */
87
91
  async ensureHistoryIndex(name, columns) {
88
- await this.using(async (connection) => {
89
- const existing = await this.historyIndex(connection, name);
90
- if (existing.length !== 0) {
91
- this.assertHistoryIndex(existing, columns);
92
- return;
93
- }
94
- if (!/^[a-z_]+$/u.test(name) || columns.some((column) => !/^[a-z_]+$/u.test(column)))
95
- throw new MysqlStorageSchemaError("MySQL Agent history index name is invalid.");
96
- const quoted = columns.map((column) => `\`${column}\``).join(", ");
97
- try {
98
- await connection.query(`CREATE INDEX \`${name}\` ON \`${this.tableName}\` (${quoted})`);
99
- }
100
- catch (error) {
101
- if (error.code !== "ER_DUP_KEYNAME")
102
- throw error;
103
- }
104
- this.assertHistoryIndex(await this.historyIndex(connection, name), columns);
105
- });
106
- }
107
- /**
108
- * Reads complete physical index metadata for one fixed history index.
109
- *
110
- * @param connection Active MySQL connection.
111
- * @param name Fixed required index name.
112
- * @returns Ordered native index components.
113
- */
114
- async historyIndex(connection, name) {
115
- const [rows] = await connection.query("SELECT index_name AS index_name, non_unique AS non_unique, " +
116
- "column_name AS column_name, seq_in_index AS seq_in_index, " +
117
- "sub_part AS sub_part, collation AS collation, index_type AS index_type " +
118
- "FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name=? " +
119
- "AND index_name=? ORDER BY seq_in_index", [this.tableName, name]);
120
- return rows;
121
- }
122
- /**
123
- * Rejects prefixes, wrong order, or a different native index.
124
- *
125
- * @param rows Ordered native index components.
126
- * @param columns Required complete index columns.
127
- */
128
- assertHistoryIndex(rows, columns) {
129
- if (rows.length !== columns.length ||
130
- rows.some((row, index) => row.column_name !== columns[index] ||
131
- Number(row.seq_in_index) !== index + 1 ||
132
- row.sub_part !== null ||
133
- Number(row.non_unique) !== 1 ||
134
- row.collation !== "A" ||
135
- row.index_type !== "BTREE"))
136
- throw new MysqlStorageSchemaError("MySQL Agent history index is incompatible.");
92
+ if (this.lifecycle.prepareIndex !== undefined)
93
+ return this.lifecycle.prepareIndex(name, columns);
94
+ await this.using((connection) => new MysqlTableInitializer(this.table, this.tableSpec, this.createOperation).ensureHistoryIndex(connection, name, columns, "create"));
137
95
  }
138
96
  /**
139
97
  * Creates a MySQL record-family storage handle.
@@ -146,13 +104,15 @@ export class MysqlRecordStorage extends RecordStorage {
146
104
  * @param createOperation Creates optional table-creation SQL.
147
105
  * @param tableSpec Supplies the canonical table layout.
148
106
  * @param stringifiers The schema-bound message stringifiers.
107
+ * @param publicHandle Whether this is a public factory record handle.
149
108
  */
150
- constructor(context, recordSpec, table, lifecycle, onClose, createOperation, tableSpec, stringifiers = new StringifierRegistry()) {
109
+ constructor(context, recordSpec, table, lifecycle, onClose, createOperation, tableSpec, stringifiers = defaultStringifierRegistry, publicHandle = false) {
151
110
  super(context, recordSpec);
152
111
  this.table = table;
153
112
  this.lifecycle = lifecycle;
154
113
  this.onClose = onClose;
155
114
  this.createOperation = createOperation;
115
+ this.publicHandle = publicHandle;
156
116
  this.#idColumn = new MysqlIdColumn(recordSpec.idType, stringifiers);
157
117
  this.#columnMapping = new MysqlColumnMapping(stringifiers);
158
118
  this.tableSpec =
@@ -175,15 +135,66 @@ export class MysqlRecordStorage extends RecordStorage {
175
135
  super.close();
176
136
  this.onClose();
177
137
  }
138
+ /**
139
+ * Registers a complete public operation before invoking configurable callbacks.
140
+ * @typeParam T Operation result type.
141
+ * @param work Complete operation.
142
+ * @returns Admitted operation outcome.
143
+ */
144
+ admit(work) {
145
+ if (!this.isOpen() || (this.publicHandle && this.lifecycle.publicOpen?.() === false))
146
+ return Promise.reject(new Error("MySQL record storage is closed."));
147
+ const { promise, resolve, reject } = Promise.withResolvers();
148
+ void this.lifecycle.track?.(promise);
149
+ try {
150
+ void work().then(resolve, reject);
151
+ }
152
+ catch (error) {
153
+ reject(error);
154
+ }
155
+ return promise;
156
+ }
157
+ /**
158
+ * @inheritdoc
159
+ */
160
+ index(query = {}) {
161
+ return this.admit(() => super.index(query));
162
+ }
163
+ /**
164
+ * @inheritdoc
165
+ */
166
+ query(query = {}) {
167
+ return this.admit(() => super.query(query));
168
+ }
169
+ /**
170
+ * @inheritdoc
171
+ */
172
+ queryEntries(query = {}) {
173
+ return this.admit(() => super.queryEntries(query));
174
+ }
175
+ /**
176
+ * @inheritdoc
177
+ */
178
+ queryPlan(plan) {
179
+ return this.admit(async () => (await super.queryPlanEntries(plan)).map((entry) => entry.record));
180
+ }
181
+ /**
182
+ * @inheritdoc
183
+ */
184
+ queryPlanEntries(plan) {
185
+ return this.admit(() => super.queryPlanEntries(plan));
186
+ }
178
187
  /**
179
188
  * Deletes the record identified by an ID.
180
189
  *
181
190
  * @param id Identifies the record to delete.
182
191
  * @returns Resolves whether a record was deleted.
183
192
  */
184
- async delete(id) {
185
- this.validateId(id);
186
- return super.delete(id);
193
+ delete(id) {
194
+ return this.admit(() => {
195
+ this.validateId(id);
196
+ return super.delete(id);
197
+ });
187
198
  }
188
199
  /**
189
200
  * Reads the record identified by an ID.
@@ -191,9 +202,11 @@ export class MysqlRecordStorage extends RecordStorage {
191
202
  * @param id Identifies the record to read.
192
203
  * @returns Resolves to the stored record when present.
193
204
  */
194
- async read(id) {
195
- this.validateId(id);
196
- return super.read(id);
205
+ read(id) {
206
+ return this.admit(() => {
207
+ this.validateId(id);
208
+ return super.read(id);
209
+ });
197
210
  }
198
211
  /**
199
212
  * Writes one record.
@@ -201,9 +214,11 @@ export class MysqlRecordStorage extends RecordStorage {
201
214
  * @param record Provides the record to write.
202
215
  * @returns Resolves after the record is written.
203
216
  */
204
- async write(record) {
205
- this.validateId(this.recordSpec.idValueIn(record));
206
- await super.write(record);
217
+ write(record) {
218
+ return this.admit(() => {
219
+ this.validateId(this.recordSpec.idValueIn(record));
220
+ return super.write(record);
221
+ });
207
222
  }
208
223
  /**
209
224
  * Writes a sequence of records.
@@ -211,11 +226,13 @@ export class MysqlRecordStorage extends RecordStorage {
211
226
  * @param records Provides the records to write.
212
227
  * @returns Resolves after the records are written.
213
228
  */
214
- async writeAll(records) {
215
- const stored = [...records];
216
- for (const record of stored)
217
- this.validateId(this.recordSpec.idValueIn(record));
218
- await super.writeAll(stored);
229
+ writeAll(records) {
230
+ return this.admit(() => {
231
+ const stored = [...records];
232
+ for (const record of stored)
233
+ this.validateId(this.recordSpec.idValueIn(record));
234
+ return super.writeAll(stored);
235
+ });
219
236
  }
220
237
  /**
221
238
  * Rejects an oversized storage slot before beginning compare-and-set work.
@@ -225,9 +242,11 @@ export class MysqlRecordStorage extends RecordStorage {
225
242
  * @param next Provides the replacement record.
226
243
  * @returns Resolves whether the conditional mutation was applied.
227
244
  */
228
- async compareAndSet(id, expected, next) {
229
- this.validateId(id);
230
- return super.compareAndSet(id, expected, next);
245
+ compareAndSet(id, expected, next) {
246
+ return this.admit(() => {
247
+ this.validateId(id);
248
+ return super.compareAndSet(id, expected, next);
249
+ });
231
250
  }
232
251
  /**
233
252
  * Writes an immutable record when an identical record is absent.
@@ -235,7 +254,16 @@ export class MysqlRecordStorage extends RecordStorage {
235
254
  * @param record Provides the immutable record.
236
255
  * @returns Resolves after the record is written or confirmed identical.
237
256
  */
238
- async writeImmutable(record) {
257
+ writeImmutable(record) {
258
+ return this.admit(() => this.writeImmutableAdmitted(record));
259
+ }
260
+ /**
261
+ * Writes an immutable record within an admitted complete operation.
262
+ *
263
+ * @param record Original record.
264
+ * @returns Completion after insertion or identical-content confirmation.
265
+ */
266
+ async writeImmutableAdmitted(record) {
239
267
  const id = this.recordSpec.idValueIn(record);
240
268
  this.idKey(id);
241
269
  await this.using(async (connection) => {
@@ -260,7 +288,16 @@ export class MysqlRecordStorage extends RecordStorage {
260
288
  * @param record Provides the immutable record to check.
261
289
  * @returns Resolves when the record is absent or identical.
262
290
  */
263
- async assertImmutable(record) {
291
+ assertImmutable(record) {
292
+ return this.admit(() => this.assertImmutableAdmitted(record));
293
+ }
294
+ /**
295
+ * Checks immutable content within an admitted complete operation.
296
+ *
297
+ * @param record Original record.
298
+ * @returns Completion after absent or identical content is confirmed.
299
+ */
300
+ async assertImmutableAdmitted(record) {
264
301
  const id = this.recordSpec.idValueIn(record);
265
302
  this.idKey(id);
266
303
  await this.using(async (connection) => {
@@ -467,6 +504,8 @@ export class MysqlRecordStorage extends RecordStorage {
467
504
  if (bound !== undefined) {
468
505
  return work(bound);
469
506
  }
507
+ if (this.lifecycle.prepare !== undefined)
508
+ await this.lifecycle.prepare();
470
509
  const connection = await this.lifecycle.acquire();
471
510
  try {
472
511
  await this.ready(connection);
@@ -486,77 +525,16 @@ export class MysqlRecordStorage extends RecordStorage {
486
525
  * @returns Resolves when the table is ready.
487
526
  */
488
527
  async ready(connection) {
489
- this.#ready ??= this.createAndInspect(connection).catch((error) => {
528
+ if (this.lifecycle.prepare !== undefined)
529
+ return;
530
+ this.#ready ??= new MysqlTableInitializer(this.table, this.tableSpec, this.createOperation)
531
+ .prepare(connection, "create")
532
+ .catch((error) => {
490
533
  this.#ready = undefined;
491
534
  throw mysqlError(MysqlStorageSchemaError, "MySQL record-family schema is incompatible.", error);
492
535
  });
493
536
  await this.#ready;
494
537
  }
495
- /**
496
- * Creates the table when absent and verifies its stored schema.
497
- *
498
- * @param connection Provides the connection used for schema operations.
499
- * @returns Resolves after schema verification.
500
- */
501
- async createAndInspect(connection) {
502
- const columnsSql = this.tableSpec.columns.map(mysqlColumnDefinition).join(", ");
503
- const primarySql = this.tableSpec.primaryKey.map((name) => `\`${name}\``).join(", ");
504
- await connection.query(this.createOperation?.() ??
505
- `CREATE TABLE IF NOT EXISTS \`${this.table.tableName}\` ` +
506
- `(${columnsSql}, PRIMARY KEY (${primarySql})) ENGINE=InnoDB`);
507
- const [columns] = await connection.query("SELECT column_name AS column_name, column_type AS column_type, " +
508
- "is_nullable AS is_nullable, column_default AS column_default, " +
509
- "collation_name AS collation_name, extra AS extra " +
510
- "FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=?", [this.table.tableName]);
511
- const expected = new Map(this.tableSpec.columns.map((column) => [column.name.toLowerCase(), column]));
512
- for (const column of this.tableSpec.columns) {
513
- const actual = columns.find((candidate) => candidate.column_name.toLowerCase() === column.name.toLowerCase());
514
- if (actual === undefined)
515
- throw new Error(`MySQL table ${this.table.tableName} lacks ${column.name}.`);
516
- this.assertCompatibleColumn(column, actual);
517
- }
518
- for (const column of columns)
519
- if (!expected.has(column.column_name.toLowerCase()))
520
- throw new Error(`MySQL table ${this.table.tableName} has incompatible extra column ${column.column_name}.`);
521
- const [primary] = await connection.query("SELECT column_name AS column_name, seq_in_index AS seq_in_index " +
522
- "FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name=? " +
523
- "AND index_name='PRIMARY' ORDER BY seq_in_index", [this.table.tableName]);
524
- if (columns.some((column) => column.column_type !== undefined) &&
525
- (primary.length !== this.tableSpec.primaryKey.length ||
526
- primary.some((column, index) => column.column_name.toLowerCase() !== this.tableSpec.primaryKey[index]?.toLowerCase())))
527
- throw new Error(`MySQL table ${this.table.tableName} has an incompatible primary key.`);
528
- const [indexes] = await connection.query("SELECT index_name AS index_name, non_unique AS non_unique, " +
529
- "column_name AS column_name, seq_in_index AS seq_in_index " +
530
- "FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name=? " +
531
- "ORDER BY index_name, seq_in_index", [this.table.tableName]);
532
- for (const index of groupedIndexes(indexes))
533
- if (index.nonUnique === 0 &&
534
- index.name.toLowerCase() !== "primary" &&
535
- !this.tableSpec.primaryKey.every((name) => index.columns.some((column) => column.toLowerCase() === name.toLowerCase())))
536
- throw new Error(`MySQL table ${this.table.tableName} has incompatible unique index ${index.name}.`);
537
- const [engines] = await connection.query("SELECT engine AS engine FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=?", [this.table.tableName]);
538
- const engine = engines[0]?.engine;
539
- if (engine !== undefined && !["innodb", "myisam", "aria"].includes(engine.toLowerCase()))
540
- throw new Error(`MySQL table ${this.table.tableName} has unsupported engine ${engine}.`);
541
- }
542
- /**
543
- * Verifies one physical column against the canonical table specification.
544
- *
545
- * @param expected Describes the required column.
546
- * @param actual Describes the stored column.
547
- */
548
- assertCompatibleColumn(expected, actual) {
549
- if (!compatibleMysqlType(expected.mysqlType, actual.column_type))
550
- throw new Error(`MySQL table ${this.table.tableName} has an incompatible ${expected.name} type.`);
551
- if (actual.is_nullable !== undefined && (actual.is_nullable === "YES") !== expected.nullable)
552
- throw new Error(`MySQL table ${this.table.tableName} has incompatible nullable ${expected.name}.`);
553
- if (!sameDefault(expected.defaultSql, actual.column_default))
554
- throw new Error(`MySQL table ${this.table.tableName} has incompatible ${expected.name} default.`);
555
- if (isBinaryType(expected.mysqlType) &&
556
- actual.collation_name !== undefined &&
557
- actual.collation_name !== null)
558
- throw new Error(`MySQL table ${this.table.tableName} has incompatible ${expected.name} collation.`);
559
- }
560
538
  /**
561
539
  * Reads one record on the supplied connection.
562
540
  *
@@ -796,10 +774,14 @@ export class MysqlRecordStorage extends RecordStorage {
796
774
  return `\`${field}\` <=> ?`;
797
775
  });
798
776
  const field = item.field === "id" ? "ID" : item.field;
799
- values.push(this.queryValue(field, field === "ID" ? after.id : after.values[index]?.value));
777
+ const value = this.queryValue(field, field === "ID" ? after.id : after.values[index]?.value);
800
778
  const prior = prefix.length === 0 ? "" : `${prefix.join(" AND ")} AND `;
801
- const comparison = item.direction === "desc" ? "<" : ">";
802
- return `${prior}\`${field}\` ${comparison} ?`;
779
+ if (value === null)
780
+ return `${prior}${item.direction === "desc" ? "1=0" : `\`${field}\` IS NOT NULL`}`;
781
+ values.push(value);
782
+ if (item.direction === "desc" && field !== "ID")
783
+ return `${prior}(\`${field}\` < ? OR \`${field}\` IS NULL)`;
784
+ return `${prior}\`${field}\` ${item.direction === "desc" ? "<" : ">"} ?`;
803
785
  });
804
786
  const prefixes = order.map((item, index) => {
805
787
  const field = item.field === "id" ? "ID" : item.field;
@@ -1103,6 +1085,201 @@ export class MysqlRecordStorage extends RecordStorage {
1103
1085
  return ColumnMappings.value(this.#columnMapping, column.type, value);
1104
1086
  }
1105
1087
  }
1088
+ /**
1089
+ * Prepares one declared MySQL/MariaDB table without constructing Storage.
1090
+ *
1091
+ * @typeParam I Typed record identifier.
1092
+ * @typeParam R Stored record message.
1093
+ */
1094
+ export class MysqlTableInitializer {
1095
+ table;
1096
+ spec;
1097
+ customCreate;
1098
+ /**
1099
+ * Binds the canonical physical table declaration.
1100
+ *
1101
+ * @param table Resolved table identity.
1102
+ * @param spec Canonical physical layout.
1103
+ * @param customCreate Optional custom create SQL.
1104
+ */
1105
+ constructor(table, spec, customCreate) {
1106
+ this.table = table;
1107
+ this.spec = spec;
1108
+ this.customCreate = customCreate;
1109
+ }
1110
+ /**
1111
+ * Creates when requested and inspects the complete physical layout.
1112
+ *
1113
+ * @param connection Active preparation connection.
1114
+ * @param mode Creation or read-only inspection.
1115
+ * @returns Completion after compatibility is proven.
1116
+ */
1117
+ async prepare(connection, mode) {
1118
+ if (mode === "create")
1119
+ await connection.query(this.customCreate?.() ?? this.createSql());
1120
+ const nativeMetadata = await this.inspectColumns(connection);
1121
+ await this.inspectPrimary(connection, nativeMetadata);
1122
+ await this.inspectUnique(connection);
1123
+ await this.inspectEngine(connection);
1124
+ }
1125
+ /**
1126
+ * Builds default table creation SQL.
1127
+ *
1128
+ * @returns Canonical create-if-absent SQL.
1129
+ */
1130
+ createSql() {
1131
+ const columns = this.spec.columns.map(mysqlColumnDefinition).join(", ");
1132
+ const primary = this.spec.primaryKey.map((name) => `\`${name}\``).join(", ");
1133
+ return (`CREATE TABLE IF NOT EXISTS \`${this.table.tableName}\` ` +
1134
+ `(${columns}, PRIMARY KEY (${primary})) ENGINE=InnoDB`);
1135
+ }
1136
+ /**
1137
+ * Inspects every declared physical column.
1138
+ *
1139
+ * @param connection Active preparation connection.
1140
+ * @returns Whether native column metadata is available.
1141
+ */
1142
+ async inspectColumns(connection) {
1143
+ const [columns] = await connection.query("SELECT column_name AS column_name, column_type AS column_type, " +
1144
+ "is_nullable AS is_nullable, column_default AS column_default, " +
1145
+ "collation_name AS collation_name, extra AS extra " +
1146
+ "FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=?", [this.table.tableName]);
1147
+ const expected = new Map(this.spec.columns.map((column) => [column.name.toLowerCase(), column]));
1148
+ for (const column of this.spec.columns) {
1149
+ const actual = columns.find((candidate) => candidate.column_name.toLowerCase() === column.name.toLowerCase());
1150
+ if (actual === undefined)
1151
+ throw new Error(`MySQL table ${this.table.tableName} lacks ${column.name}.`);
1152
+ this.assertCompatibleColumn(column, actual);
1153
+ }
1154
+ for (const column of columns)
1155
+ if (!expected.has(column.column_name.toLowerCase()))
1156
+ throw new Error(`MySQL table ${this.table.tableName} has incompatible extra column ${column.column_name}.`);
1157
+ return columns.some((column) => column.column_type !== undefined);
1158
+ }
1159
+ /**
1160
+ * Inspects the declared primary key.
1161
+ *
1162
+ * @param connection Active preparation connection.
1163
+ * @param nativeMetadata Whether this metadata source reports native types.
1164
+ * @returns Completion after primary-key inspection.
1165
+ */
1166
+ async inspectPrimary(connection, nativeMetadata) {
1167
+ const [primary] = await connection.query("SELECT column_name AS column_name, seq_in_index AS seq_in_index " +
1168
+ "FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name=? " +
1169
+ "AND index_name='PRIMARY' ORDER BY seq_in_index", [this.table.tableName]);
1170
+ if (nativeMetadata &&
1171
+ (primary.length !== this.spec.primaryKey.length ||
1172
+ primary.some((column, index) => column.column_name.toLowerCase() !== this.spec.primaryKey[index]?.toLowerCase())))
1173
+ throw new Error(`MySQL table ${this.table.tableName} has an incompatible primary key.`);
1174
+ }
1175
+ /**
1176
+ * Rejects unrelated unique constraints on the family table.
1177
+ *
1178
+ * @param connection Active preparation connection.
1179
+ * @returns Completion after unique-key inspection.
1180
+ */
1181
+ async inspectUnique(connection) {
1182
+ const [indexes] = await connection.query("SELECT index_name AS index_name, non_unique AS non_unique, " +
1183
+ "column_name AS column_name, seq_in_index AS seq_in_index " +
1184
+ "FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name=? " +
1185
+ "ORDER BY index_name, seq_in_index", [this.table.tableName]);
1186
+ for (const index of groupedIndexes(indexes))
1187
+ if (index.nonUnique === 0 &&
1188
+ index.name.toLowerCase() !== "primary" &&
1189
+ !this.spec.primaryKey.every((name) => index.columns.some((column) => column.toLowerCase() === name.toLowerCase())))
1190
+ throw new Error(`MySQL table ${this.table.tableName} has incompatible unique index ${index.name}.`);
1191
+ }
1192
+ /**
1193
+ * Checks the table engine supported by this provider.
1194
+ *
1195
+ * @param connection Active preparation connection.
1196
+ * @returns Completion after engine inspection.
1197
+ */
1198
+ async inspectEngine(connection) {
1199
+ const [engines] = await connection.query("SELECT engine AS engine FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=?", [this.table.tableName]);
1200
+ const engine = engines[0]?.engine;
1201
+ if (engine !== undefined && !["innodb", "myisam", "aria"].includes(engine.toLowerCase()))
1202
+ throw new Error(`MySQL table ${this.table.tableName} has unsupported engine ${engine}.`);
1203
+ }
1204
+ /**
1205
+ * Checks one declared column against native metadata.
1206
+ *
1207
+ * @param expected Canonical column.
1208
+ * @param actual Native column metadata.
1209
+ */
1210
+ assertCompatibleColumn(expected, actual) {
1211
+ if (!compatibleMysqlType(expected.mysqlType, actual.column_type))
1212
+ throw new Error(`MySQL table ${this.table.tableName} has an incompatible ${expected.name} type.`);
1213
+ if (actual.is_nullable !== undefined && (actual.is_nullable === "YES") !== expected.nullable)
1214
+ throw new Error(`MySQL table ${this.table.tableName} has incompatible nullable ${expected.name}.`);
1215
+ if (!sameDefault(expected.defaultSql, actual.column_default))
1216
+ throw new Error(`MySQL table ${this.table.tableName} has incompatible ${expected.name} default.`);
1217
+ if (isBinaryType(expected.mysqlType) &&
1218
+ actual.collation_name !== undefined &&
1219
+ actual.collation_name !== null)
1220
+ throw new Error(`MySQL table ${this.table.tableName} has incompatible ${expected.name} collation.`);
1221
+ }
1222
+ /**
1223
+ * Creates or checks one complete native Agent history index.
1224
+ *
1225
+ * @param connection Active preparation connection.
1226
+ * @param name Fixed provider index name.
1227
+ * @param columns Ordered complete index columns.
1228
+ * @param mode Creation or read-only inspection.
1229
+ * @returns Completion after exact compatibility.
1230
+ */
1231
+ async ensureHistoryIndex(connection, name, columns, mode) {
1232
+ const existing = await this.historyIndex(connection, name);
1233
+ if (existing.length !== 0) {
1234
+ this.assertHistoryIndex(existing, columns);
1235
+ return;
1236
+ }
1237
+ if (mode === "check")
1238
+ throw new MysqlStorageSchemaError("MySQL Agent history index is missing.");
1239
+ if (!/^[a-z_]+$/u.test(name) || columns.some((column) => !/^[a-z_]+$/u.test(column)))
1240
+ throw new MysqlStorageSchemaError("MySQL Agent history index name is invalid.");
1241
+ const quoted = columns.map((column) => `\`${column}\``).join(", ");
1242
+ try {
1243
+ await connection.query(`CREATE INDEX \`${name}\` ON \`${this.table.tableName}\` (${quoted})`);
1244
+ }
1245
+ catch (error) {
1246
+ if (error.code !== "ER_DUP_KEYNAME")
1247
+ throw error;
1248
+ }
1249
+ this.assertHistoryIndex(await this.historyIndex(connection, name), columns);
1250
+ }
1251
+ /**
1252
+ * Reads a fixed Agent audit index definition.
1253
+ *
1254
+ * @param connection Active preparation connection.
1255
+ * @param name Fixed index name.
1256
+ * @returns Ordered native index components.
1257
+ */
1258
+ async historyIndex(connection, name) {
1259
+ const [rows] = await connection.query("SELECT index_name AS index_name, non_unique AS non_unique, " +
1260
+ "column_name AS column_name, seq_in_index AS seq_in_index, " +
1261
+ "sub_part AS sub_part, collation AS collation, index_type AS index_type " +
1262
+ "FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name=? " +
1263
+ "AND index_name=? ORDER BY seq_in_index", [this.table.tableName, name]);
1264
+ return rows;
1265
+ }
1266
+ /**
1267
+ * Checks the complete ordered native index definition.
1268
+ *
1269
+ * @param rows Ordered native components.
1270
+ * @param columns Required complete columns.
1271
+ */
1272
+ assertHistoryIndex(rows, columns) {
1273
+ if (rows.length !== columns.length ||
1274
+ rows.some((row, index) => row.column_name !== columns[index] ||
1275
+ Number(row.seq_in_index) !== index + 1 ||
1276
+ row.sub_part !== null ||
1277
+ Number(row.non_unique) !== 1 ||
1278
+ row.collation !== "A" ||
1279
+ row.index_type !== "BTREE"))
1280
+ throw new MysqlStorageSchemaError("MySQL Agent history index is incompatible.");
1281
+ }
1282
+ }
1106
1283
  function mysqlColumnDefinition(column) {
1107
1284
  const nullable = column.nullable ? " NULL" : " NOT NULL";
1108
1285
  const defaultSql = column.defaultSql === undefined ? "" : ` DEFAULT ${column.defaultSql}`;