sasat 0.21.21 → 0.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,436 +0,0 @@
1
- 'use strict';
2
-
3
- const SqlString$1 = require('sqlstring');
4
- const mysql = require('mysql2');
5
- const util = require('util');
6
- const path = require('path');
7
- const fs = require('fs-extra');
8
- const yaml = require('js-yaml');
9
-
10
- function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
11
-
12
- function _interopNamespaceCompat(e) {
13
- if (e && typeof e === 'object' && 'default' in e) return e;
14
- const n = Object.create(null);
15
- if (e) {
16
- for (const k in e) {
17
- n[k] = e[k];
18
- }
19
- }
20
- n.default = e;
21
- return n;
22
- }
23
-
24
- const SqlString__default = /*#__PURE__*/_interopDefaultCompat(SqlString$1);
25
- const mysql__namespace = /*#__PURE__*/_interopNamespaceCompat(mysql);
26
- const path__default = /*#__PURE__*/_interopDefaultCompat(path);
27
- const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
28
- const yaml__default = /*#__PURE__*/_interopDefaultCompat(yaml);
29
-
30
- const { escapeId, escape } = SqlString__default;
31
- const SqlString = {
32
- escape: (value) => escape(value, true),
33
- escapeId: (name) => escapeId(name)
34
- };
35
-
36
- const assignDeep = (base, ...objects) => {
37
- const assign = (target, key, value) => {
38
- if (key === "__proto__" || key === "constructor") {
39
- return;
40
- }
41
- if (Array.isArray(target[key]) && Array.isArray(value)) {
42
- target[key] = [...target[key], ...value];
43
- } else if (typeof target[key] === "object" && typeof value === "object") {
44
- assignDeep(target[key], value);
45
- } else {
46
- target[key] = value;
47
- }
48
- };
49
- objects.forEach((obj) => {
50
- if (typeof obj === "object") {
51
- Object.entries(obj).forEach(([key, value]) => {
52
- assign(base, key, value);
53
- });
54
- }
55
- });
56
- return base;
57
- };
58
-
59
- const readYmlFile = (filepath) => yaml__default.load(fs__default.readFileSync(filepath, "utf8"));
60
- const mkDirIfNotExist = (path) => {
61
- if (!fs__default.pathExistsSync(path)) fs__default.mkdirpSync(path);
62
- };
63
- const writeFileIfNotExist = (path, data) => {
64
- if (fs__default.existsSync(path)) return Promise.resolve();
65
- return fs__default.writeFile(path, data);
66
- };
67
- const writeYmlFile = (path$1, fileName, obj) => {
68
- mkDirIfNotExist(path$1);
69
- fs__default.writeFileSync(
70
- path.join(path$1, fileName),
71
- yaml__default.dump(obj, {
72
- skipInvalid: true,
73
- noRefs: true,
74
- sortKeys: (a, b) => {
75
- if (b === "tableName") return 1;
76
- if (a === "tableName") return -1;
77
- if (a > b) return 1;
78
- if (a < b) return -1;
79
- return 0;
80
- }
81
- })
82
- );
83
- };
84
- const readInitialSchema = () => {
85
- return readYmlFile(path.join(config().migration.dir, "initialSchema.yml"));
86
- };
87
- const writeCurrentSchema = (schema) => {
88
- writeYmlFile(config().migration.dir, "currentSchema.yml", schema);
89
- };
90
-
91
- class SasatConfigLoader {
92
- static loadConfig() {
93
- const fileName = "sasat.yml";
94
- const filepath = path__default.join(process.cwd(), fileName);
95
- if (!fs__default.existsSync(filepath)) return defaultConf;
96
- return readYmlFile(filepath);
97
- }
98
- conf;
99
- constructor() {
100
- const conf = this.readValue({
101
- ...defaultConf,
102
- ...SasatConfigLoader.loadConfig()
103
- });
104
- this.conf = {
105
- ...conf
106
- };
107
- }
108
- getConfig() {
109
- return this.conf;
110
- }
111
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
112
- readValue(value) {
113
- if (!value) return value;
114
- if (Array.isArray(value)) return value.map((it) => this.readValue(it));
115
- if (typeof value === "string" && value.startsWith("$"))
116
- return process.env[value.slice(1)];
117
- if (typeof value === "object") {
118
- for (const key in value) {
119
- if (Object.prototype.hasOwnProperty.call(value, key))
120
- value[key] = this.readValue(value[key]);
121
- }
122
- return value;
123
- }
124
- return value;
125
- }
126
- }
127
-
128
- const defaultConfDb = {
129
- host: "127.0.0.1",
130
- port: 3306,
131
- user: "root",
132
- database: "sasat",
133
- password: ""
134
- };
135
- const defaultConfMigration = {
136
- table: "__migrate__",
137
- dir: "migrations",
138
- out: "sasat"
139
- };
140
- const defaultConf = {
141
- db: defaultConfDb,
142
- migration: defaultConfMigration,
143
- generator: {
144
- addJsExtToImportStatement: false,
145
- gql: {
146
- subscription: true
147
- }
148
- }
149
- // redis: defaultCofRedis,
150
- };
151
- let conf;
152
- const config = () => {
153
- if (conf === void 0) conf = new SasatConfigLoader().getConfig();
154
- return conf;
155
- };
156
- function setConfig(update) {
157
- conf = assignDeep(config(), update);
158
- return conf;
159
- }
160
-
161
- const formatQuery = (str, ...params) => {
162
- let ret = str[0];
163
- for (let i = 0; i < params.length; i++) {
164
- if (typeof params[i] === "function") ret += params[i]();
165
- else if (Array.isArray(params[i]))
166
- ret += params[i].map((it) => SqlString.escape(it)).join(", ");
167
- else ret += SqlString.escape(params[i]);
168
- ret += str[i + 1];
169
- }
170
- return ret;
171
- };
172
-
173
- const parent = (field2) => ({
174
- kind: "parent",
175
- field: field2
176
- });
177
- const child = (field2) => ({
178
- kind: "child",
179
- field: field2
180
- });
181
- const contextOrError = (field2, errorMessage) => ({
182
- kind: "context",
183
- field: field2,
184
- onNotDefined: {
185
- action: "error",
186
- message: errorMessage
187
- }
188
- });
189
- const contextOrDefault = (field2, defaultValue) => ({
190
- kind: "context",
191
- field: field2,
192
- onNotDefined: {
193
- action: "defaultValue",
194
- value: defaultValue
195
- }
196
- });
197
- const fixed = (value) => ({
198
- kind: "fixed",
199
- value
200
- });
201
- const today = (thresholdHour, date) => ({
202
- kind: "today",
203
- type: date ? "date" : "datetime",
204
- thresholdHour
205
- });
206
- const now = () => ({
207
- kind: "now"
208
- });
209
- const values = (begin, end) => ({
210
- kind: "range",
211
- begin,
212
- end
213
- });
214
- const betweenToday = (thresholdHour) => ({
215
- kind: "date-range",
216
- range: "today",
217
- thresholdHour
218
- });
219
- const custom = (conditionName, parentRequiredFields, childRequiredFields) => ({
220
- kind: "custom",
221
- conditionName,
222
- parentRequiredFields,
223
- childRequiredFields
224
- });
225
- const field = (column) => ({
226
- kind: "field",
227
- column
228
- });
229
- const arg = (name, type) => ({
230
- kind: "arg",
231
- name,
232
- type
233
- });
234
- const betweenRel = (left, range) => ({
235
- kind: "comparison",
236
- left,
237
- operator: "BETWEEN",
238
- right: range
239
- });
240
- const betweenQuery = (left, begin, end) => ({
241
- kind: "between",
242
- operator: "BETWEEN",
243
- left,
244
- begin,
245
- end
246
- });
247
- const comparisonRel = (left, operator, right) => ({
248
- kind: "comparison",
249
- left,
250
- right,
251
- operator
252
- });
253
- const inRel = (left, right) => ({
254
- kind: "comparison",
255
- left,
256
- right,
257
- operator: "IN"
258
- });
259
- const isNullRel = (value) => ({
260
- kind: "isNull",
261
- value,
262
- not: false
263
- });
264
- const isNotNullRel = (value) => ({
265
- kind: "isNull",
266
- value,
267
- not: true
268
- });
269
- const comparisonQuery = (left, operator, right) => ({
270
- kind: "comparison",
271
- left,
272
- right,
273
- operator
274
- });
275
- const Conditions = {
276
- betweenRel,
277
- betweenQuery,
278
- custom,
279
- rel: {
280
- between: betweenRel,
281
- comparison: comparisonRel,
282
- in: inRel,
283
- isNull: isNullRel,
284
- isNotNull: isNotNullRel
285
- },
286
- query: {
287
- between: betweenQuery,
288
- comparison: comparisonQuery
289
- },
290
- value: {
291
- parent,
292
- child,
293
- contextOrError,
294
- contextOrDefault,
295
- fixed,
296
- today,
297
- now,
298
- field,
299
- arg
300
- },
301
- range: {
302
- values,
303
- today: betweenToday
304
- }
305
- };
306
-
307
- const pick = (target, keys) => Object.fromEntries(keys.map((key) => [key, target[key]]));
308
- const unique = (array) => {
309
- const result = [];
310
- for (let i = 0, l = array.length; i < l; i += 1) {
311
- if (!result.includes(array[i])) {
312
- result.push(array[i]);
313
- }
314
- }
315
- return result;
316
- };
317
- const nonNullable = (value) => value != null;
318
-
319
- const noop = () => {
320
- };
321
- class SQLClient {
322
- logger = noop;
323
- rawQuery(sql) {
324
- this.logger(sql);
325
- return this.execSql(sql);
326
- }
327
- rawCommand(sql) {
328
- this.logger(sql);
329
- return this.execSql(sql);
330
- }
331
- query(templateString, ...params) {
332
- return this.rawQuery(formatQuery(templateString, ...params));
333
- }
334
- command(templateString, ...params) {
335
- return this.rawCommand(formatQuery(templateString, ...params));
336
- }
337
- }
338
- class SQLTransaction extends SQLClient {
339
- }
340
- class DBClient extends SQLClient {
341
- _released;
342
- constructor(logger = noop) {
343
- super();
344
- this._released = false;
345
- this.logger = logger;
346
- }
347
- isReleased() {
348
- return this._released;
349
- }
350
- }
351
-
352
- class MySqlTransaction extends SQLTransaction {
353
- constructor(connection) {
354
- super();
355
- this.connection = connection;
356
- }
357
- commit() {
358
- const result = util.promisify(this.connection.commit).bind(this.connection)();
359
- this.connection.end();
360
- return result;
361
- }
362
- async rollback() {
363
- await util.promisify(this.connection.rollback).bind(this.connection)();
364
- this.connection.end();
365
- return;
366
- }
367
- execSql(sql) {
368
- return util.promisify(this.connection.query).bind(this.connection)(
369
- sql
370
- );
371
- }
372
- }
373
-
374
- class MysqlClient extends DBClient {
375
- constructor(connectionOption, poolOption, logger) {
376
- super(logger);
377
- this.connectionOption = connectionOption;
378
- this.pool = mysql__namespace.createPool({
379
- ...config().db,
380
- dateStrings: true,
381
- ...connectionOption,
382
- ...poolOption
383
- });
384
- this.release = this.release.bind(this);
385
- }
386
- pool;
387
- async transaction() {
388
- const connection = mysql__namespace.createConnection({
389
- ...config().db,
390
- dateStrings: true,
391
- ...this.connectionOption
392
- });
393
- await util.promisify(connection.beginTransaction).bind(connection)();
394
- return new MySqlTransaction(connection);
395
- }
396
- async release() {
397
- await util.promisify(this.pool.end).bind(this.pool)();
398
- this._released = true;
399
- }
400
- execSql(sql) {
401
- return util.promisify(this.pool.query).bind(this.pool)(sql);
402
- }
403
- }
404
-
405
- let client;
406
- const getDbClient = (...config) => {
407
- if (client && !client.isReleased()) return client;
408
- client = new MysqlClient(...config);
409
- return client;
410
- };
411
-
412
- class SasatError extends Error {
413
- constructor(message) {
414
- super(message);
415
- Object.setPrototypeOf(this, new.target.prototype);
416
- this.name = "SasatError";
417
- }
418
- }
419
-
420
- exports.Conditions = Conditions;
421
- exports.SasatError = SasatError;
422
- exports.SqlString = SqlString;
423
- exports.assignDeep = assignDeep;
424
- exports.config = config;
425
- exports.defaultConf = defaultConf;
426
- exports.formatQuery = formatQuery;
427
- exports.getDbClient = getDbClient;
428
- exports.mkDirIfNotExist = mkDirIfNotExist;
429
- exports.nonNullable = nonNullable;
430
- exports.pick = pick;
431
- exports.readInitialSchema = readInitialSchema;
432
- exports.setConfig = setConfig;
433
- exports.unique = unique;
434
- exports.writeCurrentSchema = writeCurrentSchema;
435
- exports.writeFileIfNotExist = writeFileIfNotExist;
436
- exports.writeYmlFile = writeYmlFile;