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

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 -1937
  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 +2 -2
  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 +108 -105
  29. package/dialects/postgresql/BasePostgreSqlPlatform.js +351 -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 -683
  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 +1546 -904
  68. package/query/QueryBuilder.js +2294 -2144
  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,892 +1,901 @@
1
- import { ReferenceKind, isRaw, } from '@mikro-orm/core';
2
- import { AliasNode, ColumnNode, ColumnUpdateNode, OperationNodeTransformer, PrimitiveValueListNode, ReferenceNode, SchemableIdentifierNode, TableNode, ValueListNode, ValueNode, ValuesNode, } from 'kysely';
1
+ import { ReferenceKind, isRaw } from '@mikro-orm/core';
2
+ import {
3
+ AliasNode,
4
+ ColumnNode,
5
+ ColumnUpdateNode,
6
+ OperationNodeTransformer,
7
+ PrimitiveValueListNode,
8
+ ReferenceNode,
9
+ SchemableIdentifierNode,
10
+ TableNode,
11
+ ValueListNode,
12
+ ValueNode,
13
+ ValuesNode,
14
+ } from 'kysely';
3
15
  export class MikroTransformer extends OperationNodeTransformer {
4
- /**
5
- * Context stack to support nested queries (subqueries, CTEs)
6
- * Each level of query scope has its own Map of table aliases/names to EntityMetadata
7
- * Top of stack (highest index) is the current scope
8
- */
9
- #contextStack = [];
10
- /**
11
- * Subquery alias map: maps subquery/CTE alias to its source table metadata
12
- * Used to resolve columns from subqueries/CTEs to their original table definitions
13
- */
14
- #subqueryAliasMap = new Map();
15
- #metadata;
16
- #platform;
17
- /**
18
- * Global map of all entities involved in the query.
19
- * Populated during AST transformation and used for result transformation.
20
- */
21
- #entityMap = new Map();
22
- #em;
23
- #options;
24
- constructor(em, options = {}) {
25
- super();
26
- this.#em = em;
27
- this.#options = options;
28
- this.#metadata = em.getMetadata();
29
- this.#platform = em.getDriver().getPlatform();
30
- }
31
- reset() {
32
- this.#subqueryAliasMap.clear();
33
- this.#entityMap.clear();
34
- }
35
- getOutputEntityMap() {
36
- return this.#entityMap;
37
- }
38
- /** @internal */
39
- getContextStack() {
40
- return this.#contextStack;
41
- }
42
- /** @internal */
43
- getSubqueryAliasMap() {
44
- return this.#subqueryAliasMap;
45
- }
46
- transformSelectQuery(node, queryId) {
47
- // Push a new context for this query scope (starts with inherited parent context)
48
- const currentContext = new Map();
49
- this.#contextStack.push(currentContext);
50
- try {
51
- // Process WITH clause (CTEs) first - they define names available in this scope
52
- if (node.with) {
53
- this.processWithNode(node.with, currentContext);
54
- }
55
- // Process FROM clause - main tables in this scope
56
- if (node.from?.froms) {
57
- for (const from of node.from.froms) {
58
- this.processFromItem(from, currentContext);
59
- }
60
- }
61
- // Process JOINs - additional tables joined into this scope
62
- if (node.joins) {
63
- for (const join of node.joins) {
64
- this.processJoinNode(join, currentContext);
65
- }
66
- }
67
- return super.transformSelectQuery(node, queryId);
68
- }
69
- finally {
70
- // Pop the context when exiting this query scope
71
- this.#contextStack.pop();
72
- }
73
- }
74
- transformInsertQuery(node, queryId) {
75
- const currentContext = new Map();
76
- this.#contextStack.push(currentContext);
77
- try {
78
- let entityMeta;
79
- if (node.into) {
80
- const tableName = this.getTableName(node.into);
81
- if (tableName) {
82
- const meta = this.findEntityMetadata(tableName);
83
- if (meta) {
84
- entityMeta = meta;
85
- currentContext.set(meta.tableName, meta);
86
- this.#entityMap.set(meta.tableName, meta);
87
- }
88
- }
89
- }
90
- const nodeWithHooks = this.#options.processOnCreateHooks && entityMeta ? this.processOnCreateHooks(node, entityMeta) : node;
91
- const nodeWithConvertedValues = this.#options.convertValues && entityMeta ? this.processInsertValues(nodeWithHooks, entityMeta) : nodeWithHooks;
92
- // Handle ON CONFLICT clause
93
- let finalNode = nodeWithConvertedValues;
94
- if (node.onConflict?.updates && entityMeta) {
95
- // Create a temporary UpdateQueryNode to reuse processOnUpdateHooks and processUpdateValues
96
- // We only care about the updates part
97
- const tempUpdateNode = {
98
- kind: 'UpdateQueryNode',
99
- table: node.into, // Dummy table
100
- updates: node.onConflict.updates,
101
- };
102
- const updatesWithHooks = this.#options.processOnUpdateHooks
103
- ? this.processOnUpdateHooks(tempUpdateNode, entityMeta).updates
104
- : node.onConflict.updates;
105
- const tempUpdateNodeWithHooks = {
106
- ...tempUpdateNode,
107
- updates: updatesWithHooks,
108
- };
109
- const updatesWithConvertedValues = this.#options.convertValues
110
- ? this.processUpdateValues(tempUpdateNodeWithHooks, entityMeta).updates
111
- : updatesWithHooks;
112
- if (updatesWithConvertedValues && updatesWithConvertedValues !== node.onConflict.updates) {
113
- // Construct the new OnConflictNode with updated values
114
- finalNode = {
115
- ...finalNode,
116
- onConflict: {
117
- ...node.onConflict,
118
- updates: updatesWithConvertedValues,
119
- },
120
- };
121
- }
122
- }
123
- return super.transformInsertQuery(finalNode, queryId);
124
- }
125
- finally {
126
- this.#contextStack.pop();
127
- }
128
- }
129
- transformUpdateQuery(node, queryId) {
130
- const currentContext = new Map();
131
- this.#contextStack.push(currentContext);
132
- try {
133
- let entityMeta;
134
- if (node.table && TableNode.is(node.table)) {
135
- const tableName = this.getTableName(node.table);
136
- if (tableName) {
137
- const meta = this.findEntityMetadata(tableName);
138
- if (meta) {
139
- entityMeta = meta;
140
- currentContext.set(meta.tableName, meta);
141
- this.#entityMap.set(meta.tableName, meta);
142
- }
143
- }
144
- }
145
- // Process FROM clause in UPDATE queries (for UPDATE with JOIN)
146
- if (node.from) {
147
- for (const fromItem of node.from.froms) {
148
- this.processFromItem(fromItem, currentContext);
149
- }
150
- }
151
- // Also process JOINs in UPDATE queries
152
- if (node.joins) {
153
- for (const join of node.joins) {
154
- this.processJoinNode(join, currentContext);
155
- }
156
- }
157
- const nodeWithHooks = this.#options.processOnUpdateHooks && entityMeta ? this.processOnUpdateHooks(node, entityMeta) : node;
158
- const nodeWithConvertedValues = this.#options.convertValues && entityMeta ? this.processUpdateValues(nodeWithHooks, entityMeta) : nodeWithHooks;
159
- return super.transformUpdateQuery(nodeWithConvertedValues, queryId);
160
- }
161
- finally {
162
- this.#contextStack.pop();
163
- }
164
- }
165
- transformDeleteQuery(node, queryId) {
166
- const currentContext = new Map();
167
- this.#contextStack.push(currentContext);
168
- try {
169
- const froms = node.from?.froms;
170
- if (froms && froms.length > 0) {
171
- const firstFrom = froms[0];
172
- if (TableNode.is(firstFrom)) {
173
- const tableName = this.getTableName(firstFrom);
174
- if (tableName) {
175
- const meta = this.findEntityMetadata(tableName);
176
- if (meta) {
177
- currentContext.set(meta.tableName, meta);
178
- this.#entityMap.set(meta.tableName, meta);
179
- }
180
- }
181
- }
182
- }
183
- // Also process JOINs in DELETE queries
184
- if (node.joins) {
185
- for (const join of node.joins) {
186
- this.processJoinNode(join, currentContext);
187
- }
188
- }
189
- return super.transformDeleteQuery(node, queryId);
190
- }
191
- finally {
192
- this.#contextStack.pop();
193
- }
194
- }
195
- transformMergeQuery(node, queryId) {
196
- const currentContext = new Map();
197
- this.#contextStack.push(currentContext);
198
- try {
199
- return super.transformMergeQuery(node, queryId);
200
- }
201
- finally {
202
- this.#contextStack.pop();
203
- }
204
- }
205
- transformIdentifier(node, queryId) {
206
- node = super.transformIdentifier(node, queryId);
207
- const parent = this.nodeStack[this.nodeStack.length - 2];
208
- // Transform table names when tableNamingStrategy is 'entity'
209
- if (this.#options.tableNamingStrategy === 'entity' && parent && SchemableIdentifierNode.is(parent)) {
210
- const meta = this.findEntityMetadata(node.name);
16
+ /**
17
+ * Context stack to support nested queries (subqueries, CTEs)
18
+ * Each level of query scope has its own Map of table aliases/names to EntityMetadata
19
+ * Top of stack (highest index) is the current scope
20
+ */
21
+ #contextStack = [];
22
+ /**
23
+ * Subquery alias map: maps subquery/CTE alias to its source table metadata
24
+ * Used to resolve columns from subqueries/CTEs to their original table definitions
25
+ */
26
+ #subqueryAliasMap = new Map();
27
+ #metadata;
28
+ #platform;
29
+ /**
30
+ * Global map of all entities involved in the query.
31
+ * Populated during AST transformation and used for result transformation.
32
+ */
33
+ #entityMap = new Map();
34
+ #em;
35
+ #options;
36
+ constructor(em, options = {}) {
37
+ super();
38
+ this.#em = em;
39
+ this.#options = options;
40
+ this.#metadata = em.getMetadata();
41
+ this.#platform = em.getDriver().getPlatform();
42
+ }
43
+ reset() {
44
+ this.#subqueryAliasMap.clear();
45
+ this.#entityMap.clear();
46
+ }
47
+ getOutputEntityMap() {
48
+ return this.#entityMap;
49
+ }
50
+ /** @internal */
51
+ getContextStack() {
52
+ return this.#contextStack;
53
+ }
54
+ /** @internal */
55
+ getSubqueryAliasMap() {
56
+ return this.#subqueryAliasMap;
57
+ }
58
+ transformSelectQuery(node, queryId) {
59
+ // Push a new context for this query scope (starts with inherited parent context)
60
+ const currentContext = new Map();
61
+ this.#contextStack.push(currentContext);
62
+ try {
63
+ // Process WITH clause (CTEs) first - they define names available in this scope
64
+ if (node.with) {
65
+ this.processWithNode(node.with, currentContext);
66
+ }
67
+ // Process FROM clause - main tables in this scope
68
+ if (node.from?.froms) {
69
+ for (const from of node.from.froms) {
70
+ this.processFromItem(from, currentContext);
71
+ }
72
+ }
73
+ // Process JOINs - additional tables joined into this scope
74
+ if (node.joins) {
75
+ for (const join of node.joins) {
76
+ this.processJoinNode(join, currentContext);
77
+ }
78
+ }
79
+ return super.transformSelectQuery(node, queryId);
80
+ } finally {
81
+ // Pop the context when exiting this query scope
82
+ this.#contextStack.pop();
83
+ }
84
+ }
85
+ transformInsertQuery(node, queryId) {
86
+ const currentContext = new Map();
87
+ this.#contextStack.push(currentContext);
88
+ try {
89
+ let entityMeta;
90
+ if (node.into) {
91
+ const tableName = this.getTableName(node.into);
92
+ if (tableName) {
93
+ const meta = this.findEntityMetadata(tableName);
94
+ if (meta) {
95
+ entityMeta = meta;
96
+ currentContext.set(meta.tableName, meta);
97
+ this.#entityMap.set(meta.tableName, meta);
98
+ }
99
+ }
100
+ }
101
+ const nodeWithHooks =
102
+ this.#options.processOnCreateHooks && entityMeta ? this.processOnCreateHooks(node, entityMeta) : node;
103
+ const nodeWithConvertedValues =
104
+ this.#options.convertValues && entityMeta ? this.processInsertValues(nodeWithHooks, entityMeta) : nodeWithHooks;
105
+ // Handle ON CONFLICT clause
106
+ let finalNode = nodeWithConvertedValues;
107
+ if (node.onConflict?.updates && entityMeta) {
108
+ // Create a temporary UpdateQueryNode to reuse processOnUpdateHooks and processUpdateValues
109
+ // We only care about the updates part
110
+ const tempUpdateNode = {
111
+ kind: 'UpdateQueryNode',
112
+ table: node.into, // Dummy table
113
+ updates: node.onConflict.updates,
114
+ };
115
+ const updatesWithHooks = this.#options.processOnUpdateHooks
116
+ ? this.processOnUpdateHooks(tempUpdateNode, entityMeta).updates
117
+ : node.onConflict.updates;
118
+ const tempUpdateNodeWithHooks = {
119
+ ...tempUpdateNode,
120
+ updates: updatesWithHooks,
121
+ };
122
+ const updatesWithConvertedValues = this.#options.convertValues
123
+ ? this.processUpdateValues(tempUpdateNodeWithHooks, entityMeta).updates
124
+ : updatesWithHooks;
125
+ if (updatesWithConvertedValues && updatesWithConvertedValues !== node.onConflict.updates) {
126
+ // Construct the new OnConflictNode with updated values
127
+ finalNode = {
128
+ ...finalNode,
129
+ onConflict: {
130
+ ...node.onConflict,
131
+ updates: updatesWithConvertedValues,
132
+ },
133
+ };
134
+ }
135
+ }
136
+ return super.transformInsertQuery(finalNode, queryId);
137
+ } finally {
138
+ this.#contextStack.pop();
139
+ }
140
+ }
141
+ transformUpdateQuery(node, queryId) {
142
+ const currentContext = new Map();
143
+ this.#contextStack.push(currentContext);
144
+ try {
145
+ let entityMeta;
146
+ if (node.table && TableNode.is(node.table)) {
147
+ const tableName = this.getTableName(node.table);
148
+ if (tableName) {
149
+ const meta = this.findEntityMetadata(tableName);
150
+ if (meta) {
151
+ entityMeta = meta;
152
+ currentContext.set(meta.tableName, meta);
153
+ this.#entityMap.set(meta.tableName, meta);
154
+ }
155
+ }
156
+ }
157
+ // Process FROM clause in UPDATE queries (for UPDATE with JOIN)
158
+ if (node.from) {
159
+ for (const fromItem of node.from.froms) {
160
+ this.processFromItem(fromItem, currentContext);
161
+ }
162
+ }
163
+ // Also process JOINs in UPDATE queries
164
+ if (node.joins) {
165
+ for (const join of node.joins) {
166
+ this.processJoinNode(join, currentContext);
167
+ }
168
+ }
169
+ const nodeWithHooks =
170
+ this.#options.processOnUpdateHooks && entityMeta ? this.processOnUpdateHooks(node, entityMeta) : node;
171
+ const nodeWithConvertedValues =
172
+ this.#options.convertValues && entityMeta ? this.processUpdateValues(nodeWithHooks, entityMeta) : nodeWithHooks;
173
+ return super.transformUpdateQuery(nodeWithConvertedValues, queryId);
174
+ } finally {
175
+ this.#contextStack.pop();
176
+ }
177
+ }
178
+ transformDeleteQuery(node, queryId) {
179
+ const currentContext = new Map();
180
+ this.#contextStack.push(currentContext);
181
+ try {
182
+ const froms = node.from?.froms;
183
+ if (froms && froms.length > 0) {
184
+ const firstFrom = froms[0];
185
+ if (TableNode.is(firstFrom)) {
186
+ const tableName = this.getTableName(firstFrom);
187
+ if (tableName) {
188
+ const meta = this.findEntityMetadata(tableName);
211
189
  if (meta) {
212
- return {
213
- ...node,
214
- name: meta.tableName,
215
- };
216
- }
217
- }
218
- // Transform column names when columnNamingStrategy is 'property'
219
- // Support ColumnNode, ColumnUpdateNode, and ReferenceNode (for JOIN conditions)
220
- if (this.#options.columnNamingStrategy === 'property' &&
221
- parent &&
222
- (ColumnNode.is(parent) || ColumnUpdateNode.is(parent) || ReferenceNode.is(parent))) {
223
- const ownerMeta = this.findOwnerEntityInContext();
224
- if (ownerMeta) {
225
- const prop = ownerMeta.properties[node.name];
226
- const fieldName = prop?.fieldNames?.[0];
227
- if (fieldName) {
228
- return {
229
- ...node,
230
- name: fieldName,
231
- };
232
- }
233
- }
234
- }
235
- return node;
236
- }
237
- /**
238
- * Find owner entity metadata for the current identifier in the context stack.
239
- * Supports both aliased and non-aliased table references.
240
- * Searches up the context stack to support correlated subqueries.
241
- * Also checks subquery/CTE aliases to resolve to their source tables.
242
- */
243
- findOwnerEntityInContext() {
244
- // Check if current column has a table reference (e.g., u.firstName)
245
- const reference = this.nodeStack.find(it => ReferenceNode.is(it));
246
- if (reference?.table && TableNode.is(reference.table)) {
247
- const tableName = this.getTableName(reference.table);
248
- if (tableName) {
249
- // First, check in subquery alias map (for CTE/subquery columns)
250
- if (this.#subqueryAliasMap.has(tableName)) {
251
- return this.#subqueryAliasMap.get(tableName);
252
- }
253
- // Find entity metadata to get the actual table name
254
- // Context uses table names (meta.tableName) as keys, not entity names
255
- const entityMeta = this.findEntityMetadata(tableName);
256
- if (entityMeta) {
257
- // Search in context stack using the actual table name
258
- const meta = this.lookupInContextStack(entityMeta.tableName);
259
- if (meta) {
260
- return meta;
261
- }
262
- // Also try with the entity name (for cases where context uses entity name)
263
- const metaByEntityName = this.lookupInContextStack(tableName);
264
- if (metaByEntityName) {
265
- return metaByEntityName;
266
- }
267
- }
268
- else {
269
- // If entity metadata not found, try direct lookup (for CTE/subquery cases)
270
- const meta = this.lookupInContextStack(tableName);
271
- if (meta) {
272
- return meta;
273
- }
274
- }
275
- }
276
- }
277
- // If no explicit table reference, use the first entity in current context
278
- if (this.#contextStack.length > 0) {
279
- const currentContext = this.#contextStack[this.#contextStack.length - 1];
280
- for (const [alias, meta] of currentContext.entries()) {
281
- if (meta) {
282
- return meta;
283
- }
284
- // If the context value is undefined but the alias is in subqueryAliasMap,
285
- // use the mapped metadata (for CTE/subquery cases)
286
- if (!meta && this.#subqueryAliasMap.has(alias)) {
287
- const mappedMeta = this.#subqueryAliasMap.get(alias);
288
- if (mappedMeta) {
289
- return mappedMeta;
290
- }
291
- }
292
- }
293
- }
294
- return undefined;
295
- }
296
- processOnCreateHooks(node, meta) {
297
- if (!node.columns || !node.values || !ValuesNode.is(node.values)) {
298
- return node;
299
- }
300
- const existingProps = new Set();
301
- for (const col of node.columns) {
302
- const prop = this.findProperty(meta, this.normalizeColumnName(col.column));
303
- if (prop) {
304
- existingProps.add(prop.name);
305
- }
306
- }
307
- const missingProps = meta.props.filter(prop => prop.onCreate && !existingProps.has(prop.name));
308
- if (missingProps.length === 0) {
309
- return node;
310
- }
311
- const newColumns = [...node.columns];
312
- for (const prop of missingProps) {
313
- newColumns.push(ColumnNode.create(prop.name));
314
- }
315
- const newRows = node.values.values.map(row => {
316
- const valuesToAdd = missingProps.map(prop => {
317
- const val = prop.onCreate(undefined, this.#em);
318
- return val;
319
- });
320
- if (ValueListNode.is(row)) {
321
- const newValues = [...row.values, ...valuesToAdd.map(v => ValueNode.create(v))];
322
- return ValueListNode.create(newValues);
323
- }
324
- if (PrimitiveValueListNode.is(row)) {
325
- const newValues = [...row.values, ...valuesToAdd];
326
- return PrimitiveValueListNode.create(newValues);
327
- }
328
- return row;
329
- });
190
+ currentContext.set(meta.tableName, meta);
191
+ this.#entityMap.set(meta.tableName, meta);
192
+ }
193
+ }
194
+ }
195
+ }
196
+ // Also process JOINs in DELETE queries
197
+ if (node.joins) {
198
+ for (const join of node.joins) {
199
+ this.processJoinNode(join, currentContext);
200
+ }
201
+ }
202
+ return super.transformDeleteQuery(node, queryId);
203
+ } finally {
204
+ this.#contextStack.pop();
205
+ }
206
+ }
207
+ transformMergeQuery(node, queryId) {
208
+ const currentContext = new Map();
209
+ this.#contextStack.push(currentContext);
210
+ try {
211
+ return super.transformMergeQuery(node, queryId);
212
+ } finally {
213
+ this.#contextStack.pop();
214
+ }
215
+ }
216
+ transformIdentifier(node, queryId) {
217
+ node = super.transformIdentifier(node, queryId);
218
+ const parent = this.nodeStack[this.nodeStack.length - 2];
219
+ // Transform table names when tableNamingStrategy is 'entity'
220
+ if (this.#options.tableNamingStrategy === 'entity' && parent && SchemableIdentifierNode.is(parent)) {
221
+ const meta = this.findEntityMetadata(node.name);
222
+ if (meta) {
330
223
  return {
331
- ...node,
332
- columns: Object.freeze(newColumns),
333
- values: ValuesNode.create(newRows),
224
+ ...node,
225
+ name: meta.tableName,
334
226
  };
335
- }
336
- processOnUpdateHooks(node, meta) {
337
- if (!node.updates) {
338
- return node;
339
- }
340
- const existingProps = new Set();
341
- for (const update of node.updates) {
342
- if (ColumnNode.is(update.column)) {
343
- const prop = this.findProperty(meta, this.normalizeColumnName(update.column.column));
344
- if (prop) {
345
- existingProps.add(prop.name);
346
- }
347
- }
348
- }
349
- const missingProps = meta.props.filter(prop => prop.onUpdate && !existingProps.has(prop.name));
350
- if (missingProps.length === 0) {
351
- return node;
352
- }
353
- const newUpdates = [...node.updates];
354
- for (const prop of missingProps) {
355
- const val = prop.onUpdate(undefined, this.#em);
356
- newUpdates.push(ColumnUpdateNode.create(ColumnNode.create(prop.name), ValueNode.create(val)));
357
- }
358
- return {
227
+ }
228
+ }
229
+ // Transform column names when columnNamingStrategy is 'property'
230
+ // Support ColumnNode, ColumnUpdateNode, and ReferenceNode (for JOIN conditions)
231
+ if (
232
+ this.#options.columnNamingStrategy === 'property' &&
233
+ parent &&
234
+ (ColumnNode.is(parent) || ColumnUpdateNode.is(parent) || ReferenceNode.is(parent))
235
+ ) {
236
+ const ownerMeta = this.findOwnerEntityInContext();
237
+ if (ownerMeta) {
238
+ const prop = ownerMeta.properties[node.name];
239
+ const fieldName = prop?.fieldNames?.[0];
240
+ if (fieldName) {
241
+ return {
359
242
  ...node,
360
- updates: Object.freeze(newUpdates),
361
- };
362
- }
363
- processInsertValues(node, meta) {
364
- if (!node.columns?.length || !node.values || !ValuesNode.is(node.values)) {
365
- return node;
366
- }
367
- const columnProps = this.mapColumnsToProperties(node.columns, meta);
368
- const shouldConvert = this.shouldConvertValues();
369
- let changed = false;
370
- const convertedRows = node.values.values.map(row => {
371
- if (ValueListNode.is(row)) {
372
- if (row.values.length !== columnProps.length) {
373
- return row;
374
- }
375
- const values = row.values.map((valueNode, idx) => {
376
- if (!ValueNode.is(valueNode)) {
377
- return valueNode;
378
- }
379
- const converted = this.prepareInputValue(columnProps[idx], valueNode.value, shouldConvert);
380
- if (converted === valueNode.value) {
381
- return valueNode;
382
- }
383
- changed = true;
384
- return valueNode.immediate ? ValueNode.createImmediate(converted) : ValueNode.create(converted);
385
- });
386
- return ValueListNode.create(values);
387
- }
388
- if (PrimitiveValueListNode.is(row)) {
389
- if (row.values.length !== columnProps.length) {
390
- return row;
391
- }
392
- const values = row.values.map((value, idx) => {
393
- const converted = this.prepareInputValue(columnProps[idx], value, shouldConvert);
394
- if (converted !== value) {
395
- changed = true;
396
- }
397
- return converted;
398
- });
399
- return PrimitiveValueListNode.create(values);
400
- }
401
- return row;
243
+ name: fieldName,
244
+ };
245
+ }
246
+ }
247
+ }
248
+ return node;
249
+ }
250
+ /**
251
+ * Find owner entity metadata for the current identifier in the context stack.
252
+ * Supports both aliased and non-aliased table references.
253
+ * Searches up the context stack to support correlated subqueries.
254
+ * Also checks subquery/CTE aliases to resolve to their source tables.
255
+ */
256
+ findOwnerEntityInContext() {
257
+ // Check if current column has a table reference (e.g., u.firstName)
258
+ const reference = this.nodeStack.find(it => ReferenceNode.is(it));
259
+ if (reference?.table && TableNode.is(reference.table)) {
260
+ const tableName = this.getTableName(reference.table);
261
+ if (tableName) {
262
+ // First, check in subquery alias map (for CTE/subquery columns)
263
+ if (this.#subqueryAliasMap.has(tableName)) {
264
+ return this.#subqueryAliasMap.get(tableName);
265
+ }
266
+ // Find entity metadata to get the actual table name
267
+ // Context uses table names (meta.tableName) as keys, not entity names
268
+ const entityMeta = this.findEntityMetadata(tableName);
269
+ if (entityMeta) {
270
+ // Search in context stack using the actual table name
271
+ const meta = this.lookupInContextStack(entityMeta.tableName);
272
+ if (meta) {
273
+ return meta;
274
+ }
275
+ // Also try with the entity name (for cases where context uses entity name)
276
+ const metaByEntityName = this.lookupInContextStack(tableName);
277
+ if (metaByEntityName) {
278
+ return metaByEntityName;
279
+ }
280
+ } else {
281
+ // If entity metadata not found, try direct lookup (for CTE/subquery cases)
282
+ const meta = this.lookupInContextStack(tableName);
283
+ if (meta) {
284
+ return meta;
285
+ }
286
+ }
287
+ }
288
+ }
289
+ // If no explicit table reference, use the first entity in current context
290
+ if (this.#contextStack.length > 0) {
291
+ const currentContext = this.#contextStack[this.#contextStack.length - 1];
292
+ for (const [alias, meta] of currentContext.entries()) {
293
+ if (meta) {
294
+ return meta;
295
+ }
296
+ // If the context value is undefined but the alias is in subqueryAliasMap,
297
+ // use the mapped metadata (for CTE/subquery cases)
298
+ if (!meta && this.#subqueryAliasMap.has(alias)) {
299
+ const mappedMeta = this.#subqueryAliasMap.get(alias);
300
+ if (mappedMeta) {
301
+ return mappedMeta;
302
+ }
303
+ }
304
+ }
305
+ }
306
+ return undefined;
307
+ }
308
+ processOnCreateHooks(node, meta) {
309
+ if (!node.columns || !node.values || !ValuesNode.is(node.values)) {
310
+ return node;
311
+ }
312
+ const existingProps = new Set();
313
+ for (const col of node.columns) {
314
+ const prop = this.findProperty(meta, this.normalizeColumnName(col.column));
315
+ if (prop) {
316
+ existingProps.add(prop.name);
317
+ }
318
+ }
319
+ const missingProps = meta.props.filter(prop => prop.onCreate && !existingProps.has(prop.name));
320
+ if (missingProps.length === 0) {
321
+ return node;
322
+ }
323
+ const newColumns = [...node.columns];
324
+ for (const prop of missingProps) {
325
+ newColumns.push(ColumnNode.create(prop.name));
326
+ }
327
+ const newRows = node.values.values.map(row => {
328
+ const valuesToAdd = missingProps.map(prop => {
329
+ const val = prop.onCreate(undefined, this.#em);
330
+ return val;
331
+ });
332
+ if (ValueListNode.is(row)) {
333
+ const newValues = [...row.values, ...valuesToAdd.map(v => ValueNode.create(v))];
334
+ return ValueListNode.create(newValues);
335
+ }
336
+ if (PrimitiveValueListNode.is(row)) {
337
+ const newValues = [...row.values, ...valuesToAdd];
338
+ return PrimitiveValueListNode.create(newValues);
339
+ }
340
+ return row;
341
+ });
342
+ return {
343
+ ...node,
344
+ columns: Object.freeze(newColumns),
345
+ values: ValuesNode.create(newRows),
346
+ };
347
+ }
348
+ processOnUpdateHooks(node, meta) {
349
+ if (!node.updates) {
350
+ return node;
351
+ }
352
+ const existingProps = new Set();
353
+ for (const update of node.updates) {
354
+ if (ColumnNode.is(update.column)) {
355
+ const prop = this.findProperty(meta, this.normalizeColumnName(update.column.column));
356
+ if (prop) {
357
+ existingProps.add(prop.name);
358
+ }
359
+ }
360
+ }
361
+ const missingProps = meta.props.filter(prop => prop.onUpdate && !existingProps.has(prop.name));
362
+ if (missingProps.length === 0) {
363
+ return node;
364
+ }
365
+ const newUpdates = [...node.updates];
366
+ for (const prop of missingProps) {
367
+ const val = prop.onUpdate(undefined, this.#em);
368
+ newUpdates.push(ColumnUpdateNode.create(ColumnNode.create(prop.name), ValueNode.create(val)));
369
+ }
370
+ return {
371
+ ...node,
372
+ updates: Object.freeze(newUpdates),
373
+ };
374
+ }
375
+ processInsertValues(node, meta) {
376
+ if (!node.columns?.length || !node.values || !ValuesNode.is(node.values)) {
377
+ return node;
378
+ }
379
+ const columnProps = this.mapColumnsToProperties(node.columns, meta);
380
+ const shouldConvert = this.shouldConvertValues();
381
+ let changed = false;
382
+ const convertedRows = node.values.values.map(row => {
383
+ if (ValueListNode.is(row)) {
384
+ if (row.values.length !== columnProps.length) {
385
+ return row;
386
+ }
387
+ const values = row.values.map((valueNode, idx) => {
388
+ if (!ValueNode.is(valueNode)) {
389
+ return valueNode;
390
+ }
391
+ const converted = this.prepareInputValue(columnProps[idx], valueNode.value, shouldConvert);
392
+ if (converted === valueNode.value) {
393
+ return valueNode;
394
+ }
395
+ changed = true;
396
+ return valueNode.immediate ? ValueNode.createImmediate(converted) : ValueNode.create(converted);
402
397
  });
403
- if (!changed) {
404
- return node;
405
- }
406
- return {
407
- ...node,
408
- values: ValuesNode.create(convertedRows),
409
- };
410
- }
411
- processUpdateValues(node, meta) {
412
- if (!node.updates?.length) {
413
- return node;
414
- }
415
- const shouldConvert = this.shouldConvertValues();
416
- let changed = false;
417
- const updates = node.updates.map(updateNode => {
418
- if (!ValueNode.is(updateNode.value)) {
419
- return updateNode;
420
- }
421
- const columnName = ColumnNode.is(updateNode.column)
422
- ? this.normalizeColumnName(updateNode.column.column)
423
- : undefined;
424
- const property = this.findProperty(meta, columnName);
425
- const converted = this.prepareInputValue(property, updateNode.value.value, shouldConvert);
426
- if (converted === updateNode.value.value) {
427
- return updateNode;
428
- }
398
+ return ValueListNode.create(values);
399
+ }
400
+ if (PrimitiveValueListNode.is(row)) {
401
+ if (row.values.length !== columnProps.length) {
402
+ return row;
403
+ }
404
+ const values = row.values.map((value, idx) => {
405
+ const converted = this.prepareInputValue(columnProps[idx], value, shouldConvert);
406
+ if (converted !== value) {
429
407
  changed = true;
430
- const newValueNode = updateNode.value.immediate
431
- ? ValueNode.createImmediate(converted)
432
- : ValueNode.create(converted);
433
- return {
434
- ...updateNode,
435
- value: newValueNode,
436
- };
408
+ }
409
+ return converted;
437
410
  });
438
- if (!changed) {
439
- return node;
440
- }
441
- return {
442
- ...node,
443
- updates,
444
- };
445
- }
446
- mapColumnsToProperties(columns, meta) {
447
- return columns.map(column => {
448
- const columnName = this.normalizeColumnName(column.column);
449
- return this.findProperty(meta, columnName);
450
- });
451
- }
452
- normalizeColumnName(identifier) {
453
- const name = identifier.name;
454
- if (!name.includes('.')) {
455
- return name;
456
- }
457
- const parts = name.split('.');
458
- return parts[parts.length - 1] ?? name;
459
- }
460
- findProperty(meta, columnName) {
461
- if (!meta || !columnName) {
462
- return undefined;
463
- }
464
- if (meta.properties[columnName]) {
465
- return meta.properties[columnName];
466
- }
467
- return meta.props.find(prop => prop.fieldNames?.includes(columnName));
468
- }
469
- shouldConvertValues() {
470
- return !!this.#options.convertValues;
471
- }
472
- prepareInputValue(prop, value, enabled) {
473
- if (!enabled || !prop || value == null) {
474
- return value;
475
- }
476
- if (typeof value === 'object' && value !== null) {
477
- if (isRaw(value)) {
478
- return value;
479
- }
480
- if ('kind' in value) {
481
- return value;
482
- }
483
- }
484
- if (prop.customType && !isRaw(value)) {
485
- return prop.customType.convertToDatabaseValue(value, this.#platform, {
486
- fromQuery: true,
487
- key: prop.name,
488
- mode: 'query-data',
489
- });
490
- }
491
- if (value instanceof Date) {
492
- return this.#platform.processDateProperty(value);
493
- }
411
+ return PrimitiveValueListNode.create(values);
412
+ }
413
+ return row;
414
+ });
415
+ if (!changed) {
416
+ return node;
417
+ }
418
+ return {
419
+ ...node,
420
+ values: ValuesNode.create(convertedRows),
421
+ };
422
+ }
423
+ processUpdateValues(node, meta) {
424
+ if (!node.updates?.length) {
425
+ return node;
426
+ }
427
+ const shouldConvert = this.shouldConvertValues();
428
+ let changed = false;
429
+ const updates = node.updates.map(updateNode => {
430
+ if (!ValueNode.is(updateNode.value)) {
431
+ return updateNode;
432
+ }
433
+ const columnName = ColumnNode.is(updateNode.column)
434
+ ? this.normalizeColumnName(updateNode.column.column)
435
+ : undefined;
436
+ const property = this.findProperty(meta, columnName);
437
+ const converted = this.prepareInputValue(property, updateNode.value.value, shouldConvert);
438
+ if (converted === updateNode.value.value) {
439
+ return updateNode;
440
+ }
441
+ changed = true;
442
+ const newValueNode = updateNode.value.immediate
443
+ ? ValueNode.createImmediate(converted)
444
+ : ValueNode.create(converted);
445
+ return {
446
+ ...updateNode,
447
+ value: newValueNode,
448
+ };
449
+ });
450
+ if (!changed) {
451
+ return node;
452
+ }
453
+ return {
454
+ ...node,
455
+ updates,
456
+ };
457
+ }
458
+ mapColumnsToProperties(columns, meta) {
459
+ return columns.map(column => {
460
+ const columnName = this.normalizeColumnName(column.column);
461
+ return this.findProperty(meta, columnName);
462
+ });
463
+ }
464
+ normalizeColumnName(identifier) {
465
+ const name = identifier.name;
466
+ if (!name.includes('.')) {
467
+ return name;
468
+ }
469
+ const parts = name.split('.');
470
+ return parts[parts.length - 1] ?? name;
471
+ }
472
+ findProperty(meta, columnName) {
473
+ if (!meta || !columnName) {
474
+ return undefined;
475
+ }
476
+ if (meta.properties[columnName]) {
477
+ return meta.properties[columnName];
478
+ }
479
+ return meta.props.find(prop => prop.fieldNames?.includes(columnName));
480
+ }
481
+ shouldConvertValues() {
482
+ return !!this.#options.convertValues;
483
+ }
484
+ prepareInputValue(prop, value, enabled) {
485
+ if (!enabled || !prop || value == null) {
486
+ return value;
487
+ }
488
+ if (typeof value === 'object' && value !== null) {
489
+ if (isRaw(value)) {
494
490
  return value;
495
- }
496
- /**
497
- * Look up a table name/alias in the context stack.
498
- * Searches from current scope (top of stack) to parent scopes (bottom).
499
- * This supports correlated subqueries and references to outer query tables.
500
- */
501
- lookupInContextStack(tableNameOrAlias) {
502
- // Search from top of stack (current scope) to bottom (parent scopes)
503
- for (let i = this.#contextStack.length - 1; i >= 0; i--) {
504
- const context = this.#contextStack[i];
505
- if (context.has(tableNameOrAlias)) {
506
- return context.get(tableNameOrAlias);
507
- }
508
- }
509
- return undefined;
510
- }
511
- /**
512
- * Process WITH node (CTE definitions)
513
- */
514
- processWithNode(withNode, context) {
515
- for (const cte of withNode.expressions) {
516
- const cteName = this.getCTEName(cte.name);
517
- if (cteName) {
518
- // CTEs are not entities, so map to undefined
519
- // They will be transformed recursively by transformSelectQuery
520
- context.set(cteName, undefined);
521
- // Also try to extract the source table from the CTE's expression
522
- // This helps resolve columns in subsequent queries that use the CTE
523
- if (cte.expression?.kind === 'SelectQueryNode') {
524
- const sourceMeta = this.extractSourceTableFromSelectQuery(cte.expression);
525
- if (sourceMeta) {
526
- this.#subqueryAliasMap.set(cteName, sourceMeta);
527
- // Add CTE to entityMap so it can be used for result transformation if needed
528
- // (though CTEs usually don't appear in result rows directly, but their columns might)
529
- this.#entityMap.set(cteName, sourceMeta);
530
- }
531
- }
532
- }
533
- }
534
- }
535
- /**
536
- * Extract CTE name from CommonTableExpressionNameNode
537
- */
538
- getCTEName(nameNode) {
539
- if (TableNode.is(nameNode.table)) {
540
- return this.getTableName(nameNode.table);
541
- }
542
- return undefined;
543
- }
544
- /**
545
- * Process a FROM item (can be TableNode or AliasNode)
546
- */
547
- processFromItem(from, // OperationNode type - can be TableNode, AliasNode, or SelectQueryNode
548
- context) {
549
- if (AliasNode.is(from)) {
550
- if (TableNode.is(from.node)) {
551
- // Regular table with alias
552
- const tableName = this.getTableName(from.node);
553
- if (tableName && from.alias) {
554
- const meta = this.findEntityMetadata(tableName);
555
- const aliasName = this.extractAliasName(from.alias);
556
- if (aliasName) {
557
- context.set(aliasName, meta);
558
- if (meta) {
559
- this.#entityMap.set(aliasName, meta);
560
- }
561
- // Also map the alias in subqueryAliasMap if the table name is a CTE
562
- if (this.#subqueryAliasMap.has(tableName)) {
563
- this.#subqueryAliasMap.set(aliasName, this.#subqueryAliasMap.get(tableName));
564
- }
565
- }
566
- }
567
- }
568
- else if (from.node?.kind === 'SelectQueryNode') {
569
- // Subquery with alias
570
- const aliasName = this.extractAliasName(from.alias);
571
- if (aliasName) {
572
- context.set(aliasName, undefined);
573
- // Try to extract the source table from the subquery
574
- const sourceMeta = this.extractSourceTableFromSelectQuery(from.node);
575
- if (sourceMeta) {
576
- this.#subqueryAliasMap.set(aliasName, sourceMeta);
577
- }
578
- }
579
- }
580
- else {
581
- // Other types with alias
582
- const aliasName = this.extractAliasName(from.alias);
583
- if (aliasName) {
584
- context.set(aliasName, undefined);
585
- }
586
- }
587
- }
588
- else if (TableNode.is(from)) {
589
- // Table without alias
590
- const tableName = this.getTableName(from);
591
- if (tableName) {
592
- const meta = this.findEntityMetadata(tableName);
593
- context.set(tableName, meta);
594
- if (meta) {
595
- this.#entityMap.set(tableName, meta);
596
- }
597
- }
598
- }
599
- }
600
- /**
601
- * Process a JOIN node
602
- */
603
- processJoinNode(join, context) {
604
- const joinTable = join.table;
605
- if (AliasNode.is(joinTable)) {
606
- if (TableNode.is(joinTable.node)) {
607
- // Regular table with alias in JOIN
608
- const tableName = this.getTableName(joinTable.node);
609
- if (tableName && joinTable.alias) {
610
- const meta = this.findEntityMetadata(tableName);
611
- const aliasName = this.extractAliasName(joinTable.alias);
612
- if (aliasName) {
613
- context.set(aliasName, meta);
614
- if (meta) {
615
- this.#entityMap.set(aliasName, meta);
616
- }
617
- // Also map the alias in subqueryAliasMap if the table name is a CTE
618
- if (this.#subqueryAliasMap.has(tableName)) {
619
- this.#subqueryAliasMap.set(aliasName, this.#subqueryAliasMap.get(tableName));
620
- }
621
- }
622
- }
623
- }
624
- else if (joinTable.node?.kind === 'SelectQueryNode') {
625
- // Subquery with alias in JOIN
626
- const aliasName = this.extractAliasName(joinTable.alias);
627
- if (aliasName) {
628
- context.set(aliasName, undefined);
629
- // Try to extract the source table from the subquery
630
- const sourceMeta = this.extractSourceTableFromSelectQuery(joinTable.node);
631
- if (sourceMeta) {
632
- this.#subqueryAliasMap.set(aliasName, sourceMeta);
633
- }
634
- }
635
- }
636
- else {
637
- // Other types with alias
638
- const aliasName = this.extractAliasName(joinTable.alias);
639
- if (aliasName) {
640
- context.set(aliasName, undefined);
641
- }
642
- }
643
- }
644
- else if (TableNode.is(joinTable)) {
645
- // Table without alias in JOIN
646
- const tableName = this.getTableName(joinTable);
647
- if (tableName) {
648
- const meta = this.findEntityMetadata(tableName);
649
- // Use table name (meta.tableName) as key to match transformUpdateQuery behavior
650
- if (meta) {
651
- context.set(meta.tableName, meta);
652
- this.#entityMap.set(meta.tableName, meta);
653
- // Also set with entity name for backward compatibility
654
- context.set(tableName, meta);
655
- }
656
- else {
657
- context.set(tableName, undefined);
658
- }
659
- }
660
- }
661
- }
662
- /**
663
- * Extract the primary source table from a SELECT query
664
- * This helps resolve columns from subqueries to their original entity tables
665
- */
666
- extractSourceTableFromSelectQuery(selectQuery) {
667
- if (!selectQuery.from?.froms || selectQuery.from.froms.length === 0) {
668
- return undefined;
669
- }
670
- // Get the first FROM table
671
- const firstFrom = selectQuery.from.froms[0];
672
- let sourceTable;
673
- if (AliasNode.is(firstFrom) && TableNode.is(firstFrom.node)) {
674
- sourceTable = firstFrom.node;
675
- }
676
- else if (TableNode.is(firstFrom)) {
677
- sourceTable = firstFrom;
678
- }
679
- if (sourceTable) {
680
- const tableName = this.getTableName(sourceTable);
681
- if (tableName) {
682
- return this.findEntityMetadata(tableName);
683
- }
684
- }
685
- return undefined;
686
- }
687
- /**
688
- * Extract alias name from an alias node
689
- */
690
- extractAliasName(alias) {
691
- if (typeof alias === 'object' && 'name' in alias) {
692
- return alias.name;
693
- }
694
- return undefined;
695
- }
696
- /**
697
- * Extract table name from a TableNode
698
- */
699
- getTableName(node) {
700
- if (!node) {
701
- return undefined;
702
- }
703
- if (TableNode.is(node) && SchemableIdentifierNode.is(node.table)) {
704
- const identifier = node.table.identifier;
705
- if (typeof identifier === 'object' && 'name' in identifier) {
706
- return identifier.name;
707
- }
708
- }
709
- return undefined;
710
- }
711
- /**
712
- * Find entity metadata by table name or entity name
713
- */
714
- findEntityMetadata(name) {
715
- const byEntity = this.#metadata.getByClassName(name, false);
716
- if (byEntity) {
717
- return byEntity;
718
- }
719
- const allMetadata = Array.from(this.#metadata);
720
- const byTable = allMetadata.find(m => m.tableName === name);
721
- if (byTable) {
722
- return byTable;
723
- }
724
- return undefined;
725
- }
726
- /**
727
- * Transform result rows by mapping database column names to property names
728
- * This is called for SELECT queries when columnNamingStrategy is 'property'
729
- */
730
- transformResult(rows, entityMap) {
731
- // Only transform if columnNamingStrategy is 'property' or convertValues is true, and we have data
732
- if ((this.#options.columnNamingStrategy !== 'property' && !this.#options.convertValues) ||
733
- !rows ||
734
- rows.length === 0) {
735
- return rows;
736
- }
737
- // If no entities found (e.g. raw query without known tables), return rows as is
738
- if (entityMap.size === 0) {
739
- return rows;
740
- }
741
- // Build a global mapping from database field names to property objects
742
- const fieldToPropertyMap = this.buildGlobalFieldMap(entityMap);
743
- const relationFieldMap = this.buildGlobalRelationFieldMap(entityMap);
744
- // Transform each row
745
- return rows.map(row => this.transformRow(row, fieldToPropertyMap, relationFieldMap));
746
- }
747
- buildGlobalFieldMap(entityMap) {
748
- const map = {};
749
- for (const [alias, meta] of entityMap.entries()) {
750
- Object.assign(map, this.buildFieldToPropertyMap(meta, alias));
751
- }
752
- return map;
753
- }
754
- buildGlobalRelationFieldMap(entityMap) {
755
- const map = {};
756
- for (const [alias, meta] of entityMap.entries()) {
757
- Object.assign(map, this.buildRelationFieldMap(meta, alias));
758
- }
759
- return map;
760
- }
761
- /**
762
- * Build a mapping from database field names to property objects
763
- * Format: { 'field_name': EntityProperty }
764
- */
765
- buildFieldToPropertyMap(meta, alias) {
766
- const map = {};
767
- for (const prop of meta.props) {
768
- if (prop.fieldNames && prop.fieldNames.length > 0) {
769
- for (const fieldName of prop.fieldNames) {
770
- if (!(fieldName in map)) {
771
- map[fieldName] = prop;
772
- }
773
- if (alias) {
774
- const dotted = `${alias}.${fieldName}`;
775
- if (!(dotted in map)) {
776
- map[dotted] = prop;
777
- }
778
- const underscored = `${alias}_${fieldName}`;
779
- if (!(underscored in map)) {
780
- map[underscored] = prop;
781
- }
782
- const doubleUnderscored = `${alias}__${fieldName}`;
783
- if (!(doubleUnderscored in map)) {
784
- map[doubleUnderscored] = prop;
785
- }
786
- }
787
- }
788
- }
789
- if (!(prop.name in map)) {
790
- map[prop.name] = prop;
791
- }
792
- }
793
- return map;
794
- }
795
- /**
796
- * Build a mapping for relation fields
797
- * For ManyToOne relations, we need to map from the foreign key field to the relation property
798
- * Format: { 'foreign_key_field': 'relationPropertyName' }
799
- */
800
- buildRelationFieldMap(meta, alias) {
801
- const map = {};
802
- for (const prop of meta.props) {
803
- // For ManyToOne/OneToOne relations, find the foreign key field
804
- if (prop.kind === ReferenceKind.MANY_TO_ONE || prop.kind === ReferenceKind.ONE_TO_ONE) {
805
- if (prop.fieldNames && prop.fieldNames.length > 0) {
806
- const fieldName = prop.fieldNames[0];
807
- map[fieldName] = prop.name;
808
- if (alias) {
809
- map[`${alias}.${fieldName}`] = prop.name;
810
- map[`${alias}_${fieldName}`] = prop.name;
811
- map[`${alias}__${fieldName}`] = prop.name;
812
- }
813
- }
814
- }
815
- }
816
- return map;
817
- }
818
- /**
819
- * Transform a single row by mapping column names to property names
820
- */
821
- transformRow(row, fieldToPropertyMap, relationFieldMap) {
822
- const transformed = { ...row };
823
- // First pass: map regular fields from fieldName to propertyName and convert values
824
- for (const [fieldName, prop] of Object.entries(fieldToPropertyMap)) {
825
- if (!(fieldName in transformed)) {
826
- continue;
827
- }
828
- const converted = this.prepareOutputValue(prop, transformed[fieldName]);
829
- if (this.#options.columnNamingStrategy === 'property' && prop.name !== fieldName) {
830
- if (!(prop.name in transformed)) {
831
- transformed[prop.name] = converted;
832
- }
833
- else {
834
- transformed[prop.name] = converted;
835
- }
836
- delete transformed[fieldName];
837
- continue;
838
- }
839
- if (this.#options.convertValues) {
840
- transformed[fieldName] = converted;
841
- }
842
- }
843
- // Second pass: handle relation fields
844
- // Only run if columnNamingStrategy is 'property', as we don't want to rename FKs otherwise
845
- if (this.#options.columnNamingStrategy === 'property') {
846
- for (const [fieldName, relationPropertyName] of Object.entries(relationFieldMap)) {
847
- if (fieldName in transformed && !(relationPropertyName in transformed)) {
848
- // Move the foreign key value to the relation property name
849
- transformed[relationPropertyName] = transformed[fieldName];
850
- delete transformed[fieldName];
851
- }
852
- }
853
- }
854
- return transformed;
855
- }
856
- prepareOutputValue(prop, value) {
857
- if (!this.#options.convertValues || !prop || value == null) {
858
- return value;
859
- }
860
- if (prop.customType) {
861
- return prop.customType.convertToJSValue(value, this.#platform);
862
- }
863
- // Aligned with EntityComparator.getResultMapper logic
864
- if (prop.runtimeType === 'boolean') {
865
- // Use !! conversion like EntityComparator: value == null ? value : !!value
866
- return value == null ? value : !!value;
867
- }
868
- if (prop.runtimeType === 'Date' && !this.#platform.isNumericProperty(prop)) {
869
- // Aligned with EntityComparator: exclude numeric timestamp properties
870
- // If already Date instance or null, return as is
871
- if (value == null || value instanceof Date) {
872
- return value;
873
- }
874
- // Handle timezone like EntityComparator.parseDate
875
- const tz = this.#platform.getTimezone();
876
- if (!tz || tz === 'local') {
877
- return this.#platform.parseDate(value);
878
- }
879
- // For non-local timezone, check if value already has timezone info
880
- // Number (timestamp) doesn't need timezone handling, string needs check
881
- if (typeof value === 'number' ||
882
- (typeof value === 'string' && (value.includes('+') || value.lastIndexOf('-') > 10 || value.endsWith('Z')))) {
883
- return this.#platform.parseDate(value);
884
- }
885
- // Append timezone if not present (only for string values)
886
- return this.#platform.parseDate(value + tz);
887
- }
888
- // For all other runtimeTypes (number, string, bigint, Buffer, object, any, etc.)
889
- // EntityComparator just assigns directly without conversion
491
+ }
492
+ if ('kind' in value) {
890
493
  return value;
891
- }
494
+ }
495
+ }
496
+ if (prop.customType && !isRaw(value)) {
497
+ return prop.customType.convertToDatabaseValue(value, this.#platform, {
498
+ fromQuery: true,
499
+ key: prop.name,
500
+ mode: 'query-data',
501
+ });
502
+ }
503
+ if (value instanceof Date) {
504
+ return this.#platform.processDateProperty(value);
505
+ }
506
+ return value;
507
+ }
508
+ /**
509
+ * Look up a table name/alias in the context stack.
510
+ * Searches from current scope (top of stack) to parent scopes (bottom).
511
+ * This supports correlated subqueries and references to outer query tables.
512
+ */
513
+ lookupInContextStack(tableNameOrAlias) {
514
+ // Search from top of stack (current scope) to bottom (parent scopes)
515
+ for (let i = this.#contextStack.length - 1; i >= 0; i--) {
516
+ const context = this.#contextStack[i];
517
+ if (context.has(tableNameOrAlias)) {
518
+ return context.get(tableNameOrAlias);
519
+ }
520
+ }
521
+ return undefined;
522
+ }
523
+ /**
524
+ * Process WITH node (CTE definitions)
525
+ */
526
+ processWithNode(withNode, context) {
527
+ for (const cte of withNode.expressions) {
528
+ const cteName = this.getCTEName(cte.name);
529
+ if (cteName) {
530
+ // CTEs are not entities, so map to undefined
531
+ // They will be transformed recursively by transformSelectQuery
532
+ context.set(cteName, undefined);
533
+ // Also try to extract the source table from the CTE's expression
534
+ // This helps resolve columns in subsequent queries that use the CTE
535
+ if (cte.expression?.kind === 'SelectQueryNode') {
536
+ const sourceMeta = this.extractSourceTableFromSelectQuery(cte.expression);
537
+ if (sourceMeta) {
538
+ this.#subqueryAliasMap.set(cteName, sourceMeta);
539
+ // Add CTE to entityMap so it can be used for result transformation if needed
540
+ // (though CTEs usually don't appear in result rows directly, but their columns might)
541
+ this.#entityMap.set(cteName, sourceMeta);
542
+ }
543
+ }
544
+ }
545
+ }
546
+ }
547
+ /**
548
+ * Extract CTE name from CommonTableExpressionNameNode
549
+ */
550
+ getCTEName(nameNode) {
551
+ if (TableNode.is(nameNode.table)) {
552
+ return this.getTableName(nameNode.table);
553
+ }
554
+ return undefined;
555
+ }
556
+ /**
557
+ * Process a FROM item (can be TableNode or AliasNode)
558
+ */
559
+ processFromItem(
560
+ from, // OperationNode type - can be TableNode, AliasNode, or SelectQueryNode
561
+ context,
562
+ ) {
563
+ if (AliasNode.is(from)) {
564
+ if (TableNode.is(from.node)) {
565
+ // Regular table with alias
566
+ const tableName = this.getTableName(from.node);
567
+ if (tableName && from.alias) {
568
+ const meta = this.findEntityMetadata(tableName);
569
+ const aliasName = this.extractAliasName(from.alias);
570
+ if (aliasName) {
571
+ context.set(aliasName, meta);
572
+ if (meta) {
573
+ this.#entityMap.set(aliasName, meta);
574
+ }
575
+ // Also map the alias in subqueryAliasMap if the table name is a CTE
576
+ if (this.#subqueryAliasMap.has(tableName)) {
577
+ this.#subqueryAliasMap.set(aliasName, this.#subqueryAliasMap.get(tableName));
578
+ }
579
+ }
580
+ }
581
+ } else if (from.node?.kind === 'SelectQueryNode') {
582
+ // Subquery with alias
583
+ const aliasName = this.extractAliasName(from.alias);
584
+ if (aliasName) {
585
+ context.set(aliasName, undefined);
586
+ // Try to extract the source table from the subquery
587
+ const sourceMeta = this.extractSourceTableFromSelectQuery(from.node);
588
+ if (sourceMeta) {
589
+ this.#subqueryAliasMap.set(aliasName, sourceMeta);
590
+ }
591
+ }
592
+ } else {
593
+ // Other types with alias
594
+ const aliasName = this.extractAliasName(from.alias);
595
+ if (aliasName) {
596
+ context.set(aliasName, undefined);
597
+ }
598
+ }
599
+ } else if (TableNode.is(from)) {
600
+ // Table without alias
601
+ const tableName = this.getTableName(from);
602
+ if (tableName) {
603
+ const meta = this.findEntityMetadata(tableName);
604
+ context.set(tableName, meta);
605
+ if (meta) {
606
+ this.#entityMap.set(tableName, meta);
607
+ }
608
+ }
609
+ }
610
+ }
611
+ /**
612
+ * Process a JOIN node
613
+ */
614
+ processJoinNode(join, context) {
615
+ const joinTable = join.table;
616
+ if (AliasNode.is(joinTable)) {
617
+ if (TableNode.is(joinTable.node)) {
618
+ // Regular table with alias in JOIN
619
+ const tableName = this.getTableName(joinTable.node);
620
+ if (tableName && joinTable.alias) {
621
+ const meta = this.findEntityMetadata(tableName);
622
+ const aliasName = this.extractAliasName(joinTable.alias);
623
+ if (aliasName) {
624
+ context.set(aliasName, meta);
625
+ if (meta) {
626
+ this.#entityMap.set(aliasName, meta);
627
+ }
628
+ // Also map the alias in subqueryAliasMap if the table name is a CTE
629
+ if (this.#subqueryAliasMap.has(tableName)) {
630
+ this.#subqueryAliasMap.set(aliasName, this.#subqueryAliasMap.get(tableName));
631
+ }
632
+ }
633
+ }
634
+ } else if (joinTable.node?.kind === 'SelectQueryNode') {
635
+ // Subquery with alias in JOIN
636
+ const aliasName = this.extractAliasName(joinTable.alias);
637
+ if (aliasName) {
638
+ context.set(aliasName, undefined);
639
+ // Try to extract the source table from the subquery
640
+ const sourceMeta = this.extractSourceTableFromSelectQuery(joinTable.node);
641
+ if (sourceMeta) {
642
+ this.#subqueryAliasMap.set(aliasName, sourceMeta);
643
+ }
644
+ }
645
+ } else {
646
+ // Other types with alias
647
+ const aliasName = this.extractAliasName(joinTable.alias);
648
+ if (aliasName) {
649
+ context.set(aliasName, undefined);
650
+ }
651
+ }
652
+ } else if (TableNode.is(joinTable)) {
653
+ // Table without alias in JOIN
654
+ const tableName = this.getTableName(joinTable);
655
+ if (tableName) {
656
+ const meta = this.findEntityMetadata(tableName);
657
+ // Use table name (meta.tableName) as key to match transformUpdateQuery behavior
658
+ if (meta) {
659
+ context.set(meta.tableName, meta);
660
+ this.#entityMap.set(meta.tableName, meta);
661
+ // Also set with entity name for backward compatibility
662
+ context.set(tableName, meta);
663
+ } else {
664
+ context.set(tableName, undefined);
665
+ }
666
+ }
667
+ }
668
+ }
669
+ /**
670
+ * Extract the primary source table from a SELECT query
671
+ * This helps resolve columns from subqueries to their original entity tables
672
+ */
673
+ extractSourceTableFromSelectQuery(selectQuery) {
674
+ if (!selectQuery.from?.froms || selectQuery.from.froms.length === 0) {
675
+ return undefined;
676
+ }
677
+ // Get the first FROM table
678
+ const firstFrom = selectQuery.from.froms[0];
679
+ let sourceTable;
680
+ if (AliasNode.is(firstFrom) && TableNode.is(firstFrom.node)) {
681
+ sourceTable = firstFrom.node;
682
+ } else if (TableNode.is(firstFrom)) {
683
+ sourceTable = firstFrom;
684
+ }
685
+ if (sourceTable) {
686
+ const tableName = this.getTableName(sourceTable);
687
+ if (tableName) {
688
+ return this.findEntityMetadata(tableName);
689
+ }
690
+ }
691
+ return undefined;
692
+ }
693
+ /**
694
+ * Extract alias name from an alias node
695
+ */
696
+ extractAliasName(alias) {
697
+ if (typeof alias === 'object' && 'name' in alias) {
698
+ return alias.name;
699
+ }
700
+ return undefined;
701
+ }
702
+ /**
703
+ * Extract table name from a TableNode
704
+ */
705
+ getTableName(node) {
706
+ if (!node) {
707
+ return undefined;
708
+ }
709
+ if (TableNode.is(node) && SchemableIdentifierNode.is(node.table)) {
710
+ const identifier = node.table.identifier;
711
+ if (typeof identifier === 'object' && 'name' in identifier) {
712
+ return identifier.name;
713
+ }
714
+ }
715
+ return undefined;
716
+ }
717
+ /**
718
+ * Find entity metadata by table name or entity name
719
+ */
720
+ findEntityMetadata(name) {
721
+ const byEntity = this.#metadata.getByClassName(name, false);
722
+ if (byEntity) {
723
+ return byEntity;
724
+ }
725
+ const allMetadata = Array.from(this.#metadata);
726
+ const byTable = allMetadata.find(m => m.tableName === name);
727
+ if (byTable) {
728
+ return byTable;
729
+ }
730
+ return undefined;
731
+ }
732
+ /**
733
+ * Transform result rows by mapping database column names to property names
734
+ * This is called for SELECT queries when columnNamingStrategy is 'property'
735
+ */
736
+ transformResult(rows, entityMap) {
737
+ // Only transform if columnNamingStrategy is 'property' or convertValues is true, and we have data
738
+ if (
739
+ (this.#options.columnNamingStrategy !== 'property' && !this.#options.convertValues) ||
740
+ !rows ||
741
+ rows.length === 0
742
+ ) {
743
+ return rows;
744
+ }
745
+ // If no entities found (e.g. raw query without known tables), return rows as is
746
+ if (entityMap.size === 0) {
747
+ return rows;
748
+ }
749
+ // Build a global mapping from database field names to property objects
750
+ const fieldToPropertyMap = this.buildGlobalFieldMap(entityMap);
751
+ const relationFieldMap = this.buildGlobalRelationFieldMap(entityMap);
752
+ // Transform each row
753
+ return rows.map(row => this.transformRow(row, fieldToPropertyMap, relationFieldMap));
754
+ }
755
+ buildGlobalFieldMap(entityMap) {
756
+ const map = {};
757
+ for (const [alias, meta] of entityMap.entries()) {
758
+ Object.assign(map, this.buildFieldToPropertyMap(meta, alias));
759
+ }
760
+ return map;
761
+ }
762
+ buildGlobalRelationFieldMap(entityMap) {
763
+ const map = {};
764
+ for (const [alias, meta] of entityMap.entries()) {
765
+ Object.assign(map, this.buildRelationFieldMap(meta, alias));
766
+ }
767
+ return map;
768
+ }
769
+ /**
770
+ * Build a mapping from database field names to property objects
771
+ * Format: { 'field_name': EntityProperty }
772
+ */
773
+ buildFieldToPropertyMap(meta, alias) {
774
+ const map = {};
775
+ for (const prop of meta.props) {
776
+ if (prop.fieldNames && prop.fieldNames.length > 0) {
777
+ for (const fieldName of prop.fieldNames) {
778
+ if (!(fieldName in map)) {
779
+ map[fieldName] = prop;
780
+ }
781
+ if (alias) {
782
+ const dotted = `${alias}.${fieldName}`;
783
+ if (!(dotted in map)) {
784
+ map[dotted] = prop;
785
+ }
786
+ const underscored = `${alias}_${fieldName}`;
787
+ if (!(underscored in map)) {
788
+ map[underscored] = prop;
789
+ }
790
+ const doubleUnderscored = `${alias}__${fieldName}`;
791
+ if (!(doubleUnderscored in map)) {
792
+ map[doubleUnderscored] = prop;
793
+ }
794
+ }
795
+ }
796
+ }
797
+ if (!(prop.name in map)) {
798
+ map[prop.name] = prop;
799
+ }
800
+ }
801
+ return map;
802
+ }
803
+ /**
804
+ * Build a mapping for relation fields
805
+ * For ManyToOne relations, we need to map from the foreign key field to the relation property
806
+ * Format: { 'foreign_key_field': 'relationPropertyName' }
807
+ */
808
+ buildRelationFieldMap(meta, alias) {
809
+ const map = {};
810
+ for (const prop of meta.props) {
811
+ // For ManyToOne/OneToOne relations, find the foreign key field
812
+ if (prop.kind === ReferenceKind.MANY_TO_ONE || prop.kind === ReferenceKind.ONE_TO_ONE) {
813
+ if (prop.fieldNames && prop.fieldNames.length > 0) {
814
+ const fieldName = prop.fieldNames[0];
815
+ map[fieldName] = prop.name;
816
+ if (alias) {
817
+ map[`${alias}.${fieldName}`] = prop.name;
818
+ map[`${alias}_${fieldName}`] = prop.name;
819
+ map[`${alias}__${fieldName}`] = prop.name;
820
+ }
821
+ }
822
+ }
823
+ }
824
+ return map;
825
+ }
826
+ /**
827
+ * Transform a single row by mapping column names to property names
828
+ */
829
+ transformRow(row, fieldToPropertyMap, relationFieldMap) {
830
+ const transformed = { ...row };
831
+ // First pass: map regular fields from fieldName to propertyName and convert values
832
+ for (const [fieldName, prop] of Object.entries(fieldToPropertyMap)) {
833
+ if (!(fieldName in transformed)) {
834
+ continue;
835
+ }
836
+ const converted = this.prepareOutputValue(prop, transformed[fieldName]);
837
+ if (this.#options.columnNamingStrategy === 'property' && prop.name !== fieldName) {
838
+ if (!(prop.name in transformed)) {
839
+ transformed[prop.name] = converted;
840
+ } else {
841
+ transformed[prop.name] = converted;
842
+ }
843
+ delete transformed[fieldName];
844
+ continue;
845
+ }
846
+ if (this.#options.convertValues) {
847
+ transformed[fieldName] = converted;
848
+ }
849
+ }
850
+ // Second pass: handle relation fields
851
+ // Only run if columnNamingStrategy is 'property', as we don't want to rename FKs otherwise
852
+ if (this.#options.columnNamingStrategy === 'property') {
853
+ for (const [fieldName, relationPropertyName] of Object.entries(relationFieldMap)) {
854
+ if (fieldName in transformed && !(relationPropertyName in transformed)) {
855
+ // Move the foreign key value to the relation property name
856
+ transformed[relationPropertyName] = transformed[fieldName];
857
+ delete transformed[fieldName];
858
+ }
859
+ }
860
+ }
861
+ return transformed;
862
+ }
863
+ prepareOutputValue(prop, value) {
864
+ if (!this.#options.convertValues || !prop || value == null) {
865
+ return value;
866
+ }
867
+ if (prop.customType) {
868
+ return prop.customType.convertToJSValue(value, this.#platform);
869
+ }
870
+ // Aligned with EntityComparator.getResultMapper logic
871
+ if (prop.runtimeType === 'boolean') {
872
+ // Use !! conversion like EntityComparator: value == null ? value : !!value
873
+ return value == null ? value : !!value;
874
+ }
875
+ if (prop.runtimeType === 'Date' && !this.#platform.isNumericProperty(prop)) {
876
+ // Aligned with EntityComparator: exclude numeric timestamp properties
877
+ // If already Date instance or null, return as is
878
+ if (value == null || value instanceof Date) {
879
+ return value;
880
+ }
881
+ // Handle timezone like EntityComparator.parseDate
882
+ const tz = this.#platform.getTimezone();
883
+ if (!tz || tz === 'local') {
884
+ return this.#platform.parseDate(value);
885
+ }
886
+ // For non-local timezone, check if value already has timezone info
887
+ // Number (timestamp) doesn't need timezone handling, string needs check
888
+ if (
889
+ typeof value === 'number' ||
890
+ (typeof value === 'string' && (value.includes('+') || value.lastIndexOf('-') > 10 || value.endsWith('Z')))
891
+ ) {
892
+ return this.#platform.parseDate(value);
893
+ }
894
+ // Append timezone if not present (only for string values)
895
+ return this.#platform.parseDate(value + tz);
896
+ }
897
+ // For all other runtimeTypes (number, string, bigint, Buffer, object, any, etc.)
898
+ // EntityComparator just assigns directly without conversion
899
+ return value;
900
+ }
892
901
  }