@nicia-ai/typegraph 0.41.0 → 0.42.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.
- package/dist/backend/drizzle/indexes.cjs +9 -9
- package/dist/backend/drizzle/indexes.d.cts +1 -2
- package/dist/backend/drizzle/indexes.d.ts +1 -2
- package/dist/backend/drizzle/indexes.js +5 -5
- package/dist/backend/index.cjs +50 -50
- package/dist/backend/index.d.cts +3 -4
- package/dist/backend/index.d.ts +3 -4
- package/dist/backend/index.js +11 -11
- package/dist/backend/postgres/index.cjs +26 -26
- package/dist/backend/postgres/index.d.cts +5 -6
- package/dist/backend/postgres/index.d.ts +5 -6
- package/dist/backend/postgres/index.js +13 -13
- package/dist/backend/postgres/pglite-store.cjs +34 -34
- package/dist/backend/postgres/pglite-store.d.cts +7 -8
- package/dist/backend/postgres/pglite-store.d.ts +7 -8
- package/dist/backend/postgres/pglite-store.js +30 -30
- package/dist/backend/postgres/pglite.cjs +15 -15
- package/dist/backend/postgres/pglite.d.cts +2 -3
- package/dist/backend/postgres/pglite.d.ts +2 -3
- package/dist/backend/postgres/pglite.js +14 -14
- package/dist/backend/sqlite/index.cjs +23 -23
- package/dist/backend/sqlite/index.d.cts +5 -6
- package/dist/backend/sqlite/index.d.ts +5 -6
- package/dist/backend/sqlite/index.js +11 -11
- package/dist/backend/sqlite/libsql.cjs +17 -17
- package/dist/backend/sqlite/libsql.d.cts +2 -3
- package/dist/backend/sqlite/libsql.d.ts +2 -3
- package/dist/backend/sqlite/libsql.js +13 -13
- package/dist/backend/sqlite/local-store.cjs +35 -35
- package/dist/backend/sqlite/local-store.d.cts +7 -8
- package/dist/backend/sqlite/local-store.d.ts +7 -8
- package/dist/backend/sqlite/local-store.js +31 -31
- package/dist/backend/sqlite/local.cjs +16 -16
- package/dist/backend/sqlite/local.d.cts +2 -3
- package/dist/backend/sqlite/local.d.ts +2 -3
- package/dist/backend/sqlite/local.js +14 -14
- package/dist/{chunk-LOKG3KQV.cjs → chunk-277UZV7X.cjs} +1113 -1089
- package/dist/chunk-277UZV7X.cjs.map +1 -0
- package/dist/{chunk-2I3DNNBU.js → chunk-2G6ZEGYO.js} +4 -4
- package/dist/{chunk-2I3DNNBU.js.map → chunk-2G6ZEGYO.js.map} +1 -1
- package/dist/{chunk-76HE7DJP.js → chunk-2HKIID5K.js} +5 -5
- package/dist/{chunk-76HE7DJP.js.map → chunk-2HKIID5K.js.map} +1 -1
- package/dist/{chunk-QOHTVDHU.js → chunk-2OOY4OYT.js} +4 -4
- package/dist/{chunk-QOHTVDHU.js.map → chunk-2OOY4OYT.js.map} +1 -1
- package/dist/{chunk-UCHW2MGP.cjs → chunk-2SO5I5AI.cjs} +196 -196
- package/dist/{chunk-UCHW2MGP.cjs.map → chunk-2SO5I5AI.cjs.map} +1 -1
- package/dist/{chunk-LFFVD5ZR.cjs → chunk-33PAKPED.cjs} +41 -41
- package/dist/{chunk-LFFVD5ZR.cjs.map → chunk-33PAKPED.cjs.map} +1 -1
- package/dist/{chunk-QCKD3RCI.cjs → chunk-3RPQDGUE.cjs} +5 -5
- package/dist/{chunk-QCKD3RCI.cjs.map → chunk-3RPQDGUE.cjs.map} +1 -1
- package/dist/{chunk-PH4IJ3V5.js → chunk-3V6D5DEC.js} +3 -3
- package/dist/{chunk-PH4IJ3V5.js.map → chunk-3V6D5DEC.js.map} +1 -1
- package/dist/{chunk-Y5UC3IXF.js → chunk-42XYPKZU.js} +3 -3
- package/dist/{chunk-Y5UC3IXF.js.map → chunk-42XYPKZU.js.map} +1 -1
- package/dist/{chunk-XZA3Y4YH.js → chunk-4WYFRACU.js} +3 -3
- package/dist/{chunk-XZA3Y4YH.js.map → chunk-4WYFRACU.js.map} +1 -1
- package/dist/{chunk-AQVDAKXH.js → chunk-4XRP2N6B.js} +3 -3
- package/dist/{chunk-AQVDAKXH.js.map → chunk-4XRP2N6B.js.map} +1 -1
- package/dist/{chunk-PWXGB77L.cjs → chunk-5AERZSHC.cjs} +4 -4
- package/dist/{chunk-PWXGB77L.cjs.map → chunk-5AERZSHC.cjs.map} +1 -1
- package/dist/{chunk-K6CD6W5J.js → chunk-5C75HQYQ.js} +5 -5
- package/dist/{chunk-K6CD6W5J.js.map → chunk-5C75HQYQ.js.map} +1 -1
- package/dist/{chunk-2J5NMMVR.cjs → chunk-5GV4JQNA.cjs} +43 -43
- package/dist/{chunk-2J5NMMVR.cjs.map → chunk-5GV4JQNA.cjs.map} +1 -1
- package/dist/{chunk-KHNKYSGP.cjs → chunk-5P6IPIT6.cjs} +41 -41
- package/dist/{chunk-KHNKYSGP.cjs.map → chunk-5P6IPIT6.cjs.map} +1 -1
- package/dist/{chunk-M2RPZS7J.cjs → chunk-5Q3P6OIC.cjs} +12 -12
- package/dist/{chunk-M2RPZS7J.cjs.map → chunk-5Q3P6OIC.cjs.map} +1 -1
- package/dist/{chunk-QXKVUJLI.cjs → chunk-5ZPRE4CV.cjs} +206 -166
- package/dist/chunk-5ZPRE4CV.cjs.map +1 -0
- package/dist/{chunk-53BSOG3O.js → chunk-6NB73BXV.js} +11 -11
- package/dist/{chunk-53BSOG3O.js.map → chunk-6NB73BXV.js.map} +1 -1
- package/dist/{chunk-SE422RES.cjs → chunk-6TJ6PKPS.cjs} +27 -27
- package/dist/{chunk-SE422RES.cjs.map → chunk-6TJ6PKPS.cjs.map} +1 -1
- package/dist/{chunk-7WLEQIHA.cjs → chunk-7Y6BV3TK.cjs} +100 -100
- package/dist/{chunk-7WLEQIHA.cjs.map → chunk-7Y6BV3TK.cjs.map} +1 -1
- package/dist/{chunk-HP6LWBLB.cjs → chunk-AO2WPYFZ.cjs} +4 -4
- package/dist/{chunk-HP6LWBLB.cjs.map → chunk-AO2WPYFZ.cjs.map} +1 -1
- package/dist/{chunk-7UTUKH4E.cjs → chunk-AQR6BHB3.cjs} +10 -10
- package/dist/{chunk-7UTUKH4E.cjs.map → chunk-AQR6BHB3.cjs.map} +1 -1
- package/dist/{chunk-X4PVHAZ6.cjs → chunk-ARN3ZODS.cjs} +6 -6
- package/dist/{chunk-X4PVHAZ6.cjs.map → chunk-ARN3ZODS.cjs.map} +1 -1
- package/dist/{chunk-YYLMXERH.js → chunk-CDYRPI5U.js} +4 -4
- package/dist/{chunk-YYLMXERH.js.map → chunk-CDYRPI5U.js.map} +1 -1
- package/dist/{chunk-3LKL3S6X.js → chunk-CI5NPLXX.js} +3 -3
- package/dist/{chunk-3LKL3S6X.js.map → chunk-CI5NPLXX.js.map} +1 -1
- package/dist/{chunk-UUIBACKJ.js → chunk-CUPJL6TS.js} +3 -3
- package/dist/{chunk-UUIBACKJ.js.map → chunk-CUPJL6TS.js.map} +1 -1
- package/dist/{chunk-JZYMOHHM.cjs → chunk-CVK4T34X.cjs} +22 -22
- package/dist/{chunk-JZYMOHHM.cjs.map → chunk-CVK4T34X.cjs.map} +1 -1
- package/dist/{chunk-L3DDZUZP.js → chunk-CVNGKTHO.js} +4 -4
- package/dist/{chunk-L3DDZUZP.js.map → chunk-CVNGKTHO.js.map} +1 -1
- package/dist/{chunk-RW24SAHI.cjs → chunk-DMZEVJGL.cjs} +13 -13
- package/dist/{chunk-RW24SAHI.cjs.map → chunk-DMZEVJGL.cjs.map} +1 -1
- package/dist/{chunk-MQBF3XGY.js → chunk-DP7KC6CL.js} +47 -23
- package/dist/chunk-DP7KC6CL.js.map +1 -0
- package/dist/{chunk-QYDUCWD2.cjs → chunk-ECU53PMN.cjs} +4 -4
- package/dist/{chunk-QYDUCWD2.cjs.map → chunk-ECU53PMN.cjs.map} +1 -1
- package/dist/{chunk-SCTZRFW5.js → chunk-EQOQOT55.js} +5 -5
- package/dist/{chunk-SCTZRFW5.js.map → chunk-EQOQOT55.js.map} +1 -1
- package/dist/{chunk-JHK6NPFV.js → chunk-EVFL2ZY5.js} +9 -9
- package/dist/{chunk-JHK6NPFV.js.map → chunk-EVFL2ZY5.js.map} +1 -1
- package/dist/{chunk-SAMJLDGG.cjs → chunk-F2KVJ6FF.cjs} +112 -112
- package/dist/{chunk-SAMJLDGG.cjs.map → chunk-F2KVJ6FF.cjs.map} +1 -1
- package/dist/{chunk-NMQ6C6TS.cjs → chunk-F7TDKSVB.cjs} +4 -4
- package/dist/{chunk-NMQ6C6TS.cjs.map → chunk-F7TDKSVB.cjs.map} +1 -1
- package/dist/{chunk-HQRZEYYB.cjs → chunk-FFQGI67R.cjs} +44 -44
- package/dist/{chunk-HQRZEYYB.cjs.map → chunk-FFQGI67R.cjs.map} +1 -1
- package/dist/{chunk-YIRLBUNN.js → chunk-FMPZPOUD.js} +3 -3
- package/dist/{chunk-YIRLBUNN.js.map → chunk-FMPZPOUD.js.map} +1 -1
- package/dist/{chunk-LL5D5T5W.cjs → chunk-FSCJOTHF.cjs} +10 -10
- package/dist/{chunk-LL5D5T5W.cjs.map → chunk-FSCJOTHF.cjs.map} +1 -1
- package/dist/{chunk-2X73QTIC.cjs → chunk-FY4VY5EV.cjs} +20 -20
- package/dist/{chunk-2X73QTIC.cjs.map → chunk-FY4VY5EV.cjs.map} +1 -1
- package/dist/{chunk-3SHAUJRB.js → chunk-GT7NEXSU.js} +3 -3
- package/dist/{chunk-3SHAUJRB.js.map → chunk-GT7NEXSU.js.map} +1 -1
- package/dist/{chunk-W66YCXWT.js → chunk-HHBKGPEI.js} +11 -10
- package/dist/chunk-HHBKGPEI.js.map +1 -0
- package/dist/{chunk-CKFBZ4LV.cjs → chunk-I73ATSAH.cjs} +4 -4
- package/dist/{chunk-CKFBZ4LV.cjs.map → chunk-I73ATSAH.cjs.map} +1 -1
- package/dist/{chunk-ELA3V6UN.js → chunk-JOYPNY33.js} +9 -9
- package/dist/{chunk-ELA3V6UN.js.map → chunk-JOYPNY33.js.map} +1 -1
- package/dist/{chunk-YIX3BEBR.cjs → chunk-K2HHCWZO.cjs} +108 -108
- package/dist/{chunk-YIX3BEBR.cjs.map → chunk-K2HHCWZO.cjs.map} +1 -1
- package/dist/{chunk-SAFZ6JTI.cjs → chunk-KTBTSHU6.cjs} +19 -2
- package/dist/chunk-KTBTSHU6.cjs.map +1 -0
- package/dist/{chunk-KOI7UEI5.js → chunk-LDCWO5B6.js} +3 -3
- package/dist/{chunk-KOI7UEI5.js.map → chunk-LDCWO5B6.js.map} +1 -1
- package/dist/{chunk-I5CRUPKO.js → chunk-LQLVJWUH.js} +7 -7
- package/dist/{chunk-I5CRUPKO.js.map → chunk-LQLVJWUH.js.map} +1 -1
- package/dist/{chunk-6N7QBIWN.js → chunk-M4GYQF2H.js} +3 -3
- package/dist/{chunk-6N7QBIWN.js.map → chunk-M4GYQF2H.js.map} +1 -1
- package/dist/{chunk-ZE7E46IZ.js → chunk-NXIZL7ZZ.js} +6 -6
- package/dist/{chunk-ZE7E46IZ.js.map → chunk-NXIZL7ZZ.js.map} +1 -1
- package/dist/{chunk-XRU7V7FF.cjs → chunk-O2GZM7UK.cjs} +7 -7
- package/dist/{chunk-XRU7V7FF.cjs.map → chunk-O2GZM7UK.cjs.map} +1 -1
- package/dist/{chunk-ZE6NVENI.js → chunk-O3USVVWS.js} +3 -3
- package/dist/{chunk-ZE6NVENI.js.map → chunk-O3USVVWS.js.map} +1 -1
- package/dist/{chunk-UDS5DZNY.cjs → chunk-O7XVCLXW.cjs} +68 -67
- package/dist/chunk-O7XVCLXW.cjs.map +1 -0
- package/dist/{chunk-KLR77R5A.cjs → chunk-OM6RIOA5.cjs} +13 -13
- package/dist/{chunk-KLR77R5A.cjs.map → chunk-OM6RIOA5.cjs.map} +1 -1
- package/dist/{chunk-LLHMAHG4.cjs → chunk-OMQ2NBOR.cjs} +27 -27
- package/dist/{chunk-LLHMAHG4.cjs.map → chunk-OMQ2NBOR.cjs.map} +1 -1
- package/dist/{chunk-DPNA466P.js → chunk-OYJSYDIH.js} +19 -3
- package/dist/chunk-OYJSYDIH.js.map +1 -0
- package/dist/{chunk-V3S74J44.js → chunk-RAWG2FEU.js} +134 -22
- package/dist/chunk-RAWG2FEU.js.map +1 -0
- package/dist/{chunk-TAUGGLNQ.js → chunk-RXOAXO3R.js} +3 -3
- package/dist/{chunk-TAUGGLNQ.js.map → chunk-RXOAXO3R.js.map} +1 -1
- package/dist/{chunk-LLE25NRD.cjs → chunk-TRC646QQ.cjs} +7 -7
- package/dist/{chunk-LLE25NRD.cjs.map → chunk-TRC646QQ.cjs.map} +1 -1
- package/dist/chunk-U3YRCZ5L.cjs +12 -0
- package/dist/{chunk-IMQKXL4E.cjs.map → chunk-U3YRCZ5L.cjs.map} +1 -1
- package/dist/{chunk-ZVME6OSV.js → chunk-UJRWOV5B.js} +5 -5
- package/dist/{chunk-ZVME6OSV.js.map → chunk-UJRWOV5B.js.map} +1 -1
- package/dist/{chunk-HAQVISUF.cjs → chunk-UTTW2Q3M.cjs} +133 -133
- package/dist/{chunk-HAQVISUF.cjs.map → chunk-UTTW2Q3M.cjs.map} +1 -1
- package/dist/{chunk-L5ET7FYQ.js → chunk-UZLEQFTV.js} +3 -3
- package/dist/{chunk-L5ET7FYQ.js.map → chunk-UZLEQFTV.js.map} +1 -1
- package/dist/{chunk-JP5EICR6.cjs → chunk-V2GZBPY2.cjs} +179 -65
- package/dist/chunk-V2GZBPY2.cjs.map +1 -0
- package/dist/{chunk-BUZWMDNL.js → chunk-VC26BUNP.js} +5 -5
- package/dist/{chunk-BUZWMDNL.js.map → chunk-VC26BUNP.js.map} +1 -1
- package/dist/chunk-VGMNGWBR.cjs +12 -0
- package/dist/{chunk-5YBDB7UG.cjs.map → chunk-VGMNGWBR.cjs.map} +1 -1
- package/dist/{chunk-XMEYZYGE.js → chunk-WYQILW5V.js} +8 -8
- package/dist/{chunk-XMEYZYGE.js.map → chunk-WYQILW5V.js.map} +1 -1
- package/dist/{chunk-YX3H63VV.cjs → chunk-X2XOQZT3.cjs} +9 -9
- package/dist/{chunk-YX3H63VV.cjs.map → chunk-X2XOQZT3.cjs.map} +1 -1
- package/dist/{chunk-N2V3HJFV.cjs → chunk-XDMPDUKL.cjs} +9 -9
- package/dist/{chunk-N2V3HJFV.cjs.map → chunk-XDMPDUKL.cjs.map} +1 -1
- package/dist/{chunk-EFZ4S22A.js → chunk-YPVQYM3L.js} +107 -67
- package/dist/chunk-YPVQYM3L.js.map +1 -0
- package/dist/{chunk-5J4VNCUD.js → chunk-Z3WIL6S3.js} +5 -5
- package/dist/{chunk-5J4VNCUD.js.map → chunk-Z3WIL6S3.js.map} +1 -1
- package/dist/{chunk-MNURF4RF.cjs → chunk-ZBV4LQD2.cjs} +4 -4
- package/dist/{chunk-MNURF4RF.cjs.map → chunk-ZBV4LQD2.cjs.map} +1 -1
- package/dist/{chunk-YGX4PMG6.js → chunk-ZGOUVMVS.js} +5 -5
- package/dist/{chunk-YGX4PMG6.js.map → chunk-ZGOUVMVS.js.map} +1 -1
- package/dist/{chunk-QZYGZVUI.js → chunk-ZIRC2U6G.js} +11 -11
- package/dist/{chunk-QZYGZVUI.js.map → chunk-ZIRC2U6G.js.map} +1 -1
- package/dist/{chunk-6QP4QXBR.js → chunk-ZOHCFYXE.js} +3 -3
- package/dist/{chunk-6QP4QXBR.js.map → chunk-ZOHCFYXE.js.map} +1 -1
- package/dist/{chunk-VWEFXG73.js → chunk-ZP2KPDNN.js} +3 -3
- package/dist/{chunk-VWEFXG73.js.map → chunk-ZP2KPDNN.js.map} +1 -1
- package/dist/{chunk-NT6ILURI.cjs → chunk-ZPCKPLMX.cjs} +8 -8
- package/dist/{chunk-NT6ILURI.cjs.map → chunk-ZPCKPLMX.cjs.map} +1 -1
- package/dist/core/index.cjs +28 -28
- package/dist/core/index.d.cts +5 -6
- package/dist/core/index.d.ts +5 -6
- package/dist/core/index.js +8 -8
- package/dist/{ddl-BCXFRLWg.d.cts → ddl-3unqC-kg.d.cts} +3 -3
- package/dist/{ddl-ByLmGgn9.d.ts → ddl-Bc4Dl8fu.d.ts} +3 -3
- package/dist/{define-graph-BSviZubs.d.ts → define-graph-Byslw2OO.d.cts} +1 -2
- package/dist/{define-graph-XyJheaFm.d.cts → define-graph-DBFnc7u_.d.ts} +1 -2
- package/dist/graph-extension/index.cjs +20 -20
- package/dist/graph-extension/index.d.cts +4 -4
- package/dist/graph-extension/index.d.ts +4 -4
- package/dist/graph-extension/index.js +5 -5
- package/dist/graph-merge/index.cjs +105 -105
- package/dist/graph-merge/index.d.cts +8 -9
- package/dist/graph-merge/index.d.ts +8 -9
- package/dist/graph-merge/index.js +25 -25
- package/dist/{index-BD_3TCgh.d.ts → index-DHXw7QAl.d.cts} +19 -4
- package/dist/{index-BihFPsPu.d.cts → index-DQzVJBHa.d.ts} +19 -4
- package/dist/index.cjs +206 -202
- package/dist/index.d.cts +13 -15
- package/dist/index.d.ts +13 -15
- package/dist/index.js +35 -35
- package/dist/indexes/index.cjs +13 -13
- package/dist/indexes/index.d.cts +4 -5
- package/dist/indexes/index.d.ts +4 -5
- package/dist/indexes/index.js +6 -6
- package/dist/interchange/index.cjs +40 -40
- package/dist/interchange/index.d.cts +9 -10
- package/dist/interchange/index.d.ts +9 -10
- package/dist/interchange/index.js +14 -14
- package/dist/{manager-C7iC5bk_.d.ts → manager-Dl0-er1G.d.ts} +21 -156
- package/dist/{manager-Dm6MCYO7.d.cts → manager-U9_zopqr.d.cts} +21 -156
- package/dist/materialize-indexes-BM3u0aXE.d.ts +258 -0
- package/dist/materialize-indexes-DzMCetZe.d.cts +258 -0
- package/dist/{postgres-DZxwzCQ8.d.cts → postgres-C5-WMKFA.d.ts} +1 -1
- package/dist/{postgres-Cb6ceh4-.d.ts → postgres-DpJqtbSX.d.cts} +1 -1
- package/dist/profiler/index.d.cts +9 -10
- package/dist/profiler/index.d.ts +9 -10
- package/dist/provenance/index.cjs +39 -39
- package/dist/provenance/index.d.cts +7 -8
- package/dist/provenance/index.d.ts +7 -8
- package/dist/provenance/index.js +9 -9
- package/dist/schema/index.cjs +48 -39
- package/dist/schema/index.d.cts +7 -8
- package/dist/schema/index.d.ts +7 -8
- package/dist/schema/index.js +15 -14
- package/dist/{searchable-aUaKh3_r.d.cts → searchable-B4mUXZT6.d.cts} +2 -2
- package/dist/{searchable-Cet4Oztt.d.ts → searchable-C7jmPNLT.d.ts} +2 -2
- package/dist/{sqlite-Cb3Ilj9_.d.ts → sqlite-Ch5tSYQY.d.ts} +1 -1
- package/dist/{sqlite-Dxklpizv.d.cts → sqlite-Da7jiYu9.d.cts} +1 -1
- package/dist/{store-view-PCT7vTKH.d.cts → store-view-6C2vTWqf.d.ts} +8 -7
- package/dist/{store-view-BDjGFjpN.d.ts → store-view-CNcOG8bQ.d.cts} +8 -7
- package/dist/{temporal-CyFsSPe8.d.ts → temporal-BtrTYTiB.d.ts} +1 -1
- package/dist/{temporal-Dn_JADWY.d.cts → temporal-CMpigMCW.d.cts} +1 -1
- package/dist/{types-CFZiEEPh.d.ts → types-D2rU5Taq.d.ts} +1 -2
- package/dist/{types-D-vOo_pM.d.ts → types-Dh-EgT-w.d.cts} +569 -2
- package/dist/{types-ho4DJJb_.d.cts → types-Dh-EgT-w.d.ts} +569 -2
- package/dist/{types-CsaG00wS.d.cts → types-G4sVM-76.d.cts} +1 -2
- package/dist/{where-DLYaXa4L.d.ts → where-B8Y21kig.d.ts} +1 -2
- package/dist/{where-udes1WRA.d.cts → where-DbZ9XDOI.d.cts} +1 -2
- package/package.json +1 -1
- package/dist/chunk-5YBDB7UG.cjs +0 -12
- package/dist/chunk-DPNA466P.js.map +0 -1
- package/dist/chunk-EFZ4S22A.js.map +0 -1
- package/dist/chunk-IMQKXL4E.cjs +0 -12
- package/dist/chunk-JP5EICR6.cjs.map +0 -1
- package/dist/chunk-LOKG3KQV.cjs.map +0 -1
- package/dist/chunk-MQBF3XGY.js.map +0 -1
- package/dist/chunk-QXKVUJLI.cjs.map +0 -1
- package/dist/chunk-SAFZ6JTI.cjs.map +0 -1
- package/dist/chunk-UDS5DZNY.cjs.map +0 -1
- package/dist/chunk-V3S74J44.js.map +0 -1
- package/dist/chunk-W66YCXWT.js.map +0 -1
- package/dist/extension-types-BLEVH4SG.d.cts +0 -571
- package/dist/extension-types-BLEVH4SG.d.ts +0 -571
- package/dist/mater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O,SAAS,iBAAiB,KAAA,EAAyC;AACxE,EAAA,OAAO,KAAA,YAAiB,cAAA;AAC1B;AAmBO,SAAS,kBAAkB,KAAA,EAAyB;AACzD,EAAA,IAAI,CAAC,gBAAA,CAAiB,KAAK,CAAA,EAAG,OAAO,KAAA;AACrC,EAAA,OAAO,KAAA,CAAM,QAAA,KAAa,MAAA,IAAU,KAAA,CAAM,QAAA,KAAa,YAAA;AACzD;AAUO,SAAS,cAAc,KAAA,EAAyB;AACrD,EAAA,OAAO,gBAAA,CAAiB,KAAK,CAAA,IAAK,KAAA,CAAM,QAAA,KAAa,QAAA;AACvD;AAKO,SAAS,kBAAkB,KAAA,EAAyB;AACzD,EAAA,OAAO,gBAAA,CAAiB,KAAK,CAAA,IAAK,KAAA,CAAM,QAAA,KAAa,YAAA;AACvD;AAKO,SAAS,mBAAmB,KAAA,EAAoC;AACrE,EAAA,OAAO,gBAAA,CAAiB,KAAK,CAAA,GAAI,KAAA,CAAM,UAAA,GAAa,MAAA;AACtD","file":"chunk-DPNA466P.js","sourcesContent":["/**\n * TypeGraph Error Hierarchy\n *\n * All errors extend TypeGraphError with:\n * - `code`: Machine-readable error code for programmatic handling\n * - `category`: Classification for error handling strategies\n * - `suggestion`: Optional recovery guidance for users\n * - `details`: Structured context about the error\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.create({ name: \"\" });\n * } catch (error) {\n * if (isTypeGraphError(error)) {\n * console.error(error.toUserMessage());\n * if (isUserRecoverable(error)) {\n * // Show to user for correction\n * }\n * }\n * }\n * ```\n */\n\nimport type { KindEntity } from \"../core/types\";\n// Type-only import: `materialize-indexes.ts` value-imports\n// `ConfigurationError` from this file, but type-only imports are erased\n// at runtime so this back-edge does not create a value cycle.\nimport type { MaterializeIndexesResult } from \"../store/materialize-indexes\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Error category for programmatic handling.\n *\n * - `user`: Caused by invalid input or incorrect usage. Recoverable by fixing input.\n * - `constraint`: Business rule or schema constraint violation. Recoverable by changing data.\n * - `system`: Internal error or infrastructure issue. May require investigation or retry.\n */\nexport type ErrorCategory = \"user\" | \"constraint\" | \"system\";\n\n/**\n * Options for TypeGraphError constructor.\n */\nexport type TypeGraphErrorOptions = Readonly<{\n /** Structured context about the error */\n details?: Record<string, unknown>;\n /** Error category for handling strategies */\n category: ErrorCategory;\n /** Recovery guidance for users */\n suggestion?: string;\n /** Underlying cause of the error */\n cause?: unknown;\n}>;\n\nfunction formatCause(cause: unknown): string {\n if (cause instanceof Error) {\n return cause.stack ?? cause.message;\n }\n if (typeof cause === \"string\") {\n return cause;\n }\n if (\n typeof cause === \"number\" ||\n typeof cause === \"boolean\" ||\n typeof cause === \"bigint\"\n ) {\n return String(cause);\n }\n if (typeof cause === \"symbol\") {\n return cause.description ?? \"Symbol\";\n }\n if (cause === undefined) {\n return \"Unknown cause\";\n }\n\n try {\n return JSON.stringify(cause);\n } catch (error) {\n return `Unserializable cause: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`;\n }\n}\n\n// ============================================================\n// Base Error\n// ============================================================\n\n/**\n * Base error class for all TypeGraph errors.\n *\n * Provides structured error information for both programmatic handling\n * and user-friendly messages.\n */\nexport class TypeGraphError extends Error {\n /** Machine-readable error code (e.g., \"VALIDATION_ERROR\") */\n readonly code: string;\n\n /** Error category for handling strategies */\n readonly category: ErrorCategory;\n\n /** Structured context about the error */\n readonly details: Readonly<Record<string, unknown>>;\n\n /** Recovery guidance for users */\n readonly suggestion?: string;\n\n constructor(message: string, code: string, options: TypeGraphErrorOptions) {\n super(message, options.cause ? { cause: options.cause } : undefined);\n this.name = \"TypeGraphError\";\n this.code = code;\n this.category = options.category;\n this.details = Object.freeze(options.details ?? {});\n if (options.suggestion !== undefined) {\n this.suggestion = options.suggestion;\n }\n }\n\n /**\n * Returns a user-friendly error message with suggestion if available.\n */\n toUserMessage(): string {\n if (this.suggestion) {\n return `${this.message}\\n\\nSuggestion: ${this.suggestion}`;\n }\n return this.message;\n }\n\n /**\n * Returns a detailed string representation for logging.\n */\n toLogString(): string {\n const lines = [\n `[${this.code}] ${this.message}`,\n ` Category: ${this.category}`,\n ];\n\n if (this.suggestion) {\n lines.push(` Suggestion: ${this.suggestion}`);\n }\n\n const detailKeys = Object.keys(this.details);\n if (detailKeys.length > 0) {\n lines.push(` Details: ${JSON.stringify(this.details)}`);\n }\n\n if (this.cause) {\n lines.push(` Cause: ${formatCause(this.cause)}`);\n }\n\n return lines.join(\"\\n\");\n }\n}\n\n// ============================================================\n// Validation Errors (category: \"user\")\n// ============================================================\n\n/**\n * Validation issue from Zod or custom validation.\n */\nexport type ValidationIssue = Readonly<{\n /** Path to the invalid field (e.g., \"address.city\") */\n path: string;\n /** Human-readable error message */\n message: string;\n /** Zod error code if from Zod validation */\n code?: string;\n}>;\n\n/**\n * Details for ValidationError.\n */\nexport type ValidationErrorDetails = Readonly<{\n /** Type of entity being validated */\n entityType?: KindEntity;\n /** Kind/type name of the entity */\n kind?: string;\n /** Operation being performed */\n operation?: \"create\" | \"update\";\n /** Entity ID if updating */\n id?: string;\n /** Individual validation issues */\n issues: readonly ValidationIssue[];\n}>;\n\n/**\n * Thrown when schema validation fails during node or edge operations.\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.create({ email: \"invalid\" });\n * } catch (error) {\n * if (error instanceof ValidationError) {\n * console.log(error.details.issues);\n * // [{ path: \"email\", message: \"Invalid email\" }]\n * }\n * }\n * ```\n */\nexport class ValidationError extends TypeGraphError {\n declare readonly details: ValidationErrorDetails;\n\n constructor(\n message: string,\n details: ValidationErrorDetails,\n options?: { cause?: unknown; suggestion?: string },\n ) {\n const fieldList =\n details.issues.length > 0 ?\n details.issues.map((index) => index.path || \"(root)\").join(\", \")\n : \"unknown\";\n\n super(message, \"VALIDATION_ERROR\", {\n details,\n category: \"user\",\n suggestion:\n options?.suggestion ??\n `Check the following fields: ${fieldList}. See error.details.issues for specific validation failures.`,\n cause: options?.cause,\n });\n this.name = \"ValidationError\";\n }\n}\n\n// ============================================================\n// Not Found Errors (category: \"user\")\n// ============================================================\n\n/**\n * Details for NodeNotFoundError.\n */\nexport type NodeNotFoundErrorDetails = Readonly<{\n kind: string;\n id: string;\n}>;\n\n/**\n * Thrown when a node is not found.\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.get(\"nonexistent-id\");\n * } catch (error) {\n * if (error instanceof NodeNotFoundError) {\n * console.log(error.details.kind, error.details.id);\n * }\n * }\n * ```\n */\nexport class NodeNotFoundError extends TypeGraphError {\n declare readonly details: NodeNotFoundErrorDetails;\n\n constructor(kind: string, id: string, options?: { cause?: unknown }) {\n super(`Node not found: ${kind}/${id}`, \"NODE_NOT_FOUND\", {\n details: { kind, id },\n category: \"user\",\n suggestion: `Verify the node ID \"${id}\" exists and has not been deleted.`,\n cause: options?.cause,\n });\n this.name = \"NodeNotFoundError\";\n }\n}\n\n/**\n * Details for EdgeNotFoundError.\n */\nexport type EdgeNotFoundErrorDetails = Readonly<{\n kind: string;\n id: string;\n}>;\n\n/**\n * Thrown when an edge is not found.\n */\nexport class EdgeNotFoundError extends TypeGraphError {\n declare readonly details: EdgeNotFoundErrorDetails;\n\n constructor(kind: string, id: string, options?: { cause?: unknown }) {\n super(`Edge not found: ${kind}/${id}`, \"EDGE_NOT_FOUND\", {\n details: { kind, id },\n category: \"user\",\n suggestion: `Verify the edge ID \"${id}\" exists and has not been deleted.`,\n cause: options?.cause,\n });\n this.name = \"EdgeNotFoundError\";\n }\n}\n\n/**\n * Details for KindNotFoundError.\n */\nexport type KindNotFoundErrorDetails = Readonly<{\n kindName: string;\n entity: KindEntity;\n graphId?: string;\n}>;\n\n/**\n * Thrown when an operation references a kind that isn't registered on\n * the graph — `getNodeCollectionOrThrow` against an unknown kind, a\n * `materializeIndexes({ kinds })` filter naming a missing kind, an\n * extension referencing an unresolved endpoint, search facade typos,\n * etc. Carries the offending `kindName` and `entity` plus the host\n * `graphId` so logs are unambiguous when multiple stores share a\n * process.\n */\nexport class KindNotFoundError extends TypeGraphError {\n declare readonly details: KindNotFoundErrorDetails;\n readonly kindName: string;\n readonly entity: KindEntity;\n\n constructor(\n kindName: string,\n entity: KindEntity,\n options?: Readonly<{\n graphId?: string;\n suggestion?: string;\n cause?: unknown;\n }>,\n ) {\n const where =\n options?.graphId === undefined ? \"\" : ` on graph \"${options.graphId}\"`;\n super(\n `${entity === \"node\" ? \"Node\" : \"Edge\"} kind \"${kindName}\" is not registered${where}.`,\n \"KIND_NOT_FOUND\",\n {\n details: {\n kindName,\n entity,\n ...(options?.graphId === undefined ?\n {}\n : { graphId: options.graphId }),\n },\n category: \"user\",\n suggestion:\n options?.suggestion ??\n \"Compile-time kinds come from defineGraph; extension kinds appear after store.evolve() returns. Check store.introspect() for the registered set.\",\n cause: options?.cause,\n },\n );\n this.name = \"KindNotFoundError\";\n this.kindName = kindName;\n this.entity = entity;\n }\n}\n\n/**\n * Details for NodeConstraintNotFoundError.\n */\nexport type NodeConstraintNotFoundErrorDetails = Readonly<{\n constraintName: string;\n kind: string;\n}>;\n\n/**\n * Thrown when a uniqueness constraint name is not found on a node kind.\n */\nexport class NodeConstraintNotFoundError extends TypeGraphError {\n declare readonly details: NodeConstraintNotFoundErrorDetails;\n\n constructor(\n constraintName: string,\n kind: string,\n options?: { cause?: unknown },\n ) {\n super(\n `Constraint not found: \"${constraintName}\" on node kind \"${kind}\"`,\n \"CONSTRAINT_NOT_FOUND\",\n {\n details: { constraintName, kind },\n category: \"user\",\n suggestion: `Verify the constraint name \"${constraintName}\" is defined in the unique constraints for \"${kind}\".`,\n cause: options?.cause,\n },\n );\n this.name = \"NodeConstraintNotFoundError\";\n }\n}\n\n/**\n * Details for NodeIndexNotFoundError.\n */\nexport type NodeIndexNotFoundErrorDetails = Readonly<{\n indexName: string;\n kind: string;\n}>;\n\n/**\n * Thrown when a declared node index name is not found on a node kind.\n */\nexport class NodeIndexNotFoundError extends TypeGraphError {\n declare readonly details: NodeIndexNotFoundErrorDetails;\n\n constructor(indexName: string, kind: string, options?: { cause?: unknown }) {\n super(\n `Index not found: \"${indexName}\" on node kind \"${kind}\"`,\n \"INDEX_NOT_FOUND\",\n {\n details: { indexName, kind },\n category: \"user\",\n suggestion: `Verify the index name \"${indexName}\" is declared via defineNodeIndex for \"${kind}\" and passed to defineGraph({ indexes }).`,\n cause: options?.cause,\n },\n );\n this.name = \"NodeIndexNotFoundError\";\n }\n}\n\n// ============================================================\n// Constraint Errors (category: \"constraint\")\n// ============================================================\n\n/**\n * Details for EndpointNotFoundError.\n */\nexport type EndpointNotFoundErrorDetails = Readonly<{\n edgeKind: string;\n endpoint: \"from\" | \"to\";\n nodeKind: string;\n nodeId: string;\n}>;\n\n/**\n * Thrown when edge endpoint node does not exist or is deleted.\n */\nexport class EndpointNotFoundError extends TypeGraphError {\n declare readonly details: EndpointNotFoundErrorDetails;\n\n constructor(\n details: EndpointNotFoundErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(\n `Endpoint node not found for edge \"${details.edgeKind}\": ${details.nodeKind}/${details.nodeId} (${details.endpoint})`,\n \"ENDPOINT_NOT_FOUND\",\n {\n details,\n category: \"constraint\",\n suggestion: `Ensure the ${details.endpoint} node exists before creating the edge.`,\n cause: options?.cause,\n },\n );\n this.name = \"EndpointNotFoundError\";\n }\n}\n\n/**\n * Details for EndpointError.\n */\nexport type EndpointErrorDetails = Readonly<{\n edgeKind: string;\n endpoint: \"from\" | \"to\";\n actualKind: string;\n expectedKinds: readonly string[];\n}>;\n\n/**\n * Thrown when edge endpoint has wrong node type.\n */\nexport class EndpointError extends TypeGraphError {\n declare readonly details: EndpointErrorDetails;\n\n constructor(details: EndpointErrorDetails, options?: { cause?: unknown }) {\n const expected = details.expectedKinds.join(\" | \");\n super(\n `Invalid ${details.endpoint} endpoint for edge \"${details.edgeKind}\": got \"${details.actualKind}\", expected ${expected}`,\n \"ENDPOINT_ERROR\",\n {\n details,\n category: \"constraint\",\n suggestion: `Use a node of type ${expected} as the ${details.endpoint} endpoint.`,\n cause: options?.cause,\n },\n );\n this.name = \"EndpointError\";\n }\n}\n\n/**\n * Details for UniquenessError.\n */\nexport type UniquenessErrorDetails = Readonly<{\n constraintName: string;\n kind: string;\n existingId: string;\n newId: string;\n fields: readonly string[];\n}>;\n\n/**\n * Thrown when uniqueness constraint is violated.\n */\nexport class UniquenessError extends TypeGraphError {\n declare readonly details: UniquenessErrorDetails;\n\n constructor(details: UniquenessErrorDetails, options?: { cause?: unknown }) {\n const fieldList = details.fields.join(\", \");\n super(\n `Uniqueness violation on \"${details.kind}\": constraint \"${details.constraintName}\" (fields: ${fieldList}) conflicts with existing node ${details.existingId}`,\n \"UNIQUENESS_VIOLATION\",\n {\n details,\n category: \"constraint\",\n suggestion: `Change the values for fields [${fieldList}] to be unique, or update the existing node ${details.existingId} instead.`,\n cause: options?.cause,\n },\n );\n this.name = \"UniquenessError\";\n }\n}\n\n/**\n * Details for CardinalityError.\n */\nexport type CardinalityErrorDetails = Readonly<{\n edgeKind: string;\n fromKind: string;\n fromId: string;\n cardinality: string;\n existingCount: number;\n}>;\n\n/**\n * Thrown when cardinality constraint is violated.\n */\nexport class CardinalityError extends TypeGraphError {\n declare readonly details: CardinalityErrorDetails;\n\n constructor(details: CardinalityErrorDetails, options?: { cause?: unknown }) {\n super(\n `Cardinality violation: \"${details.edgeKind}\" from ${details.fromKind}/${details.fromId} allows \"${details.cardinality}\" but ${details.existingCount} edge(s) already exist`,\n \"CARDINALITY_ERROR\",\n {\n details,\n category: \"constraint\",\n suggestion:\n details.cardinality === \"one\" || details.cardinality === \"unique\" ?\n `Delete the existing edge before creating a new one, or use cardinality \"many\".`\n : `Check if the cardinality constraint \"${details.cardinality}\" is correct for your use case.`,\n cause: options?.cause,\n },\n );\n this.name = \"CardinalityError\";\n }\n}\n\n/**\n * Details for DisjointError.\n */\nexport type DisjointErrorDetails = Readonly<{\n nodeId: string;\n attemptedKind: string;\n conflictingKind: string;\n}>;\n\n/**\n * Thrown when disjointness constraint is violated.\n *\n * Disjoint types cannot share the same ID - a node cannot be both\n * a Person and an Organization if they are declared disjoint.\n */\nexport class DisjointError extends TypeGraphError {\n declare readonly details: DisjointErrorDetails;\n\n constructor(details: DisjointErrorDetails, options?: { cause?: unknown }) {\n super(\n `Disjoint constraint violation: cannot create ${details.attemptedKind} with ID \"${details.nodeId}\" - conflicts with existing ${details.conflictingKind}`,\n \"DISJOINT_ERROR\",\n {\n details,\n category: \"constraint\",\n suggestion: `Use a different ID for the new ${details.attemptedKind} node, or delete the existing ${details.conflictingKind}/${details.nodeId} first.`,\n cause: options?.cause,\n },\n );\n this.name = \"DisjointError\";\n }\n}\n\n/**\n * Details for RestrictedDeleteError.\n */\nexport type RestrictedDeleteErrorDetails = Readonly<{\n nodeKind: string;\n nodeId: string;\n edgeCount: number;\n edgeKinds: readonly string[];\n}>;\n\n/**\n * Thrown when deletion is blocked due to existing edges (restrict behavior).\n */\nexport class RestrictedDeleteError extends TypeGraphError {\n declare readonly details: RestrictedDeleteErrorDetails;\n\n constructor(\n details: RestrictedDeleteErrorDetails,\n options?: { cause?: unknown },\n ) {\n const edgeList = details.edgeKinds.join(\", \");\n super(\n `Cannot delete ${details.nodeKind}/${details.nodeId}: ${details.edgeCount} connected edge(s) exist (${edgeList})`,\n \"RESTRICTED_DELETE\",\n {\n details,\n category: \"constraint\",\n suggestion: `Delete the connected edges first, or change onDelete behavior to \"cascade\" (auto-delete edges) or \"disconnect\" (soft-delete edges).`,\n cause: options?.cause,\n },\n );\n this.name = \"RestrictedDeleteError\";\n }\n}\n\n// ============================================================\n// Concurrency Errors (category: \"system\")\n// ============================================================\n\n/**\n * Details for VersionConflictError.\n */\nexport type VersionConflictErrorDetails = Readonly<{\n kind: string;\n id: string;\n expectedVersion: number;\n actualVersion: number;\n}>;\n\n/**\n * Thrown when optimistic locking detects a concurrent modification.\n *\n * This occurs when two operations try to update the same entity simultaneously.\n * The operation with the stale version fails.\n */\nexport class VersionConflictError extends TypeGraphError {\n declare readonly details: VersionConflictErrorDetails;\n\n constructor(\n details: VersionConflictErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(\n `Version conflict on ${details.kind}/${details.id}: expected version ${details.expectedVersion}, found ${details.actualVersion}`,\n \"VERSION_CONFLICT\",\n {\n details,\n category: \"system\",\n suggestion: `Fetch the latest version of the entity and retry the operation. This error indicates concurrent modification.`,\n cause: options?.cause,\n },\n );\n this.name = \"VersionConflictError\";\n }\n}\n\n// ============================================================\n// Schema Errors (category: \"system\")\n// ============================================================\n\n/**\n * Details for SchemaMismatchError.\n */\nexport type SchemaMismatchErrorDetails = Readonly<{\n graphId: string;\n expectedHash: string;\n actualHash: string;\n}>;\n\n/**\n * Thrown when the schema in code doesn't match the schema in the database.\n */\nexport class SchemaMismatchError extends TypeGraphError {\n declare readonly details: SchemaMismatchErrorDetails;\n\n constructor(\n details: SchemaMismatchErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(\n `Schema mismatch for graph \"${details.graphId}\": code schema differs from database schema`,\n \"SCHEMA_MISMATCH\",\n {\n details,\n category: \"system\",\n suggestion: `Run schema migration to update the database, or use createStoreWithSchema() for automatic migration.`,\n cause: options?.cause,\n },\n );\n this.name = \"SchemaMismatchError\";\n }\n}\n\n/**\n * Details for MigrationError.\n */\nexport type MigrationErrorDetails = Readonly<{\n graphId: string;\n fromVersion: number;\n toVersion: number;\n reason?: string;\n}>;\n\n/**\n * Thrown when schema migration fails.\n */\nexport class MigrationError extends TypeGraphError {\n declare readonly details: MigrationErrorDetails;\n\n constructor(\n message: string,\n details: MigrationErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(message, \"MIGRATION_ERROR\", {\n details,\n category: \"system\",\n suggestion: `Review the schema changes and ensure they are backwards compatible, or implement a data migration.`,\n cause: options?.cause,\n });\n this.name = \"MigrationError\";\n }\n}\n\n/**\n * Details for EagerMaterializationError.\n */\nexport type EagerMaterializationErrorDetails = Readonly<{\n graphId: string;\n failedIndexNames: readonly string[];\n}>;\n\n/**\n * Thrown by `Store.evolve(extension, { eager })` when the schema\n * commit succeeded but the follow-on `materializeIndexes()` produced\n * one or more failed entries.\n *\n * Recovery: the schema commit is NOT rolled back. The new `Store` is\n * fully constructed and (when `options.ref` was supplied) `ref.current`\n * already points to it — the caller can read the new store via the ref\n * and decide how to handle the failed indexes (retry, skip, alert).\n * The full `MaterializeIndexesResult` is attached as `.materialization`.\n *\n * @example\n * ```ts\n * const ref = { current: store };\n * try {\n * await store.evolve(extension, { ref, eager: {} });\n * } catch (error) {\n * if (error instanceof EagerMaterializationError) {\n * // schema is committed; ref.current is the new store\n * log.warn(\n * { failed: error.failedIndexNames },\n * \"indexes did not materialize; will retry\",\n * );\n * await ref.current.materializeIndexes();\n * } else {\n * throw error;\n * }\n * }\n * ```\n */\nexport class EagerMaterializationError extends TypeGraphError {\n declare readonly details: EagerMaterializationErrorDetails;\n\n /**\n * The full materialization result, including successful and failed\n * entries. Same shape as `Store.materializeIndexes()` returns.\n */\n readonly materialization: MaterializeIndexesResult;\n\n constructor(materialization: MaterializeIndexesResult, graphId: string) {\n const names = collectFailedIndexNames(materialization);\n super(\n `Eager materialization failed for ${names.length} index(es) on graph \"${graphId}\": ${names.join(\", \")}. The schema commit succeeded; the new Store is available via the ref handle (when supplied) and the failed indexes can be retried via store.materializeIndexes().`,\n \"EAGER_MATERIALIZATION_FAILED\",\n {\n details: { graphId, failedIndexNames: names },\n category: \"system\",\n suggestion: `Inspect error.materialization for per-index errors. Each failure preserves any prior successful materialization timestamp; the schema is committed regardless.`,\n },\n );\n this.name = \"EagerMaterializationError\";\n this.materialization = materialization;\n }\n\n /**\n * Names of just the indexes that failed — derived from\n * `materialization.results` so the two views can never disagree.\n */\n get failedIndexNames(): readonly string[] {\n return collectFailedIndexNames(this.materialization);\n }\n}\n\nfunction collectFailedIndexNames(\n materialization: MaterializeIndexesResult,\n): readonly string[] {\n const names: string[] = [];\n for (const entry of materialization.results) {\n if (entry.status === \"failed\") names.push(entry.indexName);\n }\n return names;\n}\n\n/**\n * Details for StaleVersionError. `actual` is `0` when no active version\n * exists yet (initial-commit race where another writer initialized first).\n */\nexport type StaleVersionErrorDetails = Readonly<{\n graphId: string;\n expected: number;\n actual: number;\n}>;\n\n/**\n * Thrown by `commitSchemaVersion` and `setActiveVersion` when the\n * caller's view of the active schema version is out of date — another\n * writer has already advanced it.\n *\n * Recovery: re-read the active version with `getActiveSchema(graphId)`,\n * recompute against the new baseline, and retry. This is a routine\n * concurrency signal, not a bug.\n */\nexport class StaleVersionError extends TypeGraphError {\n declare readonly details: StaleVersionErrorDetails;\n\n constructor(\n details: StaleVersionErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(\n `Schema version was advanced by another writer for graph \"${details.graphId}\": expected active version ${details.expected}, actual is ${details.actual}`,\n \"STALE_SCHEMA_VERSION\",\n {\n details,\n category: \"system\",\n suggestion: `Re-read the active schema version, recompute the new version against that baseline, and retry the commit.`,\n cause: options?.cause,\n },\n );\n this.name = \"StaleVersionError\";\n }\n}\n\n/**\n * Details for SchemaContentConflictError.\n */\nexport type SchemaContentConflictErrorDetails = Readonly<{\n graphId: string;\n version: number;\n existingHash: string;\n incomingHash: string;\n}>;\n\n/**\n * Thrown by `commitSchemaVersion` when a row already exists at the\n * target version with a *different* schema hash — i.e. two writers\n * committed materially different schemas at the same version number.\n *\n * Distinct from `StaleVersionError`: this is not a refetch-and-retry\n * situation, it's a content disagreement that needs operator\n * intervention. Typically caused by inconsistent application\n * deployments writing schemas that hash differently.\n */\nexport class SchemaContentConflictError extends TypeGraphError {\n declare readonly details: SchemaContentConflictErrorDetails;\n\n constructor(\n details: SchemaContentConflictErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(\n `Schema content conflict for graph \"${details.graphId}\" at version ${details.version}: existing hash ${details.existingHash} differs from incoming hash ${details.incomingHash}`,\n \"SCHEMA_CONTENT_CONFLICT\",\n {\n details,\n category: \"system\",\n suggestion: `Two writers committed different schemas at the same version. Reconcile the application deployments so they produce the same canonical schema, then retry.`,\n cause: options?.cause,\n },\n );\n this.name = \"SchemaContentConflictError\";\n }\n}\n\n// ============================================================\n// Configuration Errors (category: \"user\")\n// ============================================================\n\n/**\n * Thrown when graph configuration is invalid.\n *\n * This includes invalid schema definitions, ontology conflicts,\n * and other configuration issues detected at graph creation time.\n */\nexport class ConfigurationError extends TypeGraphError {\n constructor(\n message: string,\n details: Record<string, unknown> = {},\n options?: { cause?: unknown; suggestion?: string },\n ) {\n super(message, \"CONFIGURATION_ERROR\", {\n details,\n category: \"user\",\n suggestion:\n options?.suggestion ?? `Review your graph definition for errors.`,\n cause: options?.cause,\n });\n this.name = \"ConfigurationError\";\n }\n}\n\n/**\n * Thrown when an iterative graph algorithm exhausts its caller-visible round\n * budget before reaching its convergence predicate.\n */\nexport class GraphAlgorithmConvergenceError extends TypeGraphError {\n constructor(\n algorithm: string,\n maxIterations: number,\n options: Readonly<{ oscillating?: boolean }> = {},\n ) {\n const oscillating = options.oscillating === true;\n super(\n oscillating ?\n `${algorithm} entered a periodic label oscillation and can never converge.`\n : `${algorithm} did not converge within ${maxIterations} iterations.`,\n \"GRAPH_ALGORITHM_CONVERGENCE_ERROR\",\n {\n details: {\n algorithm,\n maxIterations,\n ...(oscillating ? { oscillating } : {}),\n },\n category: \"user\",\n suggestion:\n oscillating ?\n 'Pass onMaxIterations: \"return\" to accept the fixed-round labeling, or exclude the oscillating component from the selection.'\n : \"Increase maxIterations or reduce the selected graph before retrying.\",\n },\n );\n this.name = \"GraphAlgorithmConvergenceError\";\n }\n}\n\n/** Stable reasons a weighted traversal can reject an edge's weight value. */\nexport type InvalidEdgeWeightReason =\n \"missing\" | \"negative\" | \"non_numeric\" | \"out_of_range\";\n\n/** Details for InvalidEdgeWeightError. */\nexport type InvalidEdgeWeightErrorDetails = Readonly<{\n /** Id of the first offending edge, in binary-collation order. */\n edgeId: string;\n /** Kind of the offending edge. */\n edgeKind: string;\n /** The audited weight property. */\n property: string;\n /** Why the weight was rejected. */\n reason: InvalidEdgeWeightReason;\n /** The offending value, when one was present and renderable. */\n value?: string;\n}>;\n\nconst EDGE_WEIGHT_REASONS: Readonly<\n Record<\n InvalidEdgeWeightReason,\n Readonly<{ message: string; suggestion: string }>\n >\n> = {\n missing: {\n message: \"has no value for weight property\",\n suggestion:\n \"Set the property on every selected edge, or provide defaultWeight for edges without it.\",\n },\n negative: {\n message: \"has a negative value for weight property\",\n suggestion:\n \"Weighted traversal requires non-negative weights; repair the edge data before retrying.\",\n },\n non_numeric: {\n message: \"has a non-numeric value for weight property\",\n suggestion:\n \"Store the weight property as a JSON number on every selected edge before retrying.\",\n },\n out_of_range: {\n message: \"has a value outside the supported range for weight property\",\n suggestion:\n \"Keep weight magnitudes within the range weightedShortestPath documents (large enough to be a normal IEEE 754 double, small enough that path sums cannot overflow).\",\n },\n};\n\n/**\n * Thrown when a weighted graph algorithm finds an edge whose weight property\n * violates the weighted-traversal contract (missing without a default,\n * non-numeric, or negative). Raised before any traversal rounds run, so a\n * weighted call either observes a fully valid weight domain or fails fast.\n */\nexport class InvalidEdgeWeightError extends TypeGraphError {\n declare readonly details: InvalidEdgeWeightErrorDetails;\n\n constructor(details: InvalidEdgeWeightErrorDetails) {\n super(\n `Edge '${details.edgeId}' (kind '${details.edgeKind}') ${EDGE_WEIGHT_REASONS[details.reason].message} '${details.property}'${\n details.value === undefined ? \"\" : ` (value: ${details.value})`\n }.`,\n \"INVALID_EDGE_WEIGHT\",\n {\n details: { ...details },\n category: \"user\",\n suggestion: EDGE_WEIGHT_REASONS[details.reason].suggestion,\n },\n );\n this.name = \"InvalidEdgeWeightError\";\n }\n}\n\n/** Thrown when an operation requires a backend capability it does not expose. */\nexport class UnsupportedBackendCapabilityError extends TypeGraphError {\n constructor(\n operation: string,\n capability: string,\n details: Readonly<Record<string, unknown>> = {},\n suggestion?: string,\n ) {\n super(\n `${operation} requires backend capability '${capability}'.`,\n \"UNSUPPORTED_BACKEND_CAPABILITY\",\n {\n details: { operation, capability, ...details },\n category: \"user\",\n suggestion:\n suggestion ??\n \"Use a backend that advertises this capability before invoking the operation.\",\n },\n );\n this.name = \"UnsupportedBackendCapabilityError\";\n }\n}\n\n/** Stable reasons an intentionally trusted initial import can be rejected. */\nexport type TrustedImportErrorReason =\n | \"backend_unsupported\"\n | \"database_not_empty\"\n | \"fulltext_unsupported\"\n | \"history_unsupported\"\n | \"invalid_stream\"\n | \"revision_tracking_unsupported\"\n | \"uniqueness_unsupported\"\n | \"vector_unsupported\";\n\n/** Thrown when the trusted initial-import contract is unavailable or violated. */\nexport class TrustedImportError extends TypeGraphError {\n constructor(\n message: string,\n reason: TrustedImportErrorReason,\n details: Readonly<Record<string, unknown>> = {},\n options?: Readonly<{ cause?: unknown; suggestion?: string }>,\n ) {\n super(message, \"TRUSTED_IMPORT_ERROR\", {\n details: { ...details, reason },\n category: \"user\",\n suggestion:\n options?.suggestion ??\n \"Use the validating bulk or interchange import APIs unless every trusted-import precondition is satisfied.\",\n cause: options?.cause,\n });\n this.name = \"TrustedImportError\";\n }\n}\n\n/**\n * The stable `details.code` values raised by the recorded-capture guards on a\n * history- or revision-tracked store. These are the sanctioned branch points\n * for a portable caller that must pick a transaction strategy without\n * substring-matching {@link ConfigurationError} messages.\n *\n * - `RECORDED_CAPTURE_REQUIRES_CALLBACK_TRANSACTION`: `store.withTransaction`\n * was called on a history-enabled store, which has no flush point before the\n * caller commits — use `store.withRecordedTransaction` instead.\n * - `RECORDED_CAPTURE_RAW_SQL_DISABLED`: a raw SQL escape (`tx.sql`,\n * `backend.executeStatement`/`executeDdl`) was reached on a history-enabled\n * store, where it would bypass recorded-time capture.\n * - `REVISION_TRACKING_RAW_SQL_DISABLED`: the same raw SQL escape on a\n * revision-tracked store, where it would bypass the revision anchor.\n *\n * @see isRecordedCaptureGuardError\n */\nexport const RECORDED_CAPTURE_GUARD_CODES = [\n \"RECORDED_CAPTURE_REQUIRES_CALLBACK_TRANSACTION\",\n \"RECORDED_CAPTURE_RAW_SQL_DISABLED\",\n \"REVISION_TRACKING_RAW_SQL_DISABLED\",\n] as const;\n\n/** A stable, branchable code raised by a recorded-capture guard. */\nexport type RecordedCaptureGuardCode =\n (typeof RECORDED_CAPTURE_GUARD_CODES)[number];\n\n/**\n * A {@link ConfigurationError} narrowed to carry a {@link RecordedCaptureGuardCode}\n * in `details.code` — the shape {@link isRecordedCaptureGuardError} guarantees.\n * `C` narrows `details.code` to a single code when the guard was called with a\n * specific one; it defaults to the full union.\n */\nexport type RecordedCaptureGuardError<\n C extends RecordedCaptureGuardCode = RecordedCaptureGuardCode,\n> = ConfigurationError & Readonly<{ details: Readonly<{ code: C }> }>;\n\nfunction isRecordedCaptureGuardCode(\n value: unknown,\n): value is RecordedCaptureGuardCode {\n // Widen the readonly tuple so `includes` accepts an `unknown` needle.\n return (RECORDED_CAPTURE_GUARD_CODES as readonly unknown[]).includes(value);\n}\n\n/**\n * Type guard for the recorded-capture guard errors, so a portable caller can\n * branch on the invariant a store enforced instead of substring-matching the\n * message. Pass `code` to narrow to a single guard; omit it to match any.\n *\n * Distinguishes \"history capture forbids raw SQL here\" from \"this backend has\n * no transactions\" (the latter carries no guard code — see\n * `TransactionContext.sqlAvailability` for the capability discriminant).\n *\n * Passing `code` also narrows `details.code` to that literal on the guarded\n * branch, so a caller can read the payload without re-checking.\n *\n * @example\n * ```typescript\n * // `withTransaction` is a compile error on a history-enabled store, so widen\n * // to the base Store surface to reach the runtime guard this branches on.\n * const store: Store<typeof graph> = historyStore;\n * try {\n * store.withTransaction(externalTx);\n * } catch (error) {\n * if (\n * isRecordedCaptureGuardError(\n * error,\n * \"RECORDED_CAPTURE_REQUIRES_CALLBACK_TRANSACTION\",\n * )\n * ) {\n * // error.details.code is now the literal, not the union.\n * await historyStore.withRecordedTransaction(externalTx, run);\n * } else {\n * throw error;\n * }\n * }\n * ```\n */\nexport function isRecordedCaptureGuardError<C extends RecordedCaptureGuardCode>(\n error: unknown,\n code: C,\n): error is RecordedCaptureGuardError<C>;\nexport function isRecordedCaptureGuardError(\n error: unknown,\n): error is RecordedCaptureGuardError;\nexport function isRecordedCaptureGuardError(\n error: unknown,\n code?: RecordedCaptureGuardCode,\n): error is RecordedCaptureGuardError {\n if (!(error instanceof ConfigurationError)) return false;\n const actual = error.details[\"code\"];\n if (!isRecordedCaptureGuardCode(actual)) return false;\n return code === undefined || actual === code;\n}\n\n/**\n * Why a store's strategy-owned storage is not usable on the current\n * connection. Drives the {@link StoreNotInitializedError} message and\n * is surfaced in `details.reason` for programmatic handling.\n *\n * - `missing`: no durable materialization marker exists — the database\n * was never initialized for this graph's runtime contributions.\n * - `stale`: a marker exists but its recorded signature no longer\n * matches the resolved contribution DDL (strategy swap or DDL drift).\n * The hot path refuses rather than silently re-materializing.\n * - `failed`: the most recent boot-time materialization attempt\n * recorded an error. Boot may retry; the hot path refuses.\n */\nexport type StoreNotInitializedReason = \"missing\" | \"stale\" | \"failed\";\n\nconst STORE_NOT_INITIALIZED_REASON_PHRASE: Readonly<\n Record<StoreNotInitializedReason, string>\n> = {\n missing: \"is not initialized\",\n stale: \"is stale (recorded materialization signature no longer matches)\",\n failed: \"failed its last initialization attempt\",\n};\n\n/**\n * Details for StoreNotInitializedError. `graphId`/`reason` are always\n * present; callers may merge additional context (e.g. `logicalName`) via\n * `options.details`.\n */\nexport type StoreNotInitializedErrorDetails = Readonly<{\n graphId: string;\n reason: StoreNotInitializedReason;\n}> &\n Readonly<Record<string, unknown>>;\n\n/**\n * Thrown when a fulltext- or vector-dependent operation runs against a\n * connection whose strategy-owned storage has not been durably materialized.\n *\n * `createStore()` is a synchronous, zero-I/O attach: it never creates\n * tables, repairs DDL, or writes materialization markers. The durable\n * marker is written exclusively by the async boot path\n * (`createStoreWithSchema`). When a fulltext or embedding read/write — or\n * an adopted/business transaction — observes no valid marker, it refuses\n * loudly here instead of lazily emitting DDL on the hot path.\n */\nexport class StoreNotInitializedError extends TypeGraphError {\n declare readonly details: StoreNotInitializedErrorDetails;\n\n // `graphId`/`reason` are positional and required: both are\n // load-bearing for the message and for programmatic handling via\n // `details.reason`. Caller `details` merge underneath — spread first\n // so `graphId`/`reason` win and can't be clobbered by an\n // accidentally-colliding extra key.\n constructor(\n graphId: string,\n reason: StoreNotInitializedReason,\n options?: {\n cause?: unknown;\n details?: Readonly<Record<string, unknown>> &\n Readonly<{ graphId?: never; reason?: never }>;\n },\n ) {\n super(\n `${storageLabelFromLogicalName(options?.details?.[\"logicalName\"])} for ` +\n `graph \"${graphId}\" ${STORE_NOT_INITIALIZED_REASON_PHRASE[reason]}. ` +\n storeNotInitializedAction(reason, options?.details?.[\"logicalName\"]),\n \"STORE_NOT_INITIALIZED\",\n {\n details: { ...options?.details, graphId, reason },\n category: \"user\",\n suggestion:\n isStaleVectorSlot(reason, options?.details?.[\"logicalName\"]) ?\n \"The field's declared shape (e.g. its dimension) changed after \" +\n \"its storage was provisioned. Run store.reembedVectorField(\" +\n \"kind, fieldPath) to recreate the storage at the new shape and \" +\n \"re-embed.\"\n : \"Call createStoreWithSchema(graph, backend) once at application \" +\n \"startup. createStore() attaches to an already-initialized \" +\n \"database and does not materialize storage itself.\",\n cause: options?.cause,\n },\n );\n this.name = \"StoreNotInitializedError\";\n }\n}\n\nconst VECTOR_LOGICAL_NAME_PREFIX = \"vector:\";\n\n/**\n * A stale VECTOR slot is its own failure mode: the storage exists but was\n * provisioned at a different shape (the declared dimension changed), and\n * the fix is `store.reembedVectorField`, not a re-run of\n * `createStoreWithSchema` (whose boot pass deliberately skips drifted\n * slots). Drives the action sentence and the suggestion.\n */\nfunction isStaleVectorSlot(\n reason: StoreNotInitializedReason,\n logicalName: unknown,\n): boolean {\n return (\n reason === \"stale\" &&\n typeof logicalName === \"string\" &&\n logicalName.startsWith(VECTOR_LOGICAL_NAME_PREFIX)\n );\n}\n\n/** The actionable trailing sentence of the error message, per failure mode. */\nfunction storeNotInitializedAction(\n reason: StoreNotInitializedReason,\n logicalName: unknown,\n): string {\n if (isStaleVectorSlot(reason, logicalName)) {\n return (\n `The declared shape changed after provisioning — run ` +\n `store.reembedVectorField(kind, fieldPath) to recreate the storage ` +\n `at the new shape.`\n );\n }\n return (\n `Run createStoreWithSchema(graph, backend) during application boot, ` +\n `outside request handlers and adopted transactions, before using createStore().`\n );\n}\n\n/**\n * Human label for the un-materialized storage, derived from the\n * contribution `logicalName`: fulltext keeps \"fulltext storage\"; a vector\n * slot (\"vector:<kind>.<field>\") reads as `vector storage\n * \"<kind>.<field>\"` so the message names the exact embedding\n * field. Falls back to a neutral phrase when no logical name is supplied.\n */\nfunction storageLabelFromLogicalName(logicalName: unknown): string {\n if (typeof logicalName !== \"string\") return \"runtime storage\";\n if (logicalName.startsWith(VECTOR_LOGICAL_NAME_PREFIX)) {\n return `vector storage \"${logicalName.slice(VECTOR_LOGICAL_NAME_PREFIX.length)}\"`;\n }\n if (logicalName === \"fulltext\") return \"fulltext storage\";\n return `\"${logicalName}\" storage`;\n}\n\n// ============================================================\n// Database Errors (category: \"system\")\n// ============================================================\n\n/**\n * Details for DatabaseOperationError.\n */\nexport type DatabaseOperationErrorDetails = Readonly<{\n operation: string;\n entity: string;\n}>;\n\n/**\n * Thrown when a database operation fails unexpectedly.\n *\n * This indicates a system-level failure in the database backend,\n * not a user-recoverable error.\n */\nexport class DatabaseOperationError extends TypeGraphError {\n declare readonly details: DatabaseOperationErrorDetails;\n\n constructor(\n message: string,\n details: DatabaseOperationErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(message, \"DATABASE_OPERATION_ERROR\", {\n details,\n category: \"system\",\n suggestion: `This is a system-level database error. Check the database connection and retry the operation. If the problem persists, investigate the underlying cause.`,\n cause: options?.cause,\n });\n this.name = \"DatabaseOperationError\";\n }\n}\n\n// ============================================================\n// Vector / Embedding Errors (category: \"user\")\n// ============================================================\n\n/**\n * Details for EmbeddingDimensionChangedError.\n */\nexport type EmbeddingDimensionChangedErrorDetails = Readonly<{\n kind: string;\n fieldPath: string;\n declaredDimensions?: number;\n storedDimensions?: number;\n}>;\n\n/**\n * Thrown when an embedding field's declared dimension no longer matches the\n * dimension of its materialized per-field storage — i.e. a field's\n * `embedding(N)` was changed to `embedding(M)`. The stored vectors are invalid\n * under the new dimension and cannot be converted, only recomputed, so this is\n * a deliberate app-driven migration: call\n * `store.reembedVectorField(kind, fieldPath, ...)` to recreate the storage at\n * the new dimension and re-embed existing rows.\n */\nexport class EmbeddingDimensionChangedError extends TypeGraphError {\n declare readonly details: EmbeddingDimensionChangedErrorDetails;\n\n constructor(\n message: string,\n details: EmbeddingDimensionChangedErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(message, \"EMBEDDING_DIMENSION_CHANGED\", {\n details,\n category: \"user\",\n suggestion: `Run store.reembedVectorField(\"${details.kind}\", \"${details.fieldPath}\", { embed }) to recreate the field's storage at the new dimension and re-embed existing rows.`,\n cause: options?.cause,\n });\n this.name = \"EmbeddingDimensionChangedError\";\n }\n}\n\n// ============================================================\n// Query Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when a query predicate cannot be compiled for the target database.\n */\nexport class UnsupportedPredicateError extends TypeGraphError {\n constructor(\n message: string,\n details: Readonly<Record<string, unknown>> = {},\n options?: { cause?: unknown; suggestion?: string },\n ) {\n super(message, \"UNSUPPORTED_PREDICATE\", {\n details,\n category: \"system\",\n suggestion:\n options?.suggestion ??\n `This predicate may not be supported by your database backend. Check the documentation for supported predicates.`,\n cause: options?.cause,\n });\n this.name = \"UnsupportedPredicateError\";\n }\n}\n\n// ============================================================\n// Compiler Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when a compiler invariant is violated.\n *\n * This indicates a bug in the query compiler — the compiler reached\n * a state that should be unreachable. These errors are not user-recoverable.\n */\nexport class CompilerInvariantError extends TypeGraphError {\n constructor(\n message: string,\n details?: Readonly<Record<string, unknown>>,\n options?: { cause?: unknown },\n ) {\n super(message, \"COMPILER_INVARIANT_ERROR\", {\n details: details ?? {},\n category: \"system\",\n suggestion: `This is an internal compiler error. Please report it as a bug with the query that triggered it.`,\n cause: options?.cause,\n });\n this.name = \"CompilerInvariantError\";\n }\n}\n\n// ============================================================\n// Lifecycle Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when an operation is attempted on a backend that has been disposed.\n *\n * This typically occurs during runtime teardown — for example, when a\n * Cloudflare Workers test runner resets Durable Object storage while\n * the TypeGraph backend still has queued operations.\n */\nexport class BackendDisposedError extends TypeGraphError {\n constructor(options?: { cause?: unknown }) {\n super(\n \"Backend has been disposed — the underlying database connection is no longer available\",\n \"BACKEND_DISPOSED\",\n {\n category: \"system\",\n suggestion:\n \"Ensure all store operations complete before calling backend.close(). \" +\n \"In test environments, await store teardown before resetting the database.\",\n cause: options?.cause,\n },\n );\n this.name = \"BackendDisposedError\";\n }\n}\n\n/**\n * Thrown when a statement is issued on a transaction-scoped backend after\n * its transaction boundary has already returned.\n *\n * The usual source is a callback that lets work escape it. `Promise.all`\n * rejects on its first rejection while its siblings keep running, so\n *\n * ```typescript\n * await store.transaction(async (tx) => {\n * await Promise.all([tx.nodes.Doc.create(a), tx.nodes.Doc.create(b)]);\n * });\n * ```\n *\n * leaves `b`'s remaining statements in flight when `a` fails. Those\n * statements have nowhere safe to go: the driver is about to emit `ROLLBACK`\n * on the same pinned connection and then hand it back to the pool, where a\n * late arrival would execute inside somebody else's transaction. TypeGraph\n * refuses them here instead.\n *\n * The error is normally invisible — `Promise.all` has already rejected with\n * the original failure, and discards this one.\n */\nexport class TransactionClosedError extends TypeGraphError {\n constructor(options?: { cause?: unknown }) {\n super(\n \"Statement issued on a transaction-scoped backend after its transaction \" +\n \"boundary returned. The connection has been released; the statement was not run.\",\n \"TRANSACTION_CLOSED\",\n {\n category: \"user\",\n suggestion:\n \"Await every write started inside store.transaction(...) before the \" +\n \"callback returns. Prefer awaiting a Promise.allSettled(...) over a \" +\n \"Promise.all(...) whose rejection would orphan its siblings.\",\n cause: options?.cause,\n },\n );\n this.name = \"TransactionClosedError\";\n }\n}\n\n// ============================================================\n// Utility Functions\n// ============================================================\n\n/**\n * Type guard for TypeGraphError.\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.create({});\n * } catch (error) {\n * if (isTypeGraphError(error)) {\n * console.log(error.code, error.category);\n * }\n * }\n * ```\n */\nexport function isTypeGraphError(error: unknown): error is TypeGraphError {\n return error instanceof TypeGraphError;\n}\n\n/**\n * Check if error is recoverable by user action (user or constraint error).\n *\n * User-recoverable errors can typically be resolved by:\n * - Fixing invalid input data\n * - Using different IDs or values\n * - Deleting conflicting data first\n *\n * @example\n * ```typescript\n * if (isUserRecoverable(error)) {\n * showErrorToUser(error.toUserMessage());\n * } else {\n * logAndAlertOps(error);\n * }\n * ```\n */\nexport function isUserRecoverable(error: unknown): boolean {\n if (!isTypeGraphError(error)) return false;\n return error.category === \"user\" || error.category === \"constraint\";\n}\n\n/**\n * Check if error indicates a system/infrastructure issue.\n *\n * System errors typically require:\n * - Retry logic (for transient failures)\n * - Investigation (for persistent failures)\n * - Ops team notification\n */\nexport function isSystemError(error: unknown): boolean {\n return isTypeGraphError(error) && error.category === \"system\";\n}\n\n/**\n * Check if error is a constraint violation.\n */\nexport function isConstraintError(error: unknown): boolean {\n return isTypeGraphError(error) && error.category === \"constraint\";\n}\n\n/**\n * Extract suggestion from error if available.\n */\nexport function getErrorSuggestion(error: unknown): string | undefined {\n return isTypeGraphError(error) ? error.suggestion : undefined;\n}\n"]}
|
|
@@ -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":["sql","tables","backend","options","chunk"],"mappings":";;;;;;;;;;;;;;;;AA0HA,SAAS,mBAAA,CACP,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,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AA,IAC1B,gBAAgB,OAAA,CAAQ,cAAA;AAAA,IACxB,0BAA0B,OAAA,CAAQ,wBAAA;AAAA;AAAA;AAAA,IAGlC,oBAAoB,OAAA,CAAQ;AAAA,GAC7B,CAAA;AAED,EAAA,OAAO,EAAE,OAAA,EAAS,aAAA,EAAe,kBAAA,CAAmB,aAAA,EAAc;AACpE","file":"chunk-EFZ4S22A.js","sourcesContent":["import { type SQL as DrizzleSql } from \"drizzle-orm\";\nimport {\n type PgDatabase,\n type PgQueryResultHKT,\n type PgTransaction,\n} from \"drizzle-orm/pg-core\";\nimport { type ExtractTablesWithRelations } from \"drizzle-orm/relations\";\n\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\nfunction 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\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\nfunction isPostgresJsClient(candidate: unknown): 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): PreparedSqlStatement {\n return {\n async execute<TRow>(params: readonly unknown[]): Promise<readonly TRow[]> {\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 * @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 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 if (pgClient === undefined) {\n return {\n compile,\n async execute<TRow>(query: ExecutableSql): Promise<readonly TRow[]> {\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 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 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(pgQueryClient, sqlText);\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 { CompilerInvariantError, ConfigurationError } 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 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} from \"../../utils/sql-errors\";\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 type AdapterBackend,\n type BackendCapabilities,\n type ClaimIndexMaterializationParams,\n type CommitSchemaVersionParams,\n type ContributionMaterializationIdentity,\n type ContributionMaterializationRow,\n createBackendOverlay,\n type CreateVectorIndexParams,\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 IndexMaterializationRow,\n INTERNAL_TEMPORARY_WRITES,\n type InternalTransactionOptions,\n type KindRemovalRow,\n normalizeGraphAnalyticsCapabilities,\n POSTGRES_CAPABILITIES,\n POSTGRES_MAX_BIND_PARAMETERS,\n type RecordContributionMaterializationParams,\n type RecordIndexMaterializationParams,\n type RecordKindRemovalParams,\n type ReleaseIndexMaterializationClaimParams,\n type SchemaVersionRow,\n type SetActiveVersionParams,\n type TransactionBackend,\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 createContributionMaterializer,\n gateFulltext,\n gateFulltextMethods,\n mapContributionMaterializationRow,\n POSTGRES_CONTRIBUTION_MAT_TIMESTAMPS,\n} from \"./contribution-materializations\";\nimport { generatePgCreateTableSQL, generatePostgresDDL } from \"./ddl\";\nimport {\n type AnyPgDatabase,\n type AnyPgTransaction,\n createPostgresExecutionAdapter,\n isNeonHttpClient,\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 assertAdoptedDialect,\n type CommonOperationBackend,\n createCommonOperationBackend,\n type InternalOperationBackend,\n} from \"./operation-backend-core\";\nimport { mapHybridSearchRow } from \"./operations/hybrid\";\nimport {\n createCachedTableExistence,\n createPostgresOperationStrategy,\n} from \"./operations/strategy\";\nimport {\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\nconst NODE_INSERT_PARAM_COUNT = 9;\nconst EDGE_INSERT_PARAM_COUNT = 12;\nconst POSTGRES_NODE_INSERT_BATCH_SIZE = Math.max(\n 1,\n Math.floor(POSTGRES_MAX_BIND_PARAMETERS / NODE_INSERT_PARAM_COUNT),\n);\nconst POSTGRES_EDGE_INSERT_BATCH_SIZE = Math.max(\n 1,\n Math.floor(POSTGRES_MAX_BIND_PARAMETERS / EDGE_INSERT_PARAM_COUNT),\n);\nconst POSTGRES_GET_NODES_ID_CHUNK_SIZE = Math.max(\n 1,\n POSTGRES_MAX_BIND_PARAMETERS - 2,\n);\nconst POSTGRES_GET_EDGES_ID_CHUNK_SIZE = Math.max(\n 1,\n POSTGRES_MAX_BIND_PARAMETERS - 1,\n);\nconst FULLTEXT_UPSERT_PARAM_COUNT = 6;\nconst FULLTEXT_DELETE_FIXED_PARAM_COUNT = 2;\nconst POSTGRES_FULLTEXT_UPSERT_BATCH_SIZE = Math.max(\n 1,\n Math.floor(POSTGRES_MAX_BIND_PARAMETERS / FULLTEXT_UPSERT_PARAM_COUNT),\n);\nconst POSTGRES_FULLTEXT_DELETE_CHUNK_SIZE = Math.max(\n 1,\n POSTGRES_MAX_BIND_PARAMETERS - FULLTEXT_DELETE_FIXED_PARAM_COUNT,\n);\nconst CHECK_UNIQUE_BATCH_FIXED_PARAM_COUNT = 3;\nconst POSTGRES_CHECK_UNIQUE_BATCH_CHUNK_SIZE = Math.max(\n 1,\n POSTGRES_MAX_BIND_PARAMETERS - CHECK_UNIQUE_BATCH_FIXED_PARAM_COUNT,\n);\nconst UNIQUE_INSERT_PARAM_COUNT = 6;\nconst POSTGRES_UNIQUE_INSERT_BATCH_SIZE = Math.max(\n 1,\n Math.floor(POSTGRES_MAX_BIND_PARAMETERS / UNIQUE_INSERT_PARAM_COUNT),\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 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 capabilities = normalizeGraphAnalyticsCapabilities({\n ...baseCapabilities,\n ...httpOnlyOverrides,\n ...options.capabilities,\n });\n const adapterOptions: PostgresExecutionAdapterOptions = {\n ...(options.prepareStatements === undefined ?\n {}\n : { prepareStatements: options.prepareStatements }),\n ...(options.preparedStatementCacheMax === undefined ?\n {}\n : { preparedStatementCacheMax: options.preparedStatementCacheMax }),\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 fulltext: tables.fulltextTableName,\n uniques: getTableName(tables.uniques),\n };\n // Pre-quote identifiers so refreshStatistics() doesn't rebuild the\n // ANALYZE statements on every call. The recorded relations are ANALYZEd\n // separately under an existence guard (see refreshStatistics): a schema\n // created before recorded-time history landed (bring-your-own-pool, no DDL\n // re-run) has no recorded tables, and Postgres fails the whole ANALYZE if any\n // named relation is missing. Per-field vector tables are created lazily and\n // live outside this 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 recordedAnalyzeTables = [\n tableNames.recordedNodes,\n tableNames.recordedEdges,\n tableNames.recordedClock,\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 relation that a\n // bring-your-own-pool schema has not yet created. The Postgres probe is\n // search_path-aware, so positive results are deliberately not cached by bare\n // table name.\n const recordedTableExists = 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 async function ensureContributionMaterializationsTableImpl(): Promise<void> {\n await db.execute(sql.raw(generatePgCreateTableSQL(matTable)));\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 const contributionMaterializer = createContributionMaterializer({\n dialect: \"postgres\",\n fulltextStrategy,\n fulltextTableName: tables.fulltextTableName,\n vectorStrategy,\n execDdl: async (statement) => {\n await db.execute(sql.raw(statement));\n },\n ensureMarkerTable: ensureContributionMaterializationsTableImpl,\n getMarkers: getContributionMaterializationRows,\n recordMarker: recordContributionMaterializationRow,\n deleteMarker: deleteContributionMaterializationRow,\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 });\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: CommonOperationBackend) => Promise<T>,\n ): Promise<T> {\n if (!capabilities.transactions) {\n throw new ConfigurationError(\n \"commitSchemaVersion and setActiveVersion 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 await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${graphId}))`);\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 });\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 });\n return {\n backend: gateFulltext(\n backend,\n contributionMaterializer.assertInitialized,\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 ): Promise<T> {\n return backend.transactionWithNative(async (tx, rawSql) => {\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 = createBackendOverlay(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 await db.execute(sql.raw(statement));\n }\n },\n\n async ensureRevisionOriginsTable(): Promise<void> {\n await db.execute(\n sql.raw(generatePgCreateTableSQL(tables.revisionOrigins)),\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 ),\n\n async executeDdl(ddl: string): Promise<void> {\n await db.execute(sql.raw(ddl));\n },\n\n async ensureIndexMaterializationsTable(): Promise<void> {\n await db.execute(\n sql.raw(generatePgCreateTableSQL(tables.indexMaterializations)),\n );\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 const tableName = getTableName(tables.indexMaterializations);\n await db.execute(\n sql.raw(\n `ALTER TABLE \"${tableName}\" ADD COLUMN IF NOT EXISTS \"building_since\" timestamptz;`,\n ),\n );\n await db.execute(\n sql.raw(\n `ALTER TABLE \"${tableName}\" ADD COLUMN IF NOT EXISTS \"claim_token\" text;`,\n ),\n );\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 db.execute(sql.raw(generatePgCreateTableSQL(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 db.execute(\n sql.raw(generatePgCreateTableSQL(tables.reconciliationMarkers)),\n );\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 // 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 relations may be absent on a schema created before\n // recorded-time history landed (bring-your-own-pool, no DDL re-run).\n // Postgres fails an ANALYZE naming a missing relation, so ANALYZE\n // only the recorded tables that exist.\n const tablePresence = await Promise.all(\n recordedAnalyzeTables.map(async (tableName) => ({\n tableName,\n exists: await recordedTableExists(tableName),\n })),\n );\n const presentRecordedTables = tablePresence\n .filter((entry) => entry.exists)\n .map((entry) => entry.tableName);\n for (const tableName of presentRecordedTables) {\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 setActiveVersion(params: SetActiveVersionParams): Promise<void> {\n await runSchemaWriteTransaction(params.graphId, (target) =>\n target.setActiveVersion(params),\n );\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 return backend;\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}>;\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}>;\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 } = options;\n\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 warning per backend instance when `efSearch` is supplied but the\n // driver can't hold a transaction to scope `SET LOCAL` to.\n let efSearchUnsupportedWarned = false;\n function warnEfSearchUnsupported(): void {\n if (efSearchUnsupportedWarned) return;\n efSearchUnsupportedWarned = true;\n if (typeof console === \"undefined\" || typeof console.warn !== \"function\") {\n return;\n }\n console.warn(\n \"[typegraph] efSearch (hnsw.ef_search override) was ignored: this \" +\n \"Postgres backend has transactions disabled (e.g. drizzle-orm/neon-http), \" +\n \"and SET LOCAL needs a transaction to scope the override. Use a \" +\n \"transactional driver (node-postgres / neon-serverless / postgres-js) \" +\n \"to apply efSearch.\",\n );\n }\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; warned-and-skipped on transactionless drivers, where\n * `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 if (params.efSearch !== undefined) {\n if (capabilities.transactions) {\n overrides.push({\n name: \"hnsw.ef_search\",\n value: String(params.efSearch),\n });\n } else {\n warnEfSearchUnsupported();\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 = {\n checkUniqueBatchChunkSize: POSTGRES_CHECK_UNIQUE_BATCH_CHUNK_SIZE,\n edgeInsertBatchSize: POSTGRES_EDGE_INSERT_BATCH_SIZE,\n // Unlike the static siblings, the embedding upsert honors a runtime\n // `maxBindParameters` override so its chunk size tracks the connection's\n // actual bind budget.\n embeddingUpsertBatchSize: Math.max(\n 1,\n Math.floor(\n (capabilities.maxBindParameters ?? POSTGRES_MAX_BIND_PARAMETERS) /\n EMBEDDING_UPSERT_PARAM_COUNT,\n ),\n ),\n getEdgesChunkSize: POSTGRES_GET_EDGES_ID_CHUNK_SIZE,\n getNodesChunkSize: POSTGRES_GET_NODES_ID_CHUNK_SIZE,\n nodeInsertBatchSize: POSTGRES_NODE_INSERT_BATCH_SIZE,\n uniqueInsertBatchSize: POSTGRES_UNIQUE_INSERT_BATCH_SIZE,\n };\n\n const commonBackend = createCommonOperationBackend({\n batchConfig,\n execution: {\n execAll,\n execGet,\n execRun,\n },\n nowIso,\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\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 const operationBackend: InternalOperationBackend = {\n ...commonBackend,\n ...executeRawMethod,\n ...vectorEmbeddingMethods,\n capabilities,\n fulltextStrategy,\n ...(vectorStrategy === undefined ? {} : { vectorStrategy }),\n dialect: \"postgres\",\n tableNames,\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 try {\n await execRun(indexStatement);\n } catch (error) {\n if (!isInsufficientResourcesError(error)) throw error;\n // Parallel 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 const dropStatement = vectorStrategy.buildDropIndex?.(slot);\n if (dropStatement !== undefined) {\n await execRun(dropStatement);\n }\n const table = portableSql.identifier(\n vectorStrategy.tableName(\n slot.graphId,\n slot.nodeKind,\n slot.fieldPath,\n ),\n );\n await execRun(\n portableSql`ALTER TABLE ${table} SET (parallel_workers = 0)`,\n );\n try {\n await execRun(indexStatement);\n } finally {\n await execRun(\n portableSql`ALTER TABLE ${table} RESET (parallel_workers)`,\n );\n }\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 POSTGRES_FULLTEXT_UPSERT_BATCH_SIZE,\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 POSTGRES_FULLTEXT_DELETE_CHUNK_SIZE,\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 });\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"]}
|
package/dist/chunk-IMQKXL4E.cjs
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
var chunkN2V3HJFV_cjs = require('./chunk-N2V3HJFV.cjs');
|
|
4
|
-
|
|
5
|
-
// src/graph-extension/define-graph-extension.ts
|
|
6
|
-
function defineGraphExtension(input) {
|
|
7
|
-
return chunkN2V3HJFV_cjs.unwrap(chunkN2V3HJFV_cjs.validateGraphExtension(input, { strict: true }));
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
exports.defineGraphExtension = defineGraphExtension;
|
|
11
|
-
//# sourceMappingURL=chunk-IMQKXL4E.cjs.map
|
|
12
|
-
//# sourceMappingURL=chunk-IMQKXL4E.cjs.map
|