tspace-mysql 1.9.0 → 1.9.1-beta.2

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.
Files changed (118) hide show
  1. package/README.md +4580 -133
  2. package/dist/lib/config/index.d.ts +2 -2
  3. package/dist/lib/config/index.js +24 -16
  4. package/dist/lib/config/index.js.map +1 -1
  5. package/dist/lib/constants/index.d.ts +10 -1
  6. package/dist/lib/constants/index.js +11 -2
  7. package/dist/lib/constants/index.js.map +1 -1
  8. package/dist/lib/core/Abstracts/AbstractBuilder.d.ts +27 -23
  9. package/dist/lib/core/Abstracts/AbstractBuilder.js +11 -13
  10. package/dist/lib/core/Abstracts/AbstractBuilder.js.map +1 -1
  11. package/dist/lib/core/Abstracts/AbstractDB.d.ts +5 -2
  12. package/dist/lib/core/Abstracts/AbstractDB.js.map +1 -1
  13. package/dist/lib/core/Abstracts/AbstractModel.d.ts +7 -2
  14. package/dist/lib/core/Abstracts/AbstractModel.js.map +1 -1
  15. package/dist/lib/core/Abstracts/AbstractView.js.map +1 -1
  16. package/dist/lib/core/Blueprint.d.ts +37 -17
  17. package/dist/lib/core/Blueprint.js +38 -14
  18. package/dist/lib/core/Blueprint.js.map +1 -1
  19. package/dist/lib/core/Builder.d.ts +314 -42
  20. package/dist/lib/core/Builder.js +686 -391
  21. package/dist/lib/core/Builder.js.map +1 -1
  22. package/dist/lib/core/Cache/DBCache.js +19 -20
  23. package/dist/lib/core/Cache/DBCache.js.map +1 -1
  24. package/dist/lib/core/Cache/MemoryCache.js +3 -3
  25. package/dist/lib/core/Cache/MemoryCache.js.map +1 -1
  26. package/dist/lib/core/Cache/RedisCache.js +27 -17
  27. package/dist/lib/core/Cache/RedisCache.js.map +1 -1
  28. package/dist/lib/core/Cache/index.js +37 -17
  29. package/dist/lib/core/Cache/index.js.map +1 -1
  30. package/dist/lib/core/Contracts/AlterTable.d.ts +152 -0
  31. package/dist/lib/core/Contracts/AlterTable.js +243 -0
  32. package/dist/lib/core/Contracts/AlterTable.js.map +1 -0
  33. package/dist/lib/core/Contracts/Audit.d.ts +1 -1
  34. package/dist/lib/core/Contracts/Audit.js +2 -5
  35. package/dist/lib/core/Contracts/Audit.js.map +1 -1
  36. package/dist/lib/core/Contracts/Logger.d.ts +1 -1
  37. package/dist/lib/core/Contracts/Logger.js.map +1 -1
  38. package/dist/lib/core/DB.d.ts +103 -11
  39. package/dist/lib/core/DB.js +158 -32
  40. package/dist/lib/core/DB.js.map +1 -1
  41. package/dist/lib/core/Decorator.d.ts +144 -16
  42. package/dist/lib/core/Decorator.js +156 -14
  43. package/dist/lib/core/Decorator.js.map +1 -1
  44. package/dist/lib/core/Driver/index.d.ts +50 -14
  45. package/dist/lib/core/Driver/index.js +13 -9
  46. package/dist/lib/core/Driver/index.js.map +1 -1
  47. package/dist/lib/core/Driver/mariadb/MariadbDriver.js +84 -29
  48. package/dist/lib/core/Driver/mariadb/MariadbDriver.js.map +1 -1
  49. package/dist/lib/core/Driver/mariadb/MariadbQueryBuilder.d.ts +48 -12
  50. package/dist/lib/core/Driver/mariadb/MariadbQueryBuilder.js +189 -28
  51. package/dist/lib/core/Driver/mariadb/MariadbQueryBuilder.js.map +1 -1
  52. package/dist/lib/core/Driver/mongodb/MongodbDriver.d.ts +24 -0
  53. package/dist/lib/core/Driver/mongodb/MongodbDriver.js +261 -0
  54. package/dist/lib/core/Driver/mongodb/MongodbDriver.js.map +1 -0
  55. package/dist/lib/core/Driver/mongodb/MongodbQueryBuilder.d.ts +141 -0
  56. package/dist/lib/core/Driver/mongodb/MongodbQueryBuilder.js +571 -0
  57. package/dist/lib/core/Driver/mongodb/MongodbQueryBuilder.js.map +1 -0
  58. package/dist/lib/core/Driver/mysql/MysqlDriver.js +115 -97
  59. package/dist/lib/core/Driver/mysql/MysqlDriver.js.map +1 -1
  60. package/dist/lib/core/Driver/mysql/MysqlQueryBuilder.d.ts +48 -12
  61. package/dist/lib/core/Driver/mysql/MysqlQueryBuilder.js +189 -28
  62. package/dist/lib/core/Driver/mysql/MysqlQueryBuilder.js.map +1 -1
  63. package/dist/lib/core/Driver/postgres/PostgresDriver.js +106 -73
  64. package/dist/lib/core/Driver/postgres/PostgresDriver.js.map +1 -1
  65. package/dist/lib/core/Driver/postgres/PostgresQueryBuilder.d.ts +53 -12
  66. package/dist/lib/core/Driver/postgres/PostgresQueryBuilder.js +318 -48
  67. package/dist/lib/core/Driver/postgres/PostgresQueryBuilder.js.map +1 -1
  68. package/dist/lib/core/Driver/sqlite/SqliteDriver.d.ts +21 -0
  69. package/dist/lib/core/Driver/sqlite/SqliteDriver.js +213 -0
  70. package/dist/lib/core/Driver/sqlite/SqliteDriver.js.map +1 -0
  71. package/dist/lib/core/Driver/sqlite/SqliteQueryBuilder.d.ts +146 -0
  72. package/dist/lib/core/Driver/sqlite/SqliteQueryBuilder.js +705 -0
  73. package/dist/lib/core/Driver/sqlite/SqliteQueryBuilder.js.map +1 -0
  74. package/dist/lib/core/Join.d.ts +63 -5
  75. package/dist/lib/core/Join.js +92 -15
  76. package/dist/lib/core/Join.js.map +1 -1
  77. package/dist/lib/core/JoinModel.d.ts +65 -9
  78. package/dist/lib/core/JoinModel.js +81 -52
  79. package/dist/lib/core/JoinModel.js.map +1 -1
  80. package/dist/lib/core/Meta.d.ts +22 -16
  81. package/dist/lib/core/Meta.js +28 -21
  82. package/dist/lib/core/Meta.js.map +1 -1
  83. package/dist/lib/core/Model.d.ts +644 -134
  84. package/dist/lib/core/Model.js +1361 -631
  85. package/dist/lib/core/Model.js.map +1 -1
  86. package/dist/lib/{tools/index.d.ts → core/Package.d.ts} +11 -3
  87. package/dist/lib/{tools/index.js → core/Package.js} +20 -7
  88. package/dist/lib/core/Package.js.map +1 -0
  89. package/dist/lib/core/Pool.js +42 -30
  90. package/dist/lib/core/Pool.js.map +1 -1
  91. package/dist/lib/core/Queue.d.ts +249 -0
  92. package/dist/lib/core/Queue.js +726 -0
  93. package/dist/lib/core/Queue.js.map +1 -0
  94. package/dist/lib/core/RelationManager.d.ts +4 -4
  95. package/dist/lib/core/RelationManager.js +168 -41
  96. package/dist/lib/core/RelationManager.js.map +1 -1
  97. package/dist/lib/core/Repository.d.ts +73 -207
  98. package/dist/lib/core/Repository.js +122 -234
  99. package/dist/lib/core/Repository.js.map +1 -1
  100. package/dist/lib/core/Schema.d.ts +211 -1
  101. package/dist/lib/core/Schema.js +370 -65
  102. package/dist/lib/core/Schema.js.map +1 -1
  103. package/dist/lib/core/StateManager.d.ts +31 -12
  104. package/dist/lib/core/StateManager.js +11 -5
  105. package/dist/lib/core/StateManager.js.map +1 -1
  106. package/dist/lib/core/UtilityTypes.d.ts +103 -81
  107. package/dist/lib/core/UtilityTypes.js.map +1 -1
  108. package/dist/lib/core/index.d.ts +4 -0
  109. package/dist/lib/core/index.js +6 -2
  110. package/dist/lib/core/index.js.map +1 -1
  111. package/dist/lib/types/decorator/index.d.ts +1 -1
  112. package/dist/lib/types/index.d.ts +120 -30
  113. package/dist/lib/types/repository/index.d.ts +68 -37
  114. package/dist/lib/utils/index.d.ts +13 -2
  115. package/dist/lib/utils/index.js +81 -2
  116. package/dist/lib/utils/index.js.map +1 -1
  117. package/package.json +14 -6
  118. package/dist/lib/tools/index.js.map +0 -1
@@ -2,8 +2,9 @@ import { QueryBuilder } from "..";
2
2
  import { Blueprint } from "../../Blueprint";
3
3
  import { StateManager } from "../../StateManager";
4
4
  export declare class PostgresQueryBuilder extends QueryBuilder {
5
+ private _returnStart;
5
6
  constructor(state: StateManager);
6
- select: () => string;
7
+ select: (selectColumns?: string[]) => string;
7
8
  insert(): string;
8
9
  update(): string;
9
10
  remove(): string;
@@ -21,6 +22,11 @@ export declare class PostgresQueryBuilder extends QueryBuilder {
21
22
  database: string;
22
23
  table: string;
23
24
  }): string;
25
+ hasTable({ database, table }: {
26
+ database: string;
27
+ table: string;
28
+ }): string;
29
+ createDatabase(database: string): string;
24
30
  createTable({ database, table, schema, }: {
25
31
  database: string;
26
32
  table: string;
@@ -52,7 +58,7 @@ export declare class PostgresQueryBuilder extends QueryBuilder {
52
58
  table: string;
53
59
  constraint: string;
54
60
  }): string;
55
- createFK({ table, tableRef, key, constraint, foreign, }: {
61
+ addFK({ table, tableRef, key, constraint, foreign, }: {
56
62
  table: string;
57
63
  tableRef: string;
58
64
  key: string;
@@ -71,15 +77,44 @@ export declare class PostgresQueryBuilder extends QueryBuilder {
71
77
  database: string;
72
78
  table: string;
73
79
  }): string;
74
- hasIndex({ database, table, index, }: {
80
+ hasIndex({ database, table, name, }: {
75
81
  database: string;
76
82
  table: string;
77
- index: string;
83
+ name: string;
78
84
  }): string;
79
- createIndex({ table, index, key, }: {
85
+ addIndex({ table, name, columns, }: {
86
+ table: string;
87
+ name: string;
88
+ columns: string[];
89
+ }): string;
90
+ dropIndex({ table, name, }: {
91
+ table: string;
92
+ name: string;
93
+ }): string;
94
+ hasUnique({ database, table, name, }: {
95
+ database: string;
96
+ table: string;
97
+ name: string;
98
+ }): string;
99
+ addUnique({ table, name, columns }: {
100
+ table: string;
101
+ name: string;
102
+ columns: string[];
103
+ }): string;
104
+ dropUnique({ table, name, }: {
105
+ table: string;
106
+ name: string;
107
+ }): string;
108
+ hasPrimaryKey({ database, table, }: {
109
+ database: string;
110
+ table: string;
111
+ }): string;
112
+ addPrimaryKey({ table, columns, }: {
113
+ table: string;
114
+ columns: string[];
115
+ }): string;
116
+ dropPrimaryKey({ table }: {
80
117
  table: string;
81
- index: string;
82
- key: string;
83
118
  }): string;
84
119
  getDatabase(database: string): string;
85
120
  dropDatabase(database: string): string;
@@ -88,13 +123,15 @@ export declare class PostgresQueryBuilder extends QueryBuilder {
88
123
  truncate(table: string): string;
89
124
  sleep(second: number): string;
90
125
  format(sql: (string | null)[] | string): string;
126
+ getActiveConnections(): string;
127
+ getMaxConnections(): string;
128
+ lockTable(mode: 'WRITE' | 'READ'): string;
129
+ unlockTable(): null;
91
130
  protected bindJoin(values: string[]): string | null;
92
- protected bindWhere(values: string[]): string | null;
131
+ protected bindWhere(values: any[]): string | null;
93
132
  protected bindOrderBy(values: string[]): string | null;
94
133
  protected bindGroupBy(values: string[]): string | null;
95
- protected bindSelect(values: string[], { distinct }?: {
96
- distinct?: string;
97
- }): string;
134
+ protected bindSelect(values: string[]): string;
98
135
  protected bindFrom({ from, alias, rawAlias, }: {
99
136
  from: string[];
100
137
  alias: string | null;
@@ -103,6 +140,10 @@ export declare class PostgresQueryBuilder extends QueryBuilder {
103
140
  protected bindLimit(limit: string | number | null): string;
104
141
  protected bindOffset(offset: string | number | null): string;
105
142
  protected bindHaving(having: string | null): string;
106
- protected bindRowLevelLock(mode: "FOR_UPDATE" | "FOR_SHARE" | null): any;
143
+ protected bindRowLevelLock(rowLevelLock: {
144
+ mode: "FOR_UPDATE" | "FOR_SHARE" | null;
145
+ skipLocked: boolean | null;
146
+ nowait: boolean | null;
147
+ }): any;
107
148
  private _formatedTypeAndAttributes;
108
149
  }
@@ -1,18 +1,20 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PostgresQueryBuilder = void 0;
4
+ const pluralize_1 = require("pluralize");
4
5
  const __1 = require("..");
5
6
  class PostgresQueryBuilder extends __1.QueryBuilder {
7
+ _returnStart = 'RETURNING *';
6
8
  constructor(state) {
7
9
  super(state);
8
10
  }
9
- select = () => {
11
+ select = (selectColumns) => {
10
12
  const combindSQL = [
11
- this.bindSelect(this.$state.get("SELECT")),
13
+ this.bindSelect(selectColumns ?? this.$state.get("SELECT")),
12
14
  this.bindFrom({
13
15
  from: !this.$state.get("FROM").length
14
- ? [this.$state.get("TABLE_NAME")].map(String)
15
- : [this.$state.get("TABLE_NAME"), ...this.$state.get("FROM")].map(String),
16
+ ? [this.$state.get("TABLE_NAME")].filter(Boolean).map(String)
17
+ : [this.$state.get("TABLE_NAME"), ...this.$state.get("FROM")].filter(Boolean).map(String),
16
18
  alias: this.$state.get("ALIAS"),
17
19
  rawAlias: this.$state.get("RAW_ALIAS"),
18
20
  }),
@@ -58,24 +60,28 @@ class PostgresQueryBuilder extends __1.QueryBuilder {
58
60
  columns,
59
61
  this.$constants("VALUES"),
60
62
  values,
61
- "RETURNING *"
63
+ this._returnStart
62
64
  ]);
63
65
  return sql;
64
66
  }
65
67
  update() {
66
- const query = this.$state.get("UPDATE");
67
- if (query == null) {
68
+ if (this.$state.get("UPDATE") == null) {
68
69
  return '';
69
70
  }
71
+ const primaryKey = `${this.$state.get("TABLE_NAME")}.\`${this.$state.get("PRIMARY_KEY")}\``;
70
72
  const sql = this.format([
71
- `${this.$constants("UPDATE")}`,
72
- `${this.$state.get("TABLE_NAME")}`,
73
- `${this.$constants("SET")}`,
74
- `${query}`,
75
- this.bindWhere(this.$state.get("WHERE")),
76
- this.bindOrderBy(this.$state.get("ORDER_BY")),
77
- /* this.bindLimit(this.$state.get("LIMIT")) postgres does't support limit when update */
78
- "RETURNING *",
73
+ this.$constants("UPDATE"),
74
+ this.$state.get("TABLE_NAME"),
75
+ this.$constants("SET"),
76
+ this.$state.get("UPDATE"),
77
+ this.bindWhere([
78
+ {
79
+ column: `${primaryKey}`,
80
+ operator: `${this.$constants('IN')}`,
81
+ value: `(${this.select([primaryKey])})`
82
+ }
83
+ ]),
84
+ this._returnStart
79
85
  ]);
80
86
  return sql;
81
87
  }
@@ -84,13 +90,19 @@ class PostgresQueryBuilder extends __1.QueryBuilder {
84
90
  if (!query) {
85
91
  throw new Error("Bad query builder: DELETE state not found. Please check your query configuration.");
86
92
  }
93
+ const primaryKey = `${this.$state.get("TABLE_NAME")}.\`${this.$state.get("PRIMARY_KEY")}\``;
87
94
  let sql = this.format([
88
95
  this.$constants("DELETE"),
89
96
  this.$constants("FROM"),
90
97
  this.$state.get("TABLE_NAME"),
91
- this.bindWhere(this.$state.get("WHERE")),
92
- this.bindOrderBy(this.$state.get("ORDER_BY")),
93
- "RETURNING *",
98
+ this.bindWhere([
99
+ {
100
+ column: `${primaryKey}`,
101
+ operator: `${this.$constants('IN')}`,
102
+ value: `(${this.select([primaryKey])})`
103
+ }
104
+ ]),
105
+ this._returnStart
94
106
  ]);
95
107
  if (this.$state.get("CTE").length) {
96
108
  sql = `${this.$constants("WITH")} ${this.$state
@@ -139,12 +151,24 @@ class PostgresQueryBuilder extends __1.QueryBuilder {
139
151
  WHEN column_default LIKE 'nextval(%' THEN 'PRI'
140
152
  ELSE NULL
141
153
  END AS "Key",
154
+
142
155
  CASE
156
+ WHEN DATA_TYPE = 'USER-DEFINED' THEN
157
+ 'enum(' ||
158
+ (
159
+ SELECT string_agg(quote_literal(e.enumlabel), ',')
160
+ FROM PG_TYPE t
161
+ JOIN PG_ENUM e ON t.oid = e.enumtypid
162
+ WHERE t.typname = udt_name
163
+ )
164
+ || ')'
165
+
143
166
  WHEN
144
167
  DATA_TYPE = 'character varying' AND CHARACTER_MAXIMUM_LENGTH IS NOT NULL
145
168
  THEN DATA_TYPE || '(' || CHARACTER_MAXIMUM_LENGTH || ')'
146
169
  ELSE DATA_TYPE
147
170
  END AS "Type",
171
+
148
172
  IS_NULLABLE as "Nullable",
149
173
 
150
174
  CASE
@@ -203,6 +227,28 @@ class PostgresQueryBuilder extends __1.QueryBuilder {
203
227
  ];
204
228
  return this.format(sql);
205
229
  }
230
+ hasTable({ database, table }) {
231
+ const sql = [
232
+ `SELECT EXISTS(
233
+ SELECT 1
234
+ FROM INFORMATION_SCHEMA.TABLES
235
+ WHERE
236
+ TABLE_TYPE = 'BASE TABLE'
237
+ AND TABLE_CATALOG = '${database.replace(/\`/g, "")}'
238
+ AND TABLE_NAME LIKE '${table.replace(/\`/g, "")}'
239
+ AND UPPER(TABLE_SCHEMA) NOT IN (
240
+ 'PG_CATALOG',
241
+ 'INFORMATION_SCHEMA',
242
+ 'PG_TOAST'
243
+ )
244
+ ) AS "IS_EXISTS"`,
245
+ ];
246
+ return this.format(sql);
247
+ }
248
+ createDatabase(database) {
249
+ const sql = `CREATE DATABASE \`${database}\``;
250
+ return this.format(sql);
251
+ }
206
252
  createTable({ database, table, schema, }) {
207
253
  let columns = [];
208
254
  if (Array.isArray(schema)) {
@@ -258,7 +304,7 @@ class PostgresQueryBuilder extends __1.QueryBuilder {
258
304
  this.$constants("ALTER_TABLE"),
259
305
  `\`${table}\``,
260
306
  this.$constants("ADD"),
261
- "COLUMN",
307
+ this.$constants("COLUMN"),
262
308
  `\`${column}\` ${formatedType} ${formatedAttributes != null && formatedAttributes.length
263
309
  ? `${formatedAttributes.join(" ")}`
264
310
  : ""}`,
@@ -267,17 +313,22 @@ class PostgresQueryBuilder extends __1.QueryBuilder {
267
313
  return this.format(sql);
268
314
  }
269
315
  changeColumn({ table, column, type, attributes, }) {
270
- const { formatedAttributes, formatedType } = this._formatedTypeAndAttributes({
316
+ const { formatedAttributes, formatedType, raws } = this._formatedTypeAndAttributes({
317
+ table,
271
318
  type,
272
319
  attributes,
273
320
  key: column,
321
+ changed: true
274
322
  });
323
+ if (raws) {
324
+ return this.format(raws);
325
+ }
275
326
  const sql = [
276
327
  this.$constants("ALTER_TABLE"),
277
328
  `\`${table}\``,
278
329
  this.$constants("ALTER_COLUMN"),
279
330
  `\`${column}\``,
280
- `TYPE ${formatedType}`,
331
+ `${this.$constants("TYPE")} ${formatedType}`,
281
332
  ];
282
333
  const sqlAttr = [];
283
334
  for (const formatedAttribute of formatedAttributes) {
@@ -290,7 +341,7 @@ class PostgresQueryBuilder extends __1.QueryBuilder {
290
341
  `\`${table}\``,
291
342
  this.$constants("ALTER_COLUMN"),
292
343
  `\`${column}\``,
293
- `SET ${formatedAttribute}`,
344
+ `${this.$constants("SET")} ${formatedAttribute}`,
294
345
  ].join(" "));
295
346
  }
296
347
  if (!sqlAttr.length) {
@@ -329,7 +380,6 @@ class PostgresQueryBuilder extends __1.QueryBuilder {
329
380
  BY con.CONNAME, conrel.RELNAME, confrel.RELNAME
330
381
  ORDER
331
382
  BY conrel.RELNAME, con.CONNAME
332
-
333
383
  `,
334
384
  ];
335
385
  return this.format(sql);
@@ -378,7 +428,7 @@ class PostgresQueryBuilder extends __1.QueryBuilder {
378
428
  ];
379
429
  return this.format(sql);
380
430
  }
381
- createFK({ table, tableRef, key, constraint, foreign, }) {
431
+ addFK({ table, tableRef, key, constraint, foreign, }) {
382
432
  const sql = [
383
433
  `${this.$constants("ALTER_TABLE")}`,
384
434
  `\`${table}\``,
@@ -438,7 +488,7 @@ class PostgresQueryBuilder extends __1.QueryBuilder {
438
488
  ];
439
489
  return this.format(sql);
440
490
  }
441
- hasIndex({ database, table, index, }) {
491
+ hasIndex({ database, table, name, }) {
442
492
  const sql = [
443
493
  `
444
494
  SELECT EXISTS(
@@ -457,18 +507,103 @@ class PostgresQueryBuilder extends __1.QueryBuilder {
457
507
  t.RELKIND = 'r'
458
508
  AND kcu.TABLE_CATALOG = '${database.replace(/\`/g, "")}'
459
509
  AND t.RELNAME = '${table.replace(/\`/g, "")}'
460
- AND i.RELNAME = '${index}'
510
+ AND i.RELNAME = '${name}'
461
511
  ) AS "IS_EXISTS"
462
512
  `,
463
513
  ];
464
514
  return this.format(sql);
465
515
  }
466
- createIndex({ table, index, key, }) {
516
+ addIndex({ table, name, columns, }) {
517
+ const cols = columns
518
+ .map(col => `\`${col}\``)
519
+ .join(", ");
520
+ const sql = [
521
+ this.$constants("CREATE_INDEX"),
522
+ `\`${name}\``,
523
+ this.$constants("ON"),
524
+ `\`${table}\``,
525
+ `(${cols})`
526
+ ];
527
+ return this.format(sql);
528
+ }
529
+ dropIndex({ table, name, }) {
530
+ const sql = [
531
+ this.$constants("DROP"),
532
+ this.$constants("INDEX"),
533
+ `\`${name}\``
534
+ ];
535
+ return this.format(sql);
536
+ }
537
+ hasUnique({ database, table, name, }) {
538
+ const sql = [
539
+ `
540
+ SELECT EXISTS(
541
+ SELECT 1
542
+ FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
543
+ WHERE
544
+ TABLE_SCHEMA = '${database.replace(/['"`]/g, "")}'
545
+ AND TABLE_NAME = '${table.replace(/['"`]/g, "")}'
546
+ AND CONSTRAINT_NAME = '${name.replace(/['"`]/g, "")}'
547
+ AND CONSTRAINT_TYPE = '${this.$constants("UNIQUE")}'
548
+ ) AS "IS_EXISTS"
549
+ `
550
+ ];
551
+ return this.format(sql);
552
+ }
553
+ addUnique({ table, name, columns }) {
554
+ const cols = columns
555
+ .map(col => `\`${col}\``)
556
+ .join(", ");
467
557
  const sql = [
468
- `${this.$constants("CREATE_INDEX")}`,
469
- `\`${index.replace(/`/g, "")}\``,
470
- `${this.$constants("ON")}`,
471
- `${table}(\`${key.replace(/`/g, "")}\`)`,
558
+ this.$constants("ALTER_TABLE"),
559
+ `\`${table}\``,
560
+ this.$constants("ADD_CONSTRAINT"),
561
+ `\`${name}\``,
562
+ this.$constants("UNIQUE"),
563
+ `(${cols})`
564
+ ];
565
+ return this.format(sql);
566
+ }
567
+ dropUnique({ table, name, }) {
568
+ const sql = [
569
+ this.$constants("ALTER_TABLE"),
570
+ `\`${table}\``,
571
+ this.$constants("DROP"),
572
+ this.$constants("CONSTRAINT"),
573
+ `\`${name}\``
574
+ ];
575
+ return this.format(sql);
576
+ }
577
+ hasPrimaryKey({ database, table, }) {
578
+ const sql = `
579
+ SELECT EXISTS (
580
+ SELECT 1
581
+ FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
582
+ WHERE
583
+ TABLE_SCHEMA = '${database.replace(/['"`]/g, "")}'
584
+ AND TABLE_NAME = '${table.replace(/['"`]/g, "")}'
585
+ AND CONSTRAINT_TYPE = '${this.$constants('PRIMARY_KEY')}'
586
+ ) AS "IS_EXISTS"
587
+ `;
588
+ return this.format(sql);
589
+ }
590
+ addPrimaryKey({ table, columns, }) {
591
+ const cols = columns
592
+ .map(col => `\`${col}\``)
593
+ .join(", ");
594
+ const sql = `
595
+ ${this.$constants('ALTER_TABLE')} \`${table}\`
596
+ ${this.$constants('ADD')} ${this.$constants('PRIMARY_KEY')} (${cols})
597
+ `;
598
+ return this.format(sql);
599
+ }
600
+ dropPrimaryKey({ table }) {
601
+ const sql = [
602
+ this.$constants("ALTER_TABLE"),
603
+ `\`${table}\``,
604
+ this.$constants("DROP"),
605
+ this.$constants("CONSTRAINT"),
606
+ `\`${table}_pkey\``
472
607
  ];
473
608
  return this.format(sql);
474
609
  }
@@ -524,18 +659,55 @@ class PostgresQueryBuilder extends __1.QueryBuilder {
524
659
  const insertRegex = /^INSERT\b/i;
525
660
  const deleteRegex = /^DELETE\b/i;
526
661
  const truncateRegex = /^TRUNCATE\b/i;
662
+ if (updateRegex.test(sqlString)) {
663
+ sqlString = sqlString.replace(/(SET\s+)(.*?)(\s+WHERE)/is, (_, start, setPart, end) => {
664
+ const cleaned = setPart.replace(/`[\w$_]+`\./g, '');
665
+ return start + cleaned + end;
666
+ });
667
+ }
527
668
  if (insertRegex.test(sqlString) ||
528
- updateRegex.test(sqlString) ||
529
669
  deleteRegex.test(sqlString) ||
530
670
  truncateRegex.test(sqlString)) {
531
671
  return sqlString
532
- .replace(/`[\w_]+`\.`([\w_]+)`/g, "`$1`")
672
+ .replace(/`[\w$_]+`\.`([\w$_]+)`/g, "`$1`")
533
673
  .replace(/`([^`]+)`/g, '"$1"');
534
674
  }
535
675
  return sqlString.replace(/`([^`]+)`/g, '"$1"');
536
676
  };
537
677
  return replaceBackticksWithDoubleQuotes(formated);
538
678
  }
679
+ getActiveConnections() {
680
+ const sql = `
681
+ SELECT
682
+ COUNT(*) AS "Connections"
683
+ FROM
684
+ PG_STAT_ACTIVITY
685
+ `;
686
+ return this.format(sql);
687
+ }
688
+ getMaxConnections() {
689
+ const sql = `
690
+ SELECT
691
+ setting::int AS "MaxConnections"
692
+ FROM
693
+ PG_SETTINGS
694
+ WHERE
695
+ name = 'max_connections'
696
+ `;
697
+ return this.format(sql);
698
+ }
699
+ lockTable(mode) {
700
+ const sql = [
701
+ "LOCK TABLE",
702
+ this.$state.get('TABLE_NAME'),
703
+ mode === 'READ' ? 'IN SHARE MODE' : 'IN ACCESS EXCLUSIVE MODE'
704
+ ];
705
+ return this.format(sql);
706
+ }
707
+ unlockTable() {
708
+ // in postgress not have unlock table, unlock when trx COMMIT / ROLLBACK
709
+ return null;
710
+ }
539
711
  bindJoin(values) {
540
712
  if (!Array.isArray(values) || !values.length)
541
713
  return null;
@@ -544,9 +716,42 @@ class PostgresQueryBuilder extends __1.QueryBuilder {
544
716
  bindWhere(values) {
545
717
  if (!Array.isArray(values) || !values.length)
546
718
  return null;
547
- return `${this.$constants("WHERE")} ${values
548
- .map((v) => v.replace(/^\s/, "").replace(/\s+/g, " "))
549
- .join(" ")}`;
719
+ const serializeWhere = (wheres) => {
720
+ const resolveValue = ({ operator, value }) => {
721
+ let valueStr = '';
722
+ if (operator?.toUpperCase() === this.$constants('IN') && Array.isArray(value)) {
723
+ valueStr = `(${value.map((v) => v).join(',')})`;
724
+ }
725
+ else if (operator?.toUpperCase() === this.$constants('IS_NULL') ||
726
+ operator?.toUpperCase() === this.$constants('IS_NOT_NULL')) {
727
+ valueStr = '';
728
+ }
729
+ else {
730
+ valueStr = `${value}`;
731
+ }
732
+ return valueStr;
733
+ };
734
+ const conditionToSQL = (cond, isFirst = false) => {
735
+ const { column = '', operator = '', condition, value, nested } = cond;
736
+ if (nested && nested.length) {
737
+ const nestedSQL = nested
738
+ .map((c) => conditionToSQL(c))
739
+ .join(' ');
740
+ const valueStr = resolveValue({ operator, value });
741
+ if (!isFirst) {
742
+ return `${condition ?? this.$constants('AND')} (${column} ${operator} ${valueStr} ${nestedSQL})`;
743
+ }
744
+ return `(${column} ${operator} ${valueStr} ${nestedSQL})`;
745
+ }
746
+ const valueStr = resolveValue({ operator, value });
747
+ if (!isFirst) {
748
+ return `${condition ?? this.$constants('AND')} ${column} ${operator} ${valueStr}`.trim();
749
+ }
750
+ return `${column} ${operator} ${valueStr}`.trim();
751
+ };
752
+ return wheres.map((cond, i) => conditionToSQL(cond, !i)).join(' ');
753
+ };
754
+ return `${this.$constants("WHERE")} ${serializeWhere(values)}`;
550
755
  }
551
756
  bindOrderBy(values) {
552
757
  if (!Array.isArray(values) || !values.length)
@@ -562,17 +767,20 @@ class PostgresQueryBuilder extends __1.QueryBuilder {
562
767
  .map((v) => v.replace(/^\s/, "").replace(/\s+/g, " "))
563
768
  .join(", ")}`;
564
769
  }
565
- bindSelect(values, { distinct } = {}) {
770
+ bindSelect(values) {
566
771
  if (!values.length) {
567
- if (!distinct)
568
- return `${this.$constants("SELECT")} *`;
569
- return `${this.$constants("SELECT")} ${this.$constants("DISTINCT")} *`;
772
+ return `${this.$constants("SELECT")} *`;
570
773
  }
571
- const findIndex = values.indexOf("*");
572
- if (findIndex > -1) {
573
- const removed = values.splice(findIndex, 1);
774
+ const findIndexStar = values.indexOf("*");
775
+ if (findIndexStar > -1) {
776
+ const removed = values.splice(findIndexStar, 1);
574
777
  values.unshift(removed[0]);
575
778
  }
779
+ const findIndexDistinct = values.findIndex(v => new RegExp(`^${this.$constants("DISTINCT")}\\s*\\(`, 'i').test(v));
780
+ if (findIndexDistinct > -1) {
781
+ const [distinct] = values.splice(findIndexDistinct, 1);
782
+ values.unshift(distinct);
783
+ }
576
784
  return `${this.$constants("SELECT")} ${values.join(", ")}`;
577
785
  }
578
786
  bindFrom({ from, alias, rawAlias, }) {
@@ -607,19 +815,29 @@ class PostgresQueryBuilder extends __1.QueryBuilder {
607
815
  return "";
608
816
  return `${this.$constants("HAVING")} ${having}`;
609
817
  }
610
- bindRowLevelLock(mode) {
611
- if (mode == null)
818
+ bindRowLevelLock(rowLevelLock) {
819
+ if (rowLevelLock.mode == null)
612
820
  return '';
613
- const modeLock = mode === "FOR_UPDATE"
821
+ let modeLock = rowLevelLock.mode === "FOR_UPDATE"
614
822
  ? this.$constants("ROW_LEVEL_LOCK").update
615
823
  : this.$constants("ROW_LEVEL_LOCK").share;
824
+ if (rowLevelLock.skipLocked) {
825
+ modeLock += ` ${this.$constants("ROW_LEVEL_LOCK").skipLocked}`;
826
+ }
827
+ if (rowLevelLock.nowait) {
828
+ modeLock += ` ${this.$constants("ROW_LEVEL_LOCK").nowait}`;
829
+ }
616
830
  return modeLock;
617
831
  }
618
- _formatedTypeAndAttributes({ type, attributes, key, }) {
832
+ _formatedTypeAndAttributes({ table, type, attributes, key, changed }) {
619
833
  let formatedType = type;
620
834
  let formatedAttributes = attributes;
835
+ let raws = null;
621
836
  if (type.startsWith("INT") && attributes.some((v) => v === "PRIMARY KEY")) {
622
837
  formatedType = "SERIAL";
838
+ if (changed) {
839
+ formatedType = `INT USING "${key}"::INTEGER`;
840
+ }
623
841
  formatedAttributes = attributes.filter((attr) => {
624
842
  return !attr.startsWith("AUTO_INCREMENT");
625
843
  });
@@ -627,7 +845,7 @@ class PostgresQueryBuilder extends __1.QueryBuilder {
627
845
  if (type.startsWith("TINYINT")) {
628
846
  formatedType = "SMALLINT";
629
847
  }
630
- if (type.startsWith("LONGTEXT")) {
848
+ if (type.startsWith("LONGTEXT") || type.startsWith("MEDIUMTEXT")) {
631
849
  formatedType = "TEXT";
632
850
  }
633
851
  if (type.startsWith("ENUM")) {
@@ -639,6 +857,57 @@ class PostgresQueryBuilder extends __1.QueryBuilder {
639
857
  .reduce((sum, item) => sum + item.length, 0);
640
858
  formatedType = `VARCHAR(${totalLength}) CHECK (${key} IN ${enums})`;
641
859
  }
860
+ if (changed && type.startsWith("ENUM")) {
861
+ const enums = type.replace("ENUM", "");
862
+ const totalLength = enums
863
+ .slice(1, -1)
864
+ .split(",")
865
+ .map((s) => s.replace(/'/g, ""))
866
+ .reduce((sum, item) => sum + item.length, 0);
867
+ const enumType = `${[(0, pluralize_1.singular)(String(table ?? '')), key].join('_')}`;
868
+ raws = `
869
+ DO $$
870
+ DECLARE tname text;
871
+ BEGIN
872
+
873
+ SELECT t.TYPNAME
874
+ INTO tname
875
+ FROM PG_ATTRIBUTE a
876
+ JOIN PG_CLASS c ON c.OID = a.ATTRELID
877
+ JOIN PG_TYPE t ON t.OID = a.ATTTYPID
878
+ WHERE c.RELNAME = '${table}'
879
+ AND a.ATTNAME = '${key}'
880
+ AND a.ATTNUM > 0
881
+ AND t.TYPTYPE = 'e'
882
+ LIMIT 1;
883
+
884
+ IF tname IS NOT NULL THEN
885
+
886
+ ALTER TABLE ${table}
887
+ ALTER COLUMN ${key} DROP DEFAULT;
888
+
889
+ ALTER TABLE ${table}
890
+ ALTER COLUMN ${key} TYPE varchar(${totalLength});
891
+
892
+ EXECUTE 'DROP TYPE IF EXISTS ' || quote_ident(tname);
893
+
894
+ END IF;
895
+
896
+ DROP TYPE IF EXISTS ${enumType};
897
+
898
+ CREATE TYPE ${enumType} AS ENUM ${enums};
899
+
900
+ ALTER TABLE ${table}
901
+ ALTER COLUMN ${key} DROP DEFAULT;
902
+
903
+ ALTER TABLE ${table}
904
+ ALTER COLUMN ${key} TYPE ${enumType}
905
+ USING ${key}::${enumType};
906
+
907
+ END
908
+ $$
909
+ `;
910
+ }
642
911
  if (type.startsWith("BOOLEAN")) {
643
912
  formatedAttributes = attributes.map((attr) => {
644
913
  if (attr.startsWith("DEFAULT")) {
@@ -650,6 +919,7 @@ class PostgresQueryBuilder extends __1.QueryBuilder {
650
919
  return {
651
920
  formatedType,
652
921
  formatedAttributes,
922
+ raws
653
923
  };
654
924
  }
655
925
  }