@pdg/drizzle-mysql 0.0.0-stage → 1.0.1

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/dist/index.cjs ADDED
@@ -0,0 +1,684 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var mysql=require('mysql2/promise'),mysql2=require('drizzle-orm/mysql2'),native=require('drizzle-orm'),node_async_hooks=require('node:async_hooks'),alias=require('drizzle-orm/mysql-core/alias'),mysqlCore=require('drizzle-orm/mysql-core'),columnBuilder=require('drizzle-orm/column-builder');function _interopNamespaceDefault(e){var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var native__namespace=/*#__PURE__*/_interopNamespaceDefault(native);function createAlias(schema) {
2
+ /********************************************************************************************************************
3
+ * getDefaultAlias
4
+ * ******************************************************************************************************************/
5
+ const getDefaultAlias = (tableName) => `${tableName[0]}${(tableName.slice(1).match(/[A-Z]/g) ?? []).join('')}`.toLowerCase();
6
+ /********************************************************************************************************************
7
+ * createAlias
8
+ * ******************************************************************************************************************/
9
+ const createAlias = (tableName) => (alias$1 = getDefaultAlias(tableName)) => alias.alias(schema[tableName], alias$1);
10
+ /********************************************************************************************************************
11
+ * alias
12
+ * ******************************************************************************************************************/
13
+ const alias$1 = Object.fromEntries(Object.keys(schema).map((tableName) => [tableName, createAlias(tableName)]));
14
+ return alias$1;
15
+ }function createConditions(schema) {
16
+ const resolveTable = (table) => {
17
+ if (typeof table !== 'string')
18
+ return table;
19
+ if (!Object.hasOwn(schema, table)) {
20
+ throw new Error(`Condition: unknown table "${table}".`);
21
+ }
22
+ return schema[table];
23
+ };
24
+ const getColumn = (table, name) => {
25
+ const columns = native__namespace.getTableColumns(table);
26
+ if (!Object.hasOwn(columns, name)) {
27
+ throw new Error(`Condition: unknown column "${name}".`);
28
+ }
29
+ return columns[name];
30
+ };
31
+ const recordEntries = (values) => {
32
+ if (typeof values !== 'object' || values === null || Array.isArray(values)) {
33
+ throw new Error('Condition: expected a column/value object.');
34
+ }
35
+ return Object.entries(values);
36
+ };
37
+ const compareValue = (column, value, operator) => {
38
+ if (value === null) {
39
+ if (operator === 'eq')
40
+ return native__namespace.isNull(column);
41
+ if (operator === 'ne')
42
+ return native__namespace.isNotNull(column);
43
+ throw new Error(`${operator}: column "${column.name}" must not be null.`);
44
+ }
45
+ switch (operator) {
46
+ case 'eq':
47
+ return native__namespace.eq(column, value);
48
+ case 'ne':
49
+ return native__namespace.ne(column, value);
50
+ case 'gt':
51
+ return native__namespace.gt(column, value);
52
+ case 'gte':
53
+ return native__namespace.gte(column, value);
54
+ case 'lt':
55
+ return native__namespace.lt(column, value);
56
+ case 'lte':
57
+ return native__namespace.lte(column, value);
58
+ case 'inArray':
59
+ case 'notInArray':
60
+ if (!Array.isArray(value))
61
+ throw new Error(`${operator}: expected an array.`);
62
+ return operator === 'inArray' ? native__namespace.inArray(column, value) : native__namespace.notInArray(column, value);
63
+ case 'between':
64
+ case 'notBetween':
65
+ if (!Array.isArray(value) || value.length !== 2 || value.some((item) => item == null)) {
66
+ throw new Error(`${operator}: expected two non-null bounds.`);
67
+ }
68
+ return operator === 'between'
69
+ ? native__namespace.between(column, value[0], value[1])
70
+ : native__namespace.notBetween(column, value[0], value[1]);
71
+ default:
72
+ if (typeof value !== 'string')
73
+ throw new Error(`${operator}: expected a string pattern.`);
74
+ return native__namespace[operator](column, value);
75
+ }
76
+ };
77
+ const valueConditions = (table, values, operator) => {
78
+ const conditions = [];
79
+ for (const [name, value] of recordEntries(values)) {
80
+ const column = getColumn(table, name);
81
+ if (value !== undefined)
82
+ conditions.push(compareValue(column, value, operator));
83
+ }
84
+ return conditions;
85
+ };
86
+ function extendOperator(original, objectOperator) {
87
+ return (...args) => {
88
+ if (typeof args[0] === 'string' || native__namespace.is(args[0], mysqlCore.MySqlTable)) {
89
+ const table = typeof args[0] === 'string' ? resolveTable(args[0]) : args[0];
90
+ return objectOperator(table, args[1]);
91
+ }
92
+ return Reflect.apply(original, undefined, args);
93
+ };
94
+ }
95
+ const objectOperator = (operator) => (table, values) => native__namespace.and(...valueConditions(resolveTable(table), values, operator));
96
+ // Tables use object dispatch at runtime, not the native SQLWrapper/unknown overload.
97
+ const binaryOperator = (operator) => extendOperator(native__namespace[operator], objectOperator(operator));
98
+ const nullOperator = (operator) => ((table, input) => {
99
+ const names = typeof input === 'string' ? [input] : input === undefined ? [] : input;
100
+ if (!Array.isArray(names))
101
+ throw new Error(`${operator}: expected column names.`);
102
+ const conditions = [];
103
+ for (const name of names) {
104
+ if (name === undefined)
105
+ continue;
106
+ if (typeof name !== 'string')
107
+ throw new Error(`${operator}: expected a column name.`);
108
+ conditions.push(native__namespace[operator](getColumn(resolveTable(table), name)));
109
+ }
110
+ return native__namespace.and(...conditions);
111
+ });
112
+ const groupOperator = (operator) => (input, options) => {
113
+ const table = resolveTable(input);
114
+ const sqlConditions = [];
115
+ for (const [name, values] of recordEntries(options)) {
116
+ if (!Object.hasOwn(conditions, name) || name === 'and' || name === 'or') {
117
+ throw new Error(`Condition: unknown operator "${name}".`);
118
+ }
119
+ if (values === undefined)
120
+ continue;
121
+ if (name === 'isNull' || name === 'isNotNull') {
122
+ const condition = nullOperator(name)(table, values);
123
+ if (condition !== undefined)
124
+ sqlConditions.push(condition);
125
+ }
126
+ else {
127
+ const group = native__namespace.and(...valueConditions(table, values, name));
128
+ if (group !== undefined)
129
+ sqlConditions.push(group);
130
+ }
131
+ }
132
+ return native__namespace[operator](...sqlConditions);
133
+ };
134
+ const logicalOperator = (operator) => extendOperator((...conditions) => native__namespace[operator](...conditions.filter((condition) => condition !== false && condition !== undefined)), groupOperator(operator));
135
+ const conditions = {
136
+ eq: binaryOperator('eq'),
137
+ ne: binaryOperator('ne'),
138
+ gt: binaryOperator('gt'),
139
+ gte: binaryOperator('gte'),
140
+ lt: binaryOperator('lt'),
141
+ lte: binaryOperator('lte'),
142
+ inArray: extendOperator(native__namespace.inArray, objectOperator('inArray')),
143
+ notInArray: extendOperator(native__namespace.notInArray, objectOperator('notInArray')),
144
+ between: extendOperator(native__namespace.between, objectOperator('between')),
145
+ notBetween: extendOperator(native__namespace.notBetween, objectOperator('notBetween')),
146
+ like: extendOperator(native__namespace.like, objectOperator('like')),
147
+ notLike: extendOperator(native__namespace.notLike, objectOperator('notLike')),
148
+ ilike: extendOperator(native__namespace.ilike, objectOperator('ilike')),
149
+ notIlike: extendOperator(native__namespace.notIlike, objectOperator('notIlike')),
150
+ isNull: extendOperator(native__namespace.isNull, nullOperator('isNull')),
151
+ isNotNull: extendOperator(native__namespace.isNotNull, nullOperator('isNotNull')),
152
+ and: logicalOperator('and'),
153
+ or: logicalOperator('or'),
154
+ };
155
+ return conditions;
156
+ }function TableColumns(first, ...rest) {
157
+ if (Array.isArray(first) && native.isTable(first[0])) {
158
+ const result = {};
159
+ for (const group of [first, ...rest]) {
160
+ if (!Array.isArray(group) || !native.isTable(group[0])) {
161
+ throw new Error('columns: expected a table/column-name tuple.');
162
+ }
163
+ Object.assign(result, TableColumns(group[0], ...group.slice(1)));
164
+ }
165
+ return result;
166
+ }
167
+ if (native.isTable(first)) {
168
+ const tableColumns = native.getTableColumns(first);
169
+ if (rest.length === 0)
170
+ return Object.fromEntries(Object.values(tableColumns).map((column) => [column.name, column]));
171
+ const selected = {};
172
+ for (const selection of rest) {
173
+ if (typeof selection !== 'string') {
174
+ throw new Error('columns: expected a column name.');
175
+ }
176
+ const match = /^(.+?)\s+as\s+(.+)$/i.exec(selection.trim());
177
+ const name = (match?.[1] ?? selection).trim();
178
+ const alias = match?.[2]?.trim();
179
+ if (!Object.hasOwn(tableColumns, name)) {
180
+ throw new Error(`columns: unknown column "${name}".`);
181
+ }
182
+ if (alias)
183
+ selected[alias] = native.sql `${tableColumns[name]}`.as(alias);
184
+ else
185
+ selected[tableColumns[name].name] = tableColumns[name];
186
+ }
187
+ return selected;
188
+ }
189
+ const columns = (Array.isArray(first) ? first : [first, ...rest]);
190
+ return Object.fromEntries(columns.map((column) => {
191
+ if (typeof column === 'string' || Array.isArray(column))
192
+ throw new Error('columns: expected a column object.');
193
+ return [column.name, column];
194
+ }));
195
+ }const policies = new WeakMap();
196
+ for (const [method, policy] of Object.entries({
197
+ insertBlocked: { insert: 'blocked' },
198
+ insertAllowed: { insert: 'allowed' },
199
+ updateBlocked: { update: 'blocked' },
200
+ updateAllowed: { update: 'allowed' },
201
+ updateRequired: { update: 'required' },
202
+ createdAt: { timestamp: 'created' },
203
+ updatedAt: { timestamp: 'updated' },
204
+ })) {
205
+ Object.defineProperty(columnBuilder.ColumnBuilder.prototype, method, {
206
+ configurable: true,
207
+ value: function () {
208
+ policies.set(this, { ...policies.get(this), ...policy });
209
+ return this;
210
+ },
211
+ });
212
+ }
213
+ const tablePolicies = new WeakMap();
214
+ function getColumnPolicies(table) {
215
+ return tablePolicies.get(table) ?? {};
216
+ }
217
+ function mysqlTable(name, columns, extraConfig) {
218
+ let builders = {};
219
+ const table = typeof columns === 'function'
220
+ ? mysqlCore.mysqlTable(name, (types) => (builders = columns(types)), extraConfig)
221
+ : mysqlCore.mysqlTable(name, (builders = columns), extraConfig);
222
+ tablePolicies.set(table, Object.fromEntries(Object.entries(builders).map(([key, builder]) => [key, policies.get(builder) ?? {}])));
223
+ return table;
224
+ }/********************************************************************************************************************
225
+ * MySqlQuery
226
+ * ******************************************************************************************************************/
227
+ class MySqlQuery {
228
+ current;
229
+ getTimestamp;
230
+ // Table
231
+ t;
232
+ /********************************************************************************************************************
233
+ * constructor
234
+ * ******************************************************************************************************************/
235
+ constructor(table, current, getTimestamp) {
236
+ this.current = current;
237
+ this.getTimestamp = getTimestamp;
238
+ this.t = table;
239
+ }
240
+ drizzle = { ...createConditions({}), sqlNumber: (value) => native.sql `${value}`.mapWith(Number) };
241
+ /********************************************************************************************************************
242
+ * (PROTECTED) getTx
243
+ * ******************************************************************************************************************/
244
+ getTx() {
245
+ return this.current();
246
+ }
247
+ columns(...names) {
248
+ const table = this.t;
249
+ return TableColumns(table, ...names);
250
+ }
251
+ resolveFields(fields, table = this.t) {
252
+ if (Array.isArray(fields) && fields.length > 0 && fields.every((field) => typeof field === 'string')) {
253
+ return TableColumns(table, ...fields);
254
+ }
255
+ if (typeof fields !== 'function')
256
+ return normalizeFields(fields);
257
+ const query = {
258
+ t: table,
259
+ columns: (...names) => TableColumns(table, ...names),
260
+ };
261
+ return normalizeFields(fields(query));
262
+ }
263
+ select(fieldsOrAlias, fields) {
264
+ const tx = this.getTx();
265
+ const isAlias = native.isTable(fieldsOrAlias);
266
+ const table = isAlias ? fieldsOrAlias : this.t;
267
+ const selectedFields = this.resolveFields(isAlias ? fields : fieldsOrAlias, table);
268
+ return tx.select(selectedFields ?? TableColumns(table)).from(table);
269
+ }
270
+ async find(aliasOrFieldsOrWhere, fieldsOrWhere, where) {
271
+ const hasAlias = native.isTable(aliasOrFieldsOrWhere);
272
+ const fieldsOrCondition = hasAlias ? fieldsOrWhere : aliasOrFieldsOrWhere;
273
+ const hasFields = arguments.length === (hasAlias ? 3 : 2);
274
+ const isCondition = (value) => native.is(value, native.SQL) || typeof value === 'function';
275
+ const table = hasAlias ? aliasOrFieldsOrWhere : this.t;
276
+ const selectedFields = this.resolveFields(!hasFields && isCondition(fieldsOrCondition) ? undefined : fieldsOrCondition, table);
277
+ const conditionInput = !hasFields && isCondition(fieldsOrCondition)
278
+ ? fieldsOrCondition
279
+ : hasAlias
280
+ ? where
281
+ : isCondition(fieldsOrWhere)
282
+ ? fieldsOrWhere
283
+ : undefined;
284
+ const condition = typeof conditionInput === 'function' ? conditionInput(this) : conditionInput;
285
+ if (condition !== undefined && !native.is(condition, native.SQL)) {
286
+ throw new Error('find: the where callback must return SQL or undefined.');
287
+ }
288
+ const builder = (() => {
289
+ if (hasAlias) {
290
+ const alias = aliasOrFieldsOrWhere;
291
+ if (selectedFields === undefined) {
292
+ return this.select(alias);
293
+ }
294
+ return this.select(alias, selectedFields);
295
+ }
296
+ return selectedFields === undefined
297
+ ? this.select()
298
+ : this.select(selectedFields);
299
+ })();
300
+ const [result] = await builder.where(condition).limit(1);
301
+ return result;
302
+ }
303
+ async findByPrimaryKey(fieldsOrKey, key) {
304
+ const hasFields = arguments.length === 2;
305
+ const primaryKeyValue = hasFields ? key : fieldsOrKey;
306
+ const condition = this.primaryKeyCondition(primaryKeyValue, 'findByPrimaryKey');
307
+ if (hasFields) {
308
+ return this.find(this.resolveFields(fieldsOrKey), condition);
309
+ }
310
+ return this.find(condition);
311
+ }
312
+ /********************************************************************************************************************
313
+ * primaryKeyCondition
314
+ * ******************************************************************************************************************/
315
+ primaryKeyCondition(primaryKeyValue, method) {
316
+ // 固定された MySqlTable 型で取得し、ジェネリックによる型の拡大を避ける。
317
+ const table = this.t;
318
+ const config = mysqlCore.getTableConfig(table);
319
+ const columns = native.getTableColumns(table);
320
+ const primaryColumns = new Set(config.columns.filter((column) => column.primary));
321
+ for (const primaryKey of config.primaryKeys) {
322
+ for (const column of primaryKey.columns) {
323
+ primaryColumns.add(column);
324
+ }
325
+ }
326
+ const primaryEntries = Object.entries(columns).filter(([, column]) => primaryColumns.has(column));
327
+ if (primaryEntries.length === 0) {
328
+ throw new Error(`${method}: ${config.name} has no primary key.`);
329
+ }
330
+ const isKeyObject = typeof primaryKeyValue === 'object' && primaryKeyValue !== null && !Array.isArray(primaryKeyValue);
331
+ if (primaryEntries.length > 1 && !isKeyObject) {
332
+ throw new Error(`${method}: ${config.name} requires a composite key object.`);
333
+ }
334
+ const keyObject = isKeyObject ? primaryKeyValue : undefined;
335
+ if (keyObject &&
336
+ Object.keys(keyObject).some((name) => !primaryEntries.some(([primaryName]) => primaryName === name))) {
337
+ throw new Error(`${method}: ${config.name} received an unknown primary key field.`);
338
+ }
339
+ const conditions = primaryEntries.map(([name, column]) => {
340
+ if (keyObject && !Object.hasOwn(keyObject, name)) {
341
+ throw new Error(`${method}: missing primary key field "${name}".`);
342
+ }
343
+ const value = keyObject ? keyObject[name] : primaryKeyValue;
344
+ if (value === undefined || value === null) {
345
+ throw new Error(`${method}: primary key field "${name}" must have a value.`);
346
+ }
347
+ return native.eq(column, value);
348
+ });
349
+ const condition = native.and(...conditions);
350
+ if (!condition) {
351
+ throw new Error(`${method}: failed to build the primary key condition.`);
352
+ }
353
+ return condition;
354
+ }
355
+ /********************************************************************************************************************
356
+ * exists
357
+ * ******************************************************************************************************************/
358
+ async exists(where) {
359
+ const condition = typeof where === 'function' ? where(this) : where;
360
+ if (condition !== undefined && !native.is(condition, native.SQL)) {
361
+ throw new Error('exists: the where callback must return SQL or undefined.');
362
+ }
363
+ const [result] = await this.select({ matched: this.drizzle.sqlNumber(1) })
364
+ .where(condition)
365
+ .limit(1);
366
+ return result !== undefined;
367
+ }
368
+ /********************************************************************************************************************
369
+ * existsByPrimarykey
370
+ * ******************************************************************************************************************/
371
+ async existsByPrimaryKey(key) {
372
+ const result = await this.findByPrimaryKey({ matched: this.drizzle.sqlNumber(1) }, key);
373
+ return result !== undefined;
374
+ }
375
+ /********************************************************************************************************************
376
+ * notExists
377
+ * ******************************************************************************************************************/
378
+ async notExists(where) {
379
+ return !(await this.exists(where));
380
+ }
381
+ /********************************************************************************************************************
382
+ * notExistsByPrimaryKey
383
+ * ******************************************************************************************************************/
384
+ async notExistsByPrimaryKey(key) {
385
+ return !(await this.existsByPrimaryKey(key));
386
+ }
387
+ /********************************************************************************************************************
388
+ * count
389
+ * ******************************************************************************************************************/
390
+ async count(where) {
391
+ const condition = typeof where === 'function' ? where(this) : where;
392
+ if (condition !== undefined && !native.is(condition, native.SQL)) {
393
+ throw new Error('count: the where callback must return SQL or undefined.');
394
+ }
395
+ const [{ cnt }] = await this.select({ cnt: native.count() }).where(condition);
396
+ return cnt;
397
+ }
398
+ prepareValues(input, operation) {
399
+ const values = { ...input };
400
+ const columns = native.getTableColumns(this.t);
401
+ const policies = getColumnPolicies(this.t);
402
+ let timestamp;
403
+ let generated = false;
404
+ for (const [key, column] of Object.entries(columns)) {
405
+ const policy = policies[key] ?? {};
406
+ const auto = 'autoIncrement' in column && column.autoIncrement === true;
407
+ const rule = operation === 'insert' ? policy.insert : policy.update;
408
+ const blocked = !!policy.timestamp || rule === 'blocked' || (auto && rule !== 'allowed' && rule !== 'required');
409
+ if (blocked && Object.hasOwn(values, key))
410
+ throw new Error(`${operation}: column "${key}" is blocked.`);
411
+ if (operation === 'update' && rule === 'required' && values[key] === undefined) {
412
+ throw new Error(`update: column "${key}" is required.`);
413
+ }
414
+ if (policy.timestamp && (operation === 'insert' || policy.timestamp === 'updated')) {
415
+ if (!generated) {
416
+ timestamp = this.getTimestamp();
417
+ generated = true;
418
+ }
419
+ values[key] = timestamp;
420
+ }
421
+ }
422
+ return values;
423
+ }
424
+ /********************************************************************************************************************
425
+ * (PRIVATE) insertValues
426
+ * ******************************************************************************************************************/
427
+ async insertValues(value) {
428
+ const tx = this.getTx();
429
+ const autoIncrementColumn = mysqlCore.getTableConfig(this.t).columns.find((column) => 'autoIncrement' in column && column.autoIncrement === true);
430
+ const hasAutoIncrement = !!autoIncrementColumn;
431
+ const autoIncrementKey = autoIncrementColumn &&
432
+ Object.keys(native.getTableColumns(this.t)).find((key) => native.getTableColumns(this.t)[key] === autoIncrementColumn);
433
+ if (hasAutoIncrement) {
434
+ if (Array.isArray(value)) {
435
+ const addedItems = await tx.insert(this.t).values(value).$returningId();
436
+ return addedItems.map((item) => item[autoIncrementKey]);
437
+ }
438
+ else {
439
+ const [item] = await tx.insert(this.t).values(value).$returningId();
440
+ return item[autoIncrementKey];
441
+ }
442
+ }
443
+ else {
444
+ if (Array.isArray(value)) {
445
+ await tx.insert(this.t).values(value);
446
+ return Array(value.length).fill(undefined);
447
+ }
448
+ else {
449
+ await tx.insert(this.t).values(value);
450
+ return undefined;
451
+ }
452
+ }
453
+ }
454
+ add(value) {
455
+ const items = Array.isArray(value) ? value : [value];
456
+ const values = items.map((item) => this.prepareValues(item, 'insert'));
457
+ return this.insertValues((Array.isArray(value) ? values : values[0]));
458
+ }
459
+ /********************************************************************************************************************
460
+ * edit
461
+ * ******************************************************************************************************************/
462
+ edit(set, where) {
463
+ const condition = typeof where === 'function' ? where(this) : where;
464
+ if (!native.is(condition, native.SQL)) {
465
+ throw new Error('edit: a SQL where condition is required.');
466
+ }
467
+ const tx = this.getTx();
468
+ return tx
469
+ .update(this.t)
470
+ .set(this.prepareValues(set, 'update'))
471
+ .where(condition);
472
+ }
473
+ /********************************************************************************************************************
474
+ * editByPrimaryKey
475
+ * ******************************************************************************************************************/
476
+ editByPrimaryKey(set, key) {
477
+ return this.edit(set, this.primaryKeyCondition(key, 'editByPrimaryKey'));
478
+ }
479
+ /********************************************************************************************************************
480
+ * remove
481
+ * ******************************************************************************************************************/
482
+ remove(where) {
483
+ const condition = typeof where === 'function' ? where(this) : where;
484
+ if (!native.is(condition, native.SQL)) {
485
+ throw new Error('remove: a SQL where condition is required.');
486
+ }
487
+ const tx = this.getTx();
488
+ return tx.delete(this.t).where(condition);
489
+ }
490
+ /********************************************************************************************************************
491
+ * removeByPrimaryKey
492
+ * ******************************************************************************************************************/
493
+ removeByPrimaryKey(key) {
494
+ return this.remove(this.primaryKeyCondition(key, 'removeByPrimaryKey'));
495
+ }
496
+ /********************************************************************************************************************
497
+ * eq
498
+ * ******************************************************************************************************************/
499
+ eq(values) {
500
+ return this.drizzle.eq(this.t, values);
501
+ }
502
+ /********************************************************************************************************************
503
+ * ne
504
+ * ******************************************************************************************************************/
505
+ ne(values) {
506
+ return this.drizzle.ne(this.t, values);
507
+ }
508
+ /********************************************************************************************************************
509
+ * gt
510
+ * ******************************************************************************************************************/
511
+ gt(values) {
512
+ return this.drizzle.gt(this.t, values);
513
+ }
514
+ /********************************************************************************************************************
515
+ * gte
516
+ * ******************************************************************************************************************/
517
+ gte(values) {
518
+ return this.drizzle.gte(this.t, values);
519
+ }
520
+ /********************************************************************************************************************
521
+ * lt
522
+ * ******************************************************************************************************************/
523
+ lt(values) {
524
+ return this.drizzle.lt(this.t, values);
525
+ }
526
+ /********************************************************************************************************************
527
+ * lte
528
+ * ******************************************************************************************************************/
529
+ lte(values) {
530
+ return this.drizzle.lte(this.t, values);
531
+ }
532
+ /********************************************************************************************************************
533
+ * lte
534
+ * ******************************************************************************************************************/
535
+ inArray(values) {
536
+ return this.drizzle.inArray(this.t, values);
537
+ }
538
+ /********************************************************************************************************************
539
+ * notInArray
540
+ * ******************************************************************************************************************/
541
+ notInArray(values) {
542
+ return this.drizzle.notInArray(this.t, values);
543
+ }
544
+ /********************************************************************************************************************
545
+ * between
546
+ * ******************************************************************************************************************/
547
+ between(values) {
548
+ return this.drizzle.between(this.t, values);
549
+ }
550
+ /********************************************************************************************************************
551
+ * notBetween
552
+ * ******************************************************************************************************************/
553
+ notBetween(values) {
554
+ return this.drizzle.notBetween(this.t, values);
555
+ }
556
+ /********************************************************************************************************************
557
+ * like
558
+ * ******************************************************************************************************************/
559
+ like(values) {
560
+ return this.drizzle.like(this.t, values);
561
+ }
562
+ /********************************************************************************************************************
563
+ * notLike
564
+ * ******************************************************************************************************************/
565
+ notLike(values) {
566
+ return this.drizzle.notLike(this.t, values);
567
+ }
568
+ /********************************************************************************************************************
569
+ * ilike
570
+ * ******************************************************************************************************************/
571
+ ilike(values) {
572
+ return this.drizzle.ilike(this.t, values);
573
+ }
574
+ /********************************************************************************************************************
575
+ * notIlike
576
+ * ******************************************************************************************************************/
577
+ notIlike(values) {
578
+ return this.drizzle.notIlike(this.t, values);
579
+ }
580
+ isNull(names) {
581
+ return this.drizzle.isNull(this.t, names);
582
+ }
583
+ isNotNull(names) {
584
+ return this.drizzle.isNotNull(this.t, names);
585
+ }
586
+ /********************************************************************************************************************
587
+ * and
588
+ * ******************************************************************************************************************/
589
+ and(options) {
590
+ return this.drizzle.and(this.t, options);
591
+ }
592
+ /********************************************************************************************************************
593
+ * or
594
+ * ******************************************************************************************************************/
595
+ or(options) {
596
+ return this.drizzle.or(this.t, options);
597
+ }
598
+ }
599
+ const normalizeFields = (fields) => {
600
+ if (fields === undefined)
601
+ return undefined;
602
+ const groups = Array.isArray(fields) ? fields : [fields];
603
+ const result = {};
604
+ for (const group of groups) {
605
+ if (Array.isArray(fields) && (group === false || group === undefined))
606
+ continue;
607
+ if (typeof group !== 'object' || group === null || Array.isArray(group) || native.isTable(group) || native.is(group, native.SQL)) {
608
+ throw new Error('fields: expected a selection object or an array of selection objects.');
609
+ }
610
+ Object.assign(result, group);
611
+ }
612
+ for (const [name, field] of Object.entries(result)) {
613
+ if (native.is(field, mysqlCore.MySqlColumn) && field.name !== name) {
614
+ result[name] = native.sql `${field}`.mapWith(field).as(name);
615
+ }
616
+ }
617
+ return result;
618
+ };function drizzleMySql(options) {
619
+ const pool = mysql.createPool({ uri: options.url });
620
+ const raw = mysql2.drizzle({ client: pool, relations: native.defineRelations(options.schema) });
621
+ const context = new node_async_hooks.AsyncLocalStorage();
622
+ const current = () => context.getStore() ?? raw;
623
+ const trans = (callback) => {
624
+ const parent = context.getStore();
625
+ const execute = (tx) => context.run(tx, callback);
626
+ return parent ? parent.transaction(execute) : raw.transaction(execute);
627
+ };
628
+ const paginate = async (builder, page, limit) => {
629
+ if (!Number.isInteger(page) || page < 1 || !Number.isInteger(limit) || limit < 1) {
630
+ throw new RangeError('page and limit must be positive integers');
631
+ }
632
+ const offset = (page - 1) * limit;
633
+ const [[{ total }], data] = await Promise.all([
634
+ current().select({ total: native.count() }).from(builder.as('a')),
635
+ builder.limit(limit).offset(offset),
636
+ ]);
637
+ return {
638
+ data,
639
+ paging: {
640
+ current_page: page,
641
+ per_page: limit,
642
+ last_page: Math.ceil(total / limit),
643
+ total,
644
+ from: offset,
645
+ to: offset + data.length,
646
+ },
647
+ };
648
+ };
649
+ return {
650
+ asc: native__namespace.asc,
651
+ desc: native__namespace.desc,
652
+ count: native__namespace.count,
653
+ countDistinct: native__namespace.countDistinct,
654
+ avg: native__namespace.avg,
655
+ avgDistinct: native__namespace.avgDistinct,
656
+ sum: native__namespace.sum,
657
+ sumDistinct: native__namespace.sumDistinct,
658
+ max: native__namespace.max,
659
+ min: native__namespace.min,
660
+ not: native__namespace.not,
661
+ exists: native__namespace.exists,
662
+ notExists: native__namespace.notExists,
663
+ arrayContains: native__namespace.arrayContains,
664
+ arrayContained: native__namespace.arrayContained,
665
+ arrayOverlaps: native__namespace.arrayOverlaps,
666
+ s: options.schema,
667
+ a: createAlias(options.schema),
668
+ ...createConditions(options.schema),
669
+ columns: TableColumns,
670
+ sql: native.sql,
671
+ sqlNumber: (value) => (native.is(value, native.SQL) ? value : native.sql `${value}`).mapWith(Number),
672
+ sqlString: (value) => (native.is(value, native.SQL) ? value : native.sql `${value}`).mapWith(String),
673
+ sqlBoolean: (value) => (native.is(value, native.SQL) ? value : native.sql `${value}`).mapWith((v) => v === true || v === 1),
674
+ current,
675
+ query: (table) => new MySqlQuery(table, current, () => {
676
+ if (!options.timestamp)
677
+ throw new Error('timestamp generator is not configured');
678
+ return options.timestamp();
679
+ }),
680
+ trans,
681
+ paginate,
682
+ close: () => pool.end(),
683
+ };
684
+ }Object.defineProperty(exports,"asc",{enumerable:true,get:function(){return native.asc}});Object.defineProperty(exports,"avg",{enumerable:true,get:function(){return native.avg}});Object.defineProperty(exports,"avgDistinct",{enumerable:true,get:function(){return native.avgDistinct}});Object.defineProperty(exports,"count",{enumerable:true,get:function(){return native.count}});Object.defineProperty(exports,"countDistinct",{enumerable:true,get:function(){return native.countDistinct}});Object.defineProperty(exports,"desc",{enumerable:true,get:function(){return native.desc}});Object.defineProperty(exports,"exists",{enumerable:true,get:function(){return native.exists}});Object.defineProperty(exports,"max",{enumerable:true,get:function(){return native.max}});Object.defineProperty(exports,"min",{enumerable:true,get:function(){return native.min}});Object.defineProperty(exports,"not",{enumerable:true,get:function(){return native.not}});Object.defineProperty(exports,"notExists",{enumerable:true,get:function(){return native.notExists}});Object.defineProperty(exports,"sum",{enumerable:true,get:function(){return native.sum}});Object.defineProperty(exports,"sumDistinct",{enumerable:true,get:function(){return native.sumDistinct}});Object.defineProperty(exports,"bigint",{enumerable:true,get:function(){return mysqlCore.bigint}});Object.defineProperty(exports,"binary",{enumerable:true,get:function(){return mysqlCore.binary}});Object.defineProperty(exports,"blob",{enumerable:true,get:function(){return mysqlCore.blob}});Object.defineProperty(exports,"boolean",{enumerable:true,get:function(){return mysqlCore.boolean}});Object.defineProperty(exports,"char",{enumerable:true,get:function(){return mysqlCore.char}});Object.defineProperty(exports,"check",{enumerable:true,get:function(){return mysqlCore.check}});Object.defineProperty(exports,"customType",{enumerable:true,get:function(){return mysqlCore.customType}});Object.defineProperty(exports,"date",{enumerable:true,get:function(){return mysqlCore.date}});Object.defineProperty(exports,"datetime",{enumerable:true,get:function(){return mysqlCore.datetime}});Object.defineProperty(exports,"decimal",{enumerable:true,get:function(){return mysqlCore.decimal}});Object.defineProperty(exports,"double",{enumerable:true,get:function(){return mysqlCore.double}});Object.defineProperty(exports,"float",{enumerable:true,get:function(){return mysqlCore.float}});Object.defineProperty(exports,"foreignKey",{enumerable:true,get:function(){return mysqlCore.foreignKey}});Object.defineProperty(exports,"index",{enumerable:true,get:function(){return mysqlCore.index}});Object.defineProperty(exports,"int",{enumerable:true,get:function(){return mysqlCore.int}});Object.defineProperty(exports,"json",{enumerable:true,get:function(){return mysqlCore.json}});Object.defineProperty(exports,"longblob",{enumerable:true,get:function(){return mysqlCore.longblob}});Object.defineProperty(exports,"longtext",{enumerable:true,get:function(){return mysqlCore.longtext}});Object.defineProperty(exports,"mediumblob",{enumerable:true,get:function(){return mysqlCore.mediumblob}});Object.defineProperty(exports,"mediumint",{enumerable:true,get:function(){return mysqlCore.mediumint}});Object.defineProperty(exports,"mediumtext",{enumerable:true,get:function(){return mysqlCore.mediumtext}});Object.defineProperty(exports,"mysqlDatabase",{enumerable:true,get:function(){return mysqlCore.mysqlDatabase}});Object.defineProperty(exports,"mysqlEnum",{enumerable:true,get:function(){return mysqlCore.mysqlEnum}});Object.defineProperty(exports,"mysqlSchema",{enumerable:true,get:function(){return mysqlCore.mysqlSchema}});Object.defineProperty(exports,"mysqlTableCreator",{enumerable:true,get:function(){return mysqlCore.mysqlTableCreator}});Object.defineProperty(exports,"mysqlView",{enumerable:true,get:function(){return mysqlCore.mysqlView}});Object.defineProperty(exports,"primaryKey",{enumerable:true,get:function(){return mysqlCore.primaryKey}});Object.defineProperty(exports,"real",{enumerable:true,get:function(){return mysqlCore.real}});Object.defineProperty(exports,"serial",{enumerable:true,get:function(){return mysqlCore.serial}});Object.defineProperty(exports,"smallint",{enumerable:true,get:function(){return mysqlCore.smallint}});Object.defineProperty(exports,"text",{enumerable:true,get:function(){return mysqlCore.text}});Object.defineProperty(exports,"time",{enumerable:true,get:function(){return mysqlCore.time}});Object.defineProperty(exports,"timestamp",{enumerable:true,get:function(){return mysqlCore.timestamp}});Object.defineProperty(exports,"tinyblob",{enumerable:true,get:function(){return mysqlCore.tinyblob}});Object.defineProperty(exports,"tinyint",{enumerable:true,get:function(){return mysqlCore.tinyint}});Object.defineProperty(exports,"tinytext",{enumerable:true,get:function(){return mysqlCore.tinytext}});Object.defineProperty(exports,"unique",{enumerable:true,get:function(){return mysqlCore.unique}});Object.defineProperty(exports,"uniqueIndex",{enumerable:true,get:function(){return mysqlCore.uniqueIndex}});Object.defineProperty(exports,"varbinary",{enumerable:true,get:function(){return mysqlCore.varbinary}});Object.defineProperty(exports,"varchar",{enumerable:true,get:function(){return mysqlCore.varchar}});Object.defineProperty(exports,"year",{enumerable:true,get:function(){return mysqlCore.year}});exports.MySqlQuery=MySqlQuery;exports.TableColumns=TableColumns;exports.createConditions=createConditions;exports.default=drizzleMySql;exports.drizzleMySql=drizzleMySql;exports.mysqlTable=mysqlTable;