@itrocks/mysql-maintainer 0.4.2 → 0.7.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/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  # mysql-maintainer
8
8
 
9
- Reactively maintains database structure by updating schema and retrying on MySQL errors.
9
+ Repairs schema errors and adds indexes for slow MySQL queries.
10
10
 
11
11
  Connect this package to [`@itrocks/mysql`](https://github.com/itrocks-ts/mysql), then keep using your MySQL data
12
12
  sources normally. Their database structure is maintained automatically, as operations need it, when persistent object
@@ -46,6 +46,10 @@ the composed `@itrocks/mysql` implementation is maintained automatically.
46
46
  That is the complete setup. Keep changing and using persistent object classes through the usual it.rocks storage
47
47
  operations; the required database changes are applied when an operation first needs them.
48
48
 
49
+ If an explicit MySQL transaction needs new tables or columns, select the affected columns before starting it.
50
+ A structure error on that query lets the maintainer create or extend the table. Inside the transaction, schema
51
+ errors propagate because MySQL DDL can implicitly commit.
52
+
49
53
  ## Use outside the it.rocks framework
50
54
 
51
55
  The same integration principle can be used without `@itrocks/framework`:
@@ -85,17 +89,28 @@ For example, a read follows this simplified sequence:
85
89
  The exported classes that implement context tracking, error handling, schema updates, and retries are internal
86
90
  mechanics of this integration. They are not a separate API that an application needs to call.
87
91
 
88
- Unique indexes declared with `@Unique` from
89
- [`@itrocks/unique`](https://github.com/itrocks-ts/unique) are checked before the first insert or update of each
90
- persistent class on a database connection. This lazy preflight also detects an index added to a class after its table
91
- already exists. Writes of the same class on the same connection share one preflight, and a new connection performs the
92
- check again.
93
-
94
- If existing duplicate rows prevent a unique index from being created, the maintainer does not alter or delete those
95
- rows. It rejects the write with a generic `UniqueIndexMaintenanceError`. Operational logs contain only a fixed event
96
- name and a driver error code from a closed operational allowlist; they do not contain SQL, parameters, driver messages,
97
- arbitrary code strings, or stored values. Once an
98
- operator resolves the duplicates, a later write retries the preflight.
92
+ Schema updates include unique indexes declared with `@Unique` from
93
+ [`@itrocks/unique`](https://github.com/itrocks-ts/unique).
94
+
95
+ ## Slow queries
96
+
97
+ On the first connection, the maintainer loads its threshold from `data-path/mysql-maintainer/indexed-read.ms` or
98
+ calibrates it on the server. It measures ten indexed lookups on an InnoDB temporary table of 1,000 rows after warming
99
+ the index.
100
+ The threshold is twice the median, capped at 10 ms. All MySQL data sources in the application share this threshold.
101
+
102
+ The maintainer reads individual statement timings from MySQL Performance Schema. Enable the
103
+ `events_statements_history` consumer and grant the application account read access to that table and permission
104
+ to create temporary tables for calibration. When a timing is unavailable, those queries are skipped by the analyser.
105
+
106
+ A successful query above the threshold can trigger index maintenance on a separate session. The maintainer
107
+ applies the indexes declared on the contextual classes and then runs `EXPLAIN`. It can add one non-unique index
108
+ for a single equality or a `LIKE` with a literal prefix on a single contextual table. The plan must estimate
109
+ a full scan of at least 1,000 rows with at most 10% passing the filter, and the column must lack a leading index.
110
+
111
+ Completed analyses are cached in memory for one hour or until schema maintenance changes the database.
112
+ The cache uses the SQL template and distinguishes `LIKE` parameters with and without a leading wildcard.
113
+ Analysis runs outside caller transactions and its outcome does not affect the result returned to the caller.
99
114
 
100
115
  ## Persistent model requirements
101
116
 
@@ -1,17 +1,18 @@
1
1
  import { ObjectOrType } from '@itrocks/class-type';
2
- import { Type } from '@itrocks/class-type';
3
2
  import { Connection } from 'mariadb';
4
3
  import { QueryOptions } from 'mariadb';
5
4
  import { SqlError } from 'mariadb';
6
5
  import { AsyncLocalStorage } from 'node:async_hooks';
6
+ import type { SlowQueries } from './slow-query';
7
7
  export type Context = ObjectOrType | ObjectOrType[];
8
8
  export declare class Contextual implements Partial<Connection> {
9
9
  [x: number]: (() => Promise<void>) | undefined;
10
10
  contextStorage: AsyncLocalStorage<Context>;
11
11
  errorCount: Record<string, Record<string, Array<number>>>;
12
+ slowQueries?: SlowQueries;
12
13
  superQuery: <T = any>(sql: string | QueryOptions, values?: any) => Promise<T>;
13
- uniqueIndexPromises: WeakMap<Type, Promise<void>>;
14
- applyTo(connection: ContextualConnection): Promise<ContextualConnection>;
14
+ inTransaction: () => boolean;
15
+ applyTo(connection: ContextualConnection, inTransaction?: () => boolean, slowQueries?: SlowQueries): Promise<ContextualConnection>;
15
16
  incrementErrorCount(sql: string, error: any): this is Connection;
16
17
  isSqlError(error: any): error is SqlError;
17
18
  query<T = any>(sql: string | QueryOptions, values?: any): Promise<T>;
@@ -9,17 +9,19 @@ const MANAGED_ERROR_CODES = ['ER_BAD_FIELD_ERROR', 'ER_CANNOT_ADD_FOREIGN', 'ER_
9
9
  class Contextual {
10
10
  contextStorage = new node_async_hooks_1.AsyncLocalStorage();
11
11
  errorCount = {};
12
+ slowQueries;
12
13
  superQuery = () => new Promise(() => { });
13
- uniqueIndexPromises = new WeakMap();
14
- async applyTo(connection) {
14
+ inTransaction = () => false;
15
+ async applyTo(connection, inTransaction = () => false, slowQueries) {
15
16
  connection.contextStorage = new node_async_hooks_1.AsyncLocalStorage();
16
17
  connection.errorCount = {};
17
18
  connection.incrementErrorCount = Contextual.prototype.incrementErrorCount;
18
19
  connection.isSqlError = Contextual.prototype.isSqlError;
20
+ connection.inTransaction = inTransaction;
19
21
  connection.run = Contextual.prototype.run;
22
+ connection.slowQueries = slowQueries;
20
23
  connection.superQuery = connection.query;
21
24
  connection.query = Contextual.prototype.query;
22
- connection.uniqueIndexPromises = new WeakMap();
23
25
  return connection;
24
26
  }
25
27
  incrementErrorCount(sql, error) {
@@ -41,13 +43,19 @@ class Contextual {
41
43
  return (typeof error === 'object') && !!error.code;
42
44
  }
43
45
  async query(sql, values) {
46
+ const context = this.contextStorage.getStore();
47
+ const monitor = this.slowQueries;
48
+ const sample = (context && !this.inTransaction() && (typeof sql === 'string'))
49
+ ? monitor?.sample(sql)
50
+ : undefined;
51
+ let result;
44
52
  try {
45
53
  if (mysql_maintainer_1.DEBUG)
46
54
  console.log(sql, values);
47
- return await this.superQuery(sql, values);
55
+ result = await this.superQuery(sample ? `${sample.marker}${sql}` : sql, values);
48
56
  }
49
57
  catch (error) {
50
- if (!this.isSqlError(error) || !MANAGED_ERROR_CODES.includes(error.code)) {
58
+ if (this.inTransaction() || !this.isSqlError(error) || !MANAGED_ERROR_CODES.includes(error.code)) {
51
59
  if (mysql_maintainer_1.DEBUG)
52
60
  console.log('MAINTAINER: throw', error);
53
61
  throw error;
@@ -56,12 +64,17 @@ class Contextual {
56
64
  if (this.incrementErrorCount(sql, error)
57
65
  && (this.errorCount[sql][error.message].length < 5)
58
66
  && await new mysql_maintainer_2.MysqlMaintainer(this).manageError(error, this.contextStorage.getStore(), sql, values)) {
67
+ monitor?.invalidate();
59
68
  return this.query(sql, values);
60
69
  }
61
70
  if (mysql_maintainer_1.DEBUG)
62
71
  console.log('MAINTAINER: throw (2)', error);
63
72
  throw error;
64
73
  }
74
+ if (sample && context && !this.inTransaction() && (typeof sql === 'string')) {
75
+ void monitor?.consider(context, this.superQuery.bind(this), sql, values, sample);
76
+ }
77
+ return result;
65
78
  }
66
79
  run(context, operation) {
67
80
  return this.contextStorage.run(context, operation);
@@ -4,15 +4,17 @@ import { Connection } from 'mariadb';
4
4
  import { QueryOptions } from 'mariadb';
5
5
  import { SqlError } from 'mariadb';
6
6
  import { Context } from './contextual-connection';
7
- export { Mysql, UniqueIndexMaintenanceError } from './mysql';
7
+ export { Mysql } from './mysql';
8
8
  export declare const DEBUG = false;
9
9
  export declare class MysqlMaintainer {
10
10
  connection: Connection;
11
11
  constructor(connection: Connection);
12
+ addQueryIndex(table: string, column: string, name: string): Promise<boolean>;
12
13
  createImplicitTable(type1: ObjectOrType, type2: ObjectOrType): Promise<boolean>;
13
14
  createTable(type: Type): Promise<boolean>;
14
15
  implicitTableName(type1: ObjectOrType, type2: ObjectOrType): string;
15
16
  manageError(error: SqlError, context: Context, _sql: string | QueryOptions, _values: any[]): Promise<boolean>;
17
+ updateContextIndexes(context: Context, changed: () => void): Promise<void>;
16
18
  updateContextTables(context: Context, tableName?: string): Promise<boolean>;
17
19
  updateTable(type: Type): Promise<boolean>;
18
20
  }
@@ -1,18 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MysqlMaintainer = exports.DEBUG = exports.UniqueIndexMaintenanceError = exports.Mysql = void 0;
3
+ exports.MysqlMaintainer = exports.DEBUG = exports.Mysql = void 0;
4
4
  const class_type_1 = require("@itrocks/class-type");
5
5
  const mysql_1 = require("@itrocks/mysql");
6
6
  const mysql_to_schema_1 = require("@itrocks/mysql-to-schema");
7
7
  const reflect_to_schema_1 = require("@itrocks/reflect-to-schema");
8
8
  const schema_1 = require("@itrocks/schema");
9
+ const schema_2 = require("@itrocks/schema");
10
+ const schema_3 = require("@itrocks/schema");
9
11
  const schema_diff_1 = require("@itrocks/schema-diff");
10
12
  const schema_diff_mysql_1 = require("@itrocks/schema-diff-mysql");
11
13
  const schema_to_mysql_1 = require("@itrocks/schema-to-mysql");
12
14
  const store_1 = require("@itrocks/store");
13
15
  var mysql_2 = require("./mysql");
14
16
  Object.defineProperty(exports, "Mysql", { enumerable: true, get: function () { return mysql_2.Mysql; } });
15
- Object.defineProperty(exports, "UniqueIndexMaintenanceError", { enumerable: true, get: function () { return mysql_2.UniqueIndexMaintenanceError; } });
16
17
  exports.DEBUG = false;
17
18
  const DELETION = false;
18
19
  class MysqlMaintainer {
@@ -20,6 +21,17 @@ class MysqlMaintainer {
20
21
  constructor(connection) {
21
22
  this.connection = connection;
22
23
  }
24
+ async addQueryIndex(table, column, name) {
25
+ const current = await new mysql_to_schema_1.MysqlToTable(this.connection).convert(table);
26
+ if (!current.columns.some(field => field.name === column))
27
+ return false;
28
+ if (current.indexes.some(index => (index.keys[0]?.columnName === column) || (index.name === name)))
29
+ return false;
30
+ const ddl = new schema_diff_mysql_1.SchemaDiffMysql();
31
+ const index = new schema_2.Index(name, new schema_3.IndexKey(column));
32
+ await this.connection.query(`${ddl.tableSql(current)}\nADD ${ddl.indexSql(index)}`);
33
+ return true;
34
+ }
23
35
  async createImplicitTable(type1, type2) {
24
36
  const joinTable = this.implicitTableName(type1, type2);
25
37
  const table1 = (0, store_1.storeOf)(type1);
@@ -66,6 +78,29 @@ CONSTRAINT \`${joinTable}.${table2}_id\` FOREIGN KEY (${table2}_id) REFERENCES \
66
78
  }
67
79
  return false;
68
80
  }
81
+ async updateContextIndexes(context, changed) {
82
+ const contexts = Array.isArray(context) ? context : [context];
83
+ const ddl = new schema_diff_mysql_1.SchemaDiffMysql();
84
+ const types = new Set(contexts.map(value => (0, class_type_1.typeOf)(value)));
85
+ for (const type of types) {
86
+ const tableName = (0, store_1.storeOf)(type);
87
+ if (!tableName)
88
+ continue;
89
+ const reader = new mysql_to_schema_1.MysqlToTable(this.connection);
90
+ const current = await reader.convert(tableName);
91
+ if (!current.columns.length)
92
+ continue;
93
+ const model = new reflect_to_schema_1.ReflectToTable().convert(type);
94
+ const columns = new Set(current.columns.map(column => column.name));
95
+ model.indexes = model.indexes.filter(index => index.keys.every(key => columns.has(key.columnName)));
96
+ reader.normalize(model);
97
+ const sql = ddl.alterIndexesSql(new schema_diff_1.TableDiff(current, model));
98
+ if (!sql)
99
+ continue;
100
+ await this.connection.query(`${ddl.tableSql(current)}\n${sql}`);
101
+ changed();
102
+ }
103
+ }
69
104
  async updateContextTables(context, tableName) {
70
105
  let result = false;
71
106
  const contexts = Array.isArray(context) ? context : [context];
package/cjs/mysql.d.ts CHANGED
@@ -7,20 +7,14 @@ import { Identifier } from '@itrocks/storage';
7
7
  import { Options } from '@itrocks/storage';
8
8
  import { SearchType } from '@itrocks/storage';
9
9
  import { ContextualConnection } from './contextual-connection';
10
- export declare class UniqueIndexMaintenanceError extends Error {
11
- readonly code = "SCHEMA_UNIQUE_INDEX_MAINTENANCE_FAILED";
12
- constructor();
13
- }
14
10
  export declare class Mysql extends M {
15
- connection?: ContextualConnection;
11
+ get connection(): ContextualConnection | undefined;
12
+ set connection(connection: ContextualConnection | undefined);
16
13
  connect(): Promise<ContextualConnection>;
17
14
  deleteId<T extends object>(type: ObjectOrType<T>, id: any, property?: keyof Entity<T>): Promise<void>;
18
15
  deleteRelatedId<T extends Entity>(object: T, property: keyof T, id: Identifier): Promise<void>;
19
- ensureUniqueIndexes(type: Type): Promise<void>;
20
- private hasUniqueIndexes;
21
16
  insert<T extends object>(object: T): Promise<Entity<T>>;
22
17
  insertRelatedId<T extends Entity>(object: T, property: keyof T, id: Identifier): Promise<void>;
23
- protected maintainUniqueIndexes(type: Type, connection: ContextualConnection): Promise<void>;
24
18
  protected querySelection<T extends object>(query: SqlQuery, types: readonly Type[]): Promise<T[]>;
25
19
  read<T extends object>(type: Type<T>, id: Identifier): Promise<Entity<T>>;
26
20
  readCollection<T extends object, PT extends object>(object: Entity<T>, property: keyof T, type?: Type<PT>): Promise<Awaited<PT & {
package/cjs/mysql.js CHANGED
@@ -1,26 +1,22 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Mysql = exports.UniqueIndexMaintenanceError = void 0;
4
- const class_type_1 = require("@itrocks/class-type");
3
+ exports.Mysql = void 0;
5
4
  const mysql_1 = require("@itrocks/mysql");
6
5
  const reflect_1 = require("@itrocks/reflect");
7
- const reflect_2 = require("@itrocks/reflect");
8
- const unique_1 = require("@itrocks/unique");
9
6
  const contextual_connection_1 = require("./contextual-connection");
10
- const mysql_maintainer_1 = require("./mysql-maintainer");
11
- const safe_error_code_1 = require("./safe-error-code");
12
- const UNIQUE_INDEX_ERROR_CODE = 'SCHEMA_UNIQUE_INDEX_MAINTENANCE_FAILED';
13
- class UniqueIndexMaintenanceError extends Error {
14
- code = UNIQUE_INDEX_ERROR_CODE;
15
- constructor() {
16
- super('Unique index maintenance failed');
17
- this.name = 'UniqueIndexMaintenanceError';
18
- }
19
- }
20
- exports.UniqueIndexMaintenanceError = UniqueIndexMaintenanceError;
7
+ const slow_query_1 = require("./slow-query");
21
8
  class Mysql extends mysql_1.Mysql {
9
+ get connection() {
10
+ return super.connection;
11
+ }
12
+ set connection(connection) {
13
+ super.connection = connection;
14
+ }
22
15
  async connect() {
23
- return contextual_connection_1.Contextual.prototype.applyTo(await super.connect());
16
+ const monitor = (0, slow_query_1.slowQueries)(this.config);
17
+ const connection = await contextual_connection_1.Contextual.prototype.applyTo(await super.connect(), () => this.inTransaction, monitor);
18
+ await monitor.start(connection.superQuery.bind(connection));
19
+ return connection;
24
20
  }
25
21
  async deleteId(type, id, property = 'id') {
26
22
  return this.withContext(type, () => super.deleteId(type, id, property));
@@ -28,48 +24,12 @@ class Mysql extends mysql_1.Mysql {
28
24
  async deleteRelatedId(object, property, id) {
29
25
  return this.withContext(object, () => super.deleteRelatedId(object, property, id));
30
26
  }
31
- async ensureUniqueIndexes(type) {
32
- if (!this.hasUniqueIndexes(type))
33
- return;
34
- const connection = this.connection ?? await this.connect();
35
- const promises = connection.uniqueIndexPromises;
36
- const current = promises.get(type);
37
- if (current)
38
- return current;
39
- let maintenance;
40
- maintenance = Promise.resolve()
41
- .then(() => this.maintainUniqueIndexes(type, connection))
42
- .catch(error => {
43
- if (promises.get(type) === maintenance)
44
- promises.delete(type);
45
- console.warn('[@itrocks/mysql-maintainer] Unique index maintenance failed', {
46
- code: (0, safe_error_code_1.safeDriverErrorCode)(error),
47
- event: 'unique-index-preflight'
48
- });
49
- throw new UniqueIndexMaintenanceError();
50
- });
51
- promises.set(type, maintenance);
52
- return maintenance;
53
- }
54
- hasUniqueIndexes(type) {
55
- return new reflect_1.ReflectClass(type).properties.some(property => (0, unique_1.uniqueOf)(type, property.name) !== false);
56
- }
57
27
  async insert(object) {
58
- return this.withContext(object, async () => {
59
- await this.ensureUniqueIndexes((0, class_type_1.typeOf)(object));
60
- return super.insert(object);
61
- });
28
+ return this.withContext(object, () => super.insert(object));
62
29
  }
63
30
  async insertRelatedId(object, property, id) {
64
31
  return this.withContext(object, () => super.insertRelatedId(object, property, id));
65
32
  }
66
- async maintainUniqueIndexes(type, connection) {
67
- const originalConnection = Object.create(connection);
68
- originalConnection.query = ((sql, values) => {
69
- return connection.superQuery(sql, values);
70
- });
71
- await new mysql_maintainer_1.MysqlMaintainer(originalConnection).updateContextTables(type);
72
- }
73
33
  async querySelection(query, types) {
74
34
  return this.withContext([...types], () => super.querySelection(query, types));
75
35
  }
@@ -77,11 +37,11 @@ class Mysql extends mysql_1.Mysql {
77
37
  return this.withContext(type, () => super.read(type, id));
78
38
  }
79
39
  async readCollection(object, property, type) {
80
- type ??= new reflect_2.ReflectProperty(object, property).collectionType.elementType.type;
40
+ type ??= new reflect_1.ReflectProperty(object, property).collectionType.elementType.type;
81
41
  return this.withContext([object, type], () => super.readCollection(object, property, type));
82
42
  }
83
43
  async readCollectionIds(object, property, type) {
84
- type ??= new reflect_2.ReflectProperty(object, property).collectionType.elementType.type;
44
+ type ??= new reflect_1.ReflectProperty(object, property).collectionType.elementType.type;
85
45
  return this.withContext([object, type], () => super.readCollectionIds(object, property, type));
86
46
  }
87
47
  async readMultiple(type, ids) {
@@ -91,10 +51,7 @@ class Mysql extends mysql_1.Mysql {
91
51
  return this.withContext(type, () => super.search(type, search, options));
92
52
  }
93
53
  async update(object) {
94
- return this.withContext(object, async () => {
95
- await this.ensureUniqueIndexes((0, class_type_1.typeOf)(object));
96
- return super.update(object);
97
- });
54
+ return this.withContext(object, () => super.update(object));
98
55
  }
99
56
  async withContext(context, operation) {
100
57
  return (this.connection ?? await this.connect()).run(context, operation);
@@ -0,0 +1,13 @@
1
+ type ExplainRow = {
2
+ filtered: number | string | null;
3
+ rows: number | string | null;
4
+ table: string;
5
+ type: string;
6
+ };
7
+ export declare function likeVariants(tokens: string[], values: readonly unknown[], backslashEscapes: boolean): string[];
8
+ export declare function queryIndex(tokens: string[], plan: ExplainRow[], variants: string[]): {
9
+ column: string;
10
+ table: string;
11
+ } | undefined;
12
+ export declare function queryTokens(sql: string): string[];
13
+ export {};
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.likeVariants = likeVariants;
4
+ exports.queryIndex = queryIndex;
5
+ exports.queryTokens = queryTokens;
6
+ const endPredicate = new Set(['GROUP', 'HAVING', 'LIMIT', 'ORDER']);
7
+ const identifier = /^(?:\x60(?:\x60\x60|[^\x60])+\x60|[a-z_][a-z_0-9]*)$/i;
8
+ const sqlToken = new RegExp([
9
+ /\/\*[\s\S]*?\*\/|--(?=\s)[^\r\n]*|#[^\r\n]*/.source,
10
+ /\x60(?:\x60\x60|[^\x60])*\x60|'(?:\\[\s\S]|''|[^'\\])*'|"(?:\\[\s\S]|""|[^"\\])*"/.source,
11
+ /[a-z_][a-z_0-9]*|\S/.source
12
+ ].join('|'), 'gi');
13
+ function identifierOf(token) {
14
+ if (!token || !identifier.test(token))
15
+ return undefined;
16
+ return token.startsWith('\x60') ? token.slice(1, -1).replaceAll('\x60\x60', '\x60') : token;
17
+ }
18
+ function likeEscape(token, value) {
19
+ if (token === '?') {
20
+ return (typeof value === 'string') ? value : '';
21
+ }
22
+ const quote = token?.[0];
23
+ if (token && ((quote === "'") || (quote === '"'))) {
24
+ return token.slice(1, -1).replaceAll(quote + quote, quote).replace(/\\(.)/g, '$1');
25
+ }
26
+ return '';
27
+ }
28
+ function likeVariants(tokens, values, backslashEscapes) {
29
+ let parameter = 0;
30
+ const variants = [];
31
+ for (let index = 0; index < tokens.length; index++) {
32
+ if (tokens[index] !== '?')
33
+ continue;
34
+ const position = parameter++;
35
+ if (tokens[index - 1]?.toUpperCase() !== 'LIKE')
36
+ continue;
37
+ const pattern = values[position];
38
+ if (typeof pattern !== 'string')
39
+ continue;
40
+ const escape = (tokens[index + 1]?.toUpperCase() === 'ESCAPE')
41
+ ? likeEscape(tokens[index + 2], values[parameter])
42
+ : (backslashEscapes ? '\\' : '');
43
+ const wildcard = ((pattern[0] === '%') || (pattern[0] === '_')) && (pattern[0] !== escape);
44
+ variants.push(`${position}:${wildcard ? 'wildcard' : 'prefix'}`);
45
+ }
46
+ return variants;
47
+ }
48
+ function queryIndex(tokens, plan, variants) {
49
+ const [scan] = plan;
50
+ if ((plan.length !== 1) || (scan.type !== 'ALL') || (Number(scan.rows) < 1_000))
51
+ return;
52
+ if ((scan.filtered === null) || (Number(scan.filtered) > 10))
53
+ return;
54
+ if (tokens[0]?.toUpperCase() !== 'SELECT')
55
+ return;
56
+ const words = tokens.map(token => token.toUpperCase());
57
+ const from = words.indexOf('FROM');
58
+ const where = words.indexOf('WHERE');
59
+ if ((from < 0) || (where < from))
60
+ return;
61
+ const table = identifierOf(tokens[from + 1]);
62
+ const source = tokens.slice(from + 2, where);
63
+ if (!table || (source.length > 2) || ((source.length === 2) && (source[0].toUpperCase() !== 'AS')))
64
+ return;
65
+ const alias = source.length ? identifierOf(source.at(-1)) : table;
66
+ if (alias !== scan.table)
67
+ return;
68
+ const end = words.findIndex((word, index) => (index > where) && endPredicate.has(word));
69
+ const predicate = tokens.slice(where + 1, (end < 0) ? undefined : end);
70
+ const qualified = (predicate[1] === '.');
71
+ const column = identifierOf(predicate[qualified ? 2 : 0]);
72
+ const operator = predicate[qualified ? 3 : 1]?.toUpperCase();
73
+ const parameter = qualified ? 4 : 2;
74
+ if (!column || (qualified && (identifierOf(predicate[0]) !== alias)) || (predicate[parameter] !== '?'))
75
+ return;
76
+ const tail = predicate.slice(parameter + 1);
77
+ if (operator === 'LIKE') {
78
+ const position = tokens.slice(0, where + 1).filter(token => token === '?').length;
79
+ if (!variants.includes(`${position}:prefix`))
80
+ return;
81
+ if (tail.length && ((tail.length !== 2) || (tail[0].toUpperCase() !== 'ESCAPE')))
82
+ return;
83
+ }
84
+ else if ((operator !== '=') || tail.length) {
85
+ return;
86
+ }
87
+ if (![table, column].every(name => /^[a-z_0-9]+$/i.test(name)))
88
+ return;
89
+ return { column, table };
90
+ }
91
+ function queryTokens(sql) {
92
+ return sql.match(sqlToken) ?? [];
93
+ }
94
+ //# sourceMappingURL=query-index.js.map
@@ -4,7 +4,6 @@ exports.safeDriverErrorCode = safeDriverErrorCode;
4
4
  const SAFE_DRIVER_ERROR_CODES = new Set([
5
5
  'ER_BAD_FIELD_ERROR',
6
6
  'ER_CANNOT_ADD_FOREIGN',
7
- 'ER_DUP_ENTRY',
8
7
  'ER_NO_SUCH_TABLE'
9
8
  ]);
10
9
  function safeDriverErrorCode(error) {
@@ -0,0 +1,28 @@
1
+ import type { Connection } from 'mariadb';
2
+ import type { ConnectionConfig } from 'mariadb';
3
+ import type { Context } from './contextual-connection';
4
+ type Query = Connection['query'];
5
+ type Sample = {
6
+ marker: string;
7
+ started: number;
8
+ };
9
+ export declare function slowQueries(config: ConnectionConfig): SlowQueries;
10
+ export declare class SlowQueries {
11
+ private readonly config;
12
+ private readonly path;
13
+ private readonly examined;
14
+ private readonly pending;
15
+ private queue;
16
+ private threshold?;
17
+ constructor(config: ConnectionConfig, path: string);
18
+ private analyse;
19
+ consider(context: Context, query: Query, sql: string, values: any, sample: Sample): Promise<void>;
20
+ private initialise;
21
+ invalidate(): void;
22
+ sample(sql: string): {
23
+ marker: string;
24
+ started: number;
25
+ } | undefined;
26
+ start(query: Query): Promise<void>;
27
+ }
28
+ export {};
@@ -0,0 +1,186 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SlowQueries = void 0;
4
+ exports.slowQueries = slowQueries;
5
+ const class_type_1 = require("@itrocks/class-type");
6
+ const data_path_1 = require("@itrocks/data-path");
7
+ const store_1 = require("@itrocks/store");
8
+ const mariadb_1 = require("mariadb");
9
+ const node_crypto_1 = require("node:crypto");
10
+ const node_crypto_2 = require("node:crypto");
11
+ const node_crypto_3 = require("node:crypto");
12
+ const promises_1 = require("node:fs/promises");
13
+ const promises_2 = require("node:fs/promises");
14
+ const promises_3 = require("node:fs/promises");
15
+ const promises_4 = require("node:fs/promises");
16
+ const promises_5 = require("node:fs/promises");
17
+ const node_path_1 = require("node:path");
18
+ const node_perf_hooks_1 = require("node:perf_hooks");
19
+ const mysql_maintainer_1 = require("./mysql-maintainer");
20
+ const query_index_1 = require("./query-index");
21
+ const query_index_2 = require("./query-index");
22
+ const query_index_3 = require("./query-index");
23
+ const cacheLifetime = 60 * 60 * 1_000;
24
+ const cacheSize = 1_024;
25
+ const calibrationTable = '_itrocks_read_calibration';
26
+ const maxThreshold = 10;
27
+ const monitors = new WeakMap();
28
+ const processMarker = (0, node_crypto_3.randomUUID)();
29
+ let sequence = 0;
30
+ const thresholds = new Map();
31
+ async function calibrate(query) {
32
+ await query(`CREATE TEMPORARY TABLE ${calibrationTable} (probe VARCHAR(32) NOT NULL, INDEX probe_prefix (probe(10)))
33
+ ENGINE=InnoDB`);
34
+ try {
35
+ const values = Array.from({ length: 1_000 }, () => (0, node_crypto_2.randomBytes)(16).toString('hex'));
36
+ const rows = Array(1_000).fill('(?)').join(', ');
37
+ const select = `SELECT probe FROM ${calibrationTable} FORCE INDEX (probe_prefix) WHERE probe = ?`;
38
+ await query(`INSERT INTO ${calibrationTable} (probe) VALUES ${rows}`, values);
39
+ await query(select, [values.at(-1)]);
40
+ const measurements = [];
41
+ for (let index = 0; index < 10; index++) {
42
+ const sample = marker();
43
+ await query(`${sample}${select}`, [values[index * 100]]);
44
+ const timing = await readTiming(query, sample);
45
+ if (!timing)
46
+ return undefined;
47
+ measurements.push(timing.elapsed);
48
+ }
49
+ measurements.sort((left, right) => left - right);
50
+ const median = (measurements[4] + measurements[5]) / 2;
51
+ return (median > 0) ? Math.min(2 * median, maxThreshold) : undefined;
52
+ }
53
+ finally {
54
+ await query(`DROP TEMPORARY TABLE ${calibrationTable}`);
55
+ }
56
+ }
57
+ function marker() {
58
+ return `/* itrocks:${processMarker}:${++sequence} */ `;
59
+ }
60
+ async function readTiming(query, sample) {
61
+ const [timing] = await query(`SELECT TIMER_WAIT AS timerWait, LOCK_TIME AS lockTime, @@SESSION.sql_mode AS sqlMode
62
+ FROM performance_schema.events_statements_history
63
+ WHERE THREAD_ID = PS_CURRENT_THREAD_ID() AND LEFT(SQL_TEXT, ?) = ?`, [sample.length, sample]);
64
+ if (timing?.timerWait == null)
65
+ return undefined;
66
+ return {
67
+ backslashEscapes: !timing.sqlMode.split(',').includes('NO_BACKSLASH_ESCAPES'),
68
+ elapsed: Math.max(0, Number(timing.timerWait) - Number(timing.lockTime)) / 1e9
69
+ };
70
+ }
71
+ async function saveThreshold(path, threshold) {
72
+ const temporary = `${path}.${(0, node_crypto_3.randomUUID)()}`;
73
+ try {
74
+ await (0, promises_1.mkdir)((0, node_path_1.dirname)(path), { recursive: true });
75
+ await (0, promises_5.writeFile)(temporary, `${threshold}\n`);
76
+ await (0, promises_3.rename)(temporary, path);
77
+ }
78
+ finally {
79
+ await (0, promises_4.rm)(temporary, { force: true });
80
+ }
81
+ }
82
+ function slowQueries(config) {
83
+ let monitor = monitors.get(config);
84
+ if (monitor)
85
+ return monitor;
86
+ monitor = new SlowQueries(config, (0, data_path_1.dataPath)('mysql-maintainer', 'indexed-read.ms'));
87
+ monitors.set(config, monitor);
88
+ return monitor;
89
+ }
90
+ class SlowQueries {
91
+ config;
92
+ path;
93
+ examined = new Map();
94
+ pending = new Set();
95
+ queue = Promise.resolve();
96
+ threshold;
97
+ constructor(config, path) {
98
+ this.config = config;
99
+ this.path = path;
100
+ }
101
+ async analyse(context, sql, values, tokens, variants) {
102
+ // Use a separate session so index DDL cannot commit a caller's transaction.
103
+ const connection = await (0, mariadb_1.createConnection)({ ...this.config, multipleStatements: false });
104
+ try {
105
+ await connection.query('SET SESSION lock_wait_timeout = 1');
106
+ const maintainer = new mysql_maintainer_1.MysqlMaintainer(connection);
107
+ await maintainer.updateContextIndexes(context, () => this.invalidate());
108
+ const plan = await connection.query(`EXPLAIN ${sql}`, values);
109
+ const candidate = (0, query_index_2.queryIndex)(tokens, plan, variants);
110
+ if (!candidate)
111
+ return;
112
+ const types = Array.isArray(context) ? context : [context];
113
+ if (!types.some(type => (0, store_1.storeOf)((0, class_type_1.typeOf)(type)) === candidate.table))
114
+ return;
115
+ const hash = (0, node_crypto_1.createHash)('sha256').update(candidate.column).digest('hex').slice(0, 24);
116
+ const name = `itrocks_query_${hash}`;
117
+ if (await maintainer.addQueryIndex(candidate.table, candidate.column, name)) {
118
+ this.invalidate();
119
+ }
120
+ }
121
+ finally {
122
+ await connection.end();
123
+ }
124
+ }
125
+ async consider(context, query, sql, values, sample) {
126
+ const threshold = this.threshold;
127
+ if ((threshold === undefined) || (node_perf_hooks_1.performance.now() - sample.started <= threshold))
128
+ return;
129
+ const tokens = (0, query_index_3.queryTokens)(sql);
130
+ if (tokens.includes(';') || tokens.some(token => token.startsWith('/*!')))
131
+ return;
132
+ try {
133
+ const timing = await readTiming(query, sample.marker);
134
+ if (!timing || (timing.elapsed <= threshold))
135
+ return;
136
+ const variants = (0, query_index_1.likeVariants)(tokens, Array.isArray(values) ? values : [], timing.backslashEscapes);
137
+ const key = JSON.stringify([sql, variants]);
138
+ if (this.pending.has(key) || ((this.examined.get(key) ?? 0) > Date.now()))
139
+ return;
140
+ if (this.pending.size >= 32)
141
+ return;
142
+ this.pending.add(key);
143
+ const task = this.queue.then(async () => {
144
+ await this.analyse(context, sql, values, tokens, variants);
145
+ this.examined.delete(key);
146
+ if (this.examined.size >= cacheSize) {
147
+ this.examined.delete(this.examined.keys().next().value);
148
+ }
149
+ this.examined.set(key, Date.now() + cacheLifetime);
150
+ });
151
+ this.queue = task.catch(() => { });
152
+ await task.finally(() => this.pending.delete(key));
153
+ }
154
+ catch {
155
+ // Measurement and index maintenance are best effort after a successful application query.
156
+ }
157
+ }
158
+ async initialise(query) {
159
+ const saved = Number(await (0, promises_2.readFile)(this.path, 'utf8').catch(() => ''));
160
+ if ((saved > 0) && (saved <= maxThreshold))
161
+ return saved;
162
+ const threshold = await calibrate(query).catch(() => undefined);
163
+ if (threshold !== undefined) {
164
+ await saveThreshold(this.path, threshold).catch(() => { });
165
+ }
166
+ return threshold;
167
+ }
168
+ invalidate() {
169
+ this.examined.clear();
170
+ }
171
+ sample(sql) {
172
+ if ((this.threshold === undefined) || !/^\s*(SELECT|UPDATE|DELETE|INSERT)\b/i.test(sql))
173
+ return;
174
+ return { marker: marker(), started: node_perf_hooks_1.performance.now() };
175
+ }
176
+ async start(query) {
177
+ let starting = thresholds.get(this.path);
178
+ if (!starting) {
179
+ starting = this.initialise(query);
180
+ thresholds.set(this.path, starting);
181
+ }
182
+ this.threshold = await starting;
183
+ }
184
+ }
185
+ exports.SlowQueries = SlowQueries;
186
+ //# sourceMappingURL=slow-query.js.map
package/package.json CHANGED
@@ -5,6 +5,7 @@
5
5
  },
6
6
  "dependencies": {
7
7
  "@itrocks/class-type": "latest",
8
+ "@itrocks/data-path": "latest",
8
9
  "@itrocks/mysql": "latest",
9
10
  "@itrocks/mysql-to-schema": "latest",
10
11
  "@itrocks/reflect": "latest",
@@ -16,14 +17,14 @@
16
17
  "@itrocks/sql-build": "latest",
17
18
  "@itrocks/storage": "latest",
18
19
  "@itrocks/store": "latest",
19
- "@itrocks/unique": "latest",
20
20
  "mariadb": "^3.4"
21
21
  },
22
- "description": "Reactively maintains database structure by updating schema and retrying on MySQL errors",
22
+ "description": "Repairs schema errors and adds indexes for slow MySQL queries",
23
23
  "devDependencies": {
24
24
  "@itrocks/class-file": "latest",
25
25
  "@itrocks/rename": "latest",
26
26
  "@itrocks/sql-join": "latest",
27
+ "@itrocks/unique": "latest",
27
28
  "@types/node": "^24.10",
28
29
  "typescript": "^7.0"
29
30
  },
@@ -61,5 +62,5 @@
61
62
  "test": "npm run build && node --test \"test/**/*.test.mjs\"",
62
63
  "test:integration": "npm run build && node --test \"test/**/*.integration.mjs\""
63
64
  },
64
- "version": "0.4.2"
65
+ "version": "0.7.0"
65
66
  }