@zero-server/sdk 0.9.0 → 0.9.2

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 (126) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +460 -437
  3. package/index.js +414 -412
  4. package/lib/app.js +1172 -1172
  5. package/lib/auth/authorize.js +399 -399
  6. package/lib/auth/enrollment.js +367 -367
  7. package/lib/auth/index.js +57 -57
  8. package/lib/auth/jwt.js +731 -731
  9. package/lib/auth/oauth.js +362 -362
  10. package/lib/auth/session.js +588 -588
  11. package/lib/auth/trustedDevice.js +409 -409
  12. package/lib/auth/twoFactor.js +1150 -1150
  13. package/lib/auth/webauthn.js +946 -946
  14. package/lib/body/index.js +14 -14
  15. package/lib/body/json.js +109 -109
  16. package/lib/body/multipart.js +440 -440
  17. package/lib/body/raw.js +71 -71
  18. package/lib/body/rawBuffer.js +160 -160
  19. package/lib/body/sendError.js +25 -25
  20. package/lib/body/text.js +75 -75
  21. package/lib/body/typeMatch.js +41 -41
  22. package/lib/body/urlencoded.js +235 -235
  23. package/lib/cli.js +845 -845
  24. package/lib/cluster.js +666 -666
  25. package/lib/debug.js +372 -372
  26. package/lib/env/index.js +460 -460
  27. package/lib/errors.js +683 -683
  28. package/lib/fetch/index.js +256 -256
  29. package/lib/grpc/balancer.js +378 -378
  30. package/lib/grpc/call.js +708 -708
  31. package/lib/grpc/client.js +764 -764
  32. package/lib/grpc/codec.js +1221 -1221
  33. package/lib/grpc/credentials.js +398 -398
  34. package/lib/grpc/frame.js +262 -262
  35. package/lib/grpc/health.js +287 -287
  36. package/lib/grpc/index.js +121 -121
  37. package/lib/grpc/metadata.js +461 -461
  38. package/lib/grpc/proto.js +821 -821
  39. package/lib/grpc/reflection.js +590 -590
  40. package/lib/grpc/server.js +445 -445
  41. package/lib/grpc/status.js +118 -118
  42. package/lib/grpc/watch.js +173 -173
  43. package/lib/http/index.js +10 -10
  44. package/lib/http/request.js +727 -727
  45. package/lib/http/response.js +799 -799
  46. package/lib/lifecycle.js +557 -557
  47. package/lib/middleware/compress.js +230 -230
  48. package/lib/middleware/cookieParser.js +237 -237
  49. package/lib/middleware/cors.js +93 -93
  50. package/lib/middleware/csrf.js +136 -136
  51. package/lib/middleware/errorHandler.js +101 -101
  52. package/lib/middleware/helmet.js +175 -175
  53. package/lib/middleware/index.js +19 -17
  54. package/lib/middleware/logger.js +74 -74
  55. package/lib/middleware/rateLimit.js +88 -88
  56. package/lib/middleware/requestId.js +53 -53
  57. package/lib/middleware/static.js +326 -326
  58. package/lib/middleware/timeout.js +71 -71
  59. package/lib/middleware/validator.js +254 -254
  60. package/lib/observe/health.js +326 -326
  61. package/lib/observe/index.js +50 -50
  62. package/lib/observe/logger.js +359 -359
  63. package/lib/observe/metrics.js +805 -805
  64. package/lib/observe/tracing.js +592 -592
  65. package/lib/orm/adapters/json.js +290 -290
  66. package/lib/orm/adapters/memory.js +764 -764
  67. package/lib/orm/adapters/mongo.js +764 -764
  68. package/lib/orm/adapters/mysql.js +933 -933
  69. package/lib/orm/adapters/postgres.js +1144 -1144
  70. package/lib/orm/adapters/redis.js +1534 -1534
  71. package/lib/orm/adapters/sql-base.js +212 -212
  72. package/lib/orm/adapters/sqlite.js +858 -858
  73. package/lib/orm/audit.js +649 -649
  74. package/lib/orm/cache.js +394 -394
  75. package/lib/orm/geo.js +387 -387
  76. package/lib/orm/index.js +784 -784
  77. package/lib/orm/migrate.js +432 -432
  78. package/lib/orm/model.js +1706 -1706
  79. package/lib/orm/plugin.js +375 -375
  80. package/lib/orm/procedures.js +836 -836
  81. package/lib/orm/profiler.js +233 -233
  82. package/lib/orm/query.js +1772 -1772
  83. package/lib/orm/replicas.js +241 -241
  84. package/lib/orm/schema.js +307 -307
  85. package/lib/orm/search.js +380 -380
  86. package/lib/orm/seed/data/commerce.js +136 -136
  87. package/lib/orm/seed/data/internet.js +111 -111
  88. package/lib/orm/seed/data/locations.js +204 -204
  89. package/lib/orm/seed/data/names.js +338 -338
  90. package/lib/orm/seed/data/person.js +128 -128
  91. package/lib/orm/seed/data/phone.js +211 -211
  92. package/lib/orm/seed/data/words.js +134 -134
  93. package/lib/orm/seed/factory.js +178 -178
  94. package/lib/orm/seed/fake.js +1186 -1186
  95. package/lib/orm/seed/index.js +18 -18
  96. package/lib/orm/seed/rng.js +70 -70
  97. package/lib/orm/seed/seeder.js +124 -124
  98. package/lib/orm/seed/unique.js +68 -68
  99. package/lib/orm/snapshot.js +366 -366
  100. package/lib/orm/tenancy.js +605 -605
  101. package/lib/orm/views.js +350 -350
  102. package/lib/router/index.js +436 -436
  103. package/lib/sse/index.js +8 -8
  104. package/lib/sse/stream.js +349 -349
  105. package/lib/ws/connection.js +451 -451
  106. package/lib/ws/handshake.js +125 -125
  107. package/lib/ws/index.js +14 -14
  108. package/lib/ws/room.js +223 -223
  109. package/package.json +73 -73
  110. package/types/app.d.ts +223 -223
  111. package/types/auth.d.ts +520 -520
  112. package/types/cluster.d.ts +75 -75
  113. package/types/env.d.ts +80 -80
  114. package/types/errors.d.ts +316 -316
  115. package/types/fetch.d.ts +43 -43
  116. package/types/grpc.d.ts +432 -432
  117. package/types/index.d.ts +384 -384
  118. package/types/lifecycle.d.ts +60 -60
  119. package/types/middleware.d.ts +320 -320
  120. package/types/observe.d.ts +304 -304
  121. package/types/orm.d.ts +1887 -1887
  122. package/types/request.d.ts +109 -109
  123. package/types/response.d.ts +157 -157
  124. package/types/router.d.ts +78 -78
  125. package/types/sse.d.ts +78 -78
  126. package/types/websocket.d.ts +126 -126
@@ -1,933 +1,933 @@
1
- /**
2
- * @module orm/adapters/mysql
3
- * @description MySQL / MariaDB adapter using the optional `mysql2` driver.
4
- * Requires: `npm install mysql2`
5
- *
6
- * @example
7
- * const { Database, Model, TYPES } = require('@zero-server/sdk');
8
- *
9
- * const db = Database.connect('mysql', {
10
- * host: '127.0.0.1',
11
- * user: 'root',
12
- * password: '',
13
- * database: 'myapp',
14
- * });
15
- *
16
- * class Product extends Model {
17
- * static table = 'products';
18
- * static schema = {
19
- * id: { type: TYPES.INTEGER, primaryKey: true, autoIncrement: true },
20
- * name: { type: TYPES.STRING, required: true, maxLength: 255 },
21
- * price: { type: TYPES.DECIMAL, required: true, min: 0 },
22
- * };
23
- * static timestamps = true;
24
- * }
25
- *
26
- * db.register(Product);
27
- * await db.sync();
28
- *
29
- * await Product.create({ name: 'Widget', price: 9.99 });
30
- * const cheap = await Product.query().where('price', '<', 20).exec();
31
- */
32
- const BaseSqlAdapter = require('./sql-base');
33
- const { validateFKAction, validateCheck } = require('../schema');
34
-
35
- class MysqlAdapter extends BaseSqlAdapter
36
- {
37
- /**
38
- * @constructor
39
- * @param {object} options - Configuration options.
40
- * @param {string} [options.host='localhost'] - Server hostname.
41
- * @param {number} [options.port=3306] - Server port.
42
- * @param {string} [options.user='root'] - Database user.
43
- * @param {string} [options.password=''] - Database password.
44
- * @param {string} options.database - Database name.
45
- * @param {number} [options.connectionLimit=10] - Max pool connections.
46
- * @param {boolean} [options.waitForConnections=true] - Queue when pool is full.
47
- * @param {number} [options.queueLimit=0] - Max queued requests (0 = unlimited).
48
- * @param {number} [options.connectTimeout=10000] - Connection timeout in ms.
49
- * @param {string} [options.charset='utf8mb4'] - Default character set.
50
- * @param {string} [options.timezone='Z'] - Session timezone.
51
- * @param {boolean} [options.multipleStatements=false] - Allow multi-statement queries.
52
- * @param {boolean} [options.decimalNumbers=false] - Return DECIMAL as numbers instead of strings.
53
- * @param {string} [options.ssl] - SSL profile or options object.
54
- */
55
- constructor(options = {})
56
- {
57
- super();
58
- let mysql;
59
- try { mysql = require('mysql2/promise'); }
60
- catch (e)
61
- {
62
- throw new Error(
63
- 'MySQL adapter requires "mysql2" package.\n' +
64
- 'Install it with: npm install mysql2'
65
- );
66
- }
67
- this._pool = mysql.createPool({
68
- connectionLimit: 10,
69
- waitForConnections: true,
70
- ...options,
71
- });
72
- this._options = options;
73
-
74
- /** @private Query fingerprint tracking for prepared statement metrics */
75
- this._queryFingerprints = new Map();
76
- this._queryCount = 0;
77
- }
78
-
79
- /** @private */
80
- _typeMap(colDef)
81
- {
82
- const esc = v => v.replace(/'/g, "''");
83
- const map = {
84
- string: `VARCHAR(${colDef.maxLength || 255})`, text: 'TEXT',
85
- integer: 'INT', float: 'DOUBLE', boolean: 'TINYINT(1)',
86
- date: 'DATE', datetime: 'DATETIME', json: 'JSON', blob: 'BLOB', uuid: 'CHAR(36)',
87
- bigint: 'BIGINT', smallint: 'SMALLINT', tinyint: 'TINYINT',
88
- decimal: `DECIMAL(${colDef.precision || 10},${colDef.scale || 2})`,
89
- mediumtext: 'MEDIUMTEXT', longtext: 'LONGTEXT',
90
- mediumblob: 'MEDIUMBLOB', longblob: 'LONGBLOB',
91
- enum: colDef.enum ? `ENUM(${colDef.enum.map(v => `'${esc(String(v))}'`).join(',')})` : 'VARCHAR(255)',
92
- set: colDef.values ? `SET(${colDef.values.map(v => `'${esc(String(v))}'`).join(',')})` : 'VARCHAR(255)',
93
- timestamp: 'TIMESTAMP',
94
- time: 'TIME',
95
- year: 'YEAR',
96
- binary: `BINARY(${colDef.length || 255})`,
97
- varbinary: `VARBINARY(${colDef.length || 255})`,
98
- double: 'DOUBLE',
99
- real: 'REAL',
100
- };
101
- return map[colDef.type] || 'TEXT';
102
- }
103
-
104
- /** @private */
105
- _q(name) { return '`' + name.replace(/`/g, '``') + '`'; }
106
-
107
- /**
108
- * Create a table with the given schema.
109
- * @param {string} table - Table name.
110
- * @param {object} schema - Column definitions keyed by column name.
111
- * @returns {Promise<void>}
112
- */
113
- async createTable(table, schema, tableOptions = {})
114
- {
115
- const cols = [];
116
- const tableConstraints = [];
117
- const compositePKs = [];
118
-
119
- for (const [name, def] of Object.entries(schema))
120
- {
121
- let line = `${this._q(name)} ${this._typeMap(def)}`;
122
-
123
- // Collect composite PK candidates
124
- if (def.primaryKey && def.compositeKey) { compositePKs.push(name); }
125
- else if (def.primaryKey)
126
- {
127
- line += ' PRIMARY KEY';
128
- if (def.autoIncrement) line += ' AUTO_INCREMENT';
129
- }
130
-
131
- if (def.unsigned) line += ' UNSIGNED';
132
- if (def.required && !def.primaryKey) line += ' NOT NULL';
133
- if (def.unique && !def.compositeUnique) line += ' UNIQUE';
134
- if (def.default !== undefined && typeof def.default !== 'function')
135
- line += ` DEFAULT ${this._sqlDefault(def.default)}`;
136
-
137
- // CHECK constraint
138
- if (def.check)
139
- {
140
- line += ` CHECK(${validateCheck(def.check)})`;
141
- }
142
-
143
- if (def.charset) line += ` CHARACTER SET ${this._safeIdent(def.charset)}`;
144
- if (def.collation) line += ` COLLATE ${this._safeIdent(def.collation)}`;
145
- if (def.comment) line += ` COMMENT '${def.comment.replace(/'/g, "''")}'`;
146
- cols.push(line);
147
-
148
- // Foreign key constraint (table-level)
149
- if (def.references)
150
- {
151
- const fkName = `fk_${table}_${name}`;
152
- let fk = `CONSTRAINT ${this._q(fkName)} FOREIGN KEY (${this._q(name)}) REFERENCES ${this._q(def.references.table)}(${this._q(def.references.column || 'id')})`;
153
- if (def.references.onDelete) fk += ` ON DELETE ${validateFKAction(def.references.onDelete)}`;
154
- if (def.references.onUpdate) fk += ` ON UPDATE ${validateFKAction(def.references.onUpdate)}`;
155
- tableConstraints.push(fk);
156
- }
157
- }
158
-
159
- // Composite primary key
160
- if (compositePKs.length > 0)
161
- {
162
- tableConstraints.push(`PRIMARY KEY (${compositePKs.map(k => this._q(k)).join(', ')})`);
163
- }
164
-
165
- // Composite unique constraints
166
- const compositeUniques = {};
167
- for (const [name, def] of Object.entries(schema))
168
- {
169
- if (def.compositeUnique)
170
- {
171
- const group = typeof def.compositeUnique === 'string' ? def.compositeUnique : 'default';
172
- if (!compositeUniques[group]) compositeUniques[group] = [];
173
- compositeUniques[group].push(name);
174
- }
175
- }
176
- for (const [group, columns] of Object.entries(compositeUniques))
177
- {
178
- tableConstraints.push(`UNIQUE KEY ${this._q(`uq_${table}_${group}`)} (${columns.map(c => this._q(c)).join(', ')})`);
179
- }
180
-
181
- const allParts = [...cols, ...tableConstraints];
182
- let sql = `CREATE TABLE IF NOT EXISTS ${this._q(table)} (${allParts.join(', ')})`;
183
- const engine = tableOptions.engine || this._options.engine || 'InnoDB';
184
- const charset = tableOptions.charset || this._options.charset || 'utf8mb4';
185
- const collation = tableOptions.collation || this._options.collation || 'utf8mb4_unicode_ci';
186
- sql += ` ENGINE=${this._safeIdent(engine)}`;
187
- sql += ` DEFAULT CHARSET=${this._safeIdent(charset)}`;
188
- sql += ` COLLATE=${this._safeIdent(collation)}`;
189
- if (tableOptions.comment) sql += ` COMMENT='${tableOptions.comment.replace(/'/g, "''")}'`;
190
- await this._pool.execute(sql);
191
-
192
- // Create indexes defined in schema
193
- for (const [name, def] of Object.entries(schema))
194
- {
195
- if (def.index)
196
- {
197
- const idxName = typeof def.index === 'string' ? def.index : `idx_${table}_${name}`;
198
- await this._pool.execute(`CREATE INDEX ${this._q(idxName)} ON ${this._q(table)} (${this._q(name)})`);
199
- }
200
- }
201
-
202
- // Composite indexes
203
- const compositeIndexes = {};
204
- for (const [name, def] of Object.entries(schema))
205
- {
206
- if (def.compositeIndex)
207
- {
208
- const group = typeof def.compositeIndex === 'string' ? def.compositeIndex : 'default';
209
- if (!compositeIndexes[group]) compositeIndexes[group] = [];
210
- compositeIndexes[group].push(name);
211
- }
212
- }
213
- for (const [group, columns] of Object.entries(compositeIndexes))
214
- {
215
- const idxName = `idx_${table}_${group}`;
216
- await this._pool.execute(`CREATE INDEX ${this._q(idxName)} ON ${this._q(table)} (${columns.map(c => this._q(c)).join(', ')})`);
217
- }
218
- }
219
-
220
- /**
221
- * Drop a table if it exists.
222
- * @param {string} table - Table name.
223
- * @returns {Promise<void>}
224
- */
225
- async dropTable(table)
226
- {
227
- await this._pool.execute(`DROP TABLE IF EXISTS ${this._q(table)}`);
228
- }
229
-
230
- /**
231
- * Insert a single row.
232
- * @param {string} table - Table name.
233
- * @param {object} data - Row data as key-value pairs.
234
- * @returns {Promise<object>} The inserted row.
235
- */
236
- async insert(table, data)
237
- {
238
- const keys = Object.keys(data);
239
- const placeholders = keys.map(() => '?').join(', ');
240
- const values = keys.map(k => this._toSqlValue(data[k]));
241
- const [result] = await this._pool.execute(
242
- `INSERT INTO ${this._q(table)} (${keys.map(k => this._q(k)).join(', ')}) VALUES (${placeholders})`,
243
- values
244
- );
245
- return { ...data, id: result.insertId || data.id };
246
- }
247
-
248
- /**
249
- * Insert multiple rows in a batch.
250
- * @param {string} table - Table name.
251
- * @param {Array<object>} dataArray - Array of row objects.
252
- * @returns {Promise<Array<object>>} The inserted rows.
253
- */
254
- async insertMany(table, dataArray)
255
- {
256
- if (!dataArray.length) return [];
257
- const keys = Object.keys(dataArray[0]);
258
- const singlePlaceholders = `(${keys.map(() => '?').join(', ')})`;
259
- const allPlaceholders = dataArray.map(() => singlePlaceholders).join(', ');
260
- const values = [];
261
- for (const data of dataArray)
262
- {
263
- for (const k of keys) values.push(this._toSqlValue(data[k]));
264
- }
265
- const sql = `INSERT INTO ${this._q(table)} (${keys.map(k => this._q(k)).join(', ')}) VALUES ${allPlaceholders}`;
266
- const [result] = await this._pool.execute(sql, values);
267
- return dataArray.map((data, i) => ({ ...data, id: (result.insertId || 0) + i }));
268
- }
269
-
270
- /**
271
- * Update a single row by primary key.
272
- * @param {string} table - Table name.
273
- * @param {string} pk - Primary key column.
274
- * @param {*} pkVal - Primary key value.
275
- * @param {object} data - Fields to update.
276
- * @returns {Promise<void>}
277
- */
278
- async update(table, pk, pkVal, data)
279
- {
280
- const sets = Object.keys(data).map(k => `${this._q(k)} = ?`).join(', ');
281
- const values = [...Object.values(data).map(v => this._toSqlValue(v)), pkVal];
282
- await this._pool.execute(`UPDATE ${this._q(table)} SET ${sets} WHERE ${this._q(pk)} = ?`, values);
283
- }
284
-
285
- /**
286
- * Update rows matching the given conditions.
287
- * @param {string} table - Table name.
288
- * @param {object} conditions - Filter conditions.
289
- * @param {object} data - Fields to update.
290
- * @returns {Promise<number>} Number of affected rows.
291
- */
292
- async updateWhere(table, conditions, data)
293
- {
294
- const { clause, values: whereVals } = this._buildWhere(conditions);
295
- const sets = Object.keys(data).map(k => `${this._q(k)} = ?`).join(', ');
296
- const values = [...Object.values(data).map(v => this._toSqlValue(v)), ...whereVals];
297
- const sql = `UPDATE ${this._q(table)} SET ${sets}${clause.replace(/"/g, '`')}`;
298
- const [result] = await this._pool.execute(sql, values);
299
- return result.affectedRows;
300
- }
301
-
302
- /**
303
- * Delete a single row by primary key.
304
- * @param {string} table - Table name.
305
- * @param {string} pk - Primary key column.
306
- * @param {*} pkVal - Primary key value.
307
- * @returns {Promise<void>}
308
- */
309
- async remove(table, pk, pkVal)
310
- {
311
- await this._pool.execute(`DELETE FROM ${this._q(table)} WHERE ${this._q(pk)} = ?`, [pkVal]);
312
- }
313
-
314
- /**
315
- * Delete rows matching the given conditions.
316
- * @param {string} table - Table name.
317
- * @param {object} conditions - Filter conditions.
318
- * @returns {Promise<number>} Number of deleted rows.
319
- */
320
- async deleteWhere(table, conditions)
321
- {
322
- const { clause, values } = this._buildWhere(conditions);
323
- const sql = `DELETE FROM ${this._q(table)}${clause.replace(/"/g, '`')}`;
324
- const [result] = await this._pool.execute(sql, values);
325
- return result.affectedRows;
326
- }
327
-
328
- /**
329
- * Execute a query descriptor built by the Query builder.
330
- * @param {object} descriptor - Query descriptor with table, fields, where, orderBy, limit, offset.
331
- * @returns {Promise<Array<object>>} Result rows.
332
- */
333
- async execute(descriptor)
334
- {
335
- const { action, table, fields, where, orderBy, limit, offset, distinct, joins, groupBy, having } = descriptor;
336
- const q = this._q.bind(this);
337
-
338
- if (action === 'count')
339
- {
340
- const { clause, values } = this._buildWhereFromChain(where);
341
- const joinStr = this._buildJoins(joins, table, q);
342
- const sql = `SELECT COUNT(*) as count FROM ${q(table)}${joinStr}${clause.replace(/"/g, '`')}`;
343
- const [rows] = await this._pool.execute(sql, values);
344
- return rows[0].count;
345
- }
346
-
347
- const selectFields = fields && fields.length ? fields.map(f => q(f)).join(', ') : '*';
348
- const distinctStr = distinct ? 'DISTINCT ' : '';
349
- const joinStr = this._buildJoins(joins, table, q);
350
- let sql = `SELECT ${distinctStr}${selectFields} FROM ${q(table)}${joinStr}`;
351
- const values = [];
352
-
353
- if (where && where.length)
354
- {
355
- const { clause, values: wv } = this._buildWhereFromChain(where);
356
- sql += clause.replace(/"/g, '`');
357
- values.push(...wv);
358
- }
359
-
360
- sql += this._buildGroupBy(groupBy, q);
361
- sql += this._buildHaving(having, values, q);
362
-
363
- if (orderBy && orderBy.length)
364
- sql += ' ORDER BY ' + orderBy.map(o => `${q(o.field)} ${o.dir}`).join(', ');
365
- if (limit !== null && limit !== undefined) { sql += ' LIMIT ?'; values.push(limit); }
366
- if (offset !== null && offset !== undefined) { sql += ' OFFSET ?'; values.push(offset); }
367
-
368
- const [rows] = await this._pool.execute(sql, values);
369
- return rows;
370
- }
371
-
372
- /**
373
- * Execute an aggregate function (count, sum, avg, min, max).
374
- * @param {object} descriptor - Aggregate descriptor with table, function, field, where.
375
- * @returns {Promise<number|null>} Aggregate result.
376
- */
377
- async aggregate(descriptor)
378
- {
379
- const { table, where, aggregateFn, aggregateField, joins, groupBy, having } = descriptor;
380
- const q = this._q.bind(this);
381
- const fn = aggregateFn.toUpperCase();
382
- const joinStr = this._buildJoins(joins, table, q);
383
- const values = [];
384
-
385
- let sql = `SELECT ${fn}(${q(aggregateField)}) as result FROM ${q(table)}${joinStr}`;
386
-
387
- if (where && where.length)
388
- {
389
- const { clause, values: wv } = this._buildWhereFromChain(where);
390
- sql += clause.replace(/"/g, '`');
391
- values.push(...wv);
392
- }
393
-
394
- sql += this._buildGroupBy(groupBy, q);
395
- sql += this._buildHaving(having, values, q);
396
-
397
- const [rows] = await this._pool.execute(sql, values);
398
- return rows[0] ? rows[0].result : null;
399
- }
400
-
401
- /**
402
- * Get the query execution plan (EXPLAIN).
403
- * @param {object} descriptor - Query descriptor.
404
- * @param {object} [options] - Configuration options.
405
- * @param {boolean} [options.analyze] - Use EXPLAIN ANALYZE (MySQL 8.0.18+).
406
- * @returns {Promise<Array>} Array of execution plan rows.
407
- */
408
- async explain(descriptor, options = {})
409
- {
410
- const { table, fields, where, orderBy, limit, offset, distinct, joins, groupBy, having } = descriptor;
411
- const q = this._q.bind(this);
412
-
413
- const selectFields = fields && fields.length ? fields.map(f => q(f)).join(', ') : '*';
414
- const distinctStr = distinct ? 'DISTINCT ' : '';
415
- const joinStr = this._buildJoins(joins, table, q);
416
- let sql = `SELECT ${distinctStr}${selectFields} FROM ${q(table)}${joinStr}`;
417
- const values = [];
418
-
419
- if (where && where.length)
420
- {
421
- const { clause, values: wv } = this._buildWhereFromChain(where);
422
- sql += clause.replace(/"/g, '`');
423
- values.push(...wv);
424
- }
425
-
426
- sql += this._buildGroupBy(groupBy, q);
427
- sql += this._buildHaving(having, values, q);
428
-
429
- if (orderBy && orderBy.length)
430
- sql += ' ORDER BY ' + orderBy.map(o => `${q(o.field)} ${o.dir}`).join(', ');
431
- if (limit !== null && limit !== undefined) { sql += ' LIMIT ?'; values.push(limit); }
432
- if (offset !== null && offset !== undefined) { sql += ' OFFSET ?'; values.push(offset); }
433
-
434
- const prefix = options.analyze ? 'EXPLAIN ANALYZE' : 'EXPLAIN';
435
- const [rows] = await this._pool.execute(`${prefix} ${sql}`, values);
436
- return rows;
437
- }
438
-
439
- /**
440
- * Get prepared statement cache statistics.
441
- * mysql2 handles prepared statement caching internally per connection.
442
- * @returns {{ uniqueQueries: number, totalQueries: number, driver: string }}
443
- */
444
- stmtCacheStats()
445
- {
446
- return {
447
- uniqueQueries: this._queryFingerprints.size,
448
- totalQueries: this._queryCount,
449
- driver: 'mysql2 (internal prepared statement caching)',
450
- };
451
- }
452
-
453
- /**
454
- * Pre-warm the connection pool by creating idle connections.
455
- * @param {number} [count=5] - Number of connections to warm up.
456
- * @returns {Promise<number>} Number of connections successfully warmed.
457
- */
458
- async warmup(count)
459
- {
460
- const n = Math.min(Math.max(1, Math.floor(Number(count) || 5)), this._options.connectionLimit || 10);
461
- const connections = [];
462
- for (let i = 0; i < n; i++)
463
- {
464
- try
465
- {
466
- const conn = await this._pool.getConnection();
467
- connections.push(conn);
468
- }
469
- catch (e) { break; }
470
- }
471
- for (const conn of connections) conn.release();
472
- return connections.length;
473
- }
474
-
475
- /**
476
- * Close the database connection.
477
- * @returns {Promise<void>}
478
- */
479
- async close() { await this._pool.end(); }
480
-
481
- /** @override */
482
- async raw(sql, ...params) { const [rows] = await this._pool.execute(sql, params); return rows; }
483
-
484
- /** @override */
485
- async transaction(fn)
486
- {
487
- const conn = await this._pool.getConnection();
488
- try
489
- {
490
- await conn.beginTransaction();
491
- const result = await fn(conn);
492
- await conn.commit();
493
- return result;
494
- }
495
- catch (e) { await conn.rollback(); throw e; }
496
- finally { conn.release(); }
497
- }
498
-
499
- // -- MySQL Utilities ---------------------------------
500
-
501
- /**
502
- * List all user-created tables in the current database.
503
- * @returns {Promise<string[]>} Array of table names.
504
- */
505
- async tables()
506
- {
507
- const [rows] = await this._pool.execute('SHOW TABLES');
508
- return rows.map(r => Object.values(r)[0]);
509
- }
510
-
511
- /**
512
- * Get the columns of a table.
513
- * @param {string} table - Table name.
514
- * @returns {Promise<Array<{ Field: string, Type: string, Null: string, Key: string, Default: *, Extra: string }>>}
515
- */
516
- async columns(table)
517
- {
518
- const [rows] = await this._pool.execute(`SHOW COLUMNS FROM ${this._q(table)}`);
519
- return rows;
520
- }
521
-
522
- /**
523
- * Get the current database size in bytes.
524
- * @returns {Promise<number>} Database size in bytes.
525
- */
526
- async databaseSize()
527
- {
528
- const db = this._options.database;
529
- if (!db) return 0;
530
- const [rows] = await this._pool.execute(
531
- `SELECT SUM(data_length + index_length) AS size
532
- FROM information_schema.tables WHERE table_schema = ?`, [db]
533
- );
534
- return Number(rows[0].size) || 0;
535
- }
536
-
537
- /**
538
- * Get connection pool status.
539
- * @returns {{ total: number, idle: number, used: number, queued: number }}
540
- */
541
- poolStatus()
542
- {
543
- const pool = this._pool.pool;
544
- if (!pool) return { total: 0, idle: 0, used: 0, queued: 0 };
545
- return {
546
- total: pool._allConnections?.length || 0,
547
- idle: pool._freeConnections?.length || 0,
548
- used: (pool._allConnections?.length || 0) - (pool._freeConnections?.length || 0),
549
- queued: pool._connectionQueue?.length || 0,
550
- };
551
- }
552
-
553
- /**
554
- * Get the MySQL/MariaDB server version string.
555
- * @returns {Promise<string>} Server version string (e.g. `"8.0.35"`).
556
- */
557
- async version()
558
- {
559
- const [rows] = await this._pool.execute('SELECT VERSION() AS ver');
560
- return rows[0].ver;
561
- }
562
-
563
- /**
564
- * Ping the database to check connectivity.
565
- * @returns {Promise<boolean>} `true` if the server is reachable.
566
- */
567
- async ping()
568
- {
569
- try
570
- {
571
- const conn = await this._pool.getConnection();
572
- await conn.ping();
573
- conn.release();
574
- return true;
575
- }
576
- catch { return false; }
577
- }
578
-
579
- /**
580
- * Execute a raw statement that doesn't return rows (INSERT, UPDATE, DDL).
581
- * @param {string} sql - SQL query string.
582
- * @param {...*} params - Bound parameter values.
583
- * @returns {Promise<{ affectedRows: number, insertId: number }>}
584
- */
585
- async exec(sql, ...params)
586
- {
587
- const [result] = await this._pool.execute(sql, params);
588
- return { affectedRows: result.affectedRows || 0, insertId: result.insertId || 0 };
589
- }
590
-
591
- // -- Table Info & Debug (Schema Introspection) -----------
592
-
593
- /**
594
- * Get detailed table status (rows, size, engine, collation, etc.).
595
- * Returns a structured database overview.
596
- * @param {string} [table] - Table name. If omitted, returns all tables.
597
- * @returns {Promise<Array<{ name: string, engine: string, rows: number, dataLength: number, indexLength: number, totalSize: number, autoIncrement: number, collation: string, createTime: string, updateTime: string, comment: string }>>}
598
- */
599
- async tableStatus(table)
600
- {
601
- let sql = 'SHOW TABLE STATUS';
602
- const params = [];
603
- if (table){ sql += ` LIKE ?`; params.push(table); }
604
- const [rows] = await this._pool.execute(sql, params);
605
- return rows.map(r => ({
606
- name: r.Name, engine: r.Engine, rows: Number(r.Rows) || 0,
607
- dataLength: Number(r.Data_length) || 0, indexLength: Number(r.Index_length) || 0,
608
- totalSize: (Number(r.Data_length) || 0) + (Number(r.Index_length) || 0),
609
- autoIncrement: r.Auto_increment, collation: r.Collation,
610
- createTime: r.Create_time, updateTime: r.Update_time,
611
- comment: r.Comment || '',
612
- }));
613
- }
614
-
615
- /**
616
- * Get table size in a human-readable format.
617
- * @param {string} table - Table name.
618
- * @returns {Promise<{ rows: number, dataSize: string, indexSize: string, totalSize: string }>}
619
- */
620
- async tableSize(table)
621
- {
622
- const status = await this.tableStatus(table);
623
- if (!status.length) return { rows: 0, dataSize: '0 B', indexSize: '0 B', totalSize: '0 B' };
624
- const s = status[0];
625
- const fmt = (b) => {
626
- if (b >= 1073741824) return (b / 1073741824).toFixed(2) + ' GB';
627
- if (b >= 1048576) return (b / 1048576).toFixed(2) + ' MB';
628
- if (b >= 1024) return (b / 1024).toFixed(2) + ' KB';
629
- return b + ' B';
630
- };
631
- return { rows: s.rows, dataSize: fmt(s.dataLength), indexSize: fmt(s.indexLength), totalSize: fmt(s.totalSize) };
632
- }
633
-
634
- /**
635
- * Get indexes for a table.
636
- * @param {string} table - Table name.
637
- * @returns {Promise<Array<{ name: string, column: string, unique: boolean, type: string, cardinality: number }>>}
638
- */
639
- async indexes(table)
640
- {
641
- const [rows] = await this._pool.execute(`SHOW INDEX FROM ${this._q(table)}`);
642
- return rows.map(r => ({
643
- name: r.Key_name, column: r.Column_name, unique: !r.Non_unique,
644
- type: r.Index_type, cardinality: Number(r.Cardinality) || 0,
645
- }));
646
- }
647
-
648
- /**
649
- * Get the charset and collation of a table.
650
- * @param {string} table - Table name.
651
- * @returns {Promise<{ charset: string, collation: string }>}
652
- */
653
- async tableCharset(table)
654
- {
655
- const [rows] = await this._pool.execute(
656
- `SELECT TABLE_COLLATION FROM information_schema.tables WHERE table_schema = ? AND table_name = ?`,
657
- [this._options.database, table]
658
- );
659
- if (!rows.length) return { charset: '', collation: '' };
660
- const collation = rows[0].TABLE_COLLATION || '';
661
- const charset = collation.split('_')[0] || '';
662
- return { charset, collation };
663
- }
664
-
665
- /**
666
- * Get foreign keys for a table.
667
- * @param {string} table - Table name.
668
- * @returns {Promise<Array<{ constraintName: string, column: string, referencedTable: string, referencedColumn: string, onDelete: string, onUpdate: string }>>}
669
- */
670
- async foreignKeys(table)
671
- {
672
- const [rows] = await this._pool.execute(
673
- `SELECT CONSTRAINT_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME,
674
- DELETE_RULE, UPDATE_RULE
675
- FROM information_schema.KEY_COLUMN_USAGE kcu
676
- JOIN information_schema.REFERENTIAL_CONSTRAINTS rc USING (CONSTRAINT_NAME, CONSTRAINT_SCHEMA)
677
- WHERE kcu.TABLE_SCHEMA = ? AND kcu.TABLE_NAME = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,
678
- [this._options.database, table]
679
- );
680
- return rows.map(r => ({
681
- constraintName: r.CONSTRAINT_NAME, column: r.COLUMN_NAME,
682
- referencedTable: r.REFERENCED_TABLE_NAME, referencedColumn: r.REFERENCED_COLUMN_NAME,
683
- onDelete: r.DELETE_RULE, onUpdate: r.UPDATE_RULE,
684
- }));
685
- }
686
-
687
- /**
688
- * Get full database overview — all tables with size and row counts.
689
- * Returns a structured database summary.
690
- * @returns {Promise<{ tables: Array, totalSize: string, totalRows: number }>}
691
- */
692
- async overview()
693
- {
694
- const status = await this.tableStatus();
695
- let totalBytes = 0;
696
- let totalRows = 0;
697
- const fmt = (b) => {
698
- if (b >= 1073741824) return (b / 1073741824).toFixed(2) + ' GB';
699
- if (b >= 1048576) return (b / 1048576).toFixed(2) + ' MB';
700
- if (b >= 1024) return (b / 1024).toFixed(2) + ' KB';
701
- return b + ' B';
702
- };
703
- const tables = status.map(s => {
704
- totalBytes += s.totalSize;
705
- totalRows += s.rows;
706
- return { ...s, formattedSize: fmt(s.totalSize) };
707
- });
708
- return { tables, totalSize: fmt(totalBytes), totalRows };
709
- }
710
-
711
- /**
712
- * Get the server variables (global settings).
713
- * @param {string} [filter] - LIKE pattern to filter variables.
714
- * @returns {Promise<Object<string, string>>} Key-value map of server variables.
715
- */
716
- async variables(filter)
717
- {
718
- const sql = filter ? `SHOW VARIABLES LIKE ?` : 'SHOW VARIABLES';
719
- const params = filter ? [filter] : [];
720
- const [rows] = await this._pool.execute(sql, params);
721
- const out = {};
722
- for (const r of rows) out[r.Variable_name] = r.Value;
723
- return out;
724
- }
725
-
726
- /**
727
- * Get processlist — active connections/queries.
728
- * @returns {Promise<Array<{ id: number, user: string, host: string, db: string, command: string, time: number, state: string, info: string }>>}
729
- */
730
- async processlist()
731
- {
732
- const [rows] = await this._pool.execute('SHOW PROCESSLIST');
733
- return rows.map(r => ({
734
- id: r.Id, user: r.User, host: r.Host, db: r.db,
735
- command: r.Command, time: r.Time, state: r.State, info: r.Info,
736
- }));
737
- }
738
-
739
- /**
740
- * Alter a table's engine, charset, or collation.
741
- * @param {string} table - Table name.
742
- * @param {object} opts - Configuration options.
743
- * @param {string} [opts.engine] - e.g. 'InnoDB', 'MyISAM'
744
- * @param {string} [opts.charset] - e.g. 'utf8mb4', 'latin1'
745
- * @param {string} [opts.collation] - e.g. 'utf8mb4_unicode_ci'
746
- */
747
- async alterTable(table, opts = {})
748
- {
749
- const parts = [];
750
- if (opts.engine) parts.push(`ENGINE=${this._safeIdent(opts.engine)}`);
751
- if (opts.charset) parts.push(`DEFAULT CHARSET=${this._safeIdent(opts.charset)}`);
752
- if (opts.collation) parts.push(`COLLATE=${this._safeIdent(opts.collation)}`);
753
- if (parts.length === 0) return;
754
- await this._pool.execute(`ALTER TABLE ${this._q(table)} ${parts.join(', ')}`);
755
- }
756
-
757
- /**
758
- * Validate an identifier (engine, charset, collation) to prevent SQL injection.
759
- * Only allows alphanumeric characters, underscores, and hyphens.
760
- * @private
761
- * @param {string} value - Value to set.
762
- * @returns {string} Sanitized identifier string.
763
- */
764
- _safeIdent(value)
765
- {
766
- const s = String(value);
767
- if (!/^[a-zA-Z0-9_\-]+$/.test(s)) throw new Error(`Invalid identifier: ${s}`);
768
- return s;
769
- }
770
-
771
- // -- Schema Migrations -----------------------------------------------
772
-
773
- /**
774
- * Add a column to an existing table.
775
- * @param {string} table - Table name.
776
- * @param {string} column - Column name.
777
- * @param {object} colDef - Column definition.
778
- * @param {object} [opts] - Options.
779
- * @param {string} [opts.after] - Place column after this column.
780
- */
781
- async addColumn(table, column, colDef, opts = {})
782
- {
783
- let line = `${this._q(column)} ${this._typeMap(colDef)}`;
784
- if (colDef.unsigned) line += ' UNSIGNED';
785
- if (colDef.required) line += ' NOT NULL';
786
- if (colDef.unique) line += ' UNIQUE';
787
- if (colDef.default !== undefined && typeof colDef.default !== 'function')
788
- line += ` DEFAULT ${this._sqlDefault(colDef.default)}`;
789
- if (colDef.check) line += ` CHECK(${validateCheck(colDef.check)})`;
790
- if (colDef.comment) line += ` COMMENT '${colDef.comment.replace(/'/g, "''")}'`;
791
- let sql = `ALTER TABLE ${this._q(table)} ADD COLUMN ${line}`;
792
- if (opts.after) sql += ` AFTER ${this._q(opts.after)}`;
793
- await this._pool.execute(sql);
794
-
795
- // Add FK if specified
796
- if (colDef.references)
797
- {
798
- const fkName = `fk_${table}_${column}`;
799
- let fk = `ALTER TABLE ${this._q(table)} ADD CONSTRAINT ${this._q(fkName)} FOREIGN KEY (${this._q(column)}) REFERENCES ${this._q(colDef.references.table)}(${this._q(colDef.references.column || 'id')})`;
800
- if (colDef.references.onDelete) fk += ` ON DELETE ${validateFKAction(colDef.references.onDelete)}`;
801
- if (colDef.references.onUpdate) fk += ` ON UPDATE ${validateFKAction(colDef.references.onUpdate)}`;
802
- await this._pool.execute(fk);
803
- }
804
- }
805
-
806
- /**
807
- * Drop a column from an existing table.
808
- * @param {string} table - Table name.
809
- * @param {string} column - Column name.
810
- */
811
- async dropColumn(table, column)
812
- {
813
- await this._pool.execute(`ALTER TABLE ${this._q(table)} DROP COLUMN ${this._q(column)}`);
814
- }
815
-
816
- /**
817
- * Rename a column.
818
- * @param {string} table - Table name.
819
- * @param {string} oldName - Current column name.
820
- * @param {string} newName - New column name.
821
- */
822
- async renameColumn(table, oldName, newName)
823
- {
824
- await this._pool.execute(`ALTER TABLE ${this._q(table)} RENAME COLUMN ${this._q(oldName)} TO ${this._q(newName)}`);
825
- }
826
-
827
- /**
828
- * Rename a table.
829
- * @param {string} oldName - Current table name.
830
- * @param {string} newName - New table name.
831
- */
832
- async renameTable(oldName, newName)
833
- {
834
- await this._pool.execute(`RENAME TABLE ${this._q(oldName)} TO ${this._q(newName)}`);
835
- }
836
-
837
- /**
838
- * Create an index.
839
- * @param {string} table - Table name.
840
- * @param {string[]} columns - Column names.
841
- * @param {object} [opts] - Options.
842
- * @param {string} [opts.name] - Index name.
843
- * @param {boolean} [opts.unique] - Create a UNIQUE index.
844
- */
845
- async createIndex(table, columns, opts = {})
846
- {
847
- const name = opts.name || `idx_${table}_${columns.join('_')}`;
848
- const unique = opts.unique ? 'UNIQUE ' : '';
849
- await this._pool.execute(`CREATE ${unique}INDEX ${this._q(name)} ON ${this._q(table)} (${columns.map(c => this._q(c)).join(', ')})`);
850
- }
851
-
852
- /**
853
- * Drop an index.
854
- * @param {string} table - Table name.
855
- * @param {string} name - Index name.
856
- */
857
- async dropIndex(table, name)
858
- {
859
- await this._pool.execute(`DROP INDEX ${this._q(name)} ON ${this._q(table)}`);
860
- }
861
-
862
- /**
863
- * Add a foreign key constraint.
864
- * @param {string} table - Table name.
865
- * @param {string} column - Column name.
866
- * @param {string} refTable - Referenced table.
867
- * @param {string} refColumn - Referenced column.
868
- * @param {{ onDelete?: string, onUpdate?: string, name?: string }} [options={}]
869
- */
870
- async addForeignKey(table, column, refTable, refColumn, options = {})
871
- {
872
- const fkName = options.name || `fk_${table}_${column}`;
873
- let sql = `ALTER TABLE ${this._q(table)} ADD CONSTRAINT ${this._q(fkName)} FOREIGN KEY (${this._q(column)}) REFERENCES ${this._q(refTable)}(${this._q(refColumn)})`;
874
- if (options.onDelete) sql += ` ON DELETE ${validateFKAction(options.onDelete)}`;
875
- if (options.onUpdate) sql += ` ON UPDATE ${validateFKAction(options.onUpdate)}`;
876
- await this._pool.execute(sql);
877
- }
878
-
879
- /**
880
- * Drop a foreign key constraint.
881
- * @param {string} table - Table name.
882
- * @param {string} fkName - Constraint name.
883
- */
884
- async dropForeignKey(table, fkName)
885
- {
886
- await this._pool.execute(`ALTER TABLE ${this._q(table)} DROP FOREIGN KEY ${this._q(fkName)}`);
887
- }
888
-
889
- /**
890
- * Check if a table exists.
891
- * @param {string} table - Table name.
892
- * @returns {Promise<boolean>} `true` if the table exists.
893
- */
894
- async hasTable(table)
895
- {
896
- const [rows] = await this._pool.execute(
897
- `SELECT 1 FROM information_schema.tables WHERE table_schema = ? AND table_name = ? LIMIT 1`,
898
- [this._options.database, table]
899
- );
900
- return rows.length > 0;
901
- }
902
-
903
- /**
904
- * Check if a column exists in a table.
905
- * @param {string} table - Table name.
906
- * @param {string} column - Column name.
907
- * @returns {Promise<boolean>} `true` if the column exists.
908
- */
909
- async hasColumn(table, column)
910
- {
911
- const [rows] = await this._pool.execute(
912
- `SELECT 1 FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND column_name = ? LIMIT 1`,
913
- [this._options.database, table, column]
914
- );
915
- return rows.length > 0;
916
- }
917
-
918
- /**
919
- * Get a unified table description.
920
- * @param {string} table - Table name.
921
- * @returns {Promise<{ columns: Array, indexes: Array, foreignKeys: Array }>}
922
- */
923
- async describeTable(table)
924
- {
925
- return {
926
- columns: await this.columns(table),
927
- indexes: await this.indexes(table),
928
- foreignKeys: await this.foreignKeys(table),
929
- };
930
- }
931
- }
932
-
933
- module.exports = MysqlAdapter;
1
+ /**
2
+ * @module orm/adapters/mysql
3
+ * @description MySQL / MariaDB adapter using the optional `mysql2` driver.
4
+ * Requires: `npm install mysql2`
5
+ *
6
+ * @example
7
+ * const { Database, Model, TYPES } = require('@zero-server/sdk');
8
+ *
9
+ * const db = Database.connect('mysql', {
10
+ * host: '127.0.0.1',
11
+ * user: 'root',
12
+ * password: '',
13
+ * database: 'myapp',
14
+ * });
15
+ *
16
+ * class Product extends Model {
17
+ * static table = 'products';
18
+ * static schema = {
19
+ * id: { type: TYPES.INTEGER, primaryKey: true, autoIncrement: true },
20
+ * name: { type: TYPES.STRING, required: true, maxLength: 255 },
21
+ * price: { type: TYPES.DECIMAL, required: true, min: 0 },
22
+ * };
23
+ * static timestamps = true;
24
+ * }
25
+ *
26
+ * db.register(Product);
27
+ * await db.sync();
28
+ *
29
+ * await Product.create({ name: 'Widget', price: 9.99 });
30
+ * const cheap = await Product.query().where('price', '<', 20).exec();
31
+ */
32
+ const BaseSqlAdapter = require('./sql-base');
33
+ const { validateFKAction, validateCheck } = require('../schema');
34
+
35
+ class MysqlAdapter extends BaseSqlAdapter
36
+ {
37
+ /**
38
+ * @constructor
39
+ * @param {object} options - Configuration options.
40
+ * @param {string} [options.host='localhost'] - Server hostname.
41
+ * @param {number} [options.port=3306] - Server port.
42
+ * @param {string} [options.user='root'] - Database user.
43
+ * @param {string} [options.password=''] - Database password.
44
+ * @param {string} options.database - Database name.
45
+ * @param {number} [options.connectionLimit=10] - Max pool connections.
46
+ * @param {boolean} [options.waitForConnections=true] - Queue when pool is full.
47
+ * @param {number} [options.queueLimit=0] - Max queued requests (0 = unlimited).
48
+ * @param {number} [options.connectTimeout=10000] - Connection timeout in ms.
49
+ * @param {string} [options.charset='utf8mb4'] - Default character set.
50
+ * @param {string} [options.timezone='Z'] - Session timezone.
51
+ * @param {boolean} [options.multipleStatements=false] - Allow multi-statement queries.
52
+ * @param {boolean} [options.decimalNumbers=false] - Return DECIMAL as numbers instead of strings.
53
+ * @param {string} [options.ssl] - SSL profile or options object.
54
+ */
55
+ constructor(options = {})
56
+ {
57
+ super();
58
+ let mysql;
59
+ try { mysql = require('mysql2/promise'); }
60
+ catch (e)
61
+ {
62
+ throw new Error(
63
+ 'MySQL adapter requires "mysql2" package.\n' +
64
+ 'Install it with: npm install mysql2'
65
+ );
66
+ }
67
+ this._pool = mysql.createPool({
68
+ connectionLimit: 10,
69
+ waitForConnections: true,
70
+ ...options,
71
+ });
72
+ this._options = options;
73
+
74
+ /** @private Query fingerprint tracking for prepared statement metrics */
75
+ this._queryFingerprints = new Map();
76
+ this._queryCount = 0;
77
+ }
78
+
79
+ /** @private */
80
+ _typeMap(colDef)
81
+ {
82
+ const esc = v => v.replace(/'/g, "''");
83
+ const map = {
84
+ string: `VARCHAR(${colDef.maxLength || 255})`, text: 'TEXT',
85
+ integer: 'INT', float: 'DOUBLE', boolean: 'TINYINT(1)',
86
+ date: 'DATE', datetime: 'DATETIME', json: 'JSON', blob: 'BLOB', uuid: 'CHAR(36)',
87
+ bigint: 'BIGINT', smallint: 'SMALLINT', tinyint: 'TINYINT',
88
+ decimal: `DECIMAL(${colDef.precision || 10},${colDef.scale || 2})`,
89
+ mediumtext: 'MEDIUMTEXT', longtext: 'LONGTEXT',
90
+ mediumblob: 'MEDIUMBLOB', longblob: 'LONGBLOB',
91
+ enum: colDef.enum ? `ENUM(${colDef.enum.map(v => `'${esc(String(v))}'`).join(',')})` : 'VARCHAR(255)',
92
+ set: colDef.values ? `SET(${colDef.values.map(v => `'${esc(String(v))}'`).join(',')})` : 'VARCHAR(255)',
93
+ timestamp: 'TIMESTAMP',
94
+ time: 'TIME',
95
+ year: 'YEAR',
96
+ binary: `BINARY(${colDef.length || 255})`,
97
+ varbinary: `VARBINARY(${colDef.length || 255})`,
98
+ double: 'DOUBLE',
99
+ real: 'REAL',
100
+ };
101
+ return map[colDef.type] || 'TEXT';
102
+ }
103
+
104
+ /** @private */
105
+ _q(name) { return '`' + name.replace(/`/g, '``') + '`'; }
106
+
107
+ /**
108
+ * Create a table with the given schema.
109
+ * @param {string} table - Table name.
110
+ * @param {object} schema - Column definitions keyed by column name.
111
+ * @returns {Promise<void>}
112
+ */
113
+ async createTable(table, schema, tableOptions = {})
114
+ {
115
+ const cols = [];
116
+ const tableConstraints = [];
117
+ const compositePKs = [];
118
+
119
+ for (const [name, def] of Object.entries(schema))
120
+ {
121
+ let line = `${this._q(name)} ${this._typeMap(def)}`;
122
+
123
+ // Collect composite PK candidates
124
+ if (def.primaryKey && def.compositeKey) { compositePKs.push(name); }
125
+ else if (def.primaryKey)
126
+ {
127
+ line += ' PRIMARY KEY';
128
+ if (def.autoIncrement) line += ' AUTO_INCREMENT';
129
+ }
130
+
131
+ if (def.unsigned) line += ' UNSIGNED';
132
+ if (def.required && !def.primaryKey) line += ' NOT NULL';
133
+ if (def.unique && !def.compositeUnique) line += ' UNIQUE';
134
+ if (def.default !== undefined && typeof def.default !== 'function')
135
+ line += ` DEFAULT ${this._sqlDefault(def.default)}`;
136
+
137
+ // CHECK constraint
138
+ if (def.check)
139
+ {
140
+ line += ` CHECK(${validateCheck(def.check)})`;
141
+ }
142
+
143
+ if (def.charset) line += ` CHARACTER SET ${this._safeIdent(def.charset)}`;
144
+ if (def.collation) line += ` COLLATE ${this._safeIdent(def.collation)}`;
145
+ if (def.comment) line += ` COMMENT '${def.comment.replace(/'/g, "''")}'`;
146
+ cols.push(line);
147
+
148
+ // Foreign key constraint (table-level)
149
+ if (def.references)
150
+ {
151
+ const fkName = `fk_${table}_${name}`;
152
+ let fk = `CONSTRAINT ${this._q(fkName)} FOREIGN KEY (${this._q(name)}) REFERENCES ${this._q(def.references.table)}(${this._q(def.references.column || 'id')})`;
153
+ if (def.references.onDelete) fk += ` ON DELETE ${validateFKAction(def.references.onDelete)}`;
154
+ if (def.references.onUpdate) fk += ` ON UPDATE ${validateFKAction(def.references.onUpdate)}`;
155
+ tableConstraints.push(fk);
156
+ }
157
+ }
158
+
159
+ // Composite primary key
160
+ if (compositePKs.length > 0)
161
+ {
162
+ tableConstraints.push(`PRIMARY KEY (${compositePKs.map(k => this._q(k)).join(', ')})`);
163
+ }
164
+
165
+ // Composite unique constraints
166
+ const compositeUniques = {};
167
+ for (const [name, def] of Object.entries(schema))
168
+ {
169
+ if (def.compositeUnique)
170
+ {
171
+ const group = typeof def.compositeUnique === 'string' ? def.compositeUnique : 'default';
172
+ if (!compositeUniques[group]) compositeUniques[group] = [];
173
+ compositeUniques[group].push(name);
174
+ }
175
+ }
176
+ for (const [group, columns] of Object.entries(compositeUniques))
177
+ {
178
+ tableConstraints.push(`UNIQUE KEY ${this._q(`uq_${table}_${group}`)} (${columns.map(c => this._q(c)).join(', ')})`);
179
+ }
180
+
181
+ const allParts = [...cols, ...tableConstraints];
182
+ let sql = `CREATE TABLE IF NOT EXISTS ${this._q(table)} (${allParts.join(', ')})`;
183
+ const engine = tableOptions.engine || this._options.engine || 'InnoDB';
184
+ const charset = tableOptions.charset || this._options.charset || 'utf8mb4';
185
+ const collation = tableOptions.collation || this._options.collation || 'utf8mb4_unicode_ci';
186
+ sql += ` ENGINE=${this._safeIdent(engine)}`;
187
+ sql += ` DEFAULT CHARSET=${this._safeIdent(charset)}`;
188
+ sql += ` COLLATE=${this._safeIdent(collation)}`;
189
+ if (tableOptions.comment) sql += ` COMMENT='${tableOptions.comment.replace(/'/g, "''")}'`;
190
+ await this._pool.execute(sql);
191
+
192
+ // Create indexes defined in schema
193
+ for (const [name, def] of Object.entries(schema))
194
+ {
195
+ if (def.index)
196
+ {
197
+ const idxName = typeof def.index === 'string' ? def.index : `idx_${table}_${name}`;
198
+ await this._pool.execute(`CREATE INDEX ${this._q(idxName)} ON ${this._q(table)} (${this._q(name)})`);
199
+ }
200
+ }
201
+
202
+ // Composite indexes
203
+ const compositeIndexes = {};
204
+ for (const [name, def] of Object.entries(schema))
205
+ {
206
+ if (def.compositeIndex)
207
+ {
208
+ const group = typeof def.compositeIndex === 'string' ? def.compositeIndex : 'default';
209
+ if (!compositeIndexes[group]) compositeIndexes[group] = [];
210
+ compositeIndexes[group].push(name);
211
+ }
212
+ }
213
+ for (const [group, columns] of Object.entries(compositeIndexes))
214
+ {
215
+ const idxName = `idx_${table}_${group}`;
216
+ await this._pool.execute(`CREATE INDEX ${this._q(idxName)} ON ${this._q(table)} (${columns.map(c => this._q(c)).join(', ')})`);
217
+ }
218
+ }
219
+
220
+ /**
221
+ * Drop a table if it exists.
222
+ * @param {string} table - Table name.
223
+ * @returns {Promise<void>}
224
+ */
225
+ async dropTable(table)
226
+ {
227
+ await this._pool.execute(`DROP TABLE IF EXISTS ${this._q(table)}`);
228
+ }
229
+
230
+ /**
231
+ * Insert a single row.
232
+ * @param {string} table - Table name.
233
+ * @param {object} data - Row data as key-value pairs.
234
+ * @returns {Promise<object>} The inserted row.
235
+ */
236
+ async insert(table, data)
237
+ {
238
+ const keys = Object.keys(data);
239
+ const placeholders = keys.map(() => '?').join(', ');
240
+ const values = keys.map(k => this._toSqlValue(data[k]));
241
+ const [result] = await this._pool.execute(
242
+ `INSERT INTO ${this._q(table)} (${keys.map(k => this._q(k)).join(', ')}) VALUES (${placeholders})`,
243
+ values
244
+ );
245
+ return { ...data, id: result.insertId || data.id };
246
+ }
247
+
248
+ /**
249
+ * Insert multiple rows in a batch.
250
+ * @param {string} table - Table name.
251
+ * @param {Array<object>} dataArray - Array of row objects.
252
+ * @returns {Promise<Array<object>>} The inserted rows.
253
+ */
254
+ async insertMany(table, dataArray)
255
+ {
256
+ if (!dataArray.length) return [];
257
+ const keys = Object.keys(dataArray[0]);
258
+ const singlePlaceholders = `(${keys.map(() => '?').join(', ')})`;
259
+ const allPlaceholders = dataArray.map(() => singlePlaceholders).join(', ');
260
+ const values = [];
261
+ for (const data of dataArray)
262
+ {
263
+ for (const k of keys) values.push(this._toSqlValue(data[k]));
264
+ }
265
+ const sql = `INSERT INTO ${this._q(table)} (${keys.map(k => this._q(k)).join(', ')}) VALUES ${allPlaceholders}`;
266
+ const [result] = await this._pool.execute(sql, values);
267
+ return dataArray.map((data, i) => ({ ...data, id: (result.insertId || 0) + i }));
268
+ }
269
+
270
+ /**
271
+ * Update a single row by primary key.
272
+ * @param {string} table - Table name.
273
+ * @param {string} pk - Primary key column.
274
+ * @param {*} pkVal - Primary key value.
275
+ * @param {object} data - Fields to update.
276
+ * @returns {Promise<void>}
277
+ */
278
+ async update(table, pk, pkVal, data)
279
+ {
280
+ const sets = Object.keys(data).map(k => `${this._q(k)} = ?`).join(', ');
281
+ const values = [...Object.values(data).map(v => this._toSqlValue(v)), pkVal];
282
+ await this._pool.execute(`UPDATE ${this._q(table)} SET ${sets} WHERE ${this._q(pk)} = ?`, values);
283
+ }
284
+
285
+ /**
286
+ * Update rows matching the given conditions.
287
+ * @param {string} table - Table name.
288
+ * @param {object} conditions - Filter conditions.
289
+ * @param {object} data - Fields to update.
290
+ * @returns {Promise<number>} Number of affected rows.
291
+ */
292
+ async updateWhere(table, conditions, data)
293
+ {
294
+ const { clause, values: whereVals } = this._buildWhere(conditions);
295
+ const sets = Object.keys(data).map(k => `${this._q(k)} = ?`).join(', ');
296
+ const values = [...Object.values(data).map(v => this._toSqlValue(v)), ...whereVals];
297
+ const sql = `UPDATE ${this._q(table)} SET ${sets}${clause.replace(/"/g, '`')}`;
298
+ const [result] = await this._pool.execute(sql, values);
299
+ return result.affectedRows;
300
+ }
301
+
302
+ /**
303
+ * Delete a single row by primary key.
304
+ * @param {string} table - Table name.
305
+ * @param {string} pk - Primary key column.
306
+ * @param {*} pkVal - Primary key value.
307
+ * @returns {Promise<void>}
308
+ */
309
+ async remove(table, pk, pkVal)
310
+ {
311
+ await this._pool.execute(`DELETE FROM ${this._q(table)} WHERE ${this._q(pk)} = ?`, [pkVal]);
312
+ }
313
+
314
+ /**
315
+ * Delete rows matching the given conditions.
316
+ * @param {string} table - Table name.
317
+ * @param {object} conditions - Filter conditions.
318
+ * @returns {Promise<number>} Number of deleted rows.
319
+ */
320
+ async deleteWhere(table, conditions)
321
+ {
322
+ const { clause, values } = this._buildWhere(conditions);
323
+ const sql = `DELETE FROM ${this._q(table)}${clause.replace(/"/g, '`')}`;
324
+ const [result] = await this._pool.execute(sql, values);
325
+ return result.affectedRows;
326
+ }
327
+
328
+ /**
329
+ * Execute a query descriptor built by the Query builder.
330
+ * @param {object} descriptor - Query descriptor with table, fields, where, orderBy, limit, offset.
331
+ * @returns {Promise<Array<object>>} Result rows.
332
+ */
333
+ async execute(descriptor)
334
+ {
335
+ const { action, table, fields, where, orderBy, limit, offset, distinct, joins, groupBy, having } = descriptor;
336
+ const q = this._q.bind(this);
337
+
338
+ if (action === 'count')
339
+ {
340
+ const { clause, values } = this._buildWhereFromChain(where);
341
+ const joinStr = this._buildJoins(joins, table, q);
342
+ const sql = `SELECT COUNT(*) as count FROM ${q(table)}${joinStr}${clause.replace(/"/g, '`')}`;
343
+ const [rows] = await this._pool.execute(sql, values);
344
+ return rows[0].count;
345
+ }
346
+
347
+ const selectFields = fields && fields.length ? fields.map(f => q(f)).join(', ') : '*';
348
+ const distinctStr = distinct ? 'DISTINCT ' : '';
349
+ const joinStr = this._buildJoins(joins, table, q);
350
+ let sql = `SELECT ${distinctStr}${selectFields} FROM ${q(table)}${joinStr}`;
351
+ const values = [];
352
+
353
+ if (where && where.length)
354
+ {
355
+ const { clause, values: wv } = this._buildWhereFromChain(where);
356
+ sql += clause.replace(/"/g, '`');
357
+ values.push(...wv);
358
+ }
359
+
360
+ sql += this._buildGroupBy(groupBy, q);
361
+ sql += this._buildHaving(having, values, q);
362
+
363
+ if (orderBy && orderBy.length)
364
+ sql += ' ORDER BY ' + orderBy.map(o => `${q(o.field)} ${o.dir}`).join(', ');
365
+ if (limit !== null && limit !== undefined) { sql += ' LIMIT ?'; values.push(limit); }
366
+ if (offset !== null && offset !== undefined) { sql += ' OFFSET ?'; values.push(offset); }
367
+
368
+ const [rows] = await this._pool.execute(sql, values);
369
+ return rows;
370
+ }
371
+
372
+ /**
373
+ * Execute an aggregate function (count, sum, avg, min, max).
374
+ * @param {object} descriptor - Aggregate descriptor with table, function, field, where.
375
+ * @returns {Promise<number|null>} Aggregate result.
376
+ */
377
+ async aggregate(descriptor)
378
+ {
379
+ const { table, where, aggregateFn, aggregateField, joins, groupBy, having } = descriptor;
380
+ const q = this._q.bind(this);
381
+ const fn = aggregateFn.toUpperCase();
382
+ const joinStr = this._buildJoins(joins, table, q);
383
+ const values = [];
384
+
385
+ let sql = `SELECT ${fn}(${q(aggregateField)}) as result FROM ${q(table)}${joinStr}`;
386
+
387
+ if (where && where.length)
388
+ {
389
+ const { clause, values: wv } = this._buildWhereFromChain(where);
390
+ sql += clause.replace(/"/g, '`');
391
+ values.push(...wv);
392
+ }
393
+
394
+ sql += this._buildGroupBy(groupBy, q);
395
+ sql += this._buildHaving(having, values, q);
396
+
397
+ const [rows] = await this._pool.execute(sql, values);
398
+ return rows[0] ? rows[0].result : null;
399
+ }
400
+
401
+ /**
402
+ * Get the query execution plan (EXPLAIN).
403
+ * @param {object} descriptor - Query descriptor.
404
+ * @param {object} [options] - Configuration options.
405
+ * @param {boolean} [options.analyze] - Use EXPLAIN ANALYZE (MySQL 8.0.18+).
406
+ * @returns {Promise<Array>} Array of execution plan rows.
407
+ */
408
+ async explain(descriptor, options = {})
409
+ {
410
+ const { table, fields, where, orderBy, limit, offset, distinct, joins, groupBy, having } = descriptor;
411
+ const q = this._q.bind(this);
412
+
413
+ const selectFields = fields && fields.length ? fields.map(f => q(f)).join(', ') : '*';
414
+ const distinctStr = distinct ? 'DISTINCT ' : '';
415
+ const joinStr = this._buildJoins(joins, table, q);
416
+ let sql = `SELECT ${distinctStr}${selectFields} FROM ${q(table)}${joinStr}`;
417
+ const values = [];
418
+
419
+ if (where && where.length)
420
+ {
421
+ const { clause, values: wv } = this._buildWhereFromChain(where);
422
+ sql += clause.replace(/"/g, '`');
423
+ values.push(...wv);
424
+ }
425
+
426
+ sql += this._buildGroupBy(groupBy, q);
427
+ sql += this._buildHaving(having, values, q);
428
+
429
+ if (orderBy && orderBy.length)
430
+ sql += ' ORDER BY ' + orderBy.map(o => `${q(o.field)} ${o.dir}`).join(', ');
431
+ if (limit !== null && limit !== undefined) { sql += ' LIMIT ?'; values.push(limit); }
432
+ if (offset !== null && offset !== undefined) { sql += ' OFFSET ?'; values.push(offset); }
433
+
434
+ const prefix = options.analyze ? 'EXPLAIN ANALYZE' : 'EXPLAIN';
435
+ const [rows] = await this._pool.execute(`${prefix} ${sql}`, values);
436
+ return rows;
437
+ }
438
+
439
+ /**
440
+ * Get prepared statement cache statistics.
441
+ * mysql2 handles prepared statement caching internally per connection.
442
+ * @returns {{ uniqueQueries: number, totalQueries: number, driver: string }}
443
+ */
444
+ stmtCacheStats()
445
+ {
446
+ return {
447
+ uniqueQueries: this._queryFingerprints.size,
448
+ totalQueries: this._queryCount,
449
+ driver: 'mysql2 (internal prepared statement caching)',
450
+ };
451
+ }
452
+
453
+ /**
454
+ * Pre-warm the connection pool by creating idle connections.
455
+ * @param {number} [count=5] - Number of connections to warm up.
456
+ * @returns {Promise<number>} Number of connections successfully warmed.
457
+ */
458
+ async warmup(count)
459
+ {
460
+ const n = Math.min(Math.max(1, Math.floor(Number(count) || 5)), this._options.connectionLimit || 10);
461
+ const connections = [];
462
+ for (let i = 0; i < n; i++)
463
+ {
464
+ try
465
+ {
466
+ const conn = await this._pool.getConnection();
467
+ connections.push(conn);
468
+ }
469
+ catch (e) { break; }
470
+ }
471
+ for (const conn of connections) conn.release();
472
+ return connections.length;
473
+ }
474
+
475
+ /**
476
+ * Close the database connection.
477
+ * @returns {Promise<void>}
478
+ */
479
+ async close() { await this._pool.end(); }
480
+
481
+ /** @override */
482
+ async raw(sql, ...params) { const [rows] = await this._pool.execute(sql, params); return rows; }
483
+
484
+ /** @override */
485
+ async transaction(fn)
486
+ {
487
+ const conn = await this._pool.getConnection();
488
+ try
489
+ {
490
+ await conn.beginTransaction();
491
+ const result = await fn(conn);
492
+ await conn.commit();
493
+ return result;
494
+ }
495
+ catch (e) { await conn.rollback(); throw e; }
496
+ finally { conn.release(); }
497
+ }
498
+
499
+ // -- MySQL Utilities ---------------------------------
500
+
501
+ /**
502
+ * List all user-created tables in the current database.
503
+ * @returns {Promise<string[]>} Array of table names.
504
+ */
505
+ async tables()
506
+ {
507
+ const [rows] = await this._pool.execute('SHOW TABLES');
508
+ return rows.map(r => Object.values(r)[0]);
509
+ }
510
+
511
+ /**
512
+ * Get the columns of a table.
513
+ * @param {string} table - Table name.
514
+ * @returns {Promise<Array<{ Field: string, Type: string, Null: string, Key: string, Default: *, Extra: string }>>}
515
+ */
516
+ async columns(table)
517
+ {
518
+ const [rows] = await this._pool.execute(`SHOW COLUMNS FROM ${this._q(table)}`);
519
+ return rows;
520
+ }
521
+
522
+ /**
523
+ * Get the current database size in bytes.
524
+ * @returns {Promise<number>} Database size in bytes.
525
+ */
526
+ async databaseSize()
527
+ {
528
+ const db = this._options.database;
529
+ if (!db) return 0;
530
+ const [rows] = await this._pool.execute(
531
+ `SELECT SUM(data_length + index_length) AS size
532
+ FROM information_schema.tables WHERE table_schema = ?`, [db]
533
+ );
534
+ return Number(rows[0].size) || 0;
535
+ }
536
+
537
+ /**
538
+ * Get connection pool status.
539
+ * @returns {{ total: number, idle: number, used: number, queued: number }}
540
+ */
541
+ poolStatus()
542
+ {
543
+ const pool = this._pool.pool;
544
+ if (!pool) return { total: 0, idle: 0, used: 0, queued: 0 };
545
+ return {
546
+ total: pool._allConnections?.length || 0,
547
+ idle: pool._freeConnections?.length || 0,
548
+ used: (pool._allConnections?.length || 0) - (pool._freeConnections?.length || 0),
549
+ queued: pool._connectionQueue?.length || 0,
550
+ };
551
+ }
552
+
553
+ /**
554
+ * Get the MySQL/MariaDB server version string.
555
+ * @returns {Promise<string>} Server version string (e.g. `"8.0.35"`).
556
+ */
557
+ async version()
558
+ {
559
+ const [rows] = await this._pool.execute('SELECT VERSION() AS ver');
560
+ return rows[0].ver;
561
+ }
562
+
563
+ /**
564
+ * Ping the database to check connectivity.
565
+ * @returns {Promise<boolean>} `true` if the server is reachable.
566
+ */
567
+ async ping()
568
+ {
569
+ try
570
+ {
571
+ const conn = await this._pool.getConnection();
572
+ await conn.ping();
573
+ conn.release();
574
+ return true;
575
+ }
576
+ catch { return false; }
577
+ }
578
+
579
+ /**
580
+ * Execute a raw statement that doesn't return rows (INSERT, UPDATE, DDL).
581
+ * @param {string} sql - SQL query string.
582
+ * @param {...*} params - Bound parameter values.
583
+ * @returns {Promise<{ affectedRows: number, insertId: number }>}
584
+ */
585
+ async exec(sql, ...params)
586
+ {
587
+ const [result] = await this._pool.execute(sql, params);
588
+ return { affectedRows: result.affectedRows || 0, insertId: result.insertId || 0 };
589
+ }
590
+
591
+ // -- Table Info & Debug (Schema Introspection) -----------
592
+
593
+ /**
594
+ * Get detailed table status (rows, size, engine, collation, etc.).
595
+ * Returns a structured database overview.
596
+ * @param {string} [table] - Table name. If omitted, returns all tables.
597
+ * @returns {Promise<Array<{ name: string, engine: string, rows: number, dataLength: number, indexLength: number, totalSize: number, autoIncrement: number, collation: string, createTime: string, updateTime: string, comment: string }>>}
598
+ */
599
+ async tableStatus(table)
600
+ {
601
+ let sql = 'SHOW TABLE STATUS';
602
+ const params = [];
603
+ if (table){ sql += ` LIKE ?`; params.push(table); }
604
+ const [rows] = await this._pool.execute(sql, params);
605
+ return rows.map(r => ({
606
+ name: r.Name, engine: r.Engine, rows: Number(r.Rows) || 0,
607
+ dataLength: Number(r.Data_length) || 0, indexLength: Number(r.Index_length) || 0,
608
+ totalSize: (Number(r.Data_length) || 0) + (Number(r.Index_length) || 0),
609
+ autoIncrement: r.Auto_increment, collation: r.Collation,
610
+ createTime: r.Create_time, updateTime: r.Update_time,
611
+ comment: r.Comment || '',
612
+ }));
613
+ }
614
+
615
+ /**
616
+ * Get table size in a human-readable format.
617
+ * @param {string} table - Table name.
618
+ * @returns {Promise<{ rows: number, dataSize: string, indexSize: string, totalSize: string }>}
619
+ */
620
+ async tableSize(table)
621
+ {
622
+ const status = await this.tableStatus(table);
623
+ if (!status.length) return { rows: 0, dataSize: '0 B', indexSize: '0 B', totalSize: '0 B' };
624
+ const s = status[0];
625
+ const fmt = (b) => {
626
+ if (b >= 1073741824) return (b / 1073741824).toFixed(2) + ' GB';
627
+ if (b >= 1048576) return (b / 1048576).toFixed(2) + ' MB';
628
+ if (b >= 1024) return (b / 1024).toFixed(2) + ' KB';
629
+ return b + ' B';
630
+ };
631
+ return { rows: s.rows, dataSize: fmt(s.dataLength), indexSize: fmt(s.indexLength), totalSize: fmt(s.totalSize) };
632
+ }
633
+
634
+ /**
635
+ * Get indexes for a table.
636
+ * @param {string} table - Table name.
637
+ * @returns {Promise<Array<{ name: string, column: string, unique: boolean, type: string, cardinality: number }>>}
638
+ */
639
+ async indexes(table)
640
+ {
641
+ const [rows] = await this._pool.execute(`SHOW INDEX FROM ${this._q(table)}`);
642
+ return rows.map(r => ({
643
+ name: r.Key_name, column: r.Column_name, unique: !r.Non_unique,
644
+ type: r.Index_type, cardinality: Number(r.Cardinality) || 0,
645
+ }));
646
+ }
647
+
648
+ /**
649
+ * Get the charset and collation of a table.
650
+ * @param {string} table - Table name.
651
+ * @returns {Promise<{ charset: string, collation: string }>}
652
+ */
653
+ async tableCharset(table)
654
+ {
655
+ const [rows] = await this._pool.execute(
656
+ `SELECT TABLE_COLLATION FROM information_schema.tables WHERE table_schema = ? AND table_name = ?`,
657
+ [this._options.database, table]
658
+ );
659
+ if (!rows.length) return { charset: '', collation: '' };
660
+ const collation = rows[0].TABLE_COLLATION || '';
661
+ const charset = collation.split('_')[0] || '';
662
+ return { charset, collation };
663
+ }
664
+
665
+ /**
666
+ * Get foreign keys for a table.
667
+ * @param {string} table - Table name.
668
+ * @returns {Promise<Array<{ constraintName: string, column: string, referencedTable: string, referencedColumn: string, onDelete: string, onUpdate: string }>>}
669
+ */
670
+ async foreignKeys(table)
671
+ {
672
+ const [rows] = await this._pool.execute(
673
+ `SELECT CONSTRAINT_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME,
674
+ DELETE_RULE, UPDATE_RULE
675
+ FROM information_schema.KEY_COLUMN_USAGE kcu
676
+ JOIN information_schema.REFERENTIAL_CONSTRAINTS rc USING (CONSTRAINT_NAME, CONSTRAINT_SCHEMA)
677
+ WHERE kcu.TABLE_SCHEMA = ? AND kcu.TABLE_NAME = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,
678
+ [this._options.database, table]
679
+ );
680
+ return rows.map(r => ({
681
+ constraintName: r.CONSTRAINT_NAME, column: r.COLUMN_NAME,
682
+ referencedTable: r.REFERENCED_TABLE_NAME, referencedColumn: r.REFERENCED_COLUMN_NAME,
683
+ onDelete: r.DELETE_RULE, onUpdate: r.UPDATE_RULE,
684
+ }));
685
+ }
686
+
687
+ /**
688
+ * Get full database overview — all tables with size and row counts.
689
+ * Returns a structured database summary.
690
+ * @returns {Promise<{ tables: Array, totalSize: string, totalRows: number }>}
691
+ */
692
+ async overview()
693
+ {
694
+ const status = await this.tableStatus();
695
+ let totalBytes = 0;
696
+ let totalRows = 0;
697
+ const fmt = (b) => {
698
+ if (b >= 1073741824) return (b / 1073741824).toFixed(2) + ' GB';
699
+ if (b >= 1048576) return (b / 1048576).toFixed(2) + ' MB';
700
+ if (b >= 1024) return (b / 1024).toFixed(2) + ' KB';
701
+ return b + ' B';
702
+ };
703
+ const tables = status.map(s => {
704
+ totalBytes += s.totalSize;
705
+ totalRows += s.rows;
706
+ return { ...s, formattedSize: fmt(s.totalSize) };
707
+ });
708
+ return { tables, totalSize: fmt(totalBytes), totalRows };
709
+ }
710
+
711
+ /**
712
+ * Get the server variables (global settings).
713
+ * @param {string} [filter] - LIKE pattern to filter variables.
714
+ * @returns {Promise<Object<string, string>>} Key-value map of server variables.
715
+ */
716
+ async variables(filter)
717
+ {
718
+ const sql = filter ? `SHOW VARIABLES LIKE ?` : 'SHOW VARIABLES';
719
+ const params = filter ? [filter] : [];
720
+ const [rows] = await this._pool.execute(sql, params);
721
+ const out = {};
722
+ for (const r of rows) out[r.Variable_name] = r.Value;
723
+ return out;
724
+ }
725
+
726
+ /**
727
+ * Get processlist — active connections/queries.
728
+ * @returns {Promise<Array<{ id: number, user: string, host: string, db: string, command: string, time: number, state: string, info: string }>>}
729
+ */
730
+ async processlist()
731
+ {
732
+ const [rows] = await this._pool.execute('SHOW PROCESSLIST');
733
+ return rows.map(r => ({
734
+ id: r.Id, user: r.User, host: r.Host, db: r.db,
735
+ command: r.Command, time: r.Time, state: r.State, info: r.Info,
736
+ }));
737
+ }
738
+
739
+ /**
740
+ * Alter a table's engine, charset, or collation.
741
+ * @param {string} table - Table name.
742
+ * @param {object} opts - Configuration options.
743
+ * @param {string} [opts.engine] - e.g. 'InnoDB', 'MyISAM'
744
+ * @param {string} [opts.charset] - e.g. 'utf8mb4', 'latin1'
745
+ * @param {string} [opts.collation] - e.g. 'utf8mb4_unicode_ci'
746
+ */
747
+ async alterTable(table, opts = {})
748
+ {
749
+ const parts = [];
750
+ if (opts.engine) parts.push(`ENGINE=${this._safeIdent(opts.engine)}`);
751
+ if (opts.charset) parts.push(`DEFAULT CHARSET=${this._safeIdent(opts.charset)}`);
752
+ if (opts.collation) parts.push(`COLLATE=${this._safeIdent(opts.collation)}`);
753
+ if (parts.length === 0) return;
754
+ await this._pool.execute(`ALTER TABLE ${this._q(table)} ${parts.join(', ')}`);
755
+ }
756
+
757
+ /**
758
+ * Validate an identifier (engine, charset, collation) to prevent SQL injection.
759
+ * Only allows alphanumeric characters, underscores, and hyphens.
760
+ * @private
761
+ * @param {string} value - Value to set.
762
+ * @returns {string} Sanitized identifier string.
763
+ */
764
+ _safeIdent(value)
765
+ {
766
+ const s = String(value);
767
+ if (!/^[a-zA-Z0-9_\-]+$/.test(s)) throw new Error(`Invalid identifier: ${s}`);
768
+ return s;
769
+ }
770
+
771
+ // -- Schema Migrations -----------------------------------------------
772
+
773
+ /**
774
+ * Add a column to an existing table.
775
+ * @param {string} table - Table name.
776
+ * @param {string} column - Column name.
777
+ * @param {object} colDef - Column definition.
778
+ * @param {object} [opts] - Options.
779
+ * @param {string} [opts.after] - Place column after this column.
780
+ */
781
+ async addColumn(table, column, colDef, opts = {})
782
+ {
783
+ let line = `${this._q(column)} ${this._typeMap(colDef)}`;
784
+ if (colDef.unsigned) line += ' UNSIGNED';
785
+ if (colDef.required) line += ' NOT NULL';
786
+ if (colDef.unique) line += ' UNIQUE';
787
+ if (colDef.default !== undefined && typeof colDef.default !== 'function')
788
+ line += ` DEFAULT ${this._sqlDefault(colDef.default)}`;
789
+ if (colDef.check) line += ` CHECK(${validateCheck(colDef.check)})`;
790
+ if (colDef.comment) line += ` COMMENT '${colDef.comment.replace(/'/g, "''")}'`;
791
+ let sql = `ALTER TABLE ${this._q(table)} ADD COLUMN ${line}`;
792
+ if (opts.after) sql += ` AFTER ${this._q(opts.after)}`;
793
+ await this._pool.execute(sql);
794
+
795
+ // Add FK if specified
796
+ if (colDef.references)
797
+ {
798
+ const fkName = `fk_${table}_${column}`;
799
+ let fk = `ALTER TABLE ${this._q(table)} ADD CONSTRAINT ${this._q(fkName)} FOREIGN KEY (${this._q(column)}) REFERENCES ${this._q(colDef.references.table)}(${this._q(colDef.references.column || 'id')})`;
800
+ if (colDef.references.onDelete) fk += ` ON DELETE ${validateFKAction(colDef.references.onDelete)}`;
801
+ if (colDef.references.onUpdate) fk += ` ON UPDATE ${validateFKAction(colDef.references.onUpdate)}`;
802
+ await this._pool.execute(fk);
803
+ }
804
+ }
805
+
806
+ /**
807
+ * Drop a column from an existing table.
808
+ * @param {string} table - Table name.
809
+ * @param {string} column - Column name.
810
+ */
811
+ async dropColumn(table, column)
812
+ {
813
+ await this._pool.execute(`ALTER TABLE ${this._q(table)} DROP COLUMN ${this._q(column)}`);
814
+ }
815
+
816
+ /**
817
+ * Rename a column.
818
+ * @param {string} table - Table name.
819
+ * @param {string} oldName - Current column name.
820
+ * @param {string} newName - New column name.
821
+ */
822
+ async renameColumn(table, oldName, newName)
823
+ {
824
+ await this._pool.execute(`ALTER TABLE ${this._q(table)} RENAME COLUMN ${this._q(oldName)} TO ${this._q(newName)}`);
825
+ }
826
+
827
+ /**
828
+ * Rename a table.
829
+ * @param {string} oldName - Current table name.
830
+ * @param {string} newName - New table name.
831
+ */
832
+ async renameTable(oldName, newName)
833
+ {
834
+ await this._pool.execute(`RENAME TABLE ${this._q(oldName)} TO ${this._q(newName)}`);
835
+ }
836
+
837
+ /**
838
+ * Create an index.
839
+ * @param {string} table - Table name.
840
+ * @param {string[]} columns - Column names.
841
+ * @param {object} [opts] - Options.
842
+ * @param {string} [opts.name] - Index name.
843
+ * @param {boolean} [opts.unique] - Create a UNIQUE index.
844
+ */
845
+ async createIndex(table, columns, opts = {})
846
+ {
847
+ const name = opts.name || `idx_${table}_${columns.join('_')}`;
848
+ const unique = opts.unique ? 'UNIQUE ' : '';
849
+ await this._pool.execute(`CREATE ${unique}INDEX ${this._q(name)} ON ${this._q(table)} (${columns.map(c => this._q(c)).join(', ')})`);
850
+ }
851
+
852
+ /**
853
+ * Drop an index.
854
+ * @param {string} table - Table name.
855
+ * @param {string} name - Index name.
856
+ */
857
+ async dropIndex(table, name)
858
+ {
859
+ await this._pool.execute(`DROP INDEX ${this._q(name)} ON ${this._q(table)}`);
860
+ }
861
+
862
+ /**
863
+ * Add a foreign key constraint.
864
+ * @param {string} table - Table name.
865
+ * @param {string} column - Column name.
866
+ * @param {string} refTable - Referenced table.
867
+ * @param {string} refColumn - Referenced column.
868
+ * @param {{ onDelete?: string, onUpdate?: string, name?: string }} [options={}]
869
+ */
870
+ async addForeignKey(table, column, refTable, refColumn, options = {})
871
+ {
872
+ const fkName = options.name || `fk_${table}_${column}`;
873
+ let sql = `ALTER TABLE ${this._q(table)} ADD CONSTRAINT ${this._q(fkName)} FOREIGN KEY (${this._q(column)}) REFERENCES ${this._q(refTable)}(${this._q(refColumn)})`;
874
+ if (options.onDelete) sql += ` ON DELETE ${validateFKAction(options.onDelete)}`;
875
+ if (options.onUpdate) sql += ` ON UPDATE ${validateFKAction(options.onUpdate)}`;
876
+ await this._pool.execute(sql);
877
+ }
878
+
879
+ /**
880
+ * Drop a foreign key constraint.
881
+ * @param {string} table - Table name.
882
+ * @param {string} fkName - Constraint name.
883
+ */
884
+ async dropForeignKey(table, fkName)
885
+ {
886
+ await this._pool.execute(`ALTER TABLE ${this._q(table)} DROP FOREIGN KEY ${this._q(fkName)}`);
887
+ }
888
+
889
+ /**
890
+ * Check if a table exists.
891
+ * @param {string} table - Table name.
892
+ * @returns {Promise<boolean>} `true` if the table exists.
893
+ */
894
+ async hasTable(table)
895
+ {
896
+ const [rows] = await this._pool.execute(
897
+ `SELECT 1 FROM information_schema.tables WHERE table_schema = ? AND table_name = ? LIMIT 1`,
898
+ [this._options.database, table]
899
+ );
900
+ return rows.length > 0;
901
+ }
902
+
903
+ /**
904
+ * Check if a column exists in a table.
905
+ * @param {string} table - Table name.
906
+ * @param {string} column - Column name.
907
+ * @returns {Promise<boolean>} `true` if the column exists.
908
+ */
909
+ async hasColumn(table, column)
910
+ {
911
+ const [rows] = await this._pool.execute(
912
+ `SELECT 1 FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND column_name = ? LIMIT 1`,
913
+ [this._options.database, table, column]
914
+ );
915
+ return rows.length > 0;
916
+ }
917
+
918
+ /**
919
+ * Get a unified table description.
920
+ * @param {string} table - Table name.
921
+ * @returns {Promise<{ columns: Array, indexes: Array, foreignKeys: Array }>}
922
+ */
923
+ async describeTable(table)
924
+ {
925
+ return {
926
+ columns: await this.columns(table),
927
+ indexes: await this.indexes(table),
928
+ foreignKeys: await this.foreignKeys(table),
929
+ };
930
+ }
931
+ }
932
+
933
+ module.exports = MysqlAdapter;