@nicia-ai/typegraph 0.28.1 → 0.30.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 (178) hide show
  1. package/dist/backend/postgres/index.cjs +24 -762
  2. package/dist/backend/postgres/index.cjs.map +1 -1
  3. package/dist/backend/postgres/index.d.cts +24 -5
  4. package/dist/backend/postgres/index.d.ts +24 -5
  5. package/dist/backend/postgres/index.js +11 -753
  6. package/dist/backend/postgres/index.js.map +1 -1
  7. package/dist/backend/postgres/pglite.cjs +52 -0
  8. package/dist/backend/postgres/pglite.cjs.map +1 -0
  9. package/dist/backend/postgres/pglite.d.cts +116 -0
  10. package/dist/backend/postgres/pglite.d.ts +116 -0
  11. package/dist/backend/postgres/pglite.js +50 -0
  12. package/dist/backend/postgres/pglite.js.map +1 -0
  13. package/dist/backend/sqlite/index.cjs +23 -27
  14. package/dist/backend/sqlite/index.d.cts +22 -15
  15. package/dist/backend/sqlite/index.d.ts +22 -15
  16. package/dist/backend/sqlite/index.js +10 -10
  17. package/dist/backend/sqlite/libsql.cjs +18 -14
  18. package/dist/backend/sqlite/libsql.cjs.map +1 -1
  19. package/dist/backend/sqlite/libsql.d.cts +3 -3
  20. package/dist/backend/sqlite/libsql.d.ts +3 -3
  21. package/dist/backend/sqlite/libsql.js +17 -13
  22. package/dist/backend/sqlite/libsql.js.map +1 -1
  23. package/dist/backend/sqlite/local.cjs +19 -17
  24. package/dist/backend/sqlite/local.cjs.map +1 -1
  25. package/dist/backend/sqlite/local.d.cts +9 -3
  26. package/dist/backend/sqlite/local.d.ts +9 -3
  27. package/dist/backend/sqlite/local.js +17 -15
  28. package/dist/backend/sqlite/local.js.map +1 -1
  29. package/dist/chunk-26HWIIVS.cjs +740 -0
  30. package/dist/chunk-26HWIIVS.cjs.map +1 -0
  31. package/dist/chunk-2QA5EHEN.js +181 -0
  32. package/dist/chunk-2QA5EHEN.js.map +1 -0
  33. package/dist/chunk-3IRMLJEK.js +206 -0
  34. package/dist/chunk-3IRMLJEK.js.map +1 -0
  35. package/dist/{chunk-5MTOKWDA.js → chunk-3JLRHQ67.js} +9 -9
  36. package/dist/{chunk-5MTOKWDA.js.map → chunk-3JLRHQ67.js.map} +1 -1
  37. package/dist/{chunk-WVQXAFP3.js → chunk-454I6GDF.js} +46 -5
  38. package/dist/chunk-454I6GDF.js.map +1 -0
  39. package/dist/{chunk-CTHNVU6K.cjs → chunk-4BXHVEFB.cjs} +16 -16
  40. package/dist/{chunk-CTHNVU6K.cjs.map → chunk-4BXHVEFB.cjs.map} +1 -1
  41. package/dist/{chunk-NMOE2ZEU.cjs → chunk-4LBO6KIF.cjs} +139 -128
  42. package/dist/chunk-4LBO6KIF.cjs.map +1 -0
  43. package/dist/chunk-633N7DSE.js +258 -0
  44. package/dist/chunk-633N7DSE.js.map +1 -0
  45. package/dist/{chunk-WFUN6DCM.cjs → chunk-7JGLPAFV.cjs} +11 -11
  46. package/dist/chunk-7JGLPAFV.cjs.map +1 -0
  47. package/dist/{chunk-ZTREJOGB.js → chunk-AI3RNREM.js} +140 -69
  48. package/dist/chunk-AI3RNREM.js.map +1 -0
  49. package/dist/{chunk-TSGBRPNE.js → chunk-ENDUY2CD.js} +46 -46
  50. package/dist/chunk-ENDUY2CD.js.map +1 -0
  51. package/dist/{chunk-7V335GHG.cjs → chunk-FLRCVI2G.cjs} +12 -2
  52. package/dist/chunk-FLRCVI2G.cjs.map +1 -0
  53. package/dist/chunk-FVIGJTS7.js +305 -0
  54. package/dist/chunk-FVIGJTS7.js.map +1 -0
  55. package/dist/chunk-FWBVPATK.cjs +208 -0
  56. package/dist/chunk-FWBVPATK.cjs.map +1 -0
  57. package/dist/chunk-IE6GN7L3.cjs +319 -0
  58. package/dist/chunk-IE6GN7L3.cjs.map +1 -0
  59. package/dist/{chunk-PGU2XKMA.js → chunk-IUIJJYPI.js} +117 -106
  60. package/dist/chunk-IUIJJYPI.js.map +1 -0
  61. package/dist/{chunk-E5ROA3MN.js → chunk-IX7RE7CG.js} +3 -3
  62. package/dist/{chunk-E5ROA3MN.js.map → chunk-IX7RE7CG.js.map} +1 -1
  63. package/dist/{chunk-YEDQLNVE.cjs → chunk-JIEJCTDS.cjs} +30 -2
  64. package/dist/chunk-JIEJCTDS.cjs.map +1 -0
  65. package/dist/{chunk-WZH2MKHW.cjs → chunk-K4N35E7B.cjs} +101 -101
  66. package/dist/{chunk-WZH2MKHW.cjs.map → chunk-K4N35E7B.cjs.map} +1 -1
  67. package/dist/{chunk-NZ5PMBTG.js → chunk-K5P5OZXS.js} +12 -3
  68. package/dist/chunk-K5P5OZXS.js.map +1 -0
  69. package/dist/chunk-K5VREXMZ.js +738 -0
  70. package/dist/chunk-K5VREXMZ.js.map +1 -0
  71. package/dist/chunk-LUHU4T2F.cjs +12 -0
  72. package/dist/{chunk-4FJVSF3K.cjs.map → chunk-LUHU4T2F.cjs.map} +1 -1
  73. package/dist/{chunk-O57GYGYK.js → chunk-M6OC455F.js} +32 -18
  74. package/dist/chunk-M6OC455F.js.map +1 -0
  75. package/dist/{chunk-OYLF3IC7.js → chunk-MAQJYNJR.js} +4 -4
  76. package/dist/chunk-MAQJYNJR.js.map +1 -0
  77. package/dist/{chunk-OOS2RKRH.js → chunk-MXE2U3EX.js} +4 -4
  78. package/dist/{chunk-OOS2RKRH.js.map → chunk-MXE2U3EX.js.map} +1 -1
  79. package/dist/{chunk-TKM2WDT4.js → chunk-N2OEOGBB.js} +386 -1093
  80. package/dist/chunk-N2OEOGBB.js.map +1 -0
  81. package/dist/{chunk-EJCDOA37.js → chunk-R4JOBEJU.js} +5 -5
  82. package/dist/{chunk-EJCDOA37.js.map → chunk-R4JOBEJU.js.map} +1 -1
  83. package/dist/{chunk-FFHW2JEK.cjs → chunk-RP7YITHX.cjs} +32 -17
  84. package/dist/chunk-RP7YITHX.cjs.map +1 -0
  85. package/dist/{chunk-PYJOBZR3.cjs → chunk-SGPXKJ4A.cjs} +60 -60
  86. package/dist/chunk-SGPXKJ4A.cjs.map +1 -0
  87. package/dist/{chunk-U5ROKVRF.js → chunk-TQOYM4LN.js} +29 -3
  88. package/dist/chunk-TQOYM4LN.js.map +1 -0
  89. package/dist/{chunk-PN37HVAV.cjs → chunk-UESTHN47.cjs} +153 -71
  90. package/dist/chunk-UESTHN47.cjs.map +1 -0
  91. package/dist/chunk-VFX3LC76.cjs +183 -0
  92. package/dist/chunk-VFX3LC76.cjs.map +1 -0
  93. package/dist/chunk-WEMZM7J7.cjs +270 -0
  94. package/dist/chunk-WEMZM7J7.cjs.map +1 -0
  95. package/dist/{chunk-NYQFPGYP.cjs → chunk-WFCECD6Q.cjs} +423 -1139
  96. package/dist/chunk-WFCECD6Q.cjs.map +1 -0
  97. package/dist/{chunk-EK6RJ373.cjs → chunk-YQGLVWB2.cjs} +7 -7
  98. package/dist/{chunk-EK6RJ373.cjs.map → chunk-YQGLVWB2.cjs.map} +1 -1
  99. package/dist/{chunk-X3244EKP.cjs → chunk-ZFWNO3GE.cjs} +48 -4
  100. package/dist/chunk-ZFWNO3GE.cjs.map +1 -0
  101. package/dist/ddl-BSFlbGQF.d.cts +38 -0
  102. package/dist/ddl-EdkIiFVU.d.ts +38 -0
  103. package/dist/{extension-types-B78CZfA5.d.cts → extension-types-CwHV-Uk4.d.cts} +4 -4
  104. package/dist/{extension-types-B78CZfA5.d.ts → extension-types-CwHV-Uk4.d.ts} +4 -4
  105. package/dist/graph-extension/index.cjs +19 -19
  106. package/dist/graph-extension/index.d.cts +4 -4
  107. package/dist/graph-extension/index.d.ts +4 -4
  108. package/dist/graph-extension/index.js +4 -4
  109. package/dist/{index-CWdBFWbI.d.ts → index-DzeIiMO3.d.ts} +30 -3
  110. package/dist/{index-Bilw0pYm.d.cts → index-Ln_KHTGA.d.cts} +30 -3
  111. package/dist/index.cjs +1542 -1011
  112. package/dist/index.cjs.map +1 -1
  113. package/dist/index.d.cts +142 -12
  114. package/dist/index.d.ts +142 -12
  115. package/dist/index.js +1138 -643
  116. package/dist/index.js.map +1 -1
  117. package/dist/indexes/index.cjs +19 -19
  118. package/dist/indexes/index.d.cts +9 -9
  119. package/dist/indexes/index.d.ts +9 -9
  120. package/dist/indexes/index.js +5 -5
  121. package/dist/interchange/index.cjs +8 -14
  122. package/dist/interchange/index.cjs.map +1 -1
  123. package/dist/interchange/index.d.cts +5 -16
  124. package/dist/interchange/index.d.ts +5 -16
  125. package/dist/interchange/index.js +3 -9
  126. package/dist/interchange/index.js.map +1 -1
  127. package/dist/{manager-ehLTTNq0.d.ts → manager-BbdyNhkv.d.ts} +2 -2
  128. package/dist/{manager-c1MGaVVR.d.cts → manager-wTDgjoXG.d.cts} +2 -2
  129. package/dist/{materialize-indexes-DFavFQah.d.ts → materialize-indexes-lkawaDor.d.ts} +1 -1
  130. package/dist/{materialize-indexes-BQfaAZKA.d.cts → materialize-indexes-oanE3RU0.d.cts} +1 -1
  131. package/dist/{ddl-0Ooc2dpL.d.ts → postgres-CK2ByP1q.d.cts} +2 -471
  132. package/dist/{ddl-Dza3kDrI.d.cts → postgres-ymXYC6Rr.d.ts} +2 -471
  133. package/dist/profiler/index.cjs +10 -10
  134. package/dist/profiler/index.d.cts +7 -7
  135. package/dist/profiler/index.d.ts +7 -7
  136. package/dist/profiler/index.js +3 -3
  137. package/dist/schema/index.cjs +33 -33
  138. package/dist/schema/index.d.cts +7 -7
  139. package/dist/schema/index.d.ts +7 -7
  140. package/dist/schema/index.js +10 -10
  141. package/dist/{sqlite-BxZUPbyD.d.ts → sqlite-DxH1lrwD.d.cts} +2 -468
  142. package/dist/{sqlite-mvpXjEeB.d.cts → sqlite-R8YGOqVQ.d.ts} +2 -468
  143. package/dist/{store-Ufc1Eoey.d.ts → store--z1Tmk7U.d.cts} +124 -5
  144. package/dist/{store-D7YEMg2v.d.cts → store-CNKM334w.d.ts} +124 -5
  145. package/dist/{types-CMQymcwk.d.cts → types-BBiDqJCU.d.ts} +252 -46
  146. package/dist/{types-B-sJJ4GQ.d.ts → types-CMvxx2kd.d.ts} +2 -2
  147. package/dist/{types-CmUA9sal.d.cts → types-D5B6Be5c.d.cts} +2 -2
  148. package/dist/{types-CQ7xXJMP.d.ts → types-dL-clxO3.d.cts} +252 -46
  149. package/dist/{where-CtrLu1Zf.d.ts → where-CAo6wsBZ.d.ts} +2 -2
  150. package/dist/{where-5zf15aFZ.d.cts → where-bJjuOCeV.d.cts} +2 -2
  151. package/package.json +20 -5
  152. package/dist/chunk-3EUKJEQ3.js +0 -77
  153. package/dist/chunk-3EUKJEQ3.js.map +0 -1
  154. package/dist/chunk-4FJVSF3K.cjs +0 -12
  155. package/dist/chunk-7V335GHG.cjs.map +0 -1
  156. package/dist/chunk-FFHW2JEK.cjs.map +0 -1
  157. package/dist/chunk-HTGDWIDE.cjs +0 -89
  158. package/dist/chunk-HTGDWIDE.cjs.map +0 -1
  159. package/dist/chunk-LYRUNG6E.cjs +0 -52
  160. package/dist/chunk-LYRUNG6E.cjs.map +0 -1
  161. package/dist/chunk-NMOE2ZEU.cjs.map +0 -1
  162. package/dist/chunk-NYQFPGYP.cjs.map +0 -1
  163. package/dist/chunk-NZ5PMBTG.js.map +0 -1
  164. package/dist/chunk-O57GYGYK.js.map +0 -1
  165. package/dist/chunk-OYLF3IC7.js.map +0 -1
  166. package/dist/chunk-PCHTTG42.js +0 -47
  167. package/dist/chunk-PCHTTG42.js.map +0 -1
  168. package/dist/chunk-PGU2XKMA.js.map +0 -1
  169. package/dist/chunk-PN37HVAV.cjs.map +0 -1
  170. package/dist/chunk-PYJOBZR3.cjs.map +0 -1
  171. package/dist/chunk-TKM2WDT4.js.map +0 -1
  172. package/dist/chunk-TSGBRPNE.js.map +0 -1
  173. package/dist/chunk-U5ROKVRF.js.map +0 -1
  174. package/dist/chunk-WFUN6DCM.cjs.map +0 -1
  175. package/dist/chunk-WVQXAFP3.js.map +0 -1
  176. package/dist/chunk-X3244EKP.cjs.map +0 -1
  177. package/dist/chunk-YEDQLNVE.cjs.map +0 -1
  178. package/dist/chunk-ZTREJOGB.js.map +0 -1
@@ -0,0 +1,738 @@
1
+ import { pgvectorStrategy, quoteIdentifier, assertPgvectorEfSearch } from './chunk-FVIGJTS7.js';
2
+ import { createNodeRowMapper, POSTGRES_ROW_MAPPER_CONFIG, createEdgeRowMapper, createUniqueRowMapper, createSchemaVersionRowMapper, tables, createVectorSlotLatch, createPostgresOperationStrategy, createContributionMaterializer, gateFulltextMethods, createCommonOperationBackend, nowIso, generatePgCreateTableSQL, mapContributionMaterializationRow, POSTGRES_CONTRIBUTION_MAT_TIMESTAMPS, buildContributionInsertValues, buildContributionOnConflictSet, assertAdoptedDialect, buildKindRemovalInsertValues, POSTGRES_KIND_REMOVAL_TIMESTAMPS, buildKindRemovalOnConflictSet, mapKindRemovalRow, buildMaterializationInsertValues, POSTGRES_INDEX_MAT_TIMESTAMPS, buildMaterializationOnConflictSet, mapMaterializationRow, generatePostgresDDL, vectorSlotFromParams, mapVectorWriteError, vectorSlotFromDropIndexParams, coerceNumericScore, vectorSlotFromCreateIndexParams, gateFulltext, compileQueryWithDialect, getOrCreateLru } from './chunk-N2OEOGBB.js';
3
+ import { POSTGRES_CAPABILITIES } from './chunk-633N7DSE.js';
4
+ import { isMissingTableError } from './chunk-M6OC455F.js';
5
+ import { tsvectorStrategy, buildFulltextCapabilities, buildVectorCapabilities, assertVectorSearchLimit } from './chunk-AI3RNREM.js';
6
+ import { ConfigurationError } from './chunk-TQOYM4LN.js';
7
+ import { getTableName, sql, and, eq, isNull, inArray } from 'drizzle-orm';
8
+ import { PgDatabase, PgTransaction } from 'drizzle-orm/pg-core';
9
+
10
+ // src/backend/drizzle/execution/postgres-execution.ts
11
+ function hasFunctionProperty(value, property) {
12
+ if (value === void 0 || value === null) {
13
+ return false;
14
+ }
15
+ const candidate = value;
16
+ return typeof candidate[property] === "function";
17
+ }
18
+ function isPgNativeClient(candidate) {
19
+ return typeof candidate === "object" && hasFunctionProperty(candidate, "query");
20
+ }
21
+ function isPgliteClient(candidate) {
22
+ return typeof candidate === "object" && hasFunctionProperty(candidate, "query") && hasFunctionProperty(candidate, "dumpDataDir");
23
+ }
24
+ function isPostgresJsClient(candidate) {
25
+ return typeof candidate === "function" && hasFunctionProperty(candidate, "unsafe") && hasFunctionProperty(candidate, "begin");
26
+ }
27
+ function isNeonHttpClient(db) {
28
+ const candidate = db.$client;
29
+ return typeof candidate === "function" && hasFunctionProperty(candidate, "transaction") && !hasFunctionProperty(candidate, "begin");
30
+ }
31
+ var DEFAULT_POSTGRES_STATEMENT_CACHE_MAX = 256;
32
+ var STATEMENT_NAME_CACHE = /* @__PURE__ */ new Map();
33
+ var nextStatementId = 0;
34
+ function statementNameFor(sqlText, cacheMax) {
35
+ return getOrCreateLru(STATEMENT_NAME_CACHE, sqlText, cacheMax, () => {
36
+ const name = `tg_${nextStatementId}`;
37
+ nextStatementId += 1;
38
+ return name;
39
+ });
40
+ }
41
+ function normalizeRow(row) {
42
+ if (row === null || typeof row !== "object") return row;
43
+ let mutated;
44
+ for (const key of Object.keys(row)) {
45
+ const value = row[key];
46
+ if (value instanceof Date) {
47
+ mutated ??= { ...row };
48
+ mutated[key] = value.toISOString();
49
+ }
50
+ }
51
+ return mutated ?? row;
52
+ }
53
+ function normalizeRows(rows) {
54
+ let mutated;
55
+ for (let index = 0; index < rows.length; index += 1) {
56
+ const original = rows[index];
57
+ const normalized = normalizeRow(original);
58
+ if (normalized !== original) {
59
+ mutated ??= [...rows];
60
+ mutated[index] = normalized;
61
+ }
62
+ }
63
+ return mutated ?? rows;
64
+ }
65
+ function wrapNodePgClient(client, cacheMax) {
66
+ return {
67
+ async query(sqlText, params) {
68
+ const result = await client.query({
69
+ name: statementNameFor(sqlText, cacheMax),
70
+ text: sqlText,
71
+ values: params
72
+ });
73
+ return { rows: normalizeRows(result.rows) };
74
+ }
75
+ };
76
+ }
77
+ function wrapNodePgClientUnnamed(client) {
78
+ return {
79
+ async query(sqlText, params) {
80
+ const result = await client.query(sqlText, params);
81
+ return { rows: normalizeRows(result.rows) };
82
+ }
83
+ };
84
+ }
85
+ function adaptPostgresJsClient(sql2) {
86
+ return {
87
+ async query(sqlText, params) {
88
+ const rows = await sql2.unsafe(sqlText, params);
89
+ return { rows };
90
+ }
91
+ };
92
+ }
93
+ function resolvePgClient(db, prepareStatements, cacheMax) {
94
+ if (isNeonHttpClient(db)) {
95
+ return void 0;
96
+ }
97
+ const client = db.$client;
98
+ if (isPgliteClient(client)) {
99
+ return wrapNodePgClientUnnamed(client);
100
+ }
101
+ if (isPgNativeClient(client)) {
102
+ return prepareStatements ? wrapNodePgClient(client, cacheMax) : wrapNodePgClientUnnamed(client);
103
+ }
104
+ if (isPostgresJsClient(client)) {
105
+ return adaptPostgresJsClient(client);
106
+ }
107
+ return void 0;
108
+ }
109
+ async function executeDrizzleQuery(db, query) {
110
+ const result = await db.execute(query);
111
+ if (Array.isArray(result)) {
112
+ return result;
113
+ }
114
+ return result.rows;
115
+ }
116
+ function createPgPreparedStatement(pgClient, sqlText) {
117
+ return {
118
+ async execute(params) {
119
+ const result = await pgClient.query(sqlText, params);
120
+ return result.rows;
121
+ }
122
+ };
123
+ }
124
+ function createPostgresExecutionAdapter(db, options = {}) {
125
+ const prepareStatements = options.prepareStatements ?? true;
126
+ const cacheMax = options.preparedStatementCacheMax ?? DEFAULT_POSTGRES_STATEMENT_CACHE_MAX;
127
+ const pgClient = resolvePgClient(db, prepareStatements, cacheMax);
128
+ function compile(query) {
129
+ return compileQueryWithDialect(db, query, "PostgreSQL");
130
+ }
131
+ if (pgClient === void 0) {
132
+ return {
133
+ compile,
134
+ async execute(query) {
135
+ return executeDrizzleQuery(db, query);
136
+ }
137
+ };
138
+ }
139
+ const pgQueryClient = pgClient;
140
+ async function executeCompiled(compiledQuery) {
141
+ const result = await pgQueryClient.query(
142
+ compiledQuery.sql,
143
+ compiledQuery.params
144
+ );
145
+ return result.rows;
146
+ }
147
+ return {
148
+ compile,
149
+ async execute(query) {
150
+ const compiled = compile(query);
151
+ return executeCompiled(compiled);
152
+ },
153
+ executeCompiled,
154
+ prepare(sqlText) {
155
+ return createPgPreparedStatement(pgQueryClient, sqlText);
156
+ }
157
+ };
158
+ }
159
+
160
+ // src/backend/drizzle/postgres.ts
161
+ var POSTGRES_MAX_BIND_PARAMETERS = 65535;
162
+ var NODE_INSERT_PARAM_COUNT = 9;
163
+ var EDGE_INSERT_PARAM_COUNT = 12;
164
+ var POSTGRES_NODE_INSERT_BATCH_SIZE = Math.max(
165
+ 1,
166
+ Math.floor(POSTGRES_MAX_BIND_PARAMETERS / NODE_INSERT_PARAM_COUNT)
167
+ );
168
+ var POSTGRES_EDGE_INSERT_BATCH_SIZE = Math.max(
169
+ 1,
170
+ Math.floor(POSTGRES_MAX_BIND_PARAMETERS / EDGE_INSERT_PARAM_COUNT)
171
+ );
172
+ var POSTGRES_GET_NODES_ID_CHUNK_SIZE = Math.max(
173
+ 1,
174
+ POSTGRES_MAX_BIND_PARAMETERS - 2
175
+ );
176
+ var POSTGRES_GET_EDGES_ID_CHUNK_SIZE = Math.max(
177
+ 1,
178
+ POSTGRES_MAX_BIND_PARAMETERS - 1
179
+ );
180
+ var CHECK_UNIQUE_BATCH_FIXED_PARAM_COUNT = 3;
181
+ var POSTGRES_CHECK_UNIQUE_BATCH_CHUNK_SIZE = Math.max(
182
+ 1,
183
+ POSTGRES_MAX_BIND_PARAMETERS - CHECK_UNIQUE_BATCH_FIXED_PARAM_COUNT
184
+ );
185
+ var toNodeRow = createNodeRowMapper(POSTGRES_ROW_MAPPER_CONFIG);
186
+ var toEdgeRow = createEdgeRowMapper(POSTGRES_ROW_MAPPER_CONFIG);
187
+ var toUniqueRow = createUniqueRowMapper(POSTGRES_ROW_MAPPER_CONFIG);
188
+ var toSchemaVersionRow = createSchemaVersionRowMapper(
189
+ POSTGRES_ROW_MAPPER_CONFIG
190
+ );
191
+ function buildPostgresCapabilities(fulltextStrategy, vectorStrategy) {
192
+ return {
193
+ ...POSTGRES_CAPABILITIES,
194
+ ...vectorStrategy === void 0 ? {} : { vector: buildVectorCapabilities(vectorStrategy) },
195
+ fulltext: buildFulltextCapabilities(fulltextStrategy)
196
+ };
197
+ }
198
+ function createPostgresBackend(db, options = {}) {
199
+ const tables2 = options.tables ?? tables;
200
+ const fulltextStrategy = options.fulltext ?? tsvectorStrategy;
201
+ const vectorStrategy = options.vector === false ? void 0 : options.vector ?? pgvectorStrategy;
202
+ const vectorSlotLatch = vectorStrategy === void 0 ? void 0 : createVectorSlotLatch();
203
+ const baseCapabilities = buildPostgresCapabilities(
204
+ fulltextStrategy,
205
+ vectorStrategy
206
+ );
207
+ const httpOnlyOverrides = isNeonHttpClient(db) ? { transactions: false } : {};
208
+ const capabilities = {
209
+ ...baseCapabilities,
210
+ ...httpOnlyOverrides,
211
+ ...options.capabilities
212
+ };
213
+ const adapterOptions = {
214
+ ...options.prepareStatements === void 0 ? {} : { prepareStatements: options.prepareStatements },
215
+ ...options.preparedStatementCacheMax === void 0 ? {} : { preparedStatementCacheMax: options.preparedStatementCacheMax }
216
+ };
217
+ const executionAdapter = createPostgresExecutionAdapter(db, adapterOptions);
218
+ const tableNames = {
219
+ nodes: getTableName(tables2.nodes),
220
+ edges: getTableName(tables2.edges),
221
+ fulltext: tables2.fulltextTableName,
222
+ uniques: getTableName(tables2.uniques)
223
+ };
224
+ const analyzeStatement = sql`ANALYZE ${sql.join(
225
+ [
226
+ tableNames.nodes,
227
+ tableNames.edges,
228
+ getTableName(tables2.uniques),
229
+ tableNames.fulltext
230
+ ].map((name) => quoteIdentifier(name)),
231
+ sql`, `
232
+ )}`;
233
+ const operationStrategy = createPostgresOperationStrategy(
234
+ tables2,
235
+ fulltextStrategy
236
+ );
237
+ const operations = createPostgresOperationBackend({
238
+ db,
239
+ executionAdapter,
240
+ adapterOptions,
241
+ operationStrategy,
242
+ tableNames,
243
+ capabilities,
244
+ fulltextStrategy,
245
+ vectorStrategy,
246
+ vectorSlotLatch
247
+ });
248
+ function runSchemaWriteTransaction(graphId, fn) {
249
+ if (!capabilities.transactions) {
250
+ throw new ConfigurationError(
251
+ "commitSchemaVersion and setActiveVersion require atomic transactions, but this Postgres backend does not provide them. The drizzle-orm/neon-http driver communicates over HTTP and cannot hold a session across statements; use drizzle-orm/neon-serverless (websocket) for transactional writes.",
252
+ {
253
+ backend: "postgres",
254
+ capability: "transactions",
255
+ supportsTransactions: false
256
+ }
257
+ );
258
+ }
259
+ return db.transaction(async (tx) => {
260
+ await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${graphId}))`);
261
+ const txBackend = createTransactionBackend({
262
+ db: tx,
263
+ adapterOptions,
264
+ operationStrategy,
265
+ tableNames,
266
+ capabilities,
267
+ fulltextStrategy,
268
+ vectorStrategy});
269
+ return fn(txBackend);
270
+ });
271
+ }
272
+ const matTable = tables2.contributionMaterializations;
273
+ async function ensureContributionMaterializationsTableImpl() {
274
+ await db.execute(sql.raw(generatePgCreateTableSQL(matTable)));
275
+ }
276
+ async function getContributionMaterializationRow(identity) {
277
+ const rows = await db.select().from(matTable).where(
278
+ and(
279
+ eq(matTable.graphId, identity.graphId),
280
+ eq(matTable.logicalName, identity.logicalName),
281
+ eq(matTable.owner, identity.owner),
282
+ eq(matTable.tableName, identity.tableName)
283
+ )
284
+ );
285
+ const row = rows[0];
286
+ if (row === void 0) return void 0;
287
+ return mapContributionMaterializationRow(
288
+ row,
289
+ POSTGRES_CONTRIBUTION_MAT_TIMESTAMPS.decode
290
+ );
291
+ }
292
+ async function recordContributionMaterializationRow(params) {
293
+ await db.insert(matTable).values(
294
+ buildContributionInsertValues(
295
+ params,
296
+ POSTGRES_CONTRIBUTION_MAT_TIMESTAMPS.encode
297
+ )
298
+ ).onConflictDoUpdate({
299
+ target: [
300
+ matTable.graphId,
301
+ matTable.logicalName,
302
+ matTable.owner,
303
+ matTable.tableName
304
+ ],
305
+ set: buildContributionOnConflictSet(
306
+ matTable.materializedAt,
307
+ params.materializedAt
308
+ )
309
+ });
310
+ }
311
+ const contributionMaterializer = createContributionMaterializer({
312
+ dialect: "postgres",
313
+ fulltextStrategy,
314
+ fulltextTableName: tables2.fulltextTableName,
315
+ execDdl: async (statement) => {
316
+ await db.execute(sql.raw(statement));
317
+ },
318
+ ensureMarkerTable: ensureContributionMaterializationsTableImpl,
319
+ getMarker: getContributionMaterializationRow,
320
+ recordMarker: recordContributionMaterializationRow
321
+ });
322
+ function bindTransactionBackend(tx) {
323
+ const txBackend = createTransactionBackend({
324
+ db: tx,
325
+ adapterOptions,
326
+ operationStrategy,
327
+ tableNames,
328
+ capabilities,
329
+ fulltextStrategy,
330
+ vectorStrategy});
331
+ return gateFulltext(txBackend, contributionMaterializer.assertInitialized);
332
+ }
333
+ const backend = {
334
+ ...operations,
335
+ async bootstrapTables() {
336
+ const statements = generatePostgresDDL(tables2, fulltextStrategy);
337
+ for (const statement of statements) {
338
+ await db.execute(sql.raw(statement));
339
+ }
340
+ },
341
+ // Every fulltext-touching method asserts the durable marker instead
342
+ // of lazily emitting DDL. Steady state performs zero ensure; an
343
+ // uninitialized database throws `StoreNotInitializedError` loudly
344
+ // rather than self-healing on a read/write path (#135). Shared
345
+ // verbatim with the tx-scoped gate via `gateFulltextMethods`.
346
+ ...gateFulltextMethods(
347
+ operations,
348
+ contributionMaterializer.assertInitialized
349
+ ),
350
+ async executeDdl(ddl) {
351
+ await db.execute(sql.raw(ddl));
352
+ },
353
+ async ensureIndexMaterializationsTable() {
354
+ await db.execute(
355
+ sql.raw(generatePgCreateTableSQL(tables2.indexMaterializations))
356
+ );
357
+ },
358
+ async getIndexMaterialization(indexName) {
359
+ const t = tables2.indexMaterializations;
360
+ const rows = await db.select().from(t).where(eq(t.indexName, indexName));
361
+ const row = rows[0];
362
+ if (row === void 0) return void 0;
363
+ return mapMaterializationRow(row, POSTGRES_INDEX_MAT_TIMESTAMPS.decode);
364
+ },
365
+ async getIndexMaterializations(statusKeys) {
366
+ if (statusKeys.length === 0) return [];
367
+ const t = tables2.indexMaterializations;
368
+ const rows = await db.select().from(t).where(inArray(t.indexName, [...statusKeys]));
369
+ return rows.map(
370
+ (row) => mapMaterializationRow(row, POSTGRES_INDEX_MAT_TIMESTAMPS.decode)
371
+ );
372
+ },
373
+ async recordIndexMaterialization(params) {
374
+ const t = tables2.indexMaterializations;
375
+ await db.insert(t).values(
376
+ buildMaterializationInsertValues(
377
+ params,
378
+ POSTGRES_INDEX_MAT_TIMESTAMPS.encode
379
+ )
380
+ ).onConflictDoUpdate({
381
+ target: t.indexName,
382
+ set: buildMaterializationOnConflictSet(
383
+ t.materializedAt,
384
+ params.materializedAt
385
+ )
386
+ });
387
+ },
388
+ async ensureContributionMaterializationsTable() {
389
+ await ensureContributionMaterializationsTableImpl();
390
+ },
391
+ async getContributionMaterialization(identity) {
392
+ return getContributionMaterializationRow(identity);
393
+ },
394
+ async recordContributionMaterialization(params) {
395
+ await recordContributionMaterializationRow(params);
396
+ },
397
+ async assertRuntimeContributionsInitialized(graphId) {
398
+ await contributionMaterializer.assertInitialized(graphId);
399
+ },
400
+ async ensureKindRemovalsTable() {
401
+ await db.execute(sql.raw(generatePgCreateTableSQL(tables2.kindRemovals)));
402
+ },
403
+ async getPendingKindRemovals(graphId) {
404
+ const t = tables2.kindRemovals;
405
+ const rows = await db.select().from(t).where(and(eq(t.graphId, graphId), isNull(t.removedAt)));
406
+ return rows.map(
407
+ (row) => mapKindRemovalRow(row, POSTGRES_KIND_REMOVAL_TIMESTAMPS.decode)
408
+ );
409
+ },
410
+ async getAllKindRemovals(graphId) {
411
+ const t = tables2.kindRemovals;
412
+ const rows = await db.select().from(t).where(eq(t.graphId, graphId));
413
+ return rows.map(
414
+ (row) => mapKindRemovalRow(row, POSTGRES_KIND_REMOVAL_TIMESTAMPS.decode)
415
+ );
416
+ },
417
+ async recordKindRemoval(params) {
418
+ const t = tables2.kindRemovals;
419
+ await db.insert(t).values(
420
+ buildKindRemovalInsertValues(
421
+ params,
422
+ POSTGRES_KIND_REMOVAL_TIMESTAMPS.encode
423
+ )
424
+ ).onConflictDoUpdate({
425
+ target: [t.graphId, t.kindName, t.entity, t.schemaVersion],
426
+ set: buildKindRemovalOnConflictSet(t.removedAt, params.removedAt)
427
+ });
428
+ },
429
+ async ensureReconciliationMarkersTable() {
430
+ await db.execute(
431
+ sql.raw(generatePgCreateTableSQL(tables2.reconciliationMarkers))
432
+ );
433
+ },
434
+ async ensureRuntimeContributions(graphId) {
435
+ await contributionMaterializer.ensureRuntimeContributions(graphId);
436
+ },
437
+ /**
438
+ * Superseded by `ensureRuntimeContributions(graphId)` (#129).
439
+ * Retained as a thin back-compat wrapper for callers predating
440
+ * #129; #135 routed it through the durable-marker writer.
441
+ */
442
+ async ensureFulltextTable(graphId) {
443
+ await contributionMaterializer.ensureRuntimeContributions(graphId);
444
+ },
445
+ async getReconciliationMarker(graphId) {
446
+ const t = tables2.reconciliationMarkers;
447
+ const rows = await db.select().from(t).where(eq(t.graphId, graphId));
448
+ return rows[0]?.reconciledToVersion;
449
+ },
450
+ async setReconciliationMarker(graphId, version) {
451
+ const t = tables2.reconciliationMarkers;
452
+ await db.insert(t).values({ graphId, reconciledToVersion: version }).onConflictDoUpdate({
453
+ target: t.graphId,
454
+ set: { reconciledToVersion: version }
455
+ });
456
+ },
457
+ async refreshStatistics() {
458
+ await db.execute(analyzeStatement);
459
+ },
460
+ async commitSchemaVersion(params) {
461
+ return runSchemaWriteTransaction(
462
+ params.graphId,
463
+ (target) => target.commitSchemaVersion(params)
464
+ );
465
+ },
466
+ async setActiveVersion(params) {
467
+ await runSchemaWriteTransaction(
468
+ params.graphId,
469
+ (target) => target.setActiveVersion(params)
470
+ );
471
+ },
472
+ async transaction(fn, options2) {
473
+ const txConfig = options2?.isolationLevel ? {
474
+ isolationLevel: options2.isolationLevel.replace("_", " ")
475
+ } : void 0;
476
+ return db.transaction(
477
+ async (tx) => fn(bindTransactionBackend(tx), tx),
478
+ txConfig
479
+ );
480
+ },
481
+ adoptTransaction(externalTx) {
482
+ if (!capabilities.transactions) {
483
+ throw new ConfigurationError(
484
+ "Cross-store atomicity is unavailable on this Postgres backend: its driver does not support transactions (drizzle-orm/neon-http, Cloudflare D1). Adopting an external transaction here would let the caller's relational write commit with no way to roll back the graph write. Use a node-postgres or neon-serverless (Pool/WebSocket) connection for cross-store transactions.",
485
+ {
486
+ backend: "postgres",
487
+ capability: "transactions",
488
+ supportsTransactions: false
489
+ }
490
+ );
491
+ }
492
+ assertAdoptedDialect(externalTx, PgDatabase, "postgres");
493
+ return bindTransactionBackend(externalTx);
494
+ },
495
+ async close() {
496
+ }
497
+ };
498
+ return backend;
499
+ }
500
+ function createPostgresOperationBackend(options) {
501
+ const {
502
+ db,
503
+ executionAdapter,
504
+ adapterOptions,
505
+ operationStrategy,
506
+ tableNames,
507
+ capabilities,
508
+ fulltextStrategy,
509
+ vectorStrategy,
510
+ vectorSlotLatch
511
+ } = options;
512
+ async function execAll(query) {
513
+ return executionAdapter.execute(query);
514
+ }
515
+ async function execGet(query) {
516
+ const rows = await executionAdapter.execute(query);
517
+ return rows[0];
518
+ }
519
+ async function execRun(query) {
520
+ await executionAdapter.execute(query);
521
+ }
522
+ let efSearchUnsupportedWarned = false;
523
+ function warnEfSearchUnsupported() {
524
+ if (efSearchUnsupportedWarned) return;
525
+ efSearchUnsupportedWarned = true;
526
+ if (typeof console === "undefined" || typeof console.warn !== "function") {
527
+ return;
528
+ }
529
+ console.warn(
530
+ "[typegraph] efSearch (hnsw.ef_search override) was ignored: this Postgres backend has transactions disabled (e.g. drizzle-orm/neon-http), and SET LOCAL needs a transaction to scope the override. Use a transactional driver (node-postgres / neon-serverless / postgres-js) to apply efSearch."
531
+ );
532
+ }
533
+ async function runVectorSearch(efSearch, query) {
534
+ if (efSearch === void 0) {
535
+ return execAll(query);
536
+ }
537
+ if (!capabilities.transactions) {
538
+ warnEfSearchUnsupported();
539
+ return execAll(query);
540
+ }
541
+ const setEfSearch = sql.raw(`SET LOCAL hnsw.ef_search = ${efSearch}`);
542
+ if (db instanceof PgTransaction) {
543
+ const [setting] = await execAll(
544
+ sql`SELECT current_setting('hnsw.ef_search') AS ef_search`
545
+ );
546
+ await execRun(setEfSearch);
547
+ const rows = await execAll(query);
548
+ if (setting !== void 0) {
549
+ await execRun(
550
+ sql`SELECT set_config('hnsw.ef_search', ${setting.ef_search}, true)`
551
+ );
552
+ }
553
+ return rows;
554
+ }
555
+ return db.transaction(async (tx) => {
556
+ const txAdapter = createPostgresExecutionAdapter(tx, adapterOptions);
557
+ await txAdapter.execute(setEfSearch);
558
+ return txAdapter.execute(query);
559
+ });
560
+ }
561
+ async function ensureVectorSlotStorage(slot) {
562
+ if (vectorStrategy === void 0 || vectorSlotLatch === void 0) return;
563
+ await vectorSlotLatch.ensure(vectorStrategy, slot, async (statement) => {
564
+ await execRun(sql.raw(statement));
565
+ });
566
+ }
567
+ const commonBackend = createCommonOperationBackend({
568
+ batchConfig: {
569
+ checkUniqueBatchChunkSize: POSTGRES_CHECK_UNIQUE_BATCH_CHUNK_SIZE,
570
+ edgeInsertBatchSize: POSTGRES_EDGE_INSERT_BATCH_SIZE,
571
+ getEdgesChunkSize: POSTGRES_GET_EDGES_ID_CHUNK_SIZE,
572
+ getNodesChunkSize: POSTGRES_GET_NODES_ID_CHUNK_SIZE,
573
+ nodeInsertBatchSize: POSTGRES_NODE_INSERT_BATCH_SIZE
574
+ },
575
+ execution: {
576
+ execAll,
577
+ execGet,
578
+ execRun
579
+ },
580
+ nowIso,
581
+ operationStrategy,
582
+ rowMappers: {
583
+ toEdgeRow,
584
+ toNodeRow,
585
+ toSchemaVersionRow,
586
+ toUniqueRow
587
+ }
588
+ });
589
+ const executeCompiled = executionAdapter.executeCompiled;
590
+ const executeRawMethod = executeCompiled === void 0 ? {} : {
591
+ async executeRaw(sqlText, params) {
592
+ return executeCompiled({ params, sql: sqlText });
593
+ }
594
+ };
595
+ const vectorEmbeddingMethods = vectorStrategy === void 0 ? {} : {
596
+ async upsertEmbedding(params) {
597
+ const slot = vectorSlotFromParams(params);
598
+ await ensureVectorSlotStorage(slot);
599
+ const statements = vectorStrategy.buildUpsert(slot, params, nowIso());
600
+ try {
601
+ for (const statement of statements) {
602
+ await execRun(statement);
603
+ }
604
+ } catch (error) {
605
+ throw mapVectorWriteError(error, params);
606
+ }
607
+ },
608
+ async deleteEmbedding(params) {
609
+ const slot = vectorSlotFromParams(params);
610
+ await ensureVectorSlotStorage(slot);
611
+ const statements = vectorStrategy.buildDelete(slot, params);
612
+ for (const statement of statements) {
613
+ await execRun(statement);
614
+ }
615
+ },
616
+ async vectorSearch(params) {
617
+ assertVectorSearchLimit(params.limit);
618
+ assertPgvectorEfSearch(params.efSearch);
619
+ const slot = vectorSlotFromParams(params);
620
+ await ensureVectorSlotStorage(slot);
621
+ const query = vectorStrategy.buildSearch(slot, params);
622
+ let rows;
623
+ try {
624
+ rows = await runVectorSearch(params.efSearch, query);
625
+ } catch (error) {
626
+ throw mapVectorWriteError(error, params);
627
+ }
628
+ return rows.map((row) => ({
629
+ nodeId: row.node_id,
630
+ score: row.score
631
+ }));
632
+ }
633
+ };
634
+ const operationBackend = {
635
+ ...commonBackend,
636
+ ...executeRawMethod,
637
+ ...vectorEmbeddingMethods,
638
+ capabilities,
639
+ fulltextStrategy,
640
+ ...vectorStrategy === void 0 ? {} : { vectorStrategy },
641
+ dialect: "postgres",
642
+ tableNames,
643
+ // === Vector Index Operations ===
644
+ async createVectorIndex(params) {
645
+ if (vectorStrategy === void 0) return;
646
+ const slot = vectorSlotFromCreateIndexParams(params);
647
+ await ensureVectorSlotStorage(slot);
648
+ const indexStatement = vectorStrategy.buildCreateIndex?.(slot, {
649
+ concurrent: params.concurrent === true
650
+ });
651
+ if (indexStatement !== void 0) {
652
+ await execRun(indexStatement);
653
+ }
654
+ },
655
+ // === Fulltext Operations ===
656
+ async upsertFulltext(params) {
657
+ const timestamp = nowIso();
658
+ const statements = operationStrategy.buildUpsertFulltext(
659
+ params,
660
+ timestamp
661
+ );
662
+ for (const stmt of statements) {
663
+ await execRun(stmt);
664
+ }
665
+ },
666
+ async deleteFulltext(params) {
667
+ const statements = operationStrategy.buildDeleteFulltext(params);
668
+ for (const stmt of statements) {
669
+ await execRun(stmt);
670
+ }
671
+ },
672
+ async upsertFulltextBatch(params) {
673
+ if (params.rows.length === 0) return;
674
+ const timestamp = nowIso();
675
+ const statements = operationStrategy.buildUpsertFulltextBatch(
676
+ params,
677
+ timestamp
678
+ );
679
+ for (const stmt of statements) {
680
+ await execRun(stmt);
681
+ }
682
+ },
683
+ async deleteFulltextBatch(params) {
684
+ if (params.nodeIds.length === 0) return;
685
+ const statements = operationStrategy.buildDeleteFulltextBatch(params);
686
+ for (const stmt of statements) {
687
+ await execRun(stmt);
688
+ }
689
+ },
690
+ async fulltextSearch(params) {
691
+ const query = operationStrategy.buildFulltextSearch(params);
692
+ const rows = await execAll(query);
693
+ return rows.map((row, index) => ({
694
+ nodeId: row.node_id,
695
+ score: coerceNumericScore(row.score),
696
+ rank: index + 1,
697
+ ...row.snippet === null ? {} : { snippet: row.snippet }
698
+ }));
699
+ },
700
+ async dropVectorIndex(params) {
701
+ if (vectorStrategy === void 0) return;
702
+ const slot = vectorSlotFromDropIndexParams(params);
703
+ const dropStatement = vectorStrategy.buildDropIndex?.(slot);
704
+ if (dropStatement === void 0) return;
705
+ try {
706
+ await execRun(dropStatement);
707
+ } catch (error) {
708
+ if (!isMissingTableError(error)) throw error;
709
+ }
710
+ },
711
+ // === Query Execution ===
712
+ async execute(query) {
713
+ return executionAdapter.execute(query);
714
+ },
715
+ compileSql(query) {
716
+ return executionAdapter.compile(query);
717
+ }
718
+ };
719
+ return operationBackend;
720
+ }
721
+ function createTransactionBackend(options) {
722
+ const txExecutionAdapter = options.executionAdapter ?? createPostgresExecutionAdapter(options.db, options.adapterOptions);
723
+ return createPostgresOperationBackend({
724
+ db: options.db,
725
+ executionAdapter: txExecutionAdapter,
726
+ adapterOptions: options.adapterOptions,
727
+ operationStrategy: options.operationStrategy,
728
+ tableNames: options.tableNames,
729
+ capabilities: options.capabilities,
730
+ fulltextStrategy: options.fulltextStrategy,
731
+ vectorStrategy: options.vectorStrategy,
732
+ vectorSlotLatch: options.vectorStrategy === void 0 ? void 0 : createVectorSlotLatch()
733
+ });
734
+ }
735
+
736
+ export { createPostgresBackend };
737
+ //# sourceMappingURL=chunk-K5VREXMZ.js.map
738
+ //# sourceMappingURL=chunk-K5VREXMZ.js.map