@nicia-ai/typegraph 0.50.0 → 0.51.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -0
- package/dist/backend/drizzle/indexes.cjs +10 -8
- package/dist/backend/drizzle/indexes.d.cts +1 -1
- package/dist/backend/drizzle/indexes.d.ts +1 -1
- package/dist/backend/drizzle/indexes.js +6 -4
- package/dist/backend/index.cjs +183 -50
- package/dist/backend/index.d.cts +90 -4
- package/dist/backend/index.d.ts +90 -4
- package/dist/backend/index.js +6 -9
- package/dist/backend/postgres/index.cjs +30 -28
- package/dist/backend/postgres/index.d.cts +7 -7
- package/dist/backend/postgres/index.d.ts +7 -7
- package/dist/backend/postgres/index.js +16 -14
- package/dist/backend/postgres/pglite-store.cjs +6 -62
- package/dist/backend/postgres/pglite-store.cjs.map +1 -1
- package/dist/backend/postgres/pglite-store.d.cts +8 -8
- package/dist/backend/postgres/pglite-store.d.ts +8 -8
- package/dist/backend/postgres/pglite-store.js +6 -62
- package/dist/backend/postgres/pglite-store.js.map +1 -1
- package/dist/backend/postgres/pglite.cjs +18 -16
- package/dist/backend/postgres/pglite.d.cts +3 -3
- package/dist/backend/postgres/pglite.d.ts +3 -3
- package/dist/backend/postgres/pglite.js +17 -15
- package/dist/backend/sqlite/index.cjs +27 -25
- package/dist/backend/sqlite/index.d.cts +7 -7
- package/dist/backend/sqlite/index.d.ts +7 -7
- package/dist/backend/sqlite/index.js +14 -12
- package/dist/backend/sqlite/libsql.cjs +21 -19
- package/dist/backend/sqlite/libsql.cjs.map +1 -1
- package/dist/backend/sqlite/libsql.d.cts +3 -3
- package/dist/backend/sqlite/libsql.d.ts +3 -3
- package/dist/backend/sqlite/libsql.js +16 -14
- package/dist/backend/sqlite/libsql.js.map +1 -1
- package/dist/backend/sqlite/local-store.cjs +8 -64
- package/dist/backend/sqlite/local-store.cjs.map +1 -1
- package/dist/backend/sqlite/local-store.d.cts +8 -8
- package/dist/backend/sqlite/local-store.d.ts +8 -8
- package/dist/backend/sqlite/local-store.js +7 -64
- package/dist/backend/sqlite/local-store.js.map +1 -1
- package/dist/backend/sqlite/local.cjs +22 -19
- package/dist/backend/sqlite/local.d.cts +3 -3
- package/dist/backend/sqlite/local.d.ts +3 -3
- package/dist/backend/sqlite/local.js +18 -15
- package/dist/{chunk-TUVD4DFR.cjs → chunk-2CVDZCXH.cjs} +122 -51
- package/dist/chunk-2CVDZCXH.cjs.map +1 -0
- package/dist/{chunk-I5C6OTKR.js → chunk-2DWTBNSH.js} +3 -3
- package/dist/{chunk-I5C6OTKR.js.map → chunk-2DWTBNSH.js.map} +1 -1
- package/dist/{chunk-C76WFIVZ.cjs → chunk-2KCTP3U2.cjs} +180 -127
- package/dist/chunk-2KCTP3U2.cjs.map +1 -0
- package/dist/{chunk-BYBDM423.cjs → chunk-322TBTOQ.cjs} +48 -48
- package/dist/{chunk-BYBDM423.cjs.map → chunk-322TBTOQ.cjs.map} +1 -1
- package/dist/chunk-36SX6QXP.cjs +186 -0
- package/dist/chunk-36SX6QXP.cjs.map +1 -0
- package/dist/{chunk-H3XP6BAV.js → chunk-36VYWVQU.js} +3 -3
- package/dist/{chunk-H3XP6BAV.js.map → chunk-36VYWVQU.js.map} +1 -1
- package/dist/{chunk-VTJVMP4I.js → chunk-4DKY6RIU.js} +102 -31
- package/dist/chunk-4DKY6RIU.js.map +1 -0
- package/dist/chunk-4QKOZYMV.js +9 -0
- package/dist/chunk-4QKOZYMV.js.map +1 -0
- package/dist/{chunk-U3Z7XKAG.js → chunk-57JM6NW3.js} +8 -18
- package/dist/chunk-57JM6NW3.js.map +1 -0
- package/dist/{chunk-WCLMKNQE.cjs → chunk-5FVZSE3B.cjs} +1356 -1108
- package/dist/chunk-5FVZSE3B.cjs.map +1 -0
- package/dist/{chunk-XMY2SXOH.cjs → chunk-5WWEYV4H.cjs} +2208 -579
- package/dist/chunk-5WWEYV4H.cjs.map +1 -0
- package/dist/{chunk-WQBAQZHR.js → chunk-6NLYIMJO.js} +4 -4
- package/dist/{chunk-WQBAQZHR.js.map → chunk-6NLYIMJO.js.map} +1 -1
- package/dist/{chunk-G2TLHH6T.cjs → chunk-7B7I7YAW.cjs} +6 -6
- package/dist/{chunk-G2TLHH6T.cjs.map → chunk-7B7I7YAW.cjs.map} +1 -1
- package/dist/{chunk-EDLKIQRI.js → chunk-7G5IYROL.js} +6 -548
- package/dist/chunk-7G5IYROL.js.map +1 -0
- package/dist/{chunk-46UGOVRW.js → chunk-7QFRK6PU.js} +3 -7
- package/dist/chunk-7QFRK6PU.js.map +1 -0
- package/dist/chunk-A4C4NJ5U.cjs +12 -0
- package/dist/chunk-A4C4NJ5U.cjs.map +1 -0
- package/dist/{chunk-7CCMCMJO.cjs → chunk-AOGOC6JF.cjs} +77 -68
- package/dist/chunk-AOGOC6JF.cjs.map +1 -0
- package/dist/{chunk-TYGGUWMS.cjs → chunk-B3MN7EJR.cjs} +177 -137
- package/dist/chunk-B3MN7EJR.cjs.map +1 -0
- package/dist/{chunk-K6VKTBST.cjs → chunk-BZ5MVITP.cjs} +4 -4
- package/dist/{chunk-K6VKTBST.cjs.map → chunk-BZ5MVITP.cjs.map} +1 -1
- package/dist/{chunk-ZAQUKCUC.js → chunk-CBOD7TXH.js} +5 -5
- package/dist/{chunk-ZAQUKCUC.js.map → chunk-CBOD7TXH.js.map} +1 -1
- package/dist/{chunk-LLVOQOWE.cjs → chunk-CRZ56SZU.cjs} +6 -5
- package/dist/chunk-CRZ56SZU.cjs.map +1 -0
- package/dist/{chunk-ON47CBE4.cjs → chunk-D3GWARN7.cjs} +47 -47
- package/dist/{chunk-ON47CBE4.cjs.map → chunk-D3GWARN7.cjs.map} +1 -1
- package/dist/{chunk-W5SOCUBL.js → chunk-D3OUDFU7.js} +5 -5
- package/dist/{chunk-W5SOCUBL.js.map → chunk-D3OUDFU7.js.map} +1 -1
- package/dist/chunk-EKG2UXNX.cjs +23 -0
- package/dist/chunk-EKG2UXNX.cjs.map +1 -0
- package/dist/{chunk-2Q45FAIE.js → chunk-EVYW3532.js} +28 -19
- package/dist/chunk-EVYW3532.js.map +1 -0
- package/dist/{chunk-7PRMDZIA.cjs → chunk-FMMW3KX7.cjs} +21 -55
- package/dist/chunk-FMMW3KX7.cjs.map +1 -0
- package/dist/chunk-H2VWDQWC.cjs +571 -0
- package/dist/chunk-H2VWDQWC.cjs.map +1 -0
- package/dist/chunk-H4FY6OZK.js +13 -0
- package/dist/chunk-H4FY6OZK.js.map +1 -0
- package/dist/{chunk-OJHD3LXJ.cjs → chunk-H5IJSROF.cjs} +2 -8
- package/dist/chunk-H5IJSROF.cjs.map +1 -0
- package/dist/{chunk-U5EL6JUV.js → chunk-I5IOSA27.js} +101 -103
- package/dist/chunk-I5IOSA27.js.map +1 -0
- package/dist/{chunk-SHC7BCG5.cjs → chunk-I7YAY2VQ.cjs} +7 -7
- package/dist/{chunk-SHC7BCG5.cjs.map → chunk-I7YAY2VQ.cjs.map} +1 -1
- package/dist/chunk-IRCWIA3R.js +20 -0
- package/dist/chunk-IRCWIA3R.js.map +1 -0
- package/dist/chunk-IVQBLXBK.cjs +55 -0
- package/dist/chunk-IVQBLXBK.cjs.map +1 -0
- package/dist/{chunk-5PP4KRPV.js → chunk-IZD4HTCP.js} +5 -5
- package/dist/{chunk-5PP4KRPV.js.map → chunk-IZD4HTCP.js.map} +1 -1
- package/dist/{chunk-RDP6ZRSM.cjs → chunk-JQKMEKKW.cjs} +261 -204
- package/dist/chunk-JQKMEKKW.cjs.map +1 -0
- package/dist/chunk-JVA3KDEA.cjs +691 -0
- package/dist/chunk-JVA3KDEA.cjs.map +1 -0
- package/dist/{chunk-JG5XIJDY.js → chunk-K67P5DLL.js} +62 -22
- package/dist/chunk-K67P5DLL.js.map +1 -0
- package/dist/{chunk-MX7EKQPM.js → chunk-K6OZIHKI.js} +345 -97
- package/dist/chunk-K6OZIHKI.js.map +1 -0
- package/dist/{chunk-CS6JTQQ2.cjs → chunk-KACEYDYV.cjs} +94 -62
- package/dist/chunk-KACEYDYV.cjs.map +1 -0
- package/dist/{chunk-5OWHU7Z7.cjs → chunk-L6EVYIID.cjs} +248 -210
- package/dist/chunk-L6EVYIID.cjs.map +1 -0
- package/dist/{chunk-7OWE7WD6.js → chunk-LI4K2KEJ.js} +4 -4
- package/dist/{chunk-7OWE7WD6.js.map → chunk-LI4K2KEJ.js.map} +1 -1
- package/dist/chunk-LKZDQ2B4.js +1581 -0
- package/dist/chunk-LKZDQ2B4.js.map +1 -0
- package/dist/{chunk-45YZXI6X.cjs → chunk-LLFPQOBA.cjs} +27 -27
- package/dist/{chunk-45YZXI6X.cjs.map → chunk-LLFPQOBA.cjs.map} +1 -1
- package/dist/{chunk-ZRJTM7MT.js → chunk-LZMQ3SFK.js} +3 -3
- package/dist/{chunk-ZRJTM7MT.js.map → chunk-LZMQ3SFK.js.map} +1 -1
- package/dist/{chunk-DI6VC62F.js → chunk-M3VTS3F6.js} +3 -3
- package/dist/{chunk-DI6VC62F.js.map → chunk-M3VTS3F6.js.map} +1 -1
- package/dist/{chunk-MZ34E2GN.js → chunk-NBOS7BY3.js} +60 -21
- package/dist/chunk-NBOS7BY3.js.map +1 -0
- package/dist/{chunk-YA36ABIL.js → chunk-NGQDGL5X.js} +14 -48
- package/dist/chunk-NGQDGL5X.js.map +1 -0
- package/dist/{chunk-ZBFZGLZE.cjs → chunk-NLX5OWK7.cjs} +6 -2
- package/dist/chunk-NLX5OWK7.cjs.map +1 -0
- package/dist/chunk-NUQ2YFFH.cjs +1637 -0
- package/dist/chunk-NUQ2YFFH.cjs.map +1 -0
- package/dist/{chunk-TTCOPKUL.cjs → chunk-OGL4X4PH.cjs} +182 -184
- package/dist/chunk-OGL4X4PH.cjs.map +1 -0
- package/dist/{chunk-HY5BNOUN.cjs → chunk-OTNTGEXR.cjs} +4 -4
- package/dist/{chunk-HY5BNOUN.cjs.map → chunk-OTNTGEXR.cjs.map} +1 -1
- package/dist/chunk-OTWE63BW.js +53 -0
- package/dist/chunk-OTWE63BW.js.map +1 -0
- package/dist/chunk-PC5NGH5A.js +549 -0
- package/dist/chunk-PC5NGH5A.js.map +1 -0
- package/dist/{chunk-IPRP6TDL.cjs → chunk-PS3TUWJM.cjs} +7 -7
- package/dist/{chunk-IPRP6TDL.cjs.map → chunk-PS3TUWJM.cjs.map} +1 -1
- package/dist/{chunk-V76FGHY3.js → chunk-PVFFH7TL.js} +5 -5
- package/dist/{chunk-V76FGHY3.js.map → chunk-PVFFH7TL.js.map} +1 -1
- package/dist/chunk-QCD5JKU4.cjs +15 -0
- package/dist/chunk-QCD5JKU4.cjs.map +1 -0
- package/dist/{chunk-IRPYOHRC.js → chunk-QG5VEOKX.js} +6 -2
- package/dist/chunk-QG5VEOKX.js.map +1 -0
- package/dist/{chunk-2CYI5HRH.js → chunk-RI7RJH4G.js} +49 -17
- package/dist/chunk-RI7RJH4G.js.map +1 -0
- package/dist/{chunk-5LKOVCPP.js → chunk-RVUL2HXY.js} +6 -5
- package/dist/chunk-RVUL2HXY.js.map +1 -0
- package/dist/{chunk-WK23PGTP.cjs → chunk-S5GU4LUN.cjs} +11 -11
- package/dist/{chunk-WK23PGTP.cjs.map → chunk-S5GU4LUN.cjs.map} +1 -1
- package/dist/{chunk-S33YQEL7.js → chunk-SDPWO2Z5.js} +6 -6
- package/dist/{chunk-S33YQEL7.js.map → chunk-SDPWO2Z5.js.map} +1 -1
- package/dist/{chunk-6S3PTHL4.js → chunk-SLGGT2XD.js} +3 -3
- package/dist/{chunk-6S3PTHL4.js.map → chunk-SLGGT2XD.js.map} +1 -1
- package/dist/{chunk-HSEZ7X6Y.cjs → chunk-TIJUA4I6.cjs} +45 -45
- package/dist/{chunk-HSEZ7X6Y.cjs.map → chunk-TIJUA4I6.cjs.map} +1 -1
- package/dist/{chunk-CSNOYIB4.cjs → chunk-TM54OBHX.cjs} +13 -13
- package/dist/{chunk-CSNOYIB4.cjs.map → chunk-TM54OBHX.cjs.map} +1 -1
- package/dist/{chunk-MM3JHVKZ.cjs → chunk-TUWSVL6I.cjs} +4 -4
- package/dist/{chunk-MM3JHVKZ.cjs.map → chunk-TUWSVL6I.cjs.map} +1 -1
- package/dist/{chunk-2GIV5X4P.js → chunk-TYEYRCXL.js} +86 -33
- package/dist/chunk-TYEYRCXL.js.map +1 -0
- package/dist/{chunk-MJPZNEJZ.js → chunk-UKOVGCRN.js} +2095 -496
- package/dist/chunk-UKOVGCRN.js.map +1 -0
- package/dist/chunk-UYKDYE5D.cjs +12 -0
- package/dist/{chunk-KWNWG4RC.cjs.map → chunk-UYKDYE5D.cjs.map} +1 -1
- package/dist/{chunk-FX5ZW6PN.js → chunk-VAAC7L57.js} +95 -40
- package/dist/chunk-VAAC7L57.js.map +1 -0
- package/dist/{chunk-ISKCIQF2.cjs → chunk-VKHXYVN7.cjs} +14 -25
- package/dist/chunk-VKHXYVN7.cjs.map +1 -0
- package/dist/chunk-VUQZNUHU.js +171 -0
- package/dist/chunk-VUQZNUHU.js.map +1 -0
- package/dist/{chunk-K2XYLVVB.cjs → chunk-WDM5WQK4.cjs} +175 -136
- package/dist/chunk-WDM5WQK4.cjs.map +1 -0
- package/dist/{chunk-GVYVGGPJ.js → chunk-WFSYYU4W.js} +66 -28
- package/dist/chunk-WFSYYU4W.js.map +1 -0
- package/dist/{chunk-R7MRFE5P.js → chunk-WS5MT2UJ.js} +3 -3
- package/dist/{chunk-R7MRFE5P.js.map → chunk-WS5MT2UJ.js.map} +1 -1
- package/dist/chunk-XORONCV3.js +202 -0
- package/dist/chunk-XORONCV3.js.map +1 -0
- package/dist/chunk-ZGVTNKTX.cjs +217 -0
- package/dist/chunk-ZGVTNKTX.cjs.map +1 -0
- package/dist/core/index.cjs +20 -20
- package/dist/core/index.d.cts +4 -4
- package/dist/core/index.d.ts +4 -4
- package/dist/core/index.js +4 -4
- package/dist/{ddl-B49O7dB_.d.ts → ddl-BvcbgzHo.d.ts} +3 -3
- package/dist/{ddl-DcZG660s.d.cts → ddl-Ufebz5q5.d.cts} +3 -3
- package/dist/graph-extension/index.d.cts +2 -4
- package/dist/graph-extension/index.d.ts +2 -4
- package/dist/graph-merge/index.cjs +140 -125
- package/dist/graph-merge/index.cjs.map +1 -1
- package/dist/graph-merge/index.d.cts +8 -9
- package/dist/graph-merge/index.d.ts +8 -9
- package/dist/graph-merge/index.js +42 -27
- package/dist/graph-merge/index.js.map +1 -1
- package/dist/index.cjs +144 -143
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +11 -12
- package/dist/index.d.ts +11 -12
- package/dist/index.js +30 -29
- package/dist/index.js.map +1 -1
- package/dist/indexes/index.cjs +14 -12
- package/dist/indexes/index.d.cts +4 -4
- package/dist/indexes/index.d.ts +4 -4
- package/dist/indexes/index.js +7 -5
- package/dist/{ingestion-import-target-CI8OWIkM.d.ts → ingestion-import-target-CAs1OX-l.d.cts} +1 -1
- package/dist/{ingestion-import-target-DCpfM1PX.d.cts → ingestion-import-target-DCQSPfNx.d.ts} +1 -1
- package/dist/interchange/index.cjs +41 -39
- package/dist/interchange/index.cjs.map +1 -1
- package/dist/interchange/index.d.cts +8 -8
- package/dist/interchange/index.d.ts +8 -8
- package/dist/interchange/index.js +16 -14
- package/dist/interchange/index.js.map +1 -1
- package/dist/local-store-impl-JC7OBRAW.js +75 -0
- package/dist/local-store-impl-JC7OBRAW.js.map +1 -0
- package/dist/local-store-impl-UOS2LUIG.cjs +77 -0
- package/dist/local-store-impl-UOS2LUIG.cjs.map +1 -0
- package/dist/{manager-Cfg1ENj1.d.ts → manager-B68OrPR2.d.ts} +1 -2
- package/dist/{manager-D348fa6W.d.cts → manager-D_t7oK69.d.cts} +1 -2
- package/dist/pglite-store-impl-J5J5AA52.cjs +75 -0
- package/dist/pglite-store-impl-J5J5AA52.cjs.map +1 -0
- package/dist/pglite-store-impl-LDRH2DUH.js +73 -0
- package/dist/pglite-store-impl-LDRH2DUH.js.map +1 -0
- package/dist/{postgres-UStOycLI.d.ts → postgres-BPLSVyHM.d.ts} +1 -1
- package/dist/{postgres-CH1kkM5J.d.cts → postgres-CqvtFC2y.d.cts} +1 -1
- package/dist/profiler/index.d.cts +9 -9
- package/dist/profiler/index.d.ts +9 -9
- package/dist/provenance/index.cjs +33 -20
- package/dist/provenance/index.cjs.map +1 -1
- package/dist/provenance/index.d.cts +7 -7
- package/dist/provenance/index.d.ts +7 -7
- package/dist/provenance/index.js +24 -11
- package/dist/provenance/index.js.map +1 -1
- package/dist/{repair-validity-windows-aWX7VNvv.d.cts → repair-validity-windows-DEzCKAdy.d.cts} +7 -3
- package/dist/{repair-validity-windows-BtOEe2pS.d.ts → repair-validity-windows-GMdaS2AH.d.ts} +7 -3
- package/dist/resolve-D_H8MHtq.d.ts +1805 -0
- package/dist/resolve-WEW8gWws.d.cts +1805 -0
- package/dist/schema/index.cjs +42 -40
- package/dist/schema/index.d.cts +4 -6
- package/dist/schema/index.d.ts +4 -6
- package/dist/schema/index.js +15 -13
- package/dist/{searchable-z4BiFfHI.d.ts → searchable-C_UREI9K.d.ts} +1 -1
- package/dist/{searchable-C8-RrL3l.d.cts → searchable-ClgET_i7.d.cts} +1 -1
- package/dist/{sqlite-axLw5Lo5.d.ts → sqlite-D1mXO9Kp.d.cts} +2 -1
- package/dist/{sqlite-Cyx9j9o6.d.cts → sqlite-MZA3oZNB.d.ts} +2 -1
- package/dist/{store-CTfQ9taw.d.ts → store-CuFX7fCx.d.cts} +38 -41
- package/dist/{store-DR9J7JVB.d.cts → store-D-ZjXQpW.d.ts} +38 -41
- package/dist/{temporal-CBOrERz5.d.ts → temporal-CpyEiRY8.d.cts} +1 -1
- package/dist/{temporal-B4Ky4wzh.d.cts → temporal-y0Aep9Su.d.ts} +1 -1
- package/dist/{types-CWg4dTjj.d.ts → types-6yf0Vv-_.d.cts} +1672 -1
- package/dist/{types-CWg4dTjj.d.cts → types-6yf0Vv-_.d.ts} +1672 -1
- package/dist/{types-BScHXVM7.d.ts → types-DzJ4dlzk.d.cts} +1 -1
- package/dist/{types-BE921wRl.d.cts → types-_vVSB9k-.d.ts} +1 -1
- package/dist/{where-BWXUPV3C.d.ts → where-DuG2LCLe.d.ts} +1 -1
- package/dist/{where-CNtx1aLc.d.cts → where-Mhf_yyKX.d.cts} +1 -1
- package/package.json +5 -1
- package/dist/chunk-2CYI5HRH.js.map +0 -1
- package/dist/chunk-2GIV5X4P.js.map +0 -1
- package/dist/chunk-2Q45FAIE.js.map +0 -1
- package/dist/chunk-46UGOVRW.js.map +0 -1
- package/dist/chunk-5LKOVCPP.js.map +0 -1
- package/dist/chunk-5OWHU7Z7.cjs.map +0 -1
- package/dist/chunk-6LEOAIIB.js +0 -1160
- package/dist/chunk-6LEOAIIB.js.map +0 -1
- package/dist/chunk-7CCMCMJO.cjs.map +0 -1
- package/dist/chunk-7PRMDZIA.cjs.map +0 -1
- package/dist/chunk-C76WFIVZ.cjs.map +0 -1
- package/dist/chunk-CS6JTQQ2.cjs.map +0 -1
- package/dist/chunk-EDLKIQRI.js.map +0 -1
- package/dist/chunk-EH3JZJUM.cjs +0 -567
- package/dist/chunk-EH3JZJUM.cjs.map +0 -1
- package/dist/chunk-FX5ZW6PN.js.map +0 -1
- package/dist/chunk-GHZPZNFC.cjs +0 -132
- package/dist/chunk-GHZPZNFC.cjs.map +0 -1
- package/dist/chunk-GVYVGGPJ.js.map +0 -1
- package/dist/chunk-IHK5KA2Q.cjs +0 -262
- package/dist/chunk-IHK5KA2Q.cjs.map +0 -1
- package/dist/chunk-IRPYOHRC.js.map +0 -1
- package/dist/chunk-ISKCIQF2.cjs.map +0 -1
- package/dist/chunk-JG5XIJDY.js.map +0 -1
- package/dist/chunk-K2XYLVVB.cjs.map +0 -1
- package/dist/chunk-KWNWG4RC.cjs +0 -12
- package/dist/chunk-LLVOQOWE.cjs.map +0 -1
- package/dist/chunk-MJPZNEJZ.js.map +0 -1
- package/dist/chunk-MX7EKQPM.js.map +0 -1
- package/dist/chunk-MZ34E2GN.js.map +0 -1
- package/dist/chunk-OJHD3LXJ.cjs.map +0 -1
- package/dist/chunk-PALYTHGM.js +0 -114
- package/dist/chunk-PALYTHGM.js.map +0 -1
- package/dist/chunk-RDP6ZRSM.cjs.map +0 -1
- package/dist/chunk-S3SDEQMC.js +0 -532
- package/dist/chunk-S3SDEQMC.js.map +0 -1
- package/dist/chunk-TEC24ZDA.cjs +0 -1254
- package/dist/chunk-TEC24ZDA.cjs.map +0 -1
- package/dist/chunk-TP4NJTI3.cjs +0 -1192
- package/dist/chunk-TP4NJTI3.cjs.map +0 -1
- package/dist/chunk-TTCOPKUL.cjs.map +0 -1
- package/dist/chunk-TUVD4DFR.cjs.map +0 -1
- package/dist/chunk-TYGGUWMS.cjs.map +0 -1
- package/dist/chunk-U3Z7XKAG.js.map +0 -1
- package/dist/chunk-U5EL6JUV.js.map +0 -1
- package/dist/chunk-VTJVMP4I.js.map +0 -1
- package/dist/chunk-WCLMKNQE.cjs.map +0 -1
- package/dist/chunk-XMY2SXOH.cjs.map +0 -1
- package/dist/chunk-Y55DLLEG.js +0 -247
- package/dist/chunk-Y55DLLEG.js.map +0 -1
- package/dist/chunk-YA36ABIL.js.map +0 -1
- package/dist/chunk-ZBFZGLZE.cjs.map +0 -1
- package/dist/index-B0PrmE3K.d.cts +0 -1146
- package/dist/index-CwcXsL5R.d.ts +0 -1146
- package/dist/materialize-indexes-C9GG3O3C.d.ts +0 -266
- package/dist/materialize-indexes-CrSiW_lT.d.cts +0 -266
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/backend/drizzle/execution/sqlite-execution.ts","../src/backend/drizzle/sqlite.ts"],"names":["sql","executeCompiled","executeCompiledRun","executePreparedRunBatch","rows","chunk","tables","options"],"mappings":";;;;;;;;;;;;;AAoBA,IAAM,oCAAA,GAAuC,GAAA;AA8H7C,SAAS,eAAe,EAAA,EAA2C;AACjE,EAAA,MAAM,mBAAA,GAAsB,EAAA;AAC5B,EAAA,MAAM,kBAAA,GAAqB,mBAAA,CAAoB,OAAA,EAAS,WAAA,EAAa,IAAA;AACrE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,aAAa,CAAA;AAE3C,EAAA,OAAO,OAAA;AACT;AAEA,SAAS,yBACP,OAAA,EAC0B;AAC1B,EAAA,MAAM,kBAAA,GACJ,OAAA,CAAQ,gBAAA,IACR,4BAAA,CAA6B,QAAQ,EAAA,EAAI;AAAA,IACvC,cAAc,OAAA,CAAQ;AAAA,GACvB,CAAA;AAQH,EAAA,OAAO,4BAAA,CAA6B;AAAA,IAClC,cAAc,OAAA,CAAQ,YAAA;AAAA,IACtB,IAAI,OAAA,CAAQ,EAAA;AAAA,IACZ,gBAAA,EAAkB,kBAAA;AAAA,IAClB,mBAAmB,OAAA,CAAQ,iBAAA;AAAA,IAC3B,YAAY,OAAA,CAAQ,UAAA;AAAA,IACpB,kBAAkB,OAAA,CAAQ,gBAAA;AAAA,IAC1B,gBAAgB,OAAA,CAAQ,cAAA;AAAA,IACxB,0BAA0B,OAAA,CAAQ,wBAAA;AAAA,IAClC,iBAAA,EAAmB;AAAA,GACpB,CAAA;AACH","file":"chunk-MZ34E2GN.js","sourcesContent":["import { type SQL as DrizzleSql, sql } from \"drizzle-orm\";\nimport { type BaseSQLiteDatabase } from \"drizzle-orm/sqlite-core\";\n\nimport { isSqlFragment } from \"../../../query/sql-fragment\";\nimport {\n D1_MAX_BIND_PARAMETERS,\n DURABLE_OBJECT_MAX_BIND_PARAMETERS,\n MODERN_SQLITE_MAX_BIND_PARAMETERS,\n SQLITE_MAX_BIND_PARAMETERS,\n} from \"../../types\";\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\nconst DEFAULT_PREPARED_STATEMENT_CACHE_MAX = 256;\n\ntype PreparedAllStatement = Readonly<{\n all: (...params: readonly unknown[]) => readonly unknown[];\n /**\n * Executes a statement that returns no rows. better-sqlite3 and\n * bun:sqlite both expose it; better-sqlite3 additionally REQUIRES it for\n * non-reader statements (`all()` on those throws).\n */\n run?: (...params: readonly unknown[]) => unknown;\n /**\n * better-sqlite3's \"does this statement return rows\" flag. bun:sqlite\n * has no equivalent; `undefined` is treated as non-reader on the run\n * path (bun's `run()` accepts any statement).\n */\n reader?: boolean;\n}>;\n\ntype SqliteClientWithPrepare = Readonly<{\n prepare: (sqlText: string) => PreparedAllStatement;\n}>;\n\ntype SqliteClientCarrier = Readonly<{ $client?: unknown }>;\n\ntype DurableObjectSqlApi = Readonly<{\n exec: (...args: readonly unknown[]) => unknown;\n}>;\n\n/**\n * Runtime shape of the Durable Object storage client exposed as\n * `drizzle(ctx.storage).$client`. Structural because Drizzle does not export\n * this client type and constructor names are not stable under bundling.\n */\nexport type DurableObjectStorageClient = Readonly<{\n sql: DurableObjectSqlApi;\n transaction: <Result>(run: () => Promise<Result>) => Promise<Result>;\n transactionSync: <Result>(run: () => Result) => Result;\n}>;\n\ntype SqliteHostedPlatform = \"d1\" | \"durable-object\";\n\ntype SessionLike = Readonly<{\n constructor?: Readonly<{\n name?: string;\n }>;\n}>;\n\ntype DatabaseWithSession = Readonly<{\n _?: Readonly<{\n session?: SessionLike;\n }>;\n session?: SessionLike;\n}>;\n\n/**\n * Controls how the backend manages SQLite transactions.\n *\n * - `\"sql\"`: TypeGraph issues BEGIN / COMMIT / ROLLBACK SQL directly on\n * the connection. Default for sync drivers (better-sqlite3,\n * bun:sqlite); also selected by `createLibsqlBackend` for\n * local `@libsql/client` connections (`file:` / `:memory:`),\n * whose `client.transaction()` permanently abandons the\n * current connection — fatal for an in-memory database.\n * - `\"drizzle\"`: Delegates to Drizzle's `db.transaction()` method.\n * Default for async drivers (remote libsql/Turso, sql.js).\n * - `\"do-sqlite\"`: Delegates to the Cloudflare Durable Objects async\n * storage transaction runner (`db.$client.transaction`,\n * i.e. `ctx.storage.transaction(async ...)`). Drizzle's\n * own `db.transaction()` on DO is\n * `ctx.storage.transactionSync` and cannot span `await`,\n * so it is deliberately not used. Auto-detected for\n * `drizzle(ctx.storage)` (#140).\n * - `\"none\"`: Transactions disabled. Default for Cloudflare D1\n * (`D1Database.batch` is transactional but not an\n * interactive runner — tracked separately).\n */\nexport type SqliteTransactionMode = \"sql\" | \"drizzle\" | \"none\" | \"do-sqlite\";\n\nexport type SqliteExecutionProfileHints = Readonly<{\n isSync?: boolean;\n transactionMode?: SqliteTransactionMode;\n}>;\n\ntype SqliteExecutionAdapterOptions = Readonly<{\n profileHints?: SqliteExecutionProfileHints;\n statementCacheMax?: number;\n}>;\n\nexport type AnySqliteDatabase = BaseSQLiteDatabase<\"sync\" | \"async\", unknown>;\n\nexport type SqliteExecutionProfile = Readonly<{\n /** Hosted runtime detected independently of caller-supplied hints. */\n hostedPlatform?: SqliteHostedPlatform;\n /** Platform ceiling that capability overrides may lower but never raise. */\n hardMaxBindParameters?: number;\n isSync: boolean;\n /**\n * Detected per-statement bound-parameter ceiling for this connection:\n * Cloudflare's documented D1 / Durable Objects cap, the probed\n * `SQLITE_MAX_VARIABLE_NUMBER` on synchronous drivers, or the conservative\n * 999 floor when the limit cannot be probed (async/remote drivers).\n */\n maxBindParameters: number;\n supportsCompiledExecution: boolean;\n transactionMode: SqliteTransactionMode;\n}>;\n\nexport type SqliteExecutionAdapter = Readonly<\n SqlExecutionAdapter & {\n clearStatementCache: () => void;\n profile: SqliteExecutionProfile;\n /**\n * Executes a compiled statement that returns no rows through the\n * prepared-statement cache. Present only on synchronous drivers with a\n * preparable client — the CRUD write path falls back to drizzle's\n * `db.run()` when absent.\n */\n executeCompiledRun?: (compiledQuery: CompiledSqlQuery) => Promise<void>;\n /** Rebinds one cached non-reader statement for every parameter row. */\n executePreparedRunBatch?: (\n sqlText: string,\n params: readonly (readonly unknown[])[],\n ) => Promise<void>;\n }\n>;\n\nfunction getSessionName(db: AnySqliteDatabase): string | undefined {\n const databaseWithSession = db as DatabaseWithSession;\n const primarySessionName = databaseWithSession.session?.constructor?.name;\n if (primarySessionName !== undefined) {\n return primarySessionName;\n }\n\n return databaseWithSession._?.session?.constructor?.name;\n}\n\nfunction isD1DatabaseBySessionName(db: AnySqliteDatabase): boolean {\n return getSessionName(db) === \"SQLiteD1Session\";\n}\n\nfunction isDurableObjectBySessionName(db: AnySqliteDatabase): boolean {\n const sessionName = getSessionName(db);\n // drizzle-orm/durable-sqlite's session class is `SQLiteDOSession`\n // (verified drizzle 0.45.x). `SQLiteDurableObjectSession` is kept as\n // a defensive alias against future drizzle renames.\n return (\n sessionName === \"SQLiteDOSession\" ||\n sessionName === \"SQLiteDurableObjectSession\"\n );\n}\n\nfunction isDurableObjectStorageClient(\n value: unknown,\n): value is DurableObjectStorageClient {\n if (typeof value !== \"object\" || value === null) return false;\n const candidate = value as Record<string, unknown>;\n const sqlApi = candidate[\"sql\"];\n return (\n typeof candidate[\"transaction\"] === \"function\" &&\n typeof candidate[\"transactionSync\"] === \"function\" &&\n typeof sqlApi === \"object\" &&\n sqlApi !== null &&\n typeof (sqlApi as Record<string, unknown>)[\"exec\"] === \"function\"\n );\n}\n\n/**\n * Returns the real Durable Object storage client when the Drizzle connection\n * exposes its distinctive async + sync transaction runners and SQL API.\n * Requiring the full shape avoids mistaking better-sqlite3's transaction\n * wrapper factory for the Durable Object async runner.\n */\nexport function getDurableObjectStorageClient(\n db: AnySqliteDatabase,\n): DurableObjectStorageClient | undefined {\n const client = (db as SqliteClientCarrier).$client;\n return isDurableObjectStorageClient(client) ? client : undefined;\n}\n\nfunction detectHostedPlatform(\n db: AnySqliteDatabase,\n): SqliteHostedPlatform | undefined {\n if (\n getDurableObjectStorageClient(db) !== undefined ||\n isDurableObjectBySessionName(db)\n ) {\n return \"durable-object\";\n }\n if (isD1DatabaseBySessionName(db)) return \"d1\";\n return undefined;\n}\n\nfunction isSyncDatabaseBySessionName(db: AnySqliteDatabase): boolean {\n const sessionName = getSessionName(db);\n return (\n sessionName === \"BetterSQLiteSession\" || sessionName === \"BunSQLiteSession\"\n );\n}\n\nfunction detectSyncProfile(\n db: AnySqliteDatabase,\n profileHints: SqliteExecutionProfileHints,\n hostedPlatform: SqliteHostedPlatform | undefined,\n): boolean {\n if (hostedPlatform === \"durable-object\") return true;\n if (hostedPlatform === \"d1\") return false;\n if (profileHints.isSync !== undefined) {\n return profileHints.isSync;\n }\n\n const sessionName = getSessionName(db);\n if (\n sessionName === \"BetterSQLiteSession\" ||\n sessionName === \"BunSQLiteSession\"\n ) {\n return true;\n }\n\n try {\n const probeResult = db.get(sql`SELECT 1 AS __typegraph_sync_probe__`);\n return !(probeResult instanceof Promise);\n } catch {\n return isSyncDatabaseBySessionName(db);\n }\n}\n\nfunction detectTransactionMode(\n profileHints: SqliteExecutionProfileHints,\n isSync: boolean,\n hostedPlatform: SqliteHostedPlatform | undefined,\n): SqliteTransactionMode {\n // Hosted platform identity is authoritative. A stale hint must not disable\n // Durable Object rollback or opt D1 into unsupported interactive writes.\n if (hostedPlatform === \"durable-object\") return \"do-sqlite\";\n if (hostedPlatform === \"d1\") return \"none\";\n if (profileHints.transactionMode !== undefined) {\n return profileHints.transactionMode;\n }\n // Neither D1 nor Durable Object SQLite supports raw BEGIN/COMMIT SQL\n // through Drizzle's db.run(), and Drizzle's own db.transaction() on\n // Durable Objects is `ctx.storage.transactionSync` (cannot span an\n // await). Durable Objects expose an async storage transaction runner\n // (`ctx.storage.transaction(async ...)`, surfaced by Drizzle as\n // `db.$client.transaction`) — route those through \"do-sqlite\" (#140).\n // D1 has no equivalent interactive runner (only batch); it stays\n // \"none\" pending a separate batch-mode investigation.\n if (isSync) return \"sql\";\n return \"drizzle\";\n}\n\n// SQLITE_MAX_VARIABLE_NUMBER's compiled-in default rose from 999 to 32,766\n// in SQLite 3.32.0. Builds that override the default list it in\n// `PRAGMA compile_options`; builds that keep it do not, so the version\n// decides the fallback.\nconst MAX_VARIABLE_NUMBER_COMPILE_OPTION = /^MAX_VARIABLE_NUMBER=(\\d+)$/;\nconst FIRST_MODERN_BIND_LIMIT_MAJOR = 3;\nconst FIRST_MODERN_BIND_LIMIT_MINOR = 32;\n\nfunction parseCompiledMaxVariableNumber(\n rows: readonly unknown[],\n): number | undefined {\n for (const row of rows) {\n if (typeof row !== \"object\" || row === null) continue;\n const option = (row as Record<string, unknown>)[\"compile_options\"];\n if (typeof option !== \"string\") continue;\n const match = MAX_VARIABLE_NUMBER_COMPILE_OPTION.exec(option);\n if (match !== null) return Number(match[1]);\n }\n return undefined;\n}\n\nfunction hasModernBindLimitByVersion(rows: readonly unknown[]): boolean {\n const first = rows[0];\n if (typeof first !== \"object\" || first === null) return false;\n const version = (first as Record<string, unknown>)[\"version\"];\n if (typeof version !== \"string\") return false;\n const [major = 0, minor = 0] = version.split(\".\").map(Number);\n if (!Number.isFinite(major) || !Number.isFinite(minor)) return false;\n return (\n major > FIRST_MODERN_BIND_LIMIT_MAJOR ||\n (major === FIRST_MODERN_BIND_LIMIT_MAJOR &&\n minor >= FIRST_MODERN_BIND_LIMIT_MINOR)\n );\n}\n\n/**\n * Resolves the connection's per-statement bound-parameter ceiling. Batch\n * chunk math derives from this value, so too high breaks batched writes at\n * runtime and too low wastes round trips (999 vs 32,766 is ~33× more\n * chunks per bulk insert).\n */\nfunction detectHardMaxBindParameters(\n transactionMode: SqliteTransactionMode,\n hostedPlatform: SqliteHostedPlatform | undefined,\n): number | undefined {\n if (hostedPlatform === \"durable-object\" || transactionMode === \"do-sqlite\") {\n return DURABLE_OBJECT_MAX_BIND_PARAMETERS;\n }\n if (hostedPlatform === \"d1\") return D1_MAX_BIND_PARAMETERS;\n return undefined;\n}\n\nfunction detectMaxBindParameters(\n sqliteClient: SqliteClientWithPrepare | undefined,\n hardMaxBindParameters: number | undefined,\n): number {\n if (hardMaxBindParameters !== undefined) return hardMaxBindParameters;\n if (sqliteClient === undefined) return SQLITE_MAX_BIND_PARAMETERS;\n try {\n const compiled = parseCompiledMaxVariableNumber(\n sqliteClient.prepare(\"PRAGMA compile_options\").all(),\n );\n if (compiled !== undefined) return compiled;\n const isModern = hasModernBindLimitByVersion(\n sqliteClient.prepare(\"SELECT sqlite_version() AS version\").all(),\n );\n return isModern ?\n MODERN_SQLITE_MAX_BIND_PARAMETERS\n : SQLITE_MAX_BIND_PARAMETERS;\n } catch {\n // A client that can't answer the probes keeps the conservative floor.\n return SQLITE_MAX_BIND_PARAMETERS;\n }\n}\n\n/**\n * The single spelling of \"this object prepares statements\": returns it as a\n * property bag when it does, `undefined` otherwise. Every driver predicate\n * below and {@link resolveSqliteClient} read it, so \"prepare-capable\" cannot\n * drift between the execution path and the serialized-resource marking.\n */\nfunction preparingClient(\n client: unknown,\n): Readonly<Record<string, unknown>> | undefined {\n if (typeof client !== \"object\" || client === null) return undefined;\n const candidate = client as Readonly<Record<string, unknown>>;\n return typeof candidate[\"prepare\"] === \"function\" ? candidate : undefined;\n}\n\n/** Whether every named member of `client` is a function. */\nfunction hasMethods(\n client: Readonly<Record<string, unknown>>,\n methods: readonly string[],\n): boolean {\n return methods.every((method) => typeof client[method] === \"function\");\n}\n\n/**\n * Whether a driver client is better-sqlite3's `Database`.\n *\n * `pragma` is the discriminator: better-sqlite3 exposes it as a method, and\n * none of the other prepare-capable SQLite clients (bun:sqlite, sql.js,\n * node:sqlite) has any counterpart. Duck-typed rather than `instanceof`, so\n * the native addon is never imported by this bundler-friendly module.\n */\nexport function isBetterSqlite3Client(client: unknown): boolean {\n const candidate = preparingClient(client);\n return candidate !== undefined && hasMethods(candidate, [\"pragma\"]);\n}\n\n/**\n * Whether a driver client is a `bun:sqlite` `Database` — what\n * `drizzle-orm/bun-sqlite` exposes as `$client`.\n *\n * ONE synchronous connection: every statement from every wrapper over it runs\n * on it, in order, exactly like better-sqlite3.\n *\n * Structural, never the session's constructor name (which bundlers rename):\n * verified against `bun-types` 1.3.x `bun:sqlite`, a `Database` carries\n * `query` (the cached-statement factory better-sqlite3 does not have),\n * `prepare`, `run`/`exec`, `serialize`, and a `filename` string — where\n * better-sqlite3 names that property `name` and sql.js has neither. The\n * combination is not satisfied by any other client this package can meet.\n */\nexport function isBunSqliteClient(client: unknown): boolean {\n const candidate = preparingClient(client);\n return (\n candidate !== undefined &&\n hasMethods(candidate, [\"query\", \"run\", \"exec\", \"serialize\"]) &&\n typeof candidate[\"filename\"] === \"string\"\n );\n}\n\n/**\n * Whether a driver client is a `sql.js` `Database` — what\n * `drizzle-orm/sql-js` takes as its client.\n *\n * ONE in-WASM database handle, executed synchronously in-process, so two\n * wrappers over it serialize exactly as two wrappers over one better-sqlite3\n * handle do.\n *\n * Structural evidence (verified against `@types/sql.js` 1.4.x): `export`\n * (dump the database to bytes) and `getRowsModified` are sql.js's own API and\n * exist on no other SQLite client — better-sqlite3 and bun:sqlite spell the\n * dump `serialize` and have no rows-modified method at all — alongside the\n * `prepare`/`exec`/`run` trio every driver has.\n */\nexport function isSqlJsClient(client: unknown): boolean {\n const candidate = preparingClient(client);\n return (\n candidate !== undefined &&\n hasMethods(candidate, [\"exec\", \"run\", \"export\", \"getRowsModified\"])\n );\n}\n\n/**\n * Returns the driver client a Drizzle SQLite database prepares statements on\n * for TypeGraph's COMPILED execution path, or `undefined` when it has none it\n * can drive.\n *\n * sql.js is excluded deliberately: its `prepare` returns a sql.js `Statement`\n * (`bind`/`step`/`getAsObject`/`free`) with no `all()`, so the compiled path's\n * `prepared.all(...params)` would throw on the first statement. Drizzle's own\n * sql-js session drives that statement shape correctly, so an excluded client\n * falls back to the Drizzle path and works instead of failing — the abstention\n * is what makes the advertised sql.js support real. Every other\n * prepare-capable client returns statements with `all()` (better-sqlite3,\n * bun:sqlite).\n */\nfunction resolveSqliteClient(\n db: AnySqliteDatabase,\n): SqliteClientWithPrepare | undefined {\n const sqliteClient = (db as SqliteClientCarrier).$client;\n if (preparingClient(sqliteClient) === undefined) return;\n if (isSqlJsClient(sqliteClient)) return;\n return sqliteClient as SqliteClientWithPrepare;\n}\n\nfunction getOrCreatePreparedStatement(\n cache: Map<string, PreparedAllStatement>,\n sqliteClient: SqliteClientWithPrepare,\n sqlText: string,\n cacheMax: number,\n): PreparedAllStatement {\n return getOrCreateLru(cache, sqlText, cacheMax, () =>\n sqliteClient.prepare(sqlText),\n );\n}\n\n// Uses unconditional `await` because Drizzle returns SQLiteRaw thenables\n// that fail `instanceof Promise` checks (drizzle-team/drizzle-orm#2275).\nasync function executeDrizzleQuery<TRow>(\n db: AnySqliteDatabase,\n query: DrizzleSql,\n): Promise<readonly TRow[]> {\n return await db.all(query);\n}\n\nfunction createPreparedStatementExecutor(\n sqliteClient: SqliteClientWithPrepare,\n cache: Map<string, PreparedAllStatement>,\n sqlText: string,\n cacheMax: number,\n): PreparedSqlStatement {\n return {\n execute<TRow>(params: readonly unknown[]): Promise<readonly TRow[]> {\n const preparedStatement = getOrCreatePreparedStatement(\n cache,\n sqliteClient,\n sqlText,\n cacheMax,\n );\n const rows = preparedStatement.all(...params);\n return Promise.resolve(rows as readonly TRow[]);\n },\n };\n}\n\nexport function createSqliteExecutionAdapter(\n db: AnySqliteDatabase,\n statementCacheMaxOrOptions: number | SqliteExecutionAdapterOptions = {},\n): SqliteExecutionAdapter {\n const options: SqliteExecutionAdapterOptions =\n typeof statementCacheMaxOrOptions === \"number\" ?\n { statementCacheMax: statementCacheMaxOrOptions }\n : statementCacheMaxOrOptions;\n const statementCacheMax =\n options.statementCacheMax ?? DEFAULT_PREPARED_STATEMENT_CACHE_MAX;\n const profileHints = options.profileHints ?? {};\n\n const hostedPlatform = detectHostedPlatform(db);\n const isSync = detectSyncProfile(db, profileHints, hostedPlatform);\n const sqliteClient = isSync ? resolveSqliteClient(db) : undefined;\n const transactionMode = detectTransactionMode(\n profileHints,\n isSync,\n hostedPlatform,\n );\n const hardMaxBindParameters = detectHardMaxBindParameters(\n transactionMode,\n hostedPlatform,\n );\n const maxBindParameters = detectMaxBindParameters(\n sqliteClient,\n hardMaxBindParameters,\n );\n\n const profile: SqliteExecutionProfile = {\n ...(hostedPlatform === undefined ? {} : { hostedPlatform }),\n ...(hardMaxBindParameters === undefined ? {} : { hardMaxBindParameters }),\n isSync,\n maxBindParameters,\n supportsCompiledExecution: sqliteClient !== undefined,\n transactionMode,\n };\n\n const compile = (query: ExecutableSql): CompiledSqlQuery =>\n compileQueryWithDialect(db, query, \"SQLite\");\n\n if (sqliteClient !== undefined) {\n const client = sqliteClient;\n const statementCache = new Map<string, PreparedAllStatement>();\n\n function executeCompiled<TRow>(\n compiledQuery: CompiledSqlQuery,\n ): Promise<readonly TRow[]> {\n const preparedStatement = getOrCreatePreparedStatement(\n statementCache,\n client,\n compiledQuery.sql,\n statementCacheMax,\n );\n const rows = preparedStatement.all(...compiledQuery.params);\n return Promise.resolve(rows as readonly TRow[]);\n }\n\n function executeCompiledRun(\n compiledQuery: CompiledSqlQuery,\n ): Promise<void> {\n const preparedStatement = getOrCreatePreparedStatement(\n statementCache,\n client,\n compiledQuery.sql,\n statementCacheMax,\n );\n // better-sqlite3 rejects run() on reader statements and all() on\n // non-reader statements, so pick by the statement's own flag; a\n // client without run() (or without the reader flag but returning\n // rows) drains through all() and discards.\n if (\n preparedStatement.run === undefined ||\n preparedStatement.reader === true\n ) {\n preparedStatement.all(...compiledQuery.params);\n } else {\n preparedStatement.run(...compiledQuery.params);\n }\n return Promise.resolve();\n }\n\n function executePreparedRunBatch(\n sqlText: string,\n parameterRows: readonly (readonly unknown[])[],\n ): Promise<void> {\n const preparedStatement = getOrCreatePreparedStatement(\n statementCache,\n client,\n sqlText,\n statementCacheMax,\n );\n if (preparedStatement.run === undefined) {\n throw new Error(\n \"Trusted SQLite import requires a prepared statement run() method.\",\n );\n }\n for (const params of parameterRows) {\n preparedStatement.run(...params);\n }\n return Promise.resolve();\n }\n\n return {\n clearStatementCache() {\n statementCache.clear();\n },\n compile,\n execute<TRow>(query: ExecutableSql): Promise<readonly TRow[]> {\n const compiledQuery = compile(query);\n return executeCompiled<TRow>(compiledQuery);\n },\n executeCompiled,\n executeCompiledRun,\n executePreparedRunBatch,\n prepare(sqlText: string): PreparedSqlStatement {\n return createPreparedStatementExecutor(\n client,\n statementCache,\n sqlText,\n statementCacheMax,\n );\n },\n profile,\n };\n }\n\n return {\n clearStatementCache() {\n // No-op: no statement cache in async/D1 mode\n },\n compile,\n execute<TRow>(query: ExecutableSql): Promise<readonly TRow[]> {\n return executeDrizzleQuery<TRow>(\n db,\n isSqlFragment(query) ? toDrizzleSql(query, \"sqlite\") : query,\n );\n },\n profile,\n };\n}\n","/**\n * SQLite backend adapter for TypeGraph.\n *\n * Works with any Drizzle SQLite database instance:\n * - better-sqlite3\n * - libsql / Turso\n * - Cloudflare D1\n * - bun:sqlite\n * - sql.js\n *\n * @example\n * ```typescript\n * import { drizzle } from \"drizzle-orm/better-sqlite3\";\n * import Database from \"better-sqlite3\";\n * import { createSqliteBackend, tables } from \"@nicia-ai/typegraph/adapters/drizzle/sqlite\";\n *\n * const sqlite = new Database(\"app.db\");\n * const db = drizzle(sqlite);\n * const backend = createSqliteBackend(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 { BaseSQLiteDatabase } from \"drizzle-orm/sqlite-core\";\n\nimport { BackendDisposedError, ConfigurationError } from \"../../errors\";\nimport type { ResolvedSqlTableNames } from \"../../query/compiler/schema\";\nimport {\n buildFulltextCapabilities,\n fts5Strategy,\n type FulltextStrategy,\n} from \"../../query/dialect/fulltext-strategy\";\nimport {\n assertVectorSearchLimit,\n buildVectorCapabilities,\n resolveEfSearchOverride,\n vectorSearchFrontierTuning,\n type VectorSlot,\n type VectorStrategy,\n} from \"../../query/dialect/vector-strategy\";\nimport {\n isSqlFragment,\n sql as portableSql,\n type SqlFragment,\n} from \"../../query/sql-fragment\";\nimport { type CompiledRowsSql } from \"../../query/sql-intent\";\nimport { chunk as chunkArray } from \"../../utils/array\";\nimport { requireDefined } from \"../../utils/presence\";\nimport {\n isMissingTableError,\n isSqliteNotAuthorizedError,\n} from \"../../utils/sql-errors\";\nimport { FIND_EDGES_ENDPOINT_FIXED_PARAM_COUNT } from \"../edge-endpoint-sets\";\nimport { buildLiveNodeCandidates } from \"../live-node-candidates\";\nimport {\n type AdapterBackend,\n type BackendCapabilities,\n type CommitSchemaVersionIfKindsEmptyResult,\n type CommitSchemaVersionParams,\n type ContributionDiagnostic,\n type ContributionMaterializationIdentity,\n type ContributionMaterializationRow,\n type ContributionProbeEntry,\n type ContributionRebuildResult,\n type ContributionRebuildScope,\n type ContributionRepairResult,\n type ContributionRepopulationStats,\n type CreateVectorIndexParams,\n type DeleteEmbeddingParams,\n type DeleteFulltextBatchParams,\n type DeleteFulltextParams,\n type DropVectorIndexParams,\n type FulltextSearchParams,\n type FulltextSearchResult,\n type GraphAnalyticsCapabilities,\n type GraphBackend,\n type HybridSearchParams,\n type HybridSearchRow,\n type IdentityTableNames,\n type IndexMaterializationRow,\n INTERNAL_TEMPORARY_WRITES,\n type InternalTransactionOptions,\n type KindRemovalRow,\n type LockSchemaVersionForWriteParams,\n normalizeGraphAnalyticsCapabilities,\n type RecordContributionMaterializationParams,\n type RecordIndexMaterializationParams,\n type RecordKindRemovalParams,\n type SchemaKindEmptinessProbe,\n type SchemaVersionRow,\n type SchemaWriteTransactionBackend,\n type SetActiveVersionParams,\n SQLITE_CAPABILITIES,\n SQLITE_MAX_BIND_PARAMETERS,\n type TransactionBackend,\n type TrustedImportOptions,\n type TrustedImportSession,\n type UpsertEmbeddingBatchParams,\n type UpsertEmbeddingParams,\n type UpsertFulltextBatchParams,\n type UpsertFulltextParams,\n type VectorSearchParams,\n type VectorSearchResult,\n} from \"../types\";\nimport {\n type AnySqliteDatabase,\n createSqliteExecutionAdapter,\n getDurableObjectStorageClient,\n isBetterSqlite3Client,\n isBunSqliteClient,\n isSqlJsClient,\n type SqliteExecutionAdapter,\n type SqliteExecutionProfile,\n type SqliteExecutionProfileHints,\n} from \"./execution/sqlite-execution\";\nimport { type ExecutableSql, toDrizzleSql } from \"./execution/types\";\nimport {\n EMBEDDING_UPSERT_PARAM_COUNT,\n mapVectorWriteError,\n vectorSlotFromCreateIndexParams,\n vectorSlotFromDropIndexParams,\n vectorSlotFromParams,\n} from \"./vector-runtime\";\nexport type { SqliteTransactionMode } from \"./execution/sqlite-execution\";\nimport {\n coerceNumericScore,\n createEdgeRowMapper,\n createNodeRowMapper,\n createSchemaVersionRowMapper,\n createUniqueRowMapper,\n nowIso,\n SQLITE_ROW_MAPPER_CONFIG,\n} from \"../row-mappers\";\nimport {\n auditBackendResource,\n resolveDeclaredBackendResource,\n type SerializedResourceDeclaration,\n} from \"../transaction-resource\";\nimport {\n buildContributionInsertValues,\n buildContributionOnConflictSet,\n type ContributionMaterializer,\n contributionRebuildSupported,\n createContributionMaterializer,\n gateFulltext,\n gateFulltextMethods,\n mapContributionMaterializationRow,\n SQLITE_CONTRIBUTION_MAT_TIMESTAMPS,\n} from \"./contribution-materializations\";\nimport {\n generateSqliteCreateTableSQL,\n generateSqliteDDL,\n sqliteContributions,\n} from \"./ddl\";\nimport {\n buildMaterializationInsertValues,\n buildMaterializationOnConflictSet,\n mapMaterializationRow,\n SQLITE_INDEX_MAT_TIMESTAMPS,\n} from \"./index-materializations\";\nimport {\n buildKindRemovalInsertValues,\n buildKindRemovalOnConflictSet,\n mapKindRemovalRow,\n SQLITE_KIND_REMOVAL_TIMESTAMPS,\n} from \"./kind-removals\";\nimport {\n assertActiveSchemaVersion,\n assertAdoptedDialect,\n commitSchemaVersionIfKindsEmpty,\n createCommonOperationBackend,\n type InternalOperationBackend,\n} from \"./operation-backend-core\";\nimport { mapHybridSearchRow } from \"./operations/hybrid\";\nimport {\n createSqliteOperationStrategy,\n tableExistsFromRow,\n} from \"./operations/strategy\";\nimport {\n createSqliteTables as buildSqliteTables,\n type SqliteTables,\n tables as defaultTables,\n} from \"./schema/sqlite\";\nimport {\n analyzeImportedTables,\n assertTrustedImportDatabaseEmpty,\n createSqliteTrustedImportSession,\n restoreSecondaryIndexes,\n suspendSqliteSecondaryIndexes,\n} from \"./trusted-import\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Options for creating a SQLite backend.\n */\nexport type SqliteBackendOptions = Readonly<{\n /**\n * Custom table definitions. Use createSqliteTables() to customize table names.\n * Defaults to standard TypeGraph table names.\n */\n tables?: SqliteTables;\n /**\n * Optional execution profile hints used to avoid runtime driver reflection.\n * Set `transactionMode: \"none\"` for drivers without transactions (e.g.\n * Cloudflare D1). Durable Objects (`drizzle(ctx.storage)`) auto-detect\n * `transactionMode: \"do-sqlite\"` and do not need a hint. Hosted platform\n * identity is authoritative when it conflicts with a stale hint.\n */\n executionProfile?: SqliteExecutionProfileHints;\n /**\n * Fulltext strategy override. Defaults to `fts5Strategy` (SQLite's\n * built-in FTS5 virtual table). Most users should leave this alone.\n */\n fulltext?: FulltextStrategy;\n /**\n * Vector strategy override. When present, the backend owns per-`(kind,\n * field)` typed storage through this strategy (DDL, upsert, delete,\n * similarity search, ANN index lifecycle) and advertises\n * `strategy.capabilities` as `capabilities.vector`. `createLibsqlBackend`\n * passes `libsqlVectorStrategy` unconditionally; `createLocalSqliteBackend`\n * passes `sqliteVecStrategy` when the extension loads. When absent the\n * backend exposes no vector capability and embedding values pass through\n * writes without being indexed — matching existing behavior for SQLite\n * connections without a vector extension.\n */\n vector?: VectorStrategy;\n /**\n * Override specific backend capabilities. Useful for custom SQLite builds\n * or tests that need to simulate an engine-level capability gap. Overrides\n * may lower, but cannot raise, a hosted platform's hard parameter ceiling.\n */\n capabilities?: Partial<BackendCapabilities>;\n /**\n * Declare the connection this backend serializes every statement onto, when\n * TypeGraph's driver predicates cannot see it (`expo-sqlite`, `op-sqlite`,\n * `sqlite-proxy`, a bespoke adapter) — or declare that it serializes on\n * nothing, when detection is wrong for your topology.\n *\n * Defaults to `{ mode: \"detect\" }`. See\n * {@link SerializedResourceDeclaration} for what each mode means and for the\n * one refusal it cannot lift (`same-sqlite-backend`: one backend object\n * exporting into itself).\n */\n serializedResource?: SerializedResourceDeclaration;\n}>;\n\nconst NODE_INSERT_PARAM_COUNT = 9;\nconst EDGE_INSERT_PARAM_COUNT = 12;\nconst GET_NODES_FIXED_PARAM_COUNT = 2;\nconst GET_EDGES_FIXED_PARAM_COUNT = 1;\nconst CHECK_UNIQUE_BATCH_FIXED_PARAM_COUNT = 3;\nconst FULLTEXT_UPSERT_PARAM_COUNT = 6;\nconst FULLTEXT_DELETE_FIXED_PARAM_COUNT = 2;\nconst UNIQUE_DELETE_FIXED_PARAM_COUNT = 2;\nconst UNIQUE_INSERT_PARAM_COUNT = 6;\n\n/**\n * `PRAGMA analysis_limit` value `refreshStatistics()` sets before running\n * `ANALYZE`. Unlike Postgres (whose `ANALYZE` always examines a bounded\n * sample sized off `default_statistics_target`), SQLite's `ANALYZE`\n * defaults to a full table/index scan — O(table size) per call. A caller\n * streaming a bulk load through repeated `bulkInsert()` calls (the only\n * practical pattern for a multi-million-row load) re-triggers\n * `refreshStatistics()` on every batch once that batch's row count crosses\n * `AUTO_REFRESH_STATISTICS_ROW_THRESHOLD`; without this bound, per-call\n * cost grows with total table size, integrating to O(n²) total load time.\n * 1000 is SQLite's own documented suggestion for large databases.\n */\nexport const SQLITE_ANALYZE_ROW_LIMIT = 1000;\n\n/**\n * Barrel keys (contribution logical names) of the four relations that hold\n * Operational Identity state: current assertions, recorded-time assertions,\n * the derived closure, and the derived separation relation.\n * `ensureIdentityTables()` scopes its idempotent CREATE TABLE / CREATE INDEX\n * to exactly these when identity is first enabled on an existing database.\n */\nconst IDENTITY_TABLE_LOGICAL_NAMES: ReadonlySet<string> = new Set([\n \"identityAssertions\",\n \"recordedIdentityAssertions\",\n \"identityClosure\",\n \"identitySeparation\",\n]);\n\n/**\n * Batch chunk sizes for the SQLite operation backend, derived from the\n * connection's bound-parameter budget. Keys mirror the operation backend's\n * `batchConfig`.\n */\nexport type SqliteBatchChunkSizes = Readonly<{\n checkUniqueBatchChunkSize: number;\n edgeInsertBatchSize: number;\n /** Rows per embedding batch upsert (5 binds per row). */\n embeddingUpsertBatchSize: number;\n /** Rows per fulltext batch upsert (6 binds per row on FTS5). */\n fulltextUpsertBatchSize: number;\n /** Node ids per fulltext batch delete (2 fixed binds + one per id). */\n fulltextDeleteChunkSize: number;\n /** Endpoint ids per `findEdgesByKind` `fromIds` / `toIds` statement. */\n findEdgesEndpointChunkSize: number;\n getEdgesChunkSize: number;\n getNodesChunkSize: number;\n nodeInsertBatchSize: number;\n /** Node ids per uniqueness-sidecar hard delete. */\n uniqueDeleteChunkSize: number;\n uniqueInsertBatchSize: number;\n}>;\n\n/**\n * Derives batch chunk sizes from a per-statement bound-parameter budget.\n * The budget varies by driver — better-sqlite3 compiles in 32,766, D1 caps\n * at ~100, undetectable async drivers keep the 999 floor — so chunk math is\n * computed per backend instance rather than fixed at module scope.\n */\nexport function computeSqliteBatchChunkSizes(\n maxBindParameters: number,\n): SqliteBatchChunkSizes {\n return {\n checkUniqueBatchChunkSize: Math.max(\n 1,\n maxBindParameters - CHECK_UNIQUE_BATCH_FIXED_PARAM_COUNT,\n ),\n embeddingUpsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / EMBEDDING_UPSERT_PARAM_COUNT),\n ),\n fulltextUpsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / FULLTEXT_UPSERT_PARAM_COUNT),\n ),\n fulltextDeleteChunkSize: Math.max(\n 1,\n maxBindParameters - FULLTEXT_DELETE_FIXED_PARAM_COUNT,\n ),\n edgeInsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / EDGE_INSERT_PARAM_COUNT),\n ),\n findEdgesEndpointChunkSize: Math.max(\n 1,\n maxBindParameters - FIND_EDGES_ENDPOINT_FIXED_PARAM_COUNT,\n ),\n getEdgesChunkSize: Math.max(\n 1,\n maxBindParameters - GET_EDGES_FIXED_PARAM_COUNT,\n ),\n getNodesChunkSize: Math.max(\n 1,\n maxBindParameters - GET_NODES_FIXED_PARAM_COUNT,\n ),\n nodeInsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / NODE_INSERT_PARAM_COUNT),\n ),\n uniqueDeleteChunkSize: Math.max(\n 1,\n maxBindParameters - UNIQUE_DELETE_FIXED_PARAM_COUNT,\n ),\n uniqueInsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / UNIQUE_INSERT_PARAM_COUNT),\n ),\n };\n}\n\ntype SerializedExecutionQueue = Readonly<{\n dispose: () => void;\n runExclusive: <T>(task: () => Promise<T>) => Promise<T>;\n}>;\n\n// ============================================================\n// Utilities\n// ============================================================\n\nconst toNodeRow = createNodeRowMapper(SQLITE_ROW_MAPPER_CONFIG);\nconst toEdgeRow = createEdgeRowMapper(SQLITE_ROW_MAPPER_CONFIG);\nconst toUniqueRow = createUniqueRowMapper(SQLITE_ROW_MAPPER_CONFIG);\nconst toSchemaVersionRow = createSchemaVersionRowMapper(\n SQLITE_ROW_MAPPER_CONFIG,\n);\n\n/** A shared promise that never settles — used to absorb post-dispose work. */\nconst PENDING_FOREVER: Promise<never> = new Promise<never>(noop);\n\nfunction pendingForever<T>(): Promise<T> {\n return PENDING_FOREVER;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nfunction noop(): void {}\n\n/**\n * Tracks which serialized queue (if any) the current async execution is\n * running a task for, so a re-entrant submission — a root-backend operation\n * awaited from inside a transaction already occupying the same queue — can be\n * rejected with a typed error instead of deadlocking (the enclosing task holds\n * the queue slot until it completes, so the inner operation can never run).\n *\n * AsyncLocalStorage is loaded lazily and optionally: it is available on Node\n * and on Cloudflare workers with the `nodejs_als` compatibility flag, and a\n * runtime without it simply skips the detection (the queue behaves as before).\n */\ntype QueueTaskContext = Readonly<{\n getStore: () => unknown;\n run: <T>(store: object, callback: () => T) => T;\n}>;\n\nlet queueTaskContext: QueueTaskContext | undefined;\n\nasync function loadQueueTaskContext(): Promise<void> {\n try {\n const asyncHooks = await import(\"node:async_hooks\");\n queueTaskContext = new asyncHooks.AsyncLocalStorage<object>();\n } catch {\n // AsyncLocalStorage unavailable on this runtime: re-entrant submissions\n // stay undetected, matching the queue's previous behavior.\n }\n}\n\n// eslint-disable-next-line unicorn/prefer-top-level-await -- the dual CJS/ESM build cannot use top-level await\nvoid loadQueueTaskContext();\n\nfunction rejectReentrantQueueSubmission(): Promise<never> {\n return Promise.reject(\n new ConfigurationError(\n \"This operation was awaited from inside a transaction running on the \" +\n \"same SQLite backend and would deadlock: the transaction holds the \" +\n \"backend's serialized execution slot until it completes, so the \" +\n \"operation could never run.\",\n { backend: \"sqlite\", capability: \"concurrentRootAccess\" },\n {\n suggestion:\n \"Inside a store.transaction callback, use the transaction-scoped \" +\n \"context (tx.nodes / tx.edges / tx.backend) instead of the root \" +\n \"store or backend, or move the operation outside the transaction.\",\n },\n ),\n );\n}\n\nfunction createSerializedExecutionQueue(): SerializedExecutionQueue {\n let tail: Promise<unknown> = Promise.resolve();\n let disposed = false;\n // Unique per queue: a task running on THIS queue must not submit back to it,\n // but may freely submit to a different backend's queue.\n const taskMarker: object = {};\n\n function isDisposed(): boolean {\n return disposed;\n }\n\n return {\n dispose() {\n disposed = true;\n },\n\n runExclusive<T>(task: () => Promise<T>): Promise<T> {\n if (isDisposed()) return Promise.reject(new BackendDisposedError());\n if (queueTaskContext?.getStore() === taskMarker) {\n return rejectReentrantQueueSubmission();\n }\n\n // When disposed, runTask returns a never-settling promise so that no\n // rejection propagates through the 7+ async wrappers between this\n // queue and the store-level caller. A rejection here would become an\n // unhandled rejection if the caller abandoned the promise during\n // teardown — and JavaScript offers no way to `.catch()` a rejection\n // at the bottom of a chain without every async wrapper above it also\n // creating an independently-unhandled rejected promise.\n //\n // The tradeoff: an active caller whose operation was queued before\n // dispose() will see a permanently-pending promise rather than a\n // BackendDisposedError. Post-dispose submissions (the check above)\n // still reject immediately since the caller actively holds that\n // promise.\n const runTask = async (): Promise<T> => {\n if (isDisposed()) return pendingForever<T>();\n try {\n const context = queueTaskContext;\n return context === undefined ?\n await task()\n : await context.run(taskMarker, () => task());\n } catch (error) {\n if (isDisposed()) return pendingForever<T>();\n throw error;\n }\n };\n const result = tail.then(runTask, runTask);\n tail = result.then(\n () => 0,\n () => 0,\n );\n return result;\n },\n };\n}\n\nfunction runWithSerializedQueue<T>(\n queue: SerializedExecutionQueue | undefined,\n task: () => Promise<T>,\n): Promise<T> {\n if (queue === undefined) return task();\n return queue.runExclusive(task);\n}\n\n/** Every SQLite \"atomic transactions unavailable\" refusal shares this shape. */\nfunction throwSqliteTransactionsDisabled(message: string): never {\n throw new ConfigurationError(message, {\n backend: \"sqlite\",\n capability: \"transactions\",\n supportsTransactions: false,\n });\n}\n\nfunction buildSqliteCapabilities(\n options: Readonly<{\n fulltextStrategy: FulltextStrategy;\n vectorStrategy: VectorStrategy | undefined;\n transactionMode: SqliteExecutionAdapter[\"profile\"][\"transactionMode\"];\n maxBindParameters: number;\n }>,\n): BackendCapabilities {\n const base =\n options.transactionMode === \"none\" ?\n {\n ...SQLITE_CAPABILITIES,\n transactions: false,\n graphAnalytics: {\n ...(SQLITE_CAPABILITIES.graphAnalytics ?? {\n mathFunctions: false,\n }),\n supported: false,\n },\n }\n : SQLITE_CAPABILITIES;\n return {\n ...base,\n maxBindParameters: options.maxBindParameters,\n fulltext: buildFulltextCapabilities(options.fulltextStrategy),\n ...(options.vectorStrategy === undefined ?\n {}\n : { vector: buildVectorCapabilities(options.vectorStrategy) }),\n };\n}\n\nfunction resolveMaxBindParametersCapability(\n profile: SqliteExecutionProfile,\n override: number | undefined,\n): number {\n const requested = override ?? profile.maxBindParameters;\n return profile.hardMaxBindParameters === undefined ?\n requested\n : Math.min(requested, profile.hardMaxBindParameters);\n}\n\nfunction resolveSqliteGraphAnalyticsCapabilities(\n profile: SqliteExecutionProfile,\n override: GraphAnalyticsCapabilities | undefined,\n): GraphAnalyticsCapabilities {\n const requested = override ??\n SQLITE_CAPABILITIES.graphAnalytics ?? {\n supported: false,\n mathFunctions: false,\n };\n if (\n profile.transactionMode !== \"do-sqlite\" &&\n profile.transactionMode !== \"none\"\n ) {\n return requested;\n }\n return { ...requested, supported: false };\n}\n\n// ============================================================\n// Backend Factory\n// ============================================================\n\n/**\n * Creates a TypeGraph backend for SQLite databases.\n *\n * Works with any Drizzle SQLite instance regardless of the underlying driver.\n *\n * @param db - A Drizzle SQLite database instance\n * @param options - Backend configuration\n * @returns A GraphBackend implementation\n */\ntype CreateSqliteOperationBackendOptions = Readonly<{\n capabilities: GraphBackend[\"capabilities\"];\n db: AnySqliteDatabase;\n executionAdapter: SqliteExecutionAdapter;\n operationStrategy: ReturnType<typeof createSqliteOperationStrategy>;\n serializedQueue?: SerializedExecutionQueue;\n tableNames: ResolvedSqlTableNames;\n fulltextStrategy: FulltextStrategy;\n /**\n * Active vector strategy, or `undefined` when the connection has no\n * vector extension. When present, the backend exposes upsertEmbedding /\n * deleteEmbedding / vectorSearch / createVectorIndex / dropVectorIndex,\n * all routed through this strategy's per-`(kind, field)` storage.\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 /** Whether this operation backend is bound to an explicit transaction. */\n transactionScoped: boolean;\n}>;\n\ntype CreateSqliteTransactionBackendOptions = Readonly<{\n capabilities: GraphBackend[\"capabilities\"];\n db: AnySqliteDatabase;\n executionAdapter?: SqliteExecutionAdapter;\n operationStrategy: ReturnType<typeof createSqliteOperationStrategy>;\n profileHints: SqliteExecutionProfileHints;\n tableNames: ResolvedSqlTableNames;\n fulltextStrategy: FulltextStrategy;\n /** Active vector strategy. See {@link CreateSqliteOperationBackendOptions}. */\n vectorStrategy?: VectorStrategy | undefined;\n /** Shared durable-marker materializer. See {@link CreateSqliteOperationBackendOptions}. */\n contributionMaterializer: ContributionMaterializer;\n}>;\n\nfunction createSqliteOperationBackend(\n options: CreateSqliteOperationBackendOptions,\n): InternalOperationBackend {\n const {\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n serializedQueue,\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n transactionScoped,\n } = options;\n\n // CRUD statements route through the execution adapter's compiled path on\n // synchronous drivers so a repeated operation shape re-binds parameters\n // against a cached prepared statement instead of re-preparing through\n // drizzle's session on every call. Async drivers (remote libsql, D1)\n // have no statement cache and keep the drizzle fallback.\n const compiledExecute = executionAdapter.executeCompiled;\n const compiledRun = executionAdapter.executeCompiledRun;\n\n function execGet<T>(query: ExecutableSql): Promise<T | undefined> {\n // Fallback uses db.all()[0], not db.get(): drizzle-team/drizzle-orm#1049\n // — db.get() crashes with the libsql driver when no rows match\n // (normalizeRow receives undefined).\n //\n // The fallback branches use `await` unconditionally rather than\n // `instanceof Promise` because Drizzle returns SQLiteRaw thenables\n // that are NOT Promise instances (drizzle-team/drizzle-orm#2275).\n return runWithSerializedQueue(serializedQueue, async () => {\n if (compiledExecute === undefined) {\n const rows = await executionAdapter.execute<T>(query);\n return rows[0];\n }\n const rows = await compiledExecute<T>(executionAdapter.compile(query));\n return rows[0];\n });\n }\n\n function execAll<T>(query: ExecutableSql): Promise<T[]> {\n return runWithSerializedQueue(serializedQueue, async () => {\n if (compiledExecute === undefined) {\n return [...(await executionAdapter.execute<T>(query))];\n }\n return [...(await compiledExecute<T>(executionAdapter.compile(query)))];\n });\n }\n\n function execRun(query: ExecutableSql): Promise<void> {\n return runWithSerializedQueue(serializedQueue, async () => {\n if (compiledRun === undefined) {\n await db.run(\n isSqlFragment(query) ? toDrizzleSql(query, \"sqlite\") : query,\n );\n return;\n }\n await compiledRun(executionAdapter.compile(query));\n });\n }\n\n const batchConfig = computeSqliteBatchChunkSizes(\n capabilities.maxBindParameters ?? SQLITE_MAX_BIND_PARAMETERS,\n );\n const commonOperationMembers = createCommonOperationBackend({\n batchConfig,\n execution: {\n execAll,\n execGet,\n execRun,\n },\n nowIso,\n maxBindParameters:\n capabilities.maxBindParameters ?? SQLITE_MAX_BIND_PARAMETERS,\n operationStrategy,\n rowMappers: {\n toEdgeRow,\n toNodeRow,\n toSchemaVersionRow,\n toUniqueRow,\n },\n });\n\n const executeCompiled = executionAdapter.executeCompiled;\n const executeRawMethod: Pick<TransactionBackend, \"executeRaw\"> =\n executeCompiled === undefined ?\n {}\n : {\n executeRaw<T>(\n sqlText: string,\n params: readonly unknown[],\n ): Promise<readonly T[]> {\n return runWithSerializedQueue(serializedQueue, async () =>\n executeCompiled<T>({ params, sql: sqlText }),\n );\n },\n };\n\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`).\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 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 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 is a clean no-op against\n // an existing (possibly empty) table, matching the Postgres path\n // (where a DELETE on a missing relation would abort an enclosing\n // transaction). SELECT-only assert, never DDL.\n const slot = vectorSlotFromParams(params);\n await contributionMaterializer.assertVectorSlot(slot);\n const statements = vectorStrategy.buildDelete(slot, params);\n for (const statement of statements) {\n await execRun(statement);\n }\n },\n async deleteEmbeddingBatch(\n params: Omit<DeleteEmbeddingParams, \"nodeId\"> &\n Readonly<{ nodeIds: readonly string[] }>,\n ): Promise<void> {\n if (params.nodeIds.length === 0) return;\n const slot = vectorSlotFromParams(params);\n await contributionMaterializer.assertVectorSlot(slot);\n for (const nodeIds of chunkArray(\n [...new Set(params.nodeIds)],\n batchConfig.embeddingUpsertBatchSize,\n )) {\n const statements = vectorStrategy.buildDeleteBatch(slot, {\n ...params,\n nodeIds,\n });\n for (const statement of statements) await execRun(statement);\n }\n },\n async vectorSearch(\n params: VectorSearchParams,\n ): Promise<readonly VectorSearchResult[]> {\n assertVectorSearchLimit(params.limit);\n // Apply-or-refuse for the per-search ANN frontier. No SQLite engine\n // TypeGraph bundles has one (sqlite-vec's vec0 takes only `k`;\n // libSQL's `vector_top_k` takes only (index, query, k)), so the\n // shared predicate refuses `efSearch` here with the engine's own\n // reason instead of accepting it and searching as if it were never\n // passed. `undefined` — the overwhelmingly common case — returns\n // without touching anything.\n resolveEfSearchOverride({\n efSearch: params.efSearch,\n indexType: params.indexType,\n tuning: vectorSearchFrontierTuning(vectorStrategy),\n transactions: capabilities.transactions,\n dialect: \"SQLite\",\n engine: vectorStrategy.name,\n });\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). An unprovisioned slot surfaces the engine's\n // missing-relation error — the same contract as a query-builder\n // `similarTo()` predicate; `createVerifiedStore` catches both at\n // attach.\n const slot = vectorSlotFromParams(params);\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 let rows: readonly { node_id: string; score: number }[];\n try {\n rows = await execAll<{ node_id: string; score: number }>(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 profile\n // that disables window functions keeps the store's multi-statement\n // 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\n // fallback path applies (vectorSearch validates its limit;\n // the fulltext depth is validated inside\n // buildFulltextSearch).\n assertVectorSearchLimit(params.vector.k);\n // The hybrid statement's vector leg carries the same option on\n // the same engine, so it takes the same refusal. This path built\n // its own `VectorSearchParams` and dropped\n // `params.vector.efSearch` while doing so — the silent ignore in\n // its second location.\n resolveEfSearchOverride({\n efSearch: params.vector.efSearch,\n indexType: params.vector.indexType,\n tuning: vectorSearchFrontierTuning(vectorStrategy),\n transactions: capabilities.transactions,\n dialect: \"SQLite\",\n engine: vectorStrategy.name,\n });\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, \"sqlite\"),\n params.vector.metric === \"cosine\",\n );\n let raw: readonly Record<string, unknown>[];\n try {\n raw = await execAll<Record<string, unknown>>(statement);\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 ...commonOperationMembers,\n ...executeRawMethod,\n ...vectorEmbeddingMethods,\n /**\n * Transaction-scoped contribution marker stamp. Present so the\n * destructive rebuild can commit its marker with the DDL that\n * produced it; without it the stamp would land outside the\n * transaction and could survive a rolled-back drop.\n *\n * States the row outright rather than reusing the top-level upsert,\n * whose `materialized_at` COALESCE preserves an earlier success so a\n * failed re-attempt cannot erase it. A completed rebuild replaced the\n * storage, so the recorded timestamp must be the rebuild's.\n */\n async recordContributionMaterialization(\n params: RecordContributionMaterializationParams,\n ): Promise<void> {\n await execRun(\n operationStrategy.buildInsertContributionMaterialization(params),\n );\n },\n\n async deleteSchemaVectorSlotContribution(slot: VectorSlot): Promise<void> {\n if (vectorStrategy === undefined) return;\n for (const contribution of vectorStrategy.ownedTables(slot)) {\n await execRun(\n operationStrategy.buildDeleteContributionMaterialization({\n graphId: slot.graphId,\n logicalName: contribution.logicalName,\n owner: contribution.owner,\n tableName: contribution.tableName,\n }),\n );\n }\n contributionMaterializer.evictVectorSlot(slot);\n },\n capabilities,\n dialect: \"sqlite\",\n tableNames,\n fulltextStrategy,\n ...(vectorStrategy === undefined ? {} : { vectorStrategy }),\n\n async lockSchemaVersionForWrite(\n params: LockSchemaVersionForWriteParams,\n ): Promise<void> {\n if (!transactionScoped) {\n throw new ConfigurationError(\n \"The schema write fence requires an explicit SQLite transaction.\",\n {\n code: \"SCHEMA_WRITE_FENCE_TRANSACTION_REQUIRED\",\n graphId: params.graphId,\n },\n );\n }\n // An ordinary read suffices, unlike Postgres' `FOR SHARE` fence: SQLite\n // serializes writers through BEGIN IMMEDIATE, so no schema commit can be\n // mid-flight while this transaction holds the writer slot, and a SQLite\n // read has no post-wait row recheck that could drop the active row from\n // its own snapshot. An absent row here therefore always means the graph\n // genuinely has no active schema.\n const active = await commonOperationMembers.getActiveSchema(\n params.graphId,\n );\n assertActiveSchemaVersion(\n params.graphId,\n params.expectedVersion,\n active?.version ?? 0,\n );\n },\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. `ownedTables` already folds\n // the index DDL in, so the explicit `buildCreateIndex` step is\n // belt-and-suspenders for slots whose index intent changed after the\n // table was first materialized.\n await contributionMaterializer.ensureVectorSlot(slot);\n const indexStatement = vectorStrategy.buildCreateIndex?.(slot);\n if (indexStatement !== undefined) {\n await execRun(indexStatement);\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; DROP INDEX IF EXISTS against a missing table errors\n // on some drivers, so treat that as already-dropped.\n if (!isMissingTableError(error)) throw error;\n }\n },\n\n // === Fulltext Operations ===\n\n async upsertFulltext(params: UpsertFulltextParams): Promise<void> {\n const timestamp = nowIso();\n const statements = operationStrategy.buildUpsertFulltext(\n params,\n timestamp,\n );\n for (const stmt of statements) {\n await execRun(stmt);\n }\n },\n\n async deleteFulltext(params: DeleteFulltextParams): Promise<void> {\n const statements = operationStrategy.buildDeleteFulltext(params);\n for (const stmt of statements) {\n await execRun(stmt);\n }\n },\n\n async upsertFulltextBatch(\n params: UpsertFulltextBatchParams,\n ): Promise<void> {\n if (params.rows.length === 0) return;\n const timestamp = nowIso();\n // The strategy emits ONE statement over every row it is given, so\n // the bind budget is enforced here — same contract as node/edge\n // batch inserts.\n for (const rows of chunkArray(\n params.rows,\n batchConfig.fulltextUpsertBatchSize,\n )) {\n const statements = operationStrategy.buildUpsertFulltextBatch(\n { ...params, rows },\n timestamp,\n );\n for (const stmt of statements) {\n await execRun(stmt);\n }\n }\n },\n\n async deleteFulltextBatch(\n params: DeleteFulltextBatchParams,\n ): Promise<void> {\n if (params.nodeIds.length === 0) return;\n for (const nodeIds of chunkArray(\n params.nodeIds,\n batchConfig.fulltextDeleteChunkSize,\n )) {\n const statements = operationStrategy.buildDeleteFulltextBatch({\n ...params,\n nodeIds,\n });\n for (const stmt of statements) {\n await execRun(stmt);\n }\n }\n },\n\n async fulltextSearch(\n params: FulltextSearchParams,\n ): Promise<readonly FulltextSearchResult[]> {\n const query = operationStrategy.buildFulltextSearch(params);\n 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 // === Query Execution ===\n\n async execute<T>(query: CompiledRowsSql): Promise<readonly T[]> {\n return runWithSerializedQueue(serializedQueue, async () =>\n executionAdapter.execute<T>(query),\n );\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 * Whether a driver client is a LOCAL `@libsql/client`: one stable connection\n * that every statement from every wrapper over it runs on, in order.\n *\n * `protocol === \"file\"` is the client's own answer to \"am I local?\" — it covers\n * `file:` paths, `:memory:` databases, and an embedded replica's local file. An\n * embedded replica (`protocol: \"file\"` PLUS a `syncUrl`) is deliberately marked\n * on the same evidence as any other local client: `syncUrl` names where the\n * replica pulls FROM, while every statement this client executes still routes\n * through the one local handle, so an open export snapshot on one wrapper still\n * holds the connection another wrapper's import needs. A REMOTE client\n * (`http` / `ws`) opens an independent stream per transaction and\n * must never be treated as one serialized resource; refusing concurrent work\n * there would refuse work that succeeds. The libsql methods are required\n * alongside the protocol so an unrelated object that happens to carry\n * `protocol: \"file\"` is not adopted, and none of it imports `@libsql/client`,\n * which this bundler-friendly module must not depend on.\n *\n * Single owner of the local/remote distinction: `../sqlite/libsql.ts` picks its\n * transaction framing (raw BEGIN/COMMIT on the one local connection vs Drizzle's\n * per-stream `db.transaction()`) by asking here, so the framing and the\n * serialized-resource mark cannot drift apart.\n */\nexport function isLocalLibsqlClient(client: unknown): boolean {\n if (typeof client !== \"object\" || client === null) return false;\n const candidate = client as Readonly<Record<string, unknown>>;\n return (\n candidate[\"protocol\"] === \"file\" &&\n typeof candidate[\"execute\"] === \"function\" &&\n typeof candidate[\"batch\"] === \"function\" &&\n typeof candidate[\"executeMultiple\"] === \"function\"\n );\n}\n\n/**\n * Returns the single connection a Drizzle database serializes every statement\n * onto, if its driver is one we can positively identify as such.\n *\n * Five drivers qualify, each by its own named predicate — a driver is marked on\n * evidence of WHAT IT IS, never on the absence of a disqualifier:\n *\n * - **better-sqlite3** ({@link isBetterSqlite3Client}): a single, synchronous\n * connection, so an open transaction on one wrapper is an open transaction\n * for all of them.\n * - **bun:sqlite** ({@link isBunSqliteClient}): the same one synchronous\n * connection, reached through `drizzle-orm/bun-sqlite`.\n * - **sql.js** ({@link isSqlJsClient}): one in-WASM database handle; every\n * wrapper's statements run on it in order.\n * - **Cloudflare Durable Object storage** (`drizzle(ctx.storage)`): one storage\n * connection whose transaction frame is AMBIENT on the storage object rather\n * than a handle passed to the callback (see `runDoSqliteStorageTransaction`:\n * `transactionMode: \"do-sqlite\"` binds the OUTER `db`). A second wrapper's\n * writes therefore land inside the first\n * wrapper's open export snapshot, and because the DO backend reports\n * `capabilities.transactions: true` nothing else abstains for it. Identified by\n * {@link getDurableObjectStorageClient}, the same full-shape evidence the\n * transaction runner requires, so the framing and the mark cannot drift apart.\n * - **a local `@libsql/client`**: also one stable connection — which is exactly\n * why local clients frame transactions as raw BEGIN/COMMIT on it (see\n * {@link isLocalLibsqlClient}). libsql clients expose no `prepare`, so no\n * prepare-capable predicate can see them and the driver client is read\n * directly here.\n *\n * Unrecognized clients stay unmarked: SEPARATE connections to the same file are\n * genuinely concurrent under WAL and must not be treated as one serialized\n * resource, and a driver whose dispatch we cannot attribute proves nothing.\n * The full classification — marked, deliberately unmarked, and the remaining\n * gaps — is the inventory in `../transaction-resource.ts`.\n */\nfunction getSerializedSqliteConnection(\n db: AnySqliteDatabase,\n): object | undefined {\n const client = (db as Readonly<{ $client?: unknown }>).$client;\n if (\n isBetterSqlite3Client(client) ||\n isBunSqliteClient(client) ||\n isSqlJsClient(client)\n ) {\n return client as object;\n }\n // The storage object IS the serialized resource: every wrapper built over the\n // same `ctx.storage` shares its one connection and its ambient transaction.\n const storageClient = getDurableObjectStorageClient(db);\n if (storageClient !== undefined) return storageClient;\n return isLocalLibsqlClient(client) ? (client as object) : undefined;\n}\n\n/**\n * Whether two backends built over `client` would be treated as one serialized\n * connection. The marking predicate itself, exposed for the driver-shape unit\n * tests (mirrors `isSerializedPostgresClient`); production code reaches it only\n * through {@link createSqliteBackend}.\n */\nexport function isSerializedSqliteClient(client: unknown): boolean {\n return (\n getSerializedSqliteConnection({\n $client: client,\n } as unknown as AnySqliteDatabase) !== undefined\n );\n}\n\nexport function createSqliteBackend(\n db: AnySqliteDatabase,\n options: SqliteBackendOptions = {},\n): AdapterBackend<AnySqliteDatabase> {\n // Resolved before the backend exists so marking below is a lookup, never\n // work that could fail after wrappers already observed an unmarked backend.\n // A `serializedResource` declaration that contradicts detection is refused\n // here too, before any object a caller could hold has been built.\n const resourceAudit = resolveDeclaredBackendResource(\n getSerializedSqliteConnection(db),\n options.serializedResource,\n );\n const tables = options.tables ?? defaultTables;\n const fulltextStrategy = options.fulltext ?? fts5Strategy;\n const profileHints = options.executionProfile ?? {};\n const executionAdapter = createSqliteExecutionAdapter(db, { profileHints });\n const { isSync, transactionMode } = executionAdapter.profile;\n // The active vector strategy gates upsertEmbedding / deleteEmbedding /\n // vectorSearch and supplies the per-`(kind, field)` storage. Passed by\n // the caller that knows the connection's vector capability\n // (`createLibsqlBackend` always; `createLocalSqliteBackend` when the\n // extension loads); absent for plain SQLite drivers with no extension.\n const vectorStrategy = options.vector;\n const capabilityOverrides = options.capabilities ?? {};\n const declaredCapabilities = normalizeGraphAnalyticsCapabilities({\n ...buildSqliteCapabilities({\n fulltextStrategy,\n vectorStrategy,\n transactionMode,\n maxBindParameters: executionAdapter.profile.maxBindParameters,\n }),\n ...capabilityOverrides,\n maxBindParameters: resolveMaxBindParametersCapability(\n executionAdapter.profile,\n capabilityOverrides.maxBindParameters,\n ),\n graphAnalytics: resolveSqliteGraphAnalyticsCapabilities(\n executionAdapter.profile,\n capabilityOverrides.graphAnalytics,\n ),\n });\n // Derived last and not overridable: how far up the contribution health\n // ladder this backend goes is a structural fact about the wiring below\n // (durable markers, a catalog probe, a strategy that declares teardown\n // DDL, a transactional schema fence), and a caller who declared a\n // rebuild this backend cannot perform would be advertising a lie.\n const capabilities: BackendCapabilities = {\n ...declaredCapabilities,\n contributions: {\n supported: true,\n probe: true,\n rebuild: contributionRebuildSupported(\n fulltextStrategy,\n tables.fulltextTableName,\n declaredCapabilities.transactions,\n ),\n },\n };\n\n const tableNames: ResolvedSqlTableNames = {\n nodes: getTableName(tables.nodes),\n edges: getTableName(tables.edges),\n recordedNodes: getTableName(tables.recordedNodes),\n recordedEdges: getTableName(tables.recordedEdges),\n recordedClock: getTableName(tables.recordedClock),\n revisionOrigins: getTableName(tables.revisionOrigins),\n identityAssertions: getTableName(tables.identityAssertions),\n recordedIdentityAssertions: getTableName(tables.recordedIdentityAssertions),\n identityClosure: getTableName(tables.identityClosure),\n identitySeparation: getTableName(tables.identitySeparation),\n fulltext: tables.fulltextTableName,\n uniques: getTableName(tables.uniques),\n edgeClaims: getTableName(tables.edgeClaims),\n };\n // refreshStatistics() scopes ANALYZE to these — matching the Postgres\n // backend, which never touches unrelated tables sharing the database.\n // The recorded and identity relations are ANALYZEd separately under a\n // missing-table guard: a schema created before recorded-time history or\n // Operational Identity landed (bring-your-own-connection, no DDL re-run)\n // has no recorded_* / identity_* tables.\n const coreAnalyzeTables = [\n tableNames.nodes,\n tableNames.edges,\n tableNames.uniques,\n tableNames.fulltext,\n ];\n const guardedAnalyzeTables = [\n tableNames.recordedNodes,\n tableNames.recordedEdges,\n tableNames.recordedClock,\n tableNames.recordedIdentityAssertions,\n tableNames.identityAssertions,\n tableNames.identityClosure,\n tableNames.identitySeparation,\n ] as const;\n const operationStrategy = createSqliteOperationStrategy(\n tables,\n fulltextStrategy,\n );\n // Serialize top-level operations per backend on every transaction-capable\n // mode (\"sql\", \"drizzle\", \"do-sqlite\"). SQLite is single-writer, and two\n // concurrent `transaction()` calls on one connection open overlapping BEGINs\n // and collide with SQLITE_BUSY; the queue makes each top-level operation —\n // including a whole transaction — run to completion before the next starts.\n // A transaction's inner reads/writes run on the tx-scoped backend, which\n // does not carry the queue (see CreateSqliteTransactionBackendOptions);\n // awaiting a ROOT-backend operation from inside the transaction callback\n // would deadlock, so the queue rejects such re-entrant submissions with a\n // typed error (see rejectReentrantQueueSubmission). `none` drivers (D1 /\n // neon-http) have no transactions and manage their own concurrency, so they\n // stay unqueued.\n const serializedQueue =\n transactionMode === \"none\" ? undefined : createSerializedExecutionQueue();\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.run(sql.raw(generateSqliteCreateTableSQL(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 SQLITE_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 SQLITE_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 SQLITE_CONTRIBUTION_MAT_TIMESTAMPS.encode,\n ),\n )\n .onConflictDoUpdate({\n target: [\n matTable.graphId,\n matTable.logicalName,\n matTable.owner,\n matTable.tableName,\n ],\n set: buildContributionOnConflictSet(\n matTable.materializedAt,\n params.materializedAt,\n ),\n });\n }\n\n async function deleteContributionMaterializationRow(\n identity: ContributionMaterializationIdentity,\n ): Promise<void> {\n await db\n .delete(matTable)\n .where(\n and(\n eq(matTable.graphId, identity.graphId),\n eq(matTable.logicalName, identity.logicalName),\n eq(matTable.owner, identity.owner),\n eq(matTable.tableName, identity.tableName),\n ),\n );\n }\n\n /**\n * Uncached catalog probe backing `verifyContributions`. The shared\n * `createCachedTableExistence` wrapper is deliberately NOT used: this\n * diagnostic's whole job is to notice that a table confirmed present\n * earlier has since been dropped.\n */\n async function contributionTableExists(tableName: string): Promise<boolean> {\n const rows = await executionAdapter.execute<Record<string, unknown>>(\n operationStrategy.buildTableExists(tableName),\n );\n return tableExistsFromRow(rows[0]);\n }\n\n /**\n * The contribution descriptors for exactly the identity relations, under\n * caller-supplied physical names. Pure — nothing is executed here — and the\n * single owner of \"which DDL belongs to the identity relations\", shared by\n * `ensureIdentityTables` (which runs it) and `identityTableDdl` (which hands\n * it to a transaction).\n */\n function identityContributionsFor(\n identityTableNames: IdentityTableNames,\n ): ReturnType<typeof sqliteContributions> {\n const identityTables = buildSqliteTables({\n identityAssertions: identityTableNames.identityAssertions,\n recordedIdentityAssertions: identityTableNames.recordedIdentityAssertions,\n identityClosure: identityTableNames.identityClosure,\n identitySeparation: identityTableNames.identitySeparation,\n });\n return sqliteContributions(identityTables, fulltextStrategy).filter(\n (contribution) =>\n IDENTITY_TABLE_LOGICAL_NAMES.has(contribution.logicalName),\n );\n }\n\n const contributionMaterializer = createContributionMaterializer({\n dialect: \"sqlite\",\n fulltextStrategy,\n fulltextTableName: tables.fulltextTableName,\n vectorStrategy,\n execDdl: async (statement) => {\n await db.run(sql.raw(statement));\n },\n ensureMarkerTable: ensureContributionMaterializationsTableImpl,\n getMarkers: getContributionMaterializationRows,\n recordMarker: recordContributionMaterializationRow,\n deleteMarker: deleteContributionMaterializationRow,\n tableExists: contributionTableExists,\n // Withheld rather than wired-and-throwing when transactions are\n // disabled: the rebuild must refuse with its own typed error naming\n // the absent fence, matching `capabilities.contributions.rebuild`.\n // The graph id the materializer passes is unused — this backend's\n // schema lock is per connection, not per graph.\n ...(capabilities.transactions ?\n {\n schemaWriteTransaction: <T>(\n _graphId: string,\n fn: (tx: SchemaWriteTransactionBackend) => Promise<T>,\n ) => runSchemaWriteTransaction((target) => fn(target)),\n }\n : {}),\n });\n\n const operations = createSqliteOperationBackend({\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n transactionScoped: false,\n ...(serializedQueue === undefined ? {} : { serializedQueue }),\n });\n\n /**\n * #140: the `transactionMode: \"do-sqlite\"` primitive. Cloudflare\n * Durable Objects expose an async storage transaction runner —\n * `ctx.storage.transaction(async () => ...)`, surfaced by Drizzle as\n * `db.$client.transaction` — that rolls back SQL writes across\n * `await`. There is no Drizzle tx handle on DO: the storage\n * transaction is ambient on the object, so callers bind the *outer*\n * `db` (as the \"sql\" path binds the outer connection). Drizzle's own\n * `db.transaction()` here is `ctx.storage.transactionSync` and cannot\n * span an await, so it is deliberately not used. Shared by\n * `transaction()` (business writes) and `runSchemaWriteTransaction()`.\n * Ordinary schema-version commits are data-only; administrative removal\n * cleanup may execute transaction-scoped DDL.\n */\n function runDoSqliteStorageTransaction<T>(run: () => Promise<T>): Promise<T> {\n const storage = getDurableObjectStorageClient(db);\n if (storage === undefined) {\n throwSqliteTransactionsDisabled(\n \"transactionMode 'do-sqlite' requires a Drizzle Durable Objects \" +\n \"database (drizzle(ctx.storage)) whose `$client` exposes the SQL, \" +\n \"transactionSync, and async transaction runners.\",\n );\n }\n return runWithSerializedQueue(serializedQueue, () =>\n storage.transaction(run),\n );\n }\n\n /**\n * Executes a transaction-frame statement (BEGIN IMMEDIATE / COMMIT /\n * ROLLBACK) through the prepared-statement cache when the driver has one.\n * These are the hottest statements on the per-write path (every single\n * write is its own transaction). Local libsql also uses \"sql\" transaction\n * mode but is async (no compiled path) and keeps the drizzle fallback.\n */\n async function runFrameStatement(query: SQL): Promise<void> {\n const compiledRun = executionAdapter.executeCompiledRun;\n if (compiledRun === undefined) {\n await db.run(query);\n return;\n }\n await compiledRun(executionAdapter.compile(query));\n }\n\n /**\n * Rolls the manually framed transaction back on the failure path WITHOUT ever\n * throwing: the caller rethrows the original error immediately after.\n *\n * SQLite rolls a transaction back by itself on some errors (SQLITE_FULL,\n * SQLITE_IOERR, SQLITE_NOMEM), so by the time this runs the frame can already\n * be gone and the ROLLBACK fails with \"cannot rollback - no transaction is\n * active\". A bare `await ROLLBACK; throw error` replaces the caller's\n * actionable failure (\"disk image is malformed\") with that secondary one and\n * never reaches its own rethrow — the masking that `closeAfterFailure` and the\n * index-materialization claim release exist to prevent, applied here too.\n *\n * The two reasons a ROLLBACK can fail are NOT told apart here, deliberately.\n * SQLite reports the already-closed frame only as a message (\"cannot rollback\n * - no transaction is active\"), with no result code that distinguishes it, so\n * a classifier would have to match text through whatever wrapper the driver\n * applied — and it would buy nothing, because the handling is identical\n * either way: never mask the caller's error, always report. The report\n * therefore states both possibilities rather than asserting the benign one,\n * so an operator reading the log is not told \"nothing is leaked\" about a\n * failure that did leave the frame open. When it did, nothing here can close\n * it (the statement that would is the one that just failed) and the next\n * BEGIN on this connection fails loudly rather than silently joining it.\n */\n async function rollbackFrameQuietly(): Promise<void> {\n try {\n await runFrameStatement(sql`ROLLBACK`);\n } catch (rollbackError) {\n console.warn(\n \"typegraph: ROLLBACK failed while unwinding a failed SQLite \" +\n \"transaction; the original failure is the one thrown. Either the \" +\n \"frame was already closed (SQLite auto-rolls-back on SQLITE_FULL / \" +\n \"SQLITE_IOERR / SQLITE_NOMEM) and nothing is leaked, or it is still \" +\n \"open on this connection, in which case the next BEGIN here fails.\",\n rollbackError,\n );\n }\n }\n\n /**\n * Runs `fn` inside a SQLite write transaction (BEGIN IMMEDIATE) so that\n * the read-then-write inside `commitSchemaVersion` / `setActiveVersion`\n * is serialized against concurrent writers — a deferred BEGIN would let\n * two transactions race past the CAS read and one would later fail\n * with SQLITE_BUSY instead of producing a clean StaleVersionError.\n *\n * Refuses on `transactionMode: \"none\"`. The orphan-row crash window\n * cannot be eliminated without atomicity.\n */\n function runSchemaWriteTransaction<T>(\n fn: (tx: InternalOperationBackend) => Promise<T>,\n ): Promise<T> {\n if (transactionMode === \"none\") {\n throwSqliteTransactionsDisabled(\n \"Schema writes and removal cleanup require atomic transactions, \" +\n \"but this SQLite backend has transactions disabled. Configure a \" +\n \"driver that supports transactions (better-sqlite3, libsql, \" +\n \"bun:sqlite) to use schema commits.\",\n );\n }\n\n if (transactionMode === \"sql\") {\n return runWithSerializedQueue(serializedQueue, async () => {\n // Write-lock is held here, so the schema-write-capable\n // InternalOperationBackend is used intentionally (see its type).\n const txBackend = createTransactionBackend({\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n });\n await runFrameStatement(sql`BEGIN IMMEDIATE`);\n try {\n const result = await fn(txBackend);\n await runFrameStatement(sql`COMMIT`);\n return result;\n } catch (error) {\n await rollbackFrameQuietly();\n throw error;\n }\n });\n }\n\n if (transactionMode === \"do-sqlite\") {\n // No interactive lock-mode control on the DO storage runner; the\n // serialized queue (always present — DO is sync) provides the\n // single-writer ordering that \"immediate\" gives the other paths.\n // Raw txBackend (no `gateFulltext`, unlike the business\n // `transaction()` do-sqlite branch). Schema-version commits remain\n // data-only; administrative removal cleanup may use the target's\n // transaction-scoped DDL primitive.\n return runDoSqliteStorageTransaction(async () => {\n const txBackend = createTransactionBackend({\n capabilities,\n db,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n });\n return fn(txBackend);\n });\n }\n\n // transactionMode === \"drizzle\". Drizzle's sqlite-core transaction\n // accepts a `behavior` option that maps to BEGIN / BEGIN IMMEDIATE /\n // BEGIN EXCLUSIVE; \"immediate\" is what we need to acquire a reserved\n // write lock at the start of the transaction.\n return runWithSerializedQueue(\n serializedQueue,\n async () =>\n db.transaction(\n async (tx) => {\n const txBackend = createTransactionBackend({\n capabilities,\n db: tx,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n });\n return fn(txBackend);\n },\n { behavior: \"immediate\" },\n ) as Promise<T>,\n );\n }\n\n // Shared by the \"drizzle\" branch of `transaction()` (TypeGraph opens\n // the tx) and `adoptTransaction()` (#134 — the caller already opened\n // it): bind a tx-scoped backend to the *literal* `tx` client and gate\n // fulltext on the durable marker (a cached SELECT, never DDL).\n function bindTransactionBackend(tx: AnySqliteDatabase): TransactionBackend {\n const txBackend = createTransactionBackend({\n capabilities,\n db: tx,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n });\n return gateFulltext(\n txBackend,\n contributionMaterializer.assertInitialized,\n contributionMaterializer.refuseUnavailableFulltext,\n );\n }\n\n const backend: AdapterBackend<AnySqliteDatabase> = {\n ...operations,\n\n ...((\n isSync &&\n transactionMode === \"sql\" &&\n executionAdapter.executePreparedRunBatch !== undefined\n ) ?\n {\n async trustedImport<T>(\n fn: (session: TrustedImportSession) => Promise<T>,\n options_?: TrustedImportOptions,\n ): Promise<T> {\n return backend.transaction(async (tx) => {\n if (options_?.schemaWrite !== undefined) {\n await requireDefined(tx.lockSchemaVersionForWrite)({\n ...options_.schemaWrite,\n });\n }\n await assertTrustedImportDatabaseEmpty(tx, tableNames);\n const indexDefinitions = await suspendSqliteSecondaryIndexes(\n tx,\n tableNames,\n );\n const result = await fn(\n createSqliteTrustedImportSession(executionAdapter, tableNames),\n );\n await restoreSecondaryIndexes(tx, indexDefinitions);\n await analyzeImportedTables(tx, tableNames);\n return result;\n });\n },\n }\n : {}),\n\n async bootstrapTables(): Promise<void> {\n const statements = generateSqliteDDL(tables, fulltextStrategy);\n for (const statement of statements) {\n await db.run(sql.raw(statement));\n }\n },\n\n async ensureRevisionOriginsTable(): Promise<void> {\n await db.run(\n sql.raw(generateSqliteCreateTableSQL(tables.revisionOrigins)),\n );\n },\n\n async ensureIdentityTables(\n identityTableNames,\n options,\n ): Promise<readonly string[]> {\n // First enablement of Operational Identity on an existing populated\n // database: createStore / createSqliteBackend run no DDL, so the four\n // identity relations the enablement preflight reads/writes may not\n // exist yet. Ensure them (and their indexes and CHECK constraints)\n // idempotently — CREATE TABLE / CREATE INDEX IF NOT EXISTS — reusing the same contribution\n // DDL bootstrapTables emits, scoped to the identity relations.\n const identityContributions =\n identityContributionsFor(identityTableNames);\n const missing = [] as string[];\n for (const contribution of identityContributions) {\n if (!(await contributionTableExists(contribution.tableName))) {\n missing.push(contribution.logicalName);\n }\n }\n // Preserve missing ledger storage on already-enabled graphs so a retry\n // cannot silently accept tables created empty by an earlier failed open.\n // First enablement opts into provisioning; when every table exists,\n // idempotent DDL still repairs missing secondary indexes.\n if (missing.length === 0 || options.provisionMissing) {\n for (const contribution of identityContributions) {\n for (const ddl of contribution.createDdl) {\n await db.run(sql.raw(ddl));\n }\n }\n }\n return missing;\n },\n\n identityTableDdl(identityTableNames): readonly string[] {\n return identityContributionsFor(identityTableNames).flatMap(\n (contribution) => [...contribution.createDdl],\n );\n },\n\n // Every fulltext-touching method asserts the durable marker instead\n // of lazily emitting DDL. Steady state performs zero ensure; an\n // uninitialized database throws `StoreNotInitializedError` rather\n // than self-healing (#135). Shared verbatim with the tx-scoped gate\n // via `gateFulltextMethods`.\n ...gateFulltextMethods(\n operations,\n contributionMaterializer.assertInitialized,\n contributionMaterializer.refuseUnavailableFulltext,\n ),\n\n async executeDdl(ddl: string): Promise<void> {\n await db.run(sql.raw(ddl));\n },\n\n async ensureIndexMaterializationsTable(): Promise<void> {\n await db.run(\n sql.raw(generateSqliteCreateTableSQL(tables.indexMaterializations)),\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, SQLITE_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, SQLITE_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 SQLITE_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.run(sql.raw(generateSqliteCreateTableSQL(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, SQLITE_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, SQLITE_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 SQLITE_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.run(\n sql.raw(generateSqliteCreateTableSQL(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 async verifyContributions(\n graphId: string,\n vectorSlots: readonly VectorSlot[],\n ): Promise<readonly ContributionDiagnostic[]> {\n return contributionMaterializer.verifyContributions(graphId, vectorSlots);\n },\n\n async repairContributions(\n graphId: string,\n vectorSlots: readonly VectorSlot[],\n ): Promise<ContributionRepairResult> {\n return contributionMaterializer.repairContributions(graphId, vectorSlots);\n },\n\n async probeContributions(\n graphId: string,\n vectorSlots: readonly VectorSlot[],\n ): Promise<readonly ContributionProbeEntry[]> {\n return contributionMaterializer.probeContributions(graphId, vectorSlots);\n },\n\n async rebuildContribution(\n graphId: string,\n scope: ContributionRebuildScope,\n repopulate: (\n target: TransactionBackend,\n ) => Promise<ContributionRepopulationStats>,\n ): Promise<ContributionRebuildResult> {\n return contributionMaterializer.rebuildContribution(\n graphId,\n scope,\n repopulate,\n );\n },\n\n // Vector counterparts of the runtime-contribution methods. Present\n // only when a vector strategy is wired (omitted on a plain SQLite\n // connection with no vector extension), mirroring the embedding/\n // search methods.\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 // `ANALYZE` populates `sqlite_stat1`. With no stat table, the\n // planner falls back to heuristics that, at least for FTS5\n // virtual-table queries and multi-column index selection, can be\n // an order of magnitude slower. Running it explicitly makes the\n // planner data-driven.\n //\n // Scoped to TypeGraph-managed tables only (matching the Postgres\n // backend) — a bare `ANALYZE` touches every table in the database\n // file, including unrelated ones sharing it. Bounded by\n // `analysis_limit` (see its doc comment) so cost stays roughly\n // constant per call regardless of table size — the value is a\n // fixed internal constant, not user input, so inlining it via\n // `sql.raw` is safe; SQLite's `PRAGMA` does not accept bound\n // parameters for its value.\n try {\n await db.run(\n toDrizzleSql(\n portableSql`PRAGMA analysis_limit = ${portableSql.raw(String(SQLITE_ANALYZE_ROW_LIMIT))}`,\n \"sqlite\",\n ),\n );\n } catch (error) {\n // Cloudflare D1 and Durable Object SQLite reject this performance-only\n // tuning PRAGMA through their authorizer. Continue with scoped ANALYZE,\n // which workerd permits, but keep every unexpected failure loud.\n if (!isSqliteNotAuthorizedError(error)) throw error;\n }\n for (const tableName of coreAnalyzeTables) {\n await db.run(\n toDrizzleSql(\n portableSql`ANALYZE ${portableSql.identifier(tableName)}`,\n \"sqlite\",\n ),\n );\n }\n // The recorded and identity relations may be absent on a schema\n // created before recorded-time history or Operational Identity landed\n // (bring-your-own-connection, no DDL re-run); ANALYZE on a missing\n // table errors, so skip those.\n for (const tableName of guardedAnalyzeTables) {\n try {\n await db.run(\n toDrizzleSql(\n portableSql`ANALYZE ${portableSql.identifier(tableName)}`,\n \"sqlite\",\n ),\n );\n } catch (error) {\n if (!isMissingTableError(error)) throw error;\n }\n }\n },\n\n async commitSchemaVersion(\n params: CommitSchemaVersionParams,\n ): Promise<SchemaVersionRow> {\n return runSchemaWriteTransaction((target) =>\n target.commitSchemaVersion(params),\n );\n },\n\n async commitSchemaVersionIfKindsEmpty(\n params: CommitSchemaVersionParams,\n probes: readonly SchemaKindEmptinessProbe[],\n ): Promise<CommitSchemaVersionIfKindsEmptyResult> {\n // BEGIN IMMEDIATE already owns SQLite's serialized writer slot, so the\n // counts and schema CAS below share the same ordinary-write fence.\n return runSchemaWriteTransaction((target) =>\n commitSchemaVersionIfKindsEmpty(target, params, probes),\n );\n },\n\n async commitSchemaVersionWithPreflight(\n params: CommitSchemaVersionParams,\n // The schema-write target, not the narrowed transaction backend: a\n // preflight may have to CREATE the storage it then fills, and that DDL\n // belongs in this transaction rather than before it.\n preflight: (target: SchemaWriteTransactionBackend) => Promise<void>,\n ): Promise<SchemaVersionRow> {\n return runSchemaWriteTransaction(async (target) => {\n await preflight(target);\n return target.commitSchemaVersion(params);\n });\n },\n\n async setActiveVersion(params: SetActiveVersionParams): Promise<void> {\n await runSchemaWriteTransaction((target) =>\n target.setActiveVersion(params),\n );\n },\n\n async schemaWriteTransaction<T>(\n _graphId: string,\n fn: (tx: SchemaWriteTransactionBackend) => Promise<T>,\n ): Promise<T> {\n return runSchemaWriteTransaction((target) => fn(target));\n },\n\n async transaction<T>(\n fn: (tx: TransactionBackend) => Promise<T>,\n options?: InternalTransactionOptions,\n ): Promise<T> {\n return backend.transactionWithNative((tx) => fn(tx), options);\n },\n\n async transactionWithNative<T>(\n fn: (tx: TransactionBackend, sql: AnySqliteDatabase) => Promise<T>,\n options?: InternalTransactionOptions,\n ): Promise<T> {\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: \"sqlite\" },\n );\n }\n if (transactionMode === \"none\") {\n throwSqliteTransactionsDisabled(\n \"This SQLite backend does not support atomic transactions. \" +\n \"Operations within a transaction are not rolled back on failure. \" +\n \"Use backend.capabilities.transactions to check for transaction support, \" +\n \"or use individual operations with manual error handling.\",\n );\n }\n\n // #134/#135: NO DDL or ensure here. The tx-scoped backend\n // exposes raw fulltext methods without self-ensure wrappers; the\n // single gate is `Store.transaction()`, which asserts the durable\n // contribution marker (one cached SELECT) before this method is\n // reached. The caller's BEGIN never carries CREATE statements.\n if (transactionMode === \"sql\") {\n return runWithSerializedQueue(serializedQueue, async () => {\n // Not `bindTransactionBackend(...)`: this path frames the tx\n // with manual BEGIN/COMMIT on the *outer* `db`, so it must\n // reuse that connection's already-built `executionAdapter`\n // rather than synthesize a fresh one for a distinct handle.\n // Serves sync drivers AND local libsql connections: both keep\n // one stable connection, where raw BEGIN/COMMIT composes and\n // Drizzle's `db.transaction()` (which for libsql abandons the\n // client's connection — fatal for `:memory:`) must be avoided.\n const txBackend = createTransactionBackend({\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n });\n // Read-only multi-statement operations need one snapshot but must not\n // reserve SQLite's single writer slot. Business transactions retain\n // BEGIN IMMEDIATE so read-then-write cannot lose a lock-upgrade race.\n await runFrameStatement(\n options?.accessMode === \"read_only\" || temporaryWrites ?\n sql`BEGIN`\n : sql`BEGIN IMMEDIATE`,\n );\n\n try {\n const result = await fn(\n gateFulltext(\n txBackend,\n contributionMaterializer.assertInitialized,\n contributionMaterializer.refuseUnavailableFulltext,\n ),\n db,\n );\n await runFrameStatement(sql`COMMIT`);\n return result;\n } catch (error) {\n await rollbackFrameQuietly();\n throw error;\n }\n });\n }\n\n if (transactionMode === \"do-sqlite\") {\n return runDoSqliteStorageTransaction(async () =>\n fn(bindTransactionBackend(db), db),\n );\n }\n\n // transactionMode === \"drizzle\". Read-only work uses a deferred snapshot;\n // business transactions retain BEGIN IMMEDIATE for safe lock upgrades.\n return runWithSerializedQueue(\n serializedQueue,\n async () =>\n db.transaction(async (tx) => fn(bindTransactionBackend(tx), tx), {\n behavior:\n options?.accessMode === \"read_only\" || temporaryWrites ?\n \"deferred\"\n : \"immediate\",\n }) as Promise<T>,\n );\n },\n\n adoptTransaction(externalTx: AnySqliteDatabase): TransactionBackend {\n // #134: parity with Postgres. Cross-store atomicity needs real\n // rollback; on a \"none\" driver the caller's relational write\n // would commit with no way to undo the graph write. Refuse\n // loudly rather than silently degrade.\n if (transactionMode === \"none\") {\n throwSqliteTransactionsDisabled(\n \"Cross-store atomicity is unavailable on this SQLite backend: \" +\n \"transactions are disabled (transactionMode: 'none'). Adopting \" +\n \"an external transaction here would let the caller's relational \" +\n \"write commit with no way to roll back the graph write. \" +\n \"Configure a driver that supports transactions (better-sqlite3, \" +\n \"libsql, bun:sqlite).\",\n );\n }\n assertAdoptedDialect<AnySqliteDatabase>(\n externalTx,\n BaseSQLiteDatabase,\n \"sqlite\",\n );\n // serializedQueue is deliberately NOT applied to an adopted tx: a\n // sync better-sqlite3 driver runs the adopted statements on the\n // caller's stack, so wrapping a caller-driven tx in our queue\n // could deadlock against the caller's outer `db.transaction(...)`.\n return bindTransactionBackend(externalTx);\n },\n\n close(): Promise<void> {\n serializedQueue?.dispose();\n return Promise.resolve();\n },\n };\n\n // INVARIANT: audit before any wrapper can observe this backend — see\n // transaction-resource.ts. Unconditional: an abstention recorded as\n // \"independent\" is a verdict the guards can tell apart from a backend nobody\n // looked at.\n auditBackendResource(backend, resourceAudit);\n\n return backend;\n}\n\nfunction createTransactionBackend(\n options: CreateSqliteTransactionBackendOptions,\n): InternalOperationBackend {\n const txExecutionAdapter =\n options.executionAdapter ??\n createSqliteExecutionAdapter(options.db, {\n profileHints: options.profileHints,\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 return createSqliteOperationBackend({\n capabilities: options.capabilities,\n db: options.db,\n executionAdapter: txExecutionAdapter,\n operationStrategy: options.operationStrategy,\n tableNames: options.tableNames,\n fulltextStrategy: options.fulltextStrategy,\n vectorStrategy: options.vectorStrategy,\n contributionMaterializer: options.contributionMaterializer,\n transactionScoped: true,\n });\n}\n\n// Re-export schema utilities\nexport type { SqliteTableNames, SqliteTables } from \"./schema/sqlite\";\nexport { createSqliteTables, tables } from \"./schema/sqlite\";\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/global-symbol.ts","../src/query/dialect/profile.ts","../src/query/sql-intent.ts","../src/query/sql-fragment.ts","../src/query/dialect/like-escape.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CAAK,KAAK,KAAK,CAAA;AACrB,QAAA;AAAA,MACF;AAAA,MACA,KAAK,YAAA,EAAc;AACjB,QAAA,KAAA,CAAM,IAAA,CAAK,gBAAA,CAAiB,IAAA,CAAK,KAAK,CAAC,CAAA;AACvC,QAAA;AAAA,MACF;AAAA,MACA,KAAK,WAAA,EAAa;AAChB,QAAA,KAAA,CAAM,IAAA,CAAK,aAAA,CAAc,IAAA,CAAK,KAAA,EAAO,OAAO,CAAC,CAAA;AAC7C,QAAA;AAAA,MACF;AAAA,MACA,KAAK,aAAA,EAAe;AAClB,QAAA,MAAM,IAAIA,oCAAA;AAAA,UACR,CAAA,0CAAA,EAA6C,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA,CAAA,CAAA;AAAA,UAC5D,EAAE,aAAA,EAAe,IAAA,CAAK,KAAA,CAAM,IAAA;AAAK,SACnC;AAAA,MACF;AAAA,MACA,SAAS;AACP,QAAA,wBAAA,CAAyB,IAAI,CAAA;AAAA,MAC/B;AAAA;AACF,EACF;AAEA,EAAA,OAAO,KAAA,CAAM,KAAK,EAAE,CAAA;AACtB;;;ACvWO,IAAM,qBAAA,GAAwB;AAQ9B,IAAM,gBAAA,GAAgC,GAAA,CAAA,WAAA","file":"chunk-OJHD3LXJ.cjs","sourcesContent":["type TypeGraphGlobalSymbolName =\n | \"sql-fragment\"\n | \"sql-placeholder\"\n | \"sql-intent-registry\"\n | \"internal-temporary-writes-v1\"\n | \"external-recorded-read-source-v1\"\n | \"sql-schema-v1\"\n | \"store-runtime-v1\"\n | \"typegraph-recorded-read-source-v1\"\n | \"transaction-runtime-v1\";\n\n/** Returns a process-wide symbol shared across ESM/CJS package instances. */\nexport function typeGraphGlobalSymbol<TSymbol extends symbol>(\n name: TypeGraphGlobalSymbolName,\n): TSymbol {\n return Symbol.for(`@nicia-ai/typegraph/${name}`) as TSymbol;\n}\n","import { type SqlDialect } from \"./types\";\n\nexport type SqlDialectProfile = Readonly<{\n bindValue: (value: unknown) => unknown;\n booleanLiteralString: (value: boolean) => string;\n placeholder: (index: number) => string;\n}>;\n\nconst SQL_DIALECT_PROFILES = {\n postgres: {\n bindValue: (value: unknown) => value,\n booleanLiteralString: (value: boolean) => (value ? \"TRUE\" : \"FALSE\"),\n placeholder: (index: number) => `$${index}`,\n },\n sqlite: {\n bindValue: (value: unknown) =>\n typeof value === \"boolean\" ?\n value ? 1\n : 0\n : value,\n booleanLiteralString: (value: boolean) => (value ? \"1\" : \"0\"),\n placeholder: () => \"?\",\n },\n} satisfies Record<SqlDialect, SqlDialectProfile>;\n\nconst SQL_STRING_LITERAL_RENDERERS = {\n postgres: (value: string) => {\n if (value.includes(\"\\\\\")) {\n return `E'${value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"'\", \"''\")}'`;\n }\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n },\n sqlite: (value: string) => `'${value.replaceAll(\"'\", \"''\")}'`,\n} satisfies Record<SqlDialect, (value: string) => string>;\n\n/** Returns the primitive rendering and binding rules for a SQL dialect. */\nexport function getSqlDialectProfile(dialect: SqlDialect): SqlDialectProfile {\n return SQL_DIALECT_PROFILES[dialect];\n}\n\n/** Maps a JavaScript value to the representation expected by a SQL driver. */\nexport function bindSqlValue(value: unknown, dialect: SqlDialect): unknown {\n if (value instanceof Date) return value.toISOString();\n return getSqlDialectProfile(dialect).bindValue(value);\n}\n\n/**\n * Packs a scalar list into the single JSON-text value that a list-valued `IN`\n * parameter binds to. Every element is bound exactly as the literal form would\n * bind it, so `field.in([...])` and `field.in(param(...))` agree row for row.\n */\nexport function packSqlListValue(\n values: readonly unknown[],\n dialect: SqlDialect,\n): string {\n return JSON.stringify(values.map((value) => bindSqlValue(value, dialect)));\n}\n\n/** Renders one SQL string literal using the dialect's escaping rules. */\nexport function inlineSqlStringLiteral(\n value: string,\n dialect: SqlDialect,\n): string {\n return SQL_STRING_LITERAL_RENDERERS[dialect](value);\n}\n","import { typeGraphGlobalSymbol } from \"../utils/global-symbol\";\nimport { type SqlFragment } from \"./sql-fragment\";\n\ndeclare const SqlIntentBrand: unique symbol;\n\nexport type SqlIntent = \"rows\" | \"statement\" | \"temporary-statement\";\n\nexport type IntentSql<I extends SqlIntent> = SqlFragment &\n Readonly<{ [SqlIntentBrand]: I }>;\n\nexport type CompiledRowsSql = IntentSql<\"rows\">;\nexport type CompiledSelectSql = CompiledRowsSql;\nexport type CompiledStatementSql = IntentSql<\"statement\">;\nexport type CompiledTemporaryStatementSql = IntentSql<\"temporary-statement\">;\n\nexport function asCompiledRowsSql(query: SqlFragment): CompiledRowsSql {\n return query as CompiledRowsSql;\n}\n\nexport function asCompiledSelectSql(query: SqlFragment): CompiledSelectSql {\n return asCompiledRowsSql(query);\n}\n\nexport function asCompiledStatementSql(\n query: SqlFragment,\n): CompiledStatementSql {\n return query as CompiledStatementSql;\n}\n\n/**\n * Marks an internal statement that may write only connection-local temporary\n * state. This is intentionally separate from the public raw-statement intent:\n * history-enabled stores block arbitrary raw writes but iterative graph\n * operations still need to manage ephemeral working tables.\n */\nexport function asCompiledTemporaryStatementSql(\n query: SqlFragment,\n): CompiledTemporaryStatementSql {\n return query as CompiledTemporaryStatementSql;\n}\n\n/**\n * Statements whose good plan depends on the bound parameter values —\n * e.g. an id-array membership filter where the array cardinality varies\n * per call. PostgreSQL's prepared-statement machinery switches to a\n * generic (parameter-blind) plan after five executions, which for these\n * statements is catastrophically wrong (measured 21ms -> 310ms on the\n * subgraph edge fetch). Marked statements are executed unnamed so every\n * call is planned against the actual parameters; the re-parse cost is\n * ~1ms, the generic-plan cliff it avoids is 10-300ms.\n */\ntype SqlIntentRegistry = Readonly<{\n annIndexScanQueries: WeakMap<SqlFragment, readonly string[]>;\n forceCustomPlanQueries: WeakSet<SqlFragment>;\n}>;\n\nconst SQL_INTENT_REGISTRY: unique symbol = typeGraphGlobalSymbol(\n \"sql-intent-registry\",\n);\nconst globalWithSqlIntentRegistry = globalThis as typeof globalThis &\n Readonly<{\n [SQL_INTENT_REGISTRY]?: SqlIntentRegistry;\n }>;\nconst sqlIntentRegistry =\n globalWithSqlIntentRegistry[SQL_INTENT_REGISTRY] ??\n (() => {\n const registry: SqlIntentRegistry = {\n annIndexScanQueries: new WeakMap(),\n forceCustomPlanQueries: new WeakSet(),\n };\n Object.defineProperty(globalWithSqlIntentRegistry, SQL_INTENT_REGISTRY, {\n configurable: false,\n enumerable: false,\n value: registry,\n writable: false,\n });\n return registry;\n })();\n\nexport function markForceCustomPlan(query: SqlFragment): void {\n sqlIntentRegistry.forceCustomPlanQueries.add(query);\n}\n\nexport function shouldForceCustomPlan(query: SqlFragment): boolean {\n return sqlIntentRegistry.forceCustomPlanQueries.has(query);\n}\n\n/**\n * Statements whose plan includes an engine ANN index scan (the inline\n * `.similarTo(..., { approximate: true })` branch). The PostgreSQL\n * backend wraps their execution with the same pgvector GUC overrides\n * the search facade applies (`hnsw.iterative_scan = strict_order` /\n * `ivfflat.iterative_scan = relaxed_order` on pgvector >= 0.8), so a\n * filtered approximate query keeps scanning past the default ef_search\n * frontier instead of starving. Carries the slot index types so the\n * backend knows which GUCs apply. Backends without GUC semantics\n * ignore the brand.\n */\nexport function markAnnIndexScan(\n query: SqlFragment,\n indexTypes: readonly string[],\n): void {\n sqlIntentRegistry.annIndexScanQueries.set(query, indexTypes);\n}\n\nexport function annIndexScanTypes(\n query: SqlFragment,\n): readonly string[] | undefined {\n return sqlIntentRegistry.annIndexScanQueries.get(query);\n}\n\n/** @internal Copies execution semantics when immutable fragments are composed. */\nexport function copySqlIntents(\n target: SqlFragment,\n sources: readonly SqlFragment[],\n): void {\n if (sources.some((source) => shouldForceCustomPlan(source))) {\n markForceCustomPlan(target);\n }\n\n const indexTypes = new Set<string>();\n for (const source of sources) {\n for (const indexType of annIndexScanTypes(source) ?? []) {\n indexTypes.add(indexType);\n }\n }\n if (indexTypes.size > 0) markAnnIndexScan(target, [...indexTypes]);\n}\n\n/**\n * Whether a compiled statement can be run as raw text (`executeRaw`) without\n * losing execution semantics. Both brands above ride on the SQL *object* and\n * are honored only by `backend.execute`: the force-custom-plan flag makes\n * PostgreSQL re-plan against the actual parameters (opposed to reusing a\n * cached statement), and the ANN-scan brand drives the pgvector iterative-scan\n * GUC wrapper. A statement carrying either must not be flattened to text and\n * cached — callers fall back to `backend.execute`. Keeping this predicate\n * beside the brands means a future brand updates one place, not every caller.\n */\nexport function isRawExecutable(query: SqlFragment): boolean {\n return (\n !shouldForceCustomPlan(query) && annIndexScanTypes(query) === undefined\n );\n}\n","import { ConfigurationError } from \"../errors\";\nimport { typeGraphGlobalSymbol } from \"../utils/global-symbol\";\nimport {\n bindSqlValue,\n getSqlDialectProfile,\n inlineSqlStringLiteral,\n} from \"./dialect/profile\";\nimport { type SqlDialect } from \"./dialect/types\";\nimport { copySqlIntents } from \"./sql-intent\";\n\n/** Nominal identity shared by every package entrypoint. */\nconst SQL_FRAGMENT_BRAND: unique symbol = typeGraphGlobalSymbol(\"sql-fragment\");\nconst SQL_PLACEHOLDER_BRAND: unique symbol =\n typeGraphGlobalSymbol(\"sql-placeholder\");\n\nexport type SqlTextChunk = Readonly<{\n kind: \"text\";\n value: string;\n}>;\n\nexport type SqlParameterChunk = Readonly<{\n kind: \"parameter\";\n value: unknown;\n}>;\n\nexport type SqlIdentifierChunk = Readonly<{\n kind: \"identifier\";\n value: string;\n}>;\n\nexport type SqlPlaceholderChunk = Readonly<{\n kind: \"placeholder\";\n value: Placeholder;\n}>;\n\n/** One immutable unit in a database-independent SQL fragment. */\nexport type SqlChunk =\n SqlTextChunk | SqlParameterChunk | SqlIdentifierChunk | SqlPlaceholderChunk;\n\n/**\n * An immutable, database-independent SQL expression.\n *\n * Fragments contain syntax and bound values as separate nodes. A database\n * adapter renders the same fragment with its native placeholder convention at\n * the final execution boundary.\n */\nexport type SqlFragment = Readonly<{\n [SQL_FRAGMENT_BRAND]: true;\n append: (fragment: SqlFragment) => SqlFragment;\n chunks: readonly SqlChunk[];\n}>;\n\n/** A named value resolved when a prepared statement is executed. */\nexport class Placeholder {\n readonly [SQL_PLACEHOLDER_BRAND] = true as const;\n readonly name: string;\n\n constructor(name: string) {\n this.name = name;\n Object.freeze(this);\n }\n}\n\nclass SqlFragmentValue implements SqlFragment {\n readonly [SQL_FRAGMENT_BRAND] = true as const;\n\n readonly chunks: readonly SqlChunk[];\n\n constructor(chunks: readonly SqlChunk[]) {\n this.chunks = Object.freeze([...chunks]);\n Object.freeze(this);\n }\n\n append(fragment: SqlFragment): SqlFragment {\n return createFragment(\n [...this.chunks, ...getChunks(fragment)],\n [this, fragment],\n );\n }\n}\n\nfunction createFragment(\n chunks: readonly SqlChunk[],\n intentSources: readonly SqlFragment[] = [],\n): SqlFragment {\n const fragment = new SqlFragmentValue(chunks);\n copySqlIntents(fragment, intentSources);\n return fragment;\n}\n\nfunction getChunks(fragment: SqlFragment): readonly SqlChunk[] {\n if (!isSqlFragment(fragment)) {\n throw new ConfigurationError(\n \"Expected a SQL fragment created by TypeGraph's sql helper\",\n );\n }\n return fragment.chunks;\n}\n\n/** Returns whether a value is a TypeGraph-owned SQL fragment. */\nexport function isSqlFragment(value: unknown): value is SqlFragment {\n return (\n typeof value === \"object\" &&\n value !== null &&\n SQL_FRAGMENT_BRAND in value &&\n value[SQL_FRAGMENT_BRAND] === true &&\n \"chunks\" in value &&\n Array.isArray(value.chunks) &&\n \"append\" in value &&\n typeof value.append === \"function\"\n );\n}\n\n/** Returns whether a value is a TypeGraph named SQL placeholder. */\nexport function isSqlPlaceholder(value: unknown): value is Placeholder {\n return (\n typeof value === \"object\" &&\n value !== null &&\n SQL_PLACEHOLDER_BRAND in value &&\n value[SQL_PLACEHOLDER_BRAND] === true &&\n \"name\" in value &&\n typeof value.name === \"string\"\n );\n}\n\n/** @internal Enforces exhaustive handling at every fragment boundary. */\nexport function throwUnsupportedSqlChunk(chunk: never): never {\n throw new ConfigurationError(\"Unsupported SQL fragment chunk\", { chunk });\n}\n\nfunction textNode(value: string): SqlTextChunk {\n return Object.freeze({ kind: \"text\", value });\n}\n\nfunction parameterNode(value: unknown): SqlParameterChunk {\n return Object.freeze({ kind: \"parameter\", value });\n}\n\nfunction identifierNode(value: string): SqlIdentifierChunk {\n return Object.freeze({ kind: \"identifier\", value });\n}\n\nfunction placeholderNode(value: Placeholder): SqlPlaceholderChunk {\n return Object.freeze({ kind: \"placeholder\", value });\n}\n\nfunction templateSql(\n strings: TemplateStringsArray,\n ...values: readonly unknown[]\n): SqlFragment {\n const chunks: SqlChunk[] = [];\n const intentSources: SqlFragment[] = [];\n\n for (const [index, text] of strings.entries()) {\n if (text.length > 0) chunks.push(textNode(text));\n\n if (index >= values.length) continue;\n const value = values[index];\n if (isSqlFragment(value)) {\n chunks.push(...getChunks(value));\n intentSources.push(value);\n } else if (isSqlPlaceholder(value)) {\n chunks.push(placeholderNode(value));\n } else {\n chunks.push(parameterNode(value));\n }\n }\n\n return createFragment(chunks, intentSources);\n}\n\nfunction rawSql(value: string): SqlFragment {\n return createFragment(value.length === 0 ? [] : [textNode(value)]);\n}\n\nfunction identifierSql(value: string): SqlFragment {\n return createFragment([identifierNode(value)]);\n}\n\nfunction joinSql(\n fragments: readonly SqlFragment[],\n separator: SqlFragment = EMPTY_SQL,\n): SqlFragment {\n const chunks: SqlChunk[] = [];\n const intentSources: SqlFragment[] = [separator];\n\n for (const [index, fragment] of fragments.entries()) {\n if (index > 0) chunks.push(...getChunks(separator));\n chunks.push(...getChunks(fragment));\n intentSources.push(fragment);\n }\n\n return createFragment(chunks, intentSources);\n}\n\nfunction placeholderSql(name: string): SqlFragment {\n return createFragment([placeholderNode(new Placeholder(name))]);\n}\n\nconst EMPTY_SQL = createFragment([]);\n\n/** TypeGraph's database-independent SQL template and composition helpers. */\nexport type SqlTag = Readonly<{\n empty: () => SqlFragment;\n identifier: (value: string) => SqlFragment;\n join: (\n fragments: readonly SqlFragment[],\n separator?: SqlFragment,\n ) => SqlFragment;\n placeholder: (name: string) => SqlFragment;\n raw: (value: string) => SqlFragment;\n}> &\n ((\n strings: TemplateStringsArray,\n ...values: readonly unknown[]\n ) => SqlFragment);\n\n/** TypeGraph's database-independent SQL template and composition helpers. */\nexport const sql: SqlTag = Object.assign(templateSql, {\n empty: function empty(): SqlFragment {\n return EMPTY_SQL;\n },\n identifier: identifierSql,\n join: joinSql,\n placeholder: placeholderSql,\n raw: rawSql,\n});\n\n/** A rendered statement and its ordered bound parameters. */\nexport type RenderedSql = Readonly<{\n sql: string;\n params: readonly unknown[];\n}>;\n\nfunction quotedIdentifier(identifier: string): string {\n return `\"${identifier.replaceAll('\"', '\"\"')}\"`;\n}\n\nfunction resolvedPlaceholder(\n placeholder: Placeholder,\n bindings: Readonly<Record<string, unknown>> | undefined,\n dialect: SqlDialect,\n): unknown {\n if (bindings === undefined) return placeholder;\n\n if (!Object.hasOwn(bindings, placeholder.name)) {\n throw new ConfigurationError(\n `Missing binding for parameter \"${placeholder.name}\"`,\n { parameterName: placeholder.name },\n );\n }\n return bindSqlValue(bindings[placeholder.name], dialect);\n}\n\n/**\n * Renders a fragment for a database adapter.\n *\n * Named placeholders remain in `params` when `bindings` is omitted, allowing\n * a prepared template to resolve them later. Passing `bindings` resolves every\n * placeholder eagerly.\n */\nexport function renderSql(\n fragment: SqlFragment,\n dialect: SqlDialect,\n bindings?: Readonly<Record<string, unknown>>,\n): RenderedSql {\n const parts: string[] = [];\n const params: unknown[] = [];\n const profile = getSqlDialectProfile(dialect);\n\n for (const node of getChunks(fragment)) {\n switch (node.kind) {\n case \"text\": {\n parts.push(node.value);\n break;\n }\n case \"identifier\": {\n parts.push(quotedIdentifier(node.value));\n break;\n }\n case \"parameter\": {\n params.push(bindSqlValue(node.value, dialect));\n parts.push(profile.placeholder(params.length));\n break;\n }\n case \"placeholder\": {\n params.push(resolvedPlaceholder(node.value, bindings, dialect));\n parts.push(profile.placeholder(params.length));\n break;\n }\n default: {\n throwUnsupportedSqlChunk(node);\n }\n }\n }\n\n return Object.freeze({\n sql: parts.join(\"\"),\n params: Object.freeze(params),\n });\n}\n\n/** Renders a fragment using SQLite's `?` placeholders. */\nexport function renderSqlite(\n fragment: SqlFragment,\n bindings?: Readonly<Record<string, unknown>>,\n): RenderedSql {\n return renderSql(fragment, \"sqlite\", bindings);\n}\n\n/** Renders a fragment using PostgreSQL's numbered placeholders. */\nexport function renderPostgres(\n fragment: SqlFragment,\n bindings?: Readonly<Record<string, unknown>>,\n): RenderedSql {\n return renderSql(fragment, \"postgres\", bindings);\n}\n\nfunction inlineLiteral(value: unknown, dialect: SqlDialect): string {\n if (value === undefined || value === null) return \"NULL\";\n if (typeof value === \"string\") return inlineSqlStringLiteral(value, dialect);\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new ConfigurationError(\"Cannot inline a non-finite SQL number\", {\n value,\n });\n }\n return String(value);\n }\n if (typeof value === \"bigint\") return String(value);\n if (typeof value === \"boolean\") {\n return getSqlDialectProfile(dialect).booleanLiteralString(value);\n }\n if (value instanceof Date) {\n return inlineSqlStringLiteral(value.toISOString(), dialect);\n }\n\n throw new ConfigurationError(\"Cannot inline this SQL parameter value\", {\n value,\n });\n}\n\n/**\n * Renders a fragment with safe scalar literals instead of bound parameters.\n *\n * This is intentionally limited to DDL paths whose drivers cannot bind values.\n * Application queries should always use {@link renderSql}.\n */\nexport function renderSqlInline(\n fragment: SqlFragment,\n dialect: SqlDialect,\n): string {\n const parts: string[] = [];\n\n for (const node of getChunks(fragment)) {\n switch (node.kind) {\n case \"text\": {\n parts.push(node.value);\n break;\n }\n case \"identifier\": {\n parts.push(quotedIdentifier(node.value));\n break;\n }\n case \"parameter\": {\n parts.push(inlineLiteral(node.value, dialect));\n break;\n }\n case \"placeholder\": {\n throw new ConfigurationError(\n `Cannot inline unresolved SQL placeholder \"${node.value.name}\"`,\n { parameterName: node.value.name },\n );\n }\n default: {\n throwUnsupportedSqlChunk(node);\n }\n }\n }\n\n return parts.join(\"\");\n}\n","/**\n * Shared LIKE-escape clause for the query compiler.\n *\n * The compiler builds `contains` / `startsWith` / `endsWith` patterns by\n * escaping the literal `%`, `_`, and `\\` in user input with a backslash (see\n * the pattern builders in `compiler/predicates.ts`). For that escaping to take\n * effect the emitted `LIKE` / `ILIKE` must declare backslash as its escape\n * character. PostgreSQL's default LIKE escape is already backslash, so this\n * clause is a no-op there; SQLite has *no* default escape character, so without\n * it an escaped `\\%` matches a literal backslash followed by any character —\n * silently diverging from Postgres. Emitting it on every compiled predicate\n * makes the two backends match by construction.\n */\nimport { sql, type SqlFragment } from \"../sql-fragment\";\n\n/**\n * The backslash escape character used by the JS pattern builder\n * (`compileStringPattern` in `compiler/predicates.ts`) to prefix the literal\n * `%`, `_`, and `\\` in user input. It must match the character declared by\n * {@link likeEscapeClause}: the builder prefixes wildcards with this character,\n * and the clause tells SQL to treat it as the escape. Both are backslash.\n */\nexport const LIKE_ESCAPE_CHARACTER = \"\\\\\";\n\n/**\n * `ESCAPE '\\'` clause appended to every compiled `LIKE` / `ILIKE` predicate,\n * declaring {@link LIKE_ESCAPE_CHARACTER} as the escape character. The single\n * backslash inside the quotes is a literal in both PostgreSQL (with\n * `standard_conforming_strings`, the default) and SQLite.\n */\nexport const likeEscapeClause: SqlFragment = sql`ESCAPE '\\\\'`;\n"]}
|
package/dist/chunk-PALYTHGM.js
DELETED
|
@@ -1,114 +0,0 @@
|
|
|
1
|
-
import { typeGraphGlobalSymbol } from './chunk-46UGOVRW.js';
|
|
2
|
-
|
|
3
|
-
// src/backend/types.ts
|
|
4
|
-
function normalizeGraphAnalyticsCapabilities(capabilities) {
|
|
5
|
-
if (capabilities.graphAnalytics?.supported !== true || capabilities.transactions && capabilities.windowFunctions && capabilities.returning !== false) {
|
|
6
|
-
return capabilities;
|
|
7
|
-
}
|
|
8
|
-
return {
|
|
9
|
-
...capabilities,
|
|
10
|
-
graphAnalytics: { ...capabilities.graphAnalytics, supported: false }
|
|
11
|
-
};
|
|
12
|
-
}
|
|
13
|
-
function rowPropsToObject(props) {
|
|
14
|
-
return typeof props === "string" ? JSON.parse(props) : props;
|
|
15
|
-
}
|
|
16
|
-
function rowPropsToJsonText(props) {
|
|
17
|
-
return typeof props === "string" ? props : JSON.stringify(props);
|
|
18
|
-
}
|
|
19
|
-
function isLiveNodeRow(row) {
|
|
20
|
-
return row.deleted_at === void 0;
|
|
21
|
-
}
|
|
22
|
-
function isTombstonedNodeRow(row) {
|
|
23
|
-
return row.deleted_at !== void 0;
|
|
24
|
-
}
|
|
25
|
-
var INTERNAL_TEMPORARY_WRITES = typeGraphGlobalSymbol(
|
|
26
|
-
"internal-temporary-writes-v1"
|
|
27
|
-
);
|
|
28
|
-
var DATABASE_EXTENSION_NAMES = ["pg_trgm", "vector"];
|
|
29
|
-
function createTransactionReadBackend(backend) {
|
|
30
|
-
const getNodes = backend.getNodes;
|
|
31
|
-
const getEdges = backend.getEdges;
|
|
32
|
-
const compileSql = backend.compileSql;
|
|
33
|
-
return Object.freeze({
|
|
34
|
-
dialect: backend.dialect,
|
|
35
|
-
capabilities: backend.capabilities,
|
|
36
|
-
...backend.tableNames === void 0 ? {} : { tableNames: backend.tableNames },
|
|
37
|
-
...backend.fulltextStrategy === void 0 ? {} : { fulltextStrategy: backend.fulltextStrategy },
|
|
38
|
-
...backend.vectorStrategy === void 0 ? {} : { vectorStrategy: backend.vectorStrategy },
|
|
39
|
-
getNode: (graphId, kind, id) => backend.getNode(graphId, kind, id),
|
|
40
|
-
...getNodes === void 0 ? {} : {
|
|
41
|
-
getNodes: (graphId, kind, ids) => getNodes(graphId, kind, ids)
|
|
42
|
-
},
|
|
43
|
-
getEdge: (graphId, id) => backend.getEdge(graphId, id),
|
|
44
|
-
...getEdges === void 0 ? {} : {
|
|
45
|
-
getEdges: (graphId, ids) => getEdges(graphId, ids)
|
|
46
|
-
},
|
|
47
|
-
countEdgesFrom: (params) => backend.countEdgesFrom(params),
|
|
48
|
-
edgeExistsBetween: (params) => backend.edgeExistsBetween(params),
|
|
49
|
-
findEdgesConnectedTo: (params) => backend.findEdgesConnectedTo(params),
|
|
50
|
-
findNodesByKind: (params) => backend.findNodesByKind(params),
|
|
51
|
-
countNodesByKind: (params) => backend.countNodesByKind(params),
|
|
52
|
-
findEdgesByKind: (params) => backend.findEdgesByKind(params),
|
|
53
|
-
countEdgesByKind: (params) => backend.countEdgesByKind(params),
|
|
54
|
-
getActiveSchema: (graphId) => backend.getActiveSchema(graphId),
|
|
55
|
-
getSchemaVersion: (graphId, version) => backend.getSchemaVersion(graphId, version),
|
|
56
|
-
execute: (query) => backend.execute(query),
|
|
57
|
-
...compileSql === void 0 ? {} : { compileSql: (query) => compileSql(query) }
|
|
58
|
-
});
|
|
59
|
-
}
|
|
60
|
-
async function closeAfterFailure(resource, provisioningError) {
|
|
61
|
-
try {
|
|
62
|
-
await resource.close();
|
|
63
|
-
} catch {
|
|
64
|
-
}
|
|
65
|
-
throw provisioningError;
|
|
66
|
-
}
|
|
67
|
-
async function runOptionallyInTransaction(backend, fn, options) {
|
|
68
|
-
if ("transaction" in backend && backend.capabilities.transactions) {
|
|
69
|
-
return backend.transaction(
|
|
70
|
-
(tx) => fn(tx, { atomic: true }),
|
|
71
|
-
options?.transaction
|
|
72
|
-
);
|
|
73
|
-
}
|
|
74
|
-
return fn(options?.fallback ?? backend, { atomic: false });
|
|
75
|
-
}
|
|
76
|
-
var SQLITE_MAX_BIND_PARAMETERS = 999;
|
|
77
|
-
var MODERN_SQLITE_MAX_BIND_PARAMETERS = 32766;
|
|
78
|
-
var D1_MAX_BIND_PARAMETERS = 100;
|
|
79
|
-
var DURABLE_OBJECT_MAX_BIND_PARAMETERS = 100;
|
|
80
|
-
var POSTGRES_MAX_BIND_PARAMETERS = 65533;
|
|
81
|
-
var SQLITE_CAPABILITIES = Object.freeze({
|
|
82
|
-
transactions: true,
|
|
83
|
-
// SQLite supports transactions
|
|
84
|
-
windowFunctions: true,
|
|
85
|
-
// SQLite has supported window functions since 3.25.0
|
|
86
|
-
clearValidTo: true,
|
|
87
|
-
returning: true,
|
|
88
|
-
// SQLite has supported RETURNING since 3.35.0
|
|
89
|
-
// The bundled schema ships both claim relations and the shared operation
|
|
90
|
-
// backend implements every claim member.
|
|
91
|
-
constraintClaims: true,
|
|
92
|
-
maxBindParameters: SQLITE_MAX_BIND_PARAMETERS,
|
|
93
|
-
// Generic SQLite builds do not guarantee ENABLE_MATH_FUNCTIONS. The local
|
|
94
|
-
// better-sqlite3 factory overrides this flag for its bundled build contract.
|
|
95
|
-
graphAnalytics: Object.freeze({ supported: true, mathFunctions: false })
|
|
96
|
-
});
|
|
97
|
-
var POSTGRES_CAPABILITIES = Object.freeze({
|
|
98
|
-
transactions: true,
|
|
99
|
-
// PostgreSQL supports transactions
|
|
100
|
-
windowFunctions: true,
|
|
101
|
-
// PostgreSQL supports ROW_NUMBER() and related windows
|
|
102
|
-
clearValidTo: true,
|
|
103
|
-
returning: true,
|
|
104
|
-
// PostgreSQL has supported RETURNING since 8.2
|
|
105
|
-
// The bundled schema ships both claim relations and the shared operation
|
|
106
|
-
// backend implements every claim member.
|
|
107
|
-
constraintClaims: true,
|
|
108
|
-
maxBindParameters: POSTGRES_MAX_BIND_PARAMETERS,
|
|
109
|
-
graphAnalytics: Object.freeze({ supported: true, mathFunctions: true })
|
|
110
|
-
});
|
|
111
|
-
|
|
112
|
-
export { D1_MAX_BIND_PARAMETERS, DATABASE_EXTENSION_NAMES, DURABLE_OBJECT_MAX_BIND_PARAMETERS, INTERNAL_TEMPORARY_WRITES, MODERN_SQLITE_MAX_BIND_PARAMETERS, POSTGRES_CAPABILITIES, POSTGRES_MAX_BIND_PARAMETERS, SQLITE_CAPABILITIES, SQLITE_MAX_BIND_PARAMETERS, closeAfterFailure, createTransactionReadBackend, isLiveNodeRow, isTombstonedNodeRow, normalizeGraphAnalyticsCapabilities, rowPropsToJsonText, rowPropsToObject, runOptionallyInTransaction };
|
|
113
|
-
//# sourceMappingURL=chunk-PALYTHGM.js.map
|
|
114
|
-
//# sourceMappingURL=chunk-PALYTHGM.js.map
|