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

87.27% Statements 1578/1808
79.8% Branches 336/421
68.29% Functions 28/41
87.27% Lines 1578/1808

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 18091x 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 104x 104x 104x 8x 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 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 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 29x 29x 29x 143x                                                   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 155x 310x 194x 116x 116x   155x 155x 8x 8x 8x 8x 8x 8x 8x 8x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 141x 141x 141x 141x 141x 131x 131x 131x 141x 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 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x                                                 8x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 2x 2x 2x 2x 2x 2x 101x 101x 101x 103x               103x 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 99x 99x 99x 99x 99x 99x 99x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 38x 38x 38x 38x 38x 38x 8x 12x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 12x 5x 5x 3x 2x 38x 38x 38x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 103x 103x 103x 103x 103x 103x 103x 20x 20x 20x 20x 7x 10x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 103x 103x 103x 103x 103x 103x 103x 17x 17x 17x 17x 17x 17x 17x 2x 17x     2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 7x 2x 7x 2x 2x 2x 2x 2x 2x 2x 7x 1x 1x 1x 1x 1x 17x 103x 103x 103x 21x 21x 21x 21x 21x 21x 21x 19x 21x 2x 2x 21x 21x 21x 21x 21x 11x 11x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 18x 18x 18x 18x 18x 18x 18x 18x 18x 21x 10x 8x 21x 8x 8x 8x 8x 8x 8x 8x 8x 18x 18x 18x 18x 16x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 16x 16x 16x 16x 14x 11x 7x 7x   11x 7x 14x 16x 18x 18x 103x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 14x   14x 14x 14x 14x 20x                         20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 1x 1x 19x 19x 103x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 11x 11x 11x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 10x 10x 10x 17x 2x 2x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 7x 7x 2x 2x 7x 7x 17x 17x 17x 17x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 17x 17x 63x 63x 63x 63x 63x 63x 63x 63x 5x 5x 63x 17x 17x 17x 17x 8x 6x 17x 2x 2x 2x 2x 2x 2x 2x 17x 17x 17x 16x 16x 16x 16x 16x 16x 16x 16x 16x 10x 17x 17x 17x 17x 16x 16x 16x 16x 16x 16x 17x 4x 4x 4x 4x 4x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 16x 16x 16x 16x 12x 12x 5x 5x 5x   5x 5x 5x 5x 5x 5x 5x 2x 2x 2x   2x 5x 5x 2x 2x 5x 5x 12x 16x 16x 17x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 16x 16x 103x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 4x 9x 2x 2x 9x 9x 9x 7x 7x 7x 7x 7x 6x 9x 1x 1x 1x 1x 7x 7x 3x 3x 3x 9x 3x 3x 3x 3x 7x 7x 7x 6x 9x 1x 1x 7x 7x 7x 9x 9x 1x 1x 1x 1x 1x                                   7x 7x 7x 7x 7x 7x 7x 6x 6x 2x 2x 2x   2x 2x 1x 2x 1x 1x 1x 1x           1x 1x 1x 2x 2x 6x 7x 7x 103x 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 10x 10x 10x 10x 10x 4x 4x 4x 4x 4x 10x 7x 6x 6x 7x 8x 8x 8x 7x 1x 1x 1x 1x 8x 7x 7x 8x 8x 103x 21x 21x 21x 21x 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 8x 5x 5x 8x 8x 2x 2x 2x 2x 2x 2x 21x 21x 96x 21x 21x 21x 21x 21x 21x 103x 1x 1x 1x 1x 1x 103x                 103x 2x 2x 2x 2x 2x 103x     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 43x 43x 14x 14x 14x 14x 14x 14x 43x 14x 14x 14x 14x 14x 26x 43x 15x 15x   43x 43x 43x 43x 43x 43x 43x 43x 43x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 43x 43x 43x                                       11x 11x 86x 86x 86x 11x 2x 2x 8x 8x 8x 8x 430x 430x 430x 430x 430x 430x 430x 430x 430x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 430x 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 28x 28x 21x 28x 49x 49x 49x 49x       49x 49x 49x 49x 49x 49x 49x 49x 49x 49x                   49x 28x 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 268x 268x 268x 268x 268x 268x 268x 268x 268x 268x 268x 268x 268x 268x 268x 126x 126x 268x 140x 140x 140x 140x 140x 103x         140x 140x 140x 140x 38x 102x 140x 140x 140x 140x 140x 140x 140x 140x 140x         1x 1x 1x 1x 1x 1x 87x 87x 87x 87x 87x 87x 87x 87x 87x 77x 10x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 1x 1x 1x 1x 1x 1x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 42x 42x 42x 39x 42x 42x 18x 1x 1x 1x 1x 17x 17x 17x 17x 17x 17x 17x 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 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 7x 7x 7x 7x 7x 7x 7x 7x 7x 31x 31x 31x 7x 7x 7x  
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 './acl.ts';
import {
    binaryToStr,
    discoverBinaryColumns,
    isBinaryColumn,
    prepareInputParams,
    prepareResultRow,
    prepareResultRows,
    strToBinary,
} from '../schema/knex/binary.ts';
import {ensureDatabase} from '../schema/knex/database.ts';
import {wrapKnex} from '../schema/knex/json.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 {
    type IColumnSchema,
    methodId,
    propDefault,
    propType,
    readSqlFiles,
    snakeToCamel,
} 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;
}
 
export type {IConfig, ISchemaTable} from '../schema/knex/types.ts';
 
const errorMap: IErrorMap = {
    'knex.generic': 'Knex Error',
    '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}',
    // 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.
 */
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;
            if (knexConfig.createDatabase) {
                try {
                    const {created, database} = await ensureDatabase(knexConfig.connection ?? {});
                    if (created) {
                        this.log?.info?.({database}, 'created missing database');
                    }
                } catch (error) {
                    // Warn-and-continue: schema sync will surface the real error.
                    this.log?.warn?.(
                        {
                            err: (error as {message?: string}).message ?? String(error),
                        },
                        'could not auto-create database — will continue',
                    );
                }
            }
            this.config.context = {
                queryBuilder: wrapKnex(KnexLib(this.config.knex), {
                    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,
            };
            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;
            const self = this as unknown as Record<string, unknown>;
 
            if (schema?.sync && knex) {
                // 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) {
                // Bind all DB procedures as synthetic handlers (skips `_`-prefixed).
                await bindSyntheticHandlers(self, knex);
            }
            if (schema?.seed) {
                // Seed merges each trigger an `access_pathRefresh()` full rebuild
                // by default.  During the batch we defer it — merges only write
                // `core_triple` edges and skip the rebuild (see `core.triple.merge`
                // deferPathRefresh handling) — then run ONE refresh at the end.
                // This avoids both redundant full rebuilds and the write-vs-refresh
                // deadlock between concurrent merges.
                (this.config.context as {deferPathRefresh?: boolean}).deferPathRefresh = true;
                try {
                    let currentSeed = '';
                    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),
                                );
                            }
                            // 3. Single rebuild after all seed edges are in place.
                            if (schema?.accessPathRefresh)
                                await knex?.raw('CALL access_pathRefresh()');
                        })(),
                        {
                            getProgress: () => ({current: currentSeed || 'starting'}),
                        },
                    );
                } finally {
                    (this.config.context as {deferPathRefresh?: boolean}).deferPathRefresh = false;
                }
            }
 
            // Discover binary(16) columns for Buffer <-> string conversion.
            if (knex) {
                setBinaryCols(this.config.context, await discoverBinaryColumns(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,
            };
        },
        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('.');
            // `{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,
            ): Promise<void> => {
                const mode = opts.acl.mode ?? 'none';
                if (mode === 'none') return;
                await this.config.context
                    .queryBuilder!(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, ...where} = params;
                    const qb = this.config.context.queryBuilder!;
                    const binaryCols = getBinaryCols(this.config.context);
                    const opts = tableOptions(objectSchema, this.config, subject, object);
                    let query = qb(table);
                    for (const [key, val] of Object.entries(where)) {
                        if (isBinaryColumn(binaryCols, table, key) && typeof val === 'string') {
                            query = query.where(key, strToBinary(val));
                        } else {
                            query = query.where(key, val as string | number);
                        }
                    }
                    const row = (await query.first()) as Record<string, unknown> | undefined;
                    const keyName =
                        (
                            objectSchema[subject]?.[object] as
                                | {constraints?: {primaryKey?: string}}
                                | undefined
                        )?.constraints?.primaryKey ?? `${object}Id`;
                    // 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),
                    };
                    const masterRow = result[object] as Record<string, unknown> | undefined;
                    // Resource-backed: join the display name from
                    // `core_resource.resourceName` as `${object}Name`.
                    if (
                        opts.resource &&
                        !opts.nameColumn &&
                        masterRow &&
                        typeof masterRow[keyName] === 'string'
                    ) {
                        const [joined] = await joinResourceNames(
                            qb,
                            [masterRow],
                            keyName,
                            `${object}Name`,
                        );
                        result[object] = joined;
                    }
                    // 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,
                        ...where
                    } = params;
                    const qb = this.config.context.queryBuilder!;
                    const binaryCols = getBinaryCols(this.config.context);
                    const opts = tableOptions(objectSchema, this.config, subject, object);
                    let query = qb(table);
                    for (const [key, val] of Object.entries({...filterBy, ...where})) {
                        if (isBinaryColumn(binaryCols, table, key) && typeof val === 'string') {
                            query = query.where(key, strToBinary(val));
                        } else {
                            query = query.where(key, val as string | number);
                        }
                    }
                    if (search) {
                        const stringFields = Object.entries(
                            objectSchema[subject]?.[object]?.properties ?? {},
                        )
                            .filter(([, prop]) => propType(prop) === 'string')
                            .map(([key]) => key);
                        if (stringFields.length > 0)
                            query = query.andWhere(function () {
                                for (const field of stringFields) {
                                    this.orWhereILike(field, `%${search}%`);
                                }
                            });
                    }
                    if (order) query = query.orderBy(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[]);
                    if (limit) query = query.limit(limit);
                    if (offset) query = query.offset(offset);
                    const rows = (await query.select(select)) as Record<string, unknown>[];
                    const prepared = prepareResultRows(rows, binaryCols, table);
                    // Resource-backed: join the display name from
                    // `core_resource.resourceName` as `${object}Name`.  A table
                    // declaring `resource: {nameColumn}` keeps its real display
                    // column — no virtual field is synthesised.
                    if (opts.resource && !opts.nameColumn) {
                        return joinResourceNames(qb, prepared, `${object}Id`, `${object}Name`);
                    }
                    return prepared;
                }
                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 qb = this.config.context.queryBuilder!;
                    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;
                    // 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
                    const insertCols = prepareInputParams(cols, binaryCols, table);
                    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;
                        const detailBinaryCols = getBinaryCols(this.config.context);
                        for (const detailRow of detailRows) {
                            await qb(detail.table).insert(
                                prepareInputParams(
                                    {
                                        ...(detailRow as Record<string, unknown>),
                                        [detail.fkColumn]: masterKey,
                                    },
                                    detailBinaryCols,
                                    detail.table,
                                ),
                            );
                        }
                        const createdRows = (await qb(detail.table).where({
                            [detail.fkColumn]: masterKey,
                        })) as Record<string, unknown>[];
                        result[detailName] = prepareResultRows(
                            createdRows,
                            detailBinaryCols,
                            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 qb = this.config.context.queryBuilder!;
                    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`];
                    }
                    // 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`).
                    const preparedUpdate = prepareInputParams(update, binaryCols, table);
                    // 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;
                        const detailBinaryCols = getBinaryCols(this.config.context);
                        await qb(detail.table)
                            .where({[detail.fkColumn]: detailKey})
                            .del();
                        for (const detailRow of detailRows) {
                            await qb(detail.table).insert(
                                prepareInputParams(
                                    {
                                        ...(detailRow as Record<string, unknown>),
                                        [detail.fkColumn]: detailKey,
                                    },
                                    detailBinaryCols,
                                    detail.table,
                                ),
                            );
                        }
                    }
                    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 'remove': {
                    const {key: keyName = `${object}Id`, [keyName]: key} = params;
                    if (!(keyName in params)) {
                        throw this.error(_errors['knex.missingKey']({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']({key: keyName}), $meta);
                    }
                    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,
                    );
                    // …then release the rules that reference the record, before
                    // the entity row is deleted (see `aclReleaseResource`).
                    if (Buffer.isBuffer(masterKey)) await aclReleaseResource(opts, masterKey);
                    // Master-detail: delete each FK-constrained detail table's
                    // rows for this master BEFORE deleting the master row, so a
                    // non-cascading FK does not block the delete.
                    for (const detail of detailTables(subject, object, keyName)) {
                        await qb(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 qb('core_triple')
                                .where('subjectId', subjectBuf)
                                .where('predicateName', binding.predicate)
                                .del();
                            if (binding.reverse) {
                                await qb('core_triple')
                                    .where('objectId', subjectBuf)
                                    .where('predicateName', binding.predicate)
                                    .del();
                            }
                        }
                        if (opts.edges.length) {
                            await qb.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 qb(table).where(keyName, masterKey).del()
                        : await qb(table)
                              .where({[keyName]: key})
                              .del();
                    // Resource-backed: delete the `core_resource` row last.
                    if (Buffer.isBuffer(masterKey) && opts.resource) {
                        await qb('core_resource').where('resourceId', masterKey).del();
                    }
                    return removed;
                }
                case 'merge': {
                    const {key = `${object}Id`, [object]: objectRows, resourceType} = params;
                    let rows = objectRows as Array<{[key]: string}>;
                    const binaryCols = getBinaryCols(this.config.context);
                    if (resourceType) {
                        // create or lookup resourceId for each row based on its `name` property
                        const typeId = (
                            await this.config.context.queryBuilder!('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 this.config.context.queryBuilder!('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 this.config.context.queryBuilder!('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 =>
                        prepareInputParams(row, binaryCols, table),
                    );
                    return this.config.context.queryBuilder!(table)
                        .insert(preparedRows)
                        .onConflict(key)
                        .merge();
                }
                case 'insert': {
                    const binaryCols = getBinaryCols(this.config.context);
                    return this.config.context.queryBuilder!(table).insert(
                        prepareInputParams(params, binaryCols, table),
                    );
                }
                case 'update': {
                    const {select: _select, ...where} = params;
                    const binaryCols = getBinaryCols(this.config.context);
                    return this.config.context.queryBuilder!(table)
                        .where(
                            prepareInputParams(where as Record<string, unknown>, binaryCols, table),
                        )
                        .update(_select);
                }
                case 'delete': {
                    const binaryCols = getBinaryCols(this.config.context);
                    return this.config.context.queryBuilder!(table)
                        .where(prepareInputParams(params, binaryCols, table))
                        .del();
                }
            }
            throw this.error(_errors['knex.generic']({}), $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';
                let query = qb('core_resource as r')
                    .join('core_type as t', 't.typeId', 'r.typeId')
                    .where('t.typeAlias', typeAlias)
                    .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[]);
                    }
                }
                const rows = (await query) 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.log?.debug?.({
                $meta: {mtid: 'event', method},
                message: `Processing asset: ${name} at path: ${path}`,
            });
            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.
 */
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 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));
}