@fragno-dev/db 0.1.13 → 0.1.15

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 (178) hide show
  1. package/.turbo/turbo-build.log +179 -132
  2. package/CHANGELOG.md +30 -0
  3. package/dist/adapters/adapters.d.ts +27 -1
  4. package/dist/adapters/adapters.d.ts.map +1 -1
  5. package/dist/adapters/adapters.js.map +1 -1
  6. package/dist/adapters/drizzle/drizzle-adapter.d.ts +5 -1
  7. package/dist/adapters/drizzle/drizzle-adapter.d.ts.map +1 -1
  8. package/dist/adapters/drizzle/drizzle-adapter.js +15 -3
  9. package/dist/adapters/drizzle/drizzle-adapter.js.map +1 -1
  10. package/dist/adapters/drizzle/drizzle-query.js +7 -5
  11. package/dist/adapters/drizzle/drizzle-query.js.map +1 -1
  12. package/dist/adapters/drizzle/drizzle-uow-compiler.d.ts +0 -1
  13. package/dist/adapters/drizzle/drizzle-uow-compiler.d.ts.map +1 -1
  14. package/dist/adapters/drizzle/drizzle-uow-compiler.js +76 -44
  15. package/dist/adapters/drizzle/drizzle-uow-compiler.js.map +1 -1
  16. package/dist/adapters/drizzle/drizzle-uow-decoder.js +23 -16
  17. package/dist/adapters/drizzle/drizzle-uow-decoder.js.map +1 -1
  18. package/dist/adapters/drizzle/drizzle-uow-executor.js +18 -7
  19. package/dist/adapters/drizzle/drizzle-uow-executor.js.map +1 -1
  20. package/dist/adapters/drizzle/generate.d.ts +4 -1
  21. package/dist/adapters/drizzle/generate.d.ts.map +1 -1
  22. package/dist/adapters/drizzle/generate.js +11 -18
  23. package/dist/adapters/drizzle/generate.js.map +1 -1
  24. package/dist/adapters/drizzle/shared.d.ts +14 -1
  25. package/dist/adapters/drizzle/shared.d.ts.map +1 -0
  26. package/dist/adapters/kysely/kysely-adapter.d.ts +5 -1
  27. package/dist/adapters/kysely/kysely-adapter.d.ts.map +1 -1
  28. package/dist/adapters/kysely/kysely-adapter.js +14 -3
  29. package/dist/adapters/kysely/kysely-adapter.js.map +1 -1
  30. package/dist/adapters/kysely/kysely-query-builder.js +1 -1
  31. package/dist/adapters/kysely/kysely-query-compiler.js +3 -2
  32. package/dist/adapters/kysely/kysely-query-compiler.js.map +1 -1
  33. package/dist/adapters/kysely/kysely-query.d.ts +1 -0
  34. package/dist/adapters/kysely/kysely-query.d.ts.map +1 -1
  35. package/dist/adapters/kysely/kysely-query.js +28 -19
  36. package/dist/adapters/kysely/kysely-query.js.map +1 -1
  37. package/dist/adapters/kysely/kysely-shared.d.ts +14 -0
  38. package/dist/adapters/kysely/kysely-shared.d.ts.map +1 -0
  39. package/dist/adapters/kysely/kysely-shared.js +16 -1
  40. package/dist/adapters/kysely/kysely-shared.js.map +1 -1
  41. package/dist/adapters/kysely/kysely-uow-compiler.js +68 -16
  42. package/dist/adapters/kysely/kysely-uow-compiler.js.map +1 -1
  43. package/dist/adapters/kysely/kysely-uow-executor.js +8 -4
  44. package/dist/adapters/kysely/kysely-uow-executor.js.map +1 -1
  45. package/dist/adapters/kysely/migration/execute-base.js +1 -1
  46. package/dist/adapters/kysely/migration/execute-base.js.map +1 -1
  47. package/dist/db-fragment-definition-builder.d.ts +152 -0
  48. package/dist/db-fragment-definition-builder.d.ts.map +1 -0
  49. package/dist/db-fragment-definition-builder.js +137 -0
  50. package/dist/db-fragment-definition-builder.js.map +1 -0
  51. package/dist/fragments/internal-fragment.d.ts +19 -0
  52. package/dist/fragments/internal-fragment.d.ts.map +1 -0
  53. package/dist/fragments/internal-fragment.js +39 -0
  54. package/dist/fragments/internal-fragment.js.map +1 -0
  55. package/dist/migration-engine/generation-engine.d.ts.map +1 -1
  56. package/dist/migration-engine/generation-engine.js +35 -15
  57. package/dist/migration-engine/generation-engine.js.map +1 -1
  58. package/dist/mod.d.ts +8 -18
  59. package/dist/mod.d.ts.map +1 -1
  60. package/dist/mod.js +7 -34
  61. package/dist/mod.js.map +1 -1
  62. package/dist/node_modules/.pnpm/rou3@0.7.8/node_modules/rou3/dist/index.js +165 -0
  63. package/dist/node_modules/.pnpm/rou3@0.7.8/node_modules/rou3/dist/index.js.map +1 -0
  64. package/dist/packages/fragno/dist/api/bind-services.js +20 -0
  65. package/dist/packages/fragno/dist/api/bind-services.js.map +1 -0
  66. package/dist/packages/fragno/dist/api/error.js +48 -0
  67. package/dist/packages/fragno/dist/api/error.js.map +1 -0
  68. package/dist/packages/fragno/dist/api/fragment-definition-builder.js +320 -0
  69. package/dist/packages/fragno/dist/api/fragment-definition-builder.js.map +1 -0
  70. package/dist/packages/fragno/dist/api/fragment-instantiator.js +487 -0
  71. package/dist/packages/fragno/dist/api/fragment-instantiator.js.map +1 -0
  72. package/dist/packages/fragno/dist/api/fragno-response.js +73 -0
  73. package/dist/packages/fragno/dist/api/fragno-response.js.map +1 -0
  74. package/dist/packages/fragno/dist/api/internal/response-stream.js +81 -0
  75. package/dist/packages/fragno/dist/api/internal/response-stream.js.map +1 -0
  76. package/dist/packages/fragno/dist/api/internal/route.js +10 -0
  77. package/dist/packages/fragno/dist/api/internal/route.js.map +1 -0
  78. package/dist/packages/fragno/dist/api/mutable-request-state.js +97 -0
  79. package/dist/packages/fragno/dist/api/mutable-request-state.js.map +1 -0
  80. package/dist/packages/fragno/dist/api/request-context-storage.js +43 -0
  81. package/dist/packages/fragno/dist/api/request-context-storage.js.map +1 -0
  82. package/dist/packages/fragno/dist/api/request-input-context.js +118 -0
  83. package/dist/packages/fragno/dist/api/request-input-context.js.map +1 -0
  84. package/dist/packages/fragno/dist/api/request-middleware.js +83 -0
  85. package/dist/packages/fragno/dist/api/request-middleware.js.map +1 -0
  86. package/dist/packages/fragno/dist/api/request-output-context.js +119 -0
  87. package/dist/packages/fragno/dist/api/request-output-context.js.map +1 -0
  88. package/dist/packages/fragno/dist/api/route.js +17 -0
  89. package/dist/packages/fragno/dist/api/route.js.map +1 -0
  90. package/dist/packages/fragno/dist/internal/symbols.js +10 -0
  91. package/dist/packages/fragno/dist/internal/symbols.js.map +1 -0
  92. package/dist/query/cursor.d.ts +10 -2
  93. package/dist/query/cursor.d.ts.map +1 -1
  94. package/dist/query/cursor.js +11 -4
  95. package/dist/query/cursor.js.map +1 -1
  96. package/dist/query/execute-unit-of-work.d.ts +123 -0
  97. package/dist/query/execute-unit-of-work.d.ts.map +1 -0
  98. package/dist/query/execute-unit-of-work.js +184 -0
  99. package/dist/query/execute-unit-of-work.js.map +1 -0
  100. package/dist/query/query.d.ts +3 -3
  101. package/dist/query/query.d.ts.map +1 -1
  102. package/dist/query/result-transform.js +4 -2
  103. package/dist/query/result-transform.js.map +1 -1
  104. package/dist/query/retry-policy.d.ts +88 -0
  105. package/dist/query/retry-policy.d.ts.map +1 -0
  106. package/dist/query/retry-policy.js +61 -0
  107. package/dist/query/retry-policy.js.map +1 -0
  108. package/dist/query/unit-of-work.d.ts +171 -32
  109. package/dist/query/unit-of-work.d.ts.map +1 -1
  110. package/dist/query/unit-of-work.js +530 -133
  111. package/dist/query/unit-of-work.js.map +1 -1
  112. package/dist/schema/serialize.js +12 -7
  113. package/dist/schema/serialize.js.map +1 -1
  114. package/dist/with-database.d.ts +28 -0
  115. package/dist/with-database.d.ts.map +1 -0
  116. package/dist/with-database.js +34 -0
  117. package/dist/with-database.js.map +1 -0
  118. package/package.json +10 -3
  119. package/src/adapters/adapters.ts +30 -0
  120. package/src/adapters/drizzle/drizzle-adapter-pglite.test.ts +86 -17
  121. package/src/adapters/drizzle/drizzle-adapter-sqlite.test.ts +291 -7
  122. package/src/adapters/drizzle/drizzle-adapter.test.ts +3 -51
  123. package/src/adapters/drizzle/drizzle-adapter.ts +35 -7
  124. package/src/adapters/drizzle/drizzle-query.ts +25 -15
  125. package/src/adapters/drizzle/drizzle-uow-compiler-mysql.test.ts +1442 -0
  126. package/src/adapters/drizzle/drizzle-uow-compiler-sqlite.test.ts +1414 -0
  127. package/src/adapters/drizzle/drizzle-uow-compiler.test.ts +78 -61
  128. package/src/adapters/drizzle/drizzle-uow-compiler.ts +123 -42
  129. package/src/adapters/drizzle/drizzle-uow-decoder.ts +34 -27
  130. package/src/adapters/drizzle/drizzle-uow-executor.ts +41 -8
  131. package/src/adapters/drizzle/generate.test.ts +102 -269
  132. package/src/adapters/drizzle/generate.ts +12 -30
  133. package/src/adapters/drizzle/test-utils.ts +36 -5
  134. package/src/adapters/kysely/kysely-adapter-pglite.test.ts +66 -22
  135. package/src/adapters/kysely/kysely-adapter-sqlite.test.ts +156 -0
  136. package/src/adapters/kysely/kysely-adapter.ts +25 -2
  137. package/src/adapters/kysely/kysely-query-compiler.ts +3 -8
  138. package/src/adapters/kysely/kysely-query.ts +57 -37
  139. package/src/adapters/kysely/kysely-shared.ts +34 -0
  140. package/src/adapters/kysely/kysely-uow-compiler.test.ts +62 -74
  141. package/src/adapters/kysely/kysely-uow-compiler.ts +92 -24
  142. package/src/adapters/kysely/kysely-uow-executor.ts +26 -7
  143. package/src/adapters/kysely/kysely-uow-joins.test.ts +33 -50
  144. package/src/adapters/kysely/migration/execute-base.ts +1 -1
  145. package/src/db-fragment-definition-builder.test.ts +887 -0
  146. package/src/db-fragment-definition-builder.ts +506 -0
  147. package/src/db-fragment-instantiator.test.ts +467 -0
  148. package/src/db-fragment-integration.test.ts +408 -0
  149. package/src/fragments/internal-fragment.test.ts +160 -0
  150. package/src/fragments/internal-fragment.ts +85 -0
  151. package/src/migration-engine/generation-engine.test.ts +58 -15
  152. package/src/migration-engine/generation-engine.ts +78 -25
  153. package/src/mod.ts +35 -43
  154. package/src/query/cursor.test.ts +119 -0
  155. package/src/query/cursor.ts +17 -4
  156. package/src/query/execute-unit-of-work.test.ts +1310 -0
  157. package/src/query/execute-unit-of-work.ts +463 -0
  158. package/src/query/query.ts +4 -4
  159. package/src/query/result-transform.test.ts +129 -0
  160. package/src/query/result-transform.ts +4 -1
  161. package/src/query/retry-policy.test.ts +217 -0
  162. package/src/query/retry-policy.ts +141 -0
  163. package/src/query/unit-of-work-coordinator.test.ts +833 -0
  164. package/src/query/unit-of-work-types.test.ts +15 -2
  165. package/src/query/unit-of-work.test.ts +878 -200
  166. package/src/query/unit-of-work.ts +963 -321
  167. package/src/schema/serialize.ts +22 -11
  168. package/src/with-database.ts +140 -0
  169. package/tsdown.config.ts +1 -0
  170. package/dist/fragment.d.ts +0 -54
  171. package/dist/fragment.d.ts.map +0 -1
  172. package/dist/fragment.js +0 -92
  173. package/dist/fragment.js.map +0 -1
  174. package/dist/shared/settings-schema.js +0 -36
  175. package/dist/shared/settings-schema.js.map +0 -1
  176. package/src/fragment.test.ts +0 -341
  177. package/src/fragment.ts +0 -198
  178. package/src/shared/settings-schema.ts +0 -61
@@ -0,0 +1,1442 @@
1
+ import { assert, beforeAll, describe, expect, it } from "vitest";
2
+ import {
3
+ column,
4
+ FragnoId,
5
+ idColumn,
6
+ referenceColumn,
7
+ schema,
8
+ type AnySchema,
9
+ } from "../../schema/create";
10
+ import { createDrizzleUOWCompiler } from "./drizzle-uow-compiler";
11
+ import { drizzle } from "drizzle-orm/mysql2";
12
+ import type { DBType } from "./shared";
13
+ import { UnitOfWork, type UOWDecoder } from "../../query/unit-of-work";
14
+ import { writeAndLoadSchema } from "./test-utils";
15
+ import type { ConnectionPool } from "../../shared/connection-pool";
16
+ import { createDrizzleConnectionPool } from "./drizzle-connection-pool";
17
+ import { Cursor } from "../../query/cursor";
18
+
19
+ /**
20
+ * Integration tests for Drizzle UOW compiler and executor (MySQL).
21
+ * These tests generate a real Drizzle schema and verify compilation works correctly for MySQL.
22
+ *
23
+ * Note: These tests only verify SQL generation, not actual database execution.
24
+ */
25
+ describe("drizzle-uow-compiler (MySQL)", () => {
26
+ const testSchema = schema((s) => {
27
+ return s
28
+ .addTable("users", (t) => {
29
+ return t
30
+ .addColumn("id", idColumn())
31
+ .addColumn("name", column("string"))
32
+ .addColumn("email", column("string"))
33
+ .addColumn("age", column("integer").nullable())
34
+ .createIndex("idx_email", ["email"], { unique: true })
35
+ .createIndex("idx_name", ["name"]);
36
+ })
37
+ .addTable("posts", (t) => {
38
+ return t
39
+ .addColumn("id", idColumn())
40
+ .addColumn("title", column("string"))
41
+ .addColumn("content", column("string"))
42
+ .addColumn("userId", referenceColumn())
43
+ .addColumn("viewCount", column("integer").defaultTo(0))
44
+ .createIndex("idx_user", ["userId"])
45
+ .createIndex("idx_title", ["title"]);
46
+ })
47
+ .addReference("author", {
48
+ type: "one",
49
+ from: { table: "posts", column: "userId" },
50
+ to: { table: "users", column: "id" },
51
+ });
52
+ });
53
+
54
+ let db: DBType;
55
+ let pool: ConnectionPool<DBType>;
56
+
57
+ beforeAll(async () => {
58
+ // Write schema to file and dynamically import it
59
+ const { schemaModule, cleanup } = await writeAndLoadSchema(
60
+ "drizzle-uow-compiler-mysql",
61
+ testSchema,
62
+ "mysql",
63
+ );
64
+
65
+ // Create Drizzle instance with mysql2
66
+ // Note: We only test SQL generation, not actual query execution
67
+ // Create a mock connection that satisfies the type but doesn't actually connect
68
+ const mockConnection: unknown = {
69
+ query: () => Promise.resolve([]),
70
+ execute: () => Promise.resolve([]),
71
+ end: () => Promise.resolve(),
72
+ };
73
+
74
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
75
+ db = drizzle(mockConnection as any, {
76
+ schema: schemaModule,
77
+ mode: "default",
78
+ }) as unknown as DBType;
79
+
80
+ // Wrap in connection pool
81
+ pool = createDrizzleConnectionPool(db);
82
+
83
+ return async () => {
84
+ await cleanup();
85
+ };
86
+ });
87
+
88
+ function createTestUOWWithSchema<const T extends AnySchema>(schema: T) {
89
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
90
+ const mockExecutor = {
91
+ executeRetrievalPhase: async () => [],
92
+ executeMutationPhase: async () => ({ success: true, createdInternalIds: [] }),
93
+ };
94
+ const mockDecoder: UOWDecoder = (rawResults, operations) => {
95
+ if (rawResults.length !== operations.length) {
96
+ throw new Error("rawResults and ops must have the same length");
97
+ }
98
+ return rawResults;
99
+ };
100
+ return new UnitOfWork(compiler, mockExecutor, mockDecoder).forSchema(schema);
101
+ }
102
+
103
+ function createTestUOW(name?: string) {
104
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
105
+ const mockExecutor = {
106
+ executeRetrievalPhase: async () => [],
107
+ executeMutationPhase: async () => ({ success: true, createdInternalIds: [] }),
108
+ };
109
+ const mockDecoder: UOWDecoder = (rawResults, operations) => {
110
+ if (rawResults.length !== operations.length) {
111
+ throw new Error("rawResults and ops must have the same length");
112
+ }
113
+ return rawResults;
114
+ };
115
+ const uow = new UnitOfWork(compiler, mockExecutor, mockDecoder, name).forSchema(testSchema);
116
+
117
+ return uow;
118
+ }
119
+
120
+ it("should create a compiler with the correct structure", () => {
121
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
122
+
123
+ expect(compiler).toBeDefined();
124
+ expect(compiler.compileRetrievalOperation).toBeInstanceOf(Function);
125
+ expect(compiler.compileMutationOperation).toBeInstanceOf(Function);
126
+ });
127
+
128
+ describe("compileRetrievalOperation", () => {
129
+ it("should compile find operation with where clause", () => {
130
+ const uow = createTestUOW();
131
+ uow.find("users", (b) =>
132
+ b.whereIndex("idx_email", (eb) => eb("email", "=", "test@example.com")),
133
+ );
134
+
135
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
136
+ const compiled = uow.compile(compiler);
137
+
138
+ expect(compiled.retrievalBatch).toHaveLength(1);
139
+ expect(compiled.retrievalBatch[0].sql).toMatchInlineSnapshot(
140
+ `"select \`id\`, \`name\`, \`email\`, \`age\`, \`_internalId\`, \`_version\` from \`users\` \`users\` where \`users\`.\`email\` = ?"`,
141
+ );
142
+ expect(compiled.retrievalBatch[0].params).toEqual(["test@example.com"]);
143
+ });
144
+
145
+ it("should compile find operation with select clause", () => {
146
+ const uow = createTestUOW();
147
+ uow.find("users", (b) =>
148
+ b.whereIndex("idx_name", (eb) => eb("name", "=", "Alice")).select(["id", "name"]),
149
+ );
150
+
151
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
152
+ const compiled = uow.compile(compiler);
153
+
154
+ expect(compiled.retrievalBatch).toHaveLength(1);
155
+ expect(compiled.retrievalBatch[0].sql).toMatchInlineSnapshot(
156
+ `"select \`id\`, \`name\`, \`_internalId\`, \`_version\` from \`users\` \`users\` where \`users\`.\`name\` = ?"`,
157
+ );
158
+ expect(compiled.retrievalBatch[0].params).toEqual(["Alice"]);
159
+ });
160
+
161
+ it("should compile find operation with pageSize", () => {
162
+ const uow = createTestUOW();
163
+ uow.find("users", (b) => b.whereIndex("primary").pageSize(10));
164
+
165
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
166
+ const compiled = uow.compile(compiler);
167
+
168
+ expect(compiled.retrievalBatch).toHaveLength(1);
169
+ expect(compiled.retrievalBatch[0].sql).toMatchInlineSnapshot(
170
+ `"select \`id\`, \`name\`, \`email\`, \`age\`, \`_internalId\`, \`_version\` from \`users\` \`users\` limit ?"`,
171
+ );
172
+ expect(compiled.retrievalBatch[0].params).toEqual([10]);
173
+ });
174
+
175
+ it("should compile find operation with orderByIndex on primary index", () => {
176
+ const uow = createTestUOW();
177
+ uow.find("users", (b) => b.whereIndex("primary").orderByIndex("primary", "desc"));
178
+
179
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
180
+ const compiled = uow.compile(compiler);
181
+
182
+ expect(compiled.retrievalBatch).toHaveLength(1);
183
+ expect(compiled.retrievalBatch[0].sql).toMatchInlineSnapshot(
184
+ `"select \`id\`, \`name\`, \`email\`, \`age\`, \`_internalId\`, \`_version\` from \`users\` \`users\` order by \`users\`.\`id\` desc"`,
185
+ );
186
+ });
187
+
188
+ it("should compile find operation with orderByIndex", () => {
189
+ const uow = createTestUOW();
190
+ uow.find("users", (b) => b.whereIndex("idx_name").orderByIndex("idx_name", "desc"));
191
+
192
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
193
+ const compiled = uow.compile(compiler);
194
+
195
+ expect(compiled.retrievalBatch).toHaveLength(1);
196
+ expect(compiled.retrievalBatch[0].sql).toMatchInlineSnapshot(
197
+ `"select \`id\`, \`name\`, \`email\`, \`age\`, \`_internalId\`, \`_version\` from \`users\` \`users\` order by \`users\`.\`name\` desc"`,
198
+ );
199
+ });
200
+
201
+ it("should compile multiple find operations", () => {
202
+ const uow = createTestUOW();
203
+ uow.find("users", (b) =>
204
+ b.whereIndex("idx_email", (eb) => eb("email", "=", "user1@example.com")),
205
+ );
206
+ uow.find("posts", (b) => b.whereIndex("idx_title", (eb) => eb("title", "contains", "test")));
207
+
208
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
209
+ const compiled = uow.compile(compiler);
210
+
211
+ expect(compiled.retrievalBatch).toHaveLength(2);
212
+ expect(compiled.retrievalBatch[0].sql).toMatchInlineSnapshot(
213
+ `"select \`id\`, \`name\`, \`email\`, \`age\`, \`_internalId\`, \`_version\` from \`users\` \`users\` where \`users\`.\`email\` = ?"`,
214
+ );
215
+ expect(compiled.retrievalBatch[1].sql).toMatchInlineSnapshot(
216
+ `"select \`id\`, \`title\`, \`content\`, \`userId\`, \`viewCount\`, \`_internalId\`, \`_version\` from \`posts\` \`posts\` where \`posts\`.\`title\` like ?"`,
217
+ );
218
+ });
219
+
220
+ it("should compile find operation with selectCount", () => {
221
+ const uow = createTestUOW();
222
+ uow.find("users", (b) => b.whereIndex("primary").selectCount());
223
+
224
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
225
+ const compiled = uow.compile(compiler);
226
+
227
+ expect(compiled.retrievalBatch).toHaveLength(1);
228
+ expect(compiled.retrievalBatch[0].sql).toMatchInlineSnapshot(
229
+ `"select count(*) from \`users\`"`,
230
+ );
231
+ });
232
+
233
+ it("should compile find operation with selectCount and where clause", () => {
234
+ const uow = createTestUOW();
235
+ uow.find("users", (b) =>
236
+ b.whereIndex("idx_name", (eb) => eb("name", "starts with", "John")).selectCount(),
237
+ );
238
+
239
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
240
+ const compiled = uow.compile(compiler);
241
+
242
+ expect(compiled.retrievalBatch).toHaveLength(1);
243
+ expect(compiled.retrievalBatch[0].sql).toMatchInlineSnapshot(
244
+ `"select count(*) from \`users\` where \`users\`.\`name\` like ?"`,
245
+ );
246
+ expect(compiled.retrievalBatch[0].params).toEqual(["John%"]);
247
+ });
248
+
249
+ it("should compile find operation with cursor pagination using after", () => {
250
+ const uow = createTestUOW();
251
+ const cursor = new Cursor({
252
+ indexName: "idx_name",
253
+ orderDirection: "asc",
254
+ pageSize: 10,
255
+ indexValues: { name: "Alice" },
256
+ });
257
+ uow.find("users", (b) =>
258
+ b.whereIndex("idx_name").orderByIndex("idx_name", "asc").after(cursor).pageSize(10),
259
+ );
260
+
261
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
262
+ const compiled = uow.compile(compiler);
263
+
264
+ expect(compiled.retrievalBatch).toHaveLength(1);
265
+ expect(compiled.retrievalBatch[0].sql).toMatchInlineSnapshot(
266
+ `"select \`id\`, \`name\`, \`email\`, \`age\`, \`_internalId\`, \`_version\` from \`users\` \`users\` where \`users\`.\`name\` > ? order by \`users\`.\`name\` asc limit ?"`,
267
+ );
268
+ expect(compiled.retrievalBatch[0].params).toEqual(["Alice", 10]);
269
+ });
270
+
271
+ it("should compile find operation with cursor pagination using before", () => {
272
+ const uow = createTestUOW();
273
+ const cursor = new Cursor({
274
+ indexName: "idx_name",
275
+ orderDirection: "desc",
276
+ pageSize: 10,
277
+ indexValues: { name: "Bob" },
278
+ });
279
+ uow.find("users", (b) =>
280
+ b.whereIndex("idx_name").orderByIndex("idx_name", "desc").before(cursor).pageSize(10),
281
+ );
282
+
283
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
284
+ const compiled = uow.compile(compiler);
285
+
286
+ expect(compiled.retrievalBatch).toHaveLength(1);
287
+ expect(compiled.retrievalBatch[0].sql).toMatchInlineSnapshot(
288
+ `"select \`id\`, \`name\`, \`email\`, \`age\`, \`_internalId\`, \`_version\` from \`users\` \`users\` where \`users\`.\`name\` > ? order by \`users\`.\`name\` desc limit ?"`,
289
+ );
290
+ expect(compiled.retrievalBatch[0].params).toEqual(["Bob", 10]);
291
+ });
292
+
293
+ it("should compile find operation with cursor pagination and additional where conditions", () => {
294
+ const uow = createTestUOW();
295
+ const cursor = new Cursor({
296
+ indexName: "idx_name",
297
+ orderDirection: "asc",
298
+ pageSize: 5,
299
+ indexValues: { name: "Alice" },
300
+ });
301
+ uow.find("users", (b) =>
302
+ b
303
+ .whereIndex("idx_name", (eb) => eb("name", "starts with", "John"))
304
+ .orderByIndex("idx_name", "asc")
305
+ .after(cursor)
306
+ .pageSize(5),
307
+ );
308
+
309
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
310
+ const compiled = uow.compile(compiler);
311
+
312
+ expect(compiled.retrievalBatch).toHaveLength(1);
313
+ expect(compiled.retrievalBatch[0].sql).toMatchInlineSnapshot(
314
+ `"select \`id\`, \`name\`, \`email\`, \`age\`, \`_internalId\`, \`_version\` from \`users\` \`users\` where (\`users\`.\`name\` like ? and \`users\`.\`name\` > ?) order by \`users\`.\`name\` asc limit ?"`,
315
+ );
316
+ expect(compiled.retrievalBatch[0].params).toEqual(["John%", "Alice", 5]);
317
+ });
318
+
319
+ it("should compile find operation with join", () => {
320
+ const uow = createTestUOW();
321
+ uow.find("posts", (b) =>
322
+ b
323
+ .whereIndex("idx_title", (eb) => eb("title", "contains", "test"))
324
+ .join((jb) => jb.author()),
325
+ );
326
+
327
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
328
+ const compiled = uow.compile(compiler);
329
+
330
+ expect(compiled.retrievalBatch).toHaveLength(1);
331
+ // This should generate SQL that joins posts with users and selects author name and email
332
+ expect(compiled.retrievalBatch[0].sql).toMatchInlineSnapshot(
333
+ `"select \`posts\`.\`id\`, \`posts\`.\`title\`, \`posts\`.\`content\`, \`posts\`.\`userId\`, \`posts\`.\`viewCount\`, \`posts\`.\`_internalId\`, \`posts\`.\`_version\`, \`posts_author\`.\`data\` as \`author\` from \`posts\` \`posts\` left join lateral (select json_array(\`posts_author\`.\`id\`, \`posts_author\`.\`name\`, \`posts_author\`.\`email\`, \`posts_author\`.\`age\`, \`posts_author\`.\`_internalId\`, \`posts_author\`.\`_version\`) as \`data\` from (select * from \`users\` \`posts_author\` where \`posts_author\`.\`_internalId\` = \`posts\`.\`userId\` limit ?) \`posts_author\`) \`posts_author\` on true where \`posts\`.\`title\` like ?"`,
334
+ );
335
+ expect(compiled.retrievalBatch[0].params).toEqual([1, "%test%"]);
336
+ });
337
+
338
+ it("should compile find operation with join filtering", () => {
339
+ const uow = createTestUOW();
340
+ uow.find("posts", (b) =>
341
+ b
342
+ .whereIndex("primary")
343
+ .join((jb) =>
344
+ jb.author((builder) =>
345
+ builder.whereIndex("idx_name", (eb) => eb("name", "=", "Alice")).select(["name"]),
346
+ ),
347
+ ),
348
+ );
349
+
350
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
351
+ const compiled = uow.compile(compiler);
352
+
353
+ expect(compiled.retrievalBatch).toHaveLength(1);
354
+ const sql = compiled.retrievalBatch[0].sql;
355
+ expect(sql).toMatchInlineSnapshot(
356
+ `"select \`posts\`.\`id\`, \`posts\`.\`title\`, \`posts\`.\`content\`, \`posts\`.\`userId\`, \`posts\`.\`viewCount\`, \`posts\`.\`_internalId\`, \`posts\`.\`_version\`, \`posts_author\`.\`data\` as \`author\` from \`posts\` \`posts\` left join lateral (select json_array(\`posts_author\`.\`name\`, \`posts_author\`.\`_internalId\`, \`posts_author\`.\`_version\`) as \`data\` from (select * from \`users\` \`posts_author\` where (\`posts_author\`.\`_internalId\` = \`posts\`.\`userId\` and \`posts_author\`.\`name\` = ?) limit ?) \`posts_author\`) \`posts_author\` on true"`,
357
+ );
358
+ });
359
+
360
+ it("should compile find operation with join ordering", () => {
361
+ const uow = createTestUOW();
362
+ uow.find("posts", (b) =>
363
+ b
364
+ .whereIndex("primary")
365
+ .join((jb) => jb.author((builder) => builder.orderByIndex("idx_name", "desc"))),
366
+ );
367
+
368
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
369
+ const compiled = uow.compile(compiler);
370
+
371
+ expect(compiled.retrievalBatch).toHaveLength(1);
372
+ const sql = compiled.retrievalBatch[0].sql;
373
+ expect(sql).toMatchInlineSnapshot(
374
+ `"select \`posts\`.\`id\`, \`posts\`.\`title\`, \`posts\`.\`content\`, \`posts\`.\`userId\`, \`posts\`.\`viewCount\`, \`posts\`.\`_internalId\`, \`posts\`.\`_version\`, \`posts_author\`.\`data\` as \`author\` from \`posts\` \`posts\` left join lateral (select json_array(\`posts_author\`.\`id\`, \`posts_author\`.\`name\`, \`posts_author\`.\`email\`, \`posts_author\`.\`age\`, \`posts_author\`.\`_internalId\`, \`posts_author\`.\`_version\`) as \`data\` from (select *, row_number() over (order by \`posts_author\`.\`name\` desc) from \`users\` \`posts_author\` where \`posts_author\`.\`_internalId\` = \`posts\`.\`userId\` limit ?) \`posts_author\`) \`posts_author\` on true"`,
375
+ );
376
+ });
377
+
378
+ it("should compile find operation with join pageSize", () => {
379
+ const uow = createTestUOW();
380
+ uow.find("posts", (b) =>
381
+ b.whereIndex("primary").join((jb) => jb.author((builder) => builder.pageSize(5))),
382
+ );
383
+
384
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
385
+ const compiled = uow.compile(compiler);
386
+
387
+ expect(compiled.retrievalBatch).toHaveLength(1);
388
+ const sql = compiled.retrievalBatch[0].sql;
389
+ // Should have limit in the joined query
390
+ expect(sql).toMatchInlineSnapshot(
391
+ `"select \`posts\`.\`id\`, \`posts\`.\`title\`, \`posts\`.\`content\`, \`posts\`.\`userId\`, \`posts\`.\`viewCount\`, \`posts\`.\`_internalId\`, \`posts\`.\`_version\`, \`posts_author\`.\`data\` as \`author\` from \`posts\` \`posts\` left join lateral (select json_array(\`posts_author\`.\`id\`, \`posts_author\`.\`name\`, \`posts_author\`.\`email\`, \`posts_author\`.\`age\`, \`posts_author\`.\`_internalId\`, \`posts_author\`.\`_version\`) as \`data\` from (select * from \`users\` \`posts_author\` where \`posts_author\`.\`_internalId\` = \`posts\`.\`userId\` limit ?) \`posts_author\`) \`posts_author\` on true"`,
392
+ );
393
+ });
394
+ });
395
+
396
+ describe("compileMutationOperation", () => {
397
+ it("should compile create operation", () => {
398
+ const uow = createTestUOW();
399
+ uow.create("users", {
400
+ name: "John Doe",
401
+ email: "john@example.com",
402
+ age: 30,
403
+ });
404
+
405
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
406
+ const compiled = uow.compile(compiler);
407
+ const [batch] = compiled.mutationBatch;
408
+ assert(batch);
409
+ expect(batch.expectedAffectedRows).toBeNull();
410
+ expect(batch.query.sql).toMatchInlineSnapshot(
411
+ `"insert into \`users\` (\`id\`, \`name\`, \`email\`, \`age\`, \`_internalId\`, \`_version\`) values (?, ?, ?, ?, default, default)"`,
412
+ );
413
+ expect(batch.query.params).toMatchObject([
414
+ expect.any(String),
415
+ "John Doe",
416
+ "john@example.com",
417
+ 30,
418
+ // Note: MySQL uses DEFAULT in SQL for _version, not a parameter
419
+ ]);
420
+ });
421
+
422
+ it("should compile create operation with external id string for reference column", () => {
423
+ const uow = createTestUOW();
424
+ // Create a post with userId as just an external id string
425
+ uow.create("posts", {
426
+ title: "Test Post",
427
+ content: "Post content",
428
+ userId: "user_external_id_123",
429
+ viewCount: 5,
430
+ });
431
+
432
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
433
+ const compiled = uow.compile(compiler);
434
+ const [batch] = compiled.mutationBatch;
435
+ assert(batch);
436
+ expect(batch.expectedAffectedRows).toBeNull();
437
+ expect(batch.query.sql).toMatchInlineSnapshot(
438
+ `"insert into \`posts\` (\`id\`, \`title\`, \`content\`, \`userId\`, \`viewCount\`, \`_internalId\`, \`_version\`) values (?, ?, ?, (select \`_internalId\` from \`users\` where \`id\` = ? limit 1), ?, default, default)"`,
439
+ );
440
+ expect(batch.query.params).toMatchObject([
441
+ expect.any(String), // auto-generated post ID
442
+ "Test Post",
443
+ "Post content",
444
+ "user_external_id_123", // external id string
445
+ 5, // viewCount
446
+ // Note: MySQL uses DEFAULT in SQL for _version, not a parameter
447
+ ]);
448
+ });
449
+
450
+ it("should compile create operation with bigint for reference column (no subquery)", () => {
451
+ const uow = createTestUOW();
452
+ // Create a post with userId as a bigint directly (internal ID)
453
+ uow.create("posts", {
454
+ title: "Direct ID Post",
455
+ content: "Content with direct bigint",
456
+ userId: 12345n,
457
+ });
458
+
459
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
460
+ const compiled = uow.compile(compiler);
461
+ const [batch] = compiled.mutationBatch;
462
+ assert(batch);
463
+ expect(batch.expectedAffectedRows).toBeNull();
464
+ // Should NOT have a subquery when using bigint directly
465
+ expect(batch.query.sql).not.toMatch(/\(select.*from.*users/i);
466
+ expect(batch.query.sql).toMatchInlineSnapshot(
467
+ `"insert into \`posts\` (\`id\`, \`title\`, \`content\`, \`userId\`, \`viewCount\`, \`_internalId\`, \`_version\`) values (?, ?, ?, ?, default, default, default)"`,
468
+ );
469
+ expect(batch.query.params).toMatchObject([
470
+ expect.any(String), // auto-generated post ID
471
+ "Direct ID Post",
472
+ "Content with direct bigint",
473
+ 12345n, // bigint internal ID directly
474
+ // Note: MySQL uses DEFAULT in SQL for viewCount and _version, not parameters
475
+ ]);
476
+ });
477
+
478
+ it("should compile create operation with FragnoId object for reference column", () => {
479
+ const uow = createTestUOW();
480
+ const userId = FragnoId.fromExternal("user_ext_789", 0);
481
+ // Create a post with userId as a FragnoId object
482
+ uow.create("posts", {
483
+ title: "Post with FragnoId",
484
+ content: "Content",
485
+ userId,
486
+ });
487
+
488
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
489
+ const compiled = uow.compile(compiler);
490
+ const [batch] = compiled.mutationBatch;
491
+ assert(batch);
492
+ expect(batch.expectedAffectedRows).toBeNull();
493
+ // FragnoId should generate a subquery to lookup the internal ID from external ID
494
+ expect(batch.query.sql).toMatchInlineSnapshot(
495
+ `"insert into \`posts\` (\`id\`, \`title\`, \`content\`, \`userId\`, \`viewCount\`, \`_internalId\`, \`_version\`) values (?, ?, ?, (select \`_internalId\` from \`users\` where \`id\` = ? limit 1), default, default, default)"`,
496
+ );
497
+ });
498
+
499
+ it("should compile update operation with external id string for reference column", () => {
500
+ const uow = createTestUOW();
501
+ const postId = FragnoId.fromExternal("post123", 0);
502
+ uow.update("posts", postId, (b) =>
503
+ b.set({
504
+ userId: "new_user_external_id_456",
505
+ }),
506
+ );
507
+
508
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
509
+ const compiled = uow.compile(compiler);
510
+ const [batch] = compiled.mutationBatch;
511
+ assert(batch);
512
+ expect(batch.expectedAffectedRows).toBeNull();
513
+ // Should generate a subquery for the string external ID in UPDATE
514
+ expect(batch.query.sql).toMatchInlineSnapshot(
515
+ `"update \`posts\` set \`userId\` = (select \`_internalId\` from \`users\` where \`id\` = ? limit 1), \`_version\` = COALESCE(_version, 0) + 1 where \`posts\`.\`id\` = ?"`,
516
+ );
517
+ expect(batch.query.params).toMatchObject([
518
+ "new_user_external_id_456", // external id string
519
+ "post123", // post external id
520
+ ]);
521
+ });
522
+
523
+ it("should compile update operation with bigint for reference column (no subquery)", () => {
524
+ const uow = createTestUOW();
525
+ const postId = FragnoId.fromExternal("post456", 0);
526
+ uow.update("posts", postId, (b) =>
527
+ b.set({
528
+ userId: 99999n,
529
+ }),
530
+ );
531
+
532
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
533
+ const compiled = uow.compile(compiler);
534
+ const [batch] = compiled.mutationBatch;
535
+ assert(batch);
536
+ expect(batch.expectedAffectedRows).toBeNull();
537
+ // Should NOT have a subquery when using bigint directly
538
+ expect(batch.query.sql).not.toMatch(/\(select.*from.*users/i);
539
+ expect(batch.query.sql).toMatchInlineSnapshot(
540
+ `"update \`posts\` set \`userId\` = ?, \`_version\` = COALESCE(_version, 0) + 1 where \`posts\`.\`id\` = ?"`,
541
+ );
542
+ expect(batch.query.params).toMatchObject([
543
+ 99999n, // bigint stays as bigint for Drizzle (Drizzle handles conversion)
544
+ "post456", // post external id
545
+ ]);
546
+ });
547
+
548
+ it("should compile update operation with ID", () => {
549
+ const uow = createTestUOW();
550
+ const userId = FragnoId.fromExternal("user123", 0);
551
+ uow.update("users", userId, (b) =>
552
+ b.set({
553
+ name: "Jane Doe",
554
+ age: 25,
555
+ }),
556
+ );
557
+
558
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
559
+ const compiled = uow.compile(compiler);
560
+ const [batch] = compiled.mutationBatch;
561
+ assert(batch);
562
+ expect(batch.expectedAffectedRows).toBeNull();
563
+ expect(batch.query.sql).toMatchInlineSnapshot(
564
+ `"update \`users\` set \`name\` = ?, \`age\` = ?, \`_version\` = COALESCE(_version, 0) + 1 where \`users\`.\`id\` = ?"`,
565
+ );
566
+ expect(batch.query.params).toMatchObject(["Jane Doe", 25, "user123"]);
567
+ });
568
+
569
+ it("should compile update operation with version check", () => {
570
+ const uow = createTestUOW();
571
+ const userId = FragnoId.fromExternal("user123", 5);
572
+ uow.update("users", userId, (b) => b.set({ age: 18 }).check());
573
+
574
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
575
+ const compiled = uow.compile(compiler);
576
+ const [batch] = compiled.mutationBatch;
577
+ assert(batch);
578
+ expect(batch.expectedAffectedRows).toBe(1);
579
+ expect(batch.query.sql).toMatchInlineSnapshot(
580
+ `"update \`users\` set \`age\` = ?, \`_version\` = COALESCE(_version, 0) + 1 where (\`users\`.\`id\` = ? and \`users\`.\`_version\` = ?)"`,
581
+ );
582
+ expect(batch.query.params).toMatchObject([18, "user123", 5]);
583
+ });
584
+
585
+ it("should compile delete operation with ID", () => {
586
+ const uow = createTestUOW();
587
+ const userId = FragnoId.fromExternal("user123", 0);
588
+ uow.delete("users", userId);
589
+
590
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
591
+ const compiled = uow.compile(compiler);
592
+ const [batch] = compiled.mutationBatch;
593
+ assert(batch);
594
+ expect(batch.expectedAffectedRows).toBeNull();
595
+ expect(batch.query.sql).toMatchInlineSnapshot(
596
+ `"delete from \`users\` where \`users\`.\`id\` = ?"`,
597
+ );
598
+ expect(batch.query.params).toMatchObject(["user123"]);
599
+ });
600
+
601
+ it("should compile delete operation with version check", () => {
602
+ const uow = createTestUOW();
603
+ const userId = FragnoId.fromExternal("user123", 3);
604
+ uow.delete("users", userId, (b) => b.check());
605
+
606
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
607
+ const compiled = uow.compile(compiler);
608
+ const [batch] = compiled.mutationBatch;
609
+ assert(batch);
610
+ expect(batch.expectedAffectedRows).toBe(1);
611
+ expect(batch.query.sql).toMatchInlineSnapshot(
612
+ `"delete from \`users\` where (\`users\`.\`id\` = ? and \`users\`.\`_version\` = ?)"`,
613
+ );
614
+ expect(batch.query.params).toMatchObject(["user123", 3]);
615
+ });
616
+
617
+ it("should compile update operation with string ID", () => {
618
+ const uow = createTestUOW();
619
+ uow.update("users", "user123", (b) =>
620
+ b.set({
621
+ name: "Jane Doe",
622
+ age: 25,
623
+ }),
624
+ );
625
+
626
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
627
+ const compiled = uow.compile(compiler);
628
+ const [batch] = compiled.mutationBatch;
629
+ assert(batch);
630
+ expect(batch.expectedAffectedRows).toBeNull();
631
+ expect(batch.query.sql).toMatchInlineSnapshot(
632
+ `"update \`users\` set \`name\` = ?, \`age\` = ?, \`_version\` = COALESCE(_version, 0) + 1 where \`users\`.\`id\` = ?"`,
633
+ );
634
+ expect(batch.query.params).toMatchObject(["Jane Doe", 25, "user123"]);
635
+ });
636
+
637
+ it("should compile delete operation with string ID", () => {
638
+ const uow = createTestUOW();
639
+ uow.delete("users", "user123");
640
+
641
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
642
+ const compiled = uow.compile(compiler);
643
+ const [batch] = compiled.mutationBatch;
644
+ assert(batch);
645
+ expect(batch.expectedAffectedRows).toBeNull();
646
+ expect(batch.query.sql).toMatchInlineSnapshot(
647
+ `"delete from \`users\` where \`users\`.\`id\` = ?"`,
648
+ );
649
+ expect(batch.query.params).toMatchObject(["user123"]);
650
+ });
651
+
652
+ it("should throw when trying to check() with string ID on update", () => {
653
+ const uow = createTestUOW();
654
+ expect(() => {
655
+ uow.update("users", "user123", (b) => b.set({ name: "Jane" }).check());
656
+ }).toThrow(
657
+ 'Cannot use check() with a string ID on table "users". Version checking requires a FragnoId with version information.',
658
+ );
659
+ });
660
+
661
+ it("should throw when trying to check() with string ID on delete", () => {
662
+ const uow = createTestUOW();
663
+ expect(() => {
664
+ uow.delete("users", "user123", (b) => b.check());
665
+ }).toThrow(
666
+ 'Cannot use check() with a string ID on table "users". Version checking requires a FragnoId with version information.',
667
+ );
668
+ });
669
+
670
+ it("should compile multiple mutation operations", () => {
671
+ const uow = createTestUOW();
672
+ uow.create("users", {
673
+ name: "Alice",
674
+ email: "alice@example.com",
675
+ });
676
+ const postId = FragnoId.fromExternal("post123", 0);
677
+ uow.update("posts", postId, (b) => b.set({ viewCount: 10 }));
678
+ const userId = FragnoId.fromExternal("user456", 0);
679
+ uow.delete("posts", userId);
680
+
681
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
682
+ const compiled = uow.compile(compiler);
683
+ const [createBatch, updateBatch, deleteBatch] = compiled.mutationBatch;
684
+
685
+ expect(compiled.mutationBatch).toHaveLength(3);
686
+
687
+ assert(createBatch);
688
+ expect(createBatch.query.sql).toMatchInlineSnapshot(
689
+ `"insert into \`users\` (\`id\`, \`name\`, \`email\`, \`age\`, \`_internalId\`, \`_version\`) values (?, ?, ?, default, default, default)"`,
690
+ );
691
+ expect(createBatch.query.params).toMatchObject([
692
+ expect.any(String), // auto-generated ID
693
+ "Alice",
694
+ "alice@example.com",
695
+ // Note: MySQL uses DEFAULT in SQL for age and _version, not parameters
696
+ ]);
697
+
698
+ assert(updateBatch);
699
+ expect(updateBatch.query.sql).toMatchInlineSnapshot(
700
+ `"update \`posts\` set \`viewCount\` = ?, \`_version\` = COALESCE(_version, 0) + 1 where \`posts\`.\`id\` = ?"`,
701
+ );
702
+
703
+ assert(deleteBatch);
704
+ expect(deleteBatch.query.sql).toMatchInlineSnapshot(
705
+ `"delete from \`posts\` where \`posts\`.\`id\` = ?"`,
706
+ );
707
+ });
708
+ });
709
+
710
+ describe("complete UOW workflow", () => {
711
+ it("should compile retrieval and mutation phases together", () => {
712
+ const uow = createTestUOW("update-user-balance");
713
+
714
+ // Retrieval phase
715
+ uow.find("users", (b) => b.whereIndex("primary", (eb) => eb("id", "=", "user123")));
716
+
717
+ // Mutation phase
718
+ const userId = FragnoId.fromExternal("user123", 3);
719
+ uow.update("users", userId, (b) => b.set({ age: 31 }).check());
720
+
721
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
722
+ const compiled = uow.compile(compiler);
723
+
724
+ expect(compiled.name).toBe("update-user-balance");
725
+ expect(compiled.retrievalBatch).toHaveLength(1);
726
+ expect(compiled.mutationBatch).toHaveLength(1);
727
+
728
+ expect(compiled.retrievalBatch[0].sql).toMatchInlineSnapshot(
729
+ `"select \`id\`, \`name\`, \`email\`, \`age\`, \`_internalId\`, \`_version\` from \`users\` \`users\` where \`users\`.\`id\` = ?"`,
730
+ );
731
+
732
+ // Update should include version check in WHERE clause
733
+ const [batch] = compiled.mutationBatch;
734
+ assert(batch);
735
+ expect(batch.expectedAffectedRows).toBe(1);
736
+ expect(batch.query.sql).toMatchInlineSnapshot(
737
+ `"update \`users\` set \`age\` = ?, \`_version\` = COALESCE(_version, 0) + 1 where (\`users\`.\`id\` = ? and \`users\`.\`_version\` = ?)"`,
738
+ );
739
+ });
740
+
741
+ it("should handle complex where conditions", () => {
742
+ const uow = createTestUOW();
743
+ uow.find("users", (b) =>
744
+ b.whereIndex("idx_email", (eb) =>
745
+ eb.and(
746
+ eb("email", "contains", "@example.com"),
747
+ // @ts-expect-error - name is not indexed
748
+ eb.or(eb("name", "=", "Alice"), eb("name", "=", "Bob")),
749
+ ),
750
+ ),
751
+ );
752
+
753
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
754
+ const compiled = uow.compile(compiler);
755
+
756
+ expect(compiled.retrievalBatch).toHaveLength(1);
757
+ expect(compiled.retrievalBatch[0].sql).toMatchInlineSnapshot(
758
+ `"select \`id\`, \`name\`, \`email\`, \`age\`, \`_internalId\`, \`_version\` from \`users\` \`users\` where (\`users\`.\`email\` like ? and (\`users\`.\`name\` = ? or \`users\`.\`name\` = ?))"`,
759
+ );
760
+ expect(compiled.retrievalBatch[0].params).toEqual(["%@example.com%", "Alice", "Bob"]);
761
+ });
762
+
763
+ it("should return null for operations with always-false conditions", () => {
764
+ const uow = createTestUOW();
765
+ uow.find("users", (b) => b.whereIndex("primary", () => false));
766
+
767
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
768
+ const compiled = uow.compile(compiler);
769
+
770
+ // When condition is false, the operation should return null and not be added to batch
771
+ expect(compiled.retrievalBatch).toHaveLength(0);
772
+ });
773
+
774
+ it("should handle always-true conditions", () => {
775
+ const uow = createTestUOW();
776
+ uow.find("users", (b) => b.whereIndex("primary", () => true));
777
+
778
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
779
+ const compiled = uow.compile(compiler);
780
+
781
+ expect(compiled.retrievalBatch).toHaveLength(1);
782
+ expect(compiled.retrievalBatch[0].sql).toMatchInlineSnapshot(
783
+ `"select \`id\`, \`name\`, \`email\`, \`age\`, \`_internalId\`, \`_version\` from \`users\` \`users\`"`,
784
+ );
785
+ });
786
+ });
787
+
788
+ describe("version checking", () => {
789
+ it("should embed version check in update WHERE clause", () => {
790
+ const uow = createTestUOW();
791
+
792
+ const userId = FragnoId.fromExternal("user123", 5);
793
+ uow.update("users", userId, (b) => b.set({ age: 31 }).check());
794
+
795
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
796
+ const compiled = uow.compile(compiler);
797
+ const [batch] = compiled.mutationBatch;
798
+ assert(batch);
799
+ expect(batch.expectedAffectedRows).toBe(1);
800
+ expect(batch.query.sql).toMatchInlineSnapshot(
801
+ `"update \`users\` set \`age\` = ?, \`_version\` = COALESCE(_version, 0) + 1 where (\`users\`.\`id\` = ? and \`users\`.\`_version\` = ?)"`,
802
+ );
803
+ expect(batch.query.params).toMatchObject([31, "user123", 5]);
804
+ });
805
+
806
+ it("should embed version check in delete WHERE clause", () => {
807
+ const uow = createTestUOW();
808
+
809
+ const userId = FragnoId.fromExternal("user456", 3);
810
+ uow.delete("users", userId, (b) => b.check());
811
+
812
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
813
+ const compiled = uow.compile(compiler);
814
+ const [batch] = compiled.mutationBatch;
815
+ assert(batch);
816
+ expect(batch.expectedAffectedRows).toBe(1);
817
+ expect(batch.query.sql).toMatchInlineSnapshot(
818
+ `"delete from \`users\` where (\`users\`.\`id\` = ? and \`users\`.\`_version\` = ?)"`,
819
+ );
820
+ expect(batch.query.params).toMatchObject(["user456", 3]);
821
+ });
822
+
823
+ it("should handle version checks on different tables", () => {
824
+ const uow = createTestUOW();
825
+
826
+ const userId = FragnoId.fromExternal("user1", 2);
827
+ const postId = FragnoId.fromExternal("post1", 1);
828
+
829
+ uow.update("users", userId, (b) => b.set({ age: 30 }).check());
830
+ uow.update("posts", postId, (b) => b.set({ viewCount: 100 }).check());
831
+
832
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
833
+ const compiled = uow.compile(compiler);
834
+ const [userBatch, postBatch] = compiled.mutationBatch;
835
+
836
+ expect(compiled.mutationBatch).toHaveLength(2);
837
+
838
+ assert(userBatch);
839
+ expect(userBatch.expectedAffectedRows).toBe(1);
840
+ expect(userBatch.query.sql).toMatchInlineSnapshot(
841
+ `"update \`users\` set \`age\` = ?, \`_version\` = COALESCE(_version, 0) + 1 where (\`users\`.\`id\` = ? and \`users\`.\`_version\` = ?)"`,
842
+ );
843
+ expect(userBatch.query.params).toMatchObject([30, "user1", 2]);
844
+
845
+ assert(postBatch);
846
+ expect(postBatch.expectedAffectedRows).toBe(1);
847
+ expect(postBatch.query.sql).toMatchInlineSnapshot(
848
+ `"update \`posts\` set \`viewCount\` = ?, \`_version\` = COALESCE(_version, 0) + 1 where (\`posts\`.\`id\` = ? and \`posts\`.\`_version\` = ?)"`,
849
+ );
850
+ expect(postBatch.query.params).toMatchObject([100, "post1", 1]);
851
+ });
852
+
853
+ it("should not affect updates without version checks", () => {
854
+ const uow = createTestUOW();
855
+
856
+ const userId = FragnoId.fromExternal("user1", 0);
857
+ uow.update("users", userId, (b) => b.set({ age: 25 }));
858
+
859
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
860
+ const compiled = uow.compile(compiler);
861
+ const [batch] = compiled.mutationBatch;
862
+ assert(batch);
863
+ expect(batch.expectedAffectedRows).toBeNull();
864
+ // Should be normal update without version check
865
+ expect(batch.query.sql).toMatchInlineSnapshot(
866
+ `"update \`users\` set \`age\` = ?, \`_version\` = COALESCE(_version, 0) + 1 where \`users\`.\`id\` = ?"`,
867
+ );
868
+ });
869
+ });
870
+
871
+ describe("edge cases", () => {
872
+ it("should handle UOW with no operations", () => {
873
+ const uow = createTestUOW();
874
+
875
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
876
+ const compiled = uow.compile(compiler);
877
+
878
+ expect(compiled.retrievalBatch).toHaveLength(0);
879
+ expect(compiled.mutationBatch).toHaveLength(0);
880
+ });
881
+
882
+ it("should handle UOW with only retrieval operations", () => {
883
+ const uow = createTestUOW();
884
+ uow.find("users");
885
+
886
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
887
+ const compiled = uow.compile(compiler);
888
+
889
+ expect(compiled.retrievalBatch).toHaveLength(1);
890
+ expect(compiled.mutationBatch).toHaveLength(0);
891
+ });
892
+
893
+ it("should handle UOW with only mutation operations", () => {
894
+ const uow = createTestUOW();
895
+ uow.create("users", {
896
+ name: "Test User",
897
+ email: "test@example.com",
898
+ });
899
+
900
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
901
+ const compiled = uow.compile(compiler);
902
+
903
+ expect(compiled.retrievalBatch).toHaveLength(0);
904
+ expect(compiled.mutationBatch).toHaveLength(1);
905
+ });
906
+ });
907
+
908
+ describe("default value generation", () => {
909
+ // Create a schema with columns that have different types of defaults
910
+ const defaultsSchema = schema((s) => {
911
+ return s.addTable("logs", (t) => {
912
+ return t
913
+ .addColumn("id", idColumn())
914
+ .addColumn("message", column("string"))
915
+ .addColumn(
916
+ "sessionId",
917
+ column("string").defaultTo$((b) => b.cuid()),
918
+ ) // runtime cuid
919
+ .addColumn(
920
+ "timestamp",
921
+ column("timestamp").defaultTo$((b) => b.now()),
922
+ ) // runtime now
923
+ .addColumn("counter", column("integer").defaultTo$(42)) // runtime function
924
+ .addColumn("status", column("string").defaultTo("pending")) // static default
925
+ .createIndex("idx_session", ["sessionId"]);
926
+ });
927
+ });
928
+
929
+ let defaultsDb: DBType;
930
+ let defaultsPool: ConnectionPool<DBType>;
931
+
932
+ beforeAll(async () => {
933
+ // Write schema to file and dynamically import it
934
+ const { schemaModule, cleanup } = await writeAndLoadSchema(
935
+ "drizzle-uow-compiler-defaults-mysql",
936
+ defaultsSchema,
937
+ "mysql",
938
+ );
939
+
940
+ // Create Drizzle instance with mock connection (we only test SQL generation)
941
+ const mockConnection: unknown = {
942
+ query: () => Promise.resolve([]),
943
+ execute: () => Promise.resolve([]),
944
+ end: () => Promise.resolve(),
945
+ };
946
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
947
+ defaultsDb = drizzle(mockConnection as any, {
948
+ schema: schemaModule,
949
+ mode: "default",
950
+ }) as unknown as DBType;
951
+
952
+ // Wrap in connection pool
953
+ defaultsPool = createDrizzleConnectionPool(defaultsDb);
954
+
955
+ return async () => {
956
+ await cleanup();
957
+ };
958
+ }, 12000);
959
+
960
+ it("should generate runtime defaults for missing columns", () => {
961
+ const uow = createTestUOWWithSchema(defaultsSchema);
962
+ // Only provide message, all other columns should get defaults
963
+ uow.create("logs", {
964
+ message: "Test log",
965
+ });
966
+
967
+ const compiler = createDrizzleUOWCompiler(defaultsPool, "mysql");
968
+ const compiled = uow.compile(compiler);
969
+ const [batch] = compiled.mutationBatch;
970
+ assert(batch);
971
+
972
+ expect(batch.query.sql).toMatchInlineSnapshot(
973
+ `"insert into \`logs\` (\`id\`, \`message\`, \`sessionId\`, \`timestamp\`, \`counter\`, \`status\`, \`_internalId\`, \`_version\`) values (?, ?, ?, ?, ?, default, default, default)"`,
974
+ );
975
+
976
+ expect(batch.query.params).toMatchObject([
977
+ expect.any(String), // auto-generated ID
978
+ "Test log",
979
+ expect.any(String), // auto-generated sessionId
980
+ expect.any(String), // auto-generated timestamp (MySQL uses datetime string format)
981
+ 42, // function-generated counter
982
+ // Note: MySQL uses DEFAULT in SQL for status and _version, not parameters
983
+ ]);
984
+ });
985
+
986
+ it("should not override user-provided values with defaults", () => {
987
+ const uow = createTestUOWWithSchema(defaultsSchema);
988
+ const customTimestamp = new Date("2024-01-01");
989
+ // Provide all values explicitly
990
+ uow.create("logs", {
991
+ message: "Test log",
992
+ sessionId: "custom-session-id",
993
+ timestamp: customTimestamp,
994
+ counter: 100,
995
+ status: "active",
996
+ });
997
+
998
+ const compiler = createDrizzleUOWCompiler(defaultsPool, "mysql");
999
+ const compiled = uow.compile(compiler);
1000
+ const [batch] = compiled.mutationBatch;
1001
+ assert(batch);
1002
+
1003
+ // All user-provided values should be used, not defaults
1004
+ const params = batch.query.params;
1005
+ expect(params[1]).toBe("Test log");
1006
+ expect(params[2]).toBe("custom-session-id");
1007
+ expect(params[3]).toBe("2024-01-01 00:00:00.000"); // MySQL uses datetime string format
1008
+ expect(params[4]).toBe(100);
1009
+ expect(params[5]).toBe("active");
1010
+ });
1011
+
1012
+ it("should handle mix of provided and default values", () => {
1013
+ const uow = createTestUOWWithSchema(defaultsSchema);
1014
+ // Provide some values, let others use defaults
1015
+ uow.create("logs", {
1016
+ message: "Partial log",
1017
+ counter: 999, // override the function default
1018
+ });
1019
+
1020
+ const compiler = createDrizzleUOWCompiler(defaultsPool, "mysql");
1021
+ const compiled = uow.compile(compiler);
1022
+ const [batch] = compiled.mutationBatch;
1023
+ assert(batch);
1024
+
1025
+ expect(batch.query.params).toMatchObject([
1026
+ expect.any(String), // auto-generated ID
1027
+ "Partial log",
1028
+ expect.any(String), // auto-generated sessionId
1029
+ expect.any(String), // auto-generated timestamp (MySQL uses datetime string format)
1030
+ 999, // user-provided counter
1031
+ // Note: MySQL uses DEFAULT in SQL for status and _version, not parameters
1032
+ ]);
1033
+ });
1034
+
1035
+ it("should generate unique values for auto defaults across multiple creates", () => {
1036
+ const uow = createTestUOWWithSchema(defaultsSchema);
1037
+ uow.create("logs", { message: "Log 1" });
1038
+ uow.create("logs", { message: "Log 2" });
1039
+ uow.create("logs", { message: "Log 3" });
1040
+
1041
+ const compiler = createDrizzleUOWCompiler(defaultsPool, "mysql");
1042
+ const compiled = uow.compile(compiler);
1043
+
1044
+ expect(compiled.mutationBatch).toHaveLength(3);
1045
+
1046
+ // Extract sessionId from each create
1047
+ const sessionIds = compiled.mutationBatch.map((batch) => {
1048
+ assert(batch);
1049
+ return batch.query.params[2]; // sessionId is 3rd param (after id, message)
1050
+ });
1051
+
1052
+ // All sessionIds should be unique
1053
+ const uniqueSessionIds = new Set(sessionIds);
1054
+ expect(uniqueSessionIds.size).toBe(3);
1055
+ });
1056
+ });
1057
+
1058
+ describe("nested joins", () => {
1059
+ // Create a schema that supports nested joins
1060
+ const nestedSchema = schema((s) => {
1061
+ return s
1062
+ .addTable("users", (t) => {
1063
+ return t
1064
+ .addColumn("id", idColumn())
1065
+ .addColumn("name", column("string"))
1066
+ .addColumn("email", column("string"))
1067
+ .createIndex("idx_name", ["name"]);
1068
+ })
1069
+ .addTable("posts", (t) => {
1070
+ return t
1071
+ .addColumn("id", idColumn())
1072
+ .addColumn("title", column("string"))
1073
+ .addColumn("userId", referenceColumn())
1074
+ .createIndex("idx_user", ["userId"]);
1075
+ })
1076
+ .addTable("comments", (t) => {
1077
+ return t
1078
+ .addColumn("id", idColumn())
1079
+ .addColumn("text", column("string"))
1080
+ .addColumn("postId", referenceColumn())
1081
+ .createIndex("idx_post", ["postId"]);
1082
+ })
1083
+ .addReference("author", {
1084
+ type: "one",
1085
+ from: { table: "posts", column: "userId" },
1086
+ to: { table: "users", column: "id" },
1087
+ })
1088
+ .addReference("post", {
1089
+ type: "one",
1090
+ from: { table: "comments", column: "postId" },
1091
+ to: { table: "posts", column: "id" },
1092
+ });
1093
+ });
1094
+
1095
+ let nestedDb: DBType;
1096
+ let nestedPool: ConnectionPool<DBType>;
1097
+
1098
+ beforeAll(async () => {
1099
+ // Write schema to file and dynamically import it
1100
+ const { schemaModule, cleanup } = await writeAndLoadSchema(
1101
+ "drizzle-uow-compiler-nested-mysql",
1102
+ nestedSchema,
1103
+ "mysql",
1104
+ );
1105
+
1106
+ // Create Drizzle instance with mock connection (we only test SQL generation)
1107
+ const mockConnection: unknown = {
1108
+ query: () => Promise.resolve([]),
1109
+ execute: () => Promise.resolve([]),
1110
+ end: () => Promise.resolve(),
1111
+ };
1112
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1113
+ nestedDb = drizzle(mockConnection as any, {
1114
+ schema: schemaModule,
1115
+ mode: "default",
1116
+ }) as unknown as DBType;
1117
+
1118
+ // Wrap in connection pool
1119
+ nestedPool = createDrizzleConnectionPool(nestedDb);
1120
+
1121
+ return async () => {
1122
+ await cleanup();
1123
+ };
1124
+ }, 20000);
1125
+
1126
+ function createNestedUOW(name?: string) {
1127
+ const compiler = createDrizzleUOWCompiler(nestedPool, "mysql");
1128
+ const mockExecutor = {
1129
+ executeRetrievalPhase: async () => [],
1130
+ executeMutationPhase: async () => ({ success: true, createdInternalIds: [] }),
1131
+ };
1132
+ const mockDecoder: UOWDecoder<typeof nestedSchema> = (rawResults, operations) => {
1133
+ if (rawResults.length !== operations.length) {
1134
+ throw new Error("rawResults and ops must have the same length");
1135
+ }
1136
+ return rawResults;
1137
+ };
1138
+ return new UnitOfWork(compiler, mockExecutor, mockDecoder, name).forSchema(nestedSchema);
1139
+ }
1140
+
1141
+ it("should compile nested joins (comments -> post -> author)", () => {
1142
+ const uow = createNestedUOW();
1143
+ uow.find("comments", (b) =>
1144
+ b
1145
+ .whereIndex("primary")
1146
+ .join((jb) =>
1147
+ jb.post((postBuilder) =>
1148
+ postBuilder
1149
+ .select(["title"])
1150
+ .join((jb2) => jb2.author((authorBuilder) => authorBuilder.select(["name"]))),
1151
+ ),
1152
+ ),
1153
+ );
1154
+
1155
+ const compiler = createDrizzleUOWCompiler(nestedPool, "mysql");
1156
+ const compiled = uow.compile(compiler);
1157
+
1158
+ expect(compiled.retrievalBatch).toHaveLength(1);
1159
+ const sql = compiled.retrievalBatch[0].sql;
1160
+
1161
+ // Should contain nested lateral joins
1162
+
1163
+ // Should join comments -> post
1164
+
1165
+ // Should join post -> author within the first join
1166
+
1167
+ // Should have the nested structure with proper lateral joins
1168
+ expect(sql).toMatchInlineSnapshot(
1169
+ `"select \`comments\`.\`id\`, \`comments\`.\`text\`, \`comments\`.\`postId\`, \`comments\`.\`_internalId\`, \`comments\`.\`_version\`, \`comments_post\`.\`data\` as \`post\` from \`comments\` \`comments\` left join lateral (select json_array(\`comments_post\`.\`title\`, \`comments_post\`.\`_internalId\`, \`comments_post\`.\`_version\`, \`comments_post_author\`.\`data\`) as \`data\` from (select * from \`posts\` \`comments_post\` where \`comments_post\`.\`_internalId\` = \`comments\`.\`postId\` limit ?) \`comments_post\` left join lateral (select json_array(\`comments_post_author\`.\`name\`, \`comments_post_author\`.\`_internalId\`, \`comments_post_author\`.\`_version\`) as \`data\` from (select * from \`users\` \`comments_post_author\` where \`comments_post_author\`.\`_internalId\` = \`comments_post\`.\`userId\` limit ?) \`comments_post_author\`) \`comments_post_author\` on true) \`comments_post\` on true"`,
1170
+ );
1171
+ });
1172
+
1173
+ it("should compile nested joins with filtering at each level", () => {
1174
+ const uow = createNestedUOW();
1175
+ uow.find("comments", (b) =>
1176
+ b
1177
+ .whereIndex("primary")
1178
+ .join((jb) =>
1179
+ jb.post((postBuilder) =>
1180
+ postBuilder
1181
+ .select(["title"])
1182
+ .join((jb2) =>
1183
+ jb2.author((authorBuilder) =>
1184
+ authorBuilder
1185
+ .whereIndex("idx_name", (eb) => eb("name", "=", "Alice"))
1186
+ .select(["name"]),
1187
+ ),
1188
+ ),
1189
+ ),
1190
+ ),
1191
+ );
1192
+
1193
+ const compiler = createDrizzleUOWCompiler(nestedPool, "mysql");
1194
+ const compiled = uow.compile(compiler);
1195
+
1196
+ expect(compiled.retrievalBatch).toHaveLength(1);
1197
+ const sql = compiled.retrievalBatch[0].sql;
1198
+
1199
+ // Should have WHERE clause in the nested author join
1200
+
1201
+ expect(sql).toMatchInlineSnapshot(
1202
+ `"select \`comments\`.\`id\`, \`comments\`.\`text\`, \`comments\`.\`postId\`, \`comments\`.\`_internalId\`, \`comments\`.\`_version\`, \`comments_post\`.\`data\` as \`post\` from \`comments\` \`comments\` left join lateral (select json_array(\`comments_post\`.\`title\`, \`comments_post\`.\`_internalId\`, \`comments_post\`.\`_version\`, \`comments_post_author\`.\`data\`) as \`data\` from (select * from \`posts\` \`comments_post\` where \`comments_post\`.\`_internalId\` = \`comments\`.\`postId\` limit ?) \`comments_post\` left join lateral (select json_array(\`comments_post_author\`.\`name\`, \`comments_post_author\`.\`_internalId\`, \`comments_post_author\`.\`_version\`) as \`data\` from (select * from \`users\` \`comments_post_author\` where (\`comments_post_author\`.\`_internalId\` = \`comments_post\`.\`userId\` and \`comments_post_author\`.\`name\` = ?) limit ?) \`comments_post_author\`) \`comments_post_author\` on true) \`comments_post\` on true"`,
1203
+ );
1204
+ });
1205
+
1206
+ it("should compile nested joins with ordering and limits at each level", () => {
1207
+ const uow = createNestedUOW();
1208
+ uow.find("comments", (b) =>
1209
+ b
1210
+ .whereIndex("primary")
1211
+ .pageSize(10)
1212
+ .join((jb) =>
1213
+ jb.post((postBuilder) =>
1214
+ postBuilder
1215
+ .select(["title"])
1216
+ .pageSize(1)
1217
+ .join((jb2) =>
1218
+ jb2.author((authorBuilder) =>
1219
+ authorBuilder.orderByIndex("idx_name", "asc").pageSize(1),
1220
+ ),
1221
+ ),
1222
+ ),
1223
+ ),
1224
+ );
1225
+
1226
+ const compiler = createDrizzleUOWCompiler(nestedPool, "mysql");
1227
+ const compiled = uow.compile(compiler);
1228
+
1229
+ expect(compiled.retrievalBatch).toHaveLength(1);
1230
+ const sql = compiled.retrievalBatch[0].sql;
1231
+
1232
+ // Should have limits at all levels and ordering in nested author join
1233
+
1234
+ expect(sql).toMatchInlineSnapshot(
1235
+ `"select \`comments\`.\`id\`, \`comments\`.\`text\`, \`comments\`.\`postId\`, \`comments\`.\`_internalId\`, \`comments\`.\`_version\`, \`comments_post\`.\`data\` as \`post\` from \`comments\` \`comments\` left join lateral (select json_array(\`comments_post\`.\`title\`, \`comments_post\`.\`_internalId\`, \`comments_post\`.\`_version\`, \`comments_post_author\`.\`data\`) as \`data\` from (select * from \`posts\` \`comments_post\` where \`comments_post\`.\`_internalId\` = \`comments\`.\`postId\` limit ?) \`comments_post\` left join lateral (select json_array(\`comments_post_author\`.\`id\`, \`comments_post_author\`.\`name\`, \`comments_post_author\`.\`email\`, \`comments_post_author\`.\`_internalId\`, \`comments_post_author\`.\`_version\`) as \`data\` from (select *, row_number() over (order by \`comments_post_author\`.\`name\` asc) from \`users\` \`comments_post_author\` where \`comments_post_author\`.\`_internalId\` = \`comments_post\`.\`userId\` limit ?) \`comments_post_author\`) \`comments_post_author\` on true) \`comments_post\` on true limit ?"`,
1236
+ );
1237
+ });
1238
+
1239
+ it("should compile multiple nested joins from same table", () => {
1240
+ const uow = createNestedUOW();
1241
+ uow.find("posts", (b) =>
1242
+ b.whereIndex("primary").join((jb) =>
1243
+ // Join to author with nested structure
1244
+ jb.author((authorBuilder) => authorBuilder.select(["name", "email"])),
1245
+ ),
1246
+ );
1247
+
1248
+ const compiler = createDrizzleUOWCompiler(nestedPool, "mysql");
1249
+ const compiled = uow.compile(compiler);
1250
+
1251
+ expect(compiled.retrievalBatch).toHaveLength(1);
1252
+ const sql = compiled.retrievalBatch[0].sql;
1253
+ expect(sql).toMatchInlineSnapshot(
1254
+ `"select \`posts\`.\`id\`, \`posts\`.\`title\`, \`posts\`.\`userId\`, \`posts\`.\`_internalId\`, \`posts\`.\`_version\`, \`posts_author\`.\`data\` as \`author\` from \`posts\` \`posts\` left join lateral (select json_array(\`posts_author\`.\`name\`, \`posts_author\`.\`email\`, \`posts_author\`.\`_internalId\`, \`posts_author\`.\`_version\`) as \`data\` from (select * from \`users\` \`posts_author\` where \`posts_author\`.\`_internalId\` = \`posts\`.\`userId\` limit ?) \`posts_author\`) \`posts_author\` on true"`,
1255
+ );
1256
+ });
1257
+ });
1258
+
1259
+ describe("auth schema with session joins", () => {
1260
+ const authSchema = schema((s) => {
1261
+ return s
1262
+ .addTable("user", (t) => {
1263
+ return t
1264
+ .addColumn("id", idColumn())
1265
+ .addColumn("email", column("string"))
1266
+ .addColumn("passwordHash", column("string"))
1267
+ .addColumn(
1268
+ "createdAt",
1269
+ column("timestamp").defaultTo$((b) => b.now()),
1270
+ )
1271
+ .createIndex("idx_user_email", ["email"]);
1272
+ })
1273
+ .addTable("session", (t) => {
1274
+ return t
1275
+ .addColumn("id", idColumn())
1276
+ .addColumn("userId", referenceColumn())
1277
+ .addColumn("expiresAt", column("timestamp"))
1278
+ .addColumn(
1279
+ "createdAt",
1280
+ column("timestamp").defaultTo$((b) => b.now()),
1281
+ )
1282
+ .createIndex("idx_session_user", ["userId"]);
1283
+ })
1284
+ .addReference("sessionOwner", {
1285
+ from: {
1286
+ table: "session",
1287
+ column: "userId",
1288
+ },
1289
+ to: {
1290
+ table: "user",
1291
+ column: "id",
1292
+ },
1293
+ type: "one",
1294
+ });
1295
+ });
1296
+
1297
+ let authDb: DBType;
1298
+ let authPool: ConnectionPool<DBType>;
1299
+
1300
+ beforeAll(async () => {
1301
+ // Write schema to file and dynamically import it
1302
+ const { schemaModule, cleanup } = await writeAndLoadSchema(
1303
+ "drizzle-uow-compiler-auth-mysql",
1304
+ authSchema,
1305
+ "mysql",
1306
+ );
1307
+
1308
+ // Create Drizzle instance with mock connection (we only test SQL generation)
1309
+ const mockConnection: unknown = {
1310
+ query: () => Promise.resolve([]),
1311
+ execute: () => Promise.resolve([]),
1312
+ end: () => Promise.resolve(),
1313
+ };
1314
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1315
+ authDb = drizzle(mockConnection as any, {
1316
+ schema: schemaModule,
1317
+ mode: "default",
1318
+ }) as unknown as DBType;
1319
+
1320
+ // Wrap in connection pool
1321
+ authPool = createDrizzleConnectionPool(authDb);
1322
+
1323
+ return async () => {
1324
+ await cleanup();
1325
+ };
1326
+ }, 12000);
1327
+
1328
+ function createAuthUOW(name?: string) {
1329
+ const compiler = createDrizzleUOWCompiler(authPool, "mysql");
1330
+ const mockExecutor = {
1331
+ executeRetrievalPhase: async () => [],
1332
+ executeMutationPhase: async () => ({ success: true, createdInternalIds: [] }),
1333
+ };
1334
+ const mockDecoder: UOWDecoder = (rawResults, operations) => {
1335
+ if (rawResults.length !== operations.length) {
1336
+ throw new Error("rawResults and ops must have the same length");
1337
+ }
1338
+ return rawResults;
1339
+ };
1340
+ return new UnitOfWork(compiler, mockExecutor, mockDecoder, name).forSchema(authSchema);
1341
+ }
1342
+
1343
+ it("should compile find session with user join", () => {
1344
+ const uow = createAuthUOW();
1345
+ const sessionId = "session123";
1346
+ uow.find("session", (b) =>
1347
+ b
1348
+ .whereIndex("primary", (eb) => eb("id", "=", sessionId))
1349
+ .join((j) => j.sessionOwner((b) => b.select(["id", "email"]))),
1350
+ );
1351
+
1352
+ const compiler = createDrizzleUOWCompiler(authPool, "mysql");
1353
+ const compiled = uow.compile(compiler);
1354
+
1355
+ expect(compiled.retrievalBatch).toHaveLength(1);
1356
+ expect(compiled.retrievalBatch[0].sql).toMatchInlineSnapshot(
1357
+ `"select \`session\`.\`id\`, \`session\`.\`userId\`, \`session\`.\`expiresAt\`, \`session\`.\`createdAt\`, \`session\`.\`_internalId\`, \`session\`.\`_version\`, \`session_sessionOwner\`.\`data\` as \`sessionOwner\` from \`session\` \`session\` left join lateral (select json_array(\`session_sessionOwner\`.\`id\`, \`session_sessionOwner\`.\`email\`, \`session_sessionOwner\`.\`_internalId\`, \`session_sessionOwner\`.\`_version\`) as \`data\` from (select * from \`user\` \`session_sessionOwner\` where \`session_sessionOwner\`.\`_internalId\` = \`session\`.\`userId\` limit ?) \`session_sessionOwner\`) \`session_sessionOwner\` on true where \`session\`.\`id\` = ?"`,
1358
+ );
1359
+ expect(compiled.retrievalBatch[0].params).toEqual([1, sessionId]);
1360
+ });
1361
+
1362
+ it("should support creating and using ID in same UOW", () => {
1363
+ const uow = createAuthUOW("create-user-and-session");
1364
+
1365
+ // Create user and capture the returned ID
1366
+ const userId = uow.create("user", {
1367
+ email: "test@example.com",
1368
+ passwordHash: "hashed_password",
1369
+ });
1370
+
1371
+ // Use the returned FragnoId directly to create a session
1372
+ // The compiler should extract externalId and generate a subquery
1373
+ uow.create("session", {
1374
+ userId: userId,
1375
+ expiresAt: new Date("2025-12-31"),
1376
+ });
1377
+
1378
+ const compiler = createDrizzleUOWCompiler(authPool, "mysql");
1379
+ const compiled = uow.compile(compiler);
1380
+
1381
+ // Should have no retrieval operations
1382
+ expect(compiled.retrievalBatch).toHaveLength(0);
1383
+
1384
+ // Should have 2 mutation operations (create user, create session)
1385
+ expect(compiled.mutationBatch).toHaveLength(2);
1386
+
1387
+ const [userCreate, sessionCreate] = compiled.mutationBatch;
1388
+ assert(userCreate);
1389
+ assert(sessionCreate);
1390
+
1391
+ // Verify user create SQL
1392
+ expect(userCreate.query.sql).toMatchInlineSnapshot(
1393
+ `"insert into \`user\` (\`id\`, \`email\`, \`passwordHash\`, \`createdAt\`, \`_internalId\`, \`_version\`) values (?, ?, ?, ?, default, default)"`,
1394
+ );
1395
+ expect(userCreate.query.params).toMatchObject([
1396
+ userId.externalId, // The generated ID
1397
+ "test@example.com",
1398
+ "hashed_password",
1399
+ expect.any(String), // timestamp (MySQL uses datetime string format)
1400
+ // Note: MySQL uses DEFAULT in SQL for _version, not a parameter
1401
+ ]);
1402
+ expect(userCreate.expectedAffectedRows).toBeNull();
1403
+
1404
+ // Verify session create SQL - FragnoId generates subquery to lookup internal ID
1405
+ expect(sessionCreate.query.sql).toMatchInlineSnapshot(
1406
+ `"insert into \`session\` (\`id\`, \`userId\`, \`expiresAt\`, \`createdAt\`, \`_internalId\`, \`_version\`) values (?, (select \`_internalId\` from \`user\` where \`id\` = ? limit 1), ?, ?, default, default)"`,
1407
+ );
1408
+ expect(sessionCreate.query.params).toMatchObject([
1409
+ expect.any(String), // generated session ID
1410
+ userId.externalId, // FragnoId's externalId is used in the subquery
1411
+ expect.any(String), // expiresAt timestamp (MySQL uses datetime string format)
1412
+ expect.any(String), // createdAt timestamp (MySQL uses datetime string format)
1413
+ // Note: MySQL uses DEFAULT in SQL for _internalId and _version, not parameters
1414
+ ]);
1415
+ expect(sessionCreate.expectedAffectedRows).toBeNull();
1416
+
1417
+ // Verify the returned FragnoId has the expected structure
1418
+ expect(userId).toMatchObject({
1419
+ externalId: expect.any(String),
1420
+ version: 0,
1421
+ internalId: undefined,
1422
+ });
1423
+ });
1424
+
1425
+ it("should compile check operation", () => {
1426
+ const uow = createTestUOW();
1427
+ const userId = FragnoId.fromExternal("user123", 5);
1428
+ uow.check("users", userId);
1429
+
1430
+ const compiler = createDrizzleUOWCompiler(pool, "mysql");
1431
+ const compiled = uow.compile(compiler);
1432
+ const [batch] = compiled.mutationBatch;
1433
+ assert(batch);
1434
+ expect(batch.expectedAffectedRows).toBe(null);
1435
+ expect(batch.expectedReturnedRows).toBe(1);
1436
+ expect(batch.query.sql).toMatchInlineSnapshot(
1437
+ `"select 1 as \`exists\` from \`users\` where (\`users\`.\`id\` = ? and \`users\`.\`_version\` = ?) limit ?"`,
1438
+ );
1439
+ expect(batch.query.params).toMatchObject(["user123", 5, 1]);
1440
+ });
1441
+ });
1442
+ });