All files / core/blong-gogo/src/adapter/server knex.ts

83.78% Statements 2155/2572
79.54% Branches 424/533
77.96% Functions 46/59
83.78% Lines 2155/2572

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 25731x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 542x 542x 542x 8x 8x 8x 1x 1x 170x 170x 170x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 170x 170x 170x 170x 170x 170x 170x 170x 170x 170x 170x 1x 1x       8x 8x 8x 1x 1x             1x 1x 1x 1x 1x           1x 1x         1x 1x 16x 16x 16x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 16x 16x 16x 16x 16x 16x 16x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 6x 6x 6x 6x 6x 6x 6x 8x 4x 4x 4x 4x 4x 4x 4x 4x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 18x 18x 18x 18x 18x 18x 18x 17x 18x 10x 1x 1x 8x 8x 8x 8x 8x 6x 6x 6x 6x 6x 6x 6x 6x 8x 4x 4x 4x 4x 4x 4x 4x 4x 4x 8x 8x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 138x 138x 138x 937x 812x 812x 812x 812x 935x 937x 794x 935x 937x 138x 138x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 7x 7x 7x 3x 3x 7x           7x 8x 8x 8x 8x 8x 8x 8x 8x 8x   8x 8x 8x 8x 8x 8x 8x 8x   8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 206x 412x 264x 148x 148x   206x 206x 8x 8x 8x 8x 8x 8x 8x 8x 161x 161x 161x 161x 161x 161x 161x 161x 161x 161x 161x 161x 161x 161x 161x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 161x 161x 161x 161x 161x 151x 151x 151x 161x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 7x 7x 7x 7x 7x 7x 8x 8x 8x 8x 8x 8x 8x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x                                                       8x 404x 404x 404x 404x 404x 404x 404x 404x 404x 404x 404x 404x 404x 404x 404x 404x 404x 404x 404x 404x 404x 2x 2x 2x 2x 2x 2x 402x 402x 402x 404x               404x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 18x 18x 18x 2x 2x 400x 400x 400x 400x 400x 400x 400x 404x 404x 404x 404x 404x 404x 404x 404x 404x 404x 271x 271x 271x 271x 271x 271x 230x 230x 230x 230x 230x 241x 230x 230x 230x 230x 230x 230x 230x 230x 230x 230x 241x 128x 128x 126x 2x 271x 271x 271x 404x 404x 404x 404x 404x 404x 404x 404x 404x 404x 404x 404x 404x 404x 404x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 404x 404x 404x 404x 404x 404x 404x 78x 78x 78x 78x 52x 52x 52x 52x 52x 66x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 404x 404x 404x 404x 404x 404x 404x 18x 18x 18x 18x 18x 18x 18x 3x 18x     3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 3x 8x 2x 2x 2x 2x 2x 8x 2x 2x 2x 2x 2x 2x 2x 8x 1x 1x 1x 1x 1x 18x 404x 404x 404x 249x 249x 249x 249x 249x 249x 249x 239x 239x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 10x 239x 249x 249x 249x 249x 249x 249x 249x 249x 249x 247x 249x 2x 2x 249x 249x 249x 249x 249x 10x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 123x 123x 123x 123x 123x 123x 123x 123x 121x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 121x 121x 121x 121x 119x 125x 121x 121x   125x 121x 119x 121x 123x 123x 404x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 72x 72x 78x 78x 78x 78x 78x 1x 77x 78x 78x 78x 78x 78x 78x 78x 78x 72x 72x 78x 72x   72x 72x 72x 72x 78x                         78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 14x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x     78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x                 78x 78x 78x 1x 1x 1x 1x 78x 78x 78x 78x 78x 78x 78x 78x   78x 404x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 12x 12x 12x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 10x 10x 10x 18x 2x 2x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 8x 8x 8x 8x 8x 8x 2x 2x 2x 2x 8x 8x 18x 18x 18x 18x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 18x 18x 72x 72x 72x 72x 72x 72x 72x 72x 6x 6x 72x 18x 18x 18x 18x 8x 6x 18x 2x 2x 2x 2x 2x 2x 2x 18x 18x 18x 17x 17x 17x 17x 17x 17x 17x 17x 17x 11x 18x 18x 18x 18x 17x 17x 17x 17x 17x 17x 18x 4x 4x 4x 4x 4x 2x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 17x 17x 17x 17x 13x 13x 6x 6x 6x   6x 6x 6x 6x 6x 6x 6x 2x 2x 2x   2x 6x 6x 2x 2x 6x 6x 13x 17x 17x 18x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 17x 17x 18x 404x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 4x 10x 2x 2x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 8x 8x 8x 8x 8x 8x 8x 7x 10x 1x 1x 1x 1x 8x 8x 4x 4x 2x 10x 2x 2x 2x 2x 8x 8x 8x 7x 10x 1x 1x 8x 8x 8x 10x 10x 1x 1x 1x 1x 1x                         8x 8x 8x 8x 8x 8x 8x 7x 7x 3x 3x 3x   3x 3x 2x 3x 1x 1x 1x 1x           1x 1x 1x 3x 3x 3x 3x 3x 3x 7x 8x 8x 10x 404x                                                                             404x 12x 12x               12x 12x 12x 12x 12x 12x           12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 11x 11x 12x 12x 12x 12x 12x                                                             12x 12x 12x 12x 12x 12x 12x 12x         12x 12x 12x 11x 11x 18x 18x 18x 18x 18x 8x 8x 8x 8x 8x 18x 11x 11x 11x 11x 11x 10x 10x 11x 12x 12x 12x 11x 1x 1x 1x 1x 12x 11x 11x 12x 12x                                                                   12x 12x 404x 30x 30x 30x 30x 30x 30x 30x 30x 2x 2x 2x 2x 2x 2x 2x               2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5x 5x 5x 2x 2x 2x 2x 8x 8x 8x 3x 3x 3x 3x 3x 3x 3x 3x 8x 5x 5x 8x 8x 2x 2x 2x 2x 30x 30x 139x 30x 30x 30x 30x 404x 1x 1x 1x 1x 404x                       404x 2x 2x 2x 2x 404x             404x 404x 404x 404x 404x 404x 404x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x   8x 8x 8x 8x 8x 5x 5x 3x 3x 3x 3x 8x 8x 8x 8x 8x 8x 8x 3x 3x 8x 8x 8x 8x 8x 8x 8x 8x                                                         8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 2x 2x 2x 2x 2x 2x 2x 2x 2x 51x 51x 14x 14x 14x 14x 14x 14x 51x 14x 14x 14x 14x 14x 32x 51x 15x 15x   51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x           11x       11x 11x 51x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 51x 51x 51x                                       11x 11x 11x 11x 11x 11x 11x 11x 11x 205x 205x 205x 11x 2x 2x 8x 8x 8x 8x 777x 777x 777x 777x 777x 777x 777x 777x 777x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 777x 8x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x               8x 8x 8x 8x 8x 8x                       8x 8x 8x 8x 8x 8x           8x 8x 1x 1x 1x 1x 1x 1x 15x 15x 15x 15x 15x 15x 15x 15x     15x 46x 46x 37x 46x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x                   83x 46x 15x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 154x 154x 585x 429x 429x 429x 429x 429x 392x 1x       429x 429x 429x 429x 321x 108x 429x 429x 429x 429x 429x 429x 429x 429x 429x         1x 1x 1x 1x 1x 1x 380x 380x 380x 380x 380x 380x 380x 380x 380x 370x 10x 380x 380x 380x 380x 380x 380x 380x 380x 380x 380x 380x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 138x 138x 138x 70x 138x 138x 94x 1x 1x 1x 1x 1x 1x 1x 1x 1x 415x 415x 415x 415x 275x 140x 415x 415x 415x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 327x 327x 327x 327x 327x 327x 327x 327x 327x 327x 325x 292x 292x                               11x 11x 11x 11x 11x 325x                     11x 11x 11x 11x 11x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 330x 330x 330x 330x 330x 330x 330x 330x 330x 330x 330x 330x 330x 330x 330x 2x 2x 330x 330x 330x 330x 330x 330x 330x 330x 330x 330x 330x 330x 330x 2x 330x 330x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x                                               2x 2x 2x 1x 1x 1x 1x 133x 133x 133x 133x 133x 133x 133x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 1x 1x 1x 1x 1x 1x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 92x 92x 92x 92x 92x 92x 92x 92x 92x 136x 136x 136x 92x 92x 92x  
import { ulid, withProgress } from '@feasibleone/blong-lib';
import {
    adapter,
    type Adapter,
    type Errors,
    type IErrorMap,
    type IHandlerProxy,
    type IMeta,
    type IObjectSchema,
    type Knex,
} from '@feasibleone/blong/types';
import KnexLib from 'knex';
import crypto from 'node:crypto';
import { type TFunction, type TObject } from 'typebox';
import { v4 } from 'uuid';
import yaml from 'yaml';
import { methodParts } from '../../lib.ts';
import {
    aclActionId,
    aclActionName,
    aclActorId,
    aclActorOf,
    aclAllowed,
    aclCheckSql,
    aclConfig,
    aclEntityOf,
    aclKeyColumn,
} from '../impl/acl.ts';
import { createPathRefresh, type IPathRefresh } from '../impl/pathRefresh.ts';
import {
    binaryToStr,
    discoverBinaryColumns,
    isBinaryColumn,
    prepareInputParams,
    prepareResultRow,
    prepareResultRows,
    strToBinary,
} from '../schema/knex/binary.ts';
import { ensureDatabase } from '../schema/knex/database.ts';
import {
    discoverDateColumns,
    prepareDateParams,
    type DateColumnMap,
} from '../schema/knex/datetime.ts';
import { wrapKnex } from '../schema/knex/json.ts';
import { normalizeOrderBy, orderableTerms } from '../schema/knex/order.ts';
import {
    cascadeDelete,
    countDependants,
    discoverRelations,
    type IRelationIndex,
} from '../schema/knex/relations.ts';
import {
    bindSyntheticHandlers,
    schemaProcedureBindImpl,
    schemaProcedureSyncImpl,
} from '../schema/knex/schemaMysql.ts';
import {
    attachHandlers,
    schemaTableConstraintSyncImpl,
    schemaTableSyncImpl,
} from '../schema/knex/schemaTable.ts';
import {
    type IAclTableSpec,
    type IConfig,
    type IEdgeBinding,
    type IKnexConfig,
    type ISchemaTable,
    type ITableConstraints,
} from '../schema/knex/types.ts';
import {
    methodId,
    propDefault,
    propType,
    readSqlFiles,
    snakeToCamel,
    type IColumnSchema,
} from '../schema/knex/utils.ts';
 
// Helpers to access the binary-column map stored on the adapter context.
// Cast through `any` because the base `ServerContext & BrowserContext` type
// doesn't include this runtime property.
function getBinaryCols(ctx: object): Map<string, Set<string>> | undefined {
    return (ctx as Record<string, unknown>).binaryColumns as Map<string, Set<string>> | undefined;
}
function setBinaryCols(ctx: object, map: Map<string, Set<string>>): void {
    (ctx as Record<string, unknown>).binaryColumns = map;
}
 
// Helpers to access the date-column map stored on the adapter context.
function getDateCols(ctx: object): DateColumnMap | undefined {
    return (ctx as Record<string, unknown>).dateColumns as DateColumnMap | undefined;
}
function setDateCols(ctx: object, map: DateColumnMap): void {
    (ctx as Record<string, unknown>).dateColumns = map;
}
 
/**
 * The params a statement binds for `table`: binary columns as Buffers, date
 * columns as the literals MySQL parses. Every write and every `where` goes
 * through here, so a handler that bypasses the schema codec (a permissive
 * validation override, a raw knex call in a realm) still stores a valid date
 * (@@F-697).
 */
function prepareParams(
    ctx: object,
    table: string,
    params: Record<string, unknown>,
): Record<string, unknown> {
    return prepareDateParams(
        prepareInputParams(params, getBinaryCols(ctx), table),
        getDateCols(ctx),
        table,
    );
}
 
// The foreign-key index, discovered once per connection.
function getRelations(ctx: object): IRelationIndex | undefined {
    return (ctx as Record<string, unknown>).relations as IRelationIndex | undefined;
}
function setRelations(ctx: object, index: IRelationIndex): void {
    (ctx as Record<string, unknown>).relations = index;
}
 
/** Whether a `core_resource` row exists for `id` — a shared PK may be one. */
async function existingResource(qb: Knex, id: Buffer): Promise<unknown> {
    const row = (await qb('core_resource').where('resourceId', id).first('resourceId')) as
        | {resourceId?: unknown}
        | undefined;
    return row?.resourceId;
}
 
/**
 * How a referring table reads in a message: `sport_conferral` in the `sport`
 * subject is a "conferral", `party_person` a "person".
 */
function dependantLabel(subject: string, table: string): string {
    const prefix = `${subject}_`;
    const name = table.startsWith(prefix) ? table.slice(prefix.length) : table;
    return name.replace(/_/g, ' ');
}
 
/** ER_ROW_IS_REFERENCED_2 — a parent row a foreign key still points at. */
function isForeignKeyRefusal(error: unknown): boolean {
    const {errno, code} = (error ?? {}) as {errno?: unknown; code?: unknown};
    return errno === 1451 || code === 'ER_ROW_IS_REFERENCED_2';
}
 
/** The shared rebuild coordinator this connection's edge writers defer through. */
function getPathRefresh(ctx: object | undefined): IPathRefresh | undefined {
    return (ctx as {pathRefresh?: IPathRefresh} | undefined)?.pathRefresh;
}
function setPathRefresh(ctx: object, coordinator: IPathRefresh): void {
    (ctx as {pathRefresh?: IPathRefresh}).pathRefresh = coordinator;
}
 
/**
 * The coordinator for `config`, created on first use.
 *
 * The schema is not always resolved when the adapter builds its context (which is
 * why `start` tries as well), so this is the place that guarantees one exists
 * before a seed merge asks for it.
 */
function ensurePathRefresh(config: {
    context?: object;
    schema?: {accessPathRefresh?: boolean};
}): IPathRefresh | undefined {
    const existing = getPathRefresh(config.context);
    if (existing) return existing;
    if (!config.schema?.accessPathRefresh || !config.context) return undefined;
    const created = createPathRefresh();
    setPathRefresh(config.context, created);
    return created;
}
 
export type { IConfig, ISchemaTable } from '../schema/knex/types.ts';
 
export const errorMap: IErrorMap = {
    // The method and the verb are in the *message*, not only in the log: this is the
    // one refusal a reader cannot attribute from the error name, and a caller who saw
    // it in a dialog spent a day looking for a reserved word that was not there
    // (`@@T-599` → `@@D-742`).
    'knex.generic': 'Knex Error: no operation for {operation} in {method}',
    'knex.invalid': 'Invalid Knex Operation',
    'knex.notFound': 'Knex Not Found',
    'knex.exists': 'Knex Exists',
    'knex.unique': 'Knex Unique',
    'knex.missingKey': 'Missing key value for {key}',
    // A delete that a foreign key refuses: the caller needs to know what still
    // points at the record, not the constraint name MySQL reported (`@@D-784`).
    'knex.referenced': 'Cannot delete this {object}: {references} still refer to it',
    // Record-level (ACL) refusals from the generic CRUD — the same `acl.*` family
    // the access realm declares, so a caller sees one error name wherever the
    // check runs (adapter or realm handler).
    'acl.denied': {message: 'Not allowed to access this record', statusCode: 403},
    'acl.scopeDenied': {
        message: 'Not allowed to create a record in this scope',
        statusCode: 403,
    },
    // A single-record read refuses with "not found" so it does not leak existence.
    'acl.notFound': {message: 'Record not found', statusCode: 404},
};
 
let _errors: Errors<typeof errorMap>;
 
/**
 * Log MySQL deadlock details (including the offending query) in dev mode.
 * Called from the `wrapKnex` `onDeadlock` hook for every query path through the
 * wrapped knex: CRUD builders, `raw()`/stored-procedure calls, schema sync and
 * seed merges, and queries inside `transaction()` blocks.
 */
export function logKnexDeadlock(
    config: {debug?: boolean; logLevel?: string},
    log: unknown,
    error: unknown,
): void {
    if (!config.debug && config.logLevel !== 'debug') return;
    const err = error as {
        message?: string;
        code?: string;
        errno?: number;
        sql?: string;
        sqlMessage?: string;
    };
    (log as {error?: (...args: unknown[]) => void})?.error?.(
        {
            err: err.message ?? err,
            code: err.code,
            errno: err.errno,
            sql: err.sql,
            sqlMessage: err.sqlMessage,
        },
        'knex deadlock',
    );
}
 
/**
 * Log transient MySQL connection-error details (including the offending query)
 * in dev mode. Called from the `wrapKnex` `onConnectionError` hook whenever a
 * query path through the wrapped knex fails with a fatal/connection error
 * (`PROTOCOL_CONNECTION_LOST` and similar) — whether or not retry is enabled.
 * This is the diagnostics breadcrumb for the intermittent CI connection drops:
 * it records which query failed and how the pool was doing at that moment.
 */
/**
 * Log a connection's own `error` event.
 *
 * Unconditionally, unlike {@link logKnexConnectionError}: an error on the *socket* is not a query the
 * pool will retry, it is a connection that died, and it is quiet only when nobody is watching —
 * which is exactly the case that cost a run its life (T-250).
 */
export function logKnexConnectionEvent(log: unknown, error: unknown): void {
    const err = error as {message?: string; code?: string; errno?: number};
    (log as {warn?: (...args: unknown[]) => void})?.warn?.(
        {err: err?.message ?? String(error), code: err?.code, errno: err?.errno},
        'a database connection failed; the pool opens another',
    );
}
 
/**
 * The pool options, with an `error` listener on every connection the pool creates.
 *
 * A connection's own `error` event belongs to the socket rather than to a call: mysql2 emits it
 * there, no promise ever rejects, and with no listener Node ends the process. That is how a
 * `getaddrinfo EAI_AGAIN` for a database name that did not resolve took a whole run down, from a
 * path documented as warn-and-continue (`createDatabase`'s catch never saw it — the event was on the
 * connection, not in the `await`). `afterCreate` is the one place that covers every connection the
 * pool will ever open, replacements included, and it runs the pool's own hook when one is configured
 * rather than replacing it.
 */
export const poolOptionsWithConnectionLogging = (
    configured: Record<string, unknown> | undefined,
    log: unknown,
): Record<string, unknown> => ({
    ...(configured ?? {}),
    afterCreate: (connection: unknown, done: (error?: Error) => void): void => {
        (connection as {on?: (event: string, listener: (error: unknown) => void) => void})?.on?.(
            'error',
            (error: unknown) => logKnexConnectionEvent(log, error),
        );
        const own = configured?.afterCreate;
        if (typeof own === 'function')
            (own as (c: unknown, d: (e?: Error) => void) => void)(connection, done);
        else done();
    },
});
 
export function logKnexConnectionError(
    config: {debug?: boolean; logLevel?: string},
    log: unknown,
    error: unknown,
): void {
    if (!config.debug && config.logLevel !== 'debug') return;
    const err = error as {
        message?: string;
        code?: string;
        errno?: number;
        fatal?: boolean;
        sql?: string;
        sqlMessage?: string;
    };
    (log as {error?: (...args: unknown[]) => void})?.error?.(
        {
            err: err.message ?? err,
            code: err.code,
            errno: err.errno,
            fatal: err.fatal,
            sql: err.sql,
            sqlMessage: err.sqlMessage,
        },
        'knex connection error',
    );
}
 
export default adapter<IConfig>(({utError, schema: objectSchema}) => {
    _errors ||= utError.register(errorMap);
 
    /**
     * Master-detail: tables of `subject` whose schema declares a FK constraint
     * to the master's PK (`${subject}.${object}.${keyName}`). These are the
     * detail tables of `${subject}.${object}` — `add`/`edit` persist sibling
     * detail arrays into them and `get` returns their rows alongside the master.
     */
    const detailTables = (subject: string, object: string, keyName: string) => {
        const masterRef = `${subject}.${object}.${keyName}`;
        const result: Array<{table: string; fkColumn: string}> = [];
        for (const [name, definition] of Object.entries(objectSchema[subject] ?? {})) {
            if (name === object) continue;
            const foreign = (
                definition as {
                    constraints?: {foreign?: Record<string, string>};
                }
            )?.constraints?.foreign;
            if (!foreign) continue;
            const fkColumn = Object.keys(foreign).find(col => foreign[col] === masterRef);
            if (fkColumn) result.push({table: `${subject}_${name}`, fkColumn});
        }
        return result;
    };
 
    return {
        activation: {
            default: {
                type: 'knex',
                knex: {
                    client: 'mysql2',
                    connection: {
                        host: 'localhost',
                    },
                },
            },
        },
        async start() {
            const knexConfig = this.config.knex;
            // `connect: false` also covers this: `ensureDatabase` opens a connection of its own.
            if (knexConfig.createDatabase && this.config.connect !== false) {
                try {
                    const {created, database} = await ensureDatabase(knexConfig.connection ?? {});
                    if (created) {
                        this.signal?.frameworkDbDatabaseCreated?.({database});
                    }
                } catch (error) {
                    // Warn-and-continue: schema sync will surface the real error.
                    this.signal?.frameworkDbDatabaseCreateFailed?.({
                        error: (error as {message?: string}).message ?? String(error),
                    });
                }
            }
            this.config.context = {
                queryBuilder: wrapKnex(
                    KnexLib({
                        ...this.config.knex,
                        pool: poolOptionsWithConnectionLogging(this.config.knex.pool, this.log),
                    } as IKnexConfig),
                    {
                        onDeadlock: error => logKnexDeadlock(this.config, this.log, error),
                        onConnectionError: error =>
                            logKnexConnectionError(this.config, this.log, error),
                        retry: this.config.knex.retry,
                    },
                ) as unknown as Knex,
                // The shared rebuild: every edge writer defers through it while the
                // seed phase is open, which is what keeps the rebuild behind the
                // last write (`pathRefresh.ts`, T-174). Only a schema that declares
                // the procedure gets one.
                ...(this.config.schema?.accessPathRefresh
                    ? {pathRefresh: createPathRefresh()}
                    : {}),
            };
            super.connect();
            return super.start();
        },
        async stop(...params: unknown[]) {
            let result;
            try {
                await this.config.context.queryBuilder?.destroy();
            } finally {
                this.config.context = {};
                result = await super.stop(...params);
            }
            return result;
        },
        /**
         * After the Knex pool is ready, optionally sync the declared schema
         * (tables + procedures) and bind all DB procedures as synthetic handlers.
         *
         * When `config.namespace` is set, CRUD handlers are also auto-bound for
         * every declared table, making them reachable via normal framework
         * dispatch without writing handler files.
         */
        async ready(this: Adapter<IConfig>) {
            const schema = this.config.schema;
            const knex = this.config.context?.queryBuilder;
            // A detached adapter (`connect: false`) loads and registers without touching the
            // database: the schema sync, the seeds, the procedure binding (which lists them from
            // `information_schema`), the path drain and the binary-column discovery are all queries,
            // and the key exists for a run that only plans — `k8s` derives a tree and exits, and the
            // database it would connect to is the deployment's, which in a first deployment or a CI
            // run does not exist yet (T-235). The *policy* is the owning realm's, not this adapter's:
            // see the `k8s` block in `core/blong-server/adapter/db.ts`.
            const connecting = this.config.connect !== false;
            const self = this as unknown as Record<string, unknown>;
 
            if (schema?.sync && knex && connecting) {
                // Sort tables by ascending `order` so FK dependencies are respected.
                const tables = Object.entries(schema.tables ?? {}).sort(([, a], [, b]) => {
                    const orderOf = (spec: number | ISchemaTable | TObject): number =>
                        typeof spec === 'number'
                            ? spec
                            : typeof spec === 'object' && spec !== null
                              ? ((spec as ISchemaTable).order ?? 0)
                              : 0;
                    return orderOf(a) - orderOf(b);
                });
                const dropColumns = schema.dropColumns ?? false;
                const tableDefs: Array<{tableName: string; definition: TObject}> = [];
                let syncedTables = 0;
                await withProgress(
                    this.log,
                    'schema table sync',
                    (async () => {
                        for (const [tableName, tableConfig] of tables) {
                            const [subject, object] = tableName.split('.');
                            const {definition} = resolveTableSpec(
                                objectSchema,
                                tableConfig,
                                subject,
                                object,
                            );
                            if (!definition) continue;
                            const sqlName = tableName.replaceAll('.', '_');
                            await schemaTableSyncImpl(knex, sqlName, definition, {
                                dropColumns,
                            });
                            tableDefs.push({tableName: sqlName, definition});
                            syncedTables += 1;
                        }
                    })(),
                    {
                        getProgress: () => ({done: syncedTables, total: tables.length}),
                    },
                );
 
                // Second pass: apply constraints (PKs, unique, indexes, FKs) now
                // that all tables exist.
                let syncedConstraints = 0;
                await withProgress(
                    this.log,
                    'schema constraint sync',
                    (async () => {
                        for (const {tableName: sqlName, definition} of tableDefs) {
                            // eslint-disable-next-line @typescript-eslint/no-explicit-any
                            const constraints = (definition as any).constraints as
                                | ITableConstraints
                                | undefined;
                            if (constraints) {
                                await schemaTableConstraintSyncImpl(knex, sqlName, constraints);
                                syncedConstraints += 1;
                            }
                        }
                    })(),
                    {
                        getProgress: () => ({done: syncedConstraints, total: tableDefs.length}),
                    },
                );
 
                // Collect procedure definitions: scanned folders first, then inline.
                const procedureDefs: Array<{name: string; sql: string}> = [];
                for (const folder of schema.procedurePaths ?? [])
                    procedureDefs.push(...readSqlFiles(folder));
                for (const [name, sql] of Object.entries(schema.procedures ?? {}))
                    procedureDefs.push({name, sql});
                if (procedureDefs.length > 0)
                    await withProgress(
                        this.log,
                        'schema procedure sync',
                        schemaProcedureSyncImpl(knex, procedureDefs),
                    );
            }
 
            if (schema && knex && connecting) {
                // Bind all DB procedures as synthetic handlers (skips `_`-prefixed).
                await bindSyntheticHandlers(self, knex);
            }
            if (schema?.seed && connecting) {
                // Seed merges write `core_triple` edges and skip the rebuild by
                // default (see the deferral in `core.triple.merge`): each of them
                // counts itself in a durable generation, and the batch ends with
                // ONE rebuild through the coordinator, which waits for this
                // process's writers first and then rebuilds while the counters say
                // the paths are behind.  That is what makes the rebuild follow the
                // last write — a rebuild per merge is neither wanted (redundant
                // full rebuilds, and the write-vs-rebuild deadlock between
                // concurrent merges) nor sufficient, because a rebuild that merely
                // happened to be last left edges out of the paths until the next
                // start (T-174).
                const pathRefresh = ensurePathRefresh(this.config);
                let currentSeed = '';
                const seedPhase = async () => {
                    await withProgress(
                        this.log,
                        'seed data',
                        (async () => {
                            // 1. Process production seeds (db.asset modules)
                            await processSeedAssets(
                                this,
                                /\.db\.asset$/,
                                name => (currentSeed = name),
                            );
                            // 2. Process test seeds (dbTest.asset modules) only when dbTest is enabled
                            if (schema?.dbTest) {
                                await processSeedAssets(
                                    this,
                                    /\.dbTest\.asset$/,
                                    name => (currentSeed = name),
                                );
                            }
                        })(),
                        {
                            getProgress: () => ({current: currentSeed || 'starting'}),
                        },
                    );
                };
                if (pathRefresh) await pathRefresh.defer(knex, seedPhase);
                else await seedPhase();
            }
            if (knex && connecting) {
                // Every start makes the flattened paths catch up, whatever left them
                // behind: a writer in another process that counted its edges and died
                // before the batch owed the rebuild, or a rebuild that could not
                // finish. The counters are durable and every rebuild publishes what
                // it covered, so this is a no-op after a clean shutdown and the one
                // repair a crash needs — without waiting for the next write, and
                // without assuming any ordering between processes.
                const pathRefresh = ensurePathRefresh(this.config);
                if (pathRefresh) await pathRefresh.drain(knex);
            }
 
            // Discover binary(16) columns for Buffer <-> string conversion, the
            // date columns whose ISO values MySQL will not parse as-is, and the
            // foreign keys a scan or a cascade walks.
            if (knex && connecting) {
                setBinaryCols(this.config.context, await discoverBinaryColumns(knex));
                setDateCols(this.config.context, await discoverDateColumns(knex));
                setRelations(this.config.context, await discoverRelations(knex));
            }
 
            return super.ready();
        },
        async configChanged(
            diff: Map<string, {prev: unknown; next: unknown}>,
            next: unknown,
            _prev: unknown,
        ) {
            const knexChanged = Array.from(diff.keys()).some(
                (key: string) =>
                    key === this.config.id + '.knex' || key.startsWith(this.config.id + '.knex.'),
            );
            if (!knexChanged) return;
            await this.config.context?.queryBuilder?.destroy();
            const newKnexConfig =
                ((next as Record<string, unknown>)?.[this.config.id] as Record<string, unknown>)?.[
                    'knex'
                ] ?? this.config.knex;
            this.config.knex = newKnexConfig as IKnexConfig;
            this.config.context = {
                queryBuilder: wrapKnex(KnexLib(newKnexConfig as object), {
                    onDeadlock: error => logKnexDeadlock(this.config, this.log, error),
                    onConnectionError: error =>
                        logKnexConnectionError(this.config, this.log, error),
                    retry: (newKnexConfig as IKnexConfig).retry ?? this.config.knex.retry,
                }) as unknown as Knex,
                ...(this.config.schema?.accessPathRefresh
                    ? {pathRefresh: createPathRefresh()}
                    : {}),
            };
        },
        async exec(
            params: {
                key?: string;
                select?: string;
                order?: Parameters<Knex.QueryInterface['orderBy']>[0];
                orderBy?: Parameters<Knex.QueryInterface['orderBy']>[0];
                limit?: number;
                offset?: number;
                paging?: {pageNumber: number; pageSize: number};
                filterBy?: Record<string, unknown>;
            } & Record<string, unknown>,
            $meta: IMeta,
        ) {
            const {method} = $meta;
            const [subject, object, operation] = method!.split('.');
            // The language this read answers in: a translated column is joined and
            // coalesced with the stored name, so no data is translated in the client.
            // `@@D-635`
            const language = requestLanguage($meta);
            // `{subject}.dropdown.list` — auto-bound dropdown lists for every
            // resource-backed table of the subject (see `_dropdownList`).
            if (object === 'dropdown' && operation === 'list') {
                return (
                    this as unknown as {
                        _dropdownList(s: string, meta?: IMeta): Promise<unknown>;
                    }
                )._dropdownList(subject, $meta);
            }
            // Structure discovery for the commander explorer:
            //   `{ns}.schema.list` — databases/schemas on the server
            //   `{ns}.table.list`  — tables in a schema (params.schema)
            if (object === 'schema' && operation === 'list') {
                const qb = this.config.context.queryBuilder!;
                const rows = await qb
                    .select('SCHEMA_NAME as schemaName')
                    .from('information_schema.schemata')
                    .orderBy('SCHEMA_NAME');
                return {items: rows as Array<{schemaName: string}>};
            }
            if (object === 'table' && operation === 'list') {
                const qb = this.config.context.queryBuilder!;
                // When no schema is given, scope to the adapter's own database so
                // the explorer lists the app's tables only — not every schema the
                // connection can see (information_schema, mysql, other realms' DBs).
                const schema = (params as Record<string, unknown>).schema as string | undefined;
                const database =
                    schema ??
                    (this.config.knex?.connection as {database?: string} | undefined)?.database;
                let query = qb
                    .select('TABLE_NAME as tableName', 'TABLE_TYPE as tableType')
                    .from('information_schema.tables')
                    .orderBy('TABLE_NAME');
                if (database) query = query.where('TABLE_SCHEMA', database);
                const rows = await query;
                // Drop leftover template/placeholder tables (e.g. `$subject_$object`
                // from an unresolved schema seed) — they are not real, queryable
                // tables and clicking them would surface a "table doesn't exist".
                const junk = /[\${}]/;
                // Only the tables this subject owns (`{subject}_*`) are reachable
                // via the generic `{subject}.{object}` CRUD triples; strip the
                // `{subject}_` prefix so `access.{tableName}.find` resolves to the
                // actual table (`access.user.find` → `access_user`), instead of
                // double-prefixing (`access.access_user.find` → `access_access_user`).
                const prefix = `${subject}_`;
                return {
                    items: (rows as Array<{tableName: string; tableType: string}>)
                        .filter(row => !junk.test(row.tableName))
                        .filter(row => row.tableName.startsWith(prefix))
                        .map(row => ({
                            tableName: row.tableName.slice(prefix.length),
                            tableType: row.tableType,
                        })),
                };
            }
            const table = `${subject}_${object}`;
            // ── Record-level (ACL) gates ──────────────────────────────────────
            // A table opts into record-level authorization with
            // `acl: {mode, scopes, addScope}`; everything below is a no-op for a
            // table that does not (`mode: 'none'`, the default) and for system
            // calls, which carry no `$meta.auth` (seed merges, internal dispatches).
            const aclCfg = aclConfig(this.config.schema?.acl);
            const aclActor = ($meta?.auth as {actorId?: string} | undefined)?.actorId;
            /** The guarded table's PK column (the record key). */
            const aclKeyName = (): string => aclKeyColumn(objectSchema, subject, object);
 
            /**
             * Gate a single-record operation (`get` / `edit` / `remove`).
             * Writes are refused with 403; a read refuses with 404 so it does not
             * leak the record's existence.
             */
            const aclCheckRecord = async (
                opts: IResolvedTableOptions,
                operation: string,
                recordId: Buffer | undefined,
            ): Promise<void> => {
                const mode = opts.acl.mode ?? 'none';
                if (mode === 'none' || !aclActor || !recordId) return;
                const actionId = await aclActionId(
                    this.config.context.queryBuilder!,
                    aclCfg,
                    method!,
                );
                if (!actionId) return; // the method is not an RBAC-managed action
                const allowed = await aclAllowed(this.config.context.queryBuilder!, {
                    cfg: aclCfg,
                    actorId: aclActorId(aclActor),
                    actionId,
                    recordRef: '?',
                    recordId,
                    scopes: opts.acl.scopes,
                    selfScope: opts.acl.selfScope,
                    mode,
                });
                if (allowed) return;
                throw this.error(
                    operation === 'get'
                        ? _errors['acl.notFound']({params: {reason: 'notFound'}})
                        : _errors['acl.denied']({params: {reason: 'denied'}}),
                    $meta,
                );
            };
 
            /**
             * Release the ACL rules that reference a guarded record about to be
             * removed.
             *
             * `access_acl` keeps foreign keys to `core_resource` on
             * `principalId`, `actionId` and `targetId`, so a rule left behind
             * makes the resource delete fail *after* the entity row is already
             * gone.  What remains is a resource-only ghost, and because
             * `core.resource.ensure` matches a record by name it then skips the
             * entity insert — the entity can never be created again.  A record
             * that is being removed can no longer be a principal, a target or an
             * action, so its rules go first.
             */
            const aclReleaseResource = async (
                opts: IResolvedTableOptions,
                recordId: Buffer,
                /**
                 * The transaction the removal runs in, when there is one, so the
                 * released rules and the deletes that follow them commit together.
                 */
                qb?: Knex,
            ): Promise<void> => {
                const mode = opts.acl.mode ?? 'none';
                if (mode === 'none') return;
                const target = qb ?? this.config.context.queryBuilder!;
                await target(aclCfg.table)
                    .where('principalId', recordId)
                    .orWhere('targetId', recordId)
                    .orWhere('actionId', recordId)
                    .del();
            };
 
            /**
             * The ACL predicate for a multi-record read, correlated on the guarded
             * table's key — applied to the query **before** paging so the result
             * set (and its total) only contains records the caller may see.
             */
            const aclReadFilter = async (
                opts: IResolvedTableOptions,
            ): Promise<{sql: string; bindings: unknown[]} | undefined> => {
                const mode = opts.acl.mode ?? 'none';
                if (mode === 'none' || !aclActor) return undefined;
                const actionId = await aclActionId(
                    this.config.context.queryBuilder!,
                    aclCfg,
                    method!,
                );
                if (!actionId) return undefined;
                return aclCheckSql({
                    cfg: aclCfg,
                    actorId: aclActorId(aclActor),
                    actionId,
                    recordRef: `${table}.${aclKeyName()}`,
                    scopes: opts.acl.scopes,
                    selfScope: opts.acl.selfScope,
                    mode,
                });
            };
 
            /**
             * Gate `add`, which has no record key yet: the check runs against the
             * scope named by the declaration (`addScope.column` on the payload, or
             * `addScope.predicate` reading the ids of the submitted scope edges).
             */
            const aclCheckAdd = async (
                opts: IResolvedTableOptions,
                cols: Record<string, unknown>,
                rest: Record<string, unknown>,
            ): Promise<void> => {
                const mode = opts.acl.mode ?? 'none';
                const addScope = opts.acl.addScope;
                if (mode === 'none' || !aclActor || !addScope) return;
                const ids: string[] = [];
                if (addScope.column && typeof cols[addScope.column] === 'string') {
                    ids.push(cols[addScope.column] as string);
                }
                if (addScope.predicate) {
                    // The payload array is keyed by the edge's object name
                    // (`unit`), which the declared binding owns.
                    const binding = opts.edges.find(e => e.predicate === addScope.predicate);
                    const detailObject =
                        binding?.object ?? addScope.predicate.replace(/^has/, '').toLowerCase();
                    for (const row of (rest[detailObject] as Array<Record<string, unknown>>) ??
                        []) {
                        // The scope id is the object's key in the edge row —
                        // `{unitId: '<base64>'}` for a `belongsTo` edge.
                        const found = Object.entries(row ?? {}).find(
                            ([key, value]) => key.endsWith('Id') && typeof value === 'string',
                        );
                        if (found) ids.push(found[1] as string);
                    }
                }
                if (!ids.length) return;
                const actionId = await aclActionId(
                    this.config.context.queryBuilder!,
                    aclCfg,
                    method!,
                );
                if (!actionId) return;
                const allowed = await aclAllowed(this.config.context.queryBuilder!, {
                    cfg: aclCfg,
                    actorId: aclActorId(aclActor),
                    actionId,
                    scopeIds: ids.map(id => strToBinary(id)),
                    mode,
                });
                if (!allowed) {
                    throw this.error(
                        _errors['acl.scopeDenied']({params: {reason: 'scopeDenied'}}),
                        $meta,
                    );
                }
            };
 
            switch (operation) {
                case 'get': {
                    const {select: _select, labels, ...where} = params;
                    const qb = this.config.context.queryBuilder!;
                    const binaryCols = getBinaryCols(this.config.context);
                    const opts = tableOptions(objectSchema, this.config, subject, object);
                    const keyName =
                        (
                            objectSchema[subject]?.[object] as
                                | {constraints?: {primaryKey?: string}}
                                | undefined
                        )?.constraints?.primaryKey ?? `${object}Id`;
                    const {
                        query: joined,
                        selections: labelSelections,
                        aliases: labelAliases,
                    } = attachLabelJoins(
                        qb(table),
                        qb.raw,
                        objectSchema,
                        this.config,
                        subject,
                        object,
                        table,
                        labels,
                        language,
                    );
                    // The row's own display name arrives with it, not from a second
                    // statement. @@D-619
                    const {query: named, selection: nameSelection} = attachResourceName(
                        joined,
                        qb.raw,
                        opts,
                        table,
                        keyName,
                        object,
                        language,
                    );
                    let query = named;
                    const joinSelections = nameSelection
                        ? [...labelSelections, nameSelection]
                        : labelSelections;
                    // A filter on a joined label names the alias that carries it, not
                    // the base table — filtering the Legal Name column of a club sent
                    // `where sport_club.legalName` and the database rejected it
                    // (`@@D-743`).
                    const qualify = (key: string) =>
                        labelAliases[key] ??
                        (joinSelections.length && !key.includes('.') ? `${table}.${key}` : key);
                    for (const [key, val] of Object.entries(where)) {
                        if (isBinaryColumn(binaryCols, table, key) && typeof val === 'string') {
                            query = query.where(qualify(key), strToBinary(val));
                        } else {
                            query = query.where(qualify(key), val as string | number);
                        }
                    }
                    // `*` would take the joined tables' columns too, so the base
                    // table is named once a join is in play.
                    const row = (await (
                        joinSelections.length
                            ? query.select(`${table}.*`, ...joinSelections)
                            : query
                    ).first()) as Record<string, unknown> | undefined;
                    // Capture the raw PK **before** `prepareResultRow` mutates
                    // the row in place (Buffers → base64 strings). The edge
                    // attachment needs the binary master key.
                    const masterKey = row?.[keyName];
                    // Record-level ACL: checked after the fetch so a `where` that
                    // does not carry the key (e.g. by email address) is covered too.
                    await aclCheckRecord(
                        opts,
                        'get',
                        Buffer.isBuffer(masterKey) ? masterKey : undefined,
                    );
                    const result: Record<string, unknown> = {
                        [object]: prepareResultRow(row, binaryCols, table),
                    };
                    // Master-detail: return each FK-constrained detail table's
                    // rows as sibling arrays (e.g. `line`, `payment`) so the
                    // Open form can render them alongside the master record.
                    if (masterKey !== undefined) {
                        for (const detail of detailTables(subject, object, keyName)) {
                            const detailBinaryCols = getBinaryCols(this.config.context);
                            const detailRows = (await qb(detail.table).where({
                                [detail.fkColumn]: masterKey,
                            })) as Record<string, unknown>[];
                            result[detail.table.slice(subject.length + 1)] = prepareResultRows(
                                detailRows,
                                detailBinaryCols,
                                detail.table,
                            );
                        }
                        // Graph-edge master-detail (declarative `edges`) — the
                        // rows live in `core_triple` keyed by the resource id.
                        // Only binary (resource-backed) master keys participate.
                        if (Buffer.isBuffer(masterKey)) {
                            for (const binding of opts.edges) {
                                if (!binding.table) continue; // reverse-only cleanup binding
                                const detailObject =
                                    binding.object ??
                                    binding.predicate.replace(/^has/, '').toLowerCase();
                                result[detailObject] = await attachEdgeRows(qb, masterKey, binding);
                            }
                        }
                    }
                    return result;
                }
                case 'find': {
                    const {
                        select = '*',
                        paging,
                        orderBy,
                        order = orderBy,
                        limit = paging?.pageSize,
                        offset = paging && (paging?.pageNumber - 1) * paging?.pageSize,
                        filterBy,
                        search,
                        labels,
                        ...where
                    } = params;
                    const qb = this.config.context.queryBuilder!;
                    const binaryCols = getBinaryCols(this.config.context);
                    const opts = tableOptions(objectSchema, this.config, subject, object);
                    const {
                        query: joined,
                        selections: labelSelections,
                        aliases: labelAliases,
                    } = attachLabelJoins(
                        qb(table),
                        qb.raw,
                        objectSchema,
                        this.config,
                        subject,
                        object,
                        table,
                        labels,
                        language,
                    );
                    // The row's own display name arrives with it, not from a second
                    // statement. The key is the table's declared one, so a table whose
                    // primary key is not `<object>Id` joins on the column it has.
                    // @@D-619
                    const {query: named, selection: nameSelection} = attachResourceName(
                        joined,
                        qb.raw,
                        opts,
                        table,
                        (
                            objectSchema[subject]?.[object] as
                                | {constraints?: {primaryKey?: string}}
                                | undefined
                        )?.constraints?.primaryKey ?? `${object}Id`,
                        object,
                        language,
                    );
                    const joinSelections = nameSelection
                        ? [...labelSelections, nameSelection]
                        : labelSelections;
                    let query = named;
                    // A join puts a second table in the statement, so the base
                    // table's own columns are named explicitly: `sportId` exists on
                    // both the row and its target, and an unqualified reference is
                    // ambiguous to MySQL. A column that is itself a label belongs to
                    // the join's alias, and filtering it by the name it is shown under
                    // is what a reader does (`@@D-743`).
                    const qualify = (key: string) =>
                        labelAliases[key] ??
                        (joinSelections.length && !key.includes('.') ? `${table}.${key}` : key);
                    for (const [key, val] of Object.entries({...filterBy, ...where})) {
                        if (isBinaryColumn(binaryCols, table, key) && typeof val === 'string') {
                            query = query.where(qualify(key), strToBinary(val));
                        } else {
                            query = query.where(qualify(key), val as string | number);
                        }
                    }
                    if (search) {
                        const stringFields = Object.entries(
                            objectSchema[subject]?.[object]?.properties ?? {},
                        )
                            .filter(([, prop]) => propType(prop) === 'string')
                            .map(([key]) => qualify(key));
                        if (stringFields.length > 0)
                            query = query.andWhere(function () {
                                for (const field of stringFields) {
                                    this.orWhereILike(field, `%${search}%`);
                                }
                            });
                    }
                    // The caller's order clause, folded into what knex reads: the
                    // browser sends `{field, dir}`, and knex formats a term it cannot
                    // read as the literal `undefined` — `order by `undefined`` and a
                    // MySQL error on every sorted column @@D-742.
                    //
                    // A term may also name something this table cannot order by: a
                    // model's display field, which the read joins in rather than
                    // stores (`targetName` on an ACL rule is built from the target's
                    // resource name), or a column from a schema that has moved. MySQL
                    // fails the whole read for it — `Unknown column 'targetName' in
                    // 'order clause'` — so an unorderable term is dropped and reported
                    // instead, and the page shows its rows rather than an error.
                    // @@D-828
                    const nameAlias = opts.resource
                        ? (opts.nameColumn ?? `${object}Name`)
                        : undefined;
                    const columnNames = Object.keys(
                        objectSchema[subject]?.[object]?.properties ?? {},
                    );
                    const {terms, dropped} = orderableTerms(
                        normalizeOrderBy(order),
                        nameAlias ? [...columnNames, nameAlias] : columnNames,
                        labelAliases,
                    );
                    for (const column of dropped)
                        this.signal?.frameworkDbOrderColumnIgnored?.({subject, object, column, table});
                    for (const term of terms) {
                        query = query.orderBy(term.column, term.order);
                    }
                    // Record-level ACL: the filter is applied before paging so both
                    // the page and its total only contain readable records.
                    const aclFilter = await aclReadFilter(opts);
                    if (aclFilter)
                        query = query.whereRaw(aclFilter.sql, aclFilter.bindings as never[]);
                    // The caller may ask for the size of the whole result as well as
                    // the page (`paging.count`). A paginator cannot open its forward
                    // arrows without it: a full page says nothing about what follows,
                    // so every page looked like the last one. Counted on the same
                    // statement — filters, search, joins and ACL all still apply — but
                    // before `limit`/`offset` and without the page's ordering.
                    let recordsTotal: number | undefined;
                    if ((paging as {count?: boolean} | undefined)?.count) {
                        const counted = (await query
                            .clone()
                            .clearSelect()
                            .clearOrder()
                            .count({total: '*'})
                            .first()) as {total?: number | string} | undefined;
                        recordsTotal = Number(counted?.total ?? 0);
                    }
                    if (limit) query = query.limit(limit);
                    if (offset) query = query.offset(offset);
                    const rows = (await (joinSelections.length
                        ? query.select([
                              ...(select === '*' ? [`${table}.*`] : [select]),
                              ...joinSelections,
                          ])
                        : query.select(select))) as Record<string, unknown>[];
                    const page = prepareResultRows(rows, binaryCols, table);
                    // Two shapes, chosen by the caller: a bare page, which is what
                    // every caller that did not ask for a count reads, and the page
                    // with its total under the key the list widgets default to
                    // (`resultSet`).
                    return recordsTotal === undefined
                        ? page
                        : {items: page, pagination: {recordsTotal}};
                }
                case 'add': {
                    const {
                        key: keyName = `${object}Id`,
                        [object]: columns,
                        resourceName,
                        ...rest
                    } = params;
                    // Resolve the table definition from the declarative
                    // `schema.tables` entry first (falling back to the realm
                    // `objectSchema`), so namespace-scoped methods (e.g.
                    // `sql.person.add`) find their properties/FK constraints
                    // when the definition lives in the adapter table config.
                    const definition = resolveTableSpec(
                        objectSchema,
                        this.config.schema?.tables?.[`${subject}.${object}`],
                        subject,
                        object,
                    ).definition as unknown as Record<string, unknown> | undefined;
                    const properties = definition?.properties as
                        | Record<string, IColumnSchema>
                        | undefined;
                    const foreignKeys = (
                        definition?.constraints as
                            | Record<string, Record<string, string>>
                            | undefined
                    )?.foreign;
                    const binaryCols = getBinaryCols(this.config.context);
                    const opts = tableOptions(objectSchema, this.config, subject, object);
                    const cols = columns as Record<string, unknown>;
                    // Resource-backed: the display name lives in
                    // `core_resource.resourceName`.  By default it is the virtual
                    // `${object}Name` field — captured for the resource row and
                    // excluded from the table insert.  A table declaring
                    // `resource: {nameColumn}` names the resource from that real
                    // column instead, which therefore stays in the insert.
                    const nameColValue = opts.resource
                        ? ((opts.nameColumn ? cols[opts.nameColumn] : cols[`${object}Name`]) as
                              | string
                              | undefined)
                        : undefined;
                    if (opts.resource && !opts.nameColumn) {
                        delete cols[`${object}Name`];
                    }
                    // Generate real PKs server-side for id columns that carry a
                    // 'uuid' / 'ulid' default marker (`type.uuid()` / `type.ulid()`
                    // are submitted as the literal placeholder) OR whose not-null
                    // id the caller did not supply on a resource-backed table
                    // (PK is a FK to `core.resource`, e.g. `type.uidNotNull()`).
                    // Track the generated key so the inserted row can be selected
                    // back by it.
                    let generatedKey: string | undefined;
                    // The whole create is ONE transaction: the type row and the
                    // resource row it ensures, the entity row, its detail rows and its
                    // graph edges (whose own sync already runs in one).  Split across
                    // autocommit statements, a failure left a `core_resource` row with
                    // no entity behind it — the ghost resource of T-102, whose name is
                    // then taken for good — or a record the caller submitted without
                    // the details and edges that were part of it.
                    return await this.config.context.queryBuilder!.transaction(async trx => {
                        const qb = trx;
                        // Ensure a `core_type` row exists (mirrors core.resource.ensure)
                        // so resource-backed inserts always get a type.
                        const ensureType = async (
                            typeAlias: string,
                        ): Promise<number | undefined> => {
                            const existing = await qb('core_type')
                                .where({typeAlias})
                                .first('typeId');
                            if (existing) return existing.typeId as number;
                            await qb('core_type').insert({typeAlias}).onConflict().ignore();
                            const inserted = await qb('core_type')
                                .where({typeAlias})
                                .first('typeId');
                            return inserted ? (inserted.typeId as number) : undefined;
                        };
                        // Create the matching `core_resource` row for a generated
                        // resource-backed PK.  The name is the entity's display label
                        // in `{subject}.dropdown.list`.
                        const ensureResourceRow = async (
                            idStr: string,
                            resourceKeyCol: string,
                        ): Promise<void> => {
                            const typeAlias = `${subject}.${object}`;
                            const typeId = await ensureType(typeAlias);
                            if (!typeId) return;
                            const name =
                                (typeof resourceName === 'string' && resourceName) ||
                                nameColValue ||
                                `${subject}.${object}.${resourceKeyCol}`;
                            await qb('core_resource')
                                .insert({
                                    resourceId: strToBinary(idStr),
                                    resourceName: name,
                                    typeId,
                                })
                                .onConflict()
                                .ignore();
                        };
                        // 1) Literal 'uuid' / 'ulid' default markers on id columns.
                        for (const colName of Object.keys(cols)) {
                            if (cols[colName] !== 'uuid' && cols[colName] !== 'ulid') continue;
                            const prop = properties?.[colName];
                            const marker = cols[colName] as 'uuid' | 'ulid';
                            if (!prop || propDefault(prop) !== marker) continue;
                            const idStr = marker === 'ulid' ? ulid() : crypto.randomUUID();
                            cols[colName] = strToBinary(idStr);
                            generatedKey = idStr;
                            if (foreignKeys?.[colName] === 'core.resource.resourceId') {
                                await ensureResourceRow(idStr, colName);
                            }
                        }
                        // 2) Resource-backed not-null PK (no default marker, e.g.
                        //    `type.uidNotNull()`) with no key supplied by the caller.
                        if (
                            !generatedKey &&
                            cols[keyName] == null &&
                            foreignKeys?.[keyName] === 'core.resource.resourceId'
                        ) {
                            const pkProp = properties?.[keyName];
                            if (!pkProp || !propDefault(pkProp)) {
                                generatedKey = crypto.randomUUID();
                                cols[keyName] = strToBinary(generatedKey);
                                await ensureResourceRow(generatedKey, keyName);
                            }
                        }
                        // Record-level ACL: `add` has no record key yet, so the scope
                        // declared by `addScope` decides whether it may be created.
                        await aclCheckAdd(opts, cols, rest);
                        // Convert any string values for binary columns to Buffer,
                        // and ISO date strings to the literals MySQL stores.
                        const insertCols = prepareParams(this.config.context, table, cols);
                        const inserted = await qb(table).insert(insertCols);
                        // Select the inserted row back by the PK. Prefer the explicit
                        // key value (post-conversion) when the caller supplied one
                        // (e.g. a real ULID/UUID string) — `insertId` only works for
                        // auto-increment PKs and is 0 for a binary-PK table.
                        const masterKey = generatedKey
                            ? strToBinary(generatedKey)
                            : ((insertCols[keyName] as Buffer | string | undefined) ?? inserted[0]);
                        const row = (await qb(table)
                            .where({[keyName]: masterKey})
                            .first()) as Record<string, unknown>;
                        const result: Record<string, unknown> = {
                            [object]: prepareResultRow(row, binaryCols, table),
                        };
                        // Master-detail: persist each sibling detail array (a param
                        // whose key names a FK-constrained detail table) with the
                        // master's key as the FK column, and return the created rows.
                        for (const [detailName, detailRows] of Object.entries(rest)) {
                            if (!Array.isArray(detailRows)) continue;
                            const detail = detailTables(subject, object, keyName).find(
                                d => d.table === `${subject}_${detailName}`,
                            );
                            if (!detail) continue;
                            for (const detailRow of detailRows) {
                                await qb(detail.table).insert(
                                    prepareParams(this.config.context, detail.table, {
                                        ...(detailRow as Record<string, unknown>),
                                        [detail.fkColumn]: masterKey,
                                    }),
                                );
                            }
                            const createdRows = (await qb(detail.table).where({
                                [detail.fkColumn]: masterKey,
                            })) as Record<string, unknown>[];
                            result[detailName] = prepareResultRows(
                                createdRows,
                                getBinaryCols(this.config.context),
                                detail.table,
                            );
                        }
                        // Graph-edge master-detail: persist each declared edge from
                        // its sibling array (filtering `granted !== false` when the
                        // binding uses the pivot convention) and attach the rows.
                        if (Buffer.isBuffer(masterKey)) {
                            const opts = tableOptions(objectSchema, this.config, subject, object);
                            for (const binding of opts.edges) {
                                if (!binding.table) continue; // reverse-only cleanup binding
                                const detailObject =
                                    binding.object ??
                                    binding.predicate.replace(/^has/, '').toLowerCase();
                                const edgeRows = Array.isArray(rest[detailObject])
                                    ? (rest[detailObject] as Array<Record<string, unknown>>)
                                    : [];
                                const objectKey = binding.objectKey ?? `${detailObject}Id`;
                                const ids = edgeRows
                                    .filter(r => (binding.granted ? r.granted !== false : true))
                                    .map(r => {
                                        const id = r[objectKey];
                                        return typeof id === 'string'
                                            ? strToBinary(id).toString('hex')
                                            : undefined;
                                    })
                                    .filter((x): x is string => !!x);
                                if (ids.length) {
                                    await syncGraphEdges(qb, masterKey, binding.predicate, ids);
                                }
                                result[detailObject] = await attachEdgeRows(qb, masterKey, binding);
                            }
                        }
                        // Resource-backed: join the display name onto the master so
                        // the caller sees `${object}Name` in the created row.
                        if (opts.resource && !opts.nameColumn && Buffer.isBuffer(masterKey)) {
                            const masterRow = result[object] as Record<string, unknown> | undefined;
                            if (masterRow && typeof masterRow[`${object}Id`] === 'string') {
                                const [joined] = await joinResourceNames(
                                    qb,
                                    [masterRow],
                                    `${object}Id`,
                                    `${object}Name`,
                                );
                                result[object] = joined;
                            }
                        }
                        return result;
                    });
                }
                case 'edit': {
                    const {key: keyName = `${object}Id`, [object]: columns, ...rest} = params;
                    const binaryCols = getBinaryCols(this.config.context);
                    const opts = tableOptions(objectSchema, this.config, subject, object);
                    const cols = columns as Record<string, unknown>;
                    const {[keyName]: key, ...update} = cols as Record<string, unknown>;
                    const isBinaryKey =
                        isBinaryColumn(binaryCols, table, keyName) && typeof key === 'string';
                    // Resource-backed: the display name lives in
                    // `core_resource.resourceName`, so a change to the display
                    // field renames that row.  With `resource: {nameColumn}` the
                    // real column is updated as well (it stays in the update).
                    const nameField = opts.nameColumn ?? `${object}Name`;
                    const resourceName = opts.resource
                        ? (update[nameField] as string | undefined)
                        : undefined;
                    if (opts.resource && !opts.nameColumn) {
                        delete update[`${object}Name`];
                    }
                    // The whole edit is ONE transaction: the entity row, the resource
                    // rename, the detail rows and the graph edges (whose own sync
                    // already runs in one).  A failure between those statements left
                    // the caller's edit half-applied — a renamed record whose
                    // assignments were never changed, or a detail array deleted and
                    // never replaced.
                    return await this.config.context.queryBuilder!.transaction(async trx => {
                        const qb = trx;
                        // Record-level ACL: refuse an edit of a record the caller may
                        // not act on, before anything is written.
                        await aclCheckRecord(
                            opts,
                            'edit',
                            isBinaryKey ? strToBinary(key) : undefined,
                        );
                        // Convert any string values for binary columns to Buffer (the
                        // form round-trips them as base64 strings returned by `get`),
                        // and ISO date strings to the literals MySQL stores.
                        const preparedUpdate = prepareParams(this.config.context, table, update);
                        // Update using Buffer for binary keys
                        if (isBinaryKey) {
                            await qb(table).where(keyName, strToBinary(key)).update(preparedUpdate);
                        } else {
                            await qb(table)
                                .where({[keyName]: key})
                                .update(preparedUpdate);
                        }
                        if (
                            opts.resource &&
                            isBinaryKey &&
                            typeof resourceName === 'string' &&
                            resourceName
                        ) {
                            await qb('core_resource')
                                .where('resourceId', strToBinary(key))
                                .update({resourceName});
                        }
                        // Select back with Buffer → base64 conversion
                        let editQuery = qb(table);
                        if (isBinaryKey) {
                            editQuery = editQuery.where(keyName, strToBinary(key));
                        } else {
                            editQuery = editQuery.where({[keyName]: key});
                        }
                        const editRow = (await editQuery.first()) as Record<string, unknown>;
                        // Master-detail: replace each sibling detail array's rows for
                        // this master (delete existing, re-insert the payload rows).
                        const detailKey = isBinaryKey ? strToBinary(key) : key;
                        for (const [detailName, detailRows] of Object.entries(rest)) {
                            if (!Array.isArray(detailRows)) continue;
                            const detail = detailTables(subject, object, keyName).find(
                                d => d.table === `${subject}_${detailName}`,
                            );
                            if (!detail) continue;
                            await qb(detail.table)
                                .where({[detail.fkColumn]: detailKey})
                                .del();
                            for (const detailRow of detailRows) {
                                await qb(detail.table).insert(
                                    prepareParams(this.config.context, detail.table, {
                                        ...(detailRow as Record<string, unknown>),
                                        [detail.fkColumn]: detailKey,
                                    }),
                                );
                            }
                        }
                        const result: Record<string, unknown> = {
                            [object]: prepareResultRow(editRow, binaryCols, table),
                        };
                        // Graph-edge master-detail: bring each declared edge in line
                        // with the submitted sibling array (when present) and re-attach
                        // the fresh edge rows to the result.
                        if (isBinaryKey) {
                            const masterKeyBuf = strToBinary(key);
                            for (const binding of opts.edges) {
                                if (!binding.table) continue; // reverse-only cleanup binding
                                const detailObject =
                                    binding.object ??
                                    binding.predicate.replace(/^has/, '').toLowerCase();
                                const edgeRows = Array.isArray(rest[detailObject])
                                    ? (rest[detailObject] as Array<Record<string, unknown>>)
                                    : undefined;
                                if (edgeRows !== undefined) {
                                    const objectKey = binding.objectKey ?? `${detailObject}Id`;
                                    const ids = edgeRows
                                        .filter(r => (binding.granted ? r.granted !== false : true))
                                        .map(r => {
                                            const id = r[objectKey];
                                            return typeof id === 'string'
                                                ? strToBinary(id).toString('hex')
                                                : undefined;
                                        })
                                        .filter((x): x is string => !!x);
                                    await syncGraphEdges(qb, masterKeyBuf, binding.predicate, ids);
                                }
                                result[detailObject] = await attachEdgeRows(
                                    qb,
                                    masterKeyBuf,
                                    binding,
                                );
                            }
                        }
                        return result;
                    });
                }
                case 'scan': {
                    // `{subject}.{object}.scan` — what still refers to this record.
                    // The delete modes a model offers are built on this answer:
                    // `block` reports it as a refusal, `prompt` asks for it before a
                    // cascade, and both name the kinds in the operator's terms
                    // (`@@D-784`).
                    const {key: keyName = `${object}Id`, [keyName]: key} = params;
                    if (!(keyName in params)) {
                        throw this.error(
                            _errors['knex.missingKey']({params: {key: keyName}}),
                            $meta,
                        );
                    }
                    const binaryCols = getBinaryCols(this.config.context);
                    const isBinaryKey =
                        isBinaryColumn(binaryCols, table, keyName) && typeof key === 'string';
                    const masterKey = isBinaryKey ? strToBinary(key as string) : key;
                    const relations = getRelations(this.config.context);
                    const qb = this.config.context.queryBuilder!;
                    if (!relations || masterKey === undefined || masterKey === null) {
                        return {dependants: [], total: 0};
                    }
                    const resourceId = Buffer.isBuffer(masterKey)
                        ? await existingResource(qb, masterKey)
                        : undefined;
                    const dependants = await countDependants(qb, relations, {
                        table,
                        key: keyName,
                        value: masterKey,
                        resourceId,
                    });
                    return {
                        dependants: dependants.map(entry => ({
                            ...entry,
                            label: dependantLabel(subject, entry.table),
                        })),
                        total: dependants.reduce((sum, entry) => sum + entry.count, 0),
                    };
                }
                case 'remove': {
                    const {key: keyName = `${object}Id`, [keyName]: key} = params;
                    if (!(keyName in params)) {
                        // `params` is the map the factory interpolates (`{key}`), not a
                        // property on the error: passing `{key}` rendered `?key?`.
                        throw this.error(
                            _errors['knex.missingKey']({params: {key: keyName}}),
                            $meta,
                        );
                    }
                    const binaryCols = getBinaryCols(this.config.context);
                    const opts = tableOptions(objectSchema, this.config, subject, object);
                    const isBinaryKey =
                        isBinaryColumn(binaryCols, table, keyName) && typeof key === 'string';
                    const masterKey = isBinaryKey ? strToBinary(key as string) : key;
                    if (!masterKey) {
                        throw this.error(
                            _errors['knex.missingKey']({params: {key: keyName}}),
                            $meta,
                        );
                    }
                    // `cascade` is the caller's answer to the question `scan`
                    // answers: it takes the referring rows with it instead of
                    // refusing the delete.
                    const cascade = params.cascade === true;
                    const qb = this.config.context.queryBuilder!;
                    // Record-level ACL: refuse to delete a record the caller may
                    // not act on before anything is touched.
                    await aclCheckRecord(
                        opts,
                        'remove',
                        Buffer.isBuffer(masterKey) ? masterKey : undefined,
                    );
                    // The removal itself is ONE transaction, because a request must
                    // not half-apply: the rules that reference the record, its
                    // FK-constrained detail rows, its graph edges, the rebuild that
                    // follows them, the entity row and at last the resource row.
                    // Split across autocommit statements, a failure anywhere left the
                    // flattened paths granting what the graph no longer held — the
                    // entity row and the resource row disagreeing about whether the
                    // record exists, with nothing recording the difference.
                    return await qb.transaction(async trx => {
                        try {
                            // Release the rules that reference the record first, before the
                            // entity row is deleted (see `aclReleaseResource`).
                            if (Buffer.isBuffer(masterKey)) {
                                await aclReleaseResource(opts, masterKey, trx);
                            }
                            // Cascade: the caller answered `scan` and asked for the
                            // referring rows to go too. The walk deletes them deepest
                            // first, so the entity row below is not blocked by a
                            // constraint the caller has already agreed to break.
                            if (cascade) {
                                const relations = getRelations(this.config.context);
                                if (relations) {
                                    const roots = [{table, column: keyName, value: masterKey}];
                                    if (
                                        Buffer.isBuffer(masterKey) &&
                                        params.cascadeResource !== false &&
                                        (await existingResource(trx, masterKey))
                                    ) {
                                        roots.push({
                                            table: 'core_resource',
                                            column: 'resourceId',
                                            value: masterKey,
                                        });
                                    }
                                    const result = await cascadeDelete(trx, relations, roots);
                                    // A cascaded child that was resource-backed left its
                                    // resource row behind; drop it once nothing points at
                                    // it any more. A resource another row still needs is
                                    // left alone rather than failing the delete.
                                    for (const resourceId of result.resources) {
                                        try {
                                            await trx('core_resource')
                                                .where('resourceId', resourceId as never)
                                                .del();
                                        } catch {
                                            // Still referenced: keep it.
                                        }
                                    }
                                }
                            }
                            // Master-detail: delete each FK-constrained detail table's
                            // rows for this master before the master row, so a
                            // non-cascading FK does not block the delete. A cascade has
                            // already removed them — and it had to run first, because a
                            // detail that has children of its own (an edition with a
                            // participation) cannot be deleted before them: this delete
                            // alone is refused by the grandchild (@@F-699).
                            for (const detail of detailTables(subject, object, keyName)) {
                                await trx(detail.table)
                                    .where({[detail.fkColumn]: masterKey})
                                    .del();
                            }
                            // Graph edges: delete the subject's own edges and (when the
                            // binding declares `reverse`) the edges pointing AT it.
                            if (Buffer.isBuffer(masterKey)) {
                                const subjectBuf = masterKey as Buffer;
                                for (const binding of opts.edges) {
                                    await trx('core_triple')
                                        .where('subjectId', subjectBuf)
                                        .where('predicateName', binding.predicate)
                                        .del();
                                    if (binding.reverse) {
                                        await trx('core_triple')
                                            .where('objectId', subjectBuf)
                                            .where('predicateName', binding.predicate)
                                            .del();
                                    }
                                }
                                // The rebuild follows the edge deletes, and it has to run
                                // before the resource row goes: `core_path` holds a
                                // foreign key to `core_resource`, and the rebuild is what
                                // drops the paths that pointed at this record.
                                if (opts.edges.length) {
                                    await trx.raw('CALL access_pathRefresh()');
                                }
                            }
                            // Entity row first — its PK is a FK to `core_resource`, so
                            // the resource row must be deleted only after the entity row.
                            const removed = isBinaryKey
                                ? await trx(table).where(keyName, masterKey).del()
                                : await trx(table)
                                      .where({[keyName]: key})
                                      .del();
                            // Resource-backed: delete the `core_resource` row last.
                            if (Buffer.isBuffer(masterKey) && opts.resource) {
                                await trx('core_resource').where('resourceId', masterKey).del();
                            }
                            return removed;
                        } catch (error) {
                            // MySQL names a constraint, not a kind of record. `scan`
                            // knows which tables still point here, so a refused delete
                            // is answered in the caller's vocabulary — wherever in the
                            // transaction the refusal came from (`@@D-784`).
                            if (!isForeignKeyRefusal(error)) throw error;
                            const relations = getRelations(this.config.context);
                            const dependants = relations
                                ? await countDependants(trx, relations, {
                                      table,
                                      key: keyName,
                                      value: masterKey,
                                      resourceId: Buffer.isBuffer(masterKey)
                                          ? await existingResource(trx, masterKey)
                                          : undefined,
                                  })
                                : [];
                            throw this.error(
                                _errors['knex.referenced']({
                                    params: {
                                        object,
                                        references: dependants.length
                                            ? dependants
                                                  .map(
                                                      entry =>
                                                          `${entry.count} ${dependantLabel(subject, entry.table)}`,
                                                  )
                                                  .join(', ')
                                            : 'other records',
                                    },
                                }),
                                $meta,
                            );
                        }
                    });
                }
                case 'merge': {
                    const {key = `${object}Id`, [object]: objectRows, resourceType} = params;
                    let rows = objectRows as Array<{[key]: string}>;
                    // One transaction, for the same reason the add and edit cases
                    // have one: the resources this merge creates and the rows it
                    // writes commit together or not at all.
                    return await this.config.context.queryBuilder!.transaction(async trx => {
                        const qb = trx;
                        if (resourceType) {
                            // create or lookup resourceId for each row based on its `name` property
                            const typeId = (
                                await qb('core_type')
                                    .where({typeAlias: resourceType})
                                    .first('typeId')
                            )?.typeId;
                            if (!typeId) {
                                throw this.error(
                                    _errors['knex.notFound']({
                                        message: `Resource type not found: ${resourceType}`,
                                    }),
                                    $meta,
                                );
                            }
                            const resources = (
                                await qb('core_resource')
                                    .join('core_type', 'core_resource.typeId', 'core_type.typeId')
                                    .where('core_type.typeAlias', resourceType)
                                    .whereIn(
                                        'core_resource.resourceName',
                                        rows.map(r => r.name).filter(Boolean),
                                    )
                                    .select('resourceId', 'resourceName')
                            ).reduce(
                                (acc, row) => {
                                    acc[row.resourceName] = row.resourceId;
                                    return acc;
                                },
                                {} as Record<string, string>,
                            );
                            const newResources = [];
                            for (const row of rows) {
                                if (row.name) {
                                    let resourceId = resources[row.name];
                                    if (!resourceId) {
                                        resourceId = Buffer.alloc(16);
                                        v4(undefined, resourceId);
                                        newResources.push({
                                            resourceId,
                                            resourceName: row.name,
                                            typeId,
                                        });
                                        row[key] = resourceId;
                                    } else {
                                        row[key] = resourceId;
                                    }
                                }
                            }
                            if (newResources.length > 0)
                                await qb('core_resource').insert(newResources);
                            rows = rows.map(({name: _, ...row}) => row);
                        }
                        // Convert string values for binary columns to Buffer before insert
                        const preparedRows = rows.map(row =>
                            prepareParams(this.config.context, table, row),
                        );
                        return qb(table).insert(preparedRows).onConflict(key).merge();
                    });
                }
                case 'insert': {
                    return this.config.context.queryBuilder!(table).insert(
                        prepareParams(this.config.context, table, params),
                    );
                }
                case 'update': {
                    const {select: _select, ...where} = params;
                    return this.config.context.queryBuilder!(table)
                        .where(
                            prepareParams(
                                this.config.context,
                                table,
                                where as Record<string, unknown>,
                            ),
                        )
                        .update(_select);
                }
                case 'delete': {
                    return this.config.context.queryBuilder!(table)
                        .where(prepareParams(this.config.context, table, params))
                        .del();
                }
            }
            // The one throw in this switch that a reader cannot attribute from the
            // error: the method was routed here, so its verb looked like CRUD to the
            // gateway, and no case above claimed it. Naming the verb in the log is
            // what turns "Knex Error" into a diagnosis — without it the only trace
            // is the dialog a caller sees @@D-742.
            this.signal?.frameworkDbOperationMissing?.({operation, method: method ?? 'unknown'});
            throw this.error(
                _errors['knex.generic']({
                    params: {method: method ?? '(none)', operation: operation ?? '(none)'},
                }),
                $meta,
            );
        },
        /**
         * `{subject}.dropdown.list` — produce `{value, label}` pairs for every
         * resource-backed table of the subject.  A table is resource-backed when
         * its PK (or any column) is a FK to `core.resource.resourceId`.
         *
         * Entries are resolved directly from `core_resource` (joined with
         * `core_type` by `typeAlias = ${subject}.${object}`), so every realm gets
         * dropdowns for free, matching the `blong-mock` `{subject}.dropdown.list`
         * shape (`{value: base64, label: resourceName}`).
         *
         * Per-table overrides are declared via the `dropdown` option on the table
         * spec (see `ISchemaTable`): `typeAlias`, `joinTable`, `joinColumn`,
         * `labelColumn`.
         */
        /**
         * Evaluate the record-level ACL for one record — or for one or more
         * scopes, which is what `add` needs (the record has no key yet).
         *
         * Realm handlers cannot import this module (the runtime is not a library
         * dependency of a realm), so they reach it through the port —
         * `await this.aclCheck({recordId}, $meta)` — while the generic CRUD calls
         * the same helper directly.
         *
         * `guarded: false` means the table does not opt into the ACL, or the
         * method is not an RBAC-managed action at all: the caller is allowed.
         * `actionId` (a raw Buffer — this call never crosses a realm boundary)
         * and `predicate` are returned even for an unguarded entity, so a caller
         * can reuse them for its own live-permission check.
         */
        async aclCheck(
            params: {
                /** Guarded entity as `subject.object` — defaults to the entity of `method`. */
                entity?: string;
                /** The method whose action is checked — defaults to `$meta.method`. */
                method?: string;
                /** Binary record key as a base64/hex string. */
                recordId?: string;
                /** Scope ids (used by `add`) as base64/hex strings. */
                scopeIds?: string[];
                /** Actor id override — defaults to `$meta.auth.actorId`. */
                actorId?: string;
            },
            $meta?: IMeta,
        ): Promise<{
            guarded: boolean;
            allowed: boolean;
            entity?: string;
            predicate?: string;
            actionId?: Buffer;
        }> {
            const qb = this.config?.context?.queryBuilder;
            const method = params.method ?? $meta?.method;
            const actor = params.actorId ?? aclActorOf($meta);
            if (!qb || !method) return {guarded: false, allowed: true};
            const entity = params.entity ?? aclEntityOf(method);
            const predicate = methodParts(method).split('.').pop();
            const [subject, object] = entity ? entity.split('.') : [undefined, undefined];
            const spec =
                subject && object
                    ? resolveTableSpec(
                          objectSchema,
                          this.config?.schema?.tables?.[`${subject}.${object}`],
                          subject,
                          object,
                      ).acl
                    : undefined;
            const cfg = aclConfig(this.config?.schema?.acl);
            const actionId = await aclActionId(qb, cfg, method);
            const mode = spec?.mode ?? 'none';
            const verdict = {entity, predicate, actionId};
            if (!actionId || mode === 'none' || !actor) {
                return {guarded: false, allowed: true, ...verdict};
            }
            const allowed = await aclAllowed(qb, {
                cfg,
                actionId,
                actorId: aclActorId(actor),
                recordRef: params.recordId ? '?' : undefined,
                recordId: params.recordId ? strToBinary(params.recordId) : undefined,
                scopeIds: params.scopeIds?.map(id => strToBinary(id)),
                scopes: spec?.scopes,
                selfScope: spec?.selfScope,
                mode,
            });
            return {guarded: true, allowed, ...verdict};
        },
 
        /**
         * The ACL predicate that filters a whole result set, correlated on the
         * guarded table's key column — realm handlers apply it with
         * `query.whereRaw(sql, bindings)` before paging.  Returns `undefined`
         * when the entity is not guarded.
         */
        async aclFilter(
            params: {entity: string; method?: string; actorId?: string},
            $meta?: IMeta,
        ): Promise<{sql: string; bindings: unknown[]} | undefined> {
            const method = params.method ?? $meta?.method;
            const [subject, object] = params.entity.split('.');
            const actor = params.actorId ?? aclActorOf($meta);
            const qb = this.config?.context?.queryBuilder;
            const spec = resolveTableSpec(
                objectSchema,
                this.config?.schema?.tables?.[params.entity],
                subject,
                object,
            ).acl;
            const mode = spec?.mode ?? 'none';
            if (mode === 'none' || !actor || !method || !qb) return undefined;
            const cfg = aclConfig(this.config?.schema?.acl);
            const actionId = await aclActionId(qb, cfg, method);
            if (!actionId) return undefined;
            return aclCheckSql({
                cfg,
                actionId,
                actorId: aclActorId(actor),
                recordRef: `${subject}_${object}.${aclKeyColumn(objectSchema, subject, object)}`,
                scopes: spec?.scopes,
                selfScope: spec?.selfScope,
                mode,
            });
        },
 
        /**
         * `{subject}.dropdown.list` — produce `{value, label}` pairs for every
         * resource-backed table of the subject.  A table is resource-backed when
         * its PK (or any column) is a FK to `core.resource.resourceId`.
         *
         * Entries are resolved directly from `core_resource` (joined with
         * `core_type` by `typeAlias = ${subject}.${object}`), so every realm gets
         * dropdowns for free, matching the `blong-mock` `{subject}.dropdown.list`
         * shape (`{value: base64, label: resourceName}`).
         *
         * Per-table overrides are declared via the `dropdown` option on the table
         * spec (see `ISchemaTable`): `typeAlias`, `joinTable`, `joinColumn`,
         * `labelColumn`.
         */
        async _dropdownList(
            this: Adapter<IConfig>,
            subject: string,
            $meta?: IMeta,
        ): Promise<Record<string, Array<{value: string; label: string}>>> {
            const qb = this.config.context?.queryBuilder;
            if (!qb) return {};
            const result: Record<string, Array<{value: string; label: string}>> = {};
            const tables = this.config.schema?.tables ?? {};
            for (const [tableName, tableConfig] of Object.entries(tables)) {
                const [s, object] = tableName.split('.');
                if (s !== subject) continue;
                const {definition, dropdown} = resolveTableSpec(
                    objectSchema,
                    tableConfig,
                    s,
                    object,
                );
                if (!definition) continue;
                // Resource-backed?  Any FK pointing at core.resource.resourceId.
                const foreign = (
                    definition as unknown as {
                        constraints?: {foreign?: Record<string, string | {references?: string}>};
                    }
                )?.constraints?.foreign;
                const isResourceBacked = Object.entries(foreign ?? {}).some(([, fk]) =>
                    typeof fk === 'string'
                        ? fk === 'core.resource.resourceId'
                        : fk?.references === 'core.resource.resourceId',
                );
                if (!isResourceBacked) continue;
                const typeAlias = dropdown?.typeAlias ?? `${s}.${object}`;
                const labelColumn = dropdown?.labelColumn ?? 'resourceName';
                // A dropdown is data, so it is translated by the query that produces
                // it, in the caller's language, with the stored name as fallback —
                // the widget never rewrites an option label. `@@D-635`
                const language = requestLanguage($meta);
                const translate = !!language && labelColumn === 'resourceName';
                let query = qb('core_resource as r')
                    .join('core_type as t', 't.typeId', 'r.typeId')
                    .where('t.typeAlias', typeAlias);
                if (translate) {
                    query = query.leftJoin({r_t: 'core_translation'}, builder => {
                        builder.on('r_t.resourceId', '=', 'r.resourceId');
                        builder.onVal('r_t.languageCode', '=', language!);
                    });
                }
                query = translate
                    ? query.select(
                          'r.resourceId',
                          qb.raw('COALESCE(r_t.translatedName, r.resourceName) as label'),
                      )
                    : query.select('r.resourceId', `r.${labelColumn} as label`);
                if (dropdown?.joinTable) {
                    const joinColumn = dropdown.joinColumn ?? `${object}Id`;
                    query = query.join(
                        dropdown.joinTable,
                        `${dropdown.joinTable}.${joinColumn}`,
                        'r.resourceId',
                    );
                }
                // Record-level ACL: a dropdown is a read path, so a guarded entity
                // must not offer records the caller may not read.
                const aclSpec = resolveTableSpec(objectSchema, tableConfig, s, object).acl;
                const aclMode = aclSpec?.mode ?? 'none';
                const dropdownActor = ($meta?.auth as {actorId?: string} | undefined)?.actorId;
                if (aclMode !== 'none' && dropdownActor) {
                    const dropdownAcl = aclConfig(this.config.schema?.acl);
                    const actionId = await aclActionId(
                        qb,
                        dropdownAcl,
                        aclActionName(s, object, 'find'),
                    );
                    if (actionId) {
                        const filter = aclCheckSql({
                            cfg: dropdownAcl,
                            actorId: aclActorId(dropdownActor),
                            actionId,
                            recordRef: 'r.resourceId',
                            scopes: aclSpec?.scopes,
                            selfScope: aclSpec?.selfScope,
                            mode: aclMode,
                        });
                        query = query.whereRaw(filter.sql, filter.bindings as never[]);
                    }
                }
                // Alphabetical unless a realm overrides the list with an order of its
                // own: MySQL returns rows in no particular order, so a picker built
                // from this map listed the classifiers as the storage engine felt like
                // it (`@@D-784`).
                const rows = (await query.orderBy('label', 'asc')) as Array<{
                    resourceId: Buffer;
                    label: string;
                }>;
                result[`${s}.${object}`] = rows.map(r => ({
                    value: r.resourceId.toString('base64'),
                    label: r.label,
                }));
            }
            return result;
        },
        /**
         * Load model mocks when `config.mock` is `true`
         */
        async createHandlers({
            handlers,
            layerApi,
            kind,
        }: {
            handlers: object;
            layerApi: IHandlerProxy<unknown>;
            kind: string;
        }) {
            if (this.config?.mock && kind === 'model') {
                const {mock} = await import('@feasibleone/blong-mock');
                const models = await Promise.all(
                    Object.values(handlers)
                        .filter(handler => {
                            if (typeof this.config?.mock === 'boolean') return this.config.mock;
                            const handlerName = handler.name;
                            if (typeof this.config?.mock?.[handlerName] === 'boolean')
                                return this.config.mock[handlerName];
                            return Object.values(
                                this.config?.mock as Record<string, boolean | RegExp>,
                            ).some(
                                pattern => pattern instanceof RegExp && pattern.test(handlerName),
                            );
                        })
                        .map(model => model()),
                );
                return await mock.apply(this, [models, layerApi]);
            }
        },
        /**
         * Create or synchronise a database table from a TypeBox `TObject` schema.
         */
        async schemaTableSync(
            this: Adapter<IConfig>,
            tableName: string,
            schema: TObject,
            options: {dropColumns?: boolean} = {},
        ): Promise<{created: boolean; added: string[]; dropped: string[]}> {
            if (!this.config.context?.queryBuilder)
                throw new Error('Knex queryBuilder not available');
            return schemaTableSyncImpl(
                this.config.context.queryBuilder!,
                tableName,
                schema,
                options,
            );
        },
        /**
         * Synchronise stored procedures to the database.
         *
         * Accepts either a directory path (all `.sql` files are loaded) or an
         * array of `{name, sql}` objects.  Only procedures whose body differs
         * from the current definition are re-created.
         */
        async schemaProcedureSync(
            this: Adapter<IConfig>,
            procedures: string | Array<{name: string; sql: string}>,
        ): Promise<{created: string[]; skipped: string[]}> {
            if (!this.config.context?.queryBuilder)
                throw new Error('Knex queryBuilder not available');
            return schemaProcedureSyncImpl(this.config.context.queryBuilder!, procedures);
        },
        /**
         * Discover stored procedures whose names start with `namespace` and
         * generate a callable handler function and TypeBox schema for each.
         * Procedures starting with `_` are excluded.
         */
        async schemaProcedureBind(
            this: Adapter<IConfig>,
            namespace: string,
            schema?: string,
        ): Promise<{
            handlers: Record<string, (params: Record<string, unknown>) => Promise<unknown>>;
            schemas: Record<string, TFunction>;
        }> {
            if (!this.config.context?.queryBuilder)
                throw new Error('Knex queryBuilder not available');
            return schemaProcedureBindImpl(this.config.context.queryBuilder!, namespace, schema);
        },
        /**
         * Bind a map of handler functions as synthetic own-property handlers.
         * Each handler is stored under its `methodId` key AND its camelCase name
         * (for `super` calls in object-form realm handler overrides).
         */
        schemaHandlersBind(
            this: Adapter<IConfig>,
            handlers: Record<string, (params: Record<string, unknown>) => Promise<unknown>>,
        ): void {
            attachHandlers(this as unknown as Record<string, unknown>, handlers);
        },
    };
});
 
/**
 * Process asset modules matching the given regex pattern.
 * Iterates over all realm asset modules, reads YAML/JSON files and dispatches
 * their contents as handler method calls.
 */
async function processSeedAssets(
    ctx: Adapter<IConfig>,
    pattern: RegExp,
    onProgress?: (name: string) => void,
): Promise<void> {
    for (const realm of (await ctx.attach?.(
        pattern,
        [] as Array<{
            assets: Record<string, string>;
        }>,
    )) ?? []) {
        if (!realm?.assets) continue;
        for (const [name, path] of Object.entries<string>(realm.assets).sort(([, a], [, b]) =>
            ctx.platform.basename(a).localeCompare(ctx.platform.basename(b)),
        )) {
            const extname = ctx.platform.extname(path);
            const method = methodParts(ctx.platform.basename(path, extname).split('-').pop()!);
            onProgress?.(name);
            ctx.signal?.frameworkAssetProcessing?.({name, path, method});
            if (extname === '.yaml' || extname === '.yml') {
                const params = yaml.parse(
                    ctx.platform
                        .readFileSync(path.startsWith('file://') ? path.slice(7) : path, {
                            encoding: 'utf-8',
                        })
                        .toString('utf-8'),
                );
                await ctx.handle!(params, {method});
            } else if (extname === '.json') {
                const params = JSON.parse(
                    ctx.platform
                        .readFileSync(path.startsWith('file://') ? path.slice(7) : path, {
                            encoding: 'utf-8',
                        })
                        .toString('utf-8'),
                );
                await ctx.handle!(params, {method});
            }
        }
    }
}
 
export { attachHandlers, methodId, snakeToCamel };
 
/** Resolved per-table CRUD options (resource-backed + graph-edge bindings). */
export interface IResolvedTableOptions {
    /** Whether the table is resource-backed (PK → `core.resource`). */
    resource: boolean;
    /**
     * Real display-name column when it is not the virtual `${object}Name`
     * (declared as `resource: {nameColumn}`) — the resource row is named from it
     * and the column stays a normal table column.
     */
    nameColumn?: string;
    /** Declarative graph-edge master-detail bindings. */
    edges: IEdgeBinding[];
    /** Record-level ACL guard (`mode` defaults to `none`). */
    acl: IAclTableSpec;
}
 
/**
 * Resolve a `schema.tables` entry into its definition + dropdown override.
 *
 * A table entry is one of:
 * - a plain order number → definition from `objectSchema[subject][object]`
 * - an `ISchemaTable` spec `{definition?, order?, dropdown?, resource?, edges?}`
 *   — definition falls back to `objectSchema[subject][object]`
 * - a bare TypeBox `TObject`
 */
function resolveTableSpec(
    objectSchema: IObjectSchema,
    tableConfig: number | ISchemaTable | TObject | undefined,
    subject: string,
    object: string,
): {
    definition?: TObject;
    dropdown?: ISchemaTable['dropdown'];
    resource?: boolean;
    nameColumn?: string;
    edges?: IEdgeBinding[];
    acl?: IAclTableSpec;
} {
    if (tableConfig === undefined) return {};
    if (typeof tableConfig === 'number') {
        return {definition: objectSchema[subject]?.[object]};
    }
    if (typeof tableConfig === 'object' && tableConfig !== null) {
        // An ISchemaTable spec — either with an explicit `definition`, or a
        // partial spec (e.g. only `{order, dropdown}`) that falls back to the
        // realm schema for its definition.
        if (
            'definition' in tableConfig ||
            'order' in tableConfig ||
            'dropdown' in tableConfig ||
            'resource' in tableConfig ||
            'edges' in tableConfig ||
            'acl' in tableConfig
        ) {
            const spec = tableConfig as ISchemaTable;
            const resourceSpec =
                typeof spec.resource === 'object' && spec.resource !== null
                    ? spec.resource
                    : undefined;
            return {
                definition: spec.definition ?? objectSchema[subject]?.[object],
                dropdown: spec.dropdown,
                resource: resourceSpec ? true : spec.resource === true,
                nameColumn: resourceSpec?.nameColumn,
                edges: spec.edges,
                acl: spec.acl,
            };
        }
        return {definition: tableConfig as TObject};
    }
    return {};
}
 
/**
 * Resolve the declarative CRUD options for `subject.object` from the schema
 * table config. Tables declared with `resource: true` (or an `edges` binding)
 * get the resource-backed + graph-edge generic behaviour.
 */
function tableOptions(
    objectSchema: IObjectSchema,
    config: {schema?: {tables?: Record<string, number | ISchemaTable | TObject>}} | undefined,
    subject: string,
    object: string,
): IResolvedTableOptions {
    const tableConfig = config?.schema?.tables?.[`${subject}.${object}`];
    const spec =
        tableConfig !== undefined
            ? resolveTableSpec(objectSchema, tableConfig, subject, object)
            : {};
    const edges = spec.edges ?? [];
    return {
        // `resource` is declared explicitly — an `edges` binding alone does NOT
        // switch on the resource-backed name machinery (a table may carry edges
        // while keeping its own display-name column).
        resource: spec.resource === true,
        nameColumn: spec.nameColumn,
        edges,
        acl: spec.acl ?? {},
    };
}
 
/**
 * Batched join of `core_resource.resourceName` onto rows as the given name
 * field (e.g. `roleName`). Row ids are base64/hex strings (post
 * `prepareResultRow`); rows that already carry the name field are left as-is.
 *
 * A read folds this into its own statement (`attachResourceName`); what remains here
 * is the create, which has just written the resource row and needs the name it may
 * have inherited from an existing one, and the edge rows, whose table may carry a
 * display column of its own that must win. `@@D-619`
 */
async function joinResourceNames(
    qb: Knex,
    rows: Record<string, unknown>[],
    idField: string,
    nameField: string,
): Promise<Record<string, unknown>[]> {
    if (!rows.length) return rows;
    const ids = rows
        .map(r => (typeof r[idField] === 'string' ? (r[idField] as string) : undefined))
        .filter((x): x is string => !!x);
    if (!ids.length) return rows;
    const found = (await qb('core_resource')
        .whereIn(
            'resourceId',
            ids.map(id => strToBinary(id)),
        )
        .select('resourceId', 'resourceName')) as Array<{resourceId: Buffer; resourceName: string}>;
    const names = new Map<string, string>();
    for (const r of found) names.set(r.resourceId.toString('hex'), r.resourceName);
    return rows.map(row => {
        if (row[nameField] !== undefined) return row;
        const id = typeof row[idField] === 'string' ? (row[idField] as string) : undefined;
        if (!id) return row;
        const name = names.get(strToBinary(id).toString('hex'));
        return name !== undefined ? ({...row, [nameField]: name} as Record<string, unknown>) : row;
    });
}
 
/**
 * The language a read should answer in, taken from `$meta.language`.
 *
 * A gateway sets it from the token's `language` claim, or from the
 * `x-blong-language` header the browser sends with its active language. English
 * needs no join at all: the stored name *is* the English name and every translated
 * column falls back to it, so `undefined` means "read the base table". `@@D-635`
 */
function requestLanguage($meta?: Partial<IMeta>): string | undefined {
    const declared = ($meta as {language?: unknown} | undefined)?.language;
    const languageId =
        typeof declared === 'string'
            ? declared
            : (declared as {languageId?: unknown} | undefined)?.languageId;
    if (typeof languageId !== 'string' || !languageId) return undefined;
    return /^en(-|_|$)/i.test(languageId) ? undefined : languageId;
}
 
/**
 * Left join `core_translation` for one resource alias and project the name in the
 * requested language, falling back to the stored one.
 *
 * `resourceAlias` is a `core_resource` alias already joined into the statement; the
 * translation alias is derived from it, so two keys to one table (an athlete and a
 * coach, both people) never share a join. `raw` is the knex instance's own builder,
 * because a `COALESCE` cannot be expressed as a column name. `@@D-635`
 */
function attachTranslationJoin(
    query: Knex.QueryBuilder,
    raw: Knex['raw'],
    resourceAlias: string,
    nameColumn: string,
    language: string,
    field: string,
): {query: Knex.QueryBuilder; selection: Knex.Raw} {
    const alias = `${resourceAlias}_t`;
    const joined = query.leftJoin({[alias]: 'core_translation'}, builder => {
        builder.on(`${alias}.resourceId`, '=', `${resourceAlias}.resourceId`);
        builder.onVal(`${alias}.languageCode`, '=', language);
    });
    return {
        query: joined,
        selection: raw('COALESCE(??.translatedName, ??.??) as ??', [
            alias,
            resourceAlias,
            nameColumn,
            field,
        ]),
    };
}
 
/**
 * Project the row's own display name in the same statement as the row.
 *
 * A resource-backed table keeps its display name in `core_resource.resourceName`,
 * keyed by the row's own key — the same shape as a label join, so a read can name it
 * with one left join and one selection instead of a second query per result.
 *
 * A table declaring `resource: {nameColumn}` keeps the name in a column of its own
 * instead, and the row is what a caller reads, so the translation replaces that
 * column **in place**: the selection is appended after `<table>.*` and MySQL
 * resolves a repeated column name to the last one, which leaves an English row
 * untouched and a translated row translated. `@@D-619` `@@D-635`
 */
function attachResourceName(
    query: Knex.QueryBuilder,
    raw: Knex['raw'],
    opts: IResolvedTableOptions,
    table: string,
    keyName: string,
    object: string,
    language?: string,
): {query: Knex.QueryBuilder; selection?: string | Knex.Raw} {
    if (!opts.resource) return {query};
    if (opts.nameColumn) {
        // Nothing to join for English: the column already holds the stored name.
        if (!language) return {query};
        const alias = 'name_translation';
        const joined = query.leftJoin({[alias]: 'core_translation'}, builder => {
            builder.on(`${alias}.resourceId`, '=', `${table}.${keyName}`);
            builder.onVal(`${alias}.languageCode`, '=', language);
        });
        return {
            query: joined,
            selection: raw('COALESCE(??.translatedName, ??.??) as ??', [
                alias,
                table,
                opts.nameColumn,
                opts.nameColumn,
            ]),
        };
    }
    const joined = query.leftJoin(
        'core_resource',
        'core_resource.resourceId',
        `${table}.${keyName}`,
    );
    if (language) {
        const translated = attachTranslationJoin(
            joined,
            raw,
            'core_resource',
            'resourceName',
            language,
            `${object}Name`,
        );
        return {query: translated.query, selection: translated.selection};
    }
    return {
        query: joined,
        selection: `core_resource.resourceName as ${object}Name`,
    };
}
 
/**
 * Attach a `LEFT JOIN` for each label a read asks for, and collect the select
 * expressions that project them.
 *
 * A key column stores a key, and a key is not what a reader wants. The model names
 * the label it wants to read (`widget.body`), the browser sends those names with
 * the read (`labels`), and the label arrives with the row from the same SQL
 * statement — no second query, no per-cell lookup.
 *
 * Both sides are derived, never trusted: a requested label must be
 * `<fk minus Id>Name` for a foreign key the table actually declares, the target
 * table comes from that declaration, and the label column comes from the target's
 * own metadata — `dropdown.labelColumn`, then `resource.nameColumn`, then
 * `core_resource.resourceName`. A name that matches no declared foreign key is
 * ignored, so the parameter can widen no query. Every join is a left join, so a
 * record whose key points nowhere still comes back, with the label empty.
 *
 * The alias map is the other half of the answer: a browse column read from the
 * joined table is filterable by the name it is displayed under, and that name
 * belongs to the alias, not to the base table `@@D-743`.
 * @@D-614
 */
export function attachLabelJoins(
    query: Knex.QueryBuilder,
    raw: Knex['raw'],
    objectSchema: IObjectSchema,
    config: {schema?: {tables?: Record<string, number | ISchemaTable | TObject>}} | undefined,
    subject: string,
    object: string,
    table: string,
    labels: unknown,
    language?: string,
): {
    query: Knex.QueryBuilder;
    selections: Array<string | Knex.Raw>;
    aliases: Record<string, string>;
} {
    if (!Array.isArray(labels)) return {query, selections: [], aliases: {}};
    const definition = resolveTableSpec(
        objectSchema,
        config?.schema?.tables?.[`${subject}.${object}`],
        subject,
        object,
    ).definition as unknown as
        | {
              constraints?: {
                  foreign?: Record<string, string | {references?: string}>;
              };
          }
        | undefined;
    const foreign = definition?.constraints?.foreign ?? {};
    const wanted = labels.filter(
        (name): name is string =>
            typeof name === 'string' && /^[A-Za-z][A-Za-z0-9]*Name$/.test(name),
    );
    if (!wanted.length) return {query, selections: [], aliases: {}};
 
    let joined = query;
    const selections: Array<string | Knex.Raw> = [];
    const aliases: Record<string, string> = {};
    for (const labelField of wanted) {
        const fkColumn = `${labelField.slice(0, -'Name'.length)}Id`;
        const declaration = foreign[fkColumn];
        const reference = typeof declaration === 'string' ? declaration : declaration?.references;
        const [targetSubject, targetObject] = (reference ?? '').split('.');
        if (!targetSubject || !targetObject) continue;
        const target = resolveTableSpec(
            objectSchema,
            config?.schema?.tables?.[`${targetSubject}.${targetObject}`],
            targetSubject,
            targetObject,
        );
        const targetDefinition = target.definition as unknown as
            | {constraints?: {primaryKey?: string}}
            | undefined;
        const targetKey = targetDefinition?.constraints?.primaryKey ?? `${targetObject}Id`;
        const labelColumn = target.dropdown?.labelColumn ?? target.nameColumn;
        // The alias is derived from the key column, so two keys to one table (an
        // athlete and a coach, both people) never collide.
        const alias = `label_${fkColumn}`;
        if (labelColumn) {
            joined = joined.leftJoin(
                {[alias]: `${targetSubject}_${targetObject}`},
                `${alias}.${targetKey}`,
                `${table}.${fkColumn}`,
            );
            selections.push(`${alias}.${labelColumn} as ${labelField}`);
            aliases[labelField] = `${alias}.${labelColumn}`;
        } else if (target.resource) {
            joined = joined.leftJoin(
                {[alias]: 'core_resource'},
                `${alias}.resourceId`,
                `${table}.${fkColumn}`,
            );
            if (language) {
                const translated = attachTranslationJoin(
                    joined,
                    raw,
                    alias,
                    'resourceName',
                    language,
                    labelField,
                );
                joined = translated.query;
                selections.push(translated.selection);
            } else {
                selections.push(`${alias}.resourceName as ${labelField}`);
            }
            // A filter compares the stored name: the translation is a projection,
            // so the column the alias carries is what a `where` has to name.
            aliases[labelField] = `${alias}.resourceName`;
        }
    }
    return {query: joined, selections, aliases};
}
 
/**
 * The hex object ids of a subject's graph edges (`core_triple`).
 */
async function edgeObjectIds(qb: Knex, subjectId: Buffer, predicate: string): Promise<string[]> {
    const rows = (await qb('core_triple')
        .where('subjectId', subjectId)
        .where('predicateName', predicate)
        .select('objectId')) as Array<{objectId: Buffer}>;
    return rows.map(r => r.objectId.toString('hex'));
}
 
/**
 * Bring `subjectId -predicate-> objectId` edges in line with `objectHexIds`
 * (add missing, delete stale, refresh `access_path` once).
 */
async function syncGraphEdges(
    qb: Knex,
    subjectId: Buffer,
    predicate: string,
    objectHexIds: string[],
): Promise<void> {
    const existing = await edgeObjectIds(qb, subjectId, predicate);
    const existingSet = new Set(existing);
    const target = new Set(objectHexIds);
    const toAdd = objectHexIds.filter(id => !existingSet.has(id));
    const toRemove = existing.filter(id => !target.has(id));
    if (!toAdd.length && !toRemove.length) return;
    await qb.transaction(async trx => {
        if (toAdd.length) {
            await trx('core_triple').insert(
                toAdd.map(objectId => ({
                    subjectId,
                    predicateName: predicate,
                    objectId: Buffer.from(objectId, 'hex'),
                })),
            );
        }
        if (toRemove.length) {
            await trx('core_triple')
                .where('subjectId', subjectId)
                .where('predicateName', predicate)
                .whereIn(
                    'objectId',
                    toRemove.map(id => Buffer.from(id, 'hex')),
                )
                .del();
        }
        await trx.raw('CALL access_pathRefresh()');
    });
}
 
/**
 * Attach a graph-edge binding's rows to a result as a sibling array: the edge
 * object rows joined with their resource name (and a `granted: true` marker
 * when the binding uses the `granted` pivot convention).
 */
async function attachEdgeRows(
    qb: Knex,
    subjectId: Buffer,
    binding: IEdgeBinding,
): Promise<Record<string, unknown>[]> {
    const object = binding.object ?? binding.predicate.replace(/^has/, '').toLowerCase();
    const objectKey = binding.objectKey ?? `${object}Id`;
    const nameField = binding.nameField ?? `${object}Name`;
    const ids = await edgeObjectIds(qb, subjectId, binding.predicate);
    if (!ids.length) return [];
    const rows = (await qb(binding.table)
        .whereIn(
            objectKey,
            ids.map(hex => Buffer.from(hex, 'hex')),
        )
        .select('*')) as Record<string, unknown>[];
    // Prepare binary keys to base64 before joining names — joinResourceNames
    // expects string ids (base64/hex), not Buffers.
    const prepared = rows.map(row => ({
        ...row,
        [objectKey]: binaryToStr(row[objectKey] as Buffer),
    }));
    const named = await joinResourceNames(qb, prepared, objectKey, nameField);
    return named.map(row => (binding.granted ? {...row, granted: true} : row));
}