@nicia-ai/typegraph 0.50.0 → 0.51.1

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 (326) hide show
  1. package/README.md +12 -0
  2. package/dist/backend/drizzle/indexes.cjs +10 -8
  3. package/dist/backend/drizzle/indexes.d.cts +1 -1
  4. package/dist/backend/drizzle/indexes.d.ts +1 -1
  5. package/dist/backend/drizzle/indexes.js +6 -4
  6. package/dist/backend/index.cjs +183 -50
  7. package/dist/backend/index.d.cts +90 -4
  8. package/dist/backend/index.d.ts +90 -4
  9. package/dist/backend/index.js +6 -9
  10. package/dist/backend/postgres/index.cjs +30 -28
  11. package/dist/backend/postgres/index.d.cts +7 -7
  12. package/dist/backend/postgres/index.d.ts +7 -7
  13. package/dist/backend/postgres/index.js +16 -14
  14. package/dist/backend/postgres/pglite-store.cjs +6 -62
  15. package/dist/backend/postgres/pglite-store.cjs.map +1 -1
  16. package/dist/backend/postgres/pglite-store.d.cts +8 -8
  17. package/dist/backend/postgres/pglite-store.d.ts +8 -8
  18. package/dist/backend/postgres/pglite-store.js +6 -62
  19. package/dist/backend/postgres/pglite-store.js.map +1 -1
  20. package/dist/backend/postgres/pglite.cjs +18 -16
  21. package/dist/backend/postgres/pglite.d.cts +3 -3
  22. package/dist/backend/postgres/pglite.d.ts +3 -3
  23. package/dist/backend/postgres/pglite.js +17 -15
  24. package/dist/backend/sqlite/index.cjs +27 -25
  25. package/dist/backend/sqlite/index.d.cts +7 -7
  26. package/dist/backend/sqlite/index.d.ts +7 -7
  27. package/dist/backend/sqlite/index.js +14 -12
  28. package/dist/backend/sqlite/libsql.cjs +21 -19
  29. package/dist/backend/sqlite/libsql.cjs.map +1 -1
  30. package/dist/backend/sqlite/libsql.d.cts +3 -3
  31. package/dist/backend/sqlite/libsql.d.ts +3 -3
  32. package/dist/backend/sqlite/libsql.js +16 -14
  33. package/dist/backend/sqlite/libsql.js.map +1 -1
  34. package/dist/backend/sqlite/local-store.cjs +8 -64
  35. package/dist/backend/sqlite/local-store.cjs.map +1 -1
  36. package/dist/backend/sqlite/local-store.d.cts +8 -8
  37. package/dist/backend/sqlite/local-store.d.ts +8 -8
  38. package/dist/backend/sqlite/local-store.js +7 -64
  39. package/dist/backend/sqlite/local-store.js.map +1 -1
  40. package/dist/backend/sqlite/local.cjs +22 -19
  41. package/dist/backend/sqlite/local.d.cts +3 -3
  42. package/dist/backend/sqlite/local.d.ts +3 -3
  43. package/dist/backend/sqlite/local.js +18 -15
  44. package/dist/{chunk-TUVD4DFR.cjs → chunk-2CVDZCXH.cjs} +122 -51
  45. package/dist/chunk-2CVDZCXH.cjs.map +1 -0
  46. package/dist/{chunk-I5C6OTKR.js → chunk-2DWTBNSH.js} +3 -3
  47. package/dist/{chunk-I5C6OTKR.js.map → chunk-2DWTBNSH.js.map} +1 -1
  48. package/dist/{chunk-C76WFIVZ.cjs → chunk-2KCTP3U2.cjs} +180 -127
  49. package/dist/chunk-2KCTP3U2.cjs.map +1 -0
  50. package/dist/{chunk-BYBDM423.cjs → chunk-322TBTOQ.cjs} +48 -48
  51. package/dist/{chunk-BYBDM423.cjs.map → chunk-322TBTOQ.cjs.map} +1 -1
  52. package/dist/chunk-36SX6QXP.cjs +186 -0
  53. package/dist/chunk-36SX6QXP.cjs.map +1 -0
  54. package/dist/{chunk-H3XP6BAV.js → chunk-36VYWVQU.js} +3 -3
  55. package/dist/{chunk-H3XP6BAV.js.map → chunk-36VYWVQU.js.map} +1 -1
  56. package/dist/{chunk-VTJVMP4I.js → chunk-4DKY6RIU.js} +102 -31
  57. package/dist/chunk-4DKY6RIU.js.map +1 -0
  58. package/dist/chunk-4QKOZYMV.js +9 -0
  59. package/dist/chunk-4QKOZYMV.js.map +1 -0
  60. package/dist/{chunk-U3Z7XKAG.js → chunk-57JM6NW3.js} +8 -18
  61. package/dist/chunk-57JM6NW3.js.map +1 -0
  62. package/dist/{chunk-WCLMKNQE.cjs → chunk-5FVZSE3B.cjs} +1356 -1108
  63. package/dist/chunk-5FVZSE3B.cjs.map +1 -0
  64. package/dist/{chunk-XMY2SXOH.cjs → chunk-5WWEYV4H.cjs} +2208 -579
  65. package/dist/chunk-5WWEYV4H.cjs.map +1 -0
  66. package/dist/{chunk-WQBAQZHR.js → chunk-6NLYIMJO.js} +4 -4
  67. package/dist/{chunk-WQBAQZHR.js.map → chunk-6NLYIMJO.js.map} +1 -1
  68. package/dist/{chunk-G2TLHH6T.cjs → chunk-7B7I7YAW.cjs} +6 -6
  69. package/dist/{chunk-G2TLHH6T.cjs.map → chunk-7B7I7YAW.cjs.map} +1 -1
  70. package/dist/{chunk-EDLKIQRI.js → chunk-7G5IYROL.js} +6 -548
  71. package/dist/chunk-7G5IYROL.js.map +1 -0
  72. package/dist/{chunk-46UGOVRW.js → chunk-7QFRK6PU.js} +3 -7
  73. package/dist/chunk-7QFRK6PU.js.map +1 -0
  74. package/dist/chunk-A4C4NJ5U.cjs +12 -0
  75. package/dist/chunk-A4C4NJ5U.cjs.map +1 -0
  76. package/dist/{chunk-7CCMCMJO.cjs → chunk-AOGOC6JF.cjs} +77 -68
  77. package/dist/chunk-AOGOC6JF.cjs.map +1 -0
  78. package/dist/{chunk-TYGGUWMS.cjs → chunk-B3MN7EJR.cjs} +177 -137
  79. package/dist/chunk-B3MN7EJR.cjs.map +1 -0
  80. package/dist/{chunk-K6VKTBST.cjs → chunk-BZ5MVITP.cjs} +4 -4
  81. package/dist/{chunk-K6VKTBST.cjs.map → chunk-BZ5MVITP.cjs.map} +1 -1
  82. package/dist/{chunk-ZAQUKCUC.js → chunk-CBOD7TXH.js} +5 -5
  83. package/dist/{chunk-ZAQUKCUC.js.map → chunk-CBOD7TXH.js.map} +1 -1
  84. package/dist/{chunk-LLVOQOWE.cjs → chunk-CRZ56SZU.cjs} +6 -5
  85. package/dist/chunk-CRZ56SZU.cjs.map +1 -0
  86. package/dist/{chunk-ON47CBE4.cjs → chunk-D3GWARN7.cjs} +47 -47
  87. package/dist/{chunk-ON47CBE4.cjs.map → chunk-D3GWARN7.cjs.map} +1 -1
  88. package/dist/{chunk-W5SOCUBL.js → chunk-D3OUDFU7.js} +5 -5
  89. package/dist/{chunk-W5SOCUBL.js.map → chunk-D3OUDFU7.js.map} +1 -1
  90. package/dist/chunk-EKG2UXNX.cjs +23 -0
  91. package/dist/chunk-EKG2UXNX.cjs.map +1 -0
  92. package/dist/{chunk-2Q45FAIE.js → chunk-EVYW3532.js} +28 -19
  93. package/dist/chunk-EVYW3532.js.map +1 -0
  94. package/dist/{chunk-7PRMDZIA.cjs → chunk-FMMW3KX7.cjs} +21 -55
  95. package/dist/chunk-FMMW3KX7.cjs.map +1 -0
  96. package/dist/chunk-H2VWDQWC.cjs +571 -0
  97. package/dist/chunk-H2VWDQWC.cjs.map +1 -0
  98. package/dist/chunk-H4FY6OZK.js +13 -0
  99. package/dist/chunk-H4FY6OZK.js.map +1 -0
  100. package/dist/{chunk-OJHD3LXJ.cjs → chunk-H5IJSROF.cjs} +2 -8
  101. package/dist/chunk-H5IJSROF.cjs.map +1 -0
  102. package/dist/{chunk-U5EL6JUV.js → chunk-I5IOSA27.js} +101 -103
  103. package/dist/chunk-I5IOSA27.js.map +1 -0
  104. package/dist/{chunk-SHC7BCG5.cjs → chunk-I7YAY2VQ.cjs} +7 -7
  105. package/dist/{chunk-SHC7BCG5.cjs.map → chunk-I7YAY2VQ.cjs.map} +1 -1
  106. package/dist/chunk-IRCWIA3R.js +20 -0
  107. package/dist/chunk-IRCWIA3R.js.map +1 -0
  108. package/dist/chunk-IVQBLXBK.cjs +55 -0
  109. package/dist/chunk-IVQBLXBK.cjs.map +1 -0
  110. package/dist/{chunk-5PP4KRPV.js → chunk-IZD4HTCP.js} +5 -5
  111. package/dist/{chunk-5PP4KRPV.js.map → chunk-IZD4HTCP.js.map} +1 -1
  112. package/dist/{chunk-RDP6ZRSM.cjs → chunk-JQKMEKKW.cjs} +261 -204
  113. package/dist/chunk-JQKMEKKW.cjs.map +1 -0
  114. package/dist/chunk-JVA3KDEA.cjs +691 -0
  115. package/dist/chunk-JVA3KDEA.cjs.map +1 -0
  116. package/dist/{chunk-JG5XIJDY.js → chunk-K67P5DLL.js} +62 -22
  117. package/dist/chunk-K67P5DLL.js.map +1 -0
  118. package/dist/{chunk-MX7EKQPM.js → chunk-K6OZIHKI.js} +345 -97
  119. package/dist/chunk-K6OZIHKI.js.map +1 -0
  120. package/dist/{chunk-CS6JTQQ2.cjs → chunk-KACEYDYV.cjs} +94 -62
  121. package/dist/chunk-KACEYDYV.cjs.map +1 -0
  122. package/dist/{chunk-5OWHU7Z7.cjs → chunk-L6EVYIID.cjs} +248 -210
  123. package/dist/chunk-L6EVYIID.cjs.map +1 -0
  124. package/dist/{chunk-7OWE7WD6.js → chunk-LI4K2KEJ.js} +4 -4
  125. package/dist/{chunk-7OWE7WD6.js.map → chunk-LI4K2KEJ.js.map} +1 -1
  126. package/dist/chunk-LKZDQ2B4.js +1581 -0
  127. package/dist/chunk-LKZDQ2B4.js.map +1 -0
  128. package/dist/{chunk-45YZXI6X.cjs → chunk-LLFPQOBA.cjs} +27 -27
  129. package/dist/{chunk-45YZXI6X.cjs.map → chunk-LLFPQOBA.cjs.map} +1 -1
  130. package/dist/{chunk-ZRJTM7MT.js → chunk-LZMQ3SFK.js} +3 -3
  131. package/dist/{chunk-ZRJTM7MT.js.map → chunk-LZMQ3SFK.js.map} +1 -1
  132. package/dist/{chunk-DI6VC62F.js → chunk-M3VTS3F6.js} +3 -3
  133. package/dist/{chunk-DI6VC62F.js.map → chunk-M3VTS3F6.js.map} +1 -1
  134. package/dist/{chunk-MZ34E2GN.js → chunk-NBOS7BY3.js} +60 -21
  135. package/dist/chunk-NBOS7BY3.js.map +1 -0
  136. package/dist/{chunk-YA36ABIL.js → chunk-NGQDGL5X.js} +14 -48
  137. package/dist/chunk-NGQDGL5X.js.map +1 -0
  138. package/dist/{chunk-ZBFZGLZE.cjs → chunk-NLX5OWK7.cjs} +6 -2
  139. package/dist/chunk-NLX5OWK7.cjs.map +1 -0
  140. package/dist/chunk-NUQ2YFFH.cjs +1637 -0
  141. package/dist/chunk-NUQ2YFFH.cjs.map +1 -0
  142. package/dist/{chunk-TTCOPKUL.cjs → chunk-OGL4X4PH.cjs} +182 -184
  143. package/dist/chunk-OGL4X4PH.cjs.map +1 -0
  144. package/dist/{chunk-HY5BNOUN.cjs → chunk-OTNTGEXR.cjs} +4 -4
  145. package/dist/{chunk-HY5BNOUN.cjs.map → chunk-OTNTGEXR.cjs.map} +1 -1
  146. package/dist/chunk-OTWE63BW.js +53 -0
  147. package/dist/chunk-OTWE63BW.js.map +1 -0
  148. package/dist/chunk-PC5NGH5A.js +549 -0
  149. package/dist/chunk-PC5NGH5A.js.map +1 -0
  150. package/dist/{chunk-IPRP6TDL.cjs → chunk-PS3TUWJM.cjs} +7 -7
  151. package/dist/{chunk-IPRP6TDL.cjs.map → chunk-PS3TUWJM.cjs.map} +1 -1
  152. package/dist/{chunk-V76FGHY3.js → chunk-PVFFH7TL.js} +5 -5
  153. package/dist/{chunk-V76FGHY3.js.map → chunk-PVFFH7TL.js.map} +1 -1
  154. package/dist/chunk-QCD5JKU4.cjs +15 -0
  155. package/dist/chunk-QCD5JKU4.cjs.map +1 -0
  156. package/dist/{chunk-IRPYOHRC.js → chunk-QG5VEOKX.js} +6 -2
  157. package/dist/chunk-QG5VEOKX.js.map +1 -0
  158. package/dist/{chunk-2CYI5HRH.js → chunk-RI7RJH4G.js} +49 -17
  159. package/dist/chunk-RI7RJH4G.js.map +1 -0
  160. package/dist/{chunk-5LKOVCPP.js → chunk-RVUL2HXY.js} +6 -5
  161. package/dist/chunk-RVUL2HXY.js.map +1 -0
  162. package/dist/{chunk-WK23PGTP.cjs → chunk-S5GU4LUN.cjs} +11 -11
  163. package/dist/{chunk-WK23PGTP.cjs.map → chunk-S5GU4LUN.cjs.map} +1 -1
  164. package/dist/{chunk-S33YQEL7.js → chunk-SDPWO2Z5.js} +6 -6
  165. package/dist/{chunk-S33YQEL7.js.map → chunk-SDPWO2Z5.js.map} +1 -1
  166. package/dist/{chunk-6S3PTHL4.js → chunk-SLGGT2XD.js} +3 -3
  167. package/dist/{chunk-6S3PTHL4.js.map → chunk-SLGGT2XD.js.map} +1 -1
  168. package/dist/{chunk-HSEZ7X6Y.cjs → chunk-TIJUA4I6.cjs} +45 -45
  169. package/dist/{chunk-HSEZ7X6Y.cjs.map → chunk-TIJUA4I6.cjs.map} +1 -1
  170. package/dist/{chunk-CSNOYIB4.cjs → chunk-TM54OBHX.cjs} +13 -13
  171. package/dist/{chunk-CSNOYIB4.cjs.map → chunk-TM54OBHX.cjs.map} +1 -1
  172. package/dist/{chunk-MM3JHVKZ.cjs → chunk-TUWSVL6I.cjs} +4 -4
  173. package/dist/{chunk-MM3JHVKZ.cjs.map → chunk-TUWSVL6I.cjs.map} +1 -1
  174. package/dist/{chunk-2GIV5X4P.js → chunk-TYEYRCXL.js} +86 -33
  175. package/dist/chunk-TYEYRCXL.js.map +1 -0
  176. package/dist/{chunk-MJPZNEJZ.js → chunk-UKOVGCRN.js} +2095 -496
  177. package/dist/chunk-UKOVGCRN.js.map +1 -0
  178. package/dist/chunk-UYKDYE5D.cjs +12 -0
  179. package/dist/{chunk-KWNWG4RC.cjs.map → chunk-UYKDYE5D.cjs.map} +1 -1
  180. package/dist/{chunk-FX5ZW6PN.js → chunk-VAAC7L57.js} +95 -40
  181. package/dist/chunk-VAAC7L57.js.map +1 -0
  182. package/dist/{chunk-ISKCIQF2.cjs → chunk-VKHXYVN7.cjs} +14 -25
  183. package/dist/chunk-VKHXYVN7.cjs.map +1 -0
  184. package/dist/chunk-VUQZNUHU.js +171 -0
  185. package/dist/chunk-VUQZNUHU.js.map +1 -0
  186. package/dist/{chunk-K2XYLVVB.cjs → chunk-WDM5WQK4.cjs} +175 -136
  187. package/dist/chunk-WDM5WQK4.cjs.map +1 -0
  188. package/dist/{chunk-GVYVGGPJ.js → chunk-WFSYYU4W.js} +66 -28
  189. package/dist/chunk-WFSYYU4W.js.map +1 -0
  190. package/dist/{chunk-R7MRFE5P.js → chunk-WS5MT2UJ.js} +3 -3
  191. package/dist/{chunk-R7MRFE5P.js.map → chunk-WS5MT2UJ.js.map} +1 -1
  192. package/dist/chunk-XORONCV3.js +202 -0
  193. package/dist/chunk-XORONCV3.js.map +1 -0
  194. package/dist/chunk-ZGVTNKTX.cjs +217 -0
  195. package/dist/chunk-ZGVTNKTX.cjs.map +1 -0
  196. package/dist/core/index.cjs +20 -20
  197. package/dist/core/index.d.cts +4 -4
  198. package/dist/core/index.d.ts +4 -4
  199. package/dist/core/index.js +4 -4
  200. package/dist/{ddl-B49O7dB_.d.ts → ddl-BvcbgzHo.d.ts} +3 -3
  201. package/dist/{ddl-DcZG660s.d.cts → ddl-Ufebz5q5.d.cts} +3 -3
  202. package/dist/graph-extension/index.d.cts +2 -4
  203. package/dist/graph-extension/index.d.ts +2 -4
  204. package/dist/graph-merge/index.cjs +140 -125
  205. package/dist/graph-merge/index.cjs.map +1 -1
  206. package/dist/graph-merge/index.d.cts +8 -9
  207. package/dist/graph-merge/index.d.ts +8 -9
  208. package/dist/graph-merge/index.js +42 -27
  209. package/dist/graph-merge/index.js.map +1 -1
  210. package/dist/index.cjs +144 -143
  211. package/dist/index.cjs.map +1 -1
  212. package/dist/index.d.cts +11 -12
  213. package/dist/index.d.ts +11 -12
  214. package/dist/index.js +30 -29
  215. package/dist/index.js.map +1 -1
  216. package/dist/indexes/index.cjs +14 -12
  217. package/dist/indexes/index.d.cts +4 -4
  218. package/dist/indexes/index.d.ts +4 -4
  219. package/dist/indexes/index.js +7 -5
  220. package/dist/{ingestion-import-target-CI8OWIkM.d.ts → ingestion-import-target-CAs1OX-l.d.cts} +1 -1
  221. package/dist/{ingestion-import-target-DCpfM1PX.d.cts → ingestion-import-target-DCQSPfNx.d.ts} +1 -1
  222. package/dist/interchange/index.cjs +41 -39
  223. package/dist/interchange/index.cjs.map +1 -1
  224. package/dist/interchange/index.d.cts +8 -8
  225. package/dist/interchange/index.d.ts +8 -8
  226. package/dist/interchange/index.js +16 -14
  227. package/dist/interchange/index.js.map +1 -1
  228. package/dist/local-store-impl-JC7OBRAW.js +75 -0
  229. package/dist/local-store-impl-JC7OBRAW.js.map +1 -0
  230. package/dist/local-store-impl-UOS2LUIG.cjs +77 -0
  231. package/dist/local-store-impl-UOS2LUIG.cjs.map +1 -0
  232. package/dist/{manager-Cfg1ENj1.d.ts → manager-B68OrPR2.d.ts} +1 -2
  233. package/dist/{manager-D348fa6W.d.cts → manager-D_t7oK69.d.cts} +1 -2
  234. package/dist/pglite-store-impl-J5J5AA52.cjs +75 -0
  235. package/dist/pglite-store-impl-J5J5AA52.cjs.map +1 -0
  236. package/dist/pglite-store-impl-LDRH2DUH.js +73 -0
  237. package/dist/pglite-store-impl-LDRH2DUH.js.map +1 -0
  238. package/dist/{postgres-UStOycLI.d.ts → postgres-BPLSVyHM.d.ts} +1 -1
  239. package/dist/{postgres-CH1kkM5J.d.cts → postgres-CqvtFC2y.d.cts} +1 -1
  240. package/dist/profiler/index.d.cts +9 -9
  241. package/dist/profiler/index.d.ts +9 -9
  242. package/dist/provenance/index.cjs +33 -20
  243. package/dist/provenance/index.cjs.map +1 -1
  244. package/dist/provenance/index.d.cts +7 -7
  245. package/dist/provenance/index.d.ts +7 -7
  246. package/dist/provenance/index.js +24 -11
  247. package/dist/provenance/index.js.map +1 -1
  248. package/dist/{repair-validity-windows-aWX7VNvv.d.cts → repair-validity-windows-DEzCKAdy.d.cts} +7 -3
  249. package/dist/{repair-validity-windows-BtOEe2pS.d.ts → repair-validity-windows-GMdaS2AH.d.ts} +7 -3
  250. package/dist/resolve-D_H8MHtq.d.ts +1805 -0
  251. package/dist/resolve-WEW8gWws.d.cts +1805 -0
  252. package/dist/schema/index.cjs +42 -40
  253. package/dist/schema/index.d.cts +4 -6
  254. package/dist/schema/index.d.ts +4 -6
  255. package/dist/schema/index.js +15 -13
  256. package/dist/{searchable-z4BiFfHI.d.ts → searchable-C_UREI9K.d.ts} +1 -1
  257. package/dist/{searchable-C8-RrL3l.d.cts → searchable-ClgET_i7.d.cts} +1 -1
  258. package/dist/{sqlite-axLw5Lo5.d.ts → sqlite-D1mXO9Kp.d.cts} +2 -1
  259. package/dist/{sqlite-Cyx9j9o6.d.cts → sqlite-MZA3oZNB.d.ts} +2 -1
  260. package/dist/{store-CTfQ9taw.d.ts → store-CuFX7fCx.d.cts} +38 -41
  261. package/dist/{store-DR9J7JVB.d.cts → store-D-ZjXQpW.d.ts} +38 -41
  262. package/dist/{temporal-CBOrERz5.d.ts → temporal-CpyEiRY8.d.cts} +1 -1
  263. package/dist/{temporal-B4Ky4wzh.d.cts → temporal-y0Aep9Su.d.ts} +1 -1
  264. package/dist/{types-CWg4dTjj.d.ts → types-6yf0Vv-_.d.cts} +1672 -1
  265. package/dist/{types-CWg4dTjj.d.cts → types-6yf0Vv-_.d.ts} +1672 -1
  266. package/dist/{types-BScHXVM7.d.ts → types-DzJ4dlzk.d.cts} +1 -1
  267. package/dist/{types-BE921wRl.d.cts → types-_vVSB9k-.d.ts} +1 -1
  268. package/dist/{where-BWXUPV3C.d.ts → where-DuG2LCLe.d.ts} +1 -1
  269. package/dist/{where-CNtx1aLc.d.cts → where-Mhf_yyKX.d.cts} +1 -1
  270. package/package.json +5 -1
  271. package/dist/chunk-2CYI5HRH.js.map +0 -1
  272. package/dist/chunk-2GIV5X4P.js.map +0 -1
  273. package/dist/chunk-2Q45FAIE.js.map +0 -1
  274. package/dist/chunk-46UGOVRW.js.map +0 -1
  275. package/dist/chunk-5LKOVCPP.js.map +0 -1
  276. package/dist/chunk-5OWHU7Z7.cjs.map +0 -1
  277. package/dist/chunk-6LEOAIIB.js +0 -1160
  278. package/dist/chunk-6LEOAIIB.js.map +0 -1
  279. package/dist/chunk-7CCMCMJO.cjs.map +0 -1
  280. package/dist/chunk-7PRMDZIA.cjs.map +0 -1
  281. package/dist/chunk-C76WFIVZ.cjs.map +0 -1
  282. package/dist/chunk-CS6JTQQ2.cjs.map +0 -1
  283. package/dist/chunk-EDLKIQRI.js.map +0 -1
  284. package/dist/chunk-EH3JZJUM.cjs +0 -567
  285. package/dist/chunk-EH3JZJUM.cjs.map +0 -1
  286. package/dist/chunk-FX5ZW6PN.js.map +0 -1
  287. package/dist/chunk-GHZPZNFC.cjs +0 -132
  288. package/dist/chunk-GHZPZNFC.cjs.map +0 -1
  289. package/dist/chunk-GVYVGGPJ.js.map +0 -1
  290. package/dist/chunk-IHK5KA2Q.cjs +0 -262
  291. package/dist/chunk-IHK5KA2Q.cjs.map +0 -1
  292. package/dist/chunk-IRPYOHRC.js.map +0 -1
  293. package/dist/chunk-ISKCIQF2.cjs.map +0 -1
  294. package/dist/chunk-JG5XIJDY.js.map +0 -1
  295. package/dist/chunk-K2XYLVVB.cjs.map +0 -1
  296. package/dist/chunk-KWNWG4RC.cjs +0 -12
  297. package/dist/chunk-LLVOQOWE.cjs.map +0 -1
  298. package/dist/chunk-MJPZNEJZ.js.map +0 -1
  299. package/dist/chunk-MX7EKQPM.js.map +0 -1
  300. package/dist/chunk-MZ34E2GN.js.map +0 -1
  301. package/dist/chunk-OJHD3LXJ.cjs.map +0 -1
  302. package/dist/chunk-PALYTHGM.js +0 -114
  303. package/dist/chunk-PALYTHGM.js.map +0 -1
  304. package/dist/chunk-RDP6ZRSM.cjs.map +0 -1
  305. package/dist/chunk-S3SDEQMC.js +0 -532
  306. package/dist/chunk-S3SDEQMC.js.map +0 -1
  307. package/dist/chunk-TEC24ZDA.cjs +0 -1254
  308. package/dist/chunk-TEC24ZDA.cjs.map +0 -1
  309. package/dist/chunk-TP4NJTI3.cjs +0 -1192
  310. package/dist/chunk-TP4NJTI3.cjs.map +0 -1
  311. package/dist/chunk-TTCOPKUL.cjs.map +0 -1
  312. package/dist/chunk-TUVD4DFR.cjs.map +0 -1
  313. package/dist/chunk-TYGGUWMS.cjs.map +0 -1
  314. package/dist/chunk-U3Z7XKAG.js.map +0 -1
  315. package/dist/chunk-U5EL6JUV.js.map +0 -1
  316. package/dist/chunk-VTJVMP4I.js.map +0 -1
  317. package/dist/chunk-WCLMKNQE.cjs.map +0 -1
  318. package/dist/chunk-XMY2SXOH.cjs.map +0 -1
  319. package/dist/chunk-Y55DLLEG.js +0 -247
  320. package/dist/chunk-Y55DLLEG.js.map +0 -1
  321. package/dist/chunk-YA36ABIL.js.map +0 -1
  322. package/dist/chunk-ZBFZGLZE.cjs.map +0 -1
  323. package/dist/index-B0PrmE3K.d.cts +0 -1146
  324. package/dist/index-CwcXsL5R.d.ts +0 -1146
  325. package/dist/materialize-indexes-C9GG3O3C.d.ts +0 -266
  326. package/dist/materialize-indexes-CrSiW_lT.d.cts +0 -266
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/backend/drizzle/execution/postgres-execution.ts","../src/backend/drizzle/execution/statement-queue.ts","../src/backend/drizzle/postgres.ts"],"names":["getOrCreateLru","sql","compileQueryWithDialect","isSqlFragment","toDrizzleSql","shouldForceCustomPlan","ConfigurationError","TransactionClosedError","EMBEDDING_UPSERT_PARAM_COUNT","FIND_EDGES_ENDPOINT_FIXED_PARAM_COUNT","isPostgresConcurrentDdlRaceError","isInsufficientResourcesError","pgvectorStrategy","createNodeRowMapper","POSTGRES_ROW_MAPPER_CONFIG","createEdgeRowMapper","createUniqueRowMapper","createSchemaVersionRowMapper","POSTGRES_CAPABILITIES","buildVectorCapabilities","buildFulltextCapabilities","resolveDeclaredBackendResource","tables","tsvectorStrategy","POSTGRES_MAX_BIND_PARAMETERS","normalizeGraphAnalyticsCapabilities","contributionRebuildSupported","getTableName","createPostgresOperationStrategy","createCachedTableExistence","generatePgCreateTableSQL","DATABASE_EXTENSION_NAMES","createPostgresTables","postgresContributions","and","eq","mapContributionMaterializationRow","POSTGRES_CONTRIBUTION_MAT_TIMESTAMPS","buildContributionInsertValues","buildContributionOnConflictSet","tableExistsFromRow","createContributionMaterializer","backend","gateFulltext","requireDefined","deriveBackend","lockPostgresTrustedImportTables","assertTrustedImportDatabaseEmpty","suspendPostgresSecondaryIndexes","createPostgresTrustedImportSession","restoreSecondaryIndexes","analyzeImportedTables","generatePostgresDDL","options","gateFulltextMethods","mapMaterializationRow","POSTGRES_INDEX_MAT_TIMESTAMPS","inArray","buildMaterializationInsertValues","buildMaterializationOnConflictSet","isNull","mapKindRemovalRow","POSTGRES_KIND_REMOVAL_TIMESTAMPS","buildKindRemovalInsertValues","buildKindRemovalOnConflictSet","commitSchemaVersionIfKindsEmpty","INTERNAL_TEMPORARY_WRITES","assertAdoptedDialect","PgTransaction","auditBackendResource","resolveEfSearchOverride","vectorSearchFrontierTuning","CompilerInvariantError","createCommonOperationBackend","nowIso","vectorSlotFromParams","mapVectorWriteError","chunk","assertVectorSearchLimit","assertPgvectorEfSearch","buildLiveNodeCandidates","mapHybridSearchRow","assertActiveSchemaVersion","StaleVersionError","vectorSlotFromCreateIndexParams","coerceNumericScore","vectorSlotFromDropIndexParams","isMissingTableError","annIndexScanTypes"],"mappings":";;;;;;;;;;;;;;;;;AAgIO,SAAS,mBAAA,CACd,OACA,QAAA,EACwE;AACxE,EAAA,IAAI,KAAA,KAAU,MAAA,IAAa,KAAA,KAAU,IAAA,EAAM;AACzC,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,MAAM,SAAA,GAAY,KAAA;AAClB,EAAA,OAAO,OAAO,SAAA,CAAU,QAAQ,CAAA,KAAM,UAAA;AACxC;AAEA,SAAS,iBAAiB,SAAA,EAA+C;AAKvE,EAAA,OACE,OAAO,SAAA,KAAc,QAAA,IAAY,mBAAA,CAAoB,WAAW,OAAO,CAAA;AAE3E;AAEA,SAAS,eAAe,SAAA,EAA+C;AAUrE,EAAA,OACE,OAAO,cAAc,QAAA,IACrB,mBAAA,CAAoB,WAAW,OAAO,CAAA,IACtC,mBAAA,CAAoB,SAAA,EAAW,aAAa,CAAA;AAEhD;AAQO,IAAM,0BAAA,GAA6B,KAAA;AAGnC,SAAS,gBAAgB,EAAA,EAAuC;AACrE,EAAA,MAA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gDatabase,\n type PgQueryResultHKT,\n type PgTransaction,\n} from \"drizzle-orm/pg-core\";\nimport { type ExtractTablesWithRelations } from \"drizzle-orm/relations\";\n\nimport { ConfigurationError } from \"../../../errors\";\nimport { isSqlFragment } from \"../../../query/sql-fragment\";\nimport { shouldForceCustomPlan } from \"../../../query/sql-intent\";\nimport { getOrCreateLru } from \"./lru\";\nimport {\n type CompiledSqlQuery,\n compileQueryWithDialect,\n type ExecutableSql,\n type PreparedSqlStatement,\n type SqlExecutionAdapter,\n toDrizzleSql,\n} from \"./types\";\n\n/**\n * Edge-safe: this module is loaded on Cloudflare Workers / Vercel Edge\n * via `@neondatabase/serverless`, so it must not statically import any\n * `node:*` module. Use only platform-neutral primitives.\n */\n\ntype PgQueryResult = Readonly<{\n rows: readonly unknown[];\n}>;\n\n/**\n * The wire-protocol-shaped client the fast path calls. Both the wrapped\n * node-postgres and postgres-js clients normalize to this signature; what\n * differs is whether the underlying driver gets a server-side prepared\n * statement (node-postgres path) or relies on its own internal preparation\n * (postgres-js).\n */\ntype PgQueryClient = Readonly<{\n query: (\n sqlText: string,\n params: readonly unknown[],\n ) => Promise<PgQueryResult>;\n /**\n * Executes WITHOUT a named server-side prepared statement, so the\n * server plans against the actual parameter values on every call.\n * Used for statements marked `markForceCustomPlan` (see sql-intent).\n */\n queryUnnamed: (\n sqlText: string,\n params: readonly unknown[],\n ) => Promise<PgQueryResult>;\n}>;\n\n/**\n * Minimal shape of the node-postgres / @neondatabase/serverless client\n * we rely on. Both accept either positional `query(text, values)`\n * (unnamed) or the configuration-object form `query({name, text, values})`\n * which uses a server-side prepared statement keyed by `name`.\n */\ntype NodePgQueryConfig = Readonly<{\n name: string;\n text: string;\n values: readonly unknown[];\n}>;\n\ntype NodePgClient = Readonly<{\n query: ((\n sqlText: string,\n params?: readonly unknown[],\n ) => Promise<PgQueryResult>) &\n ((config: NodePgQueryConfig) => Promise<PgQueryResult>);\n}>;\n\n/**\n * Minimal shape of the postgres-js tagged-template `Sql` client we rely on\n * for the raw fast path. `unsafe(sqlText, params)` is postgres-js's\n * parameterized-raw-SQL entry point and resolves to a row array.\n */\ntype PostgresJsClient = ((...args: readonly unknown[]) => unknown) &\n Readonly<{\n unsafe: (\n sqlText: string,\n params?: readonly unknown[],\n queryOptions?: Readonly<{ prepare?: boolean }>,\n ) => PromiseLike<readonly unknown[]>;\n }>;\n\ntype PgSessionCarrier = Readonly<{\n client?: unknown;\n constructor?: Readonly<{ name?: string }>;\n}>;\n\ntype PgClientCarrier = Readonly<{\n $client?: unknown;\n /** Drizzle's transaction handle keeps the pinned driver here. */\n session?: PgSessionCarrier;\n /** Defensive fallback for Drizzle builds exposing only the internal bag. */\n _?: Readonly<{\n session?: PgSessionCarrier;\n }>;\n}>;\n\nexport type AnyPgDatabase = PgDatabase<\n PgQueryResultHKT,\n Record<string, unknown>\n>;\n\n/**\n * A driver-agnostic Drizzle PostgreSQL transaction handle.\n *\n * Unlike {@link AnyPgDatabase}, this type cannot be satisfied by a root\n * database. It is the native handle exposed to adapter-aware stores and\n * accepted when adopting a caller-owned PostgreSQL transaction.\n */\nexport type AnyPgTransaction = PgTransaction<\n PgQueryResultHKT,\n Record<string, unknown>,\n ExtractTablesWithRelations<Record<string, unknown>>\n>;\n\nexport type PostgresExecutionAdapter = SqlExecutionAdapter;\n\n/**\n * Duck-typing primitive for the client-shape predicates: `value` carries a\n * callable `property`. Shared with the serialized-resource detection in\n * `../postgres.ts` so both spell \"has this method\" the same way.\n */\nexport function hasFunctionProperty<K extends string>(\n value: unknown,\n property: K,\n): value is Readonly<Record<K, (...args: readonly unknown[]) => unknown>> {\n if (value === undefined || value === null) {\n return false;\n }\n const candidate = value as Readonly<Record<K, unknown>>;\n return typeof candidate[property] === \"function\";\n}\n\nfunction isPgNativeClient(candidate: unknown): candidate is NodePgClient {\n // pg `Pool` / `Client` and @neondatabase/serverless `Pool` / `Client`\n // are object instances with a `.query` method. We require non-callable\n // here so we don't accidentally swallow the postgres-js or neon-http\n // tagged-template clients (both callable, both also expose `.query`).\n return (\n typeof candidate === \"object\" && hasFunctionProperty(candidate, \"query\")\n );\n}\n\nfunction isPgliteClient(candidate: unknown): candidate is NodePgClient {\n // PGlite (Postgres-in-WASM) exposes `.query(sql, params, options)` like\n // node-postgres and so also satisfies `isPgNativeClient` — but it does NOT\n // accept the `{name, text, values}` named-statement config form. Passing\n // that object doesn't merely fail the call: it desyncs PGlite's single\n // wire connection, so every subsequent query errors with `08P01`. Detect\n // PGlite structurally via `dumpDataDir` (a PGlite-specific method absent on\n // pg `Pool`/`Client`) so `resolvePgClient` can route it to the unnamed\n // positional wrapper regardless of `prepareStatements`. Duck-typed with no\n // static import, keeping this module dependency-free and edge-safe.\n return (\n typeof candidate === \"object\" &&\n hasFunctionProperty(candidate, \"query\") &&\n hasFunctionProperty(candidate, \"dumpDataDir\")\n );\n}\n\n/**\n * PGlite 0.5.x serializes the wire-protocol parameter count as a signed\n * 16-bit integer. At 32,768 binds it silently returns no rows and leaves the\n * client returning false-empty results, so the advertised budget must stay at\n * the largest signed 16-bit value.\n */\nexport const PGLITE_MAX_BIND_PARAMETERS = 32_767;\n\n/** Returns the PGlite client that owns a root Drizzle database, if present. */\nexport function getPgliteClient(db: AnyPgDatabase): object | undefined {\n const client = (db as PgClientCarrier).$client;\n return isPgliteClient(client) ? client : undefined;\n}\n\n/** Detects a root Drizzle database backed by PGlite without importing it. */\nexport function isPgliteDatabase(db: AnyPgDatabase): boolean {\n return getPgliteClient(db) !== undefined;\n}\n\nfunction transactionSession(\n carrier: PgClientCarrier,\n): PgSessionCarrier | undefined {\n return carrier.session ?? carrier._?.session;\n}\n\nfunction hasPgliteSession(carrier: PgClientCarrier): boolean {\n return transactionSession(carrier)?.constructor?.name === \"PgliteSession\";\n}\n\n/**\n * Single owner of \"this callable client is postgres-js\". Shared with the\n * serialized-resource detection in `../postgres.ts`, which reads `options.max`\n * off the same client shape, so the fast path and the marking predicate cannot\n * drift about which callables are postgres-js.\n */\nexport function isPostgresJsClient(\n candidate: unknown,\n): candidate is PostgresJsClient {\n // postgres-js's tagged-template Sql is callable, has `.unsafe` (raw\n // parameterized executor), and has `.begin` (transaction starter). The\n // transaction-scoped `TransactionSql` replaces `.begin` with `.savepoint`;\n // accept either so a Drizzle transaction keeps the fast path pinned.\n // Neon HTTP is also callable + has `.unsafe`, but that `.unsafe` is a\n // fragment builder rather than a query executor, so we discriminate\n // on `.begin` / `.savepoint` (postgres-js only).\n return (\n typeof candidate === \"function\" &&\n hasFunctionProperty(candidate, \"unsafe\") &&\n (hasFunctionProperty(candidate, \"begin\") ||\n hasFunctionProperty(candidate, \"savepoint\"))\n );\n}\n\n/**\n * @neondatabase/serverless's `neon(url)` HTTP-only tagged-template\n * function. Distinguishing markers vs postgres-js: `.transaction`\n * (an HTTP-batch transaction submitter) instead of `.begin`. Its\n * `.query`/`.unsafe` methods have different signatures from pg's, so\n * the fast path can't drive them safely — Drizzle's neon-http session\n * handles them correctly via the `db.execute` slow path.\n *\n * Exported so the backend factory can auto-disable the `transactions`\n * capability when this driver is detected (HTTP can't hold a session,\n * so multi-statement transactions are not available regardless).\n */\nexport function isNeonHttpClient(db: AnyPgDatabase): boolean {\n const candidate = (db as PgClientCarrier).$client;\n return (\n typeof candidate === \"function\" &&\n hasFunctionProperty(candidate, \"transaction\") &&\n !hasFunctionProperty(candidate, \"begin\")\n );\n}\n\n/**\n * Default cap on the number of distinct SQL strings tracked for\n * server-side prepared statements. Mirrors the SQLite adapter's\n * `DEFAULT_PREPARED_STATEMENT_CACHE_MAX`. High-cardinality SQL text —\n * variable-length IN-list expansions, generated aliases, custom\n * `backend.execute()` calls — would otherwise grow this map (and the\n * matching per-session prepared-statement memory inside PostgreSQL)\n * without bound.\n */\nconst DEFAULT_POSTGRES_STATEMENT_CACHE_MAX = 256;\n\n/**\n * Module-scope cache mapping each unique SQL text to a stable\n * prepared-statement name. PostgreSQL only requires statement names to\n * be unique per session, so a monotonic counter is sufficient — and\n * avoids depending on a hash primitive (`node:crypto` doesn't exist on\n * Cloudflare Workers, Web Crypto's digest is async).\n *\n * The cache is module-scope on purpose: pg `Pool` reuses connections,\n * and the same SQL text needs the same statement name across every\n * adapter that might end up driving the same connection. Without\n * shared naming, two adapters could try to register two different\n * statements under the same name on a recycled connection.\n *\n * Bounded by `cacheMax` per call (LRU eviction). The counter is\n * deliberately independent of the cache size so eviction never\n * recycles a name — a recycled name could collide with a still-cached\n * statement on a long-lived pg connection (\"prepared statement\n * already exists\" error with different text).\n */\nconst STATEMENT_NAME_CACHE = new Map<string, string>();\nlet nextStatementId = 0;\n\nfunction statementNameFor(sqlText: string, cacheMax: number): string {\n return getOrCreateLru(STATEMENT_NAME_CACHE, sqlText, cacheMax, () => {\n const name = `tg_${nextStatementId}`;\n nextStatementId += 1;\n return name;\n });\n}\n\n/**\n * Test-only: reset the module-scope statement-name state. Used to\n * isolate tests that assert on counter values or eviction behavior.\n */\nexport function resetStatementNameCacheForTests(): void {\n STATEMENT_NAME_CACHE.clear();\n nextStatementId = 0;\n}\n\n/**\n * Walks a row and replaces any `Date` instance with its ISO-string\n * equivalent. Used to normalize node-postgres / neon-serverless output\n * when we bypass Drizzle's session: pg's default type parsers return\n * `Date` objects for `timestamptz` / `timestamp` / `date` columns, but\n * TypeGraph's row contract everywhere downstream is \"timestamps come\n * back as ISO strings.\" Drizzle's session installs a per-query type\n * override that does the same thing; this is the dependency-free,\n * edge-safe equivalent.\n *\n * O(columns × rows) — negligible for the row counts TypeGraph queries\n * return (typical: 1–100 rows × 5–30 columns).\n */\nfunction normalizeRow(row: unknown): unknown {\n if (row === null || typeof row !== \"object\") return row;\n let mutated: Record<string, unknown> | undefined;\n for (const key of Object.keys(row)) {\n const value = (row as Record<string, unknown>)[key];\n if (value instanceof Date) {\n mutated ??= { ...(row as Record<string, unknown>) };\n mutated[key] = value.toISOString();\n }\n }\n return mutated ?? row;\n}\n\nfunction normalizeRows(rows: readonly unknown[]): readonly unknown[] {\n // Single-pass scan; only allocate a new array if any row contained a\n // Date that needed normalizing. Most rows on most queries don't.\n let mutated: unknown[] | undefined;\n for (let index = 0; index < rows.length; index += 1) {\n const original = rows[index];\n const normalized = normalizeRow(original);\n if (normalized !== original) {\n mutated ??= [...rows] as unknown[];\n mutated[index] = normalized;\n }\n }\n return mutated ?? rows;\n}\n\n/**\n * Wraps a node-postgres / neon-serverless client so every call goes\n * through a server-side prepared statement keyed by a stable name. The\n * first call on each connection parses + plans + executes; subsequent\n * calls with the same statement name reuse the cached plan and skip\n * both parse and plan phases. Measurable on multi-CTE TypeGraph\n * queries: 3-hop drops from ~7-12ms (parse + plan + execute every call)\n * to ~0.8ms median (execute only).\n *\n * Returned rows are normalized so that `Date` objects from default pg\n * type parsers become ISO strings, matching the row shape Drizzle's\n * session would produce. Without this, `ctx.<alias>.meta.createdAt`\n * style accessors in the SELECT-result path return Date instances,\n * breaking user code that expects strings.\n */\nfunction wrapNodePgClient(\n client: NodePgClient,\n cacheMax: number,\n): PgQueryClient {\n return {\n async query(\n sqlText: string,\n params: readonly unknown[],\n ): Promise<PgQueryResult> {\n const result = await client.query({\n name: statementNameFor(sqlText, cacheMax),\n text: sqlText,\n values: params,\n });\n return { rows: normalizeRows(result.rows) };\n },\n async queryUnnamed(\n sqlText: string,\n params: readonly unknown[],\n ): Promise<PgQueryResult> {\n const result = await client.query(sqlText, params);\n return { rows: normalizeRows(result.rows) };\n },\n };\n}\n\n/**\n * Variant that bypasses server-side prepared statements entirely.\n * Required for pgbouncer in transaction-pool mode (named statements\n * registered on one backend connection aren't visible on the next),\n * and useful when memory-sensitive workloads can't afford to keep\n * prepared statements warm across the pool.\n *\n * Same Date→ISO normalization as `wrapNodePgClient` so the row contract\n * downstream stays identical.\n */\nfunction wrapNodePgClientUnnamed(client: NodePgClient): PgQueryClient {\n async function queryUnnamed(\n sqlText: string,\n params: readonly unknown[],\n ): Promise<PgQueryResult> {\n const result = await client.query(sqlText, params);\n return { rows: normalizeRows(result.rows) };\n }\n return {\n query: queryUnnamed,\n queryUnnamed,\n };\n}\n\nfunction adaptPostgresJsClient(sql: PostgresJsClient): PgQueryClient {\n async function query(\n sqlText: string,\n params: readonly unknown[],\n ): Promise<PgQueryResult> {\n // postgres-js handles its own statement preparation internally\n // (controlled by the `prepare` connection option, default true),\n // so we don't need to name statements here ourselves.\n const rows = await sql.unsafe(sqlText, params);\n return { rows };\n }\n return {\n query,\n async queryUnnamed(\n sqlText: string,\n params: readonly unknown[],\n ): Promise<PgQueryResult> {\n // Per-call opt-out of postgres-js's internal preparation\n // (verified: `unsafe(text, params, { prepare: false })` leaves\n // pg_prepared_statements empty), so custom-plan-preferring\n // statements are re-planned against their actual parameters on\n // every call — same contract as the node-postgres unnamed path.\n const rows = await sql.unsafe(sqlText, params, { prepare: false });\n return { rows };\n },\n };\n}\n\n/**\n * Resolves a Drizzle-wrapped PostgreSQL client to a uniform `{query}` shape\n * that the fast path can call. Supports:\n *\n * - `drizzle-orm/node-postgres` (pg Pool / Client) — wrapped to use\n * server-side prepared statements with stable counter-derived names\n * keyed by the SQL text (see `statementNameFor`). When\n * `prepareStatements` is `false`, falls back to unnamed\n * `client.query(text, values)` for pgbouncer transaction-pool\n * compatibility.\n * - `drizzle-orm/neon-serverless` (@neondatabase/serverless Pool) —\n * pg-Pool-compatible, takes the same wrapper as node-postgres\n * - `drizzle-orm/postgres-js` (postgres-js tagged-template Sql) — adapted\n * via `.unsafe(sql, params)`. Safe because Drizzle installs transparent\n * parsers on the same client instance at `drizzle()` time, so direct\n * calls and Drizzle-routed calls produce identical row shapes.\n * - `drizzle-orm/pglite` (PGlite, Postgres-in-WASM) — routed to the unnamed\n * wrapper unconditionally. PGlite's `.query` has no named-statement config\n * form (and server-side prepared statements buy nothing for an in-process\n * engine), so `prepareStatements` is ignored for it.\n *\n * Returns `undefined` for `drizzle-orm/neon-http` and any other driver we\n * don't recognize; callers fall back to `db.execute(sql)`, which goes\n * through the Drizzle session and is always correct (just without the\n * server-side prepared-statement perf win).\n */\nfunction resolvePgClient(\n db: AnyPgDatabase,\n prepareStatements: boolean,\n cacheMax: number,\n useTransactionClient: boolean,\n): PgQueryClient | undefined {\n // Order matters: neon-http and postgres-js are both callable + have\n // `.unsafe`, but neon-http's `.unsafe` is a fragment builder (not a\n // query executor) and its `.query` doesn't accept the {name, text,\n // values} config form. Skip the fast path entirely for neon-http and\n // let Drizzle's session route the call.\n if (isNeonHttpClient(db)) {\n return undefined;\n }\n const carrier = db as PgClientCarrier;\n // Top-level Drizzle databases expose `$client`. Transaction objects do not;\n // they retain the exact pinned pool/client transaction on `session.client`.\n // Reading that structural internal is what keeps trusted import on the same\n // connection that will COMMIT/ROLLBACK, instead of accidentally using the\n // outer pool while a transaction is open.\n const client =\n carrier.$client ??\n (useTransactionClient ? transactionSession(carrier)?.client : undefined);\n // Must precede `isPgNativeClient`: PGlite matches it too (object with\n // `.query`), but only the unnamed wrapper is safe for it (see\n // `isPgliteClient`).\n if (\n isPgliteClient(client) ||\n (useTransactionClient && hasPgliteSession(carrier))\n ) {\n if (!isPgNativeClient(client)) return undefined;\n return wrapNodePgClientUnnamed(client);\n }\n if (isPgNativeClient(client)) {\n return prepareStatements ?\n wrapNodePgClient(client, cacheMax)\n : wrapNodePgClientUnnamed(client);\n }\n if (isPostgresJsClient(client)) {\n // postgres-js handles its own preparation internally (controlled\n // by the driver's own `prepare` connection option) — the\n // `prepareStatements` flag here only affects the node-postgres\n // path.\n return adaptPostgresJsClient(client);\n }\n return undefined;\n}\n\n/**\n * Normalizes the result shape of `db.execute(sql)` across drivers.\n *\n * - `drizzle-orm/node-postgres` / `drizzle-orm/neon-serverless` return a\n * pg-style `{ rows, rowCount, ... }` object.\n * - `drizzle-orm/postgres-js` returns the raw postgres-js result, which is\n * a plain array of rows (with extra non-enumerable properties like\n * `count` / `command`).\n *\n * The backend contract is \"a row array.\" Normalize here so every caller\n * downstream can assume the same shape.\n */\nasync function executeDrizzleQuery<TRow>(\n db: AnyPgDatabase,\n query: DrizzleSql,\n): Promise<readonly TRow[]> {\n const result = await db.execute(query);\n if (Array.isArray(result)) {\n return result as readonly TRow[];\n }\n return (result as Readonly<{ rows: readonly TRow[] }>).rows;\n}\n\nfunction createPgPreparedStatement(\n pgClient: PgQueryClient,\n sqlText: string,\n maxBindParameters: number | undefined,\n): PreparedSqlStatement {\n return {\n async execute<TRow>(params: readonly unknown[]): Promise<readonly TRow[]> {\n assertWithinBindParameterLimit(params.length, maxBindParameters);\n const result = await pgClient.query(sqlText, params);\n return result.rows as readonly TRow[];\n },\n };\n}\n\n/**\n * Tuning options for the PostgreSQL execution fast path.\n *\n * Defaults are correct for `drizzle-orm/node-postgres` against a\n * standalone PostgreSQL or session-pooled deployment. Override when:\n *\n * - **Pooling through pgbouncer in transaction-pool mode.** Set\n * `prepareStatements: false`. Named statements registered on one\n * pooled backend connection aren't visible to the next, so the\n * server-side prepared-statement cache must be off.\n * - **High-cardinality SQL text.** If the application emits many\n * distinct compiled SQL strings (variable-length IN-list expansions,\n * custom `backend.execute()` calls, generated aliases), tune\n * `preparedStatementCacheMax` down to bound per-session memory more\n * aggressively, or up if memory is plentiful and you want fewer\n * re-PREPAREs.\n */\nexport type PostgresExecutionAdapterOptions = Readonly<{\n /**\n * When `true` (default), node-postgres / neon-serverless calls go\n * through `client.query({name, text, values})` so PostgreSQL caches\n * the parsed/planned statement per session. Set to `false` to issue\n * unnamed `client.query(text, values)` calls — required for\n * pgbouncer transaction-pool mode.\n */\n prepareStatements?: boolean;\n /**\n * Maximum number of distinct SQL strings tracked for prepared-\n * statement naming. Defaults to `DEFAULT_POSTGRES_STATEMENT_CACHE_MAX`\n * (256). Ignored when `prepareStatements` is `false`.\n */\n preparedStatementCacheMax?: number;\n /**\n * Maximum parameters that one statement may dispatch. Backend factories\n * pass their normalized capability here so every execution surface has a\n * final fail-loud guard after batch sizing.\n */\n maxBindParameters?: number;\n /**\n * @internal Resolve Drizzle's pinned transaction client. Trusted import uses\n * this on its private adapter; ordinary transaction backends deliberately do\n * not expose a new raw-execution surface that would change routing behavior.\n */\n useTransactionClient?: boolean;\n}>;\n\nexport function createPostgresExecutionAdapter(\n db: AnyPgDatabase,\n options: PostgresExecutionAdapterOptions = {},\n): PostgresExecutionAdapter {\n const prepareStatements = options.prepareStatements ?? true;\n const cacheMax =\n options.preparedStatementCacheMax ?? DEFAULT_POSTGRES_STATEMENT_CACHE_MAX;\n const maxBindParameters = options.maxBindParameters;\n const pgClient = resolvePgClient(\n db,\n prepareStatements,\n cacheMax,\n options.useTransactionClient ?? false,\n );\n\n function compile(query: ExecutableSql): CompiledSqlQuery {\n return compileQueryWithDialect(db, query, \"PostgreSQL\");\n }\n\n function assertCompiledWithinBindParameterLimit(\n compiledQuery: CompiledSqlQuery,\n ): void {\n assertWithinBindParameterLimit(\n compiledQuery.params.length,\n maxBindParameters,\n );\n }\n\n if (pgClient === undefined) {\n return {\n compile,\n async execute<TRow>(query: ExecutableSql): Promise<readonly TRow[]> {\n assertCompiledWithinBindParameterLimit(compile(query));\n return executeDrizzleQuery<TRow>(\n db,\n isSqlFragment(query) ? toDrizzleSql(query, \"postgres\") : query,\n );\n },\n };\n }\n\n const pgQueryClient = pgClient;\n\n async function executeCompiled<TRow>(\n compiledQuery: CompiledSqlQuery,\n ): Promise<readonly TRow[]> {\n assertCompiledWithinBindParameterLimit(compiledQuery);\n const result = await pgQueryClient.query(\n compiledQuery.sql,\n compiledQuery.params,\n );\n return result.rows as readonly TRow[];\n }\n\n return {\n compile,\n async execute<TRow>(query: ExecutableSql): Promise<readonly TRow[]> {\n // Fast path: compile via Drizzle's dialect, then execute through\n // the wrapped client directly. Bypasses Drizzle's session\n // overhead (logging spans, plan-cache bookkeeping for typed\n // queries we don't use), and on node-postgres this also enables\n // the server-side prepared-statement path because the wrapped\n // client assigns each unique SQL a stable statement name.\n const compiled = compile(query);\n assertCompiledWithinBindParameterLimit(compiled);\n if (isSqlFragment(query) && shouldForceCustomPlan(query)) {\n const result = await pgQueryClient.queryUnnamed(\n compiled.sql,\n compiled.params,\n );\n return result.rows as readonly TRow[];\n }\n return executeCompiled<TRow>(compiled);\n },\n executeCompiled,\n prepare(sqlText: string): PreparedSqlStatement {\n return createPgPreparedStatement(\n pgQueryClient,\n sqlText,\n maxBindParameters,\n );\n },\n };\n}\n\nfunction assertWithinBindParameterLimit(\n parameterCount: number,\n maxBindParameters: number | undefined,\n): void {\n if (maxBindParameters === undefined || parameterCount <= maxBindParameters) {\n return;\n }\n throw new ConfigurationError(\n `PostgreSQL statement uses ${parameterCount} bound parameters, exceeding ` +\n `this backend's limit of ${maxBindParameters}.`,\n {\n capability: \"maxBindParameters\",\n maxBindParameters,\n parameterCount,\n },\n {\n suggestion:\n \"Split the operation into smaller batches or lower the batch size before retrying.\",\n },\n );\n}\n","/**\n * Per-connection statement serialization for transaction-scoped backends.\n *\n * A pooled backend hands every statement its own connection, so concurrent\n * work is genuinely concurrent. A transaction is the opposite: every\n * statement shares one pinned connection, and the PostgreSQL wire protocol\n * has no request pipelining a driver could use to keep two in flight. Drivers\n * paper over this with an internal queue — node-postgres queues on\n * `Client._queryQueue` — but that queue is deprecated as of `pg@8.22` and is\n * removed in `pg@9`:\n *\n * > Calling client.query() when the client is already executing a query is\n * > deprecated and will be removed in pg@9.0. Use async/await or an external\n * > async flow control mechanism instead.\n *\n * TypeGraph overlaps statements on a pinned connection by construction: the\n * node write pipeline issues embedding and fulltext sync concurrently, and\n * `store.transaction()` invites callers to `Promise.all` their writes. This\n * queue is the \"external async flow control mechanism\" the deprecation asks\n * for — it keeps the concurrency at the API surface while presenting exactly\n * one statement at a time to the connection.\n *\n * Wrapping is deliberately confined to transaction-scoped adapters. On a pool\n * the queue would serialize independent connections and destroy throughput.\n *\n * Edge-safe: no `node:*` imports (loaded on Workers via neon-serverless).\n */\nimport { TransactionClosedError } from \"../../../errors\";\nimport {\n type CompiledSqlQuery,\n type ExecutableSql,\n type PreparedSqlStatement,\n type SqlExecutionAdapter,\n} from \"./types\";\n\n/**\n * A {@link SqlExecutionAdapter} that runs one statement at a time and can be\n * shut so that late statements never reach the connection.\n */\nexport type SerialExecutionAdapter = SqlExecutionAdapter &\n Readonly<{\n runExclusive: NonNullable<SqlExecutionAdapter[\"runExclusive\"]>;\n /**\n * Waits for the statement currently on the wire, then refuses every\n * later one with a {@link TransactionClosedError}.\n *\n * Callers invoke this at the transaction boundary, before the driver\n * emits `COMMIT` / `ROLLBACK` on the same connection. The driver's control\n * statement does not travel through this queue, so without the drain it\n * would overlap a live statement; without the close, a statement the\n * callback left running could land after the pool reclaimed the\n * connection — inside an unrelated transaction.\n *\n * Idempotent.\n */\n drainAndClose: () => Promise<void>;\n }>;\n\ntype StatementQueue = Readonly<{\n /** Runs tasks one at a time, in the order they were submitted. */\n enqueue: <T>(task: () => Promise<T>) => Promise<T>;\n drainAndClose: () => Promise<void>;\n}>;\n\n/**\n * Swallows a statement's outcome so the queue's tail always fulfills. The\n * caller owns the result promise; the tail only tracks completion, and an\n * untouched rejection here would surface as an unhandled rejection.\n */\nfunction ignoreOutcome(): void {\n // Intentionally empty: see above.\n}\n\nfunction createStatementQueue(): StatementQueue {\n // Always fulfilled: a failed statement must not strand its successors, and\n // an untouched rejection here would surface as an unhandled rejection.\n let tail: Promise<void> = Promise.resolve();\n let closed = false;\n\n return {\n enqueue<T>(task: () => Promise<T>): Promise<T> {\n if (closed) return Promise.reject(new TransactionClosedError());\n // Chained synchronously, so queue order is submission order.\n const result = tail.then(() => task());\n tail = result.then(ignoreOutcome, ignoreOutcome);\n return result;\n },\n\n async drainAndClose(): Promise<void> {\n // Close first: a statement whose continuation enqueues a successor must\n // find the queue already shut, or it would slip in behind the drain.\n closed = true;\n await tail;\n },\n };\n}\n\n/**\n * Wraps `adapter` so at most one statement is in flight on its connection.\n *\n * Only the I/O members are queued. `compile` is pure — it renders a Drizzle\n * `SQL` to text and params without touching the connection — so it stays\n * synchronous and unqueued.\n *\n * The queue is a leaf: nothing it runs re-enters it, so a queued statement\n * can never wait on a statement queued behind it.\n */\nexport function createSerialExecutionAdapter(\n adapter: SqlExecutionAdapter,\n): SerialExecutionAdapter {\n const { enqueue, drainAndClose } = createStatementQueue();\n const { executeCompiled, prepare } = adapter;\n\n return {\n drainAndClose,\n\n compile(query: ExecutableSql): CompiledSqlQuery {\n return adapter.compile(query);\n },\n\n execute<TRow>(query: ExecutableSql): Promise<readonly TRow[]> {\n return enqueue(() => adapter.execute<TRow>(query));\n },\n\n runExclusive<T>(\n critical: (connection: SqlExecutionAdapter) => Promise<T>,\n ): Promise<T> {\n // One queue slot for the whole group. `critical` receives the UNQUEUED\n // adapter: re-entering the queue from inside the slot it already holds\n // would deadlock, and it needs no serializing anyway — nothing else can\n // reach the connection until the slot is released.\n return enqueue(() => critical(adapter));\n },\n\n ...(executeCompiled === undefined ?\n {}\n : {\n executeCompiled<TRow>(\n compiledQuery: CompiledSqlQuery,\n ): Promise<readonly TRow[]> {\n return enqueue(() => executeCompiled<TRow>(compiledQuery));\n },\n }),\n\n ...(prepare === undefined ?\n {}\n : {\n prepare(sqlText: string): PreparedSqlStatement {\n const statement = prepare(sqlText);\n return {\n execute<TRow>(\n params: readonly unknown[],\n ): Promise<readonly TRow[]> {\n return enqueue(() => statement.execute<TRow>(params));\n },\n };\n },\n }),\n };\n}\n","/**\n * PostgreSQL backend adapter for TypeGraph.\n *\n * Works with any Drizzle PostgreSQL database instance. Tested against:\n * - `drizzle-orm/node-postgres` (pg Pool / Client)\n * - `drizzle-orm/postgres-js` (postgres-js tagged-template client)\n * - `drizzle-orm/neon-serverless` (@neondatabase/serverless Pool / Client)\n * - `drizzle-orm/neon-http` (@neondatabase/serverless `neon(url)`) —\n * transactions are auto-disabled because HTTP can't hold a session;\n * use `drizzle-orm/neon-serverless` if you need transactional writes.\n *\n * - `drizzle-orm/pglite` (PGlite, Postgres-in-WASM) — the execution\n * fast path detects PGlite and routes it correctly (its `.query` has no\n * named-statement form). For a batteries-included in-process setup, see\n * `createLocalPgliteBackend` in `@nicia-ai/typegraph/adapters/drizzle/postgres/pglite`.\n *\n * Other pg-protocol Drizzle adapters (Vercel Postgres, Supabase via pg)\n * work unchanged because they all expose a compatible `db.execute()` /\n * `db.transaction()` surface.\n *\n * @example\n * ```typescript\n * import { drizzle } from \"drizzle-orm/node-postgres\";\n * import { Pool } from \"pg\";\n * import { createPostgresBackend, tables } from \"@nicia-ai/typegraph/adapters/drizzle/postgres\";\n *\n * const pool = new Pool({ connectionString: process.env.DATABASE_URL });\n * const db = drizzle(pool);\n * const backend = createPostgresBackend(db, { tables });\n * ```\n */\nimport {\n and,\n eq,\n getTableName,\n inArray,\n isNull,\n type SQL,\n sql,\n} from \"drizzle-orm\";\nimport { PgTransaction } from \"drizzle-orm/pg-core\";\n\nimport {\n CompilerInvariantError,\n ConfigurationError,\n StaleVersionError,\n} from \"../../errors\";\nimport type { ResolvedSqlTableNames } from \"../../query/compiler/schema\";\nimport {\n buildFulltextCapabilities,\n type FulltextStrategy,\n tsvectorStrategy,\n} from \"../../query/dialect/fulltext-strategy\";\nimport {\n assertPgvectorEfSearch,\n pgvectorStrategy,\n} from \"../../query/dialect/vector/pgvector-strategy\";\nimport {\n assertVectorSearchLimit,\n buildVectorCapabilities,\n resolveEfSearchOverride,\n vectorSearchFrontierTuning,\n type VectorSlot,\n type VectorStrategy,\n} from \"../../query/dialect/vector-strategy\";\nimport {\n isSqlFragment,\n sql as portableSql,\n type SqlFragment,\n} from \"../../query/sql-fragment\";\nimport {\n annIndexScanTypes,\n type CompiledRowsSql,\n} from \"../../query/sql-intent\";\nimport { chunk as chunkArray } from \"../../utils/array\";\nimport { requireDefined } from \"../../utils/presence\";\nimport {\n isInsufficientResourcesError,\n isMissingTableError,\n isPostgresConcurrentDdlRaceError,\n} from \"../../utils/sql-errors\";\nimport { deriveBackend } from \"../derive-backend\";\nimport { FIND_EDGES_ENDPOINT_FIXED_PARAM_COUNT } from \"../edge-endpoint-sets\";\nimport { buildLiveNodeCandidates } from \"../live-node-candidates\";\nimport {\n coerceNumericScore,\n createEdgeRowMapper,\n createNodeRowMapper,\n createSchemaVersionRowMapper,\n createUniqueRowMapper,\n nowIso,\n POSTGRES_ROW_MAPPER_CONFIG,\n} from \"../row-mappers\";\nimport {\n auditBackendResource,\n resolveDeclaredBackendResource,\n type SerializedResourceDeclaration,\n} from \"../transaction-resource\";\nimport {\n type AdapterBackend,\n type BackendCapabilities,\n type ClaimIndexMaterializationParams,\n type CommitSchemaVersionIfKindsEmptyResult,\n type CommitSchemaVersionParams,\n type ContributionDiagnostic,\n type ContributionMaterializationIdentity,\n type ContributionMaterializationRow,\n type ContributionProbeEntry,\n type ContributionRebuildResult,\n type ContributionRebuildScope,\n type ContributionRepairResult,\n type ContributionRepopulationStats,\n type CreateVectorIndexParams,\n DATABASE_EXTENSION_NAMES,\n type DatabaseExtensionName,\n type DeleteEmbeddingParams,\n type DeleteFulltextBatchParams,\n type DeleteFulltextParams,\n type DropVectorIndexParams,\n type FulltextSearchParams,\n type FulltextSearchResult,\n type HybridSearchParams,\n type HybridSearchRow,\n type IdentityTableNames,\n type IndexMaterializationRow,\n INTERNAL_TEMPORARY_WRITES,\n type InternalTransactionOptions,\n type KindRemovalRow,\n type LockSchemaVersionForWriteParams,\n normalizeGraphAnalyticsCapabilities,\n POSTGRES_CAPABILITIES,\n POSTGRES_MAX_BIND_PARAMETERS,\n type RecordContributionMaterializationParams,\n type RecordIndexMaterializationParams,\n type RecordKindRemovalParams,\n type ReleaseIndexMaterializationClaimParams,\n type SchemaKindEmptinessProbe,\n type SchemaVersionRow,\n type SchemaWriteTransactionBackend,\n type SetActiveVersionParams,\n type TransactionBackend,\n type TrustedImportOptions,\n type TrustedImportSession,\n type UpsertEmbeddingBatchParams,\n type UpsertEmbeddingParams,\n type UpsertFulltextBatchParams,\n type UpsertFulltextParams,\n type VectorSearchParams,\n type VectorSearchResult,\n} from \"../types\";\nimport {\n buildContributionInsertValues,\n buildContributionOnConflictSet,\n type ContributionMaterializer,\n contributionRebuildSupported,\n createContributionMaterializer,\n gateFulltext,\n gateFulltextMethods,\n mapContributionMaterializationRow,\n POSTGRES_CONTRIBUTION_MAT_TIMESTAMPS,\n} from \"./contribution-materializations\";\nimport {\n generatePgCreateTableSQL,\n generatePostgresDDL,\n postgresContributions,\n} from \"./ddl\";\nimport {\n type AnyPgDatabase,\n type AnyPgTransaction,\n createPostgresExecutionAdapter,\n getPgliteClient,\n hasFunctionProperty,\n isNeonHttpClient,\n isPgliteDatabase,\n isPostgresJsClient,\n PGLITE_MAX_BIND_PARAMETERS,\n type PostgresExecutionAdapter,\n type PostgresExecutionAdapterOptions,\n} from \"./execution/postgres-execution\";\nimport { createSerialExecutionAdapter } from \"./execution/statement-queue\";\nimport { type ExecutableSql, toDrizzleSql } from \"./execution/types\";\nimport {\n buildMaterializationInsertValues,\n buildMaterializationOnConflictSet,\n mapMaterializationRow,\n POSTGRES_INDEX_MAT_TIMESTAMPS,\n} from \"./index-materializations\";\nimport {\n buildKindRemovalInsertValues,\n buildKindRemovalOnConflictSet,\n mapKindRemovalRow,\n POSTGRES_KIND_REMOVAL_TIMESTAMPS,\n} from \"./kind-removals\";\nimport {\n assertActiveSchemaVersion,\n assertAdoptedDialect,\n commitSchemaVersionIfKindsEmpty,\n createCommonOperationBackend,\n type InternalOperationBackend,\n} from \"./operation-backend-core\";\nimport { mapHybridSearchRow } from \"./operations/hybrid\";\nimport {\n createCachedTableExistence,\n createPostgresOperationStrategy,\n tableExistsFromRow,\n} from \"./operations/strategy\";\nimport {\n createPostgresTables as buildPostgresTables,\n type PostgresTables,\n tables as defaultTables,\n} from \"./schema/postgres\";\nimport {\n analyzeImportedTables,\n assertTrustedImportDatabaseEmpty,\n createPostgresTrustedImportSession,\n lockPostgresTrustedImportTables,\n restoreSecondaryIndexes,\n suspendPostgresSecondaryIndexes,\n} from \"./trusted-import\";\nimport {\n EMBEDDING_UPSERT_PARAM_COUNT,\n mapVectorWriteError,\n vectorSlotFromCreateIndexParams,\n vectorSlotFromDropIndexParams,\n vectorSlotFromParams,\n} from \"./vector-runtime\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Options for creating a PostgreSQL backend.\n */\nexport type PostgresBackendOptions = Readonly<{\n /**\n * Custom table definitions. Use createPostgresTables() to customize table names.\n * Defaults to standard TypeGraph table names.\n */\n tables?: PostgresTables;\n /**\n * Fulltext strategy override. Defaults to `tsvectorStrategy`\n * (Postgres built-in `tsvector` + GIN). Pass a custom strategy here to\n * swap the entire fulltext stack — DDL, MATCH condition, rank\n * expression, and snippet generation — for alternate Postgres\n * backends like ParadeDB (`pg_search`), pg_trgm similarity, or\n * pgroonga without forking TypeGraph.\n */\n fulltext?: FulltextStrategy;\n /**\n * Vector strategy override. Defaults to `pgvectorStrategy` (pgvector's\n * `vector(N)` columns + HNSW/IVFFlat). The strategy owns per-`(kind,\n * field)` typed storage — DDL, upsert, delete, similarity search, and\n * ANN index lifecycle — and advertises `strategy.capabilities` as\n * `capabilities.vector`. Pass a custom strategy to swap the entire\n * vector stack for an alternate Postgres extension without forking\n * TypeGraph.\n *\n * Pass `false` to disable vector support entirely. The backend then\n * advertises no `capabilities.vector` and omits the embedding/search\n * methods, mirroring a SQLite connection without sqlite-vec. Required\n * for an in-process Postgres (e.g. PGlite) built without the pgvector\n * extension: the default `pgvectorStrategy` assumes `vector(N)` exists,\n * so any embedding write or `CREATE EXTENSION vector` would otherwise\n * hard-fail at runtime.\n */\n vector?: VectorStrategy | false;\n /**\n * Override specific backend capabilities. Useful when the underlying\n * driver doesn't support a feature TypeGraph would otherwise assume —\n * for example, an HTTP-only Postgres driver that can't hold a session\n * across statements would need `{ transactions: false }` so\n * TypeGraph falls through to non-transactional execution paths.\n *\n * `drizzle-orm/neon-http` is auto-detected and has `transactions`\n * disabled without an explicit override; this option exists for\n * other HTTP-style drivers and for tests that need to simulate a\n * capability gap.\n */\n capabilities?: Partial<BackendCapabilities>;\n /**\n * Use server-side prepared statements (named statements cached per\n * pg connection) on the node-postgres / neon-serverless fast path.\n * Defaults to `true`. Set to `false` when pooling through pgbouncer\n * in transaction-pool mode — pgbouncer routes successive statements\n * over different backend connections, and a `name` registered on one\n * is invisible on the next.\n *\n * No effect on `drizzle-orm/postgres-js` (handles preparation\n * internally) or `drizzle-orm/neon-http` (no fast path).\n */\n prepareStatements?: boolean;\n /**\n * Cap on the number of distinct SQL strings tracked for\n * prepared-statement naming. Defaults to 256. The cache is LRU-\n * bounded so high-cardinality SQL text (variable-length IN-lists,\n * generated aliases, `backend.execute()` calls with one-off SQL)\n * doesn't grow unbounded in either the Node process or in\n * PostgreSQL's per-session prepared-statement memory. Worst-case\n * server-side footprint is roughly `cap × pool size` statements\n * across all pooled connections. Ignored when\n * `prepareStatements` is `false`.\n */\n preparedStatementCacheMax?: number;\n /**\n * Declare the connection this backend serializes every statement onto, when\n * TypeGraph's driver predicates cannot see it (Bun `SQL` at `{ max: 1 }`,\n * `pg-proxy`, a postgres-js client capped through a non-numeric string the\n * driver does not coerce) — or declare that it serializes on nothing, when\n * detection is wrong for your topology.\n *\n * Defaults to `{ mode: \"detect\" }`. See\n * {@link SerializedResourceDeclaration} for what each mode means and for the\n * one refusal it cannot lift (`same-sqlite-backend`, which is SQLite-only and\n * therefore never reached from here).\n */\n serializedResource?: SerializedResourceDeclaration;\n}>;\n\nconst NODE_INSERT_PARAM_COUNT = 9;\nconst EDGE_INSERT_PARAM_COUNT = 12;\nconst GET_NODES_FIXED_PARAM_COUNT = 2;\nconst GET_EDGES_FIXED_PARAM_COUNT = 1;\nconst FULLTEXT_UPSERT_PARAM_COUNT = 6;\nconst FULLTEXT_DELETE_FIXED_PARAM_COUNT = 2;\nconst CHECK_UNIQUE_BATCH_FIXED_PARAM_COUNT = 3;\nconst UNIQUE_DELETE_FIXED_PARAM_COUNT = 2;\nconst UNIQUE_INSERT_PARAM_COUNT = 6;\n\ntype PostgresBatchChunkSizes = Readonly<{\n checkUniqueBatchChunkSize: number;\n edgeInsertBatchSize: number;\n embeddingUpsertBatchSize: number;\n findEdgesEndpointChunkSize: number;\n fulltextDeleteChunkSize: number;\n fulltextUpsertBatchSize: number;\n getEdgesChunkSize: number;\n getNodesChunkSize: number;\n nodeInsertBatchSize: number;\n uniqueDeleteChunkSize: number;\n uniqueInsertBatchSize: number;\n}>;\n\nfunction computePostgresBatchChunkSizes(\n maxBindParameters: number,\n): PostgresBatchChunkSizes {\n return {\n checkUniqueBatchChunkSize: Math.max(\n 1,\n maxBindParameters - CHECK_UNIQUE_BATCH_FIXED_PARAM_COUNT,\n ),\n edgeInsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / EDGE_INSERT_PARAM_COUNT),\n ),\n embeddingUpsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / EMBEDDING_UPSERT_PARAM_COUNT),\n ),\n findEdgesEndpointChunkSize: Math.max(\n 1,\n maxBindParameters - FIND_EDGES_ENDPOINT_FIXED_PARAM_COUNT,\n ),\n fulltextDeleteChunkSize: Math.max(\n 1,\n maxBindParameters - FULLTEXT_DELETE_FIXED_PARAM_COUNT,\n ),\n fulltextUpsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / FULLTEXT_UPSERT_PARAM_COUNT),\n ),\n getEdgesChunkSize: Math.max(\n 1,\n maxBindParameters - GET_EDGES_FIXED_PARAM_COUNT,\n ),\n getNodesChunkSize: Math.max(\n 1,\n maxBindParameters - GET_NODES_FIXED_PARAM_COUNT,\n ),\n nodeInsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / NODE_INSERT_PARAM_COUNT),\n ),\n uniqueDeleteChunkSize: Math.max(\n 1,\n maxBindParameters - UNIQUE_DELETE_FIXED_PARAM_COUNT,\n ),\n uniqueInsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / UNIQUE_INSERT_PARAM_COUNT),\n ),\n };\n}\n\n/**\n * Barrel keys (contribution logical names) of the four relations that hold\n * Operational Identity state: current assertions, recorded-time assertions,\n * the derived closure, and the derived separation relation.\n * `ensureIdentityTables()` scopes its idempotent CREATE TABLE / CREATE INDEX\n * to exactly these when identity is first enabled on an existing database.\n */\nconst IDENTITY_TABLE_LOGICAL_NAMES: ReadonlySet<string> = new Set([\n \"identityAssertions\",\n \"recordedIdentityAssertions\",\n \"identityClosure\",\n \"identitySeparation\",\n]);\n\n/**\n * THE one-shot retry every idempotent catalog write in this backend shares.\n *\n * PostgreSQL's IF NOT EXISTS check cannot see another session's uncommitted\n * catalog row. The loser waits for the winner and is then handed the winner's\n * conflict instead of a harmless notice; retrying after that wait observes the\n * committed object. Which failures mean that is\n * {@link isPostgresConcurrentDdlRaceError}'s single decision — anything else\n * (and anything the retry cannot clear) stays loud.\n *\n * Takes a thunk rather than a statement because one caller — the extension\n * install — runs its statement inside its own transaction, and the retry\n * decision must be the same one whether the unit of work is one statement or a\n * locked pair.\n */\nasync function withConcurrentCreateRetry<T>(run: () => Promise<T>): Promise<T> {\n try {\n return await run();\n } catch (error) {\n if (!isPostgresConcurrentDdlRaceError(error)) throw error;\n return await run();\n }\n}\n\n/**\n * The advisory-lock key an extension install serializes on.\n *\n * Per extension rather than one global key: the fence exists to stop two\n * installers of the SAME catalog row from colliding, and a shared key would\n * additionally queue `vector` behind `pg_trgm` at boot for no benefit. The\n * names it interpolates are allowlisted before they reach here.\n */\nfunction extensionDdlLockKey(extension: DatabaseExtensionName): string {\n return `typegraph:extension-ddl:${extension}`;\n}\n\ntype ExecutePostgresStatement = (statement: ExecutableSql) => Promise<void>;\n\nfunction parallelWorkerResetSql(tableName: string): string {\n return `ALTER TABLE \"${tableName.replaceAll('\"', '\"\"')}\" RESET (parallel_workers);`;\n}\n\nfunction parallelWorkerResetError(\n tableName: string,\n resetError: unknown,\n): Error {\n return new Error(\n `PostgreSQL did not restore the durable parallel_workers setting on vector table ${JSON.stringify(tableName)}. Run ${parallelWorkerResetSql(tableName)} before retrying index materialization.`,\n { cause: resetError },\n );\n}\n\nfunction vectorSerialFallbackPreparationError(\n step: \"drop-index\" | \"disable-parallel-workers\",\n parallelBuildError: unknown,\n preparationError: unknown,\n): AggregateError {\n const action =\n step === \"drop-index\" ?\n \"drop the partial vector index\"\n : \"disable parallel workers for the serial retry\";\n return new AggregateError(\n [preparationError],\n `PostgreSQL could not ${action} after the parallel vector index build exhausted resources.`,\n { cause: parallelBuildError },\n );\n}\n\nfunction reportParallelWorkerResetFailure(\n tableName: string,\n resetError: unknown,\n): void {\n try {\n if (typeof console === \"undefined\" || typeof console.error !== \"function\") {\n return;\n }\n const reported = (console.error as (...data: readonly unknown[]) => unknown)(\n `[typegraph] The serial vector index rebuild failed and cleanup also failed. ${parallelWorkerResetError(tableName, resetError).message}`,\n resetError,\n );\n void Promise.resolve(reported).catch(() => {\n // Reporting must not displace the index-build failure.\n });\n } catch {\n // A hostile or replaced logger cannot displace the index-build failure.\n }\n}\n\nasync function resetVectorParallelWorkers(\n execute: ExecutePostgresStatement,\n tableName: string,\n): Promise<void> {\n try {\n await execute(\n portableSql`ALTER TABLE ${portableSql.identifier(tableName)} RESET (parallel_workers)`,\n );\n } catch (resetError) {\n throw parallelWorkerResetError(tableName, resetError);\n }\n}\n\n/** @internal */\nexport async function runVectorIndexBuildWithSerialFallback(\n execute: ExecutePostgresStatement,\n tableName: string,\n indexStatement: ExecutableSql,\n dropStatement?: ExecutableSql,\n): Promise<void> {\n // The strategy table is TypeGraph-owned, and parallel_workers is only set\n // temporarily by the fallback below. Reset it before every materialization\n // attempt so cleanup survives backend and process recreation. Keep this\n // outside the resource-failure catch: a cleanup error must never be\n // mistaken for a failed parallel build whose valid index should be dropped.\n await resetVectorParallelWorkers(execute, tableName);\n try {\n await execute(indexStatement);\n } catch (error) {\n if (!isInsufficientResourcesError(error)) throw error;\n if (dropStatement !== undefined) {\n try {\n await execute(dropStatement);\n } catch (dropError) {\n throw vectorSerialFallbackPreparationError(\n \"drop-index\",\n error,\n dropError,\n );\n }\n }\n await runSerialVectorIndexBuild(\n execute,\n tableName,\n indexStatement,\n error,\n );\n }\n}\n\n/** @internal */\nexport async function runPostgresVectorIndexBuild(\n vectorStrategy: VectorStrategy,\n execute: ExecutePostgresStatement,\n tableName: string,\n indexStatement: ExecutableSql,\n dropStatement?: ExecutableSql,\n): Promise<void> {\n if (vectorStrategy !== pgvectorStrategy) {\n await execute(indexStatement);\n return;\n }\n await runVectorIndexBuildWithSerialFallback(\n execute,\n tableName,\n indexStatement,\n dropStatement,\n );\n}\n\n/** @internal */\nexport async function runSerialVectorIndexBuild(\n execute: ExecutePostgresStatement,\n tableName: string,\n indexStatement: ExecutableSql,\n parallelBuildError?: unknown,\n): Promise<void> {\n const table = portableSql.identifier(tableName);\n try {\n await execute(portableSql`ALTER TABLE ${table} SET (parallel_workers = 0)`);\n } catch (setError) {\n if (parallelBuildError === undefined) throw setError;\n throw vectorSerialFallbackPreparationError(\n \"disable-parallel-workers\",\n parallelBuildError,\n setError,\n );\n }\n\n let buildFailure: Readonly<{ error: unknown }> | undefined;\n try {\n await execute(indexStatement);\n } catch (error) {\n buildFailure = { error };\n }\n\n try {\n await execute(portableSql`ALTER TABLE ${table} RESET (parallel_workers)`);\n } catch (resetError) {\n if (buildFailure === undefined) {\n throw parallelWorkerResetError(tableName, resetError);\n }\n reportParallelWorkerResetFailure(tableName, resetError);\n }\n\n if (buildFailure !== undefined) throw buildFailure.error;\n}\n\n// ============================================================\n// Utilities\n// ============================================================\n\nconst toNodeRow = createNodeRowMapper(POSTGRES_ROW_MAPPER_CONFIG);\nconst toEdgeRow = createEdgeRowMapper(POSTGRES_ROW_MAPPER_CONFIG);\nconst toUniqueRow = createUniqueRowMapper(POSTGRES_ROW_MAPPER_CONFIG);\nconst toSchemaVersionRow = createSchemaVersionRowMapper(\n POSTGRES_ROW_MAPPER_CONFIG,\n);\n\nfunction buildPostgresCapabilities(\n fulltextStrategy: FulltextStrategy,\n vectorStrategy: VectorStrategy | undefined,\n): BackendCapabilities {\n return {\n ...POSTGRES_CAPABILITIES,\n ...(vectorStrategy === undefined ?\n {}\n : { vector: buildVectorCapabilities(vectorStrategy) }),\n fulltext: buildFulltextCapabilities(fulltextStrategy),\n };\n}\n\n// ============================================================\n// Backend Factory\n// ============================================================\n\n/**\n * Creates a TypeGraph backend for PostgreSQL databases.\n *\n * Works with any Drizzle PostgreSQL instance regardless of the underlying driver.\n *\n * @param db - A Drizzle PostgreSQL database instance\n * @param options - Backend configuration\n * @returns A GraphBackend implementation\n */\nexport function createPostgresBackend(\n db: AnyPgDatabase,\n options: PostgresBackendOptions = {},\n): AdapterBackend<AnyPgTransaction> {\n // Resolved before the backend exists so marking it below is a lookup, never\n // work that could fail after a wrapper already observed an unmarked backend.\n // A `serializedResource` declaration that contradicts detection is refused\n // here too, before any object a caller could hold has been built.\n const resourceAudit = resolveDeclaredBackendResource(\n getSerializedPostgresClient(db),\n options.serializedResource,\n );\n const tables = options.tables ?? defaultTables;\n const fulltextStrategy = options.fulltext ?? tsvectorStrategy;\n // pgvector is compiled into a standalone Postgres server, so it is wired\n // unconditionally by default (overridable for alternate Postgres vector\n // stacks). `vector: false` disables it — required for an in-process\n // Postgres (PGlite) built without the pgvector extension, where the\n // default strategy's `vector(N)` DDL would hard-fail.\n const vectorStrategy =\n options.vector === false ? undefined : (options.vector ?? pgvectorStrategy);\n // One probe per backend instance, shared with every transaction-scoped\n // backend so the pgvector version check runs — and its pre-0.8 warning\n // fires — at most once per backend, not once per `store.transaction()`.\n const iterativeScanProbe = createIterativeScanProbe();\n const baseCapabilities = buildPostgresCapabilities(\n fulltextStrategy,\n vectorStrategy,\n );\n // HTTP-only drivers (notably `drizzle-orm/neon-http`) can't hold a\n // session across statements, so multi-statement transactions are\n // unavailable regardless of what we declare. Auto-detect and downgrade\n // the capability so callers get correct fallback behavior without\n // having to remember to override it themselves.\n const httpOnlyOverrides =\n isNeonHttpClient(db) ?\n {\n transactions: false,\n graphAnalytics: {\n ...(baseCapabilities.graphAnalytics ?? { mathFunctions: true }),\n supported: false,\n },\n }\n : {};\n const configuredMaxBindParameters =\n options.capabilities?.maxBindParameters ?? POSTGRES_MAX_BIND_PARAMETERS;\n const driverBindParameterOverrides =\n isPgliteDatabase(db) ?\n {\n maxBindParameters: Math.min(\n configuredMaxBindParameters,\n PGLITE_MAX_BIND_PARAMETERS,\n ),\n }\n : {};\n const declaredCapabilities = normalizeGraphAnalyticsCapabilities({\n ...baseCapabilities,\n ...httpOnlyOverrides,\n ...options.capabilities,\n ...driverBindParameterOverrides,\n });\n // Derived last and not overridable: how far up the contribution health\n // ladder this backend goes is a structural fact about the wiring below\n // (durable markers, a catalog probe, a strategy that declares teardown\n // DDL, a transactional schema fence), and a caller who declared a\n // rebuild this backend cannot perform would be advertising a lie. The\n // HTTP-only drivers land on `rebuild: false` here because they cannot\n // hold a session across statements, so there is no fence to run under.\n const capabilities: BackendCapabilities = {\n ...declaredCapabilities,\n contributions: {\n supported: true,\n probe: true,\n rebuild: contributionRebuildSupported(\n fulltextStrategy,\n tables.fulltextTableName,\n declaredCapabilities.transactions,\n ),\n },\n };\n const adapterOptions: PostgresExecutionAdapterOptions = {\n ...(options.prepareStatements === undefined ?\n {}\n : { prepareStatements: options.prepareStatements }),\n ...(options.preparedStatementCacheMax === undefined ?\n {}\n : { preparedStatementCacheMax: options.preparedStatementCacheMax }),\n maxBindParameters:\n capabilities.maxBindParameters ?? POSTGRES_MAX_BIND_PARAMETERS,\n };\n const executionAdapter = createPostgresExecutionAdapter(db, adapterOptions);\n const tableNames: ResolvedSqlTableNames = {\n nodes: getTableName(tables.nodes),\n edges: getTableName(tables.edges),\n recordedNodes: getTableName(tables.recordedNodes),\n recordedEdges: getTableName(tables.recordedEdges),\n recordedClock: getTableName(tables.recordedClock),\n revisionOrigins: getTableName(tables.revisionOrigins),\n identityAssertions: getTableName(tables.identityAssertions),\n recordedIdentityAssertions: getTableName(tables.recordedIdentityAssertions),\n identityClosure: getTableName(tables.identityClosure),\n identitySeparation: getTableName(tables.identitySeparation),\n fulltext: tables.fulltextTableName,\n uniques: getTableName(tables.uniques),\n edgeClaims: getTableName(tables.edgeClaims),\n };\n // Pre-quote identifiers so refreshStatistics() doesn't rebuild the\n // ANALYZE statements on every call. The recorded and identity relations\n // are ANALYZEd separately under an existence guard (see refreshStatistics):\n // a schema created before recorded-time history or Operational Identity\n // landed (bring-your-own-pool, no DDL re-run) has no recorded_* / identity_*\n // tables, and Postgres fails the whole ANALYZE if any named relation is\n // missing. Per-field vector tables are created lazily and live outside this\n // base set, so they are not ANALYZEd here.\n //\n // ONE statement per table with SKIP_LOCKED, never `ANALYZE a, b, c`:\n // ANALYZE takes a ShareUpdateExclusive lock, the same class CREATE INDEX\n // CONCURRENTLY holds for its whole build — and a CIC in another session\n // waits on every regular transaction's snapshot, ANALYZE's included. An\n // ANALYZE that queues on a CIC's table lock while that CIC waits on the\n // ANALYZE's snapshot is a two-node deadlock (observed when two\n // materializeIndexes callers race). SKIP_LOCKED makes ANALYZE skip a\n // locked table instead of queuing, so it can never join a wait cycle;\n // a skipped table is covered by the next refresh or autovacuum.\n const coreAnalyzeStatements = [\n tableNames.nodes,\n tableNames.edges,\n getTableName(tables.uniques),\n tableNames.fulltext,\n ].map((name) =>\n toDrizzleSql(\n portableSql`ANALYZE (SKIP_LOCKED) ${portableSql.identifier(name)}`,\n \"postgres\",\n ),\n );\n const guardedAnalyzeTables = [\n tableNames.recordedNodes,\n tableNames.recordedEdges,\n tableNames.recordedClock,\n tableNames.recordedIdentityAssertions,\n tableNames.identityAssertions,\n tableNames.identityClosure,\n tableNames.identitySeparation,\n ] as const;\n const operationStrategy = createPostgresOperationStrategy(\n tables,\n fulltextStrategy,\n );\n\n // Whether `tableName` currently exists, via the same catalog probe `clear()`\n // uses — so refreshStatistics() never ANALYZEs a recorded or identity\n // relation that a bring-your-own-pool schema has not yet created. The\n // Postgres probe is search_path-aware, so positive results are deliberately\n // not cached by bare table name.\n const guardedTableExists = createCachedTableExistence(\n async (tableName) => {\n const rows = await executionAdapter.execute<Record<string, unknown>>(\n operationStrategy.buildTableExists(tableName),\n );\n return rows[0];\n },\n { cacheExisting: false },\n );\n\n // Durable fulltext + vector materialization (#135): the dialect-specific\n // marker-table primitives. Orchestration (materialize / assert /\n // per-instance cache) lives once in `createContributionMaterializer`,\n // shared by the outer backend and every transaction-scoped backend so a\n // slot's marker is resolved at most once per process. Built before\n // `operations` so the operation backend's vector methods can assert/\n // ensure through it instead of issuing DDL on the hot path.\n const matTable = tables.contributionMaterializations;\n\n /**\n * Runs one IDEMPOTENT DDL statement — `CREATE ... IF NOT EXISTS` or\n * `ALTER TABLE ... ADD COLUMN IF NOT EXISTS` — with the one-shot retry a\n * concurrent boot needs.\n */\n async function executeConcurrentCreateDdl(ddl: string): Promise<void> {\n const statement = sql.raw(ddl);\n await withConcurrentCreateRetry(async () => {\n await db.execute(statement);\n });\n }\n\n async function ensureTableWithConcurrentCreateRetry(\n table: Parameters<typeof generatePgCreateTableSQL>[0],\n ): Promise<void> {\n await executeConcurrentCreateDdl(generatePgCreateTableSQL(table));\n }\n\n /**\n * THE one place this backend installs a database extension, for every\n * extension and every caller.\n *\n * An extension is database-global while the claims that reach it are not (an\n * index-materialization claim is per index), so two callers wanting different\n * objects still race on `pg_extension_name_index`. Two fences answer that,\n * and both are here because they answer different halves of it:\n *\n * - the advisory lock serializes same-key installers inside this process\n * group so the common case never raises at all (#475). It is keyed on the\n * extension so installing `vector` does not queue behind `pg_trgm`;\n * - {@link withConcurrentCreateRetry} clears the 23505 an installer that did\n * NOT take this lock can still hand us — a peer on an older version, whose\n * lock key differs, or a `capabilities.transactions: false` backend which\n * has no transaction to hang a `pg_advisory_xact_lock` on (#446).\n *\n * The lock runs in its own transaction on purpose: a 23505 poisons an\n * enclosing transaction (the next statement fails `25P02`), so the retry is\n * sound only when the failed unit of work is one this function owns\n * end-to-end.\n */\n async function ensureDatabaseExtension(\n name: DatabaseExtensionName,\n ): Promise<void> {\n // The name reaches DDL by interpolation, so the allowlist — not the\n // caller's type — is what makes the identifier trustworthy at runtime.\n const validated = DATABASE_EXTENSION_NAMES.find(\n (candidate) => candidate === name,\n );\n if (validated === undefined) {\n throw new ConfigurationError(\n `Unsupported database extension \"${name}\".`,\n { extension: name, supported: DATABASE_EXTENSION_NAMES },\n {\n suggestion: `Request one of: ${DATABASE_EXTENSION_NAMES.join(\", \")}.`,\n },\n );\n }\n const ddl = `CREATE EXTENSION IF NOT EXISTS \"${validated}\";`;\n if (!capabilities.transactions) {\n await executeConcurrentCreateDdl(ddl);\n return;\n }\n await withConcurrentCreateRetry(async () => {\n await db.transaction(async (tx) => {\n await tx.execute(\n sql`SELECT pg_advisory_xact_lock(hashtext(${extensionDdlLockKey(validated)}), 0)`,\n );\n await tx.execute(sql.raw(ddl));\n });\n });\n }\n\n async function ensureContributionMaterializationsTableImpl(): Promise<void> {\n await ensureTableWithConcurrentCreateRetry(matTable);\n }\n\n /**\n * The contribution descriptors for exactly the identity relations, under\n * caller-supplied physical names. Pure — nothing is executed here — and the\n * single owner of \"which DDL belongs to the identity relations\", shared by\n * `ensureIdentityTables` (which runs it) and `identityTableDdl` (which hands\n * it to a transaction).\n */\n function identityContributionsFor(\n identityTableNames: IdentityTableNames,\n ): ReturnType<typeof postgresContributions> {\n const identityTables = buildPostgresTables({\n identityAssertions: identityTableNames.identityAssertions,\n recordedIdentityAssertions: identityTableNames.recordedIdentityAssertions,\n identityClosure: identityTableNames.identityClosure,\n identitySeparation: identityTableNames.identitySeparation,\n });\n return postgresContributions(identityTables, fulltextStrategy).filter(\n (contribution) =>\n IDENTITY_TABLE_LOGICAL_NAMES.has(contribution.logicalName),\n );\n }\n\n async function getContributionMaterializationRow(\n identity: ContributionMaterializationIdentity,\n ): Promise<ContributionMaterializationRow | undefined> {\n const rows = await db\n .select()\n .from(matTable)\n .where(\n and(\n eq(matTable.graphId, identity.graphId),\n eq(matTable.logicalName, identity.logicalName),\n eq(matTable.owner, identity.owner),\n eq(matTable.tableName, identity.tableName),\n ),\n );\n const row = rows[0];\n if (row === undefined) return undefined;\n return mapContributionMaterializationRow(\n row,\n POSTGRES_CONTRIBUTION_MAT_TIMESTAMPS.decode,\n );\n }\n\n async function getContributionMaterializationRows(\n graphId: string,\n ): Promise<readonly ContributionMaterializationRow[]> {\n const rows = await db\n .select()\n .from(matTable)\n .where(eq(matTable.graphId, graphId));\n return rows.map((row) =>\n mapContributionMaterializationRow(\n row,\n POSTGRES_CONTRIBUTION_MAT_TIMESTAMPS.decode,\n ),\n );\n }\n\n async function recordContributionMaterializationRow(\n params: RecordContributionMaterializationParams,\n ): Promise<void> {\n await db\n .insert(matTable)\n .values(\n buildContributionInsertValues(\n params,\n POSTGRES_CONTRIBUTION_MAT_TIMESTAMPS.encode,\n ),\n )\n .onConflictDoUpdate({\n target: [\n matTable.graphId,\n matTable.logicalName,\n matTable.owner,\n matTable.tableName,\n ],\n set: buildContributionOnConflictSet(\n matTable.materializedAt,\n params.materializedAt,\n ),\n });\n }\n\n async function deleteContributionMaterializationRow(\n identity: ContributionMaterializationIdentity,\n ): Promise<void> {\n await db\n .delete(matTable)\n .where(\n and(\n eq(matTable.graphId, identity.graphId),\n eq(matTable.logicalName, identity.logicalName),\n eq(matTable.owner, identity.owner),\n eq(matTable.tableName, identity.tableName),\n ),\n );\n }\n\n /**\n * Uncached catalog probe backing `verifyContributions`. The shared\n * `createCachedTableExistence` wrapper is deliberately NOT used: this\n * diagnostic's whole job is to notice that a table confirmed present\n * earlier has since been dropped.\n */\n async function contributionTableExists(tableName: string): Promise<boolean> {\n const rows = await executionAdapter.execute<Record<string, unknown>>(\n operationStrategy.buildTableExists(tableName),\n );\n return tableExistsFromRow(rows[0]);\n }\n\n const contributionMaterializer = createContributionMaterializer({\n dialect: \"postgres\",\n fulltextStrategy,\n fulltextTableName: tables.fulltextTableName,\n vectorStrategy,\n // Contribution DDL is `CREATE ... IF NOT EXISTS` reached from every\n // booting replica, so it carries the same concurrent-create retry the\n // other create sites use. Without it the loser's 23505 is recorded as\n // `lastError` on the marker row and reported as a failed materialization,\n // when the table it wanted is in fact present.\n execDdl: async (statement) => {\n await executeConcurrentCreateDdl(statement);\n },\n ensureMarkerTable: ensureContributionMaterializationsTableImpl,\n getMarkers: getContributionMaterializationRows,\n recordMarker: recordContributionMaterializationRow,\n deleteMarker: deleteContributionMaterializationRow,\n tableExists: contributionTableExists,\n // Withheld rather than wired-and-throwing when the driver cannot hold\n // a session: the rebuild must refuse with its own typed error naming\n // the absent fence, matching `capabilities.contributions.rebuild`.\n ...(capabilities.transactions ?\n {\n schemaWriteTransaction: <T>(\n graphId: string,\n fn: (tx: SchemaWriteTransactionBackend) => Promise<T>,\n ) => runSchemaWriteTransaction(graphId, (target) => fn(target)),\n }\n : {}),\n });\n\n const operations = createPostgresOperationBackend({\n db,\n executionAdapter,\n adapterOptions,\n operationStrategy,\n tableNames,\n capabilities,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n iterativeScanProbe,\n schemaVersionsTable: tables.schemaVersions,\n transactionScoped: false,\n });\n\n /**\n * Runs `fn` inside a Postgres transaction, holding an\n * `pg_advisory_xact_lock` keyed on the graph id. The advisory lock\n * serializes all schema commits per-graph: the read-then-write CAS in\n * `commitSchemaVersion` is safe even for the initial-commit case\n * where there is no row yet to `SELECT ... FOR UPDATE`.\n *\n * Refuses on backends that don't support transactions\n * (`drizzle-orm/neon-http`). The orphan-row crash window cannot be\n * eliminated without atomicity, so silent best-effort degradation is\n * worse than a typed error.\n */\n function runSchemaWriteTransaction<T>(\n graphId: string,\n fn: (tx: InternalOperationBackend) => Promise<T>,\n ): Promise<T> {\n if (!capabilities.transactions) {\n throw new ConfigurationError(\n \"Schema writes and removal cleanup require atomic transactions, \" +\n \"but this Postgres backend does not provide them. The drizzle-orm/neon-http \" +\n \"driver communicates over HTTP and cannot hold a session across statements; \" +\n \"use drizzle-orm/neon-serverless (websocket) for transactional writes.\",\n {\n backend: \"postgres\",\n capability: \"transactions\",\n supportsTransactions: false,\n },\n );\n }\n\n return db.transaction(async (tx) => {\n // Advisory lock: hashtext($graphId) is collision-tolerant for the\n // size of an active graph set; collisions just serialize unrelated\n // graphs which is harmless. Held until the transaction commits.\n //\n // The ONE-ARGUMENT (bigint) form is deliberate and load-bearing: it\n // occupies a different lock space than the two-argument (int4, int4)\n // form every namespaced TypeGraph lock uses (`typegraph:identity`,\n // `typegraph:identity-ddl`, the recorded-write clock). PostgreSQL stores\n // the two forms with different locktag field4 values, so a bigint key can\n // never collide with an (int4, int4) key however the hashes land — the\n // schema fence is therefore independent of every lock taken INSIDE it.\n // Normalizing this to the two-argument form would merge the spaces and\n // put that independence at the mercy of `hashtext` collisions.\n await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${graphId}))`);\n // Managed entity writers lock this row FOR SHARE. Locking it FOR UPDATE\n // before any emptiness probe makes a writer-first commit wait; a\n // schema-first snapshot-isolated writer gets PostgreSQL's native\n // serialization failure instead of validating a stale row version.\n await tx.execute(sql`\n SELECT ${tables.schemaVersions.version}\n FROM ${tables.schemaVersions}\n WHERE ${tables.schemaVersions.graphId} = ${graphId}\n AND ${tables.schemaVersions.isActive} = TRUE\n FOR UPDATE\n `);\n // Advisory lock is held here, so the schema-write-capable\n // InternalOperationBackend is used intentionally (see its type).\n const { backend: txBackend, drainAndClose } = createTransactionBackend({\n db: tx,\n adapterOptions,\n operationStrategy,\n tableNames,\n capabilities,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n iterativeScanProbe,\n schemaVersionsTable: tables.schemaVersions,\n });\n try {\n return await fn(txBackend);\n } finally {\n await drainAndClose();\n }\n });\n }\n\n // Shared by `transaction()` (TypeGraph opens the tx) and\n // `adoptTransaction()` (#134 — the caller already opened it): bind a\n // tx-scoped backend to the *literal* `tx` client and gate fulltext on\n // the durable marker (a cached SELECT, never DDL).\n function bindTransactionBackend(tx: AnyPgTransaction): Readonly<{\n backend: TransactionBackend;\n drainAndClose: () => Promise<void>;\n }> {\n const { backend, drainAndClose } = createTransactionBackend({\n db: tx,\n adapterOptions,\n operationStrategy,\n tableNames,\n capabilities,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n iterativeScanProbe,\n schemaVersionsTable: tables.schemaVersions,\n });\n return {\n backend: gateFulltext(\n backend,\n contributionMaterializer.assertInitialized,\n contributionMaterializer.refuseUnavailableFulltext,\n ),\n drainAndClose,\n };\n }\n\n const backend: AdapterBackend<AnyPgTransaction> = {\n ...operations,\n\n ...((\n capabilities.transactions &&\n executionAdapter.executeCompiled !== undefined\n ) ?\n {\n async trustedImport<T>(\n fn: (session: TrustedImportSession) => Promise<T>,\n options_?: TrustedImportOptions,\n ): Promise<T> {\n return backend.transactionWithNative(async (tx, rawSql) => {\n if (options_?.schemaWrite !== undefined) {\n await requireDefined(tx.lockSchemaVersionForWrite)({\n ...options_.schemaWrite,\n });\n }\n const trustedExecutionAdapter = createPostgresExecutionAdapter(\n rawSql,\n { ...adapterOptions, useTransactionClient: true },\n );\n const executeCompiled = trustedExecutionAdapter.executeCompiled;\n if (executeCompiled === undefined) {\n throw new ConfigurationError(\n \"Trusted import could not bind raw execution to the PostgreSQL transaction.\",\n { capability: \"trustedImport\", dialect: \"postgres\" },\n );\n }\n const trustedTx = deriveBackend(tx, {\n executeRaw<T>(\n sqlText: string,\n params: readonly unknown[],\n ): Promise<readonly T[]> {\n return executeCompiled<T>({ params, sql: sqlText });\n },\n });\n await lockPostgresTrustedImportTables(trustedTx, tableNames);\n await assertTrustedImportDatabaseEmpty(trustedTx, tableNames);\n const indexDefinitions = await suspendPostgresSecondaryIndexes(\n trustedTx,\n tableNames,\n );\n const result = await fn(\n createPostgresTrustedImportSession(trustedTx, tableNames),\n );\n await restoreSecondaryIndexes(trustedTx, indexDefinitions);\n await analyzeImportedTables(trustedTx, tableNames);\n return result;\n });\n },\n }\n : {}),\n\n async bootstrapTables(): Promise<void> {\n const statements = generatePostgresDDL(tables, fulltextStrategy);\n for (const statement of statements) {\n // Cold boot is the single most contended DDL path there is — two\n // replicas starting at once run exactly this loop against the same\n // database — so it takes the concurrent-create retry rather than\n // trusting IF NOT EXISTS, for the reason `executeConcurrentCreateDdl`\n // documents.\n await executeConcurrentCreateDdl(statement);\n }\n },\n\n async ensureRevisionOriginsTable(): Promise<void> {\n await ensureTableWithConcurrentCreateRetry(tables.revisionOrigins);\n },\n\n async ensureIdentityTables(\n identityTableNames,\n options,\n ): Promise<readonly string[]> {\n // First enablement of Operational Identity on an existing populated\n // database: createStore / createPostgresBackend run no DDL, so the\n // four identity relations the enablement preflight reads/writes may\n // not exist yet. Ensure them (and their indexes and CHECK constraints)\n // idempotently — CREATE TABLE / CREATE INDEX IF NOT EXISTS — reusing the same contribution\n // DDL bootstrapTables emits, scoped to the identity relations. Stores\n // run this before opening the schema-commit transaction so DDL does not\n // re-enter its per-graph write lock.\n const identityContributions =\n identityContributionsFor(identityTableNames);\n const missing = [] as string[];\n for (const contribution of identityContributions) {\n if (!(await contributionTableExists(contribution.tableName))) {\n missing.push(contribution.logicalName);\n }\n }\n // Do not turn a missing assertion ledger on an already-enabled graph\n // into an empty-but-present table. Otherwise the first open fails, then\n // a retry silently accepts lost identity truth. First enablement opts\n // into provisioning; when all tables exist, idempotent DDL still repairs\n // missing secondary indexes.\n if (missing.length === 0 || options.provisionMissing) {\n for (const contribution of identityContributions) {\n for (const ddl of contribution.createDdl) {\n await executeConcurrentCreateDdl(ddl);\n }\n }\n }\n return missing;\n },\n\n identityTableDdl(identityTableNames): readonly string[] {\n return identityContributionsFor(identityTableNames).flatMap(\n (contribution) => [...contribution.createDdl],\n );\n },\n\n // Every fulltext-touching method asserts the durable marker instead\n // of lazily emitting DDL. Steady state performs zero ensure; an\n // uninitialized database throws `StoreNotInitializedError` loudly\n // rather than self-healing on a read/write path (#135). Shared\n // verbatim with the tx-scoped gate via `gateFulltextMethods`.\n ...gateFulltextMethods(\n operations,\n contributionMaterializer.assertInitialized,\n contributionMaterializer.refuseUnavailableFulltext,\n ),\n\n async executeDdl(ddl: string): Promise<void> {\n await db.execute(sql.raw(ddl));\n },\n\n ensureExtension: ensureDatabaseExtension,\n\n async ensureIndexMaterializationsTable(): Promise<void> {\n await ensureTableWithConcurrentCreateRetry(tables.indexMaterializations);\n // Deployments created before the build-claim columns existed get\n // them additively; fresh installs already have them from the\n // CREATE TABLE above.\n //\n // These take the concurrent-DDL retry for the same reason the CREATE\n // does, and it is the same loop two replicas run at boot: ADD COLUMN IF\n // NOT EXISTS cannot see another session's uncommitted pg_attribute row,\n // so the loser waits and is then handed 42701 (or `tuple concurrently\n // updated`) instead of the notice — a spuriously failed boot (#445).\n const tableName = getTableName(tables.indexMaterializations);\n await executeConcurrentCreateDdl(\n `ALTER TABLE \"${tableName}\" ADD COLUMN IF NOT EXISTS \"building_since\" timestamptz;`,\n );\n await executeConcurrentCreateDdl(\n `ALTER TABLE \"${tableName}\" ADD COLUMN IF NOT EXISTS \"claim_token\" text;`,\n );\n },\n\n ensureTrigramExtension(): Promise<void> {\n return ensureDatabaseExtension(\"pg_trgm\");\n },\n\n async claimIndexMaterialization(\n params: ClaimIndexMaterializationParams,\n ): Promise<boolean> {\n const t = tables.indexMaterializations;\n // Atomic claim: insert a fresh claim row, or take over an existing\n // row only when no live claim is on it (NULL or lease-expired\n // building_since). The WHERE on the conflict update makes losing\n // racers see zero returned rows — the row's own atomicity is the\n // mutex, so this works identically through pools and across\n // processes (unlike session advisory locks, which pin a\n // connection).\n const rows = await db.execute(sql`\n INSERT INTO ${t} (\n \"index_name\", \"graph_id\", \"entity\", \"kind\", \"signature\",\n \"schema_version\", \"last_attempted_at\", \"building_since\",\n \"claim_token\"\n )\n VALUES (\n ${params.indexName}, ${params.graphId}, ${params.entity},\n ${params.kind}, ${params.signature}, ${params.schemaVersion},\n now(), now(), ${params.token}\n )\n ON CONFLICT (\"index_name\") DO UPDATE SET\n \"building_since\" = now(),\n \"claim_token\" = EXCLUDED.\"claim_token\"\n WHERE ${t}.\"building_since\" IS NULL\n OR ${t}.\"building_since\" < now() - (${params.leaseMs} * interval '1 millisecond')\n RETURNING \"index_name\"\n `);\n const result = rows;\n const returned =\n Array.isArray(result) ? result : (\n ((result as Readonly<{ rows?: readonly unknown[] }>).rows ?? [])\n );\n return returned.length > 0;\n },\n\n async releaseIndexMaterializationClaim(\n params: ReleaseIndexMaterializationClaimParams,\n ): Promise<void> {\n const t = tables.indexMaterializations;\n // Token-guarded: a lease-expired claim taken over by another\n // materializer must not be released by the original holder.\n await db.execute(sql`\n UPDATE ${t}\n SET \"building_since\" = NULL, \"claim_token\" = NULL\n WHERE \"index_name\" = ${params.indexName}\n AND \"claim_token\" = ${params.token}\n `);\n },\n\n async getIndexMaterialization(\n indexName: string,\n ): Promise<IndexMaterializationRow | undefined> {\n const t = tables.indexMaterializations;\n const rows = await db.select().from(t).where(eq(t.indexName, indexName));\n const row = rows[0];\n if (row === undefined) return undefined;\n return mapMaterializationRow(row, POSTGRES_INDEX_MAT_TIMESTAMPS.decode);\n },\n\n async getIndexMaterializations(\n statusKeys: readonly string[],\n ): Promise<readonly IndexMaterializationRow[]> {\n if (statusKeys.length === 0) return [];\n const t = tables.indexMaterializations;\n const rows = await db\n .select()\n .from(t)\n .where(inArray(t.indexName, [...statusKeys]));\n return rows.map((row) =>\n mapMaterializationRow(row, POSTGRES_INDEX_MAT_TIMESTAMPS.decode),\n );\n },\n\n async recordIndexMaterialization(\n params: RecordIndexMaterializationParams,\n ): Promise<void> {\n const t = tables.indexMaterializations;\n await db\n .insert(t)\n .values(\n buildMaterializationInsertValues(\n params,\n POSTGRES_INDEX_MAT_TIMESTAMPS.encode,\n ),\n )\n .onConflictDoUpdate({\n target: t.indexName,\n set: buildMaterializationOnConflictSet(params.materializedAt),\n });\n },\n\n async ensureContributionMaterializationsTable(): Promise<void> {\n await ensureContributionMaterializationsTableImpl();\n },\n\n async getContributionMaterialization(\n identity: ContributionMaterializationIdentity,\n ): Promise<ContributionMaterializationRow | undefined> {\n return getContributionMaterializationRow(identity);\n },\n\n async recordContributionMaterialization(\n params: RecordContributionMaterializationParams,\n ): Promise<void> {\n await recordContributionMaterializationRow(params);\n },\n\n async assertRuntimeContributionsInitialized(\n graphId: string,\n ): Promise<void> {\n await contributionMaterializer.assertInitialized(graphId);\n },\n\n async ensureKindRemovalsTable(): Promise<void> {\n await ensureTableWithConcurrentCreateRetry(tables.kindRemovals);\n },\n\n async getPendingKindRemovals(\n graphId: string,\n ): Promise<readonly KindRemovalRow[]> {\n const t = tables.kindRemovals;\n const rows = await db\n .select()\n .from(t)\n .where(and(eq(t.graphId, graphId), isNull(t.removedAt)));\n return rows.map((row) =>\n mapKindRemovalRow(row, POSTGRES_KIND_REMOVAL_TIMESTAMPS.decode),\n );\n },\n\n async getAllKindRemovals(\n graphId: string,\n ): Promise<readonly KindRemovalRow[]> {\n const t = tables.kindRemovals;\n const rows = await db.select().from(t).where(eq(t.graphId, graphId));\n return rows.map((row) =>\n mapKindRemovalRow(row, POSTGRES_KIND_REMOVAL_TIMESTAMPS.decode),\n );\n },\n\n async recordKindRemoval(params: RecordKindRemovalParams): Promise<void> {\n const t = tables.kindRemovals;\n await db\n .insert(t)\n .values(\n buildKindRemovalInsertValues(\n params,\n POSTGRES_KIND_REMOVAL_TIMESTAMPS.encode,\n ),\n )\n .onConflictDoUpdate({\n target: [t.graphId, t.kindName, t.entity, t.schemaVersion],\n set: buildKindRemovalOnConflictSet(t.removedAt, params.removedAt),\n });\n },\n\n async ensureReconciliationMarkersTable(): Promise<void> {\n await ensureTableWithConcurrentCreateRetry(tables.reconciliationMarkers);\n },\n\n async ensureRuntimeContributions(graphId: string): Promise<void> {\n await contributionMaterializer.ensureRuntimeContributions(graphId);\n },\n\n /**\n * Superseded by `ensureRuntimeContributions(graphId)` (#129).\n * Retained as a thin back-compat wrapper for callers predating\n * #129; #135 routed it through the durable-marker writer.\n */\n async ensureFulltextTable(graphId: string): Promise<void> {\n await contributionMaterializer.ensureRuntimeContributions(graphId);\n },\n\n async verifyContributions(\n graphId: string,\n vectorSlots: readonly VectorSlot[],\n ): Promise<readonly ContributionDiagnostic[]> {\n return contributionMaterializer.verifyContributions(graphId, vectorSlots);\n },\n\n async repairContributions(\n graphId: string,\n vectorSlots: readonly VectorSlot[],\n ): Promise<ContributionRepairResult> {\n return contributionMaterializer.repairContributions(graphId, vectorSlots);\n },\n\n async probeContributions(\n graphId: string,\n vectorSlots: readonly VectorSlot[],\n ): Promise<readonly ContributionProbeEntry[]> {\n return contributionMaterializer.probeContributions(graphId, vectorSlots);\n },\n\n async rebuildContribution(\n graphId: string,\n scope: ContributionRebuildScope,\n repopulate: (\n target: TransactionBackend,\n ) => Promise<ContributionRepopulationStats>,\n ): Promise<ContributionRebuildResult> {\n return contributionMaterializer.rebuildContribution(\n graphId,\n scope,\n repopulate,\n );\n },\n\n // Vector counterparts of the runtime-contribution methods. Present\n // only when a vector strategy is wired (omitted under `vector: false`,\n // mirroring the embedding/search methods), so a no-vector backend\n // doesn't advertise vector materialization it can't perform.\n ...(vectorStrategy === undefined ?\n {}\n : {\n async ensureVectorSlotContribution(\n slot: VectorSlot,\n options_?: Readonly<{ force?: boolean; onDrift?: \"throw\" | \"skip\" }>,\n ): Promise<void> {\n await contributionMaterializer.ensureVectorSlot(slot, options_);\n },\n\n async ensureVectorSlotContributions(\n slots: readonly VectorSlot[],\n options_?: Readonly<{ force?: boolean; onDrift?: \"throw\" | \"skip\" }>,\n ): Promise<void> {\n await contributionMaterializer.ensureVectorSlots(slots, options_);\n },\n\n async assertVectorSlotInitialized(slot: VectorSlot): Promise<void> {\n await contributionMaterializer.assertVectorSlot(slot);\n },\n\n async assertVectorSlotsInitialized(\n slots: readonly VectorSlot[],\n ): Promise<void> {\n await contributionMaterializer.assertVectorSlots(slots);\n },\n\n async deleteVectorSlotContribution(slot: VectorSlot): Promise<void> {\n await contributionMaterializer.dropVectorSlot(slot);\n },\n }),\n\n async getReconciliationMarker(\n graphId: string,\n ): Promise<number | undefined> {\n const t = tables.reconciliationMarkers;\n const rows = await db.select().from(t).where(eq(t.graphId, graphId));\n return rows[0]?.reconciledToVersion;\n },\n\n async setReconciliationMarker(\n graphId: string,\n version: number,\n ): Promise<void> {\n const t = tables.reconciliationMarkers;\n await db\n .insert(t)\n .values({ graphId, reconciledToVersion: version })\n .onConflictDoUpdate({\n target: t.graphId,\n set: { reconciledToVersion: version },\n });\n },\n\n async refreshStatistics(): Promise<void> {\n // Scoped to TypeGraph-managed tables only — we don't touch\n // unrelated tables in the same database. Without fresh stats\n // after a bulk load the planner can pick a reverse-index scan\n // with a filter (5ms forward traversal instead of 0.5ms) until\n // autovacuum catches up. Sequential per-table statements — see\n // coreAnalyzeStatements for why they are never combined.\n for (const statement of coreAnalyzeStatements) {\n await db.execute(statement);\n }\n // The recorded and identity relations may be absent on a schema created\n // before recorded-time history or Operational Identity landed\n // (bring-your-own-pool, no DDL re-run). Postgres fails an ANALYZE naming\n // a missing relation, so ANALYZE only the guarded tables that exist.\n const tablePresence = await Promise.all(\n guardedAnalyzeTables.map(async (tableName) => ({\n tableName,\n exists: await guardedTableExists(tableName),\n })),\n );\n const presentGuardedTables = tablePresence\n .filter((entry) => entry.exists)\n .map((entry) => entry.tableName);\n for (const tableName of presentGuardedTables) {\n await db.execute(\n toDrizzleSql(\n portableSql`ANALYZE (SKIP_LOCKED) ${portableSql.identifier(tableName)}`,\n \"postgres\",\n ),\n );\n }\n },\n\n async commitSchemaVersion(\n params: CommitSchemaVersionParams,\n ): Promise<SchemaVersionRow> {\n return runSchemaWriteTransaction(params.graphId, (target) =>\n target.commitSchemaVersion(params),\n );\n },\n\n async commitSchemaVersionIfKindsEmpty(\n params: CommitSchemaVersionParams,\n probes: readonly SchemaKindEmptinessProbe[],\n ): Promise<CommitSchemaVersionIfKindsEmptyResult> {\n return runSchemaWriteTransaction(params.graphId, (target) =>\n commitSchemaVersionIfKindsEmpty(target, params, probes),\n );\n },\n\n async commitSchemaVersionWithPreflight(\n params: CommitSchemaVersionParams,\n // The schema-write target, not the narrowed transaction backend: a\n // preflight may have to CREATE the storage it then fills, and that DDL\n // belongs in this transaction rather than before it.\n preflight: (target: SchemaWriteTransactionBackend) => Promise<void>,\n ): Promise<SchemaVersionRow> {\n return runSchemaWriteTransaction(params.graphId, async (target) => {\n await preflight(target);\n return target.commitSchemaVersion(params);\n });\n },\n\n async setActiveVersion(params: SetActiveVersionParams): Promise<void> {\n await runSchemaWriteTransaction(params.graphId, (target) =>\n target.setActiveVersion(params),\n );\n },\n\n async schemaWriteTransaction<T>(\n graphId: string,\n fn: (tx: SchemaWriteTransactionBackend) => Promise<T>,\n ): Promise<T> {\n return runSchemaWriteTransaction(graphId, (target) => fn(target));\n },\n\n async transaction<T>(\n fn: (tx: TransactionBackend) => Promise<T>,\n options?: InternalTransactionOptions,\n ): Promise<T> {\n return backend.transactionWithNative((tx) => fn(tx), options);\n },\n\n async transactionWithNative<T>(\n fn: (tx: TransactionBackend, sql: AnyPgTransaction) => Promise<T>,\n options?: InternalTransactionOptions,\n ): Promise<T> {\n // #134/#135: NO DDL or ensure here. The tx-scoped backend's\n // fulltext-touching methods assert the durable contribution\n // marker (one cached SELECT — never DDL) at point of use, exactly\n // like the non-tx wrappers. A transaction that never touches\n // fulltext never asserts; one that does runs pure DML against an\n // already-materialized table, with the \"no DDL in the business\n // transaction\" guarantee backed by the durable fact.\n const temporaryWrites =\n options?.temporaryWrites === INTERNAL_TEMPORARY_WRITES;\n if (temporaryWrites && options.accessMode !== \"read_only\") {\n throw new ConfigurationError(\n \"Temporary-write transactions must be semantically read-only.\",\n { dialect: \"postgres\" },\n );\n }\n const txConfig =\n (\n options?.isolationLevel !== undefined ||\n options?.accessMode !== undefined ||\n temporaryWrites\n ) ?\n {\n ...(options.isolationLevel === undefined ?\n {}\n : {\n isolationLevel: options.isolationLevel.replace(\"_\", \" \") as\n | \"read uncommitted\"\n | \"read committed\"\n | \"repeatable read\"\n | \"serializable\",\n }),\n ...(options.accessMode === undefined && !temporaryWrites ?\n {}\n : {\n accessMode:\n temporaryWrites ?\n (\"read write\" as const)\n : (requireDefined(options.accessMode).replace(\"_\", \" \") as\n \"read only\" | \"read write\"),\n }),\n }\n : undefined;\n\n return db.transaction(async (tx) => {\n const { backend: txBackend, drainAndClose } =\n bindTransactionBackend(tx);\n try {\n return await fn(txBackend, tx);\n } finally {\n // Drizzle emits COMMIT / ROLLBACK on this same pinned connection the\n // instant the callback settles, and those control statements do not\n // travel through the backend's statement queue. Wait for whatever is\n // on the wire, and refuse anything the callback left running — a\n // `Promise.all` that rejects orphans its siblings, whose statements\n // would otherwise overlap the ROLLBACK and then land on a connection\n // the pool had already handed to somebody else.\n await drainAndClose();\n }\n }, txConfig);\n },\n\n adoptTransaction(externalTx: AnyPgTransaction): TransactionBackend {\n // #134: cross-store atomicity is unsafe without real rollback —\n // the caller's relational write on `externalTx` *would* still\n // commit even though the graph write could not be undone. Refuse\n // loudly rather than silently degrade.\n if (!capabilities.transactions) {\n throw new ConfigurationError(\n \"Cross-store atomicity is unavailable on this Postgres backend: \" +\n \"its driver does not support transactions (drizzle-orm/neon-http, \" +\n \"Cloudflare D1). Adopting an external transaction here would let \" +\n \"the caller's relational write commit with no way to roll back \" +\n \"the graph write. Use a node-postgres or neon-serverless \" +\n \"(Pool/WebSocket) connection for cross-store transactions.\",\n {\n backend: \"postgres\",\n capability: \"transactions\",\n supportsTransactions: false,\n },\n );\n }\n assertAdoptedDialect<AnyPgTransaction>(\n externalTx,\n PgTransaction,\n \"postgres\",\n );\n // The caller owns BEGIN/COMMIT/ROLLBACK via its own\n // `db.transaction(...)`. We adopt the literal `tx` client and run\n // pure DML on it — no transaction is opened or closed here, and no\n // DDL is emitted inside the caller's business transaction.\n //\n // Statements still serialize onto the pinned connection, but the queue\n // is never closed: only the caller knows when their transaction ends,\n // so it is on them to await every graph write before committing.\n return bindTransactionBackend(externalTx).backend;\n },\n\n async close(): Promise<void> {\n // Drizzle doesn't expose a close method\n // Users manage connection lifecycle themselves\n },\n };\n\n // INVARIANT: audit before any wrapper can observe this backend — see\n // transaction-resource.ts. Unconditional: an abstention recorded as\n // \"independent\" is a verdict the guards can tell apart from a backend nobody\n // looked at.\n auditBackendResource(backend, resourceAudit);\n return backend;\n}\n\n/**\n * Returns the client object a Drizzle Postgres database serializes ALL of its\n * statements onto, or `undefined` when statements can run on independent\n * connections.\n *\n * Marked (single connection — an open transaction on one wrapper blocks or\n * captures every other wrapper's statements):\n *\n * - **PGlite** — one in-process WASM Postgres connection.\n * - **A bare `pg` / `@neondatabase/serverless` `Client`** — one owned socket.\n * An export's `BEGIN ... READ ONLY` stays open across the whole stream, so a\n * concurrent import's INSERT lands inside it (\"cannot execute INSERT in a\n * read-only transaction\").\n * - **A `Pool` whose resolved cap is one connection** — the export checks out the\n * pool's only connection for the duration, so a concurrent import waits for a\n * connection that is never released. Every spelling pg-pool resolves into that\n * cap counts; {@link isSingleConnectionPgPoolCap} owns which ones those are.\n * - **A postgres-js client whose resolved cap is one connection** — the same cap\n * on a CALLABLE client. postgres-js's `begin` reserves a connection from its\n * own pool for the transaction, so with a pool of one an export snapshot holds\n * the only connection every other wrapper's statement needs.\n * {@link isSingleConnectionPostgresJsCap} owns that driver's reading of a cap,\n * which is NOT the same decision as pg-pool's.\n *\n * Deliberately NOT marked: a default pool (independent connection per\n * checkout), a postgres-js client at default size (`max` defaults to 10), a\n * neon-http tagged template (session-less HTTP), and anything unrecognized. A\n * false positive refuses legitimate concurrent work, so the predicate requires\n * positive evidence and abstains otherwise. A pool capped at one connection by\n * means other than the cap pg-pool resolves (a global `pg.defaults.max`, a\n * `pg` connection string's `?max=1` — neither of which pg honors, so neither\n * caps anything) is therefore not detected, and a serialized-connection import\n * there still fails the way it did before this guard existed.\n */\nfunction getSerializedPostgresClient(db: AnyPgDatabase): object | undefined {\n const pgliteClient = getPgliteClient(db);\n if (pgliteClient !== undefined) return pgliteClient;\n const client: unknown = (db as Readonly<{ $client?: unknown }>).$client;\n // Callable clients are examined before the object arms: a tagged-template\n // client is a FUNCTION, so `typeof client !== \"object\"` would drop it before\n // its connection cap was ever read.\n if (typeof client === \"function\") {\n return isSingleConnectionCallablePgClient(client) ? client : undefined;\n }\n if (typeof client !== \"object\" || client === null) return undefined;\n const candidate = client as Readonly<Record<string, unknown>>;\n if (!hasFunctionProperty(candidate, \"query\")) return undefined;\n if (isSingleConnectionPgPool(candidate)) return client;\n return isBarePgClient(candidate) ? client : undefined;\n}\n\n/** Whether a `pg`-shaped client is a pool whose only connection is shared. */\nfunction isSingleConnectionPgPool(\n candidate: Readonly<Record<string, unknown>>,\n): boolean {\n // `options` is a pg.Pool member (pg.Client has none), and holds the resolved\n // pool configuration. The default is 10, so an absent/other `max` says\n // nothing; what a cap of one looks like is the cap predicate's decision.\n const options: unknown = candidate[\"options\"];\n if (typeof options !== \"object\" || options === null) return false;\n return isSingleConnectionPgPoolCap(\n (options as Readonly<Record<string, unknown>>)[\"max\"],\n );\n}\n\n/**\n * Whether a pg-pool `options.max` means ONE connection.\n *\n * Numeric 1 is the obvious form. A STRING `\"1\"` is not a typo: pg-pool's\n * `options.max = options.max || options.poolSize || 10` (pg-pool 3.x\n * `index.js:89`) never coerces, so `new Pool({ max: process.env.PG_MAX })` —\n * and the legacy `new Pool({ poolSize: \"1\" })`, which lands in the same\n * `options.max` — keeps a string that its own `this._clients.length >=\n * this.options.max` comparison (`index.js:120`) then coerces. The pool really\n * is capped at one.\n *\n * `\"5\"` is NOT evidence: `1 >= \"5\"` is false, so that pool genuinely opens five\n * connections. This is the whole reason the decision is per driver — postgres-js\n * reads the identical value differently, and\n * {@link isSingleConnectionPostgresJsCap} owns that reading.\n */\nfunction isSingleConnectionPgPoolCap(value: unknown): boolean {\n return value === 1 || (typeof value === \"string\" && Number(value) === 1);\n}\n\n/**\n * Whether a CALLABLE Postgres client (a tagged-template `Sql`) is capped at one\n * connection, and is therefore one serialized resource for every wrapper over it.\n *\n * Two pieces of positive evidence, both required:\n *\n * - {@link isPostgresJsClient} — the driver identity, owned by the execution\n * adapter that already discriminates postgres-js from the other callable\n * client (neon-http). Without it, `options.max` on an unknown callable means\n * nothing we can act on.\n * - {@link isSingleConnectionPostgresJsCap} — postgres-js exposes its RESOLVED\n * options on the callable, and its `max` defaults to 10, so only a cap of one\n * says \"every statement lands on the same connection\". An absent or larger\n * `max` abstains: postgres-js at default size hands each `begin` its own\n * connection and marking it would refuse concurrent work that succeeds.\n *\n * NOT covered: Bun's `SQL`. Nothing in this package positively identifies that\n * driver (the SQLite side recognizes `BunSQLiteSession`; there is no Postgres\n * equivalent), and a cap we cannot attribute to a known driver is not evidence.\n * A `Bun.SQL` capped at one connection remains a known gap (#434).\n */\nfunction isSingleConnectionCallablePgClient(client: unknown): boolean {\n if (client === undefined || client === null) return false;\n // Read before the driver check narrows the type: postgres-js's `Sql` type\n // declares no `options` member, so the property is reached through the\n // untyped client rather than the narrowed one.\n const options: unknown = (client as Readonly<Record<string, unknown>>)[\n \"options\"\n ];\n if (!isPostgresJsClient(client)) return false;\n if (typeof options !== \"object\" || options === null) return false;\n return isSingleConnectionPostgresJsCap(\n (options as Readonly<Record<string, unknown>>)[\"max\"],\n );\n}\n\n/**\n * Whether a postgres-js `options.max` means ONE connection.\n *\n * postgres-js resolves `max` from the options object, the URL query string and\n * the `PGMAX` environment variable, and does not coerce it (`max` is absent from\n * its `ints` list, postgres@3.4.9 `src/index.js:447`). So `postgres(url +\n * \"?max=1\")` and `PGMAX=1` both yield the STRING `\"1\"`, which is one connection\n * and is marked, exactly as the numeric `postgres(url, { max: 1 })` is.\n *\n * KNOWN, DELIBERATE GAP: `[...Array(options.max)]` (`src/index.js:65`) yields\n * length 1 for ANY non-numeric string, so `postgres(url + \"?max=5\")` also opens\n * exactly one connection today and can genuinely wedge a stream pair. It is NOT\n * marked, because marking on it means marking on an upstream bug: the moment\n * postgres-js coerces `max`, that configuration becomes a five-connection pool\n * and the mark would refuse legitimate concurrent work. This is why the decision\n * is separate from {@link isSingleConnectionPgPoolCap} — the two predicates read\n * the same value with two justifications, and it is those justifications, not\n * the bodies, that will diverge as either driver changes.\n */\nfunction isSingleConnectionPostgresJsCap(value: unknown): boolean {\n return value === 1 || (typeof value === \"string\" && Number(value) === 1);\n}\n\n/** Whether a `pg`-shaped client owns exactly one connection (Client, not Pool). */\nfunction isBarePgClient(candidate: Readonly<Record<string, unknown>>): boolean {\n // Refuse every pool marker first: `Pool` exposes checkout accounting and its\n // resolved `options`; `Client` exposes none of them.\n if (\n candidate[\"options\"] !== undefined ||\n candidate[\"totalCount\"] !== undefined ||\n candidate[\"idleCount\"] !== undefined ||\n candidate[\"waitingCount\"] !== undefined\n ) {\n return false;\n }\n // Positive `pg.Client` evidence: the connection lifecycle pair plus\n // `escapeIdentifier`, which pg defines on Client and not on Pool.\n return (\n hasFunctionProperty(candidate, \"connect\") &&\n hasFunctionProperty(candidate, \"end\") &&\n hasFunctionProperty(candidate, \"escapeIdentifier\")\n );\n}\n\n/**\n * Exported for unit tests that assert the marking predicate directly against\n * real `pg` `Client` / `Pool` instances; production code reaches it only\n * through {@link createPostgresBackend}.\n *\n * @internal\n */\nexport function isSerializedPostgresClient(client: unknown): boolean {\n return (\n getSerializedPostgresClient({\n $client: client,\n } as unknown as AnyPgDatabase) !== undefined\n );\n}\n\n/**\n * Memoized \"does this server's pgvector support the iterative scan (>= 0.8)?\"\n * probe, plus a one-shot warning when it does not.\n *\n * Created once per {@link createPostgresBackend} and shared with every\n * transaction-scoped operation backend, so the probe query runs once and the\n * pre-0.8 warning fires once per backend instance rather than once per\n * `store.transaction()`. The answer is connection-independent\n * (`pg_extension.extversion`), so caching it across connections is sound.\n */\nexport type IterativeScanProbe = Readonly<{\n isSupported: (\n execAll: <T>(query: SQL) => Promise<readonly T[]>,\n ) => Promise<boolean>;\n}>;\n\n/**\n * Exported for unit testing the memoization / warn-once behavior in isolation;\n * production code reaches it only through {@link createPostgresBackend}.\n */\nexport function createIterativeScanProbe(): IterativeScanProbe {\n let probe: Promise<boolean> | undefined;\n let warned = false;\n\n function warnUnavailable(version: string): void {\n if (warned) return;\n warned = true;\n if (typeof console === \"undefined\" || typeof console.warn !== \"function\") {\n return;\n }\n console.warn(\n `[typegraph] pgvector ${version} has no iterative scan (added in 0.8), ` +\n \"so a filtered approximate vector search stays ef_search-bounded and \" +\n \"can return fewer rows than `limit` while more matches exist. Upgrade \" +\n \"pgvector to >= 0.8, or use an exact search (`approximate: false`) \" +\n \"where a full page matters.\",\n );\n }\n\n return {\n isSupported(execAll) {\n // Probing the GUC directly is unreliable — extension GUCs register only\n // once the extension library has loaded into the session, so a fresh\n // pooled connection reports NULL even on 0.8+. `extversion` is truth.\n probe ??= (async () => {\n try {\n const [row] = await execAll<{ v: string | null }>(\n sql`SELECT extversion AS v FROM pg_extension WHERE extname = 'vector'`,\n );\n if (typeof row?.v !== \"string\") return false;\n const [major = 0, minor = 0] = row.v\n .split(\".\")\n .map((part) => Number.parseInt(part, 10));\n const supported = major > 0 || (major === 0 && minor >= 8);\n if (!supported) warnUnavailable(row.v);\n return supported;\n } catch {\n return false;\n }\n })();\n return probe;\n },\n };\n}\n\ntype CreatePostgresOperationBackendOptions = Readonly<{\n db: AnyPgDatabase;\n executionAdapter: PostgresExecutionAdapter;\n /**\n * Adapter tuning (prepared-statement cache settings). Used to bind a\n * fresh, equivalently-configured adapter to a transaction client when\n * a per-search `efSearch` override opens its own transaction.\n */\n adapterOptions?: PostgresExecutionAdapterOptions | undefined;\n operationStrategy: ReturnType<typeof createPostgresOperationStrategy>;\n tableNames: ResolvedSqlTableNames;\n capabilities: BackendCapabilities;\n fulltextStrategy: FulltextStrategy;\n /**\n * Active vector strategy (`pgvectorStrategy` unless overridden), or\n * `undefined` when vector support is disabled (`vector: false`).\n */\n vectorStrategy: VectorStrategy | undefined;\n /**\n * Shared durable-marker materializer. The vector methods assert a\n * slot's marker (SELECT, never DDL) on the hot path and `createVectorIndex`\n * ensures it (privileged) — replacing the old in-process ensure-latch.\n * Shared across the outer backend and every transaction-scoped backend\n * so a slot's marker is resolved at most once per process.\n */\n contributionMaterializer: ContributionMaterializer;\n /**\n * Shared pgvector iterative-scan probe (memoized version check + one-shot\n * pre-0.8 warning). Owned by the top-level backend and reused by every\n * transaction backend so the warning fires once per backend instance.\n */\n iterativeScanProbe: IterativeScanProbe;\n schemaVersionsTable: PostgresTables[\"schemaVersions\"];\n /** Whether this operation backend is bound to an explicit transaction. */\n transactionScoped: boolean;\n}>;\n\ntype CreatePostgresTransactionBackendOptions = Readonly<{\n db: AnyPgDatabase;\n adapterOptions?: PostgresExecutionAdapterOptions;\n operationStrategy: ReturnType<typeof createPostgresOperationStrategy>;\n tableNames: ResolvedSqlTableNames;\n capabilities: BackendCapabilities;\n fulltextStrategy: FulltextStrategy;\n /** Active vector strategy. See {@link CreatePostgresOperationBackendOptions}. */\n vectorStrategy: VectorStrategy | undefined;\n /** Shared durable-marker materializer. See {@link CreatePostgresOperationBackendOptions}. */\n contributionMaterializer: ContributionMaterializer;\n /** Shared iterative-scan probe. See {@link CreatePostgresOperationBackendOptions}. */\n iterativeScanProbe: IterativeScanProbe;\n schemaVersionsTable: PostgresTables[\"schemaVersions\"];\n}>;\n\nfunction createPostgresOperationBackend(\n options: CreatePostgresOperationBackendOptions,\n): InternalOperationBackend {\n const {\n db,\n executionAdapter,\n adapterOptions,\n operationStrategy,\n tableNames,\n capabilities,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n iterativeScanProbe,\n schemaVersionsTable,\n transactionScoped,\n } = options;\n // Route through the execution adapter so driver-specific result shapes\n // (`{rows}` for node-postgres / neon-serverless; bare array for\n // postgres-js) are normalized in one place.\n async function execAll<T>(query: ExecutableSql): Promise<readonly T[]> {\n return executionAdapter.execute<T>(query);\n }\n\n async function execGet<T>(query: ExecutableSql): Promise<T | undefined> {\n const rows = await executionAdapter.execute<T>(query);\n return rows[0];\n }\n\n async function execRun(query: ExecutableSql): Promise<void> {\n await executionAdapter.execute(query);\n }\n\n type VectorSearchRow = Readonly<{ node_id: string; score: number }>;\n\n /** One transaction-local GUC override applied around a vector SELECT. */\n type SearchGucOverride = Readonly<{ name: string; value: string }>;\n\n // `hnsw.iterative_scan` exists on pgvector >= 0.8. The probe + \"warn once\"\n // state lives on the top-level backend and is SHARED with every\n // transaction-scoped operation backend (see `iterativeScanProbe` in the\n // options), so a pre-0.8 server is probed and warned about once per backend\n // instance — not once per `store.transaction()`.\n function pgvectorIterativeScanSupported(): Promise<boolean> {\n return iterativeScanProbe.isSupported(execAll);\n }\n\n /**\n * The transaction-local GUC overrides for one vector search:\n *\n * - `hnsw.ef_search` when the caller supplied `efSearch` (validated\n * upstream; whether it may be applied at all — and under which parameter\n * name — is {@link resolveEfSearchOverride}, the predicate the SQLite\n * backend reads too, which refuses a non-HNSW slot and a transactionless\n * driver where `SET LOCAL` cannot be scoped).\n * - `hnsw.iterative_scan = strict_order` on HNSW slots (pgvector >= 0.8):\n * the search SQL constrains results to live candidate nodes (and\n * optionally `minScore`), and a plain HNSW scan yields only `ef_search`\n * candidates BEFORE those filters — so a filter-heavy neighborhood can\n * under-fill top-k. The iterative scan keeps yielding until `LIMIT`\n * rows pass or it hits `hnsw.max_scan_tuples` — better recall, not a\n * full-page guarantee. `strict_order` preserves the distance ordering the\n * plan relies on (`relaxed_order` may emit slightly out of order beneath\n * our LIMIT). On pgvector < 0.8 the search stays `ef_search`-bounded and\n * the backend warns once (see `warnIterativeScanUnavailable`).\n * - `ivfflat.iterative_scan = relaxed_order` on IVFFlat slots (same\n * pgvector floor): IVFFlat has no strict_order mode, so the strategy's\n * IVFFlat search SQL re-sorts the relaxed candidate set inside a\n * MATERIALIZED wrapper (see `buildSearch`) to restore exact ordering.\n */\n async function vectorSearchGucOverrides(\n params: Pick<VectorSearchParams, \"efSearch\" | \"indexType\">,\n ): Promise<readonly SearchGucOverride[]> {\n const overrides: SearchGucOverride[] = [];\n const efSearchParameter = resolveEfSearchOverride({\n efSearch: params.efSearch,\n indexType: params.indexType,\n tuning: vectorSearchFrontierTuning(vectorStrategy),\n transactions: capabilities.transactions,\n dialect: \"PostgreSQL\",\n engine: vectorStrategy?.name ?? \"this backend\",\n });\n if (efSearchParameter !== undefined) {\n overrides.push({\n name: efSearchParameter,\n value: String(params.efSearch),\n });\n }\n if (\n params.indexType === \"hnsw\" &&\n capabilities.transactions &&\n (await pgvectorIterativeScanSupported())\n ) {\n overrides.push({ name: \"hnsw.iterative_scan\", value: \"strict_order\" });\n }\n if (\n params.indexType === \"ivfflat\" &&\n capabilities.transactions &&\n (await pgvectorIterativeScanSupported())\n ) {\n overrides.push({\n name: \"ivfflat.iterative_scan\",\n value: \"relaxed_order\",\n });\n }\n return overrides;\n }\n\n /**\n * Runs the vector SELECT, applying the given GUC overrides\n * transaction-locally. `SET LOCAL` semantics (via\n * `set_config(name, value, is_local => true)`, the parameterizable form)\n * only take effect inside an explicit transaction — issued in autocommit\n * they roll off with the statement and the next pooled query (notably\n * under transaction-mode pgbouncer) sees the session default again. So\n * with overrides present we bundle `BEGIN; SET …; SELECT …; COMMIT;`\n * onto one connection. With none we take the unchanged single-statement\n * fast path and open no transaction.\n */\n /**\n * The `SET LOCAL`-scoped vector SELECT, run as one exclusive group on the\n * transaction's connection. See {@link runVectorSearch}.\n */\n async function runVectorSearchGucGroup<Row>(\n overrides: readonly SearchGucOverride[],\n query: ExecutableSql,\n ): Promise<readonly Row[]> {\n const runExclusive = executionAdapter.runExclusive;\n if (runExclusive === undefined) {\n throw new CompilerInvariantError(\n \"A transaction-scoped Postgres backend must expose runExclusive; \" +\n \"its execution adapter was not wrapped by createSerialExecutionAdapter.\",\n );\n }\n return runExclusive(async (connection) => {\n const snapshots: SearchGucOverride[] = [];\n for (const override of overrides) {\n const [setting] = await connection.execute<{ v: string }>(\n sql`SELECT current_setting(${override.name}) AS v`,\n );\n if (setting !== undefined) {\n snapshots.push({ name: override.name, value: setting.v });\n }\n await connection.execute(\n sql`SELECT set_config(${override.name}, ${override.value}, true)`,\n );\n }\n const rows = await connection.execute<Row>(query);\n // Restore only on success: a failed SELECT aborts the caller's\n // transaction, so its rollback discards the overrides anyway and a\n // restore here would just fail against the aborted tx, masking the\n // real error.\n for (const snapshot of snapshots) {\n await connection.execute(\n sql`SELECT set_config(${snapshot.name}, ${snapshot.value}, true)`,\n );\n }\n return rows;\n });\n }\n\n async function runVectorSearch<Row = VectorSearchRow>(\n overrides: readonly SearchGucOverride[],\n query: ExecutableSql,\n ): Promise<readonly Row[]> {\n if (overrides.length === 0) {\n return execAll<Row>(query);\n }\n if (db instanceof PgTransaction) {\n // Already inside the caller's transaction (low-level\n // backend.transaction / adoptTransaction). `executionAdapter` is\n // bound to this tx client, but SET LOCAL persists to the end of the\n // caller's transaction — leaking the override into their later\n // vector searches and breaking the per-search contract. Snapshot\n // the current values, apply the overrides, then restore them once\n // the SELECT has materialized so the overrides stay scoped to this\n // one search.\n //\n // The four steps are ONE critical section, not four serialized\n // statements. A transaction has a single GUC namespace, so two searches\n // that merely take turns interleave as `A snapshot → B snapshot → A set\n // → B set → A select` and `A` runs under `B`'s efSearch. `runExclusive`\n // holds the connection for the whole group; it is always present on a\n // transaction-scoped adapter (see `createTransactionBackend`).\n return runVectorSearchGucGroup(overrides, query);\n }\n return db.transaction(async (tx) => {\n // Bind an equivalently-configured adapter to the tx client so the\n // SELECT keeps the driver result-shape normalization rather than a\n // bespoke execute. A Drizzle transaction carries no `$client`, so this\n // adapter routes through Drizzle's session (no server-side prepared\n // statement) — correct either way, and the statements below are\n // sequential, so they need no serializing wrapper.\n const txAdapter = createPostgresExecutionAdapter(tx, adapterOptions);\n for (const override of overrides) {\n await txAdapter.execute(\n sql`SELECT set_config(${override.name}, ${override.value}, true)`,\n );\n }\n return txAdapter.execute<Row>(query);\n });\n }\n\n const batchConfig = computePostgresBatchChunkSizes(\n capabilities.maxBindParameters ?? POSTGRES_MAX_BIND_PARAMETERS,\n );\n\n const commonOperationMembers = createCommonOperationBackend({\n batchConfig,\n execution: {\n execAll,\n execGet,\n execRun,\n },\n nowIso,\n maxBindParameters:\n capabilities.maxBindParameters ?? POSTGRES_MAX_BIND_PARAMETERS,\n operationStrategy,\n rowMappers: {\n toEdgeRow,\n toNodeRow,\n toSchemaVersionRow,\n toUniqueRow,\n },\n tableExistenceCache: { cacheExisting: false },\n });\n\n const executeCompiled = executionAdapter.executeCompiled;\n const executeRawMethod: Pick<TransactionBackend, \"executeRaw\"> =\n executeCompiled === undefined ?\n {}\n : {\n async executeRaw<T>(\n sqlText: string,\n params: readonly unknown[],\n ): Promise<readonly T[]> {\n return executeCompiled<T>({ params, sql: sqlText });\n },\n };\n\n // Embedding write/search methods are present only when a vector strategy\n // is wired. With `vector: false` (e.g. PGlite without pgvector) they are\n // omitted, so `capabilities.vector` is absent and the store never routes\n // embedding work here — mirroring a SQLite connection without sqlite-vec.\n const vectorEmbeddingMethods =\n vectorStrategy === undefined ?\n {}\n : {\n async upsertEmbedding(params: UpsertEmbeddingParams): Promise<void> {\n const slot = vectorSlotFromParams(params);\n // Assert the slot's durable marker (SELECT, cached) — never DDL.\n // The per-field table is provisioned by the privileged migrator\n // (`createStoreWithSchema` → `materializeVectorContributions`), so\n // a least-privilege runtime role writes embeddings without CREATE.\n await contributionMaterializer.assertVectorSlot(slot);\n const statements = vectorStrategy.buildUpsert(slot, params, nowIso());\n try {\n for (const statement of statements) {\n await execRun(statement);\n }\n } catch (error) {\n throw mapVectorWriteError(error, params);\n }\n },\n\n async upsertEmbeddingBatch(\n params: UpsertEmbeddingBatchParams,\n ): Promise<void> {\n if (params.rows.length === 0) return;\n const slot = vectorSlotFromParams(params);\n // Same SELECT-only marker assert as the single-row path — never DDL.\n await contributionMaterializer.assertVectorSlot(slot);\n // Last-write-wins dedupe: a multi-row upsert cannot affect one\n // row twice.\n const rowsById = new Map(\n params.rows.map((row) => [row.nodeId, row] as const),\n );\n const rows = [...rowsById.values()];\n const timestamp = nowIso();\n try {\n for (const chunk of chunkArray(\n rows,\n batchConfig.embeddingUpsertBatchSize,\n )) {\n const statements =\n vectorStrategy.buildUpsertBatch === undefined ?\n chunk.flatMap((row) =>\n vectorStrategy.buildUpsert(\n slot,\n {\n graphId: params.graphId,\n nodeKind: params.nodeKind,\n nodeId: row.nodeId,\n fieldPath: params.fieldPath,\n embedding: row.embedding,\n dimensions: params.dimensions,\n metric: params.metric,\n indexType: params.indexType,\n },\n timestamp,\n ),\n )\n : vectorStrategy.buildUpsertBatch(\n slot,\n { ...params, rows: chunk },\n timestamp,\n );\n for (const statement of statements) {\n await execRun(statement);\n }\n }\n } catch (error) {\n throw mapVectorWriteError(error, params);\n }\n },\n\n async deleteEmbedding(params: DeleteEmbeddingParams): Promise<void> {\n // Assert the slot's durable marker before deleting. A delete can\n // run before any embedding was ever written for the field (e.g. a\n // node hard-deleted having never carried one); the per-field table\n // was provisioned at boot, so the DELETE targets an existing\n // (possibly empty) table and is a clean no-op — never a DELETE\n // against a missing relation, which would abort an enclosing\n // Postgres transaction. SELECT-only assert, never DDL.\n const slot = vectorSlotFromParams(params);\n await contributionMaterializer.assertVectorSlot(slot);\n const statements = vectorStrategy.buildDelete(slot, params);\n for (const statement of statements) {\n await execRun(statement);\n }\n },\n async deleteEmbeddingBatch(\n params: Omit<DeleteEmbeddingParams, \"nodeId\"> &\n Readonly<{ nodeIds: readonly string[] }>,\n ): Promise<void> {\n if (params.nodeIds.length === 0) return;\n const slot = vectorSlotFromParams(params);\n await contributionMaterializer.assertVectorSlot(slot);\n for (const nodeIds of chunkArray(\n [...new Set(params.nodeIds)],\n batchConfig.embeddingUpsertBatchSize,\n )) {\n const statements = vectorStrategy.buildDeleteBatch(slot, {\n ...params,\n nodeIds,\n });\n for (const statement of statements) await execRun(statement);\n }\n },\n\n async vectorSearch(\n params: VectorSearchParams,\n ): Promise<readonly VectorSearchResult[]> {\n assertVectorSearchLimit(params.limit);\n // Validate `efSearch` against pgvector's `hnsw.ef_search` ceiling\n // before `runVectorSearch` applies it via `set_config`.\n assertPgvectorEfSearch(params.efSearch);\n const slot = vectorSlotFromParams(params);\n // Deliberately NOT marker-gated: search is read-only (no DDL\n // hazard to gate), and its params carry the caller's runtime\n // metric override, which legitimately diverges from the\n // provisioned shape on strategies that bake the metric into the\n // DDL (sqlite-vec; pgvector's table DDL is metric-free but the\n // contract is kept identical across dialects). An unprovisioned\n // slot surfaces the engine's missing-relation error — the same\n // contract as a query-builder `similarTo()` predicate;\n // `createVerifiedStore` catches both at attach.\n const query = vectorStrategy.buildSearch(\n slot,\n params,\n // Store-compiled candidates (predicates + subclass + currency)\n // take precedence; the live-node default covers direct backend use.\n params.candidates ??\n buildLiveNodeCandidates(\n tableNames.nodes,\n params.graphId,\n params.nodeKind,\n nowIso(),\n ),\n );\n const gucOverrides = await vectorSearchGucOverrides(params);\n let rows: readonly { node_id: string; score: number }[];\n try {\n rows = await runVectorSearch(gucOverrides, query);\n } catch (error) {\n // A query vector whose dimension no longer matches the stored\n // column surfaces the same typed error as the write path.\n throw mapVectorWriteError(error, params);\n }\n return rows.map((row) => ({\n nodeId: row.node_id,\n score: row.score,\n }));\n },\n // Single-statement hybrid needs ROW_NUMBER(); a capability\n // profile that disables window functions keeps the store's\n // multi-statement fallback by simply not exposing the member.\n ...(capabilities.windowFunctions ?\n {\n async hybridSearch(\n params: HybridSearchParams,\n ): Promise<readonly HybridSearchRow[]> {\n assertVectorSearchLimit(params.limit);\n // Source depths get the same boundary validation the fallback\n // path applies (vectorSearch validates its limit; the fulltext\n // depth is validated inside buildFulltextSearch).\n assertVectorSearchLimit(params.vector.k);\n assertPgvectorEfSearch(params.vector.efSearch);\n const slot = vectorSlotFromParams({\n graphId: params.graphId,\n nodeKind: params.nodeKind,\n fieldPath: params.vector.fieldPath,\n dimensions: params.vector.dimensions,\n metric: params.vector.metric,\n indexType: params.vector.indexType,\n });\n // Read-only, not marker-gated — see vectorSearch above.\n const candidates =\n params.candidates ??\n buildLiveNodeCandidates(\n tableNames.nodes,\n params.graphId,\n params.nodeKind,\n nowIso(),\n );\n const vectorParams: VectorSearchParams = {\n graphId: params.graphId,\n nodeKind: params.nodeKind,\n fieldPath: params.vector.fieldPath,\n queryEmbedding: params.vector.queryEmbedding,\n metric: params.vector.metric,\n dimensions: params.vector.dimensions,\n indexType: params.vector.indexType,\n limit: params.vector.k,\n ...(params.vector.minScore === undefined ?\n {}\n : { minScore: params.vector.minScore }),\n };\n // The vector leg references the statement's shared\n // tg_hybrid_cand CTE; the actual candidates SQL is emitted\n // once by buildHybridSearch.\n const vectorSql = vectorStrategy.buildSearch(\n slot,\n vectorParams,\n portableSql.raw(\"SELECT node_id FROM tg_hybrid_cand\"),\n );\n const statement = operationStrategy.buildHybridSearch(\n { ...params, candidates },\n toDrizzleSql(vectorSql, \"postgres\"),\n params.vector.metric === \"cosine\",\n );\n const gucOverrides = await vectorSearchGucOverrides({\n indexType: params.vector.indexType,\n ...(params.vector.efSearch === undefined ?\n {}\n : { efSearch: params.vector.efSearch }),\n });\n let raw: readonly Record<string, unknown>[];\n try {\n raw = await runVectorSearch<Record<string, unknown>>(\n gucOverrides,\n statement,\n );\n } catch (error) {\n throw mapVectorWriteError(error, vectorParams);\n }\n return raw.map((row) => mapHybridSearchRow(row, toNodeRow));\n },\n }\n : {}),\n };\n\n /**\n * Takes the transaction-scoped share lock on the graph's active schema row,\n * returning the version it locked — or `undefined` when the statement found\n * no active row to lock, which at `read committed` does not by itself mean the\n * graph has no active version — see the fence that calls this.\n */\n async function lockActiveSchemaVersion(\n graphId: string,\n ): Promise<number | undefined> {\n const active = await execGet<{ version: number }>(sql`\n SELECT ${schemaVersionsTable.version} AS version\n FROM ${schemaVersionsTable}\n WHERE ${schemaVersionsTable.graphId} = ${graphId}\n AND ${schemaVersionsTable.isActive} = TRUE\n FOR SHARE\n `);\n return active?.version;\n }\n\n const operationBackend: InternalOperationBackend = {\n ...commonOperationMembers,\n ...executeRawMethod,\n ...vectorEmbeddingMethods,\n /**\n * Transaction-scoped contribution marker stamp. Present so the\n * destructive rebuild can commit its marker with the DDL that\n * produced it; without it the stamp would land outside the\n * transaction and could survive a rolled-back drop.\n *\n * States the row outright rather than reusing the top-level upsert,\n * whose `materialized_at` COALESCE preserves an earlier success so a\n * failed re-attempt cannot erase it. A completed rebuild replaced the\n * storage, so the recorded timestamp must be the rebuild's.\n */\n async recordContributionMaterialization(\n params: RecordContributionMaterializationParams,\n ): Promise<void> {\n await execRun(\n operationStrategy.buildInsertContributionMaterialization(params),\n );\n },\n\n async deleteSchemaVectorSlotContribution(slot: VectorSlot): Promise<void> {\n if (vectorStrategy === undefined) return;\n for (const contribution of vectorStrategy.ownedTables(slot)) {\n await execRun(\n operationStrategy.buildDeleteContributionMaterialization({\n graphId: slot.graphId,\n logicalName: contribution.logicalName,\n owner: contribution.owner,\n tableName: contribution.tableName,\n }),\n );\n }\n // Eviction is conservative if the surrounding transaction later rolls\n // back: the next access re-reads the still-durable marker.\n contributionMaterializer.evictVectorSlot(slot);\n },\n capabilities,\n fulltextStrategy,\n ...(vectorStrategy === undefined ? {} : { vectorStrategy }),\n dialect: \"postgres\",\n tableNames,\n\n async lockSchemaVersionForWrite(\n params: LockSchemaVersionForWriteParams,\n ): Promise<void> {\n if (!transactionScoped) {\n throw new ConfigurationError(\n \"The schema write fence requires an explicit PostgreSQL transaction.\",\n {\n code: \"SCHEMA_WRITE_FENCE_TRANSACTION_REQUIRED\",\n graphId: params.graphId,\n },\n );\n }\n const locked = await lockActiveSchemaVersion(params.graphId);\n if (locked !== undefined) {\n assertActiveSchemaVersion(\n params.graphId,\n params.expectedVersion,\n locked,\n );\n return;\n }\n\n // An empty locked read is not evidence of an absent active version. At\n // `read committed`, a `FOR SHARE` read that blocks behind an in-flight\n // schema commit rechecks only the row versions its own statement snapshot\n // saw: once that commit lands, the row this statement waited on no longer\n // satisfies `is_active = TRUE`, and the winner's freshly inserted active\n // row was never in the snapshot to be substituted in.\n //\n // Either way this transaction holds no share lock on an active row, so the\n // write is rejected. That is why the version reported below needs no lock\n // of its own — and why the fence must NOT retry the locked read: the\n // dropped row keeps the share lock the first read took on it, so a second\n // `FOR SHARE` waits on the row the *next* schema commit has already taken\n // `FOR UPDATE` while that commit waits on the dropped row in its\n // deactivate-all. PostgreSQL breaks the cycle by killing one of the two,\n // and the schema commit — waiting first, so timing out first — is the one\n // that dies.\n //\n // A non-locking read names the version honestly: a schema commit's\n // deactivate-then-insert pair is atomic, so no committed state has zero\n // active rows for a graph that has one, and an ordinary read never waits\n // and so has no recheck to be fooled by. It yields `0` only for a graph\n // that genuinely has no active version. A rollback landing back on\n // `expectedVersion` reports `expected === actual`; the rejection stands,\n // because nothing is holding the fence.\n const settled = await commonOperationMembers.getActiveSchema(\n params.graphId,\n );\n throw new StaleVersionError({\n graphId: params.graphId,\n expected: params.expectedVersion,\n actual: settled?.version ?? 0,\n });\n },\n\n // === Vector Index Operations ===\n\n async createVectorIndex(params: CreateVectorIndexParams): Promise<void> {\n if (vectorStrategy === undefined) return;\n const slot = vectorSlotFromCreateIndexParams(params);\n // Ensure the per-field table + its durable marker first (privileged,\n // idempotent), then create its ANN index. pgvector's `ownedTables`\n // builds the table only — the HNSW/IVFFlat index is created here (and\n // only here) so it picks up the declared `m`/`ef_construction`/`lists`\n // from `slot.indexParams` rather than defaults.\n await contributionMaterializer.ensureVectorSlot(slot);\n // Honor the `concurrent` flag materializeIndexes passes on Postgres so the\n // ANN build doesn't take a write-blocking lock on a live table. execRun is\n // autocommit, which CONCURRENTLY requires.\n const indexStatement = vectorStrategy.buildCreateIndex?.(slot, {\n concurrent: params.concurrent === true,\n });\n if (indexStatement !== undefined) {\n const strategyTableName = vectorStrategy.tableName(\n slot.graphId,\n slot.nodeKind,\n slot.fieldPath,\n );\n // Built-in pgvector HNSW/IVFFlat builds stage the build graph in dynamic\n // shared memory, and resource-constrained hosts reject the\n // allocation (SQLSTATE class 53 — e.g. containers with the 64MB\n // /dev/shm default fail a 50k x 384-dim HNSW build with 53100\n // from dsm_impl_posix). Retry serially: drop the INVALID\n // leftover the failed CONCURRENTLY build leaves behind (its\n // IF NOT EXISTS would otherwise mask the retry), pin the\n // strategy table to parallel_workers = 0 (maintenance builds\n // take min(storage parameter, max_parallel_maintenance_workers)),\n // rebuild in local memory, and restore the setting.\n await runPostgresVectorIndexBuild(\n vectorStrategy,\n execRun,\n strategyTableName,\n indexStatement,\n vectorStrategy.buildDropIndex?.(slot),\n );\n }\n },\n\n // === Fulltext Operations ===\n\n async upsertFulltext(params: UpsertFulltextParams): Promise<void> {\n const timestamp = nowIso();\n const statements = operationStrategy.buildUpsertFulltext(\n params,\n timestamp,\n );\n for (const stmt of statements) {\n await execRun(stmt);\n }\n },\n\n async deleteFulltext(params: DeleteFulltextParams): Promise<void> {\n const statements = operationStrategy.buildDeleteFulltext(params);\n for (const stmt of statements) {\n await execRun(stmt);\n }\n },\n\n async upsertFulltextBatch(\n params: UpsertFulltextBatchParams,\n ): Promise<void> {\n if (params.rows.length === 0) return;\n const timestamp = nowIso();\n // The strategy emits ONE statement over every row it is given, so\n // the bind budget is enforced here — same contract as node/edge\n // batch inserts.\n for (const rows of chunkArray(\n params.rows,\n batchConfig.fulltextUpsertBatchSize,\n )) {\n const statements = operationStrategy.buildUpsertFulltextBatch(\n { ...params, rows },\n timestamp,\n );\n for (const stmt of statements) {\n await execRun(stmt);\n }\n }\n },\n\n async deleteFulltextBatch(\n params: DeleteFulltextBatchParams,\n ): Promise<void> {\n if (params.nodeIds.length === 0) return;\n for (const nodeIds of chunkArray(\n params.nodeIds,\n batchConfig.fulltextDeleteChunkSize,\n )) {\n const statements = operationStrategy.buildDeleteFulltextBatch({\n ...params,\n nodeIds,\n });\n for (const stmt of statements) {\n await execRun(stmt);\n }\n }\n },\n\n async fulltextSearch(\n params: FulltextSearchParams,\n ): Promise<readonly FulltextSearchResult[]> {\n const query = operationStrategy.buildFulltextSearch(params);\n // pg returns `numeric` as a string to preserve precision; coerce at the\n // backend boundary so FulltextSearchResult.score is always `number`.\n const rows = await execAll<{\n node_id: string;\n score: number | string;\n snippet: string | null;\n }>(query);\n return rows.map((row, index) => ({\n nodeId: row.node_id,\n score: coerceNumericScore(row.score),\n rank: index + 1,\n ...(row.snippet === null ? {} : { snippet: row.snippet }),\n }));\n },\n\n async dropVectorIndex(params: DropVectorIndexParams): Promise<void> {\n if (vectorStrategy === undefined) return;\n const slot = vectorSlotFromDropIndexParams(params);\n const dropStatement = vectorStrategy.buildDropIndex?.(slot);\n if (dropStatement === undefined) return;\n try {\n await execRun(dropStatement);\n } catch (error) {\n // The per-field table (and thus its index) may never have been\n // materialized; treat a missing relation as already-dropped.\n if (!isMissingTableError(error)) throw error;\n }\n },\n\n // === Query Execution ===\n\n async execute<T>(query: CompiledRowsSql): Promise<readonly T[]> {\n // Statements the compiler branded as containing an ANN index scan\n // (inline `approximate: true`) get the same pgvector GUC wrapping\n // the search facade applies — most importantly\n // `hnsw.iterative_scan = strict_order`, without which a filtered\n // approximate query starves at the default ef_search frontier.\n // On pgvector < 0.8 the override list is empty and this falls\n // through to the plain fast path.\n const annTypes =\n isSqlFragment(query) ? annIndexScanTypes(query) : undefined;\n if (annTypes !== undefined && vectorStrategy !== undefined) {\n const overrides: SearchGucOverride[] = [];\n for (const indexType of annTypes) {\n if (indexType !== \"hnsw\" && indexType !== \"ivfflat\") continue;\n overrides.push(...(await vectorSearchGucOverrides({ indexType })));\n }\n return runVectorSearch<T>(overrides, query);\n }\n return executionAdapter.execute<T>(query);\n },\n\n compileSql(\n query: SqlFragment,\n ): Readonly<{ sql: string; params: readonly unknown[] }> {\n return executionAdapter.compile(query);\n },\n };\n\n return operationBackend;\n}\n\n/**\n * A transaction-scoped backend plus the hook that shuts its statement queue\n * at the transaction boundary. See {@link SerialExecutionAdapter.drainAndClose}.\n */\ntype BoundTransactionBackend = Readonly<{\n backend: InternalOperationBackend;\n drainAndClose: () => Promise<void>;\n}>;\n\nfunction createTransactionBackend(\n options: CreatePostgresTransactionBackendOptions,\n): BoundTransactionBackend {\n // Every statement this backend issues rides one pinned connection, which\n // can carry exactly one query at a time. Serialize them here rather than\n // relying on the driver's own queue: node-postgres deprecated\n // `client.query()` on a busy client in 8.22 and removes the queue in pg@9.\n // The wrap is unconditional because the overlap is created inside TypeGraph\n // (the node write pipeline syncs embeddings and fulltext concurrently), not\n // only by user code.\n const txExecutionAdapter = createSerialExecutionAdapter(\n createPostgresExecutionAdapter(options.db, options.adapterOptions),\n );\n\n // The transaction-scoped backend shares the outer backend's\n // contribution materializer: the per-field vector table is provisioned\n // (DDL) only by the privileged outer backend, so a tx-scoped vector op\n // only ASSERTS the durable marker (SELECT, never DDL) and can't poison\n // anything on rollback. The shared per-instance cache means a slot\n // confirmed once stays a pure `Set.has` inside every later transaction.\n const backend = createPostgresOperationBackend({\n db: options.db,\n executionAdapter: txExecutionAdapter,\n adapterOptions: options.adapterOptions,\n operationStrategy: options.operationStrategy,\n tableNames: options.tableNames,\n capabilities: options.capabilities,\n fulltextStrategy: options.fulltextStrategy,\n vectorStrategy: options.vectorStrategy,\n contributionMaterializer: options.contributionMaterializer,\n // The probe is process-wide truth, so the outer instance's is reused\n // rather than a fresh one per transaction.\n iterativeScanProbe: options.iterativeScanProbe,\n schemaVersionsTable: options.schemaVersionsTable,\n transactionScoped: true,\n });\n\n return { backend, drainAndClose: txExecutionAdapter.drainAndClose };\n}\n\n// Re-export schema utilities\nexport type { PostgresTableNames, PostgresTables } from \"./schema/postgres\";\nexport { createPostgresTables, tables } from \"./schema/postgres\";\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/backend/sqlite/local-options.ts","../src/backend/sqlite/local.ts"],"names":["tables"],"mappings":";;;;;;;;;;AA8BO,IAAM,4BAAA,GACX;AAAA,EACE,WAAA,EAAa,KAAA;AAAA,EACb,WAAA,EAAa,QAAA;AAAA,EACb,aAAA,EAAe,GAAA;AAAA,EACf,YAAA,EAAc,MAAA;AAAA,EACd,aAAA,EAAe,MAAA;AAAA,EACf,sBAAA,EAAwB;AAC1B;;;AC0BF,IAAM,WAAA,GAAc,aAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA;AAWjD,SAAS,uBAAuB,KAAA,EAAwB;AACtD,EAAA,IAAI,KAAA,YAAiB,KAAA,EAAO,OAAO,KAAA,CAAM,OAAA;AACzC,EAAA,OAAO,OAAO,KAAK,CAAA;AACrB;AAEA,SAAS,sCACP,OAAA,EACuC;AACvC,EAAA,MAAM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ent":["/** Journal modes accepted by local SQLite connections. */\nexport type LocalSqliteJournalMode =\n \"wal\" | \"delete\" | \"truncate\" | \"persist\" | \"memory\" | \"off\";\n\n/** Synchronous levels accepted by local SQLite connections. */\nexport type LocalSqliteSynchronousMode = \"off\" | \"normal\" | \"full\" | \"extra\";\n\n/** Connection pragmas applied when TypeGraph opens a local SQLite database. */\nexport type LocalSqlitePragmaOptions = Readonly<{\n /** `PRAGMA journal_mode`. Default: `\"wal\"` (no-op on `\":memory:\"`). */\n journalMode?: LocalSqliteJournalMode;\n /** `PRAGMA synchronous`. Default: `\"normal\"`. */\n synchronous?: LocalSqliteSynchronousMode;\n /** `PRAGMA busy_timeout`, in milliseconds. Default: `5000`. */\n busyTimeoutMs?: number;\n /**\n * `PRAGMA cache_size`, expressed as a negative KiB value. Positive values\n * mean pages in SQLite and are rejected to prevent accidental oversizing.\n */\n cacheSizeKib?: number | undefined;\n /** `PRAGMA mmap_size`, in non-negative bytes. */\n mmapSizeBytes?: number | undefined;\n /**\n * `PRAGMA wal_autocheckpoint`, in WAL pages. Use `0` to disable automatic\n * checkpoints and run them explicitly after controlled bulk loads.\n */\n walAutocheckpointPages?: number | undefined;\n}>;\n\n/** Defaults for TypeGraph-owned local SQLite connections. */\nexport const DEFAULT_LOCAL_SQLITE_PRAGMAS: Required<LocalSqlitePragmaOptions> =\n {\n journalMode: \"wal\",\n synchronous: \"normal\",\n busyTimeoutMs: 5000,\n cacheSizeKib: undefined,\n mmapSizeBytes: undefined,\n walAutocheckpointPages: undefined,\n };\n","/**\n * Local SQLite backend using better-sqlite3.\n *\n * This module depends on the `better-sqlite3` native addon and should only\n * be imported in Node.js environments. For bundler-friendly SQLite DDL\n * generation and Drizzle backend creation, import from `@nicia-ai/typegraph/adapters/drizzle/sqlite`.\n *\n * @example In-memory database (default)\n * ```typescript\n * import { createLocalSqliteBackend } from \"@nicia-ai/typegraph/adapters/drizzle/sqlite/local\";\n *\n * const { backend, db } = createLocalSqliteBackend();\n * const store = createStore(graph, backend);\n * ```\n *\n * @example File-based database for persistent local development\n * ```typescript\n * import { createLocalSqliteBackend } from \"@nicia-ai/typegraph/adapters/drizzle/sqlite/local\";\n *\n * const { backend, db } = createLocalSqliteBackend({ path: \"./dev.db\" });\n * const store = createStore(graph, backend);\n * ```\n */\nimport { createRequire } from \"node:module\";\n\nimport Database from \"better-sqlite3\";\nimport {\n type BetterSQLite3Database,\n drizzle,\n} from \"drizzle-orm/better-sqlite3\";\n\nimport { ConfigurationError } from \"../../errors\";\nimport { sqliteVecStrategy } from \"../../query/dialect/vector/sqlite-vec-strategy\";\nimport { wrapWithManagedClose } from \"../derive-backend\";\nimport { generateSqliteDDL } from \"../drizzle/ddl\";\nimport { type AnySqliteDatabase } from \"../drizzle/execution\";\nexport type { AnySqliteDatabase } from \"../drizzle/execution\";\nimport {\n createSqliteBackend,\n type SqliteTables,\n tables as defaultTables,\n} from \"../drizzle/sqlite\";\nimport {\n DEFAULT_LOCAL_SQLITE_PRAGMAS,\n type LocalSqliteJournalMode,\n type LocalSqlitePragmaOptions,\n type LocalSqliteSynchronousMode,\n} from \"./local-options\";\n\nexport {\n DEFAULT_LOCAL_SQLITE_PRAGMAS,\n type LocalSqliteJournalMode,\n type LocalSqlitePragmaOptions,\n type LocalSqliteSynchronousMode,\n} from \"./local-options\";\nimport { type AdapterBackend, type BackendCapabilities } from \"../types\";\n\nexport type {\n ContributionDiagnostic,\n ContributionDiagnosticState,\n ContributionRepairEntry,\n ContributionRepairResult,\n} from \"../types\";\n\nconst nodeRequire = createRequire(import.meta.url);\n\n// ============================================================\n// Native Addon Helpers\n// ============================================================\n\ntype NodeModuleVersionMismatch = Readonly<{\n compiled: number;\n required: number;\n}>;\n\nfunction getUnknownErrorMessage(error: unknown): string {\n if (error instanceof Error) return error.message;\n return String(error);\n}\n\nfunction parseNodeModuleVersionMismatchMessage(\n message: string,\n): NodeModuleVersionMismatch | undefined {\n const regexp =\n /NODE_MODULE_VERSION (?<compiled>\\d+)[\\s\\S]*?NODE_MODULE_VERSION (?<required>\\d+)/;\n const match = regexp.exec(message);\n if (!match?.groups) return undefined;\n\n const compiled = Number(match.groups[\"compiled\"]);\n const required = Number(match.groups[\"required\"]);\n\n if (!Number.isFinite(compiled) || !Number.isFinite(required))\n return undefined;\n\n return { compiled, required };\n}\n\nfunction createDatabase(path: string): Database.Database {\n try {\n return new Database(path);\n } catch (error) {\n const message = getUnknownErrorMessage(error);\n const mismatch = parseNodeModuleVersionMismatchMessage(message);\n if (!mismatch) throw error;\n\n throw new ConfigurationError(\n [\n \"Failed to load better-sqlite3 native addon.\",\n `It was compiled for NODE_MODULE_VERSION ${mismatch.compiled}, but this Node.js runtime requires ${mismatch.required}.`,\n \"This usually happens after switching Node versions without rebuilding native dependencies.\",\n \"Rebuild with: pnpm rebuild better-sqlite3 (or npm rebuild better-sqlite3).\",\n ].join(\" \"),\n {\n nodeVersion: process.version,\n nodeModuleVersion: process.versions.modules,\n compiledNodeModuleVersion: mismatch.compiled,\n requiredNodeModuleVersion: mismatch.required,\n },\n { cause: error },\n );\n }\n}\n\n// ============================================================\n// Types\n// ============================================================\n\nconst LOCAL_SQLITE_JOURNAL_MODES: readonly LocalSqliteJournalMode[] = [\n \"wal\",\n \"delete\",\n \"truncate\",\n \"persist\",\n \"memory\",\n \"off\",\n];\n\nconst LOCAL_SQLITE_SYNCHRONOUS_MODES: readonly LocalSqliteSynchronousMode[] = [\n \"off\",\n \"normal\",\n \"full\",\n \"extra\",\n];\n\nconst SQLITE_MAX_WAL_AUTOCHECKPOINT_PAGES = 2_147_483_647;\n\nfunction applyConnectionPragmas(\n sqlite: Database.Database,\n pragmas: LocalSqlitePragmaOptions | false | undefined,\n): void {\n if (pragmas === false) return;\n const resolved: Required<LocalSqlitePragmaOptions> = {\n ...DEFAULT_LOCAL_SQLITE_PRAGMAS,\n ...pragmas,\n };\n\n // Runtime guards mirror the compile-time unions: pragma values are spliced\n // into pragma statements, so reject anything outside the allowlists rather\n // than forwarding it to SQLite.\n if (!LOCAL_SQLITE_JOURNAL_MODES.includes(resolved.journalMode)) {\n throw new ConfigurationError(\n `Invalid journalMode pragma: ${resolved.journalMode}. ` +\n `Expected one of: ${LOCAL_SQLITE_JOURNAL_MODES.join(\", \")}.`,\n { journalMode: resolved.journalMode },\n );\n }\n if (!LOCAL_SQLITE_SYNCHRONOUS_MODES.includes(resolved.synchronous)) {\n throw new ConfigurationError(\n `Invalid synchronous pragma: ${resolved.synchronous}. ` +\n `Expected one of: ${LOCAL_SQLITE_SYNCHRONOUS_MODES.join(\", \")}.`,\n { synchronous: resolved.synchronous },\n );\n }\n if (\n !Number.isSafeInteger(resolved.busyTimeoutMs) ||\n resolved.busyTimeoutMs < 0\n ) {\n throw new ConfigurationError(\n `Invalid busyTimeoutMs pragma: ${String(resolved.busyTimeoutMs)}. ` +\n \"Expected a non-negative integer number of milliseconds.\",\n { busyTimeoutMs: resolved.busyTimeoutMs },\n );\n }\n if (\n resolved.cacheSizeKib !== undefined &&\n (!Number.isSafeInteger(resolved.cacheSizeKib) || resolved.cacheSizeKib >= 0)\n ) {\n throw new ConfigurationError(\n `Invalid cacheSizeKib pragma: ${String(resolved.cacheSizeKib)}. ` +\n \"Expected a negative safe integer — SQLite's own cache_size pragma \" +\n \"interprets a positive value as a page count, not KiB, so a caller \" +\n 'who passes e.g. 131072 meaning \"131072 KiB\" silently gets ' +\n \"131072 pages (~512MiB at the default 4KiB page size) instead.\",\n { cacheSizeKib: resolved.cacheSizeKib },\n );\n }\n if (\n resolved.mmapSizeBytes !== undefined &&\n (!Number.isSafeInteger(resolved.mmapSizeBytes) ||\n resolved.mmapSizeBytes < 0)\n ) {\n throw new ConfigurationError(\n `Invalid mmapSizeBytes pragma: ${String(resolved.mmapSizeBytes)}. ` +\n \"Expected a non-negative safe integer number of bytes.\",\n { mmapSizeBytes: resolved.mmapSizeBytes },\n );\n }\n if (\n resolved.walAutocheckpointPages !== undefined &&\n (!Number.isSafeInteger(resolved.walAutocheckpointPages) ||\n resolved.walAutocheckpointPages < 0 ||\n resolved.walAutocheckpointPages > SQLITE_MAX_WAL_AUTOCHECKPOINT_PAGES)\n ) {\n throw new ConfigurationError(\n `Invalid walAutocheckpointPages pragma: ${String(resolved.walAutocheckpointPages)}. ` +\n `Expected an integer between 0 and ${SQLITE_MAX_WAL_AUTOCHECKPOINT_PAGES} ` +\n \"WAL pages (0 disables automatic checkpointing entirely).\",\n { walAutocheckpointPages: resolved.walAutocheckpointPages },\n );\n }\n\n // \":memory:\" databases always journal in memory; SQLite answers the WAL\n // request with \"memory\" instead of erroring, so no special-casing needed.\n sqlite.pragma(`journal_mode = ${resolved.journalMode}`);\n sqlite.pragma(`synchronous = ${resolved.synchronous}`);\n sqlite.pragma(`busy_timeout = ${resolved.busyTimeoutMs}`);\n if (resolved.cacheSizeKib !== undefined) {\n sqlite.pragma(`cache_size = ${resolved.cacheSizeKib}`);\n }\n if (resolved.mmapSizeBytes !== undefined) {\n sqlite.pragma(`mmap_size = ${resolved.mmapSizeBytes}`);\n }\n if (resolved.walAutocheckpointPages !== undefined) {\n sqlite.pragma(`wal_autocheckpoint = ${resolved.walAutocheckpointPages}`);\n }\n}\n\n/**\n * Options for creating a local SQLite backend.\n */\nexport type LocalSqliteBackendOptions = Readonly<{\n /**\n * Path to the SQLite database file.\n * Defaults to \":memory:\" for an in-memory database.\n */\n path?: string;\n\n /**\n * Connection pragmas applied at open. Defaults to\n * {@link DEFAULT_LOCAL_SQLITE_PRAGMAS} (WAL, `synchronous=NORMAL`, 5s busy\n * timeout, and SQLite's own tiny built-in page cache / disabled mmap\n * left untouched). Individual values merge over the defaults; pass\n * `false` to skip pragma configuration entirely and keep the driver\n * defaults (rollback journal, `synchronous=FULL`, and better-sqlite3's\n * own 5s busy timeout from its `timeout` constructor option). Set\n * `cacheSizeKib`/`mmapSizeBytes` explicitly once a database's working\n * set is known to exceed SQLite's 2MiB default cache — otherwise every\n * query pays a fresh disk read per page past that tiny working set. Set\n * `walAutocheckpointPages` explicitly for a bulk-insert-heavy workload —\n * SQLite's own default checkpoints every ~4MiB of WAL growth, which gets\n * more expensive as the database file grows over a large load.\n */\n pragmas?: LocalSqlitePragmaOptions | false;\n\n /**\n * Custom table definitions.\n * Defaults to standard TypeGraph table names.\n */\n tables?: SqliteTables;\n\n /**\n * Override specific backend capabilities — e.g. to simulate an engine-level\n * gap like missing SQL window functions in tests. Forwarded to\n * createSqliteBackend.\n */\n capabilities?: Partial<BackendCapabilities>;\n}>;\n\n/**\n * Result of creating a local SQLite backend.\n */\nexport type LocalSqliteBackendResult = Readonly<{\n /**\n * The GraphBackend instance for use with createStore.\n */\n backend: AdapterBackend<AnySqliteDatabase>;\n\n /**\n * The underlying Drizzle database instance.\n * Useful for direct SQL access or cleanup.\n */\n db: BetterSQLite3Database;\n}>;\n\n// ============================================================\n// Factory Function\n// ============================================================\n\n/**\n * Creates a SQLite backend with minimal configuration.\n *\n * This is a convenience function for local development and testing.\n * It handles database creation, schema migration, and backend setup.\n *\n * For production deployments or custom configurations, use createSqliteBackend\n * directly with your own Drizzle database instance.\n *\n * @param options - Configuration options\n * @returns Backend and database instances\n *\n * @example In-memory database (default)\n * ```typescript\n * const { backend } = createLocalSqliteBackend();\n * const store = createStore(graph, backend);\n * ```\n *\n * @example File-based database\n * ```typescript\n * const { backend, db } = createLocalSqliteBackend({ path: \"./data.db\" });\n * const store = createStore(graph, backend);\n * ```\n */\nexport function createLocalSqliteBackend(\n options: LocalSqliteBackendOptions = {},\n): LocalSqliteBackendResult {\n const path = options.path ?? \":memory:\";\n const tables = options.tables ?? defaultTables;\n\n const sqlite = createDatabase(path);\n try {\n applyConnectionPragmas(sqlite, options.pragmas);\n\n // Best-effort: load sqlite-vec so embedding fields are persisted to\n // per-`(kind, field)` `vec0` storage. Without it, nodes with\n // `embedding()` fields validate and insert but their vectors are silently\n // dropped. When the user has installed sqlite-vec as a peer dep we load\n // it and wire the strategy; otherwise we proceed without vector support.\n const hasSqliteVec = tryLoadSqliteVec(sqlite);\n\n const db = drizzle(sqlite);\n\n // Generate and execute DDL from schema\n const ddlStatements = generateSqliteDDL(tables);\n for (const statement of ddlStatements) {\n sqlite.exec(statement);\n }\n\n const backend = createSqliteBackend(db, {\n executionProfile: {\n isSync: true,\n },\n tables,\n ...(hasSqliteVec ? { vector: sqliteVecStrategy } : {}),\n capabilities: {\n ...options.capabilities,\n graphAnalytics: {\n supported:\n options.capabilities?.graphAnalytics?.supported ??\n options.capabilities?.transactions !== false,\n mathFunctions:\n options.capabilities?.graphAnalytics?.mathFunctions ?? true,\n },\n },\n });\n const managedBackend = wrapWithManagedClose(backend, () => {\n sqlite.close();\n });\n\n return { backend: managedBackend, db };\n } catch (error) {\n try {\n sqlite.close();\n } catch {\n // Preserve the provisioning error; a cleanup failure is secondary.\n }\n throw error;\n }\n}\n\nfunction tryLoadSqliteVec(sqlite: Database.Database): boolean {\n try {\n // `sqlite-vec` is an optional peer dep; resolved via createRequire so\n // bundlers don't mark it as a hard import. Node resolves the package\n // only when it's actually installed.\n const module_: unknown = nodeRequire(\"sqlite-vec\");\n if (\n typeof module_ === \"object\" &&\n module_ !== null &&\n \"load\" in module_ &&\n typeof module_.load === \"function\"\n ) {\n (module_ as { load: (db: Database.Database) => void }).load(sqlite);\n return true;\n }\n return false;\n } catch {\n return false;\n }\n}\nexport type { GraphIdentityConfig } from \"../../core/define-graph\";\n"]}