@nicia-ai/typegraph 0.2.0 → 0.3.0

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 (146) hide show
  1. package/README.md +23 -0
  2. package/dist/{ast-BVyihVbP.d.cts → ast-CXFx6bF6.d.ts} +45 -165
  3. package/dist/{ast-BVyihVbP.d.ts → ast-D-3bOanX.d.cts} +45 -165
  4. package/dist/backend/drizzle/index.cjs +20 -20
  5. package/dist/backend/drizzle/index.d.cts +6 -5
  6. package/dist/backend/drizzle/index.d.ts +6 -5
  7. package/dist/backend/drizzle/index.js +8 -8
  8. package/dist/backend/drizzle/postgres.cjs +9 -9
  9. package/dist/backend/drizzle/postgres.d.cts +9 -11
  10. package/dist/backend/drizzle/postgres.d.ts +9 -11
  11. package/dist/backend/drizzle/postgres.js +6 -6
  12. package/dist/backend/drizzle/schema/postgres.cjs +10 -10
  13. package/dist/backend/drizzle/schema/postgres.d.cts +6 -5
  14. package/dist/backend/drizzle/schema/postgres.d.ts +6 -5
  15. package/dist/backend/drizzle/schema/postgres.js +3 -3
  16. package/dist/backend/drizzle/schema/sqlite.cjs +10 -10
  17. package/dist/backend/drizzle/schema/sqlite.d.cts +6 -5
  18. package/dist/backend/drizzle/schema/sqlite.d.ts +6 -5
  19. package/dist/backend/drizzle/schema/sqlite.js +3 -3
  20. package/dist/backend/drizzle/sqlite.cjs +9 -9
  21. package/dist/backend/drizzle/sqlite.d.cts +17 -18
  22. package/dist/backend/drizzle/sqlite.d.ts +17 -18
  23. package/dist/backend/drizzle/sqlite.js +6 -6
  24. package/dist/backend/postgres/index.cjs +21 -17
  25. package/dist/backend/postgres/index.d.cts +8 -7
  26. package/dist/backend/postgres/index.d.ts +8 -7
  27. package/dist/backend/postgres/index.js +8 -8
  28. package/dist/backend/sqlite/index.cjs +27 -21
  29. package/dist/backend/sqlite/index.cjs.map +1 -1
  30. package/dist/backend/sqlite/index.d.cts +7 -6
  31. package/dist/backend/sqlite/index.d.ts +7 -6
  32. package/dist/backend/sqlite/index.js +18 -12
  33. package/dist/backend/sqlite/index.js.map +1 -1
  34. package/dist/{chunk-YM5AL65Y.cjs → chunk-2WVFEIHR.cjs} +29 -3
  35. package/dist/chunk-2WVFEIHR.cjs.map +1 -0
  36. package/dist/{chunk-4PIEL2VO.js → chunk-3PURVEA4.js} +36 -5
  37. package/dist/chunk-3PURVEA4.js.map +1 -0
  38. package/dist/chunk-4HARSV2G.js +1448 -0
  39. package/dist/chunk-4HARSV2G.js.map +1 -0
  40. package/dist/{chunk-IIAT36MI.js → chunk-54WJF3DW.js} +29 -3
  41. package/dist/chunk-54WJF3DW.js.map +1 -0
  42. package/dist/chunk-CMHFS34N.cjs +390 -0
  43. package/dist/chunk-CMHFS34N.cjs.map +1 -0
  44. package/dist/chunk-DD6ONEBN.cjs +1264 -0
  45. package/dist/chunk-DD6ONEBN.cjs.map +1 -0
  46. package/dist/chunk-F2BZSEFE.js +388 -0
  47. package/dist/chunk-F2BZSEFE.js.map +1 -0
  48. package/dist/{chunk-DDM2FZRJ.cjs → chunk-JQDWEX6V.cjs} +24 -24
  49. package/dist/{chunk-DDM2FZRJ.cjs.map → chunk-JQDWEX6V.cjs.map} +1 -1
  50. package/dist/chunk-NP4G4ZKM.js +1228 -0
  51. package/dist/chunk-NP4G4ZKM.js.map +1 -0
  52. package/dist/{chunk-UJAGXJDG.cjs → chunk-NU2XNMVI.cjs} +38 -7
  53. package/dist/chunk-NU2XNMVI.cjs.map +1 -0
  54. package/dist/{chunk-JKTO7TW3.js → chunk-O5XPCJLF.js} +25 -3
  55. package/dist/chunk-O5XPCJLF.js.map +1 -0
  56. package/dist/{chunk-2QHQ2C4P.js → chunk-OGGLFYFA.js} +36 -5
  57. package/dist/chunk-OGGLFYFA.js.map +1 -0
  58. package/dist/{chunk-SV5H3XM5.cjs → chunk-OYL2SGBD.cjs} +26 -2
  59. package/dist/chunk-OYL2SGBD.cjs.map +1 -0
  60. package/dist/chunk-SFY2PPOY.cjs +1469 -0
  61. package/dist/chunk-SFY2PPOY.cjs.map +1 -0
  62. package/dist/{chunk-JDAET5LO.js → chunk-SMLIWLS7.js} +9 -9
  63. package/dist/chunk-SMLIWLS7.js.map +1 -0
  64. package/dist/{chunk-VXRVGFCI.js → chunk-U3452TEU.js} +17 -17
  65. package/dist/{chunk-VXRVGFCI.js.map → chunk-U3452TEU.js.map} +1 -1
  66. package/dist/{chunk-MNO33ASC.cjs → chunk-UYMT4LO2.cjs} +9 -8
  67. package/dist/chunk-UYMT4LO2.cjs.map +1 -0
  68. package/dist/chunk-V7CS2MDB.cjs +289 -0
  69. package/dist/chunk-V7CS2MDB.cjs.map +1 -0
  70. package/dist/chunk-WE5BKYNB.js +287 -0
  71. package/dist/chunk-WE5BKYNB.js.map +1 -0
  72. package/dist/{chunk-L642L24T.js → chunk-XDTYTNYL.js} +14 -21
  73. package/dist/chunk-XDTYTNYL.js.map +1 -0
  74. package/dist/{chunk-N4AOJ3VF.cjs → chunk-XZL6MCZJ.cjs} +38 -7
  75. package/dist/chunk-XZL6MCZJ.cjs.map +1 -0
  76. package/dist/{chunk-DBFCKELK.cjs → chunk-ZJHQZZT2.cjs} +18 -27
  77. package/dist/chunk-ZJHQZZT2.cjs.map +1 -0
  78. package/dist/index-Dkicw49A.d.cts +373 -0
  79. package/dist/index-Dkicw49A.d.ts +373 -0
  80. package/dist/index.cjs +5915 -3377
  81. package/dist/index.cjs.map +1 -1
  82. package/dist/index.d.cts +24 -664
  83. package/dist/index.d.ts +24 -664
  84. package/dist/index.js +5781 -3223
  85. package/dist/index.js.map +1 -1
  86. package/dist/indexes/index.cjs +16 -16
  87. package/dist/indexes/index.d.cts +5 -4
  88. package/dist/indexes/index.d.ts +5 -4
  89. package/dist/indexes/index.js +2 -2
  90. package/dist/interchange/index.cjs +9 -9
  91. package/dist/interchange/index.cjs.map +1 -1
  92. package/dist/interchange/index.d.cts +5 -3
  93. package/dist/interchange/index.d.ts +5 -3
  94. package/dist/interchange/index.js +8 -8
  95. package/dist/interchange/index.js.map +1 -1
  96. package/dist/manager-Jc5Btay9.d.cts +493 -0
  97. package/dist/manager-e9LXthrx.d.ts +493 -0
  98. package/dist/profiler/index.cjs +2 -8
  99. package/dist/profiler/index.cjs.map +1 -1
  100. package/dist/profiler/index.d.cts +9 -161
  101. package/dist/profiler/index.d.ts +9 -161
  102. package/dist/profiler/index.js +4 -4
  103. package/dist/profiler/index.js.map +1 -1
  104. package/dist/schema/index.cjs +145 -0
  105. package/dist/schema/index.cjs.map +1 -0
  106. package/dist/schema/index.d.cts +237 -0
  107. package/dist/schema/index.d.ts +237 -0
  108. package/dist/schema/index.js +72 -0
  109. package/dist/schema/index.js.map +1 -0
  110. package/dist/{store-BPhjw5S8.d.ts → store-DM3Tk3Pw.d.ts} +874 -1283
  111. package/dist/{store-DNOOQEm8.d.cts → store-nbBybLWP.d.cts} +874 -1283
  112. package/dist/{test-helpers-BjyRYJZX.d.ts → test-helpers-CIq1Hhj1.d.ts} +5 -1
  113. package/dist/{test-helpers-NoQXhleQ.d.cts → test-helpers-DPRFVky4.d.cts} +5 -1
  114. package/dist/{types-D_3mEv2y.d.ts → types-BL1GyVku.d.cts} +2 -2
  115. package/dist/{types-DsRfx0yk.d.ts → types-Cdbi4hcx.d.ts} +228 -4
  116. package/dist/{types-BrSfFSpW.d.cts → types-DCGa53O2.d.ts} +2 -2
  117. package/dist/{types-aapj0GLz.d.cts → types-DDP0MGBF.d.cts} +228 -4
  118. package/dist/{types-CX4cLd7M.d.ts → types-DHRsi6j9.d.cts} +4 -3
  119. package/dist/types-DTJEu_-h.d.cts +158 -0
  120. package/dist/types-DTJEu_-h.d.ts +158 -0
  121. package/dist/{types-a5rAxC92.d.cts → types-ZT5mlism.d.ts} +4 -3
  122. package/package.json +17 -2
  123. package/dist/chunk-2FURVVAX.cjs +0 -350
  124. package/dist/chunk-2FURVVAX.cjs.map +0 -1
  125. package/dist/chunk-2QHQ2C4P.js.map +0 -1
  126. package/dist/chunk-4PIEL2VO.js.map +0 -1
  127. package/dist/chunk-DBFCKELK.cjs.map +0 -1
  128. package/dist/chunk-H7THXVH6.cjs +0 -314
  129. package/dist/chunk-H7THXVH6.cjs.map +0 -1
  130. package/dist/chunk-HXAPXPZH.cjs +0 -680
  131. package/dist/chunk-HXAPXPZH.cjs.map +0 -1
  132. package/dist/chunk-IIAT36MI.js.map +0 -1
  133. package/dist/chunk-JDAET5LO.js.map +0 -1
  134. package/dist/chunk-JKTO7TW3.js.map +0 -1
  135. package/dist/chunk-L642L24T.js.map +0 -1
  136. package/dist/chunk-MNO33ASC.cjs.map +0 -1
  137. package/dist/chunk-N4AOJ3VF.cjs.map +0 -1
  138. package/dist/chunk-QB3WBMDT.js +0 -646
  139. package/dist/chunk-QB3WBMDT.js.map +0 -1
  140. package/dist/chunk-SV5H3XM5.cjs.map +0 -1
  141. package/dist/chunk-UJAGXJDG.cjs.map +0 -1
  142. package/dist/chunk-X4EVMBON.js +0 -312
  143. package/dist/chunk-X4EVMBON.js.map +0 -1
  144. package/dist/chunk-XZL4NLV6.js +0 -348
  145. package/dist/chunk-XZL4NLV6.js.map +0 -1
  146. package/dist/chunk-YM5AL65Y.cjs.map +0 -1
@@ -0,0 +1,1469 @@
1
+ 'use strict';
2
+
3
+ var chunkOYL2SGBD_cjs = require('./chunk-OYL2SGBD.cjs');
4
+ var drizzleOrm = require('drizzle-orm');
5
+
6
+ // src/backend/types.ts
7
+ var SQLITE_CAPABILITIES = {
8
+ jsonb: false,
9
+ // SQLite uses TEXT with json functions
10
+ partialIndexes: true,
11
+ // SQLite supports WHERE in CREATE INDEX
12
+ ginIndexes: false,
13
+ // SQLite doesn't have GIN
14
+ cte: true,
15
+ // SQLite supports WITH
16
+ returning: true,
17
+ // SQLite 3.35+ supports RETURNING
18
+ transactions: true
19
+ // SQLite supports transactions
20
+ };
21
+ var POSTGRES_CAPABILITIES = {
22
+ jsonb: true,
23
+ // PostgreSQL has native JSONB
24
+ partialIndexes: true,
25
+ ginIndexes: true,
26
+ cte: true,
27
+ returning: true,
28
+ transactions: true
29
+ // PostgreSQL supports transactions
30
+ };
31
+ var D1_CAPABILITIES = {
32
+ jsonb: false,
33
+ // D1 uses TEXT with json functions
34
+ partialIndexes: true,
35
+ ginIndexes: false,
36
+ cte: true,
37
+ returning: true,
38
+ transactions: false
39
+ // D1 does NOT support atomic transactions
40
+ };
41
+
42
+ // src/backend/drizzle/row-mappers.ts
43
+ function requireTimestamp(value, field) {
44
+ if (value === void 0) {
45
+ throw new chunkOYL2SGBD_cjs.DatabaseOperationError(
46
+ `Expected non-null ${field} timestamp`,
47
+ { operation: "select", entity: "row" }
48
+ );
49
+ }
50
+ return value;
51
+ }
52
+ function nowIso() {
53
+ return (/* @__PURE__ */ new Date()).toISOString();
54
+ }
55
+ function nullToUndefined(value) {
56
+ return value ?? void 0;
57
+ }
58
+ function formatPostgresTimestamp(value) {
59
+ if (value === null || value === void 0) return void 0;
60
+ if (value instanceof Date) return value.toISOString();
61
+ if (typeof value === "string") {
62
+ if (value.includes("T")) return value;
63
+ const date = new Date(value);
64
+ if (!Number.isNaN(date.getTime())) return date.toISOString();
65
+ return value;
66
+ }
67
+ return void 0;
68
+ }
69
+ function normalizeJsonColumn(value) {
70
+ return typeof value === "string" ? value : JSON.stringify(value ?? {});
71
+ }
72
+ var SQLITE_ROW_MAPPER_CONFIG = {
73
+ formatTimestamp: (value) => nullToUndefined(value),
74
+ normalizeJson: (value) => value
75
+ };
76
+ var POSTGRES_ROW_MAPPER_CONFIG = {
77
+ formatTimestamp: formatPostgresTimestamp,
78
+ normalizeJson: normalizeJsonColumn
79
+ };
80
+ function createNodeRowMapper(config) {
81
+ return (row) => ({
82
+ graph_id: row.graph_id,
83
+ kind: row.kind,
84
+ id: row.id,
85
+ props: config.normalizeJson(row.props),
86
+ version: row.version,
87
+ valid_from: nullToUndefined(config.formatTimestamp(row.valid_from)),
88
+ valid_to: nullToUndefined(config.formatTimestamp(row.valid_to)),
89
+ created_at: requireTimestamp(config.formatTimestamp(row.created_at), "created_at"),
90
+ updated_at: requireTimestamp(config.formatTimestamp(row.updated_at), "updated_at"),
91
+ deleted_at: nullToUndefined(config.formatTimestamp(row.deleted_at))
92
+ });
93
+ }
94
+ function createEdgeRowMapper(config) {
95
+ return (row) => ({
96
+ graph_id: row.graph_id,
97
+ id: row.id,
98
+ kind: row.kind,
99
+ from_kind: row.from_kind,
100
+ from_id: row.from_id,
101
+ to_kind: row.to_kind,
102
+ to_id: row.to_id,
103
+ props: config.normalizeJson(row.props),
104
+ valid_from: nullToUndefined(config.formatTimestamp(row.valid_from)),
105
+ valid_to: nullToUndefined(config.formatTimestamp(row.valid_to)),
106
+ created_at: requireTimestamp(config.formatTimestamp(row.created_at), "created_at"),
107
+ updated_at: requireTimestamp(config.formatTimestamp(row.updated_at), "updated_at"),
108
+ deleted_at: nullToUndefined(config.formatTimestamp(row.deleted_at))
109
+ });
110
+ }
111
+ function createUniqueRowMapper(config) {
112
+ return (row) => ({
113
+ graph_id: row.graph_id,
114
+ node_kind: row.node_kind,
115
+ constraint_name: row.constraint_name,
116
+ key: row.key,
117
+ node_id: row.node_id,
118
+ concrete_kind: row.concrete_kind,
119
+ deleted_at: nullToUndefined(config.formatTimestamp(row.deleted_at))
120
+ });
121
+ }
122
+ function createSchemaVersionRowMapper(config) {
123
+ return (row) => {
124
+ const isActiveValue = row.is_active;
125
+ const isActive = isActiveValue === true || isActiveValue === 1 || isActiveValue === "1";
126
+ return {
127
+ graph_id: row.graph_id,
128
+ version: row.version,
129
+ schema_hash: row.schema_hash,
130
+ schema_doc: config.normalizeJson(row.schema_doc),
131
+ created_at: requireTimestamp(config.formatTimestamp(row.created_at), "created_at"),
132
+ is_active: isActive
133
+ };
134
+ };
135
+ }
136
+
137
+ // src/backend/drizzle/operation-backend-core.ts
138
+ function chunkArray(values, size) {
139
+ if (values.length <= size) {
140
+ return [values];
141
+ }
142
+ const chunks = [];
143
+ for (let index = 0; index < values.length; index += size) {
144
+ chunks.push(values.slice(index, index + size));
145
+ }
146
+ return chunks;
147
+ }
148
+ function createCommonOperationBackend(options) {
149
+ const { batchConfig, execution, operationStrategy, rowMappers } = options;
150
+ const nowIso2 = options.nowIso ?? nowIso;
151
+ return {
152
+ async insertNode(params) {
153
+ const timestamp = nowIso2();
154
+ const query = operationStrategy.buildInsertNode(params, timestamp);
155
+ const row = await execution.execGet(query);
156
+ if (!row) throw new chunkOYL2SGBD_cjs.DatabaseOperationError("Insert node failed: no row returned", { operation: "insert", entity: "node" });
157
+ return rowMappers.toNodeRow(row);
158
+ },
159
+ async insertNodeNoReturn(params) {
160
+ const timestamp = nowIso2();
161
+ const query = operationStrategy.buildInsertNodeNoReturn(params, timestamp);
162
+ await execution.execRun(query);
163
+ },
164
+ async insertNodesBatch(params) {
165
+ if (params.length === 0) {
166
+ return;
167
+ }
168
+ const timestamp = nowIso2();
169
+ for (const chunk of chunkArray(params, batchConfig.nodeInsertBatchSize)) {
170
+ const query = operationStrategy.buildInsertNodesBatch(chunk, timestamp);
171
+ await execution.execRun(query);
172
+ }
173
+ },
174
+ async insertNodesBatchReturning(params) {
175
+ if (params.length === 0) {
176
+ return [];
177
+ }
178
+ const timestamp = nowIso2();
179
+ const allRows = [];
180
+ for (const chunk of chunkArray(params, batchConfig.nodeInsertBatchSize)) {
181
+ const query = operationStrategy.buildInsertNodesBatchReturning(chunk, timestamp);
182
+ const rows = await execution.execAll(query);
183
+ allRows.push(...rows.map((row) => rowMappers.toNodeRow(row)));
184
+ }
185
+ return allRows;
186
+ },
187
+ async getNode(graphId, kind, id) {
188
+ const query = operationStrategy.buildGetNode(graphId, kind, id);
189
+ const row = await execution.execGet(query);
190
+ return row ? rowMappers.toNodeRow(row) : void 0;
191
+ },
192
+ async getNodes(graphId, kind, ids) {
193
+ if (ids.length === 0) return [];
194
+ const allRows = [];
195
+ for (const chunk of chunkArray(ids, batchConfig.getNodesChunkSize)) {
196
+ const query = operationStrategy.buildGetNodes(graphId, kind, chunk);
197
+ const rows = await execution.execAll(query);
198
+ allRows.push(...rows.map((row) => rowMappers.toNodeRow(row)));
199
+ }
200
+ return allRows;
201
+ },
202
+ async updateNode(params) {
203
+ const timestamp = nowIso2();
204
+ const query = operationStrategy.buildUpdateNode(params, timestamp);
205
+ const row = await execution.execGet(query);
206
+ if (!row) throw new chunkOYL2SGBD_cjs.DatabaseOperationError("Update node failed: no row returned", { operation: "update", entity: "node" });
207
+ return rowMappers.toNodeRow(row);
208
+ },
209
+ async deleteNode(params) {
210
+ const timestamp = nowIso2();
211
+ const query = operationStrategy.buildDeleteNode(params, timestamp);
212
+ await execution.execRun(query);
213
+ },
214
+ // IMPORTANT: This cascade is not atomic. Callers must ensure this runs
215
+ // within a transaction to prevent partial deletion on intermediate failure.
216
+ async hardDeleteNode(params) {
217
+ const deleteUniquesQuery = operationStrategy.buildHardDeleteUniquesByNode(
218
+ params.graphId,
219
+ params.id
220
+ );
221
+ await execution.execRun(deleteUniquesQuery);
222
+ const deleteEmbeddingsQuery = operationStrategy.buildHardDeleteEmbeddingsByNode(
223
+ params.graphId,
224
+ params.kind,
225
+ params.id
226
+ );
227
+ await execution.execRun(deleteEmbeddingsQuery);
228
+ const deleteEdgesQuery = operationStrategy.buildHardDeleteEdgesByNode(
229
+ params.graphId,
230
+ params.kind,
231
+ params.id
232
+ );
233
+ await execution.execRun(deleteEdgesQuery);
234
+ const query = operationStrategy.buildHardDeleteNode(params);
235
+ await execution.execRun(query);
236
+ },
237
+ async insertEdge(params) {
238
+ const timestamp = nowIso2();
239
+ const query = operationStrategy.buildInsertEdge(params, timestamp);
240
+ const row = await execution.execGet(query);
241
+ if (!row) throw new chunkOYL2SGBD_cjs.DatabaseOperationError("Insert edge failed: no row returned", { operation: "insert", entity: "edge" });
242
+ return rowMappers.toEdgeRow(row);
243
+ },
244
+ async insertEdgeNoReturn(params) {
245
+ const timestamp = nowIso2();
246
+ const query = operationStrategy.buildInsertEdgeNoReturn(params, timestamp);
247
+ await execution.execRun(query);
248
+ },
249
+ async insertEdgesBatch(params) {
250
+ if (params.length === 0) {
251
+ return;
252
+ }
253
+ const timestamp = nowIso2();
254
+ for (const chunk of chunkArray(params, batchConfig.edgeInsertBatchSize)) {
255
+ const query = operationStrategy.buildInsertEdgesBatch(chunk, timestamp);
256
+ await execution.execRun(query);
257
+ }
258
+ },
259
+ async insertEdgesBatchReturning(params) {
260
+ if (params.length === 0) {
261
+ return [];
262
+ }
263
+ const timestamp = nowIso2();
264
+ const allRows = [];
265
+ for (const chunk of chunkArray(params, batchConfig.edgeInsertBatchSize)) {
266
+ const query = operationStrategy.buildInsertEdgesBatchReturning(chunk, timestamp);
267
+ const rows = await execution.execAll(query);
268
+ allRows.push(...rows.map((row) => rowMappers.toEdgeRow(row)));
269
+ }
270
+ return allRows;
271
+ },
272
+ async getEdge(graphId, id) {
273
+ const query = operationStrategy.buildGetEdge(graphId, id);
274
+ const row = await execution.execGet(query);
275
+ return row ? rowMappers.toEdgeRow(row) : void 0;
276
+ },
277
+ async getEdges(graphId, ids) {
278
+ if (ids.length === 0) return [];
279
+ const allRows = [];
280
+ for (const chunk of chunkArray(ids, batchConfig.getEdgesChunkSize)) {
281
+ const query = operationStrategy.buildGetEdges(graphId, chunk);
282
+ const rows = await execution.execAll(query);
283
+ allRows.push(...rows.map((row) => rowMappers.toEdgeRow(row)));
284
+ }
285
+ return allRows;
286
+ },
287
+ async updateEdge(params) {
288
+ const timestamp = nowIso2();
289
+ const query = operationStrategy.buildUpdateEdge(params, timestamp);
290
+ const row = await execution.execGet(query);
291
+ if (!row) throw new chunkOYL2SGBD_cjs.DatabaseOperationError("Update edge failed: no row returned", { operation: "update", entity: "edge" });
292
+ return rowMappers.toEdgeRow(row);
293
+ },
294
+ async deleteEdge(params) {
295
+ const timestamp = nowIso2();
296
+ const query = operationStrategy.buildDeleteEdge(params, timestamp);
297
+ await execution.execRun(query);
298
+ },
299
+ async hardDeleteEdge(params) {
300
+ const query = operationStrategy.buildHardDeleteEdge(params);
301
+ await execution.execRun(query);
302
+ },
303
+ async countEdgesFrom(params) {
304
+ const query = operationStrategy.buildCountEdgesFrom(params);
305
+ const row = await execution.execGet(query);
306
+ return Number(row?.count ?? 0);
307
+ },
308
+ async edgeExistsBetween(params) {
309
+ const query = operationStrategy.buildEdgeExistsBetween(params);
310
+ const row = await execution.execGet(query);
311
+ return row !== void 0;
312
+ },
313
+ async findEdgesConnectedTo(params) {
314
+ const query = operationStrategy.buildFindEdgesConnectedTo(params);
315
+ const rows = await execution.execAll(query);
316
+ return rows.map((row) => rowMappers.toEdgeRow(row));
317
+ },
318
+ async findNodesByKind(params) {
319
+ const query = operationStrategy.buildFindNodesByKind(params);
320
+ const rows = await execution.execAll(query);
321
+ return rows.map((row) => rowMappers.toNodeRow(row));
322
+ },
323
+ async countNodesByKind(params) {
324
+ const query = operationStrategy.buildCountNodesByKind(params);
325
+ const row = await execution.execGet(query);
326
+ return Number(row?.count ?? 0);
327
+ },
328
+ async findEdgesByKind(params) {
329
+ const query = operationStrategy.buildFindEdgesByKind(params);
330
+ const rows = await execution.execAll(query);
331
+ return rows.map((row) => rowMappers.toEdgeRow(row));
332
+ },
333
+ async countEdgesByKind(params) {
334
+ const query = operationStrategy.buildCountEdgesByKind(params);
335
+ const row = await execution.execGet(query);
336
+ return Number(row?.count ?? 0);
337
+ },
338
+ async insertUnique(params) {
339
+ const query = operationStrategy.buildInsertUnique(params);
340
+ const result = await execution.execGet(query);
341
+ if (result && result.node_id !== params.nodeId) {
342
+ throw new chunkOYL2SGBD_cjs.UniquenessError({
343
+ constraintName: params.constraintName,
344
+ kind: params.nodeKind,
345
+ existingId: result.node_id,
346
+ newId: params.nodeId,
347
+ fields: []
348
+ });
349
+ }
350
+ },
351
+ async deleteUnique(params) {
352
+ const timestamp = nowIso2();
353
+ const query = operationStrategy.buildDeleteUnique(params, timestamp);
354
+ await execution.execRun(query);
355
+ },
356
+ async checkUnique(params) {
357
+ const query = operationStrategy.buildCheckUnique(params);
358
+ const row = await execution.execGet(query);
359
+ return row ? rowMappers.toUniqueRow(row) : void 0;
360
+ },
361
+ async getActiveSchema(graphId) {
362
+ const query = operationStrategy.buildGetActiveSchema(graphId);
363
+ const row = await execution.execGet(query);
364
+ return row ? rowMappers.toSchemaVersionRow(row) : void 0;
365
+ },
366
+ async insertSchema(params) {
367
+ const timestamp = nowIso2();
368
+ const query = operationStrategy.buildInsertSchema(params, timestamp);
369
+ const row = await execution.execGet(query);
370
+ if (!row) throw new chunkOYL2SGBD_cjs.DatabaseOperationError("Insert schema failed: no row returned", { operation: "insert", entity: "schema" });
371
+ return rowMappers.toSchemaVersionRow(row);
372
+ },
373
+ async getSchemaVersion(graphId, version) {
374
+ const query = operationStrategy.buildGetSchemaVersion(graphId, version);
375
+ const row = await execution.execGet(query);
376
+ return row ? rowMappers.toSchemaVersionRow(row) : void 0;
377
+ },
378
+ async setActiveSchema(graphId, version) {
379
+ const queries = operationStrategy.buildSetActiveSchema(graphId, version);
380
+ await execution.execRun(queries.deactivateAll);
381
+ await execution.execRun(queries.activateVersion);
382
+ }
383
+ };
384
+ }
385
+ function buildTemporalConditions(table, params) {
386
+ const conditions = [];
387
+ const mode = params.temporalMode;
388
+ if (mode === "includeTombstones") return conditions;
389
+ if (params.excludeDeleted !== false) {
390
+ conditions.push(drizzleOrm.sql`${table.deletedAt} IS NULL`);
391
+ }
392
+ if (mode === "current" || mode === "asOf") {
393
+ const asOf = params.asOf;
394
+ conditions.push(
395
+ drizzleOrm.sql`(${table.validFrom} IS NULL OR ${table.validFrom} <= ${asOf})`,
396
+ drizzleOrm.sql`(${table.validTo} IS NULL OR ${table.validTo} > ${asOf})`
397
+ );
398
+ }
399
+ return conditions;
400
+ }
401
+ function buildFindNodesByKind(tables, params) {
402
+ const { nodes } = tables;
403
+ const conditions = [
404
+ drizzleOrm.sql`${nodes.graphId} = ${params.graphId}`,
405
+ drizzleOrm.sql`${nodes.kind} = ${params.kind}`,
406
+ ...buildTemporalConditions(nodes, params)
407
+ ];
408
+ const whereClause = drizzleOrm.sql.join(conditions, drizzleOrm.sql` AND `);
409
+ if (params.limit !== void 0 && params.offset !== void 0) {
410
+ return drizzleOrm.sql`
411
+ SELECT * FROM ${nodes}
412
+ WHERE ${whereClause}
413
+ ORDER BY ${nodes.createdAt} DESC
414
+ LIMIT ${params.limit} OFFSET ${params.offset}
415
+ `;
416
+ }
417
+ if (params.limit !== void 0) {
418
+ return drizzleOrm.sql`
419
+ SELECT * FROM ${nodes}
420
+ WHERE ${whereClause}
421
+ ORDER BY ${nodes.createdAt} DESC
422
+ LIMIT ${params.limit}
423
+ `;
424
+ }
425
+ return drizzleOrm.sql`
426
+ SELECT * FROM ${nodes}
427
+ WHERE ${whereClause}
428
+ ORDER BY ${nodes.createdAt} DESC
429
+ `;
430
+ }
431
+ function buildCountNodesByKind(tables, params) {
432
+ const { nodes } = tables;
433
+ const conditions = [
434
+ drizzleOrm.sql`${nodes.graphId} = ${params.graphId}`,
435
+ drizzleOrm.sql`${nodes.kind} = ${params.kind}`,
436
+ ...buildTemporalConditions(nodes, params)
437
+ ];
438
+ const whereClause = drizzleOrm.sql.join(conditions, drizzleOrm.sql` AND `);
439
+ return drizzleOrm.sql`
440
+ SELECT COUNT(*) as count FROM ${nodes}
441
+ WHERE ${whereClause}
442
+ `;
443
+ }
444
+ function buildFindEdgesByKind(tables, params) {
445
+ const { edges } = tables;
446
+ const conditions = [
447
+ drizzleOrm.sql`${edges.graphId} = ${params.graphId}`,
448
+ drizzleOrm.sql`${edges.kind} = ${params.kind}`,
449
+ ...buildTemporalConditions(edges, params)
450
+ ];
451
+ if (params.fromKind !== void 0) {
452
+ conditions.push(drizzleOrm.sql`${edges.fromKind} = ${params.fromKind}`);
453
+ }
454
+ if (params.fromId !== void 0) {
455
+ conditions.push(drizzleOrm.sql`${edges.fromId} = ${params.fromId}`);
456
+ }
457
+ if (params.toKind !== void 0) {
458
+ conditions.push(drizzleOrm.sql`${edges.toKind} = ${params.toKind}`);
459
+ }
460
+ if (params.toId !== void 0) {
461
+ conditions.push(drizzleOrm.sql`${edges.toId} = ${params.toId}`);
462
+ }
463
+ const whereClause = drizzleOrm.sql.join(conditions, drizzleOrm.sql` AND `);
464
+ if (params.limit !== void 0 && params.offset !== void 0) {
465
+ return drizzleOrm.sql`
466
+ SELECT * FROM ${edges}
467
+ WHERE ${whereClause}
468
+ ORDER BY ${edges.createdAt} DESC
469
+ LIMIT ${params.limit} OFFSET ${params.offset}
470
+ `;
471
+ }
472
+ if (params.limit !== void 0) {
473
+ return drizzleOrm.sql`
474
+ SELECT * FROM ${edges}
475
+ WHERE ${whereClause}
476
+ ORDER BY ${edges.createdAt} DESC
477
+ LIMIT ${params.limit}
478
+ `;
479
+ }
480
+ return drizzleOrm.sql`
481
+ SELECT * FROM ${edges}
482
+ WHERE ${whereClause}
483
+ ORDER BY ${edges.createdAt} DESC
484
+ `;
485
+ }
486
+ function buildCountEdgesByKind(tables, params) {
487
+ const { edges } = tables;
488
+ const conditions = [
489
+ drizzleOrm.sql`${edges.graphId} = ${params.graphId}`,
490
+ drizzleOrm.sql`${edges.kind} = ${params.kind}`,
491
+ ...buildTemporalConditions(edges, params)
492
+ ];
493
+ if (params.fromKind !== void 0) {
494
+ conditions.push(drizzleOrm.sql`${edges.fromKind} = ${params.fromKind}`);
495
+ }
496
+ if (params.fromId !== void 0) {
497
+ conditions.push(drizzleOrm.sql`${edges.fromId} = ${params.fromId}`);
498
+ }
499
+ if (params.toKind !== void 0) {
500
+ conditions.push(drizzleOrm.sql`${edges.toKind} = ${params.toKind}`);
501
+ }
502
+ if (params.toId !== void 0) {
503
+ conditions.push(drizzleOrm.sql`${edges.toId} = ${params.toId}`);
504
+ }
505
+ const whereClause = drizzleOrm.sql.join(conditions, drizzleOrm.sql` AND `);
506
+ return drizzleOrm.sql`
507
+ SELECT COUNT(*) as count FROM ${edges}
508
+ WHERE ${whereClause}
509
+ `;
510
+ }
511
+ function sqlNull(value) {
512
+ return value ?? drizzleOrm.sql.raw("NULL");
513
+ }
514
+ function quotedColumn(column) {
515
+ return drizzleOrm.sql.raw(`"${column.name.replaceAll('"', '""')}"`);
516
+ }
517
+ function nodeColumnList(nodes) {
518
+ return drizzleOrm.sql.raw(`"${nodes.graphId.name}", "${nodes.kind.name}", "${nodes.id.name}", "${nodes.props.name}", "${nodes.version.name}", "${nodes.validFrom.name}", "${nodes.validTo.name}", "${nodes.createdAt.name}", "${nodes.updatedAt.name}"`);
519
+ }
520
+ function edgeColumnList(edges) {
521
+ return drizzleOrm.sql.raw(`"${edges.graphId.name}", "${edges.id.name}", "${edges.kind.name}", "${edges.fromKind.name}", "${edges.fromId.name}", "${edges.toKind.name}", "${edges.toId.name}", "${edges.props.name}", "${edges.validFrom.name}", "${edges.validTo.name}", "${edges.createdAt.name}", "${edges.updatedAt.name}"`);
522
+ }
523
+
524
+ // src/backend/drizzle/operations/edges.ts
525
+ function buildInsertEdge(tables, params, timestamp) {
526
+ const { edges } = tables;
527
+ const propsJson = JSON.stringify(params.props);
528
+ const columns = edgeColumnList(edges);
529
+ return drizzleOrm.sql`
530
+ INSERT INTO ${edges} (${columns})
531
+ VALUES (
532
+ ${params.graphId}, ${params.id}, ${params.kind},
533
+ ${params.fromKind}, ${params.fromId}, ${params.toKind}, ${params.toId},
534
+ ${propsJson}, ${sqlNull(params.validFrom)}, ${sqlNull(params.validTo)},
535
+ ${timestamp}, ${timestamp}
536
+ )
537
+ RETURNING *
538
+ `;
539
+ }
540
+ function buildInsertEdgeNoReturn(tables, params, timestamp) {
541
+ const { edges } = tables;
542
+ const propsJson = JSON.stringify(params.props);
543
+ const columns = edgeColumnList(edges);
544
+ return drizzleOrm.sql`
545
+ INSERT INTO ${edges} (${columns})
546
+ VALUES (
547
+ ${params.graphId}, ${params.id}, ${params.kind},
548
+ ${params.fromKind}, ${params.fromId}, ${params.toKind}, ${params.toId},
549
+ ${propsJson}, ${sqlNull(params.validFrom)}, ${sqlNull(params.validTo)},
550
+ ${timestamp}, ${timestamp}
551
+ )
552
+ `;
553
+ }
554
+ function buildInsertEdgesBatch(tables, params, timestamp) {
555
+ const { edges } = tables;
556
+ const columns = edgeColumnList(edges);
557
+ const values = params.map((edgeParams) => {
558
+ const propsJson = JSON.stringify(edgeParams.props);
559
+ return drizzleOrm.sql`(${edgeParams.graphId}, ${edgeParams.id}, ${edgeParams.kind}, ${edgeParams.fromKind}, ${edgeParams.fromId}, ${edgeParams.toKind}, ${edgeParams.toId}, ${propsJson}, ${sqlNull(edgeParams.validFrom)}, ${sqlNull(edgeParams.validTo)}, ${timestamp}, ${timestamp})`;
560
+ });
561
+ return drizzleOrm.sql`
562
+ INSERT INTO ${edges} (${columns})
563
+ VALUES ${drizzleOrm.sql.join(values, drizzleOrm.sql`, `)}
564
+ `;
565
+ }
566
+ function buildInsertEdgesBatchReturning(tables, params, timestamp) {
567
+ const { edges } = tables;
568
+ const columns = edgeColumnList(edges);
569
+ const values = params.map((edgeParams) => {
570
+ const propsJson = JSON.stringify(edgeParams.props);
571
+ return drizzleOrm.sql`(${edgeParams.graphId}, ${edgeParams.id}, ${edgeParams.kind}, ${edgeParams.fromKind}, ${edgeParams.fromId}, ${edgeParams.toKind}, ${edgeParams.toId}, ${propsJson}, ${sqlNull(edgeParams.validFrom)}, ${sqlNull(edgeParams.validTo)}, ${timestamp}, ${timestamp})`;
572
+ });
573
+ return drizzleOrm.sql`
574
+ INSERT INTO ${edges} (${columns})
575
+ VALUES ${drizzleOrm.sql.join(values, drizzleOrm.sql`, `)}
576
+ RETURNING *
577
+ `;
578
+ }
579
+ function buildGetEdge(tables, graphId, id) {
580
+ const { edges } = tables;
581
+ return drizzleOrm.sql`
582
+ SELECT * FROM ${edges}
583
+ WHERE ${edges.graphId} = ${graphId}
584
+ AND ${edges.id} = ${id}
585
+ `;
586
+ }
587
+ function buildGetEdges(tables, graphId, ids) {
588
+ const { edges } = tables;
589
+ const idPlaceholders = drizzleOrm.sql.join(
590
+ ids.map((edgeId) => drizzleOrm.sql`${edgeId}`),
591
+ drizzleOrm.sql`, `
592
+ );
593
+ return drizzleOrm.sql`
594
+ SELECT * FROM ${edges}
595
+ WHERE ${edges.graphId} = ${graphId}
596
+ AND ${edges.id} IN (${idPlaceholders})
597
+ `;
598
+ }
599
+ function buildUpdateEdge(tables, params, timestamp) {
600
+ const { edges } = tables;
601
+ const propsJson = JSON.stringify(params.props);
602
+ const setParts = [
603
+ drizzleOrm.sql`${quotedColumn(edges.props)} = ${propsJson}`,
604
+ drizzleOrm.sql`${quotedColumn(edges.updatedAt)} = ${timestamp}`
605
+ ];
606
+ if (params.validTo !== void 0) {
607
+ setParts.push(drizzleOrm.sql`${quotedColumn(edges.validTo)} = ${params.validTo}`);
608
+ }
609
+ if (params.clearDeleted) {
610
+ setParts.push(drizzleOrm.sql`${quotedColumn(edges.deletedAt)} = NULL`);
611
+ }
612
+ const setClause = drizzleOrm.sql.join(setParts, drizzleOrm.sql`, `);
613
+ if (params.clearDeleted) {
614
+ return drizzleOrm.sql`
615
+ UPDATE ${edges}
616
+ SET ${setClause}
617
+ WHERE ${edges.graphId} = ${params.graphId}
618
+ AND ${edges.id} = ${params.id}
619
+ RETURNING *
620
+ `;
621
+ }
622
+ return drizzleOrm.sql`
623
+ UPDATE ${edges}
624
+ SET ${setClause}
625
+ WHERE ${edges.graphId} = ${params.graphId}
626
+ AND ${edges.id} = ${params.id}
627
+ AND ${edges.deletedAt} IS NULL
628
+ RETURNING *
629
+ `;
630
+ }
631
+ function buildDeleteEdge(tables, params, timestamp) {
632
+ const { edges } = tables;
633
+ return drizzleOrm.sql`
634
+ UPDATE ${edges}
635
+ SET ${quotedColumn(edges.deletedAt)} = ${timestamp}
636
+ WHERE ${edges.graphId} = ${params.graphId}
637
+ AND ${edges.id} = ${params.id}
638
+ AND ${edges.deletedAt} IS NULL
639
+ `;
640
+ }
641
+ function buildHardDeleteEdge(tables, params) {
642
+ const { edges } = tables;
643
+ return drizzleOrm.sql`
644
+ DELETE FROM ${edges}
645
+ WHERE ${edges.graphId} = ${params.graphId}
646
+ AND ${edges.id} = ${params.id}
647
+ `;
648
+ }
649
+ function buildHardDeleteEdgesByNode(tables, graphId, nodeKind, nodeId) {
650
+ const { edges } = tables;
651
+ return drizzleOrm.sql`
652
+ DELETE FROM ${edges}
653
+ WHERE ${edges.graphId} = ${graphId}
654
+ AND (
655
+ (${edges.fromKind} = ${nodeKind} AND ${edges.fromId} = ${nodeId})
656
+ OR (${edges.toKind} = ${nodeKind} AND ${edges.toId} = ${nodeId})
657
+ )
658
+ `;
659
+ }
660
+ function buildCountEdgesFrom(tables, params) {
661
+ const { edges } = tables;
662
+ if (params.activeOnly) {
663
+ return drizzleOrm.sql`
664
+ SELECT COUNT(*) as count FROM ${edges}
665
+ WHERE ${edges.graphId} = ${params.graphId}
666
+ AND ${edges.kind} = ${params.edgeKind}
667
+ AND ${edges.fromKind} = ${params.fromKind}
668
+ AND ${edges.fromId} = ${params.fromId}
669
+ AND ${edges.deletedAt} IS NULL
670
+ AND ${edges.validTo} IS NULL
671
+ `;
672
+ }
673
+ return drizzleOrm.sql`
674
+ SELECT COUNT(*) as count FROM ${edges}
675
+ WHERE ${edges.graphId} = ${params.graphId}
676
+ AND ${edges.kind} = ${params.edgeKind}
677
+ AND ${edges.fromKind} = ${params.fromKind}
678
+ AND ${edges.fromId} = ${params.fromId}
679
+ AND ${edges.deletedAt} IS NULL
680
+ `;
681
+ }
682
+ function buildEdgeExistsBetween(tables, params) {
683
+ const { edges } = tables;
684
+ return drizzleOrm.sql`
685
+ SELECT 1 FROM ${edges}
686
+ WHERE ${edges.graphId} = ${params.graphId}
687
+ AND ${edges.kind} = ${params.edgeKind}
688
+ AND ${edges.fromKind} = ${params.fromKind}
689
+ AND ${edges.fromId} = ${params.fromId}
690
+ AND ${edges.toKind} = ${params.toKind}
691
+ AND ${edges.toId} = ${params.toId}
692
+ AND ${edges.deletedAt} IS NULL
693
+ LIMIT 1
694
+ `;
695
+ }
696
+ function buildFindEdgesConnectedTo(tables, params) {
697
+ const { edges } = tables;
698
+ return drizzleOrm.sql`
699
+ SELECT * FROM ${edges}
700
+ WHERE ${edges.graphId} = ${params.graphId}
701
+ AND ${edges.deletedAt} IS NULL
702
+ AND ${edges.fromKind} = ${params.nodeKind}
703
+ AND ${edges.fromId} = ${params.nodeId}
704
+ UNION ALL
705
+ SELECT * FROM ${edges}
706
+ WHERE ${edges.graphId} = ${params.graphId}
707
+ AND ${edges.deletedAt} IS NULL
708
+ AND ${edges.toKind} = ${params.nodeKind}
709
+ AND ${edges.toId} = ${params.nodeId}
710
+ AND NOT (
711
+ ${edges.fromKind} = ${params.nodeKind}
712
+ AND ${edges.fromId} = ${params.nodeId}
713
+ )
714
+ `;
715
+ }
716
+ function buildInsertNode(tables, params, timestamp) {
717
+ const { nodes } = tables;
718
+ const propsJson = JSON.stringify(params.props);
719
+ const columns = nodeColumnList(nodes);
720
+ return drizzleOrm.sql`
721
+ INSERT INTO ${nodes} (${columns})
722
+ VALUES (
723
+ ${params.graphId}, ${params.kind}, ${params.id}, ${propsJson},
724
+ 1, ${sqlNull(params.validFrom)}, ${sqlNull(params.validTo)},
725
+ ${timestamp}, ${timestamp}
726
+ )
727
+ RETURNING *
728
+ `;
729
+ }
730
+ function buildInsertNodeNoReturn(tables, params, timestamp) {
731
+ const { nodes } = tables;
732
+ const propsJson = JSON.stringify(params.props);
733
+ const columns = nodeColumnList(nodes);
734
+ return drizzleOrm.sql`
735
+ INSERT INTO ${nodes} (${columns})
736
+ VALUES (
737
+ ${params.graphId}, ${params.kind}, ${params.id}, ${propsJson},
738
+ 1, ${sqlNull(params.validFrom)}, ${sqlNull(params.validTo)},
739
+ ${timestamp}, ${timestamp}
740
+ )
741
+ `;
742
+ }
743
+ function buildInsertNodesBatch(tables, params, timestamp) {
744
+ const { nodes } = tables;
745
+ const columns = nodeColumnList(nodes);
746
+ const values = params.map((nodeParams) => {
747
+ const propsJson = JSON.stringify(nodeParams.props);
748
+ return drizzleOrm.sql`(${nodeParams.graphId}, ${nodeParams.kind}, ${nodeParams.id}, ${propsJson}, 1, ${sqlNull(nodeParams.validFrom)}, ${sqlNull(nodeParams.validTo)}, ${timestamp}, ${timestamp})`;
749
+ });
750
+ return drizzleOrm.sql`
751
+ INSERT INTO ${nodes} (${columns})
752
+ VALUES ${drizzleOrm.sql.join(values, drizzleOrm.sql`, `)}
753
+ `;
754
+ }
755
+ function buildInsertNodesBatchReturning(tables, params, timestamp) {
756
+ const { nodes } = tables;
757
+ const columns = nodeColumnList(nodes);
758
+ const values = params.map((nodeParams) => {
759
+ const propsJson = JSON.stringify(nodeParams.props);
760
+ return drizzleOrm.sql`(${nodeParams.graphId}, ${nodeParams.kind}, ${nodeParams.id}, ${propsJson}, 1, ${sqlNull(nodeParams.validFrom)}, ${sqlNull(nodeParams.validTo)}, ${timestamp}, ${timestamp})`;
761
+ });
762
+ return drizzleOrm.sql`
763
+ INSERT INTO ${nodes} (${columns})
764
+ VALUES ${drizzleOrm.sql.join(values, drizzleOrm.sql`, `)}
765
+ RETURNING *
766
+ `;
767
+ }
768
+ function buildGetNode(tables, graphId, kind, id) {
769
+ const { nodes } = tables;
770
+ return drizzleOrm.sql`
771
+ SELECT * FROM ${nodes}
772
+ WHERE ${nodes.graphId} = ${graphId}
773
+ AND ${nodes.kind} = ${kind}
774
+ AND ${nodes.id} = ${id}
775
+ `;
776
+ }
777
+ function buildGetNodes(tables, graphId, kind, ids) {
778
+ const { nodes } = tables;
779
+ const idPlaceholders = drizzleOrm.sql.join(
780
+ ids.map((nodeId) => drizzleOrm.sql`${nodeId}`),
781
+ drizzleOrm.sql`, `
782
+ );
783
+ return drizzleOrm.sql`
784
+ SELECT * FROM ${nodes}
785
+ WHERE ${nodes.graphId} = ${graphId}
786
+ AND ${nodes.kind} = ${kind}
787
+ AND ${nodes.id} IN (${idPlaceholders})
788
+ `;
789
+ }
790
+ function buildUpdateNode(tables, params, timestamp) {
791
+ const { nodes } = tables;
792
+ const propsJson = JSON.stringify(params.props);
793
+ const setParts = [
794
+ drizzleOrm.sql`${quotedColumn(nodes.props)} = ${propsJson}`,
795
+ drizzleOrm.sql`${quotedColumn(nodes.updatedAt)} = ${timestamp}`
796
+ ];
797
+ if (params.incrementVersion) {
798
+ setParts.push(
799
+ drizzleOrm.sql`${quotedColumn(nodes.version)} = ${quotedColumn(nodes.version)} + 1`
800
+ );
801
+ }
802
+ if (params.validTo !== void 0) {
803
+ setParts.push(drizzleOrm.sql`${quotedColumn(nodes.validTo)} = ${params.validTo}`);
804
+ }
805
+ if (params.clearDeleted) {
806
+ setParts.push(drizzleOrm.sql`${quotedColumn(nodes.deletedAt)} = NULL`);
807
+ }
808
+ const setClause = drizzleOrm.sql.join(setParts, drizzleOrm.sql`, `);
809
+ if (params.clearDeleted) {
810
+ return drizzleOrm.sql`
811
+ UPDATE ${nodes}
812
+ SET ${setClause}
813
+ WHERE ${nodes.graphId} = ${params.graphId}
814
+ AND ${nodes.kind} = ${params.kind}
815
+ AND ${nodes.id} = ${params.id}
816
+ RETURNING *
817
+ `;
818
+ }
819
+ return drizzleOrm.sql`
820
+ UPDATE ${nodes}
821
+ SET ${setClause}
822
+ WHERE ${nodes.graphId} = ${params.graphId}
823
+ AND ${nodes.kind} = ${params.kind}
824
+ AND ${nodes.id} = ${params.id}
825
+ AND ${nodes.deletedAt} IS NULL
826
+ RETURNING *
827
+ `;
828
+ }
829
+ function buildDeleteNode(tables, params, timestamp) {
830
+ const { nodes } = tables;
831
+ return drizzleOrm.sql`
832
+ UPDATE ${nodes}
833
+ SET ${quotedColumn(nodes.deletedAt)} = ${timestamp}
834
+ WHERE ${nodes.graphId} = ${params.graphId}
835
+ AND ${nodes.kind} = ${params.kind}
836
+ AND ${nodes.id} = ${params.id}
837
+ AND ${nodes.deletedAt} IS NULL
838
+ `;
839
+ }
840
+ function buildHardDeleteNode(tables, params) {
841
+ const { nodes } = tables;
842
+ return drizzleOrm.sql`
843
+ DELETE FROM ${nodes}
844
+ WHERE ${nodes.graphId} = ${params.graphId}
845
+ AND ${nodes.kind} = ${params.kind}
846
+ AND ${nodes.id} = ${params.id}
847
+ `;
848
+ }
849
+ function createSchemaDialectStrategy(dialect) {
850
+ const trueLiteral = dialect === "sqlite" ? drizzleOrm.sql.raw("1") : drizzleOrm.sql.raw("TRUE");
851
+ const falseLiteral = dialect === "sqlite" ? drizzleOrm.sql.raw("0") : drizzleOrm.sql.raw("FALSE");
852
+ return {
853
+ booleanLiteral(value) {
854
+ return value ? trueLiteral : falseLiteral;
855
+ }
856
+ };
857
+ }
858
+ var SCHEMA_DIALECT_STRATEGIES = {
859
+ postgres: createSchemaDialectStrategy("postgres"),
860
+ sqlite: createSchemaDialectStrategy("sqlite")
861
+ };
862
+ function buildInsertSchema(tables, params, timestamp, dialect = "sqlite") {
863
+ const { schemaVersions } = tables;
864
+ const strategy = SCHEMA_DIALECT_STRATEGIES[dialect];
865
+ const schemaDocumentJson = JSON.stringify(params.schemaDoc);
866
+ const isActiveValue = strategy.booleanLiteral(params.isActive);
867
+ const columns = drizzleOrm.sql.raw(`"${schemaVersions.graphId.name}", "${schemaVersions.version.name}", "${schemaVersions.schemaHash.name}", "${schemaVersions.schemaDoc.name}", "${schemaVersions.createdAt.name}", "${schemaVersions.isActive.name}"`);
868
+ return drizzleOrm.sql`
869
+ INSERT INTO ${schemaVersions} (${columns})
870
+ VALUES (
871
+ ${params.graphId}, ${params.version},
872
+ ${params.schemaHash}, ${schemaDocumentJson},
873
+ ${timestamp}, ${isActiveValue}
874
+ )
875
+ RETURNING *
876
+ `;
877
+ }
878
+ function buildGetActiveSchema(tables, graphId, dialect = "sqlite") {
879
+ const { schemaVersions } = tables;
880
+ const strategy = SCHEMA_DIALECT_STRATEGIES[dialect];
881
+ return drizzleOrm.sql`
882
+ SELECT * FROM ${schemaVersions}
883
+ WHERE ${schemaVersions.graphId} = ${graphId}
884
+ AND ${schemaVersions.isActive} = ${strategy.booleanLiteral(true)}
885
+ `;
886
+ }
887
+ function buildGetSchemaVersion(tables, graphId, version) {
888
+ const { schemaVersions } = tables;
889
+ return drizzleOrm.sql`
890
+ SELECT * FROM ${schemaVersions}
891
+ WHERE ${schemaVersions.graphId} = ${graphId}
892
+ AND ${schemaVersions.version} = ${version}
893
+ `;
894
+ }
895
+ function buildSetActiveSchema(tables, graphId, version, dialect = "sqlite") {
896
+ const { schemaVersions } = tables;
897
+ const strategy = SCHEMA_DIALECT_STRATEGIES[dialect];
898
+ const deactivateAll = drizzleOrm.sql`
899
+ UPDATE ${schemaVersions}
900
+ SET ${quotedColumn(schemaVersions.isActive)} = ${strategy.booleanLiteral(false)}
901
+ WHERE ${schemaVersions.graphId} = ${graphId}
902
+ `;
903
+ const activateVersion = drizzleOrm.sql`
904
+ UPDATE ${schemaVersions}
905
+ SET ${quotedColumn(schemaVersions.isActive)} = ${strategy.booleanLiteral(true)}
906
+ WHERE ${schemaVersions.graphId} = ${graphId}
907
+ AND ${schemaVersions.version} = ${version}
908
+ `;
909
+ return { deactivateAll, activateVersion };
910
+ }
911
+ function buildInsertUniqueSqlite(tables, params) {
912
+ const { uniques } = tables;
913
+ const columns = drizzleOrm.sql.raw(`"${uniques.graphId.name}", "${uniques.nodeKind.name}", "${uniques.constraintName.name}", "${uniques.key.name}", "${uniques.nodeId.name}", "${uniques.concreteKind.name}", "${uniques.deletedAt.name}"`);
914
+ const conflictColumns = drizzleOrm.sql.raw(`"${uniques.graphId.name}", "${uniques.nodeKind.name}", "${uniques.constraintName.name}", "${uniques.key.name}"`);
915
+ return drizzleOrm.sql`
916
+ INSERT INTO ${uniques} (${columns})
917
+ VALUES (
918
+ ${params.graphId}, ${params.nodeKind}, ${params.constraintName},
919
+ ${params.key}, ${params.nodeId}, ${params.concreteKind}, ${drizzleOrm.sql.raw("NULL")}
920
+ )
921
+ ON CONFLICT (${conflictColumns})
922
+ DO UPDATE SET
923
+ ${quotedColumn(uniques.nodeId)} = CASE
924
+ WHEN ${quotedColumn(uniques.nodeId)} = ${params.nodeId} THEN ${params.nodeId}
925
+ WHEN ${quotedColumn(uniques.deletedAt)} IS NOT NULL THEN ${params.nodeId}
926
+ ELSE ${quotedColumn(uniques.nodeId)}
927
+ END,
928
+ ${quotedColumn(uniques.concreteKind)} = CASE
929
+ WHEN ${quotedColumn(uniques.nodeId)} = ${params.nodeId} THEN ${params.concreteKind}
930
+ WHEN ${quotedColumn(uniques.deletedAt)} IS NOT NULL THEN ${params.concreteKind}
931
+ ELSE ${quotedColumn(uniques.concreteKind)}
932
+ END,
933
+ ${quotedColumn(uniques.deletedAt)} = CASE
934
+ WHEN ${quotedColumn(uniques.nodeId)} = ${params.nodeId} THEN NULL
935
+ WHEN ${quotedColumn(uniques.deletedAt)} IS NOT NULL THEN NULL
936
+ ELSE ${quotedColumn(uniques.deletedAt)}
937
+ END
938
+ RETURNING ${quotedColumn(uniques.nodeId)} as node_id
939
+ `;
940
+ }
941
+ function buildInsertUniquePostgres(tables, params) {
942
+ const { uniques } = tables;
943
+ const columns = drizzleOrm.sql.raw(`"${uniques.graphId.name}", "${uniques.nodeKind.name}", "${uniques.constraintName.name}", "${uniques.key.name}", "${uniques.nodeId.name}", "${uniques.concreteKind.name}", "${uniques.deletedAt.name}"`);
944
+ const conflictColumns = drizzleOrm.sql.raw(`"${uniques.graphId.name}", "${uniques.nodeKind.name}", "${uniques.constraintName.name}", "${uniques.key.name}"`);
945
+ const tableName = drizzleOrm.getTableName(uniques);
946
+ const existingColumn = (column) => drizzleOrm.sql.raw(`"${tableName}"."${column.name}"`);
947
+ return drizzleOrm.sql`
948
+ INSERT INTO ${uniques} (${columns})
949
+ VALUES (
950
+ ${params.graphId}, ${params.nodeKind}, ${params.constraintName},
951
+ ${params.key}, ${params.nodeId}, ${params.concreteKind}, ${drizzleOrm.sql.raw("NULL")}
952
+ )
953
+ ON CONFLICT (${conflictColumns})
954
+ DO UPDATE SET
955
+ ${quotedColumn(uniques.nodeId)} = CASE
956
+ WHEN ${existingColumn(uniques.nodeId)} = ${params.nodeId} THEN ${params.nodeId}
957
+ WHEN ${existingColumn(uniques.deletedAt)} IS NOT NULL THEN ${params.nodeId}
958
+ ELSE ${existingColumn(uniques.nodeId)}
959
+ END,
960
+ ${quotedColumn(uniques.concreteKind)} = CASE
961
+ WHEN ${existingColumn(uniques.nodeId)} = ${params.nodeId} THEN ${params.concreteKind}
962
+ WHEN ${existingColumn(uniques.deletedAt)} IS NOT NULL THEN ${params.concreteKind}
963
+ ELSE ${existingColumn(uniques.concreteKind)}
964
+ END,
965
+ ${quotedColumn(uniques.deletedAt)} = CASE
966
+ WHEN ${existingColumn(uniques.nodeId)} = ${params.nodeId} THEN NULL
967
+ WHEN ${existingColumn(uniques.deletedAt)} IS NOT NULL THEN NULL
968
+ ELSE ${existingColumn(uniques.deletedAt)}
969
+ END
970
+ RETURNING ${quotedColumn(uniques.nodeId)} as node_id
971
+ `;
972
+ }
973
+ var UNIQUE_INSERT_BUILDERS = {
974
+ postgres: buildInsertUniquePostgres,
975
+ sqlite: buildInsertUniqueSqlite
976
+ };
977
+ function buildInsertUnique(tables, dialect, params) {
978
+ const builder = UNIQUE_INSERT_BUILDERS[dialect];
979
+ return builder(tables, params);
980
+ }
981
+ function buildDeleteUnique(tables, params, timestamp) {
982
+ const { uniques } = tables;
983
+ return drizzleOrm.sql`
984
+ UPDATE ${uniques}
985
+ SET ${quotedColumn(uniques.deletedAt)} = ${timestamp}
986
+ WHERE ${uniques.graphId} = ${params.graphId}
987
+ AND ${uniques.nodeKind} = ${params.nodeKind}
988
+ AND ${uniques.constraintName} = ${params.constraintName}
989
+ AND ${uniques.key} = ${params.key}
990
+ AND ${uniques.deletedAt} IS NULL
991
+ `;
992
+ }
993
+ function buildHardDeleteUniquesByNode(tables, graphId, nodeId) {
994
+ const { uniques } = tables;
995
+ return drizzleOrm.sql`
996
+ DELETE FROM ${uniques}
997
+ WHERE ${uniques.graphId} = ${graphId}
998
+ AND ${uniques.nodeId} = ${nodeId}
999
+ `;
1000
+ }
1001
+ function buildHardDeleteEmbeddingsByNode(tables, graphId, nodeKind, nodeId) {
1002
+ const { embeddings } = tables;
1003
+ return drizzleOrm.sql`
1004
+ DELETE FROM ${embeddings}
1005
+ WHERE ${embeddings.graphId} = ${graphId}
1006
+ AND ${embeddings.nodeKind} = ${nodeKind}
1007
+ AND ${embeddings.nodeId} = ${nodeId}
1008
+ `;
1009
+ }
1010
+ function buildCheckUnique(tables, params) {
1011
+ const { uniques } = tables;
1012
+ return drizzleOrm.sql`
1013
+ SELECT * FROM ${uniques}
1014
+ WHERE ${uniques.graphId} = ${params.graphId}
1015
+ AND ${uniques.nodeKind} = ${params.nodeKind}
1016
+ AND ${uniques.constraintName} = ${params.constraintName}
1017
+ AND ${uniques.key} = ${params.key}
1018
+ AND ${uniques.deletedAt} IS NULL
1019
+ `;
1020
+ }
1021
+ function assertFiniteNumberArray(array, name) {
1022
+ for (const [index, value] of array.entries()) {
1023
+ if (typeof value !== "number" || !Number.isFinite(value)) {
1024
+ throw new TypeError(
1025
+ `${name}[${index}] must be a finite number, got: ${value}`
1026
+ );
1027
+ }
1028
+ }
1029
+ }
1030
+ function formatEmbeddingLiteral(embedding) {
1031
+ assertFiniteNumberArray(embedding, "embedding");
1032
+ return `[${embedding.join(",")}]`;
1033
+ }
1034
+ function buildUpsertEmbeddingPostgres(tables, params, timestamp) {
1035
+ const { embeddings } = tables;
1036
+ const embeddingLiteral = formatEmbeddingLiteral(params.embedding);
1037
+ const columns = drizzleOrm.sql.raw(
1038
+ `"${embeddings.graphId.name}", "${embeddings.nodeKind.name}", "${embeddings.nodeId.name}", "${embeddings.fieldPath.name}", "${embeddings.embedding.name}", "${embeddings.dimensions.name}", "${embeddings.createdAt.name}", "${embeddings.updatedAt.name}"`
1039
+ );
1040
+ const conflictColumns = drizzleOrm.sql.raw(
1041
+ `"${embeddings.graphId.name}", "${embeddings.nodeKind.name}", "${embeddings.nodeId.name}", "${embeddings.fieldPath.name}"`
1042
+ );
1043
+ const column = (target) => drizzleOrm.sql.raw(`"${target.name}"`);
1044
+ return drizzleOrm.sql`
1045
+ INSERT INTO ${embeddings} (${columns})
1046
+ VALUES (
1047
+ ${params.graphId}, ${params.nodeKind}, ${params.nodeId}, ${params.fieldPath},
1048
+ ${embeddingLiteral}::vector, ${params.dimensions}, ${timestamp}, ${timestamp}
1049
+ )
1050
+ ON CONFLICT (${conflictColumns})
1051
+ DO UPDATE SET
1052
+ ${column(embeddings.embedding)} = ${embeddingLiteral}::vector,
1053
+ ${column(embeddings.dimensions)} = ${params.dimensions},
1054
+ ${column(embeddings.updatedAt)} = ${timestamp}
1055
+ `;
1056
+ }
1057
+ function buildDeleteEmbedding(tables, params) {
1058
+ const { embeddings } = tables;
1059
+ return drizzleOrm.sql`
1060
+ DELETE FROM ${embeddings}
1061
+ WHERE ${embeddings.graphId} = ${params.graphId}
1062
+ AND ${embeddings.nodeKind} = ${params.nodeKind}
1063
+ AND ${embeddings.nodeId} = ${params.nodeId}
1064
+ AND ${embeddings.fieldPath} = ${params.fieldPath}
1065
+ `;
1066
+ }
1067
+ function buildGetEmbedding(tables, graphId, nodeKind, nodeId, fieldPath) {
1068
+ const { embeddings } = tables;
1069
+ return drizzleOrm.sql`
1070
+ SELECT * FROM ${embeddings}
1071
+ WHERE ${embeddings.graphId} = ${graphId}
1072
+ AND ${embeddings.nodeKind} = ${nodeKind}
1073
+ AND ${embeddings.nodeId} = ${nodeId}
1074
+ AND ${embeddings.fieldPath} = ${fieldPath}
1075
+ `;
1076
+ }
1077
+ function buildDistanceExpression(embeddingColumn, queryLiteral, metric) {
1078
+ const vectorParameter = drizzleOrm.sql`${queryLiteral}::vector`;
1079
+ switch (metric) {
1080
+ case "cosine": {
1081
+ return drizzleOrm.sql`(${embeddingColumn} <=> ${vectorParameter})`;
1082
+ }
1083
+ case "l2": {
1084
+ return drizzleOrm.sql`(${embeddingColumn} <-> ${vectorParameter})`;
1085
+ }
1086
+ case "inner_product": {
1087
+ return drizzleOrm.sql`(${embeddingColumn} <#> ${vectorParameter})`;
1088
+ }
1089
+ default: {
1090
+ const _exhaustive = metric;
1091
+ throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);
1092
+ }
1093
+ }
1094
+ }
1095
+ function buildVectorSearchScoreExpression(distanceExpression, metric) {
1096
+ switch (metric) {
1097
+ case "cosine": {
1098
+ return drizzleOrm.sql`(1 - (${distanceExpression}))`;
1099
+ }
1100
+ case "l2":
1101
+ case "inner_product": {
1102
+ return distanceExpression;
1103
+ }
1104
+ default: {
1105
+ const _exhaustive = metric;
1106
+ throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);
1107
+ }
1108
+ }
1109
+ }
1110
+ function buildVectorSearchMinScoreCondition(distanceExpression, metric, minScore) {
1111
+ switch (metric) {
1112
+ case "cosine": {
1113
+ const threshold = 1 - minScore;
1114
+ return drizzleOrm.sql`${distanceExpression} <= ${threshold}`;
1115
+ }
1116
+ case "l2": {
1117
+ return drizzleOrm.sql`${distanceExpression} <= ${minScore}`;
1118
+ }
1119
+ case "inner_product": {
1120
+ const negativeThreshold = -minScore;
1121
+ return drizzleOrm.sql`${distanceExpression} <= ${negativeThreshold}`;
1122
+ }
1123
+ default: {
1124
+ const _exhaustive = metric;
1125
+ throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);
1126
+ }
1127
+ }
1128
+ }
1129
+ function buildVectorSearchPostgres(tables, params) {
1130
+ const { embeddings } = tables;
1131
+ const queryLiteral = formatEmbeddingLiteral(params.queryEmbedding);
1132
+ if (params.minScore !== void 0 && !Number.isFinite(params.minScore)) {
1133
+ throw new TypeError(
1134
+ `minScore must be a finite number, got: ${params.minScore}`
1135
+ );
1136
+ }
1137
+ if (!Number.isInteger(params.limit) || params.limit <= 0) {
1138
+ throw new Error(`limit must be a positive integer, got: ${params.limit}`);
1139
+ }
1140
+ const embeddingColumn = drizzleOrm.sql`${embeddings.embedding}`;
1141
+ const distanceExpression = buildDistanceExpression(
1142
+ embeddingColumn,
1143
+ queryLiteral,
1144
+ params.metric
1145
+ );
1146
+ const conditions = [
1147
+ drizzleOrm.sql`${embeddings.graphId} = ${params.graphId}`,
1148
+ drizzleOrm.sql`${embeddings.nodeKind} = ${params.nodeKind}`,
1149
+ drizzleOrm.sql`${embeddings.fieldPath} = ${params.fieldPath}`
1150
+ ];
1151
+ if (params.minScore !== void 0) {
1152
+ conditions.push(
1153
+ buildVectorSearchMinScoreCondition(
1154
+ distanceExpression,
1155
+ params.metric,
1156
+ params.minScore
1157
+ )
1158
+ );
1159
+ }
1160
+ const whereClause = drizzleOrm.sql.join(conditions, drizzleOrm.sql` AND `);
1161
+ const scoreExpression = buildVectorSearchScoreExpression(
1162
+ distanceExpression,
1163
+ params.metric
1164
+ );
1165
+ return drizzleOrm.sql`
1166
+ SELECT
1167
+ ${embeddings.nodeId} as node_id,
1168
+ ${scoreExpression} as score
1169
+ FROM ${embeddings}
1170
+ WHERE ${whereClause}
1171
+ ORDER BY ${distanceExpression} ASC
1172
+ LIMIT ${params.limit}
1173
+ `;
1174
+ }
1175
+
1176
+ // src/backend/drizzle/operations/strategy.ts
1177
+ function bindTableOperationBuilders(tables, builders) {
1178
+ const boundEntries = Object.entries(builders).map(([name, builder]) => {
1179
+ function boundBuilder(...args) {
1180
+ return builder(tables, ...args);
1181
+ }
1182
+ return [name, boundBuilder];
1183
+ });
1184
+ return Object.fromEntries(boundEntries);
1185
+ }
1186
+ var COMMON_TABLE_OPERATION_BUILDERS = {
1187
+ buildInsertNode,
1188
+ buildInsertNodeNoReturn,
1189
+ buildInsertNodesBatch,
1190
+ buildInsertNodesBatchReturning,
1191
+ buildGetNode,
1192
+ buildGetNodes,
1193
+ buildUpdateNode,
1194
+ buildDeleteNode,
1195
+ buildHardDeleteNode,
1196
+ buildInsertEdge,
1197
+ buildInsertEdgeNoReturn,
1198
+ buildInsertEdgesBatch,
1199
+ buildInsertEdgesBatchReturning,
1200
+ buildGetEdge,
1201
+ buildGetEdges,
1202
+ buildUpdateEdge,
1203
+ buildDeleteEdge,
1204
+ buildHardDeleteEdge,
1205
+ buildHardDeleteEdgesByNode,
1206
+ buildCountEdgesFrom,
1207
+ buildEdgeExistsBetween,
1208
+ buildFindEdgesConnectedTo,
1209
+ buildFindNodesByKind,
1210
+ buildCountNodesByKind,
1211
+ buildFindEdgesByKind,
1212
+ buildCountEdgesByKind,
1213
+ buildDeleteUnique,
1214
+ buildHardDeleteUniquesByNode,
1215
+ buildHardDeleteEmbeddingsByNode,
1216
+ buildCheckUnique,
1217
+ buildGetSchemaVersion
1218
+ };
1219
+ function createCommonOperationStrategy(tables, dialect) {
1220
+ const tableOperations = bindTableOperationBuilders(
1221
+ tables,
1222
+ COMMON_TABLE_OPERATION_BUILDERS
1223
+ );
1224
+ return {
1225
+ ...tableOperations,
1226
+ buildInsertUnique(params) {
1227
+ return buildInsertUnique(tables, dialect, params);
1228
+ },
1229
+ buildGetActiveSchema(graphId) {
1230
+ return buildGetActiveSchema(tables, graphId, dialect);
1231
+ },
1232
+ buildInsertSchema(params, timestamp) {
1233
+ return buildInsertSchema(tables, params, timestamp, dialect);
1234
+ },
1235
+ buildSetActiveSchema(graphId, version) {
1236
+ return buildSetActiveSchema(tables, graphId, version, dialect);
1237
+ }
1238
+ };
1239
+ }
1240
+ function createSqliteOperationStrategy(tables) {
1241
+ return createCommonOperationStrategy(tables, "sqlite");
1242
+ }
1243
+ function createPostgresOperationStrategy(tables) {
1244
+ const common = createCommonOperationStrategy(tables, "postgres");
1245
+ return {
1246
+ ...common,
1247
+ buildUpsertEmbedding(params, timestamp) {
1248
+ return buildUpsertEmbeddingPostgres(tables, params, timestamp);
1249
+ },
1250
+ buildDeleteEmbedding(params) {
1251
+ return buildDeleteEmbedding(tables, params);
1252
+ },
1253
+ buildGetEmbedding(graphId, nodeKind, nodeId, fieldPath) {
1254
+ return buildGetEmbedding(tables, graphId, nodeKind, nodeId, fieldPath);
1255
+ },
1256
+ buildVectorSearch(params) {
1257
+ return buildVectorSearchPostgres(tables, params);
1258
+ }
1259
+ };
1260
+ }
1261
+ function assertPositiveInteger(value, name) {
1262
+ if (!Number.isInteger(value) || value <= 0) {
1263
+ throw new Error(`${name} must be a positive integer, got: ${value}`);
1264
+ }
1265
+ }
1266
+ function assertSafeIdentifier(value, name) {
1267
+ if (!/^[a-z0-9_]+$/i.test(value)) {
1268
+ throw new Error(
1269
+ `${name} must contain only alphanumeric characters and underscores, got: ${value}`
1270
+ );
1271
+ }
1272
+ }
1273
+ var MAX_IDENTIFIER_LENGTH = 63;
1274
+ function sanitizeIdentifier(s) {
1275
+ return s.toLowerCase().replaceAll(/[^a-z0-9_]/g, "_");
1276
+ }
1277
+ function quoteIdentifier(value) {
1278
+ return `"${value.replaceAll('"', '""')}"`;
1279
+ }
1280
+ function shortHash(input) {
1281
+ let h1 = 3735928559;
1282
+ let h2 = 1103547991;
1283
+ for (let index = 0; index < input.length; index++) {
1284
+ const ch = input.codePointAt(index);
1285
+ h1 = Math.imul(h1 ^ ch, 2654435761);
1286
+ h2 = Math.imul(h2 ^ ch, 1597334677);
1287
+ }
1288
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
1289
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
1290
+ const hi = (h2 >>> 0).toString(16).padStart(8, "0");
1291
+ const lo = (h1 >>> 0).toString(16).padStart(8, "0");
1292
+ return `${hi}${lo}`.slice(0, 8);
1293
+ }
1294
+ function generateVectorIndexName(graphId, nodeKind, fieldPath, metric = "cosine") {
1295
+ const parts = [
1296
+ "idx_emb",
1297
+ sanitizeIdentifier(graphId),
1298
+ sanitizeIdentifier(nodeKind),
1299
+ sanitizeIdentifier(fieldPath),
1300
+ metric
1301
+ ];
1302
+ const name = parts.join("_");
1303
+ if (name.length <= MAX_IDENTIFIER_LENGTH) {
1304
+ return name;
1305
+ }
1306
+ const hash = shortHash(name);
1307
+ const truncated = name.slice(0, MAX_IDENTIFIER_LENGTH - 1 - hash.length);
1308
+ return `${truncated}_${hash}`;
1309
+ }
1310
+ function getOperatorClass(metric) {
1311
+ switch (metric) {
1312
+ case "cosine": {
1313
+ return "vector_cosine_ops";
1314
+ }
1315
+ case "l2": {
1316
+ return "vector_l2_ops";
1317
+ }
1318
+ case "inner_product": {
1319
+ return "vector_ip_ops";
1320
+ }
1321
+ default: {
1322
+ const _exhaustive = metric;
1323
+ throw new Error("Unsupported vector metric: " + String(_exhaustive));
1324
+ }
1325
+ }
1326
+ }
1327
+ function escapeSqlString(value) {
1328
+ const tag = `tg${crypto.randomUUID().replaceAll("-", "").slice(0, 8)}`;
1329
+ return `$${tag}$${value}$${tag}$`;
1330
+ }
1331
+ async function createPostgresVectorIndex(db, options) {
1332
+ const {
1333
+ graphId,
1334
+ nodeKind,
1335
+ fieldPath,
1336
+ dimensions,
1337
+ embeddingsTableName = "typegraph_node_embeddings",
1338
+ indexType = "hnsw",
1339
+ metric = "cosine",
1340
+ hnswM = 16,
1341
+ hnswEfConstruction = 64,
1342
+ ivfflatLists = 100
1343
+ } = options;
1344
+ assertPositiveInteger(dimensions, "dimensions");
1345
+ assertPositiveInteger(hnswM, "hnswM");
1346
+ assertPositiveInteger(hnswEfConstruction, "hnswEfConstruction");
1347
+ assertPositiveInteger(ivfflatLists, "ivfflatLists");
1348
+ const indexName = generateVectorIndexName(graphId, nodeKind, fieldPath, metric);
1349
+ const operatorClass = getOperatorClass(metric);
1350
+ const quotedEmbeddingsTableName = quoteIdentifier(embeddingsTableName);
1351
+ assertSafeIdentifier(indexName, "indexName");
1352
+ const safeGraphId = escapeSqlString(graphId);
1353
+ const safeNodeKind = escapeSqlString(nodeKind);
1354
+ const safeFieldPath = escapeSqlString(fieldPath);
1355
+ let indexSql;
1356
+ if (indexType === "hnsw") {
1357
+ indexSql = drizzleOrm.sql.raw(`
1358
+ CREATE INDEX IF NOT EXISTS ${indexName}
1359
+ ON ${quotedEmbeddingsTableName}
1360
+ USING hnsw ((embedding::vector(${dimensions})) ${operatorClass})
1361
+ WITH (m = ${hnswM}, ef_construction = ${hnswEfConstruction})
1362
+ WHERE graph_id = ${safeGraphId}
1363
+ AND node_kind = ${safeNodeKind}
1364
+ AND field_path = ${safeFieldPath}
1365
+ `);
1366
+ } else if (indexType === "ivfflat") {
1367
+ indexSql = drizzleOrm.sql.raw(`
1368
+ CREATE INDEX IF NOT EXISTS ${indexName}
1369
+ ON ${quotedEmbeddingsTableName}
1370
+ USING ivfflat ((embedding::vector(${dimensions})) ${operatorClass})
1371
+ WITH (lists = ${ivfflatLists})
1372
+ WHERE graph_id = ${safeGraphId}
1373
+ AND node_kind = ${safeNodeKind}
1374
+ AND field_path = ${safeFieldPath}
1375
+ `);
1376
+ } else {
1377
+ return {
1378
+ indexName,
1379
+ success: true,
1380
+ message: `Index type "${indexType}" not supported, skipping index creation`
1381
+ };
1382
+ }
1383
+ try {
1384
+ await db.execute(indexSql);
1385
+ return {
1386
+ indexName,
1387
+ success: true,
1388
+ message: `Created ${indexType.toUpperCase()} index "${indexName}" for ${nodeKind}.${fieldPath}`
1389
+ };
1390
+ } catch (error) {
1391
+ return {
1392
+ indexName,
1393
+ success: false,
1394
+ message: `Failed to create index: ${error instanceof Error ? error.message : String(error)}`
1395
+ };
1396
+ }
1397
+ }
1398
+ async function dropPostgresVectorIndex(db, indexName) {
1399
+ assertSafeIdentifier(indexName, "indexName");
1400
+ try {
1401
+ const dropSql = drizzleOrm.sql.raw(`DROP INDEX IF EXISTS ${indexName}`);
1402
+ await db.execute(dropSql);
1403
+ return {
1404
+ indexName,
1405
+ success: true,
1406
+ message: `Dropped index "${indexName}"`
1407
+ };
1408
+ } catch (error) {
1409
+ return {
1410
+ indexName,
1411
+ success: false,
1412
+ message: `Failed to drop index: ${error instanceof Error ? error.message : String(error)}`
1413
+ };
1414
+ }
1415
+ }
1416
+ function createSqliteVectorIndex(_options) {
1417
+ const indexName = generateVectorIndexName(
1418
+ _options.graphId,
1419
+ _options.nodeKind,
1420
+ _options.fieldPath,
1421
+ _options.metric
1422
+ );
1423
+ return {
1424
+ indexName,
1425
+ success: true,
1426
+ message: "SQLite/sqlite-vec uses optimized internal indexing, no explicit index needed"
1427
+ };
1428
+ }
1429
+ function dropSqliteVectorIndex(graphId, nodeKind, fieldPath, metric = "cosine") {
1430
+ const indexName = generateVectorIndexName(graphId, nodeKind, fieldPath, metric);
1431
+ return {
1432
+ indexName,
1433
+ success: true,
1434
+ message: "SQLite/sqlite-vec does not use explicit indexes"
1435
+ };
1436
+ }
1437
+
1438
+ // src/backend/drizzle/execution/types.ts
1439
+ function compileQueryWithDialect(db, query, backendName) {
1440
+ const databaseWithCompiler = db;
1441
+ const compiler = databaseWithCompiler.dialect;
1442
+ if (compiler === void 0) {
1443
+ throw new Error(`${backendName} backend is missing a SQL compiler`);
1444
+ }
1445
+ return compiler.sqlToQuery(query);
1446
+ }
1447
+
1448
+ exports.D1_CAPABILITIES = D1_CAPABILITIES;
1449
+ exports.POSTGRES_CAPABILITIES = POSTGRES_CAPABILITIES;
1450
+ exports.POSTGRES_ROW_MAPPER_CONFIG = POSTGRES_ROW_MAPPER_CONFIG;
1451
+ exports.SQLITE_CAPABILITIES = SQLITE_CAPABILITIES;
1452
+ exports.SQLITE_ROW_MAPPER_CONFIG = SQLITE_ROW_MAPPER_CONFIG;
1453
+ exports.compileQueryWithDialect = compileQueryWithDialect;
1454
+ exports.createCommonOperationBackend = createCommonOperationBackend;
1455
+ exports.createEdgeRowMapper = createEdgeRowMapper;
1456
+ exports.createNodeRowMapper = createNodeRowMapper;
1457
+ exports.createPostgresOperationStrategy = createPostgresOperationStrategy;
1458
+ exports.createPostgresVectorIndex = createPostgresVectorIndex;
1459
+ exports.createSchemaVersionRowMapper = createSchemaVersionRowMapper;
1460
+ exports.createSqliteOperationStrategy = createSqliteOperationStrategy;
1461
+ exports.createSqliteVectorIndex = createSqliteVectorIndex;
1462
+ exports.createUniqueRowMapper = createUniqueRowMapper;
1463
+ exports.dropPostgresVectorIndex = dropPostgresVectorIndex;
1464
+ exports.dropSqliteVectorIndex = dropSqliteVectorIndex;
1465
+ exports.formatPostgresTimestamp = formatPostgresTimestamp;
1466
+ exports.generateVectorIndexName = generateVectorIndexName;
1467
+ exports.nowIso = nowIso;
1468
+ //# sourceMappingURL=chunk-SFY2PPOY.cjs.map
1469
+ //# sourceMappingURL=chunk-SFY2PPOY.cjs.map