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