Compare commits
829 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2f2c5e2061 | |||
| a70a01dbcb | |||
| 1da477d3ab | |||
| cfce889cda | |||
| 8d7b41302f | |||
| 7e475e571f | |||
| a6303704a3 | |||
| 2c4d62f013 | |||
| da2641597a | |||
| aafa022f5b | |||
| 838865c0bb | |||
| ea038d3d23 | |||
| 92c0881d9d | |||
| 50ba1a0213 | |||
| afe768193f | |||
| 64c40ec2c7 | |||
| 80fafc25ce | |||
| d9324a5226 | |||
| 40503750fa | |||
| 49507d2af6 | |||
| 54422235e9 | |||
| e38b6e0318 | |||
| 690d4c545d | |||
| da01757870 | |||
| c0a18d6a5a | |||
| 1407458c6f | |||
| b36f697b50 | |||
| b819202acf | |||
| f53c0a0d4e | |||
| a16edfa29b | |||
| 5f7e173abf | |||
| 80dbd818f2 | |||
| ffc9b1b046 | |||
| 881f0f4114 | |||
| 4868a86513 | |||
| 093677add4 | |||
| c75445087f | |||
| 7d24ff2971 | |||
| 4df2ab575f | |||
| de6186e04f | |||
| 2cdcc7f01a | |||
| 12de518db4 | |||
| f45c33701d | |||
| faff0410dc | |||
| c18c8bf957 | |||
| f170b97985 | |||
| b9f8ff0e8f | |||
| 41dbdae4e2 | |||
| 6da7cc9b4c | |||
| 52d5d474f5 | |||
| 11980a6b8e | |||
| dddec5cadd | |||
| be44e188e3 | |||
| dc5e8c63bd | |||
| 0f32760e3c | |||
| 49048b148e | |||
| b6d9167945 | |||
| 5fdb9a352c | |||
| c7dd9b60eb | |||
| 02d15a7ebd | |||
| 43b442a626 | |||
| 1acfe91582 | |||
| 549907fd67 | |||
| 1e84e1e632 | |||
| 50ef01398d | |||
| 9163ef1f4d | |||
| 1fc6ffccc5 | |||
| af9cee12c1 | |||
| f5e7691e2b | |||
| 1cc77c9543 | |||
| da27e4aa02 | |||
| df52a0bc78 | |||
| 8948fbee29 | |||
| 053bb22f35 | |||
| 71b65e88e8 | |||
| ffbc653d85 | |||
| f03ddcca32 | |||
| e681b651eb | |||
| c97bb14fab | |||
| 676d1cda92 | |||
| 10f5525410 | |||
| ac16a4716b | |||
| 895f12dfe7 | |||
| 4853aa18f0 | |||
| f7fea5b4b8 | |||
| 674b312ed7 | |||
| fd6080637c | |||
| 9c17ee4f93 | |||
| f7b58da831 | |||
| bb5136e5cb | |||
| 340b1d1a71 | |||
| 48a4a4b73d | |||
| 21fd7ce098 | |||
| 4f975c3379 | |||
| 3d420836fd | |||
| de868175c3 | |||
| 195687f1bf | |||
| 07dd481010 | |||
| 387f468591 | |||
| 50632afa6e | |||
| 5ad03a486e | |||
| 8364ce2aa2 | |||
| 8c3e234ad5 | |||
| 7731dfca49 | |||
| 34b92b19f3 | |||
| 14ae1a5331 | |||
| 705d7be62d | |||
| 419e0d3e09 | |||
| e896ba94e3 | |||
| 4831f4e0f1 | |||
| ce2d4ae6a6 | |||
| 16603ecfcb | |||
| 42dddb97de | |||
| d5ca2c4b3d | |||
| 5f726694eb | |||
| 89954fe7ce | |||
| d3c8f2ac33 | |||
| f861b36bf4 | |||
| 7704a535d0 | |||
| 99a37ca779 | |||
| 80b30f995e | |||
| 4073706a47 | |||
| 2d75c1aa3d | |||
| 1f41a8c8a7 | |||
| 89b373ab28 | |||
| 7d913e9aae | |||
| fb643592fe | |||
| 54cc766b41 | |||
| f55a7dad19 | |||
| 5723c659fd | |||
| 3725af73b9 | |||
| 89ccfac0ac | |||
| de033d078b | |||
| 98147dd526 | |||
| 848d27ada1 | |||
| a6ca996e4a | |||
| 6f3286cafd | |||
| 96b6371d70 | |||
| 875b95d4f5 | |||
| 8a8244b5c1 | |||
| c046f6d4d9 | |||
| 7e089d0c40 | |||
| e180564028 | |||
| 63b3a64ca6 | |||
| 9b6a28330b | |||
| 842c5ee849 | |||
| d89a66ec36 | |||
| bf70f1bd1a | |||
| 361fb98b5d | |||
| 3b88065d35 | |||
| 805055f734 | |||
| a817b30f0b | |||
| fd31ae3bf9 | |||
| 9dc4d5e6b4 | |||
| 3117dc60e3 | |||
| cd0df83c15 | |||
| 71de8e0241 | |||
| 72ab366192 | |||
| b5e2e6fcd3 | |||
| 7a2a8cee5a | |||
| a331cf7e57 | |||
| 9489e0a5d7 | |||
| ac79fa1c78 | |||
| 0e522c068a | |||
| 451393c4f4 | |||
| 43fce6bb0d | |||
| ce152a4369 | |||
| e79a0943ed | |||
| 1b8c246799 | |||
| 79b99b09fa | |||
| 8be8924901 | |||
| cdc9ddc6ec | |||
| 0467b01a1f | |||
| e70d458340 | |||
| 08535840c6 | |||
| 543c368958 | |||
| ce4b0fdf8a | |||
| 135c9ff6f7 | |||
| e493f8f0cd | |||
| 2676fc58c8 | |||
| 824bb5b8db | |||
| 8ffc98999d | |||
| 956392694a | |||
| 8e62d370cf | |||
| f0799fdf6d | |||
| 9dffd36c5d | |||
| f3adb7c430 | |||
| 7a98937db2 | |||
| 260ac72722 | |||
| 879164ed74 | |||
| 0388f17988 | |||
| e72ddfd89b | |||
| 3fa10f82f4 | |||
| 2bc4a6cad0 | |||
| 3e771c0f07 | |||
| 859434d049 | |||
| 4bc1cc1847 | |||
| 249efd04d7 | |||
| d92c652ac1 | |||
| 921acff927 | |||
| eddfa9840e | |||
| bd1c634546 | |||
| 7ca4af6a9f | |||
| e995d2c226 | |||
| d85d08398d | |||
| 1ffb6be119 | |||
| 131aa13a2a | |||
| c9e992a197 | |||
| 7be51f5897 | |||
| 402da26c16 | |||
| b75971e6e9 | |||
| 181f7e869d | |||
| 47996ea7c4 | |||
| c2777abc2d | |||
| 7d23d157bb | |||
| 7747ffba47 | |||
| c9ef12f62b | |||
| db6940ab45 | |||
| 49d77ee642 | |||
| 005c9d8295 | |||
| 50661c5e31 | |||
| d8897d971b | |||
| ff891b4e1c | |||
| 392fd3ce37 | |||
| 4fbf90ee11 | |||
| d35b5587df | |||
| d6555726ed | |||
| 211a1a7281 | |||
| 73c586bcbf | |||
| 8a2254fa1f | |||
| 88a0637f57 | |||
| 4df12ce5a8 | |||
| 73ac958c74 | |||
| adc686043e | |||
| 461fa44be0 | |||
| 041cc06139 | |||
| 9a55773b2f | |||
| 2eca06141f | |||
| ed3182f233 | |||
| a4b2f41938 | |||
| 98e120fca0 | |||
| c7fb48d4b6 | |||
| f6b6188bdd | |||
| 2716cd2528 | |||
| 2b776ee2d6 | |||
| 3c272ba380 | |||
| 88838f6b95 | |||
| faf6a07965 | |||
| 8d9e595513 | |||
| d234902b7c | |||
| 4b074692f4 | |||
| 16292a5e52 | |||
| 277c7d3516 | |||
| 57956a9c86 | |||
| 3044e77b4a | |||
| 4f5bbedb3a | |||
| a4c357f94c | |||
| 5f0b67cb7a | |||
| 33ded6edaf | |||
| 7ff8da876d | |||
| bdfd7ea03a | |||
| ef9cd12ec4 | |||
| 510a9d1c64 | |||
| 65e6522f8f | |||
| 92ede964e1 | |||
| 9892883e9e | |||
| 9fdce595eb | |||
| 63e9ec2f9c | |||
| 6479c5a359 | |||
| 193ee11fe1 | |||
| 7d34b8d628 | |||
| f064a3bbe4 | |||
| f446af57b5 | |||
| 3afad4d432 | |||
| 32781427d7 | |||
| be9d203665 | |||
| c9099d2d73 | |||
| 7424aeff41 | |||
| 6167d5cf17 | |||
| 8c1a4b89af | |||
| ae589b69db | |||
| 7bc6a818f0 | |||
| 1337a2291d | |||
| 2d3261fe86 | |||
| 0a803bd984 | |||
| e67a0f40e4 | |||
| ad658b2d82 | |||
| d18f1bbfe0 | |||
| 07c0b72253 | |||
| 359d62395e | |||
| cb57716c65 | |||
| dc6ae60226 | |||
| f6c686c9f4 | |||
| 53d4e01d06 | |||
| f71c954cbc | |||
| b0ccf50cbd | |||
| eb97743cc7 | |||
| b94a98607a | |||
| 31474ce57e | |||
| 4b884bb4c7 | |||
| cb22bd80d2 | |||
| 5ad3631915 | |||
| d98011852d | |||
| 489a8a9d3c | |||
| 5d48e0cdc5 | |||
| 6559e0ab15 | |||
| 5b9973d898 | |||
| 3d64548491 | |||
| 6319a8003c | |||
| 80cf891792 | |||
| 7e33f8f43b | |||
| 278d3faf1f | |||
| 1f095d482d | |||
| 6a643e4bcd | |||
| 8d8fc58413 | |||
| 351563efe1 | |||
| aee4049128 | |||
| 395012e58e | |||
| ef11fb915d | |||
| 56fae744d4 | |||
| 60d9aa7c59 | |||
| 9bbd91b39d | |||
| 80b1f6fcde | |||
| bdbd097280 | |||
| f75c0c7036 | |||
| 6110a5d0ab | |||
| f333370e1f | |||
| 65022716b3 | |||
| e8afca3f16 | |||
| 72ab400d4d | |||
| 171b168b3e | |||
| 2897b88f9e | |||
| ebe1423098 | |||
| 4bc2f6b415 | |||
| faaacd3fbb | |||
| 0f51aa3972 | |||
| 0cc6f78bcf | |||
| 4c5c941b6e | |||
| 8b9a3d1fc8 | |||
| 5a0771a1f4 | |||
| a5f8c42c98 | |||
| 703c208d30 | |||
| 40c9becc81 | |||
| 4cffb644c7 | |||
| fa5aac7475 | |||
| 89071030db | |||
| fea03bc0ca | |||
| c3b6fdaead | |||
| 0e0aafc698 | |||
| b8c8d4e4a0 | |||
| c2ccd67689 | |||
| c9e2602e8f | |||
| 5e8bb0aa13 | |||
| 138647a552 | |||
| c4b87be3e8 | |||
| b22b493338 | |||
| aec046a264 | |||
| 316cd40122 | |||
| f815011a08 | |||
| 61418d5a67 | |||
| 0e0687ccfc | |||
| b5ae85eca2 | |||
| 5ef7f04775 | |||
| ba0b157583 | |||
| 509f40526e | |||
| 862281fc47 | |||
| 8766fd20d1 | |||
| ac51eb7754 | |||
| ed85333977 | |||
| bcdb4cc71b | |||
| f386012069 | |||
| 0db3089576 | |||
| c5313afea7 | |||
| 3e2823cbb6 | |||
| 5f4ad92681 | |||
| 8200a6d8d7 | |||
| e6f8a09532 | |||
| 0731554629 | |||
| a50d3b7a5d | |||
| 20a9ed1dc6 | |||
| b9fbc558f7 | |||
| 132a87baa3 | |||
| ce260f4e43 | |||
| 756440febc | |||
| 81439a07f0 | |||
| 4c72171b60 | |||
| 84e5076787 | |||
| 57db2174d5 | |||
| 58bcfe075d | |||
| d22cfa8c80 | |||
| 0144a8482a | |||
| 28ef9bddb3 | |||
| 73390f09c2 | |||
| dae7518ae4 | |||
| 0117693f62 | |||
| 409505c743 | |||
| 6fa0a11c7b | |||
| 3c24342841 | |||
| b8eaf9a10d | |||
| 322967df59 | |||
| a3a6d63b40 | |||
| 5b91500796 | |||
| 7985e05a97 | |||
| 23d39ce54d | |||
| 5fd8f27bfb | |||
| 0b769f5b4a | |||
| 5ca0b38605 | |||
| b126ec18b6 | |||
| d8bb0b5ae6 | |||
| aede9b5bd3 | |||
| bb19512438 | |||
| a002cc174f | |||
| 6acd7b0a75 | |||
| 5360f5fcff | |||
| 3e4e697d1c | |||
| 1ad51ffe21 | |||
| 2811759d5e | |||
| 6b013afb88 | |||
| ad5125a624 | |||
| 73079dba00 | |||
| 2a91126d76 | |||
| ade4f4d645 | |||
| e99f742a32 | |||
| d15822965b | |||
| 65660916dc | |||
| c6c9c6aad0 | |||
| 7585f49a0a | |||
| bc2e7fc228 | |||
| bdb6368d72 | |||
| 7920162093 | |||
| 25f62508f5 | |||
| f7377d5763 | |||
| 126976c9f8 | |||
| f5bf66c875 | |||
| e66b26818b | |||
| 46d4398440 | |||
| dd628ed58b | |||
| e07ce18be5 | |||
| 1174c23e0d | |||
| fa7098d543 | |||
| 9a27d65044 | |||
| 3887ffe82a | |||
| 7cd81af3a9 | |||
| e3485ee996 | |||
| cb94132d9f | |||
| 44a87f08ef | |||
| 4a08e793c6 | |||
| b53e0992b2 | |||
| 8c983ddb67 | |||
| 59ece7e106 | |||
| abb28667f1 | |||
| 3a59dd12d2 | |||
| 8fc8b5b35f | |||
| 497b3e6a11 | |||
| 100b496dd2 | |||
| 09aa80d109 | |||
| ae1ed83831 | |||
| 2e440a0801 | |||
| 0c4517a61a | |||
| 108c51b6ae | |||
| d5e3fe50f8 | |||
| 4c8404e555 | |||
| 6e440ab3de | |||
| a768b67dcc | |||
| 49cb8d7314 | |||
| 7302079dbe | |||
| be2e212cf9 | |||
| f2f8a3a348 | |||
| cdefd5d046 | |||
| ad617b4d6d | |||
| 173b418e60 | |||
| 5fc3a8a32f | |||
| 4e9bf5ace3 | |||
| e04c9f4b33 | |||
| fee6431392 | |||
| 18a3a48db1 | |||
| 6c86783f9a | |||
| 44132244fa | |||
| a3fc683c80 | |||
| 73b09b87d5 | |||
| 9c3a114ca0 | |||
| 53f635df55 | |||
| 78d15f097a | |||
| ffc0cbb024 | |||
| fbf0f488cf | |||
| 429899ddad | |||
| 5bb5965710 | |||
| 4d28830861 | |||
| 2f06bf2541 | |||
| 49a785fa34 | |||
| 2cae138fba | |||
| f2e624ea91 | |||
| 9a2efd8e1f | |||
| d7d1098baa | |||
| f0f025b340 | |||
| f6e3e31625 | |||
| a3825e78bd | |||
| 23593f8e99 | |||
| 09cb5eb5ac | |||
| aa07b36dd5 | |||
| 335ad5264f | |||
| 9afff9f3c5 | |||
| 407f75378e | |||
| 3734401a95 | |||
| 7383f5a7d9 | |||
| 9c765e7945 | |||
| 2ce2b779bb | |||
| 9a34509a06 | |||
| efeee19a95 | |||
| a9ac2ed069 | |||
| e5928b17ca | |||
| 35908b167f | |||
| 8c45a9f952 | |||
| f7415736d1 | |||
| ae708b2b01 | |||
| 376860ba88 | |||
| 7a8a0fceec | |||
| e3cd67603d | |||
| 64d04a8d9f | |||
| 41ce47c4f4 | |||
| 05cb948bf7 | |||
| 00378fde23 | |||
| f56291ed02 | |||
| 4ff42a82f7 | |||
| d869a21d13 | |||
| fed91737f5 | |||
| 78ed74ef8e | |||
| 16b03c0196 | |||
| 0348fc722f | |||
| 453af2f6cc | |||
| 6e901b07a3 | |||
| a8771a1736 | |||
| cd05aafa56 | |||
| 534945ad07 | |||
| e0c582850e | |||
| ba851ae72e | |||
| 8ac2d8510e | |||
| ab7de45084 | |||
| 0f201fccc0 | |||
| 2756f806f2 | |||
| 9113c87ef3 | |||
| 207cb6f670 | |||
| 5187c955f6 | |||
| 9c5e1e40e3 | |||
| 0761780bc4 | |||
| a7234901b2 | |||
| 1025227272 | |||
| 9a4c63b0fc | |||
| 90218aec7a | |||
| f79451eea7 | |||
| 2cf599cff8 | |||
| 587f9a0a99 | |||
| 087f143f87 | |||
| 24ddbca8d3 | |||
| a579f4400d | |||
| 5b0e63eb4c | |||
| e1c3462484 | |||
| e6d1650c5b | |||
| fbfe5af903 | |||
| 9289c47df7 | |||
| f0d12d87fa | |||
| 778d334085 | |||
| 217635f709 | |||
| 2315e83463 | |||
| 3961b26363 | |||
| 8c3b7501af | |||
| 3822e8ac47 | |||
| 626bcc88dd | |||
| c8e9f6818b | |||
| 6aafd74853 | |||
| 26e817f69b | |||
| 5e10d892d6 | |||
| a3a4da0922 | |||
| 8c3cc71a5a | |||
| 8e658f0a13 | |||
| e2848932a5 | |||
| bffd5c1ece | |||
| e24a6f58ae | |||
| 3cf46ee508 | |||
| 403f00219b | |||
| 3a17e2e5cf | |||
| b5a6f33e50 | |||
| f98109e7cb | |||
| 3b01dd0f5d | |||
| b4d7f1eb88 | |||
| 1dd1303600 | |||
| 4784a78d1c | |||
| 4b1b65ca2e | |||
| f4c291275b | |||
| e6710e83fc | |||
| 3c8fb6fb84 | |||
| fe888bcf11 | |||
| 509a6303d1 | |||
| ef69d2b277 | |||
| f89812fe52 | |||
| 2d2e528e1f | |||
| 47e2fe3ce7 | |||
| 058e99502a | |||
| 6aabb72618 | |||
| ee37302095 | |||
| 6b6d6c6bd2 | |||
| 8bd0b250b7 | |||
| 7bace9e9bb | |||
| 3dedb87bd7 | |||
| ee6b80c3b5 | |||
| 825fa17b1f | |||
| 034d111807 | |||
| d00505dc97 | |||
| e50998859d | |||
| 9553016377 | |||
| 3245f3be67 | |||
| 4b5919e2ce | |||
| a5cc692422 | |||
| cf2ad7ae36 | |||
| 2a7b27f1c6 | |||
| 077e17b59a | |||
| 449b473ee6 | |||
| 18934137dd | |||
| 67a0bf383f | |||
| b496eef690 | |||
| 02cb3ff004 | |||
| 40e3fa3035 | |||
| b3623e0af7 | |||
| b1c034b2f1 | |||
| de353fb5c2 | |||
| ca0720a9d8 | |||
| e834484d89 | |||
| 615aeceaff | |||
| 4f28ee9d76 | |||
| 2bb2d53bca | |||
| cda165ff9a | |||
| 95cc6a5e11 | |||
| e9a7ebe19f | |||
| b88bf865c3 | |||
| 0505851451 | |||
| 4413ec7255 | |||
| 03437f7886 | |||
| 8d48e30b39 | |||
| f0af3db770 | |||
| ea1e3b4251 | |||
| b2d7137154 | |||
| ebdf4c0240 | |||
| f703b42dc4 | |||
| 90120b9f4a | |||
| d5c2e08449 | |||
| f1ab642cde | |||
| fc7f8f81da | |||
| cd9e863079 | |||
| 3dfab26028 | |||
| 25bb72a7a8 | |||
| 74879e137d | |||
| 5f289e8400 | |||
| 4efa360f89 | |||
| 72f38795b4 | |||
| 43bb445f77 | |||
| 2337e97949 | |||
| 0e400f4e7d | |||
| 554cb87d96 | |||
| 5ca48c0b35 | |||
| e6aec72312 | |||
| f15b77b7cf | |||
| c59b7b1fb0 | |||
| ebaa9477d7 | |||
| dce232a298 | |||
| 07fae32db0 | |||
| e7ebe0aa81 | |||
| e36281fc31 | |||
| f53487a42d | |||
| c578e4f0eb | |||
| 48cae1320b | |||
| 3325a5c497 | |||
| 16316f1b68 | |||
| 0e4ab0db7e | |||
| f28727f61e | |||
| a57ac0a827 | |||
| 20e9cbe0ff | |||
| 2c1b1ddc55 | |||
| 064390b2b1 | |||
| 2b294b543f | |||
| d85e4ac347 | |||
| e26f592ea5 | |||
| b0b734d145 | |||
| bc7180cdb3 | |||
| 54f1fc4f94 | |||
| fe9833482f | |||
| 62f1b48638 | |||
| f79d277999 | |||
| 3691e56210 | |||
| 0702c63bc0 | |||
| 47d8c40ca5 | |||
| fa17e10592 | |||
| 1c67ec5692 | |||
| f170b0868d | |||
| 766ba7917e | |||
| af260308b3 | |||
| a36fedbda0 | |||
| d45ac3947d | |||
| 86bc5e41bb | |||
| a5ec23a705 | |||
| 2a40a882f2 | |||
| 521e0b6cb6 | |||
| 3a6e0c3f04 | |||
| d198183465 | |||
| 9efc618607 | |||
| 2b0ea0204f | |||
| f221e4b5d6 | |||
| cf5cab01cf | |||
| 0751fc3b85 | |||
| 2591cfb673 | |||
| b885744709 | |||
| 861ac67a9d | |||
| 8c44962aaf | |||
| b9294de1e6 | |||
| 4af6462fb8 | |||
| 436c28a265 | |||
| d7480403bc | |||
| ae8776e092 | |||
| 1d49768151 | |||
| 13736999d9 | |||
| d0d21f5565 | |||
| 8fa6206bc4 | |||
| 01156ec1c9 | |||
| c2beb0d8f6 | |||
| f26e45139e | |||
| b103c574fd | |||
| ea64cb31a5 | |||
| 63880362ed | |||
| c68fb84759 | |||
| 36f904f065 | |||
| 6efabd6cd3 | |||
| 2a7aff93ed | |||
| 3e245bcef3 | |||
| 8f9261a8e9 | |||
| e3bf2c8e9b | |||
| dba3a5ab87 | |||
| 516c85026b | |||
| 10c5341c72 | |||
| 0c278c3d76 | |||
| a913f9b992 | |||
| 27a242c634 | |||
| bbf71138cf | |||
| a1f79dae98 | |||
| 92d1afba9b | |||
| 1cc5c4ac84 | |||
| e45b87a9b7 | |||
| 958fcd417c | |||
| a27e350b6f | |||
| 0c2b00b0d6 | |||
| 65458dc146 | |||
| e5dea28482 | |||
| 8878f8a8d3 | |||
| 0483668007 | |||
| 0a841a2b85 | |||
| 8a5469b6f5 | |||
| 40357f0d5d | |||
| 5c118e3946 | |||
| a341bae948 | |||
| 093dd41e97 | |||
| f6bee94e22 | |||
| 644817721e | |||
| 33b2cb9aec | |||
| bb1369037b | |||
| d580bea7d4 | |||
| 6fdac75127 | |||
| 16828c8c12 | |||
| 93c4087ffe | |||
| c18fc6134e | |||
| 8a4d2bc34f | |||
| 0dbb3db431 | |||
| 8fca1c7044 | |||
| fd80fa9b6d | |||
| 626aa48c26 | |||
| f3d6e8fd6e | |||
| b61c2424d7 | |||
| 93a4b411ef | |||
| 181d75ef9e | |||
| 410fac35d7 | |||
| bf154369e7 | |||
| 486191603f | |||
| f89f4efb28 | |||
| 4e5aeb54f2 | |||
| a5d06a3d54 | |||
| 23aa8ff4de | |||
| f74f4ed5b5 | |||
| 0f4b534b60 | |||
| 6d013d890e | |||
| 1324b2830e | |||
| 0286cdbca6 | |||
| 47b4969e2d | |||
| 36c19f7799 | |||
| ea7a4e4fb3 | |||
| 645682a7c7 | |||
| 6ffa895884 | |||
| bff17db433 | |||
| c7fc08f69a | |||
| aa03c69591 | |||
| f51672a945 | |||
| d69820c42b | |||
| 9f67cc26c1 | |||
| c9dfe2b808 | |||
| b1f08bc690 | |||
| 5fd9f03291 | |||
| 404bf6bac6 | |||
| 1943005f62 | |||
| 1a66ff359f | |||
| e9ab04a446 | |||
| 5af8a86d62 | |||
| abe1ff38dd | |||
| 23b34bbc25 | |||
| ca29bbce2f | |||
| 4209d553e7 | |||
| 8d2f661ab8 | |||
| cd69784646 | |||
| b8bbe3e2db | |||
| 26c4df0fb0 | |||
| e91bde4655 | |||
| 78907bba3e | |||
| c121e087f3 | |||
| 724e298e9c | |||
| 7bfbd2508c | |||
| 361e0ede47 | |||
| ddcdf0b0dd | |||
| 26542e722b | |||
| e599cc427f | |||
| 085c5c6b43 | |||
| d0b22b81c8 | |||
| 79669c25c4 | |||
| 80bf86967f | |||
| de1e02ee52 |
+42
-47
@@ -35,7 +35,7 @@ TCC += -I${TOP}/ext/fts3 -I${TOP}/ext/async -I${TOP}/ext/session
|
||||
TCC += -I${TOP}/ext/userauth
|
||||
|
||||
# Define this for the autoconf-based build, so that the code knows it can
|
||||
# include the generated config.h
|
||||
# include the generated sqlite_cfg.h
|
||||
#
|
||||
TCC += -D_HAVE_SQLITE_CONFIG_H -DBUILD_sqlite
|
||||
|
||||
@@ -184,7 +184,7 @@ LIBOBJS0 = alter.lo analyze.lo attach.lo auth.lo \
|
||||
main.lo malloc.lo mem0.lo mem1.lo mem2.lo mem3.lo mem5.lo \
|
||||
memdb.lo memjournal.lo \
|
||||
mutex.lo mutex_noop.lo mutex_unix.lo mutex_w32.lo \
|
||||
notify.lo opcodes.lo os.lo os_unix.lo os_win.lo \
|
||||
notify.lo opcodes.lo os.lo os_kv.lo os_unix.lo os_win.lo \
|
||||
pager.lo parse.lo pcache.lo pcache1.lo pragma.lo prepare.lo printf.lo \
|
||||
random.lo resolve.lo rowset.lo rtree.lo \
|
||||
sqlite3session.lo select.lo sqlite3rbu.lo status.lo stmt.lo \
|
||||
@@ -257,6 +257,7 @@ SRC = \
|
||||
$(TOP)/src/os.h \
|
||||
$(TOP)/src/os_common.h \
|
||||
$(TOP)/src/os_setup.h \
|
||||
$(TOP)/src/os_kv.c \
|
||||
$(TOP)/src/os_unix.c \
|
||||
$(TOP)/src/os_win.c \
|
||||
$(TOP)/src/os_win.h \
|
||||
@@ -377,7 +378,7 @@ SRC += \
|
||||
opcodes.h \
|
||||
parse.c \
|
||||
parse.h \
|
||||
config.h \
|
||||
sqlite_cfg.h \
|
||||
shell.c \
|
||||
sqlite3.h
|
||||
|
||||
@@ -433,6 +434,9 @@ TESTSRC = \
|
||||
$(TOP)/ext/fts3/fts3_term.c \
|
||||
$(TOP)/ext/fts3/fts3_test.c \
|
||||
$(TOP)/ext/session/test_session.c \
|
||||
$(TOP)/ext/recover/sqlite3recover.c \
|
||||
$(TOP)/ext/recover/dbdata.c \
|
||||
$(TOP)/ext/recover/test_recover.c \
|
||||
$(TOP)/ext/rbu/test_rbu.c
|
||||
|
||||
# Statically linked extensions
|
||||
@@ -492,6 +496,7 @@ TESTSRC2 = \
|
||||
$(TOP)/src/main.c \
|
||||
$(TOP)/src/mem5.c \
|
||||
$(TOP)/src/os.c \
|
||||
$(TOP)/src/os_kv.c \
|
||||
$(TOP)/src/os_unix.c \
|
||||
$(TOP)/src/os_win.c \
|
||||
$(TOP)/src/pager.c \
|
||||
@@ -503,6 +508,7 @@ TESTSRC2 = \
|
||||
$(TOP)/src/pcache1.c \
|
||||
$(TOP)/src/select.c \
|
||||
$(TOP)/src/tokenize.c \
|
||||
$(TOP)/src/treeview.c \
|
||||
$(TOP)/src/utf.c \
|
||||
$(TOP)/src/util.c \
|
||||
$(TOP)/src/vdbeapi.c \
|
||||
@@ -554,7 +560,7 @@ HDR = \
|
||||
$(TOP)/src/vdbeInt.h \
|
||||
$(TOP)/src/vxworks.h \
|
||||
$(TOP)/src/whereInt.h \
|
||||
config.h
|
||||
sqlite_cfg.h
|
||||
|
||||
# Header files used by extensions
|
||||
#
|
||||
@@ -620,7 +626,10 @@ SHELL_OPT += -DSQLITE_ENABLE_DBSTAT_VTAB
|
||||
SHELL_OPT += -DSQLITE_ENABLE_BYTECODE_VTAB
|
||||
SHELL_OPT += -DSQLITE_ENABLE_OFFSET_SQL_FUNC
|
||||
FUZZERSHELL_OPT =
|
||||
FUZZCHECK_OPT = -DSQLITE_ENABLE_MEMSYS5 -DSQLITE_OSS_FUZZ
|
||||
FUZZCHECK_OPT += -I$(TOP)/test
|
||||
FUZZCHECK_OPT += -I$(TOP)/ext/recover
|
||||
FUZZCHECK_OPT += -DSQLITE_OMIT_LOAD_EXTENSION
|
||||
FUZZCHECK_OPT += -DSQLITE_ENABLE_MEMSYS5 -DSQLITE_OSS_FUZZ
|
||||
FUZZCHECK_OPT += -DSQLITE_MAX_MEMORY=50000000
|
||||
FUZZCHECK_OPT += -DSQLITE_PRINTF_PRECISION_LIMIT=1000
|
||||
FUZZCHECK_OPT += -DSQLITE_ENABLE_FTS4
|
||||
@@ -630,8 +639,14 @@ FUZZCHECK_OPT += -DSQLITE_ENABLE_RTREE
|
||||
FUZZCHECK_OPT += -DSQLITE_ENABLE_GEOPOLY
|
||||
FUZZCHECK_OPT += -DSQLITE_ENABLE_DBSTAT_VTAB
|
||||
FUZZCHECK_OPT += -DSQLITE_ENABLE_BYTECODE_VTAB
|
||||
FUZZCHECK_SRC = $(TOP)/test/fuzzcheck.c $(TOP)/test/ossfuzz.c
|
||||
FUZZCHECK_SRC += $(TOP)/test/fuzzcheck.c
|
||||
FUZZCHECK_SRC += $(TOP)/test/ossfuzz.c
|
||||
FUZZCHECK_SRC += $(TOP)/test/fuzzinvariants.c
|
||||
FUZZCHECK_SRC += $(TOP)/ext/recover/dbdata.c
|
||||
FUZZCHECK_SRC += $(TOP)/ext/recover/sqlite3recover.c
|
||||
FUZZCHECK_SRC += $(TOP)/test/vt02.c
|
||||
DBFUZZ_OPT =
|
||||
ST_OPT = -DSQLITE_OS_KV_OPTIONAL
|
||||
|
||||
# This is the default Makefile target. The objects listed here
|
||||
# are what get build when you type just "make" with no arguments.
|
||||
@@ -680,7 +695,7 @@ fuzzershell$(TEXE): $(TOP)/tool/fuzzershell.c sqlite3.c sqlite3.h
|
||||
$(LTLINK) -o $@ $(FUZZERSHELL_OPT) \
|
||||
$(TOP)/tool/fuzzershell.c sqlite3.c $(TLIBS)
|
||||
|
||||
fuzzcheck$(TEXE): $(FUZZCHECK_SRC) sqlite3.c sqlite3.h
|
||||
fuzzcheck$(TEXE): $(FUZZCHECK_SRC) sqlite3.c sqlite3.h $(FUZZCHECK_DEP)
|
||||
$(LTLINK) -o $@ $(FUZZCHECK_OPT) $(FUZZCHECK_SRC) sqlite3.c $(TLIBS)
|
||||
|
||||
ossshell$(TEXE): $(TOP)/test/ossfuzz.c $(TOP)/test/ossshell.c sqlite3.c sqlite3.h
|
||||
@@ -874,7 +889,7 @@ hash.lo: $(TOP)/src/hash.c $(HDR)
|
||||
insert.lo: $(TOP)/src/insert.c $(HDR)
|
||||
$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/insert.c
|
||||
|
||||
json.lo: $(TOP)/src/json.c
|
||||
json.lo: $(TOP)/src/json.c $(HDR)
|
||||
$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/json.c
|
||||
|
||||
legacy.lo: $(TOP)/src/legacy.c $(HDR)
|
||||
@@ -937,6 +952,9 @@ pcache1.lo: $(TOP)/src/pcache1.c $(HDR) $(TOP)/src/pcache.h
|
||||
os.lo: $(TOP)/src/os.c $(HDR)
|
||||
$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/os.c
|
||||
|
||||
os_kv.lo: $(TOP)/src/os_kv.c $(HDR)
|
||||
$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/os_kv.c
|
||||
|
||||
os_unix.lo: $(TOP)/src/os_unix.c $(HDR)
|
||||
$(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/os_unix.c
|
||||
|
||||
@@ -1101,6 +1119,9 @@ SHELL_SRC = \
|
||||
$(TOP)/ext/expert/sqlite3expert.h \
|
||||
$(TOP)/ext/misc/zipfile.c \
|
||||
$(TOP)/ext/misc/memtrace.c \
|
||||
$(TOP)/ext/recover/dbdata.c \
|
||||
$(TOP)/ext/recover/sqlite3recover.c \
|
||||
$(TOP)/ext/recover/sqlite3recover.h \
|
||||
$(TOP)/src/test_windirent.c
|
||||
|
||||
shell.c: $(SHELL_SRC) $(TOP)/tool/mkshellc.tcl
|
||||
@@ -1280,6 +1301,12 @@ valgrindfuzz: fuzzcheck$(TEXT) $(FUZZDATA) sessionfuzz$(TEXE) $(TOP)/test/sessio
|
||||
tcltest: ./testfixture$(TEXE)
|
||||
./testfixture$(TEXE) $(TOP)/test/veryquick.test $(TESTOPTS)
|
||||
|
||||
# Runs all the same tests cases as the "tcltest" target but uses
|
||||
# the testrunner.tcl script to run them in multiple cores
|
||||
# concurrently.
|
||||
testrunner: testfixture$(TEXE)
|
||||
./testfixture$(TEXE) $(TOP)/test/testrunner.tcl
|
||||
|
||||
# Minimal testing that runs in less than 3 minutes
|
||||
#
|
||||
quicktest: ./testfixture$(TEXE)
|
||||
@@ -1380,7 +1407,7 @@ LogEst$(TEXE): $(TOP)/tool/logest.c sqlite3.h
|
||||
wordcount$(TEXE): $(TOP)/test/wordcount.c sqlite3.lo
|
||||
$(LTLINK) -o $@ $(TOP)/test/wordcount.c sqlite3.lo $(TLIBS)
|
||||
|
||||
speedtest1$(TEXE): $(TOP)/test/speedtest1.c sqlite3.c
|
||||
speedtest1$(TEXE): $(TOP)/test/speedtest1.c sqlite3.c Makefile
|
||||
$(LTLINK) $(ST_OPT) -o $@ $(TOP)/test/speedtest1.c sqlite3.c $(TLIBS)
|
||||
|
||||
startup$(TEXE): $(TOP)/test/startup.c sqlite3.c
|
||||
@@ -1469,6 +1496,7 @@ clean:
|
||||
rm -rf .libs .deps
|
||||
rm -f lemon$(BEXE) lempar.c parse.* sqlite*.tar.gz
|
||||
rm -f mkkeywordhash$(BEXE) keywordhash.h
|
||||
rm -f mksourceid$(BEXE)
|
||||
rm -f *.da *.bb *.bbg gmon.out
|
||||
rm -rf tsrc .target_source
|
||||
rm -f tclsqlite3$(TEXE)
|
||||
@@ -1493,7 +1521,8 @@ clean:
|
||||
rm -f threadtest5
|
||||
|
||||
distclean: clean
|
||||
rm -f config.h config.log config.status libtool Makefile sqlite3.pc
|
||||
rm -f sqlite_cfg.h config.log config.status libtool Makefile sqlite3.pc \
|
||||
$(TESTPROGS)
|
||||
|
||||
#
|
||||
# Windows section
|
||||
@@ -1513,42 +1542,8 @@ sqlite3.dll: $(REAL_LIBOBJ) sqlite3.def
|
||||
$(TCC) -shared -o $@ sqlite3.def \
|
||||
-Wl,"--strip-all" $(REAL_LIBOBJ)
|
||||
|
||||
|
||||
#
|
||||
# fiddle/wasm section
|
||||
# Fiddle app
|
||||
#
|
||||
fiddle_dir = ext/fiddle
|
||||
fiddle_dir_abs = $(TOP)/$(fiddle_dir)
|
||||
# ^^^ some emcc opts require absolute paths
|
||||
fiddle_html = $(fiddle_dir)/fiddle.html
|
||||
fiddle_module_js = $(fiddle_dir)/fiddle-module.js
|
||||
fiddle_generated = $(fiddle_module_js) \
|
||||
$(fiddle_dir)/fiddle-module.wasm
|
||||
sqlite3_wasm_js = $(fiddle_dir)/sqlite3.js
|
||||
sqlite3_wasm = $(fiddle_dir)/sqlite3.wasm
|
||||
sqlite3_wasm_generated = $(sqlite3_wasm) $(sqlite3_wasm_js)
|
||||
clean-wasm:
|
||||
rm -f $(fiddle_generated) $(sqlite3_wasm_generated)
|
||||
clean: clean-wasm
|
||||
#emcc_opt = -O0
|
||||
#emcc_opt = -O1
|
||||
#emcc_opt = -O2
|
||||
#emcc_opt = -O3
|
||||
emcc_opt = -Oz
|
||||
emcc_flags = $(emcc_opt) -sALLOW_TABLE_GROWTH -I. $(SHELL_OPT)
|
||||
$(fiddle_module_js): Makefile sqlite3.c shell.c \
|
||||
$(fiddle_dir)/EXPORTED_RUNTIME_METHODS $(fiddle_dir)/EXPORTED_FUNCTIONS.fiddle
|
||||
emcc -o $@ $(emcc_flags) \
|
||||
-sEXPORTED_RUNTIME_METHODS=@$(fiddle_dir_abs)/EXPORTED_RUNTIME_METHODS \
|
||||
-sEXPORTED_FUNCTIONS=@$(fiddle_dir_abs)/EXPORTED_FUNCTIONS.fiddle \
|
||||
sqlite3.c shell.c
|
||||
$(sqlite3_wasm_js): Makefile sqlite3.c \
|
||||
$(fiddle_dir)/EXPORTED_RUNTIME_METHODS $(fiddle_dir)/EXPORTED_FUNCTIONS.sqlite3
|
||||
emcc -o $@ $(emcc_flags) \
|
||||
-sEXPORTED_RUNTIME_METHODS=@$(fiddle_dir_abs)/EXPORTED_RUNTIME_METHODS \
|
||||
-sEXPORTED_FUNCTIONS=@$(fiddle_dir_abs)/EXPORTED_FUNCTIONS.sqlite3 \
|
||||
--no-entry \
|
||||
sqlite3.c
|
||||
fiddle: $(fiddle_module_js)
|
||||
sqlite3-wasm: $(sqlite3_wasm_js)
|
||||
wasm: fiddle sqlite3-wasm
|
||||
fiddle: sqlite3.c shell.c
|
||||
make -C ext/wasm fiddle emcc_opt=-Os
|
||||
|
||||
+29
-3
@@ -1251,7 +1251,7 @@ LIBOBJS0 = vdbe.lo parse.lo alter.lo analyze.lo attach.lo auth.lo \
|
||||
main.lo malloc.lo mem0.lo mem1.lo mem2.lo mem3.lo mem5.lo \
|
||||
memdb.lo memjournal.lo \
|
||||
mutex.lo mutex_noop.lo mutex_unix.lo mutex_w32.lo \
|
||||
notify.lo opcodes.lo os.lo os_unix.lo os_win.lo \
|
||||
notify.lo opcodes.lo os.lo os_kv.lo os_unix.lo os_win.lo \
|
||||
pager.lo pcache.lo pcache1.lo pragma.lo prepare.lo printf.lo \
|
||||
random.lo resolve.lo rowset.lo rtree.lo \
|
||||
sqlite3session.lo select.lo sqlite3rbu.lo status.lo stmt.lo \
|
||||
@@ -1332,6 +1332,7 @@ SRC00 = \
|
||||
$(TOP)\src\mutex_w32.c \
|
||||
$(TOP)\src\notify.c \
|
||||
$(TOP)\src\os.c \
|
||||
$(TOP)\src\os_kv.c \
|
||||
$(TOP)\src\os_unix.c \
|
||||
$(TOP)\src\os_win.c
|
||||
|
||||
@@ -1587,6 +1588,9 @@ TESTEXT = \
|
||||
$(TOP)\ext\misc\unionvtab.c \
|
||||
$(TOP)\ext\misc\wholenumber.c \
|
||||
$(TOP)\ext\rtree\test_rtreedoc.c \
|
||||
$(TOP)\ext\recover\sqlite3recover.c \
|
||||
$(TOP)\ext\recover\test_recover.c \
|
||||
$(TOP)\ext\recover\dbdata.c \
|
||||
fts5.c
|
||||
|
||||
# If use of zlib is enabled, add the "zipfile.c" source file.
|
||||
@@ -1697,15 +1701,25 @@ SHELL_COMPILE_OPTS = $(SHELL_COMPILE_OPTS) -DSQLITE_ENABLE_OFFSET_SQL_FUNC=1
|
||||
#
|
||||
MPTESTER_COMPILE_OPTS = -DSQLITE_ENABLE_FTS5
|
||||
FUZZERSHELL_COMPILE_OPTS =
|
||||
FUZZCHECK_OPTS = -DSQLITE_ENABLE_MEMSYS5 -DSQLITE_OSS_FUZZ -DSQLITE_MAX_MEMORY=50000000 -DSQLITE_PRINTF_PRECISION_LIMIT=1000
|
||||
FUZZCHECK_OPTS = $(FUZZCHECK_OPTS) -I$(TOP)\test -I$(TOP)\ext\recover
|
||||
FUZZCHECK_OPTS = $(FUZZCHECK_OPTS) -DSQLITE_ENABLE_MEMSYS5
|
||||
FUZZCHECK_OPTS = $(FUZZCHECK_OPTS) -DSQLITE_OSS_FUZZ
|
||||
FUZZCHECK_OPTS = $(FUZZCHECK_OPTS) -DSQLITE_MAX_MEMORY=50000000
|
||||
FUZZCHECK_OPTS = $(FUZZCHECK_OPTS) -DSQLITE_PRINTF_PRECISION_LIMIT=1000
|
||||
FUZZCHECK_OPTS = $(FUZZCHECK_OPTS) -DSQLITE_OMIT_LOAD_EXTENSION
|
||||
FUZZCHECK_OPTS = $(FUZZCHECK_OPTS) -DSQLITE_ENABLE_FTS4
|
||||
FUZZCHECK_OPTS = $(FUZZCHECK_OPTS) -DSQLITE_ENABLE_FTS5
|
||||
FUZZCHECK_OPTS = $(FUZZCHECK_OPTS) -DSQLITE_ENABLE_RTREE
|
||||
FUZZCHECK_OPTS = $(FUZZCHECK_OPTS) -DSQLITE_ENABLE_GEOPOLY
|
||||
FUZZCHECK_OPTS = $(FUZZCHECK_OPTS) -DSQLITE_ENABLE_DBSTAT_VTAB
|
||||
FUZZCHECK_OPTS = $(FUZZCHECK_OPTS) -DSQLITE_ENABLE_BYTECODE_VTAB
|
||||
FUZZCHECK_SRC = $(FUZZCHECK_SRC) $(TOP)\test\fuzzcheck.c
|
||||
FUZZCHECK_SRC = $(FUZZCHECK_SRC) $(TOP)\test\ossfuzz.c
|
||||
FUZZCHECK_SRC = $(FUZZCHECK_SRC) $(TOP)\test\fuzzinvariants.c
|
||||
FUZZCHECK_SRC = $(FUZZCHECK_SRC) $(TOP)\test\vt02.c
|
||||
FUZZCHECK_SRC = $(FUZZCHECK_SRC) $(TOP)\ext\recover\dbdata.c
|
||||
FUZZCHECK_SRC = $(FUZZCHECK_SRC) $(TOP)\ext\recover\sqlite3recover.c
|
||||
|
||||
FUZZCHECK_SRC = $(TOP)\test\fuzzcheck.c $(TOP)\test\ossfuzz.c
|
||||
OSSSHELL_SRC = $(TOP)\test\ossshell.c $(TOP)\test\ossfuzz.c
|
||||
DBFUZZ_COMPILE_OPTS = -DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_LOAD_EXTENSION
|
||||
KV_COMPILE_OPTS = -DSQLITE_THREADSAFE=0 -DSQLITE_DIRECT_OVERFLOW_READ
|
||||
@@ -2053,6 +2067,9 @@ pcache1.lo: $(TOP)\src\pcache1.c $(HDR) $(TOP)\src\pcache.h
|
||||
os.lo: $(TOP)\src\os.c $(HDR)
|
||||
$(LTCOMPILE) $(CORE_COMPILE_OPTS) -c $(TOP)\src\os.c
|
||||
|
||||
os_kv.lo: $(TOP)\src\os_kv.c $(HDR)
|
||||
$(LTCOMPILE) $(CORE_COMPILE_OPTS) -c $(TOP)\src\os_kv.c
|
||||
|
||||
os_unix.lo: $(TOP)\src\os_unix.c $(HDR)
|
||||
$(LTCOMPILE) $(CORE_COMPILE_OPTS) -c $(TOP)\src\os_unix.c
|
||||
|
||||
@@ -2224,6 +2241,9 @@ SHELL_SRC = \
|
||||
$(TOP)\ext\expert\sqlite3expert.c \
|
||||
$(TOP)\ext\expert\sqlite3expert.h \
|
||||
$(TOP)\ext\misc\memtrace.c \
|
||||
$(TOP)/ext/recover/dbdata.c \
|
||||
$(TOP)/ext/recover/sqlite3recover.c \
|
||||
$(TOP)/ext/recover/sqlite3recover.h \
|
||||
$(TOP)\src\test_windirent.c
|
||||
|
||||
# If use of zlib is enabled, add the "zipfile.c" source file.
|
||||
@@ -2475,6 +2495,12 @@ tcltest: testfixture.exe
|
||||
@set PATH=$(LIBTCLPATH);$(PATH)
|
||||
.\testfixture.exe $(TOP)\test\veryquick.test $(TESTOPTS)
|
||||
|
||||
# Runs all the same tests cases as the "tcltest" target but uses
|
||||
# the testrunner.tcl script to run them in multiple cores
|
||||
# concurrently.
|
||||
testrunner: testfixture.exe
|
||||
.\testfixture.exe $(TOP)\test\testrunner.tcl
|
||||
|
||||
smoketest: $(TESTPROGS)
|
||||
@set PATH=$(LIBTCLPATH);$(PATH)
|
||||
.\testfixture.exe $(TOP)\test\main.test $(TESTOPTS)
|
||||
|
||||
+109
-74
@@ -11,8 +11,6 @@
|
||||
#
|
||||
# See the file "license.terms" for information on usage and redistribution
|
||||
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
|
||||
#
|
||||
# RCS: @(#) $Id: Makefile.in,v 1.59 2005/07/26 19:17:02 mdejong Exp $
|
||||
|
||||
#========================================================================
|
||||
# Add additional lines to handle any additional AC_SUBST cases that
|
||||
@@ -60,6 +58,8 @@ PKG_HEADERS = @PKG_HEADERS@
|
||||
#========================================================================
|
||||
|
||||
PKG_LIB_FILE = @PKG_LIB_FILE@
|
||||
PKG_LIB_FILE8 = @PKG_LIB_FILE8@
|
||||
PKG_LIB_FILE9 = @PKG_LIB_FILE9@
|
||||
PKG_STUB_LIB_FILE = @PKG_STUB_LIB_FILE@
|
||||
|
||||
lib_BINARIES = $(PKG_LIB_FILE)
|
||||
@@ -73,10 +73,11 @@ exec_prefix = @exec_prefix@
|
||||
|
||||
bindir = @bindir@
|
||||
libdir = @libdir@
|
||||
includedir = @includedir@
|
||||
datarootdir = @datarootdir@
|
||||
runstatedir = @runstatedir@
|
||||
datadir = @datadir@
|
||||
mandir = @mandir@
|
||||
includedir = @includedir@
|
||||
|
||||
DESTDIR =
|
||||
|
||||
@@ -85,24 +86,25 @@ pkgdatadir = $(datadir)/$(PKG_DIR)
|
||||
pkglibdir = $(libdir)/$(PKG_DIR)
|
||||
pkgincludedir = $(includedir)/$(PKG_DIR)
|
||||
|
||||
top_builddir = .
|
||||
top_builddir = @abs_top_builddir@
|
||||
|
||||
INSTALL = @INSTALL@
|
||||
INSTALL_PROGRAM = @INSTALL_PROGRAM@
|
||||
INSTALL_OPTIONS =
|
||||
INSTALL = @INSTALL@ $(INSTALL_OPTIONS)
|
||||
INSTALL_DATA_DIR = @INSTALL_DATA_DIR@
|
||||
INSTALL_DATA = @INSTALL_DATA@
|
||||
INSTALL_PROGRAM = @INSTALL_PROGRAM@
|
||||
INSTALL_SCRIPT = @INSTALL_SCRIPT@
|
||||
INSTALL_LIBRARY = @INSTALL_LIBRARY@
|
||||
|
||||
PACKAGE_NAME = @PACKAGE_NAME@
|
||||
PACKAGE_VERSION = @PACKAGE_VERSION@
|
||||
CC = @CC@
|
||||
CCLD = @CCLD@
|
||||
CFLAGS_DEFAULT = @CFLAGS_DEFAULT@
|
||||
CFLAGS_WARNING = @CFLAGS_WARNING@
|
||||
CLEANFILES = @CLEANFILES@
|
||||
EXEEXT = @EXEEXT@
|
||||
LDFLAGS_DEFAULT = @LDFLAGS_DEFAULT@
|
||||
MAKE_LIB = @MAKE_LIB@
|
||||
MAKE_SHARED_LIB = @MAKE_SHARED_LIB@
|
||||
MAKE_STATIC_LIB = @MAKE_STATIC_LIB@
|
||||
MAKE_STUB_LIB = @MAKE_STUB_LIB@
|
||||
OBJEXT = @OBJEXT@
|
||||
RANLIB = @RANLIB@
|
||||
@@ -117,8 +119,6 @@ TCL_SRC_DIR = @TCL_SRC_DIR@
|
||||
#TK_BIN_DIR = @TK_BIN_DIR@
|
||||
#TK_SRC_DIR = @TK_SRC_DIR@
|
||||
|
||||
# This is no longer necessary even for packages that use private Tcl headers
|
||||
#TCL_TOP_DIR_NATIVE = @TCL_TOP_DIR_NATIVE@
|
||||
# Not used, but retained for reference of what libs Tcl required
|
||||
#TCL_LIBS = @TCL_LIBS@
|
||||
|
||||
@@ -132,41 +132,52 @@ TCL_SRC_DIR = @TCL_SRC_DIR@
|
||||
EXTRA_PATH = $(top_builddir):$(TCL_BIN_DIR)
|
||||
#EXTRA_PATH = $(top_builddir):$(TCL_BIN_DIR):$(TK_BIN_DIR)
|
||||
TCLLIBPATH = $(top_builddir)
|
||||
TCLSH_ENV = TCL_LIBRARY=`@CYGPATH@ $(TCL_SRC_DIR)/library` \
|
||||
@LD_LIBRARY_PATH_VAR@="$(EXTRA_PATH):$(@LD_LIBRARY_PATH_VAR@)" \
|
||||
TCLSH_ENV = TCL_LIBRARY=`@CYGPATH@ $(TCL_SRC_DIR)/library`
|
||||
PKG_ENV = @LD_LIBRARY_PATH_VAR@="$(EXTRA_PATH):$(@LD_LIBRARY_PATH_VAR@)" \
|
||||
PATH="$(EXTRA_PATH):$(PATH)" \
|
||||
TCLLIBPATH="$(TCLLIBPATH)"
|
||||
# TK_LIBRARY=`@CYGPATH@ $(TK_SRC_DIR)/library`
|
||||
|
||||
TCLSH_PROG = @TCLSH_PROG@
|
||||
TCLSH = $(TCLSH_ENV) $(TCLSH_PROG)
|
||||
TCLSH = $(TCLSH_ENV) $(PKG_ENV) $(TCLSH_PROG)
|
||||
|
||||
#WISH_ENV = TK_LIBRARY=`@CYGPATH@ $(TK_SRC_DIR)/library`
|
||||
#WISH_PROG = @WISH_PROG@
|
||||
#WISH = $(TCLSH_ENV) $(WISH_PROG)
|
||||
|
||||
#WISH = $(TCLSH_ENV) $(WISH_ENV) $(PKG_ENV) $(WISH_PROG)
|
||||
|
||||
SHARED_BUILD = @SHARED_BUILD@
|
||||
|
||||
INCLUDES = @PKG_INCLUDES@ @TCL_INCLUDES@ -I$(srcdir)/..
|
||||
INCLUDES = @PKG_INCLUDES@ @TCL_INCLUDES@ -I. -I$(srcdir)/..
|
||||
#INCLUDES = @PKG_INCLUDES@ @TCL_INCLUDES@ @TK_INCLUDES@ @TK_XINCLUDES@
|
||||
|
||||
PKG_CFLAGS = @PKG_CFLAGS@
|
||||
|
||||
# TCL_DEFS is not strictly need here, but if you remove it, then you
|
||||
# must make sure that configure.in checks for the necessary components
|
||||
# must make sure that configure.ac checks for the necessary components
|
||||
# that your library may use. TCL_DEFS can actually be a problem if
|
||||
# you do not compile with a similar machine setup as the Tcl core was
|
||||
# compiled with.
|
||||
#DEFS = $(TCL_DEFS) @DEFS@ $(PKG_CFLAGS)
|
||||
DEFS = @DEFS@ $(PKG_CFLAGS)
|
||||
|
||||
# Move pkgIndex.tcl to 'BINARIES' var if it is generated in the Makefile
|
||||
CONFIG_CLEAN_FILES = Makefile pkgIndex.tcl
|
||||
CLEANFILES = @CLEANFILES@
|
||||
|
||||
CPPFLAGS = @CPPFLAGS@
|
||||
LIBS = @PKG_LIBS@ @LIBS@
|
||||
AR = @AR@
|
||||
CFLAGS = @CFLAGS@
|
||||
COMPILE = $(CC) $(DEFS) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
|
||||
LDFLAGS = @LDFLAGS@
|
||||
LDFLAGS_DEFAULT = @LDFLAGS_DEFAULT@
|
||||
COMPILE = $(CC) $(DEFS) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) \
|
||||
$(CFLAGS_DEFAULT) $(CFLAGS_WARNING) $(SHLIB_CFLAGS) $(CFLAGS)
|
||||
|
||||
GDB = gdb
|
||||
VALGRIND = valgrind
|
||||
VALGRINDARGS = --tool=memcheck --num-callers=8 --leak-resolution=high \
|
||||
--leak-check=yes --show-reachable=yes -v
|
||||
|
||||
.SUFFIXES: .c .$(OBJEXT)
|
||||
|
||||
#========================================================================
|
||||
# Start of user-definable TARGETS section
|
||||
@@ -174,7 +185,7 @@ COMPILE = $(CC) $(DEFS) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(C
|
||||
|
||||
#========================================================================
|
||||
# TEA TARGETS. Please note that the "libraries:" target refers to platform
|
||||
# independent files, and the "binaries:" target inclues executable programs and
|
||||
# independent files, and the "binaries:" target includes executable programs and
|
||||
# platform-dependent libraries. Modify these targets so that they install
|
||||
# the various pieces of your package. The make and install rules
|
||||
# for the BINARIES that you specified above have already been done.
|
||||
@@ -193,7 +204,6 @@ binaries: $(BINARIES)
|
||||
|
||||
libraries:
|
||||
|
||||
|
||||
#========================================================================
|
||||
# Your doc target should differentiate from doc builds (by the developer)
|
||||
# and doc installs (see install-doc), which just install the docs on the
|
||||
@@ -216,11 +226,11 @@ install-binaries: binaries install-lib-binaries install-bin-binaries
|
||||
#========================================================================
|
||||
|
||||
install-libraries: libraries
|
||||
@mkdir -p $(DESTDIR)$(includedir)
|
||||
@$(INSTALL_DATA_DIR) "$(DESTDIR)$(includedir)"
|
||||
@echo "Installing header files in $(DESTDIR)$(includedir)"
|
||||
@list='$(PKG_HEADERS)'; for i in $$list; do \
|
||||
echo "Installing $(srcdir)/$$i" ; \
|
||||
$(INSTALL_DATA) $(srcdir)/$$i $(DESTDIR)$(includedir) ; \
|
||||
$(INSTALL_DATA) $(srcdir)/$$i "$(DESTDIR)$(includedir)" ; \
|
||||
done;
|
||||
|
||||
#========================================================================
|
||||
@@ -229,12 +239,11 @@ install-libraries: libraries
|
||||
#========================================================================
|
||||
|
||||
install-doc: doc
|
||||
@mkdir -p $(DESTDIR)$(mandir)/mann
|
||||
@$(INSTALL_DATA_DIR) "$(DESTDIR)$(mandir)/mann"
|
||||
@echo "Installing documentation in $(DESTDIR)$(mandir)"
|
||||
@list='$(srcdir)/doc/*.n'; for i in $$list; do \
|
||||
echo "Installing $$i"; \
|
||||
rm -f $(DESTDIR)$(mandir)/mann/`basename $$i`; \
|
||||
$(INSTALL_DATA) $$i $(DESTDIR)$(mandir)/mann ; \
|
||||
$(INSTALL_DATA) $$i "$(DESTDIR)$(mandir)/mann" ; \
|
||||
done
|
||||
|
||||
test: binaries libraries
|
||||
@@ -244,7 +253,21 @@ shell: binaries libraries
|
||||
@$(TCLSH) $(SCRIPT)
|
||||
|
||||
gdb:
|
||||
$(TCLSH_ENV) gdb $(TCLSH_PROG) $(SCRIPT)
|
||||
$(TCLSH_ENV) $(PKG_ENV) $(GDB) $(TCLSH_PROG) $(SCRIPT)
|
||||
|
||||
gdb-test: binaries libraries
|
||||
$(TCLSH_ENV) $(PKG_ENV) $(GDB) \
|
||||
--args $(TCLSH_PROG) `@CYGPATH@ $(srcdir)/tests/all.tcl` \
|
||||
$(TESTFLAGS) -singleproc 1 \
|
||||
-load "package ifneeded $(PACKAGE_NAME) $(PACKAGE_VERSION) \
|
||||
[list load `@CYGPATH@ $(PKG_LIB_FILE)` [string totitle $(PACKAGE_NAME)]]"
|
||||
|
||||
valgrind: binaries libraries
|
||||
$(TCLSH_ENV) $(PKG_ENV) $(VALGRIND) $(VALGRINDARGS) $(TCLSH_PROG) \
|
||||
`@CYGPATH@ $(srcdir)/tests/all.tcl` $(TESTFLAGS)
|
||||
|
||||
valgrindshell: binaries libraries
|
||||
$(TCLSH_ENV) $(PKG_ENV) $(VALGRIND) $(VALGRINDARGS) $(TCLSH_PROG) $(SCRIPT)
|
||||
|
||||
depend:
|
||||
|
||||
@@ -283,49 +306,70 @@ $(PKG_STUB_LIB_FILE): $(PKG_STUB_OBJECTS)
|
||||
# As necessary, add $(srcdir):$(srcdir)/compat:....
|
||||
#========================================================================
|
||||
|
||||
VPATH = $(srcdir):$(srcdir)/generic:$(srcdir)/unix:$(srcdir)/win
|
||||
VPATH = $(srcdir):$(srcdir)/generic:$(srcdir)/unix:$(srcdir)/win:$(srcdir)/macosx
|
||||
|
||||
.c.@OBJEXT@:
|
||||
$(COMPILE) -c `@CYGPATH@ $<` -o $@
|
||||
|
||||
tclsample.@OBJEXT@: sampleUuid.h
|
||||
|
||||
$(srcdir)/manifest.uuid:
|
||||
printf "git-" >$(srcdir)/manifest.uuid
|
||||
(cd $(srcdir); git rev-parse HEAD >>$(srcdir)/manifest.uuid || \
|
||||
(printf "svn-r" >$(srcdir)/manifest.uuid ; \
|
||||
svn info --show-item last-changed-revision >>$(srcdir)/manifest.uuid) || \
|
||||
printf "unknown" >$(srcdir)/manifest.uuid)
|
||||
|
||||
sampleUuid.h: $(srcdir)/manifest.uuid
|
||||
echo "#define SAMPLE_VERSION_UUID \\" >$@
|
||||
cat $(srcdir)/manifest.uuid >>$@
|
||||
echo "" >>$@
|
||||
|
||||
#========================================================================
|
||||
# Distribution creation
|
||||
# You may need to tweak this target to make it work correctly.
|
||||
#========================================================================
|
||||
|
||||
#COMPRESS = tar cvf $(PKG_DIR).tar $(PKG_DIR); compress $(PKG_DIR).tar
|
||||
COMPRESS = gtar zcvf $(PKG_DIR).tar.gz $(PKG_DIR)
|
||||
COMPRESS = tar zcvf $(PKG_DIR).tar.gz $(PKG_DIR)
|
||||
DIST_ROOT = /tmp/dist
|
||||
DIST_DIR = $(DIST_ROOT)/$(PKG_DIR)
|
||||
|
||||
DIST_INSTALL_DATA = CPPROG='cp -p' $(INSTALL) -m 644
|
||||
DIST_INSTALL_SCRIPT = CPPROG='cp -p' $(INSTALL) -m 755
|
||||
|
||||
dist-clean:
|
||||
rm -rf $(DIST_DIR) $(DIST_ROOT)/$(PKG_DIR).tar.*
|
||||
|
||||
dist: dist-clean
|
||||
mkdir -p $(DIST_DIR)
|
||||
cp -p $(srcdir)/README* $(srcdir)/license* \
|
||||
$(srcdir)/aclocal.m4 $(srcdir)/configure $(srcdir)/*.in \
|
||||
$(DIST_DIR)/
|
||||
chmod 664 $(DIST_DIR)/Makefile.in $(DIST_DIR)/aclocal.m4
|
||||
chmod 775 $(DIST_DIR)/configure $(DIST_DIR)/configure.in
|
||||
dist: dist-clean $(srcdir)/manifest.uuid
|
||||
$(INSTALL_DATA_DIR) $(DIST_DIR)
|
||||
|
||||
for i in $(srcdir)/*.[ch]; do \
|
||||
if [ -f $$i ]; then \
|
||||
cp -p $$i $(DIST_DIR)/ ; \
|
||||
fi; \
|
||||
done;
|
||||
# TEA files
|
||||
$(DIST_INSTALL_DATA) $(srcdir)/Makefile.in \
|
||||
$(srcdir)/aclocal.m4 $(srcdir)/configure.ac \
|
||||
$(DIST_DIR)/
|
||||
$(DIST_INSTALL_SCRIPT) $(srcdir)/configure $(DIST_DIR)/
|
||||
|
||||
mkdir $(DIST_DIR)/tclconfig
|
||||
cp $(srcdir)/tclconfig/install-sh $(srcdir)/tclconfig/tcl.m4 \
|
||||
$(DIST_DIR)/tclconfig/
|
||||
chmod 664 $(DIST_DIR)/tclconfig/tcl.m4
|
||||
chmod +x $(DIST_DIR)/tclconfig/install-sh
|
||||
$(INSTALL_DATA_DIR) $(DIST_DIR)/tclconfig
|
||||
$(DIST_INSTALL_DATA) $(srcdir)/tclconfig/README.txt \
|
||||
$(srcdir)/manifest.uuid \
|
||||
$(srcdir)/tclconfig/tcl.m4 $(srcdir)/tclconfig/install-sh \
|
||||
$(DIST_DIR)/tclconfig/
|
||||
|
||||
list='demos doc generic library mac tests unix win'; \
|
||||
# Extension files
|
||||
$(DIST_INSTALL_DATA) \
|
||||
$(srcdir)/ChangeLog \
|
||||
$(srcdir)/README.sha \
|
||||
$(srcdir)/license.terms \
|
||||
$(srcdir)/README \
|
||||
$(srcdir)/pkgIndex.tcl.in \
|
||||
$(DIST_DIR)/
|
||||
|
||||
list='demos doc generic library macosx tests unix win'; \
|
||||
for p in $$list; do \
|
||||
if test -d $(srcdir)/$$p ; then \
|
||||
mkdir $(DIST_DIR)/$$p; \
|
||||
cp -p $(srcdir)/$$p/*.* $(DIST_DIR)/$$p/; \
|
||||
$(INSTALL_DATA_DIR) $(DIST_DIR)/$$p; \
|
||||
$(DIST_INSTALL_DATA) $(srcdir)/$$p/* $(DIST_DIR)/$$p/; \
|
||||
fi; \
|
||||
done
|
||||
|
||||
@@ -337,10 +381,10 @@ dist: dist-clean
|
||||
|
||||
#========================================================================
|
||||
# Don't modify the file to clean here. Instead, set the "CLEANFILES"
|
||||
# variable in configure.in
|
||||
# variable in configure.ac
|
||||
#========================================================================
|
||||
|
||||
clean:
|
||||
clean:
|
||||
-test -z "$(BINARIES)" || rm -f $(BINARIES)
|
||||
-rm -f *.$(OBJEXT) core *.core
|
||||
-test -z "$(CLEANFILES)" || rm -f $(CLEANFILES)
|
||||
@@ -348,7 +392,7 @@ clean:
|
||||
distclean: clean
|
||||
-rm -f *.tab.c
|
||||
-rm -f $(CONFIG_CLEAN_FILES)
|
||||
-rm -f config.h config.cache config.log config.status
|
||||
-rm -f config.cache config.log config.status
|
||||
|
||||
#========================================================================
|
||||
# Install binary object libraries. On Windows this includes both .dll and
|
||||
@@ -362,25 +406,17 @@ distclean: clean
|
||||
#========================================================================
|
||||
|
||||
install-lib-binaries: binaries
|
||||
@mkdir -p $(DESTDIR)$(pkglibdir)
|
||||
@$(INSTALL_DATA_DIR) "$(DESTDIR)$(pkglibdir)"
|
||||
@list='$(lib_BINARIES)'; for p in $$list; do \
|
||||
if test -f $$p; then \
|
||||
echo " $(INSTALL_PROGRAM) $$p $(DESTDIR)$(pkglibdir)/$$p"; \
|
||||
$(INSTALL_PROGRAM) $$p $(DESTDIR)$(pkglibdir)/$$p; \
|
||||
stub=`echo $$p|sed -e "s/.*\(stub\).*/\1/"`; \
|
||||
if test "x$$stub" = "xstub"; then \
|
||||
echo " $(RANLIB_STUB) $(DESTDIR)$(pkglibdir)/$$p"; \
|
||||
$(RANLIB_STUB) $(DESTDIR)$(pkglibdir)/$$p; \
|
||||
else \
|
||||
echo " $(RANLIB) $(DESTDIR)$(pkglibdir)/$$p"; \
|
||||
$(RANLIB) $(DESTDIR)$(pkglibdir)/$$p; \
|
||||
fi; \
|
||||
echo " $(INSTALL_LIBRARY) $$p $(DESTDIR)$(pkglibdir)/$$p"; \
|
||||
$(INSTALL_LIBRARY) $$p "$(DESTDIR)$(pkglibdir)/$$p"; \
|
||||
ext=`echo $$p|sed -e "s/.*\.//"`; \
|
||||
if test "x$$ext" = "xdll"; then \
|
||||
lib=`basename $$p|sed -e 's/.[^.]*$$//'`.lib; \
|
||||
if test -f $$lib; then \
|
||||
echo " $(INSTALL_DATA) $$lib $(DESTDIR)$(pkglibdir)/$$lib"; \
|
||||
$(INSTALL_DATA) $$lib $(DESTDIR)$(pkglibdir)/$$lib; \
|
||||
$(INSTALL_DATA) $$lib "$(DESTDIR)$(pkglibdir)/$$lib"; \
|
||||
fi; \
|
||||
fi; \
|
||||
fi; \
|
||||
@@ -389,12 +425,12 @@ install-lib-binaries: binaries
|
||||
if test -f $(srcdir)/$$p; then \
|
||||
destp=`basename $$p`; \
|
||||
echo " Install $$destp $(DESTDIR)$(pkglibdir)/$$destp"; \
|
||||
$(INSTALL_DATA) $(srcdir)/$$p $(DESTDIR)$(pkglibdir)/$$destp; \
|
||||
$(INSTALL_DATA) $(srcdir)/$$p "$(DESTDIR)$(pkglibdir)/$$destp"; \
|
||||
fi; \
|
||||
done
|
||||
@if test "x$(SHARED_BUILD)" = "x1"; then \
|
||||
echo " Install pkgIndex.tcl $(DESTDIR)$(pkglibdir)"; \
|
||||
$(INSTALL_DATA) pkgIndex.tcl $(DESTDIR)$(pkglibdir); \
|
||||
$(INSTALL_DATA) pkgIndex.tcl "$(DESTDIR)$(pkglibdir)"; \
|
||||
fi
|
||||
|
||||
#========================================================================
|
||||
@@ -407,33 +443,32 @@ install-lib-binaries: binaries
|
||||
#========================================================================
|
||||
|
||||
install-bin-binaries: binaries
|
||||
@mkdir -p $(DESTDIR)$(bindir)
|
||||
@$(INSTALL_DATA_DIR) "$(DESTDIR)$(bindir)"
|
||||
@list='$(bin_BINARIES)'; for p in $$list; do \
|
||||
if test -f $$p; then \
|
||||
echo " $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/$$p"; \
|
||||
$(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/$$p; \
|
||||
$(INSTALL_PROGRAM) $$p "$(DESTDIR)$(bindir)/$$p"; \
|
||||
fi; \
|
||||
done
|
||||
|
||||
.SUFFIXES: .c .$(OBJEXT)
|
||||
|
||||
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
|
||||
cd $(top_builddir) \
|
||||
&& CONFIG_FILES=$@ CONFIG_HEADERS= $(SHELL) ./config.status
|
||||
|
||||
uninstall-binaries:
|
||||
list='$(lib_BINARIES)'; for p in $$list; do \
|
||||
rm -f $(DESTDIR)$(pkglibdir)/$$p; \
|
||||
rm -f "$(DESTDIR)$(pkglibdir)/$$p"; \
|
||||
done
|
||||
list='$(PKG_TCL_SOURCES)'; for p in $$list; do \
|
||||
p=`basename $$p`; \
|
||||
rm -f $(DESTDIR)$(pkglibdir)/$$p; \
|
||||
rm -f "$(DESTDIR)$(pkglibdir)/$$p"; \
|
||||
done
|
||||
list='$(bin_BINARIES)'; for p in $$list; do \
|
||||
rm -f $(DESTDIR)$(bindir)/$$p; \
|
||||
rm -f "$(DESTDIR)$(bindir)/$$p"; \
|
||||
done
|
||||
|
||||
.PHONY: all binaries clean depend distclean doc install libraries test
|
||||
.PHONY: gdb gdb-test valgrind valgrindshell
|
||||
|
||||
# Tell versions [3.59,3.63) of GNU make to not export all variables.
|
||||
# Otherwise a system limit (for SysV at least) may be exceeded.
|
||||
|
||||
+60
-34
@@ -2,11 +2,9 @@
|
||||
dnl This file is an input file used by the GNU "autoconf" program to
|
||||
dnl generate the file "configure", which is run during Tcl installation
|
||||
dnl to configure the system for the local environment.
|
||||
#
|
||||
# RCS: @(#) $Id: configure.in,v 1.43 2005/07/26 19:17:05 mdejong Exp $
|
||||
|
||||
#-----------------------------------------------------------------------
|
||||
# Sample configure.in for Tcl Extensions. The only places you should
|
||||
# Sample configure.ac for Tcl Extensions. The only places you should
|
||||
# need to modify this file are marked by the string __CHANGE__
|
||||
#-----------------------------------------------------------------------
|
||||
|
||||
@@ -17,9 +15,11 @@ dnl to configure the system for the local environment.
|
||||
# This initializes the environment with PACKAGE_NAME and PACKAGE_VERSION
|
||||
# set as provided. These will also be added as -D defs in your Makefile
|
||||
# so you can encode the package version directly into the source files.
|
||||
# This will also define a special symbol for Windows (BUILD_<PACKAGE_NAME>
|
||||
# so that we create the export library with the dll.
|
||||
#-----------------------------------------------------------------------
|
||||
|
||||
AC_INIT([sqlite], [3.32.0])
|
||||
AC_INIT([sqlite],[3.40.0])
|
||||
|
||||
#--------------------------------------------------------------------
|
||||
# Call TEA_INIT as the first TEA_ macro to set up initial vars.
|
||||
@@ -27,7 +27,7 @@ AC_INIT([sqlite], [3.32.0])
|
||||
# as well as PKG_LIB_FILE and PKG_STUB_LIB_FILE.
|
||||
#--------------------------------------------------------------------
|
||||
|
||||
TEA_INIT([3.9])
|
||||
TEA_INIT()
|
||||
|
||||
AC_CONFIG_AUX_DIR(tclconfig)
|
||||
|
||||
@@ -55,8 +55,8 @@ TEA_PREFIX
|
||||
#-----------------------------------------------------------------------
|
||||
# Standard compiler checks.
|
||||
# This sets up CC by using the CC env var, or looks for gcc otherwise.
|
||||
# This also calls AC_PROG_CC, AC_PROG_INSTALL and a few others to create
|
||||
# the basic setup necessary to compile executables.
|
||||
# This also calls AC_PROG_CC and a few others to create the basic setup
|
||||
# necessary to compile executables.
|
||||
#-----------------------------------------------------------------------
|
||||
|
||||
TEA_SETUP_COMPILER
|
||||
@@ -73,11 +73,19 @@ TEA_SETUP_COMPILER
|
||||
|
||||
TEA_ADD_SOURCES([tclsqlite3.c])
|
||||
TEA_ADD_HEADERS([])
|
||||
TEA_ADD_INCLUDES([-I\"`\${CYGPATH} \${srcdir}/generic`\"])
|
||||
TEA_ADD_INCLUDES([])
|
||||
TEA_ADD_LIBS([])
|
||||
TEA_ADD_CFLAGS([-DSQLITE_ENABLE_FTS3=1])
|
||||
TEA_ADD_CFLAGS([-DSQLITE_ENABLE_FTS4=1])
|
||||
TEA_ADD_CFLAGS([-DSQLITE_ENABLE_FTS5=1])
|
||||
TEA_ADD_CFLAGS([-DSQLITE_3_SUFFIX_ONLY=1])
|
||||
TEA_ADD_CFLAGS([-DSQLITE_ENABLE_RTREE=1])
|
||||
TEA_ADD_CFLAGS([-DSQLITE_ENABLE_GEOPOLY=1])
|
||||
TEA_ADD_CFLAGS([-DSQLITE_ENABLE_MATH_FUNCTIONS=1])
|
||||
TEA_ADD_CFLAGS([-DSQLITE_ENABLE_DESERIALIZE=1])
|
||||
TEA_ADD_CFLAGS([-DSQLITE_ENABLE_DBPAGE_VTAB=1])
|
||||
TEA_ADD_CFLAGS([-DSQLITE_ENABLE_BYTECODE_VTAB=1])
|
||||
TEA_ADD_CFLAGS([-DSQLITE_ENABLE_DBSTAT_VTAB=1])
|
||||
TEA_ADD_STUB_SOURCES([])
|
||||
TEA_ADD_TCL_SOURCES([])
|
||||
|
||||
@@ -99,6 +107,31 @@ if test x$with_system_sqlite != xno; then
|
||||
LIBS="$LIBS -lsqlite3"])])
|
||||
fi
|
||||
|
||||
#--------------------------------------------------------------------
|
||||
# __CHANGE__
|
||||
#
|
||||
# You can add more files to clean if your extension creates any extra
|
||||
# files by extending CLEANFILES.
|
||||
# Add pkgIndex.tcl if it is generated in the Makefile instead of ./configure
|
||||
# and change Makefile.in to move it from CONFIG_CLEAN_FILES to BINARIES var.
|
||||
#
|
||||
# A few miscellaneous platform-specific items:
|
||||
# TEA_ADD_* any platform specific compiler/build info here.
|
||||
#--------------------------------------------------------------------
|
||||
|
||||
#CLEANFILES="$CLEANFILES pkgIndex.tcl"
|
||||
if test "${TEA_PLATFORM}" = "windows" ; then
|
||||
# Ensure no empty if clauses
|
||||
:
|
||||
#TEA_ADD_SOURCES([win/winFile.c])
|
||||
#TEA_ADD_INCLUDES([-I\"$(${CYGPATH} ${srcdir}/win)\"])
|
||||
else
|
||||
# Ensure no empty else clauses
|
||||
:
|
||||
#TEA_ADD_SOURCES([unix/unixFile.c])
|
||||
#TEA_ADD_LIBS([-lsuperfly])
|
||||
fi
|
||||
|
||||
#--------------------------------------------------------------------
|
||||
# __CHANGE__
|
||||
# Choose which headers you need. Extension authors should try very
|
||||
@@ -151,28 +184,6 @@ TEA_CONFIG_CFLAGS
|
||||
|
||||
TEA_ENABLE_SYMBOLS
|
||||
|
||||
#--------------------------------------------------------------------
|
||||
# Everyone should be linking against the Tcl stub library. If you
|
||||
# can't for some reason, remove this definition. If you aren't using
|
||||
# stubs, you also need to modify the SHLIB_LD_LIBS setting below to
|
||||
# link against the non-stubbed Tcl library. Add Tk too if necessary.
|
||||
#--------------------------------------------------------------------
|
||||
|
||||
AC_DEFINE(USE_TCL_STUBS, 1, [Use Tcl stubs])
|
||||
#AC_DEFINE(USE_TK_STUBS, 1, [Use Tk stubs])
|
||||
|
||||
|
||||
#--------------------------------------------------------------------
|
||||
# Redefine fdatasync as fsync on systems that lack fdatasync
|
||||
#--------------------------------------------------------------------
|
||||
#
|
||||
#AC_CHECK_FUNC(fdatasync, , AC_DEFINE(fdatasync, fsync))
|
||||
# Check for library functions that SQLite can optionally use.
|
||||
AC_CHECK_FUNCS([fdatasync usleep fullfsync localtime_r gmtime_r])
|
||||
|
||||
AC_FUNC_STRERROR_R
|
||||
|
||||
|
||||
#--------------------------------------------------------------------
|
||||
# This macro generates a line to use when building a library. It
|
||||
# depends on values set by the TEA_ENABLE_SHARED, TEA_ENABLE_SYMBOLS,
|
||||
@@ -193,9 +204,24 @@ TEA_PROG_TCLSH
|
||||
#TEA_PROG_WISH
|
||||
|
||||
#--------------------------------------------------------------------
|
||||
# Finally, substitute all of the various values into the Makefile.
|
||||
# You may alternatively have a special pkgIndex.tcl.in or other files
|
||||
# which require substituting th AC variables in. Include these here.
|
||||
# Setup a *Config.sh.in configuration file.
|
||||
#--------------------------------------------------------------------
|
||||
|
||||
AC_OUTPUT([Makefile pkgIndex.tcl])
|
||||
#TEA_EXPORT_CONFIG([sample])
|
||||
#AC_SUBST(SAMPLE_VAR)
|
||||
|
||||
#--------------------------------------------------------------------
|
||||
# Specify files to substitute AC variables in. You may alternatively
|
||||
# have a special pkgIndex.tcl.in or other files which require
|
||||
# substituting the AC variables in. Include these here.
|
||||
#--------------------------------------------------------------------
|
||||
|
||||
AC_CONFIG_FILES([Makefile pkgIndex.tcl])
|
||||
#AC_CONFIG_FILES([sampleConfig.sh])
|
||||
|
||||
#--------------------------------------------------------------------
|
||||
# Finally, substitute all of the various values into the files
|
||||
# specified with AC_CONFIG_FILES.
|
||||
#--------------------------------------------------------------------
|
||||
|
||||
AC_OUTPUT
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
# -*- tcl -*-
|
||||
# Tcl package index file, version 1.1
|
||||
#
|
||||
# Tcl package index file
|
||||
#
|
||||
# Note sqlite*3* init specifically
|
||||
#
|
||||
package ifneeded sqlite3 @PACKAGE_VERSION@ \
|
||||
[list load [file join $dir @PKG_LIB_FILE@] Sqlite3]
|
||||
if {[package vsatisfies [package provide Tcl] 9.0-]} {
|
||||
package ifneeded sqlite3 @PACKAGE_VERSION@ \
|
||||
[list load [file join $dir @PKG_LIB_FILE9@] sqlite3]
|
||||
} else {
|
||||
package ifneeded sqlite3 @PACKAGE_VERSION@ \
|
||||
[list load [file join $dir @PKG_LIB_FILE8@] sqlite3]
|
||||
}
|
||||
|
||||
+525
-626
File diff suppressed because it is too large
Load Diff
@@ -251,7 +251,18 @@ INCLUDES = $(SQL_INCLUDES) $(TCL_INCLUDES) -I"$(WINDIR)" \
|
||||
-I"$(GENERICDIR)" -I"$(ROOT)\.."
|
||||
BASE_CLFAGS = $(cflags) $(cdebug) $(crt) $(INCLUDES) \
|
||||
-DSQLITE_3_SUFFIX_ONLY=1 -DSQLITE_ENABLE_RTREE=1 \
|
||||
-DSQLITE_ENABLE_FTS3=1 -DSQLITE_OMIT_DEPRECATED=1
|
||||
-DSQLITE_ENABLE_FTS3=1 -DSQLITE_OMIT_DEPRECATED=1 \
|
||||
-DSQLITE_ENABLE_FTS4=1 \
|
||||
-DSQLITE_ENABLE_FTS5=1 \
|
||||
-DSQLITE_3_SUFFIX_ONLY=1 \
|
||||
-DSQLITE_ENABLE_RTREE=1 \
|
||||
-DSQLITE_ENABLE_GEOPOLY=1 \
|
||||
-DSQLITE_ENABLE_MATH_FUNCTIONS=1 \
|
||||
-DSQLITE_ENABLE_DESERIALIZE=1 \
|
||||
-DSQLITE_ENABLE_DBPAGE_VTAB=1 \
|
||||
-DSQLITE_ENABLE_BYTECODE_VTAB=1 \
|
||||
-DSQLITE_ENABLE_DBSTAT_VTAB=1
|
||||
|
||||
CON_CFLAGS = $(cflags) $(cdebug) $(crt) -DCONSOLE -DSQLITE_ENABLE_FTS3=1
|
||||
TCL_CFLAGS = -DBUILD_sqlite -DUSE_TCL_STUBS \
|
||||
-DPACKAGE_VERSION="\"$(DOTVERSION)\"" $(BASE_CLFAGS) \
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#! /bin/sh
|
||||
# Guess values for system-dependent variables and create Makefiles.
|
||||
# Generated by GNU Autoconf 2.69 for sqlite 3.39.0.
|
||||
# Generated by GNU Autoconf 2.69 for sqlite 3.40.0.
|
||||
#
|
||||
#
|
||||
# Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
|
||||
@@ -726,8 +726,8 @@ MAKEFLAGS=
|
||||
# Identity of this package.
|
||||
PACKAGE_NAME='sqlite'
|
||||
PACKAGE_TARNAME='sqlite'
|
||||
PACKAGE_VERSION='3.39.0'
|
||||
PACKAGE_STRING='sqlite 3.39.0'
|
||||
PACKAGE_VERSION='3.40.0'
|
||||
PACKAGE_STRING='sqlite 3.40.0'
|
||||
PACKAGE_BUGREPORT=''
|
||||
PACKAGE_URL=''
|
||||
|
||||
@@ -1468,7 +1468,7 @@ if test "$ac_init_help" = "long"; then
|
||||
# Omit some internal or obsolete options to make the list less imposing.
|
||||
# This message is too long to be a string in the A/UX 3.1 sh.
|
||||
cat <<_ACEOF
|
||||
\`configure' configures sqlite 3.39.0 to adapt to many kinds of systems.
|
||||
\`configure' configures sqlite 3.40.0 to adapt to many kinds of systems.
|
||||
|
||||
Usage: $0 [OPTION]... [VAR=VALUE]...
|
||||
|
||||
@@ -1533,7 +1533,7 @@ fi
|
||||
|
||||
if test -n "$ac_init_help"; then
|
||||
case $ac_init_help in
|
||||
short | recursive ) echo "Configuration of sqlite 3.39.0:";;
|
||||
short | recursive ) echo "Configuration of sqlite 3.40.0:";;
|
||||
esac
|
||||
cat <<\_ACEOF
|
||||
|
||||
@@ -1661,7 +1661,7 @@ fi
|
||||
test -n "$ac_init_help" && exit $ac_status
|
||||
if $ac_init_version; then
|
||||
cat <<\_ACEOF
|
||||
sqlite configure 3.39.0
|
||||
sqlite configure 3.40.0
|
||||
generated by GNU Autoconf 2.69
|
||||
|
||||
Copyright (C) 2012 Free Software Foundation, Inc.
|
||||
@@ -2080,7 +2080,7 @@ cat >config.log <<_ACEOF
|
||||
This file contains any messages produced by compilers while
|
||||
running configure, to aid debugging if configure makes a mistake.
|
||||
|
||||
It was created by sqlite $as_me 3.39.0, which was
|
||||
It was created by sqlite $as_me 3.40.0, which was
|
||||
generated by GNU Autoconf 2.69. Invocation command line was
|
||||
|
||||
$ $0 $@
|
||||
@@ -11875,7 +11875,7 @@ fi
|
||||
|
||||
#########
|
||||
# Output the config header
|
||||
ac_config_headers="$ac_config_headers config.h"
|
||||
ac_config_headers="$ac_config_headers sqlite_cfg.h"
|
||||
|
||||
|
||||
#########
|
||||
@@ -12390,7 +12390,7 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
|
||||
# report actual input values of CONFIG_FILES etc. instead of their
|
||||
# values after options handling.
|
||||
ac_log="
|
||||
This file was extended by sqlite $as_me 3.39.0, which was
|
||||
This file was extended by sqlite $as_me 3.40.0, which was
|
||||
generated by GNU Autoconf 2.69. Invocation command line was
|
||||
|
||||
CONFIG_FILES = $CONFIG_FILES
|
||||
@@ -12456,7 +12456,7 @@ _ACEOF
|
||||
cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
|
||||
ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
|
||||
ac_cs_version="\\
|
||||
sqlite config.status 3.39.0
|
||||
sqlite config.status 3.40.0
|
||||
configured by $0, generated by GNU Autoconf 2.69,
|
||||
with options \\"\$ac_cs_config\\"
|
||||
|
||||
@@ -12838,7 +12838,7 @@ for ac_config_target in $ac_config_targets
|
||||
do
|
||||
case $ac_config_target in
|
||||
"libtool") CONFIG_COMMANDS="$CONFIG_COMMANDS libtool" ;;
|
||||
"config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;;
|
||||
"sqlite_cfg.h") CONFIG_HEADERS="$CONFIG_HEADERS sqlite_cfg.h" ;;
|
||||
"Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;;
|
||||
"sqlite3.pc") CONFIG_FILES="$CONFIG_FILES sqlite3.pc" ;;
|
||||
|
||||
|
||||
+1
-1
@@ -806,7 +806,7 @@ AC_SUBST(AMALGAMATION_LINE_MACROS)
|
||||
|
||||
#########
|
||||
# Output the config header
|
||||
AC_CONFIG_HEADERS(config.h)
|
||||
AC_CONFIG_HEADERS(sqlite_cfg.h)
|
||||
|
||||
#########
|
||||
# Generate the output files.
|
||||
|
||||
@@ -391,6 +391,16 @@ do_setup_rec_test $tn.18.1 {
|
||||
SEARCH SomeObject USING COVERING INDEX SomeObject_idx_00000078 (x=?)
|
||||
}
|
||||
|
||||
|
||||
do_setup_rec_test $tn.19.0 {
|
||||
CREATE TABLE t1("index");
|
||||
} {
|
||||
SELECT * FROM t1 ORDER BY "index";
|
||||
} {
|
||||
CREATE INDEX t1_idx_01a7214e ON t1('index');
|
||||
SCAN t1 USING COVERING INDEX t1_idx_01a7214e
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
proc do_candidates_test {tn sql res} {
|
||||
|
||||
@@ -820,6 +820,10 @@ static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
|
||||
*/
|
||||
static int idxIdentifierRequiresQuotes(const char *zId){
|
||||
int i;
|
||||
int nId = STRLEN(zId);
|
||||
|
||||
if( sqlite3_keyword_check(zId, nId) ) return 1;
|
||||
|
||||
for(i=0; zId[i]; i++){
|
||||
if( !(zId[i]=='_')
|
||||
&& !(zId[i]>='0' && zId[i]<='9')
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
_fiddle_exec
|
||||
_fiddle_interrupt
|
||||
_fiddle_experiment
|
||||
_fiddle_the_db
|
||||
_fiddle_db_arg
|
||||
@@ -1,11 +0,0 @@
|
||||
ccall
|
||||
cwrap
|
||||
stackAlloc
|
||||
stackSave
|
||||
stackRestore
|
||||
UTF8ToString
|
||||
removeFunction
|
||||
addFunction
|
||||
setValue
|
||||
getValue
|
||||
allocate
|
||||
@@ -1,33 +0,0 @@
|
||||
# This GNU makefile exists primarily to simplify/speed up development
|
||||
# from emacs. It is not part of the canonical build process.
|
||||
default:
|
||||
make -C ../.. wasm -e emcc_opt=-O0
|
||||
|
||||
clean:
|
||||
make -C ../../ clean-wasm
|
||||
|
||||
fiddle_files = emscripten.css fiddle.html \
|
||||
fiddle.js fiddle-module.js \
|
||||
fiddle-module.wasm fiddle-worker.js
|
||||
|
||||
# fiddle_remote is the remote destination for the fiddle app. It
|
||||
# must be a [user@]HOST:/path for rsync.
|
||||
# Note that the target "should probably" contain a symlink of
|
||||
# index.html -> fiddle.html.
|
||||
fiddle_remote ?=
|
||||
ifeq (,$(fiddle_remote))
|
||||
ifneq (,$(wildcard /home/stephan))
|
||||
fiddle_remote = wh2:www/wh/sqlite3/.
|
||||
else ifneq (,$(wildcard /home/drh))
|
||||
#fiddle_remote = if appropriate, add that user@host:/path here
|
||||
endif
|
||||
endif
|
||||
|
||||
$(fiddle_files): default
|
||||
|
||||
push-fiddle: $(fiddle_files)
|
||||
@if [ x = "x$(fiddle_remote)" ]; then \
|
||||
echo "fiddle_remote must be a [user@]HOST:/path for rsync"; \
|
||||
exit 1; \
|
||||
fi
|
||||
rsync -va $(fiddle_files) $(fiddle_remote)
|
||||
@@ -1,54 +0,0 @@
|
||||
/**
|
||||
Helpers for writing sqlite3-specific tests.
|
||||
*/
|
||||
self/*window or worker*/.SqliteTestUtil = {
|
||||
/** Running total of the number of tests run via
|
||||
this API. */
|
||||
counter: 0,
|
||||
/**
|
||||
If expr is a function, it is called and its result
|
||||
is returned, coerced to a bool, else expr, coerced to
|
||||
a bool, is returned.
|
||||
*/
|
||||
toBool: function(expr){
|
||||
return (expr instanceof Function) ? !!expr() : !!expr;
|
||||
},
|
||||
/** abort() if expr is false. If expr is a function, it
|
||||
is called and its result is evaluated.
|
||||
*/
|
||||
assert: function(expr, msg){
|
||||
++this.counter;
|
||||
if(!this.toBool(expr)) abort(msg || "Assertion failed.");
|
||||
return this;
|
||||
},
|
||||
/** Identical to assert() but throws instead of calling
|
||||
abort(). */
|
||||
affirm: function(expr, msg){
|
||||
++this.counter;
|
||||
if(!this.toBool(expr)) throw new Error(msg || "Affirmation failed.");
|
||||
return this;
|
||||
},
|
||||
/** Calls f() and squelches any exception it throws. If it
|
||||
does not throw, this function throws. */
|
||||
mustThrow: function(f, msg){
|
||||
++this.counter;
|
||||
let err;
|
||||
try{ f(); } catch(e){err=e;}
|
||||
if(!err) throw new Error(msg || "Expected exception.");
|
||||
return this;
|
||||
},
|
||||
/** Throws if expr is truthy or expr is a function and expr()
|
||||
returns truthy. */
|
||||
throwIf: function(expr, msg){
|
||||
++this.counter;
|
||||
if(this.toBool(expr)) throw new Error(msg || "throwIf() failed");
|
||||
return this;
|
||||
},
|
||||
/** Throws if expr is falsy or expr is a function and expr()
|
||||
returns falsy. */
|
||||
throwUnless: function(expr, msg){
|
||||
++this.counter;
|
||||
if(!this.toBool(expr)) throw new Error(msg || "throwUnless() failed");
|
||||
return this;
|
||||
}
|
||||
};
|
||||
@@ -1,197 +0,0 @@
|
||||
/*
|
||||
2022-05-20
|
||||
|
||||
The author disclaims copyright to this source code. In place of a
|
||||
legal notice, here is a blessing:
|
||||
|
||||
* May you do good and not evil.
|
||||
* May you find forgiveness for yourself and forgive others.
|
||||
* May you share freely, never taking more than you give.
|
||||
|
||||
***********************************************************************
|
||||
|
||||
This is the JS Worker file for the sqlite3 fiddle app. It loads the
|
||||
sqlite3 wasm module and offers access to the db via the Worker
|
||||
message-passing interface.
|
||||
|
||||
Forewarning: this API is still very much Under Construction and
|
||||
subject to any number of changes as experience reveals what those
|
||||
need to be.
|
||||
|
||||
Because we can have only a single message handler, as opposed to an
|
||||
arbitrary number of discrete event listeners like with DOM elements,
|
||||
we have to define a lower-level message API. Messages abstractly
|
||||
look like:
|
||||
|
||||
{ type: string, data: type-specific value }
|
||||
|
||||
Where 'type' is used for dispatching and 'data' is a
|
||||
'type'-dependent value.
|
||||
|
||||
The 'type' values expected by each side of the main/worker
|
||||
connection vary. The types are described below but subject to
|
||||
change at any time as this experiment evolves.
|
||||
|
||||
Workers-to-Main types
|
||||
|
||||
- stdout, stderr: indicate stdout/stderr output from the wasm
|
||||
layer. The data property is the string of the output, noting
|
||||
that the emscripten binding emits these one line at a time. Thus,
|
||||
if a C-side puts() emits multiple lines in a single call, the JS
|
||||
side will see that as multiple calls. Example:
|
||||
|
||||
{type:'stdout', data: 'Hi, world.'}
|
||||
|
||||
- module: Status text. This is intended to alert the main thread
|
||||
about module loading status so that, e.g., the main thread can
|
||||
update a progress widget and DTRT when the module is finished
|
||||
loading and available for work. Status messages come in the form
|
||||
|
||||
{type:'module', data:{
|
||||
type:'status',
|
||||
data: {text:string|null, step:1-based-integer}
|
||||
}
|
||||
|
||||
with an incrementing step value for each subsequent message. When
|
||||
the module loading is complete, a message with a text value of
|
||||
null is posted.
|
||||
|
||||
- working: data='start'|'end'. Indicates that work is about to be
|
||||
sent to the module or has just completed. This can be used, e.g.,
|
||||
to disable UI elements which should not be activated while work
|
||||
is pending. Example:
|
||||
|
||||
{type:'working', data:'start'}
|
||||
|
||||
Main-to-Worker types:
|
||||
|
||||
- shellExec: data=text to execute as if it had been entered in the
|
||||
sqlite3 CLI shell app (as opposed to sqlite3_exec()). This event
|
||||
causes the worker to emit a 'working' event (data='start') before
|
||||
it starts and a 'working' event (data='end') when it finished. If
|
||||
called while work is currently being executed it emits stderr
|
||||
message instead of doing actual work, as the underlying db cannot
|
||||
handle concurrent tasks. Example:
|
||||
|
||||
{type:'shellExec', data: 'select * from sqlite_master'}
|
||||
|
||||
- More TBD as the higher-level db layer develops.
|
||||
*/
|
||||
|
||||
/*
|
||||
Apparent browser(s) bug: console messages emitted may be duplicated
|
||||
in the console, even though they're provably only run once. See:
|
||||
|
||||
https://stackoverflow.com/questions/49659464
|
||||
|
||||
Noting that it happens in Firefox as well as Chrome. Harmless but
|
||||
annoying.
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
const wMsg = (type,data)=>postMessage({type, data});
|
||||
|
||||
self.onerror = function(/*message, source, lineno, colno, error*/) {
|
||||
const err = arguments[4];
|
||||
if(err && 'ExitStatus'==err.name){
|
||||
/* This is relevant for the sqlite3 shell binding but not the
|
||||
lower-level binding. */
|
||||
Module._isDead = true;
|
||||
Module.printErr("FATAL ERROR:", err.message);
|
||||
Module.printErr("Restarting the app requires reloading the page.");
|
||||
wMsg('error', err);
|
||||
}
|
||||
Module.setStatus('Exception thrown, see JavaScript console');
|
||||
Module.setStatus = function(text) {
|
||||
console.error('[post-exception status]', text);
|
||||
};
|
||||
};
|
||||
|
||||
self.Module = {
|
||||
/* ^^^ cannot declare that const because fiddle-module.js
|
||||
(auto-generated) includes a decl for it and runs in this scope. */
|
||||
preRun: [],
|
||||
postRun: [],
|
||||
//onRuntimeInitialized: function(){},
|
||||
print: function(text){wMsg('stdout', Array.prototype.slice.call(arguments));},
|
||||
printErr: function(text){wMsg('stderr', Array.prototype.slice.call(arguments));},
|
||||
/**
|
||||
Intercepts status updates from the Module object and fires
|
||||
worker events with a type of 'status' and a payload of:
|
||||
|
||||
{
|
||||
text: string | null, // null at end of load process
|
||||
step: integer // starts at 1, increments 1 per call
|
||||
}
|
||||
|
||||
We have no way of knowing in advance how many steps will
|
||||
be processed/posted, so creating a "percentage done" view is
|
||||
not really practical. One can be approximated by giving it a
|
||||
current value of message.step and max value of message.step+1,
|
||||
though.
|
||||
|
||||
When work is finished, a message with a text value of null is
|
||||
submitted.
|
||||
|
||||
After a message with text==null is posted, the module may later
|
||||
post messages about fatal problems, e.g. an exit() being
|
||||
triggered, so it is recommended that UI elements for posting
|
||||
status messages not be outright removed from the DOM when
|
||||
text==null, and that they instead be hidden until/unless
|
||||
text!=null.
|
||||
*/
|
||||
setStatus: function f(text){
|
||||
if(!f.last) f.last = { step: 0, text: '' };
|
||||
else if(text === f.last.text) return;
|
||||
f.last.text = text;
|
||||
wMsg('module',{
|
||||
type:'status',
|
||||
data:{step: ++f.last.step, text: text||null}
|
||||
});
|
||||
},
|
||||
totalDependencies: 0,
|
||||
monitorRunDependencies: function(left) {
|
||||
this.totalDependencies = Math.max(this.totalDependencies, left);
|
||||
this.setStatus(left
|
||||
? ('Preparing... (' + (this.totalDependencies-left)
|
||||
+ '/' + this.totalDependencies + ')')
|
||||
: 'All downloads complete.');
|
||||
}
|
||||
};
|
||||
|
||||
const shellExec = function f(sql){
|
||||
if(!f._) f._ = Module.cwrap('fiddle_exec', null, ['string']);
|
||||
if(Module._isDead){
|
||||
wMsg('stderr', "shell module has exit()ed. Cannot run SQL.");
|
||||
return;
|
||||
}
|
||||
wMsg('working','start');
|
||||
try {
|
||||
if(f._running) wMsg('stderr','Cannot run multiple commands concurrently.');
|
||||
else{
|
||||
f._running = true;
|
||||
f._(sql);
|
||||
}
|
||||
} finally {
|
||||
wMsg('working','end');
|
||||
delete f._running;
|
||||
}
|
||||
};
|
||||
|
||||
self.onmessage = function(ev){
|
||||
ev = ev.data;
|
||||
//console.debug("worker: onmessage.data",ev);
|
||||
switch(ev.type){
|
||||
case 'shellExec': shellExec(ev.data); return;
|
||||
};
|
||||
console.warn("Unknown fiddle-worker message type:",ev);
|
||||
};
|
||||
self.Module.setStatus('Downloading...');
|
||||
importScripts('fiddle-module.js')
|
||||
/* loads the wasm module and notifies, via Module.setStatus() and
|
||||
Module.onRuntimeInitialized(), when it's done loading. The latter
|
||||
is called _before_ the final call to Module.setStatus(). */;
|
||||
|
||||
Module["onRuntimeInitialized"] = function onRuntimeInitialized() {
|
||||
wMsg('fiddle-ready');
|
||||
};
|
||||
@@ -1,199 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en-us">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
||||
<title>sqlite3 fiddle</title>
|
||||
<!--script src="jqterm/jqterm-bundle.min.js"></script>
|
||||
<link rel="stylesheet" href="jqterm/jquery.terminal.min.css"/-->
|
||||
<link rel="stylesheet" href="emscripten.css"/>
|
||||
<style>
|
||||
/* The following styles are for app-level use. */
|
||||
textarea {
|
||||
font-family: monospace;
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
header {
|
||||
font-size: 130%;
|
||||
font-weight: bold;
|
||||
}
|
||||
#main-wrapper {
|
||||
display: flex;
|
||||
flex-direction: column-reverse;
|
||||
flex: 20 1 auto;
|
||||
}
|
||||
#main-wrapper.side-by-side {
|
||||
flex-direction: row-reverse;
|
||||
}
|
||||
#main-wrapper.swapio {
|
||||
flex-direction: column;
|
||||
}
|
||||
#main-wrapper.side-by-side.swapio {
|
||||
flex-direction: row;
|
||||
}
|
||||
.ta-wrapper{
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
margin: 0 0.25em;
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
.ta-wrapper.input { flex: 10 1 auto; }
|
||||
.ta-wrapper.output { flex: 20 1 auto; }
|
||||
.ta-wrapper textarea {
|
||||
font-size: 110%;
|
||||
filter: invert(100%);
|
||||
flex: 10 1 auto;
|
||||
}
|
||||
.button-bar {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
flex: 0 1 auto;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.button-bar button {
|
||||
margin: 0.25em 1em;
|
||||
}
|
||||
label[for] {
|
||||
cursor: pointer;
|
||||
}
|
||||
fieldset {
|
||||
border-radius: 0.5em;
|
||||
}
|
||||
.error {
|
||||
color: red;
|
||||
background-color: yellow;
|
||||
}
|
||||
.hidden, .initially-hidden {
|
||||
position: absolute !important;
|
||||
opacity: 0 !important;
|
||||
pointer-events: none !important;
|
||||
display: none !important;
|
||||
}
|
||||
fieldset.options {
|
||||
font-size: 75%;
|
||||
}
|
||||
fieldset > legend {
|
||||
padding: 0 0.5em;
|
||||
}
|
||||
span.labeled-input {
|
||||
padding: 0.25em;
|
||||
margin: 0.25em 0.5em;
|
||||
border-radius: 0.25em;
|
||||
white-space: nowrap;
|
||||
background: #0002;
|
||||
}
|
||||
#notes-caveats {
|
||||
border-top: 1px dotted;
|
||||
padding-top: 0.25em;
|
||||
margin-top: 0.5em;
|
||||
}
|
||||
.center { text-align: center; }
|
||||
|
||||
body.terminal-mode {
|
||||
max-height: calc(100% - 2em);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
#view-terminal {
|
||||
}
|
||||
.app-view {
|
||||
flex: 20 1 auto;
|
||||
}
|
||||
#titlebar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 0.5em;
|
||||
}
|
||||
#view-split {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header id='titlebar'><span>sqlite3 fiddle</span></header>
|
||||
<!-- emscripten bits -->
|
||||
<figure id="module-spinner">
|
||||
<div class="spinner"></div>
|
||||
<div class='center'><strong>Initializing app...</strong></div>
|
||||
<div class='center'>
|
||||
On a slow internet connection this may take a moment. If this
|
||||
message displays for "a long time", intialization may have
|
||||
failed and the JavaScript console may contain clues as to why.
|
||||
</div>
|
||||
</figure>
|
||||
<div class="emscripten" id="module-status">Downloading...</div>
|
||||
<div class="emscripten">
|
||||
<progress value="0" max="100" id="module-progress" hidden='1'></progress>
|
||||
</div><!-- /emscripten bits -->
|
||||
|
||||
<div id='view-terminal' class='app-view hidden initially-hidden'>
|
||||
This is a placeholder for a terminal-like view.
|
||||
</div>
|
||||
|
||||
<div id='view-split' class='app-view initially-hidden'>
|
||||
<fieldset class='options'>
|
||||
<legend>Options</legend>
|
||||
<div class=''>
|
||||
<span class='labeled-input'>
|
||||
<input type='checkbox' id='opt-cb-sbs'
|
||||
data-csstgt='#main-wrapper'
|
||||
data-cssclass='side-by-side'
|
||||
data-config='sideBySide'>
|
||||
<label for='opt-cb-sbs'>Side-by-side</label>
|
||||
</span>
|
||||
<span class='labeled-input'>
|
||||
<input type='checkbox' id='opt-cb-swapio'
|
||||
data-csstgt='#main-wrapper'
|
||||
data-cssclass='swapio'
|
||||
data-config='swapInOut'>
|
||||
<label for='opt-cb-swapio'>Swap in/out</label>
|
||||
</span>
|
||||
<span class='labeled-input'>
|
||||
<input type='checkbox' id='opt-cb-autoscroll'
|
||||
data-config='autoScrollOutput'>
|
||||
<label for='opt-cb-autoscroll'>Auto-scroll output</label>
|
||||
</span>
|
||||
<span class='labeled-input'>
|
||||
<input type='checkbox' id='opt-cb-autoclear'
|
||||
data-config='autoClearOutput'>
|
||||
<label for='opt-cb-autoclear'>Auto-clear output</label>
|
||||
</span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<div id='main-wrapper' class=''>
|
||||
<div class='ta-wrapper input'>
|
||||
<textarea id="input"
|
||||
placeholder="Shell input. Ctrl-enter/shift-enter runs it.">
|
||||
-- Use ctrl-enter or shift-enter to execute SQL
|
||||
.nullvalue NULL
|
||||
.mode box
|
||||
CREATE TABLE t(a,b);
|
||||
INSERT INTO t(a,b) VALUES('abc',123),('def',456),(NULL,789),('ghi',012);
|
||||
SELECT * FROM t;</textarea>
|
||||
<div class='button-bar'>
|
||||
<button id='btn-shell-exec'>Run</button>
|
||||
<button id='btn-clear'>Clear Input</button>
|
||||
<button data-cmd='.help'>Help</button>
|
||||
<select id='select-examples'></select>
|
||||
</div>
|
||||
</div>
|
||||
<div class='ta-wrapper output'>
|
||||
<textarea id="output" readonly
|
||||
placeholder="Shell output."></textarea>
|
||||
<div class='button-bar'>
|
||||
<button id='btn-clear-output'>Clear Output</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div> <!-- #view-split -->
|
||||
<!-- Maintenance notes:
|
||||
|
||||
... TODO... currently being refactored...
|
||||
|
||||
-->
|
||||
<script src="fiddle.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,480 +0,0 @@
|
||||
/*
|
||||
2022-05-20
|
||||
|
||||
The author disclaims copyright to this source code. In place of a
|
||||
legal notice, here is a blessing:
|
||||
|
||||
* May you do good and not evil.
|
||||
* May you find forgiveness for yourself and forgive others.
|
||||
* May you share freely, never taking more than you give.
|
||||
|
||||
***********************************************************************
|
||||
|
||||
This is the main entry point for the sqlite3 fiddle app. It sets up the
|
||||
various UI bits, loads a Worker for the db connection, and manages the
|
||||
communication between the UI and worker.
|
||||
*/
|
||||
(function(){
|
||||
'use strict';
|
||||
|
||||
/* Recall that the 'self' symbol, except where locally
|
||||
overwritten, refers to the global window or worker object. */
|
||||
|
||||
/**
|
||||
The SqliteFiddle object is intended to be the primary
|
||||
app-level object for the main-thread side of the sqlite
|
||||
fiddle application. It uses a worker thread to load the
|
||||
sqlite WASM module and communicate with it.
|
||||
*/
|
||||
const SF/*local convenience alias*/
|
||||
= window.SqliteFiddle/*canonical name*/ = {
|
||||
/* Config options. */
|
||||
config: {
|
||||
/* If true, SqliteFiddle.echo() will auto-scroll the
|
||||
output widget to the bottom when it receives output,
|
||||
else it won't. */
|
||||
autoScrollOutput: true,
|
||||
/* If true, the output area will be cleared before each
|
||||
command is run, else it will not. */
|
||||
autoClearOutput: false,
|
||||
/* If true, SqliteFiddle.echo() will echo its output to
|
||||
the console, in addition to its normal output widget.
|
||||
That slows it down but is useful for testing. */
|
||||
echoToConsole: false,
|
||||
/* If true, display input/output areas side-by-side. */
|
||||
sideBySide: false,
|
||||
/* If true, swap positions of the input/output areas. */
|
||||
swapInOut: false
|
||||
},
|
||||
/**
|
||||
Emits the given text, followed by a line break, to the
|
||||
output widget. If given more than one argument, they are
|
||||
join()'d together with a space between each. As a special
|
||||
case, if passed a single array, that array is used in place
|
||||
of the arguments array (this is to facilitate receiving
|
||||
lists of arguments via worker events).
|
||||
*/
|
||||
echo: function f(text) {
|
||||
/* Maintenance reminder: we currently require/expect a textarea
|
||||
output element. It might be nice to extend this to behave
|
||||
differently if the output element is a non-textarea element,
|
||||
in which case it would need to append the given text as a TEXT
|
||||
node and add a line break. */
|
||||
if(!f._){
|
||||
f._ = document.getElementById('output');
|
||||
f._.value = ''; // clear browser cache
|
||||
}
|
||||
if(arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
|
||||
else if(1===arguments.length && Array.isArray(text)) text = text.join(' ');
|
||||
// These replacements are necessary if you render to raw HTML
|
||||
//text = text.replace(/&/g, "&");
|
||||
//text = text.replace(/</g, "<");
|
||||
//text = text.replace(/>/g, ">");
|
||||
//text = text.replace('\n', '<br>', 'g');
|
||||
if(null===text){/*special case: clear output*/
|
||||
f._.value = '';
|
||||
return;
|
||||
}else if(this.echo._clearPending){
|
||||
delete this.echo._clearPending;
|
||||
f._.value = '';
|
||||
}
|
||||
if(this.config.echoToConsole) console.log(text);
|
||||
if(this.jqTerm) window.Module.jqTerm.echo(text);
|
||||
f._.value += text + "\n";
|
||||
if(this.config.autoScrollOutput){
|
||||
f._.scrollTop = f._.scrollHeight;
|
||||
}
|
||||
},
|
||||
_msgMap: {},
|
||||
addMsgHandler: function f(type,callback){
|
||||
if(Array.isArray(type)){
|
||||
type.forEach((t)=>this.addMsgHandler(t, callback));
|
||||
return this;
|
||||
}
|
||||
(this._msgMap.hasOwnProperty(type)
|
||||
? this._msgMap[type]
|
||||
: (this._msgMap[type] = [])).push(callback);
|
||||
return this;
|
||||
},
|
||||
runMsgHandlers: function(msg){
|
||||
const list = (this._msgMap.hasOwnProperty(msg.type)
|
||||
? this._msgMap[msg.type] : false);
|
||||
if(!list){
|
||||
console.warn("No handlers found for message type:",msg);
|
||||
return false;
|
||||
}
|
||||
//console.debug("runMsgHandlers",msg);
|
||||
list.forEach((f)=>f(msg));
|
||||
return true;
|
||||
},
|
||||
clearMsgHandlers: function(type){
|
||||
delete this._msgMap[type];
|
||||
return this;
|
||||
},
|
||||
/* Posts a message in the form {type, data} to the db worker. Returns this. */
|
||||
wMsg: function(type,data){
|
||||
this.worker.postMessage({type, data});
|
||||
return this;
|
||||
}
|
||||
};
|
||||
|
||||
SF.worker = new Worker('fiddle-worker.js');
|
||||
SF.worker.onmessage = (ev)=>SF.runMsgHandlers(ev.data);
|
||||
SF.addMsgHandler(['stdout', 'stderr'], (ev)=>SF.echo(ev.data));
|
||||
|
||||
/* querySelectorAll() proxy */
|
||||
const EAll = function(/*[element=document,] cssSelector*/){
|
||||
return (arguments.length>1 ? arguments[0] : document)
|
||||
.querySelectorAll(arguments[arguments.length-1]);
|
||||
};
|
||||
/* querySelector() proxy */
|
||||
const E = function(/*[element=document,] cssSelector*/){
|
||||
return (arguments.length>1 ? arguments[0] : document)
|
||||
.querySelector(arguments[arguments.length-1]);
|
||||
};
|
||||
|
||||
/** Handles status updates from the Module object. */
|
||||
SF.addMsgHandler('module', function f(ev){
|
||||
ev = ev.data;
|
||||
if('status'!==ev.type){
|
||||
console.warn("Unexpected module-type message:",ev);
|
||||
return;
|
||||
}
|
||||
if(!f.ui){
|
||||
f.ui = {
|
||||
status: E('#module-status'),
|
||||
progress: E('#module-progress'),
|
||||
spinner: E('#module-spinner')
|
||||
};
|
||||
}
|
||||
const msg = ev.data;
|
||||
if(f.ui.progres){
|
||||
progress.value = msg.step;
|
||||
progress.max = msg.step + 1/*we don't know how many steps to expect*/;
|
||||
}
|
||||
if(1==msg.step){
|
||||
f.ui.progress.classList.remove('hidden');
|
||||
f.ui.spinner.classList.remove('hidden');
|
||||
}
|
||||
if(msg.text){
|
||||
f.ui.status.classList.remove('hidden');
|
||||
f.ui.status.innerText = msg.text;
|
||||
}else{
|
||||
if(f.ui.progress){
|
||||
f.ui.progress.remove();
|
||||
f.ui.spinner.remove();
|
||||
delete f.ui.progress;
|
||||
delete f.ui.spinner;
|
||||
}
|
||||
f.ui.status.classList.add('hidden');
|
||||
/* The module can post messages about fatal problems,
|
||||
e.g. an exit() being triggered or assertion failure,
|
||||
after the last "load" message has arrived, so
|
||||
leave f.ui.status and message listener intact. */
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
The 'fiddle-ready' event is fired (with no payload) when the
|
||||
wasm module has finished loading. Interestingly, that happens
|
||||
_before_ the final module:status event */
|
||||
SF.addMsgHandler('fiddle-ready', function(){
|
||||
SF.clearMsgHandlers('fiddle-ready');
|
||||
self.onSFLoaded();
|
||||
});
|
||||
|
||||
/**
|
||||
Performs all app initialization which must wait until after the
|
||||
worker module is loaded. This function removes itself when it's
|
||||
called.
|
||||
*/
|
||||
self.onSFLoaded = function(){
|
||||
delete this.onSFLoaded;
|
||||
// Unhide all elements which start out hidden
|
||||
EAll('.initially-hidden').forEach((e)=>e.classList.remove('initially-hidden'));
|
||||
|
||||
const taInput = E('#input');
|
||||
const btnClearIn = E('#btn-clear');
|
||||
btnClearIn.addEventListener('click',function(){
|
||||
taInput.value = '';
|
||||
},false);
|
||||
// Ctrl-enter and shift-enter both run the current SQL.
|
||||
taInput.addEventListener('keydown',function(ev){
|
||||
if((ev.ctrlKey || ev.shiftKey) && 13 === ev.keyCode){
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
btnShellExec.click();
|
||||
}
|
||||
}, false);
|
||||
const taOutput = E('#output');
|
||||
const btnClearOut = E('#btn-clear-output');
|
||||
btnClearOut.addEventListener('click',function(){
|
||||
taOutput.value = '';
|
||||
if(SF.jqTerm) SF.jqTerm.clear();
|
||||
},false);
|
||||
const btnShellExec = E('#btn-shell-exec');
|
||||
btnShellExec.addEventListener('click',function(){
|
||||
const sql = taInput.value.trim();
|
||||
if(sql) SF.dbExec(sql);
|
||||
},false);
|
||||
|
||||
/** To be called immediately before work is sent to the
|
||||
worker. Updates some UI elements. The 'working'/'end'
|
||||
event will apply the inverse, undoing the bits this
|
||||
function does. This impl is not in the 'working'/'start'
|
||||
event handler because that event is given to us
|
||||
asynchronously _after_ we need to have performed this
|
||||
work.
|
||||
*/
|
||||
const preStartWork = function f(){
|
||||
if(!f._){
|
||||
const title = E('title');
|
||||
f._ = {
|
||||
btnLabel: btnShellExec.innerText,
|
||||
pageTitle: title,
|
||||
pageTitleOrig: title.innerText
|
||||
};
|
||||
}
|
||||
f._.pageTitle.innerText = "[working...] "+f._.pageTitleOrig;
|
||||
btnShellExec.setAttribute('disabled','disabled');
|
||||
};
|
||||
|
||||
/* Sends the given text to the db module to evaluate as if it
|
||||
had been entered in the sqlite3 CLI shell. If it's null or
|
||||
empty, this is a no-op except that the very first call will
|
||||
initialize the db and output an informational header. */
|
||||
SF.dbExec = function f(sql){
|
||||
if(this.config.autoClearOutput){
|
||||
this.echo._clearPending = true;
|
||||
}
|
||||
preStartWork();
|
||||
this.wMsg('shellExec',sql);
|
||||
};
|
||||
|
||||
SF.addMsgHandler('working',function f(ev){
|
||||
switch(ev.data){
|
||||
case 'start': /* See notes in preStartWork(). */; return;
|
||||
case 'end':
|
||||
preStartWork._.pageTitle.innerText = preStartWork._.pageTitleOrig;
|
||||
btnShellExec.innerText = preStartWork._.btnLabel;
|
||||
btnShellExec.removeAttribute('disabled');
|
||||
return;
|
||||
}
|
||||
console.warn("Unhandled 'working' event:",ev.data);
|
||||
});
|
||||
|
||||
/* For each checkbox with data-csstgt, set up a handler which
|
||||
toggles the given CSS class on the element matching
|
||||
E(data-csstgt). */
|
||||
EAll('input[type=checkbox][data-csstgt]')
|
||||
.forEach(function(e){
|
||||
const tgt = E(e.dataset.csstgt);
|
||||
const cssClass = e.dataset.cssclass || 'error';
|
||||
e.checked = tgt.classList.contains(cssClass);
|
||||
e.addEventListener('change', function(){
|
||||
tgt.classList[
|
||||
this.checked ? 'add' : 'remove'
|
||||
](cssClass)
|
||||
}, false);
|
||||
});
|
||||
/* For each checkbox with data-config=X, set up a binding to
|
||||
SF.config[X]. These must be set up AFTER data-csstgt
|
||||
checkboxes so that those two states can be synced properly. */
|
||||
EAll('input[type=checkbox][data-config]')
|
||||
.forEach(function(e){
|
||||
const confVal = !!SF.config[e.dataset.config];
|
||||
if(e.checked !== confVal){
|
||||
/* Ensure that data-csstgt mappings (if any) get
|
||||
synced properly. */
|
||||
e.checked = confVal;
|
||||
e.dispatchEvent(new Event('change'));
|
||||
}
|
||||
e.addEventListener('change', function(){
|
||||
SF.config[this.dataset.config] = this.checked;
|
||||
}, false);
|
||||
});
|
||||
/* For each button with data-cmd=X, map a click handler which
|
||||
calls dbExec(X). */
|
||||
const cmdClick = function(){SF.dbExec(this.dataset.cmd);};
|
||||
EAll('button[data-cmd]').forEach(
|
||||
e => e.addEventListener('click', cmdClick, false)
|
||||
);
|
||||
|
||||
/**
|
||||
Given a DOM element, this routine measures its "effective
|
||||
height", which is the bounding top/bottom range of this element
|
||||
and all of its children, recursively. For some DOM structure
|
||||
cases, a parent may have a reported height of 0 even though
|
||||
children have non-0 sizes.
|
||||
|
||||
Returns 0 if !e or if the element really has no height.
|
||||
*/
|
||||
const effectiveHeight = function f(e){
|
||||
if(!e) return 0;
|
||||
if(!f.measure){
|
||||
f.measure = function callee(e, depth){
|
||||
if(!e) return;
|
||||
const m = e.getBoundingClientRect();
|
||||
if(0===depth){
|
||||
callee.top = m.top;
|
||||
callee.bottom = m.bottom;
|
||||
}else{
|
||||
callee.top = m.top ? Math.min(callee.top, m.top) : callee.top;
|
||||
callee.bottom = Math.max(callee.bottom, m.bottom);
|
||||
}
|
||||
Array.prototype.forEach.call(e.children,(e)=>callee(e,depth+1));
|
||||
if(0===depth){
|
||||
//console.debug("measure() height:",e.className, callee.top, callee.bottom, (callee.bottom - callee.top));
|
||||
f.extra += callee.bottom - callee.top;
|
||||
}
|
||||
return f.extra;
|
||||
};
|
||||
}
|
||||
f.extra = 0;
|
||||
f.measure(e,0);
|
||||
return f.extra;
|
||||
};
|
||||
|
||||
/**
|
||||
Returns a function, that, as long as it continues to be invoked,
|
||||
will not be triggered. The function will be called after it stops
|
||||
being called for N milliseconds. If `immediate` is passed, call
|
||||
the callback immediately and hinder future invocations until at
|
||||
least the given time has passed.
|
||||
|
||||
If passed only 1 argument, or passed a falsy 2nd argument,
|
||||
the default wait time set in this function's $defaultDelay
|
||||
property is used.
|
||||
|
||||
Source: underscore.js, by way of https://davidwalsh.name/javascript-debounce-function
|
||||
*/
|
||||
const debounce = function f(func, wait, immediate) {
|
||||
var timeout;
|
||||
if(!wait) wait = f.$defaultDelay;
|
||||
return function() {
|
||||
const context = this, args = Array.prototype.slice.call(arguments);
|
||||
const later = function() {
|
||||
timeout = undefined;
|
||||
if(!immediate) func.apply(context, args);
|
||||
};
|
||||
const callNow = immediate && !timeout;
|
||||
clearTimeout(timeout);
|
||||
timeout = setTimeout(later, wait);
|
||||
if(callNow) func.apply(context, args);
|
||||
};
|
||||
};
|
||||
debounce.$defaultDelay = 500 /*arbitrary*/;
|
||||
|
||||
const ForceResizeKludge = (function(){
|
||||
/* Workaround for Safari mayhem regarding use of vh CSS units....
|
||||
We cannot use vh units to set the terminal area size because
|
||||
Safari chokes on that, so we calculate that height here. Larger
|
||||
than ~95% is too big for Firefox on Android, causing the input
|
||||
area to move off-screen. */
|
||||
const bcl = document.body.classList;
|
||||
const appViews = EAll('.app-view');
|
||||
const resized = function f(){
|
||||
if(f.$disabled) return;
|
||||
const wh = window.innerHeight;
|
||||
var ht;
|
||||
var extra = 0;
|
||||
const elemsToCount = [
|
||||
E('body > header'),
|
||||
E('body > footer')
|
||||
];
|
||||
elemsToCount.forEach((e)=>e ? extra += effectiveHeight(e) : false);
|
||||
ht = wh - extra;
|
||||
appViews.forEach(function(e){
|
||||
e.style.height =
|
||||
e.style.maxHeight = [
|
||||
"calc(", (ht>=100 ? ht : 100), "px",
|
||||
" - 2em"/*fudge value*/,")"
|
||||
/* ^^^^ hypothetically not needed, but both
|
||||
Chrome/FF on Linux will force scrollbars on the
|
||||
body if this value is too small. */
|
||||
].join('');
|
||||
});
|
||||
};
|
||||
resized.$disabled = true/*gets deleted when setup is finished*/;
|
||||
window.addEventListener('resize', debounce(resized, 250), false);
|
||||
return resized;
|
||||
})();
|
||||
|
||||
/** Set up a selection list of examples */
|
||||
(function(){
|
||||
const xElem = E('#select-examples');
|
||||
const examples = [
|
||||
{name: "Timer on", sql: ".timer on"},
|
||||
{name: "Setup table T", sql:`.nullvalue NULL
|
||||
CREATE TABLE t(a,b);
|
||||
INSERT INTO t(a,b) VALUES('abc',123),('def',456),(NULL,789),('ghi',012);
|
||||
SELECT * FROM t;`},
|
||||
{name: "Table list", sql: ".tables"},
|
||||
{name: "Box Mode", sql: ".mode box"},
|
||||
{name: "JSON Mode", sql: ".mode json"},
|
||||
{name: "Mandlebrot", sql: `WITH RECURSIVE
|
||||
xaxis(x) AS (VALUES(-2.0) UNION ALL SELECT x+0.05 FROM xaxis WHERE x<1.2),
|
||||
yaxis(y) AS (VALUES(-1.0) UNION ALL SELECT y+0.1 FROM yaxis WHERE y<1.0),
|
||||
m(iter, cx, cy, x, y) AS (
|
||||
SELECT 0, x, y, 0.0, 0.0 FROM xaxis, yaxis
|
||||
UNION ALL
|
||||
SELECT iter+1, cx, cy, x*x-y*y + cx, 2.0*x*y + cy FROM m
|
||||
WHERE (x*x + y*y) < 4.0 AND iter<28
|
||||
),
|
||||
m2(iter, cx, cy) AS (
|
||||
SELECT max(iter), cx, cy FROM m GROUP BY cx, cy
|
||||
),
|
||||
a(t) AS (
|
||||
SELECT group_concat( substr(' .+*#', 1+min(iter/7,4), 1), '')
|
||||
FROM m2 GROUP BY cy
|
||||
)
|
||||
SELECT group_concat(rtrim(t),x'0a') as Mandelbrot FROM a;`}
|
||||
];
|
||||
const newOpt = function(lbl,val){
|
||||
const o = document.createElement('option');
|
||||
o.value = val;
|
||||
if(!val) o.setAttribute('disabled',true);
|
||||
o.appendChild(document.createTextNode(lbl));
|
||||
xElem.appendChild(o);
|
||||
};
|
||||
newOpt("Examples (replaces input!)");
|
||||
examples.forEach((o)=>newOpt(o.name, o.sql));
|
||||
//xElem.setAttribute('disabled',true);
|
||||
xElem.selectedIndex = 0;
|
||||
xElem.addEventListener('change', function(){
|
||||
taInput.value = '-- ' +
|
||||
this.selectedOptions[0].innerText +
|
||||
'\n' + this.value;
|
||||
//dbExec(this.value);
|
||||
});
|
||||
})()/* example queries */;
|
||||
|
||||
SF.echo(null/*clear any output generated by the init process*/);
|
||||
if(window.jQuery && window.jQuery.terminal){
|
||||
/* Set up the terminal-style view... */
|
||||
const eTerm = window.jQuery('#view-terminal').empty();
|
||||
SF.jqTerm = eTerm.terminal(dbExec,{
|
||||
prompt: 'sqlite> ',
|
||||
greetings: false /* note that the docs incorrectly call this 'greeting' */
|
||||
});
|
||||
/* Set up a button to toggle the views... */
|
||||
const head = E('header#titlebar');
|
||||
const btnToggleView = document.createElement('button');
|
||||
btnToggleView.appendChild(document.createTextNode("Toggle View"));
|
||||
btnToggleView.addEventListener('click',function f(){
|
||||
EAll('.app-view').forEach(e=>e.classList.toggle('hidden'));
|
||||
if(document.body.classList.toggle('terminal-mode')){
|
||||
ForceResizeKludge();
|
||||
}
|
||||
}, false);
|
||||
btnToggleView.click()/*default to terminal view*/;
|
||||
}
|
||||
SF.dbExec(null/*init the db and output the header*/);
|
||||
SF.echo('This experimental app is provided in the hope that it',
|
||||
'may prove interesting or useful but is not an officially',
|
||||
'supported deliverable of the sqlite project. It is subject to',
|
||||
'any number of changes or outright removal at any time.\n');
|
||||
delete ForceResizeKludge.$disabled;
|
||||
ForceResizeKludge();
|
||||
}/*onSFLoaded()*/;
|
||||
})();
|
||||
@@ -1,94 +0,0 @@
|
||||
This directory houses a "fiddle"-style application which embeds a
|
||||
[Web Assembly (WASM)](https://en.wikipedia.org/wiki/WebAssembly)
|
||||
build of the sqlite3 shell app into an HTML page, effectively running
|
||||
the shell in a client-side browser.
|
||||
|
||||
It requires [emscripten][] and that the build environment be set up for
|
||||
emscripten. A mini-HOWTO for setting that up follows...
|
||||
|
||||
First, install the Emscripten SDK, as documented
|
||||
[here](https://emscripten.org/docs/getting_started/downloads.html) and summarized
|
||||
below for Linux environments:
|
||||
|
||||
```
|
||||
# Clone the emscripten repository:
|
||||
$ git clone https://github.com/emscripten-core/emsdk.git
|
||||
$ cd emsdk
|
||||
|
||||
# Download and install the latest SDK tools:
|
||||
$ ./emsdk install latest
|
||||
|
||||
# Make the "latest" SDK "active" for the current user:
|
||||
$ ./emsdk activate latest
|
||||
```
|
||||
|
||||
Those parts only need to be run once. The following needs to be run for each
|
||||
shell instance which needs the `emcc` compiler:
|
||||
|
||||
```
|
||||
# Activate PATH and other environment variables in the current terminal:
|
||||
$ source ./emsdk_env.sh
|
||||
|
||||
$ which emcc
|
||||
/path/to/emsdk/upstream/emscripten/emcc
|
||||
```
|
||||
|
||||
That `env` script needs to be sourced for building this application from the
|
||||
top of the sqlite3 build tree:
|
||||
|
||||
```
|
||||
$ make fiddle
|
||||
```
|
||||
|
||||
Or:
|
||||
|
||||
```
|
||||
$ cd ext/fiddle
|
||||
$ make
|
||||
```
|
||||
|
||||
That will generate the fiddle application under
|
||||
[ext/fiddle](/dir/ext/fiddle), as `fiddle.html`. That application
|
||||
cannot, due to XMLHttpRequest security limitations, run if the HTML
|
||||
file is opened directly in the browser (i.e. if it is opened using a
|
||||
`file://` URL), so it needs to be served via an HTTP server. For
|
||||
example, using [althttpd][]:
|
||||
|
||||
```
|
||||
$ cd ext/fiddle
|
||||
$ althttpd -debug 1 -jail 0 -port 9090 -root .
|
||||
```
|
||||
|
||||
Then browse to `http://localhost:9090/fiddle.html`.
|
||||
|
||||
Note that when serving this app via [althttpd][], it must be a version
|
||||
from 2022-05-17 or newer so that it recognizes the `.wasm` file
|
||||
extension and responds with the mimetype `application/wasm`, as the
|
||||
WASM loader is pedantic about that detail.
|
||||
|
||||
# Known Quirks and Limitations
|
||||
|
||||
Some "impedence mismatch" between C and WASM/JavaScript is to be
|
||||
expected.
|
||||
|
||||
## No I/O
|
||||
|
||||
sqlite3 shell commands which require file I/O or pipes are disabled in
|
||||
the WASM build.
|
||||
|
||||
## `exit()` Triggered from C
|
||||
|
||||
When C code calls `exit()`, as happens (for example) when running an
|
||||
"unsafe" command when safe mode is active, WASM's connection to the
|
||||
sqlite3 shell environment has no sensible choice but to shut down
|
||||
because `exit()` leaves it in a state we can no longer recover
|
||||
from. The JavaScript-side application attempts to recognize this and
|
||||
warn the user that restarting the application is necessary. Currently
|
||||
the only way to restart it is to reload the page. Restructuring the
|
||||
shell code such that it could be "rebooted" without restarting the
|
||||
JS app would require some invasive changes which are not currently
|
||||
on any TODO list but have not been entirely ruled out long-term.
|
||||
|
||||
|
||||
[emscripten]: https://emscripten.org
|
||||
[althttpd]: https://sqlite.org/althttpd
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,121 +0,0 @@
|
||||
/*
|
||||
2022-05-22
|
||||
|
||||
The author disclaims copyright to this source code. In place of a
|
||||
legal notice, here is a blessing:
|
||||
|
||||
* May you do good and not evil.
|
||||
* May you find forgiveness for yourself and forgive others.
|
||||
* May you share freely, never taking more than you give.
|
||||
|
||||
***********************************************************************
|
||||
|
||||
This file contains bootstrapping code used by various test scripts
|
||||
which live in this file's directory.
|
||||
*/
|
||||
(function(){
|
||||
/* querySelectorAll() proxy */
|
||||
const EAll = function(/*[element=document,] cssSelector*/){
|
||||
return (arguments.length>1 ? arguments[0] : document)
|
||||
.querySelectorAll(arguments[arguments.length-1]);
|
||||
};
|
||||
/* querySelector() proxy */
|
||||
const E = function(/*[element=document,] cssSelector*/){
|
||||
return (arguments.length>1 ? arguments[0] : document)
|
||||
.querySelector(arguments[arguments.length-1]);
|
||||
};
|
||||
|
||||
/* emscripten-related bits... */
|
||||
self.Module = {
|
||||
/* ^^^ cannot declare that const because sqlite3.js
|
||||
(auto-generated) includes a decl for it and runs in this
|
||||
scope. */
|
||||
preRun: [],
|
||||
postRun: [],
|
||||
//onRuntimeInitialized: function(){},
|
||||
print: function(){
|
||||
console.log.apply(console, Array.prototype.slice.call(arguments));
|
||||
},
|
||||
printErr: function(){
|
||||
console.error.apply(console, Array.prototype.slice.call(arguments));
|
||||
},
|
||||
setStatus: function f(text){
|
||||
if(!f.last){
|
||||
f.last = { text: '', step: 0 };
|
||||
f.ui = {
|
||||
status: E('#module-status'),
|
||||
progress: E('#module-progress'),
|
||||
spinner: E('#module-spinner')
|
||||
};
|
||||
}
|
||||
if(text === f.last.text) return;
|
||||
f.last.text = text;
|
||||
if(f.ui.progress){
|
||||
f.ui.progress.value = f.last.step;
|
||||
f.ui.progress.max = f.last.step + 1;
|
||||
}
|
||||
++f.last.step;
|
||||
if(text) {
|
||||
f.ui.status.classList.remove('hidden');
|
||||
f.ui.status.innerText = text;
|
||||
}else{
|
||||
if(f.ui.progress){
|
||||
f.ui.progress.remove();
|
||||
f.ui.spinner.remove();
|
||||
delete f.ui.progress;
|
||||
delete f.ui.spinner;
|
||||
}
|
||||
f.ui.status.classList.add('hidden');
|
||||
}
|
||||
},
|
||||
totalDependencies: 0,
|
||||
monitorRunDependencies: function(left) {
|
||||
this.totalDependencies = Math.max(this.totalDependencies, left);
|
||||
this.setStatus(left
|
||||
? ('Preparing... (' + (this.totalDependencies-left)
|
||||
+ '/' + this.totalDependencies + ')')
|
||||
: 'All downloads complete.');
|
||||
},
|
||||
/**
|
||||
Loads sqlite3-api.js and calls the given callback (if
|
||||
provided), passing it an object:
|
||||
|
||||
{
|
||||
api:sqlite3_c-like API wrapper,
|
||||
SQLite3: OO wrapper
|
||||
}
|
||||
|
||||
Whether this is synchronous or async depends on whether
|
||||
it's run in the main thread (async) or a worker
|
||||
(synchronous).
|
||||
|
||||
If called after the module has been loaded, it uses a
|
||||
cached reference, noting that multiple async calls may end
|
||||
up loading it multiple times.
|
||||
*/
|
||||
loadSqliteAPI: function f(callback){
|
||||
const namespace = self.Module;
|
||||
if(namespace.sqlite3){
|
||||
if(callback) callback(namespace.sqlite3);
|
||||
return;
|
||||
}
|
||||
const theScript = 'sqlite3-api.js';
|
||||
if(self.importScripts){/*worker*/
|
||||
importScripts(theScript);
|
||||
if(callback) callback(namespace.sqlite3);
|
||||
}else{/*main thread*/
|
||||
new Promise((resolve, reject) => {
|
||||
const script = document.createElement('script');
|
||||
document.body.appendChild(script);
|
||||
script.onload = resolve;
|
||||
script.onerror = reject;
|
||||
script.async = true;
|
||||
script.src = theScript;
|
||||
}).then(() => {
|
||||
if(callback) callback(namespace.sqlite3);
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
})(self/*window or worker*/);
|
||||
@@ -1,31 +0,0 @@
|
||||
textarea {
|
||||
font-family: monospace;
|
||||
}
|
||||
header {
|
||||
font-size: 130%;
|
||||
font-weight: bold;
|
||||
}
|
||||
.hidden, .initially-hidden {
|
||||
position: absolute !important;
|
||||
opacity: 0 !important;
|
||||
pointer-events: none !important;
|
||||
display: none !important;
|
||||
}
|
||||
fieldset.options {
|
||||
font-size: 75%;
|
||||
}
|
||||
fieldset > legend {
|
||||
padding: 0 0.5em;
|
||||
}
|
||||
span.labeled-input {
|
||||
padding: 0.25em;
|
||||
margin: 0.25em 0.5em;
|
||||
border-radius: 0.25em;
|
||||
white-space: nowrap;
|
||||
background: #0002;
|
||||
}
|
||||
.center { text-align: center; }
|
||||
.error {
|
||||
color: red;
|
||||
background-color: yellow;
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
/*
|
||||
2022-05-22
|
||||
|
||||
The author disclaims copyright to this source code. In place of a
|
||||
legal notice, here is a blessing:
|
||||
|
||||
* May you do good and not evil.
|
||||
* May you find forgiveness for yourself and forgive others.
|
||||
* May you share freely, never taking more than you give.
|
||||
|
||||
***********************************************************************
|
||||
|
||||
A basic test script for sqlite3-api.js.
|
||||
*/
|
||||
(function(){
|
||||
const T = self.SqliteTestUtil;
|
||||
const log = console.log.bind(console);
|
||||
|
||||
const test1 = function(db,api){
|
||||
log("Basic sanity tests...");
|
||||
T.assert(db._pDb);
|
||||
let st = db.prepare("select 3 as a");
|
||||
//log("statement =",st);
|
||||
T.assert(st._pStmt)
|
||||
.assert(!st._mayGet)
|
||||
.assert('a' === st.getColumnName(0))
|
||||
.assert(st === db._statements[st._pStmt])
|
||||
.assert(1===st.columnCount)
|
||||
.assert(0===st.parameterCount)
|
||||
.mustThrow(()=>st.bind(1,null))
|
||||
.assert(true===st.step())
|
||||
.assert(3 === st.get(0))
|
||||
.mustThrow(()=>st.get(1))
|
||||
.mustThrow(()=>st.get(0,~api.SQLITE_INTEGER))
|
||||
.assert(3 === st.get(0,api.SQLITE_INTEGER))
|
||||
.assert(3 === st.getInt(0))
|
||||
.assert('3' === st.get(0,api.SQLITE_TEXT))
|
||||
.assert('3' === st.getString(0))
|
||||
.assert(3.0 === st.get(0,api.SQLITE_FLOAT))
|
||||
.assert(3.0 === st.getFloat(0))
|
||||
.assert(st.get(0,api.SQLITE_BLOB) instanceof Uint8Array)
|
||||
.assert(st.getBlob(0) instanceof Uint8Array)
|
||||
.assert(3 === st.get([])[0])
|
||||
.assert(3 === st.get({}).a)
|
||||
.assert(3 === st.getJSON(0))
|
||||
.assert(st._mayGet)
|
||||
.assert(false===st.step())
|
||||
.assert(!st._mayGet)
|
||||
;
|
||||
let pId = st._pStmt;
|
||||
st.finalize();
|
||||
T.assert(!st._pStmt)
|
||||
.assert(!db._statements[pId]);
|
||||
|
||||
let list = [];
|
||||
db.exec({
|
||||
sql:`CREATE TABLE t(a,b);
|
||||
INSERT INTO t(a,b) VALUES(1,2),(3,4),(?,?);`,
|
||||
multi: true,
|
||||
saveSql: list,
|
||||
bind: [5,6]
|
||||
});
|
||||
T.assert(2 === list.length);
|
||||
//log("Exec'd SQL:", list);
|
||||
let counter = 0, colNames = [];
|
||||
db.exec("SELECT a a, b b FROM t",{
|
||||
rowMode: 'object',
|
||||
callback: function(row,stmt){
|
||||
if(!counter) stmt.getColumnNames(colNames);
|
||||
++counter;
|
||||
T.assert(row.a%2 && row.a<6);
|
||||
}
|
||||
});
|
||||
assert(2 === colNames.length);
|
||||
assert('a' === colNames[0]);
|
||||
T.assert(3 === counter);
|
||||
db.exec("SELECT a a, b b FROM t",{
|
||||
rowMode: 'array',
|
||||
callback: function(row,stmt){
|
||||
++counter;
|
||||
assert(Array.isArray(row));
|
||||
T.assert(0===row[1]%2 && row[1]<7);
|
||||
}
|
||||
});
|
||||
T.assert(6 === counter);
|
||||
};
|
||||
|
||||
const testUDF = function(db){
|
||||
log("Testing UDF...");
|
||||
db.createFunction("foo",function(a,b){return a+b});
|
||||
T.assert(7===db.selectValue("select foo(3,4)")).
|
||||
assert(5===db.selectValue("select foo(3,?)",2)).
|
||||
assert(5===db.selectValue("select foo(?,?)",[1,4])).
|
||||
assert(5===db.selectValue("select foo($a,$b)",{$a:0,$b:5}));
|
||||
db.createFunction("bar", {
|
||||
arity: -1,
|
||||
callback: function(){
|
||||
var rc = 0;
|
||||
for(let i = 0; i < arguments.length; ++i) rc += arguments[i];
|
||||
return rc;
|
||||
}
|
||||
});
|
||||
|
||||
log("Testing DB::selectValue() w/ UDF...");
|
||||
T.assert(0===db.selectValue("select bar()")).
|
||||
assert(1===db.selectValue("select bar(1)")).
|
||||
assert(3===db.selectValue("select bar(1,2)")).
|
||||
assert(-1===db.selectValue("select bar(1,2,-4)"));
|
||||
|
||||
T.assert('hi' === db.selectValue("select ?",'hi')).
|
||||
assert(null===db.selectValue("select null")).
|
||||
assert(null === db.selectValue("select ?",null)).
|
||||
assert(null === db.selectValue("select ?",[null])).
|
||||
assert(null === db.selectValue("select $a",{$a:null}));
|
||||
};
|
||||
|
||||
const runTests = function(namespace){
|
||||
T.assert(Module._free instanceof Function).
|
||||
assert(Module.allocate instanceof Function).
|
||||
assert(Module.addFunction instanceof Function).
|
||||
assert(Module.removeFunction instanceof Function);
|
||||
const api = namespace.api;
|
||||
const oo = namespace.SQLite3;
|
||||
console.log("Loaded module:",api.sqlite3_libversion(),
|
||||
api.sqlite3_sourceid());
|
||||
log("Build options:",oo.compileOptionUsed());
|
||||
const db = new oo.DB();
|
||||
try {
|
||||
log("DB:",db.filename);
|
||||
[
|
||||
test1, testUDF
|
||||
].forEach((f)=>f(db, api));
|
||||
}finally{
|
||||
db.close();
|
||||
}
|
||||
log("Total Test count:",T.counter);
|
||||
};
|
||||
|
||||
self.Module.postRun.push(function(theModule){
|
||||
/** Use a timeout so that we are (hopefully) out from under the
|
||||
module init stack when our setup gets run. Just on principle,
|
||||
not because we _need_ to be. */
|
||||
setTimeout(()=>theModule.loadSqliteAPI(runTests), 0);
|
||||
});
|
||||
})(self/*window or worker*/);
|
||||
+11
-9
@@ -2888,7 +2888,7 @@ static int fts3TermSelectMerge(
|
||||
**
|
||||
** Similar padding is added in the fts3DoclistOrMerge() function.
|
||||
*/
|
||||
pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
|
||||
pTS->aaOutput[0] = sqlite3_malloc64((i64)nDoclist + FTS3_VARINT_MAX + 1);
|
||||
pTS->anOutput[0] = nDoclist;
|
||||
if( pTS->aaOutput[0] ){
|
||||
memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
|
||||
@@ -4308,8 +4308,7 @@ static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
|
||||
char *aPoslist = 0; /* Position list for deferred tokens */
|
||||
int nPoslist = 0; /* Number of bytes in aPoslist */
|
||||
int iPrev = -1; /* Token number of previous deferred token */
|
||||
|
||||
assert( pPhrase->doclist.bFreeList==0 );
|
||||
char *aFree = (pPhrase->doclist.bFreeList ? pPhrase->doclist.pList : 0);
|
||||
|
||||
for(iToken=0; iToken<pPhrase->nToken; iToken++){
|
||||
Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
|
||||
@@ -4323,6 +4322,7 @@ static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
|
||||
|
||||
if( pList==0 ){
|
||||
sqlite3_free(aPoslist);
|
||||
sqlite3_free(aFree);
|
||||
pPhrase->doclist.pList = 0;
|
||||
pPhrase->doclist.nList = 0;
|
||||
return SQLITE_OK;
|
||||
@@ -4343,6 +4343,7 @@ static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
|
||||
nPoslist = (int)(aOut - aPoslist);
|
||||
if( nPoslist==0 ){
|
||||
sqlite3_free(aPoslist);
|
||||
sqlite3_free(aFree);
|
||||
pPhrase->doclist.pList = 0;
|
||||
pPhrase->doclist.nList = 0;
|
||||
return SQLITE_OK;
|
||||
@@ -4375,13 +4376,14 @@ static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
|
||||
nDistance = iPrev - nMaxUndeferred;
|
||||
}
|
||||
|
||||
aOut = (char *)sqlite3_malloc(nPoslist+8);
|
||||
aOut = (char *)sqlite3Fts3MallocZero(nPoslist+FTS3_BUFFER_PADDING);
|
||||
if( !aOut ){
|
||||
sqlite3_free(aPoslist);
|
||||
return SQLITE_NOMEM;
|
||||
}
|
||||
|
||||
pPhrase->doclist.pList = aOut;
|
||||
assert( p1 && p2 );
|
||||
if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
|
||||
pPhrase->doclist.bFreeList = 1;
|
||||
pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
|
||||
@@ -4394,6 +4396,7 @@ static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
|
||||
}
|
||||
}
|
||||
|
||||
if( pPhrase->doclist.pList!=aFree ) sqlite3_free(aFree);
|
||||
return SQLITE_OK;
|
||||
}
|
||||
#endif /* SQLITE_DISABLE_FTS4_DEFERRED */
|
||||
@@ -4742,7 +4745,7 @@ static int fts3EvalIncrPhraseNext(
|
||||
if( bEof==0 ){
|
||||
int nList = 0;
|
||||
int nByte = a[p->nToken-1].nList;
|
||||
char *aDoclist = sqlite3_malloc(nByte+FTS3_BUFFER_PADDING);
|
||||
char *aDoclist = sqlite3_malloc64((i64)nByte+FTS3_BUFFER_PADDING);
|
||||
if( !aDoclist ) return SQLITE_NOMEM;
|
||||
memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
|
||||
memset(&aDoclist[nByte], 0, FTS3_BUFFER_PADDING);
|
||||
@@ -5568,11 +5571,10 @@ static int fts3EvalTestExpr(
|
||||
|
||||
default: {
|
||||
#ifndef SQLITE_DISABLE_FTS4_DEFERRED
|
||||
if( pCsr->pDeferred
|
||||
&& (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
|
||||
){
|
||||
if( pCsr->pDeferred && (pExpr->bDeferred || (
|
||||
pExpr->iDocid==pCsr->iPrevId && pExpr->pPhrase->doclist.pList
|
||||
))){
|
||||
Fts3Phrase *pPhrase = pExpr->pPhrase;
|
||||
assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
|
||||
if( pExpr->bDeferred ){
|
||||
fts3EvalInvalidatePoslist(pPhrase);
|
||||
}
|
||||
|
||||
+1
-1
@@ -558,7 +558,7 @@ struct Fts3MultiSegReader {
|
||||
int nAdvance; /* How many seg-readers to advance */
|
||||
Fts3SegFilter *pFilter; /* Pointer to filter object */
|
||||
char *aBuffer; /* Buffer to merge doclists in */
|
||||
int nBuffer; /* Allocated size of aBuffer[] in bytes */
|
||||
i64 nBuffer; /* Allocated size of aBuffer[] in bytes */
|
||||
|
||||
int iColFilter; /* If >=0, filter for this column */
|
||||
int bRestart;
|
||||
|
||||
@@ -621,7 +621,7 @@ static int porterNext(
|
||||
if( n>c->nAllocated ){
|
||||
char *pNew;
|
||||
c->nAllocated = n+20;
|
||||
pNew = sqlite3_realloc(c->zToken, c->nAllocated);
|
||||
pNew = sqlite3_realloc64(c->zToken, c->nAllocated);
|
||||
if( !pNew ) return SQLITE_NOMEM;
|
||||
c->zToken = pNew;
|
||||
}
|
||||
|
||||
@@ -185,7 +185,7 @@ static int simpleNext(
|
||||
if( n>c->nTokenAllocated ){
|
||||
char *pNew;
|
||||
c->nTokenAllocated = n+20;
|
||||
pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
|
||||
pNew = sqlite3_realloc64(c->pToken, c->nTokenAllocated);
|
||||
if( !pNew ) return SQLITE_NOMEM;
|
||||
c->pToken = pNew;
|
||||
}
|
||||
|
||||
+35
-30
@@ -649,7 +649,7 @@ static int fts3PendingListAppendVarint(
|
||||
|
||||
/* Allocate or grow the PendingList as required. */
|
||||
if( !p ){
|
||||
p = sqlite3_malloc(sizeof(*p) + 100);
|
||||
p = sqlite3_malloc64(sizeof(*p) + 100);
|
||||
if( !p ){
|
||||
return SQLITE_NOMEM;
|
||||
}
|
||||
@@ -658,14 +658,14 @@ static int fts3PendingListAppendVarint(
|
||||
p->nData = 0;
|
||||
}
|
||||
else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
|
||||
int nNew = p->nSpace * 2;
|
||||
p = sqlite3_realloc(p, sizeof(*p) + nNew);
|
||||
i64 nNew = p->nSpace * 2;
|
||||
p = sqlite3_realloc64(p, sizeof(*p) + nNew);
|
||||
if( !p ){
|
||||
sqlite3_free(*pp);
|
||||
*pp = 0;
|
||||
return SQLITE_NOMEM;
|
||||
}
|
||||
p->nSpace = nNew;
|
||||
p->nSpace = (int)nNew;
|
||||
p->aData = (char *)&p[1];
|
||||
}
|
||||
|
||||
@@ -1222,7 +1222,7 @@ int sqlite3Fts3ReadBlock(
|
||||
int nByte = sqlite3_blob_bytes(p->pSegments);
|
||||
*pnBlob = nByte;
|
||||
if( paBlob ){
|
||||
char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
|
||||
char *aByte = sqlite3_malloc64((i64)nByte + FTS3_NODE_PADDING);
|
||||
if( !aByte ){
|
||||
rc = SQLITE_NOMEM;
|
||||
}else{
|
||||
@@ -1339,7 +1339,7 @@ static int fts3SegReaderNext(
|
||||
int nTerm = fts3HashKeysize(pElem);
|
||||
if( (nTerm+1)>pReader->nTermAlloc ){
|
||||
sqlite3_free(pReader->zTerm);
|
||||
pReader->zTerm = (char*)sqlite3_malloc((nTerm+1)*2);
|
||||
pReader->zTerm = (char*)sqlite3_malloc64(((i64)nTerm+1)*2);
|
||||
if( !pReader->zTerm ) return SQLITE_NOMEM;
|
||||
pReader->nTermAlloc = (nTerm+1)*2;
|
||||
}
|
||||
@@ -1347,7 +1347,7 @@ static int fts3SegReaderNext(
|
||||
pReader->zTerm[nTerm] = '\0';
|
||||
pReader->nTerm = nTerm;
|
||||
|
||||
aCopy = (char*)sqlite3_malloc(nCopy);
|
||||
aCopy = (char*)sqlite3_malloc64(nCopy);
|
||||
if( !aCopy ) return SQLITE_NOMEM;
|
||||
memcpy(aCopy, pList->aData, nCopy);
|
||||
pReader->nNode = pReader->nDoclist = nCopy;
|
||||
@@ -1634,7 +1634,7 @@ int sqlite3Fts3SegReaderNew(
|
||||
nExtra = nRoot + FTS3_NODE_PADDING;
|
||||
}
|
||||
|
||||
pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
|
||||
pReader = (Fts3SegReader *)sqlite3_malloc64(sizeof(Fts3SegReader) + nExtra);
|
||||
if( !pReader ){
|
||||
return SQLITE_NOMEM;
|
||||
}
|
||||
@@ -1726,7 +1726,7 @@ int sqlite3Fts3SegReaderPending(
|
||||
if( nElem==nAlloc ){
|
||||
Fts3HashElem **aElem2;
|
||||
nAlloc += 16;
|
||||
aElem2 = (Fts3HashElem **)sqlite3_realloc(
|
||||
aElem2 = (Fts3HashElem **)sqlite3_realloc64(
|
||||
aElem, nAlloc*sizeof(Fts3HashElem *)
|
||||
);
|
||||
if( !aElem2 ){
|
||||
@@ -2060,7 +2060,7 @@ static int fts3NodeAddTerm(
|
||||
** this is not expected to be a serious problem.
|
||||
*/
|
||||
assert( pTree->aData==(char *)&pTree[1] );
|
||||
pTree->aData = (char *)sqlite3_malloc(nReq);
|
||||
pTree->aData = (char *)sqlite3_malloc64(nReq);
|
||||
if( !pTree->aData ){
|
||||
return SQLITE_NOMEM;
|
||||
}
|
||||
@@ -2078,7 +2078,7 @@ static int fts3NodeAddTerm(
|
||||
|
||||
if( isCopyTerm ){
|
||||
if( pTree->nMalloc<nTerm ){
|
||||
char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
|
||||
char *zNew = sqlite3_realloc64(pTree->zMalloc, (i64)nTerm*2);
|
||||
if( !zNew ){
|
||||
return SQLITE_NOMEM;
|
||||
}
|
||||
@@ -2104,7 +2104,7 @@ static int fts3NodeAddTerm(
|
||||
** now. Instead, the term is inserted into the parent of pTree. If pTree
|
||||
** has no parent, one is created here.
|
||||
*/
|
||||
pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
|
||||
pNew = (SegmentNode *)sqlite3_malloc64(sizeof(SegmentNode) + p->nNodeSize);
|
||||
if( !pNew ){
|
||||
return SQLITE_NOMEM;
|
||||
}
|
||||
@@ -2242,7 +2242,7 @@ static int fts3SegWriterAdd(
|
||||
){
|
||||
int nPrefix; /* Size of term prefix in bytes */
|
||||
int nSuffix; /* Size of term suffix in bytes */
|
||||
int nReq; /* Number of bytes required on leaf page */
|
||||
i64 nReq; /* Number of bytes required on leaf page */
|
||||
int nData;
|
||||
SegmentWriter *pWriter = *ppWriter;
|
||||
|
||||
@@ -2251,13 +2251,13 @@ static int fts3SegWriterAdd(
|
||||
sqlite3_stmt *pStmt;
|
||||
|
||||
/* Allocate the SegmentWriter structure */
|
||||
pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
|
||||
pWriter = (SegmentWriter *)sqlite3_malloc64(sizeof(SegmentWriter));
|
||||
if( !pWriter ) return SQLITE_NOMEM;
|
||||
memset(pWriter, 0, sizeof(SegmentWriter));
|
||||
*ppWriter = pWriter;
|
||||
|
||||
/* Allocate a buffer in which to accumulate data */
|
||||
pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
|
||||
pWriter->aData = (char *)sqlite3_malloc64(p->nNodeSize);
|
||||
if( !pWriter->aData ) return SQLITE_NOMEM;
|
||||
pWriter->nSize = p->nNodeSize;
|
||||
|
||||
@@ -2332,7 +2332,7 @@ static int fts3SegWriterAdd(
|
||||
** the buffer to make it large enough.
|
||||
*/
|
||||
if( nReq>pWriter->nSize ){
|
||||
char *aNew = sqlite3_realloc(pWriter->aData, nReq);
|
||||
char *aNew = sqlite3_realloc64(pWriter->aData, nReq);
|
||||
if( !aNew ) return SQLITE_NOMEM;
|
||||
pWriter->aData = aNew;
|
||||
pWriter->nSize = nReq;
|
||||
@@ -2357,7 +2357,7 @@ static int fts3SegWriterAdd(
|
||||
*/
|
||||
if( isCopyTerm ){
|
||||
if( nTerm>pWriter->nMalloc ){
|
||||
char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
|
||||
char *zNew = sqlite3_realloc64(pWriter->zMalloc, (i64)nTerm*2);
|
||||
if( !zNew ){
|
||||
return SQLITE_NOMEM;
|
||||
}
|
||||
@@ -2665,12 +2665,12 @@ static void fts3ColumnFilter(
|
||||
static int fts3MsrBufferData(
|
||||
Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
|
||||
char *pList,
|
||||
int nList
|
||||
i64 nList
|
||||
){
|
||||
if( nList>pMsr->nBuffer ){
|
||||
char *pNew;
|
||||
pMsr->nBuffer = nList*2;
|
||||
pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
|
||||
pNew = (char *)sqlite3_realloc64(pMsr->aBuffer, pMsr->nBuffer);
|
||||
if( !pNew ) return SQLITE_NOMEM;
|
||||
pMsr->aBuffer = pNew;
|
||||
}
|
||||
@@ -2726,7 +2726,7 @@ int sqlite3Fts3MsrIncrNext(
|
||||
fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
|
||||
|
||||
if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
|
||||
rc = fts3MsrBufferData(pMsr, pList, nList+1);
|
||||
rc = fts3MsrBufferData(pMsr, pList, (i64)nList+1);
|
||||
if( rc!=SQLITE_OK ) return rc;
|
||||
assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
|
||||
pList = pMsr->aBuffer;
|
||||
@@ -2863,11 +2863,11 @@ int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
|
||||
return SQLITE_OK;
|
||||
}
|
||||
|
||||
static int fts3GrowSegReaderBuffer(Fts3MultiSegReader *pCsr, int nReq){
|
||||
static int fts3GrowSegReaderBuffer(Fts3MultiSegReader *pCsr, i64 nReq){
|
||||
if( nReq>pCsr->nBuffer ){
|
||||
char *aNew;
|
||||
pCsr->nBuffer = nReq*2;
|
||||
aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
|
||||
aNew = sqlite3_realloc64(pCsr->aBuffer, pCsr->nBuffer);
|
||||
if( !aNew ){
|
||||
return SQLITE_NOMEM;
|
||||
}
|
||||
@@ -2958,7 +2958,8 @@ int sqlite3Fts3SegReaderStep(
|
||||
){
|
||||
pCsr->nDoclist = apSegment[0]->nDoclist;
|
||||
if( fts3SegReaderIsPending(apSegment[0]) ){
|
||||
rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
|
||||
rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist,
|
||||
(i64)pCsr->nDoclist);
|
||||
pCsr->aDoclist = pCsr->aBuffer;
|
||||
}else{
|
||||
pCsr->aDoclist = apSegment[0]->aDoclist;
|
||||
@@ -3011,7 +3012,8 @@ int sqlite3Fts3SegReaderStep(
|
||||
|
||||
nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
|
||||
|
||||
rc = fts3GrowSegReaderBuffer(pCsr, nByte+nDoclist+FTS3_NODE_PADDING);
|
||||
rc = fts3GrowSegReaderBuffer(pCsr,
|
||||
(i64)nByte+nDoclist+FTS3_NODE_PADDING);
|
||||
if( rc ) return rc;
|
||||
|
||||
if( isFirst ){
|
||||
@@ -3037,7 +3039,7 @@ int sqlite3Fts3SegReaderStep(
|
||||
fts3SegReaderSort(apSegment, nMerge, j, xCmp);
|
||||
}
|
||||
if( nDoclist>0 ){
|
||||
rc = fts3GrowSegReaderBuffer(pCsr, nDoclist+FTS3_NODE_PADDING);
|
||||
rc = fts3GrowSegReaderBuffer(pCsr, (i64)nDoclist+FTS3_NODE_PADDING);
|
||||
if( rc ) return rc;
|
||||
memset(&pCsr->aBuffer[nDoclist], 0, FTS3_NODE_PADDING);
|
||||
pCsr->aDoclist = pCsr->aBuffer;
|
||||
@@ -3750,7 +3752,7 @@ struct NodeReader {
|
||||
static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
|
||||
if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
|
||||
int nAlloc = nMin;
|
||||
char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
|
||||
char *a = (char *)sqlite3_realloc64(pBlob->a, nAlloc);
|
||||
if( a ){
|
||||
pBlob->nAlloc = nAlloc;
|
||||
pBlob->a = a;
|
||||
@@ -3899,6 +3901,8 @@ static int fts3IncrmergePush(
|
||||
pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
|
||||
}
|
||||
pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
|
||||
assert( nPrefix+nSuffix<=nTerm );
|
||||
assert( nPrefix>=0 );
|
||||
memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
|
||||
pBlk->n += nSuffix;
|
||||
|
||||
@@ -4021,6 +4025,7 @@ static int fts3IncrmergeAppend(
|
||||
pLeaf = &pWriter->aNodeWriter[0];
|
||||
nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
|
||||
nSuffix = nTerm - nPrefix;
|
||||
if(nSuffix<=0 ) return FTS_CORRUPT_VTAB;
|
||||
|
||||
nSpace = sqlite3Fts3VarintLen(nPrefix);
|
||||
nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
|
||||
@@ -4544,7 +4549,7 @@ static int fts3RepackSegdirLevel(
|
||||
if( nIdx>=nAlloc ){
|
||||
int *aNew;
|
||||
nAlloc += 16;
|
||||
aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
|
||||
aNew = sqlite3_realloc64(aIdx, nAlloc*sizeof(int));
|
||||
if( !aNew ){
|
||||
rc = SQLITE_NOMEM;
|
||||
break;
|
||||
@@ -4918,7 +4923,7 @@ int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
|
||||
|
||||
/* Allocate space for the cursor, filter and writer objects */
|
||||
const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
|
||||
pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
|
||||
pWriter = (IncrmergeWriter *)sqlite3_malloc64(nAlloc);
|
||||
if( !pWriter ) return SQLITE_NOMEM;
|
||||
pFilter = (Fts3SegFilter *)&pWriter[1];
|
||||
pCsr = (Fts3MultiSegReader *)&pFilter[1];
|
||||
@@ -5554,7 +5559,7 @@ int sqlite3Fts3DeferredTokenList(
|
||||
return SQLITE_OK;
|
||||
}
|
||||
|
||||
pRet = (char *)sqlite3_malloc(p->pList->nData);
|
||||
pRet = (char *)sqlite3_malloc64(p->pList->nData);
|
||||
if( !pRet ) return SQLITE_NOMEM;
|
||||
|
||||
nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
|
||||
@@ -5574,7 +5579,7 @@ int sqlite3Fts3DeferToken(
|
||||
int iCol /* Column that token must appear in (or -1) */
|
||||
){
|
||||
Fts3DeferredToken *pDeferred;
|
||||
pDeferred = sqlite3_malloc(sizeof(*pDeferred));
|
||||
pDeferred = sqlite3_malloc64(sizeof(*pDeferred));
|
||||
if( !pDeferred ){
|
||||
return SQLITE_NOMEM;
|
||||
}
|
||||
|
||||
+1
-1
@@ -286,7 +286,7 @@ void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
|
||||
char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
|
||||
|
||||
#define fts5BufferZero(x) sqlite3Fts5BufferZero(x)
|
||||
#define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
|
||||
#define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,(i64)c)
|
||||
#define fts5BufferFree(a) sqlite3Fts5BufferFree(a)
|
||||
#define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
|
||||
#define fts5BufferSet(a,b,c,d) sqlite3Fts5BufferSet(a,b,c,d)
|
||||
|
||||
+13
-10
@@ -4087,7 +4087,9 @@ static void fts5WriteAppendRowid(
|
||||
fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
|
||||
}else{
|
||||
assert_nc( p->rc || iRowid>pWriter->iPrevRowid );
|
||||
fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
|
||||
fts5BufferAppendVarint(&p->rc, &pPage->buf,
|
||||
(u64)iRowid - (u64)pWriter->iPrevRowid
|
||||
);
|
||||
}
|
||||
pWriter->iPrevRowid = iRowid;
|
||||
pWriter->bFirstRowidInDoclist = 0;
|
||||
@@ -4851,7 +4853,7 @@ int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
|
||||
|
||||
static void fts5AppendRowid(
|
||||
Fts5Index *p,
|
||||
i64 iDelta,
|
||||
u64 iDelta,
|
||||
Fts5Iter *pUnused,
|
||||
Fts5Buffer *pBuf
|
||||
){
|
||||
@@ -4861,7 +4863,7 @@ static void fts5AppendRowid(
|
||||
|
||||
static void fts5AppendPoslist(
|
||||
Fts5Index *p,
|
||||
i64 iDelta,
|
||||
u64 iDelta,
|
||||
Fts5Iter *pMulti,
|
||||
Fts5Buffer *pBuf
|
||||
){
|
||||
@@ -4936,10 +4938,10 @@ static void fts5MergeAppendDocid(
|
||||
}
|
||||
#endif
|
||||
|
||||
#define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \
|
||||
assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \
|
||||
fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
|
||||
(iLastRowid) = (iRowid); \
|
||||
#define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \
|
||||
assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \
|
||||
fts5BufferSafeAppendVarint((pBuf), (u64)(iRowid) - (u64)(iLastRowid)); \
|
||||
(iLastRowid) = (iRowid); \
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -5210,7 +5212,7 @@ static void fts5SetupPrefixIter(
|
||||
int nMerge = 1;
|
||||
|
||||
void (*xMerge)(Fts5Index*, Fts5Buffer*, int, Fts5Buffer*);
|
||||
void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
|
||||
void (*xAppend)(Fts5Index*, u64, Fts5Iter*, Fts5Buffer*);
|
||||
if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
|
||||
xMerge = fts5MergeRowidLists;
|
||||
xAppend = fts5AppendRowid;
|
||||
@@ -5249,7 +5251,7 @@ static void fts5SetupPrefixIter(
|
||||
Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
|
||||
p1->xSetOutputs(p1, pSeg);
|
||||
if( p1->base.nData ){
|
||||
xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
|
||||
xAppend(p, (u64)p1->base.iRowid-(u64)iLastRowid, p1, &doclist);
|
||||
iLastRowid = p1->base.iRowid;
|
||||
}
|
||||
}
|
||||
@@ -5297,7 +5299,7 @@ static void fts5SetupPrefixIter(
|
||||
iLastRowid = 0;
|
||||
}
|
||||
|
||||
xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
|
||||
xAppend(p, (u64)p1->base.iRowid-(u64)iLastRowid, p1, &doclist);
|
||||
iLastRowid = p1->base.iRowid;
|
||||
}
|
||||
|
||||
@@ -6276,6 +6278,7 @@ int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum, int bUseCksum){
|
||||
|
||||
/* If this is a new term, query for it. Update cksum3 with the results. */
|
||||
fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
|
||||
if( p->rc ) break;
|
||||
|
||||
if( eDetail==FTS5_DETAIL_NONE ){
|
||||
if( 0==fts5MultiIterIsEmpty(p, pIter) ){
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
# This file implements regression tests for SQLite library. The
|
||||
# focus of this script is testing the FTS5 module.
|
||||
#
|
||||
# TESTRUNNER: slow
|
||||
|
||||
source [file join [file dirname [info script]] fts5_common.tcl]
|
||||
set testprefix fts5ah
|
||||
|
||||
@@ -16,12 +16,16 @@ source [file join [file dirname [info script]] fts5_common.tcl]
|
||||
source $testdir/malloc_common.tcl
|
||||
set testprefix fts5fault4
|
||||
|
||||
# If SQLITE_ENABLE_FTS3 is defined, omit this file.
|
||||
# If SQLITE_ENABLE_FTS5 is not defined, omit this file.
|
||||
ifcapable !fts5 {
|
||||
finish_test
|
||||
return
|
||||
}
|
||||
|
||||
set ::TMPDBERROR [list 1 \
|
||||
{unable to open a temporary database file for storing temporary tables}
|
||||
]
|
||||
|
||||
#-------------------------------------------------------------------------
|
||||
# An OOM while dropping an fts5 table.
|
||||
#
|
||||
@@ -391,7 +395,7 @@ do_faultsim_test 14.1 -faults oom-t* -prep {
|
||||
} -body {
|
||||
db eval { ALTER TABLE "tbl one" RENAME TO "tbl two" }
|
||||
} -test {
|
||||
faultsim_test_result {0 {}}
|
||||
faultsim_test_result {0 {}} $::TMPDBERROR
|
||||
}
|
||||
|
||||
finish_test
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
# 2022 August 9
|
||||
#
|
||||
# The author disclaims copyright to this source code. In place of
|
||||
# a legal notice, here is a blessing:
|
||||
#
|
||||
# May you do good and not evil.
|
||||
# May you find forgiveness for yourself and forgive others.
|
||||
# May you share freely, never taking more than you give.
|
||||
#
|
||||
#***********************************************************************
|
||||
#
|
||||
# This test is focused on edge cases that cause ubsan errors.
|
||||
#
|
||||
|
||||
source [file join [file dirname [info script]] fts5_common.tcl]
|
||||
set testprefix fts5ubsan
|
||||
|
||||
# If SQLITE_ENABLE_FTS5 is defined, omit this file.
|
||||
ifcapable !fts5 {
|
||||
finish_test
|
||||
return
|
||||
}
|
||||
|
||||
do_execsql_test 1.0 {
|
||||
CREATE VIRTUAL TABLE x1 USING fts5(x);
|
||||
}
|
||||
|
||||
set BIG 9000000000000000000
|
||||
set SMALL -9000000000000000000
|
||||
|
||||
do_execsql_test 1.1 {
|
||||
BEGIN;
|
||||
INSERT INTO x1 (rowid, x) VALUES($BIG, 'aaa aba acc');
|
||||
INSERT INTO x1 (rowid, x) VALUES($SMALL, 'aaa abc acb');
|
||||
COMMIT;
|
||||
}
|
||||
|
||||
do_execsql_test 1.2 {
|
||||
SELECT rowid, x FROM x1('ab*');
|
||||
} [list $SMALL {aaa abc acb} $BIG {aaa aba acc}]
|
||||
|
||||
do_execsql_test 1.3 {
|
||||
SELECT rowid, x FROM x1('ac*');
|
||||
} [list $SMALL {aaa abc acb} $BIG {aaa aba acc}]
|
||||
|
||||
reset_db
|
||||
do_execsql_test 2.0 {
|
||||
CREATE VIRTUAL TABLE x1 USING fts5(x);
|
||||
}
|
||||
|
||||
do_execsql_test 2.1 {
|
||||
INSERT INTO x1 (rowid, x) VALUES($BIG, 'aaa aba acc');
|
||||
INSERT INTO x1 (rowid, x) VALUES($SMALL, 'aaa abc acb');
|
||||
}
|
||||
|
||||
do_execsql_test 2.2 {
|
||||
INSERT INTO x1 (x1) VALUES('optimize');
|
||||
}
|
||||
|
||||
finish_test
|
||||
+3
-2
@@ -299,8 +299,9 @@ static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
|
||||
|
||||
if( U_SUCCESS(status) ){
|
||||
sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
|
||||
}else{
|
||||
assert(!pExpr);
|
||||
pExpr = sqlite3_get_auxdata(p, 0);
|
||||
}
|
||||
if( !pExpr ){
|
||||
icuFunctionError(p, "uregex_open", status);
|
||||
return;
|
||||
}
|
||||
|
||||
+1
-1
@@ -47,7 +47,7 @@
|
||||
**
|
||||
** sqlite3 *db;
|
||||
** sqlite3_open(":memory:", &db);
|
||||
** sqlite3_load_extention(db, "./cksumvfs");
|
||||
** sqlite3_load_extension(db, "./cksumvfs");
|
||||
** sqlite3_close(db);
|
||||
**
|
||||
** If this extension is compiled with -DSQLITE_CKSUMVFS_STATIC and
|
||||
|
||||
+8
-1
@@ -280,6 +280,7 @@ static char *csv_read_one_field(CsvReader *p){
|
||||
}
|
||||
p->cTerm = (char)c;
|
||||
}
|
||||
assert( p->z==0 || p->n<p->nAlloc );
|
||||
if( p->z ) p->z[p->n] = 0;
|
||||
p->bNotFirst = 1;
|
||||
return p->z;
|
||||
@@ -750,7 +751,7 @@ static int csvtabNext(sqlite3_vtab_cursor *cur){
|
||||
i++;
|
||||
}
|
||||
}while( pCur->rdr.cTerm==',' );
|
||||
if( z==0 || (pCur->rdr.cTerm==EOF && i<pTab->nCol) ){
|
||||
if( z==0 && i==0 ){
|
||||
pCur->iRowid = -1;
|
||||
}else{
|
||||
pCur->iRowid++;
|
||||
@@ -811,6 +812,12 @@ static int csvtabFilter(
|
||||
CsvCursor *pCur = (CsvCursor*)pVtabCursor;
|
||||
CsvTable *pTab = (CsvTable*)pVtabCursor->pVtab;
|
||||
pCur->iRowid = 0;
|
||||
|
||||
/* Ensure the field buffer is always allocated. Otherwise, if the
|
||||
** first field is zero bytes in size, this may be mistaken for an OOM
|
||||
** error in csvtabNext(). */
|
||||
if( csv_append(&pCur->rdr, 0) ) return SQLITE_NOMEM;
|
||||
|
||||
if( pCur->rdr.in==0 ){
|
||||
assert( pCur->rdr.zIn==pTab->zData );
|
||||
assert( pTab->iStart>=0 );
|
||||
|
||||
+117
-10
@@ -72,6 +72,7 @@ SQLITE_EXTENSION_INIT1
|
||||
|
||||
/* The end-of-input character */
|
||||
#define RE_EOF 0 /* End of input */
|
||||
#define RE_START 0xfffffff /* Start of input - larger than an UTF-8 */
|
||||
|
||||
/* The NFA is implemented as sequence of opcodes taken from the following
|
||||
** set. Each opcode has a single integer argument.
|
||||
@@ -93,6 +94,33 @@ SQLITE_EXTENSION_INIT1
|
||||
#define RE_OP_SPACE 15 /* space: [ \t\n\r\v\f] */
|
||||
#define RE_OP_NOTSPACE 16 /* Not a digit */
|
||||
#define RE_OP_BOUNDARY 17 /* Boundary between word and non-word */
|
||||
#define RE_OP_ATSTART 18 /* Currently at the start of the string */
|
||||
|
||||
#if defined(SQLITE_DEBUG)
|
||||
/* Opcode names used for symbolic debugging */
|
||||
static const char *ReOpName[] = {
|
||||
"EOF",
|
||||
"MATCH",
|
||||
"ANY",
|
||||
"ANYSTAR",
|
||||
"FORK",
|
||||
"GOTO",
|
||||
"ACCEPT",
|
||||
"CC_INC",
|
||||
"CC_EXC",
|
||||
"CC_VALUE",
|
||||
"CC_RANGE",
|
||||
"WORD",
|
||||
"NOTWORD",
|
||||
"DIGIT",
|
||||
"NOTDIGIT",
|
||||
"SPACE",
|
||||
"NOTSPACE",
|
||||
"BOUNDARY",
|
||||
"ATSTART",
|
||||
};
|
||||
#endif /* SQLITE_DEBUG */
|
||||
|
||||
|
||||
/* Each opcode is a "state" in the NFA */
|
||||
typedef unsigned short ReStateNumber;
|
||||
@@ -127,7 +155,7 @@ struct ReCompiled {
|
||||
int *aArg; /* Arguments to each operator */
|
||||
unsigned (*xNextChar)(ReInput*); /* Next character function */
|
||||
unsigned char zInit[12]; /* Initial text to match */
|
||||
int nInit; /* Number of characters in zInit */
|
||||
int nInit; /* Number of bytes in zInit */
|
||||
unsigned nState; /* Number of entries in aOp[] and aArg[] */
|
||||
unsigned nAlloc; /* Slots allocated for aOp[] and aArg[] */
|
||||
};
|
||||
@@ -200,7 +228,7 @@ static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){
|
||||
ReStateNumber *pToFree;
|
||||
unsigned int i = 0;
|
||||
unsigned int iSwap = 0;
|
||||
int c = RE_EOF+1;
|
||||
int c = RE_START;
|
||||
int cPrev = 0;
|
||||
int rc = 0;
|
||||
ReInput in;
|
||||
@@ -219,6 +247,7 @@ static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){
|
||||
in.i++;
|
||||
}
|
||||
if( in.i+pRe->nInit>in.mx ) return 0;
|
||||
c = RE_START-1;
|
||||
}
|
||||
|
||||
if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){
|
||||
@@ -247,6 +276,10 @@ static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){
|
||||
if( pRe->aArg[x]==c ) re_add_state(pNext, x+1);
|
||||
break;
|
||||
}
|
||||
case RE_OP_ATSTART: {
|
||||
if( cPrev==RE_START ) re_add_state(pThis, x+1);
|
||||
break;
|
||||
}
|
||||
case RE_OP_ANY: {
|
||||
if( c!=0 ) re_add_state(pNext, x+1);
|
||||
break;
|
||||
@@ -328,7 +361,9 @@ static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){
|
||||
}
|
||||
}
|
||||
for(i=0; i<pNext->nState; i++){
|
||||
if( pRe->aOp[pNext->aState[i]]==RE_OP_ACCEPT ){ rc = 1; break; }
|
||||
int x = pNext->aState[i];
|
||||
while( pRe->aOp[x]==RE_OP_GOTO ) x += pRe->aArg[x];
|
||||
if( pRe->aOp[x]==RE_OP_ACCEPT ){ rc = 1; break; }
|
||||
}
|
||||
re_match_end:
|
||||
sqlite3_free(pToFree);
|
||||
@@ -483,7 +518,6 @@ static const char *re_subcompile_string(ReCompiled *p){
|
||||
iStart = p->nState;
|
||||
switch( c ){
|
||||
case '|':
|
||||
case '$':
|
||||
case ')': {
|
||||
p->sIn.i--;
|
||||
return 0;
|
||||
@@ -520,6 +554,14 @@ static const char *re_subcompile_string(ReCompiled *p){
|
||||
re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1);
|
||||
break;
|
||||
}
|
||||
case '$': {
|
||||
re_append(p, RE_OP_MATCH, RE_EOF);
|
||||
break;
|
||||
}
|
||||
case '^': {
|
||||
re_append(p, RE_OP_ATSTART, 0);
|
||||
break;
|
||||
}
|
||||
case '{': {
|
||||
int m = 0, n = 0;
|
||||
int sz, j;
|
||||
@@ -538,6 +580,7 @@ static const char *re_subcompile_string(ReCompiled *p){
|
||||
if( m==0 ){
|
||||
if( n==0 ) return "both m and n are zero in '{m,n}'";
|
||||
re_insert(p, iPrev, RE_OP_FORK, sz+1);
|
||||
iPrev++;
|
||||
n--;
|
||||
}else{
|
||||
for(j=1; j<m; j++) re_copy(p, iPrev, sz);
|
||||
@@ -656,11 +699,7 @@ static const char *re_compile(ReCompiled **ppRe, const char *zIn, int noCase){
|
||||
re_free(pRe);
|
||||
return zErr;
|
||||
}
|
||||
if( rePeek(pRe)=='$' && pRe->sIn.i+1>=pRe->sIn.mx ){
|
||||
re_append(pRe, RE_OP_MATCH, RE_EOF);
|
||||
re_append(pRe, RE_OP_ACCEPT, 0);
|
||||
*ppRe = pRe;
|
||||
}else if( pRe->sIn.i>=pRe->sIn.mx ){
|
||||
if( pRe->sIn.i>=pRe->sIn.mx ){
|
||||
re_append(pRe, RE_OP_ACCEPT, 0);
|
||||
*ppRe = pRe;
|
||||
}else{
|
||||
@@ -685,7 +724,7 @@ static const char *re_compile(ReCompiled **ppRe, const char *zIn, int noCase){
|
||||
pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6));
|
||||
pRe->zInit[j++] = 0x80 | (x&0x3f);
|
||||
}else if( x<=0xffff ){
|
||||
pRe->zInit[j++] = (unsigned char)(0xd0 | (x>>12));
|
||||
pRe->zInit[j++] = (unsigned char)(0xe0 | (x>>12));
|
||||
pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f);
|
||||
pRe->zInit[j++] = 0x80 | (x&0x3f);
|
||||
}else{
|
||||
@@ -744,6 +783,67 @@ static void re_sql_func(
|
||||
}
|
||||
}
|
||||
|
||||
#if defined(SQLITE_DEBUG)
|
||||
/*
|
||||
** This function is used for testing and debugging only. It is only available
|
||||
** if the SQLITE_DEBUG compile-time option is used.
|
||||
**
|
||||
** Compile a regular expression and then convert the compiled expression into
|
||||
** text and return that text.
|
||||
*/
|
||||
static void re_bytecode_func(
|
||||
sqlite3_context *context,
|
||||
int argc,
|
||||
sqlite3_value **argv
|
||||
){
|
||||
const char *zPattern;
|
||||
const char *zErr;
|
||||
ReCompiled *pRe;
|
||||
sqlite3_str *pStr;
|
||||
int i;
|
||||
int n;
|
||||
char *z;
|
||||
|
||||
zPattern = (const char*)sqlite3_value_text(argv[0]);
|
||||
if( zPattern==0 ) return;
|
||||
zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
|
||||
if( zErr ){
|
||||
re_free(pRe);
|
||||
sqlite3_result_error(context, zErr, -1);
|
||||
return;
|
||||
}
|
||||
if( pRe==0 ){
|
||||
sqlite3_result_error_nomem(context);
|
||||
return;
|
||||
}
|
||||
pStr = sqlite3_str_new(0);
|
||||
if( pStr==0 ) goto re_bytecode_func_err;
|
||||
if( pRe->nInit>0 ){
|
||||
sqlite3_str_appendf(pStr, "INIT ");
|
||||
for(i=0; i<pRe->nInit; i++){
|
||||
sqlite3_str_appendf(pStr, "%02x", pRe->zInit[i]);
|
||||
}
|
||||
sqlite3_str_appendf(pStr, "\n");
|
||||
}
|
||||
for(i=0; (unsigned)i<pRe->nState; i++){
|
||||
sqlite3_str_appendf(pStr, "%-8s %4d\n",
|
||||
ReOpName[(unsigned char)pRe->aOp[i]], pRe->aArg[i]);
|
||||
}
|
||||
n = sqlite3_str_length(pStr);
|
||||
z = sqlite3_str_finish(pStr);
|
||||
if( n==0 ){
|
||||
sqlite3_free(z);
|
||||
}else{
|
||||
sqlite3_result_text(context, z, n-1, sqlite3_free);
|
||||
}
|
||||
|
||||
re_bytecode_func_err:
|
||||
re_free(pRe);
|
||||
}
|
||||
|
||||
#endif /* SQLITE_DEBUG */
|
||||
|
||||
|
||||
/*
|
||||
** Invoke this routine to register the regexp() function with the
|
||||
** SQLite database connection.
|
||||
@@ -768,6 +868,13 @@ int sqlite3_regexp_init(
|
||||
rc = sqlite3_create_function(db, "regexpi", 2,
|
||||
SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
|
||||
(void*)db, re_sql_func, 0, 0);
|
||||
#if defined(SQLITE_DEBUG)
|
||||
if( rc==SQLITE_OK ){
|
||||
rc = sqlite3_create_function(db, "regexp_bytecode", 1,
|
||||
SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
|
||||
0, re_bytecode_func, 0, 0);
|
||||
}
|
||||
#endif /* SQLITE_DEBUG */
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
+81
-44
@@ -30,6 +30,16 @@ SQLITE_EXTENSION_INIT1
|
||||
|
||||
#ifndef SQLITE_OMIT_VIRTUALTABLE
|
||||
|
||||
|
||||
#define STMT_NUM_INTEGER_COLUMN 10
|
||||
typedef struct StmtRow StmtRow;
|
||||
struct StmtRow {
|
||||
sqlite3_int64 iRowid; /* Rowid value */
|
||||
char *zSql; /* column "sql" */
|
||||
int aCol[STMT_NUM_INTEGER_COLUMN+1]; /* all other column values */
|
||||
StmtRow *pNext; /* Next row to return */
|
||||
};
|
||||
|
||||
/* stmt_vtab is a subclass of sqlite3_vtab which will
|
||||
** serve as the underlying representation of a stmt virtual table
|
||||
*/
|
||||
@@ -47,8 +57,7 @@ typedef struct stmt_cursor stmt_cursor;
|
||||
struct stmt_cursor {
|
||||
sqlite3_vtab_cursor base; /* Base class - must be first */
|
||||
sqlite3 *db; /* Database connection for this cursor */
|
||||
sqlite3_stmt *pStmt; /* Statement cursor is currently pointing at */
|
||||
sqlite3_int64 iRowid; /* The rowid */
|
||||
StmtRow *pRow; /* Current row */
|
||||
};
|
||||
|
||||
/*
|
||||
@@ -92,7 +101,7 @@ static int stmtConnect(
|
||||
"CREATE TABLE x(sql,ncol,ro,busy,nscan,nsort,naidx,nstep,"
|
||||
"reprep,run,mem)");
|
||||
if( rc==SQLITE_OK ){
|
||||
pNew = sqlite3_malloc( sizeof(*pNew) );
|
||||
pNew = sqlite3_malloc64( sizeof(*pNew) );
|
||||
*ppVtab = (sqlite3_vtab*)pNew;
|
||||
if( pNew==0 ) return SQLITE_NOMEM;
|
||||
memset(pNew, 0, sizeof(*pNew));
|
||||
@@ -114,7 +123,7 @@ static int stmtDisconnect(sqlite3_vtab *pVtab){
|
||||
*/
|
||||
static int stmtOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
|
||||
stmt_cursor *pCur;
|
||||
pCur = sqlite3_malloc( sizeof(*pCur) );
|
||||
pCur = sqlite3_malloc64( sizeof(*pCur) );
|
||||
if( pCur==0 ) return SQLITE_NOMEM;
|
||||
memset(pCur, 0, sizeof(*pCur));
|
||||
pCur->db = ((stmt_vtab*)p)->db;
|
||||
@@ -122,10 +131,21 @@ static int stmtOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
|
||||
return SQLITE_OK;
|
||||
}
|
||||
|
||||
static void stmtCsrReset(stmt_cursor *pCur){
|
||||
StmtRow *pRow = 0;
|
||||
StmtRow *pNext = 0;
|
||||
for(pRow=pCur->pRow; pRow; pRow=pNext){
|
||||
pNext = pRow->pNext;
|
||||
sqlite3_free(pRow);
|
||||
}
|
||||
pCur->pRow = 0;
|
||||
}
|
||||
|
||||
/*
|
||||
** Destructor for a stmt_cursor.
|
||||
*/
|
||||
static int stmtClose(sqlite3_vtab_cursor *cur){
|
||||
stmtCsrReset((stmt_cursor*)cur);
|
||||
sqlite3_free(cur);
|
||||
return SQLITE_OK;
|
||||
}
|
||||
@@ -136,8 +156,9 @@ static int stmtClose(sqlite3_vtab_cursor *cur){
|
||||
*/
|
||||
static int stmtNext(sqlite3_vtab_cursor *cur){
|
||||
stmt_cursor *pCur = (stmt_cursor*)cur;
|
||||
pCur->iRowid++;
|
||||
pCur->pStmt = sqlite3_next_stmt(pCur->db, pCur->pStmt);
|
||||
StmtRow *pNext = pCur->pRow->pNext;
|
||||
sqlite3_free(pCur->pRow);
|
||||
pCur->pRow = pNext;
|
||||
return SQLITE_OK;
|
||||
}
|
||||
|
||||
@@ -151,39 +172,11 @@ static int stmtColumn(
|
||||
int i /* Which column to return */
|
||||
){
|
||||
stmt_cursor *pCur = (stmt_cursor*)cur;
|
||||
switch( i ){
|
||||
case STMT_COLUMN_SQL: {
|
||||
sqlite3_result_text(ctx, sqlite3_sql(pCur->pStmt), -1, SQLITE_TRANSIENT);
|
||||
break;
|
||||
}
|
||||
case STMT_COLUMN_NCOL: {
|
||||
sqlite3_result_int(ctx, sqlite3_column_count(pCur->pStmt));
|
||||
break;
|
||||
}
|
||||
case STMT_COLUMN_RO: {
|
||||
sqlite3_result_int(ctx, sqlite3_stmt_readonly(pCur->pStmt));
|
||||
break;
|
||||
}
|
||||
case STMT_COLUMN_BUSY: {
|
||||
sqlite3_result_int(ctx, sqlite3_stmt_busy(pCur->pStmt));
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
assert( i==STMT_COLUMN_MEM );
|
||||
i = SQLITE_STMTSTATUS_MEMUSED +
|
||||
STMT_COLUMN_NSCAN - SQLITE_STMTSTATUS_FULLSCAN_STEP;
|
||||
/* Fall thru */
|
||||
}
|
||||
case STMT_COLUMN_NSCAN:
|
||||
case STMT_COLUMN_NSORT:
|
||||
case STMT_COLUMN_NAIDX:
|
||||
case STMT_COLUMN_NSTEP:
|
||||
case STMT_COLUMN_REPREP:
|
||||
case STMT_COLUMN_RUN: {
|
||||
sqlite3_result_int(ctx, sqlite3_stmt_status(pCur->pStmt,
|
||||
i-STMT_COLUMN_NSCAN+SQLITE_STMTSTATUS_FULLSCAN_STEP, 0));
|
||||
break;
|
||||
}
|
||||
StmtRow *pRow = pCur->pRow;
|
||||
if( i==STMT_COLUMN_SQL ){
|
||||
sqlite3_result_text(ctx, pRow->zSql, -1, SQLITE_TRANSIENT);
|
||||
}else{
|
||||
sqlite3_result_int(ctx, pRow->aCol[i]);
|
||||
}
|
||||
return SQLITE_OK;
|
||||
}
|
||||
@@ -194,7 +187,7 @@ static int stmtColumn(
|
||||
*/
|
||||
static int stmtRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
|
||||
stmt_cursor *pCur = (stmt_cursor*)cur;
|
||||
*pRowid = pCur->iRowid;
|
||||
*pRowid = pCur->pRow->iRowid;
|
||||
return SQLITE_OK;
|
||||
}
|
||||
|
||||
@@ -204,7 +197,7 @@ static int stmtRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
|
||||
*/
|
||||
static int stmtEof(sqlite3_vtab_cursor *cur){
|
||||
stmt_cursor *pCur = (stmt_cursor*)cur;
|
||||
return pCur->pStmt==0;
|
||||
return pCur->pRow==0;
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -219,9 +212,53 @@ static int stmtFilter(
|
||||
int argc, sqlite3_value **argv
|
||||
){
|
||||
stmt_cursor *pCur = (stmt_cursor *)pVtabCursor;
|
||||
pCur->pStmt = 0;
|
||||
pCur->iRowid = 0;
|
||||
return stmtNext(pVtabCursor);
|
||||
sqlite3_stmt *p = 0;
|
||||
sqlite3_int64 iRowid = 1;
|
||||
StmtRow **ppRow = 0;
|
||||
|
||||
stmtCsrReset(pCur);
|
||||
ppRow = &pCur->pRow;
|
||||
for(p=sqlite3_next_stmt(pCur->db, 0); p; p=sqlite3_next_stmt(pCur->db, p)){
|
||||
const char *zSql = sqlite3_sql(p);
|
||||
sqlite3_int64 nSql = zSql ? strlen(zSql)+1 : 0;
|
||||
StmtRow *pNew = (StmtRow*)sqlite3_malloc64(sizeof(StmtRow) + nSql);
|
||||
|
||||
if( pNew==0 ) return SQLITE_NOMEM;
|
||||
memset(pNew, 0, sizeof(StmtRow));
|
||||
if( zSql ){
|
||||
pNew->zSql = (char*)&pNew[1];
|
||||
memcpy(pNew->zSql, zSql, nSql);
|
||||
}
|
||||
pNew->aCol[STMT_COLUMN_NCOL] = sqlite3_column_count(p);
|
||||
pNew->aCol[STMT_COLUMN_RO] = sqlite3_stmt_readonly(p);
|
||||
pNew->aCol[STMT_COLUMN_BUSY] = sqlite3_stmt_busy(p);
|
||||
pNew->aCol[STMT_COLUMN_NSCAN] = sqlite3_stmt_status(
|
||||
p, SQLITE_STMTSTATUS_FULLSCAN_STEP, 0
|
||||
);
|
||||
pNew->aCol[STMT_COLUMN_NSORT] = sqlite3_stmt_status(
|
||||
p, SQLITE_STMTSTATUS_SORT, 0
|
||||
);
|
||||
pNew->aCol[STMT_COLUMN_NAIDX] = sqlite3_stmt_status(
|
||||
p, SQLITE_STMTSTATUS_AUTOINDEX, 0
|
||||
);
|
||||
pNew->aCol[STMT_COLUMN_NSTEP] = sqlite3_stmt_status(
|
||||
p, SQLITE_STMTSTATUS_VM_STEP, 0
|
||||
);
|
||||
pNew->aCol[STMT_COLUMN_REPREP] = sqlite3_stmt_status(
|
||||
p, SQLITE_STMTSTATUS_REPREPARE, 0
|
||||
);
|
||||
pNew->aCol[STMT_COLUMN_RUN] = sqlite3_stmt_status(
|
||||
p, SQLITE_STMTSTATUS_RUN, 0
|
||||
);
|
||||
pNew->aCol[STMT_COLUMN_MEM] = sqlite3_stmt_status(
|
||||
p, SQLITE_STMTSTATUS_MEMUSED, 0
|
||||
);
|
||||
pNew->iRowid = iRowid++;
|
||||
*ppRow = pNew;
|
||||
ppRow = &pNew->pNext;
|
||||
}
|
||||
|
||||
return SQLITE_OK;
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
# 2022 November 07
|
||||
#
|
||||
# The author disclaims copyright to this source code. In place of
|
||||
# a legal notice, here is a blessing:
|
||||
#
|
||||
# May you do good and not evil.
|
||||
# May you find forgiveness for yourself and forgive others.
|
||||
# May you share freely, never taking more than you give.
|
||||
#
|
||||
#***********************************************************************
|
||||
#
|
||||
#
|
||||
|
||||
source [file join [file dirname [info script]] rbu_common.tcl]
|
||||
set ::testprefix rburename
|
||||
|
||||
|
||||
do_execsql_test 1.0 {
|
||||
CREATE TABLE t1(a, b);
|
||||
INSERT INTO t1 VALUES(1, 2);
|
||||
INSERT INTO t1 VALUES(3, 4);
|
||||
INSERT INTO t1 VALUES(5, 6);
|
||||
}
|
||||
|
||||
forcedelete test.db-vacuum
|
||||
|
||||
proc my_rename {old new} {
|
||||
lappend ::my_rename_calls [list [file tail $old] [file tail $new]]
|
||||
file rename $old $new
|
||||
}
|
||||
|
||||
do_test 1.1 {
|
||||
sqlite3rbu_vacuum rbu test.db
|
||||
rbu rename_handler my_rename
|
||||
while {[rbu step]=="SQLITE_OK"} {}
|
||||
rbu close
|
||||
} SQLITE_DONE
|
||||
|
||||
do_test 1.2 {
|
||||
set ::my_rename_calls
|
||||
} {{test.db-oal test.db-wal}}
|
||||
|
||||
proc my_rename {old new} {
|
||||
error "something went wrong"
|
||||
}
|
||||
|
||||
do_test 1.3 {
|
||||
sqlite3rbu_vacuum rbu test.db
|
||||
rbu rename_handler my_rename
|
||||
while {[rbu step]=="SQLITE_OK"} {}
|
||||
list [catch { rbu close } msg] $msg
|
||||
} {1 SQLITE_IOERR}
|
||||
|
||||
finish_test
|
||||
@@ -227,10 +227,11 @@ do_test 6.1 {
|
||||
rbu close
|
||||
} {SQLITE_OK}
|
||||
|
||||
do_execsql_test 6.2 {
|
||||
SELECT 1 FROM sqlite_master LIMIT 1;
|
||||
PRAGMA wal_checkpoint;
|
||||
} {1 0 4 4}
|
||||
do_test 6.2 {
|
||||
execsql { SELECT 1 FROM sqlite_master LIMIT 1 }
|
||||
execsql { PRAGMA wal_checkpoint }
|
||||
execsql { SELECT 1 FROM sqlite_master LIMIT 1 }
|
||||
} {1}
|
||||
|
||||
do_test 6.3 {
|
||||
sqlite3rbu_vacuum rbu test.db test.db2
|
||||
|
||||
+53
-27
@@ -393,6 +393,8 @@ struct sqlite3rbu {
|
||||
int nPagePerSector; /* Pages per sector for pTargetFd */
|
||||
i64 iOalSz;
|
||||
i64 nPhaseOneStep;
|
||||
void *pRenameArg;
|
||||
int (*xRename)(void*, const char*, const char*);
|
||||
|
||||
/* The following state variables are used as part of the incremental
|
||||
** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
|
||||
@@ -2781,7 +2783,7 @@ static void rbuOpenDatabase(sqlite3rbu *p, sqlite3 *dbMain, int *pbRetry){
|
||||
sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
|
||||
if( p->zState==0 ){
|
||||
const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
|
||||
p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile);
|
||||
p->zState = rbuMPrintf(p, "file:///%s-vacuum?modeof=%s", zFile, zFile);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3241,32 +3243,7 @@ static void rbuMoveOalFile(sqlite3rbu *p){
|
||||
}
|
||||
|
||||
if( p->rc==SQLITE_OK ){
|
||||
#if defined(_WIN32_WCE)
|
||||
{
|
||||
LPWSTR zWideOal;
|
||||
LPWSTR zWideWal;
|
||||
|
||||
zWideOal = rbuWinUtf8ToUnicode(zOal);
|
||||
if( zWideOal ){
|
||||
zWideWal = rbuWinUtf8ToUnicode(zWal);
|
||||
if( zWideWal ){
|
||||
if( MoveFileW(zWideOal, zWideWal) ){
|
||||
p->rc = SQLITE_OK;
|
||||
}else{
|
||||
p->rc = SQLITE_IOERR;
|
||||
}
|
||||
sqlite3_free(zWideWal);
|
||||
}else{
|
||||
p->rc = SQLITE_IOERR_NOMEM;
|
||||
}
|
||||
sqlite3_free(zWideOal);
|
||||
}else{
|
||||
p->rc = SQLITE_IOERR_NOMEM;
|
||||
}
|
||||
}
|
||||
#else
|
||||
p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
|
||||
#endif
|
||||
p->rc = p->xRename(p->pRenameArg, zOal, zWal);
|
||||
}
|
||||
|
||||
if( p->rc!=SQLITE_OK
|
||||
@@ -4005,6 +3982,7 @@ static sqlite3rbu *openRbuHandle(
|
||||
|
||||
/* Create the custom VFS. */
|
||||
memset(p, 0, sizeof(sqlite3rbu));
|
||||
sqlite3rbu_rename_handler(p, 0, 0);
|
||||
rbuCreateVfs(p);
|
||||
|
||||
/* Open the target, RBU and state databases */
|
||||
@@ -4396,6 +4374,54 @@ int sqlite3rbu_savestate(sqlite3rbu *p){
|
||||
return rc;
|
||||
}
|
||||
|
||||
/*
|
||||
** Default xRename callback for RBU.
|
||||
*/
|
||||
static int xDefaultRename(void *pArg, const char *zOld, const char *zNew){
|
||||
int rc = SQLITE_OK;
|
||||
#if defined(_WIN32_WCE)
|
||||
{
|
||||
LPWSTR zWideOld;
|
||||
LPWSTR zWideNew;
|
||||
|
||||
zWideOld = rbuWinUtf8ToUnicode(zOld);
|
||||
if( zWideOld ){
|
||||
zWideNew = rbuWinUtf8ToUnicode(zNew);
|
||||
if( zWideNew ){
|
||||
if( MoveFileW(zWideOld, zWideNew) ){
|
||||
rc = SQLITE_OK;
|
||||
}else{
|
||||
rc = SQLITE_IOERR;
|
||||
}
|
||||
sqlite3_free(zWideNew);
|
||||
}else{
|
||||
rc = SQLITE_IOERR_NOMEM;
|
||||
}
|
||||
sqlite3_free(zWideOld);
|
||||
}else{
|
||||
rc = SQLITE_IOERR_NOMEM;
|
||||
}
|
||||
}
|
||||
#else
|
||||
rc = rename(zOld, zNew) ? SQLITE_IOERR : SQLITE_OK;
|
||||
#endif
|
||||
return rc;
|
||||
}
|
||||
|
||||
void sqlite3rbu_rename_handler(
|
||||
sqlite3rbu *pRbu,
|
||||
void *pArg,
|
||||
int (*xRename)(void *pArg, const char *zOld, const char *zNew)
|
||||
){
|
||||
if( xRename ){
|
||||
pRbu->xRename = xRename;
|
||||
pRbu->pRenameArg = pArg;
|
||||
}else{
|
||||
pRbu->xRename = xDefaultRename;
|
||||
pRbu->pRenameArg = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**************************************************************************
|
||||
** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
|
||||
** of a standard VFS in the following ways:
|
||||
|
||||
@@ -544,6 +544,34 @@ SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int*pnTwo);
|
||||
|
||||
SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
|
||||
|
||||
/*
|
||||
** As part of applying an RBU update or performing an RBU vacuum operation,
|
||||
** the system must at one point move the *-oal file to the equivalent *-wal
|
||||
** path. Normally, it does this by invoking POSIX function rename(2) directly.
|
||||
** Except on WINCE platforms, where it uses win32 API MoveFileW(). This
|
||||
** function may be used to register a callback that the RBU module will invoke
|
||||
** instead of one of these APIs.
|
||||
**
|
||||
** If a callback is registered with an RBU handle, it invokes it instead
|
||||
** of rename(2) when it needs to move a file within the file-system. The
|
||||
** first argument passed to the xRename() callback is a copy of the second
|
||||
** argument (pArg) passed to this function. The second is the full path
|
||||
** to the file to move and the third the full path to which it should be
|
||||
** moved. The callback function should return SQLITE_OK to indicate
|
||||
** success. If an error occurs, it should return an SQLite error code.
|
||||
** In this case the RBU operation will be abandoned and the error returned
|
||||
** to the RBU user.
|
||||
**
|
||||
** Passing a NULL pointer in place of the xRename argument to this function
|
||||
** restores the default behaviour.
|
||||
*/
|
||||
SQLITE_API void sqlite3rbu_rename_handler(
|
||||
sqlite3rbu *pRbu,
|
||||
void *pArg,
|
||||
int (*xRename)(void *pArg, const char *zOld, const char *zNew)
|
||||
);
|
||||
|
||||
|
||||
/*
|
||||
** Create an RBU VFS named zName that accesses the underlying file-system
|
||||
** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
|
||||
|
||||
+54
-3
@@ -26,6 +26,14 @@
|
||||
# endif
|
||||
#endif
|
||||
#include <assert.h>
|
||||
#include <string.h>
|
||||
|
||||
typedef struct TestRbu TestRbu;
|
||||
struct TestRbu {
|
||||
sqlite3rbu *pRbu;
|
||||
Tcl_Interp *interp;
|
||||
Tcl_Obj *xRename;
|
||||
};
|
||||
|
||||
/* From main.c */
|
||||
extern const char *sqlite3ErrName(int);
|
||||
@@ -55,6 +63,20 @@ void test_rbu_delta(sqlite3_context *pCtx, int nArg, sqlite3_value **apVal){
|
||||
Tcl_DecrRefCount(pScript);
|
||||
}
|
||||
|
||||
static int xRenameCallback(void *pArg, const char *zOld, const char *zNew){
|
||||
int rc = SQLITE_OK;
|
||||
TestRbu *pTest = (TestRbu*)pArg;
|
||||
Tcl_Obj *pEval = Tcl_DuplicateObj(pTest->xRename);
|
||||
|
||||
Tcl_IncrRefCount(pEval);
|
||||
Tcl_ListObjAppendElement(pTest->interp, pEval, Tcl_NewStringObj(zOld, -1));
|
||||
Tcl_ListObjAppendElement(pTest->interp, pEval, Tcl_NewStringObj(zNew, -1));
|
||||
|
||||
rc = Tcl_EvalObjEx(pTest->interp, pEval, TCL_GLOBAL_ONLY);
|
||||
Tcl_DecrRefCount(pEval);
|
||||
|
||||
return rc ? SQLITE_IOERR : SQLITE_OK;
|
||||
}
|
||||
|
||||
static int SQLITE_TCLAPI test_sqlite3rbu_cmd(
|
||||
ClientData clientData,
|
||||
@@ -63,7 +85,8 @@ static int SQLITE_TCLAPI test_sqlite3rbu_cmd(
|
||||
Tcl_Obj *CONST objv[]
|
||||
){
|
||||
int ret = TCL_OK;
|
||||
sqlite3rbu *pRbu = (sqlite3rbu*)clientData;
|
||||
TestRbu *pTest = (TestRbu*)clientData;
|
||||
sqlite3rbu *pRbu = pTest->pRbu;
|
||||
struct RbuCmd {
|
||||
const char *zName;
|
||||
int nArg;
|
||||
@@ -82,6 +105,7 @@ static int SQLITE_TCLAPI test_sqlite3rbu_cmd(
|
||||
{"temp_size_limit", 3, "LIMIT"}, /* 10 */
|
||||
{"temp_size", 2, ""}, /* 11 */
|
||||
{"dbRbu_eval", 3, "SQL"}, /* 12 */
|
||||
{"rename_handler", 3, "SCRIPT"},/* 13 */
|
||||
{0,0,0}
|
||||
};
|
||||
int iCmd;
|
||||
@@ -127,6 +151,8 @@ static int SQLITE_TCLAPI test_sqlite3rbu_cmd(
|
||||
}
|
||||
ret = TCL_ERROR;
|
||||
}
|
||||
if( pTest->xRename ) Tcl_DecrRefCount(pTest->xRename);
|
||||
ckfree(pTest);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -214,6 +240,19 @@ static int SQLITE_TCLAPI test_sqlite3rbu_cmd(
|
||||
break;
|
||||
}
|
||||
|
||||
case 13: /* rename_handler */ {
|
||||
Tcl_Obj *pScript = objv[2];
|
||||
assert( !sqlite3_stricmp(aCmd[13].zName, "rename_handler") );
|
||||
if( Tcl_GetCharLength(pScript)==0 ){
|
||||
sqlite3rbu_rename_handler(pRbu, 0, 0);
|
||||
}else{
|
||||
pTest->xRename = Tcl_DuplicateObj(pScript);
|
||||
Tcl_IncrRefCount(pTest->xRename);
|
||||
sqlite3rbu_rename_handler(pRbu, pTest, xRenameCallback);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
default: /* seems unlikely */
|
||||
assert( !"cannot happen" );
|
||||
break;
|
||||
@@ -222,6 +261,18 @@ static int SQLITE_TCLAPI test_sqlite3rbu_cmd(
|
||||
return ret;
|
||||
}
|
||||
|
||||
static void createRbuWrapper(
|
||||
Tcl_Interp *interp,
|
||||
const char *zCmd,
|
||||
sqlite3rbu *pRbu
|
||||
){
|
||||
TestRbu *pTest = (TestRbu*)ckalloc(sizeof(TestRbu));
|
||||
memset(pTest, 0, sizeof(TestRbu));
|
||||
pTest->pRbu = pRbu;
|
||||
pTest->interp = interp;
|
||||
Tcl_CreateObjCommand(interp, zCmd, test_sqlite3rbu_cmd, (ClientData)pTest, 0);
|
||||
}
|
||||
|
||||
/*
|
||||
** Tclcmd: sqlite3rbu CMD <target-db> <rbu-db> ?<state-db>?
|
||||
*/
|
||||
@@ -247,7 +298,7 @@ static int SQLITE_TCLAPI test_sqlite3rbu(
|
||||
if( objc==5 ) zStateDb = Tcl_GetString(objv[4]);
|
||||
|
||||
pRbu = sqlite3rbu_open(zTarget, zRbu, zStateDb);
|
||||
Tcl_CreateObjCommand(interp, zCmd, test_sqlite3rbu_cmd, (ClientData)pRbu, 0);
|
||||
createRbuWrapper(interp, zCmd, pRbu);
|
||||
Tcl_SetObjResult(interp, objv[1]);
|
||||
return TCL_OK;
|
||||
}
|
||||
@@ -276,7 +327,7 @@ static int SQLITE_TCLAPI test_sqlite3rbu_vacuum(
|
||||
if( zStateDb && zStateDb[0]=='\0' ) zStateDb = 0;
|
||||
|
||||
pRbu = sqlite3rbu_vacuum(zTarget, zStateDb);
|
||||
Tcl_CreateObjCommand(interp, zCmd, test_sqlite3rbu_cmd, (ClientData)pRbu, 0);
|
||||
createRbuWrapper(interp, zCmd, pRbu);
|
||||
Tcl_SetObjResult(interp, objv[1]);
|
||||
return TCL_OK;
|
||||
}
|
||||
|
||||
@@ -71,16 +71,20 @@
|
||||
** It contains one entry for each b-tree pointer between a parent and
|
||||
** child page in the database.
|
||||
*/
|
||||
|
||||
#if !defined(SQLITEINT_H)
|
||||
#include "sqlite3ext.h"
|
||||
|
||||
typedef unsigned char u8;
|
||||
typedef unsigned int u32;
|
||||
|
||||
#endif
|
||||
SQLITE_EXTENSION_INIT1
|
||||
#include <string.h>
|
||||
#include <assert.h>
|
||||
|
||||
#ifndef SQLITE_OMIT_VIRTUALTABLE
|
||||
|
||||
#define DBDATA_PADDING_BYTES 100
|
||||
|
||||
typedef struct DbdataTable DbdataTable;
|
||||
@@ -102,11 +106,12 @@ struct DbdataCursor {
|
||||
|
||||
/* Only for the sqlite_dbdata table */
|
||||
u8 *pRec; /* Buffer containing current record */
|
||||
int nRec; /* Size of pRec[] in bytes */
|
||||
int nHdr; /* Size of header in bytes */
|
||||
sqlite3_int64 nRec; /* Size of pRec[] in bytes */
|
||||
sqlite3_int64 nHdr; /* Size of header in bytes */
|
||||
int iField; /* Current field number */
|
||||
u8 *pHdrPtr;
|
||||
u8 *pPtr;
|
||||
u32 enc; /* Text encoding */
|
||||
|
||||
sqlite3_int64 iIntkey; /* Integer key value */
|
||||
};
|
||||
@@ -299,14 +304,14 @@ static int dbdataClose(sqlite3_vtab_cursor *pCursor){
|
||||
/*
|
||||
** Utility methods to decode 16 and 32-bit big-endian unsigned integers.
|
||||
*/
|
||||
static unsigned int get_uint16(unsigned char *a){
|
||||
static u32 get_uint16(unsigned char *a){
|
||||
return (a[0]<<8)|a[1];
|
||||
}
|
||||
static unsigned int get_uint32(unsigned char *a){
|
||||
return ((unsigned int)a[0]<<24)
|
||||
| ((unsigned int)a[1]<<16)
|
||||
| ((unsigned int)a[2]<<8)
|
||||
| ((unsigned int)a[3]);
|
||||
static u32 get_uint32(unsigned char *a){
|
||||
return ((u32)a[0]<<24)
|
||||
| ((u32)a[1]<<16)
|
||||
| ((u32)a[2]<<8)
|
||||
| ((u32)a[3]);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -321,7 +326,7 @@ static unsigned int get_uint32(unsigned char *a){
|
||||
*/
|
||||
static int dbdataLoadPage(
|
||||
DbdataCursor *pCsr, /* Cursor object */
|
||||
unsigned int pgno, /* Page number of page to load */
|
||||
u32 pgno, /* Page number of page to load */
|
||||
u8 **ppPage, /* OUT: pointer to page buffer */
|
||||
int *pnPage /* OUT: Size of (*ppPage) in bytes */
|
||||
){
|
||||
@@ -331,25 +336,27 @@ static int dbdataLoadPage(
|
||||
|
||||
*ppPage = 0;
|
||||
*pnPage = 0;
|
||||
sqlite3_bind_int64(pStmt, 2, pgno);
|
||||
if( SQLITE_ROW==sqlite3_step(pStmt) ){
|
||||
int nCopy = sqlite3_column_bytes(pStmt, 0);
|
||||
if( nCopy>0 ){
|
||||
u8 *pPage;
|
||||
pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);
|
||||
if( pPage==0 ){
|
||||
rc = SQLITE_NOMEM;
|
||||
}else{
|
||||
const u8 *pCopy = sqlite3_column_blob(pStmt, 0);
|
||||
memcpy(pPage, pCopy, nCopy);
|
||||
memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
|
||||
if( pgno>0 ){
|
||||
sqlite3_bind_int64(pStmt, 2, pgno);
|
||||
if( SQLITE_ROW==sqlite3_step(pStmt) ){
|
||||
int nCopy = sqlite3_column_bytes(pStmt, 0);
|
||||
if( nCopy>0 ){
|
||||
u8 *pPage;
|
||||
pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);
|
||||
if( pPage==0 ){
|
||||
rc = SQLITE_NOMEM;
|
||||
}else{
|
||||
const u8 *pCopy = sqlite3_column_blob(pStmt, 0);
|
||||
memcpy(pPage, pCopy, nCopy);
|
||||
memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
|
||||
}
|
||||
*ppPage = pPage;
|
||||
*pnPage = nCopy;
|
||||
}
|
||||
*ppPage = pPage;
|
||||
*pnPage = nCopy;
|
||||
}
|
||||
rc2 = sqlite3_reset(pStmt);
|
||||
if( rc==SQLITE_OK ) rc = rc2;
|
||||
}
|
||||
rc2 = sqlite3_reset(pStmt);
|
||||
if( rc==SQLITE_OK ) rc = rc2;
|
||||
|
||||
return rc;
|
||||
}
|
||||
@@ -358,17 +365,30 @@ static int dbdataLoadPage(
|
||||
** Read a varint. Put the value in *pVal and return the number of bytes.
|
||||
*/
|
||||
static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){
|
||||
sqlite3_int64 v = 0;
|
||||
sqlite3_uint64 u = 0;
|
||||
int i;
|
||||
for(i=0; i<8; i++){
|
||||
v = (v<<7) + (z[i]&0x7f);
|
||||
if( (z[i]&0x80)==0 ){ *pVal = v; return i+1; }
|
||||
u = (u<<7) + (z[i]&0x7f);
|
||||
if( (z[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
|
||||
}
|
||||
v = (v<<8) + (z[i]&0xff);
|
||||
*pVal = v;
|
||||
u = (u<<8) + (z[i]&0xff);
|
||||
*pVal = (sqlite3_int64)u;
|
||||
return 9;
|
||||
}
|
||||
|
||||
/*
|
||||
** Like dbdataGetVarint(), but set the output to 0 if it is less than 0
|
||||
** or greater than 0xFFFFFFFF. This can be used for all varints in an
|
||||
** SQLite database except for key values in intkey tables.
|
||||
*/
|
||||
static int dbdataGetVarintU32(const u8 *z, sqlite3_int64 *pVal){
|
||||
sqlite3_int64 val;
|
||||
int nRet = dbdataGetVarint(z, &val);
|
||||
if( val<0 || val>0xFFFFFFFF ) val = 0;
|
||||
*pVal = val;
|
||||
return nRet;
|
||||
}
|
||||
|
||||
/*
|
||||
** Return the number of bytes of space used by an SQLite value of type
|
||||
** eType.
|
||||
@@ -405,9 +425,10 @@ static int dbdataValueBytes(int eType){
|
||||
*/
|
||||
static void dbdataValue(
|
||||
sqlite3_context *pCtx,
|
||||
u32 enc,
|
||||
int eType,
|
||||
u8 *pData,
|
||||
int nData
|
||||
sqlite3_int64 nData
|
||||
){
|
||||
if( eType>=0 && dbdataValueBytes(eType)<=nData ){
|
||||
switch( eType ){
|
||||
@@ -449,7 +470,19 @@ static void dbdataValue(
|
||||
default: {
|
||||
int n = ((eType-12) / 2);
|
||||
if( eType % 2 ){
|
||||
sqlite3_result_text(pCtx, (const char*)pData, n, SQLITE_TRANSIENT);
|
||||
switch( enc ){
|
||||
#ifndef SQLITE_OMIT_UTF16
|
||||
case SQLITE_UTF16BE:
|
||||
sqlite3_result_text16be(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
|
||||
break;
|
||||
case SQLITE_UTF16LE:
|
||||
sqlite3_result_text16le(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
|
||||
break;
|
||||
#endif
|
||||
default:
|
||||
sqlite3_result_text(pCtx, (char*)pData, n, SQLITE_TRANSIENT);
|
||||
break;
|
||||
}
|
||||
}else{
|
||||
sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
|
||||
}
|
||||
@@ -477,6 +510,7 @@ static int dbdataNext(sqlite3_vtab_cursor *pCursor){
|
||||
rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);
|
||||
if( rc!=SQLITE_OK ) return rc;
|
||||
if( pCsr->aPage ) break;
|
||||
if( pCsr->bOnePage ) return SQLITE_OK;
|
||||
pCsr->iPgno++;
|
||||
}
|
||||
pCsr->iCell = pTab->bPtr ? -2 : 0;
|
||||
@@ -540,7 +574,7 @@ static int dbdataNext(sqlite3_vtab_cursor *pCursor){
|
||||
if( bNextPage || iOff>pCsr->nPage ){
|
||||
bNextPage = 1;
|
||||
}else{
|
||||
iOff += dbdataGetVarint(&pCsr->aPage[iOff], &nPayload);
|
||||
iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload);
|
||||
}
|
||||
|
||||
/* If this is a leaf intkey cell, load the rowid */
|
||||
@@ -587,7 +621,7 @@ static int dbdataNext(sqlite3_vtab_cursor *pCursor){
|
||||
/* Load content from overflow pages */
|
||||
if( nPayload>nLocal ){
|
||||
sqlite3_int64 nRem = nPayload - nLocal;
|
||||
unsigned int pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
|
||||
u32 pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
|
||||
while( nRem>0 ){
|
||||
u8 *aOvfl = 0;
|
||||
int nOvfl = 0;
|
||||
@@ -607,7 +641,8 @@ static int dbdataNext(sqlite3_vtab_cursor *pCursor){
|
||||
}
|
||||
}
|
||||
|
||||
iHdr = dbdataGetVarint(pCsr->pRec, &nHdr);
|
||||
iHdr = dbdataGetVarintU32(pCsr->pRec, &nHdr);
|
||||
if( nHdr>nPayload ) nHdr = 0;
|
||||
pCsr->nHdr = nHdr;
|
||||
pCsr->pHdrPtr = &pCsr->pRec[iHdr];
|
||||
pCsr->pPtr = &pCsr->pRec[pCsr->nHdr];
|
||||
@@ -621,7 +656,7 @@ static int dbdataNext(sqlite3_vtab_cursor *pCursor){
|
||||
if( pCsr->pHdrPtr>&pCsr->pRec[pCsr->nRec] ){
|
||||
bNextPage = 1;
|
||||
}else{
|
||||
pCsr->pHdrPtr += dbdataGetVarint(pCsr->pHdrPtr, &iType);
|
||||
pCsr->pHdrPtr += dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
|
||||
pCsr->pPtr += dbdataValueBytes(iType);
|
||||
}
|
||||
}
|
||||
@@ -660,6 +695,18 @@ static int dbdataEof(sqlite3_vtab_cursor *pCursor){
|
||||
return pCsr->aPage==0;
|
||||
}
|
||||
|
||||
/*
|
||||
** Return true if nul-terminated string zSchema ends in "()". Or false
|
||||
** otherwise.
|
||||
*/
|
||||
static int dbdataIsFunction(const char *zSchema){
|
||||
size_t n = strlen(zSchema);
|
||||
if( n>2 && zSchema[n-2]=='(' && zSchema[n-1]==')' ){
|
||||
return (int)n-2;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
** Determine the size in pages of database zSchema (where zSchema is
|
||||
** "main", "temp" or the name of an attached database) and set
|
||||
@@ -670,10 +717,16 @@ static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){
|
||||
DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;
|
||||
char *zSql = 0;
|
||||
int rc, rc2;
|
||||
int nFunc = 0;
|
||||
sqlite3_stmt *pStmt = 0;
|
||||
|
||||
zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema);
|
||||
if( (nFunc = dbdataIsFunction(zSchema))>0 ){
|
||||
zSql = sqlite3_mprintf("SELECT %.*s(0)", nFunc, zSchema);
|
||||
}else{
|
||||
zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema);
|
||||
}
|
||||
if( zSql==0 ) return SQLITE_NOMEM;
|
||||
|
||||
rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
|
||||
sqlite3_free(zSql);
|
||||
if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
|
||||
@@ -684,6 +737,25 @@ static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){
|
||||
return rc;
|
||||
}
|
||||
|
||||
/*
|
||||
** Attempt to figure out the encoding of the database by retrieving page 1
|
||||
** and inspecting the header field. If successful, set the pCsr->enc variable
|
||||
** and return SQLITE_OK. Otherwise, return an SQLite error code.
|
||||
*/
|
||||
static int dbdataGetEncoding(DbdataCursor *pCsr){
|
||||
int rc = SQLITE_OK;
|
||||
int nPg1 = 0;
|
||||
u8 *aPg1 = 0;
|
||||
rc = dbdataLoadPage(pCsr, 1, &aPg1, &nPg1);
|
||||
assert( rc!=SQLITE_OK || nPg1==0 || nPg1>=512 );
|
||||
if( rc==SQLITE_OK && nPg1>0 ){
|
||||
pCsr->enc = get_uint32(&aPg1[56]);
|
||||
}
|
||||
sqlite3_free(aPg1);
|
||||
return rc;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** xFilter method for sqlite_dbdata and sqlite_dbptr.
|
||||
*/
|
||||
@@ -701,19 +773,28 @@ static int dbdataFilter(
|
||||
assert( pCsr->iPgno==1 );
|
||||
if( idxNum & 0x01 ){
|
||||
zSchema = (const char*)sqlite3_value_text(argv[0]);
|
||||
if( zSchema==0 ) zSchema = "";
|
||||
}
|
||||
if( idxNum & 0x02 ){
|
||||
pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]);
|
||||
pCsr->bOnePage = 1;
|
||||
}else{
|
||||
pCsr->nPage = dbdataDbsize(pCsr, zSchema);
|
||||
rc = dbdataDbsize(pCsr, zSchema);
|
||||
}
|
||||
|
||||
if( rc==SQLITE_OK ){
|
||||
int nFunc = 0;
|
||||
if( pTab->pStmt ){
|
||||
pCsr->pStmt = pTab->pStmt;
|
||||
pTab->pStmt = 0;
|
||||
}else if( (nFunc = dbdataIsFunction(zSchema))>0 ){
|
||||
char *zSql = sqlite3_mprintf("SELECT %.*s(?2)", nFunc, zSchema);
|
||||
if( zSql==0 ){
|
||||
rc = SQLITE_NOMEM;
|
||||
}else{
|
||||
rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
|
||||
sqlite3_free(zSql);
|
||||
}
|
||||
}else{
|
||||
rc = sqlite3_prepare_v2(pTab->db,
|
||||
"SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1,
|
||||
@@ -726,13 +807,20 @@ static int dbdataFilter(
|
||||
}else{
|
||||
pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
|
||||
}
|
||||
|
||||
/* Try to determine the encoding of the db by inspecting the header
|
||||
** field on page 1. */
|
||||
if( rc==SQLITE_OK ){
|
||||
rc = dbdataGetEncoding(pCsr);
|
||||
}
|
||||
|
||||
if( rc==SQLITE_OK ){
|
||||
rc = dbdataNext(pCursor);
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
/*
|
||||
/*
|
||||
** Return a column for the sqlite_dbdata or sqlite_dbptr table.
|
||||
*/
|
||||
static int dbdataColumn(
|
||||
@@ -776,11 +864,12 @@ static int dbdataColumn(
|
||||
case DBDATA_COLUMN_VALUE: {
|
||||
if( pCsr->iField<0 ){
|
||||
sqlite3_result_int64(ctx, pCsr->iIntkey);
|
||||
}else{
|
||||
}else if( &pCsr->pRec[pCsr->nRec] >= pCsr->pPtr ){
|
||||
sqlite3_int64 iType;
|
||||
dbdataGetVarint(pCsr->pHdrPtr, &iType);
|
||||
dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
|
||||
dbdataValue(
|
||||
ctx, iType, pCsr->pPtr, &pCsr->pRec[pCsr->nRec] - pCsr->pPtr
|
||||
ctx, pCsr->enc, iType, pCsr->pPtr,
|
||||
&pCsr->pRec[pCsr->nRec] - pCsr->pPtr
|
||||
);
|
||||
}
|
||||
break;
|
||||
@@ -849,3 +938,5 @@ int sqlite3_dbdata_init(
|
||||
SQLITE_EXTENSION_INIT2(pApi);
|
||||
return sqlite3DbdataRegister(db);
|
||||
}
|
||||
|
||||
#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
|
||||
@@ -0,0 +1,277 @@
|
||||
# 2022 August 28
|
||||
#
|
||||
# The author disclaims copyright to this source code. In place of
|
||||
# a legal notice, here is a blessing:
|
||||
#
|
||||
# May you do good and not evil.
|
||||
# May you find forgiveness for yourself and forgive others.
|
||||
# May you share freely, never taking more than you give.
|
||||
#
|
||||
#***********************************************************************
|
||||
#
|
||||
|
||||
source [file join [file dirname [info script]] recover_common.tcl]
|
||||
set testprefix recover1
|
||||
|
||||
proc compare_result {db1 db2 sql} {
|
||||
set r1 [$db1 eval $sql]
|
||||
set r2 [$db2 eval $sql]
|
||||
if {$r1 != $r2} {
|
||||
puts "r1: $r1"
|
||||
puts "r2: $r2"
|
||||
error "mismatch for $sql"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
proc compare_dbs {db1 db2} {
|
||||
compare_result $db1 $db2 "SELECT sql FROM sqlite_master ORDER BY 1"
|
||||
foreach tbl [$db1 eval {SELECT name FROM sqlite_master WHERE type='table'}] {
|
||||
compare_result $db1 $db2 "SELECT * FROM $tbl"
|
||||
}
|
||||
|
||||
compare_result $db1 $db2 "PRAGMA page_size"
|
||||
compare_result $db1 $db2 "PRAGMA auto_vacuum"
|
||||
compare_result $db1 $db2 "PRAGMA encoding"
|
||||
compare_result $db1 $db2 "PRAGMA user_version"
|
||||
compare_result $db1 $db2 "PRAGMA application_id"
|
||||
}
|
||||
|
||||
proc do_recover_test {tn} {
|
||||
forcedelete test.db2
|
||||
forcedelete rstate.db
|
||||
|
||||
uplevel [list do_test $tn.1 {
|
||||
set R [sqlite3_recover_init db main test.db2]
|
||||
$R config testdb rstate.db
|
||||
$R run
|
||||
$R finish
|
||||
} {}]
|
||||
|
||||
sqlite3 db2 test.db2
|
||||
uplevel [list do_test $tn.2 [list compare_dbs db db2] {}]
|
||||
db2 close
|
||||
|
||||
forcedelete test.db2
|
||||
forcedelete rstate.db
|
||||
|
||||
uplevel [list do_test $tn.3 {
|
||||
set ::sqlhook [list]
|
||||
set R [sqlite3_recover_init_sql db main my_sql_hook]
|
||||
$R config testdb rstate.db
|
||||
$R config rowids 1
|
||||
$R run
|
||||
$R finish
|
||||
} {}]
|
||||
|
||||
sqlite3 db2 test.db2
|
||||
execsql [join $::sqlhook ";"] db2
|
||||
db2 close
|
||||
sqlite3 db2 test.db2
|
||||
uplevel [list do_test $tn.4 [list compare_dbs db db2] {}]
|
||||
db2 close
|
||||
}
|
||||
|
||||
proc my_sql_hook {sql} {
|
||||
lappend ::sqlhook $sql
|
||||
return 0
|
||||
}
|
||||
|
||||
do_execsql_test 1.0 {
|
||||
CREATE TABLE t1(a INTEGER PRIMARY KEY, b);
|
||||
CREATE TABLE t2(a INTEGER PRIMARY KEY, b) WITHOUT ROWID;
|
||||
WITH s(i) AS (
|
||||
SELECT 1 UNION ALL SELECT i+1 FROM s WHERE i<10
|
||||
)
|
||||
INSERT INTO t1 SELECT i*2, hex(randomblob(250)) FROM s;
|
||||
INSERT INTO t2 SELECT * FROM t1;
|
||||
}
|
||||
|
||||
do_recover_test 1
|
||||
|
||||
do_execsql_test 2.0 {
|
||||
ALTER TABLE t1 ADD COLUMN c DEFAULT 'xyz'
|
||||
}
|
||||
do_recover_test 2
|
||||
|
||||
do_execsql_test 3.0 {
|
||||
CREATE INDEX i1 ON t1(c);
|
||||
}
|
||||
do_recover_test 3
|
||||
|
||||
do_execsql_test 4.0 {
|
||||
CREATE VIEW v1 AS SELECT * FROM t2;
|
||||
}
|
||||
do_recover_test 4
|
||||
|
||||
do_execsql_test 5.0 {
|
||||
CREATE UNIQUE INDEX i2 ON t1(c, b);
|
||||
}
|
||||
do_recover_test 5
|
||||
|
||||
#--------------------------------------------------------------------------
|
||||
#
|
||||
reset_db
|
||||
do_execsql_test 6.0 {
|
||||
CREATE TABLE t1(
|
||||
a INTEGER PRIMARY KEY,
|
||||
b INT,
|
||||
c TEXT,
|
||||
d INT GENERATED ALWAYS AS (a*abs(b)) VIRTUAL,
|
||||
e TEXT GENERATED ALWAYS AS (substr(c,b,b+1)) STORED,
|
||||
f TEXT GENERATED ALWAYS AS (substr(c,b,b+1)) STORED
|
||||
);
|
||||
|
||||
INSERT INTO t1 VALUES(1, 2, 'hello world');
|
||||
}
|
||||
do_recover_test 6
|
||||
|
||||
do_execsql_test 7.0 {
|
||||
CREATE TABLE t2(i, j GENERATED ALWAYS AS (i+1) STORED, k);
|
||||
INSERT INTO t2 VALUES(10, 'ten');
|
||||
}
|
||||
do_execsql_test 7.1 {
|
||||
SELECT * FROM t2
|
||||
} {10 11 ten}
|
||||
|
||||
do_recover_test 7.2
|
||||
|
||||
#--------------------------------------------------------------------------
|
||||
#
|
||||
reset_db
|
||||
do_execsql_test 8.0 {
|
||||
CREATE TABLE x1(a INTEGER PRIMARY KEY AUTOINCREMENT, b, c);
|
||||
WITH s(i) AS (
|
||||
SELECT 1 UNION ALL SELECT i+1 FROM s WHERE i<2
|
||||
)
|
||||
INSERT INTO x1(b, c) SELECT hex(randomblob(100)), hex(randomblob(100)) FROM s;
|
||||
|
||||
CREATE INDEX x1b ON x1(b);
|
||||
CREATE INDEX x1cb ON x1(c, b);
|
||||
DELETE FROM x1 WHERE a>50;
|
||||
|
||||
ANALYZE;
|
||||
}
|
||||
|
||||
do_recover_test 8
|
||||
|
||||
#-------------------------------------------------------------------------
|
||||
reset_db
|
||||
ifcapable fts5 {
|
||||
do_execsql_test 9.1 {
|
||||
CREATE VIRTUAL TABLE ft5 USING fts5(a, b);
|
||||
INSERT INTO ft5 VALUES('hello', 'world');
|
||||
}
|
||||
do_recover_test 9
|
||||
}
|
||||
|
||||
#-------------------------------------------------------------------------
|
||||
reset_db
|
||||
do_execsql_test 10.1 {
|
||||
CREATE TABLE x1(a PRIMARY KEY, str TEXT) WITHOUT ROWID;
|
||||
INSERT INTO x1 VALUES(1, '
|
||||
\nhello\012world(\n0)(\n1)
|
||||
');
|
||||
INSERT INTO x1 VALUES(2, '
|
||||
\nhello
|
||||
');
|
||||
}
|
||||
do_execsql_test 10.2 "
|
||||
INSERT INTO x1 VALUES(3, '\012hello there\015world');
|
||||
INSERT INTO x1 VALUES(4, '\015hello there\015world');
|
||||
"
|
||||
do_recover_test 10
|
||||
|
||||
#-------------------------------------------------------------------------
|
||||
reset_db
|
||||
do_execsql_test 11.1 {
|
||||
PRAGMA page_size = 4096;
|
||||
PRAGMA encoding='utf16';
|
||||
PRAGMA auto_vacuum = 2;
|
||||
PRAGMA user_version = 45;
|
||||
PRAGMA application_id = 22;
|
||||
|
||||
CREATE TABLE u1(u, v);
|
||||
INSERT INTO u1 VALUES('edvin marton', 'bond');
|
||||
INSERT INTO u1 VALUES(1, 4.0);
|
||||
}
|
||||
do_execsql_test 11.1a {
|
||||
PRAGMA auto_vacuum;
|
||||
} {2}
|
||||
|
||||
do_recover_test 11
|
||||
|
||||
do_test 12.1 {
|
||||
set R [sqlite3_recover_init db "" test.db2]
|
||||
$R config lostandfound ""
|
||||
$R config invalid xyz
|
||||
} {12}
|
||||
do_test 12.2 {
|
||||
$R run
|
||||
$R run
|
||||
} {0}
|
||||
|
||||
do_test 12.3 {
|
||||
$R finish
|
||||
} {}
|
||||
|
||||
|
||||
|
||||
#-------------------------------------------------------------------------
|
||||
reset_db
|
||||
file_control_reservebytes db 16
|
||||
do_execsql_test 12.1 {
|
||||
PRAGMA auto_vacuum = 2;
|
||||
PRAGMA user_version = 45;
|
||||
PRAGMA application_id = 22;
|
||||
|
||||
CREATE TABLE u1(u, v);
|
||||
CREATE UNIQUE INDEX i1 ON u1(u, v);
|
||||
INSERT INTO u1 VALUES(1, 2), (3, 4);
|
||||
|
||||
CREATE TABLE u2(u, v);
|
||||
CREATE UNIQUE INDEX i2 ON u1(u, v);
|
||||
INSERT INTO u2 VALUES(hex(randomblob(500)), hex(randomblob(1000)));
|
||||
INSERT INTO u2 VALUES(hex(randomblob(500)), hex(randomblob(1000)));
|
||||
INSERT INTO u2 VALUES(hex(randomblob(500)), hex(randomblob(1000)));
|
||||
INSERT INTO u2 VALUES(hex(randomblob(50000)), hex(randomblob(20000)));
|
||||
}
|
||||
|
||||
do_recover_test 12
|
||||
|
||||
#-------------------------------------------------------------------------
|
||||
reset_db
|
||||
sqlite3 db ""
|
||||
do_recover_test 13
|
||||
|
||||
do_execsql_test 14.1 {
|
||||
PRAGMA auto_vacuum = 2;
|
||||
PRAGMA user_version = 45;
|
||||
PRAGMA application_id = 22;
|
||||
|
||||
CREATE TABLE u1(u, v);
|
||||
CREATE UNIQUE INDEX i1 ON u1(u, v);
|
||||
INSERT INTO u1 VALUES(1, 2), (3, 4);
|
||||
|
||||
CREATE TABLE u2(u, v);
|
||||
CREATE UNIQUE INDEX i2 ON u1(u, v);
|
||||
INSERT INTO u2 VALUES(hex(randomblob(500)), hex(randomblob(1000)));
|
||||
INSERT INTO u2 VALUES(hex(randomblob(500)), hex(randomblob(1000)));
|
||||
INSERT INTO u2 VALUES(hex(randomblob(500)), hex(randomblob(1000)));
|
||||
INSERT INTO u2 VALUES(hex(randomblob(50000)), hex(randomblob(20000)));
|
||||
}
|
||||
do_recover_test 14
|
||||
|
||||
#-------------------------------------------------------------------------
|
||||
reset_db
|
||||
execsql {
|
||||
PRAGMA journal_mode=OFF;
|
||||
PRAGMA mmap_size=10;
|
||||
}
|
||||
do_execsql_test 15.1 {
|
||||
CREATE TABLE t1(x);
|
||||
} {}
|
||||
do_recover_test 15
|
||||
|
||||
finish_test
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
|
||||
|
||||
if {![info exists testdir]} {
|
||||
set testdir [file join [file dirname [info script]] .. .. test]
|
||||
}
|
||||
source $testdir/tester.tcl
|
||||
|
||||
if {[info commands sqlite3_recover_init]==""} {
|
||||
finish_test
|
||||
return -code return
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
# 2019 April 23
|
||||
#
|
||||
# The author disclaims copyright to this source code. In place of
|
||||
# a legal notice, here is a blessing:
|
||||
#
|
||||
# May you do good and not evil.
|
||||
# May you find forgiveness for yourself and forgive others.
|
||||
# May you share freely, never taking more than you give.
|
||||
#
|
||||
#***********************************************************************
|
||||
#
|
||||
# Tests for the SQLITE_RECOVER_ROWIDS option.
|
||||
#
|
||||
|
||||
source [file join [file dirname [info script]] recover_common.tcl]
|
||||
set testprefix recoverclobber
|
||||
|
||||
proc recover {db output} {
|
||||
set R [sqlite3_recover_init db main test.db2]
|
||||
$R run
|
||||
$R finish
|
||||
}
|
||||
|
||||
forcedelete test.db2
|
||||
do_execsql_test 1.0 {
|
||||
ATTACH 'test.db2' AS aux;
|
||||
CREATE TABLE aux.x1(x, one);
|
||||
INSERT INTO x1 VALUES(1, 'one'), (2, 'two'), (3, 'three');
|
||||
|
||||
CREATE TABLE t1(a, b);
|
||||
INSERT INTO t1 VALUES(1, 1), (2, 2), (3, 3), (4, 4);
|
||||
|
||||
DETACH aux;
|
||||
}
|
||||
|
||||
breakpoint
|
||||
do_test 1.1 {
|
||||
recover db test.db2
|
||||
} {}
|
||||
|
||||
do_execsql_test 1.2 {
|
||||
ATTACH 'test.db2' AS aux;
|
||||
SELECT * FROM aux.t1;
|
||||
} {1 1 2 2 3 3 4 4}
|
||||
|
||||
do_catchsql_test 1.3 {
|
||||
SELECT * FROM aux.x1;
|
||||
} {1 {no such table: aux.x1}}
|
||||
|
||||
finish_test
|
||||
@@ -0,0 +1,67 @@
|
||||
# 2022 August 28
|
||||
#
|
||||
# The author disclaims copyright to this source code. In place of
|
||||
# a legal notice, here is a blessing:
|
||||
#
|
||||
# May you do good and not evil.
|
||||
# May you find forgiveness for yourself and forgive others.
|
||||
# May you share freely, never taking more than you give.
|
||||
#
|
||||
#***********************************************************************
|
||||
#
|
||||
|
||||
source [file join [file dirname [info script]] recover_common.tcl]
|
||||
set testprefix recovercorrupt
|
||||
|
||||
database_may_be_corrupt
|
||||
|
||||
do_execsql_test 1.0 {
|
||||
PRAGMA page_size = 512;
|
||||
CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c);
|
||||
INSERT INTO t1 VALUES(1, 2, 3);
|
||||
INSERT INTO t1 VALUES(2, hex(randomblob(100)), randomblob(200));
|
||||
CREATE INDEX i1 ON t1(b, c);
|
||||
CREATE TABLE t2(a PRIMARY KEY, b, c) WITHOUT ROWID;
|
||||
INSERT INTO t2 VALUES(1, 2, 3);
|
||||
INSERT INTO t2 VALUES(2, hex(randomblob(100)), randomblob(200));
|
||||
ANALYZE;
|
||||
PRAGMA writable_schema = 1;
|
||||
DELETE FROM sqlite_schema WHERE name='t2';
|
||||
}
|
||||
|
||||
do_test 1.1 {
|
||||
expr [file size test.db]>3072
|
||||
} {1}
|
||||
|
||||
proc toggle_bit {blob bit} {
|
||||
set byte [expr {$bit / 8}]
|
||||
set bit [expr {$bit & 0x0F}]
|
||||
binary scan $blob a${byte}ca* A x B
|
||||
set x [expr {$x ^ (1 << $bit)}]
|
||||
binary format a*ca* $A $x $B
|
||||
}
|
||||
|
||||
|
||||
db_save_and_close
|
||||
for {set ii 0} {$ii < 10000} {incr ii} {
|
||||
db_restore_and_reopen
|
||||
db func toggle_bit toggle_bit
|
||||
set bitsperpage [expr 512*8]
|
||||
|
||||
set pg [expr {($ii / $bitsperpage)+1}]
|
||||
set byte [expr {$ii % $bitsperpage}]
|
||||
db eval {
|
||||
UPDATE sqlite_dbpage SET data = toggle_bit(data, $byte) WHERE pgno=$pg
|
||||
}
|
||||
|
||||
set R [sqlite3_recover_init db main test.db2]
|
||||
$R config lostandfound lost_and_found
|
||||
$R run
|
||||
do_test 1.2.$ii {
|
||||
$R finish
|
||||
} {}
|
||||
}
|
||||
|
||||
|
||||
finish_test
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
# 2022 August 28
|
||||
#
|
||||
# The author disclaims copyright to this source code. In place of
|
||||
# a legal notice, here is a blessing:
|
||||
#
|
||||
# May you do good and not evil.
|
||||
# May you find forgiveness for yourself and forgive others.
|
||||
# May you share freely, never taking more than you give.
|
||||
#
|
||||
#***********************************************************************
|
||||
#
|
||||
|
||||
source [file join [file dirname [info script]] recover_common.tcl]
|
||||
set testprefix recovercorrupt2
|
||||
|
||||
do_execsql_test 1.0 {
|
||||
PRAGMA page_size = 512;
|
||||
CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c);
|
||||
INSERT INTO t1 VALUES(1, 2, 3);
|
||||
INSERT INTO t1 VALUES(2, hex(randomblob(100)), randomblob(200));
|
||||
CREATE INDEX i1 ON t1(b, c);
|
||||
CREATE TABLE t2(a PRIMARY KEY, b, c) WITHOUT ROWID;
|
||||
INSERT INTO t2 VALUES(1, 2, 3);
|
||||
INSERT INTO t2 VALUES(2, hex(randomblob(100)), randomblob(200));
|
||||
ANALYZE;
|
||||
PRAGMA writable_schema = 1;
|
||||
UPDATE sqlite_schema SET sql = 'CREATE INDEX i1 ON o(world)' WHERE name='i1';
|
||||
DELETE FROM sqlite_schema WHERE name='sqlite_stat4';
|
||||
}
|
||||
|
||||
do_test 1.1 {
|
||||
set R [sqlite3_recover_init db main test.db2]
|
||||
$R run
|
||||
$R finish
|
||||
} {}
|
||||
|
||||
sqlite3 db2 test.db2
|
||||
do_execsql_test -db db2 1.2 {
|
||||
SELECT sql FROM sqlite_schema
|
||||
} {
|
||||
{CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c)}
|
||||
{CREATE TABLE t2(a PRIMARY KEY, b, c) WITHOUT ROWID}
|
||||
{CREATE TABLE sqlite_stat1(tbl,idx,stat)}
|
||||
}
|
||||
db2 close
|
||||
|
||||
do_execsql_test 1.3 {
|
||||
PRAGMA writable_schema = 1;
|
||||
UPDATE sqlite_schema SET sql = 'CREATE TABLE t2 syntax error!' WHERE name='t2';
|
||||
}
|
||||
|
||||
do_test 1.4 {
|
||||
set R [sqlite3_recover_init db main test.db2]
|
||||
$R run
|
||||
$R finish
|
||||
} {}
|
||||
|
||||
sqlite3 db2 test.db2
|
||||
do_execsql_test -db db2 1.5 {
|
||||
SELECT sql FROM sqlite_schema
|
||||
} {
|
||||
{CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c)}
|
||||
{CREATE TABLE sqlite_stat1(tbl,idx,stat)}
|
||||
}
|
||||
db2 close
|
||||
|
||||
#-------------------------------------------------------------------------
|
||||
#
|
||||
reset_db
|
||||
do_test 2.0 {
|
||||
sqlite3 db {}
|
||||
db deserialize [decode_hexdb {
|
||||
| size 8192 pagesize 4096 filename x3.db
|
||||
| page 1 offset 0
|
||||
| 0: 53 51 4c 69 74 65 20 66 6f 72 6d 61 74 20 33 00 SQLite format 3.
|
||||
| 16: 10 00 01 01 00 40 20 20 00 00 00 02 00 00 00 02 .....@ ........
|
||||
| 32: 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 04 ................
|
||||
| 48: 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 ................
|
||||
| 80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 ................
|
||||
| 96: 00 2e 63 00 0d 00 00 00 01 0f d8 00 0f d8 00 00 ..c.............
|
||||
| 4048: 00 00 00 00 00 00 00 00 26 01 06 17 11 11 01 39 ........&......9
|
||||
| 4064: 74 61 62 6c 65 74 31 74 31 02 43 52 45 41 54 45 tablet1t1.CREATE
|
||||
| 4080: 20 54 41 42 4c 45 20 74 31 28 61 2c 62 2c 63 29 TABLE t1(a,b,c)
|
||||
| page 2 offset 4096
|
||||
| 0: 0d 00 00 00 01 0f ce 00 0f ce 00 00 00 00 00 00 ................
|
||||
| 4032: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ff ff ..............(.
|
||||
| 4048: ff ff ff ff ff ff ff 28 04 27 25 23 61 61 61 61 .........'%#aaaa
|
||||
| 4064: 61 61 61 61 61 61 61 61 61 62 62 62 62 62 62 62 aaaaaaaaabbbbbbb
|
||||
| 4080: 62 62 62 62 62 63 63 63 63 63 63 63 63 63 63 63 bbbbbccccccccccc
|
||||
| end x3.db
|
||||
}]} {}
|
||||
|
||||
do_test 2.1 {
|
||||
set R [sqlite3_recover_init db main test.db2]
|
||||
$R run
|
||||
$R finish
|
||||
} {}
|
||||
|
||||
sqlite3 db2 test.db2
|
||||
do_execsql_test -db db2 2.2 {
|
||||
SELECT sql FROM sqlite_schema
|
||||
} {
|
||||
{CREATE TABLE t1(a,b,c)}
|
||||
}
|
||||
do_execsql_test -db db2 2.3 {
|
||||
SELECT * FROM t1
|
||||
} {}
|
||||
db2 close
|
||||
|
||||
#-------------------------------------------------------------------------
|
||||
#
|
||||
reset_db
|
||||
do_test 3.0 {
|
||||
sqlite3 db {}
|
||||
db deserialize [decode_hexdb {
|
||||
.open --hexdb
|
||||
| size 4096 pagesize 1024 filename corrupt032.txt.db
|
||||
| page 1 offset 0
|
||||
| 0: 53 51 4c 69 74 65 20 66 6f 72 6d 61 74 20 33 00 SQLite format 3.
|
||||
| 16: 04 00 01 01 08 40 20 20 00 00 00 02 00 00 00 03 .....@ ........
|
||||
| 32: 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 04 ................
|
||||
| 48: 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 ................
|
||||
| 80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 ................
|
||||
| 96: 00 2e 24 80 0d 00 00 00 01 03 d4 00 03 d4 00 00 ..$.............
|
||||
| 976: 00 00 00 00 22 01 06 17 11 11 01 31 74 61 62 6c ...........1tabl
|
||||
| 992: 65 74 31 74 31 02 43 52 45 41 54 45 20 54 41 42 et1t1.CREATE TAB
|
||||
| 1008: 4c 45 20 74 31 28 78 29 00 00 00 00 00 00 00 00 LE t1(x)........
|
||||
| page 2 offset 1024
|
||||
| 0: 0d 00 00 00 01 02 06 00 02 06 00 00 00 00 00 00 ................
|
||||
| 512: 00 00 00 00 00 00 8b 60 01 03 97 46 00 00 00 00 .......`...F....
|
||||
| 1008: 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 00 ................
|
||||
| end corrupt032.txt.db
|
||||
}]} {}
|
||||
|
||||
do_test 3.1 {
|
||||
set R [sqlite3_recover_init db main test.db2]
|
||||
$R run
|
||||
$R finish
|
||||
} {}
|
||||
|
||||
#-------------------------------------------------------------------------
|
||||
#
|
||||
reset_db
|
||||
do_test 4.0 {
|
||||
sqlite3 db {}
|
||||
db deserialize [decode_hexdb {
|
||||
.open --hexdb
|
||||
| size 4096 pagesize 4096 filename crash-00f2d3627f1b43.db
|
||||
| page 1 offset 0
|
||||
| 0: 53 51 4c 69 74 65 20 66 6f 72 6d 61 74 20 33 00 SQLite format 3.
|
||||
| 16: 00 01 01 02 00 40 20 20 01 00 ff 00 42 01 10 01 .....@ ....B...
|
||||
| 32: ef 00 00 87 00 ff ff ff f0 01 01 10 ff ff 00 00 ................
|
||||
| end crash-00f2d3627f1b43.db
|
||||
}]} {}
|
||||
|
||||
do_test 4.1 {
|
||||
set R [sqlite3_recover_init db main test.db2]
|
||||
catch { $R run }
|
||||
list [catch { $R finish } msg] $msg
|
||||
} {1 {unable to open database file}}
|
||||
|
||||
#-------------------------------------------------------------------------
|
||||
#
|
||||
reset_db
|
||||
do_test 5.0 {
|
||||
sqlite3 db {}
|
||||
db deserialize [decode_hexdb {
|
||||
.open --hexdb
|
||||
| size 16384 pagesize 4096 filename crash-7b75760a4c5f15.db
|
||||
| page 1 offset 0
|
||||
| 0: 53 51 4c 69 74 65 20 66 6f 72 6d 61 74 20 33 00 SQLite format 3.
|
||||
| 16: 10 00 01 01 00 40 20 20 00 00 00 00 00 00 00 04 .....@ ........
|
||||
| 32: 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 00 ................
|
||||
| 96: 00 00 00 00 0d 00 00 00 03 0f 4e 00 0f bc 0f 90 ..........N.....
|
||||
| 112: 0f 4e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 .N..............
|
||||
| 3904: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 40 03 ..............@.
|
||||
| 3920: 06 17 11 11 01 6d 74 61 62 6c 65 74 32 74 32 04 .....mtablet2t2.
|
||||
| 3936: 43 52 45 41 54 45 20 54 41 42 4c 45 20 74 32 28 CREATE TABLE t2(
|
||||
| 3952: 78 2c 79 2c 7a 20 50 52 49 4d 41 52 59 20 4b 45 x,y,z PRIMARY KE
|
||||
| 3968: 59 29 20 57 49 54 48 4f 55 54 20 52 4f 57 49 44 Y) WITHOUT ROWID
|
||||
| 3984: 2a 02 06 17 13 11 01 3f 69 6e 64 65 78 74 31 61 *......?indext1a
|
||||
| 4000: 74 31 03 43 52 45 41 54 45 20 49 4e 44 45 58 20 t1.CREATE INDEX
|
||||
| 4016: 74 31 61 20 4f 4e 20 74 31 28 61 29 42 01 06 17 t1a ON t1(a)B...
|
||||
| 4032: 11 11 01 71 74 61 62 6c 65 74 31 74 31 02 43 52 ...qtablet1t1.CR
|
||||
| 4048: 45 41 54 45 20 54 41 42 4c 45 20 74 31 28 61 20 EATE TABLE t1(a
|
||||
| 4064: 49 4e 54 2c 62 20 54 45 58 54 2c 63 20 42 4c 4f INT,b TEXT,c BLO
|
||||
| 4080: 42 2c 64 20 52 45 41 4c 29 20 53 54 52 49 43 54 B,d REAL) STRICT
|
||||
| page 2 offset 4096
|
||||
| 0: 0d 00 00 00 14 0c ae 00 0f df 0f bd 0f 9a 0f 76 ...............v
|
||||
| 16: 0f 51 0f 2b 0f 04 0e dc 0e b3 0e 89 0e 5e 0e 32 .Q.+.........^.2
|
||||
| 32: 0e 05 0d 1a 0d a8 0d 78 0d 47 0d 15 0c e2 00 00 .......x.G......
|
||||
| 3232: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 32 14 ..............2.
|
||||
| 3248: 05 06 3f 34 07 15 f4 c9 23 af e2 b3 b6 61 62 63 ..?4....#....abc
|
||||
| 3264: 30 32 30 78 79 7a 01 00 00 00 00 00 00 00 00 00 020xyz..........
|
||||
| 3280: 00 00 00 00 00 00 00 00 00 00 c3 b0 96 7e fb 4e .............~.N
|
||||
| 3296: c5 4c 31 13 05 06 1f 32 07 dd f2 2a a5 7e b2 4d .L1....2...*.~.M
|
||||
| 3312: 82 61 62 63 30 31 39 78 79 7a 01 00 00 00 00 00 .abc019xyz......
|
||||
| 3328: 00 00 00 00 00 00 00 00 00 00 00 00 00 c3 a3 d6 ................
|
||||
| 3344: e9 f1 c2 fd f3 30 12 05 06 1f 30 07 8f 8f f5 c4 .....0....0.....
|
||||
| 3360: 35 b6 7f 8d 61 62 63 30 31 38 00 00 00 00 00 00 5...abc018......
|
||||
| 3376: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 43 ...............C
|
||||
| 3392: b2 13 1f 9d 56 8a 47 21 b1 05 06 1f 2e 07 7f 46 ....V.G!.......F
|
||||
| 3408: 91 03 3f 97 fb f7 61 62 63 30 00 00 00 00 00 00 ..?...abc0......
|
||||
| 3440: c3 bb d8 96 86 c2 e8 2b 2e 10 05 06 1f 2c 07 6d .......+.....,.m
|
||||
| 3456: 85 7b ce d0 32 d2 54 61 62 63 30 00 00 00 00 00 ....2.Tabc0.....
|
||||
| 3488: 43 a1 eb 44 14 dc 03 7b 2d 0f 05 06 1f 2a 07 d9 C..D....-....*..
|
||||
| 3504: ab ec bf 34 51 70 f3 61 62 63 30 31 35 78 79 7a ...4Qp.abc015xyz
|
||||
| 3520: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 c3 ................
|
||||
| 3536: b6 3d f4 46 b1 6a af 2c 0e 05 06 1f 28 07 36 75 .=.F.j.,....(.6u
|
||||
| 3552: e9 a2 bd 05 04 ea 61 62 63 30 31 34 78 79 7a 00 ......abc014xyz.
|
||||
| 3568: 00 00 00 00 00 00 00 00 00 00 00 00 00 c3 ab 23 ...............#
|
||||
| 3584: a7 6a 34 ca f8 2b 0d 05 06 1f 26 07 48 45 ab e0 .j4..+....&.HE..
|
||||
| 3600: 8c 7c ff 0c 61 62 63 30 31 33 78 79 7a 00 00 00 .|..abc013xyz...
|
||||
| 3616: 00 00 00 00 0d d0 00 00 00 00 43 b8 d3 93 f4 92 ..........C.....
|
||||
| 3632: 5b 7a 2a 0c 05 06 1f 24 07 be 6d 1e db 61 5d 80 [z*....$..m..a].
|
||||
| 3648: 9f 61 62 63 30 31 32 78 79 7a 00 00 00 00 00 00 .abc012xyz......
|
||||
| 3664: 00 00 00 00 00 00 43 b5 a1 a4 af 7b c6 60 29 0b ......C......`).
|
||||
| 3680: 05 06 1f 22 07 6e a2 a3 64 68 d4 a6 bd 61 62 63 .....n..dh...abc
|
||||
| 3696: 30 31 31 78 79 7a 00 00 00 00 00 00 00 00 00 00 011xyz..........
|
||||
| 3712: 00 c3 c4 1e ff 0f fc e6 ff 28 0a 05 06 1f 20 07 .........(.... .
|
||||
| 3728: 50 f9 4a bb a5 7a 1e ca 61 62 63 30 31 30 78 79 P.J..z..abc010xy
|
||||
| 3744: 7a 00 00 00 00 00 00 00 00 00 00 c3 a7 90 ed d9 z...............
|
||||
| 3760: 5c 2c d5 27 09 05 06 1f 1e 07 90 8e 1d d9 1c 3a .,.'...........:
|
||||
| 3776: e8 c1 61 62 63 30 30 39 78 79 7a 00 00 00 00 00 ..abc009xyz.....
|
||||
| 3792: 00 00 00 00 43 a7 97 87 cf b0 ff 79 26 08 05 06 ....C......y&...
|
||||
| 3808: 1f 1c 07 86 65 f6 7c 50 7a 2c 76 61 62 63 30 30 ....e.|Pz,vabc00
|
||||
| 3824: 38 78 79 7a 00 00 00 00 00 00 00 00 c3 b0 e3 4c 8xyz...........L
|
||||
| 3840: 4f d3 41 b5 25 07 05 06 1f 1a 07 8b 20 e5 68 11 O.A.%....... .h.
|
||||
| 3856: 13 55 87 61 62 63 30 30 37 78 79 7a 00 00 00 00 .U.abc007xyz....
|
||||
| 3872: 00 00 00 c3 b6 a3 74 f1 9c 33 f8 24 06 05 06 1f ......t..3.$....
|
||||
| 3888: 18 07 97 3c bc 34 49 94 54 ab 61 62 63 30 30 36 ...<.4I.T.abc006
|
||||
| 3904: 78 79 7a 00 00 00 00 00 00 c3 88 00 c2 ca 4c 4d xyz...........LM
|
||||
| 3920: d3 23 05 05 06 1f 16 07 59 37 11 10 e9 e5 3d d5 .#......Y7....=.
|
||||
| 3936: 61 62 63 30 30 35 78 79 7a 00 00 00 00 00 c3 c0 abc005xyz.......
|
||||
| 3952: 15 12 67 ed 4b 79 22 04 05 06 1f 14 07 93 39 01 ..g.Ky........9.
|
||||
| 3968: 7f b8 c7 99 58 61 62 63 30 30 34 78 79 7a 00 00 ....Xabc004xyz..
|
||||
| 3984: 09 c0 43 bf e0 e7 6d 70 fd 61 21 03 05 06 1f 12 ..C...mp.a!.....
|
||||
| 4000: 07 b6 df 8d 8b 27 08 22 5a 61 62 63 30 30 33 78 .....'..Zabc003x
|
||||
| 4016: 79 7a 00 00 00 c3 c7 ea 0f dc dd 32 22 20 02 05 yz.........2. ..
|
||||
| 4032: 06 1f 10 07 2f a6 da 71 df 66 b3 b5 61 62 63 30 ..../..q.f..abc0
|
||||
| 4048: 30 32 78 79 7a 00 00 c3 ce d9 8d e9 ec 20 45 1f 02xyz........ E.
|
||||
| 4064: 01 05 06 1f 0e 07 5a 47 53 20 3b 48 8f c0 61 62 ......ZGS ;H..ab
|
||||
| 4080: 63 30 30 31 78 79 7a 00 c3 c9 e6 81 f8 d9 24 04 c001xyz.......$.
|
||||
| page 3 offset 8192
|
||||
| 0: 0a 00 00 00 14 0e fd 00 0f f3 0f e6 0f d9 0f cc ................
|
||||
| 16: 0f bf 0f b2 0f a5 0f 98 0f 8b 0f 7e 0f 71 0f 64 ...........~.q.d
|
||||
| 32: 0f 57 0f 4a 0f 3d 0f 30 0f 24 00 00 00 00 00 00 .W.J.=.0.$......
|
||||
| 3824: 00 00 00 00 00 00 00 00 00 00 00 00 00 0c 03 06 ................
|
||||
| 3840: 01 7f 46 91 03 3f 97 fb f7 11 0c 03 06 01 6e a2 ..F..?........n.
|
||||
| 3856: a3 64 68 d4 a6 bd 0b 0c 03 06 01 6d 85 7b ce d0 .dh........m....
|
||||
| 3872: 32 d2 54 10 0b 03 06 09 5a 47 53 20 3b 48 8f c0 2.T.....ZGS ;H..
|
||||
| 3888: 0c 03 06 01 59 37 11 10 e9 e5 3d d5 05 0c 03 06 ....Y7....=.....
|
||||
| 3904: 01 50 f9 4a bb a5 7a 1e ca 0a 0c 03 06 01 48 45 .P.J..z.......HE
|
||||
| 3920: ab e0 8c 7c ff 0c 0d 0c 03 06 01 36 75 e9 a2 bd ...|.......6u...
|
||||
| 3936: 05 04 ea 0e 0c 03 06 01 2f a6 da 71 df 66 b3 b5 ......../..q.f..
|
||||
| 3952: 02 0c 03 06 01 15 f4 c9 23 af e2 b3 b6 14 0c 03 ........#.......
|
||||
| 3968: 06 01 dd f2 2a a5 7e b2 4d 82 13 0c 03 06 01 d9 ....*.~.M.......
|
||||
| 3984: ab ec bf 34 51 70 f3 0f 0c 03 06 01 be 6d 1e db ...4Qp.......m..
|
||||
| 4000: 61 5d 80 9f 0c 0c 03 06 01 b6 df 8d 8b 27 08 22 a]...........'..
|
||||
| 4016: 5a 03 0c 03 06 01 97 3c bc 34 49 94 54 ab 06 0c Z......<.4I.T...
|
||||
| 4032: 03 06 01 93 39 01 7f b8 c7 99 58 04 0c 03 06 01 ....9.....X.....
|
||||
| 4048: 90 8e 1d d9 1c 3a e8 c1 09 0c 03 06 01 8f 8f f5 .....:..........
|
||||
| 4064: c4 35 b6 7f 8d 12 0c 03 06 01 8b 20 e5 68 11 13 .5......... .h..
|
||||
| 4080: 55 87 07 0c 03 06 01 86 65 f6 7c 50 7a 2b 06 08 U.......e.|Pz+..
|
||||
| page 4 offset 12288
|
||||
| 0: 0a 00 00 00 14 0f 62 00 0f 7a 0f a1 0f c9 0f d9 ......b..z......
|
||||
| 16: 0f 81 0f d1 0f f1 0f f9 0f e1 0f 89 0e 6a 0f c1 .............j..
|
||||
| 32: 0f 91 0f 99 0f b9 0f 72 0f 62 0f e9 0f b1 0f a9 .......r.b......
|
||||
| 3936: 00 00 07 04 01 01 01 11 0e 9e 07 04 01 01 01 0b ................
|
||||
| 3952: 31 16 07 04 01 01 01 10 37 36 06 04 09 01 01 ab 1.......76......
|
||||
| 3968: 58 07 04 01 01 01 05 1c 28 07 04 01 01 01 0a 10 X.......(.......
|
||||
| 3984: cf 07 04 01 01 01 0d b2 e3 07 04 01 01 01 0e d3 ................
|
||||
| 4000: f2 07 04 01 01 01 02 41 ad 07 04 01 01 01 14 3e .......A.......>
|
||||
| 4016: 22 07 04 01 01 01 13 27 45 07 04 01 01 01 0f ad .......'E.......
|
||||
| 4032: dd 07 04 01 01 01 0c 2e a1 07 04 01 01 01 03 df ................
|
||||
| 4048: e1 07 04 01 01 01 06 59 a7 07 04 01 01 01 04 27 .......Y.......'
|
||||
| 4064: bd 07 04 01 01 01 09 d0 e0 07 04 01 01 01 12 39 ...............9
|
||||
| 4080: 4f 07 04 01 01 01 07 c4 11 06 04 00 00 00 00 00 O...............
|
||||
| end crash-7b75760a4c5f15.db
|
||||
}]} {}
|
||||
|
||||
do_test 5.1 {
|
||||
set R [sqlite3_recover_init db main test.db2]
|
||||
catch { $R run }
|
||||
list [catch { $R finish } msg] $msg
|
||||
} {0 {}}
|
||||
|
||||
finish_test
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
# 2022 August 28
|
||||
#
|
||||
# The author disclaims copyright to this source code. In place of
|
||||
# a legal notice, here is a blessing:
|
||||
#
|
||||
# May you do good and not evil.
|
||||
# May you find forgiveness for yourself and forgive others.
|
||||
# May you share freely, never taking more than you give.
|
||||
#
|
||||
#***********************************************************************
|
||||
#
|
||||
|
||||
source [file join [file dirname [info script]] recover_common.tcl]
|
||||
set testprefix recoverfault
|
||||
|
||||
|
||||
#--------------------------------------------------------------------------
|
||||
proc compare_result {db1 db2 sql} {
|
||||
set r1 [$db1 eval $sql]
|
||||
set r2 [$db2 eval $sql]
|
||||
if {$r1 != $r2} {
|
||||
puts "r1: $r1"
|
||||
puts "r2: $r2"
|
||||
error "mismatch for $sql"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
proc compare_dbs {db1 db2} {
|
||||
compare_result $db1 $db2 "SELECT sql FROM sqlite_master ORDER BY 1"
|
||||
foreach tbl [$db1 eval {SELECT name FROM sqlite_master WHERE type='table'}] {
|
||||
compare_result $db1 $db2 "SELECT * FROM $tbl"
|
||||
}
|
||||
}
|
||||
#--------------------------------------------------------------------------
|
||||
|
||||
do_execsql_test 1.0 {
|
||||
CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c);
|
||||
INSERT INTO t1 VALUES(1, 2, 3);
|
||||
INSERT INTO t1 VALUES(2, hex(randomblob(1000)), randomblob(2000));
|
||||
CREATE INDEX i1 ON t1(b, c);
|
||||
ANALYZE;
|
||||
}
|
||||
faultsim_save_and_close
|
||||
|
||||
do_faultsim_test 1 -faults oom* -prep {
|
||||
catch { db2 close }
|
||||
faultsim_restore_and_reopen
|
||||
} -body {
|
||||
set R [sqlite3_recover_init db main test.db2]
|
||||
$R run
|
||||
$R finish
|
||||
} -test {
|
||||
faultsim_test_result {0 {}} {1 {}}
|
||||
if {$testrc==0} {
|
||||
sqlite3 db2 test.db2
|
||||
compare_dbs db db2
|
||||
db2 close
|
||||
}
|
||||
}
|
||||
|
||||
faultsim_restore_and_reopen
|
||||
do_execsql_test 2.0 {
|
||||
CREATE TABLE t2(a INTEGER PRIMARY KEY, b, c);
|
||||
INSERT INTO t2 VALUES(1, 2, 3);
|
||||
INSERT INTO t2 VALUES(2, hex(randomblob(1000)), hex(randomblob(2000)));
|
||||
PRAGMA writable_schema = 1;
|
||||
DELETE FROM sqlite_schema WHERE name='t2';
|
||||
}
|
||||
faultsim_save_and_close
|
||||
|
||||
do_faultsim_test 2 -faults oom* -prep {
|
||||
faultsim_restore_and_reopen
|
||||
} -body {
|
||||
set R [sqlite3_recover_init db main test.db2]
|
||||
$R config lostandfound lost_and_found
|
||||
$R run
|
||||
$R finish
|
||||
} -test {
|
||||
faultsim_test_result {0 {}} {1 {}}
|
||||
}
|
||||
|
||||
finish_test
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
# 2022 August 28
|
||||
#
|
||||
# The author disclaims copyright to this source code. In place of
|
||||
# a legal notice, here is a blessing:
|
||||
#
|
||||
# May you do good and not evil.
|
||||
# May you find forgiveness for yourself and forgive others.
|
||||
# May you share freely, never taking more than you give.
|
||||
#
|
||||
#***********************************************************************
|
||||
#
|
||||
|
||||
source [file join [file dirname [info script]] recover_common.tcl]
|
||||
set testprefix recoverfault2
|
||||
|
||||
|
||||
#--------------------------------------------------------------------------
|
||||
proc compare_result {db1 db2 sql} {
|
||||
set r1 [$db1 eval $sql]
|
||||
set r2 [$db2 eval $sql]
|
||||
if {$r1 != $r2} {
|
||||
puts "r1: $r1"
|
||||
puts "r2: $r2"
|
||||
error "mismatch for $sql"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
proc compare_dbs {db1 db2} {
|
||||
compare_result $db1 $db2 "SELECT sql FROM sqlite_master ORDER BY 1"
|
||||
foreach tbl [$db1 eval {SELECT name FROM sqlite_master WHERE type='table'}] {
|
||||
compare_result $db1 $db2 "SELECT * FROM $tbl"
|
||||
}
|
||||
}
|
||||
#--------------------------------------------------------------------------
|
||||
|
||||
do_execsql_test 1.0 "
|
||||
CREATE TABLE t1(a INTEGER PRIMARY KEY, b);
|
||||
INSERT INTO t1 VALUES(2, '\012hello\015world\012today\n');
|
||||
"
|
||||
faultsim_save_and_close
|
||||
|
||||
proc my_sql_hook {sql} {
|
||||
lappend ::lSql $sql
|
||||
return 0
|
||||
}
|
||||
|
||||
do_faultsim_test 1 -faults oom* -prep {
|
||||
catch { db2 close }
|
||||
faultsim_restore_and_reopen
|
||||
set ::lSql [list]
|
||||
} -body {
|
||||
set R [sqlite3_recover_init_sql db main my_sql_hook]
|
||||
$R run
|
||||
$R finish
|
||||
} -test {
|
||||
faultsim_test_result {0 {}} {1 {}}
|
||||
if {$testrc==0} {
|
||||
sqlite3 db2 ""
|
||||
db2 eval [join $::lSql ";"]
|
||||
compare_dbs db db2
|
||||
db2 close
|
||||
}
|
||||
}
|
||||
|
||||
ifcapable utf16 {
|
||||
reset_db
|
||||
do_execsql_test 2.0 "
|
||||
PRAGMA encoding='utf-16';
|
||||
CREATE TABLE t1(a INTEGER PRIMARY KEY, b);
|
||||
INSERT INTO t1 VALUES(2, '\012hello\015world\012today\n');
|
||||
"
|
||||
faultsim_save_and_close
|
||||
|
||||
proc my_sql_hook {sql} {
|
||||
lappend ::lSql $sql
|
||||
return 0
|
||||
}
|
||||
|
||||
do_faultsim_test 2 -faults oom-t* -prep {
|
||||
catch { db2 close }
|
||||
faultsim_restore_and_reopen
|
||||
set ::lSql [list]
|
||||
} -body {
|
||||
set R [sqlite3_recover_init_sql db main my_sql_hook]
|
||||
$R run
|
||||
$R finish
|
||||
} -test {
|
||||
faultsim_test_result {0 {}} {1 {}}
|
||||
if {$testrc==0} {
|
||||
sqlite3 db2 ""
|
||||
db2 eval [join $::lSql ";"]
|
||||
compare_dbs db db2
|
||||
db2 close
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
finish_test
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
# 2019 April 23
|
||||
#
|
||||
# The author disclaims copyright to this source code. In place of
|
||||
# a legal notice, here is a blessing:
|
||||
#
|
||||
# May you do good and not evil.
|
||||
# May you find forgiveness for yourself and forgive others.
|
||||
# May you share freely, never taking more than you give.
|
||||
#
|
||||
#***********************************************************************
|
||||
#
|
||||
#
|
||||
|
||||
source [file join [file dirname [info script]] recover_common.tcl]
|
||||
set testprefix recoverold
|
||||
|
||||
proc compare_result {db1 db2 sql} {
|
||||
set r1 [$db1 eval $sql]
|
||||
set r2 [$db2 eval $sql]
|
||||
if {$r1 != $r2} {
|
||||
puts "sql: $sql"
|
||||
puts "r1: $r1"
|
||||
puts "r2: $r2"
|
||||
error "mismatch for $sql"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
proc compare_dbs {db1 db2} {
|
||||
compare_result $db1 $db2 "SELECT sql FROM sqlite_master ORDER BY 1"
|
||||
foreach tbl [$db1 eval {SELECT name FROM sqlite_master WHERE type='table'}] {
|
||||
compare_result $db1 $db2 "SELECT * FROM $tbl"
|
||||
}
|
||||
}
|
||||
|
||||
proc do_recover_test {tn {tsql {}} {res {}}} {
|
||||
forcedelete test.db2
|
||||
forcedelete rstate.db
|
||||
|
||||
set R [sqlite3_recover_init db main test.db2]
|
||||
$R config lostandfound lost_and_found
|
||||
$R run
|
||||
$R finish
|
||||
|
||||
sqlite3 db2 test.db2
|
||||
|
||||
if {$tsql==""} {
|
||||
uplevel [list do_test $tn.1 [list compare_dbs db db2] {}]
|
||||
} else {
|
||||
uplevel [list do_execsql_test -db db2 $tn.1 $tsql $res]
|
||||
}
|
||||
db2 close
|
||||
|
||||
forcedelete test.db2
|
||||
forcedelete rstate.db
|
||||
|
||||
set ::sqlhook [list]
|
||||
set R [sqlite3_recover_init_sql db main my_sql_hook]
|
||||
$R config lostandfound lost_and_found
|
||||
$R run
|
||||
$R finish
|
||||
|
||||
sqlite3 db2 test.db2
|
||||
db2 eval [join $::sqlhook ";"]
|
||||
|
||||
|
||||
db cache flush
|
||||
if {$tsql==""} {
|
||||
compare_dbs db db2
|
||||
uplevel [list do_test $tn.sql [list compare_dbs db db2] {}]
|
||||
} else {
|
||||
uplevel [list do_execsql_test -db db2 $tn.sql $tsql $res]
|
||||
}
|
||||
db2 close
|
||||
}
|
||||
|
||||
proc my_sql_hook {sql} {
|
||||
lappend ::sqlhook $sql
|
||||
return 0
|
||||
}
|
||||
|
||||
|
||||
set doc {
|
||||
hello
|
||||
world
|
||||
}
|
||||
do_execsql_test 1.1.1 {
|
||||
CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c);
|
||||
INSERT INTO t1 VALUES(1, 4, X'1234567800');
|
||||
INSERT INTO t1 VALUES(2, 'test', 8.1);
|
||||
INSERT INTO t1 VALUES(3, $doc, 8.4);
|
||||
}
|
||||
do_recover_test 1.1.2
|
||||
|
||||
do_execsql_test 1.2.1 "
|
||||
DELETE FROM t1;
|
||||
INSERT INTO t1 VALUES(13, 'hello\r\nworld', 13);
|
||||
"
|
||||
do_recover_test 1.2.2
|
||||
|
||||
do_execsql_test 1.3.1 "
|
||||
CREATE TABLE t2(i INTEGER PRIMARY KEY AUTOINCREMENT, b, c);
|
||||
INSERT INTO t2 VALUES(NULL, 1, 2);
|
||||
INSERT INTO t2 VALUES(NULL, 3, 4);
|
||||
INSERT INTO t2 VALUES(NULL, 5, 6);
|
||||
CREATE TABLE t3(i INTEGER PRIMARY KEY AUTOINCREMENT, b, c);
|
||||
INSERT INTO t3 VALUES(NULL, 1, 2);
|
||||
INSERT INTO t3 VALUES(NULL, 3, 4);
|
||||
INSERT INTO t3 VALUES(NULL, 5, 6);
|
||||
DELETE FROM t2;
|
||||
"
|
||||
do_recover_test 1.3.2
|
||||
|
||||
#-------------------------------------------------------------------------
|
||||
reset_db
|
||||
do_execsql_test 2.1.0 {
|
||||
PRAGMA auto_vacuum = 0;
|
||||
CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c)) WITHOUT ROWID;
|
||||
INSERT INTO t1 VALUES(1, 2, 3);
|
||||
INSERT INTO t1 VALUES(4, 5, 6);
|
||||
INSERT INTO t1 VALUES(7, 8, 9);
|
||||
}
|
||||
|
||||
do_recover_test 2.1.1
|
||||
|
||||
do_execsql_test 2.2.0 {
|
||||
PRAGMA writable_schema = 1;
|
||||
DELETE FROM sqlite_master WHERE name='t1';
|
||||
}
|
||||
do_recover_test 2.2.1 {
|
||||
SELECT name FROM sqlite_master
|
||||
} {lost_and_found}
|
||||
|
||||
do_execsql_test 2.3.0 {
|
||||
CREATE TABLE lost_and_found(a, b, c);
|
||||
}
|
||||
do_recover_test 2.3.1 {
|
||||
SELECT name FROM sqlite_master
|
||||
} {lost_and_found lost_and_found_0}
|
||||
|
||||
do_execsql_test 2.4.0 {
|
||||
CREATE TABLE lost_and_found_0(a, b, c);
|
||||
}
|
||||
do_recover_test 2.4.1 {
|
||||
SELECT name FROM sqlite_master;
|
||||
SELECT * FROM lost_and_found_1;
|
||||
} {lost_and_found lost_and_found_0 lost_and_found_1
|
||||
2 2 3 {} 2 3 1
|
||||
2 2 3 {} 5 6 4
|
||||
2 2 3 {} 8 9 7
|
||||
}
|
||||
|
||||
do_execsql_test 2.5 {
|
||||
CREATE TABLE x1(a, b, c);
|
||||
WITH s(i) AS (
|
||||
SELECT 1 UNION ALL SELECT i+1 FROM s WHERE i<100
|
||||
)
|
||||
INSERT INTO x1 SELECT i, i, hex(randomblob(500)) FROM s;
|
||||
DROP TABLE x1;
|
||||
}
|
||||
do_recover_test 2.5.1 {
|
||||
SELECT name FROM sqlite_master;
|
||||
SELECT * FROM lost_and_found_1;
|
||||
} {lost_and_found lost_and_found_0 lost_and_found_1
|
||||
2 2 3 {} 2 3 1
|
||||
2 2 3 {} 5 6 4
|
||||
2 2 3 {} 8 9 7
|
||||
}
|
||||
|
||||
ifcapable !secure_delete {
|
||||
do_test 2.6 {
|
||||
forcedelete test.db2
|
||||
set R [sqlite3_recover_init db main test.db2]
|
||||
$R config lostandfound lost_and_found
|
||||
$R config freelistcorrupt 1
|
||||
$R run
|
||||
$R finish
|
||||
sqlite3 db2 test.db2
|
||||
execsql { SELECT count(*) FROM lost_and_found_1; } db2
|
||||
} {103}
|
||||
db2 close
|
||||
}
|
||||
|
||||
#-------------------------------------------------------------------------
|
||||
breakpoint
|
||||
reset_db
|
||||
do_recover_test 3.0
|
||||
|
||||
finish_test
|
||||
@@ -0,0 +1,100 @@
|
||||
# 2022 October 14
|
||||
#
|
||||
# The author disclaims copyright to this source code. In place of
|
||||
# a legal notice, here is a blessing:
|
||||
#
|
||||
# May you do good and not evil.
|
||||
# May you find forgiveness for yourself and forgive others.
|
||||
# May you share freely, never taking more than you give.
|
||||
#
|
||||
#***********************************************************************
|
||||
#
|
||||
|
||||
source [file join [file dirname [info script]] recover_common.tcl]
|
||||
|
||||
db close
|
||||
sqlite3_test_control_pending_byte 0x1000000
|
||||
|
||||
set testprefix recoverpgsz
|
||||
|
||||
foreach {pgsz bOverflow} {
|
||||
512 0 1024 0 2048 0 4096 0 8192 0 16384 0 32768 0 65536 0
|
||||
512 1 1024 1 2048 1 4096 1 8192 1 16384 1 32768 1 65536 1
|
||||
} {
|
||||
reset_db
|
||||
execsql "PRAGMA page_size = $pgsz"
|
||||
execsql "PRAGMA auto_vacuum = 0"
|
||||
do_execsql_test 1.$pgsz.$bOverflow.1 {
|
||||
CREATE TABLE t1(a, b, c);
|
||||
CREATE INDEX i1 ON t1(b, a, c);
|
||||
INSERT INTO t1(a, b) VALUES(1, 2), (3, 4), (5, 6);
|
||||
DELETE FROM t1 WHERE a=3;
|
||||
}
|
||||
if {$bOverflow} {
|
||||
do_execsql_test 1.$pgsz.$bOverflow.1a {
|
||||
UPDATE t1 SET c = randomblob(100000);
|
||||
}
|
||||
}
|
||||
db close
|
||||
|
||||
|
||||
set fd [open test.db]
|
||||
fconfigure $fd -encoding binary -translation binary
|
||||
seek $fd $pgsz
|
||||
set pg1 [read $fd $pgsz]
|
||||
set pg2 [read $fd $pgsz]
|
||||
close $fd
|
||||
|
||||
set fd2 [open test.db2 w]
|
||||
fconfigure $fd2 -encoding binary -translation binary
|
||||
seek $fd2 $pgsz
|
||||
puts -nonewline $fd2 $pg1
|
||||
close $fd2
|
||||
|
||||
sqlite3 db2 test.db2
|
||||
do_test 1.$pgsz.$bOverflow.2 {
|
||||
set R [sqlite3_recover_init db2 main test.db3]
|
||||
$R run
|
||||
$R finish
|
||||
} {}
|
||||
|
||||
sqlite3 db3 test.db3
|
||||
do_test 1.$pgsz.$bOverflow.3 {
|
||||
db3 eval { SELECT * FROM sqlite_schema }
|
||||
db3 eval { PRAGMA page_size }
|
||||
} $pgsz
|
||||
|
||||
db2 close
|
||||
db3 close
|
||||
|
||||
forcedelete test.db3
|
||||
forcedelete test.db2
|
||||
|
||||
set fd2 [open test.db2 w]
|
||||
fconfigure $fd2 -encoding binary -translation binary
|
||||
seek $fd2 $pgsz
|
||||
puts -nonewline $fd2 $pg2
|
||||
close $fd2
|
||||
|
||||
sqlite3 db2 test.db2
|
||||
do_test 1.$pgsz.$bOverflow.4 {
|
||||
set R [sqlite3_recover_init db2 main test.db3]
|
||||
$R run
|
||||
$R finish
|
||||
} {}
|
||||
|
||||
sqlite3 db3 test.db3
|
||||
do_test 1.$pgsz.$bOverflow.5 {
|
||||
db3 eval { SELECT * FROM sqlite_schema }
|
||||
db3 eval { PRAGMA page_size }
|
||||
} $pgsz
|
||||
|
||||
db2 close
|
||||
db3 close
|
||||
}
|
||||
|
||||
|
||||
finish_test
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
# 2022 September 07
|
||||
#
|
||||
# The author disclaims copyright to this source code. In place of
|
||||
# a legal notice, here is a blessing:
|
||||
#
|
||||
# May you do good and not evil.
|
||||
# May you find forgiveness for yourself and forgive others.
|
||||
# May you share freely, never taking more than you give.
|
||||
#
|
||||
#***********************************************************************
|
||||
#
|
||||
# Tests for the SQLITE_RECOVER_ROWIDS option.
|
||||
#
|
||||
|
||||
source [file join [file dirname [info script]] recover_common.tcl]
|
||||
set testprefix recoverrowid
|
||||
|
||||
proc recover {db bRowids output} {
|
||||
forcedelete $output
|
||||
|
||||
set R [sqlite3_recover_init db main test.db2]
|
||||
$R config rowids $bRowids
|
||||
$R run
|
||||
$R finish
|
||||
}
|
||||
|
||||
do_execsql_test 1.0 {
|
||||
CREATE TABLE t1(a, b);
|
||||
INSERT INTO t1 VALUES(1, 1), (2, 2), (3, 3), (4, 4);
|
||||
DELETE FROM t1 WHERE a IN (1, 3);
|
||||
}
|
||||
|
||||
do_test 1.1 {
|
||||
recover db 0 test.db2
|
||||
sqlite3 db2 test.db2
|
||||
execsql { SELECT rowid, a, b FROM t1 ORDER BY rowid} db2
|
||||
} {1 2 2 2 4 4}
|
||||
|
||||
do_test 1.2 {
|
||||
db2 close
|
||||
recover db 1 test.db2
|
||||
sqlite3 db2 test.db2
|
||||
execsql { SELECT rowid, a, b FROM t1 ORDER BY rowid} db2
|
||||
} {2 2 2 4 4 4}
|
||||
db2 close
|
||||
|
||||
|
||||
|
||||
|
||||
finish_test
|
||||
@@ -0,0 +1,87 @@
|
||||
# 2022 September 25
|
||||
#
|
||||
# The author disclaims copyright to this source code. In place of
|
||||
# a legal notice, here is a blessing:
|
||||
#
|
||||
# May you do good and not evil.
|
||||
# May you find forgiveness for yourself and forgive others.
|
||||
# May you share freely, never taking more than you give.
|
||||
#
|
||||
#***********************************************************************
|
||||
#
|
||||
# Tests for the SQLITE_RECOVER_SLOWINDEXES option.
|
||||
#
|
||||
|
||||
source [file join [file dirname [info script]] recover_common.tcl]
|
||||
set testprefix recoverslowidx
|
||||
|
||||
do_execsql_test 1.0 {
|
||||
PRAGMA auto_vacuum = 0;
|
||||
CREATE TABLE t1(a, b);
|
||||
CREATE INDEX i1 ON t1(a);
|
||||
INSERT INTO t1 VALUES(1, 1), (2, 2), (3, 3), (4, 4);
|
||||
}
|
||||
|
||||
proc my_sql_hook {sql} {
|
||||
lappend ::lSql $sql
|
||||
return 0
|
||||
}
|
||||
|
||||
do_test 1.1 {
|
||||
set lSql [list]
|
||||
set R [sqlite3_recover_init_sql db main my_sql_hook]
|
||||
while {[$R step]==0} { }
|
||||
$R finish
|
||||
} {}
|
||||
|
||||
do_test 1.2 {
|
||||
set lSql
|
||||
} [list {*}{
|
||||
{BEGIN}
|
||||
{PRAGMA writable_schema = on}
|
||||
{PRAGMA encoding = 'UTF-8'}
|
||||
{PRAGMA page_size = '1024'}
|
||||
{PRAGMA auto_vacuum = '0'}
|
||||
{PRAGMA user_version = '0'}
|
||||
{PRAGMA application_id = '0'}
|
||||
{CREATE TABLE t1(a, b)}
|
||||
{INSERT OR IGNORE INTO 't1'(_rowid_, 'a', 'b') VALUES (1, 1, 1)}
|
||||
{INSERT OR IGNORE INTO 't1'(_rowid_, 'a', 'b') VALUES (2, 2, 2)}
|
||||
{INSERT OR IGNORE INTO 't1'(_rowid_, 'a', 'b') VALUES (3, 3, 3)}
|
||||
{INSERT OR IGNORE INTO 't1'(_rowid_, 'a', 'b') VALUES (4, 4, 4)}
|
||||
{CREATE INDEX i1 ON t1(a)}
|
||||
{PRAGMA writable_schema = off}
|
||||
{COMMIT}
|
||||
}]
|
||||
|
||||
do_test 1.3 {
|
||||
set lSql [list]
|
||||
set R [sqlite3_recover_init_sql db main my_sql_hook]
|
||||
$R config slowindexes 1
|
||||
while {[$R step]==0} { }
|
||||
$R finish
|
||||
} {}
|
||||
|
||||
do_test 1.4 {
|
||||
set lSql
|
||||
} [list {*}{
|
||||
{BEGIN}
|
||||
{PRAGMA writable_schema = on}
|
||||
{PRAGMA encoding = 'UTF-8'}
|
||||
{PRAGMA page_size = '1024'}
|
||||
{PRAGMA auto_vacuum = '0'}
|
||||
{PRAGMA user_version = '0'}
|
||||
{PRAGMA application_id = '0'}
|
||||
{CREATE TABLE t1(a, b)}
|
||||
{CREATE INDEX i1 ON t1(a)}
|
||||
{INSERT OR IGNORE INTO 't1'(_rowid_, 'a', 'b') VALUES (1, 1, 1)}
|
||||
{INSERT OR IGNORE INTO 't1'(_rowid_, 'a', 'b') VALUES (2, 2, 2)}
|
||||
{INSERT OR IGNORE INTO 't1'(_rowid_, 'a', 'b') VALUES (3, 3, 3)}
|
||||
{INSERT OR IGNORE INTO 't1'(_rowid_, 'a', 'b') VALUES (4, 4, 4)}
|
||||
{PRAGMA writable_schema = off}
|
||||
{COMMIT}
|
||||
}]
|
||||
|
||||
|
||||
finish_test
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
# 2022 September 13
|
||||
#
|
||||
# The author disclaims copyright to this source code. In place of
|
||||
# a legal notice, here is a blessing:
|
||||
#
|
||||
# May you do good and not evil.
|
||||
# May you find forgiveness for yourself and forgive others.
|
||||
# May you share freely, never taking more than you give.
|
||||
#
|
||||
#***********************************************************************
|
||||
#
|
||||
#
|
||||
|
||||
source [file join [file dirname [info script]] recover_common.tcl]
|
||||
set testprefix recoversql
|
||||
|
||||
do_execsql_test 1.0 {
|
||||
CREATE TABLE "x.1" (x, y);
|
||||
INSERT INTO "x.1" VALUES(1, 1), (2, 2), (3, 3);
|
||||
CREATE INDEX "i.1" ON "x.1"(y, x);
|
||||
}
|
||||
|
||||
proc sql_hook {sql} {
|
||||
incr ::iSqlHook
|
||||
if {$::iSqlHook==$::sql_hook_cnt} { return 4 }
|
||||
return 0
|
||||
}
|
||||
|
||||
do_test 1.1 {
|
||||
set ::sql_hook_cnt -1
|
||||
set ::iSqlHook 0
|
||||
set R [sqlite3_recover_init_sql db main sql_hook]
|
||||
$R run
|
||||
$R finish
|
||||
} {}
|
||||
|
||||
set nSqlCall $iSqlHook
|
||||
|
||||
for {set ii 1} {$ii<$nSqlCall} {incr ii} {
|
||||
set iSqlHook 0
|
||||
set sql_hook_cnt $ii
|
||||
do_test 1.$ii.a {
|
||||
set R [sqlite3_recover_init_sql db main sql_hook]
|
||||
$R run
|
||||
} {1}
|
||||
do_test 1.$ii.b {
|
||||
list [catch { $R finish } msg] $msg
|
||||
} {1 {callback returned an error - 4}}
|
||||
}
|
||||
|
||||
|
||||
finish_test
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,249 @@
|
||||
/*
|
||||
** 2022-08-27
|
||||
**
|
||||
** The author disclaims copyright to this source code. In place of
|
||||
** a legal notice, here is a blessing:
|
||||
**
|
||||
** May you do good and not evil.
|
||||
** May you find forgiveness for yourself and forgive others.
|
||||
** May you share freely, never taking more than you give.
|
||||
**
|
||||
*************************************************************************
|
||||
**
|
||||
** This file contains the public interface to the "recover" extension -
|
||||
** an SQLite extension designed to recover data from corrupted database
|
||||
** files.
|
||||
*/
|
||||
|
||||
/*
|
||||
** OVERVIEW:
|
||||
**
|
||||
** To use the API to recover data from a corrupted database, an
|
||||
** application:
|
||||
**
|
||||
** 1) Creates an sqlite3_recover handle by calling either
|
||||
** sqlite3_recover_init() or sqlite3_recover_init_sql().
|
||||
**
|
||||
** 2) Configures the new handle using one or more calls to
|
||||
** sqlite3_recover_config().
|
||||
**
|
||||
** 3) Executes the recovery by repeatedly calling sqlite3_recover_step() on
|
||||
** the handle until it returns something other than SQLITE_OK. If it
|
||||
** returns SQLITE_DONE, then the recovery operation completed without
|
||||
** error. If it returns some other non-SQLITE_OK value, then an error
|
||||
** has occurred.
|
||||
**
|
||||
** 4) Retrieves any error code and English language error message using the
|
||||
** sqlite3_recover_errcode() and sqlite3_recover_errmsg() APIs,
|
||||
** respectively.
|
||||
**
|
||||
** 5) Destroys the sqlite3_recover handle and frees all resources
|
||||
** using sqlite3_recover_finish().
|
||||
**
|
||||
** The application may abandon the recovery operation at any point
|
||||
** before it is finished by passing the sqlite3_recover handle to
|
||||
** sqlite3_recover_finish(). This is not an error, but the final state
|
||||
** of the output database, or the results of running the partial script
|
||||
** delivered to the SQL callback, are undefined.
|
||||
*/
|
||||
|
||||
#ifndef _SQLITE_RECOVER_H
|
||||
#define _SQLITE_RECOVER_H
|
||||
|
||||
#include "sqlite3.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/*
|
||||
** An instance of the sqlite3_recover object represents a recovery
|
||||
** operation in progress.
|
||||
**
|
||||
** Constructors:
|
||||
**
|
||||
** sqlite3_recover_init()
|
||||
** sqlite3_recover_init_sql()
|
||||
**
|
||||
** Destructor:
|
||||
**
|
||||
** sqlite3_recover_finish()
|
||||
**
|
||||
** Methods:
|
||||
**
|
||||
** sqlite3_recover_config()
|
||||
** sqlite3_recover_errcode()
|
||||
** sqlite3_recover_errmsg()
|
||||
** sqlite3_recover_run()
|
||||
** sqlite3_recover_step()
|
||||
*/
|
||||
typedef struct sqlite3_recover sqlite3_recover;
|
||||
|
||||
/*
|
||||
** These two APIs attempt to create and return a new sqlite3_recover object.
|
||||
** In both cases the first two arguments identify the (possibly
|
||||
** corrupt) database to recover data from. The first argument is an open
|
||||
** database handle and the second the name of a database attached to that
|
||||
** handle (i.e. "main", "temp" or the name of an attached database).
|
||||
**
|
||||
** If sqlite3_recover_init() is used to create the new sqlite3_recover
|
||||
** handle, then data is recovered into a new database, identified by
|
||||
** string parameter zUri. zUri may be an absolute or relative file path,
|
||||
** or may be an SQLite URI. If the identified database file already exists,
|
||||
** it is overwritten.
|
||||
**
|
||||
** If sqlite3_recover_init_sql() is invoked, then any recovered data will
|
||||
** be returned to the user as a series of SQL statements. Executing these
|
||||
** SQL statements results in the same database as would have been created
|
||||
** had sqlite3_recover_init() been used. For each SQL statement in the
|
||||
** output, the callback function passed as the third argument (xSql) is
|
||||
** invoked once. The first parameter is a passed a copy of the fourth argument
|
||||
** to this function (pCtx) as its first parameter, and a pointer to a
|
||||
** nul-terminated buffer containing the SQL statement formated as UTF-8 as
|
||||
** the second. If the xSql callback returns any value other than SQLITE_OK,
|
||||
** then processing is immediately abandoned and the value returned used as
|
||||
** the recover handle error code (see below).
|
||||
**
|
||||
** If an out-of-memory error occurs, NULL may be returned instead of
|
||||
** a valid handle. In all other cases, it is the responsibility of the
|
||||
** application to avoid resource leaks by ensuring that
|
||||
** sqlite3_recover_finish() is called on all allocated handles.
|
||||
*/
|
||||
sqlite3_recover *sqlite3_recover_init(
|
||||
sqlite3* db,
|
||||
const char *zDb,
|
||||
const char *zUri
|
||||
);
|
||||
sqlite3_recover *sqlite3_recover_init_sql(
|
||||
sqlite3* db,
|
||||
const char *zDb,
|
||||
int (*xSql)(void*, const char*),
|
||||
void *pCtx
|
||||
);
|
||||
|
||||
/*
|
||||
** Configure an sqlite3_recover object that has just been created using
|
||||
** sqlite3_recover_init() or sqlite3_recover_init_sql(). This function
|
||||
** may only be called before the first call to sqlite3_recover_step()
|
||||
** or sqlite3_recover_run() on the object.
|
||||
**
|
||||
** The second argument passed to this function must be one of the
|
||||
** SQLITE_RECOVER_* symbols defined below. Valid values for the third argument
|
||||
** depend on the specific SQLITE_RECOVER_* symbol in use.
|
||||
**
|
||||
** SQLITE_OK is returned if the configuration operation was successful,
|
||||
** or an SQLite error code otherwise.
|
||||
*/
|
||||
int sqlite3_recover_config(sqlite3_recover*, int op, void *pArg);
|
||||
|
||||
/*
|
||||
** SQLITE_RECOVER_LOST_AND_FOUND:
|
||||
** The pArg argument points to a string buffer containing the name
|
||||
** of a "lost-and-found" table in the output database, or NULL. If
|
||||
** the argument is non-NULL and the database contains seemingly
|
||||
** valid pages that cannot be associated with any table in the
|
||||
** recovered part of the schema, data is extracted from these
|
||||
** pages to add to the lost-and-found table.
|
||||
**
|
||||
** SQLITE_RECOVER_FREELIST_CORRUPT:
|
||||
** The pArg value must actually be a pointer to a value of type
|
||||
** int containing value 0 or 1 cast as a (void*). If this option is set
|
||||
** (argument is 1) and a lost-and-found table has been configured using
|
||||
** SQLITE_RECOVER_LOST_AND_FOUND, then is assumed that the freelist is
|
||||
** corrupt and an attempt is made to recover records from pages that
|
||||
** appear to be linked into the freelist. Otherwise, pages on the freelist
|
||||
** are ignored. Setting this option can recover more data from the
|
||||
** database, but often ends up "recovering" deleted records. The default
|
||||
** value is 0 (clear).
|
||||
**
|
||||
** SQLITE_RECOVER_ROWIDS:
|
||||
** The pArg value must actually be a pointer to a value of type
|
||||
** int containing value 0 or 1 cast as a (void*). If this option is set
|
||||
** (argument is 1), then an attempt is made to recover rowid values
|
||||
** that are not also INTEGER PRIMARY KEY values. If this option is
|
||||
** clear, then new rowids are assigned to all recovered rows. The
|
||||
** default value is 1 (set).
|
||||
**
|
||||
** SQLITE_RECOVER_SLOWINDEXES:
|
||||
** The pArg value must actually be a pointer to a value of type
|
||||
** int containing value 0 or 1 cast as a (void*). If this option is clear
|
||||
** (argument is 0), then when creating an output database, the recover
|
||||
** module creates and populates non-UNIQUE indexes right at the end of the
|
||||
** recovery operation - after all recoverable data has been inserted
|
||||
** into the new database. This is faster overall, but means that the
|
||||
** final call to sqlite3_recover_step() for a recovery operation may
|
||||
** be need to create a large number of indexes, which may be very slow.
|
||||
**
|
||||
** Or, if this option is set (argument is 1), then non-UNIQUE indexes
|
||||
** are created in the output database before it is populated with
|
||||
** recovered data. This is slower overall, but avoids the slow call
|
||||
** to sqlite3_recover_step() at the end of the recovery operation.
|
||||
**
|
||||
** The default option value is 0.
|
||||
*/
|
||||
#define SQLITE_RECOVER_LOST_AND_FOUND 1
|
||||
#define SQLITE_RECOVER_FREELIST_CORRUPT 2
|
||||
#define SQLITE_RECOVER_ROWIDS 3
|
||||
#define SQLITE_RECOVER_SLOWINDEXES 4
|
||||
|
||||
/*
|
||||
** Perform a unit of work towards the recovery operation. This function
|
||||
** must normally be called multiple times to complete database recovery.
|
||||
**
|
||||
** If no error occurs but the recovery operation is not completed, this
|
||||
** function returns SQLITE_OK. If recovery has been completed successfully
|
||||
** then SQLITE_DONE is returned. If an error has occurred, then an SQLite
|
||||
** error code (e.g. SQLITE_IOERR or SQLITE_NOMEM) is returned. It is not
|
||||
** considered an error if some or all of the data cannot be recovered
|
||||
** due to database corruption.
|
||||
**
|
||||
** Once sqlite3_recover_step() has returned a value other than SQLITE_OK,
|
||||
** all further such calls on the same recover handle are no-ops that return
|
||||
** the same non-SQLITE_OK value.
|
||||
*/
|
||||
int sqlite3_recover_step(sqlite3_recover*);
|
||||
|
||||
/*
|
||||
** Run the recovery operation to completion. Return SQLITE_OK if successful,
|
||||
** or an SQLite error code otherwise. Calling this function is the same
|
||||
** as executing:
|
||||
**
|
||||
** while( SQLITE_OK==sqlite3_recover_step(p) );
|
||||
** return sqlite3_recover_errcode(p);
|
||||
*/
|
||||
int sqlite3_recover_run(sqlite3_recover*);
|
||||
|
||||
/*
|
||||
** If an error has been encountered during a prior call to
|
||||
** sqlite3_recover_step(), then this function attempts to return a
|
||||
** pointer to a buffer containing an English language explanation of
|
||||
** the error. If no error message is available, or if an out-of memory
|
||||
** error occurs while attempting to allocate a buffer in which to format
|
||||
** the error message, NULL is returned.
|
||||
**
|
||||
** The returned buffer remains valid until the sqlite3_recover handle is
|
||||
** destroyed using sqlite3_recover_finish().
|
||||
*/
|
||||
const char *sqlite3_recover_errmsg(sqlite3_recover*);
|
||||
|
||||
/*
|
||||
** If this function is called on an sqlite3_recover handle after
|
||||
** an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK.
|
||||
*/
|
||||
int sqlite3_recover_errcode(sqlite3_recover*);
|
||||
|
||||
/*
|
||||
** Clean up a recovery object created by a call to sqlite3_recover_init().
|
||||
** The results of using a recovery object with any API after it has been
|
||||
** passed to this function are undefined.
|
||||
**
|
||||
** This function returns the same value as sqlite3_recover_errcode().
|
||||
*/
|
||||
int sqlite3_recover_finish(sqlite3_recover*);
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* end of the 'extern "C"' block */
|
||||
#endif
|
||||
|
||||
#endif /* ifndef _SQLITE_RECOVER_H */
|
||||
@@ -0,0 +1,311 @@
|
||||
/*
|
||||
** 2022-08-27
|
||||
**
|
||||
** The author disclaims copyright to this source code. In place of
|
||||
** a legal notice, here is a blessing:
|
||||
**
|
||||
** May you do good and not evil.
|
||||
** May you find forgiveness for yourself and forgive others.
|
||||
** May you share freely, never taking more than you give.
|
||||
**
|
||||
*************************************************************************
|
||||
**
|
||||
*/
|
||||
|
||||
#include "sqlite3recover.h"
|
||||
#include "sqliteInt.h"
|
||||
|
||||
#include <tcl.h>
|
||||
#include <assert.h>
|
||||
|
||||
#ifndef SQLITE_OMIT_VIRTUALTABLE
|
||||
|
||||
typedef struct TestRecover TestRecover;
|
||||
struct TestRecover {
|
||||
sqlite3_recover *p;
|
||||
Tcl_Interp *interp;
|
||||
Tcl_Obj *pScript;
|
||||
};
|
||||
|
||||
static int xSqlCallback(void *pSqlArg, const char *zSql){
|
||||
TestRecover *p = (TestRecover*)pSqlArg;
|
||||
Tcl_Obj *pEval = 0;
|
||||
int res = 0;
|
||||
|
||||
pEval = Tcl_DuplicateObj(p->pScript);
|
||||
Tcl_IncrRefCount(pEval);
|
||||
|
||||
res = Tcl_ListObjAppendElement(p->interp, pEval, Tcl_NewStringObj(zSql, -1));
|
||||
if( res==TCL_OK ){
|
||||
res = Tcl_EvalObjEx(p->interp, pEval, 0);
|
||||
}
|
||||
|
||||
Tcl_DecrRefCount(pEval);
|
||||
if( res ){
|
||||
Tcl_BackgroundError(p->interp);
|
||||
return TCL_ERROR;
|
||||
}else{
|
||||
Tcl_Obj *pObj = Tcl_GetObjResult(p->interp);
|
||||
if( Tcl_GetCharLength(pObj)==0 ){
|
||||
res = 0;
|
||||
}else if( Tcl_GetIntFromObj(p->interp, pObj, &res) ){
|
||||
Tcl_BackgroundError(p->interp);
|
||||
return TCL_ERROR;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
static int getDbPointer(Tcl_Interp *interp, Tcl_Obj *pObj, sqlite3 **pDb){
|
||||
Tcl_CmdInfo info;
|
||||
if( 0==Tcl_GetCommandInfo(interp, Tcl_GetString(pObj), &info) ){
|
||||
Tcl_AppendResult(interp, "no such handle: ", Tcl_GetString(pObj), 0);
|
||||
return TCL_ERROR;
|
||||
}
|
||||
*pDb = *(sqlite3 **)info.objClientData;
|
||||
return TCL_OK;
|
||||
}
|
||||
|
||||
/*
|
||||
** Implementation of the command created by [sqlite3_recover_init]:
|
||||
**
|
||||
** $cmd config OP ARG
|
||||
** $cmd run
|
||||
** $cmd errmsg
|
||||
** $cmd errcode
|
||||
** $cmd finalize
|
||||
*/
|
||||
static int testRecoverCmd(
|
||||
void *clientData,
|
||||
Tcl_Interp *interp,
|
||||
int objc,
|
||||
Tcl_Obj *CONST objv[]
|
||||
){
|
||||
static struct RecoverSub {
|
||||
const char *zSub;
|
||||
int nArg;
|
||||
const char *zMsg;
|
||||
} aSub[] = {
|
||||
{ "config", 2, "ARG" }, /* 0 */
|
||||
{ "run", 0, "" }, /* 1 */
|
||||
{ "errmsg", 0, "" }, /* 2 */
|
||||
{ "errcode", 0, "" }, /* 3 */
|
||||
{ "finish", 0, "" }, /* 4 */
|
||||
{ "step", 0, "" }, /* 5 */
|
||||
{ 0 }
|
||||
};
|
||||
int rc = TCL_OK;
|
||||
int iSub = 0;
|
||||
TestRecover *pTest = (TestRecover*)clientData;
|
||||
|
||||
if( objc<2 ){
|
||||
Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
|
||||
return TCL_ERROR;
|
||||
}
|
||||
rc = Tcl_GetIndexFromObjStruct(interp,
|
||||
objv[1], aSub, sizeof(aSub[0]), "sub-command", 0, &iSub
|
||||
);
|
||||
if( rc!=TCL_OK ) return rc;
|
||||
if( (objc-2)!=aSub[iSub].nArg ){
|
||||
Tcl_WrongNumArgs(interp, 2, objv, aSub[iSub].zMsg);
|
||||
return TCL_ERROR;
|
||||
}
|
||||
|
||||
switch( iSub ){
|
||||
case 0: assert( sqlite3_stricmp("config", aSub[iSub].zSub)==0 ); {
|
||||
const char *aOp[] = {
|
||||
"testdb", /* 0 */
|
||||
"lostandfound", /* 1 */
|
||||
"freelistcorrupt", /* 2 */
|
||||
"rowids", /* 3 */
|
||||
"slowindexes", /* 4 */
|
||||
"invalid", /* 5 */
|
||||
0
|
||||
};
|
||||
int iOp = 0;
|
||||
int res = 0;
|
||||
if( Tcl_GetIndexFromObj(interp, objv[2], aOp, "option", 0, &iOp) ){
|
||||
return TCL_ERROR;
|
||||
}
|
||||
switch( iOp ){
|
||||
case 0:
|
||||
res = sqlite3_recover_config(pTest->p,
|
||||
789, (void*)Tcl_GetString(objv[3]) /* MAGIC NUMBER! */
|
||||
);
|
||||
break;
|
||||
case 1: {
|
||||
const char *zStr = Tcl_GetString(objv[3]);
|
||||
res = sqlite3_recover_config(pTest->p,
|
||||
SQLITE_RECOVER_LOST_AND_FOUND, (void*)(zStr[0] ? zStr : 0)
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 2: {
|
||||
int iVal = 0;
|
||||
if( Tcl_GetBooleanFromObj(interp, objv[3], &iVal) ) return TCL_ERROR;
|
||||
res = sqlite3_recover_config(pTest->p,
|
||||
SQLITE_RECOVER_FREELIST_CORRUPT, (void*)&iVal
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 3: {
|
||||
int iVal = 0;
|
||||
if( Tcl_GetBooleanFromObj(interp, objv[3], &iVal) ) return TCL_ERROR;
|
||||
res = sqlite3_recover_config(pTest->p,
|
||||
SQLITE_RECOVER_ROWIDS, (void*)&iVal
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 4: {
|
||||
int iVal = 0;
|
||||
if( Tcl_GetBooleanFromObj(interp, objv[3], &iVal) ) return TCL_ERROR;
|
||||
res = sqlite3_recover_config(pTest->p,
|
||||
SQLITE_RECOVER_SLOWINDEXES, (void*)&iVal
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 5: {
|
||||
res = sqlite3_recover_config(pTest->p, 12345, 0);
|
||||
break;
|
||||
}
|
||||
}
|
||||
Tcl_SetObjResult(interp, Tcl_NewIntObj(res));
|
||||
break;
|
||||
}
|
||||
case 1: assert( sqlite3_stricmp("run", aSub[iSub].zSub)==0 ); {
|
||||
int res = sqlite3_recover_run(pTest->p);
|
||||
Tcl_SetObjResult(interp, Tcl_NewIntObj(res));
|
||||
break;
|
||||
}
|
||||
case 2: assert( sqlite3_stricmp("errmsg", aSub[iSub].zSub)==0 ); {
|
||||
const char *zErr = sqlite3_recover_errmsg(pTest->p);
|
||||
Tcl_SetObjResult(interp, Tcl_NewStringObj(zErr, -1));
|
||||
break;
|
||||
}
|
||||
case 3: assert( sqlite3_stricmp("errcode", aSub[iSub].zSub)==0 ); {
|
||||
int errCode = sqlite3_recover_errcode(pTest->p);
|
||||
Tcl_SetObjResult(interp, Tcl_NewIntObj(errCode));
|
||||
break;
|
||||
}
|
||||
case 4: assert( sqlite3_stricmp("finish", aSub[iSub].zSub)==0 ); {
|
||||
int res = sqlite3_recover_errcode(pTest->p);
|
||||
int res2;
|
||||
if( res!=SQLITE_OK ){
|
||||
const char *zErr = sqlite3_recover_errmsg(pTest->p);
|
||||
Tcl_SetObjResult(interp, Tcl_NewStringObj(zErr, -1));
|
||||
}
|
||||
res2 = sqlite3_recover_finish(pTest->p);
|
||||
assert( res2==res );
|
||||
if( res ) return TCL_ERROR;
|
||||
break;
|
||||
}
|
||||
case 5: assert( sqlite3_stricmp("step", aSub[iSub].zSub)==0 ); {
|
||||
int res = sqlite3_recover_step(pTest->p);
|
||||
Tcl_SetObjResult(interp, Tcl_NewIntObj(res));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return TCL_OK;
|
||||
}
|
||||
|
||||
/*
|
||||
** sqlite3_recover_init DB DBNAME URI
|
||||
*/
|
||||
static int test_sqlite3_recover_init(
|
||||
void *clientData,
|
||||
Tcl_Interp *interp,
|
||||
int objc,
|
||||
Tcl_Obj *CONST objv[]
|
||||
){
|
||||
static int iTestRecoverCmd = 1;
|
||||
|
||||
TestRecover *pNew = 0;
|
||||
sqlite3 *db = 0;
|
||||
const char *zDb = 0;
|
||||
const char *zUri = 0;
|
||||
char zCmd[128];
|
||||
int bSql = clientData ? 1 : 0;
|
||||
|
||||
if( objc!=4 ){
|
||||
const char *zErr = (bSql ? "DB DBNAME SCRIPT" : "DB DBNAME URI");
|
||||
Tcl_WrongNumArgs(interp, 1, objv, zErr);
|
||||
return TCL_ERROR;
|
||||
}
|
||||
if( getDbPointer(interp, objv[1], &db) ) return TCL_ERROR;
|
||||
zDb = Tcl_GetString(objv[2]);
|
||||
if( zDb[0]=='\0' ) zDb = 0;
|
||||
|
||||
pNew = ckalloc(sizeof(TestRecover));
|
||||
if( bSql==0 ){
|
||||
zUri = Tcl_GetString(objv[3]);
|
||||
pNew->p = sqlite3_recover_init(db, zDb, zUri);
|
||||
}else{
|
||||
pNew->interp = interp;
|
||||
pNew->pScript = objv[3];
|
||||
Tcl_IncrRefCount(pNew->pScript);
|
||||
pNew->p = sqlite3_recover_init_sql(db, zDb, xSqlCallback, (void*)pNew);
|
||||
}
|
||||
|
||||
sprintf(zCmd, "sqlite_recover%d", iTestRecoverCmd++);
|
||||
Tcl_CreateObjCommand(interp, zCmd, testRecoverCmd, (void*)pNew, 0);
|
||||
|
||||
Tcl_SetObjResult(interp, Tcl_NewStringObj(zCmd, -1));
|
||||
return TCL_OK;
|
||||
}
|
||||
|
||||
/*
|
||||
** Declaration for public API function in file dbdata.c. This may be called
|
||||
** with NULL as the final two arguments to register the sqlite_dbptr and
|
||||
** sqlite_dbdata virtual tables with a database handle.
|
||||
*/
|
||||
#ifdef _WIN32
|
||||
__declspec(dllexport)
|
||||
#endif
|
||||
int sqlite3_dbdata_init(sqlite3*, char**, const sqlite3_api_routines*);
|
||||
|
||||
/*
|
||||
** sqlite3_recover_init DB DBNAME URI
|
||||
*/
|
||||
static int test_sqlite3_dbdata_init(
|
||||
void *clientData,
|
||||
Tcl_Interp *interp,
|
||||
int objc,
|
||||
Tcl_Obj *CONST objv[]
|
||||
){
|
||||
sqlite3 *db = 0;
|
||||
|
||||
if( objc!=2 ){
|
||||
Tcl_WrongNumArgs(interp, 1, objv, "DB");
|
||||
return TCL_ERROR;
|
||||
}
|
||||
if( getDbPointer(interp, objv[1], &db) ) return TCL_ERROR;
|
||||
sqlite3_dbdata_init(db, 0, 0);
|
||||
|
||||
Tcl_ResetResult(interp);
|
||||
return TCL_OK;
|
||||
}
|
||||
|
||||
#endif /* SQLITE_OMIT_VIRTUALTABLE */
|
||||
|
||||
int TestRecover_Init(Tcl_Interp *interp){
|
||||
#ifndef SQLITE_OMIT_VIRTUALTABLE
|
||||
struct Cmd {
|
||||
const char *zCmd;
|
||||
Tcl_ObjCmdProc *xProc;
|
||||
void *pArg;
|
||||
} aCmd[] = {
|
||||
{ "sqlite3_recover_init", test_sqlite3_recover_init, 0 },
|
||||
{ "sqlite3_recover_init_sql", test_sqlite3_recover_init, (void*)1 },
|
||||
{ "sqlite3_dbdata_init", test_sqlite3_dbdata_init, (void*)1 },
|
||||
};
|
||||
int i;
|
||||
|
||||
for(i=0; i<sizeof(aCmd)/sizeof(struct Cmd); i++){
|
||||
struct Cmd *p = &aCmd[i];
|
||||
Tcl_CreateObjCommand(interp, p->zCmd, p->xProc, p->pArg, 0);
|
||||
}
|
||||
#endif
|
||||
return TCL_OK;
|
||||
}
|
||||
|
||||
+1
-1
@@ -1695,7 +1695,7 @@ static int geopolyUpdate(
|
||||
sqlite3_free(p);
|
||||
nChange = 1;
|
||||
}
|
||||
for(jj=1; jj<pRtree->nAux; jj++){
|
||||
for(jj=1; jj<nData-2; jj++){
|
||||
nChange++;
|
||||
sqlite3_bind_value(pUp, jj+2, aData[jj+2]);
|
||||
}
|
||||
|
||||
+1
-1
@@ -3235,7 +3235,7 @@ static int rtreeUpdate(
|
||||
rtreeReference(pRtree);
|
||||
assert(nData>=1);
|
||||
|
||||
cell.iRowid = 0; /* Used only to suppress a compiler warning */
|
||||
memset(&cell, 0, sizeof(cell));
|
||||
|
||||
/* Constraint handling. A write operation on an r-tree table may return
|
||||
** SQLITE_CONSTRAINT for two reasons:
|
||||
|
||||
@@ -733,4 +733,27 @@ do_execsql_test 19.1 {
|
||||
SELECT v0.x FROM v0, rt0 WHERE v0.x = rt0.b;
|
||||
} {0.0}
|
||||
|
||||
# 2022-06-20 https://sqlite.org/forum/forumpost/57bdf2217d
|
||||
#
|
||||
reset_db
|
||||
do_execsql_test 20.0 {
|
||||
CREATE VIRTUAL TABLE rt0 USING rtree(id, x0, x1);
|
||||
CREATE TABLE t0(a INT);
|
||||
CREATE TABLE t1(b INT);
|
||||
INSERT INTO rt0 VALUES(0, 0, 0);
|
||||
}
|
||||
do_catchsql_test 20.1 {
|
||||
SELECT * FROM t1 JOIN t0 ON x0>a RIGHT JOIN rt0 ON true WHERE +x0 = 0;
|
||||
} {1 {ON clause references tables to its right}}
|
||||
do_catchsql_test 20.2 {
|
||||
SELECT * FROM t1 JOIN t0 ON x0>a RIGHT JOIN rt0 ON true WHERE x0 = 0;
|
||||
} {1 {ON clause references tables to its right}}
|
||||
db null -
|
||||
do_execsql_test 20.3 {
|
||||
SELECT * FROM t1 JOIN t0 ON true RIGHT JOIN rt0 ON x0>a WHERE +x0 = 0;
|
||||
} {- - 0 0.0 0.0}
|
||||
do_execsql_test 20.4 {
|
||||
SELECT * FROM t1 JOIN t0 ON true RIGHT JOIN rt0 ON x0>a WHERE x0 = 0;
|
||||
} {- - 0 0.0 0.0}
|
||||
|
||||
finish_test
|
||||
|
||||
@@ -23,6 +23,10 @@ ifcapable !rtree {
|
||||
return
|
||||
}
|
||||
|
||||
set ::TMPDBERROR [list 1 \
|
||||
{unable to open a temporary database file for storing temporary tables}
|
||||
]
|
||||
|
||||
# Test summary:
|
||||
#
|
||||
# rtree3-1: Test OOM in simple CREATE TABLE, INSERT, DELETE and SELECT
|
||||
@@ -196,9 +200,9 @@ do_test rtree3-7.prep {
|
||||
do_faultsim_test rtree3-7 -faults oom-* -prep {
|
||||
faultsim_restore_and_reopen
|
||||
} -body {
|
||||
execsql { ALTER TABLE rt RENAME TO rt2 }
|
||||
execsql { ALTER TABLE rt RENAME TO rt2 }
|
||||
} -test {
|
||||
faultsim_test_result {0 {}}
|
||||
faultsim_test_result {0 {}} $::TMPDBERROR
|
||||
}
|
||||
|
||||
do_faultsim_test rtree3-8 -faults oom-* -prep {
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
_fiddle_db_arg
|
||||
_fiddle_db_filename
|
||||
_fiddle_exec
|
||||
_fiddle_experiment
|
||||
_fiddle_interrupt
|
||||
_fiddle_main
|
||||
_fiddle_reset_db
|
||||
_fiddle_db_handle
|
||||
_fiddle_db_vfs
|
||||
_fiddle_export_db
|
||||
@@ -0,0 +1,655 @@
|
||||
#######################################################################
|
||||
# This GNU makefile drives the build of the sqlite3 WASM
|
||||
# components. It is not part of the canonical build process.
|
||||
#
|
||||
# This build assumes a Linux platform and is not intended for
|
||||
# general-purpose client-level use, except for creating builds with
|
||||
# custom configurations. It is primarily intended for the sqlite
|
||||
# project's own development of the JS/WASM components.
|
||||
#
|
||||
# Primary targets:
|
||||
#
|
||||
# default, all = build in dev mode
|
||||
#
|
||||
# o0, o1, o2, o3, os, oz = full clean/rebuild with the -Ox level indicated
|
||||
# by the target name. Rebuild is necessary for all components to get
|
||||
# the desired optimization level.
|
||||
#
|
||||
# dist = create end user deliverables. Add dist.build=oX to build
|
||||
# with a specific optimization level, where oX is one of the
|
||||
# above-listed o? target names.
|
||||
#
|
||||
# clean = clean up
|
||||
########################################################################
|
||||
SHELL := $(shell which bash 2>/dev/null)
|
||||
MAKEFILE := $(lastword $(MAKEFILE_LIST))
|
||||
CLEAN_FILES :=
|
||||
DISTCLEAN_FILES := ./--dummy--
|
||||
default: all
|
||||
release: oz
|
||||
|
||||
# Emscripten SDK home dir and related binaries...
|
||||
EMSDK_HOME ?= $(word 1,$(wildcard $(HOME)/emsdk $(HOME)/src/emsdk))
|
||||
emcc.bin ?= $(word 1,$(wildcard $(EMSDK_HOME)/upstream/emscripten/emcc) $(shell which emcc))
|
||||
ifeq (,$(emcc.bin))
|
||||
$(error Cannot find emcc.)
|
||||
endif
|
||||
|
||||
wasm-strip ?= $(shell which wasm-strip 2>/dev/null)
|
||||
ifeq (,$(filter clean,$(MAKECMDGOALS)))
|
||||
ifeq (,$(wasm-strip))
|
||||
$(info WARNING: *******************************************************************)
|
||||
$(info WARNING: builds using -O2/-O3/-Os/-Oz will minify WASM-exported names,)
|
||||
$(info WARNING: breaking _All The Things_. The workaround for that is to build)
|
||||
$(info WARNING: with -g3 (which explodes the file size) and then strip the debug)
|
||||
$(info WARNING: info after compilation, using wasm-strip, to shrink the wasm file.)
|
||||
$(info WARNING: wasm-strip was not found in the PATH so we cannot strip those.)
|
||||
$(info WARNING: If this build uses any optimization level higher than -O1 then)
|
||||
$(info WARNING: the ***resulting JS code WILL NOT BE USABLE***.)
|
||||
$(info WARNING: wasm-strip is part of the wabt package:)
|
||||
$(info WARNING: https://github.com/WebAssembly/wabt)
|
||||
$(info WARNING: on Ubuntu-like systems it can be installed with:)
|
||||
$(info WARNING: sudo apt install wabt)
|
||||
$(info WARNING: *******************************************************************)
|
||||
endif
|
||||
endif # 'make clean' check
|
||||
|
||||
ifeq (,$(wasm-strip))
|
||||
maybe-wasm-strip = echo "not wasm-stripping"
|
||||
else
|
||||
maybe-wasm-strip = $(wasm-strip)
|
||||
endif
|
||||
|
||||
dir.top := ../..
|
||||
# Reminder: some Emscripten flags require absolute paths but we want
|
||||
# relative paths for most stuff simply to reduce noise. The
|
||||
# $(abspath...) GNU make function can transform relative paths to
|
||||
# absolute.
|
||||
dir.wasm := $(patsubst %/,%,$(dir $(MAKEFILE)))
|
||||
dir.api := api
|
||||
dir.jacc := jaccwabyt
|
||||
dir.common := common
|
||||
dir.fiddle := fiddle
|
||||
dir.tool := $(dir.top)/tool
|
||||
########################################################################
|
||||
# dir.dout = output dir for deliverables.
|
||||
#
|
||||
# MAINTENANCE REMINDER: the output .js and .wasm files of emcc must be
|
||||
# in _this_ dir, rather than a subdir, or else parts of the generated
|
||||
# code get confused and cannot load property. Specifically, when X.js
|
||||
# loads X.wasm, whether or not X.js uses the correct path for X.wasm
|
||||
# depends on how it's loaded: an HTML script tag will resolve it
|
||||
# intuitively, whereas a Worker's call to importScripts() will not.
|
||||
# That's a fundamental incompatibility with how URL resolution in
|
||||
# JS happens between those two contexts. See:
|
||||
#
|
||||
# https://zzz.buzz/2017/03/14/relative-uris-in-web-development/
|
||||
#
|
||||
# We unfortunately have no way, from Worker-initiated code, to
|
||||
# automatically resolve the path from X.js to X.wasm.
|
||||
#
|
||||
# We have an "only slightly unsightly" solution for our main builds
|
||||
# but it does not work for the WASMFS builds, so those builds have to
|
||||
# be built to _this_ directory and can only run when the client app is
|
||||
# loaded from the same directory.
|
||||
dir.dout := $(dir.wasm)/jswasm
|
||||
# dir.tmp = output dir for intermediary build files, as opposed to
|
||||
# end-user deliverables.
|
||||
dir.tmp := $(dir.wasm)/bld
|
||||
CLEAN_FILES += $(dir.tmp)/* $(dir.dout)/*
|
||||
ifeq (,$(wildcard $(dir.dout)))
|
||||
dir._tmp := $(shell mkdir -p $(dir.dout))
|
||||
endif
|
||||
ifeq (,$(wildcard $(dir.tmp)))
|
||||
dir._tmp := $(shell mkdir -p $(dir.tmp))
|
||||
endif
|
||||
|
||||
cflags.common := -I. -I.. -I$(dir.top)
|
||||
CLEAN_FILES += *~ $(dir.jacc)/*~ $(dir.api)/*~ $(dir.common)/*~
|
||||
emcc.WASM_BIGINT ?= 1
|
||||
sqlite3.c := $(dir.top)/sqlite3.c
|
||||
sqlite3.h := $(dir.top)/sqlite3.h
|
||||
SQLITE_OPT = \
|
||||
-DSQLITE_ENABLE_FTS4 \
|
||||
-DSQLITE_ENABLE_RTREE \
|
||||
-DSQLITE_ENABLE_EXPLAIN_COMMENTS \
|
||||
-DSQLITE_ENABLE_UNKNOWN_SQL_FUNCTION \
|
||||
-DSQLITE_ENABLE_STMTVTAB \
|
||||
-DSQLITE_ENABLE_DBPAGE_VTAB \
|
||||
-DSQLITE_ENABLE_DBSTAT_VTAB \
|
||||
-DSQLITE_ENABLE_BYTECODE_VTAB \
|
||||
-DSQLITE_ENABLE_OFFSET_SQL_FUNC \
|
||||
-DSQLITE_OMIT_LOAD_EXTENSION \
|
||||
-DSQLITE_OMIT_DEPRECATED \
|
||||
-DSQLITE_OMIT_UTF16 \
|
||||
-DSQLITE_OMIT_SHARED_CACHE \
|
||||
-DSQLITE_OMIT_WAL \
|
||||
-DSQLITE_THREADSAFE=0 \
|
||||
-DSQLITE_TEMP_STORE=3 \
|
||||
-DSQLITE_OS_KV_OPTIONAL=1 \
|
||||
'-DSQLITE_DEFAULT_UNIX_VFS="unix-none"' \
|
||||
-DSQLITE_USE_URI=1 \
|
||||
-DSQLITE_WASM_ENABLE_C_TESTS
|
||||
# ^^^ most flags are set in sqlite3-wasm.c but we need them
|
||||
# made explicit here for building speedtest1.c.
|
||||
|
||||
ifneq (,$(filter release,$(MAKECMDGOALS)))
|
||||
emcc_opt ?= -Oz -flto
|
||||
else
|
||||
emcc_opt ?= -O0
|
||||
# ^^^^ build times for -O levels higher than 0 are painful at
|
||||
# dev-time.
|
||||
endif
|
||||
# When passing emcc_opt from the CLI, += and re-assignment have no
|
||||
# effect, so emcc_opt+=-g3 doesn't work. So...
|
||||
emcc_opt_full := $(emcc_opt) -g3
|
||||
# ^^^ ALWAYS use -g3. See below for why.
|
||||
#
|
||||
# ^^^ -flto improves runtime speed at -O0 considerably but doubles
|
||||
# build time.
|
||||
#
|
||||
# ^^^^ -O3, -Oz, -Os minify symbol names and there appears to be no
|
||||
# way around that except to use -g3, but -g3 causes the binary file
|
||||
# size to absolutely explode (approx. 5x larger). This minification
|
||||
# utterly breaks the resulting module, making it unsable except as
|
||||
# self-contained/self-referential-only code, as ALL of the exported
|
||||
# symbols get minified names.
|
||||
#
|
||||
# However, we have an option for using -Oz or -Os:
|
||||
#
|
||||
# Build with (-Os -g3) or (-Oz -g3) then use wasm-strip, from the wabt
|
||||
# tools package (https://github.com/WebAssembly/wabt), to strip the
|
||||
# debugging symbols. That results in a small build with unmangled
|
||||
# symbol names. -Oz gives ever-so-slightly better compression than
|
||||
# -Os: not quite 1% in some completely unscientific tests. Runtime
|
||||
# speed for the unit tests is all over the place either way so it's
|
||||
# difficult to say whether -Os gives any speed benefit over -Oz.
|
||||
#
|
||||
# (Much later: -O2 consistently gives the best speeds.)
|
||||
########################################################################
|
||||
|
||||
|
||||
$(sqlite3.c) $(sqlite3.h):
|
||||
$(MAKE) -C $(dir.top) sqlite3.c
|
||||
|
||||
.PHONY: clean distclean
|
||||
clean:
|
||||
-rm -f $(CLEAN_FILES)
|
||||
distclean: clean
|
||||
-rm -f $(DISTCLEAN_FILES)
|
||||
|
||||
ifeq (release,$(filter release,$(MAKECMDGOALS)))
|
||||
ifeq (,$(wasm-strip))
|
||||
$(error Cannot make release-quality binary because wasm-strip is not available. \
|
||||
See notes in the warning above)
|
||||
endif
|
||||
else
|
||||
$(info Development build. Use '$(MAKE) release' for a smaller release build.)
|
||||
endif
|
||||
|
||||
bin.version-info := $(dir.wasm)/version-info
|
||||
# ^^^^ NOT in $(dir.tmp) because we need it to survive the cleanup
|
||||
# process for the dist build to work properly.
|
||||
$(bin.version-info): $(dir.wasm)/version-info.c $(sqlite3.h) $(MAKEFILE)
|
||||
$(CC) -O0 -I$(dir.top) -o $@ $<
|
||||
DISTCLEAN_FILES += $(bin.version-info)
|
||||
|
||||
bin.stripccomments := $(dir.tool)/stripccomments
|
||||
$(bin.stripccomments): $(bin.stripccomments).c $(MAKEFILE)
|
||||
$(CC) -o $@ $<
|
||||
DISTCLEAN_FILES += $(bin.stripccomments)
|
||||
|
||||
EXPORTED_FUNCTIONS.api.in := $(abspath $(dir.api)/EXPORTED_FUNCTIONS.sqlite3-api)
|
||||
EXPORTED_FUNCTIONS.api := $(dir.tmp)/EXPORTED_FUNCTIONS.api
|
||||
$(EXPORTED_FUNCTIONS.api): $(EXPORTED_FUNCTIONS.api.in) $(MAKEFILE)
|
||||
cat $(EXPORTED_FUNCTIONS.api.in) > $@
|
||||
|
||||
sqlite3-license-version.js := $(dir.tmp)/sqlite3-license-version.js
|
||||
sqlite3-license-version-header.js := $(dir.api)/sqlite3-license-version-header.js
|
||||
sqlite3-api-build-version.js := $(dir.tmp)/sqlite3-api-build-version.js
|
||||
# sqlite3-api.jses = the list of JS files which make up $(sqlite3-api.js), in
|
||||
# the order they need to be assembled.
|
||||
sqlite3-api.jses := $(sqlite3-license-version.js)
|
||||
sqlite3-api.jses += $(dir.api)/sqlite3-api-prologue.js
|
||||
sqlite3-api.jses += $(dir.common)/whwasmutil.js
|
||||
sqlite3-api.jses += $(dir.jacc)/jaccwabyt.js
|
||||
sqlite3-api.jses += $(dir.api)/sqlite3-api-glue.js
|
||||
sqlite3-api.jses += $(sqlite3-api-build-version.js)
|
||||
sqlite3-api.jses += $(dir.api)/sqlite3-api-oo1.js
|
||||
sqlite3-api.jses += $(dir.api)/sqlite3-api-worker1.js
|
||||
sqlite3-api.jses += $(dir.api)/sqlite3-api-opfs.js
|
||||
sqlite3-api.jses += $(dir.api)/sqlite3-api-cleanup.js
|
||||
|
||||
# "External" API files which are part of our distribution
|
||||
# but not part of the sqlite3-api.js amalgamation.
|
||||
SOAP.js := $(dir.api)/sqlite3-opfs-async-proxy.js
|
||||
sqlite3-worker1.js := $(dir.api)/sqlite3-worker1.js
|
||||
sqlite3-worker1-promiser.js := $(dir.api)/sqlite3-worker1-promiser.js
|
||||
define CP_XAPI
|
||||
sqlite3-api.ext.jses += $$(dir.dout)/$$(notdir $(1))
|
||||
$$(dir.dout)/$$(notdir $(1)): $(1) $$(MAKEFILE)
|
||||
cp $$< $$@
|
||||
endef
|
||||
$(foreach X,$(SOAP.js) $(sqlite3-worker1.js) $(sqlite3-worker1-promiser.js),\
|
||||
$(eval $(call CP_XAPI,$(X))))
|
||||
all: $(sqlite3-api.ext.jses)
|
||||
|
||||
sqlite3-api.js := $(dir.tmp)/sqlite3-api.js
|
||||
$(sqlite3-api.js): $(sqlite3-api.jses) $(MAKEFILE)
|
||||
@echo "Making $@..."
|
||||
@for i in $(sqlite3-api.jses); do \
|
||||
echo "/* BEGIN FILE: $$i */"; \
|
||||
cat $$i; \
|
||||
echo "/* END FILE: $$i */"; \
|
||||
done > $@
|
||||
|
||||
$(sqlite3-api-build-version.js): $(bin.version-info) $(MAKEFILE)
|
||||
@echo "Making $@..."
|
||||
@{ \
|
||||
echo 'self.sqlite3ApiBootstrap.initializers.push(function(sqlite3){'; \
|
||||
echo -n ' sqlite3.version = '; \
|
||||
$(bin.version-info) --json; \
|
||||
echo ';'; \
|
||||
echo '});'; \
|
||||
} > $@
|
||||
|
||||
########################################################################
|
||||
# --post-js and --pre-js are emcc flags we use to append/prepend JS to
|
||||
# the generated emscripten module file.
|
||||
pre-js.js := $(dir.api)/pre-js.js
|
||||
post-js.js := $(dir.tmp)/post-js.js
|
||||
post-jses := \
|
||||
$(dir.api)/post-js-header.js \
|
||||
$(sqlite3-api.js) \
|
||||
$(dir.api)/post-js-footer.js
|
||||
$(post-js.js): $(post-jses) $(MAKEFILE)
|
||||
@echo "Making $@..."
|
||||
@for i in $(post-jses); do \
|
||||
echo "/* BEGIN FILE: $$i */"; \
|
||||
cat $$i; \
|
||||
echo "/* END FILE: $$i */"; \
|
||||
done > $@
|
||||
extern-post-js.js := $(dir.api)/extern-post-js.js
|
||||
extern-pre-js.js := $(dir.api)/extern-pre-js.js
|
||||
pre-post-common.flags := \
|
||||
--post-js=$(post-js.js) \
|
||||
--extern-post-js=$(extern-post-js.js) \
|
||||
--extern-pre-js=$(sqlite3-license-version.js)
|
||||
pre-post-jses.deps := $(post-js.js) \
|
||||
$(extern-post-js.js) $(extern-pre-js.js) $(sqlite3-license-version.js)
|
||||
$(sqlite3-license-version.js): $(sqlite3.h) $(sqlite3-license-version-header.js) $(MAKEFILE)
|
||||
@echo "Making $@..."; { \
|
||||
cat $(sqlite3-license-version-header.js); \
|
||||
echo '/*'; \
|
||||
echo '** This code was built from sqlite3 version...'; \
|
||||
echo "** "; \
|
||||
awk -e '/define SQLITE_VERSION/{$$1=""; print "**" $$0}' \
|
||||
-e '/define SQLITE_SOURCE_ID/{$$1=""; print "**" $$0}' $(sqlite3.h); \
|
||||
echo '*/'; \
|
||||
} > $@
|
||||
|
||||
########################################################################
|
||||
# call-make-pre-js creates rules for pre-js-$(1).js. $1 = the base
|
||||
# name of the JS file on whose behalf this pre-js is for.
|
||||
define call-make-pre-js
|
||||
pre-post-$(1).flags ?=
|
||||
$$(dir.tmp)/pre-js-$(1).js: $$(pre-js.js) $$(MAKEFILE)
|
||||
cp $$(pre-js.js) $$@
|
||||
@if [ sqlite3-wasmfs = $(1) ]; then \
|
||||
echo "delete Module[xNameOfInstantiateWasm] /*for WASMFS build*/;"; \
|
||||
elif [ sqlite3 != $(1) ]; then \
|
||||
echo "Module[xNameOfInstantiateWasm].uri = '$(1).wasm';"; \
|
||||
fi >> $$@
|
||||
pre-post-$(1).deps := $$(pre-post-jses.deps) $$(dir.tmp)/pre-js-$(1).js
|
||||
pre-post-$(1).flags += --pre-js=$$(dir.tmp)/pre-js-$(1).js
|
||||
endef
|
||||
#$(error $(call call-make-pre-js,sqlite3-wasmfs))
|
||||
# /post-js and pre-js
|
||||
########################################################################
|
||||
|
||||
########################################################################
|
||||
# emcc flags for .c/.o/.wasm/.js.
|
||||
emcc.flags :=
|
||||
#emcc.flags += -v # _very_ loud but also informative about what it's doing
|
||||
# -g3 is needed to keep -O2 and higher from creating broken JS via
|
||||
# minification.
|
||||
|
||||
########################################################################
|
||||
# emcc flags for .c/.o.
|
||||
emcc.cflags :=
|
||||
emcc.cflags += -std=c99 -fPIC
|
||||
# -------------^^^^^^^^ we currently need c99 for WASM-specific sqlite3 APIs.
|
||||
emcc.cflags += -I. -I$(dir.top)
|
||||
|
||||
########################################################################
|
||||
# emcc flags specific to building the final .js/.wasm file...
|
||||
emcc.jsflags := -fPIC
|
||||
emcc.jsflags += --minify 0
|
||||
emcc.jsflags += --no-entry
|
||||
emcc.jsflags += -sMODULARIZE
|
||||
emcc.jsflags += -sSTRICT_JS
|
||||
emcc.jsflags += -sDYNAMIC_EXECUTION=0
|
||||
emcc.jsflags += -sNO_POLYFILL
|
||||
emcc.jsflags += -sEXPORTED_FUNCTIONS=@$(EXPORTED_FUNCTIONS.api)
|
||||
emcc.exportedRuntimeMethods := \
|
||||
-sEXPORTED_RUNTIME_METHODS=FS,wasmMemory
|
||||
# FS ==> stdio/POSIX I/O proxies
|
||||
# wasmMemory ==> required by our code for use with -sIMPORTED_MEMORY
|
||||
emcc.jsflags += $(emcc.exportedRuntimeMethods)
|
||||
emcc.jsflags += -sUSE_CLOSURE_COMPILER=0
|
||||
emcc.jsflags += -sIMPORTED_MEMORY
|
||||
emcc.environment := -sENVIRONMENT=web,worker
|
||||
########################################################################
|
||||
# -sINITIAL_MEMORY: How much memory we need to start with is governed
|
||||
# at least in part by whether -sALLOW_MEMORY_GROWTH is enabled. If so,
|
||||
# we can start with less. If not, we need as much as we'll ever
|
||||
# possibly use (which, of course, we can't know for sure). Note,
|
||||
# however, that speedtest1 shows that performance for even moderate
|
||||
# workloads MAY suffer considerably if we start small and have to grow
|
||||
# at runtime. e.g. OPFS-backed (speedtest1 --size 75) take MAY take X
|
||||
# time with 16mb+ memory and 3X time when starting with 8MB. However,
|
||||
# such test results are inconsistent due to browser internals which
|
||||
# are opaque to us.
|
||||
emcc.jsflags += -sALLOW_MEMORY_GROWTH
|
||||
emcc.INITIAL_MEMORY.128 := 13107200
|
||||
emcc.INITIAL_MEMORY.96 := 100663296
|
||||
emcc.INITIAL_MEMORY.64 := 64225280
|
||||
emcc.INITIAL_MEMORY.32 := 33554432
|
||||
emcc.INITIAL_MEMORY.16 := 16777216
|
||||
emcc.INITIAL_MEMORY.8 := 8388608
|
||||
emcc.INITIAL_MEMORY ?= 16
|
||||
ifeq (,$(emcc.INITIAL_MEMORY.$(emcc.INITIAL_MEMORY)))
|
||||
$(error emcc.INITIAL_MEMORY must be one of: 8, 16, 32, 64, 96, 128 (megabytes))
|
||||
endif
|
||||
emcc.jsflags += -sINITIAL_MEMORY=$(emcc.INITIAL_MEMORY.$(emcc.INITIAL_MEMORY))
|
||||
# /INITIAL_MEMORY
|
||||
########################################################################
|
||||
|
||||
emcc.jsflags += $(emcc.environment)
|
||||
#emcc.jsflags += -sTOTAL_STACK=4194304
|
||||
|
||||
sqlite3.js.init-func := sqlite3InitModule
|
||||
# ^^^^ $(sqlite3.js.init-func) symbol name is hard-coded in
|
||||
# $(extern-post-js.js) as well as in numerous docs. If changed, it
|
||||
# needs to be globally modified in *.js and all related documentation.
|
||||
|
||||
emcc.jsflags += -sEXPORT_NAME=$(sqlite3.js.init-func)
|
||||
emcc.jsflags += -sGLOBAL_BASE=4096 # HYPOTHETICALLY keep func table indexes from overlapping w/ heap addr.
|
||||
#emcc.jsflags += -sSTRICT # fails due to missing __syscall_...()
|
||||
#emcc.jsflags += -sALLOW_UNIMPLEMENTED_SYSCALLS
|
||||
#emcc.jsflags += -sFILESYSTEM=0 # only for experimentation. sqlite3 needs the FS API
|
||||
#emcc.jsflags += -sABORTING_MALLOC
|
||||
emcc.jsflags += -sALLOW_TABLE_GROWTH
|
||||
# -sALLOW_TABLE_GROWTH is required for installing new SQL UDFs
|
||||
emcc.jsflags += -Wno-limited-postlink-optimizations
|
||||
# ^^^^^ it likes to warn when we have "limited optimizations" via the -g3 flag.
|
||||
#emcc.jsflags += -sSTANDALONE_WASM # causes OOM errors, not sure why
|
||||
# https://lld.llvm.org/WebAssembly.html
|
||||
emcc.jsflags += -sERROR_ON_UNDEFINED_SYMBOLS=0
|
||||
emcc.jsflags += -sLLD_REPORT_UNDEFINED
|
||||
#emcc.jsflags += --allow-undefined
|
||||
#emcc.jsflags += --import-undefined
|
||||
#emcc.jsflags += --unresolved-symbols=import-dynamic --experimental-pic
|
||||
#emcc.jsflags += --experimental-pic --unresolved-symbols=ingore-all --import-undefined
|
||||
#emcc.jsflags += --unresolved-symbols=ignore-all
|
||||
emcc.jsflags += -sWASM_BIGINT=$(emcc.WASM_BIGINT)
|
||||
|
||||
########################################################################
|
||||
# -sMEMORY64=1 fails to load, erroring with:
|
||||
# invalid memory limits flags 0x5
|
||||
# (enable via --experimental-wasm-memory64)
|
||||
#
|
||||
# ^^^^ MEMORY64=2 builds and loads but dies when we do things like:
|
||||
#
|
||||
# new Uint8Array(wasm.heap8u().buffer, ptr, n)
|
||||
#
|
||||
# because ptr is now a BigInt, so is invalid for passing to arguments
|
||||
# which have strict must-be-a-Number requirements.
|
||||
########################################################################
|
||||
|
||||
|
||||
########################################################################
|
||||
# -sSINGLE_FILE:
|
||||
# https://github.com/emscripten-core/emscripten/blob/main/src/settings.js#L1704
|
||||
# -sSINGLE_FILE=1 would be really nice but we have to build with -g3
|
||||
# for -O2 and higher to work (else minification breaks the code) and
|
||||
# cannot wasm-strip the binary before it gets encoded into the JS
|
||||
# file. The result is that the generated JS file is, because of the -g3
|
||||
# debugging info, _huge_.
|
||||
########################################################################
|
||||
|
||||
########################################################################
|
||||
# AN EXPERIMENT: undocumented Emscripten feature: if the target file
|
||||
# extension is "mjs", it defaults to ES6 module builds:
|
||||
# https://github.com/emscripten-core/emscripten/issues/14383
|
||||
ifeq (,$(filter esm,$(MAKECMDGOALS)))
|
||||
sqlite3.js.ext := js
|
||||
else
|
||||
esm.deps := $(filter-out esm,$(MAKECMDGOALS))
|
||||
esm: $(if $(esm.deps),$(esm.deps),all)
|
||||
sqlite3.js.ext := mjs
|
||||
endif
|
||||
# /esm
|
||||
########################################################################
|
||||
sqlite3.js := $(dir.dout)/sqlite3.$(sqlite3.js.ext)
|
||||
sqlite3.wasm := $(dir.dout)/sqlite3.wasm
|
||||
sqlite3-wasm.c := $(dir.api)/sqlite3-wasm.c
|
||||
# sqlite3-wasm.o vs sqlite3-wasm.c: building against the latter
|
||||
# (predictably) results in a slightly faster binary, but we're close
|
||||
# enough to the target speed requirements that the 500ms makes a
|
||||
# difference. Thus we build all binaries against sqlite3-wasm.c
|
||||
# instead of building a shared copy of sqlite3-wasm.o.
|
||||
$(eval $(call call-make-pre-js,sqlite3))
|
||||
$(sqlite3.js):
|
||||
$(sqlite3.js): $(MAKEFILE) $(sqlite3.wasm.obj) \
|
||||
$(EXPORTED_FUNCTIONS.api) \
|
||||
$(pre-post-sqlite3.deps)
|
||||
@echo "Building $@ ..."
|
||||
$(emcc.bin) -o $@ $(emcc_opt_full) $(emcc.flags) \
|
||||
$(emcc.jsflags) $(pre-post-common.flags) $(pre-post-sqlite3.flags) \
|
||||
$(cflags.common) $(SQLITE_OPT) $(sqlite3-wasm.c)
|
||||
chmod -x $(sqlite3.wasm)
|
||||
$(maybe-wasm-strip) $(sqlite3.wasm)
|
||||
@ls -la $@ $(sqlite3.wasm)
|
||||
$(sqlite3.wasm): $(sqlite3.js)
|
||||
CLEAN_FILES += $(sqlite3.js) $(sqlite3.wasm)
|
||||
all: $(sqlite3.js)
|
||||
wasm: $(sqlite3.js)
|
||||
# End main Emscripten-based module build
|
||||
########################################################################
|
||||
|
||||
########################################################################
|
||||
# batch-runner.js...
|
||||
dir.sql := sql
|
||||
speedtest1 := ../../speedtest1
|
||||
speedtest1.c := ../../test/speedtest1.c
|
||||
speedtest1.sql := $(dir.sql)/speedtest1.sql
|
||||
speedtest1.cliflags := --size 25 --big-transactions
|
||||
$(speedtest1):
|
||||
$(MAKE) -C ../.. speedtest1
|
||||
$(speedtest1.sql): $(speedtest1) $(MAKEFILE)
|
||||
$(speedtest1) $(speedtest1.cliflags) --script $@
|
||||
batch-runner.list: $(MAKEFILE) $(speedtest1.sql) $(dir.sql)/000-mandelbrot.sql
|
||||
bash split-speedtest1-script.sh $(dir.sql)/speedtest1.sql
|
||||
ls -1 $(dir.sql)/*.sql | grep -v speedtest1.sql | sort > $@
|
||||
clean-batch:
|
||||
rm -f batch-runner.list $(dir.sql)/speedtest1*.sql
|
||||
# ^^^ we don't do this along with 'clean' because we clean/rebuild on
|
||||
# a regular basis with different -Ox flags and rebuilding the batch
|
||||
# pieces each time is an unnecessary time sink.
|
||||
batch: batch-runner.list
|
||||
all: batch
|
||||
# end batch-runner.js
|
||||
########################################################################
|
||||
# speedtest1.js...
|
||||
# speedtest1-common.eflags = emcc flags used by multiple builds of speedtest1
|
||||
# speedtest1.eflags = emcc flags used by main build of speedtest1
|
||||
speedtest1-common.eflags := $(emcc_opt_full)
|
||||
speedtest1.eflags :=
|
||||
speedtest1.eflags += -sENVIRONMENT=web
|
||||
speedtest1.eflags += -sALLOW_MEMORY_GROWTH
|
||||
speedtest1.eflags += -sINITIAL_MEMORY=$(emcc.INITIAL_MEMORY.$(emcc.INITIAL_MEMORY))
|
||||
speedtest1-common.eflags += -sINVOKE_RUN=0
|
||||
speedtest1-common.eflags += --no-entry
|
||||
#speedtest1-common.eflags += -flto
|
||||
speedtest1-common.eflags += -sABORTING_MALLOC
|
||||
speedtest1-common.eflags += -sSTRICT_JS
|
||||
speedtest1-common.eflags += -sMODULARIZE
|
||||
speedtest1-common.eflags += -Wno-limited-postlink-optimizations
|
||||
EXPORTED_FUNCTIONS.speedtest1 := $(abspath $(dir.tmp)/EXPORTED_FUNCTIONS.speedtest1)
|
||||
speedtest1-common.eflags += -sEXPORTED_FUNCTIONS=@$(EXPORTED_FUNCTIONS.speedtest1)
|
||||
speedtest1-common.eflags += $(emcc.exportedRuntimeMethods)
|
||||
speedtest1-common.eflags += -sALLOW_TABLE_GROWTH
|
||||
speedtest1-common.eflags += -sDYNAMIC_EXECUTION=0
|
||||
speedtest1-common.eflags += --minify 0
|
||||
speedtest1-common.eflags += -sEXPORT_NAME=$(sqlite3.js.init-func)
|
||||
speedtest1-common.eflags += -sWASM_BIGINT=$(emcc.WASM_BIGINT)
|
||||
speedtest1-common.eflags += $(pre-post-common.flags)
|
||||
speedtest1.exit-runtime0 := -sEXIT_RUNTIME=0
|
||||
speedtest1.exit-runtime1 := -sEXIT_RUNTIME=1
|
||||
# Re -sEXIT_RUNTIME=1 vs 0: if it's 1 and speedtest1 crashes, we get
|
||||
# this error from emscripten:
|
||||
#
|
||||
# > native function `free` called after runtime exit (use
|
||||
# NO_EXIT_RUNTIME to keep it alive after main() exits))
|
||||
#
|
||||
# If it's 0 and it crashes, we get:
|
||||
#
|
||||
# > stdio streams had content in them that was not flushed. you should
|
||||
# set EXIT_RUNTIME to 1 (see the FAQ), or make sure to emit a newline
|
||||
# when you printf etc.
|
||||
#
|
||||
# and pending output is not flushed because it didn't end with a
|
||||
# newline (by design). The lesser of the two evils seems to be
|
||||
# -sEXIT_RUNTIME=1 but we need EXIT_RUNTIME=0 for the worker-based app
|
||||
# which runs speedtest1 multiple times.
|
||||
|
||||
$(EXPORTED_FUNCTIONS.speedtest1): $(EXPORTED_FUNCTIONS.api)
|
||||
@echo "Making $@ ..."
|
||||
@{ echo _wasm_main; cat $(EXPORTED_FUNCTIONS.api); } > $@
|
||||
speedtest1.js := $(dir.dout)/speedtest1.js
|
||||
speedtest1.wasm := $(subst .js,.wasm,$(speedtest1.js))
|
||||
speedtest1.cflags := $(cflags.common) -DSQLITE_SPEEDTEST1_WASM
|
||||
speedtest1.cses := $(speedtest1.c) $(sqlite3-wasm.c)
|
||||
$(eval $(call call-make-pre-js,speedtest1))
|
||||
$(speedtest1.js): $(MAKEFILE) $(speedtest1.cses) \
|
||||
$(pre-post-speedtest1.deps) \
|
||||
$(EXPORTED_FUNCTIONS.speedtest1)
|
||||
@echo "Building $@ ..."
|
||||
$(emcc.bin) \
|
||||
$(speedtest1.eflags) $(speedtest1-common.eflags) $(speedtest1.cflags) \
|
||||
$(pre-post-speedtest1.flags) \
|
||||
$(SQLITE_OPT) \
|
||||
$(speedtest1.exit-runtime0) \
|
||||
-o $@ $(speedtest1.cses) -lm
|
||||
$(maybe-wasm-strip) $(speedtest1.wasm)
|
||||
ls -la $@ $(speedtest1.wasm)
|
||||
|
||||
speedtest1: $(speedtest1.js)
|
||||
all: speedtest1
|
||||
CLEAN_FILES += $(speedtest1.js) $(speedtest1.wasm)
|
||||
# end speedtest1.js
|
||||
########################################################################
|
||||
|
||||
########################################################################
|
||||
# Convenience rules to rebuild with various -Ox levels. Much
|
||||
# experimentation shows -O2 to be the clear winner in terms of speed.
|
||||
# Note that build times with anything higher than -O0 are somewhat
|
||||
# painful.
|
||||
|
||||
.PHONY: o0 o1 o2 o3 os oz
|
||||
o-xtra := -flto
|
||||
# ^^^^ -flto can have a considerably performance boost at -O0 but
|
||||
# doubles the build time and seems to have negligible effect on
|
||||
# higher optimization levels.
|
||||
o0: clean
|
||||
$(MAKE) -e "emcc_opt=-O0"
|
||||
o1: clean
|
||||
$(MAKE) -e "emcc_opt=-O1 $(o-xtra)"
|
||||
o2: clean
|
||||
$(MAKE) -e "emcc_opt=-O2 $(o-xtra)"
|
||||
o3: clean
|
||||
$(MAKE) -e "emcc_opt=-O3 $(o-xtra)"
|
||||
os: clean
|
||||
@echo "WARNING: -Os can result in a build with mysteriously missing pieces!"
|
||||
$(MAKE) -e "emcc_opt=-Os $(o-xtra)"
|
||||
oz: clean
|
||||
$(MAKE) -e "emcc_opt=-Oz $(o-xtra)"
|
||||
|
||||
########################################################################
|
||||
# Sub-makes...
|
||||
|
||||
include fiddle.make
|
||||
|
||||
# Only add wasmfs if wasmfs.enable=1 or we're running (dist)clean
|
||||
wasmfs.enable ?= $(if $(filter %clean,$(MAKECMDGOALS)),1,0)
|
||||
ifeq (1,$(wasmfs.enable))
|
||||
# wasmfs build disabled 2022-10-19 per /chat discussion.
|
||||
# OPFS-over-wasmfs was initially a stopgap measure and a convenient
|
||||
# point of comparison for the OPFS sqlite3_vfs's performance, but it
|
||||
# currently doubles our deliverables and build maintenance burden for
|
||||
# little, if any, benefit.
|
||||
#
|
||||
########################################################################
|
||||
# Some platforms do not support the WASMFS build. Raspberry Pi OS is one
|
||||
# of them. As such platforms are discovered, add their (uname -m) name
|
||||
# to PLATFORMS_WITH_NO_WASMFS to exclude the wasmfs build parts.
|
||||
PLATFORMS_WITH_NO_WASMFS := aarch64 # add any others here
|
||||
THIS_ARCH := $(shell /usr/bin/uname -m)
|
||||
ifneq (,$(filter $(THIS_ARCH),$(PLATFORMS_WITH_NO_WASMFS)))
|
||||
$(info This platform does not support the WASMFS build.)
|
||||
HAVE_WASMFS := 0
|
||||
else
|
||||
HAVE_WASMFS := 1
|
||||
include wasmfs.make
|
||||
endif
|
||||
endif
|
||||
# /wasmfs
|
||||
########################################################################
|
||||
|
||||
########################################################################
|
||||
# Create deliverables:
|
||||
ifneq (,$(filter dist,$(MAKECMDGOALS)))
|
||||
include dist.make
|
||||
endif
|
||||
|
||||
########################################################################
|
||||
# Push files to public wasm-testing.sqlite.org server
|
||||
wasm-testing.include = $(dir.dout) *.js *.html \
|
||||
batch-runner.list $(dir.sql) $(dir.common) $(dir.fiddle) $(dir.jacc)
|
||||
wasm-testing.exclude = sql/speedtest1.sql
|
||||
wasm-testing.dir = /jail/sites/wasm-testing
|
||||
wasm-testing.dest ?= wasm-testing:$(wasm-testing.dir)
|
||||
# ---------------------^^^^^^^^^^^^ ssh alias
|
||||
.PHONY: push-testing
|
||||
push-testing:
|
||||
rsync -z -e ssh --ignore-times --chown=stephan:www-data --group -r \
|
||||
$(patsubst %,--exclude=%,$(wasm-testing.exclude)) \
|
||||
$(wasm-testing.include) $(wasm-testing.dest)
|
||||
@echo "Updating gzipped copies..."; \
|
||||
ssh wasm-testing 'cd $(wasm-testing.dir) && bash .gzip' || \
|
||||
echo "SSH failed: it's likely that stale content will be served via old gzip files."
|
||||
|
||||
########################################################################
|
||||
# If we find a copy of the sqlite.org/wasm docs checked out, copy
|
||||
# certain files over to it, noting that some need automatable edits...
|
||||
WDOCS.home ?= ../../../wdoc
|
||||
.PHONY: update-docs
|
||||
ifneq (,$(wildcard $(WDOCS.home)/api-index.md))
|
||||
WDOCS.jswasm := $(WDOCS.home)/jswasm
|
||||
update-docs: $(bin.stripccomments) $(sqlite3.js) $(sqlite3.wasm)
|
||||
@echo "Copying files to the /wasm docs. Be sure to use an -Oz build for this!"
|
||||
cp $(sqlite3.wasm) $(WDOCS.jswasm)/.
|
||||
$(bin.stripccomments) -k -k < $(sqlite3.js) \
|
||||
| sed -e '/^[ \t]*$$/d' > $(WDOCS.jswasm)/sqlite3.js
|
||||
cp demo-123.js demo-123.html demo-123-worker.html $(WDOCS.home)
|
||||
sed -n -e '/EXTRACT_BEGIN/,/EXTRACT_END/p' \
|
||||
module-symbols.html > $(WDOCS.home)/module-symbols.html
|
||||
else
|
||||
update-docs:
|
||||
@echo "Cannot find wasm docs checkout."; \
|
||||
echo "Pass WDOCS.home=/path/to/wasm/docs/checkout or edit this makefile to suit."; \
|
||||
exit 127
|
||||
endif
|
||||
# end /wasm docs
|
||||
########################################################################
|
||||
@@ -0,0 +1,23 @@
|
||||
This is the README for the sqlite3 WASM/JS distribution.
|
||||
|
||||
Main project page: https://sqlite.org
|
||||
|
||||
Documentation: https://sqlite.org/wasm
|
||||
|
||||
This archive contains the sqlite3.js and sqlite3.wasm file which make
|
||||
up the sqlite3 WASM/JS build.
|
||||
|
||||
The jswasm directory contains the core sqlite3 deliverables and the
|
||||
top-level directory contains demonstration and test apps. Browsers
|
||||
will not serve WASM files from file:// URLs, so the demo/test apps
|
||||
require a web server and that server must include the following
|
||||
headers in its response when serving the files:
|
||||
|
||||
Cross-Origin-Opener-Policy: same-origin
|
||||
Cross-Origin-Embedder-Policy: require-corp
|
||||
|
||||
One simple way to get the demo apps up and running on Unix-style
|
||||
systems is to install althttpd (https://sqlite.org/althttpd) and run:
|
||||
|
||||
althttpd --enable-sab --page index.html
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
This directory houses the [Web Assembly (WASM)](https://en.wikipedia.org/wiki/WebAssembly)
|
||||
parts of the sqlite3 build.
|
||||
|
||||
It requires [emscripten][] and that the build environment be set up for
|
||||
emscripten. A mini-HOWTO for setting that up follows...
|
||||
|
||||
First, install the Emscripten SDK, as documented
|
||||
[here](https://emscripten.org/docs/getting_started/downloads.html) and summarized
|
||||
below for Linux environments:
|
||||
|
||||
```
|
||||
# Clone the emscripten repository:
|
||||
$ sudo apt install git
|
||||
$ git clone https://github.com/emscripten-core/emsdk.git
|
||||
$ cd emsdk
|
||||
|
||||
# Download and install the latest SDK tools:
|
||||
$ ./emsdk install latest
|
||||
|
||||
# Make the "latest" SDK "active" for the current user:
|
||||
$ ./emsdk activate latest
|
||||
```
|
||||
|
||||
Those parts only need to be run once, but the SDK can be updated using:
|
||||
|
||||
```
|
||||
$ git pull
|
||||
$ ./emsdk install latest
|
||||
$ ./emsdk activate latest
|
||||
```
|
||||
|
||||
The following needs to be run for each shell instance which needs the
|
||||
`emcc` compiler:
|
||||
|
||||
```
|
||||
# Activate PATH and other environment variables in the current terminal:
|
||||
$ source ./emsdk_env.sh
|
||||
|
||||
$ which emcc
|
||||
/path/to/emsdk/upstream/emscripten/emcc
|
||||
```
|
||||
|
||||
Optionally, add that to your login shell's resource file (`~/.bashrc`
|
||||
or equivalent).
|
||||
|
||||
That `env` script needs to be sourced for building this application
|
||||
from the top of the sqlite3 build tree:
|
||||
|
||||
```
|
||||
$ make fiddle
|
||||
```
|
||||
|
||||
Or:
|
||||
|
||||
```
|
||||
$ cd ext/wasm
|
||||
$ make
|
||||
```
|
||||
|
||||
That will generate the a number of files required for a handful of
|
||||
test and demo applications which can be accessed via
|
||||
`index.html`. WASM content cannot, due to XMLHttpRequest security
|
||||
limitations, be loaded if the containing HTML file is opened directly
|
||||
in the browser (i.e. if it is opened using a `file://` URL), so it
|
||||
needs to be served via an HTTP server. For example, using
|
||||
[althttpd][]:
|
||||
|
||||
```
|
||||
$ cd ext/wasm
|
||||
$ althttpd --enable-sab --max-age 1 --page index.html
|
||||
```
|
||||
|
||||
That will open the system's browser and run the index page, from which
|
||||
all of the test and demo applications can be accessed.
|
||||
|
||||
Note that when serving this app via [althttpd][], it must be a version
|
||||
from 2022-09-26 or newer so that it recognizes the `--enable-sab`
|
||||
flag, which causes althttpd to emit two HTTP response headers which
|
||||
are required to enable JavaScript's `SharedArrayBuffer` and `Atomics`
|
||||
APIs. Those APIs are required in order to enable the OPFS-related
|
||||
features in the apps which use them.
|
||||
|
||||
# Testing on a remote machine that is accessed via SSH
|
||||
|
||||
*NB: The following are developer notes, last validated on 2022-08-18*
|
||||
|
||||
* Remote: Install git, emsdk, and althttpd
|
||||
* Use a [version of althttpd][althttpd] from
|
||||
September 26, 2022 or newer.
|
||||
* Remote: Install the SQLite source tree. CD to ext/wasm
|
||||
* Remote: "`make`" to build WASM
|
||||
* Remote: `althttpd --enable-sab --port 8080 --popup`
|
||||
* Local: `ssh -L 8180:localhost:8080 remote`
|
||||
* Local: Point your web-browser at http://localhost:8180/index.html
|
||||
|
||||
In order to enable [SharedArrayBuffers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer),
|
||||
the web-browser requires that the two extra Cross-Origin lines be present
|
||||
in HTTP reply headers and that the request must come from "localhost".
|
||||
Since the web-server is on a different machine from
|
||||
the web-broser, the localhost requirement means that the connection must be tunneled
|
||||
using SSH.
|
||||
|
||||
|
||||
[emscripten]: https://emscripten.org
|
||||
[althttpd]: https://sqlite.org/althttpd
|
||||
+46
-2
@@ -1,3 +1,4 @@
|
||||
_sqlite3_aggregate_context
|
||||
_sqlite3_bind_blob
|
||||
_sqlite3_bind_double
|
||||
_sqlite3_bind_int
|
||||
@@ -7,6 +8,7 @@ _sqlite3_bind_parameter_count
|
||||
_sqlite3_bind_parameter_index
|
||||
_sqlite3_bind_text
|
||||
_sqlite3_changes
|
||||
_sqlite3_changes64
|
||||
_sqlite3_clear_bindings
|
||||
_sqlite3_close_v2
|
||||
_sqlite3_column_blob
|
||||
@@ -21,30 +23,72 @@ _sqlite3_column_text
|
||||
_sqlite3_column_type
|
||||
_sqlite3_compileoption_get
|
||||
_sqlite3_compileoption_used
|
||||
_sqlite3_create_function
|
||||
_sqlite3_create_function_v2
|
||||
_sqlite3_create_window_function
|
||||
_sqlite3_data_count
|
||||
_sqlite3_db_filename
|
||||
_sqlite3_db_handle
|
||||
_sqlite3_db_name
|
||||
_sqlite3_deserialize
|
||||
_sqlite3_errmsg
|
||||
_sqlite3_error_offset
|
||||
_sqlite3_errstr
|
||||
_sqlite3_exec
|
||||
_sqlite3_expanded_sql
|
||||
_sqlite3_extended_errcode
|
||||
_sqlite3_extended_result_codes
|
||||
_sqlite3_file_control
|
||||
_sqlite3_finalize
|
||||
_sqlite3_interrupt
|
||||
_sqlite3_free
|
||||
_sqlite3_initialize
|
||||
_sqlite3_libversion
|
||||
_sqlite3_libversion_number
|
||||
_sqlite3_malloc
|
||||
_sqlite3_malloc64
|
||||
_sqlite3_msize
|
||||
_sqlite3_open
|
||||
_sqlite3_open_v2
|
||||
_sqlite3_prepare_v2
|
||||
_sqlite3_prepare_v2
|
||||
_sqlite3_prepare_v3
|
||||
_sqlite3_randomness
|
||||
_sqlite3_realloc
|
||||
_sqlite3_realloc64
|
||||
_sqlite3_reset
|
||||
_sqlite3_result_blob
|
||||
_sqlite3_result_double
|
||||
_sqlite3_result_error
|
||||
_sqlite3_result_error_code
|
||||
_sqlite3_result_error_nomem
|
||||
_sqlite3_result_error_toobig
|
||||
_sqlite3_result_int
|
||||
_sqlite3_result_int64
|
||||
_sqlite3_result_null
|
||||
_sqlite3_result_text
|
||||
_sqlite3_serialize
|
||||
_sqlite3_shutdown
|
||||
_sqlite3_sourceid
|
||||
_sqlite3_sql
|
||||
_sqlite3_step
|
||||
_sqlite3_strglob
|
||||
_sqlite3_strlike
|
||||
_sqlite3_total_changes
|
||||
_sqlite3_total_changes64
|
||||
_sqlite3_trace_v2
|
||||
_sqlite3_uri_boolean
|
||||
_sqlite3_uri_int64
|
||||
_sqlite3_uri_key
|
||||
_sqlite3_uri_parameter
|
||||
_sqlite3_user_data
|
||||
_sqlite3_value_blob
|
||||
_sqlite3_value_bytes
|
||||
_sqlite3_value_double
|
||||
_sqlite3_value_int
|
||||
_sqlite3_value_int64
|
||||
_sqlite3_value_text
|
||||
_sqlite3_value_type
|
||||
_sqlite3_vfs_find
|
||||
_sqlite3_vfs_register
|
||||
_sqlite3_vfs_unregister
|
||||
_malloc
|
||||
_free
|
||||
@@ -0,0 +1,3 @@
|
||||
FS
|
||||
wasmMemory
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
# sqlite3-api.js And Friends
|
||||
|
||||
This is the README for the files `sqlite3-*.js` and
|
||||
`sqlite3-wasm.c`. This collection of files is used to build a
|
||||
single-file distribution of the sqlite3 WASM API. It is broken into
|
||||
multiple JS files because:
|
||||
|
||||
1. To facilitate including or excluding certain components for
|
||||
specific use cases. e.g. by removing `sqlite3-api-oo1.js` if the
|
||||
OO#1 API is not needed.
|
||||
|
||||
2. To facilitate modularizing the pieces for use in different WASM
|
||||
build environments. e.g. the files `post-js-*.js` are for use with
|
||||
Emscripten's `--post-js` feature, and nowhere else.
|
||||
|
||||
3. Certain components must be in their own standalone files in order
|
||||
to be loaded as JS Workers.
|
||||
|
||||
Note that the structure described here is the current state of things,
|
||||
not necessarily the "final" state.
|
||||
|
||||
The overall idea is that the following files get concatenated
|
||||
together, in the listed order, the resulting file is loaded by a
|
||||
browser client:
|
||||
|
||||
- `sqlite3-api-prologue.js`\
|
||||
Contains the initial bootstrap setup of the sqlite3 API
|
||||
objects. This is exposed as a function, rather than objects, so that
|
||||
the next step can pass in a config object which abstracts away parts
|
||||
of the WASM environment, to facilitate plugging it in to arbitrary
|
||||
WASM toolchains.
|
||||
- `../common/whwasmutil.js`\
|
||||
A semi-third-party collection of JS/WASM utility code intended to
|
||||
replace much of the Emscripten glue. The sqlite3 APIs internally use
|
||||
these APIs instead of their Emscripten counterparts, in order to be
|
||||
more portable to arbitrary WASM toolchains. This API is
|
||||
configurable, in principle, for use with arbitrary WASM
|
||||
toolchains. It is "semi-third-party" in that it was created in order
|
||||
to support this tree but is standalone and maintained together
|
||||
with...
|
||||
- `../jaccwabyt/jaccwabyt.js`\
|
||||
Another semi-third-party API which creates bindings between JS
|
||||
and C structs, such that changes to the struct state from either JS
|
||||
or C are visible to the other end of the connection. This is also an
|
||||
independent spinoff project, conceived for the sqlite3 project but
|
||||
maintained separately.
|
||||
- `sqlite3-api-glue.js`\
|
||||
Invokes functionality exposed by the previous two files to
|
||||
flesh out low-level parts of `sqlite3-api-prologue.js`. Most of
|
||||
these pieces related to the `sqlite3.capi.wasm` object.
|
||||
- `sqlite3-api-build-version.js`\
|
||||
Gets created by the build process and populates the
|
||||
`sqlite3.version` object. This part is not critical, but records the
|
||||
version of the library against which this module was built.
|
||||
- `sqlite3-api-oo1.js`\
|
||||
Provides a high-level object-oriented wrapper to the lower-level C
|
||||
API, colloquially known as OO API #1. Its API is similar to other
|
||||
high-level sqlite3 JS wrappers and should feel relatively familiar
|
||||
to anyone familiar with such APIs. That said, it is not a "required
|
||||
component" and can be elided from builds which do not want it.
|
||||
- `sqlite3-api-worker1.js`\
|
||||
A Worker-thread-based API which uses OO API #1 to provide an
|
||||
interface to a database which can be driven from the main Window
|
||||
thread via the Worker message-passing interface. Like OO API #1,
|
||||
this is an optional component, offering one of any number of
|
||||
potential implementations for such an API.
|
||||
- `sqlite3-worker1.js`\
|
||||
Is not part of the amalgamated sources and is intended to be
|
||||
loaded by a client Worker thread. It loads the sqlite3 module
|
||||
and runs the Worker #1 API which is implemented in
|
||||
`sqlite3-api-worker1.js`.
|
||||
- `sqlite3-worker1-promiser.js`\
|
||||
Is likewise not part of the amalgamated sources and provides
|
||||
a Promise-based interface into the Worker #1 API. This is
|
||||
a far user-friendlier way to interface with databases running
|
||||
in a Worker thread.
|
||||
- `sqlite3-api-opfs.js`\
|
||||
is an sqlite3 VFS implementation which supports Google Chrome's
|
||||
Origin-Private FileSystem (OPFS) as a storage layer to provide
|
||||
persistent storage for database files in a browser. It requires...
|
||||
- `sqlite3-opfs-async-proxy.js`\
|
||||
is the asynchronous backend part of the OPFS proxy. It speaks
|
||||
directly to the (async) OPFS API and channels those results back
|
||||
to its synchronous counterpart. This file, because it must be
|
||||
started in its own Worker, is not part of the amalgamation.
|
||||
- **`api/sqlite3-api-cleanup.js`**\
|
||||
The previous files do not immediately extend the library. Instead
|
||||
they add callback functions to be called during its
|
||||
bootstrapping. Some also temporarily create global objects in order
|
||||
to communicate their state to the files which follow them. This file
|
||||
cleans up any dangling globals and runs the API bootstrapping
|
||||
process, which is what finally executes the initialization code
|
||||
installed by the previous files. As of this writing, this code
|
||||
ensures that the previous files leave no more than a single global
|
||||
symbol installed. When adapting the API for non-Emscripten
|
||||
toolchains, this "should" be the only file where changes are needed.
|
||||
|
||||
The build process glues those files together, resulting in
|
||||
`sqlite3-api.js`, which is everything except for the `post-js-*.js`
|
||||
files, and `sqlite3.js`, which is the Emscripten-generated amalgamated
|
||||
output and includes the `post-js-*.js` parts, as well as the
|
||||
Emscripten-provided module loading pieces.
|
||||
|
||||
The non-JS outlier file is `sqlite3-wasm.c`: it is a proxy for
|
||||
`sqlite3.c` which `#include`'s that file and adds a couple more
|
||||
WASM-specific helper functions, at least one of which requires access
|
||||
to private/static `sqlite3.c` internals. `sqlite3.wasm` is compiled
|
||||
from this file rather than `sqlite3.c`.
|
||||
|
||||
The following files are part of the build process but are injected
|
||||
into the build-generated `sqlite3.js` along with `sqlite3-api.js`.
|
||||
|
||||
- `extern-pre-js.js`\
|
||||
Emscripten-specific header for Emscripten's `--extern-pre-js`
|
||||
flag. As of this writing, that file is only used for experimentation
|
||||
purposes and holds no code relevant to the production deliverables.
|
||||
- `pre-js.js`\
|
||||
Emscripten-specific header for Emscripten's `--pre-js` flag. This
|
||||
file is intended as a place to override certain Emscripten behavior
|
||||
before it starts up, but corner-case Emscripten bugs keep that from
|
||||
being a reality.
|
||||
- `post-js-header.js`\
|
||||
Emscripten-specific header for the `--post-js` input. It opens up
|
||||
a lexical scope by starting a post-run handler for Emscripten.
|
||||
- `post-js-footer.js`\
|
||||
Emscripten-specific footer for the `--post-js` input. This closes
|
||||
off the lexical scope opened by `post-js-header.js`.
|
||||
- `extern-post-js.js`\
|
||||
Emscripten-specific header for Emscripten's `--extern-post-js`
|
||||
flag. This file overwrites the Emscripten-installed
|
||||
`sqlite3InitModule()` function with one which, after the module is
|
||||
loaded, also initializes the asynchronous parts of the sqlite3
|
||||
module. For example, the OPFS VFS support.
|
||||
@@ -0,0 +1,103 @@
|
||||
/* extern-post-js.js must be appended to the resulting sqlite3.js
|
||||
file. It gets its name from being used as the value for the
|
||||
--extern-post-js=... Emscripten flag. Note that this code, unlike
|
||||
most of the associated JS code, runs outside of the
|
||||
Emscripten-generated module init scope, in the current
|
||||
global scope. */
|
||||
(function(){
|
||||
/**
|
||||
In order to hide the sqlite3InitModule()'s resulting Emscripten
|
||||
module from downstream clients (and simplify our documentation by
|
||||
being able to elide those details), we rewrite
|
||||
sqlite3InitModule() to return the sqlite3 object.
|
||||
|
||||
Unfortunately, we cannot modify the module-loader/exporter-based
|
||||
impls which Emscripten installs at some point in the file above
|
||||
this.
|
||||
*/
|
||||
const originalInit = self.sqlite3InitModule;
|
||||
if(!originalInit){
|
||||
throw new Error("Expecting self.sqlite3InitModule to be defined by the Emscripten build.");
|
||||
}
|
||||
/**
|
||||
We need to add some state which our custom Module.locateFile()
|
||||
can see, but an Emscripten limitation currently prevents us from
|
||||
attaching it to the sqlite3InitModule function object:
|
||||
|
||||
https://github.com/emscripten-core/emscripten/issues/18071
|
||||
|
||||
The only(?) current workaround is to temporarily stash this state
|
||||
into the global scope and delete it when sqlite3InitModule()
|
||||
is called.
|
||||
*/
|
||||
const initModuleState = self.sqlite3InitModuleState = Object.assign(Object.create(null),{
|
||||
moduleScript: self?.document?.currentScript,
|
||||
isWorker: ('undefined' !== typeof WorkerGlobalScope),
|
||||
location: self.location,
|
||||
urlParams: new URL(self.location.href).searchParams
|
||||
});
|
||||
initModuleState.debugModule =
|
||||
(new URL(self.location.href).searchParams).has('sqlite3.debugModule')
|
||||
? (...args)=>console.warn('sqlite3.debugModule:',...args)
|
||||
: ()=>{};
|
||||
|
||||
if(initModuleState.urlParams.has('sqlite3.dir')){
|
||||
initModuleState.sqlite3Dir = initModuleState.urlParams.get('sqlite3.dir') +'/';
|
||||
}else if(initModuleState.moduleScript){
|
||||
const li = initModuleState.moduleScript.src.split('/');
|
||||
li.pop();
|
||||
initModuleState.sqlite3Dir = li.join('/') + '/';
|
||||
}
|
||||
|
||||
self.sqlite3InitModule = (...args)=>{
|
||||
//console.warn("Using replaced sqlite3InitModule()",self.location);
|
||||
return originalInit(...args).then((EmscriptenModule)=>{
|
||||
if(self.window!==self &&
|
||||
(EmscriptenModule['ENVIRONMENT_IS_PTHREAD']
|
||||
|| EmscriptenModule['_pthread_self']
|
||||
|| 'function'===typeof threadAlert
|
||||
|| self.location.pathname.endsWith('.worker.js')
|
||||
)){
|
||||
/** Workaround for wasmfs-generated worker, which calls this
|
||||
routine from each individual thread and requires that its
|
||||
argument be returned. All of the criteria above are fragile,
|
||||
based solely on inspection of the offending code, not public
|
||||
Emscripten details. */
|
||||
return EmscriptenModule;
|
||||
}
|
||||
EmscriptenModule.sqlite3.scriptInfo = initModuleState;
|
||||
//console.warn("sqlite3.scriptInfo =",EmscriptenModule.sqlite3.scriptInfo);
|
||||
const f = EmscriptenModule.sqlite3.asyncPostInit;
|
||||
delete EmscriptenModule.sqlite3.asyncPostInit;
|
||||
return f();
|
||||
}).catch((e)=>{
|
||||
console.error("Exception loading sqlite3 module:",e);
|
||||
throw e;
|
||||
});
|
||||
};
|
||||
self.sqlite3InitModule.ready = originalInit.ready;
|
||||
|
||||
if(self.sqlite3InitModuleState.moduleScript){
|
||||
const sim = self.sqlite3InitModuleState;
|
||||
let src = sim.moduleScript.src.split('/');
|
||||
src.pop();
|
||||
sim.scriptDir = src.join('/') + '/';
|
||||
}
|
||||
initModuleState.debugModule('sqlite3InitModuleState =',initModuleState);
|
||||
if(0){
|
||||
console.warn("Replaced sqlite3InitModule()");
|
||||
console.warn("self.location.href =",self.location.href);
|
||||
if('undefined' !== typeof document){
|
||||
console.warn("document.currentScript.src =",
|
||||
document?.currentScript?.src);
|
||||
}
|
||||
}
|
||||
/* Replace the various module exports performed by the Emscripten
|
||||
glue... */
|
||||
if (typeof exports === 'object' && typeof module === 'object')
|
||||
module.exports = sqlite3InitModule;
|
||||
else if (typeof exports === 'object')
|
||||
exports["sqlite3InitModule"] = sqlite3InitModule;
|
||||
/* AMD modules get injected in a way we cannot override,
|
||||
so we can't handle those here. */
|
||||
})();
|
||||
@@ -0,0 +1,7 @@
|
||||
/* extern-pre-js.js must be prepended to the resulting sqlite3.js
|
||||
file. This file is currently only used for holding snippets during
|
||||
test and development.
|
||||
|
||||
It gets its name from being used as the value for the
|
||||
--extern-pre-js=... Emscripten flag.
|
||||
*/
|
||||
@@ -0,0 +1,4 @@
|
||||
/* The current function scope was opened via post-js-header.js, which
|
||||
gets prepended to this at build-time. This file closes that
|
||||
scope. */
|
||||
})/*postRun.push(...)*/;
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
post-js-header.js is to be prepended to other code to create
|
||||
post-js.js for use with Emscripten's --post-js flag. This code
|
||||
requires that it be running in that context. The Emscripten
|
||||
environment must have been set up already but it will not have
|
||||
loaded its WASM when the code in this file is run. The function it
|
||||
installs will be run after the WASM module is loaded, at which
|
||||
point the sqlite3 JS API bits will get set up.
|
||||
*/
|
||||
if(!Module.postRun) Module.postRun = [];
|
||||
Module.postRun.push(function(Module/*the Emscripten-style module object*/){
|
||||
'use strict';
|
||||
/* This function will contain at least the following:
|
||||
|
||||
- post-js-header.js (this file)
|
||||
- sqlite3-api-prologue.js => Bootstrapping bits to attach the rest to
|
||||
- common/whwasmutil.js => Replacements for much of Emscripten's glue
|
||||
- jaccwaby/jaccwabyt.js => Jaccwabyt (C/JS struct binding)
|
||||
- sqlite3-api-glue.js => glues previous parts together
|
||||
- sqlite3-api-oo.js => SQLite3 OO API #1
|
||||
- sqlite3-api-worker1.js => Worker-based API
|
||||
- sqlite3-api-opfs.js => OPFS VFS
|
||||
- sqlite3-api-cleanup.js => final API cleanup
|
||||
- post-js-footer.js => closes this postRun() function
|
||||
*/
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
BEGIN FILE: api/pre-js.js
|
||||
|
||||
This file is intended to be prepended to the sqlite3.js build using
|
||||
Emscripten's --pre-js=THIS_FILE flag (or equivalent).
|
||||
*/
|
||||
|
||||
// See notes in extern-post-js.js
|
||||
const sqlite3InitModuleState = self.sqlite3InitModuleState || Object.create(null);
|
||||
delete self.sqlite3InitModuleState;
|
||||
sqlite3InitModuleState.debugModule('self.location =',self.location);
|
||||
|
||||
/**
|
||||
This custom locateFile() tries to figure out where to load `path`
|
||||
from. The intent is to provide a way for foo/bar/X.js loaded from a
|
||||
Worker constructor or importScripts() to be able to resolve
|
||||
foo/bar/X.wasm (in the latter case, with some help):
|
||||
|
||||
1) If URL param named the same as `path` is set, it is returned.
|
||||
|
||||
2) If sqlite3InitModuleState.sqlite3Dir is set, then (thatName + path)
|
||||
is returned (note that it's assumed to end with '/').
|
||||
|
||||
3) If this code is running in the main UI thread AND it was loaded
|
||||
from a SCRIPT tag, the directory part of that URL is used
|
||||
as the prefix. (This form of resolution unfortunately does not
|
||||
function for scripts loaded via importScripts().)
|
||||
|
||||
4) If none of the above apply, (prefix+path) is returned.
|
||||
*/
|
||||
Module['locateFile'] = function(path, prefix) {
|
||||
let theFile;
|
||||
const up = this.urlParams;
|
||||
if(up.has(path)){
|
||||
theFile = up.get(path);
|
||||
}else if(this.sqlite3Dir){
|
||||
theFile = this.sqlite3Dir + path;
|
||||
}else if(this.scriptDir){
|
||||
theFile = this.scriptDir + path;
|
||||
}else{
|
||||
theFile = prefix + path;
|
||||
}
|
||||
sqlite3InitModuleState.debugModule(
|
||||
"locateFile(",arguments[0], ',', arguments[1],")",
|
||||
'sqlite3InitModuleState.scriptDir =',this.scriptDir,
|
||||
'up.entries() =',Array.from(up.entries()),
|
||||
"result =", theFile
|
||||
);
|
||||
return theFile;
|
||||
}.bind(sqlite3InitModuleState);
|
||||
|
||||
/**
|
||||
Bug warning: a custom Module.instantiateWasm() does not work
|
||||
in WASMFS builds:
|
||||
|
||||
https://github.com/emscripten-core/emscripten/issues/17951
|
||||
|
||||
In such builds we must disable this.
|
||||
*/
|
||||
const xNameOfInstantiateWasm = true
|
||||
? 'instantiateWasm'
|
||||
: 'emscripten-bug-17951';
|
||||
Module[xNameOfInstantiateWasm] = function callee(imports,onSuccess){
|
||||
imports.env.foo = function(){};
|
||||
const uri = Module.locateFile(
|
||||
callee.uri, (
|
||||
('undefined'===typeof scriptDirectory/*var defined by Emscripten glue*/)
|
||||
? '' : scriptDirectory)
|
||||
);
|
||||
sqlite3InitModuleState.debugModule(
|
||||
"instantiateWasm() uri =", uri
|
||||
);
|
||||
const wfetch = ()=>fetch(uri, {credentials: 'same-origin'});
|
||||
const loadWasm = WebAssembly.instantiateStreaming
|
||||
? async ()=>{
|
||||
return WebAssembly.instantiateStreaming(wfetch(), imports)
|
||||
.then((arg)=>onSuccess(arg.instance, arg.module));
|
||||
}
|
||||
: async ()=>{ // Safari < v15
|
||||
return wfetch()
|
||||
.then(response => response.arrayBuffer())
|
||||
.then(bytes => WebAssembly.instantiate(bytes, imports))
|
||||
.then((arg)=>onSuccess(arg.instance, arg.module));
|
||||
};
|
||||
loadWasm();
|
||||
return {};
|
||||
};
|
||||
/*
|
||||
It is literally impossible to reliably get the name of _this_ script
|
||||
at runtime, so impossible to derive X.wasm from script name
|
||||
X.js. Thus we need, at build-time, to redefine
|
||||
Module[xNameOfInstantiateWasm].uri by appending it to a build-specific
|
||||
copy of this file with the name of the wasm file. This is apparently
|
||||
why Emscripten hard-codes the name of the wasm file into their glue
|
||||
scripts.
|
||||
*/
|
||||
Module[xNameOfInstantiateWasm].uri = 'sqlite3.wasm';
|
||||
/* END FILE: api/pre-js.js, noting that the build process may add a
|
||||
line after this one to change the above .uri to a build-specific
|
||||
one. */
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
2022-07-22
|
||||
|
||||
The author disclaims copyright to this source code. In place of a
|
||||
legal notice, here is a blessing:
|
||||
|
||||
* May you do good and not evil.
|
||||
* May you find forgiveness for yourself and forgive others.
|
||||
* May you share freely, never taking more than you give.
|
||||
|
||||
***********************************************************************
|
||||
|
||||
This file is the tail end of the sqlite3-api.js constellation,
|
||||
intended to be appended after all other sqlite3-api-*.js files so
|
||||
that it can finalize any setup and clean up any global symbols
|
||||
temporarily used for setting up the API's various subsystems.
|
||||
*/
|
||||
'use strict';
|
||||
if('undefined' !== typeof Module){ // presumably an Emscripten build
|
||||
/**
|
||||
Install a suitable default configuration for sqlite3ApiBootstrap().
|
||||
*/
|
||||
const SABC = Object.assign(
|
||||
Object.create(null), {
|
||||
Module: Module /* ==> Currently needs to be exposed here for
|
||||
test code. NOT part of the public API. */,
|
||||
exports: Module['asm'],
|
||||
memory: Module.wasmMemory /* gets set if built with -sIMPORT_MEMORY */
|
||||
},
|
||||
self.sqlite3ApiConfig || Object.create(null)
|
||||
);
|
||||
|
||||
/**
|
||||
For current (2022-08-22) purposes, automatically call
|
||||
sqlite3ApiBootstrap(). That decision will be revisited at some
|
||||
point, as we really want client code to be able to call this to
|
||||
configure certain parts. Clients may modify
|
||||
self.sqlite3ApiBootstrap.defaultConfig to tweak the default
|
||||
configuration used by a no-args call to sqlite3ApiBootstrap(),
|
||||
but must have first loaded their WASM module in order to be
|
||||
able to provide the necessary configuration state.
|
||||
*/
|
||||
//console.warn("self.sqlite3ApiConfig = ",self.sqlite3ApiConfig);
|
||||
self.sqlite3ApiConfig = SABC;
|
||||
let sqlite3;
|
||||
try{
|
||||
sqlite3 = self.sqlite3ApiBootstrap();
|
||||
}catch(e){
|
||||
console.error("sqlite3ApiBootstrap() error:",e);
|
||||
throw e;
|
||||
}finally{
|
||||
delete self.sqlite3ApiBootstrap;
|
||||
delete self.sqlite3ApiConfig;
|
||||
}
|
||||
|
||||
if(self.location && +self.location.port > 1024){
|
||||
console.warn("Installing sqlite3 bits as global S for local dev/test purposes.");
|
||||
self.S = sqlite3;
|
||||
}
|
||||
|
||||
/* Clean up temporary references to our APIs... */
|
||||
delete sqlite3.util /* arguable, but these are (currently) internal-use APIs */;
|
||||
Module.sqlite3 = sqlite3 /* Needed for customized sqlite3InitModule() to be able to
|
||||
pass the sqlite3 object off to the client. */;
|
||||
}else{
|
||||
console.warn("This is not running in an Emscripten module context, so",
|
||||
"self.sqlite3ApiBootstrap() is _not_ being called due to lack",
|
||||
"of config info for the WASM environment.",
|
||||
"It must be called manually.");
|
||||
}
|
||||
@@ -0,0 +1,720 @@
|
||||
/*
|
||||
2022-07-22
|
||||
|
||||
The author disclaims copyright to this source code. In place of a
|
||||
legal notice, here is a blessing:
|
||||
|
||||
* May you do good and not evil.
|
||||
* May you find forgiveness for yourself and forgive others.
|
||||
* May you share freely, never taking more than you give.
|
||||
|
||||
***********************************************************************
|
||||
|
||||
This file glues together disparate pieces of JS which are loaded in
|
||||
previous steps of the sqlite3-api.js bootstrapping process:
|
||||
sqlite3-api-prologue.js, whwasmutil.js, and jaccwabyt.js. It
|
||||
initializes the main API pieces so that the downstream components
|
||||
(e.g. sqlite3-api-oo1.js) have all that they need.
|
||||
*/
|
||||
self.sqlite3ApiBootstrap.initializers.push(function(sqlite3){
|
||||
'use strict';
|
||||
const toss = (...args)=>{throw new Error(args.join(' '))};
|
||||
const toss3 = sqlite3.SQLite3Error.toss;
|
||||
const capi = sqlite3.capi, wasm = sqlite3.wasm, util = sqlite3.util;
|
||||
self.WhWasmUtilInstaller(wasm);
|
||||
delete self.WhWasmUtilInstaller;
|
||||
|
||||
/**
|
||||
Install JS<->C struct bindings for the non-opaque struct types we
|
||||
need... */
|
||||
sqlite3.StructBinder = self.Jaccwabyt({
|
||||
heap: 0 ? wasm.memory : wasm.heap8u,
|
||||
alloc: wasm.alloc,
|
||||
dealloc: wasm.dealloc,
|
||||
functionTable: wasm.functionTable,
|
||||
bigIntEnabled: wasm.bigIntEnabled,
|
||||
memberPrefix: '$'
|
||||
});
|
||||
delete self.Jaccwabyt;
|
||||
|
||||
if(0){
|
||||
/* "The problem" is that the following isn't even remotely
|
||||
type-safe. OTOH, nothing about WASM pointers is. */
|
||||
const argPointer = wasm.xWrap.argAdapter('*');
|
||||
wasm.xWrap.argAdapter('StructType', (v)=>{
|
||||
if(v && v.constructor && v instanceof StructBinder.StructType){
|
||||
v = v.pointer;
|
||||
}
|
||||
return wasm.isPtr(v)
|
||||
? argPointer(v)
|
||||
: toss("Invalid (object) type for StructType-type argument.");
|
||||
});
|
||||
}
|
||||
|
||||
{/* Convert Arrays and certain TypedArrays to strings for
|
||||
'flexible-string'-type arguments */
|
||||
const xString = wasm.xWrap.argAdapter('string');
|
||||
wasm.xWrap.argAdapter(
|
||||
'flexible-string', (v)=>xString(util.flexibleString(v))
|
||||
);
|
||||
}
|
||||
|
||||
if(1){// WhWasmUtil.xWrap() bindings...
|
||||
/**
|
||||
Add some descriptive xWrap() aliases for '*' intended to (A)
|
||||
initially improve readability/correctness of capi.signatures
|
||||
and (B) eventually perhaps provide automatic conversion from
|
||||
higher-level representations, e.g. capi.sqlite3_vfs to
|
||||
`sqlite3_vfs*` via capi.sqlite3_vfs.pointer.
|
||||
*/
|
||||
const aPtr = wasm.xWrap.argAdapter('*');
|
||||
wasm.xWrap.argAdapter('sqlite3*', aPtr)
|
||||
('sqlite3_stmt*', aPtr)
|
||||
('sqlite3_context*', aPtr)
|
||||
('sqlite3_value*', aPtr)
|
||||
('sqlite3_vfs*', aPtr)
|
||||
('void*', aPtr);
|
||||
wasm.xWrap.resultAdapter('sqlite3*', aPtr)
|
||||
('sqlite3_context*', aPtr)
|
||||
('sqlite3_stmt*', aPtr)
|
||||
('sqlite3_vfs*', aPtr)
|
||||
('void*', aPtr);
|
||||
|
||||
/**
|
||||
Populate api object with sqlite3_...() by binding the "raw" wasm
|
||||
exports into type-converting proxies using wasm.xWrap().
|
||||
*/
|
||||
for(const e of wasm.bindingSignatures){
|
||||
capi[e[0]] = wasm.xWrap.apply(null, e);
|
||||
}
|
||||
for(const e of wasm.bindingSignatures.wasm){
|
||||
wasm[e[0]] = wasm.xWrap.apply(null, e);
|
||||
}
|
||||
|
||||
/* For C API functions which cannot work properly unless
|
||||
wasm.bigIntEnabled is true, install a bogus impl which
|
||||
throws if called when bigIntEnabled is false. */
|
||||
const fI64Disabled = function(fname){
|
||||
return ()=>toss(fname+"() disabled due to lack",
|
||||
"of BigInt support in this build.");
|
||||
};
|
||||
for(const e of wasm.bindingSignatures.int64){
|
||||
capi[e[0]] = wasm.bigIntEnabled
|
||||
? wasm.xWrap.apply(null, e)
|
||||
: fI64Disabled(e[0]);
|
||||
}
|
||||
|
||||
/* There's no(?) need to expose bindingSignatures to clients,
|
||||
implicitly making it part of the public interface. */
|
||||
delete wasm.bindingSignatures;
|
||||
|
||||
if(wasm.exports.sqlite3_wasm_db_error){
|
||||
util.sqlite3_wasm_db_error = wasm.xWrap(
|
||||
'sqlite3_wasm_db_error', 'int', 'sqlite3*', 'int', 'string'
|
||||
);
|
||||
}else{
|
||||
util.sqlite3_wasm_db_error = function(pDb,errCode,msg){
|
||||
console.warn("sqlite3_wasm_db_error() is not exported.",arguments);
|
||||
return errCode;
|
||||
};
|
||||
}
|
||||
|
||||
}/*xWrap() bindings*/;
|
||||
|
||||
/**
|
||||
When registering a VFS and its related components it may be
|
||||
necessary to ensure that JS keeps a reference to them to keep
|
||||
them from getting garbage collected. Simply pass each such value
|
||||
to this function and a reference will be held to it for the life
|
||||
of the app.
|
||||
*/
|
||||
capi.sqlite3_vfs_register.addReference = function f(...args){
|
||||
if(!f._) f._ = [];
|
||||
f._.push(...args);
|
||||
};
|
||||
|
||||
/**
|
||||
Internal helper to assist in validating call argument counts in
|
||||
the hand-written sqlite3_xyz() wrappers. We do this only for
|
||||
consistency with non-special-case wrappings.
|
||||
*/
|
||||
const __dbArgcMismatch = (pDb,f,n)=>{
|
||||
return sqlite3.util.sqlite3_wasm_db_error(pDb, capi.SQLITE_MISUSE,
|
||||
f+"() requires "+n+" argument"+
|
||||
(1===n?"":'s')+".");
|
||||
};
|
||||
|
||||
/**
|
||||
Helper for flexible-string conversions which require a
|
||||
byte-length counterpart argument. Passed a value and its
|
||||
ostensible length, this function returns [V,N], where V
|
||||
is either v or a transformed copy of v and N is either n,
|
||||
-1, or the byte length of v (if it's a byte array).
|
||||
*/
|
||||
const __flexiString = function(v,n){
|
||||
if('string'===typeof v){
|
||||
n = -1;
|
||||
}else if(util.isSQLableTypedArray(v)){
|
||||
n = v.byteLength;
|
||||
v = util.typedArrayToString(v);
|
||||
}else if(Array.isArray(v)){
|
||||
v = v.join("");
|
||||
n = -1;
|
||||
}
|
||||
return [v, n];
|
||||
};
|
||||
|
||||
if(1){/* Special-case handling of sqlite3_exec() */
|
||||
const __exec = wasm.xWrap("sqlite3_exec", "int",
|
||||
["sqlite3*", "flexible-string", "*", "*", "**"]);
|
||||
/* Documented in the api object's initializer. */
|
||||
capi.sqlite3_exec = function f(pDb, sql, callback, pVoid, pErrMsg){
|
||||
if(f.length!==arguments.length){
|
||||
return __dbArgcMismatch(pDb,"sqlite3_exec",f.length);
|
||||
}else if('function' !== typeof callback){
|
||||
return __exec(pDb, sql, callback, pVoid, pErrMsg);
|
||||
}
|
||||
/* Wrap the callback in a WASM-bound function and convert the callback's
|
||||
`(char**)` arguments to arrays of strings... */
|
||||
const cbwrap = function(pVoid, nCols, pColVals, pColNames){
|
||||
let rc = capi.SQLITE_ERROR;
|
||||
try {
|
||||
let aVals = [], aNames = [], i = 0, offset = 0;
|
||||
for( ; i < nCols; offset += (wasm.ptrSizeof * ++i) ){
|
||||
aVals.push( wasm.cstringToJs(wasm.getPtrValue(pColVals + offset)) );
|
||||
aNames.push( wasm.cstringToJs(wasm.getPtrValue(pColNames + offset)) );
|
||||
}
|
||||
rc = callback(pVoid, nCols, aVals, aNames) | 0;
|
||||
/* The first 2 args of the callback are useless for JS but
|
||||
we want the JS mapping of the C API to be as close to the
|
||||
C API as possible. */
|
||||
}catch(e){
|
||||
/* If we set the db error state here, the higher-level exec() call
|
||||
replaces it with its own, so we have no way of reporting the
|
||||
exception message except the console. We must not propagate
|
||||
exceptions through the C API. */
|
||||
}
|
||||
return rc;
|
||||
};
|
||||
let pFunc, rc;
|
||||
try{
|
||||
pFunc = wasm.installFunction("ipipp", cbwrap);
|
||||
rc = __exec(pDb, sql, pFunc, pVoid, pErrMsg);
|
||||
}catch(e){
|
||||
rc = util.sqlite3_wasm_db_error(pDb, capi.SQLITE_ERROR,
|
||||
"Error running exec(): "+e.message);
|
||||
}finally{
|
||||
if(pFunc) wasm.uninstallFunction(pFunc);
|
||||
}
|
||||
return rc;
|
||||
};
|
||||
}/*sqlite3_exec() proxy*/;
|
||||
|
||||
if(1){/* Special-case handling of sqlite3_create_function_v2()
|
||||
and sqlite3_create_window_function() */
|
||||
const sqlite3CreateFunction = wasm.xWrap(
|
||||
"sqlite3_create_function_v2", "int",
|
||||
["sqlite3*", "string"/*funcName*/, "int"/*nArg*/,
|
||||
"int"/*eTextRep*/, "*"/*pApp*/,
|
||||
"*"/*xStep*/,"*"/*xFinal*/, "*"/*xValue*/, "*"/*xDestroy*/]
|
||||
);
|
||||
const sqlite3CreateWindowFunction = wasm.xWrap(
|
||||
"sqlite3_create_window_function", "int",
|
||||
["sqlite3*", "string"/*funcName*/, "int"/*nArg*/,
|
||||
"int"/*eTextRep*/, "*"/*pApp*/,
|
||||
"*"/*xStep*/,"*"/*xFinal*/, "*"/*xValue*/,
|
||||
"*"/*xInverse*/, "*"/*xDestroy*/]
|
||||
);
|
||||
|
||||
const __udfSetResult = function(pCtx, val){
|
||||
//console.warn("udfSetResult",typeof val, val);
|
||||
switch(typeof val) {
|
||||
case 'undefined':
|
||||
/* Assume that the client already called sqlite3_result_xxx(). */
|
||||
break;
|
||||
case 'boolean':
|
||||
capi.sqlite3_result_int(pCtx, val ? 1 : 0);
|
||||
break;
|
||||
case 'bigint':
|
||||
if(wasm.bigIntEnabled){
|
||||
if(util.bigIntFits64(val)) capi.sqlite3_result_int64(pCtx, val);
|
||||
else toss3("BigInt value",val.toString(),"is too BigInt for int64.");
|
||||
}else if(util.bigIntFits32(val)){
|
||||
capi.sqlite3_result_int(pCtx, Number(val));
|
||||
}else if(util.bigIntFitsDouble(val)){
|
||||
capi.sqlite3_result_double(pCtx, Number(val));
|
||||
}else{
|
||||
toss3("BigInt value",val.toString(),"is too BigInt.");
|
||||
}
|
||||
break;
|
||||
case 'number': {
|
||||
(util.isInt32(val)
|
||||
? capi.sqlite3_result_int
|
||||
: capi.sqlite3_result_double)(pCtx, val);
|
||||
break;
|
||||
}
|
||||
case 'string':
|
||||
capi.sqlite3_result_text(pCtx, val, -1, capi.SQLITE_TRANSIENT);
|
||||
break;
|
||||
case 'object':
|
||||
if(null===val/*yes, typeof null === 'object'*/) {
|
||||
capi.sqlite3_result_null(pCtx);
|
||||
break;
|
||||
}else if(util.isBindableTypedArray(val)){
|
||||
const pBlob = wasm.allocFromTypedArray(val);
|
||||
capi.sqlite3_result_blob(
|
||||
pCtx, pBlob, val.byteLength,
|
||||
wasm.exports[sqlite3.config.deallocExportName]
|
||||
);
|
||||
break;
|
||||
}
|
||||
// else fall through
|
||||
default:
|
||||
toss3("Don't not how to handle this UDF result value:",(typeof val), val);
|
||||
};
|
||||
}/*__udfSetResult()*/;
|
||||
|
||||
const __udfConvertArgs = function(argc, pArgv){
|
||||
let i, pVal, valType, arg;
|
||||
const tgt = [];
|
||||
for(i = 0; i < argc; ++i){
|
||||
pVal = wasm.getPtrValue(pArgv + (wasm.ptrSizeof * i));
|
||||
/**
|
||||
Curiously: despite ostensibly requiring 8-byte
|
||||
alignment, the pArgv array is parcelled into chunks of
|
||||
4 bytes (1 pointer each). The values those point to
|
||||
have 8-byte alignment but the individual argv entries
|
||||
do not.
|
||||
*/
|
||||
valType = capi.sqlite3_value_type(pVal);
|
||||
switch(valType){
|
||||
case capi.SQLITE_INTEGER:
|
||||
if(wasm.bigIntEnabled){
|
||||
arg = capi.sqlite3_value_int64(pVal);
|
||||
if(util.bigIntFitsDouble(arg)) arg = Number(arg);
|
||||
}
|
||||
else arg = capi.sqlite3_value_double(pVal)/*yes, double, for larger integers*/;
|
||||
break;
|
||||
case capi.SQLITE_FLOAT:
|
||||
arg = capi.sqlite3_value_double(pVal);
|
||||
break;
|
||||
case capi.SQLITE_TEXT:
|
||||
arg = capi.sqlite3_value_text(pVal);
|
||||
break;
|
||||
case capi.SQLITE_BLOB:{
|
||||
const n = capi.sqlite3_value_bytes(pVal);
|
||||
const pBlob = capi.sqlite3_value_blob(pVal);
|
||||
if(n && !pBlob) sqlite3.WasmAllocError.toss(
|
||||
"Cannot allocate memory for blob argument of",n,"byte(s)"
|
||||
);
|
||||
arg = n ? wasm.heap8u().slice(pBlob, pBlob + Number(n)) : null;
|
||||
break;
|
||||
}
|
||||
case capi.SQLITE_NULL:
|
||||
arg = null; break;
|
||||
default:
|
||||
toss3("Unhandled sqlite3_value_type()",valType,
|
||||
"is possibly indicative of incorrect",
|
||||
"pointer size assumption.");
|
||||
}
|
||||
tgt.push(arg);
|
||||
}
|
||||
return tgt;
|
||||
}/*__udfConvertArgs()*/;
|
||||
|
||||
const __udfSetError = (pCtx, e)=>{
|
||||
if(e instanceof sqlite3.WasmAllocError){
|
||||
capi.sqlite3_result_error_nomem(pCtx);
|
||||
}else{
|
||||
const msg = ('string'===typeof e) ? e : e.message;
|
||||
capi.sqlite3_result_error(pCtx, msg, -1);
|
||||
}
|
||||
};
|
||||
|
||||
const __xFunc = function(callback){
|
||||
return function(pCtx, argc, pArgv){
|
||||
try{ __udfSetResult(pCtx, callback(pCtx, ...__udfConvertArgs(argc, pArgv))) }
|
||||
catch(e){
|
||||
//console.error('xFunc() caught:',e);
|
||||
__udfSetError(pCtx, e);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const __xInverseAndStep = function(callback){
|
||||
return function(pCtx, argc, pArgv){
|
||||
try{ callback(pCtx, ...__udfConvertArgs(argc, pArgv)) }
|
||||
catch(e){ __udfSetError(pCtx, e) }
|
||||
};
|
||||
};
|
||||
|
||||
const __xFinalAndValue = function(callback){
|
||||
return function(pCtx){
|
||||
try{ __udfSetResult(pCtx, callback(pCtx)) }
|
||||
catch(e){ __udfSetError(pCtx, e) }
|
||||
};
|
||||
};
|
||||
|
||||
const __xDestroy = function(callback){
|
||||
return function(pVoid){
|
||||
try{ callback(pVoid) }
|
||||
catch(e){ console.error("UDF xDestroy method threw:",e) }
|
||||
};
|
||||
};
|
||||
|
||||
const __xMap = Object.assign(Object.create(null), {
|
||||
xFunc: {sig:'v(pip)', f:__xFunc},
|
||||
xStep: {sig:'v(pip)', f:__xInverseAndStep},
|
||||
xInverse: {sig:'v(pip)', f:__xInverseAndStep},
|
||||
xFinal: {sig:'v(p)', f:__xFinalAndValue},
|
||||
xValue: {sig:'v(p)', f:__xFinalAndValue},
|
||||
xDestroy: {sig:'v(p)', f:__xDestroy}
|
||||
});
|
||||
|
||||
const __xWrapFuncs = function(theFuncs, tgtUninst){
|
||||
const rc = []
|
||||
let k;
|
||||
for(k in theFuncs){
|
||||
let fArg = theFuncs[k];
|
||||
if('function'===typeof fArg){
|
||||
const w = __xMap[k];
|
||||
fArg = wasm.installFunction(w.sig, w.f(fArg));
|
||||
tgtUninst.push(fArg);
|
||||
}
|
||||
rc.push(fArg);
|
||||
}
|
||||
return rc;
|
||||
};
|
||||
|
||||
/* Documented in the api object's initializer. */
|
||||
capi.sqlite3_create_function_v2 = function f(
|
||||
pDb, funcName, nArg, eTextRep, pApp,
|
||||
xFunc, //void (*xFunc)(sqlite3_context*,int,sqlite3_value**)
|
||||
xStep, //void (*xStep)(sqlite3_context*,int,sqlite3_value**)
|
||||
xFinal, //void (*xFinal)(sqlite3_context*)
|
||||
xDestroy //void (*xDestroy)(void*)
|
||||
){
|
||||
if(f.length!==arguments.length){
|
||||
return __dbArgcMismatch(pDb,"sqlite3_create_function_v2",f.length);
|
||||
}
|
||||
/* Wrap the callbacks in a WASM-bound functions... */
|
||||
const uninstall = [/*funcs to uninstall on error*/];
|
||||
let rc;
|
||||
try{
|
||||
const funcArgs = __xWrapFuncs({xFunc, xStep, xFinal, xDestroy},
|
||||
uninstall);
|
||||
rc = sqlite3CreateFunction(pDb, funcName, nArg, eTextRep,
|
||||
pApp, ...funcArgs);
|
||||
}catch(e){
|
||||
console.error("sqlite3_create_function_v2() setup threw:",e);
|
||||
for(let v of uninstall){
|
||||
wasm.uninstallFunction(v);
|
||||
}
|
||||
rc = util.sqlite3_wasm_db_error(pDb, capi.SQLITE_ERROR,
|
||||
"Creation of UDF threw: "+e.message);
|
||||
}
|
||||
return rc;
|
||||
};
|
||||
|
||||
capi.sqlite3_create_function = function f(
|
||||
pDb, funcName, nArg, eTextRep, pApp,
|
||||
xFunc, xStep, xFinal
|
||||
){
|
||||
return (f.length===arguments.length)
|
||||
? capi.sqlite3_create_function_v2(pDb, funcName, nArg, eTextRep,
|
||||
pApp, xFunc, xStep, xFinal, 0)
|
||||
: __dbArgcMismatch(pDb,"sqlite3_create_function",f.length);
|
||||
};
|
||||
|
||||
/* Documented in the api object's initializer. */
|
||||
capi.sqlite3_create_window_function = function f(
|
||||
pDb, funcName, nArg, eTextRep, pApp,
|
||||
xStep, //void (*xStep)(sqlite3_context*,int,sqlite3_value**)
|
||||
xFinal, //void (*xFinal)(sqlite3_context*)
|
||||
xValue, //void (*xFinal)(sqlite3_context*)
|
||||
xInverse,//void (*xStep)(sqlite3_context*,int,sqlite3_value**)
|
||||
xDestroy //void (*xDestroy)(void*)
|
||||
){
|
||||
if(f.length!==arguments.length){
|
||||
return __dbArgcMismatch(pDb,"sqlite3_create_window_function",f.length);
|
||||
}
|
||||
/* Wrap the callbacks in a WASM-bound functions... */
|
||||
const uninstall = [/*funcs to uninstall on error*/];
|
||||
let rc;
|
||||
try{
|
||||
const funcArgs = __xWrapFuncs({xStep, xFinal, xValue, xInverse, xDestroy},
|
||||
uninstall);
|
||||
rc = sqlite3CreateWindowFunction(pDb, funcName, nArg, eTextRep,
|
||||
pApp, ...funcArgs);
|
||||
}catch(e){
|
||||
console.error("sqlite3_create_window_function() setup threw:",e);
|
||||
for(let v of uninstall){
|
||||
wasm.uninstallFunction(v);
|
||||
}
|
||||
rc = util.sqlite3_wasm_db_error(pDb, capi.SQLITE_ERROR,
|
||||
"Creation of UDF threw: "+e.message);
|
||||
}
|
||||
return rc;
|
||||
};
|
||||
/**
|
||||
A helper for UDFs implemented in JS and bound to WASM by the
|
||||
client. Given a JS value, udfSetResult(pCtx,X) calls one of the
|
||||
sqlite3_result_xyz(pCtx,...) routines, depending on X's data
|
||||
type:
|
||||
|
||||
- `null`: sqlite3_result_null()
|
||||
- `boolean`: sqlite3_result_int()
|
||||
- `number`: sqlite3_result_int() or sqlite3_result_double()
|
||||
- `string`: sqlite3_result_text()
|
||||
- Uint8Array or Int8Array: sqlite3_result_blob()
|
||||
- `undefined`: indicates that the UDF called one of the
|
||||
`sqlite3_result_xyz()` routines on its own, making this
|
||||
function a no-op. Results are _undefined_ if this function is
|
||||
passed the `undefined` value but did _not_ call one of the
|
||||
`sqlite3_result_xyz()` routines.
|
||||
|
||||
Anything else triggers sqlite3_result_error().
|
||||
*/
|
||||
capi.sqlite3_create_function_v2.udfSetResult =
|
||||
capi.sqlite3_create_function.udfSetResult =
|
||||
capi.sqlite3_create_window_function.udfSetResult = __udfSetResult;
|
||||
|
||||
/**
|
||||
A helper for UDFs implemented in JS and bound to WASM by the
|
||||
client. When passed the
|
||||
(argc,argv) values from the UDF-related functions which receive
|
||||
them (xFunc, xStep, xInverse), it creates a JS array
|
||||
representing those arguments, converting each to JS in a manner
|
||||
appropriate to its data type: numeric, text, blob
|
||||
(Uint8Array), or null.
|
||||
|
||||
Results are undefined if it's passed anything other than those
|
||||
two arguments from those specific contexts.
|
||||
|
||||
Thus an argc of 4 will result in a length-4 array containing
|
||||
the converted values from the corresponding argv.
|
||||
|
||||
The conversion will throw only on allocation error or an internal
|
||||
error.
|
||||
*/
|
||||
capi.sqlite3_create_function_v2.udfConvertArgs =
|
||||
capi.sqlite3_create_function.udfConvertArgs =
|
||||
capi.sqlite3_create_window_function.udfConvertArgs = __udfConvertArgs;
|
||||
|
||||
/**
|
||||
A helper for UDFs implemented in JS and bound to WASM by the
|
||||
client. It expects to be a passed `(sqlite3_context*, Error)`
|
||||
(an exception object or message string). And it sets the
|
||||
current UDF's result to sqlite3_result_error_nomem() or
|
||||
sqlite3_result_error(), depending on whether the 2nd argument
|
||||
is a sqlite3.WasmAllocError object or not.
|
||||
*/
|
||||
capi.sqlite3_create_function_v2.udfSetError =
|
||||
capi.sqlite3_create_function.udfSetError =
|
||||
capi.sqlite3_create_window_function.udfSetError = __udfSetError;
|
||||
|
||||
}/*sqlite3_create_function_v2() and sqlite3_create_window_function() proxies*/;
|
||||
|
||||
if(1){/* Special-case handling of sqlite3_prepare_v2() and
|
||||
sqlite3_prepare_v3() */
|
||||
/**
|
||||
Scope-local holder of the two impls of sqlite3_prepare_v2/v3().
|
||||
*/
|
||||
const __prepare = Object.create(null);
|
||||
/**
|
||||
This binding expects a JS string as its 2nd argument and
|
||||
null as its final argument. In order to compile multiple
|
||||
statements from a single string, the "full" impl (see
|
||||
below) must be used.
|
||||
*/
|
||||
__prepare.basic = wasm.xWrap('sqlite3_prepare_v3',
|
||||
"int", ["sqlite3*", "string",
|
||||
"int"/*ignored for this impl!*/,
|
||||
"int", "**",
|
||||
"**"/*MUST be 0 or null or undefined!*/]);
|
||||
/**
|
||||
Impl which requires that the 2nd argument be a pointer
|
||||
to the SQL string, instead of being converted to a
|
||||
string. This variant is necessary for cases where we
|
||||
require a non-NULL value for the final argument
|
||||
(exec()'ing multiple statements from one input
|
||||
string). For simpler cases, where only the first
|
||||
statement in the SQL string is required, the wrapper
|
||||
named sqlite3_prepare_v2() is sufficient and easier to
|
||||
use because it doesn't require dealing with pointers.
|
||||
*/
|
||||
__prepare.full = wasm.xWrap('sqlite3_prepare_v3',
|
||||
"int", ["sqlite3*", "*", "int", "int",
|
||||
"**", "**"]);
|
||||
|
||||
/* Documented in the api object's initializer. */
|
||||
capi.sqlite3_prepare_v3 = function f(pDb, sql, sqlLen, prepFlags, ppStmt, pzTail){
|
||||
if(f.length!==arguments.length){
|
||||
return __dbArgcMismatch(pDb,"sqlite3_prepare_v3",f.length);
|
||||
}
|
||||
const [xSql, xSqlLen] = __flexiString(sql, sqlLen);
|
||||
switch(typeof xSql){
|
||||
case 'string': return __prepare.basic(pDb, xSql, xSqlLen, prepFlags, ppStmt, null);
|
||||
case 'number': return __prepare.full(pDb, xSql, xSqlLen, prepFlags, ppStmt, pzTail);
|
||||
default:
|
||||
return util.sqlite3_wasm_db_error(
|
||||
pDb, capi.SQLITE_MISUSE,
|
||||
"Invalid SQL argument type for sqlite3_prepare_v2/v3()."
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/* Documented in the api object's initializer. */
|
||||
capi.sqlite3_prepare_v2 = function f(pDb, sql, sqlLen, ppStmt, pzTail){
|
||||
return (f.length===arguments.length)
|
||||
? capi.sqlite3_prepare_v3(pDb, sql, sqlLen, 0, ppStmt, pzTail)
|
||||
: __dbArgcMismatch(pDb,"sqlite3_prepare_v2",f.length);
|
||||
};
|
||||
}/*sqlite3_prepare_v2/v3()*/;
|
||||
|
||||
{/* Import C-level constants and structs... */
|
||||
const cJson = wasm.xCall('sqlite3_wasm_enum_json');
|
||||
if(!cJson){
|
||||
toss("Maintenance required: increase sqlite3_wasm_enum_json()'s",
|
||||
"static buffer size!");
|
||||
}
|
||||
wasm.ctype = JSON.parse(wasm.cstringToJs(cJson));
|
||||
//console.debug('wasm.ctype length =',wasm.cstrlen(cJson));
|
||||
for(const t of ['access', 'blobFinalizers', 'dataTypes',
|
||||
'encodings', 'fcntl', 'flock', 'ioCap',
|
||||
'openFlags', 'prepareFlags', 'resultCodes',
|
||||
'serialize', 'syncFlags', 'trace', 'udfFlags',
|
||||
'version'
|
||||
]){
|
||||
for(const e of Object.entries(wasm.ctype[t])){
|
||||
// ^^^ [k,v] there triggers a buggy code transormation via one
|
||||
// of the Emscripten-driven optimizers.
|
||||
capi[e[0]] = e[1];
|
||||
}
|
||||
}
|
||||
const __rcMap = Object.create(null);
|
||||
for(const t of ['resultCodes']){
|
||||
for(const e of Object.entries(wasm.ctype[t])){
|
||||
__rcMap[e[1]] = e[0];
|
||||
}
|
||||
}
|
||||
/**
|
||||
For the given integer, returns the SQLITE_xxx result code as a
|
||||
string, or undefined if no such mapping is found.
|
||||
*/
|
||||
capi.sqlite3_js_rc_str = (rc)=>__rcMap[rc];
|
||||
/* Bind all registered C-side structs... */
|
||||
const notThese = Object.assign(Object.create(null),{
|
||||
// Structs NOT to register
|
||||
WasmTestStruct: true
|
||||
});
|
||||
if(!util.isUIThread()){
|
||||
/* We remove the kvvfs VFS from Worker threads below. */
|
||||
notThese.sqlite3_kvvfs_methods = true;
|
||||
}
|
||||
for(const s of wasm.ctype.structs){
|
||||
if(!notThese[s.name]){
|
||||
capi[s.name] = sqlite3.StructBinder(s);
|
||||
}
|
||||
}
|
||||
}/*end C constant imports*/
|
||||
|
||||
const pKvvfs = capi.sqlite3_vfs_find("kvvfs");
|
||||
if( pKvvfs ){/* kvvfs-specific glue */
|
||||
if(util.isUIThread()){
|
||||
const kvvfsMethods = new capi.sqlite3_kvvfs_methods(
|
||||
wasm.exports.sqlite3_wasm_kvvfs_methods()
|
||||
);
|
||||
delete capi.sqlite3_kvvfs_methods;
|
||||
|
||||
const kvvfsMakeKey = wasm.exports.sqlite3_wasm_kvvfsMakeKeyOnPstack,
|
||||
pstack = wasm.pstack,
|
||||
pAllocRaw = wasm.exports.sqlite3_wasm_pstack_alloc;
|
||||
|
||||
const kvvfsStorage = (zClass)=>
|
||||
((115/*=='s'*/===wasm.getMemValue(zClass))
|
||||
? sessionStorage : localStorage);
|
||||
|
||||
/**
|
||||
Implementations for members of the object referred to by
|
||||
sqlite3_wasm_kvvfs_methods(). We swap out the native
|
||||
implementations with these, which use localStorage or
|
||||
sessionStorage for their backing store.
|
||||
*/
|
||||
const kvvfsImpls = {
|
||||
xRead: (zClass, zKey, zBuf, nBuf)=>{
|
||||
const stack = pstack.pointer,
|
||||
astack = wasm.scopedAllocPush();
|
||||
try {
|
||||
const zXKey = kvvfsMakeKey(zClass,zKey);
|
||||
if(!zXKey) return -3/*OOM*/;
|
||||
const jKey = wasm.cstringToJs(zXKey);
|
||||
const jV = kvvfsStorage(zClass).getItem(jKey);
|
||||
if(!jV) return -1;
|
||||
const nV = jV.length /* Note that we are relying 100% on v being
|
||||
ASCII so that jV.length is equal to the
|
||||
C-string's byte length. */;
|
||||
if(nBuf<=0) return nV;
|
||||
else if(1===nBuf){
|
||||
wasm.setMemValue(zBuf, 0);
|
||||
return nV;
|
||||
}
|
||||
const zV = wasm.scopedAllocCString(jV);
|
||||
if(nBuf > nV + 1) nBuf = nV + 1;
|
||||
wasm.heap8u().copyWithin(zBuf, zV, zV + nBuf - 1);
|
||||
wasm.setMemValue(zBuf + nBuf - 1, 0);
|
||||
return nBuf - 1;
|
||||
}catch(e){
|
||||
console.error("kvstorageRead()",e);
|
||||
return -2;
|
||||
}finally{
|
||||
pstack.restore(stack);
|
||||
wasm.scopedAllocPop(astack);
|
||||
}
|
||||
},
|
||||
xWrite: (zClass, zKey, zData)=>{
|
||||
const stack = pstack.pointer;
|
||||
try {
|
||||
const zXKey = kvvfsMakeKey(zClass,zKey);
|
||||
if(!zXKey) return 1/*OOM*/;
|
||||
const jKey = wasm.cstringToJs(zXKey);
|
||||
kvvfsStorage(zClass).setItem(jKey, wasm.cstringToJs(zData));
|
||||
return 0;
|
||||
}catch(e){
|
||||
console.error("kvstorageWrite()",e);
|
||||
return capi.SQLITE_IOERR;
|
||||
}finally{
|
||||
pstack.restore(stack);
|
||||
}
|
||||
},
|
||||
xDelete: (zClass, zKey)=>{
|
||||
const stack = pstack.pointer;
|
||||
try {
|
||||
const zXKey = kvvfsMakeKey(zClass,zKey);
|
||||
if(!zXKey) return 1/*OOM*/;
|
||||
kvvfsStorage(zClass).removeItem(wasm.cstringToJs(zXKey));
|
||||
return 0;
|
||||
}catch(e){
|
||||
console.error("kvstorageDelete()",e);
|
||||
return capi.SQLITE_IOERR;
|
||||
}finally{
|
||||
pstack.restore(stack);
|
||||
}
|
||||
}
|
||||
}/*kvvfsImpls*/;
|
||||
for(const k of Object.keys(kvvfsImpls)){
|
||||
kvvfsMethods[kvvfsMethods.memberKey(k)] =
|
||||
wasm.installFunction(
|
||||
kvvfsMethods.memberSignature(k),
|
||||
kvvfsImpls[k]
|
||||
);
|
||||
}
|
||||
}else{
|
||||
/* Worker thread: unregister kvvfs to avoid it being used
|
||||
for anything other than local/sessionStorage. It "can"
|
||||
be used that way but it's not really intended to be. */
|
||||
capi.sqlite3_vfs_unregister(pKvvfs);
|
||||
}
|
||||
}/*pKvvfs*/
|
||||
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,654 @@
|
||||
/*
|
||||
2022-07-22
|
||||
|
||||
The author disclaims copyright to this source code. In place of a
|
||||
legal notice, here is a blessing:
|
||||
|
||||
* May you do good and not evil.
|
||||
* May you find forgiveness for yourself and forgive others.
|
||||
* May you share freely, never taking more than you give.
|
||||
|
||||
***********************************************************************
|
||||
|
||||
This file implements the initializer for the sqlite3 "Worker API
|
||||
#1", a very basic DB access API intended to be scripted from a main
|
||||
window thread via Worker-style messages. Because of limitations in
|
||||
that type of communication, this API is minimalistic and only
|
||||
capable of serving relatively basic DB requests (e.g. it cannot
|
||||
process nested query loops concurrently).
|
||||
|
||||
This file requires that the core C-style sqlite3 API and OO API #1
|
||||
have been loaded.
|
||||
*/
|
||||
|
||||
/**
|
||||
sqlite3.initWorker1API() implements a Worker-based wrapper around
|
||||
SQLite3 OO API #1, colloquially known as "Worker API #1".
|
||||
|
||||
In order to permit this API to be loaded in worker threads without
|
||||
automatically registering onmessage handlers, initializing the
|
||||
worker API requires calling initWorker1API(). If this function is
|
||||
called from a non-worker thread then it throws an exception. It
|
||||
must only be called once per Worker.
|
||||
|
||||
When initialized, it installs message listeners to receive Worker
|
||||
messages and then it posts a message in the form:
|
||||
|
||||
```
|
||||
{type:'sqlite3-api', result:'worker1-ready'}
|
||||
```
|
||||
|
||||
to let the client know that it has been initialized. Clients may
|
||||
optionally depend on this function not returning until
|
||||
initialization is complete, as the initialization is synchronous.
|
||||
In some contexts, however, listening for the above message is
|
||||
a better fit.
|
||||
|
||||
Note that the worker-based interface can be slightly quirky because
|
||||
of its async nature. In particular, any number of messages may be posted
|
||||
to the worker before it starts handling any of them. If, e.g., an
|
||||
"open" operation fails, any subsequent messages will fail. The
|
||||
Promise-based wrapper for this API (`sqlite3-worker1-promiser.js`)
|
||||
is more comfortable to use in that regard.
|
||||
|
||||
The documentation for the input and output worker messages for
|
||||
this API follows...
|
||||
|
||||
====================================================================
|
||||
Common message format...
|
||||
|
||||
Each message posted to the worker has an operation-independent
|
||||
envelope and operation-dependent arguments:
|
||||
|
||||
```
|
||||
{
|
||||
type: string, // one of: 'open', 'close', 'exec', 'config-get'
|
||||
|
||||
messageId: OPTIONAL arbitrary value. The worker will copy it as-is
|
||||
into response messages to assist in client-side dispatching.
|
||||
|
||||
dbId: a db identifier string (returned by 'open') which tells the
|
||||
operation which database instance to work on. If not provided, the
|
||||
first-opened db is used. This is an "opaque" value, with no
|
||||
inherently useful syntax or information. Its value is subject to
|
||||
change with any given build of this API and cannot be used as a
|
||||
basis for anything useful beyond its one intended purpose.
|
||||
|
||||
args: ...operation-dependent arguments...
|
||||
|
||||
// the framework may add other properties for testing or debugging
|
||||
// purposes.
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
Response messages, posted back to the main thread, look like:
|
||||
|
||||
```
|
||||
{
|
||||
type: string. Same as above except for error responses, which have the type
|
||||
'error',
|
||||
|
||||
messageId: same value, if any, provided by the inbound message
|
||||
|
||||
dbId: the id of the db which was operated on, if any, as returned
|
||||
by the corresponding 'open' operation.
|
||||
|
||||
result: ...operation-dependent result...
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
====================================================================
|
||||
Error responses
|
||||
|
||||
Errors are reported messages in an operation-independent format:
|
||||
|
||||
```
|
||||
{
|
||||
type: "error",
|
||||
|
||||
messageId: ...as above...,
|
||||
|
||||
dbId: ...as above...
|
||||
|
||||
result: {
|
||||
|
||||
operation: type of the triggering operation: 'open', 'close', ...
|
||||
|
||||
message: ...error message text...
|
||||
|
||||
errorClass: string. The ErrorClass.name property from the thrown exception.
|
||||
|
||||
input: the message object which triggered the error.
|
||||
|
||||
stack: _if available_, a stack trace array.
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
====================================================================
|
||||
"config-get"
|
||||
|
||||
This operation fetches the serializable parts of the sqlite3 API
|
||||
configuration.
|
||||
|
||||
Message format:
|
||||
|
||||
```
|
||||
{
|
||||
type: "config-get",
|
||||
messageId: ...as above...,
|
||||
args: currently ignored and may be elided.
|
||||
}
|
||||
```
|
||||
|
||||
Response:
|
||||
|
||||
```
|
||||
{
|
||||
type: "config-get",
|
||||
messageId: ...as above...,
|
||||
result: {
|
||||
|
||||
version: sqlite3.version object
|
||||
|
||||
bigIntEnabled: bool. True if BigInt support is enabled.
|
||||
|
||||
wasmfsOpfsDir: path prefix, if any, _intended_ for use with
|
||||
WASMFS OPFS persistent storage.
|
||||
|
||||
wasmfsOpfsEnabled: true if persistent storage is enabled in the
|
||||
current environment. Only files stored under wasmfsOpfsDir
|
||||
will persist using that mechanism, however. It is legal to use
|
||||
the non-WASMFS OPFS VFS to open a database via a URI-style
|
||||
db filename.
|
||||
|
||||
vfsList: result of sqlite3.capi.sqlite3_js_vfs_list()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
====================================================================
|
||||
"open" a database
|
||||
|
||||
Message format:
|
||||
|
||||
```
|
||||
{
|
||||
type: "open",
|
||||
messageId: ...as above...,
|
||||
args:{
|
||||
|
||||
filename [=":memory:" or "" (unspecified)]: the db filename.
|
||||
See the sqlite3.oo1.DB constructor for peculiarities and
|
||||
transformations,
|
||||
|
||||
vfs: sqlite3_vfs name. Ignored if filename is ":memory:" or "".
|
||||
This may change how the given filename is resolved.
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Response:
|
||||
|
||||
```
|
||||
{
|
||||
type: "open",
|
||||
messageId: ...as above...,
|
||||
result: {
|
||||
filename: db filename, possibly differing from the input.
|
||||
|
||||
dbId: an opaque ID value which must be passed in the message
|
||||
envelope to other calls in this API to tell them which db to
|
||||
use. If it is not provided to future calls, they will default to
|
||||
operating on the least-recently-opened db. This property is, for
|
||||
API consistency's sake, also part of the containing message
|
||||
envelope. Only the `open` operation includes it in the `result`
|
||||
property.
|
||||
|
||||
persistent: true if the given filename resides in the
|
||||
known-persistent storage, else false.
|
||||
|
||||
vfs: name of the VFS the "main" db is using.
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
====================================================================
|
||||
"close" a database
|
||||
|
||||
Message format:
|
||||
|
||||
```
|
||||
{
|
||||
type: "close",
|
||||
messageId: ...as above...
|
||||
dbId: ...as above...
|
||||
args: OPTIONAL {unlink: boolean}
|
||||
}
|
||||
```
|
||||
|
||||
If the `dbId` does not refer to an opened ID, this is a no-op. If
|
||||
the `args` object contains a truthy `unlink` value then the database
|
||||
will be unlinked (deleted) after closing it. The inability to close a
|
||||
db (because it's not opened) or delete its file does not trigger an
|
||||
error.
|
||||
|
||||
Response:
|
||||
|
||||
```
|
||||
{
|
||||
type: "close",
|
||||
messageId: ...as above...,
|
||||
result: {
|
||||
|
||||
filename: filename of closed db, or undefined if no db was closed
|
||||
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
====================================================================
|
||||
"exec" SQL
|
||||
|
||||
All SQL execution is processed through the exec operation. It offers
|
||||
most of the features of the oo1.DB.exec() method, with a few limitations
|
||||
imposed by the state having to cross thread boundaries.
|
||||
|
||||
Message format:
|
||||
|
||||
```
|
||||
{
|
||||
type: "exec",
|
||||
messageId: ...as above...
|
||||
dbId: ...as above...
|
||||
args: string (SQL) or {... see below ...}
|
||||
}
|
||||
```
|
||||
|
||||
Response:
|
||||
|
||||
```
|
||||
{
|
||||
type: "exec",
|
||||
messageId: ...as above...,
|
||||
dbId: ...as above...
|
||||
result: {
|
||||
input arguments, possibly modified. See below.
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The arguments are in the same form accepted by oo1.DB.exec(), with
|
||||
the exceptions noted below.
|
||||
|
||||
A function-type args.callback property cannot cross
|
||||
the window/Worker boundary, so is not useful here. If
|
||||
args.callback is a string then it is assumed to be a
|
||||
message type key, in which case a callback function will be
|
||||
applied which posts each row result via:
|
||||
|
||||
postMessage({type: thatKeyType,
|
||||
rowNumber: 1-based-#,
|
||||
row: theRow,
|
||||
columnNames: anArray
|
||||
})
|
||||
|
||||
And, at the end of the result set (whether or not any result rows
|
||||
were produced), it will post an identical message with
|
||||
(row=undefined, rowNumber=null) to alert the caller than the result
|
||||
set is completed. Note that a row value of `null` is a legal row
|
||||
result for certain arg.rowMode values.
|
||||
|
||||
(Design note: we don't use (row=undefined, rowNumber=undefined) to
|
||||
indicate end-of-results because fetching those would be
|
||||
indistinguishable from fetching from an empty object unless the
|
||||
client used hasOwnProperty() (or similar) to distinguish "missing
|
||||
property" from "property with the undefined value". Similarly,
|
||||
`null` is a legal value for `row` in some case , whereas the db
|
||||
layer won't emit a result value of `undefined`.)
|
||||
|
||||
The callback proxy must not recurse into this interface. An exec()
|
||||
call will tie up the Worker thread, causing any recursion attempt
|
||||
to wait until the first exec() is completed.
|
||||
|
||||
The response is the input options object (or a synthesized one if
|
||||
passed only a string), noting that options.resultRows and
|
||||
options.columnNames may be populated by the call to db.exec().
|
||||
|
||||
*/
|
||||
self.sqlite3ApiBootstrap.initializers.push(function(sqlite3){
|
||||
sqlite3.initWorker1API = function(){
|
||||
'use strict';
|
||||
const toss = (...args)=>{throw new Error(args.join(' '))};
|
||||
if('function' !== typeof importScripts){
|
||||
toss("initWorker1API() must be run from a Worker thread.");
|
||||
}
|
||||
const self = this.self;
|
||||
const sqlite3 = this.sqlite3 || toss("Missing this.sqlite3 object.");
|
||||
const DB = sqlite3.oo1.DB;
|
||||
|
||||
/**
|
||||
Returns the app-wide unique ID for the given db, creating one if
|
||||
needed.
|
||||
*/
|
||||
const getDbId = function(db){
|
||||
let id = wState.idMap.get(db);
|
||||
if(id) return id;
|
||||
id = 'db#'+(++wState.idSeq)+'@'+db.pointer;
|
||||
/** ^^^ can't simply use db.pointer b/c closing/opening may re-use
|
||||
the same address, which could map pending messages to a wrong
|
||||
instance. */
|
||||
wState.idMap.set(db, id);
|
||||
return id;
|
||||
};
|
||||
|
||||
/**
|
||||
Internal helper for managing Worker-level state.
|
||||
*/
|
||||
const wState = {
|
||||
/**
|
||||
Each opened DB is added to this.dbList, and the first entry in
|
||||
that list is the default db. As each db is closed, its entry is
|
||||
removed from the list.
|
||||
*/
|
||||
dbList: [],
|
||||
/** Sequence number of dbId generation. */
|
||||
idSeq: 0,
|
||||
/** Map of DB instances to dbId. */
|
||||
idMap: new WeakMap,
|
||||
/** Temp holder for "transferable" postMessage() state. */
|
||||
xfer: [],
|
||||
open: function(opt){
|
||||
const db = new DB(opt);
|
||||
this.dbs[getDbId(db)] = db;
|
||||
if(this.dbList.indexOf(db)<0) this.dbList.push(db);
|
||||
return db;
|
||||
},
|
||||
close: function(db,alsoUnlink){
|
||||
if(db){
|
||||
delete this.dbs[getDbId(db)];
|
||||
const filename = db.filename;
|
||||
const pVfs = sqlite3.wasm.sqlite3_wasm_db_vfs(db.pointer, 0);
|
||||
db.close();
|
||||
const ddNdx = this.dbList.indexOf(db);
|
||||
if(ddNdx>=0) this.dbList.splice(ddNdx, 1);
|
||||
if(alsoUnlink && filename && pVfs){
|
||||
sqlite3.wasm.sqlite3_wasm_vfs_unlink(pVfs, filename);
|
||||
}
|
||||
}
|
||||
},
|
||||
/**
|
||||
Posts the given worker message value. If xferList is provided,
|
||||
it must be an array, in which case a copy of it passed as
|
||||
postMessage()'s second argument and xferList.length is set to
|
||||
0.
|
||||
*/
|
||||
post: function(msg,xferList){
|
||||
if(xferList && xferList.length){
|
||||
self.postMessage( msg, Array.from(xferList) );
|
||||
xferList.length = 0;
|
||||
}else{
|
||||
self.postMessage(msg);
|
||||
}
|
||||
},
|
||||
/** Map of DB IDs to DBs. */
|
||||
dbs: Object.create(null),
|
||||
/** Fetch the DB for the given id. Throw if require=true and the
|
||||
id is not valid, else return the db or undefined. */
|
||||
getDb: function(id,require=true){
|
||||
return this.dbs[id]
|
||||
|| (require ? toss("Unknown (or closed) DB ID:",id) : undefined);
|
||||
}
|
||||
};
|
||||
|
||||
/** Throws if the given db is falsy or not opened, else returns its
|
||||
argument. */
|
||||
const affirmDbOpen = function(db = wState.dbList[0]){
|
||||
return (db && db.pointer) ? db : toss("DB is not opened.");
|
||||
};
|
||||
|
||||
/** Extract dbId from the given message payload. */
|
||||
const getMsgDb = function(msgData,affirmExists=true){
|
||||
const db = wState.getDb(msgData.dbId,false) || wState.dbList[0];
|
||||
return affirmExists ? affirmDbOpen(db) : db;
|
||||
};
|
||||
|
||||
const getDefaultDbId = function(){
|
||||
return wState.dbList[0] && getDbId(wState.dbList[0]);
|
||||
};
|
||||
|
||||
const guessVfs = function(filename){
|
||||
const m = /^file:.+(vfs=(\w+))/.exec(filename);
|
||||
return sqlite3.capi.sqlite3_vfs_find(m ? m[2] : 0);
|
||||
};
|
||||
|
||||
const isSpecialDbFilename = (n)=>{
|
||||
return ""===n || ':'===n[0];
|
||||
};
|
||||
|
||||
/**
|
||||
A level of "organizational abstraction" for the Worker1
|
||||
API. Each method in this object must map directly to a Worker1
|
||||
message type key. The onmessage() dispatcher attempts to
|
||||
dispatch all inbound messages to a method of this object,
|
||||
passing it the event.data part of the inbound event object. All
|
||||
methods must return a plain Object containing any result
|
||||
state, which the dispatcher may amend. All methods must throw
|
||||
on error.
|
||||
*/
|
||||
const wMsgHandler = {
|
||||
open: function(ev){
|
||||
const oargs = Object.create(null), args = (ev.args || Object.create(null));
|
||||
if(args.simulateError){ // undocumented internal testing option
|
||||
toss("Throwing because of simulateError flag.");
|
||||
}
|
||||
const rc = Object.create(null);
|
||||
const pDir = sqlite3.capi.sqlite3_wasmfs_opfs_dir();
|
||||
let byteArray, pVfs;
|
||||
oargs.vfs = args.vfs;
|
||||
if(isSpecialDbFilename(args.filename)){
|
||||
oargs.filename = args.filename || "";
|
||||
}else{
|
||||
oargs.filename = args.filename;
|
||||
byteArray = args.byteArray;
|
||||
if(byteArray) pVfs = guessVfs(args.filename);
|
||||
}
|
||||
if(pVfs){
|
||||
/* 2022-11-02: this feature is as-yet untested except that
|
||||
sqlite3_wasm_vfs_create_file() has been tested from the
|
||||
browser dev console. */
|
||||
let pMem;
|
||||
try{
|
||||
pMem = sqlite3.wasm.allocFromTypedArray(byteArray);
|
||||
const rc = sqlite3.wasm.sqlite3_wasm_vfs_create_file(
|
||||
pVfs, oargs.filename, pMem, byteArray.byteLength
|
||||
);
|
||||
if(rc) sqlite3.SQLite3Error.toss(rc);
|
||||
}catch(e){
|
||||
throw new sqlite3.SQLite3Error(
|
||||
e.name+' creating '+args.filename+": "+e.message, {
|
||||
cause: e
|
||||
}
|
||||
);
|
||||
}finally{
|
||||
if(pMem) sqlite3.wasm.dealloc(pMem);
|
||||
}
|
||||
}
|
||||
const db = wState.open(oargs);
|
||||
rc.filename = db.filename;
|
||||
rc.persistent = (!!pDir && db.filename.startsWith(pDir+'/'))
|
||||
|| !!sqlite3.capi.sqlite3_js_db_uses_vfs(db.pointer, "opfs");
|
||||
rc.dbId = getDbId(db);
|
||||
rc.vfs = db.dbVfsName();
|
||||
return rc;
|
||||
},
|
||||
|
||||
close: function(ev){
|
||||
const db = getMsgDb(ev,false);
|
||||
const response = {
|
||||
filename: db && db.filename
|
||||
};
|
||||
if(db){
|
||||
const doUnlink = ((ev.args && 'object'===typeof ev.args)
|
||||
? !!ev.args.unlink : false);
|
||||
wState.close(db, doUnlink);
|
||||
}
|
||||
return response;
|
||||
},
|
||||
|
||||
exec: function(ev){
|
||||
const rc = (
|
||||
'string'===typeof ev.args
|
||||
) ? {sql: ev.args} : (ev.args || Object.create(null));
|
||||
if('stmt'===rc.rowMode){
|
||||
toss("Invalid rowMode for 'exec': stmt mode",
|
||||
"does not work in the Worker API.");
|
||||
}else if(!rc.sql){
|
||||
toss("'exec' requires input SQL.");
|
||||
}
|
||||
const db = getMsgDb(ev);
|
||||
if(rc.callback || Array.isArray(rc.resultRows)){
|
||||
// Part of a copy-avoidance optimization for blobs
|
||||
db._blobXfer = wState.xfer;
|
||||
}
|
||||
const theCallback = rc.callback;
|
||||
let rowNumber = 0;
|
||||
const hadColNames = !!rc.columnNames;
|
||||
if('string' === typeof theCallback){
|
||||
if(!hadColNames) rc.columnNames = [];
|
||||
/* Treat this as a worker message type and post each
|
||||
row as a message of that type. */
|
||||
rc.callback = function(row,stmt){
|
||||
wState.post({
|
||||
type: theCallback,
|
||||
columnNames: rc.columnNames,
|
||||
rowNumber: ++rowNumber,
|
||||
row: row
|
||||
}, wState.xfer);
|
||||
}
|
||||
}
|
||||
try {
|
||||
db.exec(rc);
|
||||
if(rc.callback instanceof Function){
|
||||
rc.callback = theCallback;
|
||||
/* Post a sentinel message to tell the client that the end
|
||||
of the result set has been reached (possibly with zero
|
||||
rows). */
|
||||
wState.post({
|
||||
type: theCallback,
|
||||
columnNames: rc.columnNames,
|
||||
rowNumber: null /*null to distinguish from "property not set"*/,
|
||||
row: undefined /*undefined because null is a legal row value
|
||||
for some rowType values, but undefined is not*/
|
||||
});
|
||||
}
|
||||
}finally{
|
||||
delete db._blobXfer;
|
||||
if(rc.callback) rc.callback = theCallback;
|
||||
}
|
||||
return rc;
|
||||
}/*exec()*/,
|
||||
|
||||
'config-get': function(){
|
||||
const rc = Object.create(null), src = sqlite3.config;
|
||||
[
|
||||
'wasmfsOpfsDir', 'bigIntEnabled'
|
||||
].forEach(function(k){
|
||||
if(Object.getOwnPropertyDescriptor(src, k)) rc[k] = src[k];
|
||||
});
|
||||
rc.wasmfsOpfsEnabled = !!sqlite3.capi.sqlite3_wasmfs_opfs_dir();
|
||||
rc.version = sqlite3.version;
|
||||
rc.vfsList = sqlite3.capi.sqlite3_js_vfs_list();
|
||||
rc.opfsEnabled = !!sqlite3.opfs;
|
||||
return rc;
|
||||
},
|
||||
|
||||
/**
|
||||
Exports the database to a byte array, as per
|
||||
sqlite3_serialize(). Response is an object:
|
||||
|
||||
{
|
||||
byteArray: Uint8Array (db file contents),
|
||||
filename: the current db filename,
|
||||
mimetype: 'application/x-sqlite3'
|
||||
}
|
||||
*/
|
||||
export: function(ev){
|
||||
const db = getMsgDb(ev);
|
||||
const response = {
|
||||
byteArray: sqlite3.capi.sqlite3_js_db_export(db.pointer),
|
||||
filename: db.filename,
|
||||
mimetype: 'application/x-sqlite3'
|
||||
};
|
||||
wState.xfer.push(response.byteArray.buffer);
|
||||
return response;
|
||||
}/*export()*/,
|
||||
|
||||
toss: function(ev){
|
||||
toss("Testing worker exception");
|
||||
},
|
||||
|
||||
'opfs-tree': async function(ev){
|
||||
if(!sqlite3.opfs) toss("OPFS support is unavailable.");
|
||||
const response = await sqlite3.opfs.treeList();
|
||||
return response;
|
||||
}
|
||||
}/*wMsgHandler*/;
|
||||
|
||||
self.onmessage = async function(ev){
|
||||
ev = ev.data;
|
||||
let result, dbId = ev.dbId, evType = ev.type;
|
||||
const arrivalTime = performance.now();
|
||||
try {
|
||||
if(wMsgHandler.hasOwnProperty(evType) &&
|
||||
wMsgHandler[evType] instanceof Function){
|
||||
result = await wMsgHandler[evType](ev);
|
||||
}else{
|
||||
toss("Unknown db worker message type:",ev.type);
|
||||
}
|
||||
}catch(err){
|
||||
evType = 'error';
|
||||
result = {
|
||||
operation: ev.type,
|
||||
message: err.message,
|
||||
errorClass: err.name,
|
||||
input: ev
|
||||
};
|
||||
if(err.stack){
|
||||
result.stack = ('string'===typeof err.stack)
|
||||
? err.stack.split(/\n\s*/) : err.stack;
|
||||
}
|
||||
if(0) console.warn("Worker is propagating an exception to main thread.",
|
||||
"Reporting it _here_ for the stack trace:",err,result);
|
||||
}
|
||||
if(!dbId){
|
||||
dbId = result.dbId/*from 'open' cmd*/
|
||||
|| getDefaultDbId();
|
||||
}
|
||||
// Timing info is primarily for use in testing this API. It's not part of
|
||||
// the public API. arrivalTime = when the worker got the message.
|
||||
wState.post({
|
||||
type: evType,
|
||||
dbId: dbId,
|
||||
messageId: ev.messageId,
|
||||
workerReceivedTime: arrivalTime,
|
||||
workerRespondTime: performance.now(),
|
||||
departureTime: ev.departureTime,
|
||||
// TODO: move the timing bits into...
|
||||
//timing:{
|
||||
// departure: ev.departureTime,
|
||||
// workerReceived: arrivalTime,
|
||||
// workerResponse: performance.now();
|
||||
//},
|
||||
result: result
|
||||
}, wState.xfer);
|
||||
};
|
||||
self.postMessage({type:'sqlite3-api',result:'worker1-ready'});
|
||||
}.bind({self, sqlite3});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
** LICENSE for the sqlite3 WebAssembly/JavaScript APIs.
|
||||
**
|
||||
** This bundle (typically released as sqlite3.js or sqlite3-wasmfs.js)
|
||||
** is an amalgamation of JavaScript source code from two projects:
|
||||
**
|
||||
** 1) https://emscripten.org: the Emscripten "glue code" is covered by
|
||||
** the terms of the MIT license and University of Illinois/NCSA
|
||||
** Open Source License, as described at:
|
||||
**
|
||||
** https://emscripten.org/docs/introducing_emscripten/emscripten_license.html
|
||||
**
|
||||
** 2) https://sqlite.org: all code and documentation labeled as being
|
||||
** from this source are released under the same terms as the sqlite3
|
||||
** C library:
|
||||
**
|
||||
** 2022-10-16
|
||||
**
|
||||
** The author disclaims copyright to this source code. In place of a
|
||||
** legal notice, here is a blessing:
|
||||
**
|
||||
** * May you do good and not evil.
|
||||
** * May you find forgiveness for yourself and forgive others.
|
||||
** * May you share freely, never taking more than you give.
|
||||
*/
|
||||
@@ -0,0 +1,830 @@
|
||||
/*
|
||||
2022-09-16
|
||||
|
||||
The author disclaims copyright to this source code. In place of a
|
||||
legal notice, here is a blessing:
|
||||
|
||||
* May you do good and not evil.
|
||||
* May you find forgiveness for yourself and forgive others.
|
||||
* May you share freely, never taking more than you give.
|
||||
|
||||
***********************************************************************
|
||||
|
||||
A Worker which manages asynchronous OPFS handles on behalf of a
|
||||
synchronous API which controls it via a combination of Worker
|
||||
messages, SharedArrayBuffer, and Atomics. It is the asynchronous
|
||||
counterpart of the API defined in sqlite3-api-opfs.js.
|
||||
|
||||
Highly indebted to:
|
||||
|
||||
https://github.com/rhashimoto/wa-sqlite/blob/master/src/examples/OriginPrivateFileSystemVFS.js
|
||||
|
||||
for demonstrating how to use the OPFS APIs.
|
||||
|
||||
This file is to be loaded as a Worker. It does not have any direct
|
||||
access to the sqlite3 JS/WASM bits, so any bits which it needs (most
|
||||
notably SQLITE_xxx integer codes) have to be imported into it via an
|
||||
initialization process.
|
||||
|
||||
This file represents an implementation detail of a larger piece of
|
||||
code, and not a public interface. Its details may change at any time
|
||||
and are not intended to be used by any client-level code.
|
||||
*/
|
||||
"use strict";
|
||||
const toss = function(...args){throw new Error(args.join(' '))};
|
||||
if(self.window === self){
|
||||
toss("This code cannot run from the main thread.",
|
||||
"Load it as a Worker from a separate Worker.");
|
||||
}else if(!navigator.storage.getDirectory){
|
||||
toss("This API requires navigator.storage.getDirectory.");
|
||||
}
|
||||
|
||||
/**
|
||||
Will hold state copied to this object from the syncronous side of
|
||||
this API.
|
||||
*/
|
||||
const state = Object.create(null);
|
||||
|
||||
/**
|
||||
verbose:
|
||||
|
||||
0 = no logging output
|
||||
1 = only errors
|
||||
2 = warnings and errors
|
||||
3 = debug, warnings, and errors
|
||||
*/
|
||||
state.verbose = 2;
|
||||
|
||||
const loggers = {
|
||||
0:console.error.bind(console),
|
||||
1:console.warn.bind(console),
|
||||
2:console.log.bind(console)
|
||||
};
|
||||
const logImpl = (level,...args)=>{
|
||||
if(state.verbose>level) loggers[level]("OPFS asyncer:",...args);
|
||||
};
|
||||
const log = (...args)=>logImpl(2, ...args);
|
||||
const warn = (...args)=>logImpl(1, ...args);
|
||||
const error = (...args)=>logImpl(0, ...args);
|
||||
const metrics = Object.create(null);
|
||||
metrics.reset = ()=>{
|
||||
let k;
|
||||
const r = (m)=>(m.count = m.time = m.wait = 0);
|
||||
for(k in state.opIds){
|
||||
r(metrics[k] = Object.create(null));
|
||||
}
|
||||
let s = metrics.s11n = Object.create(null);
|
||||
s = s.serialize = Object.create(null);
|
||||
s.count = s.time = 0;
|
||||
s = metrics.s11n.deserialize = Object.create(null);
|
||||
s.count = s.time = 0;
|
||||
};
|
||||
metrics.dump = ()=>{
|
||||
let k, n = 0, t = 0, w = 0;
|
||||
for(k in state.opIds){
|
||||
const m = metrics[k];
|
||||
n += m.count;
|
||||
t += m.time;
|
||||
w += m.wait;
|
||||
m.avgTime = (m.count && m.time) ? (m.time / m.count) : 0;
|
||||
}
|
||||
console.log(self.location.href,
|
||||
"metrics for",self.location.href,":\n",
|
||||
metrics,
|
||||
"\nTotal of",n,"op(s) for",t,"ms",
|
||||
"approx",w,"ms spent waiting on OPFS APIs.");
|
||||
console.log("Serialization metrics:",metrics.s11n);
|
||||
};
|
||||
|
||||
/**
|
||||
__openFiles is a map of sqlite3_file pointers (integers) to
|
||||
metadata related to a given OPFS file handles. The pointers are, in
|
||||
this side of the interface, opaque file handle IDs provided by the
|
||||
synchronous part of this constellation. Each value is an object
|
||||
with a structure demonstrated in the xOpen() impl.
|
||||
*/
|
||||
const __openFiles = Object.create(null);
|
||||
/**
|
||||
__autoLocks is a Set of sqlite3_file pointers (integers) which were
|
||||
"auto-locked". i.e. those for which we obtained a sync access
|
||||
handle without an explicit xLock() call. Such locks will be
|
||||
released during db connection idle time, whereas a sync access
|
||||
handle obtained via xLock(), or subsequently xLock()'d after
|
||||
auto-acquisition, will not be released until xUnlock() is called.
|
||||
|
||||
Maintenance reminder: if we relinquish auto-locks at the end of the
|
||||
operation which acquires them, we pay a massive performance
|
||||
penalty: speedtest1 benchmarks take up to 4x as long. By delaying
|
||||
the lock release until idle time, the hit is negligible.
|
||||
*/
|
||||
const __autoLocks = new Set();
|
||||
|
||||
/**
|
||||
Expects an OPFS file path. It gets resolved, such that ".."
|
||||
components are properly expanded, and returned. If the 2nd arg is
|
||||
true, the result is returned as an array of path elements, else an
|
||||
absolute path string is returned.
|
||||
*/
|
||||
const getResolvedPath = function(filename,splitIt){
|
||||
const p = new URL(
|
||||
filename, 'file://irrelevant'
|
||||
).pathname;
|
||||
return splitIt ? p.split('/').filter((v)=>!!v) : p;
|
||||
};
|
||||
|
||||
/**
|
||||
Takes the absolute path to a filesystem element. Returns an array
|
||||
of [handleOfContainingDir, filename]. If the 2nd argument is truthy
|
||||
then each directory element leading to the file is created along
|
||||
the way. Throws if any creation or resolution fails.
|
||||
*/
|
||||
const getDirForFilename = async function f(absFilename, createDirs = false){
|
||||
const path = getResolvedPath(absFilename, true);
|
||||
const filename = path.pop();
|
||||
let dh = state.rootDir;
|
||||
for(const dirName of path){
|
||||
if(dirName){
|
||||
dh = await dh.getDirectoryHandle(dirName, {create: !!createDirs});
|
||||
}
|
||||
}
|
||||
return [dh, filename];
|
||||
};
|
||||
|
||||
/**
|
||||
An error class specifically for use with getSyncHandle(), the goal
|
||||
of which is to eventually be able to distinguish unambiguously
|
||||
between locking-related failures and other types, noting that we
|
||||
cannot currently do so because createSyncAccessHandle() does not
|
||||
define its exceptions in the required level of detail.
|
||||
*/
|
||||
class GetSyncHandleError extends Error {
|
||||
constructor(errorObject, ...msg){
|
||||
super();
|
||||
this.error = errorObject;
|
||||
this.message = [
|
||||
...msg, ': Original exception ['+errorObject.name+']:',
|
||||
errorObject.message
|
||||
].join(' ');
|
||||
this.name = 'GetSyncHandleError';
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
Returns the sync access handle associated with the given file
|
||||
handle object (which must be a valid handle object, as created by
|
||||
xOpen()), lazily opening it if needed.
|
||||
|
||||
In order to help alleviate cross-tab contention for a dabase,
|
||||
if an exception is thrown while acquiring the handle, this routine
|
||||
will wait briefly and try again, up to 3 times. If acquisition
|
||||
still fails at that point it will give up and propagate the
|
||||
exception.
|
||||
*/
|
||||
const getSyncHandle = async (fh)=>{
|
||||
if(!fh.syncHandle){
|
||||
const t = performance.now();
|
||||
log("Acquiring sync handle for",fh.filenameAbs);
|
||||
const maxTries = 4, msBase = 300;
|
||||
let i = 1, ms = msBase;
|
||||
for(; true; ms = msBase * ++i){
|
||||
try {
|
||||
//if(i<3) toss("Just testing getSyncHandle() wait-and-retry.");
|
||||
//TODO? A config option which tells it to throw here
|
||||
//randomly every now and then, for testing purposes.
|
||||
fh.syncHandle = await fh.fileHandle.createSyncAccessHandle();
|
||||
break;
|
||||
}catch(e){
|
||||
if(i === maxTries){
|
||||
throw new GetSyncHandleError(
|
||||
e, "Error getting sync handle.",maxTries,
|
||||
"attempts failed.",fh.filenameAbs
|
||||
);
|
||||
}
|
||||
warn("Error getting sync handle. Waiting",ms,
|
||||
"ms and trying again.",fh.filenameAbs,e);
|
||||
Atomics.wait(state.sabOPView, state.opIds.retry, 0, ms);
|
||||
}
|
||||
}
|
||||
log("Got sync handle for",fh.filenameAbs,'in',performance.now() - t,'ms');
|
||||
if(!fh.xLock){
|
||||
__autoLocks.add(fh.fid);
|
||||
log("Auto-locked",fh.fid,fh.filenameAbs);
|
||||
}
|
||||
}
|
||||
return fh.syncHandle;
|
||||
};
|
||||
|
||||
/**
|
||||
If the given file-holding object has a sync handle attached to it,
|
||||
that handle is remove and asynchronously closed. Though it may
|
||||
sound sensible to continue work as soon as the close() returns
|
||||
(noting that it's asynchronous), doing so can cause operations
|
||||
performed soon afterwards, e.g. a call to getSyncHandle() to fail
|
||||
because they may happen out of order from the close(). OPFS does
|
||||
not guaranty that the actual order of operations is retained in
|
||||
such cases. i.e. always "await" on the result of this function.
|
||||
*/
|
||||
const closeSyncHandle = async (fh)=>{
|
||||
if(fh.syncHandle){
|
||||
log("Closing sync handle for",fh.filenameAbs);
|
||||
const h = fh.syncHandle;
|
||||
delete fh.syncHandle;
|
||||
delete fh.xLock;
|
||||
__autoLocks.delete(fh.fid);
|
||||
return h.close();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
A proxy for closeSyncHandle() which is guaranteed to not throw.
|
||||
|
||||
This function is part of a lock/unlock step in functions which
|
||||
require a sync access handle but may be called without xLock()
|
||||
having been called first. Such calls need to release that
|
||||
handle to avoid locking the file for all of time. This is an
|
||||
_attempt_ at reducing cross-tab contention but it may prove
|
||||
to be more of a problem than a solution and may need to be
|
||||
removed.
|
||||
*/
|
||||
const closeSyncHandleNoThrow = async (fh)=>{
|
||||
try{await closeSyncHandle(fh)}
|
||||
catch(e){
|
||||
warn("closeSyncHandleNoThrow() ignoring:",e,fh);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
Stores the given value at state.sabOPView[state.opIds.rc] and then
|
||||
Atomics.notify()'s it.
|
||||
*/
|
||||
const storeAndNotify = (opName, value)=>{
|
||||
log(opName+"() => notify(",value,")");
|
||||
Atomics.store(state.sabOPView, state.opIds.rc, value);
|
||||
Atomics.notify(state.sabOPView, state.opIds.rc);
|
||||
};
|
||||
|
||||
/**
|
||||
Throws if fh is a file-holding object which is flagged as read-only.
|
||||
*/
|
||||
const affirmNotRO = function(opName,fh){
|
||||
if(fh.readOnly) toss(opName+"(): File is read-only: "+fh.filenameAbs);
|
||||
};
|
||||
const affirmLocked = function(opName,fh){
|
||||
//if(!fh.syncHandle) toss(opName+"(): File does not have a lock: "+fh.filenameAbs);
|
||||
/**
|
||||
Currently a no-op, as speedtest1 triggers xRead() without a
|
||||
lock (that seems like a bug but it's currently uninvestigated).
|
||||
This means, however, that some OPFS VFS routines may trigger
|
||||
acquisition of a lock but never let it go until xUnlock() is
|
||||
called (which it likely won't be if xLock() was not called).
|
||||
*/
|
||||
};
|
||||
|
||||
/**
|
||||
We track 2 different timers: the "metrics" timer records how much
|
||||
time we spend performing work. The "wait" timer records how much
|
||||
time we spend waiting on the underlying OPFS timer. See the calls
|
||||
to mTimeStart(), mTimeEnd(), wTimeStart(), and wTimeEnd()
|
||||
throughout this file to see how they're used.
|
||||
*/
|
||||
const __mTimer = Object.create(null);
|
||||
__mTimer.op = undefined;
|
||||
__mTimer.start = undefined;
|
||||
const mTimeStart = (op)=>{
|
||||
__mTimer.start = performance.now();
|
||||
__mTimer.op = op;
|
||||
//metrics[op] || toss("Maintenance required: missing metrics for",op);
|
||||
++metrics[op].count;
|
||||
};
|
||||
const mTimeEnd = ()=>(
|
||||
metrics[__mTimer.op].time += performance.now() - __mTimer.start
|
||||
);
|
||||
const __wTimer = Object.create(null);
|
||||
__wTimer.op = undefined;
|
||||
__wTimer.start = undefined;
|
||||
const wTimeStart = (op)=>{
|
||||
__wTimer.start = performance.now();
|
||||
__wTimer.op = op;
|
||||
//metrics[op] || toss("Maintenance required: missing metrics for",op);
|
||||
};
|
||||
const wTimeEnd = ()=>(
|
||||
metrics[__wTimer.op].wait += performance.now() - __wTimer.start
|
||||
);
|
||||
|
||||
/**
|
||||
Gets set to true by the 'opfs-async-shutdown' command to quit the
|
||||
wait loop. This is only intended for debugging purposes: we cannot
|
||||
inspect this file's state while the tight waitLoop() is running and
|
||||
need a way to stop that loop for introspection purposes.
|
||||
*/
|
||||
let flagAsyncShutdown = false;
|
||||
|
||||
|
||||
/**
|
||||
Asynchronous wrappers for sqlite3_vfs and sqlite3_io_methods
|
||||
methods, as well as helpers like mkdir(). Maintenance reminder:
|
||||
members are in alphabetical order to simplify finding them.
|
||||
*/
|
||||
const vfsAsyncImpls = {
|
||||
'opfs-async-metrics': async ()=>{
|
||||
mTimeStart('opfs-async-metrics');
|
||||
metrics.dump();
|
||||
storeAndNotify('opfs-async-metrics', 0);
|
||||
mTimeEnd();
|
||||
},
|
||||
'opfs-async-shutdown': async ()=>{
|
||||
flagAsyncShutdown = true;
|
||||
storeAndNotify('opfs-async-shutdown', 0);
|
||||
},
|
||||
mkdir: async (dirname)=>{
|
||||
mTimeStart('mkdir');
|
||||
let rc = 0;
|
||||
wTimeStart('mkdir');
|
||||
try {
|
||||
await getDirForFilename(dirname+"/filepart", true);
|
||||
}catch(e){
|
||||
state.s11n.storeException(2,e);
|
||||
rc = state.sq3Codes.SQLITE_IOERR;
|
||||
}finally{
|
||||
wTimeEnd();
|
||||
}
|
||||
storeAndNotify('mkdir', rc);
|
||||
mTimeEnd();
|
||||
},
|
||||
xAccess: async (filename)=>{
|
||||
mTimeStart('xAccess');
|
||||
/* OPFS cannot support the full range of xAccess() queries sqlite3
|
||||
calls for. We can essentially just tell if the file is
|
||||
accessible, but if it is it's automatically writable (unless
|
||||
it's locked, which we cannot(?) know without trying to open
|
||||
it). OPFS does not have the notion of read-only.
|
||||
|
||||
The return semantics of this function differ from sqlite3's
|
||||
xAccess semantics because we are limited in what we can
|
||||
communicate back to our synchronous communication partner: 0 =
|
||||
accessible, non-0 means not accessible.
|
||||
*/
|
||||
let rc = 0;
|
||||
wTimeStart('xAccess');
|
||||
try{
|
||||
const [dh, fn] = await getDirForFilename(filename);
|
||||
await dh.getFileHandle(fn);
|
||||
}catch(e){
|
||||
state.s11n.storeException(2,e);
|
||||
rc = state.sq3Codes.SQLITE_IOERR;
|
||||
}finally{
|
||||
wTimeEnd();
|
||||
}
|
||||
storeAndNotify('xAccess', rc);
|
||||
mTimeEnd();
|
||||
},
|
||||
xClose: async function(fid/*sqlite3_file pointer*/){
|
||||
const opName = 'xClose';
|
||||
mTimeStart(opName);
|
||||
__autoLocks.delete(fid);
|
||||
const fh = __openFiles[fid];
|
||||
let rc = 0;
|
||||
wTimeStart(opName);
|
||||
if(fh){
|
||||
delete __openFiles[fid];
|
||||
await closeSyncHandle(fh);
|
||||
if(fh.deleteOnClose){
|
||||
try{ await fh.dirHandle.removeEntry(fh.filenamePart) }
|
||||
catch(e){ warn("Ignoring dirHandle.removeEntry() failure of",fh,e) }
|
||||
}
|
||||
}else{
|
||||
state.s11n.serialize();
|
||||
rc = state.sq3Codes.SQLITE_NOTFOUND;
|
||||
}
|
||||
wTimeEnd();
|
||||
storeAndNotify(opName, rc);
|
||||
mTimeEnd();
|
||||
},
|
||||
xDelete: async function(...args){
|
||||
mTimeStart('xDelete');
|
||||
const rc = await vfsAsyncImpls.xDeleteNoWait(...args);
|
||||
storeAndNotify('xDelete', rc);
|
||||
mTimeEnd();
|
||||
},
|
||||
xDeleteNoWait: async function(filename, syncDir = 0, recursive = false){
|
||||
/* The syncDir flag is, for purposes of the VFS API's semantics,
|
||||
ignored here. However, if it has the value 0x1234 then: after
|
||||
deleting the given file, recursively try to delete any empty
|
||||
directories left behind in its wake (ignoring any errors and
|
||||
stopping at the first failure).
|
||||
|
||||
That said: we don't know for sure that removeEntry() fails if
|
||||
the dir is not empty because the API is not documented. It has,
|
||||
however, a "recursive" flag which defaults to false, so
|
||||
presumably it will fail if the dir is not empty and that flag
|
||||
is false.
|
||||
*/
|
||||
let rc = 0;
|
||||
wTimeStart('xDelete');
|
||||
try {
|
||||
while(filename){
|
||||
const [hDir, filenamePart] = await getDirForFilename(filename, false);
|
||||
if(!filenamePart) break;
|
||||
await hDir.removeEntry(filenamePart, {recursive});
|
||||
if(0x1234 !== syncDir) break;
|
||||
recursive = false;
|
||||
filename = getResolvedPath(filename, true);
|
||||
filename.pop();
|
||||
filename = filename.join('/');
|
||||
}
|
||||
}catch(e){
|
||||
state.s11n.storeException(2,e);
|
||||
rc = state.sq3Codes.SQLITE_IOERR_DELETE;
|
||||
}
|
||||
wTimeEnd();
|
||||
return rc;
|
||||
},
|
||||
xFileSize: async function(fid/*sqlite3_file pointer*/){
|
||||
mTimeStart('xFileSize');
|
||||
const fh = __openFiles[fid];
|
||||
let rc;
|
||||
wTimeStart('xFileSize');
|
||||
try{
|
||||
affirmLocked('xFileSize',fh);
|
||||
rc = await (await getSyncHandle(fh)).getSize();
|
||||
state.s11n.serialize(Number(rc));
|
||||
rc = 0;
|
||||
}catch(e){
|
||||
state.s11n.storeException(2,e);
|
||||
rc = state.sq3Codes.SQLITE_IOERR;
|
||||
}
|
||||
wTimeEnd();
|
||||
storeAndNotify('xFileSize', rc);
|
||||
mTimeEnd();
|
||||
},
|
||||
xLock: async function(fid/*sqlite3_file pointer*/,
|
||||
lockType/*SQLITE_LOCK_...*/){
|
||||
mTimeStart('xLock');
|
||||
const fh = __openFiles[fid];
|
||||
let rc = 0;
|
||||
const oldLockType = fh.xLock;
|
||||
fh.xLock = lockType;
|
||||
if( !fh.syncHandle ){
|
||||
wTimeStart('xLock');
|
||||
try {
|
||||
await getSyncHandle(fh);
|
||||
__autoLocks.delete(fid);
|
||||
}catch(e){
|
||||
state.s11n.storeException(1,e);
|
||||
rc = state.sq3Codes.SQLITE_IOERR_LOCK;
|
||||
fh.xLock = oldLockType;
|
||||
}
|
||||
wTimeEnd();
|
||||
}
|
||||
storeAndNotify('xLock',rc);
|
||||
mTimeEnd();
|
||||
},
|
||||
xOpen: async function(fid/*sqlite3_file pointer*/, filename,
|
||||
flags/*SQLITE_OPEN_...*/){
|
||||
const opName = 'xOpen';
|
||||
mTimeStart(opName);
|
||||
const deleteOnClose = (state.sq3Codes.SQLITE_OPEN_DELETEONCLOSE & flags);
|
||||
const create = (state.sq3Codes.SQLITE_OPEN_CREATE & flags);
|
||||
wTimeStart('xOpen');
|
||||
try{
|
||||
let hDir, filenamePart;
|
||||
try {
|
||||
[hDir, filenamePart] = await getDirForFilename(filename, !!create);
|
||||
}catch(e){
|
||||
state.s11n.storeException(1,e);
|
||||
storeAndNotify(opName, state.sq3Codes.SQLITE_NOTFOUND);
|
||||
mTimeEnd();
|
||||
wTimeEnd();
|
||||
return;
|
||||
}
|
||||
const hFile = await hDir.getFileHandle(filenamePart, {create});
|
||||
/**
|
||||
wa-sqlite, at this point, grabs a SyncAccessHandle and
|
||||
assigns it to the syncHandle prop of the file state
|
||||
object, but only for certain cases and it's unclear why it
|
||||
places that limitation on it.
|
||||
*/
|
||||
wTimeEnd();
|
||||
__openFiles[fid] = Object.assign(Object.create(null),{
|
||||
fid: fid,
|
||||
filenameAbs: filename,
|
||||
filenamePart: filenamePart,
|
||||
dirHandle: hDir,
|
||||
fileHandle: hFile,
|
||||
sabView: state.sabFileBufView,
|
||||
readOnly: create
|
||||
? false : (state.sq3Codes.SQLITE_OPEN_READONLY & flags),
|
||||
deleteOnClose: deleteOnClose
|
||||
});
|
||||
storeAndNotify(opName, 0);
|
||||
}catch(e){
|
||||
wTimeEnd();
|
||||
error(opName,e);
|
||||
state.s11n.storeException(1,e);
|
||||
storeAndNotify(opName, state.sq3Codes.SQLITE_IOERR);
|
||||
}
|
||||
mTimeEnd();
|
||||
},
|
||||
xRead: async function(fid/*sqlite3_file pointer*/,n,offset64){
|
||||
mTimeStart('xRead');
|
||||
let rc = 0, nRead;
|
||||
const fh = __openFiles[fid];
|
||||
try{
|
||||
affirmLocked('xRead',fh);
|
||||
wTimeStart('xRead');
|
||||
nRead = (await getSyncHandle(fh)).read(
|
||||
fh.sabView.subarray(0, n),
|
||||
{at: Number(offset64)}
|
||||
);
|
||||
wTimeEnd();
|
||||
if(nRead < n){/* Zero-fill remaining bytes */
|
||||
fh.sabView.fill(0, nRead, n);
|
||||
rc = state.sq3Codes.SQLITE_IOERR_SHORT_READ;
|
||||
}
|
||||
}catch(e){
|
||||
if(undefined===nRead) wTimeEnd();
|
||||
error("xRead() failed",e,fh);
|
||||
state.s11n.storeException(1,e);
|
||||
rc = state.sq3Codes.SQLITE_IOERR_READ;
|
||||
}
|
||||
storeAndNotify('xRead',rc);
|
||||
mTimeEnd();
|
||||
},
|
||||
xSync: async function(fid/*sqlite3_file pointer*/,flags/*ignored*/){
|
||||
mTimeStart('xSync');
|
||||
const fh = __openFiles[fid];
|
||||
let rc = 0;
|
||||
if(!fh.readOnly && fh.syncHandle){
|
||||
try {
|
||||
wTimeStart('xSync');
|
||||
await fh.syncHandle.flush();
|
||||
}catch(e){
|
||||
state.s11n.storeException(2,e);
|
||||
rc = state.sq3Codes.SQLITE_IOERR_FSYNC;
|
||||
}
|
||||
wTimeEnd();
|
||||
}
|
||||
storeAndNotify('xSync',rc);
|
||||
mTimeEnd();
|
||||
},
|
||||
xTruncate: async function(fid/*sqlite3_file pointer*/,size){
|
||||
mTimeStart('xTruncate');
|
||||
let rc = 0;
|
||||
const fh = __openFiles[fid];
|
||||
wTimeStart('xTruncate');
|
||||
try{
|
||||
affirmLocked('xTruncate',fh);
|
||||
affirmNotRO('xTruncate', fh);
|
||||
await (await getSyncHandle(fh)).truncate(size);
|
||||
}catch(e){
|
||||
error("xTruncate():",e,fh);
|
||||
state.s11n.storeException(2,e);
|
||||
rc = state.sq3Codes.SQLITE_IOERR_TRUNCATE;
|
||||
}
|
||||
wTimeEnd();
|
||||
storeAndNotify('xTruncate',rc);
|
||||
mTimeEnd();
|
||||
},
|
||||
xUnlock: async function(fid/*sqlite3_file pointer*/,
|
||||
lockType/*SQLITE_LOCK_...*/){
|
||||
mTimeStart('xUnlock');
|
||||
let rc = 0;
|
||||
const fh = __openFiles[fid];
|
||||
if( state.sq3Codes.SQLITE_LOCK_NONE===lockType
|
||||
&& fh.syncHandle ){
|
||||
wTimeStart('xUnlock');
|
||||
try { await closeSyncHandle(fh) }
|
||||
catch(e){
|
||||
state.s11n.storeException(1,e);
|
||||
rc = state.sq3Codes.SQLITE_IOERR_UNLOCK;
|
||||
}
|
||||
wTimeEnd();
|
||||
}
|
||||
storeAndNotify('xUnlock',rc);
|
||||
mTimeEnd();
|
||||
},
|
||||
xWrite: async function(fid/*sqlite3_file pointer*/,n,offset64){
|
||||
mTimeStart('xWrite');
|
||||
let rc;
|
||||
const fh = __openFiles[fid];
|
||||
wTimeStart('xWrite');
|
||||
try{
|
||||
affirmLocked('xWrite',fh);
|
||||
affirmNotRO('xWrite', fh);
|
||||
rc = (
|
||||
n === (await getSyncHandle(fh))
|
||||
.write(fh.sabView.subarray(0, n),
|
||||
{at: Number(offset64)})
|
||||
) ? 0 : state.sq3Codes.SQLITE_IOERR_WRITE;
|
||||
}catch(e){
|
||||
error("xWrite():",e,fh);
|
||||
state.s11n.storeException(1,e);
|
||||
rc = state.sq3Codes.SQLITE_IOERR_WRITE;
|
||||
}
|
||||
wTimeEnd();
|
||||
storeAndNotify('xWrite',rc);
|
||||
mTimeEnd();
|
||||
}
|
||||
}/*vfsAsyncImpls*/;
|
||||
|
||||
const initS11n = ()=>{
|
||||
/**
|
||||
ACHTUNG: this code is 100% duplicated in the other half of this
|
||||
proxy! The documentation is maintained in the "synchronous half".
|
||||
*/
|
||||
if(state.s11n) return state.s11n;
|
||||
const textDecoder = new TextDecoder(),
|
||||
textEncoder = new TextEncoder('utf-8'),
|
||||
viewU8 = new Uint8Array(state.sabIO, state.sabS11nOffset, state.sabS11nSize),
|
||||
viewDV = new DataView(state.sabIO, state.sabS11nOffset, state.sabS11nSize);
|
||||
state.s11n = Object.create(null);
|
||||
const TypeIds = Object.create(null);
|
||||
TypeIds.number = { id: 1, size: 8, getter: 'getFloat64', setter: 'setFloat64' };
|
||||
TypeIds.bigint = { id: 2, size: 8, getter: 'getBigInt64', setter: 'setBigInt64' };
|
||||
TypeIds.boolean = { id: 3, size: 4, getter: 'getInt32', setter: 'setInt32' };
|
||||
TypeIds.string = { id: 4 };
|
||||
const getTypeId = (v)=>(
|
||||
TypeIds[typeof v]
|
||||
|| toss("Maintenance required: this value type cannot be serialized.",v)
|
||||
);
|
||||
const getTypeIdById = (tid)=>{
|
||||
switch(tid){
|
||||
case TypeIds.number.id: return TypeIds.number;
|
||||
case TypeIds.bigint.id: return TypeIds.bigint;
|
||||
case TypeIds.boolean.id: return TypeIds.boolean;
|
||||
case TypeIds.string.id: return TypeIds.string;
|
||||
default: toss("Invalid type ID:",tid);
|
||||
}
|
||||
};
|
||||
state.s11n.deserialize = function(clear=false){
|
||||
++metrics.s11n.deserialize.count;
|
||||
const t = performance.now();
|
||||
const argc = viewU8[0];
|
||||
const rc = argc ? [] : null;
|
||||
if(argc){
|
||||
const typeIds = [];
|
||||
let offset = 1, i, n, v;
|
||||
for(i = 0; i < argc; ++i, ++offset){
|
||||
typeIds.push(getTypeIdById(viewU8[offset]));
|
||||
}
|
||||
for(i = 0; i < argc; ++i){
|
||||
const t = typeIds[i];
|
||||
if(t.getter){
|
||||
v = viewDV[t.getter](offset, state.littleEndian);
|
||||
offset += t.size;
|
||||
}else{/*String*/
|
||||
n = viewDV.getInt32(offset, state.littleEndian);
|
||||
offset += 4;
|
||||
v = textDecoder.decode(viewU8.slice(offset, offset+n));
|
||||
offset += n;
|
||||
}
|
||||
rc.push(v);
|
||||
}
|
||||
}
|
||||
if(clear) viewU8[0] = 0;
|
||||
//log("deserialize:",argc, rc);
|
||||
metrics.s11n.deserialize.time += performance.now() - t;
|
||||
return rc;
|
||||
};
|
||||
state.s11n.serialize = function(...args){
|
||||
const t = performance.now();
|
||||
++metrics.s11n.serialize.count;
|
||||
if(args.length){
|
||||
//log("serialize():",args);
|
||||
const typeIds = [];
|
||||
let i = 0, offset = 1;
|
||||
viewU8[0] = args.length & 0xff /* header = # of args */;
|
||||
for(; i < args.length; ++i, ++offset){
|
||||
/* Write the TypeIds.id value into the next args.length
|
||||
bytes. */
|
||||
typeIds.push(getTypeId(args[i]));
|
||||
viewU8[offset] = typeIds[i].id;
|
||||
}
|
||||
for(i = 0; i < args.length; ++i) {
|
||||
/* Deserialize the following bytes based on their
|
||||
corresponding TypeIds.id from the header. */
|
||||
const t = typeIds[i];
|
||||
if(t.setter){
|
||||
viewDV[t.setter](offset, args[i], state.littleEndian);
|
||||
offset += t.size;
|
||||
}else{/*String*/
|
||||
const s = textEncoder.encode(args[i]);
|
||||
viewDV.setInt32(offset, s.byteLength, state.littleEndian);
|
||||
offset += 4;
|
||||
viewU8.set(s, offset);
|
||||
offset += s.byteLength;
|
||||
}
|
||||
}
|
||||
//log("serialize() result:",viewU8.slice(0,offset));
|
||||
}else{
|
||||
viewU8[0] = 0;
|
||||
}
|
||||
metrics.s11n.serialize.time += performance.now() - t;
|
||||
};
|
||||
|
||||
state.s11n.storeException = state.asyncS11nExceptions
|
||||
? ((priority,e)=>{
|
||||
if(priority<=state.asyncS11nExceptions){
|
||||
state.s11n.serialize([e.name,': ',e.message].join(""));
|
||||
}
|
||||
})
|
||||
: ()=>{};
|
||||
|
||||
return state.s11n;
|
||||
}/*initS11n()*/;
|
||||
|
||||
const waitLoop = async function f(){
|
||||
const opHandlers = Object.create(null);
|
||||
for(let k of Object.keys(state.opIds)){
|
||||
const vi = vfsAsyncImpls[k];
|
||||
if(!vi) continue;
|
||||
const o = Object.create(null);
|
||||
opHandlers[state.opIds[k]] = o;
|
||||
o.key = k;
|
||||
o.f = vi;
|
||||
}
|
||||
/**
|
||||
waitTime is how long (ms) to wait for each Atomics.wait().
|
||||
We need to wake up periodically to give the thread a chance
|
||||
to do other things.
|
||||
*/
|
||||
const waitTime = 500;
|
||||
while(!flagAsyncShutdown){
|
||||
try {
|
||||
if('timed-out'===Atomics.wait(
|
||||
state.sabOPView, state.opIds.whichOp, 0, waitTime
|
||||
)){
|
||||
if(__autoLocks.size){
|
||||
/* Release all auto-locks. */
|
||||
for(const fid of __autoLocks){
|
||||
const fh = __openFiles[fid];
|
||||
await closeSyncHandleNoThrow(fh);
|
||||
log("Auto-unlocked",fid,fh.filenameAbs);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const opId = Atomics.load(state.sabOPView, state.opIds.whichOp);
|
||||
Atomics.store(state.sabOPView, state.opIds.whichOp, 0);
|
||||
const hnd = opHandlers[opId] ?? toss("No waitLoop handler for whichOp #",opId);
|
||||
const args = state.s11n.deserialize(
|
||||
true /* clear s11n to keep the caller from confusing this with
|
||||
an exception string written by the upcoming
|
||||
operation */
|
||||
) || [];
|
||||
//warn("waitLoop() whichOp =",opId, hnd, args);
|
||||
if(hnd.f) await hnd.f(...args);
|
||||
else error("Missing callback for opId",opId);
|
||||
}catch(e){
|
||||
error('in waitLoop():',e);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
navigator.storage.getDirectory().then(function(d){
|
||||
const wMsg = (type)=>postMessage({type});
|
||||
state.rootDir = d;
|
||||
self.onmessage = function({data}){
|
||||
switch(data.type){
|
||||
case 'opfs-async-init':{
|
||||
/* Receive shared state from synchronous partner */
|
||||
const opt = data.args;
|
||||
state.littleEndian = opt.littleEndian;
|
||||
state.asyncS11nExceptions = opt.asyncS11nExceptions;
|
||||
state.verbose = opt.verbose ?? 2;
|
||||
state.fileBufferSize = opt.fileBufferSize;
|
||||
state.sabS11nOffset = opt.sabS11nOffset;
|
||||
state.sabS11nSize = opt.sabS11nSize;
|
||||
state.sabOP = opt.sabOP;
|
||||
state.sabOPView = new Int32Array(state.sabOP);
|
||||
state.sabIO = opt.sabIO;
|
||||
state.sabFileBufView = new Uint8Array(state.sabIO, 0, state.fileBufferSize);
|
||||
state.sabS11nView = new Uint8Array(state.sabIO, state.sabS11nOffset, state.sabS11nSize);
|
||||
state.opIds = opt.opIds;
|
||||
state.sq3Codes = opt.sq3Codes;
|
||||
Object.keys(vfsAsyncImpls).forEach((k)=>{
|
||||
if(!Number.isFinite(state.opIds[k])){
|
||||
toss("Maintenance required: missing state.opIds[",k,"]");
|
||||
}
|
||||
});
|
||||
initS11n();
|
||||
metrics.reset();
|
||||
log("init state",state);
|
||||
wMsg('opfs-async-inited');
|
||||
waitLoop();
|
||||
break;
|
||||
}
|
||||
case 'opfs-async-restart':
|
||||
if(flagAsyncShutdown){
|
||||
warn("Restarting after opfs-async-shutdown. Might or might not work.");
|
||||
flagAsyncShutdown = false;
|
||||
waitLoop();
|
||||
}
|
||||
break;
|
||||
case 'opfs-async-metrics':
|
||||
metrics.dump();
|
||||
break;
|
||||
}
|
||||
};
|
||||
wMsg('opfs-async-loaded');
|
||||
}).catch((e)=>error("error initializing OPFS asyncer:",e));
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
Dummy function stubs to get sqlite3.c compiling with
|
||||
wasi-sdk. This requires, in addition:
|
||||
|
||||
-D_WASI_EMULATED_MMAN -D_WASI_EMULATED_GETPID
|
||||
|
||||
-lwasi-emulated-getpid
|
||||
*/
|
||||
typedef unsigned mode_t;
|
||||
int fchmod(int fd, mode_t mode);
|
||||
int fchmod(int fd, mode_t mode){
|
||||
return (fd && mode) ? 0 : 0;
|
||||
}
|
||||
typedef unsigned uid_t;
|
||||
typedef uid_t gid_t;
|
||||
int fchown(int fd, uid_t owner, gid_t group);
|
||||
int fchown(int fd, uid_t owner, gid_t group){
|
||||
return (fd && owner && group) ? 0 : 0;
|
||||
}
|
||||
uid_t geteuid(void);
|
||||
uid_t geteuid(void){return 0;}
|
||||
#if !defined(F_WRLCK)
|
||||
enum {
|
||||
F_WRLCK,
|
||||
F_RDLCK,
|
||||
F_GETLK,
|
||||
F_SETLK,
|
||||
F_UNLCK
|
||||
};
|
||||
#endif
|
||||
|
||||
#undef HAVE_PREAD
|
||||
|
||||
#include <wasi/api.h>
|
||||
#define WASM__KEEP __attribute__((used))
|
||||
|
||||
#if 0
|
||||
/**
|
||||
wasi-sdk cannot build sqlite3's default VFS without at least the following
|
||||
functions. They are apparently syscalls which clients have to implement or
|
||||
otherwise obtain.
|
||||
|
||||
https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md
|
||||
*/
|
||||
environ_get
|
||||
environ_sizes_get
|
||||
clock_time_get
|
||||
fd_close
|
||||
fd_fdstat_get
|
||||
fd_fdstat_set_flags
|
||||
fd_filestat_get
|
||||
fd_filestat_set_size
|
||||
fd_pread
|
||||
fd_prestat_get
|
||||
fd_prestat_dir_name
|
||||
fd_read
|
||||
fd_seek
|
||||
fd_sync
|
||||
fd_write
|
||||
path_create_directory
|
||||
path_filestat_get
|
||||
path_filestat_set_times
|
||||
path_open
|
||||
path_readlink
|
||||
path_remove_directory
|
||||
path_unlink_file
|
||||
poll_oneoff
|
||||
proc_exit
|
||||
#endif
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,259 @@
|
||||
/*
|
||||
2022-08-24
|
||||
|
||||
The author disclaims copyright to this source code. In place of a
|
||||
legal notice, here is a blessing:
|
||||
|
||||
* May you do good and not evil.
|
||||
* May you find forgiveness for yourself and forgive others.
|
||||
* May you share freely, never taking more than you give.
|
||||
|
||||
***********************************************************************
|
||||
|
||||
This file implements a Promise-based proxy for the sqlite3 Worker
|
||||
API #1. It is intended to be included either from the main thread or
|
||||
a Worker, but only if (A) the environment supports nested Workers
|
||||
and (B) it's _not_ a Worker which loads the sqlite3 WASM/JS
|
||||
module. This file's features will load that module and provide a
|
||||
slightly simpler client-side interface than the slightly-lower-level
|
||||
Worker API does.
|
||||
|
||||
This script necessarily exposes one global symbol, but clients may
|
||||
freely `delete` that symbol after calling it.
|
||||
*/
|
||||
'use strict';
|
||||
/**
|
||||
Configures an sqlite3 Worker API #1 Worker such that it can be
|
||||
manipulated via a Promise-based interface and returns a factory
|
||||
function which returns Promises for communicating with the worker.
|
||||
This proxy has an _almost_ identical interface to the normal
|
||||
worker API, with any exceptions documented below.
|
||||
|
||||
It requires a configuration object with the following properties:
|
||||
|
||||
- `worker` (required): a Worker instance which loads
|
||||
`sqlite3-worker1.js` or a functional equivalent. Note that the
|
||||
promiser factory replaces the worker.onmessage property. This
|
||||
config option may alternately be a function, in which case this
|
||||
function re-assigns this property with the result of calling that
|
||||
function, enabling delayed instantiation of a Worker.
|
||||
|
||||
- `onready` (optional, but...): this callback is called with no
|
||||
arguments when the worker fires its initial
|
||||
'sqlite3-api'/'worker1-ready' message, which it does when
|
||||
sqlite3.initWorker1API() completes its initialization. This is
|
||||
the simplest way to tell the worker to kick off work at the
|
||||
earliest opportunity.
|
||||
|
||||
- `onunhandled` (optional): a callback which gets passed the
|
||||
message event object for any worker.onmessage() events which
|
||||
are not handled by this proxy. Ideally that "should" never
|
||||
happen, as this proxy aims to handle all known message types.
|
||||
|
||||
- `generateMessageId` (optional): a function which, when passed an
|
||||
about-to-be-posted message object, generates a _unique_ message ID
|
||||
for the message, which this API then assigns as the messageId
|
||||
property of the message. It _must_ generate unique IDs on each call
|
||||
so that dispatching can work. If not defined, a default generator
|
||||
is used (which should be sufficient for most or all cases).
|
||||
|
||||
- `debug` (optional): a console.debug()-style function for logging
|
||||
information about messages.
|
||||
|
||||
This function returns a stateful factory function with the
|
||||
following interfaces:
|
||||
|
||||
- Promise function(messageType, messageArgs)
|
||||
- Promise function({message object})
|
||||
|
||||
The first form expects the "type" and "args" values for a Worker
|
||||
message. The second expects an object in the form {type:...,
|
||||
args:...} plus any other properties the client cares to set. This
|
||||
function will always set the `messageId` property on the object,
|
||||
even if it's already set, and will set the `dbId` property to the
|
||||
current database ID if it is _not_ set in the message object.
|
||||
|
||||
The function throws on error.
|
||||
|
||||
The function installs a temporary message listener, posts a
|
||||
message to the configured Worker, and handles the message's
|
||||
response via the temporary message listener. The then() callback
|
||||
of the returned Promise is passed the `message.data` property from
|
||||
the resulting message, i.e. the payload from the worker, stripped
|
||||
of the lower-level event state which the onmessage() handler
|
||||
receives.
|
||||
|
||||
Example usage:
|
||||
|
||||
```
|
||||
const config = {...};
|
||||
const sq3Promiser = sqlite3Worker1Promiser(config);
|
||||
sq3Promiser('open', {filename:"/foo.db"}).then(function(msg){
|
||||
console.log("open response",msg); // => {type:'open', result: {filename:'/foo.db'}, ...}
|
||||
});
|
||||
sq3Promiser({type:'close'}).then((msg)=>{
|
||||
console.log("close response",msg); // => {type:'close', result: {filename:'/foo.db'}, ...}
|
||||
});
|
||||
```
|
||||
|
||||
Differences from Worker API #1:
|
||||
|
||||
- exec's {callback: STRING} option does not work via this
|
||||
interface (it triggers an exception), but {callback: function}
|
||||
does and works exactly like the STRING form does in the Worker:
|
||||
the callback is called one time for each row of the result set,
|
||||
passed the same worker message format as the worker API emits:
|
||||
|
||||
{type:typeString,
|
||||
row:VALUE,
|
||||
rowNumber:1-based-#,
|
||||
columnNames: array}
|
||||
|
||||
Where `typeString` is an internally-synthesized message type string
|
||||
used temporarily for worker message dispatching. It can be ignored
|
||||
by all client code except that which tests this API. The `row`
|
||||
property contains the row result in the form implied by the
|
||||
`rowMode` option (defaulting to `'array'`). The `rowNumber` is a
|
||||
1-based integer value incremented by 1 on each call into th
|
||||
callback.
|
||||
|
||||
At the end of the result set, the same event is fired with
|
||||
(row=undefined, rowNumber=null) to indicate that
|
||||
the end of the result set has been reached. Note that the rows
|
||||
arrive via worker-posted messages, with all the implications
|
||||
of that.
|
||||
*/
|
||||
self.sqlite3Worker1Promiser = function callee(config = callee.defaultConfig){
|
||||
// Inspired by: https://stackoverflow.com/a/52439530
|
||||
if(1===arguments.length && 'function'===typeof arguments[0]){
|
||||
const f = config;
|
||||
config = Object.assign(Object.create(null), callee.defaultConfig);
|
||||
config.onready = f;
|
||||
}else{
|
||||
config = Object.assign(Object.create(null), callee.defaultConfig, config);
|
||||
}
|
||||
const handlerMap = Object.create(null);
|
||||
const noop = function(){};
|
||||
const err = config.onerror
|
||||
|| noop /* config.onerror is intentionally undocumented
|
||||
pending finding a less ambiguous name */;
|
||||
const debug = config.debug || noop;
|
||||
const idTypeMap = config.generateMessageId ? undefined : Object.create(null);
|
||||
const genMsgId = config.generateMessageId || function(msg){
|
||||
return msg.type+'#'+(idTypeMap[msg.type] = (idTypeMap[msg.type]||0) + 1);
|
||||
};
|
||||
const toss = (...args)=>{throw new Error(args.join(' '))};
|
||||
if(!config.worker) config.worker = callee.defaultConfig.worker;
|
||||
if('function'===typeof config.worker) config.worker = config.worker();
|
||||
let dbId;
|
||||
config.worker.onmessage = function(ev){
|
||||
ev = ev.data;
|
||||
debug('worker1.onmessage',ev);
|
||||
let msgHandler = handlerMap[ev.messageId];
|
||||
if(!msgHandler){
|
||||
if(ev && 'sqlite3-api'===ev.type && 'worker1-ready'===ev.result) {
|
||||
/*fired one time when the Worker1 API initializes*/
|
||||
if(config.onready) config.onready();
|
||||
return;
|
||||
}
|
||||
msgHandler = handlerMap[ev.type] /* check for exec per-row callback */;
|
||||
if(msgHandler && msgHandler.onrow){
|
||||
msgHandler.onrow(ev);
|
||||
return;
|
||||
}
|
||||
if(config.onunhandled) config.onunhandled(arguments[0]);
|
||||
else err("sqlite3Worker1Promiser() unhandled worker message:",ev);
|
||||
return;
|
||||
}
|
||||
delete handlerMap[ev.messageId];
|
||||
switch(ev.type){
|
||||
case 'error':
|
||||
msgHandler.reject(ev);
|
||||
return;
|
||||
case 'open':
|
||||
if(!dbId) dbId = ev.dbId;
|
||||
break;
|
||||
case 'close':
|
||||
if(ev.dbId===dbId) dbId = undefined;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
try {msgHandler.resolve(ev)}
|
||||
catch(e){msgHandler.reject(e)}
|
||||
}/*worker.onmessage()*/;
|
||||
return function(/*(msgType, msgArgs) || (msgEnvelope)*/){
|
||||
let msg;
|
||||
if(1===arguments.length){
|
||||
msg = arguments[0];
|
||||
}else if(2===arguments.length){
|
||||
msg = {
|
||||
type: arguments[0],
|
||||
args: arguments[1]
|
||||
};
|
||||
}else{
|
||||
toss("Invalid arugments for sqlite3Worker1Promiser()-created factory.");
|
||||
}
|
||||
if(!msg.dbId) msg.dbId = dbId;
|
||||
msg.messageId = genMsgId(msg);
|
||||
msg.departureTime = performance.now();
|
||||
const proxy = Object.create(null);
|
||||
proxy.message = msg;
|
||||
let rowCallbackId /* message handler ID for exec on-row callback proxy */;
|
||||
if('exec'===msg.type && msg.args){
|
||||
if('function'===typeof msg.args.callback){
|
||||
rowCallbackId = msg.messageId+':row';
|
||||
proxy.onrow = msg.args.callback;
|
||||
msg.args.callback = rowCallbackId;
|
||||
handlerMap[rowCallbackId] = proxy;
|
||||
}else if('string' === typeof msg.args.callback){
|
||||
toss("exec callback may not be a string when using the Promise interface.");
|
||||
/**
|
||||
Design note: the reason for this limitation is that this
|
||||
API takes over worker.onmessage() and the client has no way
|
||||
of adding their own message-type handlers to it. Per-row
|
||||
callbacks are implemented as short-lived message.type
|
||||
mappings for worker.onmessage().
|
||||
|
||||
We "could" work around this by providing a new
|
||||
config.fallbackMessageHandler (or some such) which contains
|
||||
a map of event type names to callbacks. Seems like overkill
|
||||
for now, seeing as the client can pass callback functions
|
||||
to this interface (whereas the string-form "callback" is
|
||||
needed for the over-the-Worker interface).
|
||||
*/
|
||||
}
|
||||
}
|
||||
//debug("requestWork", msg);
|
||||
let p = new Promise(function(resolve, reject){
|
||||
proxy.resolve = resolve;
|
||||
proxy.reject = reject;
|
||||
handlerMap[msg.messageId] = proxy;
|
||||
debug("Posting",msg.type,"message to Worker dbId="+(dbId||'default')+':',msg);
|
||||
config.worker.postMessage(msg);
|
||||
});
|
||||
if(rowCallbackId) p = p.finally(()=>delete handlerMap[rowCallbackId]);
|
||||
return p;
|
||||
};
|
||||
}/*sqlite3Worker1Promiser()*/;
|
||||
self.sqlite3Worker1Promiser.defaultConfig = {
|
||||
worker: function(){
|
||||
let theJs = "sqlite3-worker1.js";
|
||||
if(this.currentScript){
|
||||
const src = this.currentScript.src.split('/');
|
||||
src.pop();
|
||||
theJs = src.join('/')+'/' + theJs;
|
||||
//console.warn("promiser currentScript, theJs =",this.currentScript,theJs);
|
||||
}else{
|
||||
//console.warn("promiser self.location =",self.location);
|
||||
const urlParams = new URL(self.location.href).searchParams;
|
||||
if(urlParams.has('sqlite3.dir')){
|
||||
theJs = urlParams.get('sqlite3.dir') + '/' + theJs;
|
||||
}
|
||||
}
|
||||
return new Worker(theJs + self.location.search);
|
||||
}.bind({
|
||||
currentScript: self?.document?.currentScript
|
||||
}),
|
||||
onerror: (...args)=>console.error('worker1 promiser error',...args)
|
||||
};
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
2022-05-23
|
||||
|
||||
The author disclaims copyright to this source code. In place of a
|
||||
legal notice, here is a blessing:
|
||||
|
||||
* May you do good and not evil.
|
||||
* May you find forgiveness for yourself and forgive others.
|
||||
* May you share freely, never taking more than you give.
|
||||
|
||||
***********************************************************************
|
||||
|
||||
This is a JS Worker file for the main sqlite3 api. It loads
|
||||
sqlite3.js, initializes the module, and postMessage()'s a message
|
||||
after the module is initialized:
|
||||
|
||||
{type: 'sqlite3-api', result: 'worker1-ready'}
|
||||
|
||||
This seemingly superfluous level of indirection is necessary when
|
||||
loading sqlite3.js via a Worker. Instantiating a worker with new
|
||||
Worker("sqlite.js") will not (cannot) call sqlite3InitModule() to
|
||||
initialize the module due to a timing/order-of-operations conflict
|
||||
(and that symbol is not exported in a way that a Worker loading it
|
||||
that way can see it). Thus JS code wanting to load the sqlite3
|
||||
Worker-specific API needs to pass _this_ file (or equivalent) to the
|
||||
Worker constructor and then listen for an event in the form shown
|
||||
above in order to know when the module has completed initialization.
|
||||
|
||||
This file accepts a URL arguments to adjust how it loads sqlite3.js:
|
||||
|
||||
- `sqlite3.dir`, if set, treats the given directory name as the
|
||||
directory from which `sqlite3.js` will be loaded.
|
||||
*/
|
||||
"use strict";
|
||||
(()=>{
|
||||
const urlParams = new URL(self.location.href).searchParams;
|
||||
let theJs = 'sqlite3.js';
|
||||
if(urlParams.has('sqlite3.dir')){
|
||||
theJs = urlParams.get('sqlite3.dir') + '/' + theJs;
|
||||
}
|
||||
//console.warn("worker1 theJs =",theJs);
|
||||
importScripts(theJs);
|
||||
sqlite3InitModule().then((sqlite3)=>{
|
||||
if(sqlite3.capi.sqlite3_wasmfs_opfs_dir){
|
||||
sqlite3.capi.sqlite3_wasmfs_opfs_dir();
|
||||
}
|
||||
sqlite3.initWorker1API();
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,90 @@
|
||||
<!doctype html>
|
||||
<html lang="en-us">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
||||
<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
|
||||
<link rel="stylesheet" href="common/emscripten.css"/>
|
||||
<link rel="stylesheet" href="common/testing.css"/>
|
||||
<title>sqlite3-api batch SQL runner</title>
|
||||
</head>
|
||||
<body>
|
||||
<header id='titlebar'><span>sqlite3-api batch SQL runner</span></header>
|
||||
<!-- emscripten bits -->
|
||||
<figure id="module-spinner">
|
||||
<div class="spinner"></div>
|
||||
<div class='center'><strong>Initializing app...</strong></div>
|
||||
<div class='center'>
|
||||
On a slow internet connection this may take a moment. If this
|
||||
message displays for "a long time", intialization may have
|
||||
failed and the JavaScript console may contain clues as to why.
|
||||
</div>
|
||||
</figure>
|
||||
<div class="emscripten" id="module-status">Downloading...</div>
|
||||
<div class="emscripten">
|
||||
<progress value="0" max="100" id="module-progress" hidden='1'></progress>
|
||||
</div><!-- /emscripten bits -->
|
||||
<p>
|
||||
This page is for batch-running extracts from the output
|
||||
of <tt>speedtest1 --script</tt>, as well as other standalone SQL
|
||||
scripts.
|
||||
</p>
|
||||
<p id='warn-list' class='warning'>ACHTUNG: this file requires a generated input list
|
||||
file. Run "make batch" from this directory to generate it.
|
||||
</p>
|
||||
<p id='warn-opfs' class='warning hidden'>WARNING: if the WASMFS/OPFS layer crashes, this page may
|
||||
become completely unresponsive and need to be closed and reloaded to recover.
|
||||
</p>
|
||||
<p id='warn-websql' class='warning hidden'>WARNING: WebSQL's limited API requires that
|
||||
this app split up SQL batches into separate statements for execution. That will
|
||||
only work so long as semicolon characters are <em>only</em> used to terminate
|
||||
SQL statements, and not used within string literals or the like.
|
||||
</p>
|
||||
<hr>
|
||||
<fieldset id='toolbar'>
|
||||
<div>
|
||||
<select class='disable-during-eval' id='sql-select'>
|
||||
<option disabled selected>Populated via script code</option>
|
||||
</select>
|
||||
<button class='disable-during-eval' id='sql-run'>Run selected SQL</button>
|
||||
<button class='disable-during-eval' id='sql-run-next'>Run next...</button>
|
||||
<button class='disable-during-eval' id='sql-run-remaining'>Run all remaining...</button>
|
||||
<button class='disable-during-eval' id='export-metrics' disabled>Export metrics (WIP)<br>(broken by refactoring)</button>
|
||||
<button class='disable-during-eval' id='db-reset'>Reset db</button>
|
||||
<button id='output-clear'>Clear output</button>
|
||||
<span class='input-wrapper flex-col'>
|
||||
<label for='select-impl'>Storage impl:</label>
|
||||
<select id='select-impl'>
|
||||
<option value='virtualfs'>Virtual filesystem</option>
|
||||
<option value='memdb'>:memory:</option>
|
||||
<option value='wasmfs-opfs'>WASMFS OPFS</option>
|
||||
<option value='websql'>WebSQL</option>
|
||||
</select>
|
||||
</span>
|
||||
</fieldset>
|
||||
</div>
|
||||
<hr>
|
||||
<span class='input-wrapper'>
|
||||
<input type='checkbox' class='disable-during-eval' id='cb-reverse-log-order' checked></input>
|
||||
<label for='cb-reverse-log-order'>Reverse log order (newest first)</label>
|
||||
</span>
|
||||
<div id='test-output'></div>
|
||||
<script src="jswasm/sqlite3.js"></script>
|
||||
<script src="common/SqliteTestUtil.js"></script>
|
||||
<script src="batch-runner.js"></script>
|
||||
<style>
|
||||
.flex-col {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
#toolbar > div {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
#toolbar > div > * {
|
||||
margin: 0.25em;
|
||||
}
|
||||
</style>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,588 @@
|
||||
/*
|
||||
2022-08-29
|
||||
|
||||
The author disclaims copyright to this source code. In place of a
|
||||
legal notice, here is a blessing:
|
||||
|
||||
* May you do good and not evil.
|
||||
* May you find forgiveness for yourself and forgive others.
|
||||
* May you share freely, never taking more than you give.
|
||||
|
||||
***********************************************************************
|
||||
|
||||
A basic batch SQL runner for sqlite3-api.js. This file must be run in
|
||||
main JS thread and sqlite3.js must have been loaded before it.
|
||||
*/
|
||||
'use strict';
|
||||
(function(){
|
||||
const toss = function(...args){throw new Error(args.join(' '))};
|
||||
const warn = console.warn.bind(console);
|
||||
let sqlite3;
|
||||
const urlParams = new URL(self.location.href).searchParams;
|
||||
const cacheSize = (()=>{
|
||||
if(urlParams.has('cachesize')) return +urlParams.get('cachesize');
|
||||
return 200;
|
||||
})();
|
||||
|
||||
/** Throws if the given sqlite3 result code is not 0. */
|
||||
const checkSqliteRc = (dbh,rc)=>{
|
||||
if(rc) toss("Prepare failed:",sqlite3.capi.sqlite3_errmsg(dbh));
|
||||
};
|
||||
|
||||
const sqlToDrop = [
|
||||
"SELECT type,name FROM sqlite_schema ",
|
||||
"WHERE name NOT LIKE 'sqlite\\_%' escape '\\' ",
|
||||
"AND name NOT LIKE '\\_%' escape '\\'"
|
||||
].join('');
|
||||
|
||||
const clearDbWebSQL = function(db){
|
||||
db.handle.transaction(function(tx){
|
||||
const onErr = (e)=>console.error(e);
|
||||
const callback = function(tx, result){
|
||||
const rows = result.rows;
|
||||
let i, n;
|
||||
i = n = rows.length;
|
||||
while(i--){
|
||||
const row = rows.item(i);
|
||||
const name = JSON.stringify(row.name);
|
||||
const type = row.type;
|
||||
switch(type){
|
||||
case 'index': case 'table':
|
||||
case 'trigger': case 'view': {
|
||||
const sql2 = 'DROP '+type+' '+name;
|
||||
tx.executeSql(sql2, [], ()=>{}, onErr);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
warn("Unhandled db entry type:",type,'name =',name);
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
tx.executeSql(sqlToDrop, [], callback, onErr);
|
||||
db.handle.changeVersion(db.handle.version, "", ()=>{}, onErr, ()=>{});
|
||||
});
|
||||
};
|
||||
|
||||
const clearDbSqlite = function(db){
|
||||
// This would be SO much easier with the oo1 API, but we specifically want to
|
||||
// inject metrics we can't get via that API, and we cannot reliably (OPFS)
|
||||
// open the same DB twice to clear it using that API, so...
|
||||
const rc = sqlite3.wasm.exports.sqlite3_wasm_db_reset(db.handle);
|
||||
App.logHtml("reset db rc =",rc,db.id, db.filename);
|
||||
};
|
||||
|
||||
|
||||
const E = (s)=>document.querySelector(s);
|
||||
const App = {
|
||||
e: {
|
||||
output: E('#test-output'),
|
||||
selSql: E('#sql-select'),
|
||||
btnRun: E('#sql-run'),
|
||||
btnRunNext: E('#sql-run-next'),
|
||||
btnRunRemaining: E('#sql-run-remaining'),
|
||||
btnExportMetrics: E('#export-metrics'),
|
||||
btnClear: E('#output-clear'),
|
||||
btnReset: E('#db-reset'),
|
||||
cbReverseLog: E('#cb-reverse-log-order'),
|
||||
selImpl: E('#select-impl'),
|
||||
fsToolbar: E('#toolbar')
|
||||
},
|
||||
db: Object.create(null),
|
||||
dbs: Object.create(null),
|
||||
cache:{},
|
||||
log: console.log.bind(console),
|
||||
warn: console.warn.bind(console),
|
||||
cls: function(){this.e.output.innerHTML = ''},
|
||||
logHtml2: function(cssClass,...args){
|
||||
const ln = document.createElement('div');
|
||||
if(cssClass) ln.classList.add(cssClass);
|
||||
ln.append(document.createTextNode(args.join(' ')));
|
||||
this.e.output.append(ln);
|
||||
//this.e.output.lastElementChild.scrollIntoViewIfNeeded();
|
||||
},
|
||||
logHtml: function(...args){
|
||||
console.log(...args);
|
||||
if(1) this.logHtml2('', ...args);
|
||||
},
|
||||
logErr: function(...args){
|
||||
console.error(...args);
|
||||
if(1) this.logHtml2('error', ...args);
|
||||
},
|
||||
|
||||
execSql: async function(name,sql){
|
||||
const db = this.getSelectedDb();
|
||||
const banner = "========================================";
|
||||
this.logHtml(banner,
|
||||
"Running",name,'('+sql.length,'bytes) using',db.id);
|
||||
const capi = this.sqlite3.capi, wasm = this.sqlite3.wasm;
|
||||
let pStmt = 0, pSqlBegin;
|
||||
const stack = wasm.scopedAllocPush();
|
||||
const metrics = db.metrics = Object.create(null);
|
||||
metrics.prepTotal = metrics.stepTotal = 0;
|
||||
metrics.stmtCount = 0;
|
||||
metrics.malloc = 0;
|
||||
metrics.strcpy = 0;
|
||||
this.blockControls(true);
|
||||
if(this.gotErr){
|
||||
this.logErr("Cannot run SQL: error cleanup is pending.");
|
||||
return;
|
||||
}
|
||||
// Run this async so that the UI can be updated for the above header...
|
||||
const endRun = ()=>{
|
||||
metrics.evalSqlEnd = performance.now();
|
||||
metrics.evalTimeTotal = (metrics.evalSqlEnd - metrics.evalSqlStart);
|
||||
this.logHtml(db.id,"metrics:",JSON.stringify(metrics, undefined, ' '));
|
||||
this.logHtml("prepare() count:",metrics.stmtCount);
|
||||
this.logHtml("Time in prepare_v2():",metrics.prepTotal,"ms",
|
||||
"("+(metrics.prepTotal / metrics.stmtCount),"ms per prepare())");
|
||||
this.logHtml("Time in step():",metrics.stepTotal,"ms",
|
||||
"("+(metrics.stepTotal / metrics.stmtCount),"ms per step())");
|
||||
this.logHtml("Total runtime:",metrics.evalTimeTotal,"ms");
|
||||
this.logHtml("Overhead (time - prep - step):",
|
||||
(metrics.evalTimeTotal - metrics.prepTotal - metrics.stepTotal)+"ms");
|
||||
this.logHtml(banner,"End of",name);
|
||||
};
|
||||
|
||||
let runner;
|
||||
if('websql'===db.id){
|
||||
const who = this;
|
||||
runner = function(resolve, reject){
|
||||
/* WebSQL cannot execute multiple statements, nor can it execute SQL without
|
||||
an explicit transaction. Thus we have to do some fragile surgery on the
|
||||
input SQL. Since we're only expecting carefully curated inputs, the hope is
|
||||
that this will suffice. PS: it also can't run most SQL functions, e.g. even
|
||||
instr() results in "not authorized". */
|
||||
if('string'!==typeof sql){ // assume TypedArray
|
||||
sql = new TextDecoder().decode(sql);
|
||||
}
|
||||
sql = sql.replace(/-- [^\n]+\n/g,''); // comment lines interfere with our split()
|
||||
const sqls = sql.split(/;+\n/);
|
||||
const rxBegin = /^BEGIN/i, rxCommit = /^COMMIT/i;
|
||||
try {
|
||||
const nextSql = ()=>{
|
||||
let x = sqls.shift();
|
||||
while(sqls.length && !x) x = sqls.shift();
|
||||
return x && x.trim();
|
||||
};
|
||||
const who = this;
|
||||
const transaction = function(tx){
|
||||
try {
|
||||
let s;
|
||||
/* Try to approximate the spirit of the input scripts
|
||||
by running batches bound by BEGIN/COMMIT statements. */
|
||||
for(s = nextSql(); !!s; s = nextSql()){
|
||||
if(rxBegin.test(s)) continue;
|
||||
else if(rxCommit.test(s)) break;
|
||||
//console.log("websql sql again",sqls.length, s);
|
||||
++metrics.stmtCount;
|
||||
const t = performance.now();
|
||||
tx.executeSql(s,[], ()=>{}, (t,e)=>{
|
||||
console.error("WebSQL error",e,"SQL =",s);
|
||||
who.logErr(e.message);
|
||||
//throw e;
|
||||
return false;
|
||||
});
|
||||
metrics.stepTotal += performance.now() - t;
|
||||
}
|
||||
}catch(e){
|
||||
who.logErr("transaction():",e.message);
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
const n = sqls.length;
|
||||
const nextBatch = function(){
|
||||
if(sqls.length){
|
||||
console.log("websql sqls.length",sqls.length,'of',n);
|
||||
db.handle.transaction(transaction, (e)=>{
|
||||
who.logErr("Ignoring and contiuing:",e.message)
|
||||
//reject(e);
|
||||
return false;
|
||||
}, nextBatch);
|
||||
}else{
|
||||
resolve(who);
|
||||
}
|
||||
};
|
||||
metrics.evalSqlStart = performance.now();
|
||||
nextBatch();
|
||||
}catch(e){
|
||||
//this.gotErr = e;
|
||||
console.error("websql error:",e);
|
||||
who.logErr(e.message);
|
||||
//reject(e);
|
||||
}
|
||||
}.bind(this);
|
||||
}else{/*sqlite3 db...*/
|
||||
runner = function(resolve, reject){
|
||||
metrics.evalSqlStart = performance.now();
|
||||
try {
|
||||
let t;
|
||||
let sqlByteLen = sql.byteLength;
|
||||
const [ppStmt, pzTail] = wasm.scopedAllocPtr(2);
|
||||
t = performance.now();
|
||||
pSqlBegin = wasm.scopedAlloc( sqlByteLen + 1/*SQL + NUL*/) || toss("alloc(",sqlByteLen,") failed");
|
||||
metrics.malloc = performance.now() - t;
|
||||
metrics.byteLength = sqlByteLen;
|
||||
let pSql = pSqlBegin;
|
||||
const pSqlEnd = pSqlBegin + sqlByteLen;
|
||||
t = performance.now();
|
||||
wasm.heap8().set(sql, pSql);
|
||||
wasm.setMemValue(pSql + sqlByteLen, 0);
|
||||
metrics.strcpy = performance.now() - t;
|
||||
let breaker = 0;
|
||||
while(pSql && wasm.getMemValue(pSql,'i8')){
|
||||
wasm.setPtrValue(ppStmt, 0);
|
||||
wasm.setPtrValue(pzTail, 0);
|
||||
t = performance.now();
|
||||
let rc = capi.sqlite3_prepare_v3(
|
||||
db.handle, pSql, sqlByteLen, 0, ppStmt, pzTail
|
||||
);
|
||||
metrics.prepTotal += performance.now() - t;
|
||||
checkSqliteRc(db.handle, rc);
|
||||
pStmt = wasm.getPtrValue(ppStmt);
|
||||
pSql = wasm.getPtrValue(pzTail);
|
||||
sqlByteLen = pSqlEnd - pSql;
|
||||
if(!pStmt) continue/*empty statement*/;
|
||||
++metrics.stmtCount;
|
||||
t = performance.now();
|
||||
rc = capi.sqlite3_step(pStmt);
|
||||
capi.sqlite3_finalize(pStmt);
|
||||
pStmt = 0;
|
||||
metrics.stepTotal += performance.now() - t;
|
||||
switch(rc){
|
||||
case capi.SQLITE_ROW:
|
||||
case capi.SQLITE_DONE: break;
|
||||
default: checkSqliteRc(db.handle, rc); toss("Not reached.");
|
||||
}
|
||||
}
|
||||
resolve(this);
|
||||
}catch(e){
|
||||
if(pStmt) capi.sqlite3_finalize(pStmt);
|
||||
//this.gotErr = e;
|
||||
reject(e);
|
||||
}finally{
|
||||
capi.sqlite3_exec(db.handle,"rollback;",0,0,0);
|
||||
wasm.scopedAllocPop(stack);
|
||||
}
|
||||
}.bind(this);
|
||||
}
|
||||
let p;
|
||||
if(1){
|
||||
p = new Promise(function(res,rej){
|
||||
setTimeout(()=>runner(res, rej), 50)/*give UI a chance to output the "running" banner*/;
|
||||
});
|
||||
}else{
|
||||
p = new Promise(runner);
|
||||
}
|
||||
return p.catch(
|
||||
(e)=>this.logErr("Error via execSql("+name+",...):",e.message)
|
||||
).finally(()=>{
|
||||
endRun();
|
||||
this.blockControls(false);
|
||||
});
|
||||
},
|
||||
|
||||
clearDb: function(){
|
||||
const db = this.getSelectedDb();
|
||||
if('websql'===db.id){
|
||||
this.logErr("TODO: clear websql db.");
|
||||
return;
|
||||
}
|
||||
if(!db.handle) return;
|
||||
const capi = this.sqlite3, wasm = this.sqlite3.wasm;
|
||||
//const scope = wasm.scopedAllocPush(
|
||||
this.logErr("TODO: clear db");
|
||||
},
|
||||
|
||||
/**
|
||||
Loads batch-runner.list and populates the selection list from
|
||||
it. Returns a promise which resolves to nothing in particular
|
||||
when it completes. Only intended to be run once at the start
|
||||
of the app.
|
||||
*/
|
||||
loadSqlList: async function(){
|
||||
const sel = this.e.selSql;
|
||||
sel.innerHTML = '';
|
||||
this.blockControls(true);
|
||||
const infile = 'batch-runner.list';
|
||||
this.logHtml("Loading list of SQL files:", infile);
|
||||
let txt;
|
||||
try{
|
||||
const r = await fetch(infile);
|
||||
if(404 === r.status){
|
||||
toss("Missing file '"+infile+"'.");
|
||||
}
|
||||
if(!r.ok) toss("Loading",infile,"failed:",r.statusText);
|
||||
txt = await r.text();
|
||||
const warning = E('#warn-list');
|
||||
if(warning) warning.remove();
|
||||
}catch(e){
|
||||
this.logErr(e.message);
|
||||
throw e;
|
||||
}finally{
|
||||
this.blockControls(false);
|
||||
}
|
||||
const list = txt.split(/\n+/);
|
||||
let opt;
|
||||
if(0){
|
||||
opt = document.createElement('option');
|
||||
opt.innerText = "Select file to evaluate...";
|
||||
opt.value = '';
|
||||
opt.disabled = true;
|
||||
opt.selected = true;
|
||||
sel.appendChild(opt);
|
||||
}
|
||||
list.forEach(function(fn){
|
||||
if(!fn) return;
|
||||
opt = document.createElement('option');
|
||||
opt.value = fn;
|
||||
opt.innerText = fn.split('/').pop();
|
||||
sel.appendChild(opt);
|
||||
});
|
||||
this.logHtml("Loaded",infile);
|
||||
},
|
||||
|
||||
/** Fetch ./fn and return its contents as a Uint8Array. */
|
||||
fetchFile: async function(fn, cacheIt=false){
|
||||
if(cacheIt && this.cache[fn]) return this.cache[fn];
|
||||
this.logHtml("Fetching",fn,"...");
|
||||
let sql;
|
||||
try {
|
||||
const r = await fetch(fn);
|
||||
if(!r.ok) toss("Fetch failed:",r.statusText);
|
||||
sql = new Uint8Array(await r.arrayBuffer());
|
||||
}catch(e){
|
||||
this.logErr(e.message);
|
||||
throw e;
|
||||
}
|
||||
this.logHtml("Fetched",sql.length,"bytes from",fn);
|
||||
if(cacheIt) this.cache[fn] = sql;
|
||||
return sql;
|
||||
}/*fetchFile()*/,
|
||||
|
||||
/** Disable or enable certain UI controls. */
|
||||
blockControls: function(disable){
|
||||
//document.querySelectorAll('.disable-during-eval').forEach((e)=>e.disabled = disable);
|
||||
this.e.fsToolbar.disabled = disable;
|
||||
},
|
||||
|
||||
/**
|
||||
Converts this.metrics() to a form which is suitable for easy conversion to
|
||||
CSV. It returns an array of arrays. The first sub-array is the column names.
|
||||
The 2nd and subsequent are the values, one per test file (only the most recent
|
||||
metrics are kept for any given file).
|
||||
*/
|
||||
metricsToArrays: function(){
|
||||
const rc = [];
|
||||
Object.keys(this.dbs).sort().forEach((k)=>{
|
||||
const d = this.dbs[k];
|
||||
const m = d.metrics;
|
||||
delete m.evalSqlStart;
|
||||
delete m.evalSqlEnd;
|
||||
const mk = Object.keys(m).sort();
|
||||
if(!rc.length){
|
||||
rc.push(['db', ...mk]);
|
||||
}
|
||||
const row = [k.split('/').pop()/*remove dir prefix from filename*/];
|
||||
rc.push(row);
|
||||
row.push(...mk.map((kk)=>m[kk]));
|
||||
});
|
||||
return rc;
|
||||
},
|
||||
|
||||
metricsToBlob: function(colSeparator='\t'){
|
||||
const ar = [], ma = this.metricsToArrays();
|
||||
if(!ma.length){
|
||||
this.logErr("Metrics are empty. Run something.");
|
||||
return;
|
||||
}
|
||||
ma.forEach(function(row){
|
||||
ar.push(row.join(colSeparator),'\n');
|
||||
});
|
||||
return new Blob(ar);
|
||||
},
|
||||
|
||||
downloadMetrics: function(){
|
||||
const b = this.metricsToBlob();
|
||||
if(!b) return;
|
||||
const url = URL.createObjectURL(b);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = 'batch-runner-js-'+((new Date().getTime()/1000) | 0)+'.csv';
|
||||
this.logHtml("Triggering download of",a.download);
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
setTimeout(()=>{
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}, 500);
|
||||
},
|
||||
|
||||
/**
|
||||
Fetch file fn and eval it as an SQL blob. This is an async
|
||||
operation and returns a Promise which resolves to this
|
||||
object on success.
|
||||
*/
|
||||
evalFile: async function(fn){
|
||||
const sql = await this.fetchFile(fn);
|
||||
return this.execSql(fn,sql);
|
||||
}/*evalFile()*/,
|
||||
|
||||
/**
|
||||
Clears all DB tables in all _opened_ databases. Because of
|
||||
disparities between backends, we cannot simply "unlink" the
|
||||
databases to clean them up.
|
||||
*/
|
||||
clearStorage: function(onlySelectedDb=false){
|
||||
const list = onlySelectedDb
|
||||
? [('boolean'===typeof onlySelectedDb)
|
||||
? this.dbs[this.e.selImpl.value]
|
||||
: onlySelectedDb]
|
||||
: Object.values(this.dbs);
|
||||
for(let db of list){
|
||||
if(db && db.handle){
|
||||
this.logHtml("Clearing db",db.id);
|
||||
db.clear();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
Fetches the handle of the db associated with
|
||||
this.e.selImpl.value, opening it if needed.
|
||||
*/
|
||||
getSelectedDb: function(){
|
||||
if(!this.dbs.memdb){
|
||||
for(let opt of this.e.selImpl.options){
|
||||
const d = this.dbs[opt.value] = Object.create(null);
|
||||
d.id = opt.value;
|
||||
switch(d.id){
|
||||
case 'virtualfs':
|
||||
d.filename = 'file:/virtualfs.sqlite3?vfs=unix-none';
|
||||
break;
|
||||
case 'memdb':
|
||||
d.filename = ':memory:';
|
||||
break;
|
||||
case 'wasmfs-opfs':
|
||||
d.filename = 'file:'+(
|
||||
this.sqlite3.capi.sqlite3_wasmfs_opfs_dir()
|
||||
)+'/wasmfs-opfs.sqlite3b';
|
||||
break;
|
||||
case 'websql':
|
||||
d.filename = 'websql.db';
|
||||
break;
|
||||
default:
|
||||
this.logErr("Unhandled db selection option (see details in the console).",opt);
|
||||
toss("Unhandled db init option");
|
||||
}
|
||||
}
|
||||
}/*first-time init*/
|
||||
const dbId = this.e.selImpl.value;
|
||||
const d = this.dbs[dbId];
|
||||
if(d.handle) return d;
|
||||
if('websql' === dbId){
|
||||
d.handle = self.openDatabase('batch-runner', '0.1', 'foo', 1024 * 1024 * 50);
|
||||
d.clear = ()=>clearDbWebSQL(d);
|
||||
d.handle.transaction(function(tx){
|
||||
tx.executeSql("PRAGMA cache_size="+cacheSize);
|
||||
App.logHtml(dbId,"cache_size =",cacheSize);
|
||||
});
|
||||
}else{
|
||||
const capi = this.sqlite3.capi, wasm = this.sqlite3.wasm;
|
||||
const stack = wasm.scopedAllocPush();
|
||||
let pDb = 0;
|
||||
try{
|
||||
const oFlags = capi.SQLITE_OPEN_CREATE | capi.SQLITE_OPEN_READWRITE;
|
||||
const ppDb = wasm.scopedAllocPtr();
|
||||
const rc = capi.sqlite3_open_v2(d.filename, ppDb, oFlags, null);
|
||||
pDb = wasm.getPtrValue(ppDb)
|
||||
if(rc) toss("sqlite3_open_v2() failed with code",rc);
|
||||
capi.sqlite3_exec(pDb, "PRAGMA cache_size="+cacheSize, 0, 0, 0);
|
||||
this.logHtml(dbId,"cache_size =",cacheSize);
|
||||
}catch(e){
|
||||
if(pDb) capi.sqlite3_close_v2(pDb);
|
||||
}finally{
|
||||
wasm.scopedAllocPop(stack);
|
||||
}
|
||||
d.handle = pDb;
|
||||
d.clear = ()=>clearDbSqlite(d);
|
||||
}
|
||||
d.clear();
|
||||
this.logHtml("Opened db:",dbId,d.filename);
|
||||
console.log("db =",d);
|
||||
return d;
|
||||
},
|
||||
|
||||
run: function(sqlite3){
|
||||
delete this.run;
|
||||
this.sqlite3 = sqlite3;
|
||||
const capi = sqlite3.capi, wasm = sqlite3.wasm;
|
||||
this.logHtml("Loaded module:",capi.sqlite3_libversion(), capi.sqlite3_sourceid());
|
||||
this.logHtml("WASM heap size =",wasm.heap8().length);
|
||||
this.loadSqlList();
|
||||
if(capi.sqlite3_wasmfs_opfs_dir()){
|
||||
E('#warn-opfs').classList.remove('hidden');
|
||||
}else{
|
||||
E('#warn-opfs').remove();
|
||||
E('option[value=wasmfs-opfs]').disabled = true;
|
||||
}
|
||||
if('function' === typeof self.openDatabase){
|
||||
E('#warn-websql').classList.remove('hidden');
|
||||
}else{
|
||||
E('option[value=websql]').disabled = true;
|
||||
E('#warn-websql').remove();
|
||||
}
|
||||
const who = this;
|
||||
if(this.e.cbReverseLog.checked){
|
||||
this.e.output.classList.add('reverse');
|
||||
}
|
||||
this.e.cbReverseLog.addEventListener('change', function(){
|
||||
who.e.output.classList[this.checked ? 'add' : 'remove']('reverse');
|
||||
}, false);
|
||||
this.e.btnClear.addEventListener('click', ()=>this.cls(), false);
|
||||
this.e.btnRun.addEventListener('click', function(){
|
||||
if(!who.e.selSql.value) return;
|
||||
who.evalFile(who.e.selSql.value);
|
||||
}, false);
|
||||
this.e.btnRunNext.addEventListener('click', function(){
|
||||
++who.e.selSql.selectedIndex;
|
||||
if(!who.e.selSql.value) return;
|
||||
who.evalFile(who.e.selSql.value);
|
||||
}, false);
|
||||
this.e.btnReset.addEventListener('click', function(){
|
||||
who.clearStorage(true);
|
||||
}, false);
|
||||
this.e.btnExportMetrics.addEventListener('click', function(){
|
||||
who.logHtml2('warning',"Triggering download of metrics CSV. Check your downloads folder.");
|
||||
who.downloadMetrics();
|
||||
//const m = who.metricsToArrays();
|
||||
//console.log("Metrics:",who.metrics, m);
|
||||
});
|
||||
this.e.selImpl.addEventListener('change', function(){
|
||||
who.getSelectedDb();
|
||||
});
|
||||
this.e.btnRunRemaining.addEventListener('click', async function(){
|
||||
let v = who.e.selSql.value;
|
||||
const timeStart = performance.now();
|
||||
while(v){
|
||||
await who.evalFile(v);
|
||||
if(who.gotError){
|
||||
who.logErr("Error handling script",v,":",who.gotError.message);
|
||||
break;
|
||||
}
|
||||
++who.e.selSql.selectedIndex;
|
||||
v = who.e.selSql.value;
|
||||
}
|
||||
const timeTotal = performance.now() - timeStart;
|
||||
who.logHtml("Run-remaining time:",timeTotal,"ms ("+(timeTotal/1000/60)+" minute(s))");
|
||||
who.clearStorage();
|
||||
}, false);
|
||||
}/*run()*/
|
||||
}/*App*/;
|
||||
|
||||
self.sqlite3TestModule.initSqlite3().then(function(sqlite3_){
|
||||
sqlite3 = sqlite3_;
|
||||
self.App = App /* only to facilitate dev console access */;
|
||||
App.run(sqlite3);
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,236 @@
|
||||
/*
|
||||
2022-05-22
|
||||
|
||||
The author disclaims copyright to this source code. In place of a
|
||||
legal notice, here is a blessing:
|
||||
|
||||
* May you do good and not evil.
|
||||
* May you find forgiveness for yourself and forgive others.
|
||||
* May you share freely, never taking more than you give.
|
||||
|
||||
***********************************************************************
|
||||
|
||||
This file contains bootstrapping code used by various test scripts
|
||||
which live in this file's directory.
|
||||
*/
|
||||
'use strict';
|
||||
(function(self){
|
||||
/* querySelectorAll() proxy */
|
||||
const EAll = function(/*[element=document,] cssSelector*/){
|
||||
return (arguments.length>1 ? arguments[0] : document)
|
||||
.querySelectorAll(arguments[arguments.length-1]);
|
||||
};
|
||||
/* querySelector() proxy */
|
||||
const E = function(/*[element=document,] cssSelector*/){
|
||||
return (arguments.length>1 ? arguments[0] : document)
|
||||
.querySelector(arguments[arguments.length-1]);
|
||||
};
|
||||
|
||||
/**
|
||||
Helpers for writing sqlite3-specific tests.
|
||||
*/
|
||||
self.SqliteTestUtil = {
|
||||
/** Running total of the number of tests run via
|
||||
this API. */
|
||||
counter: 0,
|
||||
/**
|
||||
If expr is a function, it is called and its result
|
||||
is returned, coerced to a bool, else expr, coerced to
|
||||
a bool, is returned.
|
||||
*/
|
||||
toBool: function(expr){
|
||||
return (expr instanceof Function) ? !!expr() : !!expr;
|
||||
},
|
||||
/** abort() if expr is false. If expr is a function, it
|
||||
is called and its result is evaluated.
|
||||
*/
|
||||
assert: function f(expr, msg){
|
||||
if(!f._){
|
||||
f._ = ('undefined'===typeof abort
|
||||
? (msg)=>{throw new Error(msg)}
|
||||
: abort);
|
||||
}
|
||||
++this.counter;
|
||||
if(!this.toBool(expr)){
|
||||
f._(msg || "Assertion failed.");
|
||||
}
|
||||
return this;
|
||||
},
|
||||
/** Identical to assert() but throws instead of calling
|
||||
abort(). */
|
||||
affirm: function(expr, msg){
|
||||
++this.counter;
|
||||
if(!this.toBool(expr)) throw new Error(msg || "Affirmation failed.");
|
||||
return this;
|
||||
},
|
||||
/** Calls f() and squelches any exception it throws. If it
|
||||
does not throw, this function throws. */
|
||||
mustThrow: function(f, msg){
|
||||
++this.counter;
|
||||
let err;
|
||||
try{ f(); } catch(e){err=e;}
|
||||
if(!err) throw new Error(msg || "Expected exception.");
|
||||
return this;
|
||||
},
|
||||
/**
|
||||
Works like mustThrow() but expects filter to be a regex,
|
||||
function, or string to match/filter the resulting exception
|
||||
against. If f() does not throw, this test fails and an Error is
|
||||
thrown. If filter is a regex, the test passes if
|
||||
filter.test(error.message) passes. If it's a function, the test
|
||||
passes if filter(error) returns truthy. If it's a string, the
|
||||
test passes if the filter matches the exception message
|
||||
precisely. In all other cases the test fails, throwing an
|
||||
Error.
|
||||
|
||||
If it throws, msg is used as the error report unless it's falsy,
|
||||
in which case a default is used.
|
||||
*/
|
||||
mustThrowMatching: function(f, filter, msg){
|
||||
++this.counter;
|
||||
let err;
|
||||
try{ f(); } catch(e){err=e;}
|
||||
if(!err) throw new Error(msg || "Expected exception.");
|
||||
let pass = false;
|
||||
if(filter instanceof RegExp) pass = filter.test(err.message);
|
||||
else if(filter instanceof Function) pass = filter(err);
|
||||
else if('string' === typeof filter) pass = (err.message === filter);
|
||||
if(!pass){
|
||||
throw new Error(msg || ("Filter rejected this exception: "+err.message));
|
||||
}
|
||||
return this;
|
||||
},
|
||||
/** Throws if expr is truthy or expr is a function and expr()
|
||||
returns truthy. */
|
||||
throwIf: function(expr, msg){
|
||||
++this.counter;
|
||||
if(this.toBool(expr)) throw new Error(msg || "throwIf() failed");
|
||||
return this;
|
||||
},
|
||||
/** Throws if expr is falsy or expr is a function and expr()
|
||||
returns falsy. */
|
||||
throwUnless: function(expr, msg){
|
||||
++this.counter;
|
||||
if(!this.toBool(expr)) throw new Error(msg || "throwUnless() failed");
|
||||
return this;
|
||||
},
|
||||
|
||||
/**
|
||||
Parses window.location.search-style string into an object
|
||||
containing key/value pairs of URL arguments (already
|
||||
urldecoded). The object is created using Object.create(null),
|
||||
so contains only parsed-out properties and has no prototype
|
||||
(and thus no inherited properties).
|
||||
|
||||
If the str argument is not passed (arguments.length==0) then
|
||||
window.location.search.substring(1) is used by default. If
|
||||
neither str is passed in nor window exists then false is returned.
|
||||
|
||||
On success it returns an Object containing the key/value pairs
|
||||
parsed from the string. Keys which have no value are treated
|
||||
has having the boolean true value.
|
||||
|
||||
Pedantic licensing note: this code has appeared in other source
|
||||
trees, but was originally written by the same person who pasted
|
||||
it into those trees.
|
||||
*/
|
||||
processUrlArgs: function(str) {
|
||||
if( 0 === arguments.length ) {
|
||||
if( ('undefined' === typeof window) ||
|
||||
!window.location ||
|
||||
!window.location.search ) return false;
|
||||
else str = (''+window.location.search).substring(1);
|
||||
}
|
||||
if( ! str ) return false;
|
||||
str = (''+str).split(/#/,2)[0]; // remove #... to avoid it being added as part of the last value.
|
||||
const args = Object.create(null);
|
||||
const sp = str.split(/&+/);
|
||||
const rx = /^([^=]+)(=(.+))?/;
|
||||
var i, m;
|
||||
for( i in sp ) {
|
||||
m = rx.exec( sp[i] );
|
||||
if( ! m ) continue;
|
||||
args[decodeURIComponent(m[1])] = (m[3] ? decodeURIComponent(m[3]) : true);
|
||||
}
|
||||
return args;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
This is a module object for use with the emscripten-installed
|
||||
sqlite3InitModule() factory function.
|
||||
*/
|
||||
self.sqlite3TestModule = {
|
||||
/**
|
||||
Array of functions to call after Emscripten has initialized the
|
||||
wasm module. Each gets passed the Emscripten module object
|
||||
(which is _this_ object).
|
||||
*/
|
||||
postRun: [
|
||||
/* function(theModule){...} */
|
||||
],
|
||||
//onRuntimeInitialized: function(){},
|
||||
/* Proxy for C-side stdout output. */
|
||||
print: (...args)=>{console.log(...args)},
|
||||
/* Proxy for C-side stderr output. */
|
||||
printErr: (...args)=>{console.error(...args)},
|
||||
/**
|
||||
Called by the Emscripten module init bits to report loading
|
||||
progress. It gets passed an empty argument when loading is done
|
||||
(after onRuntimeInitialized() and any this.postRun callbacks
|
||||
have been run).
|
||||
*/
|
||||
setStatus: function f(text){
|
||||
if(!f.last){
|
||||
f.last = { text: '', step: 0 };
|
||||
f.ui = {
|
||||
status: E('#module-status'),
|
||||
progress: E('#module-progress'),
|
||||
spinner: E('#module-spinner')
|
||||
};
|
||||
}
|
||||
if(text === f.last.text) return;
|
||||
f.last.text = text;
|
||||
if(f.ui.progress){
|
||||
f.ui.progress.value = f.last.step;
|
||||
f.ui.progress.max = f.last.step + 1;
|
||||
}
|
||||
++f.last.step;
|
||||
if(text) {
|
||||
f.ui.status.classList.remove('hidden');
|
||||
f.ui.status.innerText = text;
|
||||
}else{
|
||||
if(f.ui.progress){
|
||||
f.ui.progress.remove();
|
||||
f.ui.spinner.remove();
|
||||
delete f.ui.progress;
|
||||
delete f.ui.spinner;
|
||||
}
|
||||
f.ui.status.classList.add('hidden');
|
||||
}
|
||||
},
|
||||
/**
|
||||
Config options used by the Emscripten-dependent initialization
|
||||
which happens via this.initSqlite3(). This object gets
|
||||
(indirectly) passed to sqlite3ApiBootstrap() to configure the
|
||||
sqlite3 API.
|
||||
*/
|
||||
sqlite3ApiConfig: {
|
||||
wasmfsOpfsDir: "/opfs"
|
||||
},
|
||||
/**
|
||||
Intended to be called by apps which need to call the
|
||||
Emscripten-installed sqlite3InitModule() routine. This function
|
||||
temporarily installs this.sqlite3ApiConfig into the self
|
||||
object, calls it sqlite3InitModule(), and removes
|
||||
self.sqlite3ApiConfig after initialization is done. Returns the
|
||||
promise from sqlite3InitModule(), and the next then() handler
|
||||
will get the sqlite3 API object as its argument.
|
||||
*/
|
||||
initSqlite3: function(){
|
||||
self.sqlite3ApiConfig = this.sqlite3ApiConfig;
|
||||
return self.sqlite3InitModule(this).finally(()=>delete self.sqlite3ApiConfig);
|
||||
}
|
||||
};
|
||||
})(self/*window or worker*/);
|
||||
@@ -0,0 +1,63 @@
|
||||
body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
textarea {
|
||||
font-family: monospace;
|
||||
}
|
||||
header {
|
||||
font-size: 130%;
|
||||
font-weight: bold;
|
||||
}
|
||||
.hidden, .initially-hidden {
|
||||
position: absolute !important;
|
||||
opacity: 0 !important;
|
||||
pointer-events: none !important;
|
||||
display: none !important;
|
||||
}
|
||||
fieldset.options {
|
||||
font-size: 75%;
|
||||
}
|
||||
fieldset > legend {
|
||||
padding: 0 0.5em;
|
||||
}
|
||||
span.labeled-input {
|
||||
padding: 0.25em;
|
||||
margin: 0.25em 0.5em;
|
||||
border-radius: 0.25em;
|
||||
white-space: nowrap;
|
||||
background: #0002;
|
||||
}
|
||||
.center { text-align: center; }
|
||||
.error {
|
||||
color: red;
|
||||
background-color: yellow;
|
||||
}
|
||||
.strong { font-weight: 700 }
|
||||
.warning { color: firebrick; }
|
||||
.green { color: darkgreen; }
|
||||
.tests-pass { background-color: green; color: white }
|
||||
.tests-fail { background-color: red; color: yellow }
|
||||
.faded { opacity: 0.5; }
|
||||
.group-start { color: blue; }
|
||||
.group-end { color: blue; }
|
||||
.input-wrapper {
|
||||
white-space: nowrap;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
#test-output {
|
||||
border: 1px inset;
|
||||
border-radius: 0.25em;
|
||||
padding: 0.25em;
|
||||
/*max-height: 30em;*/
|
||||
overflow: auto;
|
||||
white-space: break-spaces;
|
||||
display: flex; flex-direction: column;
|
||||
font-family: monospace;
|
||||
}
|
||||
#test-output.reverse {
|
||||
flex-direction: column-reverse;
|
||||
}
|
||||
label[for] { cursor: pointer }
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,44 @@
|
||||
<!doctype html>
|
||||
<html lang="en-us">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
||||
<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
|
||||
<title>Hello, sqlite3</title>
|
||||
<style>
|
||||
.warning, .error {color: red}
|
||||
.error {background-color: yellow}
|
||||
body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
font-family: monospace;
|
||||
white-space: break-spaces;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>1-2-sqlite3 worker demo</h1>
|
||||
<script>(function(){
|
||||
const logHtml = function(cssClass,...args){
|
||||
const ln = document.createElement('div');
|
||||
if(cssClass) ln.classList.add(cssClass);
|
||||
ln.append(document.createTextNode(args.join(' ')));
|
||||
document.body.append(ln);
|
||||
};
|
||||
const w = new Worker("demo-123.js?sqlite3.dir=jswasm"
|
||||
/* Note the URL argument on that name. See
|
||||
the notes in demo-123.js (search for
|
||||
"importScripts") for why we need
|
||||
that. */);
|
||||
w.onmessage = function({data}){
|
||||
switch(data.type){
|
||||
case 'log':
|
||||
logHtml(data.payload.cssClass, ...data.payload.args);
|
||||
break;
|
||||
default:
|
||||
logHtml('error',"Unhandled message:",data.type);
|
||||
};
|
||||
};
|
||||
})();</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,24 @@
|
||||
<!doctype html>
|
||||
<html lang="en-us">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
||||
<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
|
||||
<title>Hello, sqlite3</title>
|
||||
<style>
|
||||
.warning, .error {color: red}
|
||||
.error {background-color: yellow}
|
||||
body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
font-family: monospace;
|
||||
white-space: break-spaces;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>1-2-sqlite3 demo</h1>
|
||||
<script src="jswasm/sqlite3.js"></script>
|
||||
<script src="demo-123.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,289 @@
|
||||
/*
|
||||
2022-09-19
|
||||
|
||||
The author disclaims copyright to this source code. In place of a
|
||||
legal notice, here is a blessing:
|
||||
|
||||
* May you do good and not evil.
|
||||
* May you find forgiveness for yourself and forgive others.
|
||||
* May you share freely, never taking more than you give.
|
||||
|
||||
***********************************************************************
|
||||
|
||||
A basic demonstration of the SQLite3 "OO#1" API.
|
||||
*/
|
||||
'use strict';
|
||||
(function(){
|
||||
/**
|
||||
Set up our output channel differently depending
|
||||
on whether we are running in a worker thread or
|
||||
the main (UI) thread.
|
||||
*/
|
||||
let logHtml;
|
||||
if(self.window === self /* UI thread */){
|
||||
console.log("Running demo from main UI thread.");
|
||||
logHtml = function(cssClass,...args){
|
||||
const ln = document.createElement('div');
|
||||
if(cssClass) ln.classList.add(cssClass);
|
||||
ln.append(document.createTextNode(args.join(' ')));
|
||||
document.body.append(ln);
|
||||
};
|
||||
}else{ /* Worker thread */
|
||||
console.log("Running demo from Worker thread.");
|
||||
logHtml = function(cssClass,...args){
|
||||
postMessage({
|
||||
type:'log',
|
||||
payload:{cssClass, args}
|
||||
});
|
||||
};
|
||||
}
|
||||
const log = (...args)=>logHtml('',...args);
|
||||
const warn = (...args)=>logHtml('warning',...args);
|
||||
const error = (...args)=>logHtml('error',...args);
|
||||
|
||||
const demo1 = function(sqlite3){
|
||||
const capi = sqlite3.capi/*C-style API*/,
|
||||
oo = sqlite3.oo1/*high-level OO API*/;
|
||||
log("sqlite3 version",capi.sqlite3_libversion(), capi.sqlite3_sourceid());
|
||||
const db = new oo.DB("/mydb.sqlite3",'ct');
|
||||
log("transient db =",db.filename);
|
||||
/**
|
||||
Never(!) rely on garbage collection to clean up DBs and
|
||||
(especially) prepared statements. Always wrap their lifetimes
|
||||
in a try/finally construct, as demonstrated below. By and
|
||||
large, client code can entirely avoid lifetime-related
|
||||
complications of prepared statement objects by using the
|
||||
DB.exec() method for SQL execution.
|
||||
*/
|
||||
try {
|
||||
log("Create a table...");
|
||||
db.exec("CREATE TABLE IF NOT EXISTS t(a,b)");
|
||||
//Equivalent:
|
||||
db.exec({
|
||||
sql:"CREATE TABLE IF NOT EXISTS t(a,b)"
|
||||
// ... numerous other options ...
|
||||
});
|
||||
// SQL can be either a string or a byte array
|
||||
// or an array of strings which get concatenated
|
||||
// together as-is (so be sure to end each statement
|
||||
// with a semicolon).
|
||||
|
||||
log("Insert some data using exec()...");
|
||||
let i;
|
||||
for( i = 20; i <= 25; ++i ){
|
||||
db.exec({
|
||||
sql: "insert into t(a,b) values (?,?)",
|
||||
// bind by parameter index...
|
||||
bind: [i, i*2]
|
||||
});
|
||||
db.exec({
|
||||
sql: "insert into t(a,b) values ($a,$b)",
|
||||
// bind by parameter name...
|
||||
bind: {$a: i * 10, $b: i * 20}
|
||||
});
|
||||
}
|
||||
|
||||
log("Insert using a prepared statement...");
|
||||
let q = db.prepare([
|
||||
// SQL may be a string or array of strings
|
||||
// (concatenated w/o separators).
|
||||
"insert into t(a,b) ",
|
||||
"values(?,?)"
|
||||
]);
|
||||
try {
|
||||
for( i = 100; i < 103; ++i ){
|
||||
q.bind( [i, i*2] ).step();
|
||||
q.reset();
|
||||
}
|
||||
// Equivalent...
|
||||
for( i = 103; i <= 105; ++i ){
|
||||
q.bind(1, i).bind(2, i*2).stepReset();
|
||||
}
|
||||
}finally{
|
||||
q.finalize();
|
||||
}
|
||||
|
||||
log("Query data with exec() using rowMode 'array'...");
|
||||
db.exec({
|
||||
sql: "select a from t order by a limit 3",
|
||||
rowMode: 'array', // 'array' (default), 'object', or 'stmt'
|
||||
callback: function(row){
|
||||
log("row ",++this.counter,"=",row);
|
||||
}.bind({counter: 0})
|
||||
});
|
||||
|
||||
log("Query data with exec() using rowMode 'object'...");
|
||||
db.exec({
|
||||
sql: "select a as aa, b as bb from t order by aa limit 3",
|
||||
rowMode: 'object',
|
||||
callback: function(row){
|
||||
log("row ",++this.counter,"=",JSON.stringify(row));
|
||||
}.bind({counter: 0})
|
||||
});
|
||||
|
||||
log("Query data with exec() using rowMode 'stmt'...");
|
||||
db.exec({
|
||||
sql: "select a from t order by a limit 3",
|
||||
rowMode: 'stmt',
|
||||
callback: function(row){
|
||||
log("row ",++this.counter,"get(0) =",row.get(0));
|
||||
}.bind({counter: 0})
|
||||
});
|
||||
|
||||
log("Query data with exec() using rowMode INTEGER (result column index)...");
|
||||
db.exec({
|
||||
sql: "select a, b from t order by a limit 3",
|
||||
rowMode: 1, // === result column 1
|
||||
callback: function(row){
|
||||
log("row ",++this.counter,"b =",row);
|
||||
}.bind({counter: 0})
|
||||
});
|
||||
|
||||
log("Query data with exec() using rowMode $COLNAME (result column name)...");
|
||||
db.exec({
|
||||
sql: "select a a, b from t order by a limit 3",
|
||||
rowMode: '$a',
|
||||
callback: function(value){
|
||||
log("row ",++this.counter,"a =",value);
|
||||
}.bind({counter: 0})
|
||||
});
|
||||
|
||||
log("Query data with exec() without a callback...");
|
||||
let resultRows = [];
|
||||
db.exec({
|
||||
sql: "select a, b from t order by a limit 3",
|
||||
rowMode: 'object',
|
||||
resultRows: resultRows
|
||||
});
|
||||
log("Result rows:",JSON.stringify(resultRows,undefined,2));
|
||||
|
||||
log("Create a scalar UDF...");
|
||||
db.createFunction({
|
||||
name: 'twice',
|
||||
xFunc: function(pCx, arg){ // note the call arg count
|
||||
return arg + arg;
|
||||
}
|
||||
});
|
||||
log("Run scalar UDF and collect result column names...");
|
||||
let columnNames = [];
|
||||
db.exec({
|
||||
sql: "select a, twice(a), twice(''||a) from t order by a desc limit 3",
|
||||
columnNames: columnNames,
|
||||
rowMode: 'stmt',
|
||||
callback: function(row){
|
||||
log("a =",row.get(0), "twice(a) =", row.get(1),
|
||||
"twice(''||a) =",row.get(2));
|
||||
}
|
||||
});
|
||||
log("Result column names:",columnNames);
|
||||
|
||||
try{
|
||||
log("The following use of the twice() UDF will",
|
||||
"fail because of incorrect arg count...");
|
||||
db.exec("select twice(1,2,3)");
|
||||
}catch(e){
|
||||
warn("Got expected exception:",e.message);
|
||||
}
|
||||
|
||||
try {
|
||||
db.transaction( function(D) {
|
||||
D.exec("delete from t");
|
||||
log("In transaction: count(*) from t =",db.selectValue("select count(*) from t"));
|
||||
throw new sqlite3.SQLite3Error("Demonstrating transaction() rollback");
|
||||
});
|
||||
}catch(e){
|
||||
if(e instanceof sqlite3.SQLite3Error){
|
||||
log("Got expected exception from db.transaction():",e.message);
|
||||
log("count(*) from t =",db.selectValue("select count(*) from t"));
|
||||
}else{
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
db.savepoint( function(D) {
|
||||
D.exec("delete from t");
|
||||
log("In savepoint: count(*) from t =",db.selectValue("select count(*) from t"));
|
||||
D.savepoint(function(DD){
|
||||
const rows = [];
|
||||
DD.exec({
|
||||
sql: ["insert into t(a,b) values(99,100);",
|
||||
"select count(*) from t"],
|
||||
rowMode: 0,
|
||||
resultRows: rows
|
||||
});
|
||||
log("In nested savepoint. Row count =",rows[0]);
|
||||
throw new sqlite3.SQLite3Error("Demonstrating nested savepoint() rollback");
|
||||
})
|
||||
});
|
||||
}catch(e){
|
||||
if(e instanceof sqlite3.SQLite3Error){
|
||||
log("Got expected exception from nested db.savepoint():",e.message);
|
||||
log("count(*) from t =",db.selectValue("select count(*) from t"));
|
||||
}else{
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}finally{
|
||||
db.close();
|
||||
}
|
||||
|
||||
log("That's all, folks!");
|
||||
|
||||
/**
|
||||
Some of the features of the OO API not demonstrated above...
|
||||
|
||||
- get change count (total or statement-local, 32- or 64-bit)
|
||||
- get a DB's file name
|
||||
|
||||
Misc. Stmt features:
|
||||
|
||||
- Various forms of bind()
|
||||
- clearBindings()
|
||||
- reset()
|
||||
- Various forms of step()
|
||||
- Variants of get() for explicit type treatment/conversion,
|
||||
e.g. getInt(), getFloat(), getBlob(), getJSON()
|
||||
- getColumnName(ndx), getColumnNames()
|
||||
- getParamIndex(name)
|
||||
*/
|
||||
}/*demo1()*/;
|
||||
|
||||
log("Loading and initializing sqlite3 module...");
|
||||
if(self.window!==self) /*worker thread*/{
|
||||
/*
|
||||
If sqlite3.js is in a directory other than this script, in order
|
||||
to get sqlite3.js to resolve sqlite3.wasm properly, we have to
|
||||
explicitly tell it where sqlite3.js is being loaded from. We do
|
||||
that by passing the `sqlite3.dir=theDirName` URL argument to
|
||||
_this_ script. That URL argument will be seen by the JS/WASM
|
||||
loader and it will adjust the sqlite3.wasm path accordingly. If
|
||||
sqlite3.js/.wasm are in the same directory as this script then
|
||||
that's not needed.
|
||||
|
||||
URL arguments passed as part of the filename via importScripts()
|
||||
are simply lost, and such scripts see the self.location of
|
||||
_this_ script.
|
||||
*/
|
||||
let sqlite3Js = 'sqlite3.js';
|
||||
const urlParams = new URL(self.location.href).searchParams;
|
||||
if(urlParams.has('sqlite3.dir')){
|
||||
sqlite3Js = urlParams.get('sqlite3.dir') + '/' + sqlite3Js;
|
||||
}
|
||||
importScripts(sqlite3Js);
|
||||
}
|
||||
self.sqlite3InitModule({
|
||||
// We can redirect any stdout/stderr from the module
|
||||
// like so...
|
||||
print: log,
|
||||
printErr: error
|
||||
}).then(function(sqlite3){
|
||||
//console.log('sqlite3 =',sqlite3);
|
||||
log("Done initializing. Running demo...");
|
||||
try {
|
||||
demo1(sqlite3);
|
||||
}catch(e){
|
||||
error("Exception:",e.message);
|
||||
}
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,49 @@
|
||||
<!doctype html>
|
||||
<html lang="en-us">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
||||
<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
|
||||
<link rel="stylesheet" href="common/emscripten.css"/>
|
||||
<link rel="stylesheet" href="common/testing.css"/>
|
||||
<title>sqlite3-kvvfs.js tests</title>
|
||||
</head>
|
||||
<body>
|
||||
<header id='titlebar'><span>sqlite3-kvvfs.js tests</span></header>
|
||||
<!-- emscripten bits -->
|
||||
<figure id="module-spinner">
|
||||
<div class="spinner"></div>
|
||||
<div class='center'><strong>Initializing app...</strong></div>
|
||||
<div class='center'>
|
||||
On a slow internet connection this may take a moment. If this
|
||||
message displays for "a long time", intialization may have
|
||||
failed and the JavaScript console may contain clues as to why.
|
||||
</div>
|
||||
</figure>
|
||||
<div class="emscripten" id="module-status">Downloading...</div>
|
||||
<div class="emscripten">
|
||||
<progress value="0" max="100" id="module-progress" hidden='1'></progress>
|
||||
</div><!-- /emscripten bits -->
|
||||
<fieldset>
|
||||
<legend>Options</legend>
|
||||
<div class='toolbar'>
|
||||
<button id='btn-clear-log'>Clear log</button>
|
||||
<button id='btn-clear-storage'>Clear storage</button>
|
||||
<button id='btn-init-db'>(Re)init db</button>
|
||||
<button id='btn-select1'>Select db rows</button>
|
||||
<button id='btn-storage-size'>Approx. storage size</button>
|
||||
</div>
|
||||
</fieldset>
|
||||
<div id='test-output'></div>
|
||||
<style>
|
||||
.toolbar {
|
||||
display: flex;
|
||||
}
|
||||
.toolbar > * { margin: 0.25em; }
|
||||
fieldset { border-radius: 0.5em; }
|
||||
</style>
|
||||
<script src="jswasm/sqlite3.js"></script>
|
||||
<script src="common/SqliteTestUtil.js"></script>
|
||||
<script src="demo-jsstorage.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,114 @@
|
||||
/*
|
||||
2022-09-12
|
||||
|
||||
The author disclaims copyright to this source code. In place of a
|
||||
legal notice, here is a blessing:
|
||||
|
||||
* May you do good and not evil.
|
||||
* May you find forgiveness for yourself and forgive others.
|
||||
* May you share freely, never taking more than you give.
|
||||
|
||||
***********************************************************************
|
||||
|
||||
A basic test script for sqlite3.wasm with kvvfs support. This file
|
||||
must be run in main JS thread and sqlite3.js must have been loaded
|
||||
before it.
|
||||
*/
|
||||
'use strict';
|
||||
(function(){
|
||||
const T = self.SqliteTestUtil;
|
||||
const toss = function(...args){throw new Error(args.join(' '))};
|
||||
const debug = console.debug.bind(console);
|
||||
const eOutput = document.querySelector('#test-output');
|
||||
const logC = console.log.bind(console)
|
||||
const logE = function(domElement){
|
||||
eOutput.append(domElement);
|
||||
};
|
||||
const logHtml = function(cssClass,...args){
|
||||
const ln = document.createElement('div');
|
||||
if(cssClass) ln.classList.add(cssClass);
|
||||
ln.append(document.createTextNode(args.join(' ')));
|
||||
logE(ln);
|
||||
}
|
||||
const log = function(...args){
|
||||
logC(...args);
|
||||
logHtml('',...args);
|
||||
};
|
||||
const warn = function(...args){
|
||||
logHtml('warning',...args);
|
||||
};
|
||||
const error = function(...args){
|
||||
logHtml('error',...args);
|
||||
};
|
||||
|
||||
const runTests = function(sqlite3){
|
||||
const capi = sqlite3.capi,
|
||||
oo = sqlite3.oo1,
|
||||
wasm = sqlite3.wasm;
|
||||
log("Loaded module:",capi.sqlite3_libversion(), capi.sqlite3_sourceid());
|
||||
T.assert( 0 !== capi.sqlite3_vfs_find(null) );
|
||||
if(!capi.sqlite3_vfs_find('kvvfs')){
|
||||
error("This build is not kvvfs-capable.");
|
||||
return;
|
||||
}
|
||||
|
||||
const dbStorage = 0 ? 'session' : 'local';
|
||||
const theStore = 's'===dbStorage[0] ? sessionStorage : localStorage;
|
||||
const db = new oo.JsStorageDb( dbStorage );
|
||||
// Or: oo.DB(dbStorage, 'c', 'kvvfs')
|
||||
log("db.storageSize():",db.storageSize());
|
||||
document.querySelector('#btn-clear-storage').addEventListener('click',function(){
|
||||
const sz = db.clearStorage();
|
||||
log("kvvfs",db.filename+"Storage cleared:",sz,"entries.");
|
||||
});
|
||||
document.querySelector('#btn-clear-log').addEventListener('click',function(){
|
||||
eOutput.innerText = '';
|
||||
});
|
||||
document.querySelector('#btn-init-db').addEventListener('click',function(){
|
||||
try{
|
||||
const saveSql = [];
|
||||
db.exec({
|
||||
sql: ["drop table if exists t;",
|
||||
"create table if not exists t(a);",
|
||||
"insert into t(a) values(?),(?),(?)"],
|
||||
bind: [performance.now() >> 0,
|
||||
(performance.now() * 2) >> 0,
|
||||
(performance.now() / 2) >> 0],
|
||||
saveSql
|
||||
});
|
||||
console.log("saveSql =",saveSql,theStore);
|
||||
log("DB (re)initialized.");
|
||||
}catch(e){
|
||||
error(e.message);
|
||||
}
|
||||
});
|
||||
const btnSelect = document.querySelector('#btn-select1');
|
||||
btnSelect.addEventListener('click',function(){
|
||||
log("DB rows:");
|
||||
try{
|
||||
db.exec({
|
||||
sql: "select * from t order by a",
|
||||
rowMode: 0,
|
||||
callback: (v)=>log(v)
|
||||
});
|
||||
}catch(e){
|
||||
error(e.message);
|
||||
}
|
||||
});
|
||||
document.querySelector('#btn-storage-size').addEventListener('click',function(){
|
||||
log("size.storageSize(",dbStorage,") says", db.storageSize(),
|
||||
"bytes");
|
||||
});
|
||||
log("Storage backend:",db.filename);
|
||||
if(0===db.selectValue('select count(*) from sqlite_master')){
|
||||
log("DB is empty. Use the init button to populate it.");
|
||||
}else{
|
||||
log("DB contains data from a previous session. Use the Clear Ctorage button to delete it.");
|
||||
btnSelect.click();
|
||||
}
|
||||
};
|
||||
|
||||
sqlite3InitModule(self.sqlite3TestModule).then((sqlite3)=>{
|
||||
runTests(sqlite3);
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,34 @@
|
||||
<!doctype html>
|
||||
<html lang="en-us">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
||||
<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
|
||||
<link rel="stylesheet" href="common/emscripten.css"/>
|
||||
<link rel="stylesheet" href="common/testing.css"/>
|
||||
<title>worker-promise tests</title>
|
||||
</head>
|
||||
<body>
|
||||
<header id='titlebar'><span>worker-promise tests</span></header>
|
||||
<!-- emscripten bits -->
|
||||
<figure id="module-spinner">
|
||||
<div class="spinner"></div>
|
||||
<div class='center'><strong>Initializing app...</strong></div>
|
||||
<div class='center'>
|
||||
On a slow internet connection this may take a moment. If this
|
||||
message displays for "a long time", intialization may have
|
||||
failed and the JavaScript console may contain clues as to why.
|
||||
</div>
|
||||
</figure>
|
||||
<div class="emscripten" id="module-status">Downloading...</div>
|
||||
<div class="emscripten">
|
||||
<progress value="0" max="100" id="module-progress" hidden='1'></progress>
|
||||
</div><!-- /emscripten bits -->
|
||||
<div>Most stuff on this page happens in the dev console.</div>
|
||||
<hr>
|
||||
<div id='test-output'></div>
|
||||
<script src="common/SqliteTestUtil.js"></script>
|
||||
<script src="jswasm/sqlite3-worker1-promiser.js"></script>
|
||||
<script src="demo-worker1-promiser.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user