@spinajs/orm-sql 2.0.180 → 2.0.181

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,1027 +1,1027 @@
1
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
- return c > 3 && r && Object.defineProperty(target, key, r), r;
6
- };
7
- var __metadata = (this && this.__metadata) || function (k, v) {
8
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
- };
10
- /* eslint-disable @typescript-eslint/no-unsafe-call */
11
- /* eslint-disable @typescript-eslint/no-unsafe-member-access */
12
- /* eslint-disable @typescript-eslint/no-empty-interface */
13
- /* eslint-disable prettier/prettier */
14
- import { InvalidOperation, InvalidArgument } from '@spinajs/exceptions';
15
- import { LimitBuilder, DropTableQueryBuilder, AlterColumnQueryBuilder, TableCloneQueryCompiler, OnDuplicateQueryBuilder, DeleteQueryBuilder, LimitQueryCompiler, InsertQueryBuilder, OrderByBuilder, SelectQueryBuilder, UpdateQueryBuilder, SelectQueryCompiler, TableQueryCompiler, TableQueryBuilder, ColumnQueryBuilder, ColumnQueryCompiler, RawQuery, OrderByQueryCompiler, OnDuplicateQueryCompiler, IndexQueryCompiler, IndexQueryBuilder, ForeignKeyBuilder, ForeignKeyQueryCompiler, AlterTableQueryBuilder, CloneTableQueryBuilder, AlterTableQueryCompiler, ColumnAlterationType, AlterColumnQueryCompiler, TableAliasCompiler, DropTableCompiler, DropEventQueryBuilder, TableHistoryQueryCompiler, EventQueryBuilder } from '@spinajs/orm';
16
- import { use } from 'typescript-mix';
17
- import { NewInstance, Inject, Container } from '@spinajs/di';
18
- import _ from 'lodash';
19
- let SqlTableAliasCompiler = class SqlTableAliasCompiler {
20
- compile(builder, tbl) {
21
- let table = '';
22
- if (builder.Database) {
23
- table += `\`${builder.Database}\`.`;
24
- }
25
- table += `\`${tbl ? tbl : builder.Table}\``;
26
- if (builder.TableAlias) {
27
- table += ` as \`${builder.TableAlias}\``;
28
- }
29
- return table;
30
- }
31
- };
32
- SqlTableAliasCompiler = __decorate([
33
- NewInstance()
34
- ], SqlTableAliasCompiler);
35
- export { SqlTableAliasCompiler };
36
- let SqlQueryCompiler = class SqlQueryCompiler extends SelectQueryCompiler {
37
- constructor(_builder, _container) {
38
- super();
39
- this._builder = _builder;
40
- this._container = _container;
41
- if (_builder === null && _builder === undefined) {
42
- throw new InvalidArgument('builder cannot be null or undefined');
43
- }
44
- }
45
- tryConvertValue(v) {
46
- let val = v;
47
- const converters = this._container.get('__orm_db_value_converters__');
48
- if (converters && v && converters.has(v.constructor.name)) {
49
- const converter = this._container.resolve(converters.get(v.constructor.name));
50
- val = converter.toDB(val, null, null);
51
- }
52
- return val;
53
- }
54
- };
55
- SqlQueryCompiler = __decorate([
56
- NewInstance(),
57
- __metadata("design:paramtypes", [Object, Object])
58
- ], SqlQueryCompiler);
59
- export { SqlQueryCompiler };
60
- let SqlOrderByQueryCompiler = class SqlOrderByQueryCompiler extends OrderByQueryCompiler {
61
- constructor(builder) {
62
- super();
63
- if (!builder) {
64
- throw new InvalidOperation('builder cannot be null or undefined');
65
- }
66
- this._builder = builder;
67
- }
68
- compile() {
69
- const sort = this._builder.getSort();
70
- let stmt = '';
71
- const bindings = [];
72
- if (sort) {
73
- stmt = ` ORDER BY ${sort.column} ${sort.order}`;
74
- }
75
- return {
76
- bindings,
77
- expression: stmt,
78
- };
79
- }
80
- };
81
- SqlOrderByQueryCompiler = __decorate([
82
- NewInstance(),
83
- __metadata("design:paramtypes", [OrderByBuilder])
84
- ], SqlOrderByQueryCompiler);
85
- export { SqlOrderByQueryCompiler };
86
- let SqlWithRecursiveCompiler = class SqlWithRecursiveCompiler {
87
- recursive(builder) {
88
- const statement = builder.CteRecursive.build();
89
- let exprr = `WITH RECURSIVE recursive_cte(${statement.Statements[0]}) AS`;
90
- exprr += ` ( `;
91
- exprr += statement.Statements[1];
92
- exprr += ` UNION ALL `;
93
- exprr += statement.Statements[2];
94
- exprr += ` ) `;
95
- exprr += 'SELECT * FROM recursive_cte';
96
- return {
97
- bindings: statement.Bindings,
98
- expression: exprr,
99
- };
100
- }
101
- };
102
- SqlWithRecursiveCompiler = __decorate([
103
- NewInstance()
104
- ], SqlWithRecursiveCompiler);
105
- export { SqlWithRecursiveCompiler };
106
- let SqlForeignKeyQueryCompiler = class SqlForeignKeyQueryCompiler {
107
- constructor(_builder) {
108
- this._builder = _builder;
109
- if (!_builder) {
110
- throw new Error('foreign key query builder cannot be null');
111
- }
112
- }
113
- compile() {
114
- const exprr = `FOREIGN KEY (${this._builder.ForeignKeyField}) REFERENCES ${this._builder.Table}(${this._builder.PrimaryKey}) ON DELETE ${this._builder.OnDeleteAction} ON UPDATE ${this._builder.OnUpdateAction}`;
115
- return {
116
- bindings: [],
117
- expression: exprr,
118
- };
119
- }
120
- };
121
- SqlForeignKeyQueryCompiler = __decorate([
122
- NewInstance(),
123
- __metadata("design:paramtypes", [ForeignKeyBuilder])
124
- ], SqlForeignKeyQueryCompiler);
125
- export { SqlForeignKeyQueryCompiler };
126
- let SqlLimitQueryCompiler = class SqlLimitQueryCompiler extends LimitQueryCompiler {
127
- constructor(builder) {
128
- super();
129
- if (!builder) {
130
- throw new InvalidOperation('builder cannot be null or undefined');
131
- }
132
- this._builder = builder;
133
- }
134
- compile() {
135
- const limits = this._builder.getLimits();
136
- const bindings = [];
137
- let stmt = '';
138
- if (limits.limit > 0) {
139
- stmt += ` LIMIT ?`;
140
- bindings.push(limits.limit);
141
- }
142
- else {
143
- if (limits.offset > 0) {
144
- stmt += ` LIMIT 18446744073709551615`;
145
- }
146
- }
147
- if (limits.offset > 0) {
148
- stmt += ` OFFSET ?`;
149
- bindings.push(limits.offset);
150
- }
151
- return {
152
- bindings,
153
- expression: stmt,
154
- };
155
- }
156
- };
157
- SqlLimitQueryCompiler = __decorate([
158
- NewInstance(),
159
- __metadata("design:paramtypes", [LimitBuilder])
160
- ], SqlLimitQueryCompiler);
161
- export { SqlLimitQueryCompiler };
162
- let SqlGroupByCompiler = class SqlGroupByCompiler {
163
- group(builder) {
164
- let bindings = [];
165
- let stmt = ' GROUP BY ';
166
- const builds = builder.GroupStatements.map((x) => x.build());
167
- stmt += builds.map((x) => x.Statements).join(',');
168
- bindings = builds.map((x) => x.Bindings);
169
- return {
170
- bindings,
171
- expression: builds.length != 0 ? stmt : '',
172
- };
173
- }
174
- };
175
- SqlGroupByCompiler = __decorate([
176
- NewInstance()
177
- ], SqlGroupByCompiler);
178
- export { SqlGroupByCompiler };
179
- let SqlColumnsCompiler = class SqlColumnsCompiler {
180
- columns(builder) {
181
- return {
182
- bindings: [],
183
- expression: builder
184
- .getColumns()
185
- .map((c) => {
186
- return c.build().Statements[0];
187
- })
188
- .join(','),
189
- };
190
- }
191
- };
192
- SqlColumnsCompiler = __decorate([
193
- NewInstance()
194
- ], SqlColumnsCompiler);
195
- export { SqlColumnsCompiler };
196
- let SqlWhereCompiler = class SqlWhereCompiler {
197
- where(builder) {
198
- const where = [];
199
- const bindings = [];
200
- builder.Statements.map((x) => {
201
- return x.build();
202
- }).forEach((r) => {
203
- where.push(...r.Statements);
204
- if (Array.isArray(r.Bindings)) {
205
- bindings.push(...r.Bindings);
206
- }
207
- });
208
- return {
209
- bindings,
210
- expression: where.join(` ${builder.Op.toUpperCase()} `),
211
- };
212
- }
213
- };
214
- SqlWhereCompiler = __decorate([
215
- NewInstance()
216
- ], SqlWhereCompiler);
217
- export { SqlWhereCompiler };
218
- let SqlJoinCompiler = class SqlJoinCompiler {
219
- join(builder) {
220
- const result = builder.JoinStatements.map((s) => s.build());
221
- return {
222
- bindings: _.flatMap(result, (r) => r.Bindings),
223
- expression: _.flatMap(result, (r) => r.Statements).join(' '),
224
- };
225
- }
226
- };
227
- SqlJoinCompiler = __decorate([
228
- NewInstance()
229
- ], SqlJoinCompiler);
230
- export { SqlJoinCompiler };
231
- let SqlSelectQueryCompiler = class SqlSelectQueryCompiler extends SqlQueryCompiler {
232
- constructor(_container, builder) {
233
- super(builder, _container);
234
- }
235
- compile() {
236
- if (this._builder.CteRecursive) {
237
- return this.recursive(this._builder);
238
- }
239
- const columns = this.select();
240
- const from = this.from();
241
- const limit = this.limit();
242
- const sort = this.sort();
243
- const where = this.where(this._builder);
244
- const join = this.join(this._builder);
245
- const group = this.group(this._builder);
246
- const expression = columns + ' ' + from + (join.expression ? ` ${join.expression}` : '') + (where.expression ? ` WHERE ${where.expression}` : '') + group.expression + sort.expression + limit.expression;
247
- const bindings = [];
248
- bindings.push(...join.bindings);
249
- bindings.push(...where.bindings);
250
- bindings.push(...sort.bindings);
251
- bindings.push(...limit.bindings);
252
- bindings.push(...group.bindings);
253
- return {
254
- bindings,
255
- expression: expression.trim(),
256
- };
257
- }
258
- limit() {
259
- const compiler = this._container.resolve(LimitQueryCompiler, [this._builder]);
260
- return compiler.compile();
261
- }
262
- sort() {
263
- const compiler = this._container.resolve(OrderByQueryCompiler, [this._builder]);
264
- return compiler.compile();
265
- }
266
- select() {
267
- let _stmt = 'SELECT ';
268
- if (this._builder.IsDistinct) {
269
- _stmt += 'DISTINCT ';
270
- }
271
- if (this._builder.getColumns().length === 0) {
272
- return _stmt + '*';
273
- }
274
- return _stmt + this.columns(this._builder).expression;
275
- }
276
- from() {
277
- return 'FROM ' + this._container.resolve(TableAliasCompiler).compile(this._builder);
278
- }
279
- };
280
- __decorate([
281
- use(SqlWhereCompiler, SqlColumnsCompiler, TableAliasCompiler, SqlJoinCompiler, SqlWithRecursiveCompiler, SqlGroupByCompiler),
282
- __metadata("design:type", Object)
283
- ], SqlSelectQueryCompiler.prototype, "this", void 0);
284
- SqlSelectQueryCompiler = __decorate([
285
- NewInstance(),
286
- Inject(Container),
287
- __metadata("design:paramtypes", [Object, SelectQueryBuilder])
288
- ], SqlSelectQueryCompiler);
289
- export { SqlSelectQueryCompiler };
290
- let SqlUpdateQueryCompiler = class SqlUpdateQueryCompiler extends SqlQueryCompiler {
291
- constructor(_container, builder) {
292
- super(builder, _container);
293
- this._container = _container;
294
- }
295
- compile() {
296
- const table = this.table();
297
- const set = this.set();
298
- const where = this.where(this._builder);
299
- const bindings = [];
300
- bindings.push(...set.bindings);
301
- bindings.push(...where.bindings);
302
- return {
303
- bindings,
304
- expression: `${table} ${set.expression} WHERE ${where.expression}`,
305
- };
306
- }
307
- set() {
308
- let bindings = [];
309
- const exprr = [];
310
- for (const prop of Object.keys(this._builder.Value)) {
311
- const v = this._builder.Value[`${prop}`];
312
- exprr.push(`\`${prop}\` = ?`);
313
- bindings = bindings.concat(this.tryConvertValue(v));
314
- }
315
- return {
316
- bindings,
317
- expression: exprr.join(','),
318
- };
319
- }
320
- table() {
321
- return `UPDATE ${this._container.resolve(TableAliasCompiler).compile(this._builder)} SET`;
322
- }
323
- };
324
- __decorate([
325
- use(SqlWhereCompiler, TableAliasCompiler),
326
- __metadata("design:type", Object)
327
- ], SqlUpdateQueryCompiler.prototype, "this", void 0);
328
- SqlUpdateQueryCompiler = __decorate([
329
- NewInstance(),
330
- Inject(Container),
331
- __metadata("design:paramtypes", [Object, UpdateQueryBuilder])
332
- ], SqlUpdateQueryCompiler);
333
- export { SqlUpdateQueryCompiler };
334
- let SqlDeleteQueryCompiler = class SqlDeleteQueryCompiler extends SqlQueryCompiler {
335
- constructor(_container, builder) {
336
- super(builder, _container);
337
- }
338
- compile() {
339
- const _bindings = [];
340
- const _from = this.from();
341
- const _limit = this.limit();
342
- const _where = this.where(this._builder);
343
- let _expression = '';
344
- _expression = _from + (_where.expression ? ` WHERE ${_where.expression}` : '') + _limit.expression;
345
- _bindings.push(..._where.bindings);
346
- _bindings.push(..._limit.bindings);
347
- return {
348
- bindings: _bindings,
349
- expression: _expression.trim(),
350
- };
351
- }
352
- limit() {
353
- const compiler = this._container.resolve(LimitQueryCompiler, [this._builder]);
354
- return compiler.compile();
355
- }
356
- from() {
357
- return `DELETE FROM ${this._container.resolve(TableAliasCompiler).compile(this._builder)}`;
358
- }
359
- };
360
- __decorate([
361
- use(SqlWhereCompiler, TableAliasCompiler),
362
- __metadata("design:type", Object)
363
- ], SqlDeleteQueryCompiler.prototype, "this", void 0);
364
- SqlDeleteQueryCompiler = __decorate([
365
- NewInstance(),
366
- Inject(Container),
367
- __metadata("design:paramtypes", [Object, DeleteQueryBuilder])
368
- ], SqlDeleteQueryCompiler);
369
- export { SqlDeleteQueryCompiler };
370
- let SqlOnDuplicateQueryCompiler = class SqlOnDuplicateQueryCompiler {
371
- constructor(builder) {
372
- this._builder = builder;
373
- }
374
- compile() {
375
- const columns = this._builder
376
- .getColumnsToUpdate()
377
- .map((c) => {
378
- if (_.isString(c)) {
379
- return `\`${c}\` = ?`;
380
- }
381
- else {
382
- return c.Query;
383
- }
384
- })
385
- .join(',');
386
- const parent = this._builder.getParent();
387
- const valueMap = parent.getColumns().map((c) => c.Column);
388
- const bindings = this._builder.getColumnsToUpdate().map((c) => {
389
- if (_.isString(c)) {
390
- return parent.Values[0][valueMap.indexOf(c)];
391
- }
392
- else {
393
- return c.Bindings;
394
- }
395
- });
396
- return {
397
- bindings,
398
- expression: `ON DUPLICATE KEY UPDATE ${columns}`,
399
- };
400
- }
401
- };
402
- SqlOnDuplicateQueryCompiler = __decorate([
403
- NewInstance(),
404
- __metadata("design:paramtypes", [OnDuplicateQueryBuilder])
405
- ], SqlOnDuplicateQueryCompiler);
406
- export { SqlOnDuplicateQueryCompiler };
407
- let SqlIndexQueryCompiler = class SqlIndexQueryCompiler extends IndexQueryCompiler {
408
- constructor(builder) {
409
- super();
410
- this._builder = builder;
411
- }
412
- compile() {
413
- return {
414
- bindings: [],
415
- expression: `CREATE ${this._builder.Unique ? 'UNIQUE ' : ''}INDEX \`${this._builder.Name}\` ON \`${this._builder.Table}\` (${this._builder.Columns.map((c) => `\`${c}\``).join(',')});`,
416
- };
417
- }
418
- };
419
- SqlIndexQueryCompiler = __decorate([
420
- NewInstance(),
421
- __metadata("design:paramtypes", [IndexQueryBuilder])
422
- ], SqlIndexQueryCompiler);
423
- export { SqlIndexQueryCompiler };
424
- let SqlInsertQueryCompiler = class SqlInsertQueryCompiler extends SqlQueryCompiler {
425
- constructor(_container, builder) {
426
- super(builder, _container);
427
- }
428
- compile() {
429
- const into = this.into();
430
- const columns = this.columns();
431
- const values = this.values();
432
- const upsort = this.upsort();
433
- return {
434
- bindings: values.bindings.concat(upsort.bindings),
435
- expression: `${into} ${columns} ${values.data} ${upsort.expression}`.trim(),
436
- };
437
- }
438
- upsort() {
439
- if (this._builder.Update) {
440
- return this._container.resolve(OnDuplicateQueryCompiler, [this._builder.DuplicateQueryBuilder]).compile();
441
- }
442
- return {
443
- bindings: [],
444
- expression: '',
445
- };
446
- }
447
- values() {
448
- if (this._builder.Values.length === 0) {
449
- throw new InvalidArgument('values count invalid');
450
- }
451
- const bindings = [];
452
- let data = 'VALUES ';
453
- data += this._builder.Values.map((val) => {
454
- const toInsert = val
455
- .filter((v, i) => {
456
- // eslint-disable-next-line security/detect-object-injection
457
- const descriptor = this._builder.getColumns()[i].Descriptor;
458
- if (descriptor) {
459
- if (!descriptor.Nullable && (v === null || v === undefined) && !descriptor.AutoIncrement) {
460
- throw new InvalidArgument(`value column ${descriptor.Name} cannot be null`);
461
- }
462
- if (descriptor.AutoIncrement && descriptor.PrimaryKey)
463
- return false;
464
- }
465
- return true;
466
- })
467
- .map((v) => {
468
- if (v === undefined) {
469
- return 'DEFAULT';
470
- }
471
- if (v === null) {
472
- return 'NULL';
473
- }
474
- bindings.push(this.tryConvertValue(v));
475
- return '?';
476
- });
477
- return `(` + toInsert.join(',') + ')';
478
- }).join(',');
479
- return {
480
- bindings,
481
- data,
482
- };
483
- }
484
- columns() {
485
- const columns = this._builder
486
- .getColumns()
487
- .filter((c) => {
488
- const descriptor = c.Descriptor;
489
- if (descriptor && descriptor.AutoIncrement && descriptor.PrimaryKey)
490
- return false;
491
- return true;
492
- })
493
- .map((c) => {
494
- return c.Column;
495
- })
496
- .map((c) => {
497
- return `\`${c instanceof RawQuery ? c.Query : c}\``;
498
- });
499
- if (columns.length === 0) {
500
- throw new InvalidArgument('invalid column count');
501
- }
502
- return `(` + columns.join(',') + ')';
503
- }
504
- into() {
505
- return `INSERT${this._builder.Ignore ? ' IGNORE' : ''} INTO ${this._container.resolve(TableAliasCompiler).compile(this._builder)}`;
506
- }
507
- };
508
- __decorate([
509
- use(TableAliasCompiler),
510
- __metadata("design:type", Object)
511
- ], SqlInsertQueryCompiler.prototype, "this", void 0);
512
- SqlInsertQueryCompiler = __decorate([
513
- NewInstance(),
514
- Inject(Container),
515
- __metadata("design:paramtypes", [Object, InsertQueryBuilder])
516
- ], SqlInsertQueryCompiler);
517
- export { SqlInsertQueryCompiler };
518
- let SqlDropTableQueryCompiler = class SqlDropTableQueryCompiler extends DropTableCompiler {
519
- constructor(container, builder) {
520
- super();
521
- this.container = container;
522
- this.builder = builder;
523
- }
524
- compile() {
525
- const exists = this.builder.Exists ? ' IF EXISTS' : '';
526
- const exprr = `DROP TABLE${exists} ${this.container.resolve(TableAliasCompiler).compile(this.builder)}`;
527
- return {
528
- bindings: [],
529
- expression: exprr,
530
- };
531
- }
532
- };
533
- SqlDropTableQueryCompiler = __decorate([
534
- NewInstance(),
535
- Inject(Container),
536
- __metadata("design:paramtypes", [Container, DropTableQueryBuilder])
537
- ], SqlDropTableQueryCompiler);
538
- export { SqlDropTableQueryCompiler };
539
- let SqlAlterTableQueryCompiler = class SqlAlterTableQueryCompiler extends AlterTableQueryCompiler {
540
- constructor(container, builder) {
541
- super();
542
- this.container = container;
543
- this.builder = builder;
544
- }
545
- compile() {
546
- const _table = this._table();
547
- let _outputs = [];
548
- if (this.builder.DroppedColumns.length !== 0) {
549
- _outputs = _outputs.concat(this.builder.DroppedColumns.map((c) => {
550
- return {
551
- bindings: [],
552
- expression: `${_table} DROP COLUMN ${c}`,
553
- };
554
- }));
555
- }
556
- if (this.builder.NewTableName) {
557
- _outputs.push({
558
- bindings: [],
559
- expression: `${_table} RENAME TO ${this.container.resolve(TableAliasCompiler).compile(this.builder, this.builder.NewTableName)}`,
560
- });
561
- }
562
- if (this.builder.Columns.length !== 0) {
563
- _outputs = _outputs.concat(this.builder.Columns.map((c) => {
564
- const compiler = this.container.resolve(AlterColumnQueryCompiler, [c]).compile();
565
- return {
566
- bindings: compiler.bindings,
567
- expression: `${_table} ${compiler.expression}`,
568
- };
569
- }));
570
- }
571
- return _outputs;
572
- }
573
- _table() {
574
- return `ALTER TABLE ${this.container.resolve(TableAliasCompiler).compile(this.builder)}`;
575
- }
576
- };
577
- SqlAlterTableQueryCompiler = __decorate([
578
- NewInstance(),
579
- Inject(Container),
580
- __metadata("design:paramtypes", [Container, AlterTableQueryBuilder])
581
- ], SqlAlterTableQueryCompiler);
582
- export { SqlAlterTableQueryCompiler };
583
- let SqlTableCloneQueryCompiler = class SqlTableCloneQueryCompiler extends TableCloneQueryCompiler {
584
- constructor(container, builder) {
585
- super();
586
- this.container = container;
587
- this.builder = builder;
588
- }
589
- compile() {
590
- const _tblName = this.container.resolve(TableAliasCompiler).compile(this.builder, this.builder.CloneSource);
591
- const _table = this._table();
592
- const out1 = {
593
- bindings: [],
594
- expression: `${_table} LIKE ${_tblName}`,
595
- };
596
- if (!this.builder.Shallow) {
597
- const fOut = this.builder.Filter !== undefined
598
- ? this.builder.Filter.toDB()
599
- : {
600
- bindings: [],
601
- // if no filter is provided, copy all the data
602
- expression: `SELECT * FROM ${_tblName}`,
603
- };
604
- const fExprr = `INSERT INTO \`${this.builder.Table}\` ${fOut.expression}`;
605
- return [
606
- out1,
607
- {
608
- bindings: fOut.bindings,
609
- expression: fExprr,
610
- },
611
- ];
612
- }
613
- return [out1];
614
- }
615
- _table() {
616
- return `CREATE${this.builder.Temporary ? ' TEMPORARY ' : ' '}TABLE ${this.container.resolve(TableAliasCompiler).compile(this.builder)}`;
617
- }
618
- };
619
- __decorate([
620
- use(TableAliasCompiler),
621
- __metadata("design:type", Object)
622
- ], SqlTableCloneQueryCompiler.prototype, "this", void 0);
623
- SqlTableCloneQueryCompiler = __decorate([
624
- NewInstance(),
625
- Inject(Container),
626
- __metadata("design:paramtypes", [Container, CloneTableQueryBuilder])
627
- ], SqlTableCloneQueryCompiler);
628
- export { SqlTableCloneQueryCompiler };
629
- let SqlTruncateTableQueryCompiler = class SqlTruncateTableQueryCompiler extends TableQueryCompiler {
630
- constructor(container, builder) {
631
- super();
632
- this.container = container;
633
- this.builder = builder;
634
- }
635
- compile() {
636
- return {
637
- bindings: [],
638
- expression: `TRUNCATE TABLE ${this.container.resolve(TableAliasCompiler).compile(this.builder)}`,
639
- };
640
- }
641
- };
642
- SqlTruncateTableQueryCompiler = __decorate([
643
- NewInstance(),
644
- __metadata("design:paramtypes", [Container, TableQueryBuilder])
645
- ], SqlTruncateTableQueryCompiler);
646
- export { SqlTruncateTableQueryCompiler };
647
- let SqlTableHistoryQueryCompiler = class SqlTableHistoryQueryCompiler extends TableHistoryQueryCompiler {
648
- constructor(container, builder) {
649
- super();
650
- this.container = container;
651
- this.builder = builder;
652
- }
653
- compile() {
654
- const tblAliasCompiler = this.container.resolve(TableAliasCompiler);
655
- const hTtblName = tblAliasCompiler.compile(this.builder, `${this.builder.Table}__history`);
656
- const tblName = tblAliasCompiler.compile(this.builder, `${this.builder.Table}`);
657
- const hTriggerName = `${this.builder.Table}__history`;
658
- const tblTriggerName = this.builder.Table;
659
- const dropUnique = this.builder.Columns.filter((c) => c.Unique).map((c) => {
660
- return {
661
- bindings: [],
662
- expression: `ALTER TABLE ${hTtblName} DROP INDEX ${c.Name}`,
663
- };
664
- });
665
- const pKey = this.builder.Columns.find((c) => c.PrimaryKey);
666
- return [
667
- // clone table
668
- {
669
- bindings: [],
670
- expression: `CREATE TABLE ${hTtblName} LIKE ${tblAliasCompiler.compile(this.builder)}`,
671
- },
672
- ...dropUnique,
673
- {
674
- bindings: [],
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ /* eslint-disable @typescript-eslint/no-unsafe-call */
11
+ /* eslint-disable @typescript-eslint/no-unsafe-member-access */
12
+ /* eslint-disable @typescript-eslint/no-empty-interface */
13
+ /* eslint-disable prettier/prettier */
14
+ import { InvalidOperation, InvalidArgument } from '@spinajs/exceptions';
15
+ import { LimitBuilder, DropTableQueryBuilder, AlterColumnQueryBuilder, TableCloneQueryCompiler, OnDuplicateQueryBuilder, DeleteQueryBuilder, LimitQueryCompiler, InsertQueryBuilder, OrderByBuilder, SelectQueryBuilder, UpdateQueryBuilder, SelectQueryCompiler, TableQueryCompiler, TableQueryBuilder, ColumnQueryBuilder, ColumnQueryCompiler, RawQuery, OrderByQueryCompiler, OnDuplicateQueryCompiler, IndexQueryCompiler, IndexQueryBuilder, ForeignKeyBuilder, ForeignKeyQueryCompiler, AlterTableQueryBuilder, CloneTableQueryBuilder, AlterTableQueryCompiler, ColumnAlterationType, AlterColumnQueryCompiler, TableAliasCompiler, DropTableCompiler, DropEventQueryBuilder, TableHistoryQueryCompiler, EventQueryBuilder } from '@spinajs/orm';
16
+ import { use } from 'typescript-mix';
17
+ import { NewInstance, Inject, Container } from '@spinajs/di';
18
+ import _ from 'lodash';
19
+ let SqlTableAliasCompiler = class SqlTableAliasCompiler {
20
+ compile(builder, tbl) {
21
+ let table = '';
22
+ if (builder.Database) {
23
+ table += `\`${builder.Database}\`.`;
24
+ }
25
+ table += `\`${tbl ? tbl : builder.Table}\``;
26
+ if (builder.TableAlias) {
27
+ table += ` as \`${builder.TableAlias}\``;
28
+ }
29
+ return table;
30
+ }
31
+ };
32
+ SqlTableAliasCompiler = __decorate([
33
+ NewInstance()
34
+ ], SqlTableAliasCompiler);
35
+ export { SqlTableAliasCompiler };
36
+ let SqlQueryCompiler = class SqlQueryCompiler extends SelectQueryCompiler {
37
+ constructor(_builder, _container) {
38
+ super();
39
+ this._builder = _builder;
40
+ this._container = _container;
41
+ if (_builder === null && _builder === undefined) {
42
+ throw new InvalidArgument('builder cannot be null or undefined');
43
+ }
44
+ }
45
+ tryConvertValue(v) {
46
+ let val = v;
47
+ const converters = this._container.get('__orm_db_value_converters__');
48
+ if (converters && v && converters.has(v.constructor.name)) {
49
+ const converter = this._container.resolve(converters.get(v.constructor.name));
50
+ val = converter.toDB(val, null, null);
51
+ }
52
+ return val;
53
+ }
54
+ };
55
+ SqlQueryCompiler = __decorate([
56
+ NewInstance(),
57
+ __metadata("design:paramtypes", [Object, Object])
58
+ ], SqlQueryCompiler);
59
+ export { SqlQueryCompiler };
60
+ let SqlOrderByQueryCompiler = class SqlOrderByQueryCompiler extends OrderByQueryCompiler {
61
+ constructor(builder) {
62
+ super();
63
+ if (!builder) {
64
+ throw new InvalidOperation('builder cannot be null or undefined');
65
+ }
66
+ this._builder = builder;
67
+ }
68
+ compile() {
69
+ const sort = this._builder.getSort();
70
+ let stmt = '';
71
+ const bindings = [];
72
+ if (sort) {
73
+ stmt = ` ORDER BY ${sort.column} ${sort.order}`;
74
+ }
75
+ return {
76
+ bindings,
77
+ expression: stmt,
78
+ };
79
+ }
80
+ };
81
+ SqlOrderByQueryCompiler = __decorate([
82
+ NewInstance(),
83
+ __metadata("design:paramtypes", [OrderByBuilder])
84
+ ], SqlOrderByQueryCompiler);
85
+ export { SqlOrderByQueryCompiler };
86
+ let SqlWithRecursiveCompiler = class SqlWithRecursiveCompiler {
87
+ recursive(builder) {
88
+ const statement = builder.CteRecursive.build();
89
+ let exprr = `WITH RECURSIVE recursive_cte(${statement.Statements[0]}) AS`;
90
+ exprr += ` ( `;
91
+ exprr += statement.Statements[1];
92
+ exprr += ` UNION ALL `;
93
+ exprr += statement.Statements[2];
94
+ exprr += ` ) `;
95
+ exprr += 'SELECT * FROM recursive_cte';
96
+ return {
97
+ bindings: statement.Bindings,
98
+ expression: exprr,
99
+ };
100
+ }
101
+ };
102
+ SqlWithRecursiveCompiler = __decorate([
103
+ NewInstance()
104
+ ], SqlWithRecursiveCompiler);
105
+ export { SqlWithRecursiveCompiler };
106
+ let SqlForeignKeyQueryCompiler = class SqlForeignKeyQueryCompiler {
107
+ constructor(_builder) {
108
+ this._builder = _builder;
109
+ if (!_builder) {
110
+ throw new Error('foreign key query builder cannot be null');
111
+ }
112
+ }
113
+ compile() {
114
+ const exprr = `FOREIGN KEY (${this._builder.ForeignKeyField}) REFERENCES ${this._builder.Table}(${this._builder.PrimaryKey}) ON DELETE ${this._builder.OnDeleteAction} ON UPDATE ${this._builder.OnUpdateAction}`;
115
+ return {
116
+ bindings: [],
117
+ expression: exprr,
118
+ };
119
+ }
120
+ };
121
+ SqlForeignKeyQueryCompiler = __decorate([
122
+ NewInstance(),
123
+ __metadata("design:paramtypes", [ForeignKeyBuilder])
124
+ ], SqlForeignKeyQueryCompiler);
125
+ export { SqlForeignKeyQueryCompiler };
126
+ let SqlLimitQueryCompiler = class SqlLimitQueryCompiler extends LimitQueryCompiler {
127
+ constructor(builder) {
128
+ super();
129
+ if (!builder) {
130
+ throw new InvalidOperation('builder cannot be null or undefined');
131
+ }
132
+ this._builder = builder;
133
+ }
134
+ compile() {
135
+ const limits = this._builder.getLimits();
136
+ const bindings = [];
137
+ let stmt = '';
138
+ if (limits.limit > 0) {
139
+ stmt += ` LIMIT ?`;
140
+ bindings.push(limits.limit);
141
+ }
142
+ else {
143
+ if (limits.offset > 0) {
144
+ stmt += ` LIMIT 18446744073709551615`;
145
+ }
146
+ }
147
+ if (limits.offset > 0) {
148
+ stmt += ` OFFSET ?`;
149
+ bindings.push(limits.offset);
150
+ }
151
+ return {
152
+ bindings,
153
+ expression: stmt,
154
+ };
155
+ }
156
+ };
157
+ SqlLimitQueryCompiler = __decorate([
158
+ NewInstance(),
159
+ __metadata("design:paramtypes", [LimitBuilder])
160
+ ], SqlLimitQueryCompiler);
161
+ export { SqlLimitQueryCompiler };
162
+ let SqlGroupByCompiler = class SqlGroupByCompiler {
163
+ group(builder) {
164
+ let bindings = [];
165
+ let stmt = ' GROUP BY ';
166
+ const builds = builder.GroupStatements.map((x) => x.build());
167
+ stmt += builds.map((x) => x.Statements).join(',');
168
+ bindings = builds.map((x) => x.Bindings);
169
+ return {
170
+ bindings,
171
+ expression: builds.length != 0 ? stmt : '',
172
+ };
173
+ }
174
+ };
175
+ SqlGroupByCompiler = __decorate([
176
+ NewInstance()
177
+ ], SqlGroupByCompiler);
178
+ export { SqlGroupByCompiler };
179
+ let SqlColumnsCompiler = class SqlColumnsCompiler {
180
+ columns(builder) {
181
+ return {
182
+ bindings: [],
183
+ expression: builder
184
+ .getColumns()
185
+ .map((c) => {
186
+ return c.build().Statements[0];
187
+ })
188
+ .join(','),
189
+ };
190
+ }
191
+ };
192
+ SqlColumnsCompiler = __decorate([
193
+ NewInstance()
194
+ ], SqlColumnsCompiler);
195
+ export { SqlColumnsCompiler };
196
+ let SqlWhereCompiler = class SqlWhereCompiler {
197
+ where(builder) {
198
+ const where = [];
199
+ const bindings = [];
200
+ builder.Statements.map((x) => {
201
+ return x.build();
202
+ }).forEach((r) => {
203
+ where.push(...r.Statements);
204
+ if (Array.isArray(r.Bindings)) {
205
+ bindings.push(...r.Bindings);
206
+ }
207
+ });
208
+ return {
209
+ bindings,
210
+ expression: where.join(` ${builder.Op.toUpperCase()} `),
211
+ };
212
+ }
213
+ };
214
+ SqlWhereCompiler = __decorate([
215
+ NewInstance()
216
+ ], SqlWhereCompiler);
217
+ export { SqlWhereCompiler };
218
+ let SqlJoinCompiler = class SqlJoinCompiler {
219
+ join(builder) {
220
+ const result = builder.JoinStatements.map((s) => s.build());
221
+ return {
222
+ bindings: _.flatMap(result, (r) => r.Bindings),
223
+ expression: _.flatMap(result, (r) => r.Statements).join(' '),
224
+ };
225
+ }
226
+ };
227
+ SqlJoinCompiler = __decorate([
228
+ NewInstance()
229
+ ], SqlJoinCompiler);
230
+ export { SqlJoinCompiler };
231
+ let SqlSelectQueryCompiler = class SqlSelectQueryCompiler extends SqlQueryCompiler {
232
+ constructor(_container, builder) {
233
+ super(builder, _container);
234
+ }
235
+ compile() {
236
+ if (this._builder.CteRecursive) {
237
+ return this.recursive(this._builder);
238
+ }
239
+ const columns = this.select();
240
+ const from = this.from();
241
+ const limit = this.limit();
242
+ const sort = this.sort();
243
+ const where = this.where(this._builder);
244
+ const join = this.join(this._builder);
245
+ const group = this.group(this._builder);
246
+ const expression = columns + ' ' + from + (join.expression ? ` ${join.expression}` : '') + (where.expression ? ` WHERE ${where.expression}` : '') + group.expression + sort.expression + limit.expression;
247
+ const bindings = [];
248
+ bindings.push(...join.bindings);
249
+ bindings.push(...where.bindings);
250
+ bindings.push(...sort.bindings);
251
+ bindings.push(...limit.bindings);
252
+ bindings.push(...group.bindings);
253
+ return {
254
+ bindings,
255
+ expression: expression.trim(),
256
+ };
257
+ }
258
+ limit() {
259
+ const compiler = this._container.resolve(LimitQueryCompiler, [this._builder]);
260
+ return compiler.compile();
261
+ }
262
+ sort() {
263
+ const compiler = this._container.resolve(OrderByQueryCompiler, [this._builder]);
264
+ return compiler.compile();
265
+ }
266
+ select() {
267
+ let _stmt = 'SELECT ';
268
+ if (this._builder.IsDistinct) {
269
+ _stmt += 'DISTINCT ';
270
+ }
271
+ if (this._builder.getColumns().length === 0) {
272
+ return _stmt + '*';
273
+ }
274
+ return _stmt + this.columns(this._builder).expression;
275
+ }
276
+ from() {
277
+ return 'FROM ' + this._container.resolve(TableAliasCompiler).compile(this._builder);
278
+ }
279
+ };
280
+ __decorate([
281
+ use(SqlWhereCompiler, SqlColumnsCompiler, TableAliasCompiler, SqlJoinCompiler, SqlWithRecursiveCompiler, SqlGroupByCompiler),
282
+ __metadata("design:type", Object)
283
+ ], SqlSelectQueryCompiler.prototype, "this", void 0);
284
+ SqlSelectQueryCompiler = __decorate([
285
+ NewInstance(),
286
+ Inject(Container),
287
+ __metadata("design:paramtypes", [Object, SelectQueryBuilder])
288
+ ], SqlSelectQueryCompiler);
289
+ export { SqlSelectQueryCompiler };
290
+ let SqlUpdateQueryCompiler = class SqlUpdateQueryCompiler extends SqlQueryCompiler {
291
+ constructor(_container, builder) {
292
+ super(builder, _container);
293
+ this._container = _container;
294
+ }
295
+ compile() {
296
+ const table = this.table();
297
+ const set = this.set();
298
+ const where = this.where(this._builder);
299
+ const bindings = [];
300
+ bindings.push(...set.bindings);
301
+ bindings.push(...where.bindings);
302
+ return {
303
+ bindings,
304
+ expression: `${table} ${set.expression} WHERE ${where.expression}`,
305
+ };
306
+ }
307
+ set() {
308
+ let bindings = [];
309
+ const exprr = [];
310
+ for (const prop of Object.keys(this._builder.Value)) {
311
+ const v = this._builder.Value[`${prop}`];
312
+ exprr.push(`\`${prop}\` = ?`);
313
+ bindings = bindings.concat(this.tryConvertValue(v));
314
+ }
315
+ return {
316
+ bindings,
317
+ expression: exprr.join(','),
318
+ };
319
+ }
320
+ table() {
321
+ return `UPDATE ${this._container.resolve(TableAliasCompiler).compile(this._builder)} SET`;
322
+ }
323
+ };
324
+ __decorate([
325
+ use(SqlWhereCompiler, TableAliasCompiler),
326
+ __metadata("design:type", Object)
327
+ ], SqlUpdateQueryCompiler.prototype, "this", void 0);
328
+ SqlUpdateQueryCompiler = __decorate([
329
+ NewInstance(),
330
+ Inject(Container),
331
+ __metadata("design:paramtypes", [Object, UpdateQueryBuilder])
332
+ ], SqlUpdateQueryCompiler);
333
+ export { SqlUpdateQueryCompiler };
334
+ let SqlDeleteQueryCompiler = class SqlDeleteQueryCompiler extends SqlQueryCompiler {
335
+ constructor(_container, builder) {
336
+ super(builder, _container);
337
+ }
338
+ compile() {
339
+ const _bindings = [];
340
+ const _from = this.from();
341
+ const _limit = this.limit();
342
+ const _where = this.where(this._builder);
343
+ let _expression = '';
344
+ _expression = _from + (_where.expression ? ` WHERE ${_where.expression}` : '') + _limit.expression;
345
+ _bindings.push(..._where.bindings);
346
+ _bindings.push(..._limit.bindings);
347
+ return {
348
+ bindings: _bindings,
349
+ expression: _expression.trim(),
350
+ };
351
+ }
352
+ limit() {
353
+ const compiler = this._container.resolve(LimitQueryCompiler, [this._builder]);
354
+ return compiler.compile();
355
+ }
356
+ from() {
357
+ return `DELETE FROM ${this._container.resolve(TableAliasCompiler).compile(this._builder)}`;
358
+ }
359
+ };
360
+ __decorate([
361
+ use(SqlWhereCompiler, TableAliasCompiler),
362
+ __metadata("design:type", Object)
363
+ ], SqlDeleteQueryCompiler.prototype, "this", void 0);
364
+ SqlDeleteQueryCompiler = __decorate([
365
+ NewInstance(),
366
+ Inject(Container),
367
+ __metadata("design:paramtypes", [Object, DeleteQueryBuilder])
368
+ ], SqlDeleteQueryCompiler);
369
+ export { SqlDeleteQueryCompiler };
370
+ let SqlOnDuplicateQueryCompiler = class SqlOnDuplicateQueryCompiler {
371
+ constructor(builder) {
372
+ this._builder = builder;
373
+ }
374
+ compile() {
375
+ const columns = this._builder
376
+ .getColumnsToUpdate()
377
+ .map((c) => {
378
+ if (_.isString(c)) {
379
+ return `\`${c}\` = ?`;
380
+ }
381
+ else {
382
+ return c.Query;
383
+ }
384
+ })
385
+ .join(',');
386
+ const parent = this._builder.getParent();
387
+ const valueMap = parent.getColumns().map((c) => c.Column);
388
+ const bindings = this._builder.getColumnsToUpdate().map((c) => {
389
+ if (_.isString(c)) {
390
+ return parent.Values[0][valueMap.indexOf(c)];
391
+ }
392
+ else {
393
+ return c.Bindings;
394
+ }
395
+ });
396
+ return {
397
+ bindings,
398
+ expression: `ON DUPLICATE KEY UPDATE ${columns}`,
399
+ };
400
+ }
401
+ };
402
+ SqlOnDuplicateQueryCompiler = __decorate([
403
+ NewInstance(),
404
+ __metadata("design:paramtypes", [OnDuplicateQueryBuilder])
405
+ ], SqlOnDuplicateQueryCompiler);
406
+ export { SqlOnDuplicateQueryCompiler };
407
+ let SqlIndexQueryCompiler = class SqlIndexQueryCompiler extends IndexQueryCompiler {
408
+ constructor(builder) {
409
+ super();
410
+ this._builder = builder;
411
+ }
412
+ compile() {
413
+ return {
414
+ bindings: [],
415
+ expression: `CREATE ${this._builder.Unique ? 'UNIQUE ' : ''}INDEX \`${this._builder.Name}\` ON \`${this._builder.Table}\` (${this._builder.Columns.map((c) => `\`${c}\``).join(',')});`,
416
+ };
417
+ }
418
+ };
419
+ SqlIndexQueryCompiler = __decorate([
420
+ NewInstance(),
421
+ __metadata("design:paramtypes", [IndexQueryBuilder])
422
+ ], SqlIndexQueryCompiler);
423
+ export { SqlIndexQueryCompiler };
424
+ let SqlInsertQueryCompiler = class SqlInsertQueryCompiler extends SqlQueryCompiler {
425
+ constructor(_container, builder) {
426
+ super(builder, _container);
427
+ }
428
+ compile() {
429
+ const into = this.into();
430
+ const columns = this.columns();
431
+ const values = this.values();
432
+ const upsort = this.upsort();
433
+ return {
434
+ bindings: values.bindings.concat(upsort.bindings),
435
+ expression: `${into} ${columns} ${values.data} ${upsort.expression}`.trim(),
436
+ };
437
+ }
438
+ upsort() {
439
+ if (this._builder.Update) {
440
+ return this._container.resolve(OnDuplicateQueryCompiler, [this._builder.DuplicateQueryBuilder]).compile();
441
+ }
442
+ return {
443
+ bindings: [],
444
+ expression: '',
445
+ };
446
+ }
447
+ values() {
448
+ if (this._builder.Values.length === 0) {
449
+ throw new InvalidArgument('values count invalid');
450
+ }
451
+ const bindings = [];
452
+ let data = 'VALUES ';
453
+ data += this._builder.Values.map((val) => {
454
+ const toInsert = val
455
+ .filter((v, i) => {
456
+ // eslint-disable-next-line security/detect-object-injection
457
+ const descriptor = this._builder.getColumns()[i].Descriptor;
458
+ if (descriptor) {
459
+ if (!descriptor.Nullable && (v === null || v === undefined) && !descriptor.AutoIncrement) {
460
+ throw new InvalidArgument(`value column ${descriptor.Name} cannot be null`);
461
+ }
462
+ if (descriptor.AutoIncrement && descriptor.PrimaryKey)
463
+ return false;
464
+ }
465
+ return true;
466
+ })
467
+ .map((v) => {
468
+ if (v === undefined) {
469
+ return 'DEFAULT';
470
+ }
471
+ if (v === null) {
472
+ return 'NULL';
473
+ }
474
+ bindings.push(this.tryConvertValue(v));
475
+ return '?';
476
+ });
477
+ return `(` + toInsert.join(',') + ')';
478
+ }).join(',');
479
+ return {
480
+ bindings,
481
+ data,
482
+ };
483
+ }
484
+ columns() {
485
+ const columns = this._builder
486
+ .getColumns()
487
+ .filter((c) => {
488
+ const descriptor = c.Descriptor;
489
+ if (descriptor && descriptor.AutoIncrement && descriptor.PrimaryKey)
490
+ return false;
491
+ return true;
492
+ })
493
+ .map((c) => {
494
+ return c.Column;
495
+ })
496
+ .map((c) => {
497
+ return `\`${c instanceof RawQuery ? c.Query : c}\``;
498
+ });
499
+ if (columns.length === 0) {
500
+ throw new InvalidArgument('invalid column count');
501
+ }
502
+ return `(` + columns.join(',') + ')';
503
+ }
504
+ into() {
505
+ return `INSERT${this._builder.Ignore ? ' IGNORE' : ''} INTO ${this._container.resolve(TableAliasCompiler).compile(this._builder)}`;
506
+ }
507
+ };
508
+ __decorate([
509
+ use(TableAliasCompiler),
510
+ __metadata("design:type", Object)
511
+ ], SqlInsertQueryCompiler.prototype, "this", void 0);
512
+ SqlInsertQueryCompiler = __decorate([
513
+ NewInstance(),
514
+ Inject(Container),
515
+ __metadata("design:paramtypes", [Object, InsertQueryBuilder])
516
+ ], SqlInsertQueryCompiler);
517
+ export { SqlInsertQueryCompiler };
518
+ let SqlDropTableQueryCompiler = class SqlDropTableQueryCompiler extends DropTableCompiler {
519
+ constructor(container, builder) {
520
+ super();
521
+ this.container = container;
522
+ this.builder = builder;
523
+ }
524
+ compile() {
525
+ const exists = this.builder.Exists ? ' IF EXISTS' : '';
526
+ const exprr = `DROP TABLE${exists} ${this.container.resolve(TableAliasCompiler).compile(this.builder)}`;
527
+ return {
528
+ bindings: [],
529
+ expression: exprr,
530
+ };
531
+ }
532
+ };
533
+ SqlDropTableQueryCompiler = __decorate([
534
+ NewInstance(),
535
+ Inject(Container),
536
+ __metadata("design:paramtypes", [Container, DropTableQueryBuilder])
537
+ ], SqlDropTableQueryCompiler);
538
+ export { SqlDropTableQueryCompiler };
539
+ let SqlAlterTableQueryCompiler = class SqlAlterTableQueryCompiler extends AlterTableQueryCompiler {
540
+ constructor(container, builder) {
541
+ super();
542
+ this.container = container;
543
+ this.builder = builder;
544
+ }
545
+ compile() {
546
+ const _table = this._table();
547
+ let _outputs = [];
548
+ if (this.builder.DroppedColumns.length !== 0) {
549
+ _outputs = _outputs.concat(this.builder.DroppedColumns.map((c) => {
550
+ return {
551
+ bindings: [],
552
+ expression: `${_table} DROP COLUMN ${c}`,
553
+ };
554
+ }));
555
+ }
556
+ if (this.builder.NewTableName) {
557
+ _outputs.push({
558
+ bindings: [],
559
+ expression: `${_table} RENAME TO ${this.container.resolve(TableAliasCompiler).compile(this.builder, this.builder.NewTableName)}`,
560
+ });
561
+ }
562
+ if (this.builder.Columns.length !== 0) {
563
+ _outputs = _outputs.concat(this.builder.Columns.map((c) => {
564
+ const compiler = this.container.resolve(AlterColumnQueryCompiler, [c]).compile();
565
+ return {
566
+ bindings: compiler.bindings,
567
+ expression: `${_table} ${compiler.expression}`,
568
+ };
569
+ }));
570
+ }
571
+ return _outputs;
572
+ }
573
+ _table() {
574
+ return `ALTER TABLE ${this.container.resolve(TableAliasCompiler).compile(this.builder)}`;
575
+ }
576
+ };
577
+ SqlAlterTableQueryCompiler = __decorate([
578
+ NewInstance(),
579
+ Inject(Container),
580
+ __metadata("design:paramtypes", [Container, AlterTableQueryBuilder])
581
+ ], SqlAlterTableQueryCompiler);
582
+ export { SqlAlterTableQueryCompiler };
583
+ let SqlTableCloneQueryCompiler = class SqlTableCloneQueryCompiler extends TableCloneQueryCompiler {
584
+ constructor(container, builder) {
585
+ super();
586
+ this.container = container;
587
+ this.builder = builder;
588
+ }
589
+ compile() {
590
+ const _tblName = this.container.resolve(TableAliasCompiler).compile(this.builder, this.builder.CloneSource);
591
+ const _table = this._table();
592
+ const out1 = {
593
+ bindings: [],
594
+ expression: `${_table} LIKE ${_tblName}`,
595
+ };
596
+ if (!this.builder.Shallow) {
597
+ const fOut = this.builder.Filter !== undefined
598
+ ? this.builder.Filter.toDB()
599
+ : {
600
+ bindings: [],
601
+ // if no filter is provided, copy all the data
602
+ expression: `SELECT * FROM ${_tblName}`,
603
+ };
604
+ const fExprr = `INSERT INTO \`${this.builder.Table}\` ${fOut.expression}`;
605
+ return [
606
+ out1,
607
+ {
608
+ bindings: fOut.bindings,
609
+ expression: fExprr,
610
+ },
611
+ ];
612
+ }
613
+ return [out1];
614
+ }
615
+ _table() {
616
+ return `CREATE${this.builder.Temporary ? ' TEMPORARY ' : ' '}TABLE ${this.container.resolve(TableAliasCompiler).compile(this.builder)}`;
617
+ }
618
+ };
619
+ __decorate([
620
+ use(TableAliasCompiler),
621
+ __metadata("design:type", Object)
622
+ ], SqlTableCloneQueryCompiler.prototype, "this", void 0);
623
+ SqlTableCloneQueryCompiler = __decorate([
624
+ NewInstance(),
625
+ Inject(Container),
626
+ __metadata("design:paramtypes", [Container, CloneTableQueryBuilder])
627
+ ], SqlTableCloneQueryCompiler);
628
+ export { SqlTableCloneQueryCompiler };
629
+ let SqlTruncateTableQueryCompiler = class SqlTruncateTableQueryCompiler extends TableQueryCompiler {
630
+ constructor(container, builder) {
631
+ super();
632
+ this.container = container;
633
+ this.builder = builder;
634
+ }
635
+ compile() {
636
+ return {
637
+ bindings: [],
638
+ expression: `TRUNCATE TABLE ${this.container.resolve(TableAliasCompiler).compile(this.builder)}`,
639
+ };
640
+ }
641
+ };
642
+ SqlTruncateTableQueryCompiler = __decorate([
643
+ NewInstance(),
644
+ __metadata("design:paramtypes", [Container, TableQueryBuilder])
645
+ ], SqlTruncateTableQueryCompiler);
646
+ export { SqlTruncateTableQueryCompiler };
647
+ let SqlTableHistoryQueryCompiler = class SqlTableHistoryQueryCompiler extends TableHistoryQueryCompiler {
648
+ constructor(container, builder) {
649
+ super();
650
+ this.container = container;
651
+ this.builder = builder;
652
+ }
653
+ compile() {
654
+ const tblAliasCompiler = this.container.resolve(TableAliasCompiler);
655
+ const hTtblName = tblAliasCompiler.compile(this.builder, `${this.builder.Table}__history`);
656
+ const tblName = tblAliasCompiler.compile(this.builder, `${this.builder.Table}`);
657
+ const hTriggerName = `${this.builder.Table}__history`;
658
+ const tblTriggerName = this.builder.Table;
659
+ const dropUnique = this.builder.Columns.filter((c) => c.Unique).map((c) => {
660
+ return {
661
+ bindings: [],
662
+ expression: `ALTER TABLE ${hTtblName} DROP INDEX ${c.Name}`,
663
+ };
664
+ });
665
+ const pKey = this.builder.Columns.find((c) => c.PrimaryKey);
666
+ return [
667
+ // clone table
668
+ {
669
+ bindings: [],
670
+ expression: `CREATE TABLE ${hTtblName} LIKE ${tblAliasCompiler.compile(this.builder)}`,
671
+ },
672
+ ...dropUnique,
673
+ {
674
+ bindings: [],
675
675
  expression: `ALTER TABLE ${hTtblName}
676
676
  CHANGE COLUMN ${pKey.Name} ${pKey.Name} INT NOT NULL ,
677
- DROP PRIMARY KEY;`,
678
- },
679
- // remove primary key & add history columns
680
- {
681
- bindings: [],
682
- expression: `ALTER TABLE ${hTtblName} ADD __action__ VARCHAR(8) DEFAULT 'insert' FIRST, ADD __revision__ INT(6) NOT NULL AFTER __action__, ADD __start__ DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER __revision__, ADD __end__ DATETIME AFTER __start__`,
683
- },
684
- {
685
- bindings: [],
686
- expression: `ALTER TABLE ${hTtblName} ADD PRIMARY KEY (${pKey.Name}, __revision__)`,
687
- },
688
- {
689
- bindings: [],
677
+ DROP PRIMARY KEY;`,
678
+ },
679
+ // remove primary key & add history columns
680
+ {
681
+ bindings: [],
682
+ expression: `ALTER TABLE ${hTtblName} ADD __action__ VARCHAR(8) DEFAULT 'insert' FIRST, ADD __revision__ INT(6) NOT NULL AFTER __action__, ADD __start__ DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER __revision__, ADD __end__ DATETIME AFTER __start__`,
683
+ },
684
+ {
685
+ bindings: [],
686
+ expression: `ALTER TABLE ${hTtblName} ADD PRIMARY KEY (${pKey.Name}, __revision__)`,
687
+ },
688
+ {
689
+ bindings: [],
690
690
  expression: `DELIMITER $$
691
691
  CREATE TRIGGER ${hTriggerName}__insert_trigger BEFORE INSERT ON ${hTtblName} FOR EACH ROW
692
692
  BEGIN
693
693
  DECLARE rev INT;
694
694
  SET rev = (SELECT IFNULL(MAX(__revision__), 0) FROM ${hTtblName} WHERE Id = NEW.Id);
695
695
  SET NEW.__revision__ = rev + 1;
696
- END;`,
697
- },
698
- // create tracking triggers
699
- {
700
- bindings: [],
701
- expression: `DROP TRIGGER IF EXISTS ${tblTriggerName}__insert_trigger`,
702
- },
703
- {
704
- bindings: [],
705
- expression: `DROP TRIGGER IF EXISTS ${tblTriggerName}__update_trigger`,
706
- },
707
- {
708
- bindings: [],
709
- expression: `DROP TRIGGER IF EXISTS ${tblTriggerName}__delete_trigger`,
710
- },
711
- // insert into history table & update __end__ date for all operations
712
- {
713
- bindings: [],
696
+ END;`,
697
+ },
698
+ // create tracking triggers
699
+ {
700
+ bindings: [],
701
+ expression: `DROP TRIGGER IF EXISTS ${tblTriggerName}__insert_trigger`,
702
+ },
703
+ {
704
+ bindings: [],
705
+ expression: `DROP TRIGGER IF EXISTS ${tblTriggerName}__update_trigger`,
706
+ },
707
+ {
708
+ bindings: [],
709
+ expression: `DROP TRIGGER IF EXISTS ${tblTriggerName}__delete_trigger`,
710
+ },
711
+ // insert into history table & update __end__ date for all operations
712
+ {
713
+ bindings: [],
714
714
  expression: `DELIMITER $$
715
715
  CREATE TRIGGER ${tblTriggerName}__insert_trigger AFTER INSERT ON ${tblName} FOR EACH ROW BEGIN
716
716
  DECLARE rev INT;
717
717
  SET rev = (SELECT IFNULL(MAX(__revision__), 0) FROM ${hTtblName} WHERE Id = NEW.Id);
718
718
  UPDATE ${hTtblName} SET __end__ = NOW() WHERE Id = NEW.Id AND __revision__ = rev;
719
719
  INSERT INTO ${hTtblName} SELECT 'insert', 0, NOW(), NULL, d.* FROM ${tblName} AS d WHERE d.${pKey.Name} = NEW.${pKey.Name};
720
- END;`,
721
- },
722
- {
723
- bindings: [],
720
+ END;`,
721
+ },
722
+ {
723
+ bindings: [],
724
724
  expression: `DELIMITER $$
725
725
  CREATE TRIGGER ${tblTriggerName}__update_trigger AFTER UPDATE ON ${tblName} FOR EACH ROW BEGIN
726
726
  DECLARE rev INT;
727
727
  SET rev = (SELECT IFNULL(MAX(__revision__), 0) FROM ${hTtblName} WHERE Id = NEW.Id);
728
728
  UPDATE ${hTtblName} SET __end__ = NOW() WHERE Id = NEW.Id AND __revision__ = rev;
729
729
  INSERT INTO ${hTtblName} SELECT 'update', 0, NOW(), NULL, d.* FROM ${tblName} AS d WHERE d.${pKey.Name} = NEW.${pKey.Name};
730
- END;`,
731
- },
732
- {
733
- bindings: [],
730
+ END;`,
731
+ },
732
+ {
733
+ bindings: [],
734
734
  expression: `DELIMITER $$
735
735
  CREATE TRIGGER ${tblTriggerName}__delete_trigger BEFORE DELETE ON ${tblName} FOR EACH ROW BEGIN
736
736
  DECLARE rev INT;
737
737
  SET rev = (SELECT IFNULL(MAX(__revision__), 0) FROM ${hTtblName} WHERE Id = NEW.Id);
738
738
  UPDATE ${hTtblName} SET __end__ = NOW() WHERE Id = NEW.Id AND __revision__ = rev;
739
739
  INSERT INTO ${hTtblName} SELECT 'delete', 0, NOW(), NULL, d.* FROM ${tblName} AS d WHERE d.${pKey.Name} = NEW.${pKey.Name};
740
- END;`,
741
- },
742
- ];
743
- }
744
- };
745
- SqlTableHistoryQueryCompiler = __decorate([
746
- NewInstance(),
747
- Inject(Container),
748
- __metadata("design:paramtypes", [Container, TableQueryBuilder])
749
- ], SqlTableHistoryQueryCompiler);
750
- export { SqlTableHistoryQueryCompiler };
751
- let SqlTableQueryCompiler = class SqlTableQueryCompiler extends TableQueryCompiler {
752
- constructor(container, builder) {
753
- super();
754
- this.container = container;
755
- this.builder = builder;
756
- }
757
- compile() {
758
- const _table = this._table();
759
- const _columns = this._columns();
760
- const _keys = this._foreignKeys();
761
- const _primaryKey = this._primaryKeys();
762
- const createOutput = {
763
- bindings: [],
764
- expression: `${_table} (${_columns} ${_primaryKey ? ',' + _primaryKey : ''} ${_keys ? ',' + _keys : ''})`,
765
- };
766
- if (this.builder.TrackHistory) {
767
- const hCompiler = this.container.resolve(TableHistoryQueryCompiler, [this.builder]);
768
- return [createOutput, ...hCompiler.compile()];
769
- }
770
- else {
771
- return [createOutput];
772
- }
773
- }
774
- _columns() {
775
- return this.builder.Columns.map((c) => {
776
- return this.container.resolve(ColumnQueryCompiler, [c]).compile().expression;
777
- }).join(',');
778
- }
779
- _foreignKeys() {
780
- return this.builder.ForeignKeys.map((f) => {
781
- return this.container.resolve(ForeignKeyQueryCompiler, [f]).compile().expression;
782
- }).join(',');
783
- }
784
- _primaryKeys() {
785
- const _keys = this.builder.Columns.filter((x) => x.PrimaryKey)
786
- .map((c) => `\`${c.Name}\``)
787
- .join(',');
788
- if (!_.isEmpty(_keys)) {
789
- return `PRIMARY KEY (${_keys})`;
790
- }
791
- return '';
792
- }
793
- _table() {
794
- return `CREATE${this.builder.Temporary ? ' TEMPORARY ' : ' '}TABLE ${this.builder.CheckExists ? 'IF NOT EXISTS ' : ''}${this.container.resolve(TableAliasCompiler).compile(this.builder)}`;
795
- }
796
- };
797
- SqlTableQueryCompiler = __decorate([
798
- NewInstance(),
799
- Inject(Container),
800
- __metadata("design:paramtypes", [Container, TableQueryBuilder])
801
- ], SqlTableQueryCompiler);
802
- export { SqlTableQueryCompiler };
803
- let SqlColumnQueryCompiler = class SqlColumnQueryCompiler {
804
- constructor(builder) {
805
- this.builder = builder;
806
- this._statementsMappings = {
807
- set: (builder) => `SET(${builder.Args[0].map((a) => `'${a}\'`).join(',')})`,
808
- string: (builder) => `VARCHAR(${builder.Args[0] ? builder.Args[0] : 255})`,
809
- boolean: () => `TINYINT(1)`,
810
- float: (builder) => {
811
- const _precision = builder.Args[0] ? builder.Args[0] : 8;
812
- const _scale = builder.Args[1] ? builder.Args[1] : 2;
813
- return `${builder.Type.toUpperCase()}(${_precision},${_scale})`;
814
- },
815
- double: (builder) => this._statementsMappings.float(builder),
816
- decimal: (builder) => this._statementsMappings.float(builder),
817
- enum: (builder) => `${builder.Type.toUpperCase()}(${builder.Args[0].map((a) => `'${a}'`).join(',')})`,
818
- binary: (builder) => `BINARY(${builder.Args[0] ?? 255}`,
819
- smallint: (builder) => builder.Type.toUpperCase(),
820
- tinyint: (builder) => builder.Type.toUpperCase(),
821
- mediumint: (builder) => builder.Type.toUpperCase(),
822
- int: (builder) => builder.Type.toUpperCase(),
823
- bigint: (builder) => builder.Type.toUpperCase(),
824
- tinytext: (builder) => builder.Type.toUpperCase(),
825
- mediumtext: (builder) => builder.Type.toUpperCase(),
826
- longtext: (builder) => builder.Type.toUpperCase(),
827
- text: (builder) => builder.Type.toUpperCase(),
828
- bit: (builder) => builder.Type.toUpperCase(),
829
- date: (builder) => builder.Type.toUpperCase(),
830
- time: (builder) => builder.Type.toUpperCase(),
831
- dateTime: (builder) => builder.Type.toUpperCase(),
832
- timestamp: (builder) => builder.Type.toUpperCase(),
833
- json: (builder) => builder.Type.toUpperCase(),
834
- tinyblob: (builder) => builder.Type.toUpperCase(),
835
- mediumblob: (builder) => builder.Type.toUpperCase(),
836
- longblob: (builder) => builder.Type.toUpperCase(),
837
- // COLUMN ADDITIONA PROPS
838
- unsigned: () => 'UNSIGNED',
839
- charset: (builder) => `CHARACTER SET '${builder.Charset}'`,
840
- collation: (builder) => `COLLATE '${builder.Collation}'`,
841
- notnull: () => `NOT NULL`,
842
- default: () => this._defaultCompiler(),
843
- autoincrement: () => `AUTO_INCREMENT`,
844
- comment: (builder) => `COMMENT '${builder.Comment}'`,
845
- };
846
- if (!builder) {
847
- throw new Error('column query builder cannot be null');
848
- }
849
- }
850
- compile() {
851
- const _stmt = [];
852
- _stmt.push(`\`${this.builder.Name}\``);
853
- _stmt.push(this._statementsMappings[this.builder.Type](this.builder));
854
- if (this.builder.Unsigned) {
855
- _stmt.push(this._statementsMappings.unsigned());
856
- }
857
- if (this.builder.Charset) {
858
- _stmt.push(this._statementsMappings.charset(this.builder));
859
- }
860
- if (this.builder.Collation) {
861
- _stmt.push(this._statementsMappings.collation(this.builder));
862
- }
863
- if (this.builder.NotNull) {
864
- _stmt.push(this._statementsMappings.notnull());
865
- }
866
- if (this.builder.Default) {
867
- _stmt.push(this._statementsMappings.default());
868
- }
869
- if (this.builder.AutoIncrement) {
870
- _stmt.push(this._statementsMappings.autoincrement());
871
- }
872
- if (this.builder.Comment) {
873
- _stmt.push(this._statementsMappings.comment(this.builder));
874
- }
875
- if (this.builder.Unique) {
876
- _stmt.push('UNIQUE');
877
- }
878
- return {
879
- bindings: [],
880
- expression: _stmt.filter((x) => !_.isEmpty(x)).join(' '),
881
- };
882
- }
883
- _defaultCompiler() {
884
- let _stmt = '';
885
- if (_.isNil(this.builder.Default) || (_.isNil(this.builder.Default.Query) && _.isNil(this.builder.Default.Value))) {
886
- return _stmt;
887
- }
888
- if (_.isString(this.builder.Default.Value)) {
889
- _stmt = `DEFAULT '${this.builder.Default.Value.trim()}'`;
890
- }
891
- else if (_.isNumber(this.builder.Default.Value)) {
892
- _stmt = `DEFAULT ${this.builder.Default.Value}`;
893
- }
894
- else if (this.builder.Default.Query instanceof RawQuery) {
895
- _stmt = `DEFAULT ${this.builder.Default.Query.Query}`;
896
- }
897
- return _stmt;
898
- }
899
- };
900
- SqlColumnQueryCompiler = __decorate([
901
- NewInstance(),
902
- __metadata("design:paramtypes", [ColumnQueryBuilder])
903
- ], SqlColumnQueryCompiler);
904
- export { SqlColumnQueryCompiler };
905
- let SqlAlterColumnQueryCompiler = class SqlAlterColumnQueryCompiler extends SqlColumnQueryCompiler {
906
- constructor(builder) {
907
- super(builder);
908
- }
909
- compile() {
910
- const builder = this.builder;
911
- if (builder.AlterType === ColumnAlterationType.Rename) {
912
- const bld = this.builder;
913
- return {
914
- bindings: [],
915
- expression: `RENAME COLUMN \`${bld.OldName}\` TO \`${bld.Name}\``,
916
- };
917
- }
918
- const cDefinition = super.compile();
919
- if (builder.AlterType === ColumnAlterationType.Add) {
920
- return {
921
- bindings: cDefinition.bindings,
922
- expression: `ADD ${cDefinition.expression} ${builder.AfterColumn ? `AFTER \`${builder.AfterColumn}\`` : ''}`,
923
- };
924
- }
925
- if (builder.AlterType === ColumnAlterationType.Modify) {
926
- return {
927
- bindings: cDefinition.bindings,
928
- expression: `MODIFY ${cDefinition.expression}`,
929
- };
930
- }
931
- }
932
- };
933
- SqlAlterColumnQueryCompiler = __decorate([
934
- NewInstance(),
935
- __metadata("design:paramtypes", [AlterColumnQueryBuilder])
936
- ], SqlAlterColumnQueryCompiler);
937
- export { SqlAlterColumnQueryCompiler };
938
- let SqlEventQueryCompiler = class SqlEventQueryCompiler extends SqlQueryCompiler {
939
- constructor(container, builder) {
940
- super(builder, container);
941
- }
942
- compile() {
943
- const schedule = this._createSchedule();
944
- const action = this._action();
945
- return {
946
- bindings: action.bindings,
947
- expression: `CREATE EVENT ${this._builder.Name} ON SCHEDULE ${schedule} DO BEGIN ${action.expression} END`,
948
- };
949
- }
950
- _createSchedule() {
951
- if (this._builder.FromNowInverval) {
952
- return `AT CURRENT_TIMESTAMP + INTERVAL ${this._getInterval(this._builder.FromNowInverval)}`;
953
- }
954
- if (this._builder.At) {
955
- return `AT ${this._builder.At.toFormat(`yyyy-mm-dd HH:mm:ss`)}`;
956
- }
957
- if (this._builder.EveryInterval) {
958
- return `EVERY ${this._getInterval(this._builder.EveryInterval)}`;
959
- }
960
- }
961
- _getInterval(desc) {
962
- return Object.getOwnPropertyNames(desc)
963
- .map((x) => {
964
- if (desc[`${x}`] > 0) {
965
- return `${desc[`${x}`]} ${x.toUpperCase()}`;
966
- }
967
- return null;
968
- })
969
- .find((x) => x !== null);
970
- }
971
- _action() {
972
- if (this._builder.RawSql) {
973
- const res = this._builder.RawSql.build();
974
- return {
975
- expression: res.Statements.join(';'),
976
- bindings: res.Bindings,
977
- };
978
- }
979
- else {
980
- const qResult = this._builder.Queries.reduce((prev, curr) => {
981
- const res = curr.toDB();
982
- if (Array.isArray(res)) {
983
- res.forEach((x) => {
984
- prev.bindings = prev.bindings.concat(x.bindings);
985
- prev.expression.push(x.expression);
986
- });
987
- }
988
- else {
989
- prev.bindings = prev.bindings.concat(res.bindings);
990
- prev.expression.push(res.expression);
991
- }
992
- return prev;
993
- }, {
994
- expression: [],
995
- bindings: [],
996
- });
997
- return {
998
- expression: qResult.expression.join(';'),
999
- bindings: qResult.bindings,
1000
- };
1001
- }
1002
- }
1003
- };
1004
- SqlEventQueryCompiler = __decorate([
1005
- NewInstance(),
1006
- Inject(Container),
1007
- __metadata("design:paramtypes", [Object, EventQueryBuilder])
1008
- ], SqlEventQueryCompiler);
1009
- export { SqlEventQueryCompiler };
1010
- let SqlDropEventQueryCompiler = class SqlDropEventQueryCompiler extends SqlQueryCompiler {
1011
- constructor(container, builder) {
1012
- super(builder, container);
1013
- }
1014
- compile() {
1015
- return {
1016
- bindings: [],
1017
- expression: `DROP EVENT IF EXISTS ${this._builder.Name}`,
1018
- };
1019
- }
1020
- };
1021
- SqlDropEventQueryCompiler = __decorate([
1022
- NewInstance(),
1023
- Inject(Container),
1024
- __metadata("design:paramtypes", [Object, DropEventQueryBuilder])
1025
- ], SqlDropEventQueryCompiler);
1026
- export { SqlDropEventQueryCompiler };
740
+ END;`,
741
+ },
742
+ ];
743
+ }
744
+ };
745
+ SqlTableHistoryQueryCompiler = __decorate([
746
+ NewInstance(),
747
+ Inject(Container),
748
+ __metadata("design:paramtypes", [Container, TableQueryBuilder])
749
+ ], SqlTableHistoryQueryCompiler);
750
+ export { SqlTableHistoryQueryCompiler };
751
+ let SqlTableQueryCompiler = class SqlTableQueryCompiler extends TableQueryCompiler {
752
+ constructor(container, builder) {
753
+ super();
754
+ this.container = container;
755
+ this.builder = builder;
756
+ }
757
+ compile() {
758
+ const _table = this._table();
759
+ const _columns = this._columns();
760
+ const _keys = this._foreignKeys();
761
+ const _primaryKey = this._primaryKeys();
762
+ const createOutput = {
763
+ bindings: [],
764
+ expression: `${_table} (${_columns} ${_primaryKey ? ',' + _primaryKey : ''} ${_keys ? ',' + _keys : ''})`,
765
+ };
766
+ if (this.builder.TrackHistory) {
767
+ const hCompiler = this.container.resolve(TableHistoryQueryCompiler, [this.builder]);
768
+ return [createOutput, ...hCompiler.compile()];
769
+ }
770
+ else {
771
+ return [createOutput];
772
+ }
773
+ }
774
+ _columns() {
775
+ return this.builder.Columns.map((c) => {
776
+ return this.container.resolve(ColumnQueryCompiler, [c]).compile().expression;
777
+ }).join(',');
778
+ }
779
+ _foreignKeys() {
780
+ return this.builder.ForeignKeys.map((f) => {
781
+ return this.container.resolve(ForeignKeyQueryCompiler, [f]).compile().expression;
782
+ }).join(',');
783
+ }
784
+ _primaryKeys() {
785
+ const _keys = this.builder.Columns.filter((x) => x.PrimaryKey)
786
+ .map((c) => `\`${c.Name}\``)
787
+ .join(',');
788
+ if (!_.isEmpty(_keys)) {
789
+ return `PRIMARY KEY (${_keys})`;
790
+ }
791
+ return '';
792
+ }
793
+ _table() {
794
+ return `CREATE${this.builder.Temporary ? ' TEMPORARY ' : ' '}TABLE ${this.builder.CheckExists ? 'IF NOT EXISTS ' : ''}${this.container.resolve(TableAliasCompiler).compile(this.builder)}`;
795
+ }
796
+ };
797
+ SqlTableQueryCompiler = __decorate([
798
+ NewInstance(),
799
+ Inject(Container),
800
+ __metadata("design:paramtypes", [Container, TableQueryBuilder])
801
+ ], SqlTableQueryCompiler);
802
+ export { SqlTableQueryCompiler };
803
+ let SqlColumnQueryCompiler = class SqlColumnQueryCompiler {
804
+ constructor(builder) {
805
+ this.builder = builder;
806
+ this._statementsMappings = {
807
+ set: (builder) => `SET(${builder.Args[0].map((a) => `'${a}\'`).join(',')})`,
808
+ string: (builder) => `VARCHAR(${builder.Args[0] ? builder.Args[0] : 255})`,
809
+ boolean: () => `TINYINT(1)`,
810
+ float: (builder) => {
811
+ const _precision = builder.Args[0] ? builder.Args[0] : 8;
812
+ const _scale = builder.Args[1] ? builder.Args[1] : 2;
813
+ return `${builder.Type.toUpperCase()}(${_precision},${_scale})`;
814
+ },
815
+ double: (builder) => this._statementsMappings.float(builder),
816
+ decimal: (builder) => this._statementsMappings.float(builder),
817
+ enum: (builder) => `${builder.Type.toUpperCase()}(${builder.Args[0].map((a) => `'${a}'`).join(',')})`,
818
+ binary: (builder) => `BINARY(${builder.Args[0] ?? 255}`,
819
+ smallint: (builder) => builder.Type.toUpperCase(),
820
+ tinyint: (builder) => builder.Type.toUpperCase(),
821
+ mediumint: (builder) => builder.Type.toUpperCase(),
822
+ int: (builder) => builder.Type.toUpperCase(),
823
+ bigint: (builder) => builder.Type.toUpperCase(),
824
+ tinytext: (builder) => builder.Type.toUpperCase(),
825
+ mediumtext: (builder) => builder.Type.toUpperCase(),
826
+ longtext: (builder) => builder.Type.toUpperCase(),
827
+ text: (builder) => builder.Type.toUpperCase(),
828
+ bit: (builder) => builder.Type.toUpperCase(),
829
+ date: (builder) => builder.Type.toUpperCase(),
830
+ time: (builder) => builder.Type.toUpperCase(),
831
+ dateTime: (builder) => builder.Type.toUpperCase(),
832
+ timestamp: (builder) => builder.Type.toUpperCase(),
833
+ json: (builder) => builder.Type.toUpperCase(),
834
+ tinyblob: (builder) => builder.Type.toUpperCase(),
835
+ mediumblob: (builder) => builder.Type.toUpperCase(),
836
+ longblob: (builder) => builder.Type.toUpperCase(),
837
+ // COLUMN ADDITIONA PROPS
838
+ unsigned: () => 'UNSIGNED',
839
+ charset: (builder) => `CHARACTER SET '${builder.Charset}'`,
840
+ collation: (builder) => `COLLATE '${builder.Collation}'`,
841
+ notnull: () => `NOT NULL`,
842
+ default: () => this._defaultCompiler(),
843
+ autoincrement: () => `AUTO_INCREMENT`,
844
+ comment: (builder) => `COMMENT '${builder.Comment}'`,
845
+ };
846
+ if (!builder) {
847
+ throw new Error('column query builder cannot be null');
848
+ }
849
+ }
850
+ compile() {
851
+ const _stmt = [];
852
+ _stmt.push(`\`${this.builder.Name}\``);
853
+ _stmt.push(this._statementsMappings[this.builder.Type](this.builder));
854
+ if (this.builder.Unsigned) {
855
+ _stmt.push(this._statementsMappings.unsigned());
856
+ }
857
+ if (this.builder.Charset) {
858
+ _stmt.push(this._statementsMappings.charset(this.builder));
859
+ }
860
+ if (this.builder.Collation) {
861
+ _stmt.push(this._statementsMappings.collation(this.builder));
862
+ }
863
+ if (this.builder.NotNull) {
864
+ _stmt.push(this._statementsMappings.notnull());
865
+ }
866
+ if (this.builder.Default) {
867
+ _stmt.push(this._statementsMappings.default());
868
+ }
869
+ if (this.builder.AutoIncrement) {
870
+ _stmt.push(this._statementsMappings.autoincrement());
871
+ }
872
+ if (this.builder.Comment) {
873
+ _stmt.push(this._statementsMappings.comment(this.builder));
874
+ }
875
+ if (this.builder.Unique) {
876
+ _stmt.push('UNIQUE');
877
+ }
878
+ return {
879
+ bindings: [],
880
+ expression: _stmt.filter((x) => !_.isEmpty(x)).join(' '),
881
+ };
882
+ }
883
+ _defaultCompiler() {
884
+ let _stmt = '';
885
+ if (_.isNil(this.builder.Default) || (_.isNil(this.builder.Default.Query) && _.isNil(this.builder.Default.Value))) {
886
+ return _stmt;
887
+ }
888
+ if (_.isString(this.builder.Default.Value)) {
889
+ _stmt = `DEFAULT '${this.builder.Default.Value.trim()}'`;
890
+ }
891
+ else if (_.isNumber(this.builder.Default.Value)) {
892
+ _stmt = `DEFAULT ${this.builder.Default.Value}`;
893
+ }
894
+ else if (this.builder.Default.Query instanceof RawQuery) {
895
+ _stmt = `DEFAULT ${this.builder.Default.Query.Query}`;
896
+ }
897
+ return _stmt;
898
+ }
899
+ };
900
+ SqlColumnQueryCompiler = __decorate([
901
+ NewInstance(),
902
+ __metadata("design:paramtypes", [ColumnQueryBuilder])
903
+ ], SqlColumnQueryCompiler);
904
+ export { SqlColumnQueryCompiler };
905
+ let SqlAlterColumnQueryCompiler = class SqlAlterColumnQueryCompiler extends SqlColumnQueryCompiler {
906
+ constructor(builder) {
907
+ super(builder);
908
+ }
909
+ compile() {
910
+ const builder = this.builder;
911
+ if (builder.AlterType === ColumnAlterationType.Rename) {
912
+ const bld = this.builder;
913
+ return {
914
+ bindings: [],
915
+ expression: `RENAME COLUMN \`${bld.OldName}\` TO \`${bld.Name}\``,
916
+ };
917
+ }
918
+ const cDefinition = super.compile();
919
+ if (builder.AlterType === ColumnAlterationType.Add) {
920
+ return {
921
+ bindings: cDefinition.bindings,
922
+ expression: `ADD ${cDefinition.expression} ${builder.AfterColumn ? `AFTER \`${builder.AfterColumn}\`` : ''}`,
923
+ };
924
+ }
925
+ if (builder.AlterType === ColumnAlterationType.Modify) {
926
+ return {
927
+ bindings: cDefinition.bindings,
928
+ expression: `MODIFY ${cDefinition.expression}`,
929
+ };
930
+ }
931
+ }
932
+ };
933
+ SqlAlterColumnQueryCompiler = __decorate([
934
+ NewInstance(),
935
+ __metadata("design:paramtypes", [AlterColumnQueryBuilder])
936
+ ], SqlAlterColumnQueryCompiler);
937
+ export { SqlAlterColumnQueryCompiler };
938
+ let SqlEventQueryCompiler = class SqlEventQueryCompiler extends SqlQueryCompiler {
939
+ constructor(container, builder) {
940
+ super(builder, container);
941
+ }
942
+ compile() {
943
+ const schedule = this._createSchedule();
944
+ const action = this._action();
945
+ return {
946
+ bindings: action.bindings,
947
+ expression: `CREATE EVENT ${this._builder.Name} ON SCHEDULE ${schedule} DO BEGIN ${action.expression} END`,
948
+ };
949
+ }
950
+ _createSchedule() {
951
+ if (this._builder.FromNowInverval) {
952
+ return `AT CURRENT_TIMESTAMP + INTERVAL ${this._getInterval(this._builder.FromNowInverval)}`;
953
+ }
954
+ if (this._builder.At) {
955
+ return `AT ${this._builder.At.toFormat(`yyyy-mm-dd HH:mm:ss`)}`;
956
+ }
957
+ if (this._builder.EveryInterval) {
958
+ return `EVERY ${this._getInterval(this._builder.EveryInterval)}`;
959
+ }
960
+ }
961
+ _getInterval(desc) {
962
+ return Object.getOwnPropertyNames(desc)
963
+ .map((x) => {
964
+ if (desc[`${x}`] > 0) {
965
+ return `${desc[`${x}`]} ${x.toUpperCase()}`;
966
+ }
967
+ return null;
968
+ })
969
+ .find((x) => x !== null);
970
+ }
971
+ _action() {
972
+ if (this._builder.RawSql) {
973
+ const res = this._builder.RawSql.build();
974
+ return {
975
+ expression: res.Statements.join(';'),
976
+ bindings: res.Bindings,
977
+ };
978
+ }
979
+ else {
980
+ const qResult = this._builder.Queries.reduce((prev, curr) => {
981
+ const res = curr.toDB();
982
+ if (Array.isArray(res)) {
983
+ res.forEach((x) => {
984
+ prev.bindings = prev.bindings.concat(x.bindings);
985
+ prev.expression.push(x.expression);
986
+ });
987
+ }
988
+ else {
989
+ prev.bindings = prev.bindings.concat(res.bindings);
990
+ prev.expression.push(res.expression);
991
+ }
992
+ return prev;
993
+ }, {
994
+ expression: [],
995
+ bindings: [],
996
+ });
997
+ return {
998
+ expression: qResult.expression.join(';'),
999
+ bindings: qResult.bindings,
1000
+ };
1001
+ }
1002
+ }
1003
+ };
1004
+ SqlEventQueryCompiler = __decorate([
1005
+ NewInstance(),
1006
+ Inject(Container),
1007
+ __metadata("design:paramtypes", [Object, EventQueryBuilder])
1008
+ ], SqlEventQueryCompiler);
1009
+ export { SqlEventQueryCompiler };
1010
+ let SqlDropEventQueryCompiler = class SqlDropEventQueryCompiler extends SqlQueryCompiler {
1011
+ constructor(container, builder) {
1012
+ super(builder, container);
1013
+ }
1014
+ compile() {
1015
+ return {
1016
+ bindings: [],
1017
+ expression: `DROP EVENT IF EXISTS ${this._builder.Name}`,
1018
+ };
1019
+ }
1020
+ };
1021
+ SqlDropEventQueryCompiler = __decorate([
1022
+ NewInstance(),
1023
+ Inject(Container),
1024
+ __metadata("design:paramtypes", [Object, DropEventQueryBuilder])
1025
+ ], SqlDropEventQueryCompiler);
1026
+ export { SqlDropEventQueryCompiler };
1027
1027
  //# sourceMappingURL=compilers.js.map