Compare commits

...

563 Commits

Author SHA1 Message Date
drh 2f2c5e2061 Version 3.40.0
FossilOrigin-Name: 89c459e766ea7e9165d0beeb124708b955a4950d0f4792f457465d71b158d318
2022-11-16 12:10:08 +00:00
drh a70a01dbcb Previous change to the fake_big_file command in the test harness was not
correct.  This one should fix the problem.

FossilOrigin-Name: 6ee57a2e4e3399481100c40da0229d2d33cbe3290016185c8a60839d14b209f6
2022-11-14 19:42:01 +00:00
drh 1da477d3ab Change the fake_big_file test command so that it fails for files larger than
2MB on Windows, as we have observed that Window10 will sometimes bluescreen
when operating on very large sparse files.

FossilOrigin-Name: d39ffd2abadcc85c46ba17612f9f575005b4818e18bf39362b8ee574837cfad9
2022-11-14 18:57:21 +00:00
dan cfce889cda Avoid running bigsort.test with SQLITE_DEBUG builds. The assert() statements added in [7c96a56] make it too slow.
FossilOrigin-Name: fa68dd8928c76888d535e649794743eeefd3abe0f909792a128955710bfc948a
2022-11-14 17:48:26 +00:00
stephan 8d7b41302f Remove some outdated code comments. No code changes.
FossilOrigin-Name: 80ff592a9d0157bfa8bd1f9959c3aa26cab0ec16fdccf7b58a7523b8912c1a8c
2022-11-13 19:29:51 +00:00
drh 7e475e571f Disable the ability to change the schema_version cookie when
SQLITE_DBCONFIG_DEFENSIVE mode is enabled.  This is a security
enhancement inspired by the question in
[forum:/forumpost/2b9cc3dae1f1e5f6|forum post 2b9cc3dae1f1e5f6].

FossilOrigin-Name: 1d81381e8f5db5d7064cc313b8544ca3cb1ca9e8cd61e71368a2d2e598befc9c
2022-11-12 17:17:01 +00:00
drh a6303704a3 Remove unnecessary tabs in the ChaCha20 implementation.
[forum:/forumpost/0cdce5db8c|Forum post 0cdce5db8c].

FossilOrigin-Name: b7179efbdb2bdc878acec0abfe272821f7e0d7d9e5ef06cd7fd796ef295e54ab
2022-11-10 23:10:11 +00:00
stephan 2c4d62f013 Automatically relinquish implicitly-acquired OPFS file locks during VFS idle time in an attempt to help alleviate cross-tab locking contention like that described in [forum:58a377083cd24a|forum post 58a377083cd24a].
FossilOrigin-Name: 8daf24ff73dd9928057412e0e4c2e2b2e47e1dca66acfb6b07c846e8d97582cc
2022-11-10 13:22:35 +00:00
stephan da2641597a Rework automatically acquired OPFS locks to be released during idle time. This eliminates the performance hit reported in [46304ba057707c].
FossilOrigin-Name: a7fe91afca473fe55c983bc81d214df4ef3699863c7423fa4b6b9cde23d6a3b4
2022-11-10 13:14:30 +00:00
stephan aafa022f5b OPFS: if an op which needs a lock is called when no lock has been obtained, automatically lock it at the start of the op and unlock it at the end of that op. This is an attempt to alleviate the cross-tab contention described in [forum post 58a377083cd24a|forum:58a377083cd24a] but it increases speedtest1 run time by approximately 4x. Perhaps auto-lock can be combined with the older idle-time-based auto-unlock to unlock such locks (but not those from xLock()) to improve this?
FossilOrigin-Name: 46304ba057707c3b072b6e7bb8c4af774f653aa5814099f0866cd87b2b73abeb
2022-11-10 11:35:10 +00:00
dan 838865c0bb Better handle an error in the fts5 integrity-check code. dbsqlfuzz e87c62f9b67ea21aebdc36ab71cab7cc3eda8dc3.
FossilOrigin-Name: ae43e97087a3207a5ca3ffae75fbe7a33c01f4a38ce0d1d7eed8591ae3083617
2022-11-09 11:17:57 +00:00
drh ea038d3d23 Additional defense against corrupt database files in dbdata.c.
FossilOrigin-Name: 2e70d1e5c9b2c9e068be3ccf8a6062edf7bdde2e46d60ba8ce54eda851af6008
2022-11-09 11:02:39 +00:00
drh 92c0881d9d Increase the precision of the nData parameter to the dbdataValue() routine
inside the sqlite_dbdata virtual table, to avoid the possibility of integer
overflow.

FossilOrigin-Name: 295447b44fc7658891352a9b3f792379b52a76ee5dcfd498b7028f5f87b40e9e
2022-11-09 10:17:25 +00:00
dan 50ba1a0213 Fix a problem with URI formatting in calls to sqlite3rbu_vacuum(zDb, NULL) causing problems on win32. First reported here <https://sqlite.org/forum/forumpost/a7ae915a9d>.
FossilOrigin-Name: 77ccc8ea8a901df64feabe08e1210087d060f0bc133242e87a94a71b68b5b5fa
2022-11-08 20:04:05 +00:00
dan afe768193f Do not attempt to run test script dbpagefault.test with SQLITE_OMIT_VIRTUALTABLE builds.
FossilOrigin-Name: 901918c4867557e51160ef9c495e4e007de26cfe07c237addc00a388662957e8
2022-11-08 19:36:26 +00:00
dan 64c40ec2c7 Fix a problem in main.mk preventing the amalgamation-testfixture target from building.
FossilOrigin-Name: ccf00a0e22a2a9815ff7db1c6c6457fce35aaf50843c1b5ff2adda22d6f70314
2022-11-08 15:49:12 +00:00
drh 80fafc25ce Further improvements to the handling of the u32 and u16 typedefs in the
shell.c source file.

FossilOrigin-Name: 55a19677d723147aeb2b4a86bbd01756ddeb2072cba72c3145ad32d335e203b0
2022-11-07 19:40:20 +00:00
drh d9324a5226 Improve the ability of mkshellc.tcl to remove redundant typedefs from the
generated shell.c code.  This is needed to get shell.c to build on older
C compilers.

FossilOrigin-Name: 3645585f37631d60cefab1d55cdb1ee060aae87317b9b158a01329ca8a4d3e1e
2022-11-07 18:36:02 +00:00
dan 40503750fa Add the sqlite3rbu_rename_handler() API. To override the default routine that RBU uses to rename files.
FossilOrigin-Name: ebbb1f88e7b5d6cbe84d400f1a187acedb4c668d0b7e4c63bf1496e57da9b8ad
2022-11-07 18:00:18 +00:00
stephan 49507d2af6 Minor doc updates in speed-check.sh. No code changes.
FossilOrigin-Name: d2ed4116fbf1de3c840f84e05db6f29f7b489518ac07d56f61df153deab6bf6b
2022-11-07 17:21:53 +00:00
drh 54422235e9 Fix an obsolete comment.
FossilOrigin-Name: e377c0a1ef030395293c5f24d7cb8e5b36ce972e9fac31b99c8425075486a46a
2022-11-07 15:23:51 +00:00
drh e38b6e0318 Fix typo in comment.
FossilOrigin-Name: c3b94d7d4697a5c3983253f6266c544d8037617778a09d491bc12eb13f08ac75
2022-11-07 15:01:05 +00:00
stephan 690d4c545d Add sqlite3.wasm.alloc.impl() as a "public back door" into the low-level non-throwing allocator. Correct sqlite3.WasmAllocError constructor to behave like its usages expect it to and add tests for that.
FossilOrigin-Name: cea8bf9a144d842c4755c3130273524926e8c4831d7f21c4e34d4e8c74109c8c
2022-11-07 13:06:20 +00:00
drh da01757870 Fix requirements marks so that they match documentation corrections.
FossilOrigin-Name: 10d6189d23133006b39ea230045a918483721dd48f5558f77e57e23693097d16
2022-11-07 12:21:06 +00:00
stephan c0a18d6a5a Minor wasm doc touchups. No code changes.
FossilOrigin-Name: 2c448368913a844bdb5e69f8fa3bad91a2b6612ba3b7f3f650dd07b81db25a77
2022-11-07 12:12:27 +00:00
drh 1407458c6f Fix the documentation regarding negative length parameters for
sqlite3_result_text() interfaces, to point out that the length parameter
to sqlite3_result_text64() cannot be negative.
[forum:/forumpost/cf1d043b07|Forum post cf1d043b07].
Comment/documentation change only.

FossilOrigin-Name: 8016507651f377b08deb3a13cc559d56ce6e934c3073a8e63d05fd946b8403a4
2022-11-07 11:19:28 +00:00
drh b36f697b50 Make sure that the recoverStrlen() function (used internally by the new
recovery extension) is 64-bit safe.

FossilOrigin-Name: ea30a6bfc463acce26a4d710e7bf56519ad096ce2fe904ee7e199f5c55068034
2022-11-07 11:05:53 +00:00
drh b819202acf The recoverAssertMutexHeld() function is for testing and verification only
and should be a harmless no-op for production builds.
[forum/forumpost/b4f2c7d402|Forum post b4f2c7d402].

FossilOrigin-Name: d75504710c86af0037ac897106aadffe54955463195ee4dfb2cdfc81d396cbb4
2022-11-06 17:19:34 +00:00
dan f53c0a0d4e Update test file dbpagefault.test to account for the restriction on using SQLITE_VTAB_DIRECTONLY virtual tables from within triggers.
FossilOrigin-Name: 2b68fc8aa35cc69e4d2c26aaebbf3f2b1f1c08d15ca9efcbe5be21d45735d3f1
2022-11-05 19:26:45 +00:00
dan a16edfa29b Tweaks to recover module test scripts to work with various permutations.
FossilOrigin-Name: 454c61e818f6941c9a23f6600e37828a3f2b2ad3c6dbc8d6223570aed5d9cd8b
2022-11-04 18:32:45 +00:00
dan 5f7e173abf Another test case fix for auto-vacuum builds.
FossilOrigin-Name: c1c47eff48e0831b5aed987e90d797aee99caf1861fa8318c6c3ecfb108de7e6
2022-11-04 17:07:33 +00:00
dan 80dbd818f2 Fixes to recover module test scripts so that they may be used with SQLITE_DEFAULT_AUTOVACUUM and SQLITE_SECURE_DELETE builds.
FossilOrigin-Name: 0e5597ce5353dea2cdb092b166b57ba1d60f8115eb468349f2b2869803691a2c
2022-11-04 16:39:39 +00:00
dan ffc9b1b046 Fix Tcl tests so that they again build and run with SQLITE_OMIT_VIRTUALTABLE defined.
FossilOrigin-Name: 06a9dbea40c8a0cdfae6b127a1ce1cba0547acdf1115c087e9b790a78c264b52
2022-11-04 15:17:14 +00:00
drh 881f0f4114 Remove an unimportant testcase() macro that is no longer reachable due to the
improvement in corruption detection.

FossilOrigin-Name: cd7e3568a9b0c0f5ef5ca8a29c55cefe2bbad2dbc88a3718a87bb24a8ada3b7f
2022-11-04 12:59:04 +00:00
dan 4868a86513 Add another test case for the OP_Found fix.
FossilOrigin-Name: 6cdd64a445fe16d547d7bf5ea26dad3ab6d9d5f7d1c2b49fdc9d7a2edaa031c6
2022-11-04 11:59:40 +00:00
drh 093677add4 Enhance the ability of the OP_Found and similar opcodes to detect truncated
index records and report SQLITE_CORRUPT.
dbsqlfuzz 2b12f90aeff8e081706c7e9b58834f04869f446c.  Test cases in TH3.

FossilOrigin-Name: 059a09da2c5fd9c7e723c713565fbaf71602079feef0704129cc5cbbd0033936
2022-11-04 11:54:42 +00:00
stephan c75445087f Correct sqlite3-wasm.c's SQLITE_DEFAULT_CACHE_SIZE (it's measured in kb, not bytes).
FossilOrigin-Name: 479ad980dfe509403e184e39a5aa441171e47b3297e05039f85516e72e9f15be
2022-11-04 09:02:21 +00:00
stephan 7d24ff2971 Add experimental esm target to ext/wasm/GNUmakefile to tell emcc to generate sqlite3.mjs (ES6 module) instead of sqlite3.js. Related to discussion at [forum:ed4596cf8496a39b].
FossilOrigin-Name: e55d8eba83012492d85418dc0faedce5896027ecc70295a5ca1826f61a5edbaf
2022-11-03 22:51:20 +00:00
stephan 4df2ab575f Globally replace '' with "" for empty JS strings to please C preprocessor.
FossilOrigin-Name: e92e1f42bef94a1df29f66b4111ebfde93eba3759bc5d5a9c95f714508851346
2022-11-03 21:21:10 +00:00
stephan de6186e04f Minor build cleanups and fix a harmless race condition in the OPFS part of tester1.js.
FossilOrigin-Name: 70ee6ee014bc4e2c1daa9b4a8909cf76ccecf32de1eb39055f20d3d0b1daa1bd
2022-11-02 14:08:59 +00:00
drh 2cdcc7f01a Clarify documentation regarding the --recovery-db option to ".recover" and
the magic 789 configuration option it is associated with.

FossilOrigin-Name: f6fa0cffa921ccde8910e7fa4a63c2e4ef8ddb376c8ce99e436b27ac332c4498
2022-11-02 14:08:26 +00:00
drh 12de518db4 Minor improvements to API documentation in comments for the recovery
extension.

FossilOrigin-Name: ed1c3515ad6a988e07a8b4583fbc38be257e6eae7443b01a242b98207ce78162
2022-11-02 13:09:14 +00:00
stephan f45c33701d Add sqlite3_wasm_vfs_create_file() to replace Emscripten's FS.createDataFile() in a (mostly) VFS-agnostic way. Add a test for worker1's export (to bytearray) support. Re-add worker1 open-from-bytearray using sqlite3_wasm_vfs_create_file() but it's untested (requires a new interactive test app or maybe reconsideration).
FossilOrigin-Name: b35e1225c91a3cadc0d25af1e4e790237256d194990faa13190e343ed03e11c5
2022-11-02 11:53:31 +00:00
drh faff0410dc Emcc seems confused by SQLITE_DEBUG, for reasons unknown. Use NDEBUG instead
to simplify the #ifdef logic in sqlite3recover.c.

FossilOrigin-Name: 2610779ac84ac4a1a6901b6244653faf0c49ac6f0a4710a19aaf2a13106ae742
2022-11-02 11:25:33 +00:00
stephan c18c8bf957 Fix a symbol name typo which broke and exception-handling case in OPFS xOpen().
FossilOrigin-Name: 5bc83d569594e104e90b1acef1a5fd23655b2089de393a6776e799fdef2082f5
2022-11-02 08:49:05 +00:00
stephan f170b97985 Fix a missing symbol in non-SQLITE_DEBUG builds.
FossilOrigin-Name: 17cdcad627205cdc8ae8114df44ad2a44e59603200efb238fbbb5c30ea0a453e
2022-11-02 08:10:22 +00:00
drh b9f8ff0e8f Fix a harmless compiler warning.
FossilOrigin-Name: 663a89164fdd43529a13cab4b9d9f04fe519e7c6b954f9c91e32e4d7ae25eb46
2022-11-01 21:42:50 +00:00
dan 41dbdae4e2 Instead of (const char*), use a special type - sqlite3_filename - as the filename argument passed to VFS method xOpen().
FossilOrigin-Name: 90df04e5a25907e748227c484b601b7dbd87c037556a0e87f8423f529d08bb6b
2022-11-01 19:35:54 +00:00
drh 6da7cc9b4c Fix harmless compiler warnings.
FossilOrigin-Name: de829770aa0f59b4cd3ab1dc5eec90be82663dca3199c2cf6d97f4c41ce9f799
2022-11-01 18:56:39 +00:00
dan 52d5d474f5 Instead of (const char*), use a special type - sqlite3_filename - as the filename argument passed to VFS method xOpen().
FossilOrigin-Name: bd1fe4de8a2e8b8de19a7f90b9fdafb641ad11a6f0c96c0b4495d5bf80885675
2022-11-01 17:43:19 +00:00
mistachkin 11980a6b8e Fix compilation errors in the recover API seen with MSVC.
FossilOrigin-Name: 78d17c4fedc1629bf161f9858f2b8bf35506155ccaa0acc084b419d244d4f75d
2022-11-01 14:13:05 +00:00
drh dddec5cadd Fix a #ifdef involving SQLITE_OS_KV that was adding code unnecessarily.
FossilOrigin-Name: b6c1b6e4a3bc21c40d6faca6f70842df5201f21c96a076a895410660630461c0
2022-11-01 13:12:20 +00:00
drh be44e188e3 Enforce affinity on materialized tables for subqueries and views. Also,
do not allow UNION ALL flattening if the affinity of a result column varies
between different arms of the compound.  This is a fix for
ticket [57c47526c34f01e8].

FossilOrigin-Name: 88a05141c28e5ff1357c3c599493e4ffb8f3821bab04be80244deac62e49135c
2022-11-01 12:10:39 +00:00
drh dc5e8c63bd Improvements to comments. Change the "optimization_control" TCL command
in the test harness so that it returns the new optimization mask, for
verification.

FossilOrigin-Name: a3a500127d4752ee05c183e9ac97a2bc27768bf7063b04b5c1405cd3fd3931f5
2022-11-01 12:01:10 +00:00
stephan 0f32760e3c Minor internal cleanups in the js pieces.
FossilOrigin-Name: 271391b4e32220ab4c32d69f579ecd2b03eb99da898955a1ef8fffc27216719d
2022-11-01 11:09:34 +00:00
stephan 49048b148e Significant cleanups and expansion of the sqlite3.opfs utilities. Add oo1.DB.dbVfsName(). Add VFS name to worker1:open's arguments and result.
FossilOrigin-Name: 86a341d7e061f946b39e8647ddd4743013b851b33ae9e6e755d8dbc53fba5286
2022-11-01 07:49:49 +00:00
drh b6d9167945 Do not flatten a UNION ALL subquery where the column affinities do not match
on all arms.  Force that subquery to be materialized.

FossilOrigin-Name: 1b8a128832c1633cbb86999d347fef64ac45fe134dac61132112fc97f24676a0
2022-11-01 01:07:29 +00:00
drh 5fdb9a352c Enforce column affinity on the materialization of a subquery or view.
FossilOrigin-Name: b6692de374d7f489d8cf8877bdfef19501bc5ecb0781d42750807eeb58f2e7cd
2022-11-01 00:52:22 +00:00
drh c7dd9b60eb Make the UPDATE method of the sqlite_dbpage virtual table rebust against
OOM errors.  [forum:/forumpost/bbcf0dd6ca|Forum post bbcf0dd6ca].  Test case
in TH3.

FossilOrigin-Name: d15c9a4a323b825eb80e706e12e9df95e5db458024f51e6e537940efc8234d8b
2022-10-31 18:01:05 +00:00
stephan 02d15a7ebd Worker1: use a list, rather than a single slot, to manage the default db link so that we can keep the least-recently-opened db as the default. Re-introduce worker1.export() but do not yet expose it until an equivalent import() (or open() option) is implemented.
FossilOrigin-Name: c7750c101d9b7baa31496731bc34ea0a9b2bad0c11e2b3e92a8c7b327135c1bb
2022-10-31 13:50:05 +00:00
stephan 43b442a626 Internal tweaks to the OPFS VFS result codes.
FossilOrigin-Name: 32e1a2d2eb8738ae1635e413829f6cf7f64c63d2a86b72940a573de89948e529
2022-10-31 11:53:34 +00:00
stephan 1acfe91582 Add oo1.DB.exec() 'returnValue' option, which specifies what exec() should return. Defaults to the db object and enables direct return of the result rows array or a list of the individual SQL statements. Other code-adjacent internal cleanups.
FossilOrigin-Name: 69d36a6aa5e2cd79d26c0fd3e0d20fe8838fd1be97db07725233bfff1dfe6643
2022-10-31 11:09:14 +00:00
dan 549907fd67 Avoid a segfault that could occur when running the recover API on a database handle with memory-mapping enabled.
FossilOrigin-Name: e02c697281a777c33070168af784b2d291397e488244a217620897f40aed7158
2022-10-31 10:53:23 +00:00
drh 1e84e1e632 Extra OOM check in shell_error_context() of the CLI.
[forum:/forumpost/5708841db0|forum post 5708841db0].

FossilOrigin-Name: cb12ac5de17e677f089d7b0b46803efbd9a9178972ffb0454a8b557b06633658
2022-10-31 01:22:38 +00:00
stephan 50ef01398d Add oo1.DB.selectArray() and selectObject().
FossilOrigin-Name: 7660db2a2e9c4f3a6a9343d6929744ad0f4be6820976411f9080165491da59b7
2022-10-30 11:39:47 +00:00
stephan 9163ef1f4d Adjust automatic OPFS locking retries such that they will wait up to a total of 3 seconds spanning 4 attempts.
FossilOrigin-Name: bbce49d81abc491ca666474040a53057e26e99131fea9449de253f88f4415ded
2022-10-30 10:24:53 +00:00
stephan 1fc6ffccc5 Minor WASM build cleanups. Enable custom Module.instantiateWasm() when not in WASMFS mode (where it doesn't work). Add sqlite3.debugModule URL param to enable some module-init-time debugging output.
FossilOrigin-Name: 50f678846a2b3c3d0818f0bae89f2ee86252a2e6a9c7029ebaae3953ca0fa14c
2022-10-30 09:47:33 +00:00
stephan af9cee12c1 Reduce wasm module's starting memory from 128mb to 16mb. The latter value is needed only for WASMFS-based batch-runner.js, as WASMFS builds cannot be configured for dynamic memory growth without a tremendous performance hit.
FossilOrigin-Name: ed9d93c48752ba6e18edc1238a8ccdbf6bb65c74fb52a89d515f8b0ab6bea13a
2022-10-30 08:39:18 +00:00
mistachkin f5e7691e2b Minor updates to the Windows batch tools.
FossilOrigin-Name: b42f56205fa8e06431fb1a45c48257d93605fea0ed95bd766f71e27292d1af33
2022-10-30 07:01:31 +00:00
stephan 1cc77c9543 Update ext/wasm/README.md for recent developments.
FossilOrigin-Name: c76ec31ebf4d80ec8cbd2aa2017e1d6bc32eae66bfbcc130c053ddb403599c6b
2022-10-29 12:31:50 +00:00
stephan da27e4aa02 More styling of module-symbols.html.
FossilOrigin-Name: a36f42a8364b745c410a6f837d005a193f6a93134cac087ac18bee2897cad730
2022-10-29 10:14:56 +00:00
stephan df52a0bc78 Expand and document the wasm doc-update make rules. Extend the dist rules to fail more readily if there's a problem.
FossilOrigin-Name: 362ec11ec09f441b745cbd8ac8366b6bc998aba6e2b70782a88f189a3ffa9923
2022-10-29 09:45:01 +00:00
stephan 8948fbee29 Move the sqlite3.capi.wasm namespace to sqlite3.wasm. This causes a tiny bit of naming confusion with the sqlite3.wasm *file*, but seems to make more sense than having it as a sub-namespace of capi.
FossilOrigin-Name: 3f16eb18d6186ca972fca952ccac18649e7a905213f589e53c0c9333e695448d
2022-10-29 07:54:10 +00:00
drh 053bb22f35 Fix harmless compiler warnings in testing code.
FossilOrigin-Name: 2f53612388507f9b1ecbec3c15281825beab54b8062d97d0ab6f009c5fed347b
2022-10-28 18:52:05 +00:00
drh 71b65e88e8 Add sqlite3recover() support to fuzzcheck.
FossilOrigin-Name: e65c5bdc5bd6e1989c3de59798ff0a761125fc490fdec8c7671ca70ed688c4f8
2022-10-28 18:35:06 +00:00
stephan ffbc653d85 Remove sqlite3_interrupt() from the WASM build, as it is essentially impossible to employ in JS's threading model.
FossilOrigin-Name: e85387590061edbb6cdc04de792ab86f43afaa5c8d1b0792206cb5b481c7d76a
2022-10-28 14:33:50 +00:00
stephan f03ddcca32 Add ext/wasm/module-symbols.html. Adjacent minor JS touchups.
FossilOrigin-Name: 24f12e681e06e3b71a6ac9c82255fe0270953a74c711405841f7e385eeafe874
2022-10-28 11:40:46 +00:00
stephan e681b651eb Minor sqlite3.oo1 API reorg prompted by documenting.
FossilOrigin-Name: 55237924ca363c5a3e0f8c82620eb6626a98311615866197375a86876b9da3a1
2022-10-28 10:36:18 +00:00
drh c97bb14fab Fix a minor problem with sqlite_dbdata.
FossilOrigin-Name: 58c2e49279c8f77f006b0c2ce351776bc711633f9c1a39c7a37969838d49ec0b
2022-10-27 23:17:49 +00:00
dan 676d1cda92 Fix another crash in the recover extension triggered by a corrupt database.
FossilOrigin-Name: d125377378916fb3147612a536fde15ee955176eea9ea6eaa4a2ee5f1e8e1cbe
2022-10-27 20:27:45 +00:00
dan 10f5525410 Fix another problem to do with recovering from in-memory databases.
FossilOrigin-Name: 5a7bfd4a217cd80882a1827674b479cdc547419a785e06e0ee82cb8cfca42701
2022-10-27 19:06:42 +00:00
dan ac16a4716b Ensure that the VFS wrapper in the recover extension does not attempt to invoke undefined methods on the underlying VFS.
FossilOrigin-Name: 347c575108bc8112613a02afda1247bdbed24c15def7eb412d0b27aba047715b
2022-10-27 19:02:51 +00:00
dan 895f12dfe7 Fix an assert() failure in the recover extension triggered by a zero value as the first page-number in an overflow page chain.
FossilOrigin-Name: 44c0874c33e76ce708022e5c38c74f75565a8cea9f4c5b067cc0a54079aeee20
2022-10-27 18:35:09 +00:00
drh 4853aa18f0 In the CLI, ensure that input to utf8_width_print is not NULL, or if it is,
change it to an empty string.  For for the problem reported by
[forum:/forumpost/2961cf13eec61876|forum post 2961cf13eec61876].

FossilOrigin-Name: 9ecc9d25ea62a7777bbf621989a5c577b612784121a20465cda4d4023fa9634d
2022-10-27 18:20:08 +00:00
dan f7fea5b4b8 Change the name of the ".recover" command option "--freelist-corrupt" to "--ignore-freelist".
FossilOrigin-Name: afce8443ace57c3c99c6810be98f05ed716ae504b68098726c869843c643bbf0
2022-10-27 18:19:45 +00:00
stephan 674b312ed7 speedtest1.html: when vfs==kvvfs, increase --size from 2 to 4, as enabled by [a4d40f6346e7]. --size 5 is 4.96mb out of (supposedly) 5mb, which works but is a bit too close to the edge.
FossilOrigin-Name: a608d584a8a68ebaf8566cffc9c33f59309b710e7b29229a15bef529702f35d5
2022-10-27 14:41:38 +00:00
drh fd6080637c Automatically set temp_store=MEMORY if the VFS is kvvfs.
FossilOrigin-Name: a4d40f6346e7eb2a5239684dba86f297358122768a4d4bf6786b6028f4300e04
2022-10-27 14:28:15 +00:00
drh 9c17ee4f93 Do not accept a NULL pointer for the filename in KVVFS.
FossilOrigin-Name: fdecbd3b5bcdeb358015f461ac6c863f12ab180ab4624ed50734e41e557d8186
2022-10-27 14:00:21 +00:00
drh f7b58da831 The kvvfs VFS should remember the page size when writing to the database.
FossilOrigin-Name: fc5503c8acb085042e877c9de43256a4fee27f63ab35e2ddad18e40734ed00d4
2022-10-27 12:46:17 +00:00
stephan bb5136e5cb Re-enable the .recovery and .dbinfo commands in shell.c.in in the fiddle build, as those were fixed by [3d20d77a3511] and [cd0aa27d1732].
FossilOrigin-Name: ba3a7a4a9997f62b78467d78d95fa5b58a03ecb2e2ccb68f4d316fc08fd02f86
2022-10-27 11:32:20 +00:00
dan 340b1d1a71 Do not use sqlite3_result_text16() in the recover extension if SQLITE_OMIT_UTF16 is defined.
FossilOrigin-Name: 3d20d77a3511bb223474da8491e1da8aec098c41c1b81ab78ff80fbd37d5b568
2022-10-27 11:25:08 +00:00
dan 48a4a4b73d Fix a problem with running ".recover" on an in-memory database.
FossilOrigin-Name: 87b4cca2b84845cee603d40fbf16c9635d6dc2d19d2f37ae86abfeff716c9a85
2022-10-27 11:12:54 +00:00
dan 21fd7ce098 Do not use sqlite3_mutex_xxx() functions in sqlite3recover.c when built with SQLITE_THREADSAFE=0.
FossilOrigin-Name: cd0aa27d1732abc61c8a8440118ff629f7dca185d2f515ce1f6090c49d8dc890
2022-10-27 10:51:49 +00:00
stephan 4f975c3379 Minor doc typo fixes.
FossilOrigin-Name: ed8d3f25a4d6ac04d9f7918c791d8d2c6f23ce846278ca63f8fbadb7ea27369f
2022-10-27 03:57:48 +00:00
stephan 3d420836fd Restructure and simplify the feature-detection #defines of the recovery support in shell.c.in and disable it when building fiddle because it uses features we elide from the wasm build (e.g. utf16), leading to link errors.
FossilOrigin-Name: ddd10c05c5d16d7205c347c5c1e73a75faecb2b7ec88a4a15875856765e1b143
2022-10-27 03:56:01 +00:00
stephan de868175c3 Expose sqlite3_randomness() to WASM and add a custom binding for it which can populate a JS byte array. Add WhWasmUtil.isPtr().
FossilOrigin-Name: 333e67076b4bc967bb543ef8e265c63f6e3498c38ac121a7d1eff4a1d7a71c63
2022-10-27 03:03:16 +00:00
dan 195687f1bf Disable the push-down optimization for sub-queries that are INTERSECT, UNION or EXCEPT compounds. dbsqlfuzz a34f455c91ad75a0cf8cd9476841903f42930a7a.
FossilOrigin-Name: 346a3b12b861ce7ba369e98cd336f79a1d4f7a7bb9acd7a4f63f37b391755bf5
2022-10-26 21:14:21 +00:00
drh 07dd481010 Remove an unused variable from the recovery extension.
FossilOrigin-Name: a029dddff4f4ed7275538610cbd9cea658b905b72924860ec9cda9e76dabcfac
2022-10-26 20:12:46 +00:00
dan 387f468591 Add the "recover" extension in ext/recover/, for salvaging data from corrupt databases.
FossilOrigin-Name: a820792548da596ed0f8ab3fd1c04ec16647abbe51a2a5aac9e17c4f58be6d97
2022-10-26 18:41:12 +00:00
dan 50632afa6e Remove an undefined left-shift operation from the recover extension.
FossilOrigin-Name: a67082357a2cc348faf8236aafa7f39eb5cb673b1d114a594c6d5bb257f85b73
2022-10-26 18:29:19 +00:00
dan 5ad03a486e Merge further changes from trunk, including fix to dbdata.c.
FossilOrigin-Name: bcf6b48d52c1ce656899f50bd508c0920cae8cf2ef3c0758a7633981f0f0f484
2022-10-26 18:22:22 +00:00
dan 8364ce2aa2 Make the shell .recover command and the dbdata.c module more robust in the face of corrupted databases.
FossilOrigin-Name: 4eef562a00ae988f2426c9af51f4165c0e4cbccd601061664a0c54c19b9cc70f
2022-10-26 18:04:34 +00:00
stephan 8c3e234ad5 Correct misuse of localhost-mode-only symbol S in fiddle-worker.js, which should fix the outage reported in [forum:67d985ac0bbe407f|forum post 67d985ac0bbe407f].
FossilOrigin-Name: 3b5aa50c223ac35c7d73e4629420a01408cd74d19ae5b887f91b7a657d91e026
2022-10-26 15:40:17 +00:00
stephan 7731dfca49 Corrected link to fiddle in ext/wasm/index.html (broken by [3d7b4f36b7dd]).
FossilOrigin-Name: 6efa0bae1678bf719a0693feeceb4c1e252fc86502bee9ee2a6d8af9a91d9b20
2022-10-26 15:34:51 +00:00
stephan 34b92b19f3 Replace the newly-removed oo1.DB.getFilename() with DB.dbFilename() with the hope that the distinction from the dbInstance.filename property is clearer.
FossilOrigin-Name: 0b80543d75504c733b73b32f73b96074a4b0cebad64e47032926a3fefee41726
2022-10-26 11:27:33 +00:00
stephan 14ae1a5331 Remove oo1.DB.hasFilename() and getFilename(), as they are unnecessary.
FossilOrigin-Name: 75c546b982024bf2b527c85271111d54158cb010867f6e29fc89e86cc8457cc5
2022-10-26 11:12:14 +00:00
drh 705d7be62d Remove the sqlite3StdTypeMap global constant that was made
obsolete by [aa6e908619624867].

FossilOrigin-Name: 3dfdfb3f12edb3f4267942598efd05d573e13b7c5d6cdbc3404373f41b8993dd
2022-10-26 11:11:31 +00:00
stephan 419e0d3e09 Add --download-version flag to ext/wasm/version-info.c and correct dist target's output version format to match.
FossilOrigin-Name: 6f2a40d06dd9a56491d27928ed3785e08308c7dcea2b3f768097fc98ba91a910
2022-10-26 06:05:44 +00:00
stephan e896ba94e3 Add doc page link to the wasm dist README.txt.
FossilOrigin-Name: c2380668d9a2ad04f6f27ef052190bda17cdb112895e93b94ae1da70db6983c8
2022-10-25 16:57:42 +00:00
stephan 4831f4e0f1 Correct -O level for fiddle build when built from the top-most directory (-Os instead of -O0).
FossilOrigin-Name: ff4fc29c38b78dfd471e25942304cba352469d6018f1c09158172795dbdd438c
2022-10-25 16:04:44 +00:00
stephan ce2d4ae6a6 Rename fiddle.html to index.html and move fiddle push-to-server rules from GNUmakefile into fiddle.make.
FossilOrigin-Name: 3d7b4f36b7dd01058d57fc8ef7689d9bbf1a219166796ed427180cd59d2c189d
2022-10-25 15:59:27 +00:00
stephan 16603ecfcb speedtest1: use the current (or default) vfs->xDelete method to unlink the db. This is specifically necessary when running the opfs vfs in a wasm build of speedtest1. This worked without this fix until recently because the affected test code was performing similar acrobatics in its stead.
FossilOrigin-Name: d3c830bd37a402161b486d3631feceae5d00f89c2522aed65fcd2e666bd64238
2022-10-25 15:38:38 +00:00
drh 42dddb97de Enhance the sqlite3_strglob() and sqlite3_strlike() interfaces so that they
will do sensible things with NULL string pointers.  This is an extra layer
of defense against bugs such as reported by
[forum:/forumpost/730b554179|forum post 730b554179].

FossilOrigin-Name: 8ba9c884bded52e3e044ff39c826c04838e7c31f05d802f4a14d9ce5a01ab721
2022-10-25 13:44:18 +00:00
drh d5ca2c4b3d Make the ".dump" command of the CLI more robust against malformed databases.
See [forum:/forumpost/730b554179|forum post 730b554179].

FossilOrigin-Name: 0573edfb9e0b1fd51e8da20592c71b02040968c33fdec41c31a6b1b7d3e83262
2022-10-25 13:42:10 +00:00
dan 5f726694eb Merge latest trunk changes with this branch.
FossilOrigin-Name: 757e3f585959f4f113fee48fe3d504f037604c53a95c8d47ce5c2bccfb2af8ff
2022-10-25 11:05:31 +00:00
stephan 89954fe7ce Minor doc tweaks in the JS GNUmakefile.
FossilOrigin-Name: 9c8df130b8137cb4705f805907d1ff754d7f4b07bf181e1d05f1798b7aa5f4f6
2022-10-25 08:41:00 +00:00
stephan d3c8f2ac33 Remove persistence from the 'reverse log order?' checkbox in tester1.js to eliminate an inconsistency between the main-thread and worker-thread modes (the latter having no option for persistence of that setting).
FossilOrigin-Name: ecf906b07f50b4fcc551d20326a1bb1189bd6c2274627fd293f9460658ebea07
2022-10-25 08:15:57 +00:00
stephan f861b36bf4 Minor cleanups and doc improvements in the OPFS sqlite3_vfs proxy.
FossilOrigin-Name: 48645f7bcacf81c4149f26d20ee1752fbe93a02f96b85bd7e28bfa49322137e5
2022-10-25 08:06:17 +00:00
drh 7704a535d0 Fix typo in comment.
FossilOrigin-Name: f65c95658fe4d30817da8de7eb88e823ea1cd8be40e347d626870bad3cc13359
2022-10-24 18:42:45 +00:00
drh 99a37ca779 Add a comment to a previously undescribed member of the Walker union.
FossilOrigin-Name: 69d704224e9ed022fcec591beff2ffcc4daf3e7fc586debfdcf00b25c1fddd87
2022-10-24 18:33:50 +00:00
dan 80b30f995e Use the same "PRAGMA synchronous" setting for the output of a "VACUUM INTO" as are configured for the database being vacuumed.
FossilOrigin-Name: 86cb21ca12581cae9a29f42ba707bd9d789e667e5ddc0f64b24940d5d5c9a118
2022-10-24 15:51:24 +00:00
drh 4073706a47 Improve the ability of the query planner to recognize covering indexes even
on tables with more than 63 columns and where the index is over columns
beyond the 63rd column.

FossilOrigin-Name: f058773e41495ddbae698f9e9a4f62b7003112ea8614dfad69471340058735e4
2022-10-24 13:20:48 +00:00
drh 2d75c1aa3d Update the fuzzinvariant logic in fuzzcheck to the latest code from
dbsqlfuzz.

FossilOrigin-Name: 739ad584765f1fc0eb196db870785da1726805cc2d9dd0a831a37a9e55a4afe9
2022-10-24 12:38:32 +00:00
drh 1f41a8c8a7 Fix built-in documentation for the ".mode qbox" command in the CLI.
FossilOrigin-Name: 3d7ea33be1076fd21681bdcff0c489646c017594b42b4a21a74e9e2d3947890b
2022-10-24 11:10:40 +00:00
drh 89b373ab28 Test cases for covering indexes on wide tables.
FossilOrigin-Name: 64c3777eb356b15094a9e9fcc135499ba22f4d847fb117afa6ccf19986e33585
2022-10-24 11:02:02 +00:00
drh 7d913e9aae The wide-table covering index detection must take into account aggregate
queries.

FossilOrigin-Name: 9ac73f83c53b9fba10bb1b8bbfd1a8dc8a2dc4a655e811d5b96335dbf2b6fdac
2022-10-23 20:09:13 +00:00
drh fb643592fe More frequently send the complete SELECT statement into sqlite3WhereBegin()
so that it can more accurately determine index coverage.

FossilOrigin-Name: f6d09c5a0df940dbaa716df70df28218985b83540b34c468989729a3421ef38c
2022-10-22 23:09:29 +00:00
drh 54cc766b41 Enhance the query planner with the ability to discern when an index is
covering even when it indexes columns well beyond the 63rd column.

FossilOrigin-Name: 1390417be45dd84e9118f6e761f23b8ff7476d26411e165bbaab678881e4eadd
2022-10-22 20:13:46 +00:00
drh f55a7dad19 This branch attempts to improve the detection of covering indexes. This
first check-in merely improves a parameter name to sqlite3WhereBegin() to
be more descriptive of what it contains, and ensures that a subroutine is
not inlines so that sqlite3WhereBegin() runs slightly faster.

FossilOrigin-Name: cadf5f6bb1ce0492ef858ada476288e8057afd3609caa18b09c818d3845d7244
2022-10-22 14:16:02 +00:00
drh 5723c659fd Clarification on the meaning of SrcList and SrcItem and especially the
SrcItem.colUsed and Index.colNotIdxed fields.  Comment changes only - no
changes to code.

FossilOrigin-Name: d96f6cc8475ae5509b8bff2db75e3c6f69a214d58d8979fbc0162ae488a040dc
2022-10-22 13:49:35 +00:00
stephan 3725af73b9 Add SQLITE_DQS to the compileoptions_used list, per request in [forum post 8b1060122b|forum:8b1060122b]. Force DQS=0 in sqlite3-wasm.c.
FossilOrigin-Name: fcd9e0dbe3226f3f7ccc15b11fc3aa3b8058571bef274c25a33e9753e22f7551
2022-10-21 17:48:49 +00:00
stephan 89ccfac0ac Macro name typo fix in OS_KV builds.
FossilOrigin-Name: 9cf1142b0cdb13347e3f551c862cb4714cadfe5ad637f049cf0a4b8bb6125b32
2022-10-21 17:37:05 +00:00
drh de033d078b Ensure that the RtreeCell object in rtreeUpdate has all bytes initialized.
FossilOrigin-Name: 1e38742bde09cd879eb370bcf8604ed7ed00759209bcb4ed0374350e4b9e842d
2022-10-21 17:18:58 +00:00
stephan 98147dd526 Add kvvfs tests to tester1.js. Fix a scopedAlloc() misuse in oo1.DB ctor caused by refactoring earlier this morning (and caught by these new tests).
FossilOrigin-Name: 8e0f001ab76de6dbc17295b9085f7f61ce274c43f8c432ea4d2ec3153d248ff3
2022-10-21 06:58:27 +00:00
stephan 848d27ada1 Add timing info and OPFS sanity tests to tester1.js
FossilOrigin-Name: 99915b0076422487cdd181a54e55694404fba13e4a540329b5ede9e2c9e12532
2022-10-21 06:26:17 +00:00
stephan a6ca996e4a Expose sqlite3_vfs_unregister() to WASM and unregister kvvfs in Worker threads to avoid its unintended use there (in contexts other than local/sessionStorage). Correct registration of window functions, extend oo1.DB.createFunction() to support window functions, and add window function tests to tester1.js. Correct an incorrect 1-arg handling case for DB.exec(). Add per-test assertion counts to tester1.js.
FossilOrigin-Name: f07ce15479b7224b0d1ba9f147a433136e70c1461aa667d2737d4a918f778f55
2022-10-21 05:27:40 +00:00
stephan 6f3286cafd Make semantics for UDF xFinal() result handling and error reporting handling more flexible.
FossilOrigin-Name: 89f3e1982ec32c010af67d15ef780847df20de568669e5c9d02f3cf084f51330
2022-10-20 23:48:38 +00:00
stephan 96b6371d70 Add more JS tests. Flesh out the aggregate UDF tests to use sqlite3_aggregate_context() so that they can each be used multiple times in the same statement. Add sqlite3_js_aggregate_context() convenience helper.
FossilOrigin-Name: 9d034ef5e1bab7c9651c2450dc85765fa6365d3f1414c711550de858ff8b3ece
2022-10-20 21:28:31 +00:00
stephan 875b95d4f5 Apply magic.txt correction and addition reported in [forum post 2d2366a04a0385|forum:2d2366a04a0385].
FossilOrigin-Name: 9bf26e2aa3579f354ed2d314e1bf3e3ef117cbd71500ef5f76caa1de5cce1edc
2022-10-20 18:58:14 +00:00
stephan 8a8244b5c1 Rename sqlite3_web_... to sqlite3_js_... Document the worker1.close.unlink option. Fix unlink usage in speedtest1.html. Minor JS build cleanups.
FossilOrigin-Name: ac9af71b72a749b0a040273a88480d56f49570b569389a4ea20cc055f494d8ff
2022-10-20 18:31:32 +00:00
drh c046f6d4d9 Add a bit to the optimization disabling mask for the indexed expression
optimization.

FossilOrigin-Name: 56df1482ab45d4d41f937b27c5a877b52fa082bfc6809ea682b62b47a51333de
2022-10-20 16:30:05 +00:00
dan 7e089d0c40 Add test case for previous commit.
FossilOrigin-Name: 535867a9c8719358380f89fd80473c484def9bb72744dd2fd28ada65999ee901
2022-10-20 16:22:39 +00:00
drh e180564028 Only enable the bMaybeNullRow flag on IndexedExpr for an index on an
expression, not on a virtual column.  But do enable it for the right operand
of a right join.

FossilOrigin-Name: a9657c87c53c19228a42559c82c54b504a5ad729e407e9e2c7dabcc0c949b261
2022-10-20 16:12:02 +00:00
drh 63b3a64ca6 The generalized indexed expression optimization of [2435112867fbd7b6] makes
the prior [a47efb7c8520a011] enhancement from 2017 obsolete.  This check-in
removes the older optimization.

FossilOrigin-Name: 56442c9bdd7844454c79acf83323380ea3509cb2e0b9a3d538a6b51726ae6d07
2022-10-20 13:36:32 +00:00
dan 9b6a28330b Fix minor problems in test1.c test code.
FossilOrigin-Name: 6e545e2b846795fc67f8a90c04de284861a8a429ac686a7476b41c8ed7aabf75
2022-10-20 10:46:17 +00:00
stephan 842c5ee849 Rework sqlite3_wasm_vfs_unlink(), add sqlite3_wasm_db_vfs(), update some docs.
FossilOrigin-Name: cdd46858f0e63bc7bfce8e339b3db9efdec43b6443ee76563a847f53d0176831
2022-10-20 05:14:37 +00:00
stephan d89a66ec36 Minor internal JS cleanups.
FossilOrigin-Name: 818ef0b5c909e733b643455278f7cc45533178f1cc6617058c00ed64fa44896a
2022-10-20 04:00:05 +00:00
drh bf70f1bd1a In the CLI, never use strcmp() or strncmp() directly. Instead use
wrapper functions cli_strcmp() and cli_strncmp() that work correctly even
if the input is a NULL pointer.
[forum:/forumpost/142b868da7560d0b|Forum post 142b868da7560d0b].

FossilOrigin-Name: 7450a561f8577c3ee41f84074c6ef39e29e56876cab4fd763e6489c66f603223
2022-10-19 18:04:42 +00:00
dan 361fb98b5d Move file /ext/misc/dbdata.c to the /ext/recover/ directory.
FossilOrigin-Name: f6d5ac807efcf6140016a8b8f0c74566c0bfc98ad92bd8fca03c5cc80ebf3dec
2022-10-19 18:03:39 +00:00
drh 3b88065d35 Fix references to "SrcList_item" in comments as that object has since
[bfd5bf2c73110fcb] (2021-02-21) been called "SrcItem".  Comment changes
only.  No changes to code.

FossilOrigin-Name: e3648a07f5607dbd4d6ad5b6e5a62a4a1d0b173d3f22aa36c74b768281fc86d8
2022-10-19 11:58:24 +00:00
drh 805055f734 If a query uses an index where one or more of the columns of the index is
an expression or a virtual column, and if the corresponding expression is
used elsewhere in the query, then strive to read the value of the expression
out of the index, rather than recomputing it.  This is the
"Indexed Expression Optimizations".

FossilOrigin-Name: 2435112867fbd7b6ebb7f2c2b9da57cdf1e23fab6c2869870b66133a9f9faedc
2022-10-19 10:56:05 +00:00
stephan a817b30f0b Update the wasm/js 'push' rule to account for this morning's changes.
FossilOrigin-Name: c4a0f745fbaf6f950810f92765cbe66dde66e226b78ec5dd9017473bf4c9c268
2022-10-19 07:51:12 +00:00
stephan fd31ae3bf9 Rename several demo/test files and include more of them in the end-user dist archive.
FossilOrigin-Name: 9c85835f6f50eb3b1a2b89c817816335743f04440c48bfa05aa89ec519cc0d51
2022-10-19 07:34:36 +00:00
stephan 9dc4d5e6b4 Minor wasm/js build tweaks.
FossilOrigin-Name: bcbee1ec010ae74f0749aa7fda008698198a8cd52a7aa12d6458d43d3e739eb0
2022-10-19 06:14:24 +00:00
stephan 3117dc60e3 Update the dist rules for this evening's js/wasm build changes and include an index.html specifically for the subset of apps included in the dist archive.
FossilOrigin-Name: a0ef0f32e96638b502b3951e524d590bdfb09dd39be453686b075102da67b7db
2022-10-19 06:06:42 +00:00
stephan cd0df83c15 Apply considerable acrobatics to get the JS/WASM deliverables building to and loadable from a directory other than the one which contains the app-level code. Requires an only-slightly-leaky abstraction of passing a URL argument when loading sqlite3.js but provides much greater flexibility in where the JS/WASM files are located.
FossilOrigin-Name: 6d468dab9eb84d4548f68014959f02fe4f66455472ff24fe729382bb2972e3d1
2022-10-19 04:44:58 +00:00
stephan 71de8e0241 Considerable wasm/js build cleanups and reworking. Remove wasmfs builds from the end-user deliverables and disable the wasmfs build by default, per /chat discussion, as it doubles our deliverable count for only marginal gain. Attempt to move the sqlite3.js/wasm files into subdirectories but rediscovered that that breaks loading in Worker mode because URI resolution of the wasm files differs depending on whether the main script is loaded from a script tag or a Worker.
FossilOrigin-Name: 5b23e0675efdd2f1ea7b4f5836a579e8d6aa8a25b3f1a6a950520ad845ff01bb
2022-10-19 01:07:30 +00:00
drh 72ab366192 If a virtual column whose value is constant gets indexed, do not include
that column in the IndexedExpr list.
dbsqlfuzz 59ac17a99b9a5c4930ee71cc153c9428a0c0e794

FossilOrigin-Name: c21eb903f06a16d4fafa5f895be08414fa58e6a91c148030aec8676b40c2d66d
2022-10-18 22:37:07 +00:00
stephan b5e2e6fcd3 More work on the JS end-user deliverables. Add tool/stripccomments.c to support that.
FossilOrigin-Name: 2156f0744acfe425457430a0f6a7e02de907de85edba81a6d4eef40293e561c8
2022-10-18 20:36:50 +00:00
drh 7a2a8cee5a Improved byte-code comments for the OP_Column opcodes used by the
indexed expression optimization.

FossilOrigin-Name: bf6d837fddbf74d5b3f40ad01ea4564edfac00b651d6f3f0e996cc5dc18bb06c
2022-10-18 20:27:02 +00:00
drh a331cf7e57 Fix the indexed expression resolver for generated columns so that it picks
the correct table in a self-join.

FossilOrigin-Name: 54c3eb085aca92da2b819f3532ee4750b377265f7e1e914600ea3c3d535efe51
2022-10-18 16:47:41 +00:00
drh 9489e0a5d7 Merge recent trunk fixes into the index-expr-opt branch.
FossilOrigin-Name: 6198ab4b871c464448ae303072bde0a810cac566a516cc29b1bf806fbd0a6c7b
2022-10-18 16:32:22 +00:00
dan ac79fa1c78 Add new test file windowE.test, to test the window functions modules response to an inconsistent collation sequence.
FossilOrigin-Name: 740a2eb0928d54fdf735a8e573c6a61a34dbd295b46e5b6ef39e957fd2623293
2022-10-18 15:02:08 +00:00
drh 0e522c068a Correct sort order for serial-type 10 entries in the database file. This
is a continuation of [4fb77e96fa89a23a].

FossilOrigin-Name: 904b54625d985e742888e06ba792cab316b9ec9d6669d9cf509bac48030373ca
2022-10-18 13:27:31 +00:00
drh 451393c4f4 Merge trunk fixes into the index-expr-opt branch.
FossilOrigin-Name: c7b9cc645b394a1b638a9a13ca83d321215aaa78d69ca70c6baa0ee692ed21bf
2022-10-18 11:28:33 +00:00
drh 43fce6bb0d Fix sqlite3VdbeRecordCompareWithSkip() so that it sorts the internal-use
serial-type of 10 together with NULLs.
dbsqlfuzz 5ff35e9d49a5fcca5051e23960ff2f483a538bab

FossilOrigin-Name: 4fb77e96fa89a23a9365320c4190834edd6c09cfaf1ca30b34ce19b747ebbec0
2022-10-18 10:27:06 +00:00
stephan ce152a4369 Add ext/wasm/README-dist.txt, intended to have been in the previous checkin.
FossilOrigin-Name: c9080b6505b839cc0bb5bd25ce7df0daa91a0a303d037ffe6e77888c8584b932
2022-10-17 17:36:11 +00:00
stephan e79a0943ed Initial draft of archive generation for the wasm/js deliverables.
FossilOrigin-Name: f6cee114c71e11ca1f508c8f60be5753871cbd4fd6c45ce397824bddbf00ffd9
2022-10-17 17:34:41 +00:00
stephan 1b8c246799 Repair version-info.c after a local mishap caused all of the intended edits from [36e197cb3d0c]/[e9b407a4d0a0] to get deleted before checkin. Simplify version-info build (only requires sqlite3.h, not the library).
FossilOrigin-Name: 6e511df500c63e27f932be9d601b641144562614dead99371477eca4594fb3fd
2022-10-17 16:47:59 +00:00
drh 79b99b09fa Merge trunk changes into the index-expr-opt branch.
FossilOrigin-Name: a1485ce6c8374135290eb0a1e4eb4e225497ad7096847a4e2377c9c054946ca7
2022-10-17 16:31:55 +00:00
drh 8be8924901 Fix a potential call to strlen() with a null argument in the command-line shell
following an OOM error. [forum:/forumpost/9c4f2ebe22|forum post 9c4f2ebe22].

FossilOrigin-Name: b6413a6dff8ac9b7088b1381afbbbf799e376455d11786530cc5fc825747ab53
2022-10-17 16:09:33 +00:00
stephan cdc9ddc6ec Missing file-rename for the previous checkin.
FossilOrigin-Name: e9b407a4d0a0fcd9f26d457beede19d41141327befe84be621681952be5d1e69
2022-10-17 15:53:16 +00:00
stephan 0467b01a1f Rework ext/wasm/version-info.c to make it more useful for the upcoming dist build rules.
FossilOrigin-Name: 36e197cb3d0cbb76e4c1381d77f7d8856e7391f2ef6671c13b9b6b0133315814
2022-10-17 15:52:12 +00:00
drh e70d458340 Improved comments and function names. No logic changes.
FossilOrigin-Name: 8f460b3b15bf4b88a224907d2f83e4ed6bf84d6b3f480008a1b187ea49c6ce1d
2022-10-17 14:46:39 +00:00
drh 08535840c6 Get the indexed expression optimization working for virtual generated columns.
FossilOrigin-Name: 8a510cb0880349370ad19b0852f270ca072bff7871f0dc272964af31c32a7c37
2022-10-17 14:30:01 +00:00
drh 543c368958 Merge trunk enhancements into index-expr-opt branch.
FossilOrigin-Name: 56ef97e64efb84176df570819474901d492209ff80ce4355ff896dea9d2b8a51
2022-10-17 14:29:04 +00:00
drh ce4b0fdf8a Make use of alloca() in wherePathSolver() when SQLITE_USE_ALLOCA is defined.
FossilOrigin-Name: 45752471521f8d4a6cad4bce40f907018acd403ffd3b8170020c34e4e0b6b91b
2022-10-17 10:15:41 +00:00
drh 135c9ff6f7 Remove a use of alloca() that does more harm than good.
FossilOrigin-Name: 2ab3cf4d71b23a4c0b69f977828d82df7bbc080c29ae189e0d78d38efee50c96
2022-10-17 09:56:51 +00:00
stephan e493f8f0cd Typo fix.
FossilOrigin-Name: 650126c92aa191d6361a32ec90ca7def60a2df22ba6bec1d2354692fe3504423
2022-10-16 23:33:24 +00:00
stephan 2676fc58c8 Minor tweak to get bring an edge case of oo1.DB.createFunction() into aggreement with its docs.
FossilOrigin-Name: 8d59ccd9f357fbed0b0790508ca9027194fc4b0131029f9f460c7b4bde806a5f
2022-10-16 18:57:15 +00:00
stephan 824bb5b8db Add aggregate function support to sqlite3.oo1.DB.createFunction(). Change signature of the options object used by that function so that the callback property names match those of the corresponding C APIs.
FossilOrigin-Name: a7db6e4b50beebfb1c97e0c4de49538d8199c166b18a0b1b175736c593128a00
2022-10-16 18:50:55 +00:00
stephan 8ffc98999d JS: add build-time-generated version info to the sqlite3.version object. Remove some stray debug output from tester1.js.
FossilOrigin-Name: b5f462c2d85d503f6492ec20580d57cb4c926712f6306a6be764bd09d1f5e8b8
2022-10-16 16:38:15 +00:00
stephan 956392694a Add a top-level license and build-time version info header to generated sqlite3*.js. Correct a broken link in ext/wasm/index.html.
FossilOrigin-Name: 0f1a06e8e39a1fbc74f1aff9cc59787282dfbf847d6c5c7edb3f7d410db0e4b7
2022-10-16 15:38:03 +00:00
dan 8e62d370cf Exclude slow test recovercorrupt.test from veryquick.test.
FossilOrigin-Name: ff9a733532fe11bb253246b45a94681a174c976aafee5c780af571893e8ce694
2022-10-15 19:18:10 +00:00
dan f0799fdf6d Add missing comments and fix other code issues.
FossilOrigin-Name: 8ed4e4a80d8104d20b211a0b3e299abdb955cabdd36979bf6aae54266dc9778d
2022-10-15 18:26:30 +00:00
dan 9dffd36c5d Merge latest trunk changes.
FossilOrigin-Name: 42255ead8e44b24a8abc04aca49f170c55f3b52f42366a0d8ef248ee65fcc7ce
2022-10-15 15:39:46 +00:00
drh f3adb7c430 Enable the index-on-expression optimization even when the expression is
used as an argument to an aggregate function.

FossilOrigin-Name: 462b3c7f39724dc814f55e7a225e7d0c48f81c524cdda797a66e9e198c35ce58
2022-10-15 12:01:40 +00:00
drh 7a98937db2 Only extract an expression from an index when the index is not a null row
in an outer join.

FossilOrigin-Name: 08b033c737d1a84859291f50e2985c9dad8d660a50185d55d3171165a8e08d4c
2022-10-15 11:27:01 +00:00
drh 260ac72722 Merge fixes from trunk.
FossilOrigin-Name: 1cb65f36c3539302767f551ed53082f054666a7cb2696cef0990ab6747edbc52
2022-10-14 19:56:58 +00:00
dan 879164ed74 Fix a problem with using the push-down optimization on compound SELECTs where component SELECTs use different collation sequences. dbsqlfuzz 11516f050100243e5a845f5a2b48a90ed2efaf2e.
FossilOrigin-Name: ed14863dd72e35fa3a23320c3d5a8166515faea39a555c28a27b2d35e701eac4
2022-10-14 19:30:34 +00:00
drh 0388f17988 Add missing initializer from the extension loader. Fix for
check-in [d6d449978245b4fa].

FossilOrigin-Name: 565d74c36f2dd4612860c7ee561682c50db28cfa5384346528292019dbfdf86c
2022-10-14 19:21:12 +00:00
stephan e72ddfd89b Generic minor cleanups and docs in the OPFS async proxy.
FossilOrigin-Name: a4423ca234453c14eb40db7fe5943f63b30fd9dc2207388e8a2966733a004e9d
2022-10-14 15:52:29 +00:00
dan 3fa10f82f4 Handle recovering databases with reserved bytes at the end of each page.
FossilOrigin-Name: 52d0235ef3f21683daadf2343514f7b95a67c3589266f75c1e00e04f11dc6214
2022-10-14 15:46:19 +00:00
dan 2bc4a6cad0 Fix a problem in the LIKE and GLOB operators that may occur when the character immediately following a "%" or "*" wildcard is U+80. Reported by [forum:61bf7ccbdf].
FossilOrigin-Name: 2da677c45b643482eec39e4db7079c772760bc966dc71bf6c01658cc468f5823
2022-10-14 15:10:36 +00:00
stephan 3e771c0f07 Remove a resolved TODO comment.
FossilOrigin-Name: 32fd4ac382f774189ac34f6fff80e55e6e56dd2aa67b0db88d5a88324f17f6ff
2022-10-14 13:26:18 +00:00
drh 859434d049 Cancel IndexExpr objects when they go out of scope.
FossilOrigin-Name: 0963519371bb7ac02adb323430855760fb9b82a23745e47c504aaf393d22ac34
2022-10-14 02:00:54 +00:00
drh 4bc1cc1847 This experimental branch attempts to use columns for an index-on-expression
in place of the expression that is being indexed.  This particular check-in
mostly works, but there are still issues.

FossilOrigin-Name: 2e8d4fd4cfd9e82f33c707ba246fe2bb3ca01762cf5ac5905058fbc7adf0abe7
2022-10-13 21:08:34 +00:00
dan 249efd04d7 Add tests for detecting page size of databases.
FossilOrigin-Name: 31f9e2369fcf59032b7c4c9f5bfc85e7ef7c174003b0b9e2757dad5a4c79b370
2022-10-13 20:06:17 +00:00
stephan d92c652ac1 Move the rest of testing1.js into tester1.js and eliminate the dependency on jaccwabyt_test.c. Extend the list of default config-related #defines in sqlite3-wasm.c and reorganize them for maintainability.
FossilOrigin-Name: 4e2a8aff2dd4b6e148f45184e2523ebe47815257eca97fa3d32bcbf9625f0def
2022-10-13 16:48:35 +00:00
drh 921acff927 Optimize the IS NULL and IS NOT NULL operators so that they avoid loading
large strings or blobs off of disk if all it needs to know is whether or
not the string or blob is NULL.

FossilOrigin-Name: cb94350185f555c333b628ee846c47bcc9df5f76bb82de569b8322f30dbbe1bc
2022-10-13 15:09:44 +00:00
drh eddfa9840e Improvements to the description of the OPFLAG_TYPEOFARG option to OP_Column.
FossilOrigin-Name: 5e9c67ba18b701aabbb0546acdfc532c9e8f0d27fb0a2c899415a5c47096c90b
2022-10-13 14:54:32 +00:00
drh bd1c634546 Adjust the implementation of sqlite3VdbeTypeofColumn() to make it easier
to test (and slightly smaller).

FossilOrigin-Name: 79fdd021df256c6a2b9973fd6bf8e52ffaaf4d369d40489b8395ac97880b1325
2022-10-13 14:35:20 +00:00
drh 7ca4af6a9f Fix a typo in the documentation of the OP_Column opcode.
[forum:/forumpost/a2b5bd6d43|Forum post a2b5bd6d43].

FossilOrigin-Name: 043e76e6166da5cf8e213cce46aaccb1f910e1fdbdb5556576eafb81b3bc5faa
2022-10-13 14:01:11 +00:00
drh e995d2c226 Proposed optimization to the IS NULL and NOT NULL operators that avoids
loading the entire content of larges strings and BLOBs.  Response to
[forum:/info/3c08d4715dc05b00|forum post 3c08d4715dc05b00].

FossilOrigin-Name: 45f171565442f9fd6574fb93ae7abe83c168b20be68af42531bc55571450d3ab
2022-10-13 12:47:33 +00:00
stephan d85d08398d Port the first 180-odd unit tests from testing1.* into the new tester1.*. Fix a stray-keystroke-induced typo which broke pstack.allocChunks().
FossilOrigin-Name: ef689e33e464829f5cbe4ca24a53d9dba59abe74d3d80a37a91b93a4eccccf2d
2022-10-13 08:03:31 +00:00
drh 1ffb6be119 Updates to the fuzzer query invariant checker - tracking changes made
over in dbsqlfuzz.

FossilOrigin-Name: 4ca16a304ad10fbb48f78b4384b347fe883e1a4f222f113ac981e89845c3e113
2022-10-12 18:40:25 +00:00
drh 131aa13a2a Changes to Makefile.msc to fix the build on Windows following the previous
merge.

FossilOrigin-Name: 368fa6b25bc803ded7c1a0184615980902657879370caec22ceea42496ec0566
2022-10-12 18:30:08 +00:00
stephan c9e992a197 Merge fiddle-opfs branch into trunk.
FossilOrigin-Name: 98f954942a8d4824b5c4bd1d27cfeff7a71a029dc5a54220b76d59e367996581
2022-10-12 18:13:52 +00:00
stephan 7be51f5897 Merge trunk into fiddle-opfs as a preliminary step for a clean merge in the other direction.
FossilOrigin-Name: 5e1848ce384a78fe5dfa1b5c1b2acb9c2fac34a8f0ba6c652e0541dcf24e9027
2022-10-12 16:35:22 +00:00
stephan 402da26c16 Add initial infrastructure for setting up function/regression tests for the JS/WASM APIs.
FossilOrigin-Name: 7f5db9829b6e60fadb756fea5442da1f4368c8428bb5cdaf14f97f0c3c8451d9
2022-10-12 15:54:28 +00:00
stephan b75971e6e9 Minor doc cleanups and corrections in sqlite3-wasm.c
FossilOrigin-Name: 5144c122a921e4240901cf4eb46347b92213273eec7cf0977952ab2b60722c27
2022-10-12 15:40:16 +00:00
stephan 181f7e869d Correct mismatched H1 tags in test code. Minor CSS tweaks.
FossilOrigin-Name: 4d8eb90a370054d4482c20637ab56f5e01f4d10215f2af4e35fb9a1f85ecb700
2022-10-12 14:39:15 +00:00
drh 47996ea7c4 Add the sqlite3_value_encoding() interface.
FossilOrigin-Name: d6d449978245b4fa66c152132da468eea7977eab4d1fe53bb2fe3ef543d8030f
2022-10-12 12:49:29 +00:00
drh c2777abc2d Enhance the OP_IsType opcode so that it is slightly smaller and faster and
so that it works correctly with invalid serial-type codes 10 and 11.

FossilOrigin-Name: 846f863e0d55eb7e78c8d355bbbcd73e1946d0ba566c2cb31683cde5f4353d1b
2022-10-11 13:57:55 +00:00
drh 7d23d157bb Improved the ability of the CLI to handle very long input lines.
Potentially a fix for the bug reported by
[forum:/forumpost/fa4bb2941a|forum post fa4bb2941a].

FossilOrigin-Name: d0e107ee00101f42b4c9bf372625311d04b83c96a4a9caacac866ea03d8e7fa4
2022-10-11 12:02:42 +00:00
drh 7747ffba47 Enhance the "PRAGMA integrity_check" statement so that it verifies datatype
constraints on non-STRICT tables:  (1) Columns with TEXT affinity should not
contain numeric values, and (2) columns with NUMERIC affinity should not
contain TEXT values that could be converted into numbers.

FossilOrigin-Name: aa6e9086196248675b9e33dbfaad9ef67097432535896790f80d2470002978b1
2022-10-10 23:54:17 +00:00
drh c9ef12f62b Code clean-up for the integrity_check enhancement.
FossilOrigin-Name: a140173102febe9ef8064ee9b95bee489db54caba149e577d69e4d75161bf390
2022-10-10 21:21:04 +00:00
drh db6940ab45 Fix corner-case bugs in the new integrity_check logic. All tests pass now.
FossilOrigin-Name: dbab9d52a842085da67f5d0b8e96c665adc16331accf380b4c234e9b05bdb7fb
2022-10-10 19:38:01 +00:00
drh 49d77ee642 An attempt to enhance PRAGMA integrity check so that it does data type
checking on non-STRICT tables.  Specifically:  (1) Columns with TEXT affinity
should not contain numeric values, and (2) columns with numeric affinity should
not contain text values that can be converted to numeric.

FossilOrigin-Name: 8b1e7f0524637728cebe81c7d3ff8ad8a5a55782eac6409b425dad538024f596
2022-10-10 18:25:05 +00:00
drh 005c9d8295 Improved detection of database corrupting when moving pages on an
autovacuumed database when creating a new btree.
dbsqlfuzz 9a55397eae13cec64aebf1fd35489c3a90bdaac5

FossilOrigin-Name: 327965bc71023d9380a9d6805062659108dab4bfcd386b7aba813754f270d33a
2022-10-10 12:02:53 +00:00
stephan 50661c5e31 Remove some extraneous debug output.
FossilOrigin-Name: 56ff42053f7b73b380c103a84f29e285cfbfb6e18a25b3a50a6d78e32610914e
2022-10-09 17:08:36 +00:00
stephan d8897d971b Remove a now-unnecessary --cachesize flag for the OPFS sqlite3_vfs speedtest1-worker.html invocation.
FossilOrigin-Name: 08b516d6953256cfb8792cfee9e6ed7450fd55d84196b66b77409cfaee3c8729
2022-10-09 17:03:48 +00:00
stephan ff891b4e1c Minor cleaups in the post-init async phase of sqlite3 module initialization.
FossilOrigin-Name: 2e024a6b533524b7732cea8aa27b16363e17b4c32731ddf31085e91fc728c1af
2022-10-09 15:12:37 +00:00
stephan 392fd3ce37 Remove ext/wasm/kvvfs.make which was inadvertently resurrected in [92b500da70a3].
FossilOrigin-Name: 2e7fa085fc0b1202c6502d89e2603ae76a93451754b07b32ab4f0211f213f980
2022-10-09 13:35:14 +00:00
stephan 4fbf90ee11 Refactor kvvfs JS bits to make use of [ea370b9b05f7ed7eaa]. At main-thread startup, if kvvfs is available, replace the kvvfs I/O methods with JS impls. Checkin part 2 of 2, to account for cherrypicking [ea370b9b05f7ed7eaa] into the kv-vfs branch.
FossilOrigin-Name: a9047e020a097b2259bc9935b63ca1c538a3a7f1d050e15f0d0a08cfb84acc7c
2022-10-09 13:26:15 +00:00
stephan d35b5587df Refactor os_kv.c so that the kvvfs read/write/delete methods can be swapped out at runtime by JS implementations. This eliminates the kvvfs dependency on Emscripten. Checkin part 1 of 2, to account for cherrypicking.
FossilOrigin-Name: ea370b9b05f7ed7eaa154ba58019f6642217eabc18517e721567adf948d93980
2022-10-09 13:19:27 +00:00
stephan d6555726ed Add -DSQLITE_OS_KV_OPTIONAL to speedtest1 flags for kvvfs testing purposes.
FossilOrigin-Name: 92b500da70a3dc64e910c232a2cac7620b6609162c2a5058b269d3b83d763c02
2022-10-09 11:42:12 +00:00
drh 211a1a7281 When casting an odd-length BLOB into a TEXT with encoding UTF16, omit the
last byte.  dbsqlfuzz c5df68b5bbdf6c9f3c1851e41e88f49ac05c9969

FossilOrigin-Name: 1e2796b3741a4c0b966e6c01a7d62dea8de9d1f4bededea3d7ba7004dabc2ffe
2022-10-08 17:27:05 +00:00
dan 73c586bcbf Fix a problem causing the seek-scan optimization to skip over valid rows that could occur when it is used with expressions of the form (a IN (?,?..) AND b >= ?). dbsqlfuzz ab1db6dc0efb04cba1cd3431ee6da4894fdc4520.
FossilOrigin-Name: 63d9efe277759d4daa29794846b60c6f55491496618f423f61468df72d0a4633
2022-10-07 18:57:15 +00:00
drh 8a2254fa1f Improved tracing output for showing all registers used by the
OP_SeekGE opcode.  This applies to debugging builds only.

FossilOrigin-Name: 0aa6dee7f72279114a47cbb69fdbda0b916a2c365f7a147946869f167bd018b7
2022-10-07 15:55:35 +00:00
dan 88a0637f57 Ensure the page-size, auto-vacuum and other settings are copied into the recovered database.
FossilOrigin-Name: 078520f2825bcb82d01b30209409e9bf8b6c99084c192345df41c9f531d08f51
2022-10-06 21:00:23 +00:00
dan 4df12ce5a8 Add code to determine the database page-size by searching for well-formed pages.
FossilOrigin-Name: 0dbd0ccef532e076fa82c9fad4dc9fe632c0ef43e3483cc288cbb7eca336a9b9
2022-10-06 17:20:12 +00:00
dan 73ac958c74 Fix a problem that occurred when using a bloom filter to optimize an (ipk = ?) lookup in the case where the RHS of the expression is a TEXT value. First reported by [forum:/forumpost/f61a8b7053|forum post f61a8b7053].
FossilOrigin-Name: 8e14c351b29bb434ac4e2510681e95716424a73e340d39feff4919f0431c2e00
2022-10-06 14:10:11 +00:00
dan adc686043e Improve handling of corruption in the sqlite_schema table b-tree structure.
FossilOrigin-Name: 2be0dba12fb9b98cd9632f1ff3f30aeb29661a2e121b68c2f3335617b027797b
2022-10-05 16:58:28 +00:00
dan 461fa44be0 Merge latest trunk changes.
FossilOrigin-Name: b0feecaa84b88f534edb49056cf7e92256f4a687c8b4c44e1d1186709a304378
2022-10-04 19:47:17 +00:00
dan 041cc06139 Better handling for databases with corrupt headers.
FossilOrigin-Name: 17f68d803685405d880025134c71bac01077962d677f2902a608952d0b9cdb5a
2022-10-04 19:43:12 +00:00
stephan 9a55773b2f Replace time-based auto-unlock of opfs sync handles with lock acquisition/release via sqlite3_io_methods::xLock/xUnlock().
FossilOrigin-Name: 2625b7cfe1640c1d7e779ec1f37db970541598c0dc3e22e5eecf3c772d95ad40
2022-10-04 17:06:51 +00:00
drh 2eca06141f Attempt to clarify the operation of the xLock and xUnlock VFS I/O methods.
Assert() statements added to prove that they behave as the documentation says.

FossilOrigin-Name: 3efa811251d4510a074231a1e0b667783cc5f90777466b9dcae675cd9892b423
2022-10-04 14:50:46 +00:00
stephan ed3182f233 Tweaks to the opfs async wait/relinquish times.
FossilOrigin-Name: 35f33c23e5849de1c43c4499ee0a7fa11d26ae34949c1e820c3fa8e8873f9c2b
2022-10-04 11:14:23 +00:00
drh a4b2f41938 Change the name of the autoconf-generated configuration file from "config.h"
to "sqlite_cfg.h" to work around a bug in a dependency checker, reported
in [https://twitter.com/josecastillo/status/1577136108097314816|a tweet from Jose Castillo].

FossilOrigin-Name: 897e187cad981126fc5f6ea8e382e937825af10b0c9589b0a23b9fbaa4ca58b8
2022-10-04 10:35:10 +00:00
stephan 98e120fca0 Update ext/wasm/api/README.md to account for recent changes.
FossilOrigin-Name: 9d488081fc82a9abe3e81c7897fe6b29b6b337f62d0c62cb9cec7517bd54b53f
2022-10-04 09:12:43 +00:00
stephan c7fb48d4b6 OPFS async proxy: add a wait-and-retry policy to the get-sync-handle step to help account for cross-tab locking.
FossilOrigin-Name: 45c48c63d311052105d102189208495b2b53fa3c4174884ecf63b757aa4016e5
2022-10-04 09:12:05 +00:00
stephan f6b6188bdd Update the 'start in speedtest kvvfs' link in speedtest1-worker to account for recent changes.
FossilOrigin-Name: f4d5ba412e0c1a031430a32c9ed1e11a09af33f9883150e660cc05e49fe56e6a
2022-10-04 08:58:22 +00:00
stephan 2716cd2528 Minor pstack doc update.
FossilOrigin-Name: 6b4fb7c4e399ecc948ad41f5fa3139a9293cc822cd7efa2b83dc5fb1660b3ec6
2022-10-04 01:21:34 +00:00
stephan 2b776ee2d6 Minor cleanups and additions in sqlite3.capi.wasm.pstack.
FossilOrigin-Name: 97bd670d3859bd3f2e62c15065b238b85ef614f26479e56a14be42c5784aedf4
2022-10-04 01:11:10 +00:00
stephan 3c272ba380 Add a test/debug mechanism to shut down the OPFS async listener so that it can be inspected (it normally can't be because its tight event-listening loop ties up the thread) and then restarted.
FossilOrigin-Name: 7d0bcff4e9b899cd25b393b9f0a02c5dcee2e229f0a0fa01719c7dcd7dcbe7c1
2022-10-04 00:54:00 +00:00
stephan 88838f6b95 Set default page cache size to 16mb in wasm builds. Fix an off-by-one counter in sqlite3_wasm_enum_json(). Minor coding style conformance tweaks.
FossilOrigin-Name: 72a9e589cc318ec50941739e2edf2c0636284b316c3bf87b71fd363b37619da3
2022-10-03 23:13:05 +00:00
stephan faf6a07965 Add a --cachesize flag to the speedtest1-worker-opfs link in index.html because opfs is much faster with that.
FossilOrigin-Name: 5b8f8e33afc47c9f0c64dbe34643d7d1c37a0a82afb4656e714a86ef54a9ce6f
2022-10-03 22:51:24 +00:00
stephan 8d9e595513 Minor JS doc updates and typo fixes.
FossilOrigin-Name: 3cfcc14dfd220536141aeffb902fdc8db1cea055b2a0609b88e092fc3df94688
2022-10-03 22:38:00 +00:00
stephan d234902b7c Add configurable cache_size to batch-runner and speedtest1-worker. Add SQL tracing to demo-123.js just for demonstration's sake.
FossilOrigin-Name: 2ab065133bec19f71a1dc382946fdbd020920b2e38a526f4126a3a1e8df5de87
2022-10-03 18:07:25 +00:00
stephan 4b074692f4 Omit WAL mode from the wasm build.
FossilOrigin-Name: 88efe2a62b81e5ee9119f54204e397fda59666a327158c7b7c972e84a716869e
2022-10-03 18:05:27 +00:00
drh 16292a5e52 Adjust the --help output for speedtest1 to clarify that the argument to
the --cachesize option is in pages, not bytes.

FossilOrigin-Name: d7c2be6bdc3402e5a339d0f7b76d2c25f3a444dcbf54a77c1ccb790d1195a7cf
2022-10-03 15:22:59 +00:00
drh 277c7d3516 Copy all of the fiddle-opfs changes to speedtest1 into trunk.
FossilOrigin-Name: f3d31c9982cab517a3907a28c571225cee614ee78375c70eb2efb9a2b6b4b042
2022-10-03 13:56:52 +00:00
stephan 57956a9c86 Resolve/remove a TODO.
FossilOrigin-Name: 2ea35fea3bac2637e935643edfa7913b792e529de3a8980dbb8678d98ed5bcf9
2022-10-03 13:46:20 +00:00
drh 3044e77b4a Add the --vfs option to speedtest1.
FossilOrigin-Name: aeb884029ac1c68f0d7361dda0a545cff19ed265b608c1e329a1926397c5c8a3
2022-10-03 13:45:03 +00:00
stephan 4f5bbedb3a Export sqlite3_trace_v2() to wasm and use it to ensure that the new per-VFS post-open SQL support in the DB ctor works. Default opfs vfs to journal_mode=truncate, as it's faster in that mode. Add 't' DB open-mode flag to enable SQL tracing to console.log().
FossilOrigin-Name: 508f7f6d63e52f61fae5abe817579a4e130fa7fbd18733d741d521a5bdabb7ce
2022-10-03 13:03:41 +00:00
stephan a4c357f94c Reimplement fiddle_reset_db() so that it works with all VFSes.
FossilOrigin-Name: 18462052903bfeb037dd9af3a1fe1898d141eff5d6f527721858120553de808d
2022-10-03 11:42:45 +00:00
stephan 5f0b67cb7a Experimentally relinquish the OPFS VFS sync access handle when the db is idle and reacquire it on demand, the goal being to help alleviate cross-tab locking issues.
FossilOrigin-Name: 2703ac9842335962e488e597168d70b1389b95a6ad39edf70a211b95979b4708
2022-10-03 11:33:35 +00:00
stephan 33ded6edaf Add journal=MODE to the list of supported URL flags for speedtest1-worker.html.
FossilOrigin-Name: 5c43e8d2ec23f28fdce63874d9d4c8ccbb4a8f81030b19d65ff5711a7c32697e
2022-10-03 11:23:47 +00:00
stephan 7ff8da876d OPFS VFS now lazily opens its sync access handle, as a step towards experimenting with relinquishing it during idle times to help avoid cross-tab and page-reload locking issues.
FossilOrigin-Name: a984e1ba435731413a541f86c50232bc7d6e33aff6ba4cca90f89188e7b82a2c
2022-10-03 09:21:37 +00:00
stephan bdfd7ea03a Partial revert of [a82e6faaa642] to remove the 'I' alias for 'j' wasm function signature letter. In hindsight, that change seems premature.
FossilOrigin-Name: dcd46af9141f4edf816010923941a76d0edd3f18cfe429c52f599ad2a0d52651
2022-10-03 08:30:22 +00:00
stephan ef9cd12ec4 Minor JS API tweaks prompted by documenting them.
FossilOrigin-Name: a82e6faaa642b09d241232c4daa67134d4dfa24bf3ca3725740346ca5269b381
2022-10-03 08:21:06 +00:00
stephan 510a9d1c64 More cleanups in the UDF argument and result handling, in particular int64. Consolidate some duplicate int64/bigint range checking code. Expose the UDF low-level utilities (arg/result conversion) to client code. Add the sqlite3_context pointer to the JS-side UDF wrappers for API consistency.
FossilOrigin-Name: 10ab77af952abf09f93f342a9d07a3b133f2c4c0a3588df3390cd3a923cafae4
2022-10-02 22:50:04 +00:00
stephan 65e6522f8f Minor doc typo fix in sqlite.h.in.
FossilOrigin-Name: 372802aaa22a830bf498bb0d9561ae02b32e5e191c4d7d771ea152140f6685a1
2022-10-02 20:13:46 +00:00
stephan 92ede964e1 JS: clean up create_function() wrapper and add support for create_window_function(). Eliminate an extraneous blob copy when a UDF returns a blob. Make use of newfound JS-fu to clean up how sqlite3ApiBootstrap() config is initialized.
FossilOrigin-Name: d3bad9347c5423fa7f19ae729461636f1043c99a1f01f168efa10bebefb1cdd1
2022-10-02 20:08:53 +00:00
stephan 9892883e9e js: implement a hand-written wrapper for sqlite3_create_function_v2() which converts, if necessary, JS-function-type args to WASM function wrappers. Replace DB.createFunction() impl with the new one.
FossilOrigin-Name: 435ab33384017967e46f52b70bee851a85a28808990a0e58dd5288f606b89c9c
2022-10-02 18:47:39 +00:00
stephan 9fdce595eb Doc typo fixes.
FossilOrigin-Name: e528675da3971907666c7d2d09763975a105ec585dc5122145f65905d535bed8
2022-10-02 03:14:38 +00:00
stephan 63e9ec2f9c More fleshing out of sqlite3.capi.wasm.pstack.
FossilOrigin-Name: eb5726677a727a958df11f1fba078d30c7c0ba2a9bdb158e8641b35b5f971af3
2022-10-02 03:11:13 +00:00
stephan 6479c5a359 Document the roles of the new (this past week) JS files added to the build process.
FossilOrigin-Name: 8b3bc7313aff551e5ee0b7aeb927095cf19b9b96abbdd922066c130656b8aa7d
2022-10-02 01:48:14 +00:00
stephan 193ee11fe1 General internal cleanups in the oo1 API.
FossilOrigin-Name: f9db664f756f3707afcb5dce87f6d946625848f27ea84337af68de72d4ad6c6b
2022-10-02 00:09:40 +00:00
drh 7d34b8d628 Performance optimization in sqlite3_prepare() (discovered while working
on the stmt-cache branch).

FossilOrigin-Name: cd494240cc6184bb028d1f1049086f57c0a71a43d7ed1405fd4205240e1b9e61
2022-10-01 20:27:29 +00:00
stephan f064a3bbe4 Correct fiddle db export breakage caused by a post-testing API change made in [1fa019c88dea].
FossilOrigin-Name: e73cc44ec36c7585ebb914bdeed5b39480fca7c7a8d3c4426bfe769c87b98d17
2022-10-01 19:21:52 +00:00
stephan f446af57b5 Pedantic constness tweak.
FossilOrigin-Name: c8a173cf16d2567bf9b13f52904077a2e7209776c76613c7bff59cd66e24bf11
2022-10-01 18:55:10 +00:00
stephan 3afad4d432 wasm: correct a memleak caused by a shadowed var in the previous checkin. Add a stack-like allocator, sqlite3.capi.wasm.pstack, as a faster way of managing short-lived pointers (like the one which got shadowed).
FossilOrigin-Name: 1fa019c88deac6b6e5155b620bdab1d7145846290daafb9adbefcf4f0fe542cf
2022-10-01 18:47:42 +00:00
stephan 32781427d7 Fiddle: fix makefile dependency issue and duplicate inclusion of post-js.js. Reimplement db export using sqlite3_serialize().
FossilOrigin-Name: 29db7de79232c21d19b91bb0fc253114e02e21dd9bf90619453dbe72a4c8bf7f
2022-10-01 16:01:41 +00:00
stephan be9d203665 Merge trunk into fiddle-opfs branch.
FossilOrigin-Name: 64ebcbe41615a6d7776597564105ea7638e4a9095a764ea558c2620640429cf8
2022-10-01 13:45:14 +00:00
stephan c9099d2d73 Tweak sqlite3-worker1.js to be able to load either sqlite3.js or sqlite3-wasmfs.js, noting that the latter still does not load in a Worker because of an Emscripten loader bug.
FossilOrigin-Name: 000ef7059bfb54dc4f829b81a8d8c927c0382980218d8a3d60cd2c4d89151c90
2022-10-01 13:38:27 +00:00
drh 7424aeff41 Replace the Parse.disableVtab field with Parse.prepFlags for increased
generality, a small size reduction, and a small performance increase.

FossilOrigin-Name: b7da0bcdf70e53ab1ec00a0694e17c7429e23bc6eb3f39b622d06a930aa2f6a3
2022-10-01 13:17:53 +00:00
stephan 6167d5cf17 Note two wasm-related potential TODOs.
FossilOrigin-Name: 5636e82864457d870754ee7125c307dc5d2195197a5c0266579da9f102938b89
2022-10-01 12:04:49 +00:00
stephan 8c1a4b89af Remove a couple of weird quirks of the Worker1 and Promiser APIs. The Worker1 (now undocumented) unlink capability needs to be reevaluated to work equivalently for all storage backends.
FossilOrigin-Name: 9f2b331a32cbaadfd20d04c9908171355322c1aa1d9d6df3628f3b2fb4391ec1
2022-09-30 23:49:43 +00:00
stephan ae589b69db Tweaks to the Worker1 and Promiser APIs prompted by documenting them.
FossilOrigin-Name: c68b9aa160e2c1197ae7eb06a634017ac2b281393074afa4582762d5458c6889
2022-09-30 23:02:11 +00:00
drh 7bc6a818f0 Remove one of the NEVER() macros added by [5166acf3f0040459] because it
is reachable after all.

FossilOrigin-Name: bd8ae5febbb8d3122f1e2e09b9fcdd6ac20c075ae1cf60bcdbd36080f3736417
2022-09-30 22:40:57 +00:00
drh 1337a2291d New test cases in fuzzdata8.db
FossilOrigin-Name: aa367a3c974041323edb759855f0b83803439ceef2846da2d73eadd80efeaac4
2022-09-30 20:59:09 +00:00
drh 2d3261fe86 Fix a bug in the demoDelete fix from [d76a301e22e05722].
FossilOrigin-Name: 7e761a02530ffbb055a766eb6c995f11fc2adbabb9a52502124f672fdcff0d10
2022-09-30 20:53:36 +00:00
drh 0a803bd984 Add NEVER() to two error-detection tests that were made unreachable by
the previous check-in.

FossilOrigin-Name: 5166acf3f00404597e77910aee88920ab833af8447766f50bf4f70525606cf95
2022-09-30 20:48:22 +00:00
stephan e67a0f40e4 Add JS wrapper for sqlite3_exec() which knows how to handle a JS callback. Add some console.error() reporting of module-load failures, as they otherwise often get silently swallowed up by the loader's mechanisms. Add 'flexible-string' JS-to-WASM argument converter which performs more X-to-string conversions than the 'string' arg converter does.
FossilOrigin-Name: 96818aa83f4ccc574f558231249ecbdd39763b4351cf4cf6d33f53774a3ee5e6
2022-09-30 20:35:37 +00:00
dan ad658b2d82 Better handle a case of database corruption where a b-tree page is one of its own ancestor pages.
FossilOrigin-Name: a24e46804893a7e6e8f3130abca882f9a3aa3b7b2b82aa39a0a20856172766d5
2022-09-30 20:15:21 +00:00
stephan d18f1bbfe0 Add sqlite3.version object. Add more state to the Worker #1 config-get response, including sqlite3.version.
FossilOrigin-Name: 711f458d188a0dbe6612069c856ade29323ab426dfa4f80e7b82757ccc474cb8
2022-09-30 16:49:03 +00:00
stephan 07c0b72253 Add oo1.JsStorageDb.clearStorage/storageSize() methods, copies of capi.sqlite3_web_kvvfs_clear/size().
FossilOrigin-Name: 1e09efe7fa15b8908f8b8353164a8361de778e27ea6c0b11c402bf4e1c56333d
2022-09-30 15:46:08 +00:00
stephan 359d62395e batch-runner.js: force WebSQL batches to not abort for a failed statement (necessary for apples-to-apples-ish benchmark comparisons).
FossilOrigin-Name: 60f0c5cb04d2baf8431e523434d8753e39377f4b2c6bad225c2e5487a4be419b
2022-09-30 15:24:58 +00:00
drh cb57716c65 Improvements to the "demoDelete" method in the demovfs, suggested by
[forum:/forumpost/cad18961c2|forum post cad18961c2].

FossilOrigin-Name: d76a301e22e0572262917dfe9557a5051339a65416a473dd2d9989a49975403e
2022-09-30 14:35:18 +00:00
stephan dc6ae60226 Expose sqlite3_msize() to wasm.
FossilOrigin-Name: aa6ad34f3b693b554be58ee2895f79397162c5b8877c709653c8508fc625e8f4
2022-09-30 12:10:36 +00:00
stephan f6c686c9f4 Add oo1.JsStorageDb() as a convenience wrapper for oo1.DB(...,'kvvfs'). Minor doc cleanups.
FossilOrigin-Name: 8a7998709f859a562cf6829485cb9921f8823af0efabe003741348ab1169fb89
2022-09-30 11:01:44 +00:00
stephan 53d4e01d06 wasm: expose sqlite3_de/serialize(), sqlite3_malloc/free() and friends, noting that the former explicitly lies on use of the latter for memory management so is not generically safe for use in wasm.
FossilOrigin-Name: fbc0edb5d31aa0dea92460e853f15f08c642451a7878994116b530cf172325cc
2022-09-30 10:55:28 +00:00
stephan f71c954cbc Add JS infrastructure to ostensibly allow us to customize the wasm imports, which will hypothetically allow us to eliminate the dependency on EM_JS(), but the corresponding Emscripten glue-level feature currently breaks fatally with WASMFS builds so it's disabled.
FossilOrigin-Name: 88d9253b0db5494bf1c9b6d24f22524eeec856b89e64a66ffb30d945f0df21d3
2022-09-29 22:08:22 +00:00
stephan b0ccf50cbd Ensure that the wasm builds always, even when passing -Ox flags from the CLI, use -g3 to avoid problems caused by symbol minification with optimization levels -O2 and higher.
FossilOrigin-Name: 27d24d5d270e272af07d96cf07bdbe79ba07a9c69ba3c70beb76ebf4f90fc97a
2022-09-29 17:35:25 +00:00
stephan eb97743cc7 Finish eliminating explicit Emscripten module dependencies in test code and fiddle. The only remnant in public code is the Emscripten-generated module load/init interface.
FossilOrigin-Name: 7be78dd4efc410f13ff1ceda1fad82b309cc24de2d5106c8bd6b2adeaa13b106
2022-09-29 16:54:23 +00:00
stephan b94a98607a Rework the Emscripten-emitted module loader/init function such that it passes on the sqlite3 module, instead of the Emscripten module, to the first then() of sqlite3InitModule()'s returned Promise. This eliminates any need to mention the Emscripten module object in client-side code unless they want to configure it in advance for loading-status reports.
FossilOrigin-Name: 0dbaa0e2b5abf5c23e2039ec90a3055ebb3c063aaf4e556c42546defe6fbb86d
2022-09-29 13:17:50 +00:00
drh 31474ce57e Fix misuse of the sqlite3_set_auxdata() interface in the ICU extension.
FossilOrigin-Name: f25cf63471cbed1edb27591e57fead62550d4046dbdcb61312288f0f6f24c646
2022-09-28 19:14:01 +00:00
stephan 4b884bb4c7 Wasm: expose sqlite3_exec() and use it to simplify the db-reset logic in batch-runner.js a bit.
FossilOrigin-Name: 2e2821f782511b9d2274a89a5a922582aba18c7e9dc7ce01080e713942a56d7d
2022-09-28 18:10:50 +00:00
stephan cb22bd80d2 More work on batch-runner.html/js to facilitate speed comparisons between various VFSes and WebSQL.
FossilOrigin-Name: 3bd1bc240676e56da87fc49f3c67a1edc4fafcf2a2416298d19ae4f80b676a72
2022-09-28 17:52:52 +00:00
stephan 5ad3631915 Correct duplicate copies of sqlite3-api.js being embedded in the wasmfs-based builds.
FossilOrigin-Name: bbfcfba260f39a9c91e82d87e06b1c2cb297c03498b4530aa3e7e01ef9916012
2022-09-28 13:01:49 +00:00
stephan d98011852d Work around broken -Os wasm builds by adding the -g3 flag. Unrelated documentation tweaks.
FossilOrigin-Name: f5d6bf8616341037fa3e229edf820d19acef3e0a6207a652b2b143de0a493214
2022-09-28 07:53:47 +00:00
stephan 489a8a9d3c Minor doc correction.
FossilOrigin-Name: 093f6e4b36db294e8e47df2fc75a4bc4fc101e2b6ff0201c912ccd1dcf394479
2022-09-27 17:03:01 +00:00
drh 5d48e0cdc5 Provide the SQLITE_MAX_ALLOCATION_SIZE compile-time option for limiting the
maximum memory allocation size.

FossilOrigin-Name: 584de6a996c78b8e41bdfcd05a8e2a3844664c6b4efedb5883c8b8af388462b5
2022-09-27 16:35:06 +00:00
stephan 6559e0ab15 Comment the -O2 wasm builds as being broken (mysteriously missing JS bits).
FossilOrigin-Name: f61475ef8244fd1f6553eca9cc2317e5de2cc04443e24afb7b91ebd3fc1bd402
2022-09-27 14:31:34 +00:00
stephan 5b9973d898 WASM API renaming. Reworked JS API bootstrap's async post-init into a generic mechanism, no longer OPFS-specific.
FossilOrigin-Name: c42a8cb090cad1108dfd6be574202d744c59e053b505bc4c17252dc6b65d26bf
2022-09-27 13:40:12 +00:00
stephan 3d64548491 wasm/js: rename /persistent to /opfs to account for potential future persistent storage options. Minor flag-handling cleanups in the speedtest1 pages. Minor API tweaks in oo1.
FossilOrigin-Name: 4dc972a3656b2a9ec915bfb3f653136560c753ce4024c3f0d0d0c28f66db7a0a
2022-09-27 09:17:37 +00:00
drh 6319a8003c Make the legacy FTS3 code more robust against integer overflow during
memory allocation.

FossilOrigin-Name: 5517bc50988b5339c2fd071b29de1b5ca03037b0b635c3b112cf7108fab54d5f
2022-09-27 01:53:05 +00:00
drh 80cf891792 Enhance defensive mode so that it disallows CREATE TRIGGER statements if the
statements within the trigger attempt to write on a shadow table.

FossilOrigin-Name: 3283bbd12a60f472ed03cb7c6209a605a3bf9f3d9083371e17840b56e8b3f559
2022-09-27 00:56:45 +00:00
dan 7e33f8f43b Modify implementation of recovery to break recovery of the lost_and_found table into multiple steps.
FossilOrigin-Name: adedfd040bb2d1c2dcda0b91c6073f12953e45d9b860a8f217d990e861d66dfb
2022-09-26 20:51:16 +00:00
stephan 278d3faf1f Fiddle: replace db export routine with a C-side one which works for both Emscripten FS-hosted and OPFS-hosted db files. Minor code-adjacent cleanups.
FossilOrigin-Name: 3579a8d6f1f6cd3cd8aad9949536870c5fe7bae8c1778f700dd85d763e266b94
2022-09-26 13:55:10 +00:00
stephan 1f095d482d Get fiddle db export working for OPFS VFS. Add root dir handle to the main OPFS VFS worker to enable creation of certain utility functions without delegating to the async worker. Add sqlite3.capi.sqlite3_wasm_rc_str() to map integer result codes back to their SQLITE_xxx counterparts. Minor doc touchups.
FossilOrigin-Name: 9b2244e1c8a40efe6547094a1b57acc8f2173145a8731abb0e36268ce0a8ef41
2022-09-26 11:38:58 +00:00
stephan 6a643e4bcd wasm: change StructBinder signature for sqlite3_file::pMethods from 'P' to 'p' to eliminate an unnecessary and inconsistent level of magic.
FossilOrigin-Name: 85f2e877e53899860af4dc6630044b471a9c7c82faba1f4e1e60ae991460b943
2022-09-26 11:34:31 +00:00
dan 8d8fc58413 Add the SQLITE_RECOVER_SLOWINDEXES option, for specifying that indexes should be created and populated along with tables, instead of separately at the end of the recovery operation.
FossilOrigin-Name: ad9dba9d1eae786575c7f31e34b342b6f5b26e719bbe27b61609cad8cfd0a505
2022-09-24 19:54:49 +00:00
dan 351563efe1 Add sqlite3_recover_step() to header file sqlite3recover.h. Update the API docs in this file.
FossilOrigin-Name: 47f416153035d6bf0ae27587583d2957c87c02caecbd4e7f363bcb2bc27cf159
2022-09-24 19:17:20 +00:00
dan aee4049128 Update things to use sqlite3_recover_step() internally.
FossilOrigin-Name: f4b15aad3005237b7ac507eed2b9b07e0f5c9407ab28f2656a21c9845f13d35f
2022-09-24 18:05:52 +00:00
stephan 395012e58e Fiddle: move, rather than copy, data buffers between the threads. Fix the case of an uploaded db failing to install because its filename is the same as the opened db.
FossilOrigin-Name: bcec4f964a7b02f59be05286ff715bac654a32b19f05a743e402f4cdb207cab8
2022-09-24 11:32:00 +00:00
stephan ef11fb915d Resolve "already configured" warnings from shell's main() when starting it up in fiddle mode.
FossilOrigin-Name: 114ef3552af977b272a0baddeb9a2326484b60acfc75284e43c55530f86b413f
2022-09-24 10:15:08 +00:00
stephan 56fae744d4 Reworked out the OPFS async proxy metrics are fetched so that they play more nicely with the tight event-polling loop.
FossilOrigin-Name: ef503ced5c2ca842be9aea9ef13719a378ed3020e884032db09afee1b8eba0a1
2022-09-24 10:12:19 +00:00
stephan 60d9aa7c59 Refactoring towards getting fiddle to support OPFS as a first-class citizen. Certain operations, e.g. import, export, and unlink, are not OPFS-aware.
FossilOrigin-Name: 1b923ed6438d7fef4508936e0c4bc026a368721698b1539961e3fb3140a185cb
2022-09-24 07:36:45 +00:00
dan 9bbd91b39d Internal changes to the recover extension towards a step() style interface.
FossilOrigin-Name: 73926d5c8cd1ecece134b5a73b44ee1dfca74dc200606e3f009b06cdecf8cee9
2022-09-23 21:01:10 +00:00
dan 80b1f6fcde Fix various compiler warnings in new code on this branch.
FossilOrigin-Name: ae49e9efde3012158061def6e0a8d993abbc5933514a21f84bc10f700f61b5e2
2022-09-23 11:40:43 +00:00
dan bdbd097280 Merge latest trunk changes into this branch.
FossilOrigin-Name: e87fa70ab0f9b95bbcde18567f47906a222a3fd02b4f3c2903d2bb087d361b7c
2022-09-23 11:30:24 +00:00
stephan f75c0c7036 Reformulate some JS to work around a buggy/broken code transformation in one of the Emscripten-driven code optimizers.
FossilOrigin-Name: e1249369d5ec1c582c280b1f578b35d53637fdf1cbd97c16d5ed95b136b83e56
2022-09-21 20:24:12 +00:00
stephan 6110a5d0ab Put pieces in place for fiddle to support opfs, but more cleanup is required in the sqlite3.js/fiddle connection. bigIntEnabled now defaults to whether the Emscripten's module has bigint enabled. Add wasm-sensible defaults for several SQLITE_ENABLE/OMIT flags in sqlite3-wasm.c.
FossilOrigin-Name: 7c7fb7535e86b3960eea7f29ab7e6d5197c166b4ee64ad4a9bc0749f2869badc
2022-09-21 19:51:25 +00:00
drh f333370e1f Reduced and improved comments on the constraintCompatibleWithOuterJoin()
function.

FossilOrigin-Name: 38aaf26e082bd95df6b64df43e1772fe6e20c4eb71307dcd97559cac7f11f8f1
2022-09-21 18:21:31 +00:00
stephan 65022716b3 shell.c.in: when building in fiddle mode, define _POSIX_SOURCE (ifndef) so that emcc's string.h reveals strdup().
FossilOrigin-Name: fb85b269c43147f153977606dd8ede7b93744bf955e4c1a2b198907fd8a94620
2022-09-21 16:21:21 +00:00
stephan e8afca3f16 Correct mistyped --shrink-memory flag in speedtest1-worker. Minor OPFS proxy cleanups.
FossilOrigin-Name: 86e2b55ec9483fa5add51a479c6509d73461f1ac6fca5d49e057b1c66f4314d2
2022-09-21 14:02:47 +00:00
stephan 72ab400d4d Doc cleanups and additions. Add a way for the OPFS async runner to propagate exception text to the calling thread.
FossilOrigin-Name: 5c5e80652825cf883e6c17809cb98f2bf17d5feac2d263f6f492479154730dab
2022-09-21 12:27:35 +00:00
stephan 171b168b3e Added some structure to the wasm demo link list.
FossilOrigin-Name: 777077c4c2249e1ec78390d4f65aaf281c1fbefcef4bcc7609199e995645ceb6
2022-09-21 12:25:40 +00:00
drh 2897b88f9e The RIGHT JOIN logic added to version 3.39.0 added a new restriction on the
query flattener which resulted in a performance regression for some queries,
as documented by [forum:/forumpost/96b9e5709cf47cda|forum post 96b9e5709cf47cda].
This change removes that restriction (thus restoring performance) and fixes the
problem that RIGHT JOIN was having in a different way.

FossilOrigin-Name: 501609eddf2a46d51e8cd56477a22d4df142a166e78fe4322c0db11d1eed6687
2022-09-21 09:54:41 +00:00
stephan ebe1423098 Add a link to fiddle.html in the wasm test app index.html.
FossilOrigin-Name: 96c734c07acfbea153d9aaf293a28a2d49d78de19fec4fb90c4c08fb1fd0ddbd
2022-09-21 08:41:40 +00:00
stephan 4bc2f6b415 Move fiddle build rules into the wasm-centric build files. Add rule to push wasm bits to the wasm test server.
FossilOrigin-Name: 113f8204dc4ac849d5632d3de1680b6e0da871e107ef484c8d7273799bee3d88
2022-09-21 08:39:03 +00:00
drh faaacd3fbb Break out the decision of whether or not a constraint term is usable by
an outer join into a subroutine: constraintCompatibleWithOuterJoin().

FossilOrigin-Name: c7fbc9b0453050e2746af27e3a11e0c3701bef8c56da8e19173242c6ea3aff8b
2022-09-21 00:16:59 +00:00
drh 0f51aa3972 Do not allow EP_InnerON terms to be used on a outer join.
FossilOrigin-Name: f47aa745690c018800243bf76930b2499ff4537411c4e27b4b16ba3854cc2bf8
2022-09-20 22:19:13 +00:00
drh 0cc6f78bcf Add new test cases that (current) get an incorrect answer.
FossilOrigin-Name: fe5c37736444e397ace387b761ec2491229785d7a437f3f60232aedf9d1f00ec
2022-09-20 21:07:52 +00:00
drh 4c5c941b6e New test cases for query flattening when there are ON clauses and outer joins.
FossilOrigin-Name: db55387b1972bc7bc6855bd3497af744a111e7d28d09893cd985fbb01be41bcc
2022-09-20 19:45:04 +00:00
drh 8b9a3d1fc8 Modify the OP_IfNotOpen opcode so that the jump is taken if the cursor is open
but was previously set to a NULL row using OP_NullRow.

FossilOrigin-Name: 1292d68caa7086610ddda343f3852e63de8da1eb66536ee4716b6529f5a31bc6
2022-09-20 19:22:17 +00:00
drh 5a0771a1f4 Remove code that has been previously commented out.
FossilOrigin-Name: 852b385a5de622aa32026824210d4bd23db52a4a8a697b83d22d6000edeba487
2022-09-20 18:18:00 +00:00
drh a5f8c42c98 Merge the fuzzcheck fix from trunk into the flattener improvement branch.
FossilOrigin-Name: 930a8c1561d0d5dc70dc5378edac77f79ac59ab6569b561de3dfb02f160c38c5
2022-09-20 17:43:40 +00:00
drh 703c208d30 Update the fuzz invariant checker to conform to the latest changes in
dbsqlfuzz.

FossilOrigin-Name: 8d8c124349d2a25200ace9a60d76751594b722468ad0c39d927a5d2c6e2464e0
2022-09-20 17:21:54 +00:00
drh 40c9becc81 Is the query flattener restriction 29 (do not allow both EP_InnerON and
EP_OuterON constraints on the same FROM clause term) really necessary?   This
branch explores what happens if we omit that restriction.  This is an effort
to address the performance regression reported by
[forum:/forumpost/96b9e5709cf47cda|forum post 96b9e5709cf47cda] that is caused
by flattener restriction 29.

FossilOrigin-Name: 19270577ad1d08c9e6e5f0600396b8a1ccda9df1e67a0df845aee6b60437f379
2022-09-20 16:57:49 +00:00
stephan 4cffb644c7 Correct a too-strict is-opfs-available check.
FossilOrigin-Name: 1b5f1b4a6c1457f98c258459e23e321fc59793de298fecb84031b87f02156cd5
2022-09-20 16:20:35 +00:00
stephan fa5aac7475 Merge kv-vfs-magic-names branch into fiddle-opfs branch and make some kvvfs-relevant tweaks.
FossilOrigin-Name: e3d36dcdd37e59f17a07d3611d08744eb86f439fab82a648490dd608bcaa3185
2022-09-20 16:10:39 +00:00
stephan 89071030db Export the sqlite3_uri_...() family of functions to wasm.
FossilOrigin-Name: 72bebc848fce5c3b4766017d016ccb2360de2bd0cb3e47e710c80dbcb6b8b707
2022-09-20 14:52:26 +00:00
stephan fea03bc0ca Merge opfs-proxy-atomics branch into the fiddle-opfs branch.
FossilOrigin-Name: 25a36920d44544547a84161681cd41e292b4a70df60ac3630791873a79237d98
2022-09-20 14:39:54 +00:00
drh c3b6fdaead When compiled with SQLITE_OS_KV_OPTIONAL, the magic names ":localStorage:"
and ":sessionStorage:" are recognized and converted to use the kv-vfs.

FossilOrigin-Name: c5db9262d0388ccb0e84c6a4b4e2e786dd634f13874e4034ba7b175befa4ce90
2022-09-20 14:36:53 +00:00
stephan 0e0aafc698 Remove an obsolete file.
FossilOrigin-Name: 1e43855498b4329f733bd6e0731841dc884e885de7d2d338d402d05d54309427
2022-09-20 14:21:58 +00:00
stephan b8c8d4e4a0 Speed up de/serialization of func args and return values in the OPFS VFS proxy.
FossilOrigin-Name: 5bf235bbe035e4ace7a54851e190742528af6b4266328a1b8bbb9fb3dd7f2118
2022-09-20 13:25:39 +00:00
stephan c2ccd67689 OPFS proxy: remove one sanity-checking-only level of proxy function to shave off a few microseconds.
FossilOrigin-Name: b534831f3efb8910a17e29956e3e87cc80055ea66e15dbef992b6a556ff042f8
2022-09-20 10:47:36 +00:00
stephan c9e2602e8f Remove extraneous result-code SAB slots. Doc additions.
FossilOrigin-Name: 88de20712bbe3e11ea74af95edc34e9ab9f346f9aa0a30931e5a9e1f96ce57b0
2022-09-20 10:11:52 +00:00
stephan 5e8bb0aa13 An alternative messaging strategy for the OPFS VFS proxy which uses only SharedArrayBuffer and Atomics, instead of worker messages, for communication (only the initial one-time handshake during initialization uses worker messages). It runs speedtest1 approx. 15-20% faster but still 20-ish% slower than WASMFS.
FossilOrigin-Name: a83ee3082d89439ea3ad5737e63e25bebb0f91895aca006ce5fecf5b93a2651a
2022-09-20 08:27:57 +00:00
stephan 138647a552 OPFS VFS: further internal refactoring towards experimenting with a new comms model.
FossilOrigin-Name: 5ca412ced24b4e3af5f467e710a597ed440badf7b8335346aade11d3cad3d1a1
2022-09-20 03:31:02 +00:00
stephan c4b87be3e8 OPFS VFS: moved i/o buffer from per-file to the VFS, and related refactoring, in prep for experimentation with a new inter-worker comms model.
FossilOrigin-Name: d4d63e4580ad8d497310608175308c03c517e051d7865cb66aa0b10356612d7d
2022-09-20 01:28:47 +00:00
drh b22b493338 Clarify comments that describe query flattener restrictions associated with
outer joins.  No code changes.

FossilOrigin-Name: 2647d73bb1876d01851f52cb3fd6af08a962ab336b6d51c160d27b1baf94f75f
2022-09-19 19:25:15 +00:00
stephan aec046a264 Further metrics and buffer-copy optimizations in the OPFS proxy, but with little effect.
FossilOrigin-Name: d1f1fe6f1c60640f7770dfb9245c459a09b8d24ec2ddf664dff77c810bd51f96
2022-09-19 18:22:29 +00:00
drh 316cd40122 Fix a minor comment typo. No changes to code or documentation.
FossilOrigin-Name: 8032db4ade66f70a102abb9d3a49e20620e204c45ad7a954a49d20403985bf07
2022-09-19 17:41:59 +00:00
stephan f815011a08 Cut the speedtest1 runtime of the OPFS VFS proxy by approximately 3/4ths via xRead/xWrite buffer-copying optimizations. Still slower than the WASMFS impl by approx. 1/5th.
FossilOrigin-Name: fb7f287310d74a3e236125ae9c49b859f9263c29ae85161c1bcf9dd0778d8a51
2022-09-19 17:09:09 +00:00
stephan 61418d5a67 Remove an obsolete file. Update wasmfs build for today's changes. Fix the case that OPFS.xTruncate() is passed a BigInt instead of a Number.
FossilOrigin-Name: 976053925013bf1975f5f9222e28ba648af28e305bb6bdae600eb24d0e136bec
2022-09-19 14:56:13 +00:00
stephan 0e0687ccfc Add sqlite3_web_vfs_list() to JS API. Corrected OPFS VFS's registering itself as the default VFS. speedtest1-worker now uses the xDelete() of both the default VFS and OPFS, to avoid that it starts up with a persistent OPFS test db (the native app calls unlink(), but that unlink call operates on a different virtual filesystem than the OPFS VFS).
FossilOrigin-Name: 2ec7e09139a510b9fd29e4c97283b20740a00f369193c6fecbb734f187e81b48
2022-09-19 13:44:23 +00:00
stephan b5ae85eca2 Merge kv-vfs branch into fiddle-opfs. Adjust various JS APIs and apps to deal with the new method of handling kvvfs. Adjust speedtest1 JS build to include sqlite3-api.js so that it can use kvvfs and opfs VFSes. Permit passing of the vfs as a URL parameter to certain demo/test apps. Milestone: speedtest-worker.html?vfs=opfs runs with the standalone OPFS impl.
FossilOrigin-Name: ec09f32f7ae2249aaf27388ad2062982afa8bbbb5f88d236d6d9068bf33ad93d
2022-09-19 13:16:35 +00:00
stephan 5ef7f04775 speedtest1: add --vfs NAME flag and eliminate code duplication in argc size verification for all flags which take a value.
FossilOrigin-Name: 281d09867134e0a057cfadd9bfcbf0e21b8ac9737a278c41973d33a3101be7bc
2022-09-19 11:47:38 +00:00
stephan ba0b157583 Minor doc improvements in demo-123.js.
FossilOrigin-Name: 9370ce94780e974da03d5c74cf9a5983eed333e7b3bc54e605c5f30b3fa99287
2022-09-19 10:13:01 +00:00
stephan 509f40526e Generic cleanups in the OPFS VFS proxies.
FossilOrigin-Name: 7d5f6adc3b964413fc96ad8d2735312c3e58348024cabdd2099682cbf696eaf7
2022-09-19 09:58:01 +00:00
stephan 862281fc47 Correct OPFS VFS xRead() to copy the result buffer if the result code is SQLITE_IOERR_SHORT_READ.
FossilOrigin-Name: 56668f9902c6e896b6c63621a444444c6f58ee20f88a5feae97f1699be35892d
2022-09-19 09:25:25 +00:00
stephan 8766fd20d1 Replace OPFS VFS xSleep() impl with a more efficient one (no Worker round-trip needed).
FossilOrigin-Name: b9773f164878b0a1b7c88cc7a6d1374ea95f64920065e8b2b178a1afffd82fe5
2022-09-19 05:19:04 +00:00
stephan ac51eb7754 Rename demo-oo1.* to demo-123.* and add demo-123-worker.html, which runs the same demo via a Worker. Doc typo fixes.
FossilOrigin-Name: 2e4a005bd35424caeaa99ace23162cf79e2ebdb159475ffad92b85dc864ad764
2022-09-19 03:57:31 +00:00
stephan ed85333977 Disable build of wasmfs-using components on aarch64 (ARM), as wasmfs won't build there.
FossilOrigin-Name: 9a9eeebc2c27b734041089131b4952d7c0440df48ef32f355641aca61d4b30a0
2022-09-19 00:40:53 +00:00
drh bcdb4cc71b Remove a NEVER macro in defragmentPage() that dbsqlfuzz discovered can be
true.  crash-32d9312f145cdce41613573f6431d9a3e439e3d7

FossilOrigin-Name: 90403759e1cf30f7c11fa8170d6df59a0dd138e1de59d2b60bec7ba15d74f67c
2022-09-18 17:59:28 +00:00
stephan f386012069 Numerous cleanups in the JS bits. Removed some now-defunct wasm test files. Expose sqlite3.opfs object containing various OPFS-specific utilities.
FossilOrigin-Name: 26e625d05d9820033b23536f18ad3ddc59ed712ad507d4b0c7fe88abd15d2be8
2022-09-18 17:32:35 +00:00
stephan 0db3089576 Move the OPFS VFS bits back into api/sqlite3-api-opfs.js. Refactor the OPFS VFS init process to use a Promise-returning function which the client must call, as that eliminates any uncertainty about when the VFS (necessarily activated asynchronously) actually becomes available to the client. Rename x-sync-async.* to test-opfs-vfs.* Milestone: first successful test of OPFS without WASMFS.
FossilOrigin-Name: b2abf60dbfa6648f671a3932cb65feb28d05a0d5b7f792351d14f9c13d9798c5
2022-09-18 03:05:55 +00:00
stephan c5313afea7 Move the OPFS VFS bits back into api/sqlite3-api-opfs.js. Refactor the OPFS VFS init process to use a Promise-returning function which the client must call, as that eliminates any uncertainty about when the VFS (necessarily activated asynchronously) actually becomes available to the client.
FossilOrigin-Name: 1c660970d0f62bcfd6e698a72b050d99972a1e39f45a5ac24194a190f8f78ab3
2022-09-18 02:35:30 +00:00
stephan 3e2823cbb6 Plug OPFS methods in to their sqlite3_vfs/io_methods counterparts. Add URL args to control debug output and running of sanity-checks in the OPFS init code.
FossilOrigin-Name: a0e93ed20b2463606a63b03ce8ca41ec1fb22886db5c5c898ace86ba24636f70
2022-09-18 00:16:12 +00:00
stephan 5f4ad92681 Correct OPFS xRead() and xWrite() impls and add a very basic sanity test for them.
FossilOrigin-Name: cd06cc670029763955cf60ffcf944b36d41cb005b859d9b9fd0eea1b6741d0e9
2022-09-17 23:47:20 +00:00
stephan 8200a6d8d7 Implement OPFS xAccess(), albeit with more limited semantics than the VFS API calls for. Add a way for OPFS xDelete() to optionally recursively remove empty dirs left over after deleting a file.
FossilOrigin-Name: c342b5d745f301104c59851c753287ebbbe95a69a56cb522d376d0f3e352c30f
2022-09-17 23:29:27 +00:00
stephan e6f8a09532 Generic cleanups in the OPFS sync/async proxy.
FossilOrigin-Name: f36bddbe54c3acbfaa958042e4d24724f130bdca551401033f9bc63f3da73492
2022-09-17 21:13:26 +00:00
stephan 0731554629 Add the remaining vfs/io_methods wrappers to the OPFS sync/async proxy, but most are not yet tested.
FossilOrigin-Name: 44db9132145b3072488ea91db53f6c06be74544beccad5fd07efd22c0f03dc04
2022-09-17 20:50:12 +00:00
drh a50d3b7a5d Fix an uninitialized variable in the decoder kv-vfs.
FossilOrigin-Name: 354726aa6c399053785f29104de15091629ce4bc275b9e2205cb3656a9e81cd7
2022-09-17 18:31:31 +00:00
drh 20a9ed1dc6 Include the kv-vfs as an optional VFS on unix builds if the
SQLITE_OS_KV_OPTIONAL compile-time option is present.

FossilOrigin-Name: 852812d1e2ec3c53ad7c6c64662b37d861fefcf1baeee3d58eba88bcb3f6d8df
2022-09-17 18:29:49 +00:00
drh b9fbc558f7 Merge the latest trunk enhancements into the kv-vfs branch.
FossilOrigin-Name: 37c7ca25a6e837e7f83b96a32e2b1a455730e48a48012c458ae2e734a3ccdd1f
2022-09-17 17:26:44 +00:00
stephan 132a87baa3 Add initial bits of an experimental async-impl-via-synchronous-interface proxy intended to marshal OPFS via sqlite3_vfs API.
FossilOrigin-Name: 38da059b472415da52f57de7332fbeb8a91e3add1f4be3ff9c1924b52672f77c
2022-09-17 15:08:22 +00:00
stephan ce260f4e43 Merge kv-vfs branch into fiddle-opfs branch. Adjust speedtest1 --size flags to account for new size limit.
FossilOrigin-Name: afb79050e635f3c698e51f06c346cbf23b096cfda7d0f1d8e68514ea0c25b7b7
2022-09-16 20:16:50 +00:00
drh 756440febc Corrections to the xRead method for databases in the os_kv.c VFS so that it
correctly reads the header, and thus avoids unnecessary cache flushes.  This
changes also includes an optimization to the header read logic.

FossilOrigin-Name: ef54961ce69fddb4cfeeff0860288de2858a6f7a5aa396691e8e99933eb9af54
2022-09-16 15:19:04 +00:00
stephan 81439a07f0 When calculating kvvfs sessionStorage/localStorage size, multiply it by 2 to account for JS using 16-bit characters.
FossilOrigin-Name: 52d1b185b9f6cee1eb3dec436f47e0f52e4621a127abfad8c27f92fd78147889
2022-09-16 12:49:45 +00:00
stephan 4c72171b60 Merge kv-vfs branch into fiddle-opfs branch for [21915af560b1|synchronous=off fix]. Remove some duplicate debug output in OPFS test code.
FossilOrigin-Name: 13899bb98c80525276d2484598b94e4206358f243f06d45c02700024f7e226fd
2022-09-16 11:45:09 +00:00
drh 84e5076787 Fix os_kv.c so that it uses SQLITE_FCNTL_SYNC and hence
works even with PRAGMA synchronous=OFF.

FossilOrigin-Name: 21915af560b111aeeaee751790356151a5f063c2fc703dd4b35b22dc393409fb
2022-09-16 11:37:01 +00:00
stephan 57db2174d5 Add batch-runner-kvvfs.html, a kvvfs-specific build of batch-runner.html. Reduce the speedtest1 --size X value for the batch list generation to 5 so that the kvvfs batch runner can handle it.
FossilOrigin-Name: d8df25920a047d5cf2093cc6233128c5e6057a9104d0c4397e643645bd646fe1
2022-09-16 02:30:49 +00:00
stephan 58bcfe075d Remove --nosync flag from speedtest1-kvvfs.html, as that seems to be the trigger for the 'no such table: z1' error. That app now warns if that flag is passed to it via URL args.
FossilOrigin-Name: ad0677e8abcc077636d1cf1d8485be4943506382581edf832e6b8a2021560040
2022-09-16 02:28:03 +00:00
stephan d22cfa8c80 Pull the src/os_kv.c part of [13839759f8f4] into the kv-vfs branch.
FossilOrigin-Name: e334449912d5176e355d02024a07ed867741f71c9d10ce6744ca800414bf3eeb
2022-09-16 01:08:06 +00:00
stephan 0144a8482a Add return value checks to kvstorageWrite(), necessary for recognizing storage-full errors in the JS binding. speedtest1-kvvfs.html runs successfully on localStorage with --size 1 to 6 and starts failing with storage shortage at --size 7.
FossilOrigin-Name: 13839759f8f45e4eb0aa6a5052801f3964d5b2dc2e427e5e91ee6692176381eb
2022-09-16 01:05:19 +00:00
stephan 28ef9bddb3 More work on the synchronous OPFS experimentation. Numerous wasm/js build tweaks. Add speeedtest-wasmfs.html, the wasmfs/opfs counterpart of speedtest1.html.
FossilOrigin-Name: 00ee49a3a2c148480f614e49a0ee5b35a255758c0a53693f0b464b31e7a4045b
2022-09-15 06:42:41 +00:00
dan 73390f09c2 Fix windows builds of recover extension.
FossilOrigin-Name: abcbb6abfe08fc590123f0aa1bd72cfdecc75908f078f1348dc0e957de98bf52
2022-09-15 03:54:52 +00:00
stephan dae7518ae4 Remove some stale comments. Get scratchpad-opfs-worker2.js running again in prep for reuse in experimenting with the OPFS all-synchronous API.
FossilOrigin-Name: 4cbbd370186f84e440f496e7f11c641d7dc1723acc46e4a31483392e0eb046e9
2022-09-15 03:16:49 +00:00
stephan 0117693f62 Split wasmfs-enabled build of sqlite3.js/wasm into sqlite3-wasmfs.js/wasm, as enabling wasmfs breaks all tests/demos which run from a Worker thread.
FossilOrigin-Name: 08476f3c218d45846e7496bdae0b06e2122466111fdf2aa2aabb1805b15ef982
2022-09-15 03:09:00 +00:00
stephan 409505c743 Clean up some JS documentation.
FossilOrigin-Name: 925fdbfc6c1f9f06951346bc0d4fb81ffb5797d5f1123728931973f6cb1a0efa
2022-09-15 02:27:48 +00:00
dan 6fa0a11c7b Include recovery extension in configure/make builds of testfixture.
FossilOrigin-Name: d2f4652144c4a54012a2176c178c5ade3463bd017515f472cfa8dafdde192df3
2022-09-14 20:45:46 +00:00
dan 3c24342841 Extra tests and fixes.
FossilOrigin-Name: deed5336931b23bb507c064d08e9899b33f04e4f7eee03beb8d7147eb4caa030
2022-09-14 18:57:46 +00:00
dan b8eaf9a10d Fix recovery of utf-16 databases.
FossilOrigin-Name: 5b05be0861f35804270fbd184ad4b89c23e98cc2fbd56b9e4fe6197daef5fe49
2022-09-14 16:37:59 +00:00
dan 322967df59 Add OOM tests for the recovery extension.
FossilOrigin-Name: 9b6b4c7162439a889144edb561356afc66436db921a867c20871f0c556716502
2022-09-13 20:40:57 +00:00
dan a3a6d63b40 Fix a broken error handling case in the recovery extension.
FossilOrigin-Name: 60089547e1fc77ecc02f207ebf75ee3160e5ff25f41d12e02e170fd7fde66602
2022-09-13 19:47:01 +00:00
stephan 5b91500796 Add/apply various kvvfs-specific utility APIs to the JS layer to assist in testing and analysis. Correct a backwards default arg check for sqlite3ApiBootstrap(). Add exports for sqlite3_db_handle(), sqlite3_file_control(), and the SQLITE_FCNTL_xxx enum.
FossilOrigin-Name: 0d78961870ee9f22f1ba16d423377d28dcc36e04b1e31ffd57f3e2fd51f8f0f2
2022-09-13 19:27:03 +00:00
dan 7985e05a97 Add tests. Deal issues surrounding aborting recovery from within the SQL callback, and avoiding the pending-byte page.
FossilOrigin-Name: 4e97dd31f5240d9231167ae172a5116426c42177a1ed3c5422b9d51b762d5a87
2022-09-13 18:08:24 +00:00
stephan 23d39ce54d Get testing1.js working with a kvvfs build.
FossilOrigin-Name: 333a45725d1708e0fefa559c33ce1c7eeb425cdb04f594b1f2b48166c1478c79
2022-09-12 22:27:00 +00:00
stephan 5fd8f27bfb Remove an extraneous key-copy op in the EM_JS impl of kvstorageDelete().
FossilOrigin-Name: 1c5aeee45564c14e7e2e7730f3f52106339ea3148fb5aa786fa767a35db46f51
2022-09-12 20:21:34 +00:00
stephan 0b769f5b4a Merge kv-vfs branch into fiddle-opfs and add speedtest1-kvvfs.html test app (which currently fails early on).
FossilOrigin-Name: 8b1608a9a37131121cb3a0cb1e8dbad5e39dc1fc2a341d056f09537f179b2e7a
2022-09-12 20:18:28 +00:00
dan 5ca0b38605 Fix some problems with handling corrupt database in the recovery extension.
FossilOrigin-Name: ed318be8241981ef96334ba13d3201a717cc812a59aed64e3dc67f7e7e71854b
2022-09-12 20:02:33 +00:00
drh b126ec18b6 Fix the &lt;sys/time.h&gt; include in os_kv.c.
FossilOrigin-Name: 878cc93e779c3857adc711f212520f007256274fcd3f6f3d72c754a937fcd198
2022-09-12 19:33:20 +00:00
drh d8bb0b5ae6 Add a gettimeofday()-based implementation of xCurrentTimeInt64() to os_kv.c.
FossilOrigin-Name: e393ed650ef124143f84e9d787fb996e308dd7af6b8f50df72a6f085b67bf9c3
2022-09-12 19:29:34 +00:00
dan aede9b5bd3 More tests for the recover module.
FossilOrigin-Name: 37fb093b95c6b7d7ad07a275697df73b69f9fb5c5549aea8544b26e38f24833f
2022-09-12 19:23:50 +00:00
drh bb19512438 Fix a debugging/testing edit in the previous check-in.
FossilOrigin-Name: 6fc8d34c0ae1f8277544be741f2f0835fad8e475d35bd24573224ccc1699b8bd
2022-09-12 18:10:41 +00:00
stephan a002cc174f Add sqlite3.oo1.DB.clearKvvfsStorage(). Add controls to kvvfs1.js demo to reset and query the db without requiring the dev console.
FossilOrigin-Name: d845c6c22bd5d3fffc66e0566df346d690dd8bd1fc1688e312161b1a1edcfd79
2022-09-12 17:59:04 +00:00
drh 6acd7b0a75 Faster text decoder for kv_os.c.
FossilOrigin-Name: 3354a2edb762d70ccc31d4d25f81b70e644d76e01cb1e81d2e97b5414d809d30
2022-09-12 17:44:35 +00:00
stephan 5360f5fcff Merge kv-vfs branch into fiddle-opfs branch to add kvvfs-based wasm build and demo.
FossilOrigin-Name: a7d8b26acd3c1ae344369e4d70804c0cab45272c0983cfd32d616a0a7b28acb9
2022-09-12 16:09:50 +00:00
drh 3e4e697d1c New run-time options to the speed-check.sh script.
FossilOrigin-Name: ff46bc9d2a844dde9dafa157114f4d9ee157205ca5c08ed9ee32f018de310e62
2022-09-12 16:07:24 +00:00
drh 1ad51ffe21 Fix uninitialized variable in rollback-journal processing in os_kv.c
FossilOrigin-Name: e49682c5eac91958f143e639c5656ca54560d14f5805d514bf4aa0c206e63844
2022-09-12 15:59:35 +00:00
stephan 2811759d5e Resolve missing kvvfs JS test: sqlite3_initialize() must be called by the client in this build. Add basic sanity test of kvvfs using sessionStorage().
FossilOrigin-Name: 250a935aeb94d3fadec0d3fe22de85de4e658e2fdb3be3aa9a8bbc8f7b7d8414
2022-09-12 13:05:54 +00:00
drh 6b013afb88 Fix the amalgamation so that it builds with the standard unix backend again.
FossilOrigin-Name: 0adf158f4e5791339988185cc29347c75056b062e0db65b5999fdfa1f433c1ed
2022-09-12 12:41:07 +00:00
stephan ad5125a624 Initial build of kvvfs in wasm. It loads but cannot find the VFS for as-yet-unknown reasons (sqlite3 shell works fine), and most APIs throw "null function or function signature mismatch" from deep within wasm, presumably as a side effect of the "missing" VFS.
FossilOrigin-Name: 1a2f24a0bdfc6eaae478916b8f4f9c6b63ead9964534fc2951fb4e995ffe61f1
2022-09-12 12:39:28 +00:00
stephan 73079dba00 Minor cleanups and documentation in the wasm pieces.
FossilOrigin-Name: 4e6ce329872eb733ba2f7f7879747c52761ae97790fd8ed169a25a79854cc3d9
2022-09-11 16:59:40 +00:00
stephan 2a91126d76 Correct the result code from kvstorageRead() for the OOM case to be a negative value.
FossilOrigin-Name: cdbf09fa1b0c93aeb3222a157de33a4688ae629c2b829ffff0f1f62364c5ae1c
2022-09-11 05:44:15 +00:00
stephan ade4f4d645 Minor cleanups and docs for the EM_JS() impls of the kvvfs read/write/delete ops.
FossilOrigin-Name: 53b7572e441be4b4b29b4228d0f95b24457d7faaf6c0b568ed5c970a55e21ffb
2022-09-11 05:38:39 +00:00
stephan e99f742a32 Add EM_JS() impl for kvstorageRead().
FossilOrigin-Name: 06610314fcf644f323c2f7ae11d7f4349b195e66d0ebbee590438dd99d97eb96
2022-09-11 04:49:29 +00:00
stephan d15822965b Initial prototype impls of write/delete-key ops for the pending kvvfs which use sessionStorage or localStorage for db page storage. read-key op is pending.
FossilOrigin-Name: a4bd96f5348e607d0fcb627b751f9d86a188173a4b3bfb2c95f92913a78bd31e
2022-09-11 02:43:08 +00:00
dan 65660916dc Rework recover extension code for readability.
FossilOrigin-Name: 1a2540960e40e3c8c622448fd3862e249bd463c29ae4ce5e39942e942533f60a
2022-09-10 20:01:49 +00:00
drh c6c9c6aad0 Improved comments in os_kv.c. Better names for the key/value name spaces.
FossilOrigin-Name: 8e1652a3856765c9146cc2a7e3b598a2dc7dc84c556b35eab9a35184514384b9
2022-09-10 18:38:21 +00:00
drh 7585f49a0a Move the vfskv.c extension to src/os_kv.c and make it part of the amalgamation,
activated if and only if SQLITE_OS_KV is true.

FossilOrigin-Name: f6632e69c2ec1a7ddc4e51f3567e3bc082ee94a6dd51fdafdc0c3bf386a32d4c
2022-09-10 18:20:59 +00:00
dan bc2e7fc228 Further fixes to comments in sqlite3recover.h. Also rework some data structures in sqlite3recover.c.
FossilOrigin-Name: 599d1f8ec2f9e24924a6f9e66c85664360c7b95531b07a4efe1dd8c096b3fc99
2022-09-09 20:44:56 +00:00
mistachkin bdb6368d72 Fix harmless compiler warning seen with MSVC.
FossilOrigin-Name: 73c4c68d3b4c16caf8281dabddd7365d24691e5ee2da89b1783eca66bfbd9280
2022-09-09 17:50:29 +00:00
dan 7920162093 Handle recovery of virtual tables by recovering each shadow table individually, then writing the CREATE VIRTUAL TABLE statement directly into the sqlite_schema table.
FossilOrigin-Name: 5f2d5ccd56c06c3468377126acfd4be39b79b05bb6fb09b674b2e185df143aa3
2022-09-09 16:25:19 +00:00
drh 25f62508f5 Database must be named either "local" or "session". Each has a distinct
namespace.

FossilOrigin-Name: c8e41279294ea7c2f041c7d4cbbd85fce47d55f2f56180ca837316f7dfd75237
2022-09-09 16:16:33 +00:00
drh f7377d5763 Separate sqlite3_io_methods objects for database files and journals.
FossilOrigin-Name: 74fbf6c2a97729e481d5562344e960d0c237aeb1f07240262d32a24fb1f4b5a3
2022-09-09 14:22:41 +00:00
drh 126976c9f8 Simple reading and writing now works.
FossilOrigin-Name: 00845ac9ef2616e90f5f6a20da3dd040fa8bdcfe73f72fe9c06039561150a82d
2022-09-09 11:41:54 +00:00
stephan f5bf66c875 Remove a reference to a completed TODO.
FossilOrigin-Name: 757ad69607201a26802a304839b8454b1634712458539d6aa8cf999ab2447e59
2022-09-09 05:39:36 +00:00
stephan e66b26818b speedtest1 wasm: add a link in the worker variant which launches the main-thread variant with the selected CLI flags. Append collected stdout/stderr to the main-thread page after execution is finished to avoid having to open the dev tools (which inexplicably slows down wasm execution).
FossilOrigin-Name: 02709ee2beab36d144b807fd9ffaee639e3c1bdd1908a34e05f3fd23dad2ef66
2022-09-09 04:50:18 +00:00
dan 46d4398440 Update comments in sqlite3recover.h.
FossilOrigin-Name: 14164047c43e3ca43aa010c77ea00dfa85400e15645ee0f5b90a677898b6a836
2022-09-08 21:43:18 +00:00
stephan dd628ed58b Make use of the --big-transactions flag in the speedtest1 JS apps.
FossilOrigin-Name: f2846dcbcaac7880394fb14597c3a60ed310419128c4c5b863cd771a7e5cdeb5
2022-09-08 21:33:50 +00:00
stephan e07ce18be5 Add speedtest1 --big-transactions flag to cause its large tests which rely on implicit transactions to be wrapped in BEGIN/COMMIT, per /chat discussion. Added to support of the WASMFS build, which slows down significantly when thousands of implicit transactions are used.
FossilOrigin-Name: 51395c005da46b7fa5a5f28809dd8fea263a6bac2b1492759b3d5a5aa7d399ca
2022-09-08 21:09:42 +00:00
stephan 1174c23e0d Minor build cleanups and tweaks in the speedtest1 wasm apps.
FossilOrigin-Name: 5240fb4d795dea826f23cf5d2152b519f5a46f49bb2499ea868fa7c7f4ce788b
2022-09-08 20:04:52 +00:00
stephan fa7098d543 Experimentally add --nomutex flag to speedtest1 to have it open db with the SQLITE_OPEN_NOMUTEX flag.
FossilOrigin-Name: 45ef576b2ee6369ab1e3aa2ad284764bb334f92a69a33d88b7292bbc0a1b1fda
2022-09-08 19:53:59 +00:00
dan 9a27d65044 Update the shell to use the recover extension for the .recover command.
FossilOrigin-Name: ae832e77084eddd696c80cb926d070a5db9d45dce34156a02522b3140e8f5e8b
2022-09-08 19:22:29 +00:00
dan 3887ffe82a Fix problems with recovering the sqlite_sequence table.
FossilOrigin-Name: 356d2209ea5f6b69ce15b62027c63419c2d039e52f01c74a3810a6317abf4fb0
2022-09-08 17:42:33 +00:00
drh 7cd81af3a9 Compiles and loads as an extension. Starts to run but quickly hits issues.
FossilOrigin-Name: 2e38726f46918b28b5c638967f960a20afd3fe84ad245f3bea39a1d64980435b
2022-09-08 17:12:12 +00:00
drh e3485ee996 Compiles without error, but untested.
FossilOrigin-Name: a329939c32e33d8d00066ba3d4327f07cca1b4e67de0b8d85f1e7f98afe40954
2022-09-08 16:27:50 +00:00
drh cb94132d9f Code snapshot. Completely untested. Probably does not compile.
FossilOrigin-Name: 51e267696d25f2f83b5bb847d5254ab15573ef1a16ea3d7dd8279c73c0bee539
2022-09-08 15:48:01 +00:00
stephan 44a87f08ef Add speedtest1-worker.html, an interactive Worker-thread variant of speedtest1.html. Add ext/wasm/index.html to act as a gateway to the various test pages.
FossilOrigin-Name: f16c68ee6d5ebb8dec2ab656dbab2ddb5f1d5133153ad553f986b31020adaa38
2022-09-08 15:30:59 +00:00
dan 4a08e793c6 Add new test file recoverclobber.test.
FossilOrigin-Name: cb4e950c472bd24a79a8505a7f8e4c3a0f7821648297d05cc760738b777d5149
2022-09-08 11:04:23 +00:00
drh b53e0992b2 Enhance an assert() to impose for tighter constraints on the operation of pcache.
FossilOrigin-Name: 42105eb43a916a7cd839fa6c582eaffaef17f50b23c3e05142400c379feb73c7
2022-09-07 20:11:22 +00:00
drh 8c983ddb67 An improved technique for ensuring that the Rekey() operation does not
overwrite an existing page number.  This approach does not change the
semantics of the underlying pluggable pcache and it is easier to prove
correct.  This replaces the changes at
[aadd38f99a3e5abc] and [81cff9f1955874aa].

FossilOrigin-Name: 7dbddde79e3ca1b81e00288616fc27434698ce6dcb47714728fce8602ae91f45
2022-09-07 19:28:18 +00:00
drh 59ece7e106 Non-working code towards a VFS for text key/value storage.
FossilOrigin-Name: f9c89ee8d5ef46342bea78fa8d4da058d9ea628183ec985642bbda1cdfeacd5f
2022-09-07 17:29:22 +00:00
dan abb28667f1 Ensure that the recover extension properly escapes CR and NL characters in text mode. Also that it holds transactions open on both input and output databases for the duration of a recovery operation.
FossilOrigin-Name: 6cca8913e703635ad89415a60fc84000ac188d9df43f45594b8ad87facb91d54
2022-09-07 16:41:33 +00:00
stephan 3a59dd12d2 Add a note about Emscripten's -sSINGLE_FILE flag, why it would be nice, and why we can't use it.
FossilOrigin-Name: 5ea0623630d769a8f3f07a40cd119be86b631192cdb5178131876b01b40ee5e0
2022-09-06 23:04:51 +00:00
stephan 8fc8b5b35f Get speedtest1.js working with WASMFS/OPFS.
FossilOrigin-Name: 40e60f570d4f489d58d12e27c1c067b41d6c5a5e374c5fce0baa8881ef183216
2022-09-06 20:17:15 +00:00
dan 497b3e6a11 Tests and a fix for the SQLITE_RECOVER_ROWIDS option.
FossilOrigin-Name: 1d5000f5718004110776ff58284d824854a93fe1cd1f6d8a4e8b8b0c2b2c3076
2022-09-06 19:38:06 +00:00
stephan 100b496dd2 Initial build of speedtest1.wasm and speedtest1.html with which to run it.
FossilOrigin-Name: 4441535e3e54dc1881f700fa3878964eb8554a6790fd6aa32945f7cc104a8467
2022-09-06 16:47:43 +00:00
stephan 09aa80d109 Minor internal doc clarifications.
FossilOrigin-Name: 09796cc2bfce7bc4ce11db9673d20737259e9928f0484660cba3a9751f7d01c5
2022-09-06 16:35:54 +00:00
stephan ae1ed83831 Merge trunk into fiddle-opfs branch.
FossilOrigin-Name: 7f76eaec793720db87415a476ddf539bc4dea3e74c8e5406d6739206aebdacc2
2022-09-06 09:59:06 +00:00
drh 2e440a0801 Add the tool/omittest-msvc.tcl script that will try to build using MSVC
using various compile-time options, to ensure that the compile-time options
all build without errors.

FossilOrigin-Name: 6b00ecb59fd303f7985902c35a46db9e729201d4beaedea46596b728d9e4b1c8
2022-09-05 22:54:36 +00:00
drh 0c4517a61a Get the tool/omittest-msvc.tcl script working.
FossilOrigin-Name: 82b89f8a074858a81d841dfc26436e8d39ce4907b8f989eba4d848db16758303
2022-09-05 22:53:24 +00:00
dan 108c51b6ae Fix a problem with script mode and lost-and-found tables.
FossilOrigin-Name: 09ec588d2fe24dd321e88318fe90a9ae912cbc73c8a2d59a10c821625dd12d9d
2022-09-05 21:22:35 +00:00
dan d5e3fe50f8 Add a mode to output SQL statements instead of populating a database to the recover extension.
FossilOrigin-Name: 73058416e7da6581000898b7988a7010e2ce6632246f4c12b4398700c7744b83
2022-09-05 21:00:22 +00:00
drh 4c8404e555 Add a prototype for a script, similar to tool/omittest.tcl, that is designed
to test builds using MSVC to ensure they work with various OMIT options.

FossilOrigin-Name: b1e37a0bd31fa9f8e58c2859a80c23a682b4702eefab2c55b243f1e21d475d6c
2022-09-05 20:42:01 +00:00
drh 6e440ab3de Fix the windows build so that it works with -DSQLITE_OMIT_AUTOINIT.
FossilOrigin-Name: f74a5ea8c986dc33d3afcda169c38abbe55728c56716cf9991a5e2ef7fc4917a
2022-09-05 18:17:03 +00:00
dan a768b67dcc Add the SQLITE_RECOVER_ROWIDS option. To specify that rowid values that are not also explicit INTEGER PRIMARY KEY values should be preserved.
FossilOrigin-Name: 69cc9aba56a196bbd159bd24868aa5ccc60bed0dc612d09ed8a3ae898f156809
2022-09-05 15:56:09 +00:00
stephan 49cb8d7314 Minor cleanups in OO API #1. Add Sudoku SQL to batch-runner.js's list.
FossilOrigin-Name: 4488cb5798f34cbba14eb8e2aa5da8420c14a85d37d278d357406aedd5c3a9e5
2022-09-05 13:24:08 +00:00
dan 7302079dbe Add an option to assume the freelist is corrupt when recovering data.
FossilOrigin-Name: 253e498f5200b8b3e2bc309587af108dd1cec8a884b3d2a49d5406525c9a4b4c
2022-09-03 21:08:38 +00:00
dan be2e212cf9 Take the freelist into account when recovering data that is not linked in to any tree associated with a schema entry.
FossilOrigin-Name: dbd1f1efb349a9c8886e42b3f07d3f4c576924136f111558c7294d0a272e415a
2022-09-03 20:31:36 +00:00
dan f2f8a3a348 Further work on making the recover extension compatible with the .recover command.
FossilOrigin-Name: f2ac315844d8db1bd1c6950a4fef7c459ddd37cc21a8f3daafa5639fad8118e2
2022-09-03 20:07:39 +00:00
stephan cdefd5d046 wasm: minor text and build cleanups.
FossilOrigin-Name: 36ceef94e1935f5e85f79e489cd0ed265a77820fb68329c190794df5e076bf84
2022-09-03 11:41:44 +00:00
dan ad617b4d6d Ensure the Pager.journalOff variable is zeroed if an error occurs while writing the initial header to the journal file.
FossilOrigin-Name: da7af290960ab8a04a1f55cdc5eeac36b47fa194edf67f0a05daa4b7f2a4071c
2022-09-02 21:19:24 +00:00
drh 173b418e60 Fix an assert() associated with the dbsqlfuzz error at [8372468bb5d8922c].
FossilOrigin-Name: 54251f81ebc43839cc97f91d2df4c320c1b96b5690cc11ce45b60c087c9becd6
2022-09-02 17:25:25 +00:00
drh 5fc3a8a32f If sqlite3PcacheMove() really performs a swap, then be sure to renumber the
second page.

FossilOrigin-Name: 81cff9f1955874aade55daa94263f58f06d966bd51ad558755f92777069a7347
2022-09-02 15:09:55 +00:00
drh 4e9bf5ace3 Enhance the pcache1 implementation so that during an xRekey operation if
another page already exists at the destination, that other page gets moved
to the source key.

FossilOrigin-Name: aadd38f99a3e5abcf9bef49f4367752f163cc79500a28f812bb71969d7de419c
2022-09-02 14:29:54 +00:00
drh e04c9f4b33 Mutex protect access to the sqlite3_test_directory and sqlite3_data_directory
global variables.  See
[forum:/forumpost/719a11e1314d1c70|forum thread 719a11e1314d1c70].

FossilOrigin-Name: 8e6ad3a3e942a326cf16432e16d6596c7206c05b6f45cd0ff3a9b836bcfc9deb
2022-09-02 11:45:26 +00:00
drh fee6431392 Improved mutex protection of the sqlite3_temp_directory and
sqlite3_data_directory global variables.

FossilOrigin-Name: ebbe9634d6dde9e097f61fb98a79111e46de422b7bbbd9ed3af7b6f22aacf5ec
2022-09-02 11:12:16 +00:00
drh 18a3a48db1 Experimental changes to put sqlite3_temp_directory behind a mutex.
FossilOrigin-Name: 5ee3515fbb88bf1ae5f8b507844f82dcc429380b6ebeab9b09b52b25ee60a60d
2022-09-02 00:36:16 +00:00
dan 6c86783f9a Further work on making recovery extension compatible with the shell tool ".recover" code.
FossilOrigin-Name: 8df7c7d0dcd1b2fcdad00e765a9868407f0ced02ac4432ee2cdf25d83b130759
2022-09-01 21:00:39 +00:00
drh 44132244fa Defer deleting a transient SELECT statement associated with a flattening
of one arm of a compound SELECT until after the parse has completed.

FossilOrigin-Name: 1c4157c71cd1e062a9c2c79787d17e34e340f28ce1e40573851dfe174f5da7d7
2022-09-01 13:51:09 +00:00
drh a3fc683c80 In the query planner, add a heuristic that will reduce the cost of a full
table scan for a materialized view or subquery if the full scan is the
outer-most loop.  This is shown to speed up some queries.

FossilOrigin-Name: 609fbb94b8f01d6792e5941ab23ce041313d359f6788c4dde6b1ca749ab49137
2022-09-01 10:29:02 +00:00
dan 73b09b87d5 Add new files for an extension to recover data from corrupted databases.
FossilOrigin-Name: f8298eeba01cb5b02ac4d642c06f3801331ca90edea533ea898a3283981a9e49
2022-08-31 20:45:43 +00:00
drh 9c3a114ca0 Enhance the b-tree page sorting code to ensure that sqlite3PagerRekey() never
overloads a page number and uses only the PENDING_BYTE page for temporary
storage.

FossilOrigin-Name: 5007742886bd20de20be3973737cf46b010359911615eb3da69cd262bd9a2435
2022-08-31 15:04:42 +00:00
stephan 53f635df55 batch-runner.js: add rudimentary metrics export to CSV. Add a toggle to reverse the log output mode (in normal order or most recent first).
FossilOrigin-Name: b26e2bc05537a1f451db1bdd36a824d71c3ea25a130b6285f31ff9799d65fa7a
2022-08-30 17:57:50 +00:00
drh 78d15f097a Improved comments in pcache1.c. No changes to code.
FossilOrigin-Name: dd017bb1b3e31c7692d29dc4865d6bda871e429978c8738a39160d0114e5bf9b
2022-08-30 16:54:41 +00:00
stephan ffc0cbb024 batch-runner.js: re-enable unlink-before-run so that OPFS speedtest1 batch can work.
FossilOrigin-Name: ba08f7a7f12601aa580a8dc493b43cdd5ab65c87d5e4b3fd2f549343e45c2d2a
2022-08-30 10:26:33 +00:00
stephan fbf0f488cf batch-runner.js: move generated SQL files into ./sql and start adding hand-written ones (like the Mandelbrot) to that set.
FossilOrigin-Name: 06c106a7d23e4486dbed092757b7588688226ad35539ecc31378a8497f59d1ec
2022-08-30 10:04:08 +00:00
stephan 429899ddad Remove the .timer script entry from fiddle app because emscripten has removed getrusage(), which breaks the timer.
FossilOrigin-Name: 9034f19ae50f196cc2b94478edfcc8d765b08bcf383166f6212b3522dea63c01
2022-08-30 09:51:24 +00:00
stephan 5bb5965710 wasm util: remove superfluous function.bind() calls to eliminate a level of call() indirection.
FossilOrigin-Name: 1aab9627983ef0f016b01f78564e79cf815ed14d4b1b6dc04ec627b96f1b2f70
2022-08-30 09:49:30 +00:00
drh 4d28830861 Any function call can abort. Take this into account when deciding if a DML
statement needs a statement journal.  See
[forum:/forumpost/9b9e4716c0d7bbd1|forum thread 9b9e4716c0d7bbd1] for more
information.

FossilOrigin-Name: 5c95ae6c9b93b9bcf698bb1cad93b2da2e28121b35e7c539b1ddc0ef2de33cfe
2022-08-30 00:11:51 +00:00
stephan 2f06bf2541 Lots of tweaking in batch-runner.js. Minor internal API update in OO #1 API.
FossilOrigin-Name: 24b82b9504db3d8e1335c2300b133f897dc1a541026dc24be5b0ffd8be66d977
2022-08-29 18:58:38 +00:00
stephan 49a785fa34 Add test descriptions to the speedtest1 '-- begin' markers for potential display by the downstream JS code which uses those markers.
FossilOrigin-Name: e5b7006f0f57f10a490d7eaeb7df77251a2f684602fed8ff161d8ce60033e7bc
2022-08-29 17:41:16 +00:00
stephan 2cae138fba Add batch-runner.js for running batch SQL scripts with timing info.
FossilOrigin-Name: 11f3ed61150c5940da6c157e5063e70c3aa0628dfd0023c47bb65b00af74ab1f
2022-08-29 12:39:34 +00:00
stephan f2e624ea91 Add get/setPtrValue() to the common wasm utils.
FossilOrigin-Name: 24d70fc458c6002d5ff3c9f8ce7c66bde299b32aca6417c2dd1236e1412b036d
2022-08-29 12:31:57 +00:00
stephan 9a2efd8e1f Add begin/end comment markers to the test blocks in speedtest1 --script output to facilitate chopping up the output into chunks for JS-side processing.
FossilOrigin-Name: ef0b7ef2d2e19b1f9437fdd7e24f040f662d9907d1fa17c6a3892fcf091b849e
2022-08-29 09:51:17 +00:00
stephan d7d1098baa oo #1 api: correct a case where a null callback is called. Rename some vars for clarity. Increase wasm-side memory in order to be able to load the speedtest1 output.
FossilOrigin-Name: b5058f14fadbc8a1886f27cff08593dd2c8e2b2cb6d7bed3b8733a55f031989f
2022-08-29 08:04:55 +00:00
drh f0f025b340 More assert() statements in the page cache.
FossilOrigin-Name: 7c96a56c0d1de966844da6c5a84c0cd6066130a10724797ce6f228a9182d9b85
2022-08-27 16:11:00 +00:00
drh f6e3e31625 Ensure that every pcache page always has either the PGHDR_DIRTY or the
PGHDR_CLEAN bit set, even during transient page reshuffling during btree
balancing.

FossilOrigin-Name: e67f03c166277951725c194674c84da61c152a5820aa6df55a726f7dda838e92
2022-08-27 14:43:34 +00:00
stephan a3825e78bd Merge changes from trunk into the fiddle-opfs branch.
FossilOrigin-Name: 34279797be0922b9df05e0d4f327f8582ab25fb6fb21583f8441ddf5deded891
2022-08-25 19:38:54 +00:00
drh 23593f8e99 Ensure that sqlite3_prepare() inputs always have a semicolon terminator in
speedtest1.

FossilOrigin-Name: c72756b0f2db30c622f00f43be9245d50e36049bd7740ee6332164f0c48f9c3d
2022-08-25 19:29:35 +00:00
drh 09cb5eb5ac Add the --script option to speedtest1.
FossilOrigin-Name: 1c87d7c58d5aec83f9e2ae3771a81aa17cfae0cf06169025a5db085e2d5749f9
2022-08-25 19:19:25 +00:00
dan aa07b36dd5 Remove a NEVER() macro for a condition that is actually reachable following an OOM. dbsqlfuzz crash-6ef3cd3b18ccc5de86120950a0498641acd90a33.txt.
FossilOrigin-Name: b573e2cffa5fedc893ed30e76e47022b3617ac5583e1eb486afa810b2514c419
2022-08-25 13:32:55 +00:00
stephan 335ad5264f Consolidate oo1.DB.exec() and oo1.DB.execMulti() into oo1.DB.exec(). This is a bit less efficient but certainly easier for a client to deal with and lightens the maintenance burden.
FossilOrigin-Name: 7eff7213dff553b76d7ce45063e3c4a19544716611a0b609593d704076b38d0b
2022-08-25 13:27:52 +00:00
stephan 9afff9f3c5 Refactor and expand the worker1 docs, consolidating them into the top of their file instead of scattered around the internals. Accommodate an API change from yesterday in demo-oo1.js.
FossilOrigin-Name: 0a65747047322b7b585e281ac275e437ce3f46e1d06105c19117213929a906ad
2022-08-25 11:39:12 +00:00
stephan 407f75378e Change DB.exec() rowMode default from 'stmt' to 'array', per /chat discussion. Add DB.exec() rowMode option for fetching a specific column by name. Add result column names to worker1 exec() callback interface, as there's otherwise no way to get that info from a worker.
FossilOrigin-Name: 1bb37e5c477b9eb098362f74a45a55be23d450fe45cdff58c1cbff08b5b3998f
2022-08-24 20:57:37 +00:00
stephan 3734401a95 Expand the worker1 'exec' op handling for per-row callbacks for API-level consistency and smooth some edges between worker1 core and worker1-promiser. Add worker1 'config-get' message to fetch the serializable parts of the sqlite3.config state. Improve the 'open' op's handling of the 'persistent' option (noting that we cannot yet test that case from a worker).
FossilOrigin-Name: 509f8839201ec1ea4863bd31493e6c29a0721ca6340755bb96656b828758fea7
2022-08-24 18:39:46 +00:00
drh 7383f5a7d9 Add a mutex to the sqlite3_db_config() interface so that it is threadsafe
when two or more threads call it on the same database connection at the same
time.

FossilOrigin-Name: 459ad8846ee1ee2d3b277a291c47121692bdf477e779b06e77be8338f62237a6
2022-08-24 17:59:00 +00:00
stephan 9c765e7945 js: resolve the mysterious "extra" unhandled exception notification, caused by inadvertently forking one promise into two separate ones (failing to properly reassign a then() result). Fix a typo in new Worker 1 code which caused the DB(filename) name to be incorrect.
FossilOrigin-Name: 7467ac88801224089b51c6ba7924f93283dd87beca602a186c83632df26cfc85
2022-08-24 14:50:10 +00:00
dan 2ce2b779bb Fix an inefficiency in the ".dump" command when outputing large blob literals.
FossilOrigin-Name: c055d05dbdfd4643d5052c6e6a736c78651fdfcd78f15f791af903df3814832d
2022-08-24 11:51:31 +00:00
stephan 9a34509a06 More work on how to configure the sqlite3 JS API bootstrapping process from higher-level code. Initial version of sqlite3-worker1-promiser, a Promise-based proxy for the Worker API #1.
FossilOrigin-Name: b030f321bd5a38cdd5d6f6735f201afa62d30d2b0ba02e67f055b4895553a878
2022-08-24 05:59:23 +00:00
stephan efeee19a95 The very basics of a Promise-based proxy for the Worker #1 API. Still requires considerable cleanup, testing, and a solution for the exec-callback-via-event-type-name problem.
FossilOrigin-Name: 1e447849fb65887e806e3348a8a68f70ea6802bc0a1e56c385a279f27cc0cdda
2022-08-24 00:51:39 +00:00
stephan a9ac2ed069 Significant restructuring of the Worker #1 request/response object structures to improve readability and clarity.
FossilOrigin-Name: 03b9db9b98cb36faa7de5a8a64d2e13c4aeaadfefb33ac92bb41056f6be3f121
2022-08-24 00:10:45 +00:00
drh e5928b17ca Change the names of the Vdbe.pVNext and Vdbe.ppVPrev fields to make them
unique.  Change to ppVPrev to save a few bytes and a few CPU cycles.

FossilOrigin-Name: 34b8ea31877ae8b40729d37b3f51ae7e15f38be841881ea4a37c9c8f0a52896d
2022-08-23 20:11:01 +00:00
drh 35908b167f Enhance assert() statements to enforce tighter bounds on the P5 operand of
the OP_Next and OP_Prev opcodes.

FossilOrigin-Name: 4e0a07fc6f96e6e7726506b7a5ee942461c1381501f253893fa94d76023b634f
2022-08-23 17:51:39 +00:00
stephan 8c45a9f952 Wasm build flag tweaks and documentation.
FossilOrigin-Name: c8eb3aa8e0f487f14791214caf70d1aa03866e01345c7fa1d5607c24c39dde1d
2022-08-23 17:02:46 +00:00
stephan f7415736d1 Add mksourceid binary to the clean rules and $(TESTPROGS) to distclean.
FossilOrigin-Name: ae3e82f5a3332bea261aca6a0dd02063cf7056c023204cc10f1ae18d75249f91
2022-08-23 16:55:19 +00:00
stephan ae708b2b01 More experimentation with how client-side config state can be passed on to initialize the JS-side sqlite3 API.
FossilOrigin-Name: ea2acc454c012a62556f6d0623d6eff60736d24aa214a64462b423623ef44d47
2022-08-22 21:37:17 +00:00
drh 376860ba88 Performance enhancement for sqlite3DbFree().
FossilOrigin-Name: c296a9d958ec360fc8d217363348b4918d665bccb3c4f27503a2dcef7db49052
2022-08-22 15:18:37 +00:00
stephan 7a8a0fceec Merge in trunk.
FossilOrigin-Name: e215d55a97e1ccbca3101621374444d2381d87ef8e8fde5271e31c8b714e43e9
2022-08-22 14:03:11 +00:00
stephan e3cd67603d Refactor JS API amalgamation such that the bootstrapping/configuration is deferred until the whole amalgamation is available, to facilitate providing clients with a way to initialize the API with their own config (noting that we're still one small level of refactoring away from being able to actually do that).
FossilOrigin-Name: 9dbe9a6aecec43b51057375ef1d2d632db0d17eac8b7552c20cc91fc2f1a55d1
2022-08-22 13:34:13 +00:00
stephan 64d04a8d9f wasm: accommodated a JS API rename.
FossilOrigin-Name: 00991335c4dae56232e999398e5e82d8161903ba7d084b16a73a150e83f1f782
2022-08-22 08:55:10 +00:00
drh 41ce47c4f4 Add the new internal interface sqlite3DbNNFreeNN(db,ptr) where both the
db and ptr parameters are guaranteed to be non-NULL.  Use this where
appropriate to save more than 2 million CPU cycles on the standard
performance test.

FossilOrigin-Name: e5eaa80e81fdf86f2875a912b880272b8d099b82b08e945a7988c5dd0fe9d6b5
2022-08-22 02:00:26 +00:00
drh 05cb948bf7 Merge the test case for dbsqlfuzz 18fe4e257be7fa3ecfb0424ab7427e41e97ef9e3
assertion fault, which is fixed with the previous check-in.

FossilOrigin-Name: 2d13ec086e96a5446462ce0f689c40c8196e740cd693f5967bfe9eb961f03463
2022-08-20 19:45:41 +00:00
drh 00378fde23 Enhance the enforcement of SQLITE_VTAB_DIRECTONLY so that it applies to
DML statements within triggers.  Do not allow DML stratements against
virtual tables within triggers unless either the virtual table is
SQLITE_VTAB_INNOCUOUS or PRAGMA trusted_schema is ON.

FossilOrigin-Name: 9433ea4070f52135be64569057f439e7bdb4b3f425d87167c9ebda50011210c1
2022-08-20 19:33:04 +00:00
dan f56291ed02 Add test case for fuzzer case crash-18fe4e.
FossilOrigin-Name: 8372468bb5d8922cf20b8bbee34cfd6044ceb09c26a4efa79a5e6df2c7c4b730
2022-08-19 20:10:51 +00:00
drh 4ff42a82f7 Add notes to ext/wasm/README.md explaining how to run tests on a remote
machine.

FossilOrigin-Name: 7a3c444fb515413254b426908e4d3528ccc664a629628c23b7b85bd21c060d0e
2022-08-18 15:53:27 +00:00
stephan d869a21d13 javascript: rename and simplify DB.callInTransaction() as DB.transaction(). Add DB.savepoint(), which works the same as transaction() but uses savepoints. Correct concatenation of arguments to SQLite3Error to use spaces instead of commas. Test that demo-oo1.js works with persistent OPFS storage (output differs due to persistent rows, but the demo works).
FossilOrigin-Name: e8c323f12b6223bc9dcbbec40698969c7917128aa50cf599c247df23f607ae61
2022-08-18 12:21:58 +00:00
stephan fed91737f5 Improve an exception check in demo-oo1.js.
FossilOrigin-Name: 55e1b775fa7ec492817cc847036df7794c3c22b78558e9e9c513f24c775dedab
2022-08-18 11:16:27 +00:00
drh 78ed74ef8e In the ".dump" command of the CLI, if a schema statement ends with an
unterminated comment, try to terminate that comment prior to appending
the ";" at the end.  [forum:/forumpost/d7be961c5c|Forum post d7be961c5c].

FossilOrigin-Name: 96e112da1ac56767cf49f26132833745b6020d2c60f5c36f86ca84f87ad30c81
2022-08-17 20:18:34 +00:00
drh 16b03c0196 Enhance the "PRAGMA integrity_check" statement so that it verifies the rows of
a WITHOUT ROWID table are in the correct order.

FossilOrigin-Name: 62f934bff495850d0763e07ffa44a557f066ecba9d039363f32287213cba819f
2022-08-17 18:07:52 +00:00
drh 0348fc722f Minor code simplification in the code generator for PRAGMA integrity check.
FossilOrigin-Name: a3b9c7a6c9be5c78a93e5125f16237d2d84b977eca81f527af0198e96435a995
2022-08-17 17:14:36 +00:00
stephan 453af2f6cc Minor cleanups, reorgs, and doc updates for the JS APIs. Renamed sqlite3(-api)-worker.js to sqlite3(-api)-worker1.js, for symmetry with sqlite3-api-oo1.js.
FossilOrigin-Name: f5059ee6f9fc55a381cbf08a30dfb9a5636c0b44341e42f4e9f12a3b109b5507
2022-08-17 16:44:05 +00:00
stephan 6e901b07a3 wasm: minor cleanups in the OO API #1 demo.
FossilOrigin-Name: b9cdcc06a8f70694d10ee5b1a0fd9f08f4c705ce576e5103bbafb36fc9cc2122
2022-08-16 17:29:59 +00:00
drh a8771a1736 Change the legacy RC4-based PRNG to use the RFC-7539 chacha20 algorithm.
FossilOrigin-Name: a0f801151925e882e120f6ab685dcacb9d3268d25b52bc665c5b927bcc7dda1e
2022-08-16 17:18:00 +00:00
drh cd05aafa56 Fix obsolete comments. Add new comments. Fix non-standard spacing.
FossilOrigin-Name: a0d224c6a69941dad1f2b35edcc7ddee343b99eae2aeed74043461f3e97ef5b4
2022-08-16 16:57:33 +00:00
drh 534945ad07 Fix an off-by-one error in the ChaCha20 initialization code.
FossilOrigin-Name: 72e220eed446ea9a02a6ef03e09a01bcb8bbca1f3b32d2e0bf52a17d9722e2f0
2022-08-16 16:40:54 +00:00
stephan e0c582850e wasm: add a small demo/presentation app for JS OO API #1 and make a few minor additions to that API.
FossilOrigin-Name: d6d79b661a1c6137d4693393e02416da4858d58dc84d144081a48d523655b483
2022-08-16 16:36:19 +00:00
stephan ba851ae72e wasm: move another file and update testing1/testing2 to account for [e38d00c2b82d]. Disable wasmfs by default as it breaks the worker-based module loader (reason as yet unknown).
FossilOrigin-Name: 6dad5e0573ee866657ee10b43e55b86fc9caac7a66c13bdbd35c3625a4783f14
2022-08-16 16:16:25 +00:00
stephan 8ac2d8510e wasm: accommodate moving generated sqlite3.js in the previous checkin.
FossilOrigin-Name: 41762f9518bb51b8b23ae6507628d6d3256044e1f2aca6e7251dc57722062c42
2022-08-16 16:11:20 +00:00
stephan ab7de45084 wasm: disable shared cache mode by default. Experimentally move wasm-build generated files up one dir to rule the extra dir out as a problem for Emscripten-related worker-loading failures.
FossilOrigin-Name: e38d00c2b82d7e51ec04cd739514f255edde679b8ddab31fa944b3517d45c3ea
2022-08-16 16:06:12 +00:00
drh 0f201fccc0 Omit an unnecessary test case from corruptN.test that does not work with the
new RFC-7539 PRNG.

FossilOrigin-Name: d9e8c65ed25c4f6222c737f4244d5362dbe433d357f7d133765157446cf4e925
2022-08-16 14:09:51 +00:00
dan 2756f806f2 Add assert() statements to verify that the SQLITE_OPEN_EXCLUSIVE flag is always passed to the VFS when opening a temporary file.
FossilOrigin-Name: e123da49ccae61d591abded52f4721aa10f20d75935c9a3e3fe826a9b8df2317
2022-08-16 10:52:35 +00:00
drh 9113c87ef3 Replace the RC4-based PRNG with one based on ChaCha20. 3x faster.
FossilOrigin-Name: 084d8776fa95c75440530028171c56547a341c9a952ba2f29bb533b538603c78
2022-08-16 00:04:40 +00:00
dan 207cb6f670 Extra test for SQLITE_MAX_COMPOUND_SELECT.
FossilOrigin-Name: c271096736889530f392ff37e631a77f3bc9c46b290dbda245fa05249f4410fc
2022-08-15 19:23:15 +00:00
drh 5187c955f6 The new --script option to dbtotxt.c looks for an SQL script at the head of
the file and generates a CLI script that will construct the database then run
the SQL.

FossilOrigin-Name: 6170e638ebeb12cc40c3247324237978401f701afc270de88ad03e183e82cefc
2022-08-15 18:36:08 +00:00
drh 9c5e1e40e3 In the documentation emphasize that the use of shared cache is discouraged.
Fix test cases so that they all work with shared cache disabled.

FossilOrigin-Name: 52c3ae063e133c5f88cad2c3084cf46218f865ac817ab937e3529d2c6a7af300
2022-08-15 12:26:26 +00:00
stephan 0761780bc4 Add worker-style variant of the tests added in [ae24ac0f7dd9], but building this with wasmfs causes them to throw inexplicable exceptions from the Emscripten glue (without wasmfs it builds and runs fine, but storage is not persistent).
FossilOrigin-Name: 6401595e59179c5c0f6e51c5362cf4391787e7a55b9c6ca655746e30d3251f2b
2022-08-13 17:13:16 +00:00
stephan a7234901b2 wasmfs: use unix-none VFS by default to avoid locking errors in non-OPFS mode.
FossilOrigin-Name: 75561dea1a1afe9cb0a7d58dd82fa519e51cf42e330922cfd8e9ccdf6db4dc0f
2022-08-13 16:36:06 +00:00
stephan 1025227272 Add scratchpad/test app for WASMFS/OPFS running in the main window thread. Enable WASMFS by default in the library build.
FossilOrigin-Name: ae24ac0f7dd9e12a40de0f6ccd61a16f010804da454085f886c217cc600cdba4
2022-08-13 16:11:38 +00:00
stephan 9a4c63b0fc Cleanups in the wasmfs/opfs integration but disable it in order to get the build into a known-working state before continuing with experimentation.
FossilOrigin-Name: 41045be752a5bd7966849638f3ca56f4905308df70f79f2cb6196ca7dce9d525
2022-08-13 13:56:00 +00:00
stephan 90218aec7a Remove OPFS from the fiddle build for the time being - will re-enable once the breakage is figured out via testing with the core API.
FossilOrigin-Name: 3bc510a614973eafa60960a99bedb063594a693bdbfd80d7eb480b293b4ab811
2022-08-13 13:51:56 +00:00
stephan f79451eea7 wasm OO API #1: added DB.callInTransaction() and Stmt.stepFinalize().
FossilOrigin-Name: e37dddc1dd9c0530e4b1c6cb0ca7cba7451caa37734d383c9b47f378d7222242
2022-08-13 13:46:19 +00:00
stephan 2cf599cff8 Corrected TextDecoder.decode() usage to run when its input references a SharedArrayBuffer.
FossilOrigin-Name: d4d773405c579e7efd95be8d81fe14d71218e62e44c523d38e02f89424ba6ce8
2022-08-13 13:42:07 +00:00
stephan 587f9a0a99 Use new -DSQLITE_DEFAULT_UNIX_VFS="unix-none" for fiddle build to bypass OPFS locking errors.
FossilOrigin-Name: b3a93ec75acb38535691d6eaceb5a1a218a5ee3f755a1e12c9255b90567fc795
2022-08-12 18:54:08 +00:00
drh 087f143f87 Add the (undocumented) SQLITE_DEFAULT_UNIX_VFS compile-time option.
FossilOrigin-Name: 49828bdec5f926cd18a069d39a5db0b1e1f3528a2affcfbaa1cf7b98aca51b3b
2022-08-12 18:46:01 +00:00
stephan 24ddbca8d3 Updated fiddle deps to ensure that sqlite3.c is built first.
FossilOrigin-Name: f0ca02611484f5031076d7fae88845e9931715e9108ec0572629200d4f6636ef
2022-08-12 18:07:22 +00:00
stephan a579f4400d Build fiddle with WASMFS OPFS support and attempt to use it if available. It does not work because of an inexplicable exception in Emscripten-generated code and perpetually-locked db, but it's not yet clear why.
FossilOrigin-Name: a16f0a46ec88c560f73d5664e4bf53fb5dd1a22e99a92c11b5c8d784816c3282
2022-08-12 17:57:09 +00:00
stephan 5b0e63eb4c Minor wasm-related doc clarification and remove an obsolete code comment.
FossilOrigin-Name: 1b1f650a08da93da97ed3a96b9a3e4eac567472c266188c02a9bffe1cf620e53
2022-08-12 17:55:18 +00:00
stephan e1c3462484 wasm: document the role of sqlite3-wasm.c. Other minor doc updates.
FossilOrigin-Name: 4c10b9b18feca82440273f8192fef951ad051bbfd8aad4d3c840cf6375130afd
2022-08-12 13:07:21 +00:00
stephan e6d1650c5b wasm: corrected (in as-yet unused code) a flags check.
FossilOrigin-Name: 06b6113783dd81252a5dd125e1cddb52a9d4e387c74cfb3ba88475e47a31060a
2022-08-12 09:32:51 +00:00
stephan fbfe5af903 Wasm-related doc additions and tweaks.
FossilOrigin-Name: ec55a3aa44a80f661dd451b9ea567449ea4c7353901cfd44a4b50ca10f00ddbd
2022-08-11 15:45:32 +00:00
stephan 9289c47df7 Merge in wasm-cleanups branch, reorganizing and updating the wasm-related components.
FossilOrigin-Name: c072594d3de3d6893c5d4a9d68439b84d043325f105b0d065575765a6e66c196
2022-08-11 09:18:09 +00:00
drh f0d12d87fa Fix another harmless comment typo that causes a typo in the documentation.
FossilOrigin-Name: bb084adb53386d8e52ca1e818a8322d2ec641b73fd8568cee01cc74c0ee9f265
2022-08-10 18:40:43 +00:00
drh 778d334085 Remove (harmless) duplicate words in comments used to generate parts of the
documentation.  [forum:/forumpost/54abbe9ccd|forum post 54abbe9ccd]

FossilOrigin-Name: b5e4f0db09ff7790862357df3c6fd38a2dcdfc82ff51b9f0d9470517648c844d
2022-08-10 18:33:57 +00:00
dan 217635f709 Fix handling of columns with names that are SQL keywords in the ".expert" command.
FossilOrigin-Name: 5e1b8221c385deb04a3ff5aafb2e9fc55aecc6ffc68328674e3afe56c4273e29
2022-08-10 15:29:21 +00:00
222 changed files with 26206 additions and 6995 deletions
+34 -154
View File
@@ -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
View File
@@ -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.
Vendored
+2 -2
View 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
View File
@@ -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.
+10
View File
@@ -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} {
+4
View File
@@ -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
View File
@@ -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
View File
@@ -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;
+1 -1
View File
@@ -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;
}
+1 -1
View File
@@ -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
View File
@@ -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;
}
+1
View File
@@ -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
View File
@@ -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
View File
@@ -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
+54
View File
@@ -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
+5 -4
View File
@@ -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
View File
@@ -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:
+28
View File
@@ -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
View File
@@ -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;
}
+133 -42
View File
@@ -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 */
+277
View File
@@ -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
+14
View File
@@ -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
}
+50
View File
@@ -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
+67
View File
@@ -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
+289
View File
@@ -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
+84
View File
@@ -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
+102
View File
@@ -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
+189
View File
@@ -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
+100
View File
@@ -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
+50
View File
@@ -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
+87
View File
@@ -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
+52
View File
@@ -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
+249
View File
@@ -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 */
+311
View File
@@ -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
View File
@@ -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
-14
View File
@@ -1,14 +0,0 @@
FS
addFunction
allocateUTF8OnStack
ccall
cwrap
getValue
intArrayFromString
lengthBytesUTF8
removeFunction
setValue
stackAlloc
stackRestore
stackSave
stringToUTF8Array
+524 -156
View File
@@ -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
########################################################################
+23
View File
@@ -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
View File
@@ -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
+25 -3
View File
@@ -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
+133
View File
@@ -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.
+103
View File
@@ -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. */
})();
+7
View File
@@ -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.
*/
+2 -1
View File
@@ -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(...)*/;
+7 -8
View File
@@ -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!
*/
+100
View File
@@ -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. */
+54 -28
View File
@@ -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
View File
@@ -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*/
});
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-421
View File
@@ -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});
+654
View File
@@ -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.
*/
+830
View File
@@ -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));
File diff suppressed because it is too large Load Diff
+259
View File
@@ -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();
});
})();
+90
View File
@@ -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>
+588
View File
@@ -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);
});
})();
+73 -10
View File
@@ -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*/);
+32 -1
View File
@@ -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
View File
@@ -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);
}
+44
View File
@@ -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>
+24
View File
@@ -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>
+289
View File
@@ -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);
}
});
})();
+49
View File
@@ -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>
+114
View File
@@ -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>
+270
View File
@@ -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;
})();
+101
View File
@@ -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)
+194
View File
@@ -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
View File
@@ -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
View File
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>
+90
View File
@@ -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>
+115
View File
@@ -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>
+13 -4
View File
@@ -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);
};
/**
+1 -3
View File
@@ -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>
-178
View File
@@ -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
}
-10
View File
@@ -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
+333
View File
@@ -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>
+40
View File
@@ -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>
+70
View File
@@ -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);
})();
+149
View File
@@ -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>
+372
View File
@@ -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>&rarr; <a id='link-main-thread' href='#' target='speedtest-main'
title='Start speedtest1.html with the selected flags'>speedtest1</a>
</span>
<span>&rarr; <a id='link-wasmfs' href='#' target='speedtest-wasmfs'
title='Start speedtest1-wasmfs.html with the selected flags'>speedtest1-wasmfs</a>
</span>
<span>&rarr; <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('&nbsp;');
};
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>
+99
View File
@@ -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());
});
})();
+174
View File
@@ -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>
+17
View File
@@ -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
+17
View File
@@ -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;
+28
View File
@@ -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;
+26
View File
@@ -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>
+85
View File
@@ -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);
});
+63
View File
@@ -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>
+28
View File
@@ -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
View File
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