@mikro-orm/sql 7.0.4-dev.9 → 7.0.4

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 (87) hide show
  1. package/AbstractSqlConnection.d.ts +94 -58
  2. package/AbstractSqlConnection.js +235 -238
  3. package/AbstractSqlDriver.d.ts +410 -155
  4. package/AbstractSqlDriver.js +2064 -1941
  5. package/AbstractSqlPlatform.d.ts +83 -73
  6. package/AbstractSqlPlatform.js +162 -158
  7. package/PivotCollectionPersister.d.ts +33 -15
  8. package/PivotCollectionPersister.js +158 -160
  9. package/README.md +1 -1
  10. package/SqlEntityManager.d.ts +67 -22
  11. package/SqlEntityManager.js +54 -38
  12. package/SqlEntityRepository.d.ts +14 -14
  13. package/SqlEntityRepository.js +23 -23
  14. package/dialects/mssql/MsSqlNativeQueryBuilder.d.ts +12 -12
  15. package/dialects/mssql/MsSqlNativeQueryBuilder.js +192 -194
  16. package/dialects/mysql/BaseMySqlPlatform.d.ts +64 -45
  17. package/dialects/mysql/BaseMySqlPlatform.js +134 -131
  18. package/dialects/mysql/MySqlExceptionConverter.d.ts +6 -6
  19. package/dialects/mysql/MySqlExceptionConverter.js +91 -77
  20. package/dialects/mysql/MySqlNativeQueryBuilder.d.ts +3 -3
  21. package/dialects/mysql/MySqlNativeQueryBuilder.js +66 -69
  22. package/dialects/mysql/MySqlSchemaHelper.d.ts +39 -39
  23. package/dialects/mysql/MySqlSchemaHelper.js +327 -319
  24. package/dialects/oracledb/OracleDialect.d.ts +81 -52
  25. package/dialects/oracledb/OracleDialect.js +155 -149
  26. package/dialects/oracledb/OracleNativeQueryBuilder.d.ts +12 -12
  27. package/dialects/oracledb/OracleNativeQueryBuilder.js +232 -236
  28. package/dialects/postgresql/BasePostgreSqlPlatform.d.ts +109 -105
  29. package/dialects/postgresql/BasePostgreSqlPlatform.js +354 -350
  30. package/dialects/postgresql/FullTextType.d.ts +10 -6
  31. package/dialects/postgresql/FullTextType.js +51 -51
  32. package/dialects/postgresql/PostgreSqlExceptionConverter.d.ts +5 -5
  33. package/dialects/postgresql/PostgreSqlExceptionConverter.js +55 -43
  34. package/dialects/postgresql/PostgreSqlNativeQueryBuilder.d.ts +1 -1
  35. package/dialects/postgresql/PostgreSqlNativeQueryBuilder.js +4 -4
  36. package/dialects/postgresql/PostgreSqlSchemaHelper.d.ts +102 -82
  37. package/dialects/postgresql/PostgreSqlSchemaHelper.js +733 -705
  38. package/dialects/sqlite/BaseSqliteConnection.d.ts +3 -5
  39. package/dialects/sqlite/BaseSqliteConnection.js +21 -19
  40. package/dialects/sqlite/NodeSqliteDialect.d.ts +1 -1
  41. package/dialects/sqlite/NodeSqliteDialect.js +23 -23
  42. package/dialects/sqlite/SqliteDriver.d.ts +1 -1
  43. package/dialects/sqlite/SqliteDriver.js +3 -3
  44. package/dialects/sqlite/SqliteExceptionConverter.d.ts +6 -6
  45. package/dialects/sqlite/SqliteExceptionConverter.js +67 -51
  46. package/dialects/sqlite/SqliteNativeQueryBuilder.d.ts +2 -2
  47. package/dialects/sqlite/SqliteNativeQueryBuilder.js +7 -7
  48. package/dialects/sqlite/SqlitePlatform.d.ts +63 -72
  49. package/dialects/sqlite/SqlitePlatform.js +139 -139
  50. package/dialects/sqlite/SqliteSchemaHelper.d.ts +70 -60
  51. package/dialects/sqlite/SqliteSchemaHelper.js +533 -520
  52. package/package.json +3 -3
  53. package/plugin/index.d.ts +42 -35
  54. package/plugin/index.js +43 -36
  55. package/plugin/transformer.d.ts +117 -94
  56. package/plugin/transformer.js +890 -881
  57. package/query/ArrayCriteriaNode.d.ts +4 -4
  58. package/query/ArrayCriteriaNode.js +18 -18
  59. package/query/CriteriaNode.d.ts +35 -25
  60. package/query/CriteriaNode.js +133 -123
  61. package/query/CriteriaNodeFactory.d.ts +49 -6
  62. package/query/CriteriaNodeFactory.js +97 -94
  63. package/query/NativeQueryBuilder.d.ts +118 -118
  64. package/query/NativeQueryBuilder.js +484 -480
  65. package/query/ObjectCriteriaNode.d.ts +12 -12
  66. package/query/ObjectCriteriaNode.js +298 -282
  67. package/query/QueryBuilder.d.ts +1557 -905
  68. package/query/QueryBuilder.js +2322 -2192
  69. package/query/QueryBuilderHelper.d.ts +153 -72
  70. package/query/QueryBuilderHelper.js +1079 -1028
  71. package/query/ScalarCriteriaNode.d.ts +3 -3
  72. package/query/ScalarCriteriaNode.js +53 -46
  73. package/query/enums.d.ts +14 -14
  74. package/query/enums.js +14 -14
  75. package/query/raw.d.ts +16 -6
  76. package/query/raw.js +10 -10
  77. package/schema/DatabaseSchema.d.ts +73 -50
  78. package/schema/DatabaseSchema.js +331 -307
  79. package/schema/DatabaseTable.d.ts +96 -73
  80. package/schema/DatabaseTable.js +1012 -927
  81. package/schema/SchemaComparator.d.ts +70 -66
  82. package/schema/SchemaComparator.js +766 -740
  83. package/schema/SchemaHelper.d.ts +109 -95
  84. package/schema/SchemaHelper.js +675 -659
  85. package/schema/SqlSchemaGenerator.d.ts +78 -58
  86. package/schema/SqlSchemaGenerator.js +535 -501
  87. package/typings.d.ts +380 -266
@@ -1,486 +1,490 @@
1
- import { LockMode, raw, RawQueryFragment, Utils, } from '@mikro-orm/core';
1
+ import { LockMode, raw, RawQueryFragment, Utils } from '@mikro-orm/core';
2
2
  import { QueryType } from './enums.js';
3
3
  /** @internal */
4
4
  export class NativeQueryBuilder {
5
- platform;
6
- type;
7
- parts = [];
8
- params = [];
9
- options = {};
10
- constructor(platform) {
11
- this.platform = platform;
12
- }
13
- select(fields) {
14
- this.type = QueryType.SELECT;
15
- this.options.select ??= [];
16
- this.options.select.push(...Utils.asArray(fields));
17
- return this;
18
- }
19
- count(fields = '*', distinct) {
20
- this.type = QueryType.COUNT;
21
- this.options.select = Utils.asArray(fields);
22
- this.options.distinct = distinct;
23
- return this;
24
- }
25
- into(tableName, options) {
26
- return this.from(tableName, options);
27
- }
28
- from(tableName, options) {
29
- if (tableName instanceof NativeQueryBuilder) {
30
- tableName = tableName.toRaw();
31
- }
32
- if (typeof tableName === 'string') {
33
- const asKeyword = this.platform.usesAsKeyword() ? ' as ' : ' ';
34
- const alias = options?.alias ? `${asKeyword}${this.platform.quoteIdentifier(options.alias)}` : '';
35
- const schema = options?.schema && options.schema !== this.platform.getDefaultSchemaName() ? `${options.schema}.` : '';
36
- tableName = this.quote(schema + tableName) + alias;
37
- }
38
- this.options.tableName = tableName;
39
- this.options.indexHint = options?.indexHint;
40
- return this;
41
- }
42
- where(sql, params) {
43
- this.options.where = { sql, params };
44
- return this;
45
- }
46
- having(sql, params) {
47
- this.options.having = { sql, params };
48
- return this;
49
- }
50
- groupBy(groupBy) {
51
- this.options.groupBy = groupBy;
52
- return this;
53
- }
54
- join(sql, params) {
55
- this.options.joins ??= [];
56
- this.options.joins.push({ sql, params });
57
- return this;
58
- }
59
- orderBy(orderBy) {
60
- this.options.orderBy = orderBy;
61
- return this;
62
- }
63
- /**
64
- * The sub-query is compiled eagerly at call time — later mutations to the
65
- * sub-query builder will not be reflected in this CTE.
66
- */
67
- with(name, query, options) {
68
- return this.addCte(name, query, options);
69
- }
70
- /**
71
- * Adds a recursive CTE (`WITH RECURSIVE` on PostgreSQL/MySQL/SQLite, plain `WITH` on MSSQL).
72
- * The sub-query is compiled eagerly later mutations will not be reflected.
73
- */
74
- withRecursive(name, query, options) {
75
- return this.addCte(name, query, options, true);
76
- }
77
- addCte(name, query, options, recursive) {
78
- this.options.ctes ??= [];
79
- if (this.options.ctes.some(cte => cte.name === name)) {
80
- throw new Error(`CTE with name '${name}' already exists`);
81
- }
82
- const { sql, params } = query instanceof NativeQueryBuilder ? query.compile() : { sql: query.sql, params: [...query.params] };
83
- this.options.ctes.push({
84
- name,
85
- sql,
86
- params,
87
- recursive,
88
- columns: options?.columns,
89
- materialized: options?.materialized,
90
- });
91
- return this;
92
- }
93
- toString() {
94
- const { sql, params } = this.compile();
95
- return this.platform.formatQuery(sql, params);
96
- }
97
- compile() {
98
- if (!this.type) {
99
- throw new Error('No query type provided');
100
- }
101
- this.parts.length = 0;
102
- this.params.length = 0;
103
- if (this.options.comment) {
104
- this.parts.push(...this.options.comment.map(comment => `/* ${comment} */`));
105
- }
106
- this.compileCtes();
107
- switch (this.type) {
108
- case QueryType.SELECT:
109
- case QueryType.COUNT:
110
- this.compileSelect();
111
- break;
112
- case QueryType.INSERT:
113
- this.compileInsert();
114
- break;
115
- case QueryType.UPDATE:
116
- this.compileUpdate();
117
- break;
118
- case QueryType.DELETE:
119
- this.compileDelete();
120
- break;
121
- case QueryType.TRUNCATE:
122
- this.compileTruncate();
123
- break;
124
- }
125
- this.addOnConflictClause();
126
- if (this.options.returning && this.platform.usesReturningStatement()) {
127
- const fields = this.options.returning.map(field => this.quote(field));
128
- this.parts.push(`returning ${fields.join(', ')}`);
129
- }
130
- this.addLockClause();
131
- return this.combineParts();
132
- }
133
- addLockClause() {
134
- if (!this.options.lockMode) {
135
- return;
136
- }
137
- if ([LockMode.PESSIMISTIC_READ, LockMode.PESSIMISTIC_PARTIAL_READ, LockMode.PESSIMISTIC_READ_OR_FAIL].includes(this.options.lockMode)) {
138
- this.parts.push('for share');
139
- }
140
- if ([LockMode.PESSIMISTIC_WRITE, LockMode.PESSIMISTIC_PARTIAL_WRITE, LockMode.PESSIMISTIC_WRITE_OR_FAIL].includes(this.options.lockMode)) {
141
- this.parts.push('for update');
142
- }
143
- if (this.options.lockTables?.length) {
144
- const fields = this.options.lockTables.map(field => this.quote(field));
145
- this.parts.push(`of ${fields.join(', ')}`);
146
- }
147
- if ([LockMode.PESSIMISTIC_PARTIAL_READ, LockMode.PESSIMISTIC_PARTIAL_WRITE].includes(this.options.lockMode)) {
148
- this.parts.push('skip locked');
149
- }
150
- if ([LockMode.PESSIMISTIC_READ_OR_FAIL, LockMode.PESSIMISTIC_WRITE_OR_FAIL].includes(this.options.lockMode)) {
151
- this.parts.push('nowait');
152
- }
153
- }
154
- addOnConflictClause() {
155
- const clause = this.options.onConflict;
156
- if (!clause) {
157
- return;
158
- }
159
- this.parts.push('on conflict');
160
- if (clause.fields instanceof RawQueryFragment) {
161
- this.parts.push(clause.fields.sql);
162
- this.params.push(...clause.fields.params);
163
- }
164
- else if (clause.fields.length > 0) {
165
- const fields = clause.fields.map(field => this.quote(field));
166
- this.parts.push(`(${fields.join(', ')})`);
167
- }
168
- if (clause.ignore) {
169
- this.parts.push('do nothing');
170
- }
171
- if (Utils.isObject(clause.merge)) {
172
- this.parts.push('do update set');
173
- const fields = Object.keys(clause.merge).map(field => {
174
- this.params.push(clause.merge[field]);
175
- return `${this.quote(field)} = ?`;
176
- });
177
- this.parts.push(fields.join(', '));
178
- }
179
- else if (clause.merge) {
180
- this.parts.push('do update set');
181
- if (clause.merge.length) {
182
- const fields = clause.merge.map(field => `${this.quote(field)} = excluded.${this.quote(field)}`);
183
- this.parts.push(fields.join(', '));
184
- }
185
- else {
186
- const dataAsArray = Utils.asArray(this.options.data);
187
- const keys = Object.keys(dataAsArray[0]);
188
- const fields = keys.map(field => `${this.quote(field)} = excluded.${this.quote(field)}`);
189
- this.parts.push(fields.join(', '));
190
- }
191
- }
192
- if (clause.where) {
193
- this.parts.push(`where ${clause.where.sql}`);
194
- this.params.push(...clause.where.params);
195
- }
196
- }
197
- combineParts() {
198
- let sql = this.parts.join(' ');
199
- if (this.options.wrap) {
200
- const [a, b] = this.options.wrap;
201
- sql = `${a}${sql}${b}`;
202
- }
203
- return { sql, params: this.params };
204
- }
205
- limit(limit) {
206
- this.options.limit = limit;
207
- return this;
208
- }
209
- offset(offset) {
210
- this.options.offset = offset;
211
- return this;
212
- }
213
- insert(data) {
214
- this.type = QueryType.INSERT;
215
- this.options.data = data;
216
- return this;
217
- }
218
- update(data) {
219
- this.type = QueryType.UPDATE;
220
- this.options.data ??= {};
221
- Object.assign(this.options.data, data);
222
- return this;
223
- }
224
- delete() {
225
- this.type = QueryType.DELETE;
226
- return this;
227
- }
228
- truncate() {
229
- this.type = QueryType.TRUNCATE;
230
- return this;
231
- }
232
- distinct() {
233
- this.options.distinct = true;
234
- return this;
235
- }
236
- distinctOn(fields) {
237
- this.options.distinctOn = fields;
238
- return this;
239
- }
240
- onConflict(options) {
241
- this.options.onConflict = options;
242
- return options;
243
- }
244
- returning(fields) {
245
- this.options.returning = fields;
246
- return this;
247
- }
248
- lockMode(lockMode, lockTables) {
249
- this.options.lockMode = lockMode;
250
- this.options.lockTables = lockTables;
251
- return this;
252
- }
253
- comment(comment) {
254
- this.options.comment ??= [];
255
- this.options.comment.push(...Utils.asArray(comment));
256
- return this;
257
- }
258
- hintComment(comment) {
259
- this.options.hintComment ??= [];
260
- this.options.hintComment.push(...Utils.asArray(comment));
261
- return this;
262
- }
263
- setFlags(flags) {
264
- this.options.flags = flags;
265
- return this;
266
- }
267
- clear(clause) {
268
- delete this.options[clause];
269
- return this;
270
- }
271
- wrap(prefix, suffix) {
272
- this.options.wrap = [prefix, suffix];
273
- return this;
274
- }
275
- as(alias) {
276
- this.wrap('(', `) as ${this.platform.quoteIdentifier(alias)}`);
277
- return this;
278
- }
279
- toRaw() {
280
- const { sql, params } = this.compile();
281
- return raw(sql, params);
282
- }
283
- compileSelect() {
284
- this.parts.push('select');
285
- this.addHintComment();
286
- this.parts.push(`${this.getFields()} from ${this.getTableName()}`);
287
- if (this.options.joins) {
288
- for (const join of this.options.joins) {
289
- this.parts.push(join.sql);
290
- this.params.push(...join.params);
291
- }
292
- }
293
- if (this.options.where?.sql.trim()) {
294
- this.parts.push(`where ${this.options.where.sql}`);
295
- this.options.where.params.forEach(p => this.params.push(p));
296
- }
297
- if (this.options.groupBy) {
298
- const fields = this.options.groupBy.map(field => this.quote(field));
299
- this.parts.push(`group by ${fields.join(', ')}`);
300
- }
301
- if (this.options.having) {
302
- this.parts.push(`having ${this.options.having.sql}`);
303
- this.params.push(...this.options.having.params);
304
- }
305
- if (this.options.orderBy) {
306
- this.parts.push(`order by ${this.options.orderBy}`);
307
- }
308
- if (this.options.limit != null) {
309
- this.parts.push(`limit ?`);
310
- this.params.push(this.options.limit);
311
- }
312
- if (this.options.offset != null) {
313
- this.parts.push(`offset ?`);
314
- this.params.push(this.options.offset);
315
- }
316
- }
317
- getFields() {
318
- if (!this.options.select || this.options.select.length === 0) {
319
- throw new Error('No fields selected');
320
- }
321
- let fields = this.options.select.map(field => this.quote(field)).join(', ');
322
- if (this.options.distinct) {
323
- fields = `distinct ${fields}`;
324
- }
325
- else if (this.options.distinctOn) {
326
- fields = `distinct on (${this.options.distinctOn.map(field => this.quote(field)).join(', ')}) ${fields}`;
327
- }
328
- if (this.type === QueryType.COUNT) {
329
- fields = `count(${fields}) as ${this.quote('count')}`;
330
- }
331
- return fields;
332
- }
333
- compileInsert() {
334
- if (!this.options.data) {
335
- throw new Error('No data provided');
336
- }
337
- this.parts.push('insert');
338
- this.addHintComment();
339
- this.parts.push(`into ${this.getTableName()}`);
340
- if (Object.keys(this.options.data).length === 0) {
341
- this.addOutputClause('inserted');
342
- this.parts.push('default values');
343
- return;
344
- }
345
- const parts = this.processInsertData();
346
- this.parts.push(parts.join(', '));
347
- }
348
- addOutputClause(type) {
349
- if (this.options.returning && this.platform.usesOutputStatement()) {
350
- const fields = this.options.returning.map(field => `${type}.${this.quote(field)}`);
351
- this.parts.push(`output ${fields.join(', ')}`);
352
- }
353
- }
354
- processInsertData() {
5
+ platform;
6
+ type;
7
+ parts = [];
8
+ params = [];
9
+ options = {};
10
+ constructor(platform) {
11
+ this.platform = platform;
12
+ }
13
+ select(fields) {
14
+ this.type = QueryType.SELECT;
15
+ this.options.select ??= [];
16
+ this.options.select.push(...Utils.asArray(fields));
17
+ return this;
18
+ }
19
+ count(fields = '*', distinct) {
20
+ this.type = QueryType.COUNT;
21
+ this.options.select = Utils.asArray(fields);
22
+ this.options.distinct = distinct;
23
+ return this;
24
+ }
25
+ into(tableName, options) {
26
+ return this.from(tableName, options);
27
+ }
28
+ from(tableName, options) {
29
+ if (tableName instanceof NativeQueryBuilder) {
30
+ tableName = tableName.toRaw();
31
+ }
32
+ if (typeof tableName === 'string') {
33
+ const asKeyword = this.platform.usesAsKeyword() ? ' as ' : ' ';
34
+ const alias = options?.alias ? `${asKeyword}${this.platform.quoteIdentifier(options.alias)}` : '';
35
+ const schema =
36
+ options?.schema && options.schema !== this.platform.getDefaultSchemaName() ? `${options.schema}.` : '';
37
+ tableName = this.quote(schema + tableName) + alias;
38
+ }
39
+ this.options.tableName = tableName;
40
+ this.options.indexHint = options?.indexHint;
41
+ return this;
42
+ }
43
+ where(sql, params) {
44
+ this.options.where = { sql, params };
45
+ return this;
46
+ }
47
+ having(sql, params) {
48
+ this.options.having = { sql, params };
49
+ return this;
50
+ }
51
+ groupBy(groupBy) {
52
+ this.options.groupBy = groupBy;
53
+ return this;
54
+ }
55
+ join(sql, params) {
56
+ this.options.joins ??= [];
57
+ this.options.joins.push({ sql, params });
58
+ return this;
59
+ }
60
+ orderBy(orderBy) {
61
+ this.options.orderBy = orderBy;
62
+ return this;
63
+ }
64
+ /**
65
+ * The sub-query is compiled eagerly at call time later mutations to the
66
+ * sub-query builder will not be reflected in this CTE.
67
+ */
68
+ with(name, query, options) {
69
+ return this.addCte(name, query, options);
70
+ }
71
+ /**
72
+ * Adds a recursive CTE (`WITH RECURSIVE` on PostgreSQL/MySQL/SQLite, plain `WITH` on MSSQL).
73
+ * The sub-query is compiled eagerly — later mutations will not be reflected.
74
+ */
75
+ withRecursive(name, query, options) {
76
+ return this.addCte(name, query, options, true);
77
+ }
78
+ addCte(name, query, options, recursive) {
79
+ this.options.ctes ??= [];
80
+ if (this.options.ctes.some(cte => cte.name === name)) {
81
+ throw new Error(`CTE with name '${name}' already exists`);
82
+ }
83
+ const { sql, params } =
84
+ query instanceof NativeQueryBuilder ? query.compile() : { sql: query.sql, params: [...query.params] };
85
+ this.options.ctes.push({
86
+ name,
87
+ sql,
88
+ params,
89
+ recursive,
90
+ columns: options?.columns,
91
+ materialized: options?.materialized,
92
+ });
93
+ return this;
94
+ }
95
+ toString() {
96
+ const { sql, params } = this.compile();
97
+ return this.platform.formatQuery(sql, params);
98
+ }
99
+ compile() {
100
+ if (!this.type) {
101
+ throw new Error('No query type provided');
102
+ }
103
+ this.parts.length = 0;
104
+ this.params.length = 0;
105
+ if (this.options.comment) {
106
+ this.parts.push(...this.options.comment.map(comment => `/* ${comment} */`));
107
+ }
108
+ this.compileCtes();
109
+ switch (this.type) {
110
+ case QueryType.SELECT:
111
+ case QueryType.COUNT:
112
+ this.compileSelect();
113
+ break;
114
+ case QueryType.INSERT:
115
+ this.compileInsert();
116
+ break;
117
+ case QueryType.UPDATE:
118
+ this.compileUpdate();
119
+ break;
120
+ case QueryType.DELETE:
121
+ this.compileDelete();
122
+ break;
123
+ case QueryType.TRUNCATE:
124
+ this.compileTruncate();
125
+ break;
126
+ }
127
+ this.addOnConflictClause();
128
+ if (this.options.returning && this.platform.usesReturningStatement()) {
129
+ const fields = this.options.returning.map(field => this.quote(field));
130
+ this.parts.push(`returning ${fields.join(', ')}`);
131
+ }
132
+ this.addLockClause();
133
+ return this.combineParts();
134
+ }
135
+ addLockClause() {
136
+ if (!this.options.lockMode) {
137
+ return;
138
+ }
139
+ if (
140
+ [LockMode.PESSIMISTIC_READ, LockMode.PESSIMISTIC_PARTIAL_READ, LockMode.PESSIMISTIC_READ_OR_FAIL].includes(
141
+ this.options.lockMode,
142
+ )
143
+ ) {
144
+ this.parts.push('for share');
145
+ }
146
+ if (
147
+ [LockMode.PESSIMISTIC_WRITE, LockMode.PESSIMISTIC_PARTIAL_WRITE, LockMode.PESSIMISTIC_WRITE_OR_FAIL].includes(
148
+ this.options.lockMode,
149
+ )
150
+ ) {
151
+ this.parts.push('for update');
152
+ }
153
+ if (this.options.lockTables?.length) {
154
+ const fields = this.options.lockTables.map(field => this.quote(field));
155
+ this.parts.push(`of ${fields.join(', ')}`);
156
+ }
157
+ if ([LockMode.PESSIMISTIC_PARTIAL_READ, LockMode.PESSIMISTIC_PARTIAL_WRITE].includes(this.options.lockMode)) {
158
+ this.parts.push('skip locked');
159
+ }
160
+ if ([LockMode.PESSIMISTIC_READ_OR_FAIL, LockMode.PESSIMISTIC_WRITE_OR_FAIL].includes(this.options.lockMode)) {
161
+ this.parts.push('nowait');
162
+ }
163
+ }
164
+ addOnConflictClause() {
165
+ const clause = this.options.onConflict;
166
+ if (!clause) {
167
+ return;
168
+ }
169
+ this.parts.push('on conflict');
170
+ if (clause.fields instanceof RawQueryFragment) {
171
+ this.parts.push(clause.fields.sql);
172
+ this.params.push(...clause.fields.params);
173
+ } else if (clause.fields.length > 0) {
174
+ const fields = clause.fields.map(field => this.quote(field));
175
+ this.parts.push(`(${fields.join(', ')})`);
176
+ }
177
+ if (clause.ignore) {
178
+ this.parts.push('do nothing');
179
+ }
180
+ if (Utils.isObject(clause.merge)) {
181
+ this.parts.push('do update set');
182
+ const fields = Object.keys(clause.merge).map(field => {
183
+ this.params.push(clause.merge[field]);
184
+ return `${this.quote(field)} = ?`;
185
+ });
186
+ this.parts.push(fields.join(', '));
187
+ } else if (clause.merge) {
188
+ this.parts.push('do update set');
189
+ if (clause.merge.length) {
190
+ const fields = clause.merge.map(field => `${this.quote(field)} = excluded.${this.quote(field)}`);
191
+ this.parts.push(fields.join(', '));
192
+ } else {
355
193
  const dataAsArray = Utils.asArray(this.options.data);
356
194
  const keys = Object.keys(dataAsArray[0]);
357
- const values = keys.map(() => '?');
358
- const parts = [];
359
- this.parts.push(`(${keys.map(key => this.quote(key)).join(', ')})`);
360
- this.addOutputClause('inserted');
361
- this.parts.push('values');
362
- for (const data of dataAsArray) {
363
- for (const key of keys) {
364
- if (typeof data[key] === 'undefined') {
365
- this.params.push(this.platform.usesDefaultKeyword() ? raw('default') : null);
366
- }
367
- else {
368
- this.params.push(data[key]);
369
- }
370
- }
371
- parts.push(`(${values.join(', ')})`);
372
- }
373
- return parts;
374
- }
375
- compileUpdate() {
376
- if (!this.options.data || Object.keys(this.options.data).length === 0) {
377
- throw new Error('No data provided');
378
- }
379
- this.parts.push('update');
380
- this.addHintComment();
381
- this.parts.push(this.getTableName());
382
- if (this.options.joins) {
383
- for (const join of this.options.joins) {
384
- this.parts.push(join.sql);
385
- this.params.push(...join.params);
386
- }
387
- }
388
- this.parts.push('set');
389
- if (this.options.data) {
390
- const parts = [];
391
- for (const key of Object.keys(this.options.data)) {
392
- parts.push(`${this.quote(key)} = ?`);
393
- this.params.push(this.options.data[key]);
394
- }
395
- this.parts.push(parts.join(', '));
396
- }
397
- this.addOutputClause('inserted');
398
- if (this.options.where?.sql.trim()) {
399
- this.parts.push(`where ${this.options.where.sql}`);
400
- this.params.push(...this.options.where.params);
401
- }
402
- }
403
- compileDelete() {
404
- this.parts.push('delete');
405
- this.addHintComment();
406
- this.parts.push(`from ${this.getTableName()}`);
407
- this.addOutputClause('deleted');
408
- if (this.options.where?.sql.trim()) {
409
- this.parts.push(`where ${this.options.where.sql}`);
410
- this.params.push(...this.options.where.params);
411
- }
412
- }
413
- compileTruncate() {
414
- const sql = `truncate table ${this.getTableName()}`;
415
- this.parts.push(sql);
416
- }
417
- addHintComment() {
418
- if (this.options.hintComment) {
419
- this.parts.push(`/*+ ${this.options.hintComment.join(' ')} */`);
420
- }
421
- }
422
- compileCtes() {
423
- const ctes = this.options.ctes;
424
- if (!ctes || ctes.length === 0) {
425
- return;
426
- }
427
- const hasRecursive = ctes.some(cte => cte.recursive);
428
- const keyword = this.getCteKeyword(hasRecursive);
429
- const cteParts = [];
430
- for (const cte of ctes) {
431
- let part = this.quote(cte.name);
432
- if (cte.columns?.length) {
433
- part += ` (${cte.columns.map(c => this.quote(c)).join(', ')})`;
434
- }
435
- part += ' as';
436
- if (cte.materialized === true) {
437
- part += ' materialized';
438
- }
439
- else if (cte.materialized === false) {
440
- part += ' not materialized';
441
- }
442
- part += ` (${cte.sql})`;
443
- this.params.push(...cte.params);
444
- cteParts.push(part);
445
- }
446
- this.parts.push(`${keyword} ${cteParts.join(', ')}`);
447
- }
448
- getCteKeyword(hasRecursive) {
449
- return hasRecursive ? 'with recursive' : 'with';
450
- }
451
- getTableName() {
452
- if (!this.options.tableName) {
453
- throw new Error('No table name provided');
454
- }
455
- const indexHint = this.options.indexHint ? ' ' + this.options.indexHint : '';
456
- if (this.options.tableName instanceof RawQueryFragment) {
457
- this.params.push(...this.options.tableName.params);
458
- return this.options.tableName.sql + indexHint;
459
- }
460
- return this.options.tableName + indexHint;
461
- }
462
- quote(id) {
463
- if (id instanceof RawQueryFragment) {
464
- return this.platform.formatQuery(id.sql, id.params);
465
- }
466
- if (id instanceof NativeQueryBuilder) {
467
- const { sql, params } = id.compile();
468
- return this.platform.formatQuery(sql, params);
469
- }
470
- if (id.endsWith('.*')) {
471
- const schema = this.platform.quoteIdentifier(id.substring(0, id.indexOf('.')));
472
- return schema + '.*';
473
- }
474
- if (id.toLowerCase().includes(' as ')) {
475
- const parts = id.split(/ as /i);
476
- const a = this.platform.quoteIdentifier(parts[0]);
477
- const b = this.platform.quoteIdentifier(parts[1]);
478
- const asKeyword = this.platform.usesAsKeyword() ? ' as ' : ' ';
479
- return `${a}${asKeyword}${b}`;
480
- }
481
- if (id === '*') {
482
- return id;
483
- }
484
- return this.platform.quoteIdentifier(id);
485
- }
195
+ const fields = keys.map(field => `${this.quote(field)} = excluded.${this.quote(field)}`);
196
+ this.parts.push(fields.join(', '));
197
+ }
198
+ }
199
+ if (clause.where) {
200
+ this.parts.push(`where ${clause.where.sql}`);
201
+ this.params.push(...clause.where.params);
202
+ }
203
+ }
204
+ combineParts() {
205
+ let sql = this.parts.join(' ');
206
+ if (this.options.wrap) {
207
+ const [a, b] = this.options.wrap;
208
+ sql = `${a}${sql}${b}`;
209
+ }
210
+ return { sql, params: this.params };
211
+ }
212
+ limit(limit) {
213
+ this.options.limit = limit;
214
+ return this;
215
+ }
216
+ offset(offset) {
217
+ this.options.offset = offset;
218
+ return this;
219
+ }
220
+ insert(data) {
221
+ this.type = QueryType.INSERT;
222
+ this.options.data = data;
223
+ return this;
224
+ }
225
+ update(data) {
226
+ this.type = QueryType.UPDATE;
227
+ this.options.data ??= {};
228
+ Object.assign(this.options.data, data);
229
+ return this;
230
+ }
231
+ delete() {
232
+ this.type = QueryType.DELETE;
233
+ return this;
234
+ }
235
+ truncate() {
236
+ this.type = QueryType.TRUNCATE;
237
+ return this;
238
+ }
239
+ distinct() {
240
+ this.options.distinct = true;
241
+ return this;
242
+ }
243
+ distinctOn(fields) {
244
+ this.options.distinctOn = fields;
245
+ return this;
246
+ }
247
+ onConflict(options) {
248
+ this.options.onConflict = options;
249
+ return options;
250
+ }
251
+ returning(fields) {
252
+ this.options.returning = fields;
253
+ return this;
254
+ }
255
+ lockMode(lockMode, lockTables) {
256
+ this.options.lockMode = lockMode;
257
+ this.options.lockTables = lockTables;
258
+ return this;
259
+ }
260
+ comment(comment) {
261
+ this.options.comment ??= [];
262
+ this.options.comment.push(...Utils.asArray(comment));
263
+ return this;
264
+ }
265
+ hintComment(comment) {
266
+ this.options.hintComment ??= [];
267
+ this.options.hintComment.push(...Utils.asArray(comment));
268
+ return this;
269
+ }
270
+ setFlags(flags) {
271
+ this.options.flags = flags;
272
+ return this;
273
+ }
274
+ clear(clause) {
275
+ delete this.options[clause];
276
+ return this;
277
+ }
278
+ wrap(prefix, suffix) {
279
+ this.options.wrap = [prefix, suffix];
280
+ return this;
281
+ }
282
+ as(alias) {
283
+ this.wrap('(', `) as ${this.platform.quoteIdentifier(alias)}`);
284
+ return this;
285
+ }
286
+ toRaw() {
287
+ const { sql, params } = this.compile();
288
+ return raw(sql, params);
289
+ }
290
+ compileSelect() {
291
+ this.parts.push('select');
292
+ this.addHintComment();
293
+ this.parts.push(`${this.getFields()} from ${this.getTableName()}`);
294
+ if (this.options.joins) {
295
+ for (const join of this.options.joins) {
296
+ this.parts.push(join.sql);
297
+ this.params.push(...join.params);
298
+ }
299
+ }
300
+ if (this.options.where?.sql.trim()) {
301
+ this.parts.push(`where ${this.options.where.sql}`);
302
+ this.options.where.params.forEach(p => this.params.push(p));
303
+ }
304
+ if (this.options.groupBy) {
305
+ const fields = this.options.groupBy.map(field => this.quote(field));
306
+ this.parts.push(`group by ${fields.join(', ')}`);
307
+ }
308
+ if (this.options.having) {
309
+ this.parts.push(`having ${this.options.having.sql}`);
310
+ this.params.push(...this.options.having.params);
311
+ }
312
+ if (this.options.orderBy) {
313
+ this.parts.push(`order by ${this.options.orderBy}`);
314
+ }
315
+ if (this.options.limit != null) {
316
+ this.parts.push(`limit ?`);
317
+ this.params.push(this.options.limit);
318
+ }
319
+ if (this.options.offset != null) {
320
+ this.parts.push(`offset ?`);
321
+ this.params.push(this.options.offset);
322
+ }
323
+ }
324
+ getFields() {
325
+ if (!this.options.select || this.options.select.length === 0) {
326
+ throw new Error('No fields selected');
327
+ }
328
+ let fields = this.options.select.map(field => this.quote(field)).join(', ');
329
+ if (this.options.distinct) {
330
+ fields = `distinct ${fields}`;
331
+ } else if (this.options.distinctOn) {
332
+ fields = `distinct on (${this.options.distinctOn.map(field => this.quote(field)).join(', ')}) ${fields}`;
333
+ }
334
+ if (this.type === QueryType.COUNT) {
335
+ fields = `count(${fields}) as ${this.quote('count')}`;
336
+ }
337
+ return fields;
338
+ }
339
+ compileInsert() {
340
+ if (!this.options.data) {
341
+ throw new Error('No data provided');
342
+ }
343
+ this.parts.push('insert');
344
+ this.addHintComment();
345
+ this.parts.push(`into ${this.getTableName()}`);
346
+ if (Object.keys(this.options.data).length === 0) {
347
+ this.addOutputClause('inserted');
348
+ this.parts.push('default values');
349
+ return;
350
+ }
351
+ const parts = this.processInsertData();
352
+ this.parts.push(parts.join(', '));
353
+ }
354
+ addOutputClause(type) {
355
+ if (this.options.returning && this.platform.usesOutputStatement()) {
356
+ const fields = this.options.returning.map(field => `${type}.${this.quote(field)}`);
357
+ this.parts.push(`output ${fields.join(', ')}`);
358
+ }
359
+ }
360
+ processInsertData() {
361
+ const dataAsArray = Utils.asArray(this.options.data);
362
+ const keys = Object.keys(dataAsArray[0]);
363
+ const values = keys.map(() => '?');
364
+ const parts = [];
365
+ this.parts.push(`(${keys.map(key => this.quote(key)).join(', ')})`);
366
+ this.addOutputClause('inserted');
367
+ this.parts.push('values');
368
+ for (const data of dataAsArray) {
369
+ for (const key of keys) {
370
+ if (typeof data[key] === 'undefined') {
371
+ this.params.push(this.platform.usesDefaultKeyword() ? raw('default') : null);
372
+ } else {
373
+ this.params.push(data[key]);
374
+ }
375
+ }
376
+ parts.push(`(${values.join(', ')})`);
377
+ }
378
+ return parts;
379
+ }
380
+ compileUpdate() {
381
+ if (!this.options.data || Object.keys(this.options.data).length === 0) {
382
+ throw new Error('No data provided');
383
+ }
384
+ this.parts.push('update');
385
+ this.addHintComment();
386
+ this.parts.push(this.getTableName());
387
+ if (this.options.joins) {
388
+ for (const join of this.options.joins) {
389
+ this.parts.push(join.sql);
390
+ this.params.push(...join.params);
391
+ }
392
+ }
393
+ this.parts.push('set');
394
+ if (this.options.data) {
395
+ const parts = [];
396
+ for (const key of Object.keys(this.options.data)) {
397
+ parts.push(`${this.quote(key)} = ?`);
398
+ this.params.push(this.options.data[key]);
399
+ }
400
+ this.parts.push(parts.join(', '));
401
+ }
402
+ this.addOutputClause('inserted');
403
+ if (this.options.where?.sql.trim()) {
404
+ this.parts.push(`where ${this.options.where.sql}`);
405
+ this.params.push(...this.options.where.params);
406
+ }
407
+ }
408
+ compileDelete() {
409
+ this.parts.push('delete');
410
+ this.addHintComment();
411
+ this.parts.push(`from ${this.getTableName()}`);
412
+ this.addOutputClause('deleted');
413
+ if (this.options.where?.sql.trim()) {
414
+ this.parts.push(`where ${this.options.where.sql}`);
415
+ this.params.push(...this.options.where.params);
416
+ }
417
+ }
418
+ compileTruncate() {
419
+ const sql = `truncate table ${this.getTableName()}`;
420
+ this.parts.push(sql);
421
+ }
422
+ addHintComment() {
423
+ if (this.options.hintComment) {
424
+ this.parts.push(`/*+ ${this.options.hintComment.join(' ')} */`);
425
+ }
426
+ }
427
+ compileCtes() {
428
+ const ctes = this.options.ctes;
429
+ if (!ctes || ctes.length === 0) {
430
+ return;
431
+ }
432
+ const hasRecursive = ctes.some(cte => cte.recursive);
433
+ const keyword = this.getCteKeyword(hasRecursive);
434
+ const cteParts = [];
435
+ for (const cte of ctes) {
436
+ let part = this.quote(cte.name);
437
+ if (cte.columns?.length) {
438
+ part += ` (${cte.columns.map(c => this.quote(c)).join(', ')})`;
439
+ }
440
+ part += ' as';
441
+ if (cte.materialized === true) {
442
+ part += ' materialized';
443
+ } else if (cte.materialized === false) {
444
+ part += ' not materialized';
445
+ }
446
+ part += ` (${cte.sql})`;
447
+ this.params.push(...cte.params);
448
+ cteParts.push(part);
449
+ }
450
+ this.parts.push(`${keyword} ${cteParts.join(', ')}`);
451
+ }
452
+ getCteKeyword(hasRecursive) {
453
+ return hasRecursive ? 'with recursive' : 'with';
454
+ }
455
+ getTableName() {
456
+ if (!this.options.tableName) {
457
+ throw new Error('No table name provided');
458
+ }
459
+ const indexHint = this.options.indexHint ? ' ' + this.options.indexHint : '';
460
+ if (this.options.tableName instanceof RawQueryFragment) {
461
+ this.params.push(...this.options.tableName.params);
462
+ return this.options.tableName.sql + indexHint;
463
+ }
464
+ return this.options.tableName + indexHint;
465
+ }
466
+ quote(id) {
467
+ if (id instanceof RawQueryFragment) {
468
+ return this.platform.formatQuery(id.sql, id.params);
469
+ }
470
+ if (id instanceof NativeQueryBuilder) {
471
+ const { sql, params } = id.compile();
472
+ return this.platform.formatQuery(sql, params);
473
+ }
474
+ if (id.endsWith('.*')) {
475
+ const schema = this.platform.quoteIdentifier(id.substring(0, id.indexOf('.')));
476
+ return schema + '.*';
477
+ }
478
+ if (id.toLowerCase().includes(' as ')) {
479
+ const parts = id.split(/ as /i);
480
+ const a = this.platform.quoteIdentifier(parts[0]);
481
+ const b = this.platform.quoteIdentifier(parts[1]);
482
+ const asKeyword = this.platform.usesAsKeyword() ? ' as ' : ' ';
483
+ return `${a}${asKeyword}${b}`;
484
+ }
485
+ if (id === '*') {
486
+ return id;
487
+ }
488
+ return this.platform.quoteIdentifier(id);
489
+ }
486
490
  }