├── .cargo └── config.toml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── libsqlite3-sys ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── Upgrade.md ├── bindgen-bindings │ └── bindgen_3.14.0.rs ├── build.rs ├── sqlcipher │ ├── LICENSE │ ├── bindgen_bundled_version.rs │ ├── sqlite3.c │ ├── sqlite3.h │ └── sqlite3ext.h ├── sqlite3 │ ├── bindgen_bundled_version.rs │ ├── sqlite3.c │ ├── sqlite3.h │ ├── sqlite3ext.h │ ├── wasm32-unknown-unknown │ │ ├── include │ │ │ ├── assert.h │ │ │ ├── ctype.h │ │ │ ├── math.h │ │ │ ├── stdio.h │ │ │ ├── stdlib.h │ │ │ ├── string.h │ │ │ ├── sys │ │ │ │ └── types.h │ │ │ └── time.h │ │ └── libc │ │ │ ├── stdlib │ │ │ └── qsort.c │ │ │ └── string │ │ │ ├── strcmp.c │ │ │ ├── strcspn.c │ │ │ ├── strlen.c │ │ │ ├── strncmp.c │ │ │ └── strrchr.c │ └── wasm32-wasi-vfs.c ├── src │ ├── error.rs │ ├── lib.rs │ └── wasm32_unknown_unknown.rs ├── upgrade.sh ├── upgrade_sqlcipher.sh └── wrapper.h ├── rustfmt.toml ├── scripts └── build.sh ├── src ├── lib.rs └── sqlite_opfs.rs └── tests └── worker.rs /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [build] 2 | rustflags = ["--cfg=web_sys_unstable_apis"] 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | /doc/ 3 | Cargo.lock 4 | /pkg/ 5 | /trash/ 6 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "logseq-sqlite" 3 | version = "0.1.7" 4 | edition = "2021" 5 | authors = ["Andelf "] 6 | repository = "https://github.com/logseq/logseq-db" 7 | documentation = "https://docs.rs/logseq-sqlite" 8 | homepage = "https://github.com/logseq/logseq-db" 9 | categories = [] 10 | description = "@logseq/sqlite db wrapper" 11 | keywords = [] 12 | readme = "README.md" 13 | license = "AGPL-3.0-or-later" 14 | 15 | [lib] 16 | crate-type = ["cdylib", "rlib"] 17 | 18 | [features] 19 | default = ["console_error_panic_hook"] 20 | 21 | [dependencies] 22 | js-sys = "0.3.65" 23 | wasm-bindgen = "0.2.88" 24 | web-sys = { version = "0.3.65", features = [ 25 | "console", 26 | "FileSystemHandle", 27 | "FileSystemHandleKind", 28 | "FileSystemFileHandle", 29 | "FileSystemEntry", 30 | "File", 31 | "FileSystem", 32 | "FileReader", 33 | "Navigator", 34 | "StorageManager", 35 | "TextEncoder", 36 | "TextDecoder", 37 | "Window", 38 | "Worker", 39 | "WorkerGlobalScope", 40 | "WorkerNavigator", 41 | "FileSystemDirectoryHandle", 42 | "FileSystemGetFileOptions", 43 | "FileSystemSyncAccessHandle", 44 | "FileSystemReadWriteOptions", 45 | "BroadcastChannel", 46 | "AddEventListenerOptions", 47 | "EventTarget", 48 | "EventListener", 49 | "Event", 50 | ] } 51 | 52 | # The `console_error_panic_hook` crate provides better debugging of panics by 53 | # logging them with `console.error`. This is great for development, but requires 54 | # all the `std::fmt` and `std::panicking` infrastructure, so isn't great for 55 | # code size when deploying. 56 | console_error_panic_hook = { version = "0.1.7", optional = true } 57 | wasm-bindgen-futures = "0.4.38" 58 | 59 | getrandom = { version = "0.2", features = ["js"] } 60 | uuid = { version = "1.5.0", features = ["v4"] } 61 | once_cell = "1.18.0" 62 | serde = { version = "1.0.193", features = ["derive"] } 63 | serde-wasm-bindgen = "0.6.0" 64 | rusqlite = { version = "0.29.0", features = ["bundled"] } 65 | libsqlite3-sys = { path = "./libsqlite3-sys", features = ["bundled"] } 66 | serde_json = "1.0.108" 67 | bincode = "1.3.3" 68 | 69 | [profile.release] 70 | opt-level = "s" 71 | lto = true 72 | debug = true 73 | 74 | [dev-dependencies] 75 | wasm-bindgen-test = "0.3.37" 76 | 77 | [patch.crates-io] 78 | libsqlite3-sys = { path = "./libsqlite3-sys" } 79 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | 663 | Additional permission under GNU GPL version 3 section 7 664 | 665 | If you modify this Program, or any covered work, by linking or combining it with any of the below libraries (or a modified version of that library), containing parts covered by the terms of any of the below libraries, the licensors of this Program grant you additional permission to convey the resulting work. 666 | 667 | * cider/cider-nrepl 668 | * clojure-complete 669 | * com.cemerick/friend 670 | * compojure 671 | * environ 672 | * hiccup 673 | * medley 674 | * org.clojure/clojure 675 | * org.clojure/clojurescript 676 | * org.clojure/core.async 677 | * org.clojure/core.cache 678 | * org.clojure/core.incubator 679 | * org.clojure/core.logic 680 | * org.clojure/core.match 681 | * org.clojure/core.memoize 682 | * org.clojure/data.csv 683 | * org.clojure/data.json 684 | * org.clojure/data.priority-map 685 | * org.clojure/java.classpath 686 | * org.clojure/java.jdbc 687 | * org.clojure/math.numeric-tower 688 | * org.clojure/tools.analyzer 689 | * org.clojure/tools.analyzer.jvm 690 | * org.clojure/tools.logging 691 | * org.clojure/tools.macro 692 | * org.clojure/tools.namespace 693 | * org.clojure/tools.nrepl 694 | * org.clojure/tools.reader 695 | * org.tcrawley/dynapath 696 | * refactor-nrepl 697 | * slingshot 698 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # logseq-sqlite 2 | 3 | ![npm](https://img.shields.io/npm/v/%40logseq/sqlite) 4 | 5 | Logseq's sqlite DB backend. 6 | 7 | Based on and wa-sqlite's sahpool. 8 | 9 | ## Build 10 | 11 | ```console 12 | ./scripts/build.sh 13 | ``` 14 | -------------------------------------------------------------------------------- /libsqlite3-sys/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | /doc/ 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /libsqlite3-sys/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "libsqlite3-sys" 3 | version = "0.26.0" 4 | authors = ["The rusqlite developers"] 5 | edition = "2018" 6 | repository = "https://github.com/rusqlite/rusqlite" 7 | description = "Native bindings to the libsqlite3 library" 8 | license = "MIT" 9 | links = "sqlite3" 10 | build = "build.rs" 11 | keywords = ["sqlite", "sqlcipher", "ffi"] 12 | categories = ["external-ffi-bindings"] 13 | 14 | [features] 15 | default = ["min_sqlite_version_3_14_0"] 16 | bundled = ["cc", "bundled_bindings"] 17 | bundled-windows = ["cc", "bundled_bindings"] 18 | bundled-sqlcipher = ["bundled"] 19 | bundled-sqlcipher-vendored-openssl = ["bundled-sqlcipher", "openssl-sys/vendored"] 20 | buildtime_bindgen = ["bindgen", "pkg-config", "vcpkg"] 21 | sqlcipher = [] 22 | min_sqlite_version_3_14_0 = ["pkg-config", "vcpkg"] 23 | # Bundle only the bindings file. Note that this does nothing if 24 | # `buildtime_bindgen` is enabled. 25 | bundled_bindings = [] 26 | # sqlite3_unlock_notify >= 3.6.12 27 | unlock_notify = [] 28 | # 3.13.0 29 | preupdate_hook = ["buildtime_bindgen"] 30 | # 3.13.0 31 | session = ["preupdate_hook", "buildtime_bindgen"] 32 | in_gecko = [] 33 | with-asan = [] 34 | wasm32-wasi-vfs = [] 35 | 36 | # lowest version shipped with Windows 10.0.10586 was 3.8.8.3 37 | # 38 | # Note that because `winsqlite3.dll` exports SQLite functions using a atypical 39 | # ABI on 32-bit systems, this is currently unsupported on these. This may change 40 | # in the future. 41 | winsqlite3 = [] 42 | 43 | [dependencies] 44 | openssl-sys = { version = "0.9", optional = true } 45 | 46 | [target.wasm32-unknown-unknown.dependencies] 47 | getrandom = { version = "0.2", features = ["js"] } 48 | js-sys = "0.3" 49 | 50 | [build-dependencies] 51 | bindgen = { version = "0.66", optional = true, default-features = false, features = ["runtime"] } 52 | pkg-config = { version = "0.3.19", optional = true } 53 | cc = { version = "1.0", optional = true } 54 | vcpkg = { version = "0.2", optional = true } 55 | -------------------------------------------------------------------------------- /libsqlite3-sys/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014-2021 The rusqlite developers 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /libsqlite3-sys/README.md: -------------------------------------------------------------------------------- 1 | # Rusqlite 2 | 3 | [![Latest Version](https://img.shields.io/crates/v/rusqlite.svg)](https://crates.io/crates/rusqlite) 4 | [![Documentation](https://docs.rs/rusqlite/badge.svg)](https://docs.rs/rusqlite) 5 | [![Build Status (GitHub)](https://github.com/rusqlite/rusqlite/workflows/CI/badge.svg)](https://github.com/rusqlite/rusqlite/actions) 6 | [![Build Status (AppVeyor)](https://ci.appveyor.com/api/projects/status/github/rusqlite/rusqlite?branch=master&svg=true)](https://ci.appveyor.com/project/rusqlite/rusqlite) 7 | [![Code Coverage](https://codecov.io/gh/rusqlite/rusqlite/branch/master/graph/badge.svg)](https://codecov.io/gh/rusqlite/rusqlite) 8 | [![Dependency Status](https://deps.rs/repo/github/rusqlite/rusqlite/status.svg)](https://deps.rs/repo/github/rusqlite/rusqlite) 9 | [![Discord Chat](https://img.shields.io/discord/927966344266256434.svg?logo=discord)](https://discord.gg/nFYfGPB8g4) 10 | 11 | Rusqlite is an ergonomic wrapper for using SQLite from Rust. 12 | 13 | Historically, the API was based on the one from [`rust-postgres`](https://github.com/sfackler/rust-postgres). However, the two have diverged in many ways, and no compatibility between the two is intended. 14 | 15 | ## Usage 16 | 17 | In your Cargo.toml: 18 | 19 | ```toml 20 | [dependencies] 21 | # `bundled` causes us to automatically compile and link in an up to date 22 | # version of SQLite for you. This avoids many common build issues, and 23 | # avoids depending on the version of SQLite on the users system (or your 24 | # system), which may be old or missing. It's the right choice for most 25 | # programs that control their own SQLite databases. 26 | # 27 | # That said, it's not ideal for all scenarios and in particular, generic 28 | # libraries built around `rusqlite` should probably not enable it, which 29 | # is why it is not a default feature -- it could become hard to disable. 30 | rusqlite = { version = "0.29.0", features = ["bundled"] } 31 | ``` 32 | 33 | Simple example usage: 34 | 35 | ```rust 36 | use rusqlite::{Connection, Result}; 37 | 38 | #[derive(Debug)] 39 | struct Person { 40 | id: i32, 41 | name: String, 42 | data: Option>, 43 | } 44 | 45 | fn main() -> Result<()> { 46 | let conn = Connection::open_in_memory()?; 47 | 48 | conn.execute( 49 | "CREATE TABLE person ( 50 | id INTEGER PRIMARY KEY, 51 | name TEXT NOT NULL, 52 | data BLOB 53 | )", 54 | (), // empty list of parameters. 55 | )?; 56 | let me = Person { 57 | id: 0, 58 | name: "Steven".to_string(), 59 | data: None, 60 | }; 61 | conn.execute( 62 | "INSERT INTO person (name, data) VALUES (?1, ?2)", 63 | (&me.name, &me.data), 64 | )?; 65 | 66 | let mut stmt = conn.prepare("SELECT id, name, data FROM person")?; 67 | let person_iter = stmt.query_map([], |row| { 68 | Ok(Person { 69 | id: row.get(0)?, 70 | name: row.get(1)?, 71 | data: row.get(2)?, 72 | }) 73 | })?; 74 | 75 | for person in person_iter { 76 | println!("Found person {:?}", person.unwrap()); 77 | } 78 | Ok(()) 79 | } 80 | ``` 81 | 82 | ### Supported SQLite Versions 83 | 84 | The base `rusqlite` package supports SQLite version 3.14.0 or newer. If you need 85 | support for older versions, please file an issue. Some cargo features require a 86 | newer SQLite version; see details below. 87 | 88 | ### Optional Features 89 | 90 | Rusqlite provides several features that are behind [Cargo 91 | features](https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section). They are: 92 | 93 | * [`load_extension`](https://docs.rs/rusqlite/~0/rusqlite/struct.LoadExtensionGuard.html) 94 | allows loading dynamic library-based SQLite extensions. 95 | * [`backup`](https://docs.rs/rusqlite/~0/rusqlite/backup/index.html) 96 | allows use of SQLite's online backup API. Note: This feature requires SQLite 3.6.11 or later. 97 | * [`functions`](https://docs.rs/rusqlite/~0/rusqlite/functions/index.html) 98 | allows you to load Rust closures into SQLite connections for use in queries. 99 | Note: This feature requires SQLite 3.7.3 or later. 100 | * `window` for [window function](https://www.sqlite.org/windowfunctions.html) support (`fun(...) OVER ...`). (Implies `functions`.) 101 | * [`trace`](https://docs.rs/rusqlite/~0/rusqlite/trace/index.html) 102 | allows hooks into SQLite's tracing and profiling APIs. Note: This feature 103 | requires SQLite 3.6.23 or later. 104 | * [`blob`](https://docs.rs/rusqlite/~0/rusqlite/blob/index.html) 105 | gives `std::io::{Read, Write, Seek}` access to SQL BLOBs. Note: This feature 106 | requires SQLite 3.7.4 or later. 107 | * [`limits`](https://docs.rs/rusqlite/~0/rusqlite/struct.Connection.html#method.limit) 108 | allows you to set and retrieve SQLite's per connection limits. 109 | * `chrono` implements [`FromSql`](https://docs.rs/rusqlite/~0/rusqlite/types/trait.FromSql.html) 110 | and [`ToSql`](https://docs.rs/rusqlite/~0/rusqlite/types/trait.ToSql.html) for various 111 | types from the [`chrono` crate](https://crates.io/crates/chrono). 112 | * `serde_json` implements [`FromSql`](https://docs.rs/rusqlite/~0/rusqlite/types/trait.FromSql.html) 113 | and [`ToSql`](https://docs.rs/rusqlite/~0/rusqlite/types/trait.ToSql.html) for the 114 | `Value` type from the [`serde_json` crate](https://crates.io/crates/serde_json). 115 | * `time` implements [`FromSql`](https://docs.rs/rusqlite/~0/rusqlite/types/trait.FromSql.html) 116 | and [`ToSql`](https://docs.rs/rusqlite/~0/rusqlite/types/trait.ToSql.html) for the 117 | `time::OffsetDateTime` type from the [`time` crate](https://crates.io/crates/time). 118 | * `url` implements [`FromSql`](https://docs.rs/rusqlite/~0/rusqlite/types/trait.FromSql.html) 119 | and [`ToSql`](https://docs.rs/rusqlite/~0/rusqlite/types/trait.ToSql.html) for the 120 | `Url` type from the [`url` crate](https://crates.io/crates/url). 121 | * `bundled` uses a bundled version of SQLite. This is a good option for cases where linking to SQLite is complicated, such as Windows. 122 | * `sqlcipher` looks for the SQLCipher library to link against instead of SQLite. This feature overrides `bundled`. 123 | * `bundled-sqlcipher` uses a bundled version of SQLCipher. This searches for and links against a system-installed crypto library to provide the crypto implementation. 124 | * `bundled-sqlcipher-vendored-openssl` allows using bundled-sqlcipher with a vendored version of OpenSSL (via the `openssl-sys` crate) as the crypto provider. 125 | - As the name implies this depends on the `bundled-sqlcipher` feature, and automatically turns it on. 126 | - If turned on, this uses the [`openssl-sys`](https://crates.io/crates/openssl-sys) crate, with the `vendored` feature enabled in order to build and bundle the OpenSSL crypto library. 127 | * `hooks` for [Commit, Rollback](http://sqlite.org/c3ref/commit_hook.html) and [Data Change](http://sqlite.org/c3ref/update_hook.html) notification callbacks. 128 | * `unlock_notify` for [Unlock](https://sqlite.org/unlock_notify.html) notification. 129 | * `vtab` for [virtual table](https://sqlite.org/vtab.html) support (allows you to write virtual table implementations in Rust). Currently, only read-only virtual tables are supported. 130 | * `series` exposes [`generate_series(...)`](https://www.sqlite.org/series.html) Table-Valued Function. (Implies `vtab`.) 131 | * [`csvtab`](https://sqlite.org/csv.html), CSV virtual table written in Rust. (Implies `vtab`.) 132 | * [`array`](https://sqlite.org/carray.html), The `rarray()` Table-Valued Function. (Implies `vtab`.) 133 | * `i128_blob` allows storing values of type `i128` type in SQLite databases. Internally, the data is stored as a 16 byte big-endian blob, with the most significant bit flipped, which allows ordering and comparison between different blobs storing i128s to work as expected. 134 | * `uuid` allows storing and retrieving `Uuid` values from the [`uuid`](https://docs.rs/uuid/) crate using blobs. 135 | * [`session`](https://sqlite.org/sessionintro.html), Session module extension. Requires `buildtime_bindgen` feature. (Implies `hooks`.) 136 | * `extra_check` fail when a query passed to execute is readonly or has a column count > 0. 137 | * `column_decltype` provides `columns()` method for Statements and Rows; omit if linking to a version of SQLite/SQLCipher compiled with `-DSQLITE_OMIT_DECLTYPE`. 138 | * `collation` exposes [`sqlite3_create_collation_v2`](https://sqlite.org/c3ref/create_collation.html). 139 | * `winsqlite3` allows linking against the SQLite present in newer versions of Windows 140 | 141 | ## Notes on building rusqlite and libsqlite3-sys 142 | 143 | `libsqlite3-sys` is a separate crate from `rusqlite` that provides the Rust 144 | declarations for SQLite's C API. By default, `libsqlite3-sys` attempts to find a SQLite library that already exists on your system using pkg-config, or a 145 | [Vcpkg](https://github.com/Microsoft/vcpkg) installation for MSVC ABI builds. 146 | 147 | You can adjust this behavior in a number of ways: 148 | 149 | * If you use the `bundled`, `bundled-sqlcipher`, or `bundled-sqlcipher-vendored-openssl` features, `libsqlite3-sys` will use the 150 | [cc](https://crates.io/crates/cc) crate to compile SQLite or SQLCipher from source and 151 | link against that. This source is embedded in the `libsqlite3-sys` crate and 152 | is currently SQLite 3.41.2 (as of `rusqlite` 0.29.0 / `libsqlite3-sys` 153 | 0.26.0). This is probably the simplest solution to any build problems. You can enable this by adding the following in your `Cargo.toml` file: 154 | ```toml 155 | [dependencies.rusqlite] 156 | version = "0.29.0" 157 | features = ["bundled"] 158 | ``` 159 | * When using any of the `bundled` features, the build script will honor `SQLITE_MAX_VARIABLE_NUMBER` and `SQLITE_MAX_EXPR_DEPTH` variables. It will also honor a `LIBSQLITE3_FLAGS` variable, which can have a format like `"-USQLITE_ALPHA -DSQLITE_BETA SQLITE_GAMMA ..."`. That would disable the `SQLITE_ALPHA` flag, and set the `SQLITE_BETA` and `SQLITE_GAMMA` flags. (The initial `-D` can be omitted, as on the last one.) 160 | * When using `bundled-sqlcipher` (and not also using `bundled-sqlcipher-vendored-openssl`), `libsqlite3-sys` will need to 161 | link against crypto libraries on the system. If the build script can find a `libcrypto` from OpenSSL or LibreSSL (it will consult `OPENSSL_LIB_DIR`/`OPENSSL_INCLUDE_DIR` and `OPENSSL_DIR` environment variables), it will use that. If building on and for Macs, and none of those variables are set, it will use the system's SecurityFramework instead. 162 | 163 | * When linking against a SQLite (or SQLCipher) library already on the system (so *not* using any of the `bundled` features), you can set the `SQLITE3_LIB_DIR` (or `SQLCIPHER_LIB_DIR`) environment variable to point to a directory containing the library. You can also set the `SQLITE3_INCLUDE_DIR` (or `SQLCIPHER_INCLUDE_DIR`) variable to point to the directory containing `sqlite3.h`. 164 | * Installing the sqlite3 development packages will usually be all that is required, but 165 | the build helpers for [pkg-config](https://github.com/alexcrichton/pkg-config-rs) 166 | and [vcpkg](https://github.com/mcgoo/vcpkg-rs) have some additional configuration 167 | options. The default when using vcpkg is to dynamically link, 168 | which must be enabled by setting `VCPKGRS_DYNAMIC=1` environment variable before build. 169 | `vcpkg install sqlite3:x64-windows` will install the required library. 170 | * When linking against a SQLite (or SQLCipher) library already on the system, you can set the `SQLITE3_STATIC` (or `SQLCIPHER_STATIC`) environment variable to 1 to request that the library be statically instead of dynamically linked. 171 | 172 | 173 | ### Binding generation 174 | 175 | We use [bindgen](https://crates.io/crates/bindgen) to generate the Rust 176 | declarations from SQLite's C header file. `bindgen` 177 | [recommends](https://github.com/servo/rust-bindgen#library-usage-with-buildrs) 178 | running this as part of the build process of libraries that used this. We tried 179 | this briefly (`rusqlite` 0.10.0, specifically), but it had some annoyances: 180 | 181 | * The build time for `libsqlite3-sys` (and therefore `rusqlite`) increased 182 | dramatically. 183 | * Running `bindgen` requires a relatively-recent version of Clang, which many 184 | systems do not have installed by default. 185 | * Running `bindgen` also requires the SQLite header file to be present. 186 | 187 | As of `rusqlite` 0.10.1, we avoid running `bindgen` at build-time by shipping 188 | pregenerated bindings for several versions of SQLite. When compiling 189 | `rusqlite`, we use your selected Cargo features to pick the bindings for the 190 | minimum SQLite version that supports your chosen features. If you are using 191 | `libsqlite3-sys` directly, you can use the same features to choose which 192 | pregenerated bindings are chosen: 193 | 194 | * `min_sqlite_version_3_14_0` - SQLite 3.14.0 bindings (this is the default) 195 | 196 | If you use any of the `bundled` features, you will get pregenerated bindings for the 197 | bundled version of SQLite/SQLCipher. If you need other specific pregenerated binding 198 | versions, please file an issue. If you want to run `bindgen` at buildtime to 199 | produce your own bindings, use the `buildtime_bindgen` Cargo feature. 200 | 201 | If you enable the `modern_sqlite` feature, we'll use the bindings we would have 202 | included with the bundled build. You generally should have `buildtime_bindgen` 203 | enabled if you turn this on, as otherwise you'll need to keep the version of 204 | SQLite you link with in sync with what rusqlite would have bundled, (usually the 205 | most recent release of SQLite). Failing to do this will cause a runtime error. 206 | 207 | ## Contributing 208 | 209 | Rusqlite has many features, and many of them impact the build configuration in 210 | incompatible ways. This is unfortunate, and makes testing changes hard. 211 | 212 | To help here: you generally should ensure that you run tests/lint for 213 | `--features bundled`, and `--features "bundled-full session buildtime_bindgen"`. 214 | 215 | If running bindgen is problematic for you, `--features bundled-full` enables 216 | bundled and all features which don't require binding generation, and can be used 217 | instead. 218 | 219 | ### Checklist 220 | 221 | - Run `cargo fmt` to ensure your Rust code is correctly formatted. 222 | - Ensure `cargo clippy --workspace --features bundled` passes without warnings. 223 | - Ensure `cargo clippy --workspace --features "bundled-full session buildtime_bindgen"` passes without warnings. 224 | - Ensure `cargo test --workspace --features bundled` reports no failures. 225 | - Ensure `cargo test --workspace --features "bundled-full session buildtime_bindgen"` reports no failures. 226 | 227 | ## Author 228 | 229 | Rusqlite is the product of hard work by a number of people. A list is available 230 | here: https://github.com/rusqlite/rusqlite/graphs/contributors 231 | 232 | ## Community 233 | 234 | Feel free to join the [Rusqlite Discord Server](https://discord.gg/nFYfGPB8g4) to discuss or get help with `rusqlite` or `libsqlite3-sys`. 235 | 236 | ## License 237 | 238 | Rusqlite and libsqlite3-sys are available under the MIT license. See the LICENSE file for more info. 239 | 240 | ### Licenses of Bundled Software 241 | 242 | Depending on the set of enabled cargo `features`, rusqlite and libsqlite3-sys will also bundle other libraries, which have their own licensing terms: 243 | 244 | - If `--features=bundled-sqlcipher` is enabled, the vendored source of [SQLcipher](https://github.com/sqlcipher/sqlcipher) will be compiled and statically linked in. SQLcipher is distributed under a BSD-style license, as described [here](libsqlite3-sys/sqlcipher/LICENSE). 245 | 246 | - If `--features=bundled` is enabled, the vendored source of SQLite will be compiled and linked in. SQLite is in the public domain, as described [here](https://www.sqlite.org/copyright.html). 247 | 248 | Both of these are quite permissive, have no bearing on the license of the code in `rusqlite` or `libsqlite3-sys` themselves, and can be entirely ignored if you do not use the feature in question. 249 | -------------------------------------------------------------------------------- /libsqlite3-sys/Upgrade.md: -------------------------------------------------------------------------------- 1 | # Checks 2 | * new [error code(s)](https://sqlite.org/rescode.html) 3 | => Update [libsqlite3-sys/src/error.rs](https://github.com/rusqlite/rusqlite/blob/006c8b77e7d235a3072237f006ebabd66b937911/libsqlite3-sys/src/error.rs#L127) 4 | And [code_to_str](https://github.com/rusqlite/rusqlite/blob/006c8b77e7d235a3072237f006ebabd66b937911/libsqlite3-sys/src/error.rs#L195) 5 | * new [SQLITE_OPEN_*](https://www.sqlite.org/c3ref/c_open_autoproxy.html) 6 | => Update [struct OpenFlags](https://github.com/rusqlite/rusqlite/blob/19d08871799500d64336f413dc329cc964149f10/src/lib.rs#L999) 7 | * new [SQLITE_LIMIT_*](https://sqlite.org/c3ref/c_limit_attached.html) 8 | => Update [enum Limit](https://github.com/rusqlite/rusqlite/blob/66ace52c4a24a811b405ffd9e9010163352a6186/libsqlite3-sys/src/lib.rs#L27) 9 | * new [SQLITE_DBCONFIG_*](https://sqlite.org/c3ref/c_dbconfig_defensive.html) 10 | => Update [enum DbConfig](https://github.com/rusqlite/rusqlite/blob/7056e656ac92330a3d78f5ac456dea1e56f6bfee/src/config.rs#L15) 11 | * new [Authorizer Action Codes](https://sqlite.org/c3ref/c_alter_table.html) 12 | => Update [enum AuthAction](https://github.com/rusqlite/rusqlite/blob/2ddbebad9763ab8054e55ef509672b7537ba7cf5/src/hooks.rs#L63) 13 | * new [SQLITE_STMTSTATUS_*](https://www.sqlite.org/c3ref/c_stmtstatus_counter.html) 14 | => Update [enum StatementStatus](https://github.com/rusqlite/rusqlite/blob/ce90b519bb9946bf1cbab77479bb92d0fbc467c0/src/statement.rs#L937) 15 | * new [SQLITE_INDEX_CONSTRAINT_*](https://sqlite.org/c3ref/c_index_constraint_eq.html) 16 | => Update [enum IndexConstraintOp](https://github.com/rusqlite/rusqlite/blob/5d42ba7c29a35dbb8eeb047e84ae0739cb152754/src/vtab/mod.rs#L267) 17 | * new [function flag(s)](https://sqlite.org/c3ref/c_deterministic.html) 18 | => Update [struct FunctionFlags](https://github.com/rusqlite/rusqlite/blob/0312937d6a75b45d7e603fa8c6b083bc7774270b/src/functions.rs#L317) -------------------------------------------------------------------------------- /libsqlite3-sys/build.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::path::Path; 3 | 4 | /// Tells whether we're building for Windows. This is more suitable than a plain 5 | /// `cfg!(windows)`, since the latter does not properly handle cross-compilation 6 | /// 7 | /// Note that there is no way to know at compile-time which system we'll be 8 | /// targetting, and this test must be made at run-time (of the build script) See 9 | /// https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts 10 | fn win_target() -> bool { 11 | env::var("CARGO_CFG_WINDOWS").is_ok() 12 | } 13 | 14 | /// Tells whether we're building for Android. 15 | /// See [`win_target`] 16 | #[cfg(any(feature = "bundled", feature = "bundled-windows"))] 17 | fn android_target() -> bool { 18 | env::var("CARGO_CFG_TARGET_OS").map_or(false, |v| v == "android") 19 | } 20 | 21 | /// Tells whether a given compiler will be used `compiler_name` is compared to 22 | /// the content of `CARGO_CFG_TARGET_ENV` (and is always lowercase) 23 | /// 24 | /// See [`win_target`] 25 | fn is_compiler(compiler_name: &str) -> bool { 26 | env::var("CARGO_CFG_TARGET_ENV").map_or(false, |v| v == compiler_name) 27 | } 28 | 29 | fn main() { 30 | let out_dir = env::var("OUT_DIR").unwrap(); 31 | let out_path = Path::new(&out_dir).join("bindgen.rs"); 32 | if cfg!(feature = "in_gecko") { 33 | // When inside mozilla-central, we are included into the build with 34 | // sqlite3.o directly, so we don't want to provide any linker arguments. 35 | std::fs::copy("sqlite3/bindgen_bundled_version.rs", out_path) 36 | .expect("Could not copy bindings to output directory"); 37 | return; 38 | } 39 | 40 | println!("cargo:rerun-if-env-changed=LIBSQLITE3_SYS_USE_PKG_CONFIG"); 41 | if env::var_os("LIBSQLITE3_SYS_USE_PKG_CONFIG").map_or(false, |s| s != "0") { 42 | build_linked::main(&out_dir, &out_path); 43 | } else if cfg!(all( 44 | feature = "sqlcipher", 45 | not(feature = "bundled-sqlcipher") 46 | )) { 47 | if cfg!(feature = "bundled") || (win_target() && cfg!(feature = "bundled-windows")) { 48 | println!( 49 | "cargo:warning=For backwards compatibility, feature 'sqlcipher' overrides 50 | features 'bundled' and 'bundled-windows'. If you want a bundled build of 51 | SQLCipher (available for the moment only on Unix), use feature 'bundled-sqlcipher' 52 | or 'bundled-sqlcipher-vendored-openssl' to also bundle OpenSSL crypto." 53 | ); 54 | } 55 | build_linked::main(&out_dir, &out_path); 56 | } else if cfg!(feature = "bundled") 57 | || (win_target() && cfg!(feature = "bundled-windows")) 58 | || cfg!(feature = "bundled-sqlcipher") 59 | { 60 | #[cfg(any( 61 | feature = "bundled", 62 | feature = "bundled-windows", 63 | feature = "bundled-sqlcipher" 64 | ))] 65 | build_bundled::main(&out_dir, &out_path); 66 | #[cfg(not(any( 67 | feature = "bundled", 68 | feature = "bundled-windows", 69 | feature = "bundled-sqlcipher" 70 | )))] 71 | panic!("The runtime test should not run this branch, which has not compiled any logic.") 72 | } else { 73 | build_linked::main(&out_dir, &out_path); 74 | } 75 | } 76 | 77 | #[cfg(any( 78 | feature = "bundled", 79 | feature = "bundled-windows", 80 | feature = "bundled-sqlcipher" 81 | ))] 82 | mod build_bundled { 83 | use std::env; 84 | use std::ffi::OsString; 85 | use std::path::{Path, PathBuf}; 86 | 87 | use super::{is_compiler, win_target}; 88 | 89 | pub fn main(out_dir: &str, out_path: &Path) { 90 | let lib_name = super::lib_name(); 91 | 92 | // This is just a sanity check, the top level `main` should ensure this. 93 | assert!(!(cfg!(feature = "bundled-windows") && !cfg!(feature = "bundled") && !win_target()), 94 | "This module should not be used: we're not on Windows and the bundled feature has not been enabled"); 95 | 96 | #[cfg(feature = "buildtime_bindgen")] 97 | { 98 | use super::{bindings, HeaderLocation}; 99 | let header = HeaderLocation::FromPath(format!("{}/sqlite3.h", lib_name)); 100 | bindings::write_to_out_dir(header, out_path); 101 | } 102 | #[cfg(not(feature = "buildtime_bindgen"))] 103 | { 104 | use std::fs; 105 | fs::copy(format!("{lib_name}/bindgen_bundled_version.rs"), out_path) 106 | .expect("Could not copy bindings to output directory"); 107 | } 108 | println!("cargo:rerun-if-changed={lib_name}/sqlite3.c"); 109 | println!("cargo:rerun-if-changed=sqlite3/wasm32-wasi-vfs.c"); 110 | let mut cfg = cc::Build::new(); 111 | cfg.file(format!("{lib_name}/sqlite3.c")) 112 | .flag("-DSQLITE_CORE") 113 | .flag("-DSQLITE_DEFAULT_FOREIGN_KEYS=1") 114 | .flag("-DSQLITE_ENABLE_API_ARMOR") 115 | .flag("-DSQLITE_ENABLE_COLUMN_METADATA") 116 | .flag("-DSQLITE_ENABLE_DBSTAT_VTAB") 117 | .flag("-DSQLITE_ENABLE_FTS3") 118 | .flag("-DSQLITE_ENABLE_FTS3_PARENTHESIS") 119 | .flag("-DSQLITE_ENABLE_FTS5") 120 | .flag("-DSQLITE_ENABLE_JSON1") 121 | .flag("-DSQLITE_ENABLE_LOAD_EXTENSION=1") 122 | .flag("-DSQLITE_ENABLE_MEMORY_MANAGEMENT") 123 | .flag("-DSQLITE_ENABLE_RTREE") 124 | .flag("-DSQLITE_ENABLE_STAT2") 125 | .flag("-DSQLITE_ENABLE_STAT4") 126 | .flag("-DSQLITE_SOUNDEX") 127 | .flag("-DSQLITE_THREADSAFE=1") 128 | .flag("-DSQLITE_USE_URI") 129 | .flag("-DHAVE_USLEEP=1") 130 | .flag("-D_POSIX_THREAD_SAFE_FUNCTIONS") // cross compile with MinGW 131 | .warnings(false); 132 | 133 | if cfg!(feature = "bundled-sqlcipher") { 134 | cfg.flag("-DSQLITE_HAS_CODEC").flag("-DSQLITE_TEMP_STORE=2"); 135 | 136 | let target = env::var("TARGET").unwrap(); 137 | let host = env::var("HOST").unwrap(); 138 | 139 | let is_windows = host.contains("windows") && target.contains("windows"); 140 | let is_apple = host.contains("apple") && target.contains("apple"); 141 | 142 | let lib_dir = env("OPENSSL_LIB_DIR").map(PathBuf::from); 143 | let inc_dir = env("OPENSSL_INCLUDE_DIR").map(PathBuf::from); 144 | let mut use_openssl = false; 145 | 146 | let (lib_dir, inc_dir) = match (lib_dir, inc_dir) { 147 | (Some(lib_dir), Some(inc_dir)) => { 148 | use_openssl = true; 149 | (lib_dir, inc_dir) 150 | } 151 | (lib_dir, inc_dir) => match find_openssl_dir(&host, &target) { 152 | None => { 153 | if is_windows && !cfg!(feature = "bundled-sqlcipher-vendored-openssl") { 154 | panic!("Missing environment variable OPENSSL_DIR or OPENSSL_DIR is not set") 155 | } else { 156 | (PathBuf::new(), PathBuf::new()) 157 | } 158 | } 159 | Some(openssl_dir) => { 160 | let lib_dir = lib_dir.unwrap_or_else(|| openssl_dir.join("lib")); 161 | let inc_dir = inc_dir.unwrap_or_else(|| openssl_dir.join("include")); 162 | 163 | assert!( 164 | Path::new(&lib_dir).exists(), 165 | "OpenSSL library directory does not exist: {}", 166 | lib_dir.to_string_lossy() 167 | ); 168 | 169 | if !Path::new(&inc_dir).exists() { 170 | panic!( 171 | "OpenSSL include directory does not exist: {}", 172 | inc_dir.to_string_lossy() 173 | ); 174 | } 175 | 176 | use_openssl = true; 177 | (lib_dir, inc_dir) 178 | } 179 | }, 180 | }; 181 | 182 | if cfg!(feature = "bundled-sqlcipher-vendored-openssl") { 183 | cfg.include(env::var("DEP_OPENSSL_INCLUDE").unwrap()); 184 | // cargo will resolve downstream to the static lib in 185 | // openssl-sys 186 | } else if use_openssl { 187 | cfg.include(inc_dir.to_string_lossy().as_ref()); 188 | let lib_name = if is_windows { "libcrypto" } else { "crypto" }; 189 | println!("cargo:rustc-link-lib=dylib={}", lib_name); 190 | println!("cargo:rustc-link-search={}", lib_dir.to_string_lossy()); 191 | } else if is_apple { 192 | cfg.flag("-DSQLCIPHER_CRYPTO_CC"); 193 | println!("cargo:rustc-link-lib=framework=Security"); 194 | println!("cargo:rustc-link-lib=framework=CoreFoundation"); 195 | } else { 196 | // branch not taken on Windows, just `crypto` is fine. 197 | println!("cargo:rustc-link-lib=dylib=crypto"); 198 | } 199 | } 200 | 201 | // on android sqlite can't figure out where to put the temp files. 202 | // the bundled sqlite on android also uses `SQLITE_TEMP_STORE=3`. 203 | // https://android.googlesource.com/platform/external/sqlite/+/2c8c9ae3b7e6f340a19a0001c2a889a211c9d8b2/dist/Android.mk 204 | if super::android_target() { 205 | cfg.flag("-DSQLITE_TEMP_STORE=3"); 206 | } 207 | 208 | if cfg!(feature = "with-asan") { 209 | cfg.flag("-fsanitize=address"); 210 | } 211 | 212 | // If explicitly requested: enable static linking against the Microsoft Visual 213 | // C++ Runtime to avoid dependencies on vcruntime140.dll and similar libraries. 214 | if cfg!(target_feature = "crt-static") && is_compiler("msvc") { 215 | cfg.static_crt(true); 216 | } 217 | 218 | // Older versions of visual studio don't support c99 (including isnan), which 219 | // causes a build failure when the linker fails to find the `isnan` 220 | // function. `sqlite` provides its own implementation, using the fact 221 | // that x != x when x is NaN. 222 | // 223 | // There may be other platforms that don't support `isnan`, they should be 224 | // tested for here. 225 | if is_compiler("msvc") { 226 | use cc::windows_registry::{find_vs_version, VsVers}; 227 | let vs_has_nan = match find_vs_version() { 228 | Ok(ver) => ver != VsVers::Vs12, 229 | Err(_msg) => false, 230 | }; 231 | if vs_has_nan { 232 | cfg.flag("-DHAVE_ISNAN"); 233 | } 234 | } else if env::var("TARGET") != Ok("wasm32-unknown-unknown".to_string()) { 235 | cfg.flag("-DHAVE_ISNAN"); 236 | } 237 | if !win_target() { 238 | cfg.flag("-DHAVE_LOCALTIME_R"); 239 | } 240 | // Target wasm32-wasi can't compile the default VFS 241 | if env::var("TARGET").map_or(false, |v| v == "wasm32-wasi") { 242 | cfg.flag("-DSQLITE_OS_OTHER") 243 | // https://github.com/rust-lang/rust/issues/74393 244 | .flag("-DLONGDOUBLE_TYPE=double"); 245 | if cfg!(feature = "wasm32-wasi-vfs") { 246 | cfg.file("sqlite3/wasm32-wasi-vfs.c"); 247 | } 248 | } 249 | if env::var("TARGET") == Ok("wasm32-unknown-unknown".to_string()) { 250 | // Apple clang doesn't support wasm32, so use Homebrew clang by default. 251 | if env::var("HOST") == Ok("x86_64-apple-darwin".to_string()) { 252 | if env::var("CC").is_err() { 253 | std::env::set_var("CC", "/usr/local/opt/llvm/bin/clang"); 254 | } 255 | if env::var("AR").is_err() { 256 | std::env::set_var("AR", "/usr/local/opt/llvm/bin/llvm-ar"); 257 | } 258 | } else if env::var("HOST") == Ok("aarch64-apple-darwin".to_string()) { 259 | if env::var("CC").is_err() { 260 | std::env::set_var("CC", "/opt/homebrew/opt/llvm/bin/clang"); 261 | } 262 | if env::var("AR").is_err() { 263 | std::env::set_var("AR", "/opt/homebrew/opt/llvm/bin/llvm-ar"); 264 | } 265 | } 266 | 267 | cfg.flag("-DSQLITE_OS_OTHER") 268 | // .flag("-DSQLITE_TEMP_STORE=3") 269 | // https://github.com/rust-lang/rust/issues/74393 270 | .flag("-DLONGDOUBLE_TYPE=double") 271 | .flag("-DSQLITE_OMIT_LOCALTIME"); 272 | cfg.include("sqlite3/wasm32-unknown-unknown/include"); 273 | cfg.file("sqlite3/wasm32-unknown-unknown/libc/stdlib/qsort.c"); 274 | cfg.file("sqlite3/wasm32-unknown-unknown/libc/string/strcmp.c"); 275 | cfg.file("sqlite3/wasm32-unknown-unknown/libc/string/strcspn.c"); 276 | cfg.file("sqlite3/wasm32-unknown-unknown/libc/string/strlen.c"); 277 | cfg.file("sqlite3/wasm32-unknown-unknown/libc/string/strncmp.c"); 278 | cfg.file("sqlite3/wasm32-unknown-unknown/libc/string/strrchr.c"); 279 | } 280 | if cfg!(feature = "unlock_notify") { 281 | cfg.flag("-DSQLITE_ENABLE_UNLOCK_NOTIFY"); 282 | } 283 | if cfg!(feature = "preupdate_hook") { 284 | cfg.flag("-DSQLITE_ENABLE_PREUPDATE_HOOK"); 285 | } 286 | if cfg!(feature = "session") { 287 | cfg.flag("-DSQLITE_ENABLE_SESSION"); 288 | } 289 | 290 | if let Ok(limit) = env::var("SQLITE_MAX_VARIABLE_NUMBER") { 291 | cfg.flag(&format!("-DSQLITE_MAX_VARIABLE_NUMBER={limit}")); 292 | } 293 | println!("cargo:rerun-if-env-changed=SQLITE_MAX_VARIABLE_NUMBER"); 294 | 295 | if let Ok(limit) = env::var("SQLITE_MAX_EXPR_DEPTH") { 296 | cfg.flag(&format!("-DSQLITE_MAX_EXPR_DEPTH={limit}")); 297 | } 298 | println!("cargo:rerun-if-env-changed=SQLITE_MAX_EXPR_DEPTH"); 299 | 300 | if let Ok(limit) = env::var("SQLITE_MAX_COLUMN") { 301 | cfg.flag(&format!("-DSQLITE_MAX_COLUMN={limit}")); 302 | } 303 | println!("cargo:rerun-if-env-changed=SQLITE_MAX_COLUMN"); 304 | 305 | if let Ok(extras) = env::var("LIBSQLITE3_FLAGS") { 306 | for extra in extras.split_whitespace() { 307 | if extra.starts_with("-D") || extra.starts_with("-U") { 308 | cfg.flag(extra); 309 | } else if extra.starts_with("SQLITE_") { 310 | cfg.flag(&format!("-D{extra}")); 311 | } else { 312 | panic!("Don't understand {} in LIBSQLITE3_FLAGS", extra); 313 | } 314 | } 315 | } 316 | println!("cargo:rerun-if-env-changed=LIBSQLITE3_FLAGS"); 317 | 318 | cfg.compile(lib_name); 319 | 320 | println!("cargo:lib_dir={out_dir}"); 321 | } 322 | 323 | fn env(name: &str) -> Option { 324 | let prefix = env::var("TARGET").unwrap().to_uppercase().replace('-', "_"); 325 | let prefixed = format!("{prefix}_{name}"); 326 | let var = env::var_os(prefixed); 327 | 328 | match var { 329 | None => env::var_os(name), 330 | _ => var, 331 | } 332 | } 333 | 334 | fn find_openssl_dir(_host: &str, _target: &str) -> Option { 335 | let openssl_dir = env("OPENSSL_DIR"); 336 | openssl_dir.map(PathBuf::from) 337 | } 338 | } 339 | 340 | fn env_prefix() -> &'static str { 341 | if cfg!(any(feature = "sqlcipher", feature = "bundled-sqlcipher")) { 342 | "SQLCIPHER" 343 | } else { 344 | "SQLITE3" 345 | } 346 | } 347 | 348 | fn lib_name() -> &'static str { 349 | if cfg!(any(feature = "sqlcipher", feature = "bundled-sqlcipher")) { 350 | "sqlcipher" 351 | } else if cfg!(all(windows, feature = "winsqlite3")) { 352 | "winsqlite3" 353 | } else { 354 | "sqlite3" 355 | } 356 | } 357 | 358 | pub enum HeaderLocation { 359 | FromEnvironment, 360 | Wrapper, 361 | FromPath(String), 362 | } 363 | 364 | impl From for String { 365 | fn from(header: HeaderLocation) -> String { 366 | match header { 367 | HeaderLocation::FromEnvironment => { 368 | let prefix = env_prefix(); 369 | let mut header = env::var(format!("{prefix}_INCLUDE_DIR")).unwrap_or_else(|_| { 370 | panic!( 371 | "{}_INCLUDE_DIR must be set if {}_LIB_DIR is set", 372 | prefix, prefix 373 | ) 374 | }); 375 | header.push_str("/sqlite3.h"); 376 | header 377 | } 378 | HeaderLocation::Wrapper => "wrapper.h".into(), 379 | HeaderLocation::FromPath(path) => path, 380 | } 381 | } 382 | } 383 | 384 | mod build_linked { 385 | #[cfg(feature = "vcpkg")] 386 | extern crate vcpkg; 387 | 388 | use super::{bindings, env_prefix, is_compiler, lib_name, win_target, HeaderLocation}; 389 | use std::env; 390 | use std::path::Path; 391 | 392 | pub fn main(_out_dir: &str, out_path: &Path) { 393 | let header = find_sqlite(); 394 | if (cfg!(any( 395 | feature = "bundled_bindings", 396 | feature = "bundled", 397 | feature = "bundled-sqlcipher" 398 | )) || (win_target() && cfg!(feature = "bundled-windows"))) 399 | && !cfg!(feature = "buildtime_bindgen") 400 | { 401 | // Generally means the `bundled_bindings` feature is enabled. 402 | // Most users are better off with turning 403 | // on buildtime_bindgen instead, but this is still supported as we 404 | // have runtime version checks and there are good reasons to not 405 | // want to run bindgen. 406 | std::fs::copy( 407 | format!("{}/bindgen_bundled_version.rs", lib_name()), 408 | out_path, 409 | ) 410 | .expect("Could not copy bindings to output directory"); 411 | } else { 412 | bindings::write_to_out_dir(header, out_path); 413 | } 414 | } 415 | 416 | fn find_link_mode() -> &'static str { 417 | // If the user specifies SQLITE3_STATIC (or SQLCIPHER_STATIC), do static 418 | // linking, unless it's explicitly set to 0. 419 | match &env::var(format!("{}_STATIC", env_prefix())) { 420 | Ok(v) if v != "0" => "static", 421 | _ => "dylib", 422 | } 423 | } 424 | // Prints the necessary cargo link commands and returns the path to the header. 425 | fn find_sqlite() -> HeaderLocation { 426 | let link_lib = lib_name(); 427 | 428 | println!("cargo:rerun-if-env-changed={}_INCLUDE_DIR", env_prefix()); 429 | println!("cargo:rerun-if-env-changed={}_LIB_DIR", env_prefix()); 430 | println!("cargo:rerun-if-env-changed={}_STATIC", env_prefix()); 431 | if cfg!(feature = "vcpkg") && is_compiler("msvc") { 432 | println!("cargo:rerun-if-env-changed=VCPKGRS_DYNAMIC"); 433 | } 434 | 435 | // dependents can access `DEP_SQLITE3_LINK_TARGET` (`sqlite3` being the 436 | // `links=` value in our Cargo.toml) to get this value. This might be 437 | // useful if you need to ensure whatever crypto library sqlcipher relies 438 | // on is available, for example. 439 | println!("cargo:link-target={link_lib}"); 440 | 441 | if win_target() && cfg!(feature = "winsqlite3") { 442 | println!("cargo:rustc-link-lib=dylib={link_lib}"); 443 | return HeaderLocation::Wrapper; 444 | } 445 | 446 | // Allow users to specify where to find SQLite. 447 | if let Ok(dir) = env::var(format!("{}_LIB_DIR", env_prefix())) { 448 | // Try to use pkg-config to determine link commands 449 | let pkgconfig_path = Path::new(&dir).join("pkgconfig"); 450 | env::set_var("PKG_CONFIG_PATH", pkgconfig_path); 451 | if pkg_config::Config::new().probe(link_lib).is_err() { 452 | // Otherwise just emit the bare minimum link commands. 453 | println!("cargo:rustc-link-lib={}={link_lib}", find_link_mode()); 454 | println!("cargo:rustc-link-search={dir}"); 455 | } 456 | return HeaderLocation::FromEnvironment; 457 | } 458 | 459 | if let Some(header) = try_vcpkg() { 460 | return header; 461 | } 462 | 463 | // See if pkg-config can do everything for us. 464 | if let Ok(mut lib) = pkg_config::Config::new() 465 | .print_system_libs(false) 466 | .probe(link_lib) 467 | { 468 | if let Some(mut header) = lib.include_paths.pop() { 469 | header.push("sqlite3.h"); 470 | HeaderLocation::FromPath(header.to_string_lossy().into()) 471 | } else { 472 | HeaderLocation::Wrapper 473 | } 474 | } else { 475 | // No env var set and pkg-config couldn't help; just output the link-lib 476 | // request and hope that the library exists on the system paths. We used to 477 | // output /usr/lib explicitly, but that can introduce other linking problems; 478 | // see https://github.com/rusqlite/rusqlite/issues/207. 479 | println!("cargo:rustc-link-lib={}={link_lib}", find_link_mode()); 480 | HeaderLocation::Wrapper 481 | } 482 | } 483 | 484 | fn try_vcpkg() -> Option { 485 | if cfg!(feature = "vcpkg") && is_compiler("msvc") { 486 | // See if vcpkg can find it. 487 | if let Ok(mut lib) = vcpkg::Config::new().probe(lib_name()) { 488 | if let Some(mut header) = lib.include_paths.pop() { 489 | header.push("sqlite3.h"); 490 | return Some(HeaderLocation::FromPath(header.to_string_lossy().into())); 491 | } 492 | } 493 | None 494 | } else { 495 | None 496 | } 497 | } 498 | } 499 | 500 | #[cfg(not(feature = "buildtime_bindgen"))] 501 | mod bindings { 502 | #![allow(dead_code)] 503 | use super::HeaderLocation; 504 | 505 | use std::fs; 506 | use std::path::Path; 507 | 508 | static PREBUILT_BINDGEN_PATHS: &[&str] = &["bindgen-bindings/bindgen_3.14.0.rs"]; 509 | 510 | pub fn write_to_out_dir(_header: HeaderLocation, out_path: &Path) { 511 | let in_path = PREBUILT_BINDGEN_PATHS[PREBUILT_BINDGEN_PATHS.len() - 1]; 512 | fs::copy(in_path, out_path).expect("Could not copy bindings to output directory"); 513 | } 514 | } 515 | 516 | #[cfg(feature = "buildtime_bindgen")] 517 | mod bindings { 518 | use super::HeaderLocation; 519 | use bindgen::callbacks::{IntKind, ParseCallbacks}; 520 | 521 | use std::fs; 522 | use std::path::Path; 523 | 524 | use super::win_target; 525 | 526 | #[derive(Debug)] 527 | struct SqliteTypeChooser; 528 | 529 | impl ParseCallbacks for SqliteTypeChooser { 530 | fn int_macro(&self, name: &str, _value: i64) -> Option { 531 | if name == "SQLITE_SERIALIZE_NOCOPY" 532 | || name.starts_with("SQLITE_DESERIALIZE_") 533 | || name.starts_with("SQLITE_PREPARE_") 534 | { 535 | Some(IntKind::UInt) 536 | } else { 537 | None 538 | } 539 | } 540 | } 541 | 542 | // Are we generating the bundled bindings? Used to avoid emitting things 543 | // that would be problematic in bundled builds. This env var is set by 544 | // `upgrade.sh`. 545 | fn generating_bundled_bindings() -> bool { 546 | // Hacky way to know if we're generating the bundled bindings 547 | println!("cargo:rerun-if-env-changed=LIBSQLITE3_SYS_BUNDLING"); 548 | match std::env::var("LIBSQLITE3_SYS_BUNDLING") { 549 | Ok(v) => v != "0", 550 | Err(_) => false, 551 | } 552 | } 553 | 554 | pub fn write_to_out_dir(header: HeaderLocation, out_path: &Path) { 555 | let header: String = header.into(); 556 | let mut output = Vec::new(); 557 | let mut bindings = bindgen::builder() 558 | .default_macro_constant_type(bindgen::MacroTypeVariation::Signed) 559 | .disable_nested_struct_naming() 560 | .trust_clang_mangling(false) 561 | .header(header.clone()) 562 | .parse_callbacks(Box::new(SqliteTypeChooser)) 563 | .blocklist_function("sqlite3_auto_extension") 564 | .raw_line( 565 | r#"extern "C" { 566 | pub fn sqlite3_auto_extension( 567 | xEntryPoint: ::std::option::Option< 568 | unsafe extern "C" fn( 569 | db: *mut sqlite3, 570 | pzErrMsg: *mut *const ::std::os::raw::c_char, 571 | pThunk: *const sqlite3_api_routines, 572 | ) -> ::std::os::raw::c_int, 573 | >, 574 | ) -> ::std::os::raw::c_int; 575 | }"#, 576 | ) 577 | .blocklist_function("sqlite3_cancel_auto_extension") 578 | .raw_line( 579 | r#"extern "C" { 580 | pub fn sqlite3_cancel_auto_extension( 581 | xEntryPoint: ::std::option::Option< 582 | unsafe extern "C" fn( 583 | db: *mut sqlite3, 584 | pzErrMsg: *mut *const ::std::os::raw::c_char, 585 | pThunk: *const sqlite3_api_routines, 586 | ) -> ::std::os::raw::c_int, 587 | >, 588 | ) -> ::std::os::raw::c_int; 589 | }"#, 590 | ); 591 | 592 | if cfg!(any(feature = "sqlcipher", feature = "bundled-sqlcipher")) { 593 | bindings = bindings.clang_arg("-DSQLITE_HAS_CODEC"); 594 | } 595 | if cfg!(feature = "unlock_notify") { 596 | bindings = bindings.clang_arg("-DSQLITE_ENABLE_UNLOCK_NOTIFY"); 597 | } 598 | if cfg!(feature = "preupdate_hook") { 599 | bindings = bindings.clang_arg("-DSQLITE_ENABLE_PREUPDATE_HOOK"); 600 | } 601 | if cfg!(feature = "session") { 602 | bindings = bindings.clang_arg("-DSQLITE_ENABLE_SESSION"); 603 | } 604 | if win_target() && cfg!(feature = "winsqlite3") { 605 | bindings = bindings 606 | .clang_arg("-DBINDGEN_USE_WINSQLITE3") 607 | .blocklist_item("NTDDI_.+") 608 | .blocklist_item("WINAPI_FAMILY.*") 609 | .blocklist_item("_WIN32_.+") 610 | .blocklist_item("_VCRT_COMPILER_PREPROCESSOR") 611 | .blocklist_item("_SAL_VERSION") 612 | .blocklist_item("__SAL_H_VERSION") 613 | .blocklist_item("_USE_DECLSPECS_FOR_SAL") 614 | .blocklist_item("_USE_ATTRIBUTES_FOR_SAL") 615 | .blocklist_item("_CRT_PACKING") 616 | .blocklist_item("_HAS_EXCEPTIONS") 617 | .blocklist_item("_STL_LANG") 618 | .blocklist_item("_HAS_CXX17") 619 | .blocklist_item("_HAS_CXX20") 620 | .blocklist_item("_HAS_NODISCARD") 621 | .blocklist_item("WDK_NTDDI_VERSION") 622 | .blocklist_item("OSVERSION_MASK") 623 | .blocklist_item("SPVERSION_MASK") 624 | .blocklist_item("SUBVERSION_MASK") 625 | .blocklist_item("WINVER") 626 | .blocklist_item("__security_cookie") 627 | .blocklist_type("size_t") 628 | .blocklist_type("__vcrt_bool") 629 | .blocklist_type("wchar_t") 630 | .blocklist_function("__security_init_cookie") 631 | .blocklist_function("__report_gsfailure") 632 | .blocklist_function("__va_start"); 633 | } 634 | 635 | // When cross compiling unless effort is taken to fix the issue, bindgen 636 | // will find the wrong headers. There's only one header included by the 637 | // amalgamated `sqlite.h`: `stdarg.h`. 638 | // 639 | // Thankfully, there's almost no case where rust code needs to use 640 | // functions taking `va_list` (It's nearly impossible to get a `va_list` 641 | // in Rust unless you get passed it by C code for some reason). 642 | // 643 | // Arguably, we should never be including these, but we include them for 644 | // the cases where they aren't totally broken... 645 | let target_arch = std::env::var("TARGET").unwrap(); 646 | let host_arch = std::env::var("HOST").unwrap(); 647 | let is_cross_compiling = target_arch != host_arch; 648 | 649 | // Note that when generating the bundled file, we're essentially always 650 | // cross compiling. 651 | if generating_bundled_bindings() || is_cross_compiling { 652 | // Get rid of va_list, as it's not 653 | bindings = bindings 654 | .blocklist_function("sqlite3_vmprintf") 655 | .blocklist_function("sqlite3_vsnprintf") 656 | .blocklist_function("sqlite3_str_vappendf") 657 | .blocklist_type("va_list") 658 | .blocklist_item("__.*"); 659 | } 660 | 661 | bindings 662 | .layout_tests(false) 663 | .generate() 664 | .unwrap_or_else(|_| panic!("could not run bindgen on header {}", header)) 665 | .write(Box::new(&mut output)) 666 | .expect("could not write output of bindgen"); 667 | let mut output = String::from_utf8(output).expect("bindgen output was not UTF-8?!"); 668 | 669 | // rusqlite's functions feature ors in the SQLITE_DETERMINISTIC flag when it 670 | // can. This flag was added in SQLite 3.8.3, but oring it in in prior 671 | // versions of SQLite is harmless. We don't want to not build just 672 | // because this flag is missing (e.g., if we're linking against 673 | // SQLite 3.7.x), so append the flag manually if it isn't present in bindgen's 674 | // output. 675 | if !output.contains("pub const SQLITE_DETERMINISTIC") { 676 | output.push_str("\npub const SQLITE_DETERMINISTIC: i32 = 2048;\n"); 677 | } 678 | 679 | fs::write(out_path, output.as_bytes()) 680 | .unwrap_or_else(|_| panic!("Could not write to {:?}", out_path)); 681 | } 682 | } 683 | -------------------------------------------------------------------------------- /libsqlite3-sys/sqlcipher/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2008-2020 Zetetic LLC 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | * Redistributions of source code must retain the above copyright 7 | notice, this list of conditions and the following disclaimer. 8 | * Redistributions in binary form must reproduce the above copyright 9 | notice, this list of conditions and the following disclaimer in the 10 | documentation and/or other materials provided with the distribution. 11 | * Neither the name of the ZETETIC LLC nor the 12 | names of its contributors may be used to endorse or promote products 13 | derived from this software without specific prior written permission. 14 | 15 | THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY 16 | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 17 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 18 | DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY 19 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 20 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 21 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 22 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 23 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 24 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 | -------------------------------------------------------------------------------- /libsqlite3-sys/sqlite3/wasm32-unknown-unknown/include/assert.h: -------------------------------------------------------------------------------- 1 | #define assert(x) (void)0 2 | -------------------------------------------------------------------------------- /libsqlite3-sys/sqlite3/wasm32-unknown-unknown/include/ctype.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/logseq/sqlite-db/6ece3d7c70d6bb6ba6d049a4942646dc3860b1f8/libsqlite3-sys/sqlite3/wasm32-unknown-unknown/include/ctype.h -------------------------------------------------------------------------------- /libsqlite3-sys/sqlite3/wasm32-unknown-unknown/include/math.h: -------------------------------------------------------------------------------- 1 | double log(double x); 2 | -------------------------------------------------------------------------------- /libsqlite3-sys/sqlite3/wasm32-unknown-unknown/include/stdio.h: -------------------------------------------------------------------------------- 1 | #define FILENAME_MAX 4096 2 | -------------------------------------------------------------------------------- /libsqlite3-sys/sqlite3/wasm32-unknown-unknown/include/stdlib.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void *malloc(size_t size); 4 | void free(void *ptr); 5 | void *realloc(void *ptr, size_t size); 6 | 7 | void qsort(void *a, size_t n, size_t es, int (*cmp)(const void *, const void *)); 8 | 9 | #define DEF_STRONG(x) 10 | -------------------------------------------------------------------------------- /libsqlite3-sys/sqlite3/wasm32-unknown-unknown/include/string.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int strcmp(const char *s1, const char *s2); 4 | size_t strcspn(const char *s1, const char *s2); 5 | size_t strlen(const char *str); 6 | int strncmp(const char *s1, const char *s2, size_t n); 7 | char *strrchr(const char *p, int ch); 8 | 9 | int memcmp(const void *str1, const void *str2, size_t n); 10 | void *memcpy(void *dest, const void *src, size_t n); 11 | void *memmove(void *str1, const void *str2, size_t n); 12 | void *memset(void *str, int c, size_t n); 13 | 14 | #define DEF_STRONG(x) 15 | #define __weak_alias(x, y) 16 | -------------------------------------------------------------------------------- /libsqlite3-sys/sqlite3/wasm32-unknown-unknown/include/sys/types.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/logseq/sqlite-db/6ece3d7c70d6bb6ba6d049a4942646dc3860b1f8/libsqlite3-sys/sqlite3/wasm32-unknown-unknown/include/sys/types.h -------------------------------------------------------------------------------- /libsqlite3-sys/sqlite3/wasm32-unknown-unknown/include/time.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/logseq/sqlite-db/6ece3d7c70d6bb6ba6d049a4942646dc3860b1f8/libsqlite3-sys/sqlite3/wasm32-unknown-unknown/include/time.h -------------------------------------------------------------------------------- /libsqlite3-sys/sqlite3/wasm32-unknown-unknown/libc/stdlib/qsort.c: -------------------------------------------------------------------------------- 1 | /* $OpenBSD: qsort.c,v 1.14 2017/01/04 15:20:30 millert Exp $ */ 2 | /*- 3 | * Copyright (c) 1992, 1993 4 | * The Regents of the University of California. All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 1. Redistributions of source code must retain the above copyright 10 | * notice, this list of conditions and the following disclaimer. 11 | * 2. Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * 3. Neither the name of the University nor the names of its contributors 15 | * may be used to endorse or promote products derived from this software 16 | * without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 19 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 22 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 23 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 24 | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 25 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 26 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 27 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 28 | * SUCH DAMAGE. 29 | */ 30 | 31 | #include 32 | #include 33 | 34 | static __inline char *med3(char *, char *, char *, int (*)(const void *, const void *)); 35 | static __inline void swapfunc(char *, char *, size_t, int); 36 | 37 | #define min(a, b) (a) < (b) ? a : b 38 | 39 | /* 40 | * Qsort routine from Bentley & McIlroy's "Engineering a Sort Function". 41 | */ 42 | #define swapcode(TYPE, parmi, parmj, n) { \ 43 | size_t i = (n) / sizeof (TYPE); \ 44 | TYPE *pi = (TYPE *) (parmi); \ 45 | TYPE *pj = (TYPE *) (parmj); \ 46 | do { \ 47 | TYPE t = *pi; \ 48 | *pi++ = *pj; \ 49 | *pj++ = t; \ 50 | } while (--i > 0); \ 51 | } 52 | 53 | #define SWAPINIT(a, es) swaptype = ((char *)a - (char *)0) % sizeof(long) || \ 54 | es % sizeof(long) ? 2 : es == sizeof(long)? 0 : 1; 55 | 56 | static __inline void 57 | swapfunc(char *a, char *b, size_t n, int swaptype) 58 | { 59 | if (swaptype <= 1) 60 | swapcode(long, a, b, n) 61 | else 62 | swapcode(char, a, b, n) 63 | } 64 | 65 | #define swap(a, b) \ 66 | if (swaptype == 0) { \ 67 | long t = *(long *)(a); \ 68 | *(long *)(a) = *(long *)(b); \ 69 | *(long *)(b) = t; \ 70 | } else \ 71 | swapfunc(a, b, es, swaptype) 72 | 73 | #define vecswap(a, b, n) if ((n) > 0) swapfunc(a, b, n, swaptype) 74 | 75 | static __inline char * 76 | med3(char *a, char *b, char *c, int (*cmp)(const void *, const void *)) 77 | { 78 | return cmp(a, b) < 0 ? 79 | (cmp(b, c) < 0 ? b : (cmp(a, c) < 0 ? c : a )) 80 | :(cmp(b, c) > 0 ? b : (cmp(a, c) < 0 ? a : c )); 81 | } 82 | 83 | void 84 | qsort(void *aa, size_t n, size_t es, int (*cmp)(const void *, const void *)) 85 | { 86 | char *pa, *pb, *pc, *pd, *pl, *pm, *pn; 87 | int cmp_result, swaptype; 88 | size_t d, r; 89 | char *a = aa; 90 | 91 | loop: SWAPINIT(a, es); 92 | if (n < 7) { 93 | for (pm = a + es; pm < a + n * es; pm += es) 94 | for (pl = pm; pl > a && cmp(pl - es, pl) > 0; 95 | pl -= es) 96 | swap(pl, pl - es); 97 | return; 98 | } 99 | pm = a + (n / 2) * es; 100 | if (n > 7) { 101 | pl = a; 102 | pn = a + (n - 1) * es; 103 | if (n > 40) { 104 | d = (n / 8) * es; 105 | pl = med3(pl, pl + d, pl + 2 * d, cmp); 106 | pm = med3(pm - d, pm, pm + d, cmp); 107 | pn = med3(pn - 2 * d, pn - d, pn, cmp); 108 | } 109 | pm = med3(pl, pm, pn, cmp); 110 | } 111 | swap(a, pm); 112 | pa = pb = a + es; 113 | 114 | pc = pd = a + (n - 1) * es; 115 | for (;;) { 116 | while (pb <= pc && (cmp_result = cmp(pb, a)) <= 0) { 117 | if (cmp_result == 0) { 118 | swap(pa, pb); 119 | pa += es; 120 | } 121 | pb += es; 122 | } 123 | while (pb <= pc && (cmp_result = cmp(pc, a)) >= 0) { 124 | if (cmp_result == 0) { 125 | swap(pc, pd); 126 | pd -= es; 127 | } 128 | pc -= es; 129 | } 130 | if (pb > pc) 131 | break; 132 | swap(pb, pc); 133 | pb += es; 134 | pc -= es; 135 | } 136 | 137 | pn = a + n * es; 138 | r = min(pa - a, pb - pa); 139 | vecswap(a, pb - r, r); 140 | r = min(pd - pc, pn - pd - es); 141 | vecswap(pb, pn - r, r); 142 | if ((r = pb - pa) > es) 143 | qsort(a, r / es, es, cmp); 144 | if ((r = pd - pc) > es) { 145 | /* Iterate rather than recurse to save stack space */ 146 | a = pn - r; 147 | n = r / es; 148 | goto loop; 149 | } 150 | /* qsort(pn - r, r / es, es, cmp);*/ 151 | } 152 | DEF_STRONG(qsort); -------------------------------------------------------------------------------- /libsqlite3-sys/sqlite3/wasm32-unknown-unknown/libc/string/strcmp.c: -------------------------------------------------------------------------------- 1 | /* $OpenBSD: strcmp.c,v 1.9 2015/08/31 02:53:57 guenther Exp $ */ 2 | 3 | /*- 4 | * Copyright (c) 1990 The Regents of the University of California. 5 | * All rights reserved. 6 | * 7 | * This code is derived from software contributed to Berkeley by 8 | * Chris Torek. 9 | * 10 | * Redistribution and use in source and binary forms, with or without 11 | * modification, are permitted provided that the following conditions 12 | * are met: 13 | * 1. Redistributions of source code must retain the above copyright 14 | * notice, this list of conditions and the following disclaimer. 15 | * 2. Redistributions in binary form must reproduce the above copyright 16 | * notice, this list of conditions and the following disclaimer in the 17 | * documentation and/or other materials provided with the distribution. 18 | * 3. Neither the name of the University nor the names of its contributors 19 | * may be used to endorse or promote products derived from this software 20 | * without specific prior written permission. 21 | * 22 | * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 23 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 25 | * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 26 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 27 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 28 | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 29 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 30 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 31 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 32 | * SUCH DAMAGE. 33 | */ 34 | 35 | #include 36 | 37 | /* 38 | * Compare strings. 39 | */ 40 | int 41 | strcmp(const char *s1, const char *s2) 42 | { 43 | while (*s1 == *s2++) 44 | if (*s1++ == 0) 45 | return (0); 46 | return (*(unsigned char *)s1 - *(unsigned char *)--s2); 47 | } 48 | DEF_STRONG(strcmp); -------------------------------------------------------------------------------- /libsqlite3-sys/sqlite3/wasm32-unknown-unknown/libc/string/strcspn.c: -------------------------------------------------------------------------------- 1 | /* $OpenBSD: strcspn.c,v 1.6 2015/08/31 02:53:57 guenther Exp $ */ 2 | /*- 3 | * Copyright (c) 1990 The Regents of the University of California. 4 | * All rights reserved. 5 | * 6 | * This code is derived from software contributed to Berkeley by 7 | * Chris Torek. 8 | * 9 | * Redistribution and use in source and binary forms, with or without 10 | * modification, are permitted provided that the following conditions 11 | * are met: 12 | * 1. Redistributions of source code must retain the above copyright 13 | * notice, this list of conditions and the following disclaimer. 14 | * 2. Redistributions in binary form must reproduce the above copyright 15 | * notice, this list of conditions and the following disclaimer in the 16 | * documentation and/or other materials provided with the distribution. 17 | * 3. Neither the name of the University nor the names of its contributors 18 | * may be used to endorse or promote products derived from this software 19 | * without specific prior written permission. 20 | * 21 | * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 22 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 | * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 25 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 26 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 27 | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 28 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 29 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 30 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 | * SUCH DAMAGE. 32 | */ 33 | 34 | #include 35 | 36 | /* 37 | * Span the complement of string s2. 38 | */ 39 | size_t 40 | strcspn(const char *s1, const char *s2) 41 | { 42 | const char *p, *spanp; 43 | char c, sc; 44 | 45 | /* 46 | * Stop as soon as we find any character from s2. Note that there 47 | * must be a NUL in s2; it suffices to stop when we find that, too. 48 | */ 49 | for (p = s1;;) { 50 | c = *p++; 51 | spanp = s2; 52 | do { 53 | if ((sc = *spanp++) == c) 54 | return (p - 1 - s1); 55 | } while (sc != 0); 56 | } 57 | /* NOTREACHED */ 58 | } 59 | DEF_STRONG(strcspn); -------------------------------------------------------------------------------- /libsqlite3-sys/sqlite3/wasm32-unknown-unknown/libc/string/strlen.c: -------------------------------------------------------------------------------- 1 | /* $OpenBSD: strlen.c,v 1.9 2015/08/31 02:53:57 guenther Exp $ */ 2 | 3 | /*- 4 | * Copyright (c) 1990, 1993 5 | * The Regents of the University of California. All rights reserved. 6 | * 7 | * Redistribution and use in source and binary forms, with or without 8 | * modification, are permitted provided that the following conditions 9 | * are met: 10 | * 1. Redistributions of source code must retain the above copyright 11 | * notice, this list of conditions and the following disclaimer. 12 | * 2. Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in the 14 | * documentation and/or other materials provided with the distribution. 15 | * 3. Neither the name of the University nor the names of its contributors 16 | * may be used to endorse or promote products derived from this software 17 | * without specific prior written permission. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 | * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 23 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 24 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 25 | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 26 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 27 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 28 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 29 | * SUCH DAMAGE. 30 | */ 31 | 32 | #include 33 | 34 | size_t 35 | strlen(const char *str) 36 | { 37 | const char *s; 38 | 39 | for (s = str; *s; ++s) 40 | ; 41 | return (s - str); 42 | } 43 | 44 | DEF_STRONG(strlen); -------------------------------------------------------------------------------- /libsqlite3-sys/sqlite3/wasm32-unknown-unknown/libc/string/strncmp.c: -------------------------------------------------------------------------------- 1 | /* $OpenBSD: strncmp.c,v 1.9 2015/08/31 02:53:57 guenther Exp $ */ 2 | 3 | /* 4 | * Copyright (c) 1989 The Regents of the University of California. 5 | * All rights reserved. 6 | * 7 | * Redistribution and use in source and binary forms, with or without 8 | * modification, are permitted provided that the following conditions 9 | * are met: 10 | * 1. Redistributions of source code must retain the above copyright 11 | * notice, this list of conditions and the following disclaimer. 12 | * 2. Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in the 14 | * documentation and/or other materials provided with the distribution. 15 | * 3. Neither the name of the University nor the names of its contributors 16 | * may be used to endorse or promote products derived from this software 17 | * without specific prior written permission. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 | * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 23 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 24 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 25 | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 26 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 27 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 28 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 29 | * SUCH DAMAGE. 30 | */ 31 | 32 | #include 33 | 34 | int 35 | strncmp(const char *s1, const char *s2, size_t n) 36 | { 37 | 38 | if (n == 0) 39 | return (0); 40 | do { 41 | if (*s1 != *s2++) 42 | return (*(unsigned char *)s1 - *(unsigned char *)--s2); 43 | if (*s1++ == 0) 44 | break; 45 | } while (--n != 0); 46 | return (0); 47 | } 48 | DEF_STRONG(strncmp); -------------------------------------------------------------------------------- /libsqlite3-sys/sqlite3/wasm32-unknown-unknown/libc/string/strrchr.c: -------------------------------------------------------------------------------- 1 | /* $OpenBSD: strrchr.c,v 1.4 2018/10/01 06:37:37 martijn Exp $ */ 2 | /* 3 | * Copyright (c) 1988 Regents of the University of California. 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 1. Redistributions of source code must retain the above copyright 10 | * notice, this list of conditions and the following disclaimer. 11 | * 2. Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * 3. Neither the name of the University nor the names of its contributors 15 | * may be used to endorse or promote products derived from this software 16 | * without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 19 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 22 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 23 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 24 | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 25 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 26 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 27 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 28 | * SUCH DAMAGE. 29 | */ 30 | 31 | #include 32 | 33 | __weak_alias(rindex, strrchr); 34 | 35 | char * 36 | strrchr(const char *p, int ch) 37 | { 38 | char *save; 39 | 40 | for (save = NULL;; ++p) { 41 | if (*p == (char) ch) 42 | save = (char *)p; 43 | if (!*p) 44 | return(save); 45 | } 46 | /* NOTREACHED */ 47 | } 48 | DEF_STRONG(strrchr); -------------------------------------------------------------------------------- /libsqlite3-sys/sqlite3/wasm32-wasi-vfs.c: -------------------------------------------------------------------------------- 1 | /* 2 | ** 2010 April 7 3 | ** 4 | ** The author disclaims copyright to this source code. In place of 5 | ** a legal notice, here is a blessing: 6 | ** 7 | ** May you do good and not evil. 8 | ** May you find forgiveness for yourself and forgive others. 9 | ** May you share freely, never taking more than you give. 10 | ** 11 | ************************************************************************* 12 | ** 13 | ** This file implements an example of a simple VFS implementation that 14 | ** omits complex features often not required or not possible on embedded 15 | ** platforms. Code is included to buffer writes to the journal file, 16 | ** which can be a significant performance improvement on some embedded 17 | ** platforms. 18 | ** 19 | ** OVERVIEW 20 | ** 21 | ** The code in this file implements a minimal SQLite VFS that can be 22 | ** used on Linux and other posix-like operating systems. The following 23 | ** system calls are used: 24 | ** 25 | ** File-system: access(), unlink(), getcwd() 26 | ** File IO: open(), read(), write(), fsync(), close(), fstat() 27 | ** Other: sleep(), usleep(), time() 28 | ** 29 | ** The following VFS features are omitted: 30 | ** 31 | ** 1. File locking. The user must ensure that there is at most one 32 | ** connection to each database when using this VFS. Multiple 33 | ** connections to a single shared-cache count as a single connection 34 | ** for the purposes of the previous statement. 35 | ** 36 | ** 2. The loading of dynamic extensions (shared libraries). 37 | ** 38 | ** 3. Temporary files. The user must configure SQLite to use in-memory 39 | ** temp files when using this VFS. The easiest way to do this is to 40 | ** compile with: 41 | ** 42 | ** -DSQLITE_TEMP_STORE=3 43 | ** 44 | ** 4. File truncation. As of version 3.6.24, SQLite may run without 45 | ** a working xTruncate() call, providing the user does not configure 46 | ** SQLite to use "journal_mode=truncate", or use both 47 | ** "journal_mode=persist" and ATTACHed databases. 48 | ** 49 | ** It is assumed that the system uses UNIX-like path-names. Specifically, 50 | ** that '/' characters are used to separate path components and that 51 | ** a path-name is a relative path unless it begins with a '/'. And that 52 | ** no UTF-8 encoded paths are greater than 512 bytes in length. 53 | ** 54 | ** JOURNAL WRITE-BUFFERING 55 | ** 56 | ** To commit a transaction to the database, SQLite first writes rollback 57 | ** information into the journal file. This usually consists of 4 steps: 58 | ** 59 | ** 1. The rollback information is sequentially written into the journal 60 | ** file, starting at the start of the file. 61 | ** 2. The journal file is synced to disk. 62 | ** 3. A modification is made to the first few bytes of the journal file. 63 | ** 4. The journal file is synced to disk again. 64 | ** 65 | ** Most of the data is written in step 1 using a series of calls to the 66 | ** VFS xWrite() method. The buffers passed to the xWrite() calls are of 67 | ** various sizes. For example, as of version 3.6.24, when committing a 68 | ** transaction that modifies 3 pages of a database file that uses 4096 69 | ** byte pages residing on a media with 512 byte sectors, SQLite makes 70 | ** eleven calls to the xWrite() method to create the rollback journal, 71 | ** as follows: 72 | ** 73 | ** Write offset | Bytes written 74 | ** ---------------------------- 75 | ** 0 512 76 | ** 512 4 77 | ** 516 4096 78 | ** 4612 4 79 | ** 4616 4 80 | ** 4620 4096 81 | ** 8716 4 82 | ** 8720 4 83 | ** 8724 4096 84 | ** 12820 4 85 | ** ++++++++++++SYNC+++++++++++ 86 | ** 0 12 87 | ** ++++++++++++SYNC+++++++++++ 88 | ** 89 | ** On many operating systems, this is an efficient way to write to a file. 90 | ** However, on some embedded systems that do not cache writes in OS 91 | ** buffers it is much more efficient to write data in blocks that are 92 | ** an integer multiple of the sector-size in size and aligned at the 93 | ** start of a sector. 94 | ** 95 | ** To work around this, the code in this file allocates a fixed size 96 | ** buffer of SQLITE_DEMOVFS_BUFFERSZ using sqlite3_malloc() whenever a 97 | ** journal file is opened. It uses the buffer to coalesce sequential 98 | ** writes into aligned SQLITE_DEMOVFS_BUFFERSZ blocks. When SQLite 99 | ** invokes the xSync() method to sync the contents of the file to disk, 100 | ** all accumulated data is written out, even if it does not constitute 101 | ** a complete block. This means the actual IO to create the rollback 102 | ** journal for the example transaction above is this: 103 | ** 104 | ** Write offset | Bytes written 105 | ** ---------------------------- 106 | ** 0 8192 107 | ** 8192 4632 108 | ** ++++++++++++SYNC+++++++++++ 109 | ** 0 12 110 | ** ++++++++++++SYNC+++++++++++ 111 | ** 112 | ** Much more efficient if the underlying OS is not caching write 113 | ** operations. 114 | */ 115 | 116 | #if !defined(SQLITE_TEST) || SQLITE_OS_UNIX 117 | 118 | #include "sqlite3.h" 119 | 120 | #include 121 | #include 122 | #include 123 | #include 124 | #include 125 | #include 126 | #include 127 | #include 128 | #include 129 | #include 130 | 131 | /* 132 | ** Size of the write buffer used by journal files in bytes. 133 | */ 134 | #ifndef SQLITE_DEMOVFS_BUFFERSZ 135 | # define SQLITE_DEMOVFS_BUFFERSZ 8192 136 | #endif 137 | 138 | /* 139 | ** The maximum pathname length supported by this VFS. 140 | */ 141 | #define MAXPATHNAME 512 142 | 143 | /* 144 | ** When using this VFS, the sqlite3_file* handles that SQLite uses are 145 | ** actually pointers to instances of type DemoFile. 146 | */ 147 | typedef struct DemoFile DemoFile; 148 | struct DemoFile { 149 | sqlite3_file base; /* Base class. Must be first. */ 150 | int fd; /* File descriptor */ 151 | 152 | char *aBuffer; /* Pointer to malloc'd buffer */ 153 | int nBuffer; /* Valid bytes of data in zBuffer */ 154 | sqlite3_int64 iBufferOfst; /* Offset in file of zBuffer[0] */ 155 | }; 156 | 157 | /* 158 | ** Write directly to the file passed as the first argument. Even if the 159 | ** file has a write-buffer (DemoFile.aBuffer), ignore it. 160 | */ 161 | static int demoDirectWrite( 162 | DemoFile *p, /* File handle */ 163 | const void *zBuf, /* Buffer containing data to write */ 164 | int iAmt, /* Size of data to write in bytes */ 165 | sqlite_int64 iOfst /* File offset to write to */ 166 | ){ 167 | off_t ofst; /* Return value from lseek() */ 168 | size_t nWrite; /* Return value from write() */ 169 | 170 | ofst = lseek(p->fd, iOfst, SEEK_SET); 171 | if( ofst!=iOfst ){ 172 | return SQLITE_IOERR_WRITE; 173 | } 174 | 175 | nWrite = write(p->fd, zBuf, iAmt); 176 | if( nWrite!=iAmt ){ 177 | return SQLITE_IOERR_WRITE; 178 | } 179 | 180 | return SQLITE_OK; 181 | } 182 | 183 | /* 184 | ** Flush the contents of the DemoFile.aBuffer buffer to disk. This is a 185 | ** no-op if this particular file does not have a buffer (i.e. it is not 186 | ** a journal file) or if the buffer is currently empty. 187 | */ 188 | static int demoFlushBuffer(DemoFile *p){ 189 | int rc = SQLITE_OK; 190 | if( p->nBuffer ){ 191 | rc = demoDirectWrite(p, p->aBuffer, p->nBuffer, p->iBufferOfst); 192 | p->nBuffer = 0; 193 | } 194 | return rc; 195 | } 196 | 197 | /* 198 | ** Close a file. 199 | */ 200 | static int demoClose(sqlite3_file *pFile){ 201 | int rc; 202 | DemoFile *p = (DemoFile*)pFile; 203 | rc = demoFlushBuffer(p); 204 | sqlite3_free(p->aBuffer); 205 | close(p->fd); 206 | return rc; 207 | } 208 | 209 | /* 210 | ** Read data from a file. 211 | */ 212 | static int demoRead( 213 | sqlite3_file *pFile, 214 | void *zBuf, 215 | int iAmt, 216 | sqlite_int64 iOfst 217 | ){ 218 | DemoFile *p = (DemoFile*)pFile; 219 | off_t ofst; /* Return value from lseek() */ 220 | int nRead; /* Return value from read() */ 221 | int rc; /* Return code from demoFlushBuffer() */ 222 | 223 | /* Flush any data in the write buffer to disk in case this operation 224 | ** is trying to read data the file-region currently cached in the buffer. 225 | ** It would be possible to detect this case and possibly save an 226 | ** unnecessary write here, but in practice SQLite will rarely read from 227 | ** a journal file when there is data cached in the write-buffer. 228 | */ 229 | rc = demoFlushBuffer(p); 230 | if( rc!=SQLITE_OK ){ 231 | return rc; 232 | } 233 | 234 | ofst = lseek(p->fd, iOfst, SEEK_SET); 235 | if( ofst!=iOfst ){ 236 | return SQLITE_IOERR_READ; 237 | } 238 | nRead = read(p->fd, zBuf, iAmt); 239 | 240 | if( nRead==iAmt ){ 241 | return SQLITE_OK; 242 | }else if( nRead>=0 ){ 243 | return SQLITE_IOERR_SHORT_READ; 244 | } 245 | 246 | return SQLITE_IOERR_READ; 247 | } 248 | 249 | /* 250 | ** Write data to a crash-file. 251 | */ 252 | static int demoWrite( 253 | sqlite3_file *pFile, 254 | const void *zBuf, 255 | int iAmt, 256 | sqlite_int64 iOfst 257 | ){ 258 | DemoFile *p = (DemoFile*)pFile; 259 | 260 | if( p->aBuffer ){ 261 | char *z = (char *)zBuf; /* Pointer to remaining data to write */ 262 | int n = iAmt; /* Number of bytes at z */ 263 | sqlite3_int64 i = iOfst; /* File offset to write to */ 264 | 265 | while( n>0 ){ 266 | int nCopy; /* Number of bytes to copy into buffer */ 267 | 268 | /* If the buffer is full, or if this data is not being written directly 269 | ** following the data already buffered, flush the buffer. Flushing 270 | ** the buffer is a no-op if it is empty. 271 | */ 272 | if( p->nBuffer==SQLITE_DEMOVFS_BUFFERSZ || p->iBufferOfst+p->nBuffer!=i ){ 273 | int rc = demoFlushBuffer(p); 274 | if( rc!=SQLITE_OK ){ 275 | return rc; 276 | } 277 | } 278 | assert( p->nBuffer==0 || p->iBufferOfst+p->nBuffer==i ); 279 | p->iBufferOfst = i - p->nBuffer; 280 | 281 | /* Copy as much data as possible into the buffer. */ 282 | nCopy = SQLITE_DEMOVFS_BUFFERSZ - p->nBuffer; 283 | if( nCopy>n ){ 284 | nCopy = n; 285 | } 286 | memcpy(&p->aBuffer[p->nBuffer], z, nCopy); 287 | p->nBuffer += nCopy; 288 | 289 | n -= nCopy; 290 | i += nCopy; 291 | z += nCopy; 292 | } 293 | }else{ 294 | return demoDirectWrite(p, zBuf, iAmt, iOfst); 295 | } 296 | 297 | return SQLITE_OK; 298 | } 299 | 300 | /* 301 | ** Truncate a file. This is a no-op for this VFS (see header comments at 302 | ** the top of the file). 303 | */ 304 | static int demoTruncate(sqlite3_file *pFile, sqlite_int64 size){ 305 | #if 0 306 | if( ftruncate(((DemoFile *)pFile)->fd, size) ) return SQLITE_IOERR_TRUNCATE; 307 | #endif 308 | return SQLITE_OK; 309 | } 310 | 311 | /* 312 | ** Sync the contents of the file to the persistent media. 313 | */ 314 | static int demoSync(sqlite3_file *pFile, int flags){ 315 | DemoFile *p = (DemoFile*)pFile; 316 | int rc; 317 | 318 | rc = demoFlushBuffer(p); 319 | if( rc!=SQLITE_OK ){ 320 | return rc; 321 | } 322 | 323 | rc = fsync(p->fd); 324 | return (rc==0 ? SQLITE_OK : SQLITE_IOERR_FSYNC); 325 | } 326 | 327 | /* 328 | ** Write the size of the file in bytes to *pSize. 329 | */ 330 | static int demoFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ 331 | DemoFile *p = (DemoFile*)pFile; 332 | int rc; /* Return code from fstat() call */ 333 | struct stat sStat; /* Output of fstat() call */ 334 | 335 | /* Flush the contents of the buffer to disk. As with the flush in the 336 | ** demoRead() method, it would be possible to avoid this and save a write 337 | ** here and there. But in practice this comes up so infrequently it is 338 | ** not worth the trouble. 339 | */ 340 | rc = demoFlushBuffer(p); 341 | if( rc!=SQLITE_OK ){ 342 | return rc; 343 | } 344 | 345 | rc = fstat(p->fd, &sStat); 346 | if( rc!=0 ) return SQLITE_IOERR_FSTAT; 347 | *pSize = sStat.st_size; 348 | return SQLITE_OK; 349 | } 350 | 351 | /* 352 | ** Locking functions. The xLock() and xUnlock() methods are both no-ops. 353 | ** The xCheckReservedLock() always indicates that no other process holds 354 | ** a reserved lock on the database file. This ensures that if a hot-journal 355 | ** file is found in the file-system it is rolled back. 356 | */ 357 | static int demoLock(sqlite3_file *pFile, int eLock){ 358 | return SQLITE_OK; 359 | } 360 | static int demoUnlock(sqlite3_file *pFile, int eLock){ 361 | return SQLITE_OK; 362 | } 363 | static int demoCheckReservedLock(sqlite3_file *pFile, int *pResOut){ 364 | *pResOut = 0; 365 | return SQLITE_OK; 366 | } 367 | 368 | /* 369 | ** No xFileControl() verbs are implemented by this VFS. 370 | */ 371 | static int demoFileControl(sqlite3_file *pFile, int op, void *pArg){ 372 | return SQLITE_OK; 373 | } 374 | 375 | /* 376 | ** The xSectorSize() and xDeviceCharacteristics() methods. These two 377 | ** may return special values allowing SQLite to optimize file-system 378 | ** access to some extent. But it is also safe to simply return 0. 379 | */ 380 | static int demoSectorSize(sqlite3_file *pFile){ 381 | return 0; 382 | } 383 | static int demoDeviceCharacteristics(sqlite3_file *pFile){ 384 | return 0; 385 | } 386 | 387 | /* 388 | ** Open a file handle. 389 | */ 390 | static int demoOpen( 391 | sqlite3_vfs *pVfs, /* VFS */ 392 | const char *zName, /* File to open, or 0 for a temp file */ 393 | sqlite3_file *pFile, /* Pointer to DemoFile struct to populate */ 394 | int flags, /* Input SQLITE_OPEN_XXX flags */ 395 | int *pOutFlags /* Output SQLITE_OPEN_XXX flags (or NULL) */ 396 | ){ 397 | static const sqlite3_io_methods demoio = { 398 | 1, /* iVersion */ 399 | demoClose, /* xClose */ 400 | demoRead, /* xRead */ 401 | demoWrite, /* xWrite */ 402 | demoTruncate, /* xTruncate */ 403 | demoSync, /* xSync */ 404 | demoFileSize, /* xFileSize */ 405 | demoLock, /* xLock */ 406 | demoUnlock, /* xUnlock */ 407 | demoCheckReservedLock, /* xCheckReservedLock */ 408 | demoFileControl, /* xFileControl */ 409 | demoSectorSize, /* xSectorSize */ 410 | demoDeviceCharacteristics /* xDeviceCharacteristics */ 411 | }; 412 | 413 | DemoFile *p = (DemoFile*)pFile; /* Populate this structure */ 414 | int oflags = 0; /* flags to pass to open() call */ 415 | char *aBuf = 0; 416 | 417 | if( zName==0 ){ 418 | return SQLITE_IOERR; 419 | } 420 | 421 | if( flags&SQLITE_OPEN_MAIN_JOURNAL ){ 422 | aBuf = (char *)sqlite3_malloc(SQLITE_DEMOVFS_BUFFERSZ); 423 | if( !aBuf ){ 424 | return SQLITE_NOMEM; 425 | } 426 | } 427 | 428 | if( flags&SQLITE_OPEN_EXCLUSIVE ) oflags |= O_EXCL; 429 | if( flags&SQLITE_OPEN_CREATE ) oflags |= O_CREAT; 430 | if( flags&SQLITE_OPEN_READONLY ) oflags |= O_RDONLY; 431 | if( flags&SQLITE_OPEN_READWRITE ) oflags |= O_RDWR; 432 | 433 | memset(p, 0, sizeof(DemoFile)); 434 | p->fd = open(zName, oflags, 0600); 435 | if( p->fd<0 ){ 436 | sqlite3_free(aBuf); 437 | return SQLITE_CANTOPEN; 438 | } 439 | p->aBuffer = aBuf; 440 | 441 | if( pOutFlags ){ 442 | *pOutFlags = flags; 443 | } 444 | p->base.pMethods = &demoio; 445 | return SQLITE_OK; 446 | } 447 | 448 | /* 449 | ** Delete the file identified by argument zPath. If the dirSync parameter 450 | ** is non-zero, then ensure the file-system modification to delete the 451 | ** file has been synced to disk before returning. 452 | */ 453 | static int demoDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ 454 | int rc; /* Return code */ 455 | 456 | rc = unlink(zPath); 457 | if( rc!=0 && errno==ENOENT ) return SQLITE_OK; 458 | 459 | if( rc==0 && dirSync ){ 460 | int dfd; /* File descriptor open on directory */ 461 | int i; /* Iterator variable */ 462 | char zDir[MAXPATHNAME+1]; /* Name of directory containing file zPath */ 463 | 464 | /* Figure out the directory name from the path of the file deleted. */ 465 | sqlite3_snprintf(MAXPATHNAME, zDir, "%s", zPath); 466 | zDir[MAXPATHNAME] = '\0'; 467 | for(i=strlen(zDir); i>1 && zDir[i]!='/'; i++); 468 | zDir[i] = '\0'; 469 | 470 | /* Open a file-descriptor on the directory. Sync. Close. */ 471 | dfd = open(zDir, O_RDONLY, 0); 472 | if( dfd<0 ){ 473 | rc = -1; 474 | }else{ 475 | rc = fsync(dfd); 476 | close(dfd); 477 | } 478 | } 479 | return (rc==0 ? SQLITE_OK : SQLITE_IOERR_DELETE); 480 | } 481 | 482 | #ifndef F_OK 483 | # define F_OK 0 484 | #endif 485 | #ifndef R_OK 486 | # define R_OK 4 487 | #endif 488 | #ifndef W_OK 489 | # define W_OK 2 490 | #endif 491 | 492 | /* 493 | ** Query the file-system to see if the named file exists, is readable or 494 | ** is both readable and writable. 495 | */ 496 | static int demoAccess( 497 | sqlite3_vfs *pVfs, 498 | const char *zPath, 499 | int flags, 500 | int *pResOut 501 | ){ 502 | int rc; /* access() return code */ 503 | int eAccess = F_OK; /* Second argument to access() */ 504 | 505 | assert( flags==SQLITE_ACCESS_EXISTS /* access(zPath, F_OK) */ 506 | || flags==SQLITE_ACCESS_READ /* access(zPath, R_OK) */ 507 | || flags==SQLITE_ACCESS_READWRITE /* access(zPath, R_OK|W_OK) */ 508 | ); 509 | 510 | if( flags==SQLITE_ACCESS_READWRITE ) eAccess = R_OK|W_OK; 511 | if( flags==SQLITE_ACCESS_READ ) eAccess = R_OK; 512 | 513 | rc = access(zPath, eAccess); 514 | *pResOut = (rc==0); 515 | return SQLITE_OK; 516 | } 517 | 518 | /* 519 | ** Argument zPath points to a nul-terminated string containing a file path. 520 | ** If zPath is an absolute path, then it is copied as is into the output 521 | ** buffer. Otherwise, if it is a relative path, then the equivalent full 522 | ** path is written to the output buffer. 523 | ** 524 | ** This function assumes that paths are UNIX style. Specifically, that: 525 | ** 526 | ** 1. Path components are separated by a '/'. and 527 | ** 2. Full paths begin with a '/' character. 528 | */ 529 | static int demoFullPathname( 530 | sqlite3_vfs *pVfs, /* VFS */ 531 | const char *zPath, /* Input path (possibly a relative path) */ 532 | int nPathOut, /* Size of output buffer in bytes */ 533 | char *zPathOut /* Pointer to output buffer */ 534 | ){ 535 | sqlite3_snprintf(nPathOut, zPathOut, "%s", zPath); 536 | zPathOut[nPathOut-1] = '\0'; 537 | 538 | return SQLITE_OK; 539 | } 540 | 541 | /* 542 | ** The following four VFS methods: 543 | ** 544 | ** xDlOpen 545 | ** xDlError 546 | ** xDlSym 547 | ** xDlClose 548 | ** 549 | ** are supposed to implement the functionality needed by SQLite to load 550 | ** extensions compiled as shared objects. This simple VFS does not support 551 | ** this functionality, so the following functions are no-ops. 552 | */ 553 | static void *demoDlOpen(sqlite3_vfs *pVfs, const char *zPath){ 554 | return 0; 555 | } 556 | static void demoDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ 557 | sqlite3_snprintf(nByte, zErrMsg, "Loadable extensions are not supported"); 558 | zErrMsg[nByte-1] = '\0'; 559 | } 560 | static void (*demoDlSym(sqlite3_vfs *pVfs, void *pH, const char *z))(void){ 561 | return 0; 562 | } 563 | static void demoDlClose(sqlite3_vfs *pVfs, void *pHandle){ 564 | return; 565 | } 566 | 567 | /* 568 | ** Parameter zByte points to a buffer nByte bytes in size. Populate this 569 | ** buffer with pseudo-random data. 570 | */ 571 | static int demoRandomness(sqlite3_vfs *pVfs, int nByte, char *zByte){ 572 | return SQLITE_OK; 573 | } 574 | 575 | /* 576 | ** Sleep for at least nMicro microseconds. Return the (approximate) number 577 | ** of microseconds slept for. 578 | */ 579 | static int demoSleep(sqlite3_vfs *pVfs, int nMicro){ 580 | sleep(nMicro / 1000000); 581 | usleep(nMicro % 1000000); 582 | return nMicro; 583 | } 584 | 585 | /* 586 | ** Set *pTime to the current UTC time expressed as a Julian day. Return 587 | ** SQLITE_OK if successful, or an error code otherwise. 588 | ** 589 | ** http://en.wikipedia.org/wiki/Julian_day 590 | ** 591 | ** This implementation is not very good. The current time is rounded to 592 | ** an integer number of seconds. Also, assuming time_t is a signed 32-bit 593 | ** value, it will stop working some time in the year 2038 AD (the so-called 594 | ** "year 2038" problem that afflicts systems that store time this way). 595 | */ 596 | static int demoCurrentTime(sqlite3_vfs *pVfs, double *pTime){ 597 | time_t t = time(0); 598 | *pTime = t/86400.0 + 2440587.5; 599 | return SQLITE_OK; 600 | } 601 | 602 | /* 603 | ** This function returns a pointer to the VFS implemented in this file. 604 | ** To make the VFS available to SQLite: 605 | ** 606 | ** sqlite3_vfs_register(sqlite3_demovfs(), 0); 607 | */ 608 | sqlite3_vfs *sqlite3_demovfs(void){ 609 | static sqlite3_vfs demovfs = { 610 | 1, /* iVersion */ 611 | sizeof(DemoFile), /* szOsFile */ 612 | MAXPATHNAME, /* mxPathname */ 613 | 0, /* pNext */ 614 | "demo", /* zName */ 615 | 0, /* pAppData */ 616 | demoOpen, /* xOpen */ 617 | demoDelete, /* xDelete */ 618 | demoAccess, /* xAccess */ 619 | demoFullPathname, /* xFullPathname */ 620 | demoDlOpen, /* xDlOpen */ 621 | demoDlError, /* xDlError */ 622 | demoDlSym, /* xDlSym */ 623 | demoDlClose, /* xDlClose */ 624 | demoRandomness, /* xRandomness */ 625 | demoSleep, /* xSleep */ 626 | demoCurrentTime, /* xCurrentTime */ 627 | }; 628 | return &demovfs; 629 | } 630 | 631 | #endif /* !defined(SQLITE_TEST) || SQLITE_OS_UNIX */ 632 | 633 | 634 | #ifdef SQLITE_TEST 635 | 636 | #if defined(INCLUDE_SQLITE_TCL_H) 637 | # include "sqlite_tcl.h" 638 | #else 639 | # include "tcl.h" 640 | # ifndef SQLITE_TCLAPI 641 | # define SQLITE_TCLAPI 642 | # endif 643 | #endif 644 | 645 | #if SQLITE_OS_UNIX 646 | static int SQLITE_TCLAPI register_demovfs( 647 | ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ 648 | Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ 649 | int objc, /* Number of arguments */ 650 | Tcl_Obj *CONST objv[] /* Command arguments */ 651 | ){ 652 | sqlite3_vfs_register(sqlite3_demovfs(), 1); 653 | return TCL_OK; 654 | } 655 | static int SQLITE_TCLAPI unregister_demovfs( 656 | ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ 657 | Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ 658 | int objc, /* Number of arguments */ 659 | Tcl_Obj *CONST objv[] /* Command arguments */ 660 | ){ 661 | sqlite3_vfs_unregister(sqlite3_demovfs()); 662 | return TCL_OK; 663 | } 664 | 665 | /* 666 | ** Register commands with the TCL interpreter. 667 | */ 668 | int Sqlitetest_demovfs_Init(Tcl_Interp *interp){ 669 | Tcl_CreateObjCommand(interp, "register_demovfs", register_demovfs, 0, 0); 670 | Tcl_CreateObjCommand(interp, "unregister_demovfs", unregister_demovfs, 0, 0); 671 | return TCL_OK; 672 | } 673 | 674 | #else 675 | int Sqlitetest_demovfs_Init(Tcl_Interp *interp){ return TCL_OK; } 676 | #endif 677 | 678 | #endif /* SQLITE_TEST */ 679 | 680 | // Register sqlite3_demovfs 681 | int sqlite3_os_init() 682 | { 683 | sqlite3_vfs_register(sqlite3_demovfs(), 0); 684 | return 0; 685 | } 686 | 687 | int sqlite3_os_end() 688 | { 689 | return 0; 690 | } 691 | -------------------------------------------------------------------------------- /libsqlite3-sys/src/error.rs: -------------------------------------------------------------------------------- 1 | use std::error; 2 | use std::fmt; 3 | use std::os::raw::c_int; 4 | 5 | /// Error Codes 6 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] 7 | #[non_exhaustive] 8 | pub enum ErrorCode { 9 | /// Internal logic error in SQLite 10 | InternalMalfunction, 11 | /// Access permission denied 12 | PermissionDenied, 13 | /// Callback routine requested an abort 14 | OperationAborted, 15 | /// The database file is locked 16 | DatabaseBusy, 17 | /// A table in the database is locked 18 | DatabaseLocked, 19 | /// A malloc() failed 20 | OutOfMemory, 21 | /// Attempt to write a readonly database 22 | ReadOnly, 23 | /// Operation terminated by sqlite3_interrupt() 24 | OperationInterrupted, 25 | /// Some kind of disk I/O error occurred 26 | SystemIoFailure, 27 | /// The database disk image is malformed 28 | DatabaseCorrupt, 29 | /// Unknown opcode in sqlite3_file_control() 30 | NotFound, 31 | /// Insertion failed because database is full 32 | DiskFull, 33 | /// Unable to open the database file 34 | CannotOpen, 35 | /// Database lock protocol error 36 | FileLockingProtocolFailed, 37 | /// The database schema changed 38 | SchemaChanged, 39 | /// String or BLOB exceeds size limit 40 | TooBig, 41 | /// Abort due to constraint violation 42 | ConstraintViolation, 43 | /// Data type mismatch 44 | TypeMismatch, 45 | /// Library used incorrectly 46 | ApiMisuse, 47 | /// Uses OS features not supported on host 48 | NoLargeFileSupport, 49 | /// Authorization denied 50 | AuthorizationForStatementDenied, 51 | /// 2nd parameter to sqlite3_bind out of range 52 | ParameterOutOfRange, 53 | /// File opened that is not a database file 54 | NotADatabase, 55 | /// SQL error or missing database 56 | Unknown, 57 | } 58 | 59 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] 60 | pub struct Error { 61 | pub code: ErrorCode, 62 | pub extended_code: c_int, 63 | } 64 | 65 | impl Error { 66 | #[must_use] 67 | pub fn new(result_code: c_int) -> Error { 68 | let code = match result_code & 0xff { 69 | super::SQLITE_INTERNAL => ErrorCode::InternalMalfunction, 70 | super::SQLITE_PERM => ErrorCode::PermissionDenied, 71 | super::SQLITE_ABORT => ErrorCode::OperationAborted, 72 | super::SQLITE_BUSY => ErrorCode::DatabaseBusy, 73 | super::SQLITE_LOCKED => ErrorCode::DatabaseLocked, 74 | super::SQLITE_NOMEM => ErrorCode::OutOfMemory, 75 | super::SQLITE_READONLY => ErrorCode::ReadOnly, 76 | super::SQLITE_INTERRUPT => ErrorCode::OperationInterrupted, 77 | super::SQLITE_IOERR => ErrorCode::SystemIoFailure, 78 | super::SQLITE_CORRUPT => ErrorCode::DatabaseCorrupt, 79 | super::SQLITE_NOTFOUND => ErrorCode::NotFound, 80 | super::SQLITE_FULL => ErrorCode::DiskFull, 81 | super::SQLITE_CANTOPEN => ErrorCode::CannotOpen, 82 | super::SQLITE_PROTOCOL => ErrorCode::FileLockingProtocolFailed, 83 | super::SQLITE_SCHEMA => ErrorCode::SchemaChanged, 84 | super::SQLITE_TOOBIG => ErrorCode::TooBig, 85 | super::SQLITE_CONSTRAINT => ErrorCode::ConstraintViolation, 86 | super::SQLITE_MISMATCH => ErrorCode::TypeMismatch, 87 | super::SQLITE_MISUSE => ErrorCode::ApiMisuse, 88 | super::SQLITE_NOLFS => ErrorCode::NoLargeFileSupport, 89 | super::SQLITE_AUTH => ErrorCode::AuthorizationForStatementDenied, 90 | super::SQLITE_RANGE => ErrorCode::ParameterOutOfRange, 91 | super::SQLITE_NOTADB => ErrorCode::NotADatabase, 92 | _ => ErrorCode::Unknown, 93 | }; 94 | 95 | Error { 96 | code, 97 | extended_code: result_code, 98 | } 99 | } 100 | } 101 | 102 | impl fmt::Display for Error { 103 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 104 | write!( 105 | f, 106 | "Error code {}: {}", 107 | self.extended_code, 108 | code_to_str(self.extended_code) 109 | ) 110 | } 111 | } 112 | 113 | impl error::Error for Error { 114 | fn description(&self) -> &str { 115 | code_to_str(self.extended_code) 116 | } 117 | } 118 | 119 | // Result codes. 120 | // Note: These are not public because our bindgen bindings export whichever 121 | // constants are present in the current version of SQLite. We repeat them here 122 | // so we don't have to worry about which version of SQLite added which 123 | // constants, and we only use them to implement code_to_str below. 124 | 125 | // Extended result codes. 126 | 127 | const SQLITE_ERROR_MISSING_COLLSEQ: c_int = super::SQLITE_ERROR | (1 << 8); 128 | const SQLITE_ERROR_RETRY: c_int = super::SQLITE_ERROR | (2 << 8); 129 | const SQLITE_ERROR_SNAPSHOT: c_int = super::SQLITE_ERROR | (3 << 8); 130 | 131 | const SQLITE_IOERR_BEGIN_ATOMIC: c_int = super::SQLITE_IOERR | (29 << 8); 132 | const SQLITE_IOERR_COMMIT_ATOMIC: c_int = super::SQLITE_IOERR | (30 << 8); 133 | const SQLITE_IOERR_ROLLBACK_ATOMIC: c_int = super::SQLITE_IOERR | (31 << 8); 134 | const SQLITE_IOERR_DATA: c_int = super::SQLITE_IOERR | (32 << 8); 135 | 136 | const SQLITE_LOCKED_VTAB: c_int = super::SQLITE_LOCKED | (2 << 8); 137 | 138 | const SQLITE_BUSY_TIMEOUT: c_int = super::SQLITE_BUSY | (3 << 8); 139 | 140 | const SQLITE_CANTOPEN_SYMLINK: c_int = super::SQLITE_CANTOPEN | (6 << 8); 141 | 142 | const SQLITE_CORRUPT_SEQUENCE: c_int = super::SQLITE_CORRUPT | (2 << 8); 143 | const SQLITE_CORRUPT_INDEX: c_int = super::SQLITE_CORRUPT | (3 << 8); 144 | 145 | const SQLITE_READONLY_CANTINIT: c_int = super::SQLITE_READONLY | (5 << 8); 146 | const SQLITE_READONLY_DIRECTORY: c_int = super::SQLITE_READONLY | (6 << 8); 147 | 148 | const SQLITE_CONSTRAINT_PINNED: c_int = super::SQLITE_CONSTRAINT | (11 << 8); 149 | const SQLITE_CONSTRAINT_DATATYPE: c_int = super::SQLITE_CONSTRAINT | (12 << 8); 150 | 151 | #[must_use] 152 | pub fn code_to_str(code: c_int) -> &'static str { 153 | match code { 154 | super::SQLITE_OK => "Successful result", 155 | super::SQLITE_ERROR => "SQL error or missing database", 156 | super::SQLITE_INTERNAL => "Internal logic error in SQLite", 157 | super::SQLITE_PERM => "Access permission denied", 158 | super::SQLITE_ABORT => "Callback routine requested an abort", 159 | super::SQLITE_BUSY => "The database file is locked", 160 | super::SQLITE_LOCKED => "A table in the database is locked", 161 | super::SQLITE_NOMEM => "A malloc() failed", 162 | super::SQLITE_READONLY => "Attempt to write a readonly database", 163 | super::SQLITE_INTERRUPT => "Operation terminated by sqlite3_interrupt()", 164 | super::SQLITE_IOERR => "Some kind of disk I/O error occurred", 165 | super::SQLITE_CORRUPT => "The database disk image is malformed", 166 | super::SQLITE_NOTFOUND => "Unknown opcode in sqlite3_file_control()", 167 | super::SQLITE_FULL => "Insertion failed because database is full", 168 | super::SQLITE_CANTOPEN => "Unable to open the database file", 169 | super::SQLITE_PROTOCOL => "Database lock protocol error", 170 | super::SQLITE_EMPTY => "Database is empty", 171 | super::SQLITE_SCHEMA => "The database schema changed", 172 | super::SQLITE_TOOBIG => "String or BLOB exceeds size limit", 173 | super::SQLITE_CONSTRAINT=> "Abort due to constraint violation", 174 | super::SQLITE_MISMATCH => "Data type mismatch", 175 | super::SQLITE_MISUSE => "Library used incorrectly", 176 | super::SQLITE_NOLFS => "Uses OS features not supported on host", 177 | super::SQLITE_AUTH => "Authorization denied", 178 | super::SQLITE_FORMAT => "Auxiliary database format error", 179 | super::SQLITE_RANGE => "2nd parameter to sqlite3_bind out of range", 180 | super::SQLITE_NOTADB => "File opened that is not a database file", 181 | super::SQLITE_NOTICE => "Notifications from sqlite3_log()", 182 | super::SQLITE_WARNING => "Warnings from sqlite3_log()", 183 | super::SQLITE_ROW => "sqlite3_step() has another row ready", 184 | super::SQLITE_DONE => "sqlite3_step() has finished executing", 185 | 186 | SQLITE_ERROR_MISSING_COLLSEQ => "SQLITE_ERROR_MISSING_COLLSEQ", 187 | SQLITE_ERROR_RETRY => "SQLITE_ERROR_RETRY", 188 | SQLITE_ERROR_SNAPSHOT => "SQLITE_ERROR_SNAPSHOT", 189 | 190 | super::SQLITE_IOERR_READ => "Error reading from disk", 191 | super::SQLITE_IOERR_SHORT_READ => "Unable to obtain number of requested bytes (file truncated?)", 192 | super::SQLITE_IOERR_WRITE => "Error writing to disk", 193 | super::SQLITE_IOERR_FSYNC => "Error flushing data to persistent storage (fsync)", 194 | super::SQLITE_IOERR_DIR_FSYNC => "Error calling fsync on a directory", 195 | super::SQLITE_IOERR_TRUNCATE => "Error attempting to truncate file", 196 | super::SQLITE_IOERR_FSTAT => "Error invoking fstat to get file metadata", 197 | super::SQLITE_IOERR_UNLOCK => "I/O error within xUnlock of a VFS object", 198 | super::SQLITE_IOERR_RDLOCK => "I/O error within xLock of a VFS object (trying to obtain a read lock)", 199 | super::SQLITE_IOERR_DELETE => "I/O error within xDelete of a VFS object", 200 | super::SQLITE_IOERR_BLOCKED => "SQLITE_IOERR_BLOCKED", // no longer used 201 | super::SQLITE_IOERR_NOMEM => "Out of memory in I/O layer", 202 | super::SQLITE_IOERR_ACCESS => "I/O error within xAccess of a VFS object", 203 | super::SQLITE_IOERR_CHECKRESERVEDLOCK => "I/O error within then xCheckReservedLock method", 204 | super::SQLITE_IOERR_LOCK => "I/O error in the advisory file locking layer", 205 | super::SQLITE_IOERR_CLOSE => "I/O error within the xClose method", 206 | super::SQLITE_IOERR_DIR_CLOSE => "SQLITE_IOERR_DIR_CLOSE", // no longer used 207 | super::SQLITE_IOERR_SHMOPEN => "I/O error within the xShmMap method (trying to open a new shared-memory segment)", 208 | super::SQLITE_IOERR_SHMSIZE => "I/O error within the xShmMap method (trying to resize an existing shared-memory segment)", 209 | super::SQLITE_IOERR_SHMLOCK => "SQLITE_IOERR_SHMLOCK", // no longer used 210 | super::SQLITE_IOERR_SHMMAP => "I/O error within the xShmMap method (trying to map a shared-memory segment into process address space)", 211 | super::SQLITE_IOERR_SEEK => "I/O error within the xRead or xWrite (trying to seek within a file)", 212 | super::SQLITE_IOERR_DELETE_NOENT => "File being deleted does not exist", 213 | super::SQLITE_IOERR_MMAP => "I/O error while trying to map or unmap part of the database file into process address space", 214 | super::SQLITE_IOERR_GETTEMPPATH => "VFS is unable to determine a suitable directory for temporary files", 215 | super::SQLITE_IOERR_CONVPATH => "cygwin_conv_path() system call failed", 216 | super::SQLITE_IOERR_VNODE => "SQLITE_IOERR_VNODE", // not documented? 217 | super::SQLITE_IOERR_AUTH => "SQLITE_IOERR_AUTH", 218 | SQLITE_IOERR_BEGIN_ATOMIC => "SQLITE_IOERR_BEGIN_ATOMIC", 219 | SQLITE_IOERR_COMMIT_ATOMIC => "SQLITE_IOERR_COMMIT_ATOMIC", 220 | SQLITE_IOERR_ROLLBACK_ATOMIC => "SQLITE_IOERR_ROLLBACK_ATOMIC", 221 | SQLITE_IOERR_DATA => "SQLITE_IOERR_DATA", 222 | 223 | super::SQLITE_LOCKED_SHAREDCACHE => "Locking conflict due to another connection with a shared cache", 224 | SQLITE_LOCKED_VTAB => "SQLITE_LOCKED_VTAB", 225 | 226 | super::SQLITE_BUSY_RECOVERY => "Another process is recovering a WAL mode database file", 227 | super::SQLITE_BUSY_SNAPSHOT => "Cannot promote read transaction to write transaction because of writes by another connection", 228 | SQLITE_BUSY_TIMEOUT => "SQLITE_BUSY_TIMEOUT", 229 | 230 | super::SQLITE_CANTOPEN_NOTEMPDIR => "SQLITE_CANTOPEN_NOTEMPDIR", // no longer used 231 | super::SQLITE_CANTOPEN_ISDIR => "Attempted to open directory as file", 232 | super::SQLITE_CANTOPEN_FULLPATH => "Unable to convert filename into full pathname", 233 | super::SQLITE_CANTOPEN_CONVPATH => "cygwin_conv_path() system call failed", 234 | SQLITE_CANTOPEN_SYMLINK => "SQLITE_CANTOPEN_SYMLINK", 235 | 236 | super::SQLITE_CORRUPT_VTAB => "Content in the virtual table is corrupt", 237 | SQLITE_CORRUPT_SEQUENCE => "SQLITE_CORRUPT_SEQUENCE", 238 | SQLITE_CORRUPT_INDEX => "SQLITE_CORRUPT_INDEX", 239 | 240 | super::SQLITE_READONLY_RECOVERY => "WAL mode database file needs recovery (requires write access)", 241 | super::SQLITE_READONLY_CANTLOCK => "Shared-memory file associated with WAL mode database is read-only", 242 | super::SQLITE_READONLY_ROLLBACK => "Database has hot journal that must be rolled back (requires write access)", 243 | super::SQLITE_READONLY_DBMOVED => "Database cannot be modified because database file has moved", 244 | SQLITE_READONLY_CANTINIT => "SQLITE_READONLY_CANTINIT", 245 | SQLITE_READONLY_DIRECTORY => "SQLITE_READONLY_DIRECTORY", 246 | 247 | super::SQLITE_ABORT_ROLLBACK => "Transaction was rolled back", 248 | 249 | super::SQLITE_CONSTRAINT_CHECK => "A CHECK constraint failed", 250 | super::SQLITE_CONSTRAINT_COMMITHOOK => "Commit hook caused rollback", 251 | super::SQLITE_CONSTRAINT_FOREIGNKEY => "Foreign key constraint failed", 252 | super::SQLITE_CONSTRAINT_FUNCTION => "Error returned from extension function", 253 | super::SQLITE_CONSTRAINT_NOTNULL => "A NOT NULL constraint failed", 254 | super::SQLITE_CONSTRAINT_PRIMARYKEY => "A PRIMARY KEY constraint failed", 255 | super::SQLITE_CONSTRAINT_TRIGGER => "A RAISE function within a trigger fired", 256 | super::SQLITE_CONSTRAINT_UNIQUE => "A UNIQUE constraint failed", 257 | super::SQLITE_CONSTRAINT_VTAB => "An application-defined virtual table error occurred", 258 | super::SQLITE_CONSTRAINT_ROWID => "A non-unique rowid occurred", 259 | SQLITE_CONSTRAINT_PINNED => "SQLITE_CONSTRAINT_PINNED", 260 | SQLITE_CONSTRAINT_DATATYPE => "SQLITE_CONSTRAINT_DATATYPE", 261 | 262 | super::SQLITE_NOTICE_RECOVER_WAL => "A WAL mode database file was recovered", 263 | super::SQLITE_NOTICE_RECOVER_ROLLBACK => "Hot journal was rolled back", 264 | 265 | super::SQLITE_WARNING_AUTOINDEX => "Automatic indexing used - database might benefit from additional indexes", 266 | 267 | super::SQLITE_AUTH_USER => "SQLITE_AUTH_USER", // not documented? 268 | 269 | _ => "Unknown error code", 270 | } 271 | } 272 | -------------------------------------------------------------------------------- /libsqlite3-sys/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_snake_case, non_camel_case_types)] 2 | #![cfg_attr(test, allow(deref_nullptr))] // https://github.com/rust-lang/rust-bindgen/issues/2066 3 | 4 | #[cfg(all(target_arch = "wasm32", target_os = "unknown"))] 5 | mod wasm32_unknown_unknown; 6 | 7 | // force linking to openssl 8 | #[cfg(feature = "bundled-sqlcipher-vendored-openssl")] 9 | extern crate openssl_sys; 10 | 11 | #[cfg(all(windows, feature = "winsqlite3", target_pointer_width = "32"))] 12 | compile_error!("The `libsqlite3-sys/winsqlite3` feature is not supported on 32 bit targets."); 13 | 14 | pub use self::error::*; 15 | 16 | use std::default::Default; 17 | use std::mem; 18 | 19 | mod error; 20 | 21 | #[must_use] 22 | pub fn SQLITE_STATIC() -> sqlite3_destructor_type { 23 | None 24 | } 25 | 26 | #[must_use] 27 | pub fn SQLITE_TRANSIENT() -> sqlite3_destructor_type { 28 | Some(unsafe { mem::transmute(-1_isize) }) 29 | } 30 | 31 | #[allow(clippy::all)] 32 | mod bindings { 33 | include!(concat!(env!("OUT_DIR"), "/bindgen.rs")); 34 | } 35 | pub use bindings::*; 36 | 37 | impl Default for sqlite3_vtab { 38 | fn default() -> Self { 39 | unsafe { mem::zeroed() } 40 | } 41 | } 42 | 43 | impl Default for sqlite3_vtab_cursor { 44 | fn default() -> Self { 45 | unsafe { mem::zeroed() } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /libsqlite3-sys/src/wasm32_unknown_unknown.rs: -------------------------------------------------------------------------------- 1 | #[cfg(not(feature = "bundled"))] 2 | compile_error!("wasm32-unknown-unknown must be built with '--features bundled'"); 3 | 4 | use crate::{sqlite3_file, sqlite3_vfs, sqlite3_vfs_register, SQLITE_IOERR, SQLITE_OK}; 5 | use std::os::raw::{c_char, c_int, c_void}; 6 | use std::ptr::null_mut; 7 | 8 | #[no_mangle] 9 | pub unsafe extern "C" fn sqlite3_os_init() -> c_int { 10 | let vfs = sqlite3_vfs { 11 | iVersion: 1, 12 | szOsFile: 0, 13 | mxPathname: 1024, 14 | pNext: null_mut(), 15 | zName: "libsqlite3-sys\0".as_ptr() as *const c_char, 16 | pAppData: null_mut(), 17 | xOpen: Some(wasm_vfs_open), 18 | xDelete: Some(wasm_vfs_delete), 19 | xAccess: Some(wasm_vfs_access), 20 | xFullPathname: Some(wasm_vfs_fullpathname), 21 | xDlOpen: Some(wasm_vfs_dlopen), 22 | xDlError: Some(wasm_vfs_dlerror), 23 | xDlSym: Some(wasm_vfs_dlsym), 24 | xDlClose: Some(wasm_vfs_dlclose), 25 | xRandomness: Some(wasm_vfs_randomness), 26 | xSleep: Some(wasm_vfs_sleep), 27 | xCurrentTime: Some(wasm_vfs_currenttime), 28 | xGetLastError: None, 29 | xCurrentTimeInt64: None, 30 | xSetSystemCall: None, 31 | xGetSystemCall: None, 32 | xNextSystemCall: None, 33 | }; 34 | 35 | sqlite3_vfs_register(Box::leak(Box::new(vfs)), 1) 36 | } 37 | 38 | const fn max(a: usize, b: usize) -> usize { 39 | [a, b][(a < b) as usize] 40 | } 41 | 42 | const ALIGN: usize = max( 43 | 8, // wasm32 max_align_t 44 | max(std::mem::size_of::(), std::mem::align_of::()), 45 | ); 46 | 47 | #[no_mangle] 48 | pub unsafe extern "C" fn malloc(size: usize) -> *mut u8 { 49 | let layout = match std::alloc::Layout::from_size_align(size + ALIGN, ALIGN) { 50 | Ok(layout) => layout, 51 | Err(_) => return null_mut(), 52 | }; 53 | 54 | let ptr = std::alloc::alloc(layout); 55 | if ptr.is_null() { 56 | return null_mut(); 57 | } 58 | 59 | *(ptr as *mut usize) = size; 60 | ptr.offset(ALIGN as isize) 61 | } 62 | 63 | #[no_mangle] 64 | pub unsafe extern "C" fn free(ptr: *mut u8) { 65 | let ptr = ptr.offset(-(ALIGN as isize)); 66 | let size = *(ptr as *mut usize); 67 | let layout = std::alloc::Layout::from_size_align_unchecked(size + ALIGN, ALIGN); 68 | 69 | std::alloc::dealloc(ptr, layout); 70 | } 71 | 72 | #[no_mangle] 73 | pub unsafe extern "C" fn realloc(ptr: *mut u8, new_size: usize) -> *mut u8 { 74 | let ptr = ptr.offset(-(ALIGN as isize)); 75 | let size = *(ptr as *mut usize); 76 | let layout = std::alloc::Layout::from_size_align_unchecked(size + ALIGN, ALIGN); 77 | 78 | let ptr = std::alloc::realloc(ptr, layout, new_size + ALIGN); 79 | if ptr.is_null() { 80 | return null_mut(); 81 | } 82 | 83 | *(ptr as *mut usize) = new_size; 84 | ptr.offset(ALIGN as isize) 85 | } 86 | 87 | #[no_mangle] 88 | pub unsafe extern "C" fn wasm_vfs_open( 89 | _arg1: *mut sqlite3_vfs, 90 | _zName: *const c_char, 91 | _arg2: *mut sqlite3_file, 92 | _flags: c_int, 93 | _pOutFlags: *mut c_int, 94 | ) -> c_int { 95 | SQLITE_IOERR 96 | } 97 | 98 | #[no_mangle] 99 | pub unsafe extern "C" fn wasm_vfs_delete( 100 | _arg1: *mut sqlite3_vfs, 101 | _zName: *const c_char, 102 | _syncDir: c_int, 103 | ) -> c_int { 104 | SQLITE_IOERR 105 | } 106 | 107 | #[no_mangle] 108 | pub unsafe extern "C" fn wasm_vfs_access( 109 | _arg1: *mut sqlite3_vfs, 110 | _zName: *const c_char, 111 | _flags: c_int, 112 | _pResOut: *mut c_int, 113 | ) -> c_int { 114 | SQLITE_IOERR 115 | } 116 | 117 | #[no_mangle] 118 | pub unsafe extern "C" fn wasm_vfs_fullpathname( 119 | _arg1: *mut sqlite3_vfs, 120 | _zName: *const c_char, 121 | _nOut: c_int, 122 | _zOut: *mut c_char, 123 | ) -> c_int { 124 | SQLITE_IOERR 125 | } 126 | 127 | #[no_mangle] 128 | pub unsafe extern "C" fn wasm_vfs_dlopen( 129 | _arg1: *mut sqlite3_vfs, 130 | _zFilename: *const c_char, 131 | ) -> *mut c_void { 132 | null_mut() 133 | } 134 | 135 | #[no_mangle] 136 | pub unsafe extern "C" fn wasm_vfs_dlerror( 137 | _arg1: *mut sqlite3_vfs, 138 | _nByte: c_int, 139 | _zErrMsg: *mut c_char, 140 | ) { 141 | // no-op 142 | } 143 | 144 | #[no_mangle] 145 | pub unsafe extern "C" fn wasm_vfs_dlsym( 146 | _arg1: *mut sqlite3_vfs, 147 | _arg2: *mut c_void, 148 | _zSymbol: *const c_char, 149 | ) -> ::std::option::Option { 150 | None 151 | } 152 | 153 | #[no_mangle] 154 | pub unsafe extern "C" fn wasm_vfs_dlclose(_arg1: *mut sqlite3_vfs, _arg2: *mut c_void) { 155 | // no-op 156 | } 157 | 158 | #[no_mangle] 159 | pub unsafe extern "C" fn wasm_vfs_sleep(_arg1: *mut sqlite3_vfs, microseconds: c_int) -> c_int { 160 | let target_date = js_sys::Date::now() + (microseconds as f64 / 1000.0); 161 | while js_sys::Date::now() < target_date {} 162 | SQLITE_OK 163 | } 164 | 165 | #[no_mangle] 166 | pub unsafe extern "C" fn wasm_vfs_randomness( 167 | _arg1: *mut sqlite3_vfs, 168 | nByte: c_int, 169 | zByte: *mut c_char, 170 | ) -> c_int { 171 | let slice = std::slice::from_raw_parts_mut(zByte as *mut u8, nByte as usize); 172 | getrandom::getrandom(slice).unwrap_or_else(|_| std::process::abort()); 173 | SQLITE_OK 174 | } 175 | 176 | #[no_mangle] 177 | pub unsafe extern "C" fn wasm_vfs_currenttime(_arg1: *mut sqlite3_vfs, pTime: *mut f64) -> c_int { 178 | // https://en.wikipedia.org/wiki/Julian_day 179 | *pTime = (js_sys::Date::now() / 86400000.0) + 2440587.5; 180 | SQLITE_OK 181 | } 182 | -------------------------------------------------------------------------------- /libsqlite3-sys/upgrade.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | 3 | SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) 4 | echo "$SCRIPT_DIR" 5 | cd "$SCRIPT_DIR" || { echo "fatal error" >&2; exit 1; } 6 | cargo clean 7 | mkdir -p "$SCRIPT_DIR/../target" "$SCRIPT_DIR/sqlite3" 8 | export SQLITE3_LIB_DIR="$SCRIPT_DIR/sqlite3" 9 | export SQLITE3_INCLUDE_DIR="$SQLITE3_LIB_DIR" 10 | 11 | # Download and extract amalgamation 12 | SQLITE=sqlite-amalgamation-3420000 13 | curl -O https://sqlite.org/2023/$SQLITE.zip 14 | unzip -p "$SQLITE.zip" "$SQLITE/sqlite3.c" > "$SQLITE3_LIB_DIR/sqlite3.c" 15 | unzip -p "$SQLITE.zip" "$SQLITE/sqlite3.h" > "$SQLITE3_LIB_DIR/sqlite3.h" 16 | unzip -p "$SQLITE.zip" "$SQLITE/sqlite3ext.h" > "$SQLITE3_LIB_DIR/sqlite3ext.h" 17 | rm -f "$SQLITE.zip" 18 | 19 | # Regenerate bindgen file for sqlite3 20 | rm -f "$SQLITE3_LIB_DIR/bindgen_bundled_version.rs" 21 | cargo update 22 | # Just to make sure there is only one bindgen.rs file in target dir 23 | find "$SCRIPT_DIR/../target" -type f -name bindgen.rs -exec rm {} \; 24 | env LIBSQLITE3_SYS_BUNDLING=1 cargo build --features "buildtime_bindgen session" --no-default-features 25 | find "$SCRIPT_DIR/../target" -type f -name bindgen.rs -exec mv {} "$SQLITE3_LIB_DIR/bindgen_bundled_version.rs" \; 26 | 27 | # Sanity checks 28 | cd "$SCRIPT_DIR/.." || { echo "fatal error" >&2; exit 1; } 29 | cargo update 30 | cargo test --features "backup blob chrono functions limits load_extension serde_json trace vtab bundled" 31 | printf ' \e[35;1mFinished\e[0m bundled sqlite3 tests\n' 32 | -------------------------------------------------------------------------------- /libsqlite3-sys/upgrade_sqlcipher.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | 3 | SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) 4 | echo "$SCRIPT_DIR" 5 | cd "$SCRIPT_DIR" || { echo "fatal error" >&2; exit 1; } 6 | cargo clean 7 | mkdir -p "$SCRIPT_DIR/../target" "$SCRIPT_DIR/sqlcipher" 8 | export SQLCIPHER_LIB_DIR="$SCRIPT_DIR/sqlcipher" 9 | export SQLCIPHER_INCLUDE_DIR="$SQLCIPHER_LIB_DIR" 10 | 11 | SQLCIPHER_VERSION="4.5.3" 12 | # Download and generate sqlcipher amalgamation 13 | mkdir -p $SCRIPT_DIR/sqlcipher.src 14 | [ -e "v${SQLCIPHER_VERSION}.tar.gz" ] || curl -sfL -O "https://github.com/sqlcipher/sqlcipher/archive/v${SQLCIPHER_VERSION}.tar.gz" 15 | tar xzf "v${SQLCIPHER_VERSION}.tar.gz" --strip-components=1 -C "$SCRIPT_DIR/sqlcipher.src" 16 | cd "$SCRIPT_DIR/sqlcipher.src" 17 | ./configure --with-crypto-lib=none 18 | make sqlite3.c 19 | cp sqlite3.c sqlite3.h sqlite3ext.h "$SCRIPT_DIR/sqlcipher/" 20 | cd "$SCRIPT_DIR" 21 | rm -rf "v${SQLCIPHER_VERSION}.tar.gz" sqlcipher.src 22 | 23 | # Regenerate bindgen file for sqlcipher 24 | rm -f "$SQLCIPHER_LIB_DIR/bindgen_bundled_version.rs" 25 | 26 | # cargo update 27 | find "$SCRIPT_DIR/../target" -type f -name bindgen.rs -exec rm {} \; 28 | env LIBSQLITE3_SYS_BUNDLING=1 cargo build --features "sqlcipher buildtime_bindgen session" 29 | find "$SCRIPT_DIR/../target" -type f -name bindgen.rs -exec mv {} "$SQLCIPHER_LIB_DIR/bindgen_bundled_version.rs" \; 30 | 31 | # Sanity checks 32 | cd "$SCRIPT_DIR/.." || { echo "fatal error" >&2; exit 1; } 33 | cargo update 34 | cargo test --features "backup blob chrono functions limits load_extension serde_json trace vtab bundled-sqlcipher-vendored-openssl" 35 | printf ' \e[35;1mFinished\e[0m bundled-sqlcipher-vendored-openssl/sqlcipher tests\n' 36 | -------------------------------------------------------------------------------- /libsqlite3-sys/wrapper.h: -------------------------------------------------------------------------------- 1 | #ifdef BINDGEN_USE_WINSQLITE3 2 | #include 3 | #else 4 | #include "sqlite3.h" 5 | #endif 6 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/logseq/sqlite-db/6ece3d7c70d6bb6ba6d049a4942646dc3860b1f8/rustfmt.toml -------------------------------------------------------------------------------- /scripts/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -ex 4 | set -o pipefail 5 | 6 | wasm-pack build --target web --release 7 | 8 | # Convert package.json name to scopled 9 | 10 | sed -i '' 's/"name": "logseq-sqlite",/"name": "@logseq\/sqlite",/g' pkg/package.json 11 | 12 | 13 | # Convert import.meta.url to location.origin 14 | 15 | sed -i '' 's/import.meta.url/location.origin/g' pkg/logseq_sqlite.js 16 | 17 | 18 | echo ".wasm file should be copied too!!!" 19 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | cell::RefCell, 3 | collections::HashMap, 4 | sync::{atomic::AtomicBool, Mutex}, 5 | }; 6 | 7 | use once_cell::sync::Lazy; 8 | use rusqlite::{named_params, params}; 9 | use serde::{Deserialize, Serialize}; 10 | use wasm_bindgen::prelude::*; 11 | 12 | pub use self::sqlite_opfs::{get_version, has_opfs_support}; 13 | 14 | mod sqlite_opfs; 15 | 16 | static INITED: AtomicBool = AtomicBool::new(false); 17 | 18 | #[wasm_bindgen] 19 | extern "C" { 20 | #[wasm_bindgen(js_namespace = console)] 21 | pub fn log(s: &str); 22 | } 23 | 24 | #[macro_export] 25 | macro_rules! console_log { 26 | ($($arg:tt)*) => {{ 27 | $crate::log(&std::format!("{}:{} {}", file!(), line!(), std::format!($($arg)*))); 28 | }}; 29 | } 30 | 31 | /// Init sqlite binding, preload file sync access handles 32 | /// This should be the only async fn 33 | #[wasm_bindgen] 34 | pub async fn ensure_init() -> Result<(), JsValue> { 35 | // avoid reentrant 36 | if INITED.load(std::sync::atomic::Ordering::Relaxed) { 37 | return Ok(()); 38 | } 39 | 40 | console_log!( 41 | "[logseq-db] init {} {}", 42 | env!("CARGO_PKG_NAME"), 43 | env!("CARGO_PKG_VERSION") 44 | ); 45 | 46 | // When the `console_error_panic_hook` feature is enabled, we can call the 47 | // `set_panic_hook` function at least once during initialization, and then 48 | // we will get better error messages if our code ever panics. 49 | // 50 | // For more details see 51 | // https://github.com/rustwasm/console_error_panic_hook#readme 52 | #[cfg(feature = "console_error_panic_hook")] 53 | console_error_panic_hook::set_once(); 54 | 55 | // init VFS backend for SQLite 56 | sqlite_opfs::init_sqlite_vfs() 57 | .await 58 | .map_err(|e| JsValue::from_str(&format!("Failed to init sqlite vfs: {:?}", e)))?; 59 | 60 | INITED.store(true, std::sync::atomic::Ordering::Relaxed); 61 | 62 | Ok(()) 63 | } 64 | 65 | /// DB pool 66 | static CONNS: Lazy>>> = 67 | Lazy::new(|| Mutex::new(HashMap::new())); 68 | 69 | static CURRENT_GRAPH: Lazy> = Lazy::new(|| Mutex::new("".to_string())); 70 | 71 | /// Dev only, close all files 72 | #[wasm_bindgen] 73 | pub async fn dev_close() { 74 | // close all db connections, using drop 75 | CONNS.lock().unwrap().clear(); 76 | 77 | unsafe { 78 | sqlite_opfs::POOL.close_all(); 79 | } 80 | } 81 | 82 | #[derive(Serialize, Deserialize, Debug)] 83 | pub struct Block { 84 | uuid: String, 85 | #[serde(rename = "type")] 86 | block_type: i32, 87 | page_uuid: String, 88 | page_journal_day: Option, 89 | name: Option, // schema/version 90 | content: Option, 91 | datoms: String, 92 | created_at: i64, 93 | updated_at: i64, 94 | } 95 | 96 | #[derive(Serialize, Deserialize, Debug)] 97 | pub struct AddrContent { 98 | addr: i64, 99 | content: String, 100 | } 101 | 102 | #[wasm_bindgen] 103 | pub async fn init_db(db: &str) -> Result<(), JsValue> { 104 | console_log!("init_db {}", db); 105 | // if already opened, skip 106 | let mut conns = CONNS.lock().unwrap(); 107 | if conns.contains_key(db) { 108 | return Ok(()); 109 | } 110 | 111 | unsafe { 112 | conns.clear(); // close all db connections, using drop 113 | sqlite_opfs::POOL.deinit(); 114 | sqlite_opfs::POOL.init(db).await?; 115 | 116 | // set current graph 117 | *CURRENT_GRAPH.lock().unwrap() = db.to_string(); 118 | } 119 | 120 | drop(conns); 121 | 122 | new_db(db)?; 123 | 124 | Ok(()) 125 | } 126 | 127 | #[wasm_bindgen] 128 | pub fn open_db(db: &str) -> Result<(), JsValue> { 129 | // if already opened, skip 130 | if CONNS.lock().unwrap().contains_key(db) { 131 | return Ok(()); 132 | } 133 | 134 | new_db(db)?; 135 | 136 | Ok(()) 137 | } 138 | 139 | #[wasm_bindgen] 140 | pub async fn list_db() -> Result { 141 | let ret = unsafe { sqlite_opfs::POOL.list_db().await? }; 142 | // convert Vec to JsValue 143 | let ret = serde_wasm_bindgen::to_value(&ret).unwrap(); 144 | Ok(ret) 145 | } 146 | 147 | #[wasm_bindgen] 148 | pub fn new_db(db: &str) -> Result<(), JsValue> { 149 | console_log!("new_db {}", db); 150 | // if already opened, skip 151 | if CONNS.lock().unwrap().contains_key(db) { 152 | return Ok(()); 153 | } 154 | 155 | // check current graph 156 | if *CURRENT_GRAPH.lock().unwrap() != db { 157 | return Err(JsValue::from_str(&format!("Current graph is not inited yet: {}", db))); 158 | } 159 | 160 | let conn = rusqlite::Connection::open(db).unwrap(); 161 | 162 | let sql = r#" 163 | CREATE TABLE IF NOT EXISTS blocks ( 164 | uuid TEXT PRIMARY KEY NOT NULL, 165 | type INTEGER NOT NULL, 166 | page_uuid TEXT, 167 | page_journal_day INTEGER, 168 | name TEXT UNIQUE, 169 | content TEXT, 170 | datoms TEXT, 171 | created_at INTEGER NOT NULL, 172 | updated_at INTEGER NOT NULL 173 | )"#; 174 | conn.execute(sql, params![]).unwrap(); 175 | 176 | let sql = "CREATE INDEX IF NOT EXISTS block_type ON blocks(type)"; 177 | conn.execute(sql, params![]).unwrap(); 178 | 179 | let sql = "CREATE TABLE IF NOT EXISTS kvs (addr INTEGER PRIMARY KEY, content TEXT)"; 180 | conn.execute(sql, params![]).unwrap(); 181 | 182 | CONNS 183 | .lock() 184 | .unwrap() 185 | .insert(db.to_string(), RefCell::new(conn)); 186 | 187 | Ok(()) 188 | } 189 | 190 | #[wasm_bindgen] 191 | pub fn unsafe_unlink_db(db: &str) -> Result<(), JsValue> { 192 | console_log!("unsafe_unlink_db {}", db); 193 | if !CONNS.lock().unwrap().contains_key(db) { 194 | return Ok(()); 195 | } 196 | 197 | let mut conns = CONNS.lock().unwrap(); 198 | let conn = conns.remove(db).unwrap().into_inner(); 199 | 200 | let sql = "DROP TABLE IF EXISTS blocks"; 201 | conn.execute(sql, params![]).unwrap(); 202 | 203 | conn.close().unwrap(); 204 | 205 | unsafe { 206 | sqlite_opfs::POOL.delete(db)?; 207 | } 208 | 209 | Ok(()) 210 | } 211 | 212 | #[wasm_bindgen] 213 | pub fn delete_blocks(db: &str, uuids: Vec) -> Result<(), JsValue> { 214 | console_log!("delete_blocks: {:?}", uuids); 215 | open_db(db)?; 216 | 217 | let conns = CONNS.lock().unwrap(); 218 | let conn = conns.get(db).unwrap().borrow(); 219 | 220 | let sql = "DELETE FROM blocks WHERE uuid = ?"; 221 | for uuid in uuids { 222 | conn.execute(sql, params![uuid]).unwrap(); 223 | } 224 | 225 | Ok(()) 226 | } 227 | 228 | #[wasm_bindgen] 229 | pub fn upsert_addr_content(db: &str, data: JsValue) -> Result<(), JsValue> { 230 | console_log!("upsert_addr_content {}", db); 231 | open_db(db)?; 232 | let conns = CONNS.lock().unwrap(); 233 | let mut conn = conns.get(db).unwrap().borrow_mut(); 234 | 235 | let tx = conn 236 | .transaction() 237 | .map_err(|e| JsValue::from_str(&format!("upsert_addr_content: {:?}", e)))?; 238 | 239 | let sql = r#"INSERT INTO kvs (addr, content) values (@addr, @content) on conflict(addr) do update set content = @content"#; 240 | 241 | let payload: Vec = 242 | serde_wasm_bindgen::from_value(data).map_err(|e| { 243 | JsValue::from_str(&format!( 244 | "Failed to deserialize AddrContent from JsValue: {:?}", 245 | e 246 | )) 247 | })?; // Vec 248 | 249 | for item in payload { 250 | tx.execute( 251 | sql, 252 | named_params! { 253 | "@addr": item.addr, 254 | "@content": item.content, 255 | }, 256 | ) 257 | .map_err(|e| JsValue::from_str(&format!("execute: {:?}", e)))?; 258 | } 259 | 260 | tx.commit() 261 | .map_err(|e| JsValue::from_str(&format!("commit: {:?}", e)))?; 262 | 263 | Ok(()) 264 | } 265 | 266 | #[wasm_bindgen] 267 | pub fn get_content_by_addr(db: &str, addr: JsValue) -> Result { 268 | open_db(db)?; 269 | let conns = CONNS.lock().unwrap(); 270 | let conn = conns.get(db).unwrap().borrow(); 271 | 272 | let addr = addr.as_f64().unwrap() as i64; 273 | console_log!("get_content_by_addr {} {:?}", db, addr); 274 | 275 | let mut stmt = conn 276 | .prepare("SELECT content FROM kvs WHERE addr = ?") 277 | .unwrap(); 278 | let mut rows = stmt.query(params![addr]).unwrap(); 279 | 280 | if let Ok(Some(row)) = rows.next() { 281 | if let Ok(content) = row.get::<_, String>(0) { 282 | return Ok(JsValue::from_str(&content)); 283 | } 284 | } 285 | 286 | Ok(JsValue::null()) 287 | } 288 | 289 | #[wasm_bindgen] 290 | pub fn upsert_blocks(db: &str, blocks: JsValue) -> Result<(), JsValue> { 291 | open_db(db)?; 292 | let conns = CONNS.lock().unwrap(); 293 | let mut conn = conns.get(db).unwrap().borrow_mut(); 294 | 295 | let tx = conn.transaction().unwrap(); 296 | 297 | let sql = r#" 298 | INSERT INTO blocks (uuid, type, page_uuid, page_journal_day, name, content,datoms, created_at, updated_at) 299 | VALUES (@uuid, @type, @page_uuid, @page_journal_day, @name, @content, @datoms, @created_at, @updated_at) 300 | ON CONFLICT (uuid) 301 | DO UPDATE 302 | SET (type, page_uuid, page_journal_day, name, content, datoms, created_at, updated_at) 303 | = (@type, @page_uuid, @page_journal_day, @name, @content, @datoms, @created_at, @updated_at) 304 | "#; 305 | 306 | let blocks: Vec = serde_wasm_bindgen::from_value(blocks).unwrap(); 307 | for block in blocks { 308 | tx.execute( 309 | sql, 310 | named_params! { 311 | "@uuid": block.uuid, 312 | "@type": block.block_type, 313 | "@page_uuid": block.page_uuid, 314 | "@page_journal_day": block.page_journal_day, 315 | "@name": block.name, 316 | "@content": block.content, 317 | "@datoms": block.datoms, 318 | "@created_at": block.created_at, 319 | "@updated_at": block.updated_at, 320 | }, 321 | ) 322 | .unwrap(); 323 | } 324 | 325 | tx.commit().unwrap(); 326 | 327 | Ok(()) 328 | } 329 | 330 | #[wasm_bindgen] 331 | pub fn fetch_all_pages(db: &str) -> Result { 332 | console_log!("fetch_all_pages {}", db); 333 | open_db(db)?; 334 | 335 | let conns = CONNS.lock().unwrap(); 336 | let conn = conns.get(db).unwrap().borrow(); 337 | 338 | let mut stmt = conn.prepare("SELECT * FROM blocks WHERE type = 2").unwrap(); 339 | let pages_iter = stmt 340 | .query_map(params![], |row| { 341 | Ok(Block { 342 | uuid: row.get(0)?, 343 | block_type: row.get(1)?, 344 | page_uuid: row.get(2)?, 345 | page_journal_day: row.get(3)?, 346 | name: row.get(4)?, 347 | content: row.get(5)?, 348 | datoms: row.get(6)?, 349 | created_at: row.get(7)?, 350 | updated_at: row.get(8)?, 351 | }) 352 | }) 353 | .unwrap(); 354 | 355 | let mut pages = Vec::new(); 356 | for page in pages_iter { 357 | pages.push(page.map_err(|e| JsValue::from_str(&format!("{:?}", e)))?); 358 | } 359 | 360 | Ok(serde_wasm_bindgen::to_value(&pages).unwrap()) 361 | } 362 | 363 | #[derive(Serialize, Deserialize, Debug)] 364 | pub struct BlockInfo { 365 | uuid: String, 366 | page_uuid: String, 367 | } 368 | 369 | /// Fetch all blocks and its page uuid 370 | /// => [{uuid: string, page_uuid: string}] 371 | #[wasm_bindgen] 372 | pub fn fetch_all_blocks(db: &str) -> Result { 373 | open_db(db)?; 374 | 375 | let conns = CONNS.lock().unwrap(); 376 | let conn = conns.get(db).unwrap().borrow(); 377 | 378 | let mut stmt = conn 379 | .prepare("SELECT uuid, page_uuid FROM blocks WHERE type = 1") 380 | .unwrap(); 381 | let blocks_iter = stmt 382 | .query_map(params![], |row| { 383 | Ok(BlockInfo { 384 | uuid: row.get(0)?, 385 | page_uuid: row.get(1)?, 386 | }) 387 | }) 388 | .unwrap(); 389 | 390 | let mut blocks = Vec::new(); 391 | for block in blocks_iter { 392 | blocks.push(block.unwrap()); 393 | } 394 | 395 | Ok(serde_wasm_bindgen::to_value(&blocks).unwrap()) 396 | } 397 | 398 | #[wasm_bindgen] 399 | pub fn fetch_recent_journals(db: &str) -> Result { 400 | open_db(db)?; 401 | 402 | let conns = CONNS.lock().unwrap(); 403 | let conn = conns.get(db).unwrap().borrow(); 404 | 405 | let mut stmt = conn 406 | .prepare("SELECT uuid FROM blocks WHERE type = 2 ORDER BY page_journal_day DESC LIMIT 3") 407 | .unwrap(); 408 | let mut uuids: Vec = vec![]; 409 | let rows = stmt.query_map(params![], |row| row.get(0)).unwrap(); 410 | 411 | for row in rows { 412 | uuids.push(row.unwrap()); 413 | } 414 | 415 | let mut sql = "SELECT * FROM blocks WHERE type = 1 AND page_uuid IN (".to_string(); 416 | for (i, uuid) in uuids.iter().enumerate() { 417 | if i > 0 { 418 | sql.push_str(", "); 419 | } 420 | sql.push_str("'"); 421 | sql.push_str(uuid); 422 | sql.push_str("'"); 423 | } 424 | sql.push_str(")"); 425 | 426 | let mut stmt = conn.prepare(&sql).unwrap(); 427 | let pages_iter = stmt 428 | .query_map(params![], |row| { 429 | Ok(Block { 430 | uuid: row.get(0)?, 431 | block_type: row.get(1)?, 432 | page_uuid: row.get(2)?, 433 | page_journal_day: row.get(3)?, 434 | name: row.get(4)?, 435 | content: row.get(5)?, 436 | datoms: row.get(6)?, 437 | created_at: row.get(7)?, 438 | updated_at: row.get(8)?, 439 | }) 440 | }) 441 | .unwrap(); 442 | 443 | let mut pages = Vec::new(); 444 | for page in pages_iter { 445 | pages.push(page.unwrap()); 446 | } 447 | 448 | Ok(serde_wasm_bindgen::to_value(&pages).unwrap()) 449 | } 450 | 451 | #[wasm_bindgen] 452 | pub fn fetch_init_data(db: &str) -> Result { 453 | open_db(db)?; 454 | 455 | let conns = CONNS.lock().unwrap(); 456 | let conn = conns.get(db).unwrap().borrow(); 457 | 458 | let mut stmt = conn 459 | .prepare("SELECT * FROM blocks WHERE type IN (3, 4, 5, 6)") 460 | .unwrap(); 461 | let blocks_iter = stmt 462 | .query_map(params![], |row| { 463 | Ok(Block { 464 | uuid: row.get(0)?, 465 | block_type: row.get(1)?, 466 | page_uuid: row.get(2)?, 467 | page_journal_day: row.get(3)?, 468 | name: row.get(4)?, 469 | content: row.get(5)?, 470 | datoms: row.get(6)?, 471 | created_at: row.get(7)?, 472 | updated_at: row.get(8)?, 473 | }) 474 | }) 475 | .unwrap(); 476 | 477 | let mut blocks = Vec::new(); 478 | for block in blocks_iter { 479 | blocks.push(block.unwrap()); 480 | } 481 | 482 | Ok(serde_wasm_bindgen::to_value(&blocks).unwrap()) 483 | } 484 | 485 | #[wasm_bindgen] 486 | pub fn fetch_blocks_excluding(db: &str, excluded_uuids: JsValue) -> Result { 487 | open_db(db)?; 488 | 489 | let conns = CONNS.lock().unwrap(); 490 | let conn = conns.get(db).unwrap().borrow(); 491 | 492 | let excluded_uuids: Vec = serde_wasm_bindgen::from_value(excluded_uuids).unwrap(); 493 | 494 | let mut sql = "SELECT * FROM blocks WHERE type = 1 AND uuid NOT IN (".to_string(); 495 | for (i, uuid) in excluded_uuids.iter().enumerate() { 496 | if i > 0 { 497 | sql.push_str(", "); 498 | } 499 | sql.push_str("'"); 500 | sql.push_str(uuid); 501 | sql.push_str("'"); 502 | } 503 | sql.push_str(")"); 504 | 505 | let mut stmt = conn.prepare(&sql).unwrap(); 506 | let blocks_iter = stmt 507 | .query_map(params![], |row| { 508 | Ok(Block { 509 | uuid: row.get(0)?, 510 | block_type: row.get(1)?, 511 | page_uuid: row.get(2)?, 512 | page_journal_day: row.get(3)?, 513 | name: row.get(4)?, 514 | content: row.get(5)?, 515 | datoms: row.get(6)?, 516 | created_at: row.get(7)?, 517 | updated_at: row.get(8)?, 518 | }) 519 | }) 520 | .unwrap(); 521 | 522 | let mut blocks = Vec::new(); 523 | for block in blocks_iter { 524 | blocks.push(block.unwrap()); 525 | } 526 | 527 | Ok(serde_wasm_bindgen::to_value(&blocks).unwrap()) 528 | } 529 | 530 | // unit test 531 | 532 | pub fn block_db_test() -> Result<(), JsValue> { 533 | let _ = new_db("my-graph").unwrap(); 534 | 535 | let dummy_blocks = vec![ 536 | Block { 537 | uuid: "1".to_string(), 538 | block_type: 1, 539 | page_uuid: "1".to_string(), 540 | page_journal_day: Some(1), 541 | name: Some("1".to_string()), 542 | content: Some("1".to_string()), 543 | datoms: "1".to_string(), 544 | created_at: 1, 545 | updated_at: 1, 546 | }, 547 | Block { 548 | uuid: "2".to_string(), 549 | block_type: 1, 550 | page_uuid: "1".to_string(), 551 | page_journal_day: Some(20011202), 552 | name: Some("2".to_string()), 553 | content: None, 554 | datoms: "2".to_string(), 555 | created_at: 2, 556 | updated_at: 2, 557 | }, 558 | Block { 559 | uuid: "3".to_string(), 560 | block_type: 1, 561 | page_uuid: "1".to_string(), 562 | page_journal_day: None, 563 | name: None, 564 | content: Some("3".to_string()), 565 | datoms: "3".to_string(), 566 | created_at: 3, 567 | updated_at: 3, 568 | }, 569 | ]; 570 | let val = serde_wasm_bindgen::to_value(&dummy_blocks).unwrap(); 571 | 572 | let _ = upsert_blocks("my-graph", val).unwrap(); 573 | 574 | let val = fetch_all_blocks("my-graph").unwrap(); 575 | let blocks: Vec = serde_wasm_bindgen::from_value(val).unwrap(); 576 | assert_eq!(blocks.len(), 3); 577 | 578 | console_log!("blocks: {:#?}", blocks); 579 | 580 | delete_blocks("my-graph", vec!["2".to_string()]).unwrap(); 581 | 582 | let val = fetch_all_blocks("my-graph").unwrap(); 583 | let blocks: Vec = serde_wasm_bindgen::from_value(val).unwrap(); 584 | assert_eq!(blocks.len(), 2); 585 | 586 | console_log!("blocks: {:#?}", blocks); 587 | 588 | Ok(()) 589 | } 590 | 591 | #[cfg(test)] 592 | pub fn rusqlite_test() -> Result<(), JsValue> { 593 | use rusqlite::Connection; 594 | 595 | #[derive(Debug)] 596 | struct Person { 597 | id: i32, 598 | name: String, 599 | data: Option>, 600 | } 601 | 602 | let conn = Connection::open("demo.db").unwrap(); 603 | conn.execute( 604 | "CREATE TABLE IF NOT EXISTS person ( 605 | id INTEGER PRIMARY KEY, 606 | name TEXT NOT NULL, 607 | data BLOB 608 | )", 609 | params![], 610 | ) 611 | .unwrap(); 612 | 613 | let me = Person { 614 | id: 1, 615 | name: "Steven".to_string(), 616 | data: None, 617 | }; 618 | 619 | let start = js_sys::Date::now(); 620 | for _ in 0..500 { 621 | conn.execute( 622 | "INSERT INTO person (name, data) VALUES (?1, ?2)", 623 | params![me.name, me.data], 624 | ) 625 | .unwrap(); 626 | } 627 | let elapsed = js_sys::Date::now() - start; 628 | console_log!("insert 500 rows: {:?}ms", elapsed); 629 | 630 | let mut stmt = conn 631 | .prepare("SELECT id, name, data FROM person limit 10") 632 | .unwrap(); 633 | let person_iter = stmt 634 | .query_map(params![], |row| { 635 | Ok(Person { 636 | id: row.get(0)?, 637 | name: row.get(1)?, 638 | data: row.get(2)?, 639 | }) 640 | }) 641 | .unwrap(); 642 | 643 | for person in person_iter { 644 | console_log!("Found person {:?}", person.unwrap()); 645 | } 646 | 647 | Ok(()) 648 | } 649 | -------------------------------------------------------------------------------- /src/sqlite_opfs.rs: -------------------------------------------------------------------------------- 1 | //! SQLite3 OPFS support 2 | //! 3 | //! Use pre-allocated files to avoid async file access. 4 | //! 5 | //! ## Files 6 | //! - logseq_metadata_*.bincode: metadata file 7 | //! - [UUID].raw: data file 8 | 9 | use core::slice; 10 | use std::{ 11 | collections::HashMap, 12 | ffi::{c_char, c_int, c_void, CStr}, 13 | mem, ptr, 14 | sync::RwLock, 15 | }; 16 | 17 | use js_sys::{Array, Function, Promise, Reflect}; 18 | use libsqlite3_sys::*; 19 | use once_cell::sync::Lazy; 20 | use serde::{Deserialize, Serialize}; 21 | use uuid::Uuid; 22 | use wasm_bindgen::prelude::*; 23 | use wasm_bindgen_futures::JsFuture; 24 | use web_sys::{ 25 | FileSystemDirectoryHandle, FileSystemFileHandle, FileSystemGetFileOptions, 26 | FileSystemReadWriteOptions, FileSystemSyncAccessHandle, 27 | }; 28 | 29 | use super::console_log; 30 | 31 | const EMPTY_FILES: usize = 6; // empty files for a single graph 32 | 33 | #[derive(Serialize, Deserialize, Debug, Clone)] 34 | pub struct GlobalMetadata { 35 | // init at library load, load all sync access handles 36 | // file_handle_pool: HashMap, 37 | // in fs metadata, path to uuid file name 38 | version: i32, 39 | #[serde(default)] 40 | empty_files: Vec, 41 | // display name to uuid file name 42 | #[serde(default)] 43 | files: HashMap, 44 | } 45 | 46 | /// File handle, inherits sqlite3_file 47 | #[repr(C)] 48 | pub struct FileHandle { 49 | _super: sqlite3_file, 50 | fname: String, 51 | flags: i32, 52 | /* 53 | #define SQLITE_LOCK_NONE 0 /* xUnlock() only */ 54 | #define SQLITE_LOCK_SHARED 1 /* xLock() or xUnlock() */ 55 | #define SQLITE_LOCK_RESERVED 2 /* xLock() only */ 56 | #define SQLITE_LOCK_PENDING 3 /* xLock() only */ 57 | #define SQLITE_LOCK_EXCLUSIVE 4 /* xLock() only */ 58 | */ 59 | lock: i32, 60 | } 61 | 62 | /// The pool 63 | pub struct Pool { 64 | meta_handle: Option, 65 | metadata: RwLock, 66 | handle_pool: RwLock>, 67 | } 68 | 69 | pub static mut POOL: Lazy = Lazy::new(|| Pool { 70 | meta_handle: None, 71 | metadata: RwLock::new(GlobalMetadata { 72 | version: 1, 73 | empty_files: Vec::new(), 74 | files: HashMap::new(), 75 | }), 76 | handle_pool: RwLock::new(HashMap::new()), 77 | }); 78 | 79 | impl Pool { 80 | pub async fn list_db(&mut self) -> Result, JsValue> { 81 | let global_this = js_sys::global().dyn_into::()?; 82 | let navigator = global_this.navigator(); 83 | let opfs_root: FileSystemDirectoryHandle = 84 | JsFuture::from(navigator.storage().get_directory()) 85 | .await? 86 | .into(); 87 | 88 | let filenames = list_all_filenames(&opfs_root).await?; 89 | console_log!("filenames {:?}", filenames); 90 | 91 | let mut ret = Vec::new(); 92 | for fname in filenames { 93 | // ref: https://www.sqlite.org/tempfiles.html 94 | if fname.starts_with("logseq_metadata_") && fname.ends_with(".bincode") { 95 | let db_name = fname 96 | .trim_start_matches("logseq_metadata_") 97 | .trim_end_matches(".bincode"); 98 | ret.push(format!("logseq_db_{}", db_name)); 99 | } 100 | } 101 | 102 | Ok(ret) 103 | } 104 | 105 | // load from metadata.json 106 | pub async fn init(&mut self, db_name: &str) -> Result<(), JsValue> { 107 | if self.meta_handle.is_some() { 108 | return Ok(()); 109 | } 110 | 111 | let global_this = js_sys::global().dyn_into::()?; 112 | let navigator = global_this.navigator(); 113 | let opfs_root: FileSystemDirectoryHandle = 114 | JsFuture::from(navigator.storage().get_directory()) 115 | .await? 116 | .into(); 117 | 118 | let metadata_filename = format!( 119 | "logseq_metadata_{}.bincode", 120 | db_name.trim_start_matches("logseq_db_") 121 | ); 122 | console_log!("metadata file: {}", metadata_filename); 123 | let metadata_file = get_file_handle_from_root(&opfs_root, &metadata_filename).await?; 124 | // save handle 125 | self.meta_handle = Some(metadata_file); 126 | 127 | let meta_size = self.meta_handle()?.get_size()? as usize; 128 | let metadata = if meta_size == 0 { 129 | // create new metadata 130 | GlobalMetadata { 131 | version: 1, 132 | empty_files: Vec::new(), 133 | files: HashMap::new(), 134 | } 135 | } else { 136 | let mut buf = vec![0; meta_size]; 137 | let _nread = self.meta_handle()?.read_with_u8_array(&mut buf[..])?; 138 | let metadata = 139 | bincode::deserialize(&buf).map_err(|e| JsValue::from_str(&e.to_string()))?; 140 | 141 | metadata 142 | }; 143 | 144 | console_log!("loading init metadata: {:#?}", metadata); 145 | 146 | for fname in metadata.files.values() { 147 | let handle = get_file_handle_from_root(&opfs_root, fname).await?; 148 | let mut pool = self.handle_pool.write().unwrap(); 149 | pool.insert(fname.clone(), handle); 150 | } 151 | for fname in &metadata.empty_files { 152 | let handle = get_file_handle_from_root(&opfs_root, fname).await?; 153 | let mut pool = self.handle_pool.write().unwrap(); 154 | pool.insert(fname.clone(), handle); 155 | } 156 | 157 | *self.metadata.write().unwrap() = metadata; 158 | 159 | // create more empty files 160 | if self.metadata.read().unwrap().empty_files.len() < EMPTY_FILES { 161 | self.init_empty_files(&opfs_root, EMPTY_FILES).await?; 162 | } 163 | self.persist_metadata()?; 164 | 165 | Ok(()) 166 | } 167 | 168 | pub fn deinit(&mut self) { 169 | if self.meta_handle.is_none() { 170 | return; 171 | } 172 | 173 | { 174 | let mut pool = self.handle_pool.write().unwrap(); 175 | for (name, handle) in pool.drain() { 176 | console_log!("closing {}", name); 177 | handle.close(); 178 | } 179 | } 180 | 181 | self.meta_handle.as_ref().unwrap().close(); 182 | self.metadata = RwLock::new(GlobalMetadata { 183 | version: 1, 184 | empty_files: Vec::new(), 185 | files: HashMap::new(), 186 | }); 187 | self.meta_handle = None; // avoid overwriting 188 | } 189 | 190 | /// Dev only. Close all files. The library will be in a unusable state. 191 | pub fn close_all(&mut self) { 192 | // close all file handles 193 | let pool = self.handle_pool.write().unwrap(); 194 | for (name, handle) in pool.iter() { 195 | console_log!("closing {}", name); 196 | handle.close(); 197 | } 198 | 199 | // close meta handle 200 | self.meta_handle.as_ref().unwrap().close(); 201 | self.meta_handle = None; // avoid overwriting 202 | } 203 | 204 | pub fn has_file(&self, path: &str) -> bool { 205 | let meta = self.metadata.read().unwrap(); 206 | meta.files.contains_key(path) 207 | } 208 | 209 | fn get_file_handle(&self, path: &str) -> Result { 210 | let meta = self.metadata.read().unwrap(); 211 | if let Some(mapped_path) = meta.files.get(path) { 212 | let pool = self.handle_pool.read().unwrap(); 213 | let handle = pool.get(&*mapped_path).unwrap(); 214 | return Ok(handle.clone()); 215 | } else { 216 | return Err(JsValue::from_str("file not found")); 217 | } 218 | } 219 | 220 | // Helper, avoid clone of FileSystemSyncAccessHandle 221 | fn with_file_handle(&self, path: &str, f: F) -> Result 222 | where 223 | F: FnOnce(&FileSystemSyncAccessHandle) -> Result, 224 | { 225 | let meta = self.metadata.read().unwrap(); 226 | if let Some(mapped_path) = meta.files.get(path) { 227 | let pool = self.handle_pool.read().unwrap(); 228 | let handle = pool.get(&*mapped_path).unwrap(); 229 | return f(handle); 230 | } else { 231 | return Err(JsValue::from_str("file not found")); 232 | } 233 | } 234 | 235 | fn get_or_create_file(&self, path: &str) -> Result { 236 | if let Ok(handle) = self.get_file_handle(path) { 237 | return Ok(handle); 238 | } else { 239 | // find a empty file 240 | let handle = { 241 | let mut meta = self.metadata.write().unwrap(); 242 | let pool = self.handle_pool.read().unwrap(); 243 | 244 | let empty_file = meta.empty_files.pop().unwrap(); 245 | let handle = pool.get(&empty_file).unwrap().clone(); 246 | // console_log!("alloc new file {}: {}", path, empty_file,); 247 | meta.files.insert(path.to_string(), empty_file); 248 | handle 249 | }; 250 | self.persist_metadata()?; 251 | 252 | Ok(handle) 253 | } 254 | } 255 | 256 | pub fn persist_metadata(&self) -> Result<(), JsValue> { 257 | let handle = self.meta_handle()?; 258 | 259 | let raw = bincode::serialize(&*self.metadata.read().unwrap()).unwrap(); 260 | 261 | let mut opts = FileSystemReadWriteOptions::default(); 262 | Reflect::set(&mut opts, &"at".into(), &0.into())?; 263 | let new_size = raw.len(); 264 | 265 | handle.write_with_u8_array_and_options(&raw, &opts)?; 266 | handle.truncate_with_u32(new_size as u32)?; 267 | handle.flush()?; 268 | 269 | Ok(()) 270 | } 271 | 272 | pub fn read(&self, handle: &FileHandle, buf: &mut [u8], offset: i64) -> Result { 273 | let mut opts = FileSystemReadWriteOptions::default(); 274 | Reflect::set(&mut opts, &"at".into(), &(offset as f64).into())?; 275 | 276 | //let handle = self.get_file_handle(&handle.fname)?; 277 | //let n = handle.read_with_u8_array_and_options(buf, &opts)? as u64; 278 | let n = self.with_file_handle(&handle.fname, |h| { 279 | h.read_with_u8_array_and_options(buf, &opts) 280 | })?; 281 | 282 | Ok(n as i64) 283 | } 284 | 285 | pub fn write(&self, handle: &FileHandle, buf: &[u8], offset: i64) -> Result<(), JsValue> { 286 | let mut opts = FileSystemReadWriteOptions::default(); 287 | Reflect::set(&mut opts, &"at".into(), &(offset as f64).into())?; 288 | 289 | let nwritten = self.with_file_handle(&handle.fname, |h| { 290 | h.write_with_u8_array_and_options(buf, &opts) 291 | })?; 292 | assert_eq!(nwritten, buf.len() as f64); 293 | Ok(()) 294 | } 295 | 296 | pub fn flush(&self, handle: &FileHandle) -> Result<(), JsValue> { 297 | self.with_file_handle(&handle.fname, |h| h.flush()) 298 | } 299 | 300 | pub fn file_size(&self, path: &str) -> Result { 301 | let size = self.with_file_handle(path, |h| h.get_size())?; 302 | 303 | Ok(size as _) 304 | } 305 | 306 | pub fn truncate(&self, handle: &FileHandle, new_size: u64) -> Result<(), JsValue> { 307 | self.with_file_handle(&handle.fname, |h| h.truncate_with_u32(new_size as _)) 308 | } 309 | 310 | pub fn delete(&self, path: &str) -> Result<(), JsValue> { 311 | { 312 | let mut meta = self.metadata.write().unwrap(); 313 | let pool = self.handle_pool.write().unwrap(); 314 | 315 | let mapped_path = meta.files.get(path).unwrap().clone(); 316 | 317 | let handle = pool.get(&mapped_path).unwrap(); 318 | 319 | meta.files.remove(path); 320 | meta.empty_files.push(mapped_path); 321 | 322 | handle.truncate_with_u32(0)?; 323 | handle.flush()?; 324 | } 325 | 326 | self.persist_metadata()?; 327 | 328 | Ok(()) 329 | } 330 | 331 | fn add_new_empty_file(&self, name: String, handle: FileSystemSyncAccessHandle) { 332 | let mut pool = self.handle_pool.write().unwrap(); 333 | pool.insert(name.clone(), handle); 334 | 335 | let mut meta = self.metadata.write().unwrap(); 336 | meta.empty_files.push(name); 337 | } 338 | 339 | async fn init_empty_files( 340 | &self, 341 | root: &FileSystemDirectoryHandle, 342 | n: usize, 343 | ) -> Result<(), JsValue> { 344 | for _ in 0..n { 345 | let name = Uuid::new_v4().to_string() + ".raw"; 346 | console_log!("create empty file: {}", name); 347 | 348 | let mut get_file_opts = &FileSystemGetFileOptions::default(); 349 | Reflect::set(&mut get_file_opts, &"create".into(), &true.into())?; 350 | 351 | let file_handle: FileSystemFileHandle = 352 | JsFuture::from(root.get_file_handle_with_options(&name, &get_file_opts)) 353 | .await? 354 | .into(); 355 | 356 | let sync_handle: FileSystemSyncAccessHandle = 357 | JsFuture::from(file_handle.create_sync_access_handle()) 358 | .await? 359 | .into(); 360 | 361 | self.add_new_empty_file(name, sync_handle); 362 | } 363 | Ok(()) 364 | } 365 | 366 | fn meta_handle(&self) -> Result<&FileSystemSyncAccessHandle, JsValue> { 367 | if let Some(handle) = &self.meta_handle { 368 | Ok(handle) 369 | } else { 370 | Err(JsValue::from_str("metadata file is not inited")) 371 | } 372 | } 373 | } 374 | 375 | async fn list_all_filenames(root: &FileSystemDirectoryHandle) -> Result, JsValue> { 376 | let entries_fn = Reflect::get(&root, &"entries".into())?; 377 | let entries = Reflect::apply(entries_fn.unchecked_ref(), &root, &Array::new())?; 378 | 379 | let mut ret = Vec::new(); 380 | let next_fn: Function = Reflect::get(&entries, &"next".into())?.unchecked_into(); 381 | let arr = Array::new(); 382 | 383 | let mut entry_fut: Promise = Reflect::apply(&next_fn, &entries, &arr)?.into(); 384 | let mut entry = JsFuture::from(entry_fut).await?; 385 | 386 | // access the iteractor 387 | let mut done = Reflect::get(&entry, &"done".into())?.as_bool().unwrap(); 388 | while !done { 389 | // Array<[string, FileSystemFileHandle]> 390 | let value: Array = Reflect::get(&entry, &"value".into())?.into(); 391 | // console_log!("value: {:?}", value); 392 | 393 | let path = value.get(0).as_string().unwrap(); 394 | ret.push(path); 395 | // ret.push(value.as_string().unwrap()); 396 | 397 | entry_fut = Reflect::apply(&next_fn, &entries, &arr)?.into(); 398 | entry = JsFuture::from(entry_fut).await?; 399 | 400 | done = Reflect::get(&entry, &"done".into())?.as_bool().unwrap(); 401 | } 402 | Ok(ret) 403 | } 404 | 405 | async fn get_file_handle_from_root( 406 | root: &FileSystemDirectoryHandle, 407 | path: &str, 408 | ) -> Result { 409 | let mut opts = FileSystemGetFileOptions::default(); 410 | Reflect::set(&mut opts, &"create".into(), &true.into())?; 411 | 412 | let handle: FileSystemFileHandle = 413 | JsFuture::from(root.get_file_handle_with_options(path, &opts)) 414 | .await? 415 | .into(); 416 | let sync_handle: FileSystemSyncAccessHandle = 417 | JsFuture::from(handle.create_sync_access_handle()) 418 | .await? 419 | .into(); 420 | 421 | Ok(sync_handle) 422 | } 423 | 424 | // sqlite part 425 | 426 | mod io_methods { 427 | use super::*; 428 | const SECTOR_SIZE: u32 = 4096; 429 | 430 | pub unsafe extern "C" fn close(fobj: *mut sqlite3_file) -> c_int { 431 | let file = &mut *(fobj as *mut FileHandle); 432 | 433 | POOL.flush(file).unwrap(); 434 | 435 | if file.flags & SQLITE_OPEN_DELETEONCLOSE != 0 { 436 | POOL.delete(&file.fname).unwrap(); 437 | } 438 | 439 | let name = mem::take(&mut file.fname); 440 | drop(name); 441 | sqlite3_free(fobj as *mut c_void); 442 | 443 | SQLITE_OK 444 | } 445 | pub unsafe extern "C" fn read( 446 | arg1: *mut sqlite3_file, 447 | arg2: *mut c_void, 448 | amount: c_int, 449 | offset: sqlite3_int64, 450 | ) -> c_int { 451 | let file: *mut FileHandle = arg1 as _; 452 | 453 | let buf = slice::from_raw_parts_mut(arg2 as *mut u8, amount as usize); 454 | match POOL.read(&*file, buf, offset) { 455 | Ok(nread) => { 456 | if (nread as i32) < amount { 457 | buf[nread as usize..].fill(0); // fill with 0 458 | return SQLITE_IOERR_SHORT_READ; 459 | } 460 | 461 | SQLITE_OK 462 | } 463 | Err(e) => { 464 | console_log!("read error: {:?}", e); 465 | SQLITE_IOERR_READ 466 | } 467 | } 468 | } 469 | pub unsafe extern "C" fn write( 470 | arg1: *mut sqlite3_file, 471 | arg2: *const c_void, 472 | amount: c_int, 473 | offset: sqlite3_int64, 474 | ) -> c_int { 475 | let file: *mut FileHandle = arg1 as _; 476 | 477 | //console_log!("{:?} size={} offset={}", (*file).fname, amount, offset); 478 | 479 | let buf = slice::from_raw_parts(arg2 as *const u8, amount as usize); 480 | match POOL.write(&*file, buf, offset as _) { 481 | Ok(_) => SQLITE_OK, 482 | Err(e) => { 483 | console_log!("write error: {:?}", e); 484 | SQLITE_IOERR_WRITE 485 | } 486 | } 487 | } 488 | pub unsafe extern "C" fn truncate(arg1: *mut sqlite3_file, size: sqlite3_int64) -> c_int { 489 | let file: *mut FileHandle = arg1 as _; 490 | match POOL.truncate(&*file, size as _) { 491 | Ok(_) => SQLITE_OK, 492 | Err(_) => SQLITE_IOERR_TRUNCATE, 493 | } 494 | } 495 | pub unsafe extern "C" fn sync(arg1: *mut sqlite3_file, _flags: c_int) -> c_int { 496 | let file: *mut FileHandle = arg1 as _; 497 | 498 | match POOL.flush(&*file) { 499 | Ok(_) => SQLITE_OK, 500 | Err(_) => SQLITE_IOERR_FSYNC, 501 | } 502 | } 503 | pub unsafe extern "C" fn file_size( 504 | arg1: *mut sqlite3_file, 505 | res_size: *mut sqlite3_int64, 506 | ) -> c_int { 507 | let file: *mut FileHandle = arg1 as _; 508 | 509 | match POOL.file_size(&(*file).fname) { 510 | Ok(size) => { 511 | *res_size = size as _; 512 | SQLITE_OK 513 | } 514 | Err(_) => SQLITE_IOERR_FSTAT, 515 | } 516 | } 517 | 518 | // lock & unlock related 519 | pub unsafe extern "C" fn lock(arg1: *mut sqlite3_file, lock_type: c_int) -> c_int { 520 | let file: *mut FileHandle = arg1 as _; 521 | (*file).lock = lock_type; 522 | 523 | SQLITE_OK 524 | } 525 | pub unsafe extern "C" fn unlock(arg1: *mut sqlite3_file, lock_type: c_int) -> c_int { 526 | let file: *mut FileHandle = arg1 as _; 527 | (*file).lock = lock_type; 528 | 529 | SQLITE_OK 530 | } 531 | 532 | // checks whether any database connection, 533 | // either in this process or in some other process, 534 | // is holding a RESERVED, PENDING, or EXCLUSIVE lock on the file 535 | pub unsafe extern "C" fn check_reserved_lock( 536 | _: *mut sqlite3_file, 537 | res_out: *mut c_int, 538 | ) -> c_int { 539 | *res_out = 1; 540 | SQLITE_OK 541 | } 542 | 543 | pub extern "C" fn sector_size(_: *mut sqlite3_file) -> c_int { 544 | SECTOR_SIZE as i32 545 | } 546 | pub extern "C" fn file_control(_: *mut sqlite3_file, _op: c_int, _arg: *mut c_void) -> c_int { 547 | SQLITE_NOTFOUND 548 | } 549 | pub extern "C" fn device_characteristics(_: *mut sqlite3_file) -> c_int { 550 | SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN | SQLITE_IOCAP_SAFE_APPEND 551 | } 552 | } 553 | 554 | static IO_METHODS: sqlite3_io_methods = sqlite3_io_methods { 555 | iVersion: 1, 556 | xClose: Some(io_methods::close), 557 | xRead: Some(io_methods::read), 558 | xWrite: Some(io_methods::write), 559 | xTruncate: Some(io_methods::truncate), 560 | xSync: Some(io_methods::sync), 561 | xFileSize: Some(io_methods::file_size), 562 | xLock: Some(io_methods::lock), 563 | xUnlock: Some(io_methods::unlock), 564 | xCheckReservedLock: Some(io_methods::check_reserved_lock), 565 | xFileControl: Some(io_methods::file_control), 566 | xSectorSize: Some(io_methods::sector_size), 567 | xDeviceCharacteristics: Some(io_methods::device_characteristics), 568 | /* Methods above are valid for version 1 */ 569 | xShmMap: None, 570 | xShmLock: None, 571 | xShmBarrier: None, 572 | xShmUnmap: None, 573 | xFetch: None, 574 | xUnfetch: None, 575 | }; 576 | 577 | // - vfs layer 578 | mod opfs_vfs { 579 | use super::*; 580 | 581 | pub unsafe extern "C" fn open( 582 | _vfs: *mut sqlite3_vfs, 583 | fname: *const c_char, 584 | fobj: *mut sqlite3_file, 585 | flags: c_int, 586 | out_flags: *mut c_int, 587 | ) -> c_int { 588 | if fname.is_null() { 589 | return SQLITE_IOERR; 590 | } 591 | 592 | let name = CStr::from_ptr(fname).to_str().unwrap(); 593 | 594 | let file = fobj as *mut FileHandle; 595 | 596 | if SQLITE_OPEN_CREATE & flags == SQLITE_OPEN_CREATE { 597 | // console_log!("open create file: {}", name); 598 | 599 | let _h = POOL.get_or_create_file(name).unwrap(); 600 | (*file).fname = name.to_string(); 601 | (*file).lock = SQLITE_LOCK_NONE; 602 | } else { 603 | // console_log!("open open file: {}", name); 604 | 605 | let _h = POOL.get_file_handle(name).unwrap(); 606 | (*file).fname = name.to_string(); 607 | (*file).lock = SQLITE_LOCK_NONE; 608 | } 609 | (*file).flags = flags; // save open flags 610 | (*file)._super.pMethods = &IO_METHODS; 611 | 612 | *out_flags = flags; 613 | 614 | SQLITE_OK 615 | } 616 | pub unsafe extern "C" fn delete( 617 | _: *mut sqlite3_vfs, 618 | fname: *const c_char, 619 | _sync_dir: c_int, 620 | ) -> c_int { 621 | let name = CStr::from_ptr(fname).to_str().unwrap(); 622 | match POOL.delete(name) { 623 | Ok(_) => SQLITE_OK, 624 | Err(_) => SQLITE_IOERR_DELETE, 625 | } 626 | } 627 | /// Query the file-system to see if the named file exists, is readable or 628 | /// is both readable and writable. 629 | /// #define SQLITE_ACCESS_EXISTS 0 630 | /// #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */ 631 | /// #define SQLITE_ACCESS_READ 2 /* Unused */ 632 | pub unsafe extern "C" fn access( 633 | _: *mut sqlite3_vfs, 634 | fname: *const c_char, 635 | _flags: c_int, 636 | res_out: *mut c_int, 637 | ) -> c_int { 638 | let name = CStr::from_ptr(fname).to_str().unwrap(); 639 | 640 | let exists = POOL.has_file(name); 641 | *res_out = if exists { 1 } else { 0 }; 642 | SQLITE_OK 643 | } 644 | 645 | pub unsafe extern "C" fn fullpathname( 646 | _: *mut sqlite3_vfs, 647 | fname: *const c_char, 648 | out: c_int, 649 | res_out: *mut c_char, 650 | ) -> c_int { 651 | let name = CStr::from_ptr(fname).to_str().unwrap(); 652 | 653 | let n = name.len(); 654 | if n > out as usize { 655 | return SQLITE_CANTOPEN; 656 | } 657 | 658 | ptr::copy_nonoverlapping(fname, res_out, name.len() + 1); 659 | res_out.offset(out as isize).write(0); 660 | 661 | SQLITE_OK 662 | } 663 | 664 | pub unsafe extern "C" fn randomness(_: *mut sqlite3_vfs, n: c_int, out: *mut c_char) -> c_int { 665 | let buf = slice::from_raw_parts_mut(out as *mut u8, n as usize); 666 | getrandom::getrandom(buf).unwrap(); 667 | SQLITE_OK 668 | } 669 | 670 | pub unsafe extern "C" fn sleep(_: *mut sqlite3_vfs, microseconds: c_int) -> c_int { 671 | console_log!("sleep {} microseconds", microseconds); 672 | 673 | let duration = std::time::Duration::from_micros(microseconds as u64); 674 | std::thread::sleep(duration); 675 | 676 | SQLITE_OK 677 | } 678 | 679 | pub unsafe extern "C" fn currenttime(_: *mut sqlite3_vfs, arg2: *mut f64) -> c_int { 680 | // wasm32-unknown-unknown does not provide std::time::SystemTime 681 | let time = js_sys::Date::new_0().get_time(); 682 | 683 | let t = time / 86400000.0 + 2440587.5; 684 | *arg2 = t; 685 | 686 | SQLITE_OK 687 | } 688 | 689 | pub unsafe extern "C" fn get_last_error( 690 | _: *mut sqlite3_vfs, 691 | _len: c_int, 692 | _buf: *mut c_char, 693 | ) -> c_int { 694 | console_log!("TODO: get_last_error"); 695 | SQLITE_OK 696 | } 697 | } 698 | 699 | pub async fn init_sqlite_vfs() -> Result<(), JsValue> { 700 | let vfs = sqlite3_vfs { 701 | iVersion: 1, 702 | szOsFile: std::mem::size_of::() as _, // size of sqlite3_file 703 | mxPathname: 1024, 704 | pNext: ptr::null_mut(), 705 | zName: "logseq-sahpool-opfs\0".as_ptr() as *const c_char, 706 | pAppData: ptr::null_mut(), 707 | xOpen: Some(opfs_vfs::open), 708 | xDelete: Some(opfs_vfs::delete), 709 | xAccess: Some(opfs_vfs::access), 710 | xFullPathname: Some(opfs_vfs::fullpathname), 711 | // run-time extension support 712 | xDlOpen: None, 713 | xDlError: None, 714 | xDlSym: None, 715 | xDlClose: None, 716 | xRandomness: Some(opfs_vfs::randomness), 717 | xSleep: Some(opfs_vfs::sleep), 718 | xCurrentTime: Some(opfs_vfs::currenttime), 719 | xGetLastError: Some(opfs_vfs::get_last_error), 720 | // The methods above are in version 1 of the sqlite_vfs object definition 721 | xCurrentTimeInt64: None, 722 | xSetSystemCall: None, 723 | xGetSystemCall: None, 724 | xNextSystemCall: None, 725 | }; 726 | 727 | unsafe { 728 | sqlite3_vfs_register(Box::leak(Box::new(vfs)), 1); 729 | } 730 | 731 | Ok(()) 732 | } 733 | 734 | #[wasm_bindgen] 735 | pub fn get_version() -> String { 736 | let version = unsafe { CStr::from_ptr(sqlite3_libversion()) }; 737 | version.to_str().unwrap().to_string() 738 | } 739 | 740 | /// Test OPFS support on current platform 741 | #[wasm_bindgen] 742 | pub fn has_opfs_support() -> bool { 743 | let global_this = match js_sys::global().dyn_into::() { 744 | Ok(v) => v, 745 | Err(_) => { 746 | console_log!("Not in Worker context, WorkerGlobalScope not found"); 747 | return false; 748 | } 749 | }; 750 | 751 | // check FileSystemSyncAccessHandle 752 | 753 | if let Ok(v) = js_sys::Reflect::get(&global_this, &"FileSystemFileHandle".try_into().unwrap()) { 754 | if v.is_undefined() { 755 | console_log!("no Atomics"); 756 | return false; 757 | } 758 | if let Ok(v) = js_sys::Reflect::get(&v, &"prototype".try_into().unwrap()) { 759 | if v.is_undefined() { 760 | console_log!("no prototype"); 761 | return false; 762 | } 763 | if let Ok(f) = js_sys::Reflect::get(&v, &"createSyncAccessHandle".try_into().unwrap()) { 764 | if f.is_undefined() { 765 | console_log!("no createSyncAccessHandle"); 766 | return false; 767 | } 768 | } 769 | } 770 | } 771 | 772 | if let Ok(v) = js_sys::Reflect::get(&global_this, &"navigator".try_into().unwrap()) { 773 | if v.is_undefined() { 774 | console_log!("no navigator"); 775 | return false; 776 | } 777 | } 778 | let navigator = global_this.navigator(); 779 | if let Ok(v) = js_sys::Reflect::get(&navigator, &"storage".try_into().unwrap()) { 780 | if v.is_undefined() { 781 | console_log!("no storage"); 782 | return false; 783 | } 784 | } 785 | 786 | let storage = navigator.storage(); 787 | if let Ok(v) = js_sys::Reflect::get(&storage, &"getDirectory".try_into().unwrap()) { 788 | if v.is_undefined() { 789 | console_log!("no getDirectory"); 790 | return false; 791 | } 792 | } 793 | 794 | true 795 | } 796 | -------------------------------------------------------------------------------- /tests/worker.rs: -------------------------------------------------------------------------------- 1 | #![cfg(target_arch = "wasm32")] 2 | 3 | extern crate wasm_bindgen_test; 4 | 5 | use logseq_sqlite::console_log; 6 | use wasm_bindgen_test::*; 7 | 8 | // wasm_bindgen_test_configure!(run_in_browser); 9 | wasm_bindgen_test_configure!(run_in_worker); 10 | 11 | #[wasm_bindgen_test] 12 | fn sqlite_version() { 13 | let x = logseq_sqlite::get_version(); 14 | assert_eq!(x, "3.42.0".to_string()); 15 | logseq_sqlite::log(&format!("sqlite version: {}", x)); 16 | } 17 | 18 | #[wasm_bindgen_test] 19 | async fn opfs_ok() { 20 | let has_opfs_support = logseq_sqlite::has_opfs_support(); 21 | assert_eq!(has_opfs_support, true); 22 | } 23 | 24 | #[wasm_bindgen_test] 25 | async fn library_init() { 26 | logseq_sqlite::ensure_init().await.unwrap(); 27 | 28 | logseq_sqlite::init_db("my-graph").await.unwrap(); 29 | 30 | // logseq_sqlite::rusqlite_test().unwrap(); 31 | 32 | logseq_sqlite::block_db_test().unwrap(); 33 | 34 | logseq_sqlite::log("all done"); 35 | } 36 | --------------------------------------------------------------------------------