Compare commits
563 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 |
+34
-154
@@ -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 \
|
||||
@@ -555,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
|
||||
#
|
||||
@@ -621,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
|
||||
@@ -631,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 $(TOP)/test/fuzzinvariants.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.
|
||||
@@ -681,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
|
||||
@@ -938,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
|
||||
|
||||
@@ -1102,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
|
||||
@@ -1387,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
|
||||
@@ -1476,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)
|
||||
@@ -1500,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
|
||||
@@ -1520,150 +1542,8 @@ sqlite3.dll: $(REAL_LIBOBJ) sqlite3.def
|
||||
$(TCC) -shared -o $@ sqlite3.def \
|
||||
-Wl,"--strip-all" $(REAL_LIBOBJ)
|
||||
|
||||
|
||||
#
|
||||
# fiddle/wasm section
|
||||
# Fiddle app
|
||||
#
|
||||
wasm_dir = ext/wasm
|
||||
wasm_dir_abs = $(TOP)/ext/wasm
|
||||
# ^^^ some emcc opts require absolute paths
|
||||
fiddle_dir = $(wasm_dir)/fiddle
|
||||
fiddle_dir_abs = $(TOP)/$(fiddle_dir)
|
||||
fiddle_module_js = $(fiddle_dir)/fiddle-module.js
|
||||
#emcc_opt = -O0
|
||||
#emcc_opt = -O1
|
||||
#emcc_opt = -O2
|
||||
#emcc_opt = -O3
|
||||
emcc_opt = -Oz
|
||||
emcc_flags = $(emcc_opt) \
|
||||
-sALLOW_TABLE_GROWTH \
|
||||
-sABORTING_MALLOC \
|
||||
-sSTRICT_JS \
|
||||
-sENVIRONMENT=web \
|
||||
-sMODULARIZE \
|
||||
-sEXPORTED_RUNTIME_METHODS=@$(wasm_dir_abs)/EXPORTED_RUNTIME_METHODS.fiddle \
|
||||
-sDYNAMIC_EXECUTION=0 \
|
||||
--minify 0 \
|
||||
-I. $(SHELL_OPT) \
|
||||
-DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_UTF16 -DSQLITE_OMIT_DEPRECATED
|
||||
$(fiddle_module_js): Makefile sqlite3.c shell.c \
|
||||
$(wasm_dir)/EXPORTED_RUNTIME_METHODS.fiddle \
|
||||
$(wasm_dir)/EXPORTED_FUNCTIONS.fiddle
|
||||
emcc -o $@ $(emcc_flags) \
|
||||
-sEXPORT_NAME=initFiddleModule \
|
||||
-sEXPORTED_FUNCTIONS=@$(wasm_dir_abs)/EXPORTED_FUNCTIONS.fiddle \
|
||||
-DSQLITE_SHELL_FIDDLE \
|
||||
sqlite3.c shell.c
|
||||
gzip < $@ > $@.gz
|
||||
gzip < $(fiddle_dir)/fiddle-module.wasm > $(fiddle_dir)/fiddle-module.wasm.gz
|
||||
$(fiddle_dir)/fiddle.js.gz: $(fiddle_dir)/fiddle.js
|
||||
gzip < $< > $@
|
||||
|
||||
fiddle_generated = $(fiddle_module_js) $(fiddle_module_js).gz \
|
||||
$(fiddle_dir)/fiddle-module.wasm \
|
||||
$(fiddle_dir)/fiddle-module.wasm.gz \
|
||||
$(fiddle_dir)/fiddle.js.gz
|
||||
|
||||
clean-fiddle:
|
||||
rm -f $(fiddle_generated)
|
||||
clean: clean-fiddle
|
||||
fiddle: $(fiddle_module_js) $(fiddle_dir)/fiddle.js.gz
|
||||
wasm: fiddle
|
||||
########################################################################
|
||||
# Explanation of the emcc build flags follows. Full docs for these can
|
||||
# be found at:
|
||||
#
|
||||
# https://github.com/emscripten-core/emscripten/blob/main/src/settings.js
|
||||
#
|
||||
# -sENVIRONMENT=web: elides bootstrap code related to non-web JS
|
||||
# environments like node.js. Removing this makes the output a tiny
|
||||
# tick larger but hypothetically makes it more portable to
|
||||
# non-browser JS environments.
|
||||
#
|
||||
# -sMODULARIZE: changes how the generated code is structured to avoid
|
||||
# declaring a global Module object and instead installing a function
|
||||
# which loads and initializes the module. The function is named...
|
||||
#
|
||||
# -sEXPORT_NAME=jsFunctionName (see -sMODULARIZE)
|
||||
#
|
||||
# -sEXPORTED_RUNTIME_METHODS=@/absolute/path/to/file: a file
|
||||
# containing a list of emscripten-supplied APIs, one per line, which
|
||||
# must be exported into the generated JS. Must be an absolute path!
|
||||
#
|
||||
# -sEXPORTED_FUNCTIONS=@/absolute/path/to/file: a file containing a
|
||||
# list of C functions, one per line, which must be exported via wasm
|
||||
# so they're visible to JS. C symbols names in that file must all
|
||||
# start with an underscore for reasons known only to the emcc
|
||||
# developers. e.g., _sqlite3_open_v2 and _sqlite3_finalize. Must be
|
||||
# an absolute path!
|
||||
#
|
||||
# -sSTRICT_JS ensures that the emitted JS code includes the 'use
|
||||
# strict' option. Note that -sSTRICT is more broadly-scoped and
|
||||
# results in build errors.
|
||||
#
|
||||
# -sALLOW_TABLE_GROWTH is required for (at a minimum) the UDF-binding
|
||||
# feature. Without it, JS functions cannot be made to proxy C-side
|
||||
# callbacks.
|
||||
#
|
||||
# -sABORTING_MALLOC causes the JS-bound _malloc() to abort rather than
|
||||
# return 0 on OOM. If set to 0 then all code which uses _malloc()
|
||||
# must, just like in C, check the result before using it, else
|
||||
# they're likely to corrupt the JS/WASM heap by writing to its
|
||||
# address of 0. It is, as of this writing, enabled in Emscripten by
|
||||
# default but we enable it explicitly in case that default changes.
|
||||
#
|
||||
# -sDYNAMIC_EXECUTION=0 disables eval() and the Function constructor.
|
||||
# If the build runs without these, it's preferable to use this flag
|
||||
# because certain execution environments disallow those constructs.
|
||||
# This flag is not strictly necessary, however.
|
||||
#
|
||||
# -sWASM_BIGINT is UNTESTED but "should" allow the int64-using C APIs
|
||||
# to work with JS/wasm, insofar as the JS environment supports the
|
||||
# BigInt type. That support requires an extremely recent browser:
|
||||
# Safari didn't get that support until late 2020.
|
||||
#
|
||||
# --no-entry: for compiling library code with no main(). If this is
|
||||
# not supplied and the code has a main(), it is called as part of the
|
||||
# module init process. Note that main() is #if'd out of shell.c
|
||||
# (renamed) when building in wasm mode.
|
||||
#
|
||||
# --pre-js/--post-js=FILE relative or absolute paths to JS files to
|
||||
# prepend/append to the emcc-generated bootstrapping JS. It's
|
||||
# easier/faster to develop with separate JS files (reduces rebuilding
|
||||
# requirements) but certain configurations, namely -sMODULARIZE, may
|
||||
# require using at least a --pre-js file. They can be used
|
||||
# individually and need not be paired.
|
||||
#
|
||||
# -O0..-O3 and -Oz: optimization levels affect not only C-style
|
||||
# optimization but whether or not the resulting generated JS code
|
||||
# gets minified. -O0 compiles _much_ more quickly than -O3 or -Oz,
|
||||
# and doesn't minimize any JS code, so is recommended for
|
||||
# development. -O3 or -Oz are recommended for deployment, but
|
||||
# primarily because -Oz will shrink the wasm file notably. JS-side
|
||||
# minification makes little difference in terms of overall
|
||||
# distributable size.
|
||||
#
|
||||
# --minify 0: disables minification of the generated JS code,
|
||||
# regardless of optimization level. Minification of the JS has
|
||||
# minimal overall effect in the larger scheme of things and results
|
||||
# in JS files which can neither be edited nor viewed as text files in
|
||||
# Fossil (which flags them as binary because of their extreme line
|
||||
# lengths). Interestingly, whether or not the comments in the
|
||||
# generated JS file get stripped is unaffected by this setting and
|
||||
# depends entirely on the optimization level. Higher optimization
|
||||
# levels reduce the size of the JS considerably even without
|
||||
# minification.
|
||||
#
|
||||
# ACHTUNG...
|
||||
#
|
||||
# -sALLOW_MEMORY_GROWTH is very tempting but has side-effects which
|
||||
# may break the higher-level code. Specifically, growning the memory
|
||||
# region beyong the default size requires that the app-visible arrays
|
||||
# which act as views for that memory buffer have to be replaced,
|
||||
# which inherently leaves any client-side references to those arrays
|
||||
# with stale state, effectively resulting in memory corruption.
|
||||
# Until/unless that can be well-encapsulated, such that the higher-level
|
||||
# bindings which access those memory heaps are known to be using the
|
||||
# proper references, DO NOT build with this option.
|
||||
#
|
||||
########################################################################
|
||||
fiddle: sqlite3.c shell.c
|
||||
make -C ext/wasm fiddle emcc_opt=-Os
|
||||
|
||||
+23
-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 $(TOP)\test\fuzzinvariants.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.
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
#########
|
||||
@@ -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')
|
||||
|
||||
+2
-2
@@ -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);
|
||||
@@ -4745,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);
|
||||
|
||||
+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;
|
||||
}
|
||||
|
||||
+32
-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;
|
||||
@@ -4547,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;
|
||||
@@ -4921,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];
|
||||
@@ -5557,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);
|
||||
@@ -5577,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;
|
||||
}
|
||||
|
||||
@@ -6278,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) ){
|
||||
|
||||
+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
|
||||
|
||||
@@ -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
@@ -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:
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
_fiddle_exec
|
||||
_fiddle_interrupt
|
||||
_fiddle_experiment
|
||||
_fiddle_the_db
|
||||
_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
|
||||
@@ -1,14 +0,0 @@
|
||||
FS
|
||||
addFunction
|
||||
allocateUTF8OnStack
|
||||
ccall
|
||||
cwrap
|
||||
getValue
|
||||
intArrayFromString
|
||||
lengthBytesUTF8
|
||||
removeFunction
|
||||
setValue
|
||||
stackAlloc
|
||||
stackRestore
|
||||
stackSave
|
||||
stringToUTF8Array
|
||||
+524
-156
@@ -1,37 +1,114 @@
|
||||
# This GNU makefile exists primarily to simplify/speed up development
|
||||
# of the sqlite3 WASM components. It is not part of the canonical
|
||||
# build process.
|
||||
#######################################################################
|
||||
# This GNU makefile drives the build of the sqlite3 WASM
|
||||
# components. It is not part of the canonical build process.
|
||||
#
|
||||
# Maintenance notes: the fiddle build is currently performed in the
|
||||
# top-level ../../Makefile.in. It may be moved into this file at some
|
||||
# point, as GNU Make has been deemed acceptable for the WASM-related
|
||||
# components (whereas POSIX Make is required for the more conventional
|
||||
# components).
|
||||
# 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)
|
||||
all:
|
||||
|
||||
.PHONY: fiddle
|
||||
ifneq (,$(wildcard /home/stephan))
|
||||
fiddle_opt ?= -O0
|
||||
else
|
||||
fiddle_opt = -Os
|
||||
endif
|
||||
fiddle:
|
||||
$(MAKE) -C ../.. fiddle -e emcc_opt=$(fiddle_opt)
|
||||
|
||||
clean:
|
||||
$(MAKE) -C ../../ clean-fiddle
|
||||
-rm -f $(CLEAN_FILES)
|
||||
|
||||
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
|
||||
dir.wasm := $(patsubst %/,%,$(dir $(abspath $(MAKEFILE))))
|
||||
# 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
|
||||
CLEAN_FILES := *~ $(dir.jacc)/*~ $(dir.api)/*~ $(dir.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 \
|
||||
@@ -45,21 +122,31 @@ SQLITE_OPT = \
|
||||
-DSQLITE_OMIT_LOAD_EXTENSION \
|
||||
-DSQLITE_OMIT_DEPRECATED \
|
||||
-DSQLITE_OMIT_UTF16 \
|
||||
-DSQLITE_THREADSAFE=0
|
||||
#SQLITE_OPT += -DSQLITE_ENABLE_MEMSYS5
|
||||
$(dir.top)/sqlite3.c:
|
||||
$(MAKE) -C $(dir.top) sqlite3.c
|
||||
|
||||
# SQLITE_OMIT_LOAD_EXTENSION: if this is true, sqlite3_vfs::xDlOpen
|
||||
# and friends may be NULL.
|
||||
-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
|
||||
.PHONY: release
|
||||
release:
|
||||
$(MAKE) 'emcc_opt=-Os -g3'
|
||||
# ^^^^^ target-specific vars, e.g.:
|
||||
# release: emcc_opt=...
|
||||
# apparently only work for file targets, not PHONY targets?
|
||||
# ^^^^ 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
|
||||
@@ -77,33 +164,19 @@ release:
|
||||
# -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.)
|
||||
########################################################################
|
||||
|
||||
# Emscripten SDK home dir and related binaries...
|
||||
EMSDK_HOME ?= $(word 1,$(wildcard $(HOME)/src/emsdk $(HOME)/emsdk))
|
||||
emcc.bin ?= $(word 1,$(wildcard $(shell which emcc) $(EMSDK_HOME)/upstream/emscripten/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 -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 -O2 then)
|
||||
$(info WARNING: the ***resulting WASM binary 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
|
||||
$(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))
|
||||
@@ -114,25 +187,54 @@ else
|
||||
$(info Development build. Use '$(MAKE) release' for a smaller release build.)
|
||||
endif
|
||||
|
||||
EXPORTED_FUNCTIONS.api.in := $(dir.api)/EXPORTED_FUNCTIONS.sqlite3-api \
|
||||
$(dir.jacc)/jaccwabyt_test.exports
|
||||
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)
|
||||
|
||||
EXPORTED_FUNCTIONS.api: $(EXPORTED_FUNCTIONS.api.in) $(MAKEFILE)
|
||||
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) > $@
|
||||
CLEAN_FILES += EXPORTED_FUNCTIONS.api
|
||||
|
||||
sqlite3-api.jses := \
|
||||
$(dir.api)/sqlite3-api-prologue.js \
|
||||
$(dir.common)/whwasmutil.js \
|
||||
$(dir.jacc)/jaccwabyt.js \
|
||||
$(dir.api)/sqlite3-api-glue.js \
|
||||
$(dir.api)/sqlite3-api-oo1.js \
|
||||
$(dir.api)/sqlite3-api-worker.js \
|
||||
$(dir.api)/sqlite3-api-opfs.js \
|
||||
$(dir.api)/sqlite3-api-cleanup.js
|
||||
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
|
||||
|
||||
sqlite3-api.js := $(dir.api)/sqlite3-api.js
|
||||
CLEAN_FILES += $(sqlite3-api.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 \
|
||||
@@ -141,13 +243,25 @@ $(sqlite3-api.js): $(sqlite3-api.jses) $(MAKEFILE)
|
||||
echo "/* END FILE: $$i */"; \
|
||||
done > $@
|
||||
|
||||
post-js.js := $(dir.api)/post-js.js
|
||||
CLEAN_FILES += $(post-js.js)
|
||||
$(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 \
|
||||
@@ -155,133 +269,387 @@ $(post-js.js): $(post-jses) $(MAKEFILE)
|
||||
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 '*/'; \
|
||||
} > $@
|
||||
|
||||
########################################################################
|
||||
# emcc flags for .c/.o/.wasm.
|
||||
emcc.flags =
|
||||
# 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) # $(SQLITE_OPT)
|
||||
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 += -sENVIRONMENT=web
|
||||
emcc.jsflags += -sMODULARIZE
|
||||
emcc.jsflags += -sSTRICT_JS
|
||||
emcc.jsflags += -sDYNAMIC_EXECUTION=0
|
||||
emcc.jsflags += -sNO_POLYFILL
|
||||
emcc.jsflags += -sEXPORTED_FUNCTIONS=@$(dir.wasm)/EXPORTED_FUNCTIONS.api
|
||||
emcc.jsflags += -sEXPORTED_RUNTIME_METHODS=FS,wasmMemory # wasmMemory==>for -sIMPORTED_MEMORY
|
||||
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.jsflags += -sINITIAL_MEMORY=13107200
|
||||
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
|
||||
emcc.jsflags += -sEXPORT_NAME=sqlite3InitModule
|
||||
|
||||
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 +=--post-js=$(post-js.js)
|
||||
#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_MEMORY_GROWTH
|
||||
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 += -sMALLOC=emmalloc
|
||||
#emcc.jsflags += -sMALLOC=dlmalloc # a good 8k larger than emmalloc
|
||||
#emcc.jsflags += -sSTANDALONE_WASM # causes OOM errors, not sure why
|
||||
#emcc.jsflags += --import=foo_bar
|
||||
#emcc.jsflags += --no-gc-sections
|
||||
# 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 += --import-undefined
|
||||
#emcc.jsflags += --unresolved-symbols=import-dynamic --experimental-pic
|
||||
#emcc.jsflags += --experimental-pic --unresolved-symbols=ingore-all --import-undefined
|
||||
#emcc.jsflags += --experimental-pic --unresolved-symbols=ingore-all --import-undefined
|
||||
#emcc.jsflags += --unresolved-symbols=ignore-all
|
||||
enable_bigint ?= 1
|
||||
ifneq (0,$(enable_bigint))
|
||||
emcc.jsflags += -sWASM_BIGINT
|
||||
endif
|
||||
emcc.jsflags += -sMEMORY64=0
|
||||
# ^^^^ MEMORY64=1 fails to load, erroring with:
|
||||
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(heapWrappers().HEAP8U.buffer, ptr, n)
|
||||
# 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.
|
||||
# which have strict must-be-a-Number requirements.
|
||||
########################################################################
|
||||
|
||||
|
||||
sqlite3.js := $(dir.api)/sqlite3.js
|
||||
sqlite3.wasm := $(dir.api)/sqlite3.wasm
|
||||
$(dir.api)/sqlite3-wasm.o: emcc.cflags += $(SQLITE_OPT)
|
||||
$(dir.api)/sqlite3-wasm.o: $(dir.top)/sqlite3.c
|
||||
$(dir.api)/wasm_util.o: emcc.cflags += $(SQLITE_OPT)
|
||||
sqlite3.wasm.c := $(dir.api)/sqlite3-wasm.c \
|
||||
$(dir.jacc)/jaccwabyt_test.c
|
||||
# ^^^ FIXME (how?): jaccwabyt_test.c is only needed for the test
|
||||
# apps. However, we want to test the release builds with those apps,
|
||||
# so we cannot simply elide that file in release builds. That
|
||||
# component is critical to the VFS bindings so needs to be tested
|
||||
# along with the core APIs.
|
||||
define WASM_C_COMPILE
|
||||
$(1).o := $$(subst .c,.o,$(1))
|
||||
sqlite3.wasm.obj += $$($(1).o)
|
||||
$$($(1).o): $$(MAKEFILE) $(1)
|
||||
$$(emcc.bin) $$(emcc_opt) $$(emcc.flags) $$(emcc.cflags) -c $(1) -o $$@
|
||||
CLEAN_FILES += $$($(1).o)
|
||||
endef
|
||||
$(foreach c,$(sqlite3.wasm.c),$(eval $(call WASM_C_COMPILE,$(c))))
|
||||
$(sqlite3.js):
|
||||
$(sqlite3.js): $(MAKEFILE) $(sqlite3.wasm.obj) \
|
||||
EXPORTED_FUNCTIONS.api \
|
||||
$(post-js.js)
|
||||
$(emcc.bin) -o $@ $(emcc_opt) $(emcc.flags) $(emcc.jsflags) $(sqlite3.wasm.obj)
|
||||
chmod -x $(sqlite3.wasm)
|
||||
ifneq (,$(wasm-strip))
|
||||
$(wasm-strip) $(sqlite3.wasm)
|
||||
endif
|
||||
@ls -la $@ $(sqlite3.wasm)
|
||||
########################################################################
|
||||
# -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
|
||||
########################################################################
|
||||
|
||||
########################################################################
|
||||
# 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 = wh: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/ $(fiddle_remote)
|
||||
# end fiddle remote push
|
||||
# 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
|
||||
|
||||
+34
-32
@@ -10,6 +10,7 @@ below for Linux environments:
|
||||
|
||||
```
|
||||
# Clone the emscripten repository:
|
||||
$ sudo apt install git
|
||||
$ git clone https://github.com/emscripten-core/emsdk.git
|
||||
$ cd emsdk
|
||||
|
||||
@@ -24,6 +25,7 @@ Those parts only need to be run once, but the SDK can be updated using:
|
||||
|
||||
```
|
||||
$ git pull
|
||||
$ ./emsdk install latest
|
||||
$ ./emsdk activate latest
|
||||
```
|
||||
|
||||
@@ -55,48 +57,48 @@ $ cd ext/wasm
|
||||
$ make
|
||||
```
|
||||
|
||||
That will generate the fiddle application under
|
||||
[ext/fiddle](/dir/ext/wasm/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][]:
|
||||
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/fiddle
|
||||
$ althttpd -page fiddle.html
|
||||
$ cd ext/wasm
|
||||
$ althttpd --enable-sab --max-age 1 --page index.html
|
||||
```
|
||||
|
||||
That will open the system's browser and run the fiddle app's page.
|
||||
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-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.
|
||||
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
|
||||
|
||||
# Known Quirks and Limitations
|
||||
*NB: The following are developer notes, last validated on 2022-08-18*
|
||||
|
||||
Some "impedence mismatch" between C and WASM/JavaScript is to be
|
||||
expected.
|
||||
* 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
|
||||
|
||||
## 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.
|
||||
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
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
_sqlite3_aggregate_context
|
||||
_sqlite3_bind_blob
|
||||
_sqlite3_bind_double
|
||||
_sqlite3_bind_int
|
||||
@@ -22,10 +23,14 @@ _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
|
||||
@@ -33,15 +38,22 @@ _sqlite3_exec
|
||||
_sqlite3_expanded_sql
|
||||
_sqlite3_extended_errcode
|
||||
_sqlite3_extended_result_codes
|
||||
_sqlite3_file_control
|
||||
_sqlite3_finalize
|
||||
_sqlite3_free
|
||||
_sqlite3_initialize
|
||||
_sqlite3_interrupt
|
||||
_sqlite3_libversion
|
||||
_sqlite3_libversion_number
|
||||
_sqlite3_malloc
|
||||
_sqlite3_malloc64
|
||||
_sqlite3_msize
|
||||
_sqlite3_open
|
||||
_sqlite3_open_v2
|
||||
_sqlite3_prepare_v2
|
||||
_sqlite3_prepare_v3
|
||||
_sqlite3_randomness
|
||||
_sqlite3_realloc
|
||||
_sqlite3_realloc64
|
||||
_sqlite3_reset
|
||||
_sqlite3_result_blob
|
||||
_sqlite3_result_double
|
||||
@@ -50,8 +62,11 @@ _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
|
||||
@@ -59,14 +74,21 @@ _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_wasm_db_error
|
||||
_sqlite3_wasm_enum_json
|
||||
_sqlite3_vfs_unregister
|
||||
_malloc
|
||||
_free
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
@@ -1,3 +1,4 @@
|
||||
/* The current function scope was opened via post-js-header.js, which
|
||||
gets prepended to this at build-time. */
|
||||
gets prepended to this at build-time. This file closes that
|
||||
scope. */
|
||||
})/*postRun.push(...)*/;
|
||||
|
||||
@@ -5,22 +5,21 @@
|
||||
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 WASM API bits will be set up.
|
||||
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:
|
||||
/* 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
|
||||
- sqlite3-api-whwasmutil.js => Replacements for much of Emscripten's glue
|
||||
- sqlite3-api-jaccwabyt.js => Jaccwabyt (C/JS struct binding)
|
||||
- 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-worker.js => Worker-based API
|
||||
- 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
|
||||
|
||||
Whew!
|
||||
*/
|
||||
|
||||
@@ -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. */
|
||||
@@ -11,34 +11,60 @@
|
||||
***********************************************************************
|
||||
|
||||
This file is the tail end of the sqlite3-api.js constellation,
|
||||
intended to be appended after all other files so that it can clean
|
||||
up any global systems temporarily used for setting up the API's
|
||||
various subsystems.
|
||||
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';
|
||||
self.sqlite3.postInit.forEach(
|
||||
self.importScripts/*global is a Worker*/
|
||||
? function(f){
|
||||
/** We try/catch/report for the sake of failures which happen in
|
||||
a Worker, as those exceptions can otherwise get completely
|
||||
swallowed, leading to confusing downstream errors which have
|
||||
nothing to do with this failure. */
|
||||
try{ f(self, self.sqlite3) }
|
||||
catch(e){
|
||||
console.error("Error in postInit() function:",e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
: (f)=>f(self, self.sqlite3)
|
||||
);
|
||||
delete self.sqlite3.postInit;
|
||||
if(self.location && +self.location.port > 1024){
|
||||
console.warn("Installing sqlite3 bits as global S for dev-testing purposes.");
|
||||
self.S = self.sqlite3;
|
||||
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.");
|
||||
}
|
||||
/* Clean up temporary global-scope references to our APIs... */
|
||||
self.sqlite3.config.Module.sqlite3 = self.sqlite3
|
||||
/* ^^^^ Currently needed by test code and Worker API setup */;
|
||||
delete self.sqlite3.capi.util /* arguable, but these are (currently) internal-use APIs */;
|
||||
delete self.sqlite3 /* clean up our global-scope reference */;
|
||||
//console.warn("Module.sqlite3 =",Module.sqlite3);
|
||||
|
||||
+670
-161
@@ -16,162 +16,14 @@
|
||||
initializes the main API pieces so that the downstream components
|
||||
(e.g. sqlite3-api-oo1.js) have all that they need.
|
||||
*/
|
||||
(function(self){
|
||||
self.sqlite3ApiBootstrap.initializers.push(function(sqlite3){
|
||||
'use strict';
|
||||
const toss = (...args)=>{throw new Error(args.join(' '))};
|
||||
|
||||
self.sqlite3 = self.sqlite3ApiBootstrap({
|
||||
Module: Module /* ==> Emscripten-style Module object. 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 */,
|
||||
bigIntEnabled: !!self.BigInt64Array,
|
||||
allocExportName: 'malloc',
|
||||
deallocExportName: 'free'
|
||||
});
|
||||
delete self.sqlite3ApiBootstrap;
|
||||
|
||||
const sqlite3 = self.sqlite3;
|
||||
const capi = sqlite3.capi, wasm = capi.wasm, util = capi.util;
|
||||
self.WhWasmUtilInstaller(capi.wasm);
|
||||
const toss3 = sqlite3.SQLite3Error.toss;
|
||||
const capi = sqlite3.capi, wasm = sqlite3.wasm, util = sqlite3.util;
|
||||
self.WhWasmUtilInstaller(wasm);
|
||||
delete self.WhWasmUtilInstaller;
|
||||
|
||||
if(0){
|
||||
/* "The problem" is that the following isn't type-safe.
|
||||
OTOH, nothing about WASM pointers is. */
|
||||
/**
|
||||
Add the `.pointer` xWrap() signature entry to extend
|
||||
the `pointer` arg handler to check for a `pointer`
|
||||
property. This can be used to permit, e.g., passing
|
||||
an SQLite3.DB instance to a C-style sqlite3_xxx function
|
||||
which takes an `sqlite3*` argument.
|
||||
*/
|
||||
const oldP = wasm.xWrap.argAdapter('pointer');
|
||||
const adapter = function(v){
|
||||
if(v && 'object'===typeof v && v.constructor){
|
||||
const x = v.pointer;
|
||||
if(Number.isInteger(x)) return x;
|
||||
else toss("Invalid (object) type for pointer-type argument.");
|
||||
}
|
||||
return oldP(v);
|
||||
};
|
||||
wasm.xWrap.argAdapter('.pointer', adapter);
|
||||
}
|
||||
|
||||
// WhWasmUtil.xWrap() bindings...
|
||||
{
|
||||
/**
|
||||
Add some descriptive xWrap() aliases for '*' intended to
|
||||
(A) initially improve readability/correctness of capi.signatures
|
||||
and (B) eventually perhaps provide some sort of type-safety
|
||||
in their conversions.
|
||||
*/
|
||||
const aPtr = wasm.xWrap.argAdapter('*');
|
||||
wasm.xWrap.argAdapter('sqlite3*', aPtr)('sqlite3_stmt*', 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 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]);
|
||||
}
|
||||
|
||||
if(wasm.exports.sqlite3_wasm_db_error){
|
||||
util.sqlite3_wasm_db_error = capi.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;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
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);
|
||||
};
|
||||
|
||||
}/*xWrap() bindings*/;
|
||||
|
||||
/**
|
||||
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"/*MUST always be negative*/,
|
||||
"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){
|
||||
/* 2022-07-08: xWrap() 'string' arg handling may be able do this
|
||||
special-case handling for us. It needs to be tested. Or maybe
|
||||
not: we always want to treat pzTail as null when passed a
|
||||
non-pointer SQL string and the argument adapters don't have
|
||||
enough state to know that. Maybe they could/should, by passing
|
||||
the currently-collected args as an array as the 2nd arg to the
|
||||
argument adapters? Or maybe we collect all args in an array,
|
||||
pass that to an optional post-args-collected callback, and give
|
||||
it a chance to manipulate the args before we pass them on? */
|
||||
if(util.isSQLableTypedArray(sql)) sql = util.typedArrayToString(sql);
|
||||
switch(typeof sql){
|
||||
case 'string': return __prepare.basic(pDb, sql, -1, prepFlags, ppStmt, null);
|
||||
case 'number': return __prepare.full(pDb, sql, sqlLen||-1, prepFlags, ppStmt, pzTail);
|
||||
default:
|
||||
return util.sqlite3_wasm_db_error(
|
||||
pDb, capi.SQLITE_MISUSE,
|
||||
"Invalid SQL argument type for sqlite3_prepare_v2/v3()."
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
capi.sqlite3_prepare_v2 =
|
||||
(pDb, sql, sqlLen, ppStmt, pzTail)=>capi.sqlite3_prepare_v3(pDb, sql, sqlLen, 0, ppStmt, pzTail);
|
||||
|
||||
/**
|
||||
Install JS<->C struct bindings for the non-opaque struct types we
|
||||
need... */
|
||||
@@ -185,6 +37,541 @@
|
||||
});
|
||||
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){
|
||||
@@ -194,18 +581,140 @@
|
||||
wasm.ctype = JSON.parse(wasm.cstringToJs(cJson));
|
||||
//console.debug('wasm.ctype length =',wasm.cstrlen(cJson));
|
||||
for(const t of ['access', 'blobFinalizers', 'dataTypes',
|
||||
'encodings', 'flock', 'ioCap',
|
||||
'encodings', 'fcntl', 'flock', 'ioCap',
|
||||
'openFlags', 'prepareFlags', 'resultCodes',
|
||||
'syncFlags', 'udfFlags', 'version'
|
||||
'serialize', 'syncFlags', 'trace', 'udfFlags',
|
||||
'version'
|
||||
]){
|
||||
for(const [k,v] of Object.entries(wasm.ctype[t])){
|
||||
capi[k] = v;
|
||||
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];
|
||||
}
|
||||
}
|
||||
/* Bind all registered C-side structs... */
|
||||
for(const s of wasm.ctype.structs){
|
||||
capi[s.name] = sqlite3.StructBinder(s);
|
||||
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*/
|
||||
|
||||
})(self);
|
||||
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*/
|
||||
|
||||
});
|
||||
|
||||
+894
-532
File diff suppressed because it is too large
Load Diff
+1277
-359
File diff suppressed because it is too large
Load Diff
+1256
-247
File diff suppressed because it is too large
Load Diff
@@ -1,421 +0,0 @@
|
||||
/*
|
||||
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 a Worker-based wrapper around SQLite3 OO 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 initWorkerAPI(). If this function
|
||||
is called from a non-worker thread then it throws an exception.
|
||||
|
||||
When initialized, it installs message listeners to receive messages
|
||||
from the main thread and then it posts a message in the form:
|
||||
|
||||
```
|
||||
{type:'sqlite3-api',data:'worker-ready'}
|
||||
```
|
||||
|
||||
This file requires that the core C-style sqlite3 API and OO API #1
|
||||
have been loaded and that self.sqlite3 contains both,
|
||||
as documented for those APIs.
|
||||
*/
|
||||
self.sqlite3.initWorkerAPI = function(){
|
||||
'use strict';
|
||||
/**
|
||||
UNDER CONSTRUCTION
|
||||
|
||||
We need an API which can proxy the DB API via a Worker message
|
||||
interface. The primary quirky factor in such an API is that we
|
||||
cannot pass callback functions between the window thread and a
|
||||
worker thread, so we have to receive all db results via
|
||||
asynchronous message-passing. That requires an asychronous API
|
||||
with a distinctly different shape that the main OO API.
|
||||
|
||||
Certain important considerations here include:
|
||||
|
||||
- Support only one db connection or multiple? The former is far
|
||||
easier, but there's always going to be a user out there who wants
|
||||
to juggle six database handles at once. Do we add that complexity
|
||||
or tell such users to write their own code using the provided
|
||||
lower-level APIs?
|
||||
|
||||
- Fetching multiple results: do we pass them on as a series of
|
||||
messages, with start/end messages on either end, or do we collect
|
||||
all results and bundle them back in a single message? The former
|
||||
is, generically speaking, more memory-efficient but the latter
|
||||
far easier to implement in this environment. The latter is
|
||||
untennable for large data sets. Despite a web page hypothetically
|
||||
being a relatively limited environment, there will always be
|
||||
those users who feel that they should/need to be able to work
|
||||
with multi-hundred-meg (or larger) blobs, and passing around
|
||||
arrays of those may quickly exhaust the JS engine's memory.
|
||||
|
||||
TODOs include, but are not limited to:
|
||||
|
||||
- The ability to manage multiple DB handles. This can
|
||||
potentially be done via a simple mapping of DB.filename or
|
||||
DB.pointer (`sqlite3*` handle) to DB objects. The open()
|
||||
interface would need to provide an ID (probably DB.pointer) back
|
||||
to the user which can optionally be passed as an argument to
|
||||
the other APIs (they'd default to the first-opened DB, for
|
||||
ease of use). Client-side usability of this feature would
|
||||
benefit from making another wrapper class (or a singleton)
|
||||
available to the main thread, with that object proxying all(?)
|
||||
communication with the worker.
|
||||
|
||||
- Revisit how virtual files are managed. We currently delete DBs
|
||||
from the virtual filesystem when we close them, for the sake of
|
||||
saving memory (the VFS lives in RAM). Supporting multiple DBs may
|
||||
require that we give up that habit. Similarly, fully supporting
|
||||
ATTACH, where a user can upload multiple DBs and ATTACH them,
|
||||
also requires the that we manage the VFS entries better.
|
||||
*/
|
||||
const toss = (...args)=>{throw new Error(args.join(' '))};
|
||||
if('function' !== typeof importScripts){
|
||||
toss("Cannot initalize the sqlite3 worker API in the main thread.");
|
||||
}
|
||||
/* This is a web worker, so init the worker-based API. */
|
||||
const self = this.self;
|
||||
const sqlite3 = this.sqlite3 || toss("Missing self.sqlite3 object.");
|
||||
const SQLite3 = sqlite3.oo1 || toss("Missing self.sqlite3.oo1 OO API.");
|
||||
const DB = SQLite3.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;
|
||||
};
|
||||
|
||||
/**
|
||||
Helper for managing Worker-level state.
|
||||
*/
|
||||
const wState = {
|
||||
defaultDb: undefined,
|
||||
idSeq: 0,
|
||||
idMap: new WeakMap,
|
||||
open: function(arg){
|
||||
// TODO: if arg is a filename, look for a db in this.dbs with the
|
||||
// same filename and close/reopen it (or just pass it back as is?).
|
||||
if(!arg && this.defaultDb) return this.defaultDb;
|
||||
//???if(this.defaultDb) this.defaultDb.close();
|
||||
let db;
|
||||
db = (Array.isArray(arg) ? new DB(...arg) : new DB(arg));
|
||||
this.dbs[getDbId(db)] = db;
|
||||
if(!this.defaultDb) this.defaultDb = db;
|
||||
return db;
|
||||
},
|
||||
close: function(db,alsoUnlink){
|
||||
if(db){
|
||||
delete this.dbs[getDbId(db)];
|
||||
db.close(alsoUnlink);
|
||||
if(db===this.defaultDb) this.defaultDb = undefined;
|
||||
}
|
||||
},
|
||||
post: function(type,data,xferList){
|
||||
if(xferList){
|
||||
self.postMessage({type, data},xferList);
|
||||
xferList.length = 0;
|
||||
}else{
|
||||
self.postMessage({type, data});
|
||||
}
|
||||
},
|
||||
/** Map of DB IDs to DBs. */
|
||||
dbs: Object.create(null),
|
||||
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. */
|
||||
const affirmDbOpen = function(db = wState.defaultDb){
|
||||
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.defaultDb;
|
||||
return affirmExists ? affirmDbOpen(db) : db;
|
||||
};
|
||||
|
||||
const getDefaultDbId = function(){
|
||||
return wState.defaultDb && getDbId(wState.defaultDb);
|
||||
};
|
||||
|
||||
/**
|
||||
A level of "organizational abstraction" for the Worker
|
||||
API. Each method in this object must map directly to a Worker
|
||||
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 response
|
||||
state, which the dispatcher may amend. All methods must throw
|
||||
on error.
|
||||
*/
|
||||
const wMsgHandler = {
|
||||
xfer: [/*Temp holder for "transferable" postMessage() state.*/],
|
||||
/**
|
||||
Proxy for DB.exec() which expects a single argument of type
|
||||
string (SQL to execute) or an options object in the form
|
||||
expected by exec(). The notable differences from exec()
|
||||
include:
|
||||
|
||||
- The default value for options.rowMode is 'array' because
|
||||
the normal default cannot cross the window/Worker boundary.
|
||||
|
||||
- A function-type options.callback property cannot cross
|
||||
the window/Worker boundary, so is not useful here. If
|
||||
options.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, data: theRow})
|
||||
|
||||
And, at the end of the result set (whether or not any
|
||||
result rows were produced), it will post an identical
|
||||
message with data:null to alert the caller than the result
|
||||
set is completed.
|
||||
|
||||
The callback proxy must not recurse into this interface, or
|
||||
results are undefined. (It hypothetically cannot recurse
|
||||
because an exec() call will be tying 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 exec().
|
||||
|
||||
This opens/creates the Worker's db if needed.
|
||||
*/
|
||||
exec: function(ev){
|
||||
const opt = (
|
||||
'string'===typeof ev.data
|
||||
) ? {sql: ev.data} : (ev.data || Object.create(null));
|
||||
if(undefined===opt.rowMode){
|
||||
/* Since the default rowMode of 'stmt' is not useful
|
||||
for the Worker interface, we'll default to
|
||||
something else. */
|
||||
opt.rowMode = 'array';
|
||||
}else if('stmt'===opt.rowMode){
|
||||
toss("Invalid rowMode for exec(): stmt mode",
|
||||
"does not work in the Worker API.");
|
||||
}
|
||||
const db = getMsgDb(ev);
|
||||
if(opt.callback || Array.isArray(opt.resultRows)){
|
||||
// Part of a copy-avoidance optimization for blobs
|
||||
db._blobXfer = this.xfer;
|
||||
}
|
||||
const callbackMsgType = opt.callback;
|
||||
if('string' === typeof callbackMsgType){
|
||||
/* Treat this as a worker message type and post each
|
||||
row as a message of that type. */
|
||||
const that = this;
|
||||
opt.callback =
|
||||
(row)=>wState.post(callbackMsgType,row,this.xfer);
|
||||
}
|
||||
try {
|
||||
db.exec(opt);
|
||||
if(opt.callback instanceof Function){
|
||||
opt.callback = callbackMsgType;
|
||||
wState.post(callbackMsgType, null);
|
||||
}
|
||||
}/*catch(e){
|
||||
console.warn("Worker is propagating:",e);throw e;
|
||||
}*/finally{
|
||||
delete db._blobXfer;
|
||||
if(opt.callback){
|
||||
opt.callback = callbackMsgType;
|
||||
}
|
||||
}
|
||||
return opt;
|
||||
}/*exec()*/,
|
||||
/**
|
||||
TO(re)DO, once we can abstract away access to the
|
||||
JS environment's virtual filesystem. Currently this
|
||||
always throws.
|
||||
|
||||
Response is (should be) an object:
|
||||
|
||||
{
|
||||
buffer: Uint8Array (db file contents),
|
||||
filename: the current db filename,
|
||||
mimetype: 'application/x-sqlite3'
|
||||
}
|
||||
|
||||
TODO is to determine how/whether this feature can support
|
||||
exports of ":memory:" and "" (temp file) DBs. The latter is
|
||||
ostensibly easy because the file is (potentially) on disk, but
|
||||
the former does not have a structure which maps directly to a
|
||||
db file image.
|
||||
*/
|
||||
export: function(ev){
|
||||
toss("export() requires reimplementing for portability reasons.");
|
||||
/**const db = getMsgDb(ev);
|
||||
const response = {
|
||||
buffer: db.exportBinaryImage(),
|
||||
filename: db.filename,
|
||||
mimetype: 'application/x-sqlite3'
|
||||
};
|
||||
this.xfer.push(response.buffer.buffer);
|
||||
return response;**/
|
||||
}/*export()*/,
|
||||
/**
|
||||
Proxy for the DB constructor. Expects to be passed a single
|
||||
object or a falsy value to use defaults. The object may
|
||||
have a filename property to name the db file (see the DB
|
||||
constructor for peculiarities and transformations) and/or a
|
||||
buffer property (a Uint8Array holding a complete database
|
||||
file's contents). The response is an object:
|
||||
|
||||
{
|
||||
filename: db filename (possibly differing from the input),
|
||||
|
||||
id: an opaque ID value intended for future distinction
|
||||
between multiple db handles. Messages including a specific
|
||||
ID will use the DB for that ID.
|
||||
|
||||
}
|
||||
|
||||
If the Worker's db is currently opened, this call closes it
|
||||
before proceeding.
|
||||
*/
|
||||
open: function(ev){
|
||||
wState.close(/*true???*/);
|
||||
const args = [], data = (ev.data || {});
|
||||
if(data.simulateError){
|
||||
toss("Throwing because of open.simulateError flag.");
|
||||
}
|
||||
if(data.filename) args.push(data.filename);
|
||||
if(data.buffer){
|
||||
args.push(data.buffer);
|
||||
this.xfer.push(data.buffer.buffer);
|
||||
}
|
||||
const db = wState.open(args);
|
||||
return {
|
||||
filename: db.filename,
|
||||
dbId: getDbId(db)
|
||||
};
|
||||
},
|
||||
/**
|
||||
Proxy for DB.close(). If ev.data may either be a boolean or
|
||||
an object with an `unlink` property. If that value is
|
||||
truthy then the db file (if the db is currently open) will
|
||||
be unlinked from the virtual filesystem, else it will be
|
||||
kept intact. The response object is:
|
||||
|
||||
{
|
||||
filename: db filename _if_ the db is opened when this
|
||||
is called, else the undefined value
|
||||
}
|
||||
*/
|
||||
close: function(ev){
|
||||
const db = getMsgDb(ev,false);
|
||||
const response = {
|
||||
filename: db && db.filename
|
||||
};
|
||||
if(db){
|
||||
wState.close(db, !!((ev.data && 'object'===typeof ev.data)
|
||||
? ev.data.unlink : ev.data));
|
||||
}
|
||||
return response;
|
||||
},
|
||||
toss: function(ev){
|
||||
toss("Testing worker exception");
|
||||
}
|
||||
}/*wMsgHandler*/;
|
||||
|
||||
/**
|
||||
UNDER CONSTRUCTION!
|
||||
|
||||
A subset of the DB API is accessible via Worker messages in the
|
||||
form:
|
||||
|
||||
{ type: apiCommand,
|
||||
dbId: optional DB ID value (not currently used!)
|
||||
data: apiArguments
|
||||
}
|
||||
|
||||
As a rule, these commands respond with a postMessage() of their
|
||||
own in the same form, but will, if needed, transform the `data`
|
||||
member to an object and may add state to it. The responses
|
||||
always have an object-format `data` part. If the inbound `data`
|
||||
is an object which has a `messageId` property, that property is
|
||||
always mirrored in the result object, for use in client-side
|
||||
dispatching of these asynchronous results. Exceptions thrown
|
||||
during processing result in an `error`-type event with a
|
||||
payload in the form:
|
||||
|
||||
{
|
||||
message: error string,
|
||||
errorClass: class name of the error type,
|
||||
dbId: DB handle ID,
|
||||
input: ev.data,
|
||||
[messageId: if set in the inbound message]
|
||||
}
|
||||
|
||||
The individual APIs are documented in the wMsgHandler object.
|
||||
*/
|
||||
self.onmessage = function(ev){
|
||||
ev = ev.data;
|
||||
let response, dbId = ev.dbId, evType = ev.type;
|
||||
const arrivalTime = performance.now();
|
||||
try {
|
||||
if(wMsgHandler.hasOwnProperty(evType) &&
|
||||
wMsgHandler[evType] instanceof Function){
|
||||
response = wMsgHandler[evType](ev);
|
||||
}else{
|
||||
toss("Unknown db worker message type:",ev.type);
|
||||
}
|
||||
}catch(err){
|
||||
evType = 'error';
|
||||
response = {
|
||||
message: err.message,
|
||||
errorClass: err.name,
|
||||
input: ev
|
||||
};
|
||||
if(err.stack){
|
||||
response.stack = ('string'===typeof err.stack)
|
||||
? err.stack.split('\n') : err.stack;
|
||||
}
|
||||
if(0) console.warn("Worker is propagating an exception to main thread.",
|
||||
"Reporting it _here_ for the stack trace:",err,response);
|
||||
}
|
||||
if(!response.messageId && ev.data
|
||||
&& 'object'===typeof ev.data && ev.data.messageId){
|
||||
response.messageId = ev.data.messageId;
|
||||
}
|
||||
if(!dbId){
|
||||
dbId = response.dbId/*from 'open' cmd*/
|
||||
|| getDefaultDbId();
|
||||
}
|
||||
if(!response.dbId) response.dbId = dbId;
|
||||
// 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.
|
||||
response.workerReceivedTime = arrivalTime;
|
||||
response.workerRespondTime = performance.now();
|
||||
response.departureTime = ev.departureTime;
|
||||
wState.post(evType, response, wMsgHandler.xfer);
|
||||
};
|
||||
setTimeout(()=>self.postMessage({type:'sqlite3-api',data:'worker-ready'}), 0);
|
||||
}.bind({self, sqlite3: self.sqlite3});
|
||||
@@ -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));
|
||||
+891
-122
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)
|
||||
};
|
||||
@@ -14,7 +14,7 @@
|
||||
sqlite3.js, initializes the module, and postMessage()'s a message
|
||||
after the module is initialized:
|
||||
|
||||
{type: 'sqlite3-api', data: 'worker-ready'}
|
||||
{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
|
||||
@@ -25,7 +25,25 @@
|
||||
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";
|
||||
importScripts('sqlite3.js');
|
||||
sqlite3InitModule().then((EmscriptenModule)=>EmscriptenModule.sqlite3.initWorkerAPI());
|
||||
(()=>{
|
||||
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);
|
||||
});
|
||||
})();
|
||||
@@ -113,6 +113,46 @@
|
||||
++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;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -122,23 +162,24 @@
|
||||
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: function(){
|
||||
console.log.apply(console, Array.prototype.slice.call(arguments));
|
||||
},
|
||||
print: (...args)=>{console.log(...args)},
|
||||
/* Proxy for C-side stderr output. */
|
||||
printErr: function(){
|
||||
console.error.apply(console, Array.prototype.slice.call(arguments));
|
||||
},
|
||||
printErr: (...args)=>{console.error(...args)},
|
||||
/**
|
||||
Called by the 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).
|
||||
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){
|
||||
@@ -168,6 +209,28 @@
|
||||
}
|
||||
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*/);
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
textarea {
|
||||
font-family: monospace;
|
||||
}
|
||||
@@ -29,4 +34,30 @@ span.labeled-input {
|
||||
color: red;
|
||||
background-color: yellow;
|
||||
}
|
||||
#test-output { font-family: monospace }
|
||||
.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 }
|
||||
|
||||
+301
-143
@@ -15,11 +15,17 @@
|
||||
|
||||
https://fossil.wanderinghorse.net/r/jaccwabyt
|
||||
|
||||
and sqlite3:
|
||||
|
||||
https://sqlite.org
|
||||
|
||||
This file is kept in sync between both of those trees.
|
||||
|
||||
Maintenance reminder: If you're reading this in a tree other than
|
||||
the Jaccwabyt tree, note that this copy may be replaced with
|
||||
one of those listed above, note that this copy may be replaced with
|
||||
upstream copies of that one from time to time. Thus the code
|
||||
installed by this function "should not" be edited outside of that
|
||||
project, else it risks getting overwritten.
|
||||
installed by this function "should not" be edited outside of those
|
||||
projects, else it risks getting overwritten.
|
||||
*/
|
||||
/**
|
||||
This function is intended to simplify porting around various bits
|
||||
@@ -63,7 +69,7 @@
|
||||
- WASM-exported "indirect function table" access and
|
||||
manipulation. e.g. creating new WASM-side functions using JS
|
||||
functions, analog to Emscripten's addFunction() and
|
||||
removeFunction() but slightly different.
|
||||
uninstallFunction() but slightly different.
|
||||
|
||||
- Get/set specific heap memory values, analog to Emscripten's
|
||||
getValue() and setValue().
|
||||
@@ -109,8 +115,8 @@
|
||||
following symbols:
|
||||
|
||||
- `memory`: a WebAssembly.Memory object representing the WASM
|
||||
memory. _Alternately_, the `memory` property can be set on the
|
||||
target instance, in particular if the WASM heap memory is
|
||||
memory. _Alternately_, the `memory` property can be set as
|
||||
`target.memory`, in particular if the WASM heap memory is
|
||||
initialized in JS an _imported_ into WASM, as opposed to being
|
||||
initialized in WASM and exported to JS.
|
||||
|
||||
@@ -132,7 +138,11 @@
|
||||
false. If it is false, certain BigInt-related features will trigger
|
||||
an exception if invoked. This property, if not set when this is
|
||||
called, will get a default value of true only if the BigInt64Array
|
||||
constructor is available, else it will default to false.
|
||||
constructor is available, else it will default to false. Note that
|
||||
having the BigInt type is not sufficient for full int64 integration
|
||||
with WASM: the target WASM file must also have been built with
|
||||
that support. In Emscripten that's done using the `-sWASM_BIGINT`
|
||||
flag.
|
||||
|
||||
Some optional APIs require that the target have the following
|
||||
methods:
|
||||
@@ -212,9 +222,10 @@ self.WhWasmUtilInstaller = function(target){
|
||||
that will certainly change.
|
||||
*/
|
||||
const ptrIR = target.pointerIR || 'i32';
|
||||
const ptrSizeof = ('i32'===ptrIR ? 4
|
||||
: ('i64'===ptrIR
|
||||
? 8 : toss("Unhandled ptrSizeof:",ptrIR)));
|
||||
const ptrSizeof = target.ptrSizeof =
|
||||
('i32'===ptrIR ? 4
|
||||
: ('i64'===ptrIR
|
||||
? 8 : toss("Unhandled ptrSizeof:",ptrIR)));
|
||||
/** Stores various cached state. */
|
||||
const cache = Object.create(null);
|
||||
/** Previously-recorded size of cache.memory.buffer, noted so that
|
||||
@@ -294,7 +305,7 @@ self.WhWasmUtilInstaller = function(target){
|
||||
an integer as the first argument and unsigned is truthy then
|
||||
the "U" (unsigned) variant of that view is returned, else the
|
||||
signed variant is returned. If passed a TypedArray value, the
|
||||
2nd argument is ignores. Note that Float32Array and
|
||||
2nd argument is ignored. Note that Float32Array and
|
||||
Float64Array views are not supported by this function.
|
||||
|
||||
Note that growth of the heap will invalidate any references to
|
||||
@@ -326,7 +337,7 @@ self.WhWasmUtilInstaller = function(target){
|
||||
if(c.HEAP64) return unsigned ? c.HEAP64U : c.HEAP64;
|
||||
break;
|
||||
default:
|
||||
if(this.bigIntEnabled){
|
||||
if(target.bigIntEnabled){
|
||||
if(n===self['BigUint64Array']) return c.HEAP64U;
|
||||
else if(n===self['BigInt64Array']) return c.HEAP64;
|
||||
break;
|
||||
@@ -334,7 +345,7 @@ self.WhWasmUtilInstaller = function(target){
|
||||
}
|
||||
toss("Invalid heapForSize() size: expecting 8, 16, 32,",
|
||||
"or (if BigInt is enabled) 64.");
|
||||
}.bind(target);
|
||||
};
|
||||
|
||||
/**
|
||||
Returns the WASM-exported "indirect function table."
|
||||
@@ -346,31 +357,33 @@ self.WhWasmUtilInstaller = function(target){
|
||||
- Use `__indirect_function_table` as the import name for the
|
||||
table, which is what LLVM does.
|
||||
*/
|
||||
}.bind(target);
|
||||
};
|
||||
|
||||
/**
|
||||
Given a function pointer, returns the WASM function table entry
|
||||
if found, else returns a falsy value.
|
||||
*/
|
||||
target.functionEntry = function(fptr){
|
||||
const ft = this.functionTable();
|
||||
const ft = target.functionTable();
|
||||
return fptr < ft.length ? ft.get(fptr) : undefined;
|
||||
}.bind(target);
|
||||
};
|
||||
|
||||
/**
|
||||
Creates a WASM function which wraps the given JS function and
|
||||
returns the JS binding of that WASM function. The signature
|
||||
argument must be the Jaccwabyt-format or Emscripten
|
||||
string must be the Jaccwabyt-format or Emscripten
|
||||
addFunction()-format function signature string. In short: in may
|
||||
have one of the following formats:
|
||||
|
||||
- Emscripten: `x...`, where the first x is a letter representing
|
||||
- Emscripten: `"x..."`, where the first x is a letter representing
|
||||
the result type and subsequent letters represent the argument
|
||||
types. See below.
|
||||
types. Functions with no arguments have only a single
|
||||
letter. See below.
|
||||
|
||||
- Jaccwabyt: `x(...)` where `x` is the letter representing the
|
||||
- Jaccwabyt: `"x(...)"` where `x` is the letter representing the
|
||||
result type and letters in the parens (if any) represent the
|
||||
argument types. See below.
|
||||
argument types. Functions with no arguments use `x()`. See
|
||||
below.
|
||||
|
||||
Supported letters:
|
||||
|
||||
@@ -391,6 +404,9 @@ self.WhWasmUtilInstaller = function(target){
|
||||
|
||||
Sidebar: this code is developed together with Jaccwabyt, thus the
|
||||
support for its signature format.
|
||||
|
||||
The arguments may be supplied in either order: (func,sig) or
|
||||
(sig,func).
|
||||
*/
|
||||
target.jsFuncToWasm = function f(func, sig){
|
||||
/** Attribution: adapted up from Emscripten-generated glue code,
|
||||
@@ -399,9 +415,14 @@ self.WhWasmUtilInstaller = function(target){
|
||||
if(!f._){/*static init...*/
|
||||
f._ = {
|
||||
// Map of signature letters to type IR values
|
||||
sigTypes: Object.create(null),
|
||||
sigTypes: Object.assign(Object.create(null),{
|
||||
i: 'i32', p: 'i32', P: 'i32', s: 'i32',
|
||||
j: 'i64', f: 'f32', d: 'f64'
|
||||
}),
|
||||
// Map of type IR values to WASM type code values
|
||||
typeCodes: Object.create(null),
|
||||
typeCodes: Object.assign(Object.create(null),{
|
||||
f64: 0x7c, f32: 0x7d, i64: 0x7e, i32: 0x7f
|
||||
}),
|
||||
/** Encodes n, which must be <2^14 (16384), into target array
|
||||
tgt, as a little-endian value, using the given method
|
||||
('push' or 'unshift'). */
|
||||
@@ -430,9 +451,9 @@ self.WhWasmUtilInstaller = function(target){
|
||||
// is not yet documented on MDN.
|
||||
sigToWasm: function(sig){
|
||||
const rc = {parameters:[], results: []};
|
||||
if('v'!==sig[0]) rc.results.push(f._.letterType(sig[0]));
|
||||
if('v'!==sig[0]) rc.results.push(f.sigTypes(sig[0]));
|
||||
for(const x of f._.sigParams(sig)){
|
||||
rc.parameters.push(f._.letterType(x));
|
||||
rc.parameters.push(f._.typeCodes(x));
|
||||
}
|
||||
return rc;
|
||||
},************/
|
||||
@@ -441,11 +462,12 @@ self.WhWasmUtilInstaller = function(target){
|
||||
invalid. */
|
||||
pushSigType: (dest, letter)=>dest.push(f._.typeCodes[f._.letterType(letter)])
|
||||
};
|
||||
f._.sigTypes.i = f._.sigTypes.p = f._.sigTypes.P = f._.sigTypes.s = 'i32';
|
||||
f._.sigTypes.j = 'i64'; f._.sigTypes.f = 'f32'; f._.sigTypes.d = 'f64';
|
||||
f._.typeCodes['i32'] = 0x7f; f._.typeCodes['i64'] = 0x7e;
|
||||
f._.typeCodes['f32'] = 0x7d; f._.typeCodes['f64'] = 0x7c;
|
||||
}/*static init*/
|
||||
if('string'===typeof func){
|
||||
const x = sig;
|
||||
sig = func;
|
||||
func = x;
|
||||
}
|
||||
const sigParams = f._.sigParams(sig);
|
||||
const wasmCode = [0x01/*count: 1*/, 0x60/*function*/];
|
||||
f._.uleb128Encode(wasmCode, 'push', sigParams.length);
|
||||
@@ -482,9 +504,12 @@ self.WhWasmUtilInstaller = function(target){
|
||||
available slot of this.functionTable(), and returns the
|
||||
function's index in that table (which acts as a pointer to that
|
||||
function). The returned pointer can be passed to
|
||||
removeFunction() to uninstall it and free up the table slot for
|
||||
uninstallFunction() to uninstall it and free up the table slot for
|
||||
reuse.
|
||||
|
||||
If passed (string,function) arguments then it treats the first
|
||||
argument as the signature and second as the function.
|
||||
|
||||
As a special case, if the passed-in function is a WASM-exported
|
||||
function then the signature argument is ignored and func is
|
||||
installed as-is, without requiring re-compilation/re-wrapping.
|
||||
@@ -498,13 +523,21 @@ self.WhWasmUtilInstaller = function(target){
|
||||
Sidebar: this function differs from Emscripten's addFunction()
|
||||
_primarily_ in that it does not share that function's
|
||||
undocumented behavior of reusing a function if it's passed to
|
||||
addFunction() more than once, which leads to removeFunction()
|
||||
addFunction() more than once, which leads to uninstallFunction()
|
||||
breaking clients which do not take care to avoid that case:
|
||||
|
||||
https://github.com/emscripten-core/emscripten/issues/17323
|
||||
*/
|
||||
target.installFunction = function f(func, sig){
|
||||
const ft = this.functionTable();
|
||||
if(2!==arguments.length){
|
||||
toss("installFunction() requires exactly 2 arguments");
|
||||
}
|
||||
if('string'===typeof func){
|
||||
const x = sig;
|
||||
sig = func;
|
||||
func = x;
|
||||
}
|
||||
const ft = target.functionTable();
|
||||
const oldLen = ft.length;
|
||||
let ptr;
|
||||
while(cache.freeFuncIndexes.length){
|
||||
@@ -532,13 +565,13 @@ self.WhWasmUtilInstaller = function(target){
|
||||
}
|
||||
// It's not a WASM-exported function, so compile one...
|
||||
try {
|
||||
ft.set(ptr, this.jsFuncToWasm(func, sig));
|
||||
ft.set(ptr, target.jsFuncToWasm(func, sig));
|
||||
}catch(e){
|
||||
if(ptr===oldLen) cache.freeFuncIndexes.push(oldLen);
|
||||
throw e;
|
||||
}
|
||||
return ptr;
|
||||
}.bind(target);
|
||||
};
|
||||
|
||||
/**
|
||||
Requires a pointer value previously returned from
|
||||
@@ -551,12 +584,12 @@ self.WhWasmUtilInstaller = function(target){
|
||||
*/
|
||||
target.uninstallFunction = function(ptr){
|
||||
const fi = cache.freeFuncIndexes;
|
||||
const ft = this.functionTable();
|
||||
const ft = target.functionTable();
|
||||
fi.push(ptr);
|
||||
const rc = ft.get(ptr);
|
||||
ft.set(ptr, null);
|
||||
return rc;
|
||||
}.bind(target);
|
||||
};
|
||||
|
||||
/**
|
||||
Given a WASM heap memory address and a data type name in the form
|
||||
@@ -602,6 +635,10 @@ self.WhWasmUtilInstaller = function(target){
|
||||
out) the pointer's value, else it will contain an essentially
|
||||
random value.
|
||||
|
||||
ACHTUNG: calling this often, e.g. in a loop, can have a noticably
|
||||
painful impact on performance. Rather than doing so, use
|
||||
heapForSize() to fetch the heap object and read directly from it.
|
||||
|
||||
See: setMemValue()
|
||||
*/
|
||||
target.getMemValue = function(ptr, type='i8'){
|
||||
@@ -614,14 +651,14 @@ self.WhWasmUtilInstaller = function(target){
|
||||
case 'i16': return c.HEAP16[ptr>>1];
|
||||
case 'i32': return c.HEAP32[ptr>>2];
|
||||
case 'i64':
|
||||
if(this.bigIntEnabled) return BigInt(c.HEAP64[ptr>>3]);
|
||||
if(target.bigIntEnabled) return BigInt(c.HEAP64[ptr>>3]);
|
||||
break;
|
||||
case 'float': case 'f32': return c.HEAP32F[ptr>>2];
|
||||
case 'double': case 'f64': return Number(c.HEAP64F[ptr>>3]);
|
||||
default: break;
|
||||
}
|
||||
toss('Invalid type for getMemValue():',type);
|
||||
}.bind(target);
|
||||
};
|
||||
|
||||
/**
|
||||
The counterpart of getMemValue(), this sets a numeric value at
|
||||
@@ -632,6 +669,10 @@ self.WhWasmUtilInstaller = function(target){
|
||||
this function behaves as if the 3rd argument were `i32`.
|
||||
|
||||
This function returns itself.
|
||||
|
||||
ACHTUNG: calling this often, e.g. in a loop, can have a noticably
|
||||
painful impact on performance. Rather than doing so, use
|
||||
heapForSize() to fetch the heap object and assign directly to it.
|
||||
*/
|
||||
target.setMemValue = function f(ptr, value, type='i8'){
|
||||
if (type.endsWith('*')) type = ptrIR;
|
||||
@@ -654,6 +695,32 @@ self.WhWasmUtilInstaller = function(target){
|
||||
toss('Invalid type for setMemValue(): ' + type);
|
||||
};
|
||||
|
||||
|
||||
/** Convenience form of getMemValue() intended for fetching
|
||||
pointer-to-pointer values. */
|
||||
target.getPtrValue = (ptr)=>target.getMemValue(ptr, ptrIR);
|
||||
|
||||
/** Convenience form of setMemValue() intended for setting
|
||||
pointer-to-pointer values. */
|
||||
target.setPtrValue = (ptr, value)=>target.setMemValue(ptr, value, ptrIR);
|
||||
|
||||
/**
|
||||
Returns true if the given value appears to be legal for use as
|
||||
a WASM pointer value. Its _range_ of values is not (cannot be)
|
||||
validated except to ensure that it is a 32-bit integer with a
|
||||
value of 0 or greater. Likewise, it cannot verify whether the
|
||||
value actually refers to allocated memory in the WASM heap.
|
||||
*/
|
||||
target.isPtr32 = (ptr)=>('number'===typeof ptr && (ptr===(ptr|0)) && ptr>=0);
|
||||
|
||||
/**
|
||||
isPtr() is an alias for isPtr32(). If/when 64-bit WASM pointer
|
||||
support becomes widespread, it will become an alias for either
|
||||
isPtr32() or the as-yet-hypothetical isPtr64(), depending on a
|
||||
configuration option.
|
||||
*/
|
||||
target.isPtr = target.isPtr32;
|
||||
|
||||
/**
|
||||
Expects ptr to be a pointer into the WASM heap memory which
|
||||
refers to a NUL-terminated C-style string encoded as UTF-8.
|
||||
@@ -669,6 +736,18 @@ self.WhWasmUtilInstaller = function(target){
|
||||
return pos - ptr;
|
||||
};
|
||||
|
||||
/** Internal helper to use in operations which need to distinguish
|
||||
between SharedArrayBuffer heap memory and non-shared heap. */
|
||||
const __SAB = ('undefined'===typeof SharedArrayBuffer)
|
||||
? function(){} : SharedArrayBuffer;
|
||||
const __utf8Decode = function(arrayBuffer, begin, end){
|
||||
return cache.utf8Decoder.decode(
|
||||
(arrayBuffer.buffer instanceof __SAB)
|
||||
? arrayBuffer.slice(begin, end)
|
||||
: arrayBuffer.subarray(begin, end)
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
Expects ptr to be a pointer into the WASM heap memory which
|
||||
refers to a NUL-terminated C-style string encoded as UTF-8. This
|
||||
@@ -677,13 +756,9 @@ self.WhWasmUtilInstaller = function(target){
|
||||
ptr is falsy, `null` is returned.
|
||||
*/
|
||||
target.cstringToJs = function(ptr){
|
||||
const n = this.cstrlen(ptr);
|
||||
if(null===n) return n;
|
||||
return n
|
||||
? cache.utf8Decoder.decode(
|
||||
new Uint8Array(heapWrappers().HEAP8U.buffer, ptr, n)
|
||||
) : "";
|
||||
}.bind(target);
|
||||
const n = target.cstrlen(ptr);
|
||||
return n ? __utf8Decode(heapWrappers().HEAP8U, ptr, ptr+n) : (null===n ? n : "");
|
||||
};
|
||||
|
||||
/**
|
||||
Given a JS string, this function returns its UTF-8 length in
|
||||
@@ -811,16 +886,16 @@ self.WhWasmUtilInstaller = function(target){
|
||||
*/
|
||||
target.cstrncpy = function(tgtPtr, srcPtr, n){
|
||||
if(!tgtPtr || !srcPtr) toss("cstrncpy() does not accept NULL strings.");
|
||||
if(n<0) n = this.cstrlen(strPtr)+1;
|
||||
if(n<0) n = target.cstrlen(strPtr)+1;
|
||||
else if(!(n>0)) return 0;
|
||||
const heap = this.heap8u();
|
||||
const heap = target.heap8u();
|
||||
let i = 0, ch;
|
||||
for(; i < n && (ch = heap[srcPtr+i]); ++i){
|
||||
heap[tgtPtr+i] = ch;
|
||||
}
|
||||
if(i<n) heap[tgtPtr + i++] = 0;
|
||||
return i;
|
||||
}.bind(target);
|
||||
};
|
||||
|
||||
/**
|
||||
For the given JS string, returns a Uint8Array of its contents
|
||||
@@ -865,13 +940,13 @@ self.WhWasmUtilInstaller = function(target){
|
||||
};
|
||||
|
||||
const __allocCStr = function(jstr, returnWithLength, allocator, funcName){
|
||||
__affirmAlloc(this, funcName);
|
||||
__affirmAlloc(target, funcName);
|
||||
if('string'!==typeof jstr) return null;
|
||||
const n = this.jstrlen(jstr),
|
||||
const n = target.jstrlen(jstr),
|
||||
ptr = allocator(n+1);
|
||||
this.jstrcpy(jstr, this.heap8u(), ptr, n+1, true);
|
||||
target.jstrcpy(jstr, target.heap8u(), ptr, n+1, true);
|
||||
return returnWithLength ? [ptr, n] : ptr;
|
||||
}.bind(target);
|
||||
};
|
||||
|
||||
/**
|
||||
Uses target.alloc() to allocate enough memory for jstrlen(jstr)+1
|
||||
@@ -924,11 +999,11 @@ self.WhWasmUtilInstaller = function(target){
|
||||
alloc levels are currently active.
|
||||
*/
|
||||
target.scopedAllocPush = function(){
|
||||
__affirmAlloc(this, 'scopedAllocPush');
|
||||
__affirmAlloc(target, 'scopedAllocPush');
|
||||
const a = [];
|
||||
cache.scopedAlloc.push(a);
|
||||
return a;
|
||||
}.bind(target);
|
||||
};
|
||||
|
||||
/**
|
||||
Cleans up all allocations made using scopedAlloc() in the context
|
||||
@@ -953,15 +1028,15 @@ self.WhWasmUtilInstaller = function(target){
|
||||
trivial code that may be a non-issue.
|
||||
*/
|
||||
target.scopedAllocPop = function(state){
|
||||
__affirmAlloc(this, 'scopedAllocPop');
|
||||
__affirmAlloc(target, 'scopedAllocPop');
|
||||
const n = arguments.length
|
||||
? cache.scopedAlloc.indexOf(state)
|
||||
: cache.scopedAlloc.length-1;
|
||||
if(n<0) toss("Invalid state object for scopedAllocPop().");
|
||||
if(0===arguments.length) state = cache.scopedAlloc[n];
|
||||
cache.scopedAlloc.splice(n,1);
|
||||
for(let p; (p = state.pop()); ) this.dealloc(p);
|
||||
}.bind(target);
|
||||
for(let p; (p = state.pop()); ) target.dealloc(p);
|
||||
};
|
||||
|
||||
/**
|
||||
Allocates n bytes of memory using this.alloc() and records that
|
||||
@@ -983,10 +1058,10 @@ self.WhWasmUtilInstaller = function(target){
|
||||
if(!cache.scopedAlloc.length){
|
||||
toss("No scopedAllocPush() scope is active.");
|
||||
}
|
||||
const p = this.alloc(n);
|
||||
const p = target.alloc(n);
|
||||
cache.scopedAlloc[cache.scopedAlloc.length-1].push(p);
|
||||
return p;
|
||||
}.bind(target);
|
||||
};
|
||||
|
||||
Object.defineProperty(target.scopedAlloc, 'level', {
|
||||
configurable: false, enumerable: false,
|
||||
@@ -1004,6 +1079,42 @@ self.WhWasmUtilInstaller = function(target){
|
||||
(jstr, returnWithLength=false)=>__allocCStr(jstr, returnWithLength,
|
||||
target.scopedAlloc, 'scopedAllocCString()');
|
||||
|
||||
// impl for allocMainArgv() and scopedAllocMainArgv().
|
||||
const __allocMainArgv = function(isScoped, list){
|
||||
if(!list.length) toss("Cannot allocate empty array.");
|
||||
const pList = target[
|
||||
isScoped ? 'scopedAlloc' : 'alloc'
|
||||
](list.length * target.ptrSizeof);
|
||||
let i = 0;
|
||||
list.forEach((e)=>{
|
||||
target.setPtrValue(pList + (target.ptrSizeof * i++),
|
||||
target[
|
||||
isScoped ? 'scopedAllocCString' : 'allocCString'
|
||||
](""+e));
|
||||
});
|
||||
return pList;
|
||||
};
|
||||
|
||||
/**
|
||||
Creates an array, using scopedAlloc(), suitable for passing to a
|
||||
C-level main() routine. The input is a collection with a length
|
||||
property and a forEach() method. A block of memory list.length
|
||||
entries long is allocated and each pointer-sized block of that
|
||||
memory is populated with a scopedAllocCString() conversion of the
|
||||
(""+value) of each element. Returns a pointer to the start of the
|
||||
list, suitable for passing as the 2nd argument to a C-style
|
||||
main() function.
|
||||
|
||||
Throws if list.length is falsy or scopedAllocPush() is not active.
|
||||
*/
|
||||
target.scopedAllocMainArgv = (list)=>__allocMainArgv(true, list);
|
||||
|
||||
/**
|
||||
Identical to scopedAllocMainArgv() but uses alloc() instead of
|
||||
scopedAllocMainArgv
|
||||
*/
|
||||
target.allocMainArgv = (list)=>__allocMainArgv(false, list);
|
||||
|
||||
/**
|
||||
Wraps function call func() in a scopedAllocPush() and
|
||||
scopedAllocPop() block, such that all calls to scopedAlloc() and
|
||||
@@ -1013,33 +1124,41 @@ self.WhWasmUtilInstaller = function(target){
|
||||
result of calling func().
|
||||
*/
|
||||
target.scopedAllocCall = function(func){
|
||||
this.scopedAllocPush();
|
||||
try{ return func() } finally{ this.scopedAllocPop() }
|
||||
}.bind(target);
|
||||
target.scopedAllocPush();
|
||||
try{ return func() } finally{ target.scopedAllocPop() }
|
||||
};
|
||||
|
||||
/** Internal impl for allocPtr() and scopedAllocPtr(). */
|
||||
const __allocPtr = function(howMany, method){
|
||||
__affirmAlloc(this, method);
|
||||
let m = this[method](howMany * ptrSizeof);
|
||||
this.setMemValue(m, 0, ptrIR)
|
||||
const __allocPtr = function(howMany, safePtrSize, method){
|
||||
__affirmAlloc(target, method);
|
||||
const pIr = safePtrSize ? 'i64' : ptrIR;
|
||||
let m = target[method](howMany * (safePtrSize ? 8 : ptrSizeof));
|
||||
target.setMemValue(m, 0, pIr)
|
||||
if(1===howMany){
|
||||
return m;
|
||||
}
|
||||
const a = [m];
|
||||
for(let i = 1; i < howMany; ++i){
|
||||
m += ptrSizeof;
|
||||
m += (safePtrSize ? 8 : ptrSizeof);
|
||||
a[i] = m;
|
||||
this.setMemValue(m, 0, ptrIR);
|
||||
target.setMemValue(m, 0, pIr);
|
||||
}
|
||||
return a;
|
||||
}.bind(target);
|
||||
};
|
||||
|
||||
/**
|
||||
Allocates a single chunk of memory capable of holding `howMany`
|
||||
pointers and zeroes them out. If `howMany` is 1 then the memory
|
||||
chunk is returned directly, else an array of pointer addresses is
|
||||
returned, which can optionally be used with "destructuring
|
||||
assignment" like this:
|
||||
Allocates one or more pointers as a single chunk of memory and
|
||||
zeroes them out.
|
||||
|
||||
The first argument is the number of pointers to allocate. The
|
||||
second specifies whether they should use a "safe" pointer size (8
|
||||
bytes) or whether they may use the default pointer size
|
||||
(typically 4 but also possibly 8).
|
||||
|
||||
How the result is returned depends on its first argument: if
|
||||
passed 1, it returns the allocated memory address. If passed more
|
||||
than one then an array of pointer addresses is returned, which
|
||||
can optionally be used with "destructuring assignment" like this:
|
||||
|
||||
```
|
||||
const [p1, p2, p3] = allocPtr(3);
|
||||
@@ -1048,14 +1167,27 @@ self.WhWasmUtilInstaller = function(target){
|
||||
ACHTUNG: when freeing the memory, pass only the _first_ result
|
||||
value to dealloc(). The others are part of the same memory chunk
|
||||
and must not be freed separately.
|
||||
|
||||
The reason for the 2nd argument is..
|
||||
|
||||
When one of the returned pointers will refer to a 64-bit value,
|
||||
e.g. a double or int64, an that value must be written or fetched,
|
||||
e.g. using setMemValue() or getMemValue(), it is important that
|
||||
the pointer in question be aligned to an 8-byte boundary or else
|
||||
it will not be fetched or written properly and will corrupt or
|
||||
read neighboring memory. It is only safe to pass false when the
|
||||
client code is certain that it will only get/fetch 4-byte values
|
||||
(or smaller).
|
||||
*/
|
||||
target.allocPtr = (howMany=1)=>__allocPtr(howMany, 'alloc');
|
||||
target.allocPtr =
|
||||
(howMany=1, safePtrSize=true)=>__allocPtr(howMany, safePtrSize, 'alloc');
|
||||
|
||||
/**
|
||||
Identical to allocPtr() except that it allocates using scopedAlloc()
|
||||
instead of alloc().
|
||||
*/
|
||||
target.scopedAllocPtr = (howMany=1)=>__allocPtr(howMany, 'scopedAlloc');
|
||||
target.scopedAllocPtr =
|
||||
(howMany=1, safePtrSize=true)=>__allocPtr(howMany, safePtrSize, 'scopedAlloc');
|
||||
|
||||
/**
|
||||
If target.exports[name] exists, it is returned, else an
|
||||
@@ -1070,11 +1202,11 @@ self.WhWasmUtilInstaller = function(target){
|
||||
|
||||
/**
|
||||
Looks up a WASM-exported function named fname from
|
||||
target.exports. If found, it is called, passed all remaining
|
||||
target.exports. If found, it is called, passed all remaining
|
||||
arguments, and its return value is returned to xCall's caller. If
|
||||
not found, an exception is thrown. This function does no
|
||||
conversion of argument or return types, but see xWrap()
|
||||
and xCallWrapped() for variants which do.
|
||||
conversion of argument or return types, but see xWrap() and
|
||||
xCallWrapped() for variants which do.
|
||||
|
||||
As a special case, if passed only 1 argument after the name and
|
||||
that argument in an Array, that array's entries become the
|
||||
@@ -1082,7 +1214,7 @@ self.WhWasmUtilInstaller = function(target){
|
||||
not legal to pass an Array object to a WASM function.)
|
||||
*/
|
||||
target.xCall = function(fname, ...args){
|
||||
const f = this.xGet(fname);
|
||||
const f = target.xGet(fname);
|
||||
if(!(f instanceof Function)) toss("Exported symbol",fname,"is not a function.");
|
||||
if(f.length!==args.length) __argcMismatch(fname,f.length)
|
||||
/* This is arguably over-pedantic but we want to help clients keep
|
||||
@@ -1090,7 +1222,7 @@ self.WhWasmUtilInstaller = function(target){
|
||||
return (2===arguments.length && Array.isArray(arguments[1]))
|
||||
? f.apply(null, arguments[1])
|
||||
: f.apply(null, args);
|
||||
}.bind(target);
|
||||
};
|
||||
|
||||
/**
|
||||
State for use with xWrap()
|
||||
@@ -1102,21 +1234,28 @@ self.WhWasmUtilInstaller = function(target){
|
||||
/** Map of type names to return result conversion functions. */
|
||||
cache.xWrap.convert.result = Object.create(null);
|
||||
|
||||
xcv.arg.i64 = (i)=>BigInt(i);
|
||||
if(target.bigIntEnabled){
|
||||
xcv.arg.i64 = (i)=>BigInt(i);
|
||||
}
|
||||
xcv.arg.i32 = (i)=>(i | 0);
|
||||
xcv.arg.i16 = (i)=>((i | 0) & 0xFFFF);
|
||||
xcv.arg.i8 = (i)=>((i | 0) & 0xFF);
|
||||
xcv.arg.f32 = xcv.arg.float = (i)=>Number(i).valueOf();
|
||||
xcv.arg.f64 = xcv.arg.double = xcv.arg.f32;
|
||||
xcv.arg.int = xcv.arg.i32;
|
||||
xcv.result['*'] = xcv.result['pointer'] = xcv.arg[ptrIR];
|
||||
xcv.result['*'] = xcv.result['pointer'] = xcv.arg['**'] = xcv.arg[ptrIR];
|
||||
xcv.result['number'] = (v)=>Number(v);
|
||||
|
||||
for(const t of ['i8', 'i16', 'i32', 'int', 'i64',
|
||||
'f32', 'float', 'f64', 'double']){
|
||||
xcv.arg[t+'*'] = xcv.result[t+'*'] = xcv.arg[ptrIR]
|
||||
xcv.result[t] = xcv.arg[t] || toss("Missing arg converter:",t);
|
||||
{ /* Copy certain xcv.arg[...] handlers to xcv.result[...] and
|
||||
add pointer-style variants of them. */
|
||||
const copyToResult = ['i8', 'i16', 'i32', 'int',
|
||||
'f32', 'float', 'f64', 'double'];
|
||||
if(target.bigIntEnabled) copyToResult.push('i64');
|
||||
for(const t of copyToResult){
|
||||
xcv.arg[t+'*'] = xcv.result[t+'*'] = xcv.arg[ptrIR];
|
||||
xcv.result[t] = xcv.arg[t] || toss("Missing arg converter:",t);
|
||||
}
|
||||
}
|
||||
xcv.arg['**'] = xcv.arg[ptrIR];
|
||||
|
||||
/**
|
||||
In order for args of type string to work in various contexts in
|
||||
@@ -1134,17 +1273,18 @@ self.WhWasmUtilInstaller = function(target){
|
||||
Would that be too much magic concentrated in one place, ready to
|
||||
backfire?
|
||||
*/
|
||||
xcv.arg.string = xcv.arg['pointer'] = xcv.arg['*'] = function(v){
|
||||
if('string'===typeof v) return target.scopedAllocCString(v);
|
||||
return v ? xcv.arg[ptrIR](v) : null;
|
||||
};
|
||||
xcv.result.string = (i)=>target.cstringToJs(i);
|
||||
xcv.result['string:free'] = function(i){
|
||||
xcv.arg.string = xcv.arg.utf8 = xcv.arg['pointer'] = xcv.arg['*']
|
||||
= function(v){
|
||||
if('string'===typeof v) return target.scopedAllocCString(v);
|
||||
return v ? xcv.arg[ptrIR](v) : null;
|
||||
};
|
||||
xcv.result.string = xcv.result.utf8 = (i)=>target.cstringToJs(i);
|
||||
xcv.result['string:free'] = xcv.result['utf8:free'] = (i)=>{
|
||||
try { return i ? target.cstringToJs(i) : null }
|
||||
finally{ target.dealloc(i) }
|
||||
};
|
||||
xcv.result.json = (i)=>JSON.parse(target.cstringToJs(i));
|
||||
xcv.result['json:free'] = function(i){
|
||||
xcv.result['json:free'] = (i)=>{
|
||||
try{ return i ? JSON.parse(target.cstringToJs(i)) : null }
|
||||
finally{ target.dealloc(i) }
|
||||
}
|
||||
@@ -1164,19 +1304,19 @@ self.WhWasmUtilInstaller = function(target){
|
||||
*/
|
||||
xcv.arg['func-ptr'] = function(v){
|
||||
if(!(v instanceof Function)) return xcv.arg[ptrIR];
|
||||
const f = this.jsFuncToWasm(v, WHAT_SIGNATURE);
|
||||
}.bind(target);
|
||||
const f = target.jsFuncToWasm(v, WHAT_SIGNATURE);
|
||||
};
|
||||
}
|
||||
|
||||
const __xArgAdapter =
|
||||
const __xArgAdapterCheck =
|
||||
(t)=>xcv.arg[t] || toss("Argument adapter not found:",t);
|
||||
|
||||
const __xResultAdapter =
|
||||
const __xResultAdapterCheck =
|
||||
(t)=>xcv.result[t] || toss("Result adapter not found:",t);
|
||||
|
||||
cache.xWrap.convertArg = (t,v)=>__xArgAdapter(t)(v);
|
||||
cache.xWrap.convertArg = (t,v)=>__xArgAdapterCheck(t)(v);
|
||||
cache.xWrap.convertResult =
|
||||
(t,v)=>(null===t ? v : (t ? __xResultAdapter(t)(v) : undefined));
|
||||
(t,v)=>(null===t ? v : (t ? __xResultAdapterCheck(t)(v) : undefined));
|
||||
|
||||
/**
|
||||
Creates a wrapper for the WASM-exported function fname. Uses
|
||||
@@ -1239,43 +1379,63 @@ self.WhWasmUtilInstaller = function(target){
|
||||
type. It's primarily intended to mark output-pointer arguments.
|
||||
|
||||
- `i64` (args and results): passes the value to BigInt() to
|
||||
convert it to an int64.
|
||||
convert it to an int64. Only available if bigIntEnabled is
|
||||
true.
|
||||
|
||||
- `f32` (`float`), `f64` (`double`) (args and results): pass
|
||||
their argument to Number(). i.e. the adaptor does not currently
|
||||
distinguish between the two types of floating-point numbers.
|
||||
|
||||
- `number` (results): converts the result to a JS Number using
|
||||
Number(theValue).valueOf(). Note that this is for result
|
||||
conversions only, as it's not possible to generically know
|
||||
which type of number to convert arguments to.
|
||||
|
||||
Non-numeric conversions include:
|
||||
|
||||
- `string` (args): has two different semantics in order to
|
||||
accommodate various uses of certain C APIs (e.g. output-style
|
||||
strings)...
|
||||
- `string` or `utf8` (args): has two different semantics in order
|
||||
to accommodate various uses of certain C APIs
|
||||
(e.g. output-style strings)...
|
||||
|
||||
- If the arg is a string, it creates a _temporary_ C-string to
|
||||
pass to the exported function, cleaning it up before the
|
||||
wrapper returns. If a long-lived C-string pointer is
|
||||
required, that requires client-side code to create the
|
||||
string, then pass its pointer to the function.
|
||||
- If the arg is a string, it creates a _temporary_
|
||||
UTF-8-encoded C-string to pass to the exported function,
|
||||
cleaning it up before the wrapper returns. If a long-lived
|
||||
C-string pointer is required, that requires client-side code
|
||||
to create the string, then pass its pointer to the function.
|
||||
|
||||
- Else the arg is assumed to be a pointer to a string the
|
||||
client has already allocated and it's passed on as
|
||||
a WASM pointer.
|
||||
|
||||
- `string` (results): treats the result value as a const C-string,
|
||||
copies it to a JS string, and returns that JS string.
|
||||
- `string` or `utf8` (results): treats the result value as a
|
||||
const C-string, encoded as UTF-8, copies it to a JS string,
|
||||
and returns that JS string.
|
||||
|
||||
- `string:free` (results): treats the result value as a non-const
|
||||
C-string, ownership of which has just been transfered to the
|
||||
caller. It copies the C-string to a JS string, frees the
|
||||
C-string, and returns the JS string. If such a result value is
|
||||
NULL, the JS result is `null`.
|
||||
- `string:free` or `utf8:free) (results): treats the result value
|
||||
as a non-const UTF-8 C-string, ownership of which has just been
|
||||
transfered to the caller. It copies the C-string to a JS
|
||||
string, frees the C-string, and returns the JS string. If such
|
||||
a result value is NULL, the JS result is `null`. Achtung: when
|
||||
using an API which returns results from a specific allocator,
|
||||
e.g. `my_malloc()`, this conversion _is not legal_. Instead, an
|
||||
equivalent conversion which uses the appropriate deallocator is
|
||||
required. For example:
|
||||
|
||||
```js
|
||||
target.xWrap.resultAdaptor('string:my_free',(i)=>{
|
||||
try { return i ? target.cstringToJs(i) : null }
|
||||
finally{ target.exports.my_free(i) }
|
||||
};
|
||||
```
|
||||
|
||||
- `json` (results): treats the result as a const C-string and
|
||||
returns the result of passing the converted-to-JS string to
|
||||
JSON.parse(). Returns `null` if the C-string is a NULL pointer.
|
||||
|
||||
- `json:free` (results): works exactly like `string:free` but
|
||||
returns the same thing as the `json` adapter.
|
||||
returns the same thing as the `json` adapter. Note the
|
||||
warning in `string:free` regarding maching allocators and
|
||||
deallocators.
|
||||
|
||||
The type names for results and arguments are validated when
|
||||
xWrap() is called and any unknown names will trigger an
|
||||
@@ -1310,34 +1470,32 @@ self.WhWasmUtilInstaller = function(target){
|
||||
if(3===arguments.length && Array.isArray(arguments[2])){
|
||||
argTypes = arguments[2];
|
||||
}
|
||||
const xf = this.xGet(fname);
|
||||
if(argTypes.length!==xf.length) __argcMismatch(fname, xf.length)
|
||||
const xf = target.xGet(fname);
|
||||
if(argTypes.length!==xf.length) __argcMismatch(fname, xf.length);
|
||||
if((null===resultType) && 0===xf.length){
|
||||
/* Func taking no args with an as-is return. We don't need a wrapper. */
|
||||
return xf;
|
||||
}
|
||||
/*Verify the arg type conversions are valid...*/;
|
||||
if(undefined!==resultType && null!==resultType) __xResultAdapter(resultType);
|
||||
argTypes.forEach(__xArgAdapter)
|
||||
if(undefined!==resultType && null!==resultType) __xResultAdapterCheck(resultType);
|
||||
argTypes.forEach(__xArgAdapterCheck);
|
||||
if(0===xf.length){
|
||||
// No args to convert, so we can create a simpler wrapper...
|
||||
return function(){
|
||||
return (arguments.length
|
||||
? __argcMismatch(fname, xf.length)
|
||||
: cache.xWrap.convertResult(resultType, xf.call(null)));
|
||||
};
|
||||
return (...args)=>(args.length
|
||||
? __argcMismatch(fname, xf.length)
|
||||
: cache.xWrap.convertResult(resultType, xf.call(null)));
|
||||
}
|
||||
return function(...args){
|
||||
if(args.length!==xf.length) __argcMismatch(fname, xf.length);
|
||||
const scope = this.scopedAllocPush();
|
||||
const scope = target.scopedAllocPush();
|
||||
try{
|
||||
const rc = xf.apply(null,args.map((v,i)=>cache.xWrap.convertArg(argTypes[i], v)));
|
||||
return cache.xWrap.convertResult(resultType, rc);
|
||||
}finally{
|
||||
this.scopedAllocPop(scope);
|
||||
target.scopedAllocPop(scope);
|
||||
}
|
||||
}.bind(this);
|
||||
}.bind(target)/*xWrap()*/;
|
||||
};
|
||||
}/*xWrap()*/;
|
||||
|
||||
/** Internal impl for xWrap.resultAdapter() and argAdaptor(). */
|
||||
const __xAdapter = function(func, argc, typeName, adapter, modeName, xcvPart){
|
||||
@@ -1428,11 +1586,10 @@ self.WhWasmUtilInstaller = function(target){
|
||||
type name, as documented for xWrap() (use a falsy value or an
|
||||
empty array for nullary functions). The 4th+ arguments are
|
||||
arguments for the call, with the special case that if the 4th
|
||||
argument is an array, it is used as the arguments for the call
|
||||
(again, falsy or an empty array for nullary functions). Returns
|
||||
the converted result of the call.
|
||||
argument is an array, it is used as the arguments for the
|
||||
call. Returns the converted result of the call.
|
||||
|
||||
This is just a thin wrapp around xWrap(). If the given function
|
||||
This is just a thin wrapper around xWrap(). If the given function
|
||||
is to be called more than once, it's more efficient to use
|
||||
xWrap() to create a wrapper, then to call that wrapper as many
|
||||
times as needed. For one-shot calls, however, this variant is
|
||||
@@ -1441,9 +1598,9 @@ self.WhWasmUtilInstaller = function(target){
|
||||
*/
|
||||
target.xCallWrapped = function(fname, resultType, argTypes, ...args){
|
||||
if(Array.isArray(arguments[3])) args = arguments[3];
|
||||
return this.xWrap(fname, resultType, argTypes||[]).apply(null, args||[]);
|
||||
}.bind(target);
|
||||
|
||||
return target.xWrap(fname, resultType, argTypes||[]).apply(null, args||[]);
|
||||
};
|
||||
|
||||
return target;
|
||||
};
|
||||
|
||||
@@ -1455,11 +1612,11 @@ self.WhWasmUtilInstaller = function(target){
|
||||
|
||||
- `onload(loadResult,config)`: optional callback. The first
|
||||
argument is the result object from
|
||||
WebAssembly.instanitate[Streaming](). The 2nd is the config
|
||||
WebAssembly.instantiate[Streaming](). The 2nd is the config
|
||||
object passed to this function. Described in more detail below.
|
||||
|
||||
- `imports`: optional imports object for
|
||||
WebAssembly.instantiate[Streaming](). The default is am empty set
|
||||
WebAssembly.instantiate[Streaming](). The default is an empty set
|
||||
of imports. If the module requires any imports, this object
|
||||
must include them.
|
||||
|
||||
@@ -1522,10 +1679,11 @@ self.WhWasmUtilInstaller.yawl = function(config){
|
||||
|| toss("Missing 'memory' object!");
|
||||
}
|
||||
if(!tgt.alloc && arg.instance.exports.malloc){
|
||||
const exports = arg.instance.exports;
|
||||
tgt.alloc = function(n){
|
||||
return this(n) || toss("Allocation of",n,"bytes failed.");
|
||||
}.bind(arg.instance.exports.malloc);
|
||||
tgt.dealloc = function(m){this(m)}.bind(arg.instance.exports.free);
|
||||
return exports.malloc(n) || toss("Allocation of",n,"bytes failed.");
|
||||
};
|
||||
tgt.dealloc = function(m){exports.free(m)};
|
||||
}
|
||||
wui(tgt);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
})();
|
||||
@@ -6,10 +6,10 @@
|
||||
<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.js tests</title>
|
||||
<title>worker-promise tests</title>
|
||||
</head>
|
||||
<body>
|
||||
<header id='titlebar'><span>sqlite3-api.js tests</span></header>
|
||||
<header id='titlebar'><span>worker-promise tests</span></header>
|
||||
<!-- emscripten bits -->
|
||||
<figure id="module-spinner">
|
||||
<div class="spinner"></div>
|
||||
@@ -27,8 +27,8 @@
|
||||
<div>Most stuff on this page happens in the dev console.</div>
|
||||
<hr>
|
||||
<div id='test-output'></div>
|
||||
<script src="api/sqlite3.js"></script>
|
||||
<script src="common/SqliteTestUtil.js"></script>
|
||||
<script src="testing1.js"></script>
|
||||
<script src="jswasm/sqlite3-worker1-promiser.js"></script>
|
||||
<script src="demo-worker1-promiser.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,270 @@
|
||||
/*
|
||||
2022-08-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.
|
||||
|
||||
***********************************************************************
|
||||
|
||||
Demonstration of the sqlite3 Worker API #1 Promiser: a Promise-based
|
||||
proxy for for the sqlite3 Worker #1 API.
|
||||
*/
|
||||
'use strict';
|
||||
(function(){
|
||||
const T = self.SqliteTestUtil;
|
||||
const eOutput = document.querySelector('#test-output');
|
||||
const warn = console.warn.bind(console);
|
||||
const error = console.error.bind(console);
|
||||
const log = console.log.bind(console);
|
||||
const logHtml = async function(cssClass,...args){
|
||||
log.apply(this, args);
|
||||
const ln = document.createElement('div');
|
||||
if(cssClass) ln.classList.add(cssClass);
|
||||
ln.append(document.createTextNode(args.join(' ')));
|
||||
eOutput.append(ln);
|
||||
};
|
||||
|
||||
let startTime;
|
||||
const testCount = async ()=>{
|
||||
logHtml("","Total test count:",T.counter+". Total time =",(performance.now() - startTime),"ms");
|
||||
};
|
||||
|
||||
//why is this triggered even when we catch() a Promise?
|
||||
//window.addEventListener('unhandledrejection', function(event) {
|
||||
// warn('unhandledrejection',event);
|
||||
//});
|
||||
|
||||
const promiserConfig = {
|
||||
worker: ()=>{
|
||||
const w = new Worker("jswasm/sqlite3-worker1.js");
|
||||
w.onerror = (event)=>error("worker.onerror",event);
|
||||
return w;
|
||||
},
|
||||
debug: 1 ? undefined : (...args)=>console.debug('worker debug',...args),
|
||||
onunhandled: function(ev){
|
||||
error("Unhandled worker message:",ev.data);
|
||||
},
|
||||
onready: function(){
|
||||
self.sqlite3TestModule.setStatus(null)/*hide the HTML-side is-loading spinner*/;
|
||||
runTests();
|
||||
},
|
||||
onerror: function(ev){
|
||||
error("worker1 error:",ev);
|
||||
}
|
||||
};
|
||||
const workerPromise = self.sqlite3Worker1Promiser(promiserConfig);
|
||||
delete self.sqlite3Worker1Promiser;
|
||||
|
||||
const wtest = async function(msgType, msgArgs, callback){
|
||||
if(2===arguments.length && 'function'===typeof msgArgs){
|
||||
callback = msgArgs;
|
||||
msgArgs = undefined;
|
||||
}
|
||||
const p = workerPromise({type: msgType, args:msgArgs});
|
||||
return callback ? p.then(callback).finally(testCount) : p;
|
||||
};
|
||||
|
||||
const runTests = async function(){
|
||||
const dbFilename = '/testing2.sqlite3';
|
||||
startTime = performance.now();
|
||||
|
||||
let sqConfig;
|
||||
await wtest('config-get', (ev)=>{
|
||||
const r = ev.result;
|
||||
log('sqlite3.config subset:', r);
|
||||
T.assert('boolean' === typeof r.bigIntEnabled)
|
||||
.assert('string'===typeof r.wasmfsOpfsDir)
|
||||
.assert('boolean' === typeof r.wasmfsOpfsEnabled);
|
||||
sqConfig = r;
|
||||
});
|
||||
logHtml('',
|
||||
"Sending 'open' message and waiting for its response before continuing...");
|
||||
|
||||
await wtest('open', {
|
||||
filename: dbFilename,
|
||||
simulateError: 0 /* if true, fail the 'open' */,
|
||||
}, function(ev){
|
||||
const r = ev.result;
|
||||
log("then open result",r);
|
||||
T.assert(ev.dbId === r.dbId)
|
||||
.assert(ev.messageId)
|
||||
.assert('string' === typeof r.vfs);
|
||||
promiserConfig.dbId = ev.dbId;
|
||||
}).then(runTests2);
|
||||
};
|
||||
|
||||
const runTests2 = async function(){
|
||||
const mustNotReach = ()=>toss("This is not supposed to be reached.");
|
||||
|
||||
await wtest('exec',{
|
||||
sql: ["create table t(a,b)",
|
||||
"insert into t(a,b) values(1,2),(3,4),(5,6)"
|
||||
].join(';'),
|
||||
multi: true,
|
||||
resultRows: [], columnNames: []
|
||||
}, function(ev){
|
||||
ev = ev.result;
|
||||
T.assert(0===ev.resultRows.length)
|
||||
.assert(0===ev.columnNames.length);
|
||||
});
|
||||
|
||||
await wtest('exec',{
|
||||
sql: 'select a a, b b from t order by a',
|
||||
resultRows: [], columnNames: [],
|
||||
}, function(ev){
|
||||
ev = ev.result;
|
||||
T.assert(3===ev.resultRows.length)
|
||||
.assert(1===ev.resultRows[0][0])
|
||||
.assert(6===ev.resultRows[2][1])
|
||||
.assert(2===ev.columnNames.length)
|
||||
.assert('b'===ev.columnNames[1]);
|
||||
});
|
||||
|
||||
await wtest('exec',{
|
||||
sql: 'select a a, b b from t order by a',
|
||||
resultRows: [], columnNames: [],
|
||||
rowMode: 'object'
|
||||
}, function(ev){
|
||||
ev = ev.result;
|
||||
T.assert(3===ev.resultRows.length)
|
||||
.assert(1===ev.resultRows[0].a)
|
||||
.assert(6===ev.resultRows[2].b)
|
||||
});
|
||||
|
||||
await wtest(
|
||||
'exec',
|
||||
{sql:'intentional_error'},
|
||||
mustNotReach
|
||||
).catch((e)=>{
|
||||
warn("Intentional error:",e);
|
||||
});
|
||||
|
||||
await wtest('exec',{
|
||||
sql:'select 1 union all select 3',
|
||||
resultRows: [],
|
||||
}, function(ev){
|
||||
ev = ev.result;
|
||||
T.assert(2 === ev.resultRows.length)
|
||||
.assert(1 === ev.resultRows[0][0])
|
||||
.assert(3 === ev.resultRows[1][0]);
|
||||
});
|
||||
|
||||
const resultRowTest1 = function f(ev){
|
||||
if(undefined === f.counter) f.counter = 0;
|
||||
if(null === ev.rowNumber){
|
||||
/* End of result set. */
|
||||
T.assert(undefined === ev.row)
|
||||
.assert(2===ev.columnNames.length)
|
||||
.assert('a'===ev.columnNames[0])
|
||||
.assert('B'===ev.columnNames[1]);
|
||||
}else{
|
||||
T.assert(ev.rowNumber > 0);
|
||||
++f.counter;
|
||||
}
|
||||
log("exec() result row:",ev);
|
||||
T.assert(null === ev.rowNumber || 'number' === typeof ev.row.B);
|
||||
};
|
||||
await wtest('exec',{
|
||||
sql: 'select a a, b B from t order by a limit 3',
|
||||
callback: resultRowTest1,
|
||||
rowMode: 'object'
|
||||
}, function(ev){
|
||||
T.assert(3===resultRowTest1.counter);
|
||||
resultRowTest1.counter = 0;
|
||||
});
|
||||
|
||||
const resultRowTest2 = function f(ev){
|
||||
if(null === ev.rowNumber){
|
||||
/* End of result set. */
|
||||
T.assert(undefined === ev.row)
|
||||
.assert(1===ev.columnNames.length)
|
||||
.assert('a'===ev.columnNames[0])
|
||||
}else{
|
||||
T.assert(ev.rowNumber > 0);
|
||||
f.counter = ev.rowNumber;
|
||||
}
|
||||
log("exec() result row:",ev);
|
||||
T.assert(null === ev.rowNumber || 'number' === typeof ev.row);
|
||||
};
|
||||
await wtest('exec',{
|
||||
sql: 'select a a from t limit 3',
|
||||
callback: resultRowTest2,
|
||||
rowMode: 0
|
||||
}, function(ev){
|
||||
T.assert(3===resultRowTest2.counter);
|
||||
});
|
||||
|
||||
const resultRowTest3 = function f(ev){
|
||||
if(null === ev.rowNumber){
|
||||
T.assert(3===ev.columnNames.length)
|
||||
.assert('foo'===ev.columnNames[0])
|
||||
.assert('bar'===ev.columnNames[1])
|
||||
.assert('baz'===ev.columnNames[2]);
|
||||
}else{
|
||||
f.counter = ev.rowNumber;
|
||||
T.assert('number' === typeof ev.row);
|
||||
}
|
||||
};
|
||||
await wtest('exec',{
|
||||
sql: "select 'foo' foo, a bar, 'baz' baz from t limit 2",
|
||||
callback: resultRowTest3,
|
||||
columnNames: [],
|
||||
rowMode: ':bar'
|
||||
}, function(ev){
|
||||
log("exec() result row:",ev);
|
||||
T.assert(2===resultRowTest3.counter);
|
||||
});
|
||||
|
||||
await wtest('exec',{
|
||||
multi: true,
|
||||
sql:[
|
||||
'pragma foreign_keys=0;',
|
||||
// ^^^ arbitrary query with no result columns
|
||||
'select a, b from t order by a desc; select a from t;'
|
||||
// multi-exec only honors results from the first
|
||||
// statement with result columns (regardless of whether)
|
||||
// it has any rows).
|
||||
],
|
||||
rowMode: 1,
|
||||
resultRows: []
|
||||
},function(ev){
|
||||
const rows = ev.result.resultRows;
|
||||
T.assert(3===rows.length).
|
||||
assert(6===rows[0]);
|
||||
});
|
||||
|
||||
await wtest('exec',{sql: 'delete from t where a>3'});
|
||||
|
||||
await wtest('exec',{
|
||||
sql: 'select count(a) from t',
|
||||
resultRows: []
|
||||
},function(ev){
|
||||
ev = ev.result;
|
||||
T.assert(1===ev.resultRows.length)
|
||||
.assert(2===ev.resultRows[0][0]);
|
||||
});
|
||||
|
||||
await wtest('export', function(ev){
|
||||
ev = ev.result;
|
||||
T.assert('string' === typeof ev.filename)
|
||||
.assert(ev.byteArray instanceof Uint8Array)
|
||||
.assert(ev.byteArray.length > 1024)
|
||||
.assert('application/x-sqlite3' === ev.mimetype);
|
||||
});
|
||||
|
||||
/***** close() tests must come last. *****/
|
||||
await wtest('close',{},function(ev){
|
||||
T.assert('string' === typeof ev.result.filename);
|
||||
});
|
||||
|
||||
await wtest('close', (ev)=>{
|
||||
T.assert(undefined === ev.result.filename);
|
||||
}).finally(()=>logHtml('',"That's all, folks!"));
|
||||
}/*runTests2()*/;
|
||||
|
||||
log("Init complete, but async init bits may still be running.");
|
||||
})();
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
<!doctype html>
|
||||
<html lang="en-us">
|
||||
<head>
|
||||
@@ -6,10 +7,10 @@
|
||||
<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-worker.js tests</title>
|
||||
<title>sqlite3-worker1.js tests</title>
|
||||
</head>
|
||||
<body>
|
||||
<header id='titlebar'><span>sqlite3-worker.js tests</span></header>
|
||||
<header id='titlebar'><span>sqlite3-worker1.js tests</span></header>
|
||||
<!-- emscripten bits -->
|
||||
<figure id="module-spinner">
|
||||
<div class="spinner"></div>
|
||||
@@ -28,6 +29,6 @@
|
||||
<hr>
|
||||
<div id='test-output'></div>
|
||||
<script src="common/SqliteTestUtil.js"></script>
|
||||
<script src="testing2.js"></script>
|
||||
<script src="demo-worker1.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -10,17 +10,21 @@
|
||||
|
||||
***********************************************************************
|
||||
|
||||
A basic test script for sqlite3-worker.js.
|
||||
A basic test script for sqlite3-worker1.js.
|
||||
|
||||
Note that the wrapper interface demonstrated in
|
||||
demo-worker1-promiser.js is much easier to use from client code, as it
|
||||
lacks the message-passing acrobatics demonstrated in this file.
|
||||
*/
|
||||
'use strict';
|
||||
(function(){
|
||||
const T = self.SqliteTestUtil;
|
||||
const SW = new Worker("api/sqlite3-worker.js");
|
||||
const SW = new Worker("jswasm/sqlite3-worker1.js");
|
||||
const DbState = {
|
||||
id: undefined
|
||||
};
|
||||
const eOutput = document.querySelector('#test-output');
|
||||
const log = console.log.bind(console)
|
||||
const log = console.log.bind(console);
|
||||
const logHtml = function(cssClass,...args){
|
||||
log.apply(this, args);
|
||||
const ln = document.createElement('div');
|
||||
@@ -31,24 +35,13 @@
|
||||
const warn = console.warn.bind(console);
|
||||
const error = console.error.bind(console);
|
||||
const toss = (...args)=>{throw new Error(args.join(' '))};
|
||||
/** Posts a worker message as {type:type, data:data}. */
|
||||
const wMsg = function(type,data){
|
||||
log("Posting message to worker dbId="+(DbState.id||'default')+':',data);
|
||||
SW.postMessage({
|
||||
type,
|
||||
dbId: DbState.id,
|
||||
data,
|
||||
departureTime: performance.now()
|
||||
});
|
||||
return SW;
|
||||
};
|
||||
|
||||
SW.onerror = function(event){
|
||||
error("onerror",event);
|
||||
};
|
||||
|
||||
let startTime;
|
||||
|
||||
|
||||
/**
|
||||
A queue for callbacks which are to be run in response to async
|
||||
DB commands. See the notes in runTests() for why we need
|
||||
@@ -74,28 +67,37 @@
|
||||
logHtml("","Total test count:",T.counter+". Total time =",(performance.now() - startTime),"ms");
|
||||
};
|
||||
|
||||
const logEventResult = function(evd){
|
||||
const logEventResult = function(ev){
|
||||
const evd = ev.result;
|
||||
logHtml(evd.errorClass ? 'error' : '',
|
||||
"runOneTest",evd.messageId,"Worker time =",
|
||||
(evd.workerRespondTime - evd.workerReceivedTime),"ms.",
|
||||
"runOneTest",ev.messageId,"Worker time =",
|
||||
(ev.workerRespondTime - ev.workerReceivedTime),"ms.",
|
||||
"Round-trip event time =",
|
||||
(performance.now() - evd.departureTime),"ms.",
|
||||
(evd.errorClass ? evd.message : "")
|
||||
(performance.now() - ev.departureTime),"ms.",
|
||||
(evd.errorClass ? ev.message : "")//, JSON.stringify(evd)
|
||||
);
|
||||
};
|
||||
|
||||
const runOneTest = function(eventType, eventData, callback){
|
||||
T.assert(eventData && 'object'===typeof eventData);
|
||||
const runOneTest = function(eventType, eventArgs, callback){
|
||||
T.assert(eventArgs && 'object'===typeof eventArgs);
|
||||
/* ^^^ that is for the testing and messageId-related code, not
|
||||
a hard requirement of all of the Worker-exposed APIs. */
|
||||
eventData.messageId = MsgHandlerQueue.push(eventType,function(ev){
|
||||
logEventResult(ev.data);
|
||||
const messageId = MsgHandlerQueue.push(eventType,function(ev){
|
||||
logEventResult(ev);
|
||||
if(callback instanceof Function){
|
||||
callback(ev);
|
||||
testCount();
|
||||
}
|
||||
});
|
||||
wMsg(eventType, eventData);
|
||||
const msg = {
|
||||
type: eventType,
|
||||
args: eventArgs,
|
||||
dbId: DbState.id,
|
||||
messageId: messageId,
|
||||
departureTime: performance.now()
|
||||
};
|
||||
log("Posting",eventType,"message to worker dbId="+(DbState.id||'default')+':',msg);
|
||||
SW.postMessage(msg);
|
||||
};
|
||||
|
||||
/** Methods which map directly to onmessage() event.type keys.
|
||||
@@ -103,23 +105,31 @@
|
||||
const dbMsgHandler = {
|
||||
open: function(ev){
|
||||
DbState.id = ev.dbId;
|
||||
log("open result",ev.data);
|
||||
log("open result",ev);
|
||||
},
|
||||
exec: function(ev){
|
||||
log("exec result",ev.data);
|
||||
log("exec result",ev);
|
||||
},
|
||||
export: function(ev){
|
||||
log("export result",ev.data);
|
||||
log("export result",ev);
|
||||
},
|
||||
error: function(ev){
|
||||
error("ERROR from the worker:",ev.data);
|
||||
logEventResult(ev.data);
|
||||
error("ERROR from the worker:",ev);
|
||||
logEventResult(ev);
|
||||
},
|
||||
resultRowTest1: function f(ev){
|
||||
if(undefined === f.counter) f.counter = 0;
|
||||
if(ev.data) ++f.counter;
|
||||
//log("exec() result row:",ev.data);
|
||||
T.assert(null===ev.data || 'number' === typeof ev.data.b);
|
||||
if(null === ev.rowNumber){
|
||||
/* End of result set. */
|
||||
T.assert(undefined === ev.row)
|
||||
.assert(Array.isArray(ev.columnNames))
|
||||
.assert(ev.columnNames.length);
|
||||
}else{
|
||||
T.assert(ev.rowNumber > 0);
|
||||
++f.counter;
|
||||
}
|
||||
//log("exec() result row:",ev);
|
||||
T.assert(null === ev.rowNumber || 'number' === typeof ev.row.b);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -143,33 +153,33 @@
|
||||
throw new Error("This is not supposed to be reached.");
|
||||
};
|
||||
runOneTest('exec',{
|
||||
sql: ["create table t(a,b)",
|
||||
sql: ["create table t(a,b);",
|
||||
"insert into t(a,b) values(1,2),(3,4),(5,6)"
|
||||
].join(';'),
|
||||
multi: true,
|
||||
],
|
||||
resultRows: [], columnNames: []
|
||||
}, function(ev){
|
||||
ev = ev.data;
|
||||
ev = ev.result;
|
||||
T.assert(0===ev.resultRows.length)
|
||||
.assert(0===ev.columnNames.length);
|
||||
});
|
||||
runOneTest('exec',{
|
||||
sql: 'select a a, b b from t order by a',
|
||||
resultRows: [], columnNames: [],
|
||||
resultRows: [], columnNames: [], saveSql:[]
|
||||
}, function(ev){
|
||||
ev = ev.data;
|
||||
ev = ev.result;
|
||||
T.assert(3===ev.resultRows.length)
|
||||
.assert(1===ev.resultRows[0][0])
|
||||
.assert(6===ev.resultRows[2][1])
|
||||
.assert(2===ev.columnNames.length)
|
||||
.assert('b'===ev.columnNames[1]);
|
||||
});
|
||||
//if(1){ error("Returning prematurely for testing."); return; }
|
||||
runOneTest('exec',{
|
||||
sql: 'select a a, b b from t order by a',
|
||||
resultRows: [], columnNames: [],
|
||||
rowMode: 'object'
|
||||
}, function(ev){
|
||||
ev = ev.data;
|
||||
ev = ev.result;
|
||||
T.assert(3===ev.resultRows.length)
|
||||
.assert(1===ev.resultRows[0].a)
|
||||
.assert(6===ev.resultRows[2].b)
|
||||
@@ -181,7 +191,7 @@
|
||||
resultRows: [],
|
||||
//rowMode: 'array', // array is the default in the Worker interface
|
||||
}, function(ev){
|
||||
ev = ev.data;
|
||||
ev = ev.result;
|
||||
T.assert(1 === ev.resultRows.length)
|
||||
.assert(1 === ev.resultRows[0][0]);
|
||||
});
|
||||
@@ -194,19 +204,19 @@
|
||||
dbMsgHandler.resultRowTest1.counter = 0;
|
||||
});
|
||||
runOneTest('exec',{
|
||||
multi: true,
|
||||
sql:[
|
||||
'pragma foreign_keys=0;',
|
||||
"pragma foreign_keys=0;",
|
||||
// ^^^ arbitrary query with no result columns
|
||||
'select a, b from t order by a desc; select a from t;'
|
||||
// multi-exec only honors results from the first
|
||||
"select a, b from t order by a desc;",
|
||||
"select a from t;"
|
||||
// multi-statement exec only honors results from the first
|
||||
// statement with result columns (regardless of whether)
|
||||
// it has any rows).
|
||||
],
|
||||
rowMode: 1,
|
||||
resultRows: []
|
||||
},function(ev){
|
||||
const rows = ev.data.resultRows;
|
||||
const rows = ev.result.resultRows;
|
||||
T.assert(3===rows.length).
|
||||
assert(6===rows[0]);
|
||||
});
|
||||
@@ -215,29 +225,29 @@
|
||||
sql: 'select count(a) from t',
|
||||
resultRows: []
|
||||
},function(ev){
|
||||
ev = ev.data;
|
||||
ev = ev.result;
|
||||
T.assert(1===ev.resultRows.length)
|
||||
.assert(2===ev.resultRows[0][0]);
|
||||
});
|
||||
if(0){
|
||||
// export requires reimpl. for portability reasons.
|
||||
runOneTest('export',{}, function(ev){
|
||||
ev = ev.data;
|
||||
T.assert('string' === typeof ev.filename)
|
||||
.assert(ev.buffer instanceof Uint8Array)
|
||||
.assert(ev.buffer.length > 1024)
|
||||
.assert('application/x-sqlite3' === ev.mimetype);
|
||||
});
|
||||
}
|
||||
runOneTest('export',{}, function(ev){
|
||||
ev = ev.result;
|
||||
log("export result:",ev);
|
||||
T.assert('string' === typeof ev.filename)
|
||||
.assert(ev.byteArray instanceof Uint8Array)
|
||||
.assert(ev.byteArray.length > 1024)
|
||||
.assert('application/x-sqlite3' === ev.mimetype);
|
||||
});
|
||||
/***** close() tests must come last. *****/
|
||||
runOneTest('close',{unlink:true},function(ev){
|
||||
ev = ev.data;
|
||||
ev = ev.result;
|
||||
T.assert('string' === typeof ev.filename);
|
||||
});
|
||||
runOneTest('close',{unlink:true},function(ev){
|
||||
ev = ev.data;
|
||||
ev = ev.result;
|
||||
T.assert(undefined === ev.filename);
|
||||
logHtml('warning',"This is the final test.");
|
||||
});
|
||||
logHtml('warning',"Finished posting tests. Waiting on async results.");
|
||||
};
|
||||
|
||||
const runTests = function(){
|
||||
@@ -261,16 +271,8 @@
|
||||
will fail and we have no way of cancelling them once they've
|
||||
been posted to the worker.
|
||||
|
||||
We currently do (2) because (A) it's certainly the most
|
||||
client-friendly thing to do and (B) it seems likely that most
|
||||
apps using this API will only have a single db to work with so
|
||||
won't need to juggle multiple DB ids. If we revert to (1) then
|
||||
the following call to runTests2() needs to be moved into the
|
||||
callback function of the runOneTest() check for the 'open'
|
||||
command. Note, also, that using approach (2) does not keep the
|
||||
user from instead using approach (1), noting that doing so
|
||||
requires explicit handling of the 'open' message to account for
|
||||
it.
|
||||
Which approach we use below depends on the boolean value of
|
||||
waitForOpen.
|
||||
*/
|
||||
const waitForOpen = 1,
|
||||
simulateOpenError = 0 /* if true, the remaining tests will
|
||||
@@ -284,11 +286,12 @@
|
||||
filename:'testing2.sqlite3',
|
||||
simulateError: simulateOpenError
|
||||
}, function(ev){
|
||||
//log("open result",ev);
|
||||
T.assert('testing2.sqlite3'===ev.data.filename)
|
||||
.assert(ev.data.dbId)
|
||||
.assert(ev.data.messageId);
|
||||
DbState.id = ev.data.dbId;
|
||||
log("open result",ev);
|
||||
T.assert('testing2.sqlite3'===ev.result.filename)
|
||||
.assert(ev.dbId)
|
||||
.assert(ev.messageId)
|
||||
.assert('string' === typeof ev.result.vfs);
|
||||
DbState.id = ev.dbId;
|
||||
if(waitForOpen) setTimeout(runTests2, 0);
|
||||
});
|
||||
if(!waitForOpen) runTests2();
|
||||
@@ -301,7 +304,7 @@
|
||||
}
|
||||
ev = ev.data/*expecting a nested object*/;
|
||||
//log("main window onmessage:",ev);
|
||||
if(ev.data && ev.data.messageId){
|
||||
if(ev.result && ev.messageId){
|
||||
/* We're expecting a queued-up callback handler. */
|
||||
const f = MsgHandlerQueue.shift();
|
||||
if('error'===ev.type){
|
||||
@@ -314,8 +317,8 @@
|
||||
}
|
||||
switch(ev.type){
|
||||
case 'sqlite3-api':
|
||||
switch(ev.data){
|
||||
case 'worker-ready':
|
||||
switch(ev.result){
|
||||
case 'worker1-ready':
|
||||
log("Message:",ev);
|
||||
self.sqlite3TestModule.setStatus(null);
|
||||
runTests();
|
||||
@@ -337,4 +340,6 @@
|
||||
}
|
||||
};
|
||||
log("Init complete, but async init bits may still be running.");
|
||||
log("Installing Worker into global scope SW for dev purposes.");
|
||||
self.SW = SW;
|
||||
})();
|
||||
@@ -0,0 +1,101 @@
|
||||
#!/do/not/make
|
||||
#^^^ help emacs select edit mode
|
||||
#
|
||||
# Intended to include'd by ./GNUmakefile.
|
||||
#
|
||||
# 'make dist' rules for creating a distribution archive of the WASM/JS
|
||||
# pieces, noting that we only build a dist of the built files, not the
|
||||
# numerous pieces required to build them.
|
||||
#######################################################################
|
||||
MAKEFILE.dist := $(lastword $(MAKEFILE_LIST))
|
||||
|
||||
########################################################################
|
||||
# Chicken/egg situation: we need $(bin.version-info) to get the version
|
||||
# info for the archive name, but that binary may not yet be built, and
|
||||
# won't be built until we expand the dependencies. We have to use a
|
||||
# temporary name for the archive.
|
||||
dist-name = sqlite-wasm-TEMP
|
||||
#ifeq (0,1)
|
||||
# $(info WARNING *******************************************************************)
|
||||
# $(info ** Be sure to create the desired build configuration before creating the)
|
||||
# $(info ** distribution archive. Use one of the following targets to do so:)
|
||||
# $(info **)
|
||||
# $(info ** o2: builds with -O2, resulting in the fastest builds)
|
||||
# $(info ** oz: builds with -Oz, resulting in the smallest builds)
|
||||
# $(info /WARNING *******************************************************************)
|
||||
#endif
|
||||
|
||||
########################################################################
|
||||
# dist.build must be the name of a target which triggers the
|
||||
# build of the files to be packed into the dist archive. The
|
||||
# intention is that it be one of (o0, o1, o2, o3, os, oz), each of
|
||||
# which uses like-named -Ox optimization level flags. The o2 target
|
||||
# provides the best overall runtime speeds. The oz target provides
|
||||
# slightly slower speeds (roughly 10%) with significantly smaller WASM
|
||||
# file sizes. Note that -O2 (the o2 target) results in faster binaries
|
||||
# than both -O3 and -Os (the o3 and os targets) in all tests run to
|
||||
# date.
|
||||
dist.build ?= oz
|
||||
|
||||
dist-dir.top := $(dist-name)
|
||||
dist-dir.jswasm := $(dist-dir.top)/$(notdir $(dir.dout))
|
||||
dist-dir.common := $(dist-dir.top)/common
|
||||
dist.top.extras := \
|
||||
demo-123.html demo-123-worker.html demo-123.js \
|
||||
tester1.html tester1-worker.html tester1.js \
|
||||
demo-jsstorage.html demo-jsstorage.js \
|
||||
demo-worker1.html demo-worker1.js \
|
||||
demo-worker1-promiser.html demo-worker1-promiser.js
|
||||
dist.jswasm.extras := $(sqlite3-api.ext.jses) $(sqlite3.wasm)
|
||||
dist.common.extras := \
|
||||
$(wildcard $(dir.common)/*.css) \
|
||||
$(dir.common)/SqliteTestUtil.js
|
||||
|
||||
.PHONY: dist
|
||||
########################################################################
|
||||
# dist: create the end-user deliverable archive.
|
||||
#
|
||||
# Maintenance reminder: because dist depends on $(dist.build), and
|
||||
# $(dist.build) will depend on clean, having any deps on
|
||||
# $(dist-archive) which themselves may be cleaned up by the clean
|
||||
# target will lead to grief in parallel builds (-j #). Thus
|
||||
# $(dist-target)'s deps must be trimmed to non-generated files or
|
||||
# files which are _not_ cleaned up by the clean target.
|
||||
#
|
||||
# Note that we require $(bin.version-info) in order to figure out the
|
||||
# dist file's name, so cannot (without a recursive make) have the
|
||||
# target name equal to the archive name.
|
||||
dist: \
|
||||
$(bin.stripccomments) $(bin.version-info) \
|
||||
$(dist.build) \
|
||||
$(MAKEFILE) $(MAKEFILE.dist)
|
||||
@echo "Making end-user deliverables..."
|
||||
@rm -fr $(dist-dir.top)
|
||||
@mkdir -p $(dist-dir.jswasm) $(dist-dir.common)
|
||||
@cp -p $(dist.top.extras) $(dist-dir.top)
|
||||
@cp -p README-dist.txt $(dist-dir.top)/README.txt
|
||||
@cp -p index-dist.html $(dist-dir.top)/index.html
|
||||
@cp -p $(dist.jswasm.extras) $(dist-dir.jswasm)
|
||||
@$(bin.stripccomments) -k -k < $(sqlite3.js) \
|
||||
> $(dist-dir.jswasm)/$(notdir $(sqlite3.js))
|
||||
@cp -p $(dist.common.extras) $(dist-dir.common)
|
||||
@set -e; \
|
||||
vnum=$$($(bin.version-info) --download-version); \
|
||||
vdir=sqlite-wasm-$$vnum; \
|
||||
arczip=$$vdir.zip; \
|
||||
echo "Making $$arczip ..."; \
|
||||
rm -fr $$arczip $$vdir; \
|
||||
mv $(dist-dir.top) $$vdir; \
|
||||
zip -qr $$arczip $$vdir; \
|
||||
rm -fr $$vdir; \
|
||||
ls -la $$arczip; \
|
||||
set +e; \
|
||||
unzip -lv $$arczip || echo "Missing unzip app? Not fatal."
|
||||
|
||||
# We need a separate `clean` rule to account for weirdness in
|
||||
# a sub-make, where we get a copy of the $(dist-name) dir
|
||||
# copied into the new $(dist-name) dir.
|
||||
.PHONY: dist-clean
|
||||
clean: dist-clean
|
||||
dist-clean:
|
||||
rm -fr $(dist-name) $(wildcard sqlite-wasm-*.zip)
|
||||
@@ -0,0 +1,194 @@
|
||||
#!/do/not/make
|
||||
#^^^ help emacs select edit mode
|
||||
#
|
||||
# Intended to include'd by ./GNUmakefile.
|
||||
#######################################################################
|
||||
MAKEFILE.fiddle := $(lastword $(MAKEFILE_LIST))
|
||||
|
||||
########################################################################
|
||||
# shell.c and its build flags...
|
||||
make-np-0 := make -C $(dir.top) -n -p
|
||||
make-np-1 := sed -e 's/(TOP)/(dir.top)/g'
|
||||
$(eval $(shell $(make-np-0) | grep -e '^SHELL_OPT ' | $(make-np-1)))
|
||||
$(eval $(shell $(make-np-0) | grep -e '^SHELL_SRC ' | $(make-np-1)))
|
||||
# ^^^ can't do that in 1 invocation b/c newlines get stripped
|
||||
ifeq (,$(SHELL_OPT))
|
||||
$(error Could not parse SHELL_OPT from $(dir.top)/Makefile.)
|
||||
endif
|
||||
ifeq (,$(SHELL_SRC))
|
||||
$(error Could not parse SHELL_SRC from $(dir.top)/Makefile.)
|
||||
endif
|
||||
$(dir.top)/shell.c: $(SHELL_SRC) $(dir.top)/tool/mkshellc.tcl
|
||||
$(MAKE) -C $(dir.top) shell.c
|
||||
# /shell.c
|
||||
########################################################################
|
||||
|
||||
EXPORTED_FUNCTIONS.fiddle := $(dir.tmp)/EXPORTED_FUNCTIONS.fiddle
|
||||
fiddle.emcc-flags = \
|
||||
$(emcc.cflags) $(emcc_opt_full) \
|
||||
--minify 0 \
|
||||
-sALLOW_TABLE_GROWTH \
|
||||
-sABORTING_MALLOC \
|
||||
-sSTRICT_JS \
|
||||
-sENVIRONMENT=web,worker \
|
||||
-sMODULARIZE \
|
||||
-sDYNAMIC_EXECUTION=0 \
|
||||
-sWASM_BIGINT=$(emcc.WASM_BIGINT) \
|
||||
-sEXPORT_NAME=$(sqlite3.js.init-func) \
|
||||
-Wno-limited-postlink-optimizations \
|
||||
$(sqlite3.js.flags.--post-js) \
|
||||
$(emcc.exportedRuntimeMethods) \
|
||||
-sEXPORTED_FUNCTIONS=@$(abspath $(EXPORTED_FUNCTIONS.fiddle)) \
|
||||
$(SQLITE_OPT) $(SHELL_OPT) \
|
||||
-DSQLITE_SHELL_FIDDLE
|
||||
# -D_POSIX_C_SOURCE is needed for strdup() with emcc
|
||||
|
||||
fiddle.EXPORTED_FUNCTIONS.in := \
|
||||
EXPORTED_FUNCTIONS.fiddle.in \
|
||||
$(EXPORTED_FUNCTIONS.api)
|
||||
|
||||
$(EXPORTED_FUNCTIONS.fiddle): $(fiddle.EXPORTED_FUNCTIONS.in) $(MAKEFILE.fiddle)
|
||||
sort -u $(fiddle.EXPORTED_FUNCTIONS.in) > $@
|
||||
|
||||
fiddle-module.js := $(dir.fiddle)/fiddle-module.js
|
||||
fiddle-module.wasm := $(subst .js,.wasm,$(fiddle-module.js))
|
||||
fiddle.cses := $(dir.top)/shell.c $(sqlite3-wasm.c)
|
||||
|
||||
fiddle.SOAP.js := $(dir.fiddle)/$(notdir $(SOAP.js))
|
||||
$(fiddle.SOAP.js): $(SOAP.js)
|
||||
cp $< $@
|
||||
|
||||
$(eval $(call call-make-pre-js,fiddle-module))
|
||||
$(fiddle-module.js): $(MAKEFILE) $(MAKEFILE.fiddle) \
|
||||
$(EXPORTED_FUNCTIONS.fiddle) \
|
||||
$(fiddle.cses) $(pre-post-fiddle-module.deps) $(fiddle.SOAP.js)
|
||||
$(emcc.bin) -o $@ $(fiddle.emcc-flags) \
|
||||
$(pre-post-common.flags) $(pre-post-fiddle-module.flags) \
|
||||
$(fiddle.cses)
|
||||
$(maybe-wasm-strip) $(fiddle-module.wasm)
|
||||
gzip < $@ > $@.gz
|
||||
gzip < $(fiddle-module.wasm) > $(fiddle-module.wasm).gz
|
||||
|
||||
$(dir.fiddle)/fiddle.js.gz: $(dir.fiddle)/fiddle.js
|
||||
gzip < $< > $@
|
||||
|
||||
clean: clean-fiddle
|
||||
clean-fiddle:
|
||||
rm -f $(fiddle-module.js) $(fiddle-module.js).gz \
|
||||
$(fiddle-module.wasm) $(fiddle-module.wasm).gz \
|
||||
$(dir.fiddle)/$(SOAP.js) \
|
||||
$(dir.fiddle)/fiddle-module.worker.js \
|
||||
EXPORTED_FUNCTIONS.fiddle
|
||||
.PHONY: fiddle
|
||||
fiddle: $(fiddle-module.js) $(dir.fiddle)/fiddle.js.gz
|
||||
all: fiddle
|
||||
|
||||
########################################################################
|
||||
# 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 = wh:www/wh/sqlite3/.
|
||||
else ifneq (,$(wildcard /home/drh))
|
||||
#fiddle_remote = if appropriate, add that user@host:/path here
|
||||
endif
|
||||
endif
|
||||
push-fiddle: fiddle
|
||||
@if [ x = "x$(fiddle_remote)" ]; then \
|
||||
echo "fiddle_remote must be a [user@]HOST:/path for rsync"; \
|
||||
exit 1; \
|
||||
fi
|
||||
rsync -va fiddle/ $(fiddle_remote)
|
||||
# end fiddle remote push
|
||||
########################################################################
|
||||
|
||||
|
||||
########################################################################
|
||||
# Explanation of the emcc build flags follows. Full docs for these can
|
||||
# be found at:
|
||||
#
|
||||
# https://github.com/emscripten-core/emscripten/blob/main/src/settings.js
|
||||
#
|
||||
# -sENVIRONMENT=web: elides bootstrap code related to non-web JS
|
||||
# environments like node.js. Removing this makes the output a tiny
|
||||
# tick larger but hypothetically makes it more portable to
|
||||
# non-browser JS environments.
|
||||
#
|
||||
# -sMODULARIZE: changes how the generated code is structured to avoid
|
||||
# declaring a global Module object and instead installing a function
|
||||
# which loads and initializes the module. The function is named...
|
||||
#
|
||||
# -sEXPORT_NAME=jsFunctionName (see -sMODULARIZE)
|
||||
#
|
||||
# -sEXPORTED_RUNTIME_METHODS=@/absolute/path/to/file: a file
|
||||
# containing a list of emscripten-supplied APIs, one per line, which
|
||||
# must be exported into the generated JS. Must be an absolute path!
|
||||
#
|
||||
# -sEXPORTED_FUNCTIONS=@/absolute/path/to/file: a file containing a
|
||||
# list of C functions, one per line, which must be exported via wasm
|
||||
# so they're visible to JS. C symbols names in that file must all
|
||||
# start with an underscore for reasons known only to the emcc
|
||||
# developers. e.g., _sqlite3_open_v2 and _sqlite3_finalize. Must be
|
||||
# an absolute path!
|
||||
#
|
||||
# -sSTRICT_JS ensures that the emitted JS code includes the 'use
|
||||
# strict' option. Note that -sSTRICT is more broadly-scoped and
|
||||
# results in build errors.
|
||||
#
|
||||
# -sALLOW_TABLE_GROWTH is required for (at a minimum) the UDF-binding
|
||||
# feature. Without it, JS functions cannot be made to proxy C-side
|
||||
# callbacks.
|
||||
#
|
||||
# -sABORTING_MALLOC causes the JS-bound _malloc() to abort rather than
|
||||
# return 0 on OOM. If set to 0 then all code which uses _malloc()
|
||||
# must, just like in C, check the result before using it, else
|
||||
# they're likely to corrupt the JS/WASM heap by writing to its
|
||||
# address of 0. It is, as of this writing, enabled in Emscripten by
|
||||
# default but we enable it explicitly in case that default changes.
|
||||
#
|
||||
# -sDYNAMIC_EXECUTION=0 disables eval() and the Function constructor.
|
||||
# If the build runs without these, it's preferable to use this flag
|
||||
# because certain execution environments disallow those constructs.
|
||||
# This flag is not strictly necessary, however.
|
||||
#
|
||||
# -sWASM_BIGINT is UNTESTED but "should" allow the int64-using C APIs
|
||||
# to work with JS/wasm, insofar as the JS environment supports the
|
||||
# BigInt type. That support requires an extremely recent browser:
|
||||
# Safari didn't get that support until late 2020.
|
||||
#
|
||||
# --no-entry: for compiling library code with no main(). If this is
|
||||
# not supplied and the code has a main(), it is called as part of the
|
||||
# module init process. Note that main() is #if'd out of shell.c
|
||||
# (renamed) when building in wasm mode.
|
||||
#
|
||||
# --pre-js/--post-js=FILE relative or absolute paths to JS files to
|
||||
# prepend/append to the emcc-generated bootstrapping JS. It's
|
||||
# easier/faster to develop with separate JS files (reduces rebuilding
|
||||
# requirements) but certain configurations, namely -sMODULARIZE, may
|
||||
# require using at least a --pre-js file. They can be used
|
||||
# individually and need not be paired.
|
||||
#
|
||||
# -O0..-O3 and -Oz: optimization levels affect not only C-style
|
||||
# optimization but whether or not the resulting generated JS code
|
||||
# gets minified. -O0 compiles _much_ more quickly than -O3 or -Oz,
|
||||
# and doesn't minimize any JS code, so is recommended for
|
||||
# development. -O3 or -Oz are recommended for deployment, but
|
||||
# primarily because -Oz will shrink the wasm file notably. JS-side
|
||||
# minification makes little difference in terms of overall
|
||||
# distributable size.
|
||||
#
|
||||
# --minify 0: disables minification of the generated JS code,
|
||||
# regardless of optimization level. Minification of the JS has
|
||||
# minimal overall effect in the larger scheme of things and results
|
||||
# in JS files which can neither be edited nor viewed as text files in
|
||||
# Fossil (which flags them as binary because of their extreme line
|
||||
# lengths). Interestingly, whether or not the comments in the
|
||||
# generated JS file get stripped is unaffected by this setting and
|
||||
# depends entirely on the optimization level. Higher optimization
|
||||
# levels reduce the size of the JS considerably even without
|
||||
# minification.
|
||||
#
|
||||
########################################################################
|
||||
+277
-199
@@ -89,213 +89,291 @@
|
||||
*/
|
||||
"use strict";
|
||||
(function(){
|
||||
/**
|
||||
Posts a message in the form {type,data} unless passed more than 2
|
||||
args, in which case it posts {type, data:[arg1...argN]}.
|
||||
*/
|
||||
const wMsg = function(type,data){
|
||||
postMessage({
|
||||
type,
|
||||
data: arguments.length<3
|
||||
? data
|
||||
: Array.prototype.slice.call(arguments,1)
|
||||
});
|
||||
};
|
||||
|
||||
const stdout = function(){wMsg('stdout', Array.prototype.slice.call(arguments));};
|
||||
const stderr = function(){wMsg('stderr', Array.prototype.slice.call(arguments));};
|
||||
|
||||
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. */
|
||||
fiddleModule.isDead = true;
|
||||
stderr("FATAL ERROR:", err.message);
|
||||
stderr("Restarting the app requires reloading the page.");
|
||||
wMsg('error', err);
|
||||
}
|
||||
console.error(err);
|
||||
fiddleModule.setStatus('Exception thrown, see JavaScript console: '+err);
|
||||
};
|
||||
|
||||
const Sqlite3Shell = {
|
||||
/** Returns the name of the currently-opened db. */
|
||||
dbFilename: function f(){
|
||||
if(!f._) f._ = fiddleModule.cwrap('fiddle_db_filename', "string", ['string']);
|
||||
return f._();
|
||||
},
|
||||
/**
|
||||
Runs the given text through the shell as if it had been typed
|
||||
in by a user. Fires a working/start event before it starts and
|
||||
working/end event when it finishes.
|
||||
*/
|
||||
exec: function f(sql){
|
||||
if(!f._) f._ = fiddleModule.cwrap('fiddle_exec', null, ['string']);
|
||||
if(fiddleModule.isDead){
|
||||
stderr("shell module has exit()ed. Cannot run SQL.");
|
||||
return;
|
||||
}
|
||||
wMsg('working','start');
|
||||
try {
|
||||
if(f._running){
|
||||
stderr('Cannot run multiple commands concurrently.');
|
||||
}else{
|
||||
f._running = true;
|
||||
f._(sql);
|
||||
}
|
||||
} finally {
|
||||
delete f._running;
|
||||
wMsg('working','end');
|
||||
}
|
||||
},
|
||||
resetDb: function f(){
|
||||
if(!f._) f._ = fiddleModule.cwrap('fiddle_reset_db', null);
|
||||
stdout("Resetting database.");
|
||||
f._();
|
||||
stdout("Reset",this.dbFilename());
|
||||
},
|
||||
/* Interrupt can't work: this Worker is tied up working, so won't get the
|
||||
interrupt event which would be needed to perform the interrupt. */
|
||||
interrupt: function f(){
|
||||
if(!f._) f._ = fiddleModule.cwrap('fiddle_interrupt', null);
|
||||
stdout("Requesting interrupt.");
|
||||
f._();
|
||||
}
|
||||
};
|
||||
|
||||
self.onmessage = function f(ev){
|
||||
ev = ev.data;
|
||||
if(!f.cache){
|
||||
f.cache = {
|
||||
prevFilename: null
|
||||
};
|
||||
}
|
||||
//console.debug("worker: onmessage.data",ev);
|
||||
switch(ev.type){
|
||||
case 'shellExec': Sqlite3Shell.exec(ev.data); return;
|
||||
case 'db-reset': Sqlite3Shell.resetDb(); return;
|
||||
case 'interrupt': Sqlite3Shell.interrupt(); return;
|
||||
/** Triggers the export of the current db. Fires an
|
||||
event in the form:
|
||||
|
||||
{type:'db-export',
|
||||
data:{
|
||||
filename: name of db,
|
||||
buffer: contents of the db file (Uint8Array),
|
||||
error: on error, a message string and no buffer property.
|
||||
}
|
||||
}
|
||||
*/
|
||||
case 'db-export': {
|
||||
const fn = Sqlite3Shell.dbFilename();
|
||||
stdout("Exporting",fn+".");
|
||||
const fn2 = fn ? fn.split(/[/\\]/).pop() : null;
|
||||
try{
|
||||
if(!fn2) throw new Error("DB appears to be closed.");
|
||||
wMsg('db-export',{
|
||||
filename: fn2,
|
||||
buffer: fiddleModule.FS.readFile(fn, {encoding:"binary"})
|
||||
});
|
||||
}catch(e){
|
||||
/* Post a failure message so that UI elements disabled
|
||||
during the export can be re-enabled. */
|
||||
wMsg('db-export',{
|
||||
filename: fn,
|
||||
error: e.message
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
case 'open': {
|
||||
/* Expects: {
|
||||
buffer: ArrayBuffer | Uint8Array,
|
||||
filename: for logging/informational purposes only
|
||||
} */
|
||||
const opt = ev.data;
|
||||
let buffer = opt.buffer;
|
||||
if(buffer instanceof Uint8Array){
|
||||
}else if(buffer instanceof ArrayBuffer){
|
||||
buffer = new Uint8Array(buffer);
|
||||
}else{
|
||||
stderr("'open' expects {buffer:Uint8Array} containing an uploaded db.");
|
||||
return;
|
||||
}
|
||||
const fn = (
|
||||
opt.filename
|
||||
? opt.filename.split(/[/\\]/).pop().replace('"','_')
|
||||
: ("db-"+((Math.random() * 10000000) | 0)+
|
||||
"-"+((Math.random() * 10000000) | 0)+".sqlite3")
|
||||
);
|
||||
/* We cannot delete the existing db file until the new one
|
||||
is installed, which means that we risk overflowing our
|
||||
quota (if any) by having both the previous and current
|
||||
db briefly installed in the virtual filesystem. */
|
||||
fiddleModule.FS.createDataFile("/", fn, buffer, true, true);
|
||||
const oldName = Sqlite3Shell.dbFilename();
|
||||
Sqlite3Shell.exec('.open "/'+fn+'"');
|
||||
if(oldName && oldName !== fn){
|
||||
try{fiddleModule.FS.unlink(oldName);}
|
||||
catch(e){/*ignored*/}
|
||||
}
|
||||
stdout("Replaced DB with",fn+".");
|
||||
return;
|
||||
}
|
||||
/**
|
||||
Posts a message in the form {type,data}. If passed more than 2
|
||||
args, the 3rd must be an array of "transferable" values to pass
|
||||
as the 2nd argument to postMessage(). */
|
||||
const wMsg =
|
||||
(type,data,transferables)=>{
|
||||
postMessage({type, data}, transferables || []);
|
||||
};
|
||||
console.warn("Unknown fiddle-worker message type:",ev);
|
||||
};
|
||||
|
||||
const stdout = (...args)=>wMsg('stdout', args);
|
||||
const stderr = (...args)=>wMsg('stderr', args);
|
||||
const toss = (...args)=>{
|
||||
throw new Error(args.join(' '));
|
||||
};
|
||||
const fixmeOPFS = "(FIXME: won't work with OPFS-over-sqlite3_vfs.)";
|
||||
let sqlite3 /* gets assigned when the wasm module is loaded */;
|
||||
|
||||
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. */
|
||||
fiddleModule.isDead = true;
|
||||
stderr("FATAL ERROR:", err.message);
|
||||
stderr("Restarting the app requires reloading the page.");
|
||||
wMsg('error', err);
|
||||
}
|
||||
console.error(err);
|
||||
fiddleModule.setStatus('Exception thrown, see JavaScript console: '+err);
|
||||
};
|
||||
|
||||
const Sqlite3Shell = {
|
||||
/** Returns the name of the currently-opened db. */
|
||||
dbFilename: function f(){
|
||||
if(!f._) f._ = sqlite3.wasm.xWrap('fiddle_db_filename', "string", ['string']);
|
||||
return f._(0);
|
||||
},
|
||||
dbHandle: function f(){
|
||||
if(!f._) f._ = sqlite3.wasm.xWrap("fiddle_db_handle", "sqlite3*");
|
||||
return f._();
|
||||
},
|
||||
dbIsOpfs: function f(){
|
||||
return sqlite3.opfs && sqlite3.capi.sqlite3_js_db_uses_vfs(
|
||||
this.dbHandle(), "opfs"
|
||||
);
|
||||
},
|
||||
runMain: function f(){
|
||||
if(f.argv) return 0===f.argv.rc;
|
||||
const dbName = "/fiddle.sqlite3";
|
||||
f.argv = [
|
||||
'sqlite3-fiddle.wasm',
|
||||
'-bail', '-safe',
|
||||
dbName
|
||||
/* Reminder: because of how we run fiddle, we have to ensure
|
||||
that any argv strings passed to its main() are valid until
|
||||
the wasm environment shuts down. */
|
||||
];
|
||||
const capi = sqlite3.capi, wasm = sqlite3.wasm;
|
||||
/* We need to call sqlite3_shutdown() in order to avoid numerous
|
||||
legitimate warnings from the shell about it being initialized
|
||||
after sqlite3_initialize() has been called. This means,
|
||||
however, that any initialization done by the JS code may need
|
||||
to be re-done (e.g. re-registration of dynamically-loaded
|
||||
VFSes). We need a more generic approach to running such
|
||||
init-level code. */
|
||||
capi.sqlite3_shutdown();
|
||||
f.argv.pArgv = wasm.allocMainArgv(f.argv);
|
||||
f.argv.rc = wasm.exports.fiddle_main(
|
||||
f.argv.length, f.argv.pArgv
|
||||
);
|
||||
if(f.argv.rc){
|
||||
stderr("Fatal error initializing sqlite3 shell.");
|
||||
fiddleModule.isDead = true;
|
||||
return false;
|
||||
}
|
||||
stdout("SQLite version", capi.sqlite3_libversion(),
|
||||
capi.sqlite3_sourceid().substr(0,19));
|
||||
stdout('Welcome to the "fiddle" shell.');
|
||||
if(sqlite3.opfs){
|
||||
stdout("\nOPFS is available. To open a persistent db, use:\n\n",
|
||||
" .open file:name?vfs=opfs\n\nbut note that some",
|
||||
"features (e.g. upload) do not yet work with OPFS.");
|
||||
sqlite3.opfs.registerVfs();
|
||||
}
|
||||
stdout('\nEnter ".help" for usage hints.');
|
||||
this.exec([ // initialization commands...
|
||||
'.nullvalue NULL',
|
||||
'.headers on'
|
||||
].join('\n'));
|
||||
return true;
|
||||
},
|
||||
/**
|
||||
emscripten module for use with build mode -sMODULARIZE.
|
||||
Runs the given text through the shell as if it had been typed
|
||||
in by a user. Fires a working/start event before it starts and
|
||||
working/end event when it finishes.
|
||||
*/
|
||||
const fiddleModule = {
|
||||
print: stdout,
|
||||
printErr: stderr,
|
||||
/**
|
||||
Intercepts status updates from the emscripting module init
|
||||
and fires worker events with a type of 'status' and a
|
||||
payload of:
|
||||
exec: function f(sql){
|
||||
if(!f._){
|
||||
if(!this.runMain()) return;
|
||||
f._ = sqlite3.wasm.xWrap('fiddle_exec', null, ['string']);
|
||||
}
|
||||
if(fiddleModule.isDead){
|
||||
stderr("shell module has exit()ed. Cannot run SQL.");
|
||||
return;
|
||||
}
|
||||
wMsg('working','start');
|
||||
try {
|
||||
if(f._running){
|
||||
stderr('Cannot run multiple commands concurrently.');
|
||||
}else if(sql){
|
||||
if(Array.isArray(sql)) sql = sql.join('');
|
||||
f._running = true;
|
||||
f._(sql);
|
||||
}
|
||||
}finally{
|
||||
delete f._running;
|
||||
wMsg('working','end');
|
||||
}
|
||||
},
|
||||
resetDb: function f(){
|
||||
if(!f._) f._ = sqlite3.wasm.xWrap('fiddle_reset_db', null);
|
||||
stdout("Resetting database.");
|
||||
f._();
|
||||
stdout("Reset",this.dbFilename());
|
||||
},
|
||||
/* Interrupt can't work: this Worker is tied up working, so won't get the
|
||||
interrupt event which would be needed to perform the interrupt. */
|
||||
interrupt: function f(){
|
||||
if(!f._) f._ = sqlite3.wasm.xWrap('fiddle_interrupt', null);
|
||||
stdout("Requesting interrupt.");
|
||||
f._();
|
||||
}
|
||||
};
|
||||
|
||||
self.onmessage = function f(ev){
|
||||
ev = ev.data;
|
||||
if(!f.cache){
|
||||
f.cache = {
|
||||
prevFilename: null
|
||||
};
|
||||
}
|
||||
//console.debug("worker: onmessage.data",ev);
|
||||
switch(ev.type){
|
||||
case 'shellExec': Sqlite3Shell.exec(ev.data); return;
|
||||
case 'db-reset': Sqlite3Shell.resetDb(); return;
|
||||
case 'interrupt': Sqlite3Shell.interrupt(); return;
|
||||
/** Triggers the export of the current db. Fires an
|
||||
event in the form:
|
||||
|
||||
{
|
||||
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}
|
||||
{type:'db-export',
|
||||
data:{
|
||||
filename: name of db,
|
||||
buffer: contents of the db file (Uint8Array),
|
||||
error: on error, a message string and no buffer property.
|
||||
}
|
||||
}
|
||||
*/
|
||||
case 'db-export': {
|
||||
const fn = Sqlite3Shell.dbFilename();
|
||||
stdout("Exporting",fn+".");
|
||||
const fn2 = fn ? fn.split(/[/\\]/).pop() : null;
|
||||
try{
|
||||
if(!fn2) toss("DB appears to be closed.");
|
||||
const buffer = sqlite3.capi.sqlite3_js_db_export(
|
||||
Sqlite3Shell.dbHandle()
|
||||
);
|
||||
wMsg('db-export',{filename: fn2, buffer: buffer.buffer}, [buffer.buffer]);
|
||||
}catch(e){
|
||||
console.error("Export failed:",e);
|
||||
/* Post a failure message so that UI elements disabled
|
||||
during the export can be re-enabled. */
|
||||
wMsg('db-export',{
|
||||
filename: fn,
|
||||
error: e.message
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
case 'open': {
|
||||
/* Expects: {
|
||||
buffer: ArrayBuffer | Uint8Array,
|
||||
filename: the filename for the db. Any dir part is
|
||||
stripped.
|
||||
}
|
||||
*/
|
||||
const opt = ev.data;
|
||||
let buffer = opt.buffer;
|
||||
stderr('open():',fixmeOPFS);
|
||||
if(buffer instanceof ArrayBuffer){
|
||||
buffer = new Uint8Array(buffer);
|
||||
}else if(!(buffer instanceof Uint8Array)){
|
||||
stderr("'open' expects {buffer:Uint8Array} containing an uploaded db.");
|
||||
return;
|
||||
}
|
||||
const fn = (
|
||||
opt.filename
|
||||
? opt.filename.split(/[/\\]/).pop().replace('"','_')
|
||||
: ("db-"+((Math.random() * 10000000) | 0)+
|
||||
"-"+((Math.random() * 10000000) | 0)+".sqlite3")
|
||||
);
|
||||
try {
|
||||
/* We cannot delete the existing db file until the new one
|
||||
is installed, which means that we risk overflowing our
|
||||
quota (if any) by having both the previous and current
|
||||
db briefly installed in the virtual filesystem. */
|
||||
const fnAbs = '/'+fn;
|
||||
const oldName = Sqlite3Shell.dbFilename();
|
||||
if(oldName && oldName===fnAbs){
|
||||
/* We cannot create the replacement file while the current file
|
||||
is opened, nor does the shell have a .close command, so we
|
||||
must temporarily switch to another db... */
|
||||
Sqlite3Shell.exec('.open :memory:');
|
||||
fiddleModule.FS.unlink(fnAbs);
|
||||
}
|
||||
fiddleModule.FS.createDataFile("/", fn, buffer, true, true);
|
||||
Sqlite3Shell.exec('.open "'+fnAbs+'"');
|
||||
if(oldName && oldName!==fnAbs){
|
||||
try{fiddleModule.fsUnlink(oldName)}
|
||||
catch(e){/*ignored*/}
|
||||
}
|
||||
stdout("Replaced DB with",fn+".");
|
||||
}catch(e){
|
||||
stderr("Error installing db",fn+":",e.message);
|
||||
}
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
importScripts('fiddle-module.js');
|
||||
console.warn("Unknown fiddle-worker message type:",ev);
|
||||
};
|
||||
|
||||
/**
|
||||
emscripten module for use with build mode -sMODULARIZE.
|
||||
*/
|
||||
const fiddleModule = {
|
||||
print: stdout,
|
||||
printErr: stderr,
|
||||
/**
|
||||
initFiddleModule() is installed via fiddle-module.js due to
|
||||
building with:
|
||||
Intercepts status updates from the emscripting module init
|
||||
and fires worker events with a type of 'status' and a
|
||||
payload of:
|
||||
|
||||
emcc ... -sMODULARIZE=1 -sEXPORT_NAME=initFiddleModule
|
||||
{
|
||||
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.
|
||||
*/
|
||||
initFiddleModule(fiddleModule).then(function(thisModule){
|
||||
wMsg('fiddle-ready');
|
||||
});
|
||||
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}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
importScripts('fiddle-module.js'+self.location.search);
|
||||
/**
|
||||
initFiddleModule() is installed via fiddle-module.js due to
|
||||
building with:
|
||||
|
||||
emcc ... -sMODULARIZE=1 -sEXPORT_NAME=initFiddleModule
|
||||
*/
|
||||
sqlite3InitModule(fiddleModule).then((_sqlite3)=>{
|
||||
sqlite3 = _sqlite3;
|
||||
const dbVfs = sqlite3.wasm.xWrap('fiddle_db_vfs', "*", ['string']);
|
||||
fiddleModule.fsUnlink = (fn)=>{
|
||||
return sqlite3.wasm.sqlite3_wasm_vfs_unlink(dbVfs(0), fn);
|
||||
};
|
||||
wMsg('fiddle-ready');
|
||||
})/*then()*/;
|
||||
})();
|
||||
|
||||
+726
-720
File diff suppressed because it is too large
Load Diff
@@ -273,11 +273,6 @@
|
||||
</fieldset>
|
||||
</div>
|
||||
</div> <!-- #view-split -->
|
||||
<!-- Maintenance notes:
|
||||
|
||||
... TODO... currently being refactored...
|
||||
|
||||
-->
|
||||
<script src="fiddle.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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">
|
||||
<title>sqlite3 WASM Demo Page Index</title>
|
||||
</head>
|
||||
<body>
|
||||
<style>
|
||||
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;
|
||||
}
|
||||
.warning { color: firebrick; }
|
||||
</style>
|
||||
<header id='titlebar'><span>sqlite3 WASM demo pages</span></header>
|
||||
<hr>
|
||||
<div>Below is the list of demo pages for the sqlite3 WASM
|
||||
builds. The intent is that <em>this</em> page be run
|
||||
using the functional equivalent of:</div>
|
||||
<blockquote><pre><a href='https://sqlite.org/althttpd'>althttpd</a> -enable-sab -page index.html</pre></blockquote>
|
||||
<div>and the individual pages be started in their own tab.
|
||||
Warnings and Caveats:
|
||||
<ul class='warning'>
|
||||
<li>Some of these pages require that the web server emit the
|
||||
so-called
|
||||
<a href='https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy'>COOP</a>
|
||||
and
|
||||
<a href='https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy'>COEP</a>
|
||||
headers. <a href='https://sqlite.org/althttpd'>althttpd</a> requires the
|
||||
<code>-enable-sab</code> flag for that.
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div>The tests and demos...
|
||||
<ul id='test-list'>
|
||||
<li>Core-most tests
|
||||
<ul>
|
||||
<li><a href='tester1.html'>tester1</a>: Core unit and
|
||||
regression tests for the various APIs and surrounding
|
||||
utility code.</li>
|
||||
<li><a href='tester1-worker.html'>tester1-worker</a>: same thing
|
||||
but running in a Worker.</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>Higher-level apps and demos...
|
||||
<ul>
|
||||
<li><a href='demo-123.html'>demo-123</a> provides a
|
||||
no-nonsense example of adding sqlite3 support to a web
|
||||
page in the UI thread.</li>
|
||||
<li><a href='demo-123-worker.html'>demo-123-worker</a> is
|
||||
the same as <code>demo-123</code> but loads and runs
|
||||
sqlite3 from a Worker thread.</li>
|
||||
<li><a href='demo-jsstorage.html'>demo-jsstorage</a>: very basic
|
||||
demo of using the key-value VFS for storing a persistent db
|
||||
in JS <code>localStorage</code> or <code>sessionStorage</code>.</li>
|
||||
<li><a href='demo-worker1.html'>demo-worker1</a>:
|
||||
Worker-based wrapper of the OO API #1. Its Promise-based
|
||||
wrapper is significantly easier to use, however.</li>
|
||||
<li><a href='demo-worker1-promiser.html'>demo-worker1-promiser</a>:
|
||||
a demo of the Promise-based wrapper of the Worker1 API.</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<style>
|
||||
#test-list { font-size: 120%; }
|
||||
</style>
|
||||
<script>//Assign a distinct target tab name for each test page...
|
||||
document.querySelectorAll('a').forEach(function(e){
|
||||
e.target = e.href;
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,115 @@
|
||||
<!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/testing.css"/>
|
||||
<title>sqlite3 WASM Testing Page Index</title>
|
||||
</head>
|
||||
<body>
|
||||
<header id='titlebar'><span>sqlite3 WASM test pages</span></header>
|
||||
<hr>
|
||||
<div>Below is the list of test pages for the sqlite3 WASM
|
||||
builds. All of them require that this directory have been
|
||||
"make"d first. The intent is that <em>this</em> page be run
|
||||
using:</div>
|
||||
<blockquote><pre>althttpd -enable-sab -page index.html</pre></blockquote>
|
||||
<div>and the individual tests be started in their own tab.
|
||||
Warnings and Caveats:
|
||||
<ul class='warning'>
|
||||
<li>Some of these pages require that
|
||||
the web server emit the so-called
|
||||
<a href='https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy'>COOP</a>
|
||||
and
|
||||
<a href='https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy'>COEP</a>
|
||||
headers. <a href='https://sqlite.org/althttpd'>althttpd</a> requires the
|
||||
<code>-enable-sab</code> flag for that.
|
||||
</li>
|
||||
<li>Any OPFS-related pages require very recent version of
|
||||
Chrome or Chromium (v102 at least, possibly newer). OPFS
|
||||
support in the other major browsers is pending. Development
|
||||
and testing is currently done against a dev-channel release
|
||||
of Chrome (v107 as of 2022-09-26).
|
||||
</li>
|
||||
<li>Whether or not WASMFS/OPFS support is enabled on any given
|
||||
page may depend on build-time options which are <em>off by
|
||||
default</em>.
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div>The tests and demos...
|
||||
<ul id='test-list'>
|
||||
<li>Core-most tests
|
||||
<ul>
|
||||
<li><a href='tester1.html'>tester1</a>: Core unit and
|
||||
regression tests for the various APIs and surrounding
|
||||
utility code.</li>
|
||||
<li><a href='tester1-worker.html'>tester1-worker</a>: same thing
|
||||
but running in a Worker.</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>High-level apps and demos...
|
||||
<ul>
|
||||
<li><a href='fiddle/index.html'>fiddle</a> is an HTML front-end
|
||||
to a wasm build of the sqlite3 shell.</li>
|
||||
<li><a href='demo-123.html'>demo-123</a> provides a
|
||||
no-nonsense example of adding sqlite3 support to a web
|
||||
page in the UI thread.</li>
|
||||
<li><a href='demo-123-worker.html'>demo-123-worker</a> is
|
||||
the same as <code>demo-123</code> but loads and runs
|
||||
sqlite3 from a Worker thread.</li>
|
||||
<li><a href='demo-jsstorage.html'>demo-jsstorage</a>: very basic
|
||||
demo of using the key-value VFS for storing a persistent db
|
||||
in JS <code>localStorage</code> or <code>sessionStorage</code>.</li>
|
||||
<li><a href='demo-worker1.html'>demo-worker1</a>:
|
||||
Worker-based wrapper of the OO API #1. Its Promise-based
|
||||
wrapper is significantly easier to use, however.</li>
|
||||
<li><a href='demo-worker1-promiser.html'>demo-worker1-promiser</a>:
|
||||
a demo of the Promise-based wrapper of the Worker1 API.</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>speedtest1 ports (sqlite3's primary benchmarking tool)...
|
||||
<ul>
|
||||
<li><a href='speedtest1.html'>speedtest1</a>: a main-thread WASM build of speedtest1.</li>
|
||||
<!--li><a href='speedtest1-wasmfs.html?flags=--size,25'>speedtest1-wasmfs</a>: a variant of speedtest1 built solely for the wasmfs/opfs feature.
|
||||
</li-->
|
||||
<li><a href='speedtest1.html?vfs=kvvfs'>speedtest1-kvvfs</a>: speedtest1 with the kvvfs.</li>
|
||||
<li><a href='speedtest1-worker.html?size=25'>speedtest1-worker</a>: an interactive Worker-thread variant of speedtest1.</li>
|
||||
<li><a href='speedtest1-worker.html?vfs=opfs&size=25'>speedtest1-worker-opfs</a>: speedtest1-worker with the
|
||||
OPFS VFS preselected and configured for a moderate workload.</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>The obligatory "misc." category...
|
||||
<ul>
|
||||
<li><a href='module-symbols.html'>module-symbols</a> gives
|
||||
a high-level overview of the symbols exposed by the JS
|
||||
module.</li>
|
||||
<li><a href='batch-runner.html'>batch-runner</a>: runs batches of SQL exported from speedtest1.</li>
|
||||
<!--li><a href='scratchpad-wasmfs-main.html'>scratchpad-wasmfs-main</a>:
|
||||
experimenting with WASMFS/OPFS-based persistence. Maintenance
|
||||
reminder: we cannot currently (2022-09-15) load WASMFS in a
|
||||
worker due to an Emscripten limitation.</li-->
|
||||
<li><a href='test-opfs-vfs.html'>test-opfs-vfs</a>
|
||||
(<a href='test-opfs-vfs.html?opfs-sanity-check&opfs-verbose'>same
|
||||
with verbose output and sanity-checking tests</a>) is an
|
||||
sqlite3_vfs OPFS proxy using SharedArrayBuffer and the
|
||||
Atomics APIs to regulate communication between the
|
||||
synchronous sqlite3_vfs interface and the async OPFS
|
||||
impl.
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<!--li><a href='x.html'></a></li-->
|
||||
</ul>
|
||||
</div>
|
||||
<style>
|
||||
#test-list { font-size: 120%; }
|
||||
</style>
|
||||
<script>//Assign a distinct target tab name for each test page...
|
||||
document.querySelectorAll('a').forEach(function(e){
|
||||
e.target = e.href;
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -361,7 +361,7 @@ self.Jaccwabyt = function StructBinderFactory(config){
|
||||
framework's native format or in Emscripten format.
|
||||
*/
|
||||
const __memberSignature = function f(obj,memberName,emscriptenFormat=false){
|
||||
if(!f._) f._ = (x)=>x.replace(/[^vipPsjrd]/g,'').replace(/[pPs]/g,'i');
|
||||
if(!f._) f._ = (x)=>x.replace(/[^vipPsjrd]/g,"").replace(/[pPs]/g,'i');
|
||||
const m = __lookupMember(obj.structInfo, memberName, true);
|
||||
return emscriptenFormat ? f._(m.signature) : m.signature;
|
||||
};
|
||||
@@ -394,7 +394,17 @@ self.Jaccwabyt = function StructBinderFactory(config){
|
||||
|
||||
const __utf8Decoder = new TextDecoder('utf-8');
|
||||
const __utf8Encoder = new TextEncoder();
|
||||
|
||||
/** Internal helper to use in operations which need to distinguish
|
||||
between SharedArrayBuffer heap memory and non-shared heap. */
|
||||
const __SAB = ('undefined'===typeof SharedArrayBuffer)
|
||||
? function(){} : SharedArrayBuffer;
|
||||
const __utf8Decode = function(arrayBuffer, begin, end){
|
||||
return __utf8Decoder.decode(
|
||||
(arrayBuffer.buffer instanceof __SAB)
|
||||
? arrayBuffer.slice(begin, end)
|
||||
: arrayBuffer.subarray(begin, end)
|
||||
);
|
||||
};
|
||||
/**
|
||||
Uses __lookupMember() to find the given obj.structInfo key.
|
||||
Returns that member if it is a string, else returns false. If the
|
||||
@@ -437,8 +447,7 @@ self.Jaccwabyt = function StructBinderFactory(config){
|
||||
//log("mem[",pos,"]",mem[pos]);
|
||||
};
|
||||
//log("addr =",addr,"pos =",pos);
|
||||
if(addr===pos) return "";
|
||||
return __utf8Decoder.decode(new Uint8Array(mem.buffer, addr, pos-addr));
|
||||
return (addr===pos) ? "" : __utf8Decode(mem, addr, pos);
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -809,9 +809,7 @@ common:
|
||||
A read-only numeric property which is the "pointer" returned by the
|
||||
configured allocator when this object is constructed. After
|
||||
`dispose()` (inherited from [StructType][]) is called, this property
|
||||
has the `undefined` value. When passing instances of this struct to
|
||||
C-bound code, `pointer` is the value which must be passed in place
|
||||
of a C-side struct pointer. When calling C-side code which takes a
|
||||
has the `undefined` value. When calling C-side code which takes a
|
||||
pointer to a struct of this type, simply pass it `myStruct.pointer`.
|
||||
|
||||
<a name='appendices'></a>
|
||||
|
||||
@@ -1,178 +0,0 @@
|
||||
#include <assert.h>
|
||||
#include <string.h> /* memset() */
|
||||
#include <stddef.h> /* offsetof() */
|
||||
#include <stdio.h> /* snprintf() */
|
||||
#include <stdint.h> /* int64_t */
|
||||
/*#include <stdlib.h>*/ /* malloc/free(), needed for emscripten exports. */
|
||||
extern void * malloc(size_t);
|
||||
extern void free(void *);
|
||||
|
||||
/*
|
||||
** 2022-06-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.
|
||||
**
|
||||
***********************************************************************
|
||||
**
|
||||
** Utility functions for use with the emscripten/WASM bits. These
|
||||
** functions ARE NOT part of the sqlite3 public API. They are strictly
|
||||
** for internal use by the JS/WASM bindings.
|
||||
**
|
||||
** This file is intended to be WASM-compiled together with sqlite3.c,
|
||||
** e.g.:
|
||||
**
|
||||
** emcc ... sqlite3.c wasm_util.c
|
||||
*/
|
||||
|
||||
/*
|
||||
** Experimenting with output parameters.
|
||||
*/
|
||||
int jaccwabyt_test_intptr(int * p){
|
||||
if(1==((int)p)%3){
|
||||
/* kludge to get emscripten to export malloc() and free() */;
|
||||
free(malloc(0));
|
||||
}
|
||||
return *p = *p * 2;
|
||||
}
|
||||
int64_t jaccwabyt_test_int64_max(void){
|
||||
return (int64_t)0x7fffffffffffffff;
|
||||
}
|
||||
int64_t jaccwabyt_test_int64_min(void){
|
||||
return ~jaccwabyt_test_int64_max();
|
||||
}
|
||||
int64_t jaccwabyt_test_int64_times2(int64_t x){
|
||||
return x * 2;
|
||||
}
|
||||
|
||||
void jaccwabyt_test_int64_minmax(int64_t * min, int64_t *max){
|
||||
*max = jaccwabyt_test_int64_max();
|
||||
*min = jaccwabyt_test_int64_min();
|
||||
/*printf("minmax: min=%lld, max=%lld\n", *min, *max);*/
|
||||
}
|
||||
int64_t jaccwabyt_test_int64ptr(int64_t * p){
|
||||
/*printf("jaccwabyt_test_int64ptr( @%lld = 0x%llx )\n", (int64_t)p, *p);*/
|
||||
return *p = *p * 2;
|
||||
}
|
||||
|
||||
void jaccwabyt_test_stack_overflow(int recurse){
|
||||
if(recurse) jaccwabyt_test_stack_overflow(recurse);
|
||||
}
|
||||
|
||||
struct WasmTestStruct {
|
||||
int v4;
|
||||
void * ppV;
|
||||
const char * cstr;
|
||||
int64_t v8;
|
||||
void (*xFunc)(void*);
|
||||
};
|
||||
typedef struct WasmTestStruct WasmTestStruct;
|
||||
void jaccwabyt_test_struct(WasmTestStruct * s){
|
||||
if(s){
|
||||
s->v4 *= 2;
|
||||
s->v8 = s->v4 * 2;
|
||||
s->ppV = s;
|
||||
s->cstr = __FILE__;
|
||||
if(s->xFunc) s->xFunc(s);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
/** For testing the 'string-free' whwasmutil.xWrap() conversion. */
|
||||
char * jaccwabyt_test_str_hello(int fail){
|
||||
char * s = fail ? 0 : (char *)malloc(6);
|
||||
if(s){
|
||||
memcpy(s, "hello", 5);
|
||||
s[5] = 0;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/*
|
||||
** Returns a NUL-terminated string containing a JSON-format metadata
|
||||
** regarding C structs, for use with the StructBinder API. The
|
||||
** returned memory is static and is only written to the first time
|
||||
** this is called.
|
||||
*/
|
||||
const char * jaccwabyt_test_ctype_json(void){
|
||||
static char strBuf[1024 * 8] = {0};
|
||||
int n = 0, structCount = 0, groupCount = 0;
|
||||
char * pos = &strBuf[1] /* skip first byte for now to help protect
|
||||
against a small race condition */;
|
||||
char const * const zEnd = pos + sizeof(strBuf);
|
||||
if(strBuf[0]) return strBuf;
|
||||
/* Leave first strBuf[0] at 0 until the end to help guard against a
|
||||
tiny race condition. If this is called twice concurrently, they
|
||||
might end up both writing to strBuf, but they'll both write the
|
||||
same thing, so that's okay. If we set byte 0 up front then the
|
||||
2nd instance might return a partially-populated string. */
|
||||
|
||||
////////////////////////////////////////////////////////////////////
|
||||
// First we need to build up our macro framework...
|
||||
////////////////////////////////////////////////////////////////////
|
||||
// Core output macros...
|
||||
#define lenCheck assert(pos < zEnd - 100)
|
||||
#define outf(format,...) \
|
||||
pos += snprintf(pos, ((size_t)(zEnd - pos)), format, __VA_ARGS__); \
|
||||
lenCheck
|
||||
#define out(TXT) outf("%s",TXT)
|
||||
#define CloseBrace(LEVEL) \
|
||||
assert(LEVEL<5); memset(pos, '}', LEVEL); pos+=LEVEL; lenCheck
|
||||
|
||||
////////////////////////////////////////////////////////////////////
|
||||
// Macros for emitting StructBinder descriptions...
|
||||
#define StructBinder__(TYPE) \
|
||||
n = 0; \
|
||||
outf("%s{", (structCount++ ? ", " : "")); \
|
||||
out("\"name\": \"" # TYPE "\","); \
|
||||
outf("\"sizeof\": %d", (int)sizeof(TYPE)); \
|
||||
out(",\"members\": {");
|
||||
#define StructBinder_(T) StructBinder__(T)
|
||||
// ^^^ indirection needed to expand CurrentStruct
|
||||
#define StructBinder StructBinder_(CurrentStruct)
|
||||
#define _StructBinder CloseBrace(2)
|
||||
#define M(MEMBER,SIG) \
|
||||
outf("%s\"%s\": " \
|
||||
"{\"offset\":%d,\"sizeof\": %d,\"signature\":\"%s\"}", \
|
||||
(n++ ? ", " : ""), #MEMBER, \
|
||||
(int)offsetof(CurrentStruct,MEMBER), \
|
||||
(int)sizeof(((CurrentStruct*)0)->MEMBER), \
|
||||
SIG)
|
||||
// End of macros
|
||||
////////////////////////////////////////////////////////////////////
|
||||
|
||||
out("\"structs\": ["); {
|
||||
|
||||
#define CurrentStruct WasmTestStruct
|
||||
StructBinder {
|
||||
M(v4,"i");
|
||||
M(cstr,"s");
|
||||
M(ppV,"p");
|
||||
M(v8,"j");
|
||||
M(xFunc,"v(p)");
|
||||
} _StructBinder;
|
||||
#undef CurrentStruct
|
||||
|
||||
} out( "]"/*structs*/);
|
||||
out("}"/*top-level object*/);
|
||||
*pos = 0;
|
||||
strBuf[0] = '{'/*end of the race-condition workaround*/;
|
||||
return strBuf;
|
||||
#undef DefGroup
|
||||
#undef Def
|
||||
#undef _DefGroup
|
||||
#undef StructBinder
|
||||
#undef StructBinder_
|
||||
#undef StructBinder__
|
||||
#undef M
|
||||
#undef _StructBinder
|
||||
#undef CurrentStruct
|
||||
#undef CloseBrace
|
||||
#undef out
|
||||
#undef outf
|
||||
#undef lenCheck
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
_jaccwabyt_test_intptr
|
||||
_jaccwabyt_test_int64ptr
|
||||
_jaccwabyt_test_int64_max
|
||||
_jaccwabyt_test_int64_min
|
||||
_jaccwabyt_test_int64_minmax
|
||||
_jaccwabyt_test_int64_times2
|
||||
_jaccwabyt_test_struct
|
||||
_jaccwabyt_test_ctype_json
|
||||
_jaccwabyt_test_stack_overflow
|
||||
_jaccwabyt_test_str_hello
|
||||
@@ -0,0 +1,333 @@
|
||||
<!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>sqlite3 Module Symbols</title>
|
||||
<style>
|
||||
body {
|
||||
font-size: 12.5pt;
|
||||
padding-bottom: 1em;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="fossil-doc" data-title="sqlite3 Module Symbols"><!-- EXTRACT_BEGIN -->
|
||||
<!--
|
||||
The part of this doc wrapped in div.fossil-doc gets snipped out
|
||||
from the canonical copy in the main tree (ext/wasm/module-symbols.html)
|
||||
and added to the wasm docs repository, where it's served from
|
||||
fossil.
|
||||
-->
|
||||
<style>
|
||||
.pseudolist {
|
||||
column-count: auto;
|
||||
column-width: 12rem;
|
||||
column-gap: 1.5em;
|
||||
width: 90%;
|
||||
margin: auto;
|
||||
}
|
||||
.pseudolist.wide {
|
||||
column-width: 21rem;
|
||||
}
|
||||
.pseudolist.wide2 {
|
||||
column-width: 25rem;
|
||||
}
|
||||
.pseudolist > span {
|
||||
font-family: monospace;
|
||||
margin: 0.25em 0;
|
||||
display: block;
|
||||
}
|
||||
.pseudolist.wrap-anywhere {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.warning { color: firebrick }
|
||||
.error { color: firebrick; background-color: yellow}
|
||||
.hidden, .initially-hidden {
|
||||
position: absolute !important;
|
||||
opacity: 0 !important;
|
||||
pointer-events: none !important;
|
||||
display: none !important;
|
||||
}
|
||||
h1::before, h2::before, h3::before, h4::before {
|
||||
/* Remove automatic numbering */
|
||||
content: "" !important;
|
||||
background-color: transparent !important;
|
||||
margin: 0 !important;
|
||||
border: 0 !important;
|
||||
padding: 0 !important;
|
||||
}
|
||||
.func-wasm {
|
||||
|
||||
}
|
||||
.func-wasm::after {
|
||||
content: "WASM";
|
||||
color: saddlebrown;
|
||||
/* ^^^^ the color must be legible in both "bright" and "dark"
|
||||
s ite themes. */
|
||||
font-size: 0.65em;
|
||||
/* baseline-shift: super; */
|
||||
vertical-align: super;
|
||||
}
|
||||
</style>
|
||||
<p id='module-load-status'><strong>Loading WASM module...</strong>
|
||||
If this takes "a long time" it may have failed and the browser's
|
||||
dev console may contain hints as to why.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
This page lists the SQLite3 APIs exported
|
||||
by <code>sqlite3.wasm</code> and exposed to clients
|
||||
by <code>sqlite3.js</code>. These lists are generated dynamically
|
||||
by loading the JS/WASM module and introspecting it, with the following
|
||||
caveats:
|
||||
</p>
|
||||
|
||||
<ul>
|
||||
<li>Some APIs are explicitly filtered out of these lists because
|
||||
they are strictly for internal use within the JS/WASM APIs and
|
||||
its own test code.
|
||||
</li>
|
||||
<li>This page runs in the main UI thread so cannot see features
|
||||
which are only available in a Worker thread. If this page were
|
||||
to function via a Worker, it would not be able to see
|
||||
functionality only available in the main thread. Starting a
|
||||
Worker here to fetch those symbols requires loading a second
|
||||
copy of the sqlite3 WASM module and JS code.
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div class='initially-hidden'>
|
||||
|
||||
<p>This page exposes a global symbol named <code>sqlite3</code>
|
||||
which can be inspected using the browser's dev tools.
|
||||
</p>
|
||||
|
||||
<p>Jump to...</p>
|
||||
<ul>
|
||||
<li><a href='#sqlite3-namespace'><code>sqlite3</code> namespace</a></li>
|
||||
<li><a href='#sqlite3-version'><code>sqlite3.version</code> object</a></li>
|
||||
<li><a href='#sqlite3-functions'><code>sqlite3_...()</code> functions</a></li>
|
||||
<li><a href='#sqlite3-constants'><code>SQLITE_...</code> constants</a></li>
|
||||
<li><a href='#sqlite3.oo1'><code>sqlite3.oo1</code> namespace</a>
|
||||
<!--ul>
|
||||
<li><a href='#sqlite3.oo1.DB'><code>sqlite3.oo1.DB</code></a></li>
|
||||
<li><a href='#sqlite3.oo1.Stmt'><code>sqlite3.oo1.Stmt</code></a></li>
|
||||
</ul-->
|
||||
</li>
|
||||
<li><a href='#sqlite3.wasm'><code>sqlite3.wasm</code> namespace</a></li>
|
||||
<li><a href='#sqlite3.wasm.pstack'><code>sqlite3.wasm.pstack</code> namespace</a></li>
|
||||
<li><a href='#compile-options'>Compilation options used in this module build</a></li>
|
||||
</ul>
|
||||
|
||||
<a id="sqlite3-namespace"></a>
|
||||
<h1><code>sqlite3</code> Namespace</h1>
|
||||
<p>
|
||||
The <code>sqlite3</code> namespace object exposes the following...
|
||||
</p>
|
||||
<div id='list-namespace' class='pseudolist'></div>
|
||||
|
||||
<a id="sqlite3-version"></a>
|
||||
<h1><code>sqlite3.version</code> Object</h1>
|
||||
<p>
|
||||
The <code>sqlite3.version</code> object exposes the following...
|
||||
</p>
|
||||
<div id='list-version' class='pseudolist wide wrap-anywhere'></div>
|
||||
|
||||
<a id="sqlite3-functions"></a>
|
||||
<h1><code>sqlite3_...()</code> Function List</h1>
|
||||
|
||||
<p>The <code>sqlite3.capi</code> namespace exposes the following
|
||||
<a href='https://sqlite.org/c3ref/funclist.html'><code>sqlite3_...()</code>
|
||||
functions</a>...
|
||||
</p>
|
||||
<div id='list-functions' class='pseudolist wide'></div>
|
||||
<p>
|
||||
<code class='func-wasm'></code> = function is specific to the JS/WASM
|
||||
bindings, not part of the C API.
|
||||
</p>
|
||||
|
||||
<a id="sqlite3-constants"></a>
|
||||
<h1><code>SQLITE_...</code> Constants</h1>
|
||||
|
||||
<p>The <code>sqlite3.capi</code> namespace exposes the following
|
||||
<a href='https://sqlite.org/c3ref/constlist.html'><code>SQLITE_...</code>
|
||||
constants</a>...
|
||||
</p>
|
||||
<div id='list-constants' class='pseudolist wide'></div>
|
||||
|
||||
<a id="sqlite3.oo1"></a>
|
||||
<h1><code>sqlite3.oo1</code> Namespace</h1>
|
||||
<p>
|
||||
The <code>sqlite3.oo1</code> namespace exposes the following...
|
||||
</p>
|
||||
<div id='list-oo1' class='pseudolist'></div>
|
||||
|
||||
<a id="sqlite3.wasm"></a>
|
||||
<h1><code>sqlite3.wasm</code> Namespace</h1>
|
||||
<p>
|
||||
The <code>sqlite3.wasm</code> namespace exposes the
|
||||
following...
|
||||
</p>
|
||||
<div id='list-wasm' class='pseudolist'></div>
|
||||
|
||||
<a id="sqlite3.wasm.pstack"></a>
|
||||
<h1><code>sqlite3.wasm.pstack</code> Namespace</h1>
|
||||
<p>
|
||||
The <code>sqlite3.wasm.pstack</code> namespace exposes the
|
||||
following...
|
||||
</p>
|
||||
<div id='list-wasm-pstack' class='pseudolist'></div>
|
||||
|
||||
<a id="compile-options"></a>
|
||||
<h1>Compilation Options</h1>
|
||||
<p>
|
||||
<code>SQLITE_...</code> compilation options used in this build
|
||||
of <code>sqlite3.wasm</code>...
|
||||
</p>
|
||||
<div id='list-compile-options' class='pseudolist wide2'></div>
|
||||
|
||||
</div><!-- .initially-hidden -->
|
||||
<script src="jswasm/sqlite3.js">/* This tag MUST be inside the
|
||||
fossil-doc block so that this part can work without modification in
|
||||
the wasm docs repo. */</script>
|
||||
<script>(async function(){
|
||||
const eNew = (tag,parent)=>{
|
||||
const e = document.createElement(tag);
|
||||
if(parent) parent.appendChild(e);
|
||||
return e;
|
||||
};
|
||||
const eLi = (label,parent)=>{
|
||||
const e = eNew('span',parent);
|
||||
e.innerText = label;
|
||||
return e;
|
||||
};
|
||||
const E = (sel)=>document.querySelector(sel);
|
||||
const EAll = (sel)=>document.querySelectorAll(sel);
|
||||
const eFuncs = E('#list-functions'),
|
||||
eConst = E('#list-constants');
|
||||
const renderConst = function(name){
|
||||
eLi(name, eConst);
|
||||
};
|
||||
const renderFunc = function(name){
|
||||
let lbl = name+'()';
|
||||
const e = eLi(lbl, eFuncs);;
|
||||
if(name.startsWith('sqlite3_js')
|
||||
|| name.startsWith('sqlite3_wasm')){
|
||||
e.classList.add('func-wasm');
|
||||
}
|
||||
};
|
||||
const renderGeneric = function(name,value,eParent){
|
||||
let lbl;
|
||||
if(value instanceof Function) lbl = name+'()';
|
||||
else{
|
||||
switch(typeof value){
|
||||
case 'number': case 'boolean': case 'string':
|
||||
lbl = name+' = '+JSON.stringify(value);
|
||||
break;
|
||||
default:
|
||||
lbl = name + ' ['+(typeof value)+']';
|
||||
}
|
||||
}
|
||||
const e = eLi(lbl, eParent);
|
||||
if(name.startsWith('sqlite3_wasm')){
|
||||
e.classList.add('func-wasm');
|
||||
}
|
||||
};
|
||||
const renderIt = async function(sqlite3){
|
||||
self.sqlite3 = sqlite3;
|
||||
console.warn("sqlite3 installed as global symbol self.sqlite3.");
|
||||
const capi = sqlite3.capi, wasm = sqlite3.wasm;
|
||||
const cmpIcase = (a,b)=>a.toLowerCase().localeCompare(b.toLowerCase());
|
||||
const renderX = function(tgtElem, container, keys){
|
||||
for(const k of keys.sort(cmpIcase)){
|
||||
renderGeneric(k, container[k], tgtElem);
|
||||
}
|
||||
};
|
||||
|
||||
const excludeNamespace = ['scriptInfo','StructBinder'];
|
||||
renderX(
|
||||
E('#list-namespace'), sqlite3,
|
||||
Object.keys(sqlite3)
|
||||
.filter((v)=>excludeNamespace.indexOf(v)<0)
|
||||
);
|
||||
renderX(
|
||||
E('#list-version'), sqlite3.version,
|
||||
Object.keys(sqlite3.version)
|
||||
);
|
||||
|
||||
/* sqlite3_...() and SQLITE_... */
|
||||
const lists = {c: [], f: []};
|
||||
for(const [k,v] of Object.entries(capi)){
|
||||
if(k.startsWith('SQLITE_')) lists.c.push(k);
|
||||
else if(k.startsWith('sqlite3_')) lists.f.push(k);
|
||||
}
|
||||
const excludeCapi = [
|
||||
'sqlite3_wasmfs_filename_is_persistent',
|
||||
'sqlite3_wasmfs_opfs_dir'
|
||||
];
|
||||
lists.c.sort().forEach(renderConst);
|
||||
lists.f
|
||||
.filter((v)=>excludeCapi.indexOf(v)<0)
|
||||
.sort()
|
||||
.forEach(renderFunc);
|
||||
lists.c = lists.f = null;
|
||||
|
||||
renderX(E('#list-oo1'), sqlite3.oo1,
|
||||
Object.keys(sqlite3.oo1) );
|
||||
|
||||
const excludeWasm = ['ctype'];
|
||||
renderX(E('#list-wasm'),
|
||||
wasm, Object.keys(wasm).filter((v)=>{
|
||||
return !v.startsWith('sqlite3_wasm_')
|
||||
&& excludeWasm.indexOf(v)<0;
|
||||
}));
|
||||
const psKeys = Object.keys(wasm.pstack);
|
||||
psKeys.push('pointer','quota','remaining');
|
||||
renderX(E('#list-wasm-pstack'), wasm.pstack, psKeys);
|
||||
|
||||
const cou = wasm.compileOptionUsed();
|
||||
//const cou2 = Object.create(null);
|
||||
//Object.entries(cou).forEach((e)=>cou2['SQLITE_'+e[0]] = e[1]);
|
||||
renderX(E('#list-compile-options'), cou, Object.keys(cou));
|
||||
};
|
||||
|
||||
/**
|
||||
This is a module object for use with the emscripten-installed
|
||||
sqlite3InitModule() factory function.
|
||||
*/
|
||||
const myModule = {
|
||||
print: (...args)=>{console.log(...args)},
|
||||
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-load-status')
|
||||
};
|
||||
}
|
||||
if(text === f.last.text) return;
|
||||
f.last.text = text;
|
||||
++f.last.step;
|
||||
if(text) {
|
||||
f.ui.status.classList.remove('hidden');
|
||||
f.ui.status.innerText = text;
|
||||
}else{
|
||||
f.ui.status.classList.add('hidden');
|
||||
EAll('.initially-hidden').forEach((e)=>{
|
||||
e.classList.remove('initially-hidden');
|
||||
});
|
||||
}
|
||||
}
|
||||
}/*myModule*/;
|
||||
self.sqlite3InitModule(myModule).then(renderIt);
|
||||
})();</script>
|
||||
</div><!-- .fossil-doc EXTRACT_END -->
|
||||
</body></html>
|
||||
@@ -0,0 +1,40 @@
|
||||
<!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 WASMFS/OPFS Main-thread Scratchpad</title>
|
||||
</head>
|
||||
<body>
|
||||
<header id='titlebar'><span>sqlite3 WASMFS/OPFS Main-thread Scratchpad</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>Scratchpad/test app for the WASMF/OPFS integration in the
|
||||
main window thread. This page requires that the sqlite3 API have
|
||||
been built with WASMFS support. If OPFS support is available then
|
||||
it "should" persist a database across reloads (watch the dev console
|
||||
output), otherwise it will not.
|
||||
</p>
|
||||
<p>All stuff on this page happens in the dev console.</p>
|
||||
<hr>
|
||||
<div id='test-output'></div>
|
||||
<script src="sqlite3-wasmfs.js"></script>
|
||||
<script src="common/SqliteTestUtil.js"></script>
|
||||
<script src="scratchpad-wasmfs-main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
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. 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 log = console.log.bind(console),
|
||||
warn = console.warn.bind(console),
|
||||
error = console.error.bind(console);
|
||||
|
||||
const stdout = log;
|
||||
const stderr = error;
|
||||
|
||||
const test1 = function(db){
|
||||
db.exec("create table if not exists t(a);")
|
||||
.transaction(function(db){
|
||||
db.prepare("insert into t(a) values(?)")
|
||||
.bind(new Date().getTime())
|
||||
.stepFinalize();
|
||||
stdout("Number of values in table t:",
|
||||
db.selectValue("select count(*) from t"));
|
||||
});
|
||||
};
|
||||
|
||||
const runTests = function(sqlite3){
|
||||
const capi = sqlite3.capi,
|
||||
oo = sqlite3.oo1,
|
||||
wasm = sqlite3.wasm;
|
||||
stdout("Loaded sqlite3:",capi.sqlite3_libversion(), capi.sqlite3_sourceid());
|
||||
const persistentDir = capi.sqlite3_wasmfs_opfs_dir();
|
||||
if(persistentDir){
|
||||
stdout("Persistent storage dir:",persistentDir);
|
||||
}else{
|
||||
stderr("No persistent storage available.");
|
||||
}
|
||||
const startTime = performance.now();
|
||||
let db;
|
||||
try {
|
||||
db = new oo.DB(persistentDir+'/foo.db');
|
||||
stdout("DB filename:",db.filename);
|
||||
const banner1 = '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>',
|
||||
banner2 = '<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<';
|
||||
[
|
||||
test1
|
||||
].forEach((f)=>{
|
||||
const n = performance.now();
|
||||
stdout(banner1,"Running",f.name+"()...");
|
||||
f(db, sqlite3);
|
||||
stdout(banner2,f.name+"() took ",(performance.now() - n),"ms");
|
||||
});
|
||||
}finally{
|
||||
if(db) db.close();
|
||||
}
|
||||
stdout("Total test time:",(performance.now() - startTime),"ms");
|
||||
};
|
||||
|
||||
sqlite3InitModule(self.sqlite3TestModule).then(runTests);
|
||||
})();
|
||||
@@ -0,0 +1,149 @@
|
||||
<!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>speedtest1-wasmfs.wasm</title>
|
||||
</head>
|
||||
<body>
|
||||
<header id='titlebar'><span>speedtest1-wasmfs.wasm</span></header>
|
||||
<div>See also: <a href='speedtest1-worker.html'>A Worker-thread variant of this page.</a></div>
|
||||
<!-- 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 class='warning'>This page starts running the main exe when it loads, which will
|
||||
block the UI until it finishes! Adding UI controls to manually configure and start it
|
||||
are TODO.</div>
|
||||
</div>
|
||||
<div class='warning'>Achtung: running it with the dev tools open may
|
||||
<em>drastically</em> slow it down. For faster results, keep the dev
|
||||
tools closed when running it!
|
||||
</div>
|
||||
<div>Output is delayed/buffered because we cannot update the UI while the
|
||||
speedtest is running. Output will appear below when ready...
|
||||
<div id='test-output'></div>
|
||||
<script src="common/SqliteTestUtil.js"></script>
|
||||
<script src="speedtest1-wasmfs.js"></script>
|
||||
<script>(function(){
|
||||
/**
|
||||
If this environment contains OPFS, this function initializes it and
|
||||
returns the name of the dir on which OPFS is mounted, else it returns
|
||||
an empty string.
|
||||
*/
|
||||
const wasmfsDir = function f(wasmUtil,dirName="/opfs"){
|
||||
if(undefined !== f._) return f._;
|
||||
if( !self.FileSystemHandle
|
||||
|| !self.FileSystemDirectoryHandle
|
||||
|| !self.FileSystemFileHandle){
|
||||
return f._ = "";
|
||||
}
|
||||
try{
|
||||
if(0===wasmUtil.xCallWrapped(
|
||||
'sqlite3_wasm_init_wasmfs', 'i32', ['string'], dirName
|
||||
)){
|
||||
return f._ = dirName;
|
||||
}else{
|
||||
return f._ = "";
|
||||
}
|
||||
}catch(e){
|
||||
// sqlite3_wasm_init_wasmfs() is not available
|
||||
return f._ = "";
|
||||
}
|
||||
};
|
||||
wasmfsDir._ = undefined;
|
||||
|
||||
const eOut = document.querySelector('#test-output');
|
||||
const log2 = function(cssClass,...args){
|
||||
const ln = document.createElement('div');
|
||||
if(cssClass) ln.classList.add(cssClass);
|
||||
ln.append(document.createTextNode(args.join(' ')));
|
||||
eOut.append(ln);
|
||||
//this.e.output.lastElementChild.scrollIntoViewIfNeeded();
|
||||
};
|
||||
const logList = [];
|
||||
const dumpLogList = function(){
|
||||
logList.forEach((v)=>log2('',v));
|
||||
logList.length = 0;
|
||||
};
|
||||
/* can't update DOM while speedtest is running unless we run
|
||||
speedtest in a worker thread. */;
|
||||
const log = (...args)=>{
|
||||
console.log(...args);
|
||||
logList.push(args.join(' '));
|
||||
};
|
||||
const logErr = function(...args){
|
||||
console.error(...args);
|
||||
logList.push('ERROR: '+args.join(' '));
|
||||
};
|
||||
|
||||
const runTests = function(sqlite3){
|
||||
console.log("Module inited.");
|
||||
const wasm = sqlite3.capi.wasm;
|
||||
const unlink = wasm.xWrap("sqlite3_wasm_vfs_unlink", "int", ["string"]);
|
||||
const pDir = wasmfsDir(wasm);
|
||||
if(pDir) log2('',"Persistent storage:",pDir);
|
||||
else{
|
||||
log2('error',"Expecting persistent storage in this build.");
|
||||
return;
|
||||
}
|
||||
const scope = wasm.scopedAllocPush();
|
||||
const dbFile = pDir+"/speedtest1.db";
|
||||
const urlParams = new URL(self.location.href).searchParams;
|
||||
const argv = ["speedtest1"];
|
||||
if(urlParams.has('flags')){
|
||||
argv.push(...(urlParams.get('flags').split(',')));
|
||||
let i = argv.indexOf('--vfs');
|
||||
if(i>=0) argv.splice(i,2);
|
||||
}else{
|
||||
argv.push(
|
||||
"--singlethread",
|
||||
"--nomutex",
|
||||
"--nosync",
|
||||
"--nomemstat"
|
||||
);
|
||||
//"--memdb", // note that memdb trumps the filename arg
|
||||
}
|
||||
|
||||
if(argv.indexOf('--memdb')>=0){
|
||||
log2('error',"WARNING: --memdb flag trumps db filename.");
|
||||
}
|
||||
argv.push("--big-transactions"/*important for tests 410 and 510!*/,
|
||||
dbFile);
|
||||
console.log("argv =",argv);
|
||||
// These log messages are not emitted to the UI until after main() returns. Fixing that
|
||||
// requires moving the main() call and related cleanup into a timeout handler.
|
||||
if(pDir) unlink(dbFile);
|
||||
log2('',"Starting native app:\n ",argv.join(' '));
|
||||
log2('',"This will take a while and the browser might warn about the runaway JS.",
|
||||
"Give it time...");
|
||||
logList.length = 0;
|
||||
setTimeout(function(){
|
||||
wasm.xCall('wasm_main', argv.length,
|
||||
wasm.scopedAllocMainArgv(argv));
|
||||
wasm.scopedAllocPop(scope);
|
||||
if(pDir) unlink(dbFile);
|
||||
logList.unshift("Done running native main(). Output:");
|
||||
dumpLogList();
|
||||
}, 25);
|
||||
}/*runTests()*/;
|
||||
|
||||
self.sqlite3TestModule.print = log;
|
||||
self.sqlite3TestModule.printErr = logErr;
|
||||
sqlite3InitModule(self.sqlite3TestModule).then(runTests);
|
||||
})();</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,372 @@
|
||||
<!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>speedtest1.wasm Worker</title>
|
||||
</head>
|
||||
<body>
|
||||
<header id='titlebar'>speedtest1.wasm Worker</header>
|
||||
<div>See also: <a href='speedtest1.html'>A main-thread variant of this page.</a></div>
|
||||
<!-- 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 id='ui-controls' class='hidden'>
|
||||
<legend>Options</legend>
|
||||
<div id='toolbar'>
|
||||
<div id='toolbar-select'>
|
||||
<select id='select-flags' size='10' multiple></select>
|
||||
<div>The following flags can be passed as URL parameters:
|
||||
vfs=NAME, size=N, journal=MODE, cachesize=SIZE
|
||||
</div>
|
||||
</div>
|
||||
<div class='toolbar-inner-vertical'>
|
||||
<div id='toolbar-selected-flags'></div>
|
||||
<div class='toolbar-inner-vertical'>
|
||||
<span>→ <a id='link-main-thread' href='#' target='speedtest-main'
|
||||
title='Start speedtest1.html with the selected flags'>speedtest1</a>
|
||||
</span>
|
||||
<span>→ <a id='link-wasmfs' href='#' target='speedtest-wasmfs'
|
||||
title='Start speedtest1-wasmfs.html with the selected flags'>speedtest1-wasmfs</a>
|
||||
</span>
|
||||
<span>→ <a id='link-kvvfs' href='#' target='speedtest-kvvfs'
|
||||
title='Start kvvfs speedtest1 with the selected flags'>speedtest1-kvvfs</a>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class='toolbar-inner-vertical' id='toolbar-runner-controls'>
|
||||
<button id='btn-reset-flags'>Reset Flags</button>
|
||||
<button id='btn-output-clear'>Clear output</button>
|
||||
<button id='btn-run'>Run</button>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<div>
|
||||
<span class='input-wrapper'>
|
||||
<input type='checkbox' class='disable-during-eval' id='cb-reverse-log-order' checked></input>
|
||||
<label for='cb-reverse-log-order' id='lbl-reverse-log-order'>Reverse log order</label>
|
||||
</span>
|
||||
</div>
|
||||
<div id='test-output'>
|
||||
</div>
|
||||
<div id='tips'>
|
||||
<strong>Tips:</strong>
|
||||
<ul>
|
||||
<li>Control-click the flags to (de)select multiple flags.</li>
|
||||
<li>The <tt>--big-transactions</tt> flag is important for two
|
||||
of the bigger tests. Without it, those tests create a
|
||||
combined total of 140k implicit transactions, reducing their
|
||||
speed to an absolute crawl, especially when WASMFS is
|
||||
activated.
|
||||
</li>
|
||||
<li>The easiest way to try different optimization levels is,
|
||||
from this directory:
|
||||
<pre>$ rm -f speedtest1.js; make -e emcc_opt='-O2' speedtest1.js</pre>
|
||||
Then reload this page. -O2 seems to consistently produce the fastest results.
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<style>
|
||||
#test-output {
|
||||
white-space: break-spaces;
|
||||
overflow: auto;
|
||||
}
|
||||
div#tips { margin-top: 1em; }
|
||||
#toolbar {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
#toolbar > * {
|
||||
margin: 0 0.5em;
|
||||
}
|
||||
.toolbar-inner-vertical {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
}
|
||||
#toolbar-select {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.toolbar-inner-vertical > *, #toolbar-select > * {
|
||||
margin: 0.2em 0;
|
||||
}
|
||||
#select-flags > option {
|
||||
white-space: pre;
|
||||
font-family: monospace;
|
||||
}
|
||||
fieldset {
|
||||
border-radius: 0.5em;
|
||||
}
|
||||
#toolbar-runner-controls { flex-grow: 1 }
|
||||
#toolbar-runner-controls > * { flex: 1 0 auto }
|
||||
#toolbar-selected-flags::before {
|
||||
font-family: initial;
|
||||
content:"Selected flags: ";
|
||||
}
|
||||
#toolbar-selected-flags {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
font-family: monospace;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
</style>
|
||||
<script>(function(){
|
||||
'use strict';
|
||||
const E = (sel)=>document.querySelector(sel);
|
||||
const eOut = E('#test-output');
|
||||
const log2 = function(cssClass,...args){
|
||||
let ln;
|
||||
if(1 || cssClass){
|
||||
ln = document.createElement('div');
|
||||
if(cssClass) ln.classList.add(cssClass);
|
||||
ln.append(document.createTextNode(args.join(' ')));
|
||||
}else{
|
||||
// This doesn't work with the "reverse order" option!
|
||||
ln = document.createTextNode(args.join(' ')+'\n');
|
||||
}
|
||||
eOut.append(ln);
|
||||
};
|
||||
const log = (...args)=>{
|
||||
//console.log(...args);
|
||||
log2('', ...args);
|
||||
};
|
||||
const logErr = function(...args){
|
||||
console.error(...args);
|
||||
log2('error', ...args);
|
||||
};
|
||||
const logWarn = function(...args){
|
||||
console.warn(...args);
|
||||
log2('warning', ...args);
|
||||
};
|
||||
|
||||
const spacePad = function(str,len=21){
|
||||
if(str.length===len) return str;
|
||||
else if(str.length>len) return str.substr(0,len);
|
||||
const a = []; a.length = len - str.length;
|
||||
return str+a.join(' ');
|
||||
};
|
||||
// OPTION elements seem to ignore white-space:pre, so do this the hard way...
|
||||
const nbspPad = function(str,len=21){
|
||||
if(str.length===len) return str;
|
||||
else if(str.length>len) return str.substr(0,len);
|
||||
const a = []; a.length = len - str.length;
|
||||
return str+a.join(' ');
|
||||
};
|
||||
|
||||
const urlParams = new URL(self.location.href).searchParams;
|
||||
const W = new Worker(
|
||||
"speedtest1-worker.js?sqlite3.dir=jswasm"+
|
||||
(urlParams.has('opfs-verbose') ? '&opfs-verbose' : '')
|
||||
);
|
||||
const mPost = function(msgType,payload){
|
||||
W.postMessage({type: msgType, data: payload});
|
||||
};
|
||||
|
||||
const eFlags = E('#select-flags');
|
||||
const eSelectedFlags = E('#toolbar-selected-flags');
|
||||
const eLinkMainThread = E('#link-main-thread');
|
||||
const eLinkWasmfs = E('#link-wasmfs');
|
||||
const eLinkKvvfs = E('#link-kvvfs');
|
||||
const getSelectedFlags = ()=>{
|
||||
const f = Array.prototype.map.call(eFlags.selectedOptions, (v)=>v.value);
|
||||
[
|
||||
'size', 'vfs', 'journal', 'cachesize'
|
||||
].forEach(function(k){
|
||||
if(urlParams.has(k)) f.push('--'+k, urlParams.get(k));
|
||||
});
|
||||
return f;
|
||||
};
|
||||
const updateSelectedFlags = function(){
|
||||
eSelectedFlags.innerText = '';
|
||||
const flags = getSelectedFlags();
|
||||
flags.forEach(function(f){
|
||||
const e = document.createElement('span');
|
||||
e.innerText = f;
|
||||
eSelectedFlags.appendChild(e);
|
||||
});
|
||||
const rxStripDash = /^(-+)?/;
|
||||
const comma = flags.join(',');
|
||||
eLinkMainThread.setAttribute('target', 'speedtest1-main-'+comma);
|
||||
eLinkMainThread.href = 'speedtest1.html?flags='+comma;
|
||||
eLinkWasmfs.setAttribute('target', 'speedtest1-wasmfs-'+comma);
|
||||
eLinkWasmfs.href = 'speedtest1-wasmfs.html?flags='+comma;
|
||||
eLinkKvvfs.setAttribute('target', 'speedtest1-kvvfs-'+comma);
|
||||
eLinkKvvfs.href = 'speedtest1.html?vfs=kvvfs&flags='+comma;
|
||||
};
|
||||
eFlags.addEventListener('change', updateSelectedFlags );
|
||||
{
|
||||
const flags = Object.create(null);
|
||||
/* TODO? Flags which require values need custom UI
|
||||
controls and some of them make little sense here
|
||||
(e.g. --script FILE). */
|
||||
flags["--autovacuum"] = "Enable AUTOVACUUM mode";
|
||||
flags["--big-transactions"] = "Important for tests 410 and 510!";
|
||||
//flags["--cachesize"] = "N Set the cache size to N pages";
|
||||
flags["--checkpoint"] = "Run PRAGMA wal_checkpoint after each test case";
|
||||
flags["--exclusive"] = "Enable locking_mode=EXCLUSIVE";
|
||||
flags["--explain"] = "Like --sqlonly but with added EXPLAIN keywords";
|
||||
//flags["--heap"] = "SZ MIN Memory allocator uses SZ bytes & min allocation MIN";
|
||||
flags["--incrvacuum"] = "Enable incremenatal vacuum mode";
|
||||
//flags["--journal"] = "M Set the journal_mode to M";
|
||||
//flags["--key"] = "KEY Set the encryption key to KEY";
|
||||
//flags["--lookaside"] = "N SZ Configure lookaside for N slots of SZ bytes each";
|
||||
flags["--memdb"] = "Use an in-memory database";
|
||||
//flags["--mmap"] = "SZ MMAP the first SZ bytes of the database file";
|
||||
flags["--multithread"] = "Set multithreaded mode";
|
||||
flags["--nomemstat"] = "Disable memory statistics";
|
||||
flags["--nomutex"] = "Open db with SQLITE_OPEN_NOMUTEX";
|
||||
flags["--nosync"] = "Set PRAGMA synchronous=OFF";
|
||||
flags["--notnull"] = "Add NOT NULL constraints to table columns";
|
||||
//flags["--output"] = "FILE Store SQL output in FILE";
|
||||
//flags["--pagesize"] = "N Set the page size to N";
|
||||
//flags["--pcache"] = "N SZ Configure N pages of pagecache each of size SZ bytes";
|
||||
//flags["--primarykey"] = "Use PRIMARY KEY instead of UNIQUE where appropriate";
|
||||
//flags["--repeat"] = "N Repeat each SELECT N times (default: 1)";
|
||||
flags["--reprepare"] = "Reprepare each statement upon every invocation";
|
||||
//flags["--reserve"] = "N Reserve N bytes on each database page";
|
||||
//flags["--script"] = "FILE Write an SQL script for the test into FILE";
|
||||
flags["--serialized"] = "Set serialized threading mode";
|
||||
flags["--singlethread"] = "Set single-threaded mode - disables all mutexing";
|
||||
flags["--sqlonly"] = "No-op. Only show the SQL that would have been run.";
|
||||
flags["--shrink-memory"] = "Invoke sqlite3_db_release_memory() frequently.";
|
||||
//flags["--size"] = "N Relative test size. Default=100";
|
||||
flags["--strict"] = "Use STRICT table where appropriate";
|
||||
flags["--stats"] = "Show statistics at the end";
|
||||
//flags["--temp"] = "N N from 0 to 9. 0: no temp table. 9: all temp tables";
|
||||
//flags["--testset"] = "T Run test-set T (main, cte, rtree, orm, fp, debug)";
|
||||
flags["--trace"] = "Turn on SQL tracing";
|
||||
//flags["--threads"] = "N Use up to N threads for sorting";
|
||||
/*
|
||||
The core API's WASM build does not support UTF16, but in
|
||||
this app it's not an issue because the data are not crossing
|
||||
JS/WASM boundaries.
|
||||
*/
|
||||
flags["--utf16be"] = "Set text encoding to UTF-16BE";
|
||||
flags["--utf16le"] = "Set text encoding to UTF-16LE";
|
||||
flags["--verify"] = "Run additional verification steps.";
|
||||
flags["--without"] = "rowid Use WITHOUT ROWID where appropriate";
|
||||
const preselectedFlags = [
|
||||
'--big-transactions',
|
||||
'--singlethread'
|
||||
];
|
||||
if(urlParams.has('flags')){
|
||||
preselectedFlags.push(...urlParams.get('flags').split(','));
|
||||
}
|
||||
if('opfs'!==urlParams.get('vfs')){
|
||||
preselectedFlags.push('--memdb');
|
||||
}
|
||||
Object.keys(flags).sort().forEach(function(f){
|
||||
const opt = document.createElement('option');
|
||||
eFlags.appendChild(opt);
|
||||
const lbl = nbspPad(f)+flags[f];
|
||||
//opt.innerText = lbl;
|
||||
opt.innerHTML = lbl;
|
||||
opt.value = f;
|
||||
if(preselectedFlags.indexOf(f) >= 0) opt.selected = true;
|
||||
});
|
||||
const cbReverseLog = E('#cb-reverse-log-order');
|
||||
const lblReverseLog = E('#lbl-reverse-log-order');
|
||||
if(cbReverseLog.checked){
|
||||
lblReverseLog.classList.add('warning');
|
||||
eOut.classList.add('reverse');
|
||||
}
|
||||
cbReverseLog.addEventListener('change', function(){
|
||||
if(this.checked){
|
||||
eOut.classList.add('reverse');
|
||||
lblReverseLog.classList.add('warning');
|
||||
}else{
|
||||
eOut.classList.remove('reverse');
|
||||
lblReverseLog.classList.remove('warning');
|
||||
}
|
||||
}, false);
|
||||
updateSelectedFlags();
|
||||
}
|
||||
E('#btn-output-clear').addEventListener('click', ()=>{
|
||||
eOut.innerText = '';
|
||||
});
|
||||
E('#btn-reset-flags').addEventListener('click',()=>{
|
||||
eFlags.value = '';
|
||||
updateSelectedFlags();
|
||||
});
|
||||
E('#btn-run').addEventListener('click',function(){
|
||||
log("Running speedtest1. UI controls will be disabled until it completes.");
|
||||
mPost('run', getSelectedFlags());
|
||||
});
|
||||
|
||||
const eControls = E('#ui-controls');
|
||||
/** Update Emscripten-related UI elements while loading the module. */
|
||||
const updateLoadStatus = function f(text){
|
||||
if(!f.last){
|
||||
f.last = { text: '', step: 0 };
|
||||
const E = (cssSelector)=>document.querySelector(cssSelector);
|
||||
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');
|
||||
}
|
||||
};
|
||||
|
||||
W.onmessage = function(msg){
|
||||
msg = msg.data;
|
||||
switch(msg.type){
|
||||
case 'ready':
|
||||
log("Worker is ready.");
|
||||
eControls.classList.remove('hidden');
|
||||
break;
|
||||
case 'stdout': log(msg.data); break;
|
||||
case 'stdout': logErr(msg.data); break;
|
||||
case 'run-start':
|
||||
eControls.disabled = true;
|
||||
log("Running speedtest1 with argv =",msg.data.join(' '));
|
||||
break;
|
||||
case 'run-end':
|
||||
log("speedtest1 finished.");
|
||||
eControls.disabled = false;
|
||||
// app output is in msg.data
|
||||
break;
|
||||
case 'error': logErr(msg.data); break;
|
||||
case 'load-status': updateLoadStatus(msg.data); break;
|
||||
default:
|
||||
logErr("Unhandled worker message type:",msg);
|
||||
break;
|
||||
}
|
||||
};
|
||||
})();</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,99 @@
|
||||
'use strict';
|
||||
(function(){
|
||||
let speedtestJs = 'speedtest1.js';
|
||||
const urlParams = new URL(self.location.href).searchParams;
|
||||
if(urlParams.has('sqlite3.dir')){
|
||||
speedtestJs = urlParams.get('sqlite3.dir') + '/' + speedtestJs;
|
||||
}
|
||||
importScripts('common/whwasmutil.js', speedtestJs);
|
||||
/**
|
||||
If this environment contains OPFS, this function initializes it and
|
||||
returns the name of the dir on which OPFS is mounted, else it returns
|
||||
an empty string.
|
||||
*/
|
||||
const wasmfsDir = function f(wasmUtil){
|
||||
if(undefined !== f._) return f._;
|
||||
const pdir = '/opfs';
|
||||
if( !self.FileSystemHandle
|
||||
|| !self.FileSystemDirectoryHandle
|
||||
|| !self.FileSystemFileHandle){
|
||||
return f._ = "";
|
||||
}
|
||||
try{
|
||||
if(0===wasmUtil.xCallWrapped(
|
||||
'sqlite3_wasm_init_wasmfs', 'i32', ['string'], pdir
|
||||
)){
|
||||
return f._ = pdir;
|
||||
}else{
|
||||
return f._ = "";
|
||||
}
|
||||
}catch(e){
|
||||
// sqlite3_wasm_init_wasmfs() is not available
|
||||
return f._ = "";
|
||||
}
|
||||
};
|
||||
wasmfsDir._ = undefined;
|
||||
|
||||
const mPost = function(msgType,payload){
|
||||
postMessage({type: msgType, data: payload});
|
||||
};
|
||||
|
||||
const App = Object.create(null);
|
||||
App.logBuffer = [];
|
||||
const logMsg = (type,msgArgs)=>{
|
||||
const msg = msgArgs.join(' ');
|
||||
App.logBuffer.push(msg);
|
||||
mPost(type,msg);
|
||||
};
|
||||
const log = (...args)=>logMsg('stdout',args);
|
||||
const logErr = (...args)=>logMsg('stderr',args);
|
||||
|
||||
const runSpeedtest = function(cliFlagsArray){
|
||||
const scope = App.wasm.scopedAllocPush();
|
||||
const dbFile = App.pDir+"/speedtest1.sqlite3";
|
||||
try{
|
||||
const argv = [
|
||||
"speedtest1.wasm", ...cliFlagsArray, dbFile
|
||||
];
|
||||
App.logBuffer.length = 0;
|
||||
mPost('run-start', [...argv]);
|
||||
App.wasm.xCall('wasm_main', argv.length,
|
||||
App.wasm.scopedAllocMainArgv(argv));
|
||||
}catch(e){
|
||||
mPost('error',e.message);
|
||||
}finally{
|
||||
App.wasm.scopedAllocPop(scope);
|
||||
mPost('run-end', App.logBuffer.join('\n'));
|
||||
App.logBuffer.length = 0;
|
||||
}
|
||||
};
|
||||
|
||||
self.onmessage = function(msg){
|
||||
msg = msg.data;
|
||||
switch(msg.type){
|
||||
case 'run': runSpeedtest(msg.data || []); break;
|
||||
default:
|
||||
logErr("Unhandled worker message type:",msg.type);
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
const EmscriptenModule = {
|
||||
print: log,
|
||||
printErr: logErr,
|
||||
setStatus: (text)=>mPost('load-status',text)
|
||||
};
|
||||
self.sqlite3InitModule(EmscriptenModule).then((sqlite3)=>{
|
||||
const S = sqlite3;
|
||||
App.vfsUnlink = function(pDb, fname){
|
||||
const pVfs = S.wasm.sqlite3_wasm_db_vfs(pDb, 0);
|
||||
if(pVfs) S.wasm.sqlite3_wasm_vfs_unlink(pVfs, fname||0);
|
||||
};
|
||||
App.pDir = wasmfsDir(S.wasm);
|
||||
App.wasm = S.wasm;
|
||||
//if(App.pDir) log("Persistent storage:",pDir);
|
||||
//else log("Using transient storage.");
|
||||
mPost('ready',true);
|
||||
log("Registered VFSes:", ...S.capi.sqlite3_js_vfs_list());
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,174 @@
|
||||
<!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>speedtest1.wasm</title>
|
||||
</head>
|
||||
<body>
|
||||
<header id='titlebar'><span>speedtest1.wasm</span></header>
|
||||
<div>See also: <a href='speedtest1-worker.html'>A Worker-thread variant of this page.</a></div>
|
||||
<!-- 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 class='warning'>This page starts running the main exe when it loads, which will
|
||||
block the UI until it finishes! Adding UI controls to manually configure and start it
|
||||
are TODO.</div>
|
||||
</div>
|
||||
<div class='warning'>Achtung: running it with the dev tools open may
|
||||
<em>drastically</em> slow it down. For faster results, keep the dev
|
||||
tools closed when running it!
|
||||
</div>
|
||||
<div>Output is delayed/buffered because we cannot update the UI while the
|
||||
speedtest is running. Output will appear below when ready...
|
||||
<div id='test-output'></div>
|
||||
<script src="common/SqliteTestUtil.js"></script>
|
||||
<script src="jswasm/speedtest1.js"></script>
|
||||
<script>(function(){
|
||||
/**
|
||||
If this environment contains OPFS, this function initializes it and
|
||||
returns the name of the dir on which OPFS is mounted, else it returns
|
||||
an empty string.
|
||||
*/
|
||||
const wasmfsDir = function f(wasmUtil){
|
||||
if(undefined !== f._) return f._;
|
||||
const pdir = '/persistent';
|
||||
if( !self.FileSystemHandle
|
||||
|| !self.FileSystemDirectoryHandle
|
||||
|| !self.FileSystemFileHandle){
|
||||
return f._ = "";
|
||||
}
|
||||
try{
|
||||
if(0===wasmUtil.xCallWrapped(
|
||||
'sqlite3_wasm_init_wasmfs', 'i32', ['string'], pdir
|
||||
)){
|
||||
return f._ = pdir;
|
||||
}else{
|
||||
return f._ = "";
|
||||
}
|
||||
}catch(e){
|
||||
// sqlite3_wasm_init_wasmfs() is not available
|
||||
return f._ = "";
|
||||
}
|
||||
};
|
||||
wasmfsDir._ = undefined;
|
||||
|
||||
const eOut = document.querySelector('#test-output');
|
||||
const log2 = function(cssClass,...args){
|
||||
const ln = document.createElement('div');
|
||||
if(cssClass) ln.classList.add(cssClass);
|
||||
ln.append(document.createTextNode(args.join(' ')));
|
||||
eOut.append(ln);
|
||||
//this.e.output.lastElementChild.scrollIntoViewIfNeeded();
|
||||
};
|
||||
const logList = [];
|
||||
const dumpLogList = function(){
|
||||
logList.forEach((v)=>log2('',v));
|
||||
logList.length = 0;
|
||||
};
|
||||
/* can't update DOM while speedtest is running unless we run
|
||||
speedtest in a worker thread. */;
|
||||
const log = (...args)=>{
|
||||
console.log(...args);
|
||||
logList.push(args.join(' '));
|
||||
};
|
||||
const logErr = function(...args){
|
||||
console.error(...args);
|
||||
logList.push('ERROR: '+args.join(' '));
|
||||
};
|
||||
|
||||
const runTests = function(sqlite3){
|
||||
const capi = sqlite3.capi, wasm = sqlite3.wasm;
|
||||
//console.debug('sqlite3 =',sqlite3);
|
||||
const pDir = wasmfsDir(wasm);
|
||||
if(pDir){
|
||||
console.warn("Persistent storage:",pDir);
|
||||
}
|
||||
const scope = wasm.scopedAllocPush();
|
||||
let dbFile = pDir+"/speedtest1.db";
|
||||
const urlParams = new URL(self.location.href).searchParams;
|
||||
const argv = ["speedtest1"];
|
||||
if(urlParams.has('flags')){
|
||||
argv.push(...(urlParams.get('flags').split(',')));
|
||||
}
|
||||
|
||||
let forceSize = 0;
|
||||
let vfs, pVfs = 0;
|
||||
if(urlParams.has('vfs')){
|
||||
vfs = urlParams.get('vfs');
|
||||
pVfs = capi.sqlite3_vfs_find(vfs);
|
||||
if(!pVfs){
|
||||
log2('error',"Unknown VFS:",vfs);
|
||||
return;
|
||||
}
|
||||
argv.push("--vfs", vfs);
|
||||
log2('',"Using VFS:",vfs);
|
||||
if('kvvfs' === vfs){
|
||||
forceSize = 4 /* 5 uses approx. 4.96mb */;
|
||||
dbFile = 'session';
|
||||
log2('warning',"kvvfs VFS: forcing --size",forceSize,
|
||||
"and filename '"+dbFile+"'.");
|
||||
capi.sqlite3_js_kvvfs_clear(dbFile);
|
||||
}
|
||||
}
|
||||
if(forceSize){
|
||||
argv.push('--size',forceSize);
|
||||
}else{
|
||||
[
|
||||
'size'
|
||||
].forEach(function(k){
|
||||
const v = urlParams.get(k);
|
||||
if(v) argv.push('--'+k, urlParams[k]);
|
||||
});
|
||||
}
|
||||
argv.push(
|
||||
"--singlethread",
|
||||
//"--nomutex",
|
||||
//"--nosync",
|
||||
//"--memdb", // note that memdb trumps the filename arg
|
||||
"--nomemstat"
|
||||
);
|
||||
argv.push("--big-transactions"/*important for tests 410 and 510!*/,
|
||||
dbFile);
|
||||
console.log("argv =",argv);
|
||||
// These log messages are not emitted to the UI until after main() returns. Fixing that
|
||||
// requires moving the main() call and related cleanup into a timeout handler.
|
||||
if(pDir) wasm.sqlite3_wasm_vfs_unlink(pVfs,dbFile);
|
||||
log2('',"Starting native app:\n ",argv.join(' '));
|
||||
log2('',"This will take a while and the browser might warn about the runaway JS.",
|
||||
"Give it time...");
|
||||
logList.length = 0;
|
||||
setTimeout(function(){
|
||||
wasm.xCall('wasm_main', argv.length,
|
||||
wasm.scopedAllocMainArgv(argv));
|
||||
wasm.scopedAllocPop(scope);
|
||||
if('kvvfs'===vfs){
|
||||
logList.unshift("KVVFS "+dbFile+" size = "+
|
||||
capi.sqlite3_js_kvvfs_size(dbFile));
|
||||
}
|
||||
if(pDir) wasm.sqlite3_wasm_vfs_unlink(pVfs,dbFile);
|
||||
logList.unshift("Done running native main(). Output:");
|
||||
dumpLogList();
|
||||
}, 50);
|
||||
}/*runTests()*/;
|
||||
|
||||
self.sqlite3TestModule.print = log;
|
||||
self.sqlite3TestModule.printErr = logErr;
|
||||
sqlite3InitModule(self.sqlite3TestModule).then(runTests);
|
||||
})();</script>
|
||||
</body>
|
||||
</html>
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
#!/bin/bash
|
||||
# Expects $1 to be a (speedtest1 --script) output file. Output is a
|
||||
# series of SQL files extracted from that file.
|
||||
infile=${1:?arg = speedtest1 --script output file}
|
||||
testnums=$(grep -e '^-- begin test' "$infile" | cut -d' ' -f4)
|
||||
if [ x = "x${testnums}" ]; then
|
||||
echo "Could not parse any begin/end blocks out of $infile" 1>&2
|
||||
exit 1
|
||||
fi
|
||||
odir=${infile%%/*}
|
||||
if [ "$odir" = "$infile" ]; then odir="."; fi
|
||||
#echo testnums=$testnums
|
||||
for n in $testnums; do
|
||||
ofile=$odir/$(printf "speedtest1-%03d.sql" $n)
|
||||
sed -n -e "/^-- begin test $n /,/^-- end test $n\$/p" $infile > $ofile
|
||||
echo -e "$n\t$ofile"
|
||||
done
|
||||
@@ -0,0 +1,17 @@
|
||||
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;
|
||||
@@ -0,0 +1,28 @@
|
||||
WITH RECURSIVE
|
||||
input(sud) AS (
|
||||
VALUES('53..7....6..195....98....6.8...6...34..8.3..17...2...6.6....28....419..5....8..79')
|
||||
),
|
||||
digits(z, lp) AS (
|
||||
VALUES('1', 1)
|
||||
UNION ALL SELECT
|
||||
CAST(lp+1 AS TEXT), lp+1 FROM digits WHERE lp<9
|
||||
),
|
||||
x(s, ind) AS (
|
||||
SELECT sud, instr(sud, '.') FROM input
|
||||
UNION ALL
|
||||
SELECT
|
||||
substr(s, 1, ind-1) || z || substr(s, ind+1),
|
||||
instr( substr(s, 1, ind-1) || z || substr(s, ind+1), '.' )
|
||||
FROM x, digits AS z
|
||||
WHERE ind>0
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM digits AS lp
|
||||
WHERE z.z = substr(s, ((ind-1)/9)*9 + lp, 1)
|
||||
OR z.z = substr(s, ((ind-1)%9) + (lp-1)*9 + 1, 1)
|
||||
OR z.z = substr(s, (((ind-1)/3) % 3) * 3
|
||||
+ ((ind-1)/27) * 27 + lp
|
||||
+ ((lp-1) / 3) * 6, 1)
|
||||
)
|
||||
)
|
||||
SELECT s FROM x WHERE ind=0;
|
||||
@@ -0,0 +1,26 @@
|
||||
<!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>Async-behind-Sync experiment</title>
|
||||
</head>
|
||||
<body>
|
||||
<header id='titlebar'><span>Async-behind-Sync sqlite3_vfs</span></header>
|
||||
<div>This performs a sanity test of the "opfs" sqlite3_vfs.
|
||||
<strong>See the dev console for all output.</strong>
|
||||
</div>
|
||||
<div>
|
||||
<a href='?delete'>Use this link</a> to delete the persistent OPFS-side db (if any).
|
||||
</div>
|
||||
<div id='test-output'></div>
|
||||
<script>
|
||||
new Worker(
|
||||
"test-opfs-vfs.js?sqlite3.dir=jswasm&"+self.location.search.substr(1)
|
||||
);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
2022-09-17
|
||||
|
||||
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 testing ground for the OPFS VFS.
|
||||
*/
|
||||
'use strict';
|
||||
const tryOpfsVfs = async function(sqlite3){
|
||||
const toss = function(...args){throw new Error(args.join(' '))};
|
||||
const logPrefix = "OPFS tester:";
|
||||
const log = (...args)=>console.log(logPrefix,...args);
|
||||
const warn = (...args)=>console.warn(logPrefix,...args);
|
||||
const error = (...args)=>console.error(logPrefix,...args);
|
||||
const opfs = sqlite3.opfs;
|
||||
log("tryOpfsVfs()");
|
||||
if(!sqlite3.opfs){
|
||||
const e = toss("OPFS is not available.");
|
||||
error(e);
|
||||
throw e;
|
||||
}
|
||||
const capi = sqlite3.capi;
|
||||
const pVfs = capi.sqlite3_vfs_find("opfs") || toss("Missing 'opfs' VFS.");
|
||||
const oVfs = capi.sqlite3_vfs.instanceForPointer(pVfs) || toss("Unexpected instanceForPointer() result.");;
|
||||
log("OPFS VFS:",pVfs, oVfs);
|
||||
|
||||
const wait = async (ms)=>{
|
||||
return new Promise((resolve)=>setTimeout(resolve, ms));
|
||||
};
|
||||
|
||||
const urlArgs = new URL(self.location.href).searchParams;
|
||||
const dbFile = "my-persistent.db";
|
||||
if(urlArgs.has('delete')) sqlite3.opfs.unlink(dbFile);
|
||||
|
||||
const db = new opfs.OpfsDb(dbFile,'ct');
|
||||
log("db file:",db.filename);
|
||||
try{
|
||||
if(opfs.entryExists(dbFile)){
|
||||
let n = db.selectValue("select count(*) from sqlite_schema");
|
||||
log("Persistent data found. sqlite_schema entry count =",n);
|
||||
}
|
||||
db.transaction((db)=>{
|
||||
db.exec({
|
||||
sql:[
|
||||
"create table if not exists t(a);",
|
||||
"insert into t(a) values(?),(?),(?);",
|
||||
],
|
||||
bind: [performance.now() | 0,
|
||||
(performance.now() |0) / 2,
|
||||
(performance.now() |0) / 4]
|
||||
});
|
||||
});
|
||||
log("count(*) from t =",db.selectValue("select count(*) from t"));
|
||||
|
||||
// Some sanity checks of the opfs utility functions...
|
||||
const testDir = '/sqlite3-opfs-'+opfs.randomFilename(12);
|
||||
const aDir = testDir+'/test/dir';
|
||||
await opfs.mkdir(aDir) || toss("mkdir failed");
|
||||
await opfs.mkdir(aDir) || toss("mkdir must pass if the dir exists");
|
||||
await opfs.unlink(testDir+'/test') && toss("delete 1 should have failed (dir not empty)");
|
||||
//await opfs.entryExists(testDir)
|
||||
await opfs.unlink(testDir+'/test/dir') || toss("delete 2 failed");
|
||||
await opfs.unlink(testDir+'/test/dir') && toss("delete 2b should have failed (dir already deleted)");
|
||||
await opfs.unlink(testDir, true) || toss("delete 3 failed");
|
||||
await opfs.entryExists(testDir) && toss("entryExists(",testDir,") should have failed");
|
||||
}finally{
|
||||
db.close();
|
||||
}
|
||||
|
||||
log("Done!");
|
||||
}/*tryOpfsVfs()*/;
|
||||
|
||||
importScripts('jswasm/sqlite3.js');
|
||||
self.sqlite3InitModule()
|
||||
.then((sqlite3)=>tryOpfsVfs(sqlite3))
|
||||
.catch((e)=>{
|
||||
console.error("Error initializing module:",e);
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
<!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 tester #1 (Worker thread)</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: monospace;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1 id='color-target'>sqlite3 WASM/JS tester #1 (Worker thread)</h1>
|
||||
<div>See <a href='tester1.html' target='tester1.html'>tester1.html</a>
|
||||
for the UI-thread variant.</div>
|
||||
<div class='input-wrapper'>
|
||||
<input type='checkbox' id='cb-log-reverse'>
|
||||
<label for='cb-log-reverse'>Reverse log order?</label>
|
||||
</div>
|
||||
<div id='test-output'></div>
|
||||
<script>(function(){
|
||||
const logTarget = document.querySelector('#test-output');
|
||||
const logHtml = function(cssClass,...args){
|
||||
const ln = document.createElement('div');
|
||||
if(cssClass){
|
||||
for(const c of (Array.isArray(cssClass) ? cssClass : [cssClass])){
|
||||
ln.classList.add(c);
|
||||
}
|
||||
}
|
||||
ln.append(document.createTextNode(args.join(' ')));
|
||||
logTarget.append(ln);
|
||||
};
|
||||
const cbReverse = document.querySelector('#cb-log-reverse');
|
||||
const cbReverseIt = ()=>{
|
||||
logTarget.classList[cbReverse.checked ? 'add' : 'remove']('reverse');
|
||||
};
|
||||
cbReverse.addEventListener('change',cbReverseIt,true);
|
||||
cbReverseIt();
|
||||
const w = new Worker("tester1.js?sqlite3.dir=jswasm");
|
||||
w.onmessage = function({data}){
|
||||
switch(data.type){
|
||||
case 'log':
|
||||
logHtml(data.payload.cssClass, ...data.payload.args);
|
||||
break;
|
||||
case 'error':
|
||||
logHtml('error', ...data.payload.args);
|
||||
break;
|
||||
case 'test-result':
|
||||
document.querySelector('#color-target').classList.add(
|
||||
data.payload.pass ? 'tests-pass' : 'tests-fail'
|
||||
);
|
||||
break;
|
||||
default:
|
||||
logHtml('error',"Unhandled message:",data.type);
|
||||
};
|
||||
};
|
||||
})();</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,28 @@
|
||||
<!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 tester #1 (UI thread)</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: monospace;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1 id='color-target'>sqlite3 WASM/JS tester #1 (UI thread)</h1>
|
||||
<div>See <a href='tester1-worker.html' target='tester1-worker.html'>tester1-worker.html</a>
|
||||
for the Worker-thread variant.</div>
|
||||
<div class='input-wrapper'>
|
||||
<input type='checkbox' id='cb-log-reverse'>
|
||||
<label for='cb-log-reverse'>Reverse log order?</label>
|
||||
</div>
|
||||
<div id='test-output'></div>
|
||||
<script src="jswasm/sqlite3.js"></script>
|
||||
<script src="tester1.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+1864
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user