sasat 0.22.8 → 0.22.9

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.mjs CHANGED
@@ -1,806 +1,3 @@
1
- import { a as SqlString, c as setConfig, i as SasatError, m as assignDeep, n as pick, r as unique, t as nonNullable } from "./util-BcMcffJ8.mjs";
2
- import { i as formatQuery, n as MySqlTransaction, r as DBClient, t as getDbClient } from "./getDbClient-CNcumqpO.mjs";
3
- import { createConnection } from "mysql2/promise";
4
- import * as SqlString$1 from "sqlstring";
5
- //#region src/db/connectors/mysql/client.ts
6
- var MysqlClient = class extends DBClient {
7
- async release() {}
8
- constructor(connectionOption, logger) {
9
- super(logger);
10
- this.connectionOption = connectionOption;
11
- }
12
- getConnection() {
13
- return createConnection({
14
- dateStrings: true,
15
- ...this.connectionOption
16
- });
17
- }
18
- async transaction() {
19
- const connection = await this.getConnection();
20
- await connection.beginTransaction();
21
- return new MySqlTransaction(connection);
22
- }
23
- async execSql(sql) {
24
- const connection = await this.getConnection();
25
- const r = await connection.query(sql);
26
- await connection.end();
27
- return r[0];
28
- }
29
- };
30
- //#endregion
31
- //#region src/runtime/dsl/query/sql/nodeToSql.ts
32
- function partitionBy(ids) {
33
- if (!ids || ids.length === 0) return "";
34
- return `PARTITION BY ${ids.map(Sql.identifier).join(",")} `;
35
- }
36
- function orderBy(sorts) {
37
- if (!sorts || sorts.length === 0) return "";
38
- return `ORDER BY ${sorts.map(Sql.sort).join(",")} `;
39
- }
40
- function windowValue(value) {
41
- if (value.type === "FOLLOWING" || value.type === "PRECEDING") return `${value.value} ${value.type}`;
42
- return value.type;
43
- }
44
- function window$1(window) {
45
- if (!window) return "";
46
- if (window.between) return `${window.type} BETWEEN ${windowValue(window.start)} AND ${window.end}`;
47
- return `${window.type} ${windowValue(window.value)}`;
48
- }
49
- function over(v) {
50
- if (!v) return "";
51
- return `OVER (${partitionBy(v.partitionBy)}${orderBy(v.orderBy)}${window$1(v.window)})`;
52
- }
53
- const Sql = {
54
- select: (expr) => {
55
- switch (expr.kind) {
56
- case 15: return expr.expr;
57
- case 0: return Sql.fieldInSelect(expr);
58
- case 13: return Sql.identifier(expr);
59
- case 1: return Sql.fn(expr);
60
- }
61
- },
62
- literal: (literal) => SqlString.escape(literal.value),
63
- fieldInCondition: (identifier) => SqlString.escapeId(identifier.table) + "." + SqlString.escapeId(identifier.name),
64
- fieldInSelect: (identifier) => {
65
- const alias = identifier.alias && identifier.name !== identifier.alias ? " AS " + SqlString.escapeId(identifier.alias) : "";
66
- return SqlString.escapeId(identifier.table) + "." + SqlString.escapeId(identifier.name) + alias;
67
- },
68
- identifier: (ident) => {
69
- return SqlString.escapeId(ident.identifier);
70
- },
71
- fn: (fn) => `${fn.fnName}(${fn.args.map(Sql.value).join(",")})${over(fn.over)}${fn.alias ? ` AS ${fn.alias}` : ""}`,
72
- value: (v) => {
73
- if (v.kind === 1) return Sql.fn(v);
74
- if (v.kind === 0) return Sql.fieldInCondition(v);
75
- if (v.kind === 13) return Sql.identifier(v);
76
- return Sql.literal(v);
77
- },
78
- between: (expr) => `${Sql.value(expr.left)} BETWEEN ${Sql.value(expr.begin)} AND ${Sql.value(expr.end)}`,
79
- contains: (expr) => {
80
- const operator = expr.isNot ? "NOT LIKE" : "LIKE";
81
- const val = (value, type) => {
82
- if (type === "contains") return "%" + value + "%";
83
- if (type === "start") return "%" + value;
84
- return value + "%";
85
- };
86
- return `${Sql.value(expr.left)} ${operator} ${SqlString.escape(val(expr.right, expr.type))}`;
87
- },
88
- in: (expr) => {
89
- if ("right" in expr) return `${Sql.value(expr.left)} ${expr.operator} (${expr.right.map(Sql.value).join(", ")})`;
90
- return `${Sql.value(expr.left)} ${expr.operator} (${Sql.queryOrRaw(expr.query)})`;
91
- },
92
- comparison: (expr) => `${Sql.value(expr.left)} ${expr.operator} ${Sql.value(expr.right)}`,
93
- compound: (expr) => `${Sql.booleanValue(expr.left)} ${expr.operator} ${Sql.booleanValue(expr.right)}`,
94
- isNull: (expr) => `${Sql.value(expr.expr)} ${expr.isNot ? "IS NOT NULL" : "IS NULL"}`,
95
- paren: (expr) => "(" + Sql.booleanValue(expr.expression) + ")",
96
- table: (table) => {
97
- if (!table.subquery) {
98
- if (table.alias === table.name) return SqlString.escapeId(table.name);
99
- return SqlString.escapeId(table.name) + " AS " + SqlString.escapeId(table.alias);
100
- }
101
- return `(${queryToSql(table.query)}) AS ${SqlString.escapeId(table.alias)}`;
102
- },
103
- join: (join) => `${join.type ? join.type + " " : ""}JOIN ${Sql.table(join.table)} ON ` + Sql.booleanValue(join.conditions),
104
- booleanValue: (expr) => {
105
- switch (expr.kind) {
106
- case 9: return Sql.between(expr);
107
- case 4: return Sql.compound(expr);
108
- case 5: return Sql.comparison(expr);
109
- case 10: return Sql.contains(expr);
110
- case 7: return Sql.paren(expr);
111
- case 8: return Sql.in(expr);
112
- case 6: return Sql.isNull(expr);
113
- case 14: return Sql.exists(expr);
114
- case 15: return expr.expr;
115
- }
116
- },
117
- exists: (expr) => {
118
- return `EXISTS (${Sql.queryOrRaw(expr.query)})`;
119
- },
120
- sort: (expr) => {
121
- const field = () => {
122
- switch (expr.field.kind) {
123
- case 0: return Sql.fieldInCondition(expr.field);
124
- case 13: return Sql.identifier(expr.field);
125
- default: return Sql.fn(expr.field);
126
- }
127
- };
128
- if (expr.direction) return `${field()} ${expr.direction === "DESC" ? "DESC" : "ASC"}`;
129
- return field();
130
- },
131
- sorts: (sorts) => sorts.map(Sql.sort).join(", "),
132
- queryOrRaw: (expr) => {
133
- if ("kind" in expr) return expr.expr;
134
- return queryToSql(expr);
135
- }
136
- };
137
- //#endregion
138
- //#region src/runtime/dsl/query/sql/queryToSql.ts
139
- const getJoin = (from) => {
140
- return from.joins.flatMap((join) => [join, ...getJoin(join.table)]);
141
- };
142
- const getLock = (lock) => {
143
- if (!lock) return "";
144
- if (lock === "FOR UPDATE") return " FOR UPDATE";
145
- return " FOR SHARE";
146
- };
147
- const queryToSql = (query) => {
148
- const select = query.select.map(Sql.select).join(", ");
149
- const join = [...getJoin(query.from), ...query.join ?? []].map(Sql.join).join(" ");
150
- const where = query.where ? " WHERE " + Sql.booleanValue(query.where) : "";
151
- const groupBy = query.groupBy ? " GROUP BY" + query.groupBy.cols.map(Sql.value).join(",") : "";
152
- const having = query.having ? "HAVING " + Sql.booleanValue(query.having) : "";
153
- const sort = query.sort && query.sort.length !== 0 ? " ORDER BY " + Sql.sorts(query.sort) : "";
154
- const limit = query.limit ? " LIMIT " + query.limit : "";
155
- const offset = query.offset ? " OFFSET " + query.offset : "";
156
- if (offset && !limit) throw new Error("LIMIT is required to use OFFSET.");
157
- return `SELECT ${select} FROM ${Sql.table(query.from)}` + join + where + groupBy + having + sort + limit + offset + getLock(query.lock);
158
- };
159
- //#endregion
160
- //#region src/db/sql/expression/comparison.ts
161
- let Comparison = /* @__PURE__ */ function(Comparison) {
162
- Comparison["eq"] = "=";
163
- Comparison["gt"] = ">";
164
- Comparison["lt"] = "<";
165
- Comparison["gte"] = ">=";
166
- Comparison["lte"] = "<=";
167
- Comparison["neq"] = "<>";
168
- Comparison["like"] = "LIKE";
169
- Comparison["notLike"] = "NOT LIKE";
170
- return Comparison;
171
- }({});
172
- const comparisonExpressionToSql = (exp) => {
173
- const type = Object.hasOwn(exp, "__type") ? exp.__type || "AND" : "AND";
174
- return Object.entries(exp).map(([key, value]) => {
175
- const column = SqlString$1.escapeId(key);
176
- if (!Array.isArray(value)) return `${column} = ${SqlString$1.escape(value)}`;
177
- if (value[0] === "IS NULL") return `${column} IS NULL`;
178
- if (value[0] === "IS NOT NULL") return `${column} IS NOT NULL`;
179
- if (value[0] === "IN") {
180
- const [, ...columns] = value;
181
- return `${column} IN (${[columns.map((column) => SqlString$1.escape(column)).join(", ")]})`;
182
- }
183
- if (value[0] === "BETWEEN") return `${column} BETWEEN ${SqlString$1.escape(value[1])} AND ${SqlString$1.escape(value[2])}`;
184
- if (Object.keys(Comparison).includes(value[0])) return `${column} ${value[0]} ${SqlString$1.escape(value[1])}`;
185
- throw new SasatError("SQL PARSE ERROR");
186
- }).join(` ${type} `);
187
- };
188
- //#endregion
189
- //#region src/db/sql/expression/conditionExpression.ts
190
- const conditionExpressionToSql = (exp) => {
191
- if (Array.isArray(exp)) return CompositeCondition.and(exp).toSQL();
192
- if (exp instanceof CompositeCondition) return exp.toSQL();
193
- return comparisonExpressionToSql(exp);
194
- };
195
- //#endregion
196
- //#region src/db/sql/expression/compositeCondition.ts
197
- var CompositeCondition = class CompositeCondition {
198
- constructor(type, conditions) {
199
- this.type = type;
200
- this.conditions = conditions;
201
- }
202
- static or(conditions) {
203
- return new CompositeCondition("OR", conditions);
204
- }
205
- static and(conditions) {
206
- return new CompositeCondition("AND", conditions);
207
- }
208
- toSQL() {
209
- return "(" + this.conditions.map(conditionExpressionToSql).join(this.type) + ")";
210
- }
211
- };
212
- //#endregion
213
- //#region src/runtime/createTypeDef.ts
214
- const makeArgs = (args) => {
215
- if (!args || args.length === 0) return "";
216
- return `(${args.map((arg) => `${arg.name}: ${arg.type}`).join(", ")})`;
217
- };
218
- const makeTypedefString = (typeName, typedef, type) => {
219
- const entries = Object.entries(typedef);
220
- if (entries.length === 0) return "";
221
- return `\
222
- ${type} ${typeName} {
223
- ${entries.map(([field, value]) => {
224
- if (!value.return) throw new Error(`Return type required: ${typeName}.${field}`);
225
- return ` ${field}${makeArgs(value.args)}: ${value.return}`;
226
- }).join("\n")}
227
- }
228
- `;
229
- };
230
- const createTypeDef = (typeDefs, inputs) => {
231
- const types = Object.entries(typeDefs).map(([type, fields]) => makeTypedefString(type, fields, "type"));
232
- const input = Object.entries(inputs).map(([type, fields]) => makeTypedefString(type, fields, "input"));
233
- return types.join("\n") + input.join("\n");
234
- };
235
- //#endregion
236
- //#region src/runtime/dsl/factory.ts
237
- const compound = (expr, operator) => {
238
- const active = expr.filter(nonNullable);
239
- if (active.length === 0) return conditions.eq(literal(1), literal(1));
240
- return active.reduce((acc, current) => ({
241
- kind: 4,
242
- left: acc,
243
- operator,
244
- right: current
245
- }));
246
- };
247
- const containsExpr = (isNot, type) => (left, right) => ({
248
- kind: 10,
249
- type,
250
- left,
251
- isNot,
252
- right
253
- });
254
- const comparison = (operator) => (left, right) => ({
255
- kind: 5,
256
- left,
257
- operator,
258
- right
259
- });
260
- const and = (...expr) => compound(expr, "AND");
261
- const or = (...expr) => compound(expr, "OR");
262
- const field = (table, name, alias) => ({
263
- kind: 0,
264
- table,
265
- name,
266
- alias
267
- });
268
- const fn = (fnName, args, alias) => ({
269
- kind: 1,
270
- fnName,
271
- args,
272
- alias
273
- });
274
- const window = (type, value) => ({
275
- kind: 18,
276
- type,
277
- between: false,
278
- value
279
- });
280
- const windowBetween = (type, start, end) => ({
281
- kind: 18,
282
- type,
283
- between: true,
284
- start,
285
- end
286
- });
287
- const paren = (expression) => ({
288
- kind: 7,
289
- expression
290
- });
291
- const In = (left, right) => {
292
- if (Array.isArray(right)) {
293
- if (right.length === 0) return conditions.eq(literal(0), literal(1));
294
- return {
295
- kind: 8,
296
- left,
297
- operator: "IN",
298
- right: right.map(literal)
299
- };
300
- }
301
- return {
302
- kind: 8,
303
- left,
304
- operator: "IN",
305
- query: right
306
- };
307
- };
308
- const notIn = (left, values) => ({
309
- kind: 8,
310
- left,
311
- operator: "NOT IN",
312
- right: values.map(literal)
313
- });
314
- const between = (left, begin, end) => ({
315
- kind: 9,
316
- left,
317
- begin,
318
- end
319
- });
320
- const isNull = (isNot) => (expr) => ({
321
- kind: 6,
322
- expr,
323
- isNot
324
- });
325
- const simpleWhere = (tableNameOrAlias, where, isOr = false) => {
326
- return (isOr ? or : and)(...Object.entries(where).map(([f, value]) => {
327
- const fe = field(tableNameOrAlias, f);
328
- if (Array.isArray(value)) return comparison(value[0])(fe, literal(value[1]));
329
- return conditions.eq(fe, literal(value));
330
- }));
331
- };
332
- const exists = (query) => ({
333
- kind: 14,
334
- query
335
- });
336
- const raw = (sql) => ({
337
- kind: 15,
338
- expr: sql
339
- });
340
- const conditions = {
341
- simpleWhere,
342
- and,
343
- or,
344
- eq: comparison("="),
345
- neq: comparison("<>"),
346
- gt: comparison(">"),
347
- gte: comparison(">="),
348
- lt: comparison("<"),
349
- lte: comparison("<="),
350
- comparison: (left, operator, right) => comparison(operator)(left, right),
351
- contains: containsExpr(false, "contains"),
352
- notContains: containsExpr(true, "contains"),
353
- startsWith: containsExpr(false, "start"),
354
- notStartsWith: containsExpr(true, "start"),
355
- endsWith: containsExpr(false, "end"),
356
- notEndsWith: containsExpr(true, "end"),
357
- in: In,
358
- notIn,
359
- between,
360
- isNull: isNull(false),
361
- isNotNull: isNull(true),
362
- exists
363
- };
364
- const table = (name, joins, alias) => ({
365
- kind: 2,
366
- subquery: false,
367
- name,
368
- alias,
369
- joins
370
- });
371
- const subQueryTable = (query, joins, alias) => ({
372
- kind: 2,
373
- subquery: true,
374
- query,
375
- alias,
376
- joins
377
- });
378
- const join = (table, conditions, type) => ({
379
- kind: 3,
380
- type,
381
- table,
382
- conditions
383
- });
384
- const literal = (value) => ({
385
- kind: 11,
386
- value
387
- });
388
- const sort = (field, direction) => ({
389
- kind: 12,
390
- field,
391
- direction
392
- });
393
- const ident = (identifier) => ({
394
- kind: 13,
395
- identifier
396
- });
397
- const QExpr = {
398
- conditions,
399
- ...conditions,
400
- field,
401
- fn,
402
- window,
403
- windowBetween,
404
- paren,
405
- table,
406
- subQueryTable,
407
- join,
408
- value: literal,
409
- sort,
410
- order: sort,
411
- ident,
412
- id: ident,
413
- raw
414
- };
415
- //#endregion
416
- //#region src/runtime/date.ts
417
- const dateOffset = (date, timeZoneHour) => {
418
- const offset = timeZoneHour ? timeZoneHour * 60 * 60 * 1e3 : date.getTimezoneOffset() * 6e4;
419
- return new Date(date.getTime() + offset);
420
- };
421
- const zeroPad = (v, len) => v.toString().padStart(len, "0");
422
- const dateToDatetimeString = (d) => {
423
- const year = d.getUTCFullYear();
424
- const month = d.getUTCMonth() + 1;
425
- const day = d.getUTCDate();
426
- const hour = d.getUTCHours();
427
- const minute = d.getUTCMinutes();
428
- const second = d.getUTCSeconds();
429
- const millisecond = d.getUTCMilliseconds();
430
- return zeroPad(year, 4) + "-" + zeroPad(month, 2) + "-" + zeroPad(day, 2) + " " + zeroPad(hour, 2) + ":" + zeroPad(minute, 2) + ":" + zeroPad(second, 2) + "." + zeroPad(millisecond, 3);
431
- };
432
- const dateToDateString = (d) => {
433
- const year = d.getUTCFullYear();
434
- const month = d.getUTCMonth() + 1;
435
- const day = d.getUTCDate();
436
- return zeroPad(year, 4) + "-" + zeroPad(month, 2) + "-" + zeroPad(day, 2);
437
- };
438
- const getTodayDateString = (timeZoneHour) => {
439
- const date = /* @__PURE__ */ new Date();
440
- date.setHours(0, 0, 0, 0);
441
- return dateToDateString(dateOffset(date, timeZoneHour));
442
- };
443
- const getTodayDateTimeString = (timeZoneHour) => {
444
- const date = /* @__PURE__ */ new Date();
445
- date.setHours(0, 0, 0, 0);
446
- return dateToDatetimeString(dateOffset(date, timeZoneHour));
447
- };
448
- const getDayRange = (date, timeZoneHour) => {
449
- date.setHours(0, 0, 0, 0);
450
- const d = dateOffset(date, timeZoneHour || 0);
451
- const begin = dateToDatetimeString(d);
452
- d.setDate(d.getDate() + 1);
453
- return [begin, dateToDatetimeString(d)];
454
- };
455
- const getDayRangeQExpr = (date, timeZoneHour) => {
456
- return getDayRange(date, timeZoneHour).map(QExpr.value);
457
- };
458
- //#endregion
459
- //#region src/runtime/gqlResolveInfoToField.ts
460
- const selectionSetToField = (selections, number) => {
461
- const result = {
462
- fields: [],
463
- relations: {},
464
- tableAlias: "t" + number
465
- };
466
- let num = number;
467
- for (const it of selections) {
468
- if (it.kind !== "Field") continue;
469
- if (it.selectionSet) {
470
- num += 1;
471
- const field = selectionSetToField(it.selectionSet.selections, num);
472
- result.relations[it.name.value] = field[0];
473
- num = field[1];
474
- } else if (it.name.value !== "__typename") result.fields.push(it.name.value);
475
- }
476
- return [result, num];
477
- };
478
- const gqlResolveInfoToField = (info) => {
479
- return selectionSetToField(info.fieldNodes[0].selectionSet.selections, 0)[0];
480
- };
481
- //#endregion
482
- //#region src/runtime/id.ts
483
- const makeNumberIdEncoder = (hashId) => {
484
- return {
485
- encode: (id) => hashId.encode(id),
486
- decode: (id) => hashId.decode(id)[0]
487
- };
488
- };
489
- //#endregion
490
- //#region src/runtime/makeResolver.ts
491
- const makeResolver = (resolver, middlewares = []) => {
492
- return (...args) => {
493
- return resolver(...middlewares.reduce((args, middleware) => {
494
- return middleware(args);
495
- }, args));
496
- };
497
- };
498
- //#endregion
499
- //#region src/runtime/resolverMiddleware.ts
500
- const makeParamsMiddleware = (update) => {
501
- return (args) => {
502
- args[1] = update(args[1]);
503
- return args;
504
- };
505
- };
506
- //#endregion
507
- //#region src/runtime/dsl/mutation/mutation.ts
508
- const escapeId = SqlString.escapeId;
509
- const onDuplicateKeyUpdate = (columns) => {
510
- if (!columns || columns.length === 0) return "";
511
- return " ON DUPLICATE KEY UPDATE " + columns.map(escapeId).map((it) => `${it} = VALUES(${it})`).join(",");
512
- };
513
- const createToSql = (dsl, tableInfo) => {
514
- const map = tableInfo[dsl.table].columnMap;
515
- const values = dsl.entities.map((it) => `(${it.map((it) => SqlString.escape(it)).join(",")})`).join(",");
516
- return `INSERT ${dsl.ignore ? "IGNORE " : ""}INTO ${escapeId(dsl.table)}(${dsl.fields.map((it) => escapeId(map[it]))}) VALUES ${values} ${onDuplicateKeyUpdate(dsl.upsert)}`;
517
- };
518
- const updateToSql = (dsl, tableInfo) => {
519
- const map = tableInfo[dsl.table].columnMap;
520
- return `UPDATE ${escapeId(dsl.table)} SET ${dsl.values.map((it) => escapeId(map[it.field]) + " = " + SqlString.escape(it.value)).join(", ")} WHERE ${Sql.booleanValue(dsl.where)}`;
521
- };
522
- const deleteToSql = (dsl) => {
523
- return `DELETE FROM ${escapeId(dsl.table)} WHERE ${Sql.booleanValue(dsl.where)}`;
524
- };
525
- //#endregion
526
- //#region src/runtime/dsl/query/createQueryResolveInfo.ts
527
- const joinToQueryResolveInfo = (parentTableAlias, property, fields, map, tableInfo) => {
528
- const info = map[parentTableAlias][property];
529
- if (!info) return void 0;
530
- return {
531
- tableAlias: fields.tableAlias || info.table,
532
- isArray: info.array,
533
- keyAliases: tableInfo[info.table].identifiableFields,
534
- joins: Object.entries(fields.relations || {}).filter(([, value]) => value).map(([key, value]) => joinToQueryResolveInfo(info.table, key, value, map, tableInfo)).filter(nonNullable),
535
- property
536
- };
537
- };
538
- const createQueryResolveInfo = (tableName, fields, map, tableInfo) => {
539
- return {
540
- tableAlias: fields.tableAlias || tableName,
541
- isArray: true,
542
- keyAliases: tableInfo[tableName].identifiableFields,
543
- joins: Object.entries(fields.relations || {}).filter(([, value]) => value).map(([key, value]) => joinToQueryResolveInfo(tableName, key, value, map, tableInfo)).filter(nonNullable),
544
- property: ""
545
- };
546
- };
547
- //#endregion
548
- //#region src/runtime/dsl/query/sql/hydrate.ts
549
- const rowToObjs = (row) => {
550
- const objs = {};
551
- for (const [key, value] of Object.entries(row)) {
552
- const [table, column] = key.split("__");
553
- if (!objs[table]) objs[table] = {};
554
- objs[table][column] = value;
555
- }
556
- return objs;
557
- };
558
- const getUnique = (obj, info) => info.keyAliases.map((it) => obj[it]).join("_~_");
559
- const execTable = (info, objs, current) => {
560
- let entity = objs[info.tableAlias];
561
- if (entity[info.keyAliases[0]] == null) entity = null;
562
- let result;
563
- let currentTarget;
564
- if (info.isArray) if (!current) {
565
- result = entity == null ? [] : [entity];
566
- currentTarget = entity;
567
- } else {
568
- currentTarget = entity == null ? null : current.find((item) => item && info.keyAliases.every((key) => item[key] === entity[key]));
569
- if (currentTarget) result = current;
570
- else {
571
- currentTarget = entity;
572
- result = current;
573
- if (currentTarget) result.push(currentTarget);
574
- }
575
- }
576
- else {
577
- currentTarget = current || entity;
578
- result = currentTarget;
579
- }
580
- if (currentTarget !== null) for (const it of info.joins) currentTarget[it.property] = execTable(it, objs, currentTarget[it.property]);
581
- return result;
582
- };
583
- /**
584
- * to use this function require to select primary keys for every table
585
- */
586
- const hydrate = (data, info) => {
587
- const result = [];
588
- const t0mapper = {};
589
- info.isArray = false;
590
- for (const row of data) {
591
- const objs = rowToObjs(row);
592
- const currentObj = objs[info.tableAlias];
593
- const unique = getUnique(currentObj, info);
594
- if (t0mapper[unique] === void 0) {
595
- t0mapper[unique] = result.length;
596
- result.push(execTable(info, objs, currentObj));
597
- continue;
598
- }
599
- const base = result[t0mapper[unique]];
600
- execTable(info, objs, base);
601
- }
602
- return result;
603
- };
604
- //#endregion
605
- //#region src/runtime/sql/runQuery.ts
606
- const notTypeName = (fieldName) => fieldName !== "__typename";
607
- const createQuery = (baseTableName, fields, options, tableInfo, relationMap, context) => {
608
- let tableCount = 0;
609
- const select = [];
610
- const resolveFields = (tableName, table) => {
611
- const tableAlias = table.tableAlias || "t" + tableCount;
612
- table.tableAlias = tableAlias;
613
- tableCount++;
614
- const info = tableInfo[tableName];
615
- select.push(...unique([...table.fields.filter((it) => {
616
- return notTypeName(it) && info.columnMap[it];
617
- }), ...info.identifiableFields]).map((it) => {
618
- const realName = info.columnMap[it] || it;
619
- return QExpr.field(tableAlias, realName, tableAlias + "__" + it);
620
- }));
621
- return QExpr.table(tableName, Object.entries(table.relations || {}).map(([relationName, table]) => {
622
- const current = tableCount;
623
- const rel = relationMap[tableName][relationName];
624
- if (!rel) return void 0;
625
- return QExpr.join(resolveFields(rel.table, table), QExpr.and(rel.condition({
626
- parentTableAlias: tableAlias,
627
- childTableAlias: table.tableAlias || "t" + current,
628
- context
629
- }), table.joinOn), table.joinType ?? "LEFT");
630
- }).filter(nonNullable), tableAlias);
631
- };
632
- return {
633
- select,
634
- from: resolveFields(baseTableName, fields),
635
- ...options
636
- };
637
- };
638
- const createPagingInnerQuery = (tableName, tableAlias, fields, option, tableInfo, relationMap) => {
639
- const map = tableInfo[tableName].columnMap;
640
- return {
641
- select: unique([
642
- ...tableInfo[tableName].identifiableKeys,
643
- ...Object.keys(fields.relations || {}).flatMap((key) => {
644
- return relationMap[tableName][key]?.requiredColumns || [];
645
- }),
646
- ...fields.fields.filter((it) => notTypeName(it) && map[it]).map((it) => map[it] || it)
647
- ]).map((it) => QExpr.field(tableAlias, it)),
648
- from: QExpr.table(tableName, option.join || [], tableAlias),
649
- limit: option.numberOfItem,
650
- offset: option.offset,
651
- where: option.where,
652
- sort: option.sort
653
- };
654
- };
655
- const createPagingFieldQuery = ({ baseTableName, fields, queryOption, pagingOption, tableInfo, relationMap, context }) => {
656
- const innerQuery = createPagingInnerQuery(baseTableName, fields.tableAlias || "t0", fields, pagingOption, tableInfo, relationMap);
657
- const main = createQuery(baseTableName, fields, queryOption, tableInfo, relationMap, context);
658
- return {
659
- select: main.select,
660
- from: {
661
- ...main.from,
662
- subquery: true,
663
- query: innerQuery
664
- }
665
- };
666
- };
667
- //#endregion
668
- //#region src/runtime/sasatDBDatasource.ts
669
- var SasatDBDatasource = class {
670
- constructor(client = getDbClient()) {
671
- this.client = client;
672
- }
673
- async create(entity, option) {
674
- const obj = {
675
- ...this.getDefaultValueString(),
676
- ...entity
677
- };
678
- const fields = Object.keys(obj);
679
- const sql = createToSql({
680
- table: this.tableName,
681
- fields,
682
- entities: [fields.map((key) => obj[key])],
683
- upsert: option?.upsert?.updateColumns,
684
- ignore: option?.ignore
685
- }, this.tableInfo);
686
- const response = await this.client.rawCommand(sql);
687
- if (!this.autoIncrementColumn) return obj;
688
- return {
689
- ...obj,
690
- [this.autoIncrementColumn]: response.insertId
691
- };
692
- }
693
- async createBulk(entities, option) {
694
- const objects = entities.map((it) => ({
695
- ...this.getDefaultValueString(),
696
- ...it
697
- }));
698
- const keys = Object.keys(objects[0]);
699
- const values = objects.map((it) => keys.map((key) => it[key]));
700
- const sql = createToSql({
701
- table: this.tableName,
702
- fields: keys,
703
- entities: values,
704
- upsert: option?.upsert?.updateColumns,
705
- ignore: option?.ignore
706
- }, this.tableInfo);
707
- return await this.client.rawCommand(sql);
708
- }
709
- async upsert(entity, updateFields = this.primaryKeys) {
710
- return this.create(entity, { upsert: { updateColumns: this.fieldToColumn(updateFields) } });
711
- }
712
- update(entity) {
713
- const sql = updateToSql({
714
- table: this.tableName,
715
- values: Object.entries(entity).filter(([, value]) => value !== void 0).map(([column, value]) => ({
716
- field: column,
717
- value
718
- })),
719
- where: this.createIdentifiableExpression(entity)
720
- }, this.tableInfo);
721
- return this.client.rawCommand(sql);
722
- }
723
- updateWhere(update, condition) {
724
- const sql = updateToSql({
725
- table: this.tableName,
726
- values: Object.entries(update).filter(([, value]) => value !== void 0).map(([column, value]) => ({
727
- field: column,
728
- value
729
- })),
730
- where: condition
731
- }, this.tableInfo);
732
- return this.client.rawCommand(sql);
733
- }
734
- async delete(entity) {
735
- return this.deleteWhere(this.createIdentifiableExpression(entity));
736
- }
737
- async deleteWhere(condition) {
738
- const sql = deleteToSql({
739
- table: this.tableName,
740
- where: condition
741
- });
742
- return this.client.rawCommand(sql);
743
- }
744
- async first(fields, option, context) {
745
- const result = await this.find(fields, option, context);
746
- if (result.length !== 0) return result[0];
747
- return null;
748
- }
749
- async find(fields = { fields: this.fields }, options, context) {
750
- const query = createQuery(this.tableName, fields, options, this.tableInfo, this.relationMap, context);
751
- return this.executeQuery(query, fields);
752
- }
753
- async findPageable(paging, fields = { fields: this.fields }, options, context) {
754
- const query = createPagingFieldQuery({
755
- baseTableName: this.tableName,
756
- fields,
757
- tableInfo: this.tableInfo,
758
- relationMap: this.relationMap,
759
- pagingOption: paging,
760
- queryOption: options,
761
- context
762
- });
763
- return this.executeQuery(query, fields);
764
- }
765
- async executeQuery(query, fields) {
766
- const info = createQueryResolveInfo(this.tableName, fields, this.relationMap, this.tableInfo);
767
- const sql = queryToSql(query);
768
- return hydrate(await this.client.rawQuery(sql), info);
769
- }
770
- createIdentifiableExpression(entity) {
771
- const expr = this.identifyFields.map((it) => {
772
- const value = entity[it];
773
- if (!value) throw new Error(`field ${it} is required`);
774
- return QExpr.eq(QExpr.field(this.tableName, this.tableInfo[this.tableName].columnMap[it]), QExpr.value(value));
775
- });
776
- return QExpr.and(...expr);
777
- }
778
- getRelationMap() {
779
- return this.relationMap[this.tableName];
780
- }
781
- fieldToColumn(fields) {
782
- return fields.map((it) => this.tableInfo[this.tableName].columnMap[it] || it);
783
- }
784
- };
785
- //#endregion
786
- //#region src/util/dateUtil.ts
787
- const getCurrentDateTimeString = () => {
788
- const pad = (number) => {
789
- if (number < 10) return "0" + number;
790
- return number;
791
- };
792
- const date = /* @__PURE__ */ new Date();
793
- return date.getFullYear() + "-" + pad(date.getMonth() + 1) + "-" + pad(date.getDate()) + " " + pad(date.getHours()) + ":" + pad(date.getMinutes()) + ":" + pad(date.getSeconds());
794
- };
795
- //#endregion
796
- //#region src/runtime/pagingOption.ts
797
- const pagingOption = (option) => {
798
- const sort = option.order ? [QExpr.sort(QExpr.field("t1", option.order), option?.asc === false ? "DESC" : "ASC")] : [];
799
- return {
800
- numberOfItem: option.numberOfItem,
801
- offset: option.offset,
802
- sort
803
- };
804
- };
805
- //#endregion
1
+ import { a as getDbClient, c as formatQuery, f as setConfig, l as SqlString, n as pick, v as assignDeep } from "./util-Dkw5bD7a.mjs";
2
+ import { _ as CompositeCondition, a as makeResolver, b as MysqlClient, c as dateOffset, d as getDayRange, f as getDayRangeQExpr, g as createTypeDef, h as QExpr, i as makeParamsMiddleware, l as dateToDateString, m as getTodayDateTimeString, n as getCurrentDateTimeString, o as makeNumberIdEncoder, p as getTodayDateString, r as SasatDBDatasource, s as gqlResolveInfoToField, t as pagingOption, u as dateToDatetimeString, v as queryToSql, y as Sql } from "./src-DebKrtYl.mjs";
806
3
  export { CompositeCondition, MysqlClient, QExpr, QExpr as qe, SasatDBDatasource, Sql, SqlString, assignDeep, createTypeDef, dateOffset, dateToDateString, dateToDatetimeString, formatQuery, getCurrentDateTimeString, getDayRange, getDayRangeQExpr, getDbClient, getTodayDateString, getTodayDateTimeString, gqlResolveInfoToField, makeNumberIdEncoder, makeParamsMiddleware, makeResolver, pagingOption, pick, queryToSql, setConfig };