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