@foul11/awesome-db 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/BitFields.d.ts +29 -0
  3. package/dist/BitFields.d.ts.map +1 -0
  4. package/dist/Error.d.ts +21 -0
  5. package/dist/Error.d.ts.map +1 -0
  6. package/dist/ORM.d.ts +14 -0
  7. package/dist/ORM.d.ts.map +1 -0
  8. package/dist/SQLParser.d.ts +1394 -0
  9. package/dist/SQLParser.d.ts.map +1 -0
  10. package/dist/WebpackFileProvider.d.ts +12 -0
  11. package/dist/WebpackFileProvider.d.ts.map +1 -0
  12. package/dist/alter/column_add.d.ts +7 -0
  13. package/dist/alter/column_add.d.ts.map +1 -0
  14. package/dist/alter/column_drop.d.ts +6 -0
  15. package/dist/alter/column_drop.d.ts.map +1 -0
  16. package/dist/alter/column_rename.d.ts +6 -0
  17. package/dist/alter/column_rename.d.ts.map +1 -0
  18. package/dist/alter/column_update.d.ts +7 -0
  19. package/dist/alter/column_update.d.ts.map +1 -0
  20. package/dist/alter/columns_order.d.ts +6 -0
  21. package/dist/alter/columns_order.d.ts.map +1 -0
  22. package/dist/alter/index.d.ts +7 -0
  23. package/dist/alter/index.d.ts.map +1 -0
  24. package/dist/alter/pragma.d.ts +4 -0
  25. package/dist/alter/pragma.d.ts.map +1 -0
  26. package/dist/alter/utils.d.ts +6 -0
  27. package/dist/alter/utils.d.ts.map +1 -0
  28. package/dist/defaults.d.ts +2 -0
  29. package/dist/defaults.d.ts.map +1 -0
  30. package/dist/index.d.ts +36 -0
  31. package/dist/index.d.ts.map +1 -0
  32. package/dist/index.mjs +1540 -0
  33. package/dist/index.mjs.map +1 -0
  34. package/dist/indexer.d.ts +12 -0
  35. package/dist/indexer.d.ts.map +1 -0
  36. package/dist/log/access_log.d.ts +7 -0
  37. package/dist/log/access_log.d.ts.map +1 -0
  38. package/dist/log/db.d.ts +6 -0
  39. package/dist/log/db.d.ts.map +1 -0
  40. package/dist/log/index.d.ts +3 -0
  41. package/dist/log/index.d.ts.map +1 -0
  42. package/dist/tables/AccessLog/index.d.ts +79 -0
  43. package/dist/tables/AccessLog/index.d.ts.map +1 -0
  44. package/dist/tables/AccessLog/schema.d.ts +17 -0
  45. package/dist/tables/AccessLog/schema.d.ts.map +1 -0
  46. package/dist/tables/Permission/index.d.ts +43 -0
  47. package/dist/tables/Permission/index.d.ts.map +1 -0
  48. package/dist/tables/Permission/schema.d.ts +12 -0
  49. package/dist/tables/Permission/schema.d.ts.map +1 -0
  50. package/dist/tables/SetString/index.d.ts +10 -0
  51. package/dist/tables/SetString/index.d.ts.map +1 -0
  52. package/dist/tables/SetString/schema.d.ts +7 -0
  53. package/dist/tables/SetString/schema.d.ts.map +1 -0
  54. package/dist/tables/Settings/index.d.ts +42 -0
  55. package/dist/tables/Settings/index.d.ts.map +1 -0
  56. package/dist/tables/Settings/schema.d.ts +8 -0
  57. package/dist/tables/Settings/schema.d.ts.map +1 -0
  58. package/dist/tables/Transaction/index.d.ts +90 -0
  59. package/dist/tables/Transaction/index.d.ts.map +1 -0
  60. package/dist/tables/Transaction/schema.d.ts +16 -0
  61. package/dist/tables/Transaction/schema.d.ts.map +1 -0
  62. package/dist/types/index.d.ts +12 -0
  63. package/dist/types/index.d.ts.map +1 -0
  64. package/dist/utils.d.ts +42 -0
  65. package/dist/utils.d.ts.map +1 -0
  66. package/eslint.config.js +7 -0
  67. package/package.json +54 -0
  68. package/src/BitFields.ts +160 -0
  69. package/src/Error.ts +13 -0
  70. package/src/ORM.ts +49 -0
  71. package/src/SQLParser.js +1204 -0
  72. package/src/WebpackFileProvider.ts +63 -0
  73. package/src/alter/column_add.ts +79 -0
  74. package/src/alter/column_drop.ts +54 -0
  75. package/src/alter/column_rename.ts +55 -0
  76. package/src/alter/column_update.ts +92 -0
  77. package/src/alter/columns_order.ts +60 -0
  78. package/src/alter/index.ts +6 -0
  79. package/src/alter/pragma.ts +10 -0
  80. package/src/alter/utils.ts +70 -0
  81. package/src/defaults.ts +3 -0
  82. package/src/index.ts +227 -0
  83. package/src/indexer.ts +75 -0
  84. package/src/log/access_log.ts +29 -0
  85. package/src/log/db.ts +28 -0
  86. package/src/log/index.ts +2 -0
  87. package/src/tables/AccessLog/index.ts +252 -0
  88. package/src/tables/AccessLog/schema.ts +20 -0
  89. package/src/tables/Permission/index.ts +220 -0
  90. package/src/tables/Permission/schema.ts +13 -0
  91. package/src/tables/SetString/index.ts +45 -0
  92. package/src/tables/SetString/schema.ts +7 -0
  93. package/src/tables/Settings/index.ts +135 -0
  94. package/src/tables/Settings/schema.ts +8 -0
  95. package/src/tables/Transaction/index.ts +343 -0
  96. package/src/tables/Transaction/schema.ts +20 -0
  97. package/src/types/index.ts +33 -0
  98. package/src/utils.ts +48 -0
  99. package/test/sqliteExtExpert.test.ts +39 -0
  100. package/tsconfig.build.json +17 -0
  101. package/tsconfig.json +16 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,1540 @@
1
+ import { Kysely as __WEBPACK_EXTERNAL_MODULE_kysely_Kysely__, SqliteDialect as __WEBPACK_EXTERNAL_MODULE_kysely_SqliteDialect__, sql as __WEBPACK_EXTERNAL_MODULE_kysely_sql__ } from "kysely";
2
+ import { Object_entries as __WEBPACK_EXTERNAL_MODULE__foul11_awesome_5cd072e2_Object_entries__, Object_keys as __WEBPACK_EXTERNAL_MODULE__foul11_awesome_5cd072e2_Object_keys__, isWebpack as __WEBPACK_EXTERNAL_MODULE__foul11_awesome_5cd072e2_isWebpack__, regex as __WEBPACK_EXTERNAL_MODULE__foul11_awesome_5cd072e2_regex__ } from "@foul11/awesome";
3
+ import { color as __WEBPACK_EXTERNAL_MODULE__foul11_awesome_log_ab373ec3_color__, f_printf as __WEBPACK_EXTERNAL_MODULE__foul11_awesome_log_ab373ec3_f_printf__, loggers as __WEBPACK_EXTERNAL_MODULE__foul11_awesome_log_ab373ec3_loggers__, pretty_message as __WEBPACK_EXTERNAL_MODULE__foul11_awesome_log_ab373ec3_pretty_message__, pretty_ms as __WEBPACK_EXTERNAL_MODULE__foul11_awesome_log_ab373ec3_pretty_ms__ } from "@foul11/awesome-log";
4
+ import { Migrator as __WEBPACK_EXTERNAL_MODULE_kysely_migration_c9f7ddf4_Migrator__ } from "kysely/migration";
5
+ import { format as __WEBPACK_EXTERNAL_MODULE__foul11_sql_formatter_5d7ed540_format__ } from "@foul11/sql-formatter";
6
+ import { v4 as __WEBPACK_EXTERNAL_MODULE_uuid_v4__ } from "uuid";
7
+ import { default as __WEBPACK_EXTERNAL_MODULE_better_sqlite3_b46a9d6d_default__ } from "better-sqlite3";
8
+ import { default as __WEBPACK_EXTERNAL_MODULE_bindings_default__ } from "bindings";
9
+ import { default as __WEBPACK_EXTERNAL_MODULE_path_default__ } from "path";
10
+ /******/ // The require scope
11
+ /******/ var __webpack_require__ = {};
12
+ /******/
13
+ /************************************************************************/
14
+ /******/ /* webpack/runtime/define property getters */
15
+ /******/ (() => {
16
+ /******/ // define getter functions for harmony exports
17
+ /******/ __webpack_require__.d = (exports, definition) => {
18
+ /******/ for(var key in definition) {
19
+ /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
20
+ /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
21
+ /******/ }
22
+ /******/ }
23
+ /******/ };
24
+ /******/ })();
25
+ /******/
26
+ /******/ /* webpack/runtime/hasOwnProperty shorthand */
27
+ /******/ (() => {
28
+ /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
29
+ /******/ })();
30
+ /******/
31
+ /************************************************************************/
32
+
33
+ ;// external "kysely"
34
+
35
+ ;// ./src/alter/utils.ts
36
+
37
+ function columnDefinition(col, columnDef) {
38
+ if (columnDef.primary) col = col.primaryKey();
39
+ if (columnDef.unique) col = col.unique();
40
+ if (columnDef.auto_increment) col = col.autoIncrement();
41
+ if (columnDef.not_null) col = col.notNull();
42
+ if (columnDef.default !== null) {
43
+ if (typeof columnDef.default == 'string' && columnDef.default[0] == '(') {
44
+ col = col.defaultTo(__WEBPACK_EXTERNAL_MODULE_kysely_sql__.raw(columnDef.default));
45
+ } else {
46
+ col = col.defaultTo(__WEBPACK_EXTERNAL_MODULE_kysely_sql__.lit(columnDef.default));
47
+ }
48
+ }
49
+ if (columnDef.references) {
50
+ if (!columnDef.references.columns.length || columnDef.references.columns.length > 1) throw new Error('Only one column can be referenced');
51
+ const column_name = columnDef.references.columns[0];
52
+ const schema_name = [...columnDef.references.table.scheme_parts, columnDef.references.table.name, column_name].join('.');
53
+ col = col.references(schema_name);
54
+ if (columnDef.references.constraints) {
55
+ col = col.modifyEnd(__WEBPACK_EXTERNAL_MODULE_kysely_sql__.raw(` ${columnDef.references.constraints}`));
56
+ }
57
+ }
58
+ return col;
59
+ }
60
+ function itAddColumn(builder, columns) {
61
+ for (const column of columns) {
62
+ builder = builder.addColumn(column.name, column.type.toLowerCase(), col => columnDefinition(col, column));
63
+ }
64
+ return builder;
65
+ }
66
+ function tmpTableName(table) {
67
+ return `alter_${Math.floor(Date.now() / 1000)}_${table}`;
68
+ }
69
+ ;// external "@foul11/awesome"
70
+
71
+ ;// ./src/SQLParser.js
72
+ /* eslint-disable no-useless-assignment, jsdoc/reject-any-type, @stylistic/function-call-spacing */
73
+ // spell-checker: words sqlv AUTOINCREMENT SAVEPOINT sqlited
74
+
75
+ /** @param {string | TemplateStringsArray} str */
76
+ function sqlv(str) {
77
+ if (Array.isArray(str)) str = str[0];
78
+ const arr = str.toString().split(/\r?\n/);
79
+ for (let i = 0; i < arr.length; i++) {
80
+ switch (true) {
81
+ case arr[i].trim().startsWith('INSERT INTO'):
82
+ case arr[i].trim().startsWith('ALTER TABLE'):
83
+ case arr[i].trim().startsWith('DROP TABLE'):
84
+ case arr[i].trim().startsWith('PRAGMA "main".foreign_key_check'):
85
+ arr[i] = arr[i] + ';';
86
+ break;
87
+ }
88
+ }
89
+ return arr.join('\n');
90
+ }
91
+ class SQLParser {
92
+ /**
93
+ * @typedef {string | number | null} sqlite_value
94
+ *
95
+ * @typedef {{
96
+ * scheme_parts: string[],
97
+ * name: string,
98
+ * }} sqlite_schema
99
+ *
100
+ * @typedef {{
101
+ * name: string,
102
+ * as: string?,
103
+ * sort: 'ASC' | 'DESC' | null,
104
+ * }} sqlite_column
105
+ *
106
+ * @typedef {{
107
+ * type: 'PRAGMA',
108
+ * name: sqlite_schema,
109
+ * value: sqlite_value,
110
+ * }} sqlite_PRAGMA
111
+ *
112
+ * @typedef {{
113
+ * type: 'SAVEPOINT',
114
+ * savepoint_name: string?,
115
+ * }} sqlite_SAVEPOINT
116
+ *
117
+ * @typedef {{
118
+ * type: 'RELEASE',
119
+ * savepoint_name: string?,
120
+ * }} sqlite_RELEASE
121
+ *
122
+ * @typedef {{
123
+ * type: 'SELECT',
124
+ * distinct: boolean,
125
+ * columns: Exclude<sqlite_column, 'sort'>[],
126
+ * from: sqlite_schema[],
127
+ * where: string?,
128
+ * group_by: string?,
129
+ * order_by: string?,
130
+ * limit: number?,
131
+ * offset: number?,
132
+ * }} sqlite_SELECT
133
+ *
134
+ * @typedef {{
135
+ * table: sqlite_schema,
136
+ * columns: string[],
137
+ * constraints: string?,
138
+ * }} sqlite_references
139
+ *
140
+ * @typedef {'TEXT' | 'INTEGER' | 'REAL' | 'BLOB' | 'DATETIME'} sqlite_types
141
+ *
142
+ * @typedef {{
143
+ * name: string,
144
+ * type: sqlite_types,
145
+ * primary: boolean,
146
+ * auto_increment: boolean,
147
+ * not_null: boolean,
148
+ * unique: boolean,
149
+ * default: sqlite_value,
150
+ * references: sqlite_references?,
151
+ * }} sqlite_column_def
152
+ *
153
+ * @typedef {Omit<Omit<sqlite_column_def, 'name'>, 'type'>} sqlite_constraint
154
+ *
155
+ * @typedef {{
156
+ * type: 'CREATE_TABLE',
157
+ * table: sqlite_schema,
158
+ * if_not_exists: boolean,
159
+ * columns: sqlite_column_def[],
160
+ * }} sqlite_CREATE_TABLE
161
+ *
162
+ * @typedef {{
163
+ * type: 'CREATE_INDEX',
164
+ * name: sqlite_schema,
165
+ * table_name: string,
166
+ * if_not_exists: boolean,
167
+ * unique: boolean,
168
+ * columns: Omit<sqlite_column, 'as'>[],
169
+ * }} sqlite_CREATE_INDEX
170
+ *
171
+ * @typedef {{
172
+ * type: 'VALUES',
173
+ * values: (number | string)[],
174
+ * }} sqlite_VALUES
175
+ *
176
+ * @typedef {{
177
+ * type: 'INSERT',
178
+ * table: sqlite_schema,
179
+ * columns: Omit<Omit<sqlite_column, 'as'>, 'sort'>[],
180
+ * expr: sqlite_VALUES | sqlite_SELECT,
181
+ * }} sqlite_INSERT
182
+ *
183
+ * @typedef {{
184
+ * type: 'DROP_TABLE',
185
+ * table: sqlite_schema,
186
+ * if_not_exists: boolean,
187
+ * }} sqlite_DROP_TABLE
188
+ *
189
+ * @typedef {{
190
+ * type: 'DROP_INDEX',
191
+ * name: sqlite_schema,
192
+ * if_not_exists: boolean,
193
+ * }} sqlite_DROP_INDEX
194
+ *
195
+ * @typedef {{
196
+ * type: 'ALTER_RENAME_TO',
197
+ * table: sqlite_schema,
198
+ * to: string,
199
+ * }} sqlite_ALTER_RENAME_TO
200
+ *
201
+ * @typedef {{
202
+ * type: 'ALTER_RENAME_COLUMN',
203
+ * table: sqlite_schema,
204
+ * from: string,
205
+ * to: string,
206
+ * }} sqlite_ALTER_RENAME_COLUMN
207
+ *
208
+ * @typedef {{
209
+ * type: 'ALTER_ADD',
210
+ * table: sqlite_schema,
211
+ * column: sqlite_column_def,
212
+ * }} sqlite_ALTER_ADD
213
+ *
214
+ * @typedef {{
215
+ * type: 'ALTER_DROP',
216
+ * table: sqlite_schema,
217
+ * column_name: string,
218
+ * }} sqlite_ALTER_DROP
219
+ *
220
+ * @typedef {sqlite_PRAGMA |
221
+ * sqlite_SAVEPOINT |
222
+ * sqlite_RELEASE |
223
+ * sqlite_SELECT |
224
+ * sqlite_CREATE_TABLE |
225
+ * sqlite_CREATE_INDEX |
226
+ * sqlite_VALUES |
227
+ * sqlite_INSERT |
228
+ * sqlite_DROP_TABLE |
229
+ * sqlite_DROP_INDEX |
230
+ * sqlite_ALTER_RENAME_TO |
231
+ * sqlite_ALTER_RENAME_COLUMN |
232
+ * sqlite_ALTER_ADD |
233
+ * sqlite_ALTER_DROP
234
+ * } sqlite_EXPRS
235
+ */
236
+ /**
237
+ * @param {string} sql
238
+ * @param {string} char
239
+ */
240
+ static splitQStrByChar(sql, char) {
241
+ const re = new RegExp(`((?=["'])(?:"[^"\\\\]*(?:\\\\[\\s\\S][^"\\\\]*)*"|'[^'\\\\]*(?:\\\\[\\s\\S][^'\\\\]*)*')|${char})`, 'g');
242
+ const out = /** @type {string[]} */[];
243
+ const acc = /** @type {string[]} */[];
244
+ /** @type {string[]} */
245
+ const res = sql.split(re);
246
+ for (const str of res) {
247
+ if (!str) continue;
248
+ acc.push(str);
249
+ if (str === char) {
250
+ out.push(acc.join(''));
251
+ acc.length = 0;
252
+ }
253
+ }
254
+ if (acc.length) out.push(acc.join(''));
255
+ return out;
256
+ }
257
+ /**
258
+ * @param {string} input
259
+ * @returns {sqlite_schema}
260
+ */
261
+ static sqliteSchema(input) {
262
+ const out = /** @type {string[]} */[];
263
+ // Регулярка объявлена вне regex функции, потому что на "\\" она багуется и не компилируется
264
+ const res = input.matchAll(/(?:(?=["'])(?:"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]*(?:\\[\s\S][^'\\]*)*')|\.|[^.]+)/ig);
265
+ for (const match of res) {
266
+ const s = match[0];
267
+ if (!s || s === '.') continue;
268
+ if (s[0] === "'" || s[0] === '"') {
269
+ out.push(s.slice(1, -1));
270
+ continue;
271
+ }
272
+ out.push(s);
273
+ }
274
+ if (!out.length) throw new Error(`Can't parse name (empty): ${input}`);
275
+ return {
276
+ scheme_parts: out.splice(0, out.length - 1),
277
+ name: out[out.length - 1]
278
+ };
279
+ }
280
+ /** @param {string | null | undefined} input */
281
+ static sqliteName(input) {
282
+ if (!input) throw new Error(`Can't parse name (empty): ${input}`);
283
+ if (input[0] === '"') return input.slice(1, -1);
284
+ return input;
285
+ }
286
+ /**
287
+ * @param {string} input
288
+ * @returns {sqlite_column[]}
289
+ */
290
+ static sqliteColumns(input) {
291
+ const out = /** @type {ReturnType<typeof SQLParser['sqliteColumns']>} */[];
292
+ const columns = SQLParser.splitQStrByChar(input, ',').map(str => str.trim().match(SQLParser.regex.column));
293
+ for (const column of columns) {
294
+ if (!column || !column.groups) throw new Error(`Can't parse column: ${input}`);
295
+ const sort = /** @type {string | null} */column.groups.sort?.toUpperCase() ?? null;
296
+ if (sort && sort !== 'ASC' && sort !== 'DESC') throw new Error(`Can't parse sort: ${input}`);
297
+ out.push({
298
+ name: SQLParser.sqliteName(column.groups.name),
299
+ as: column.groups.as ? SQLParser.sqliteName(column.groups.as) : null,
300
+ sort: (/** @type {null | 'ASC' | 'DESC'} */sort)
301
+ });
302
+ }
303
+ return out;
304
+ }
305
+ /**
306
+ * @param {RegExp} rgx
307
+ * @param {string} input
308
+ */
309
+ static matchAllGroups(rgx, input) {
310
+ /** @type {Record<string, string | undefined>} */
311
+ const out = {};
312
+ const matches = input.matchAll(rgx);
313
+ for (const match of matches) Object.assign(out, ...__WEBPACK_EXTERNAL_MODULE__foul11_awesome_5cd072e2_Object_entries__(match.groups ?? {}).map(([k, v]) => v === undefined ? {} : {
314
+ [k]: v
315
+ }));
316
+ return {
317
+ groups: out
318
+ };
319
+ }
320
+ /**
321
+ * @param {string} input
322
+ * @returns {sqlite_column_def[]}
323
+ */
324
+ static sqliteColumnsDef(input) {
325
+ const out = /** @type {ReturnType<typeof SQLParser['sqliteColumnsDef']>} */[];
326
+ const columns = SQLParser.splitQStrByChar(input, ',').map(str => str.trim().match(SQLParser.regex.column_def));
327
+ for (const column of columns) {
328
+ if (!column || !column.groups) throw new Error(`Can't parse column: ${input}`);
329
+ if (!column.groups.name) {
330
+ // if not name then it's table constraint
331
+ if (!column.groups.table_constraint) throw new Error(`Can't parse table constraint or name: ${input}`);
332
+ const table_constraint = column.groups.table_constraint.trim().match(SQLParser.regex.table_constraint);
333
+ if (!table_constraint || !table_constraint.groups) throw new Error(`Can't parse table constraint: ${input}`);
334
+ const inline_columns = /** @type {sqlite_column[]} */[];
335
+ const props = /** @type {{ primary?: boolean, unique?: boolean, auto_increment?: boolean }} */{};
336
+ switch (true) {
337
+ case !!table_constraint.groups.primary_key_expr:
338
+ inline_columns.push(...SQLParser.sqliteColumns(table_constraint.groups.primary_key_expr));
339
+ if (table_constraint.groups.auto_increment) props.auto_increment = true;
340
+ props.primary = true;
341
+ break;
342
+ case !!table_constraint.groups.unique_expr:
343
+ inline_columns.push(...SQLParser.sqliteColumns(table_constraint.groups.unique_expr));
344
+ props.unique = true;
345
+ break;
346
+ default:
347
+ throw new Error(`Can't parse table constraint type: ${input}`);
348
+ }
349
+ const inline_names = new Set(inline_columns.map(c => c.name));
350
+ for (const inline_column of out.filter(c => inline_names.has(c.name))) {
351
+ for (const prop of __WEBPACK_EXTERNAL_MODULE__foul11_awesome_5cd072e2_Object_keys__(props)) {
352
+ if (props[prop] === undefined) continue;
353
+ inline_column[prop] = props[prop];
354
+ }
355
+ }
356
+ continue;
357
+ }
358
+ const constraints = /** @type {sqlite_constraint} */{
359
+ auto_increment: false,
360
+ not_null: false,
361
+ primary: false,
362
+ unique: false,
363
+ default: null,
364
+ references: null
365
+ };
366
+ if (column.groups.constraint) {
367
+ const column_constraint = SQLParser.matchAllGroups(SQLParser.regex.constraint, column.groups.constraint.trim());
368
+ // .match(SQLParser.regex.constraint);
369
+ if (!column_constraint || !column_constraint.groups) throw new Error(`Can't parse column constraint: ${column.groups.constraint}`);
370
+ if (column_constraint.groups.auto_increment) constraints.auto_increment = true;
371
+ if (column_constraint.groups.not_null) constraints.not_null = true;
372
+ if (column_constraint.groups.primary_key) constraints.primary = true;
373
+ if (column_constraint.groups.unique) constraints.unique = true;
374
+ if (column_constraint.groups.default) {
375
+ const g = column_constraint.groups;
376
+ if (g.default_expr) {
377
+ constraints.default = g.default_expr;
378
+ } else {
379
+ constraints.default = SQLParser.sqliteValue(g.default_number ?? g.default_literal ?? g.default_const);
380
+ }
381
+ }
382
+ if (column_constraint.groups.references) constraints.references = {
383
+ table: SQLParser.sqliteSchema(column_constraint.groups.references_table ?? ''),
384
+ columns: SQLParser.splitQStrByChar(column_constraint.groups.columns_def_expr ?? '', ',').map(v => SQLParser.sqliteName(v.trim())),
385
+ constraints: column_constraint.groups.references_constraint ?? null
386
+ };
387
+ }
388
+ /** @type {string | null} */
389
+ const type = column.groups.type?.toUpperCase() ?? null;
390
+ if (!type) throw new Error(`Can't parse column type: ${input}`);
391
+ out.push({
392
+ name: SQLParser.sqliteName(column.groups.name),
393
+ type: (/** @type {sqlite_types} */type),
394
+ ...constraints
395
+ });
396
+ }
397
+ return out;
398
+ }
399
+ /**
400
+ * @param {string | null | undefined} input
401
+ * @returns {sqlite_value}
402
+ */
403
+ static sqliteValue(input) {
404
+ input = SQLParser.strOrNull(input);
405
+ if (input === null) return null;
406
+ const num = parseFloat(input);
407
+ if (!isNaN(num)) return num;
408
+ return input;
409
+ }
410
+ /** @param {string | null | undefined} str */
411
+ static strOrNull(str) {
412
+ if (str === null || str === undefined) return null;
413
+ if (str[0] === "'") return str.slice(1, -1);
414
+ return str;
415
+ }
416
+ /** @param {string | null | undefined} str */
417
+ static intOrNull(str) {
418
+ if (str === null || str === undefined) return null;
419
+ return parseInt(str);
420
+ }
421
+ static regex = {
422
+ PRAGMA: __WEBPACK_EXTERNAL_MODULE__foul11_awesome_5cd072e2_regex__`
423
+ ^(?:
424
+ PRAGMA
425
+ (?: \s+ (?<name> \S + ))?
426
+ (?: \s* = \s* (?<value> [\s\S]+ ))?
427
+ ;?)$
428
+ ``i`,
429
+ SAVEPOINT: __WEBPACK_EXTERNAL_MODULE__foul11_awesome_5cd072e2_regex__`
430
+ ^(?:
431
+ SAVEPOINT
432
+ (?: \s+ (?<name> \S+ ))?
433
+ ;?)$
434
+ ``i`,
435
+ RELEASE: __WEBPACK_EXTERNAL_MODULE__foul11_awesome_5cd072e2_regex__`
436
+ ^(?:
437
+ RELEASE
438
+ (?: \s+ (?<name> \S+ ))?
439
+ ;?)$
440
+ ``i`,
441
+ SELECT: __WEBPACK_EXTERNAL_MODULE__foul11_awesome_5cd072e2_regex__`
442
+ ^(?:
443
+ SELECT
444
+ (?: \s+ (?<distinct> DISTINCT ))?
445
+ (?: \s+ (?<columns> [\s\S]+ ))
446
+ (?: \s+ (?<from> FROM \s+ (?<table _expr> [\s\S]+?) ))
447
+ (?: \s+ (?<where> WHERE \s+ (?<where _expr> [\s\S]+?) ))?
448
+ (?: \s+ (?<group_by> GROUP \s+ BY \s+ (?<group _expr> [\s\S]+?) ))?
449
+ (?: \s+ (?<order_by> ORDER \s+ BY \s+ (?<order _expr> [\s\S]+?) ))?
450
+ (?: \s+ (?<limit> LIMIT \s+ (?<limit _expr> [\s\S]+?) ))?
451
+ (?: \s+ (?<offset> OFFSET \s+ (?<offset_expr> [\s\S]+?) ))?
452
+ ;?)$
453
+ ``i`,
454
+ CREATE_TABLE: __WEBPACK_EXTERNAL_MODULE__foul11_awesome_5cd072e2_regex__`
455
+ ^(?:
456
+ CREATE \s+ TABLE
457
+ (?: \s+ (?<if_not_exists> IF \s+ NOT \s+ EXISTS ))?
458
+ (?: \s+ (?<name> (?<name_expr> [\s\S]+?) ))
459
+ (?: \s+ (?<columns_def> \( (?<columns_def_expr> [\s\S]+?) \) ))
460
+ ;?)$
461
+ ``i`,
462
+ CREATE_INDEX: __WEBPACK_EXTERNAL_MODULE__foul11_awesome_5cd072e2_regex__`
463
+ ^(?:
464
+ CREATE
465
+ (?: \s+ (?<unique> UNIQUE ))?
466
+ (?: \s+ (?: INDEX ))
467
+ (?: \s+ (?<if_not_exists> IF \s+ NOT \s+ EXISTS ))?
468
+ (?: \s+ (?<name> (?<name_expr> [\s\S]+?) ))
469
+ (?: \s+ (?: ON ))
470
+ (?: \s+ (?<table> (?<table_expr> [\s\S]+?) ))
471
+ (?: \s+ (?<columns> \( (?<columns_expr> [\s\S]+?) \) ))
472
+ ;?)$
473
+ ``i`,
474
+ VALUES: __WEBPACK_EXTERNAL_MODULE__foul11_awesome_5cd072e2_regex__`
475
+ ^(?:
476
+ VALUES
477
+ (?: \s+ \( (?<values> [\s\S]+?) \) )
478
+ ;?)$
479
+ ``i`,
480
+ INSERT: __WEBPACK_EXTERNAL_MODULE__foul11_awesome_5cd072e2_regex__`
481
+ ^(?:
482
+ INSERT \s+ INTO
483
+ (?: \s+ (?<table> (?<table_expr> [\s\S]+?) ))
484
+ (?: \s+ (?<columns> \( (?<columns_expr> [\s\S]+?) \) ))
485
+ (?:
486
+ (?: \s+ (?<values_expr> VALUES \s+ \( (?: [\s\S]+?) \) )) |
487
+ (?: \s+ (?<select_expr> SELECT \s+ (?: [\s\S]+?) ))
488
+ )
489
+ ;?)$
490
+ ``i`,
491
+ DROP: __WEBPACK_EXTERNAL_MODULE__foul11_awesome_5cd072e2_regex__`
492
+ ^(?:
493
+ DROP
494
+ (?:
495
+ (?: \s+ TABLE) |
496
+ (?: \s+ INDEX)
497
+ )
498
+ (?: \s+ (?<if_not_exists> IF \s+ NOT \s+ EXISTS ))?
499
+ (?: \s+ (?<name> [\s\S]+? ))
500
+ ;?)$
501
+ ``i`,
502
+ ALTER_TABLE: __WEBPACK_EXTERNAL_MODULE__foul11_awesome_5cd072e2_regex__`
503
+ ^(?:
504
+ ALTER \s+ TABLE
505
+ (?: \s+ (?<table> (?<table_expr> [\s\S]+?) ))
506
+ (?:
507
+ (?:
508
+ (?: \s+ RENAME \s+ TO \s+ (?<rename_to > [\s\S]+? )) |
509
+ (?: \s+ RENAME \s+ (?: COLUMN \s+ )?
510
+ (?<rename_col_from> [\s\S]+? )
511
+ (?: \s+ TO \s+ )
512
+ (?<rename_col_to> [\s\S]+? )
513
+ ) |
514
+ (?: \s+ DROP \s+ (?: COLUMN \s+ )? (?<drop_col> [\s\S]+? ))
515
+ ) |
516
+ (?: \s+ ADD \s+ (?: COLUMN \s+ )? (?<add_col> [\s\S]+? ))
517
+ )
518
+ ;?)$
519
+ ``i`,
520
+ column: __WEBPACK_EXTERNAL_MODULE__foul11_awesome_5cd072e2_regex__`
521
+ ^(?:
522
+ (?: (?<name> [\s\S]+? ))
523
+ (?:
524
+ (?: \s+ (?<as> AS \s+ (?<as_expr> [\s\S]+? ) ))? |
525
+ (?: \s+ (?<sort> (?<sort_expr> ASC | DESC) ))?
526
+ )
527
+ ,?)$
528
+ ``i`,
529
+ column_def: __WEBPACK_EXTERNAL_MODULE__foul11_awesome_5cd072e2_regex__`
530
+ ^(?:
531
+ (?:
532
+ (?<table_constraint> (?: PRIMARY | UNIQUE | CHECK | FOREIGN ) [\s\S]+ )
533
+ ) |
534
+ (?: (?<name> [\s\S]+? ))
535
+ (?: \s+ (?<type> (?: TEXT | INTEGER | REAL | BLOB | DATETIME ) ))?
536
+ (?: \s+ (?<constraint> [\s\S]+? ))?
537
+ ,?)$
538
+ ``i`,
539
+ constraint: __WEBPACK_EXTERNAL_MODULE__foul11_awesome_5cd072e2_regex__`
540
+ (?:
541
+ // (?: \s* ) |
542
+ (?:
543
+ (?<primary_key> PRIMARY \s+ KEY
544
+ (?: (?<primary_key_sort> ASC | DESC ))?
545
+ (?: \s+ (?<auto_increment> AUTOINCREMENT ))?
546
+ )
547
+ ) |
548
+ (?: (?<not_null> NOT \s+ NULL )) |
549
+ (?: (?<unique> UNIQUE )) |
550
+ (?: (?<default> DEFAULT \s+
551
+ (?:
552
+ (?<default_expr> \( [\s\S]+ \) ) |
553
+ (?<default_number> [+-]? [\d]+ ) |
554
+ (?<default_literal> ['"] [\s\S]+ ['"] ) |
555
+ (?<default_const> TRUE | FALSE | NULL )
556
+ )
557
+ )) |
558
+ (?:
559
+ (?<references> REFERENCES \s+
560
+ (?<references_table> [\S]+)
561
+ (?: \s* (?<columns_def> \( (?<columns_def_expr> [\s\S]+?) \) ))?
562
+ (?: \s* (?<references_constraint> (?:
563
+ (?: \s*
564
+ ON \s+
565
+ (?: DELETE | UPDATE ) \s+
566
+ (?:
567
+ SET \s+ NULL |
568
+ SET \s+ DEFAULT |
569
+ CASCADE |
570
+ RESTRICT |
571
+ NO \s+ ACTION
572
+ )
573
+ ) |
574
+ (?: \s* MATCH \s+ [\S]+) |
575
+ (?: \s*
576
+ (?: NOT \s+ )?
577
+ DEFERRABLE
578
+ (?:
579
+ \s+ INITIALLY \s+ DEFERRED |
580
+ \s+ INITIALLY \s+ IMMEDIATE
581
+ )?
582
+ ))+
583
+ ))?
584
+ )
585
+ )
586
+ )
587
+ ``ig`,
588
+ table_constraint: __WEBPACK_EXTERNAL_MODULE__foul11_awesome_5cd072e2_regex__`
589
+ ^(?:
590
+ (?:
591
+ (?<primary_key> PRIMARY \s+ KEY
592
+ \(
593
+ (?: (?<primary_key_expr> [\s\S]+? ))
594
+ (?: \s+ (?<auto_increment> AUTOINCREMENT ))?
595
+ \)
596
+ )
597
+ ) |
598
+ (?: (?<unique> UNIQUE \s+ \((?<unique_expr> [\s\S]+?)\) ))
599
+ )$
600
+ ``i`
601
+ };
602
+ /** @param {string} sql */
603
+ static parse(sql) {
604
+ const out = /** @type {sqlite_EXPRS[]} */[];
605
+ const semi_split = SQLParser.splitQStrByChar(sql, ';');
606
+ for (const raw_str of semi_split) {
607
+ const str_expr = raw_str.trim();
608
+ switch (true) {
609
+ case /^PRAGMA/i.test(str_expr):
610
+ {
611
+ const parse = str_expr.match(SQLParser.regex.PRAGMA);
612
+ if (!parse || !parse.groups) throw new Error(`Can't parse: ${str_expr}`);
613
+ out.push({
614
+ type: 'PRAGMA',
615
+ name: SQLParser.sqliteSchema(parse.groups.name),
616
+ value: SQLParser.sqliteValue(parse.groups.value)
617
+ });
618
+ break;
619
+ }
620
+ case /^SAVEPOINT/i.test(str_expr):
621
+ {
622
+ const parse = str_expr.match(SQLParser.regex.SAVEPOINT);
623
+ if (!parse || !parse.groups) throw new Error(`Can't parse: ${str_expr}`);
624
+ out.push({
625
+ type: 'SAVEPOINT',
626
+ savepoint_name: SQLParser.strOrNull(parse.groups.name)
627
+ });
628
+ break;
629
+ }
630
+ case /^RELEASE/i.test(str_expr):
631
+ {
632
+ const parse = str_expr.match(SQLParser.regex.RELEASE);
633
+ if (!parse || !parse.groups) throw new Error(`Can't parse: ${str_expr}`);
634
+ out.push({
635
+ type: 'RELEASE',
636
+ savepoint_name: SQLParser.strOrNull(parse.groups.name)
637
+ });
638
+ break;
639
+ }
640
+ case /^SELECT/i.test(str_expr):
641
+ {
642
+ const parse = str_expr.match(SQLParser.regex.SELECT);
643
+ if (!parse || !parse.groups) throw new Error(`Can't parse: ${str_expr}`);
644
+ out.push({
645
+ type: 'SELECT',
646
+ distinct: !!parse.groups.distinct,
647
+ columns: SQLParser.sqliteColumns(parse.groups.columns),
648
+ from: SQLParser.splitQStrByChar(parse.groups.table_expr, ',').map(t => SQLParser.sqliteSchema(t)),
649
+ where: SQLParser.strOrNull(parse.groups.where_expr),
650
+ group_by: SQLParser.strOrNull(parse.groups.group_expr),
651
+ order_by: SQLParser.strOrNull(parse.groups.order_expr),
652
+ offset: SQLParser.intOrNull(parse.groups.offset_expr),
653
+ limit: SQLParser.intOrNull(parse.groups.limit_expr)
654
+ });
655
+ break;
656
+ }
657
+ case /^CREATE TABLE/i.test(str_expr):
658
+ {
659
+ const parse = str_expr.match(SQLParser.regex.CREATE_TABLE);
660
+ if (!parse || !parse.groups) throw new Error(`Can't parse: ${str_expr}`);
661
+ out.push({
662
+ type: 'CREATE_TABLE',
663
+ if_not_exists: !!parse.groups.if_not_exists,
664
+ table: SQLParser.sqliteSchema(parse.groups.name_expr),
665
+ columns: SQLParser.sqliteColumnsDef(parse.groups.columns_def_expr)
666
+ });
667
+ break;
668
+ }
669
+ case /^CREATE/i.test(str_expr):
670
+ {
671
+ // if not CREATE TABLE then CREATE INDEX
672
+ const parse = str_expr.match(SQLParser.regex.CREATE_INDEX);
673
+ if (!parse || !parse.groups) throw new Error(`Can't parse: ${str_expr}`);
674
+ out.push({
675
+ type: 'CREATE_INDEX',
676
+ name: SQLParser.sqliteSchema(parse.groups.name_expr),
677
+ table_name: SQLParser.sqliteName(parse.groups.table_expr),
678
+ if_not_exists: !!parse.groups.if_not_exists,
679
+ unique: !!parse.groups.unique,
680
+ columns: SQLParser.sqliteColumns(parse.groups.columns_expr)
681
+ });
682
+ break;
683
+ }
684
+ case /^INSERT/i.test(str_expr):
685
+ {
686
+ const parse = str_expr.match(SQLParser.regex.INSERT);
687
+ if (!parse || !parse.groups) throw new Error(`Can't parse: ${str_expr}`);
688
+ const expr = SQLParser.parse(`${parse.groups.values_expr || parse.groups.select_expr};`)[0];
689
+ if (!expr || expr.type !== 'SELECT' && expr.type !== 'VALUES') throw new Error(`Can't parse: ${str_expr}`);
690
+ out.push({
691
+ type: 'INSERT',
692
+ table: SQLParser.sqliteSchema(parse.groups.table_expr),
693
+ columns: SQLParser.sqliteColumns(parse.groups.columns_expr),
694
+ expr: expr
695
+ });
696
+ break;
697
+ }
698
+ case /^VALUES/i.test(str_expr):
699
+ {
700
+ const parse = str_expr.match(SQLParser.regex.VALUES);
701
+ if (!parse || !parse.groups) throw new Error(`Can't parse: ${str_expr}`);
702
+ const values = SQLParser.splitQStrByChar(parse.groups.values, ',').map(v => v[0] !== '"' ? parseFloat(v) : v.slice(1, -1));
703
+ out.push({
704
+ type: 'VALUES',
705
+ values
706
+ });
707
+ break;
708
+ }
709
+ case /^DROP TABLE/i.test(str_expr):
710
+ {
711
+ const parse = str_expr.match(SQLParser.regex.DROP);
712
+ if (!parse || !parse.groups) throw new Error(`Can't parse: ${str_expr}`);
713
+ out.push({
714
+ type: 'DROP_TABLE',
715
+ if_not_exists: !!parse.groups.if_not_exists,
716
+ table: SQLParser.sqliteSchema(parse.groups.name)
717
+ });
718
+ break;
719
+ }
720
+ case /^DROP INDEX/i.test(str_expr):
721
+ {
722
+ const parse = str_expr.match(SQLParser.regex.DROP);
723
+ if (!parse || !parse.groups) throw new Error(`Can't parse: ${str_expr}`);
724
+ out.push({
725
+ type: 'DROP_INDEX',
726
+ if_not_exists: !!parse.groups.if_not_exists,
727
+ name: SQLParser.sqliteSchema(parse.groups.name)
728
+ });
729
+ break;
730
+ }
731
+ case /^ALTER TABLE/i.test(str_expr):
732
+ {
733
+ const parse = str_expr.match(SQLParser.regex.ALTER_TABLE);
734
+ if (!parse || !parse.groups) throw new Error(`Can't parse: ${str_expr}`);
735
+ const table = SQLParser.sqliteSchema(parse.groups.table_expr);
736
+ switch (true) {
737
+ case !!parse.groups.rename_to:
738
+ out.push({
739
+ type: 'ALTER_RENAME_TO',
740
+ table,
741
+ to: SQLParser.sqliteName(parse.groups.rename_to)
742
+ });
743
+ break;
744
+ case !!parse.groups.rename_col:
745
+ out.push({
746
+ type: 'ALTER_RENAME_COLUMN',
747
+ table,
748
+ from: SQLParser.sqliteName(parse.groups.rename_col_from),
749
+ to: SQLParser.sqliteName(parse.groups.rename_col_to)
750
+ });
751
+ break;
752
+ case !!parse.groups.add_col:
753
+ {
754
+ const column = SQLParser.sqliteColumnsDef(parse.groups.add_col)[0];
755
+ if (!column) throw new Error(`Can't parse: ${str_expr}`);
756
+ out.push({
757
+ type: 'ALTER_ADD',
758
+ table,
759
+ column: column
760
+ });
761
+ break;
762
+ }
763
+ case !!parse.groups.drop_col:
764
+ out.push({
765
+ type: 'ALTER_DROP',
766
+ table,
767
+ column_name: SQLParser.sqliteName(parse.groups.drop_col)
768
+ });
769
+ break;
770
+ default:
771
+ throw new Error(`Can't parse: ${str_expr}`);
772
+ }
773
+ break;
774
+ }
775
+ case str_expr.trim() === '':
776
+ break;
777
+ default:
778
+ throw new Error(`Can't parse (default): ${str_expr}`);
779
+ }
780
+ }
781
+ return out;
782
+ }
783
+ }
784
+ class SQLiteDebugger {
785
+ /*
786
+ TODO:
787
+ Класс который будет разбивать операции с sqlv на отдельные части,
788
+ угадывать что было сделано RENAME/ADD COLUMN/REMOVE COLUMN/EDIT COLUMN и тд,
789
+ и красивенько выводить в stdout, показывать успешные операции, выполнять транзакции
790
+ */
791
+ // /** @param {import('better-sqlite3').Database} db */
792
+ /** @param {any} db */
793
+ constructor(db) {
794
+ this.db = db;
795
+ }
796
+ /**
797
+ * @param {string} table
798
+ * @returns {{
799
+ * cid: number,
800
+ * name: string,
801
+ * type: 'INTEGER' | 'REAL' | 'TEXT' | 'BLOB' | 'NUMERIC',
802
+ * notnull: boolean,
803
+ * dflt_value: string | null,
804
+ * pk: boolean,
805
+ * }[]}
806
+ */
807
+ tableInfo(table) {
808
+ return this.db.prepare(`SELECT * FROM pragma_table_info('${table}')`).all().map((/** @type {*} */r) => {
809
+ return {
810
+ ...r,
811
+ notnull: !!r.notnull,
812
+ pk: !!r.pk
813
+ };
814
+ });
815
+ }
816
+ /**
817
+ * @returns {{
818
+ * type: 'index' | 'table',
819
+ * name: string,
820
+ * tbl_name: string,
821
+ * rootpage: number,
822
+ * sql: string,
823
+ * }[]}
824
+ */
825
+ masterTable() {
826
+ return /** @type {*} */this.db.prepare(`SELECT * FROM sqlite_master`).all().filter((/** @type {*} */r) => r.name != 'sqlite_sequence');
827
+ }
828
+ /**
829
+ * @typedef {number | {
830
+ * from: number,
831
+ * to: number,
832
+ * }} sqlited_index
833
+ *
834
+ * @typedef {{
835
+ * type: 'LINK_SQLITE',
836
+ * index: number,
837
+ * link: sqlite_EXPRS,
838
+ * linked: Map<sqlited_link_logic_sub_type, Set<sqlited_link_logic | sqlited_link_sqlite>>,
839
+ * }} sqlited_link_sqlite
840
+ *
841
+ * @typedef {'SAVE/RELEASE' | 'LINK_TABLE'} sqlited_link_logic_sub_type
842
+ *
843
+ * @typedef {{
844
+ * type: 'LINK',
845
+ * sub_type: sqlited_link_logic_sub_type,
846
+ * index: sqlited_index,
847
+ * child: (sqlited_link_logic | sqlited_link_sqlite)[],
848
+ * }} sqlited_link_logic
849
+ */
850
+ /*
851
+ TODO:
852
+ t1 - новая
853
+ t2 - старая
854
+ [ ->] - необязательная операция
855
+ {number [/ link]} - номер/ссылка
856
+ {...S} - Миграция схемы
857
+ {...D} - Миграция данных
858
+
859
+ * {1 S} [Добавление столбца (t2) ->] Создание (t1) -> перенос данных (t2 -> t1) -> удаление (t2) -> переименование (t1)
860
+ - Переименование (t2) [При условии, что столбцы те же самые]
861
+ - Добавление/Удаление столбца (t2) [При условии, что столбцы создаваемых таблиц отличаются от исходных]
862
+ - Частичный перенос (t2) [При условии, что столбцы такие же, но выбраны для переноса не все]
863
+ - Изменения типа данных (t2) [При условии, что у любого столба отличается тип данных от исходного]
864
+ - Изменения дефолтного значений (t2) [При условии, что у любого столба отличается дефолтное значение от исходного]
865
+ - Изменение аттрибутов uniq, ...(t2) [При условии, что у любого столба отличается аттрибут uniq, ... от исходного]
866
+
867
+ * {2 S / before 1} Создание индексов (t2)
868
+ - Пересоздание индексов (t1) [При условии, что индексы такие же в двух таблицах до и после]
869
+ - Добавление/Удаление индексов (t2) [При условии, что индексы создаваемых таблиц отличаются от исходных, а так же может значит ошибку в случае если не будет хватать индекса]
870
+
871
+ * {3 D} Добавление данных (t2)
872
+ - Просто вставка данных в таблицу (t2)
873
+
874
+ * {4 D} Удаление данных (t2)
875
+ - Просто удаление данных из таблицы (t2)
876
+ */
877
+ /**
878
+ * @param {sqlited_index?} i1
879
+ * @param {sqlited_index?} i2
880
+ */
881
+ static sql_idx_min(i1, i2) {
882
+ if (i1 === null && i2 === null) return null;
883
+ if (i1 !== null && typeof i1 == 'object') i1 = Math.min(i1.from, i1.to);
884
+ if (i2 !== null && typeof i2 == 'object') i2 = Math.min(i2.from, i2.to);
885
+ if (i1 === null) return i2;
886
+ if (i2 === null) return i1;
887
+ return Math.min(i1, i2);
888
+ }
889
+ /**
890
+ * @param {sqlited_index?} i1
891
+ * @param {sqlited_index?} i2
892
+ */
893
+ static sql_idx_max(i1, i2) {
894
+ if (i1 === null && i2 === null) return null;
895
+ if (i1 !== null && typeof i1 == 'object') i1 = Math.max(i1.from, i1.to);
896
+ if (i2 !== null && typeof i2 == 'object') i2 = Math.max(i2.from, i2.to);
897
+ if (i1 === null) return i2;
898
+ if (i2 === null) return i1;
899
+ return Math.max(i1, i2);
900
+ }
901
+ /**
902
+ * @param {sqlited_index?} i1
903
+ * @param {sqlited_index?} i2
904
+ */
905
+ static sql_idx_outRange(i1, i2) {
906
+ const i1min = SQLiteDebugger.sql_idx_min(i1, null);
907
+ const i1max = SQLiteDebugger.sql_idx_max(i1, null);
908
+ const i2min = SQLiteDebugger.sql_idx_min(i2, null);
909
+ const i2max = SQLiteDebugger.sql_idx_max(i2, null);
910
+ if (i1min === null || i1max === null || i2min === null || i2max === null) return null;
911
+ return i1min < i2min && i1max > i2max;
912
+ }
913
+ /**
914
+ * @param {sqlited_index?} i1
915
+ * @param {sqlited_index?} i2
916
+ */
917
+ static sql_idx_inRange(i1, i2) {
918
+ const i1min = SQLiteDebugger.sql_idx_min(i1, null);
919
+ const i1max = SQLiteDebugger.sql_idx_max(i1, null);
920
+ const i2min = SQLiteDebugger.sql_idx_min(i2, null);
921
+ const i2max = SQLiteDebugger.sql_idx_max(i2, null);
922
+ if (i1min === null || i1max === null || i2min === null || i2max === null) return null;
923
+ return i1min >= i2min && i1min <= i2max && i1max <= i2max && i1max >= i2min;
924
+ }
925
+ /**
926
+ * @param {sqlited_index?} i1
927
+ * @param {sqlited_index?} i2
928
+ */
929
+ static sql_idx_invalidRange(i1, i2) {
930
+ const outRange = SQLiteDebugger.sql_idx_outRange(i1, i2);
931
+ const inRange = SQLiteDebugger.sql_idx_inRange(i1, i2);
932
+ return !outRange && !inRange;
933
+ }
934
+ /**
935
+ * @param {sqlited_link_sqlite[]} links
936
+ * @param {sqlited_link_sqlite} link
937
+ * @param {sqlited_link_logic_sub_type} sub_type
938
+ * @param {(link: sqlited_link_sqlite, input: sqlited_link_sqlite) => boolean} predicate
939
+ * @returns {sqlited_link_logic[]}
940
+ */
941
+ link_for_predicate(links, link, sub_type, predicate) {
942
+ if (!link.linked.has(sub_type)) link.linked.set(sub_type, new Set([link]));
943
+ /** @type {sqlited_link_sqlite[]} */
944
+ const out = [link];
945
+ const link_linked = link.linked.get(sub_type);
946
+ if (!link_linked) throw new Error('link_linked is null');
947
+ for (const l of links) {
948
+ if (!l.linked.has(sub_type)) l.linked.set(sub_type, new Set([l]));
949
+ const l_linked = l.linked.get(sub_type);
950
+ if (!l_linked) throw new Error('l_linked is undefined');
951
+ if (link_linked.has(l)) continue;
952
+ if (predicate(link, l)) {
953
+ link_linked.add(l);
954
+ l_linked.add(link);
955
+ out.push(l);
956
+ }
957
+ }
958
+ if (!out.length) return [];
959
+ const i_min = out.reduce((prev, l) => SQLiteDebugger.sql_idx_min(prev, l.index), /** @type {number?} */null);
960
+ const i_max = out.reduce((prev, l) => SQLiteDebugger.sql_idx_max(prev, l.index), /** @type {number?} */null);
961
+ if (i_min === null || i_max === null) throw new Error('Index is null');
962
+ return [{
963
+ type: 'LINK',
964
+ sub_type,
965
+ child: out,
966
+ index: {
967
+ from: i_min,
968
+ to: i_max
969
+ }
970
+ }];
971
+ }
972
+ /** @param {string} sql */
973
+ Heuristics_DBBrowserForSQLite(sql) {
974
+ /** @type {sqlited_link_sqlite[]} */
975
+ const parsed = SQLParser.parse(sql).map((e, i) => {
976
+ return {
977
+ type: 'LINK_SQLITE',
978
+ index: i,
979
+ link: e,
980
+ linked: new Map()
981
+ };
982
+ });
983
+ /** @type {sqlited_link_logic[]} */
984
+ const logics = [];
985
+ for (const link of parsed) {
986
+ switch (link.link.type) {
987
+ case 'SAVEPOINT':
988
+ case 'RELEASE':
989
+ logics.push(...this.link_for_predicate(parsed, link, 'SAVE/RELEASE', (stmt_link, l) => {
990
+ if ('savepoint_name' in stmt_link.link && 'savepoint_name' in l.link) return stmt_link.link.savepoint_name === l.link.savepoint_name;
991
+ return false;
992
+ }));
993
+ break;
994
+ case 'SELECT':
995
+ case 'CREATE_TABLE':
996
+ case 'INSERT':
997
+ case 'DROP_TABLE':
998
+ case 'ALTER_RENAME_TO':
999
+ case 'ALTER_RENAME_COLUMN':
1000
+ case 'ALTER_ADD':
1001
+ case 'ALTER_DROP':
1002
+ {
1003
+ let table = null;
1004
+ if ('table' in link.link) {
1005
+ table = new Set(link.link.table.name);
1006
+ } else if ('from' in link.link) {
1007
+ table = new Set(link.link.from.map(t => t.name));
1008
+ } else {
1009
+ throw new Error('table is null');
1010
+ }
1011
+ logics.push(...this.link_for_predicate(parsed, link, 'LINK_TABLE', (stmt_link, l) => {
1012
+ if ('table' in l.link) {
1013
+ return table.has(l.link.table.name);
1014
+ } else if ('from' in l.link) {
1015
+ return l.link.from.some(t => table.has(t.name));
1016
+ }
1017
+ return false;
1018
+ }));
1019
+ break;
1020
+ }
1021
+ }
1022
+ }
1023
+ console.log(logics);
1024
+ }
1025
+ /** @param {string | TemplateStringsArray} sql */
1026
+ execFrom_DBBrowser(sql) {
1027
+ if (Array.isArray(sql)) sql = sql[0];
1028
+ // this.db.exec(sql.toString());
1029
+ }
1030
+ }
1031
+ ;// ./src/utils.ts
1032
+
1033
+
1034
+ async function table_info(db, table) {
1035
+ return (await __WEBPACK_EXTERNAL_MODULE_kysely_sql__`SELECT * FROM pragma_table_info('${__WEBPACK_EXTERNAL_MODULE_kysely_sql__.raw(table)}')`.execute(db)).rows.map(r => ({
1036
+ ...r,
1037
+ notnull: !!r.notnull,
1038
+ pk: !!r.pk,
1039
+ type: r.type.toUpperCase()
1040
+ }));
1041
+ }
1042
+ async function master_table(db) {
1043
+ return (await db.selectFrom('sqlite_master').selectAll().execute()).filter(r => r.name != 'sqlite_sequence');
1044
+ }
1045
+ async function get_table_schema(db, table) {
1046
+ const master = (await master_table(db)).find(r => r.name == table);
1047
+ if (!master) return false;
1048
+ const schema = SQLParser.parse(master.sql)[0];
1049
+ if (schema?.type != 'CREATE_TABLE') return false;
1050
+ return schema;
1051
+ }
1052
+ ;// ./src/alter/pragma.ts
1053
+
1054
+ async function pragma_foreign_keys(db, enable) {
1055
+ return __WEBPACK_EXTERNAL_MODULE_kysely_sql__`PRAGMA foreign_keys = ${__WEBPACK_EXTERNAL_MODULE_kysely_sql__.lit(enable ? 1 : 0)}`.execute(db);
1056
+ }
1057
+ async function pragma_defer_foreign_keys(db, enable) {
1058
+ return __WEBPACK_EXTERNAL_MODULE_kysely_sql__`PRAGMA defer_foreign_keys = ${__WEBPACK_EXTERNAL_MODULE_kysely_sql__.lit(enable ? 1 : 0)}`.execute(db);
1059
+ }
1060
+ ;// ./src/alter/column_add.ts
1061
+
1062
+
1063
+
1064
+ /**
1065
+ * Alter column add after column, or first if null
1066
+ */
1067
+ async function alter_column_add(db, table, column_name, column_type, after, col, eb) {
1068
+ await pragma_foreign_keys(db, false);
1069
+ await db.transaction().execute(async trx => {
1070
+ const alter_table = tmpTableName(table);
1071
+ const schema = await get_table_schema(trx, table);
1072
+ if (!schema) throw new Error(`Table ${table} does not exist`);
1073
+ if (schema.columns.some(c => c.name == column_name)) return; // passthrough if column already exists
1074
+ const after_column_idx = schema.columns.findIndex(c => c.name == after);
1075
+ let columns_after = [];
1076
+ let columns_before = [];
1077
+ if (after_column_idx !== -1) {
1078
+ columns_after = schema.columns.slice(0, after_column_idx + 1);
1079
+ columns_before = schema.columns.slice(after_column_idx + 1);
1080
+ } else {
1081
+ columns_after = [];
1082
+ columns_before = schema.columns;
1083
+ }
1084
+ let builder = trx.schema.createTable(alter_table);
1085
+ builder = itAddColumn(builder, columns_after);
1086
+ builder = builder.addColumn(column_name, column_type, col);
1087
+ builder = itAddColumn(builder, columns_before);
1088
+ await builder.execute();
1089
+ await trx.insertInto(alter_table).columns([...columns_after.map(c => c.name), ...(eb ? [column_name] : []), ...columns_before.map(c => c.name)]).expression(() => trx.selectFrom(table).select([...columns_after.map(c => `${table}.${c.name}`), ...(eb ? [eb] : []), ...columns_before.map(c => `${table}.${c.name}`)])).executeTakeFirstOrThrow();
1090
+ await trx.schema.dropTable(table).execute();
1091
+ await trx.schema.alterTable(alter_table).renameTo(table).execute();
1092
+ });
1093
+ await pragma_foreign_keys(db, true);
1094
+ }
1095
+ ;// ./src/alter/column_drop.ts
1096
+
1097
+
1098
+
1099
+ /**
1100
+ * Alter column drop
1101
+ */
1102
+ async function alter_column_drop(db, table, column_name) {
1103
+ await pragma_foreign_keys(db, false);
1104
+ await db.transaction().execute(async trx => {
1105
+ const alter_table = tmpTableName(table);
1106
+ const schema = await get_table_schema(trx, table);
1107
+ if (!schema) throw new Error(`Table ${table} does not exist`);
1108
+ if (!schema.columns.find(c => c.name == column_name)?.type) return; // passthrough if column not found
1109
+ const columns = schema.columns.filter(c => c.name != column_name);
1110
+ let builder = trx.schema.createTable(alter_table);
1111
+ builder = itAddColumn(builder, columns);
1112
+ await builder.execute();
1113
+ await trx.insertInto(alter_table).columns(columns.map(c => c.name)).expression(eb => eb.selectFrom(table).select(columns.map(c => `${table}.${c.name}`))).executeTakeFirstOrThrow();
1114
+ await trx.schema.dropTable(table).execute();
1115
+ await trx.schema.alterTable(alter_table).renameTo(table).execute();
1116
+ });
1117
+ await pragma_foreign_keys(db, true);
1118
+ }
1119
+ ;// ./src/alter/column_rename.ts
1120
+
1121
+
1122
+
1123
+ /**
1124
+ * Alter column rename
1125
+ */
1126
+ async function alter_column_rename(db, table, column_name, new_column_name) {
1127
+ await pragma_foreign_keys(db, false);
1128
+ await db.transaction().execute(async trx => {
1129
+ const alter_table = tmpTableName(table);
1130
+ const schema = await get_table_schema(trx, table);
1131
+ if (!schema) throw new Error(`Table ${table} does not exist`);
1132
+ const columns = schema.columns;
1133
+ if (columns.some(c => c.name === new_column_name)) return; // passthrough if column already exists
1134
+ let builder = trx.schema.createTable(alter_table);
1135
+ builder = itAddColumn(builder, columns.map(c => ({
1136
+ ...c,
1137
+ name: c.name == column_name ? new_column_name : c.name
1138
+ })));
1139
+ await builder.execute();
1140
+ await trx.insertInto(alter_table).columns(columns.map(c => c.name == column_name ? new_column_name : c.name)).expression(eb => eb.selectFrom(table).select(columns.map(c => `${table}.${c.name}`))).executeTakeFirstOrThrow();
1141
+ await trx.schema.dropTable(table).execute();
1142
+ await trx.schema.alterTable(alter_table).renameTo(table).execute();
1143
+ });
1144
+ await pragma_foreign_keys(db, true);
1145
+ }
1146
+ ;// ./src/alter/column_update.ts
1147
+
1148
+
1149
+
1150
+
1151
+ /**
1152
+ * Alter column update settings (e.g. not null)
1153
+ */
1154
+ async function alter_column_update(db, table, column_name, column_type, col, eb = null) {
1155
+ await pragma_foreign_keys(db, false);
1156
+ await db.transaction().execute(async trx => {
1157
+ const alter_table = tmpTableName(table);
1158
+ const schema = await get_table_schema(trx, table);
1159
+ if (!schema) throw new Error(`Table ${table} does not exist`);
1160
+ let columns_after = null;
1161
+ let columns_before = null;
1162
+ const prev_column_idx = schema.columns.findIndex(c => c.name == column_name);
1163
+ if (prev_column_idx === -1) throw new Error(`Column ${column_name} does not exist`);
1164
+ columns_after = schema.columns.slice(0, prev_column_idx);
1165
+ columns_before = schema.columns.slice(prev_column_idx + 1);
1166
+ let builder = trx.schema.createTable(alter_table);
1167
+ builder = itAddColumn(builder, columns_after);
1168
+ builder = builder.addColumn(column_name, column_type, col);
1169
+ builder = itAddColumn(builder, columns_before);
1170
+ const create_schema = SQLParser.parse(builder.compile().sql)[0];
1171
+ if (create_schema?.type != 'CREATE_TABLE') throw new Error('Invalid builded SQL');
1172
+ const old_column = schema.columns.find(c => c.name == column_name);
1173
+ const new_column = create_schema.columns.find(c => c.name == column_name);
1174
+ if (!old_column || !new_column) throw new Error('new/old column not found');
1175
+ if (JSON.stringify(old_column) == JSON.stringify(new_column)) return; // passthrough if column settings are the same
1176
+ await builder.execute();
1177
+ await trx.insertInto(alter_table).columns([...columns_after.map(c => c.name), column_name, ...columns_before.map(c => c.name)]).expression(() => trx.selectFrom(table).select([...columns_after.map(c => `${table}.${c.name}`), ...(eb ? [eb] : [`${table}.${column_name}`]), ...columns_before.map(c => `${table}.${c.name}`)])).executeTakeFirstOrThrow();
1178
+ await trx.schema.dropTable(table).execute();
1179
+ await trx.schema.alterTable(alter_table).renameTo(table).execute();
1180
+ });
1181
+ await pragma_foreign_keys(db, true);
1182
+ }
1183
+ ;// ./src/alter/columns_order.ts
1184
+
1185
+
1186
+
1187
+ /**
1188
+ * Alter column order
1189
+ */
1190
+ async function alter_column_order(db, table, columns_name) {
1191
+ await pragma_foreign_keys(db, false);
1192
+ await db.transaction().execute(async trx => {
1193
+ const alter_table = tmpTableName(table);
1194
+ const schema = await get_table_schema(trx, table);
1195
+ if (!schema) throw new Error(`Table ${table} does not exist`);
1196
+ const schema_columns = new Map(schema.columns.map((c, i) => [c.name, i]));
1197
+ const new_columns = new Map(columns_name.map((c, i) => [c, i]));
1198
+ if (schema_columns.size != new_columns.size || schema_columns.size != columns_name.length) throw new Error(`Table ${table} column count mismatch`);
1199
+ if (![...schema_columns.entries()].some(([c_name, idx]) => new_columns.get(c_name) != idx)) return; // passthrough if column order is the same
1200
+ let builder = trx.schema.createTable(alter_table);
1201
+ builder = itAddColumn(builder, columns_name.map(c => schema.columns[schema_columns.get(c)]));
1202
+ await builder.execute();
1203
+ await trx.insertInto(alter_table).columns(columns_name).expression(eb => eb.selectFrom(table).select(columns_name.map(c => `${table}.${c}`))).executeTakeFirstOrThrow();
1204
+ await trx.schema.dropTable(table).execute();
1205
+ await trx.schema.alterTable(alter_table).renameTo(table).execute();
1206
+ });
1207
+ await pragma_foreign_keys(db, true);
1208
+ }
1209
+ ;// ./src/alter/index.ts
1210
+
1211
+
1212
+
1213
+
1214
+
1215
+
1216
+ ;// ./src/defaults.ts
1217
+
1218
+ const currTimeDefault = __WEBPACK_EXTERNAL_MODULE_kysely_sql__`(strftime('%FT%R:%fZ'))`;
1219
+ ;// ./src/Error.ts
1220
+ class ErrorModule extends Error {}
1221
+ class ErrorDB extends ErrorModule {}
1222
+ class ErrorMigration extends ErrorDB {}
1223
+ class ErrorSchema extends ErrorDB {}
1224
+ class ErrorQuery extends ErrorDB {}
1225
+ class ErrorUnknown extends ErrorDB {}
1226
+ class ErrorFlag extends ErrorUnknown {}
1227
+ class ErrorFlagPack extends ErrorFlag {}
1228
+ class ErrorFlagUnpack extends ErrorFlag {}
1229
+ class ErrorFlagInvalid extends ErrorFlag {}
1230
+ ;// ./src/indexer.ts
1231
+
1232
+ async function indexer(db, options) {
1233
+ const master = await master_table(db);
1234
+ const idx_exclude = new Map(options.exclude || []);
1235
+ const idx_include = new Map(options.include || []);
1236
+ const cleanupOthers = options.cleanupOthers || false;
1237
+ const tables = master.filter(r => r.type == 'table').filter(r => !options.include || idx_include.has(r.name)).map(r => r.name);
1238
+ const indexes = new Set(master.filter(r => r.type == 'index').map(r => r.name));
1239
+ const isExcluded = (table, column) => {
1240
+ const exclude = idx_exclude.get(table);
1241
+ if (exclude === true || exclude?.includes(column.name)) return true;
1242
+ return false;
1243
+ };
1244
+ const isIncluded = (table, column) => {
1245
+ const include = idx_include.get(table);
1246
+ if (options.include && !(include == true || include?.includes(column.name))) return false;
1247
+ return true;
1248
+ };
1249
+ for (const table of tables) {
1250
+ const info = await table_info(db, table);
1251
+ for (const column of info) {
1252
+ const idx_name = `autoIdx_${table}_${column.name}`;
1253
+ const skip = !isIncluded(table, column) || isExcluded(table, column) || column.pk;
1254
+ if (indexes.has(idx_name)) {
1255
+ if (cleanupOthers && skip) {
1256
+ await db.schema.dropIndex(idx_name).execute();
1257
+ }
1258
+ continue;
1259
+ }
1260
+ if (skip) continue;
1261
+ await db.schema.createIndex(idx_name).on(table).column(column.name).execute();
1262
+ }
1263
+ }
1264
+ }
1265
+ ;// ./src/ORM.ts
1266
+
1267
+ class ORM {
1268
+ static async getWhereId(id, table, column, db_builder) {
1269
+ const res = await db_builder.selectFrom(table).select(column).where('id', '=', id).executeTakeFirst();
1270
+ if (!res) throw new ErrorUnknown(`Failed to get column ${String(column)} from ${String(table)}`);
1271
+ return res[column];
1272
+ }
1273
+ static async setWhereId(id, table, value, db_builder) {
1274
+ const result = await db_builder.updateTable(table).set(value).where('id', '=', id).executeTakeFirst();
1275
+ return result.numUpdatedRows == 1n;
1276
+ }
1277
+ }
1278
+ ;// ./src/WebpackFileProvider.ts
1279
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
1280
+ function isFunction(obj) {
1281
+ return typeof obj === 'function';
1282
+ }
1283
+ function isObject(obj) {
1284
+ return typeof obj === 'object' && obj !== null;
1285
+ }
1286
+ function isMigration(obj) {
1287
+ return isObject(obj) && isFunction(obj.up);
1288
+ }
1289
+ class WebpackFileProvider {
1290
+ static db_migrations = new Map();
1291
+ #db_name;
1292
+ constructor(db_name) {
1293
+ this.#db_name = db_name;
1294
+ }
1295
+ getMigrations() {
1296
+ const migrations_list = {};
1297
+ const migrations = WebpackFileProvider.db_migrations.get(this.#db_name);
1298
+ if (!migrations) return Promise.resolve(migrations_list);
1299
+ for (const [file, exports] of Object.entries(migrations)) {
1300
+ if (isMigration(exports?.default)) {
1301
+ migrations_list[file] = exports.default;
1302
+ } else if (isMigration(exports)) {
1303
+ migrations_list[file] = exports;
1304
+ }
1305
+ }
1306
+ return Promise.resolve(migrations_list);
1307
+ }
1308
+ static setupDynamicImport(ctx, db_name) {
1309
+ for (const [fpath, exports] of ctx.keys().map(m => [m, ctx(m)])) {
1310
+ const [, db, file] = /^.+[\\/]([^\\/]+)[\\/](.+)\.[jt]s$/i.exec(fpath) ?? [];
1311
+ if (!db_name) db_name = db;
1312
+ if (!db_name || !file) continue;
1313
+ if (WebpackFileProvider.db_migrations.has(db_name)) {
1314
+ WebpackFileProvider.db_migrations.get(db_name)[file] = exports;
1315
+ } else {
1316
+ WebpackFileProvider.db_migrations.set(db_name, {
1317
+ [file]: exports
1318
+ });
1319
+ }
1320
+ }
1321
+ }
1322
+ }
1323
+ ;// external "@foul11/awesome-log"
1324
+
1325
+ ;// ./src/log/access_log.ts
1326
+ /* eslint-disable @stylistic/indent-binary-ops */
1327
+
1328
+ const logger_access_log = __WEBPACK_EXTERNAL_MODULE__foul11_awesome_log_ab373ec3_loggers__.add('access_log', {
1329
+ format: __WEBPACK_EXTERNAL_MODULE__foul11_awesome_log_ab373ec3_f_printf__(info => (`` + `${__WEBPACK_EXTERNAL_MODULE__foul11_awesome_log_ab373ec3_pretty_message__(info, {
1330
+ disable_empty: true
1331
+ })}` + `${info.runtime ? __WEBPACK_EXTERNAL_MODULE__foul11_awesome_log_ab373ec3_color__('ms', ` took ${__WEBPACK_EXTERNAL_MODULE__foul11_awesome_log_ab373ec3_pretty_ms__(info.runtime).padStart(11, ' ')}`) : ' '.repeat(6 + 11)}` + `${info.data ? ` (${__WEBPACK_EXTERNAL_MODULE__foul11_awesome_log_ab373ec3_color__('string', `'${info.data.action}'`)}, total: ${__WEBPACK_EXTERNAL_MODULE__foul11_awesome_log_ab373ec3_color__('ms', __WEBPACK_EXTERNAL_MODULE__foul11_awesome_log_ab373ec3_pretty_ms__(info.data.timings.total / 1e6).padStart(11, ' '))})` : ``}`).trim(), {
1332
+ meta: {
1333
+ label: 'access_log'
1334
+ },
1335
+ sanitize: ['data', 'runtime']
1336
+ })
1337
+ });
1338
+ /* harmony default export */ const access_log = (logger_access_log);
1339
+ ;// ./src/log/db.ts
1340
+ /* eslint-disable @stylistic/indent-binary-ops */
1341
+
1342
+ const logger_db = __WEBPACK_EXTERNAL_MODULE__foul11_awesome_log_ab373ec3_loggers__.add('db', {
1343
+ format: __WEBPACK_EXTERNAL_MODULE__foul11_awesome_log_ab373ec3_f_printf__(info => (`` + `${__WEBPACK_EXTERNAL_MODULE__foul11_awesome_log_ab373ec3_pretty_message__(info, {
1344
+ disable_empty: true
1345
+ })}` + `${info.query ? `\n${info.query}\n` : ``}` + `${info.runtime ? __WEBPACK_EXTERNAL_MODULE__foul11_awesome_log_ab373ec3_color__('string', `(runtime: ${__WEBPACK_EXTERNAL_MODULE__foul11_awesome_log_ab373ec3_color__('ms', __WEBPACK_EXTERNAL_MODULE__foul11_awesome_log_ab373ec3_pretty_ms__(info.runtime))})`) : ``}`).trim(), {
1346
+ meta: {
1347
+ label: 'db'
1348
+ },
1349
+ sanitize: ['query', 'runtime']
1350
+ })
1351
+ });
1352
+ /* harmony default export */ const db = (logger_db);
1353
+ ;// ./src/log/index.ts
1354
+
1355
+
1356
+ ;// external "kysely/migration"
1357
+
1358
+ ;// external "@foul11/sql-formatter"
1359
+
1360
+ ;// external "uuid"
1361
+
1362
+ ;// external "better-sqlite3"
1363
+
1364
+ ;// external "bindings"
1365
+
1366
+ ;// external "path"
1367
+
1368
+ ;// ./src/index.ts
1369
+
1370
+
1371
+
1372
+
1373
+
1374
+
1375
+
1376
+
1377
+
1378
+
1379
+
1380
+
1381
+
1382
+
1383
+
1384
+
1385
+
1386
+
1387
+ function create_sqlite(db_path) {
1388
+ const db = new __WEBPACK_EXTERNAL_MODULE_better_sqlite3_b46a9d6d_default__(db_path, {
1389
+ nativeBinding: __WEBPACK_EXTERNAL_MODULE__foul11_awesome_5cd072e2_isWebpack__() ? __WEBPACK_EXTERNAL_MODULE_bindings_default__({
1390
+ module_root: process.cwd(),
1391
+ bindings: 'better_sqlite3.node',
1392
+ try: [['module_root', 'dist', 'bindings'], ['module_root', 'bindings'], ['dist', 'bindings'], ['bindings']],
1393
+ path: true
1394
+ }) : null
1395
+ });
1396
+ db.function('new_uuid', () => {
1397
+ return __WEBPACK_EXTERNAL_MODULE_uuid_v4__();
1398
+ });
1399
+ return db;
1400
+ }
1401
+ function format_sqlite_no_throw(log_kysely_db, query) {
1402
+ const sql = typeof query === 'string' ? query : query.sql;
1403
+ try {
1404
+ return __WEBPACK_EXTERNAL_MODULE__foul11_sql_formatter_5d7ed540_format__(sql, {
1405
+ language: 'sqlite',
1406
+ tabWidth: 4,
1407
+ indentStyle: 'tabularRight',
1408
+ ...(typeof query !== 'string' && {
1409
+ params: query.parameters
1410
+ })
1411
+ });
1412
+ } catch (e) {
1413
+ log_kysely_db.error(e);
1414
+ return sql;
1415
+ }
1416
+ }
1417
+ function create_kysely(db, log_kysely_db) {
1418
+ const db_kysely = new __WEBPACK_EXTERNAL_MODULE_kysely_Kysely__({
1419
+ dialect: new __WEBPACK_EXTERNAL_MODULE_kysely_SqliteDialect__({
1420
+ database: db
1421
+ }),
1422
+ log: event => {
1423
+ db_kysely.transaction_logs.push(event.query.sql);
1424
+ if (log_kysely_db.isSillyEnabled()) {
1425
+ if (!db_kysely.in_migration) {
1426
+ log_kysely_db.silly(`\n${format_sqlite_no_throw(log_kysely_db, event.query)}\n`, {
1427
+ runtime: event.queryDurationMillis
1428
+ });
1429
+ } else {
1430
+ db_kysely.migration_log.push(format_sqlite_no_throw(log_kysely_db, event.query));
1431
+ }
1432
+ }
1433
+ if (event.level === 'error') {
1434
+ log_kysely_db.error(event.error, {
1435
+ query: db_kysely.transaction_logs.length ? db_kysely.transaction_logs.map(sql => format_sqlite_no_throw(log_kysely_db, sql)).join('\n') : format_sqlite_no_throw(log_kysely_db, event.query),
1436
+ runtime: event.queryDurationMillis
1437
+ });
1438
+ }
1439
+ if (/commit|begin|rollback/.test(event.query.sql)) {
1440
+ db_kysely.transaction_logs = [];
1441
+ }
1442
+ }
1443
+ });
1444
+ /**
1445
+ * Nested transaction hack
1446
+ * Catch execute method,
1447
+ * replace arg in func to proxy transaction,
1448
+ * method transaction() return this transaction
1449
+ */
1450
+ function proxy_transaction(trx) {
1451
+ return new Proxy(trx, {
1452
+ get(target, prop) {
1453
+ if (prop === 'transaction') return () => ({
1454
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
1455
+ execute: fn => fn.apply(target, [target])
1456
+ });
1457
+ if (typeof target[prop] == 'function') {
1458
+ return target[prop].bind(target);
1459
+ } else {
1460
+ return target[prop];
1461
+ }
1462
+ }
1463
+ });
1464
+ }
1465
+ const old_transaction = db_kysely.transaction;
1466
+ db_kysely.transaction = function (...trx_args) {
1467
+ const transaction = old_transaction.call(this, ...trx_args);
1468
+ return new Proxy(transaction, {
1469
+ get(target, prop) {
1470
+ if (prop === 'execute')
1471
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
1472
+ return fn => target.execute((trx, ...args) => fn.apply(target, [proxy_transaction(trx), ...args]));
1473
+ if (typeof target[prop] == 'function') {
1474
+ return target[prop].bind(target);
1475
+ } else {
1476
+ return target[prop];
1477
+ }
1478
+ }
1479
+ });
1480
+ };
1481
+ return db_kysely;
1482
+ }
1483
+ async function create_migrator(db_name, db, log_kysely_db) {
1484
+ db.in_migration = true;
1485
+ db.migration_log = [];
1486
+ db.transaction_logs = [];
1487
+ const migrator = new __WEBPACK_EXTERNAL_MODULE_kysely_migration_c9f7ddf4_Migrator__({
1488
+ db,
1489
+ provider: new WebpackFileProvider(db_name)
1490
+ });
1491
+ async function migrateToLatest() {
1492
+ const {
1493
+ error,
1494
+ results
1495
+ } = await migrator.migrateToLatest();
1496
+ for (const result of results ?? []) {
1497
+ if (result.status === 'Success') {
1498
+ log_kysely_db.info(`migration "${result.migrationName}" was executed successfully`);
1499
+ } else if (result.status === 'Error') {
1500
+ log_kysely_db.error(`failed to execute migration "${result.migrationName}"`);
1501
+ }
1502
+ }
1503
+ if (error) {
1504
+ if (!(error instanceof Error)) throw error;
1505
+ log_kysely_db.error('failed to migrate');
1506
+ log_kysely_db.error(error.stack);
1507
+ if (log_kysely_db.isDebugEnabled()) {
1508
+ log_kysely_db.debug(`\n${db.migration_log.join('\n-------------- NEXT MIGRATION SQL-request --------------\n')}\n`, {});
1509
+ // eslint-disable-next-line no-debugger
1510
+ debugger;
1511
+ }
1512
+ throw error;
1513
+ }
1514
+ }
1515
+ log_kysely_db.debug('starting migration to latest');
1516
+ await migrateToLatest();
1517
+ log_kysely_db.debug('migration to latest completed');
1518
+ db.in_migration = false;
1519
+ db.migration_log = [];
1520
+ return migrator;
1521
+ }
1522
+ async function create_db(db_path, log_kysely) {
1523
+ const db_name = __WEBPACK_EXTERNAL_MODULE_path_default__.parse(db_path).name;
1524
+ const db_sqlite = create_sqlite(db_path);
1525
+ const db_log = log_kysely.child({
1526
+ label5: db_name
1527
+ });
1528
+ const db = create_kysely(db_sqlite, db_log);
1529
+ const db_migrator = await create_migrator(db_name, db, db_log);
1530
+ return {
1531
+ db: db,
1532
+ db_migrator,
1533
+ db_sqlite,
1534
+ db_log
1535
+ };
1536
+ }
1537
+ const SqliteError = __WEBPACK_EXTERNAL_MODULE_better_sqlite3_b46a9d6d_default__.SqliteError;
1538
+ export { ErrorDB, ErrorFlag, ErrorFlagInvalid, ErrorFlagPack, ErrorFlagUnpack, ErrorMigration, ErrorModule, ErrorQuery, ErrorSchema, ErrorUnknown, ORM, SQLParser, SQLiteDebugger, SqliteError, WebpackFileProvider, alter_column_add, alter_column_drop, alter_column_order, alter_column_rename, alter_column_update, create_db, currTimeDefault, get_table_schema, indexer, access_log as logger_access_log, db as logger_db, master_table, pragma_defer_foreign_keys, pragma_foreign_keys, sqlv, table_info };
1539
+
1540
+ //# sourceMappingURL=index.mjs.map