Many hyperlinks are disabled.
Use anonymous login
to enable hyperlinks.
Changes In Branch jni-threading Excluding Merge-Ins
This is equivalent to a diff from c3190332 to 1f46ba8d
2023-08-24
| ||
14:49 | Merge the jni-threading branch into trunk, eliminating the JNI API's prior threading limitations. (check-in: 3739c8aa user: stephan tags: trunk) | |
14:31 | Correct JNI layer's misuse of an sqlite3-internal error-reporting API (no mutex held). Style cleanups. Eliminate lookups of per-thread state by approximately 85% across the test suite. (Closed-Leaf check-in: 1f46ba8d user: stephan tags: jni-threading) | |
11:57 | Add more JNI docs, tests, and a handful of Java-side overloads. (check-in: d19a431f user: stephan tags: jni-threading) | |
2023-08-21
| ||
14:28 | Address minor inaccuracies in fuzzcheck and RTREE found by UBSAN. (check-in: a64e6c2f user: drh tags: trunk) | |
2023-08-19
| ||
12:34 | Merge trunk into jni-threading branch. (check-in: 8254479c user: stephan tags: jni-threading) | |
08:12 | shell.c.in help text typo fix. No functional changes. (check-in: c3190332 user: stephan tags: trunk) | |
2023-08-18
| ||
15:39 | Rename the decimal_sci() function to decimal_exp(). Forum post fa027bb0ab. (check-in: c48f1be8 user: drh tags: trunk) | |
Changes to ext/jni/GNUmakefile.
︙ | ︙ | |||
64 65 66 67 68 69 70 71 72 73 74 75 76 77 | CommitHook.java \ NativePointerHolder.java \ OutputPointer.java \ ProgressHandler.java \ ResultCode.java \ RollbackHook.java \ SQLFunction.java \ sqlite3_context.java \ sqlite3.java \ SQLite3Jni.java \ sqlite3_stmt.java \ sqlite3_value.java \ Tester1.java \ Tracer.java \ | > | 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | CommitHook.java \ NativePointerHolder.java \ OutputPointer.java \ ProgressHandler.java \ ResultCode.java \ RollbackHook.java \ SQLFunction.java \ SQLLog.java \ sqlite3_context.java \ sqlite3.java \ SQLite3Jni.java \ sqlite3_stmt.java \ sqlite3_value.java \ Tester1.java \ Tracer.java \ |
︙ | ︙ | |||
156 157 158 159 160 161 162 163 164 165 | -DSQLITE_ENABLE_RTREE \ -DSQLITE_ENABLE_EXPLAIN_COMMENTS \ -DSQLITE_ENABLE_STMTVTAB \ -DSQLITE_ENABLE_DBPAGE_VTAB \ -DSQLITE_ENABLE_DBSTAT_VTAB \ -DSQLITE_ENABLE_BYTECODE_VTAB \ -DSQLITE_ENABLE_OFFSET_SQL_FUNC \ -DSQLITE_OMIT_LOAD_EXTENSION \ -DSQLITE_OMIT_DEPRECATED \ -DSQLITE_OMIT_SHARED_CACHE \ | > > | | | < < < | 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | -DSQLITE_ENABLE_RTREE \ -DSQLITE_ENABLE_EXPLAIN_COMMENTS \ -DSQLITE_ENABLE_STMTVTAB \ -DSQLITE_ENABLE_DBPAGE_VTAB \ -DSQLITE_ENABLE_DBSTAT_VTAB \ -DSQLITE_ENABLE_BYTECODE_VTAB \ -DSQLITE_ENABLE_OFFSET_SQL_FUNC \ -DSQLITE_ENABLE_PREUPDATE_HOOK \ -DSQLITE_ENABLE_SQLLOG \ -DSQLITE_OMIT_LOAD_EXTENSION \ -DSQLITE_OMIT_DEPRECATED \ -DSQLITE_OMIT_SHARED_CACHE \ -DSQLITE_THREADSAFE=1 \ -DSQLITE_TEMP_STORE=2 \ -DSQLITE_USE_URI=1 \ -DSQLITE_C=$(sqlite3.c) \ -DSQLITE_DEBUG SQLITE_OPT += -g -DDEBUG -UNDEBUG ifeq (1,$(enable.fts5)) SQLITE_OPT += -DSQLITE_ENABLE_FTS5 endif |
︙ | ︙ | |||
223 224 225 226 227 228 229 | $(sqlite3-jni.dll): $(sqlite3-jni.h) $(sqlite3.c) $(sqlite3.h) $(sqlite3-jni.dll): $(dir.bld.c) $(sqlite3-jni.c) $(SQLite3Jni.java) $(MAKEFILE) $(CC) $(sqlite3-jni.dll.cflags) $(SQLITE_OPT) \ $(sqlite3-jni.c) -shared -o $@ all: $(sqlite3-jni.dll) .PHONY: test | | < | | | > > > > | 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 | $(sqlite3-jni.dll): $(sqlite3-jni.h) $(sqlite3.c) $(sqlite3.h) $(sqlite3-jni.dll): $(dir.bld.c) $(sqlite3-jni.c) $(SQLite3Jni.java) $(MAKEFILE) $(CC) $(sqlite3-jni.dll.cflags) $(SQLITE_OPT) \ $(sqlite3-jni.c) -shared -o $@ all: $(sqlite3-jni.dll) .PHONY: test test.flags ?= test.main.flags = -ea -Djava.library.path=$(dir.bld.c) \ $(java.flags) -cp $(classpath) \ org.sqlite.jni.Tester1 test: $(SQLite3Jni.class) $(sqlite3-jni.dll) $(bin.java) $(test.main.flags) $(test.flags) @echo "Again in multi-threaded mode:" $(bin.java) $(test.main.flags) -t 5 -r 20 -shuffle $(test.flags) tester.scripts := $(sort $(wildcard $(dir.src)/tests/*.test)) tester.flags ?= # --verbose .PHONY: tester tester-local tester-ext ifeq (1,$(enable.tester)) tester-local: $(CLASS_FILES.tester) $(sqlite3-jni.dll) $(bin.java) -ea -Djava.library.path=$(dir.bld.c) \ |
︙ | ︙ | |||
268 269 270 271 272 273 274 | tester-ext: tester-local tester: tester-ext tests: test tester package.jar.in := $(abspath $(dir.src)/jar.in) CLEAN_FILES += $(package.jar.in) $(package.jar.in): $(MAKEFILE) $(CLASS_FILES.main) cd $(dir.src); ls -1 org/sqlite/jni/*.java org/sqlite/jni/*.class > $@ | < | | 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | tester-ext: tester-local tester: tester-ext tests: test tester package.jar.in := $(abspath $(dir.src)/jar.in) CLEAN_FILES += $(package.jar.in) $(package.jar.in): $(MAKEFILE) $(CLASS_FILES.main) cd $(dir.src); ls -1 org/sqlite/jni/*.java org/sqlite/jni/*.class > $@ @echo "To use this jar you will need the -Djava.library.path=DIR/CONTAINING/libsqlite3-jni.so flag." @echo "e.g. java -jar $@ -Djava.library.path=bld" $(package.jar): $(CLASS_FILES) $(MAKEFILE) $(package.jar.in) rm -f $(dir.src)/c/*~ $(dir.src.jni)/*~ cd $(dir.src); $(bin.jar) -cfe ../$@ org.sqlite.jni.Tester1 @$(package.jar.in) jar: $(package.jar) |
︙ | ︙ | |||
313 314 315 316 317 318 319 320 321 322 323 324 325 326 | .PHONY: dist snapshot dist: \ $(bin.version-info) $(sqlite3.canonical.c) \ $(package.jar) $(MAKEFILE) @echo "Making end-user deliverables..." @rm -fr $(dist-dir.top) @mkdir -p $(dist-dir.src) @cp -p $(dist.top.extras) $(dist-dir.top)/. @cp -p jar-dist.make $(dist-dir.top)/Makefile @cp -p $(dir.src.c)/*.[ch] $(dist-dir.src)/. @cp -p $(sqlite3.canonical.c) $(sqlite3.canonical.h) $(dist-dir.src)/. @set -e; \ | > > > > | 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 | .PHONY: dist snapshot dist: \ $(bin.version-info) $(sqlite3.canonical.c) \ $(package.jar) $(MAKEFILE) @echo "Making end-user deliverables..." @echo "****************************************************************************"; \ echo "*** WARNING: be sure to build this with JDK8 (javac 1.8) for compatibility."; \ echo "*** reasons!"; $$($(bin.javac) -version); \ echo "****************************************************************************" @rm -fr $(dist-dir.top) @mkdir -p $(dist-dir.src) @cp -p $(dist.top.extras) $(dist-dir.top)/. @cp -p jar-dist.make $(dist-dir.top)/Makefile @cp -p $(dir.src.c)/*.[ch] $(dist-dir.src)/. @cp -p $(sqlite3.canonical.c) $(sqlite3.canonical.h) $(dist-dir.src)/. @set -e; \ |
︙ | ︙ |
Changes to ext/jni/README.md.
︙ | ︙ | |||
11 12 13 14 15 16 17 | Technical support is available in the forum: <https://sqlite.org/forum> > **FOREWARNING:** this subproject is very much in development and subject to any number of changes. Please do not rely on any | | > > > | 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | Technical support is available in the forum: <https://sqlite.org/forum> > **FOREWARNING:** this subproject is very much in development and subject to any number of changes. Please do not rely on any information about its API until this disclaimer is removed. The JNI bindings released with version 3.43 are a "tech preview" and 3.44 will be "final," at which point strong backward compatibility guarantees will apply. Project goals/requirements: - A [1-to-1(-ish) mapping of the C API](#1to1ish) to Java via JNI, insofar as cross-language semantics allow for. A closely-related goal is that [the C documentation](https://sqlite.org/c3ref/intro.html) should be usable as-is, insofar as possible, for the JNI binding. |
︙ | ︙ | |||
37 38 39 40 41 42 43 | Non-goals: - Creation of high-level OO wrapper APIs. Clients are free to create them off of the C-style API. | | > | > > > > | > > | < > > > > > | > > > > > > > > > > | > > > > > | | > > > > > > > > > | > > > | > > > > > > | > | | > > | > > > > > | > | | < > < | > | | | | | | > > < > > > > > > > > < > > > > > | > | | | > > < > > > > > > | | | | | | > | | > > | | > > > | 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 | Non-goals: - Creation of high-level OO wrapper APIs. Clients are free to create them off of the C-style API. Hello World ----------------------------------------------------------------------- ```java import org.sqlite.jni.*; import static SQLite3Jni.*; ... final sqlite3 db = sqlite3_open(":memory:"); try { final int rc = sqlite3_errcode(db); if( 0 != rc ){ if( null != db ){ System.out.print("Error opening db: "+sqlite3_errmsg(db)); }else{ System.out.print("Error opening db: rc="+rc); } ... handle error ... } // ... else use the db ... }finally{ // ALWAYS close databases using sqlite3_close() or sqlite3_close_v2() // when done with them. All of their active statement handles must // first have been passed to sqlite3_finalize(). sqlite3_close_v2(db); } ``` Building ======================================================================== The canonical builds assumes a Linux-like environment and requires: - GNU Make - A JDK supporting Java 8 or higher - A modern C compiler. gcc and clang should both work. Put simply: ```console $ export JAVA_HOME=/path/to/jdk/root $ make $ make test $ make clean ``` The jar distribution can be created with `make jar`, but note that it does not contain the binary DLL file. A different DLL is needed for each target platform. <a id='1to1ish'></a> One-to-One(-ish) Mapping to C ======================================================================== This JNI binding aims to provide as close to a 1-to-1 experience with the C API as cross-language semantics allow. Interface changes are necessarily made where cross-language semantics do not allow a 1-to-1, and judiciously made where a 1-to-1 mapping would be unduly cumbersome to use in Java. In all cases, this binding makes every effort to provide semantics compatible with the C API documentation even if the interface to those semantics is slightly different. Any cases which deviate from those semantics (either removing or adding semantics) are clearly documented. Where it makes sense to do so for usability, Java-side overloads are provided which accept or return data in alternative forms or provide sensible default argument values. In all such cases they are thin proxies around the corresponding C APIs and do not introduce new semantics. In some very few cases, Java-specific capabilities have been added in new APIs, all of which have "_java" somewhere in their names. Examples include: - `sqlite3_result_java_object()` - `sqlite3_column_java_object()` - `sqlite3_column_java_casted()` - `sqlite3_value_java_object()` - `sqlite3_value_java_casted()` which, as one might surmise, collectively enable the passing of arbitrary Java objects from user-defined SQL functions through to the caller. Golden Rule: Garbage Collection Cannot Free SQLite Resources ------------------------------------------------------------------------ It is important that all databases and prepared statement handles get cleaned up by client code. A database cannot be closed if it has open statement handles. `sqlite3_close()` fails if the db cannot be closed whereas `sqlite3_close_v2()` recognizes that case and marks the db as a "zombie," pending finalization when the library detects that all pending statements have been closed. Be aware that Java garbage collection _cannot_ close a database or finalize a prepared statement. Those things require explicit API calls. Golden Rule #2: _Never_ Throw from Callbacks (Unless...) ------------------------------------------------------------------------ All routines in this API, barring explicitly documented exceptions, retain C-like semantics. For example, they are not permitted to throw or propagate exceptions and must return error information (if any) via result codes or `null`. The only cases where the C-style APIs may throw is through client-side misuse, e.g. passing in a null where it shouldn't be used. The APIs clearly mark function parameters which should not be null, but does not actively defend itself against such misuse. Some C-style APIs explicitly accept `null` as a no-op for usability's sake, and some of the JNI APIs deliberately return an error code, instead of segfaulting, when passed a `null`. Client-defined callbacks _must never throw exceptions_ unless _very explicitly documented_ as being throw-safe. Exceptions are generally reserved for higher-level bindings which are constructed to specifically deal with them and ensure that they do not leak C-level resources. In some cases, callback handlers are permitted to throw, in which cases they get translated to C-level result codes and/or messages. If a callback which is not permitted to throw throws, its exception may trigger debug output but will otherwise be suppressed. The reason some callbacks are permitted to throw and others not is because all such callbacks act as proxies for C function callback interfaces and some of those interfaces have no error-reporting mechanism. Those which are capable of propagating errors back through the library convert exceptions from callbacks into corresponding C-level error information. Those which cannot propagate errors necessarily suppress any exceptions in order to maintain the C-style semantics of the APIs. Awkward Callback Names ------------------------------------------------------------------------ In places where the Java interface uses callbacks (see below), those callbacks often have what might fairly be labeled as awkward names, e.g. `sqlScalarFunction.xFunc()` and `preupdateHook.xPreUpdate()`. Those names were chosen because they match the corresponding arguments in the C-level API docs. If they were renamed to be more Java-esque, documentation transparency would suffer. Unwieldy Constructs are Re-mapped ------------------------------------------------------------------------ Some constructs, when modelled 1-to-1 from C to Java, are unduly clumsy to work with in Java because they try to shoehorn C's way of doing certain things into Java's wildly different ways. The following subsections cover those, starting with a verbose explanation and demonstration of where such changes are "really necessary"... ### Custom Collations A prime example of where interface changes for Java are necessary for usability is [registration of a custom collation](https://sqlite.org/c3ref/create_collation.html): ```c // C: int sqlite3_create_collation(sqlite3 * db, const char * name, int eTextRep, void *pUserData, int (*xCompare)(void*,int,void const *,int,void const *)); int sqlite3_create_collation_v2(sqlite3 * db, const char * name, int eTextRep, void *pUserData, int (*xCompare)(void*,int,void const *,int,void const *), void (*xDestroy)(void*)); ``` The `pUserData` object is optional client-defined state for the `xCompare()` and/or `xDestroy()` callback functions, both of which are passed that object as their first argument. That data is passed around "externally" in C because that's how C models the world. If we were to bind that part as-is to Java, the result would be awkward to use (^Yes, we tried this.): ```java // Java: int sqlite3_create_collation(sqlite3 db, String name, int eTextRep, Object pUserData, xCompareType xCompare); int sqlite3_create_collation_v2(sqlite3 db, String name, int eTextRep, Object pUserData, xCompareType xCompare, xDestroyType xDestroy); ``` The awkwardness comes from (A) having two distinctly different objects for callbacks and (B) having their internal state provided separately, which is ill-fitting in Java. For the sake of usability, C APIs which follow that pattern use a slightly different Java interface: ```java int sqlite3_create_collation(sqlite3 db, String name, int eTextRep, Collation collation); ``` Where the `Collation` class has an abstract `xCompare()` method and no-op `xDestroy()` method which can be overridden if needed, leading to a much more Java-esque usage: ```java int rc = sqlite3_create_collation(db, "mycollation", SQLITE_UTF8, new Collation(){ // Required comparison function: @Override public int xCompare(byte[] lhs, byte[] rhs){ ... } // Optional finalizer function: @Override public void xDestroy(){ ... } // Optional local state: private String localState1 = "This is local state. There are many like it, but this one is mine."; private MyStateType localState2 = new MyStateType(); ... }); ``` Noting that: - It is possible to bind in call-scope-local state via closures, if desired, as opposed to packing it into the Collation object. - No capabilities of the C API are lost or unduly obscured via the above API reshaping, so power users need not make any compromises. - In the specific example above, `sqlite3_create_collation_v2()` becomes superfluous because the provided interface effectively provides both the v1 and v2 interfaces, the difference being that overriding the `xDestroy()` method effectively gives it v2 semantics. ### User-defined SQL Functions (a.k.a. UDFs) The [`sqlite3_create_function()`](https://sqlite.org/c3ref/create_function.html) family of APIs make heavy use of function pointers to provide client-defined callbacks, necessitating interface changes in the JNI binding. The Java API has only one core function-registration function: ```java int sqlite3_create_function(sqlite3 db, String funcName, int nArgs, int encoding, SQLFunction func); ``` > Design question: does the encoding argument serve any purpose in Java? That's as-yet undetermined. If not, it will be removed. `SQLFunction` is not used directly, but is instead instantiated via one of its three subclasses: - `SQLFunction.Scalar` implements simple scalar functions using but a single callback. - `SQLFunction.Aggregate` implements aggregate functions using two callbacks. - `SQLFunction.Window` implements window functions using four callbacks. Search [`Tester1.java`](/file/ext/jni/src/org/sqlite/jni/Tester1.java) for `SQLFunction` for how it's used. Reminder: see the disclaimer at the top of this document regarding the in-flux nature of this API. ### And so on... Various APIs which accept callbacks, e.g. `sqlite3_trace_v2()` and `sqlite3_update_hook()`, use interfaces similar to those shown above. Despite the changes in signature, the JNI layer makes every effort to provide the same semantics as the C API documentation suggests. |
Changes to ext/jni/jar-dist.make.
1 2 3 4 5 6 7 8 | #!/this/is/make #^^^^ help emacs out # # This is a POSIX-make-compatible makefile for building the sqlite3 # JNI library from "dist" zip file. It must be edited to set the # proper top-level JDK directory and, depending on the platform, add a # platform-specific -I directory. It should build as-is with any # 2020s-era version of gcc or clang. It requires JDK version 8 or | | > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #!/this/is/make #^^^^ help emacs out # # This is a POSIX-make-compatible makefile for building the sqlite3 # JNI library from "dist" zip file. It must be edited to set the # proper top-level JDK directory and, depending on the platform, add a # platform-specific -I directory. It should build as-is with any # 2020s-era version of gcc or clang. It requires JDK version 8 or # higher and that JAVA_HOME points to the top-most installation # directory of that JDK. On Ubuntu-style systems the JDK is typically # installed under /usr/lib/jvm/java-VERSION-PLATFORM. default: all JAVA_HOME = /usr/lib/jvm/java-1.8.0-openjdk-amd64 CFLAGS = \ -fPIC \ -Isrc \ |
︙ | ︙ | |||
27 28 29 30 31 32 33 | -DSQLITE_ENABLE_DBPAGE_VTAB \ -DSQLITE_ENABLE_DBSTAT_VTAB \ -DSQLITE_ENABLE_BYTECODE_VTAB \ -DSQLITE_ENABLE_OFFSET_SQL_FUNC \ -DSQLITE_OMIT_LOAD_EXTENSION \ -DSQLITE_OMIT_DEPRECATED \ -DSQLITE_OMIT_SHARED_CACHE \ | | | > > | > | 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | -DSQLITE_ENABLE_DBPAGE_VTAB \ -DSQLITE_ENABLE_DBSTAT_VTAB \ -DSQLITE_ENABLE_BYTECODE_VTAB \ -DSQLITE_ENABLE_OFFSET_SQL_FUNC \ -DSQLITE_OMIT_LOAD_EXTENSION \ -DSQLITE_OMIT_DEPRECATED \ -DSQLITE_OMIT_SHARED_CACHE \ -DSQLITE_THREADSAFE=1 \ -DSQLITE_TEMP_STORE=2 \ -DSQLITE_USE_URI=1 \ -DSQLITE_ENABLE_FTS5 \ -DSQLITE_DEBUG sqlite3-jni.dll = libsqlite3-jni.so $(sqlite3-jni.dll): @echo "************************************************************************"; \ echo "*** If this fails to build, be sure to edit this makefile ***"; \ echo "*** to configure it for your system. ***"; \ echo "************************************************************************" $(CC) $(CFLAGS) $(SQLITE_OPT) \ src/sqlite3-jni.c -shared -o $@ @echo "Now try running it with: make test" test.flags = -Djava.library.path=. sqlite3-jni-*.jar test: $(sqlite3-jni.dll) java -jar $(test.flags) java -jar $(test.flags) -t 7 -r 10 -shuffle clean: -rm -f $(sqlite3-jni.dll) all: $(sqlite3-jni.dll) |
Changes to ext/jni/src/c/sqlite3-jni.c.
︙ | ︙ | |||
9 10 11 12 13 14 15 | ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file implements the JNI bindings declared in ** org.sqlite.jni.SQLiteJni (from which sqlite3-jni.h is generated). */ | | | | | | | | | | | 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file implements the JNI bindings declared in ** org.sqlite.jni.SQLiteJni (from which sqlite3-jni.h is generated). */ /* ** If you found this comment by searching the code for ** CallStaticObjectMethod then you're the victim of an OpenJDK bug: ** ** https://bugs.openjdk.org/browse/JDK-8130659 ** ** It's known to happen with OpenJDK v8 but not with v19. ** ** This code does not use JNI's CallStaticObjectMethod(). */ /* ** Define any SQLITE_... config defaults we want if they aren't ** overridden by the builder. Please keep these alphabetized. */ |
︙ | ︙ | |||
57 58 59 60 61 62 63 | #endif #ifndef SQLITE_ENABLE_MATH_FUNCTIONS # define SQLITE_ENABLE_MATH_FUNCTIONS 1 #endif #ifndef SQLITE_ENABLE_OFFSET_SQL_FUNC # define SQLITE_ENABLE_OFFSET_SQL_FUNC 1 #endif | < < < | 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | #endif #ifndef SQLITE_ENABLE_MATH_FUNCTIONS # define SQLITE_ENABLE_MATH_FUNCTIONS 1 #endif #ifndef SQLITE_ENABLE_OFFSET_SQL_FUNC # define SQLITE_ENABLE_OFFSET_SQL_FUNC 1 #endif #ifndef SQLITE_ENABLE_RTREE # define SQLITE_ENABLE_RTREE 1 #endif //#ifndef SQLITE_ENABLE_SESSION //# define SQLITE_ENABLE_SESSION 1 //#endif #ifndef SQLITE_ENABLE_STMTVTAB |
︙ | ︙ | |||
101 102 103 104 105 106 107 | /**********************************************************************/ /* SQLITE_T... */ #ifndef SQLITE_TEMP_STORE # define SQLITE_TEMP_STORE 2 #endif #ifndef SQLITE_THREADSAFE | | | 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | /**********************************************************************/ /* SQLITE_T... */ #ifndef SQLITE_TEMP_STORE # define SQLITE_TEMP_STORE 2 #endif #ifndef SQLITE_THREADSAFE # define SQLITE_THREADSAFE 1 #endif /**********************************************************************/ /* SQLITE_USE_... */ #ifndef SQLITE_USE_URI # define SQLITE_USE_URI 1 #endif |
︙ | ︙ | |||
128 129 130 131 132 133 134 135 136 | #endif #define INC__STRINGIFY_(f) #f #define INC__STRINGIFY(f) INC__STRINGIFY_(f) #include INC__STRINGIFY(SQLITE_C) #undef INC__STRINGIFY_ #undef INC__STRINGIFY #undef SQLITE_C #include "sqlite3-jni.h" | > > > > < > | | | | | | | | | | < < | > | | > < > > > | | | | | > > | > > > | > > | > | | | | | | | < | | > > | | | | | | > | | | | | | | < | | > > | | | | | > > | | | > | | > | > | | | | < < < < < | | | | | | | | | | | > | | < < | | | | | | | | | | > > > > > > > > > > > > | | | | > | < | | > > > > > | > > > > > > > > > > > > > > > > > > > > > > > | | | > > > > > > > > > > > > > > > > > > > > > > > > | > > > > > > > > | > > > > > > > > > | > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | | | < | | | < < < < | < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < | < < < < < < < < < < < < < < < < < < | < < < < < < < < < < < < < < < < < < < < < < < < < < < | < < < < < < | < < < < < < < < < < < < | < < < > | < | | | | | > > | | | | | > > > > < > > > > | < < < < < > > | < < > | < < > > > > > > > > > > > > > > > < > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | | | 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 | #endif #define INC__STRINGIFY_(f) #f #define INC__STRINGIFY(f) INC__STRINGIFY_(f) #include INC__STRINGIFY(SQLITE_C) #undef INC__STRINGIFY_ #undef INC__STRINGIFY #undef SQLITE_C /* ** End of the sqlite3 lib setup. What follows is JNI-specific. */ #include "sqlite3-jni.h" #include <assert.h> #include <stdio.h> /* only for testing/debugging */ /* Only for debugging */ #define MARKER(pfexp) \ do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__); \ printf pfexp; \ } while(0) /* Creates a verbose JNI function name. */ #define JFuncName(Suffix) \ Java_org_sqlite_jni_SQLite3Jni_sqlite3_ ## Suffix /* Prologue for JNI functions. */ #define JDECL(ReturnType,Suffix) \ JNIEXPORT ReturnType JNICALL \ JFuncName(Suffix) /* ** Shortcuts for the first 2 parameters to all JNI bindings. ** ** The type of the jSelf arg differs, but no docs seem to mention ** this: for static methods it's of type jclass and for non-static ** it's jobject. jobject actually works for all funcs, in the sense ** that it compiles and runs so long as we don't use jSelf (which is ** only rarely needed in this code), but to be pedantically correct we ** need the proper type in the signature. ** ** https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/design.html#jni_interface_functions_and_pointers */ #define JENV_OSELF JNIEnv * const env, jobject jSelf #define JENV_CSELF JNIEnv * const env, jclass jKlazz /* ** Helpers to account for -Xcheck:jni warnings about not having ** checked for exceptions. */ #define IFTHREW if((*env)->ExceptionCheck(env)) #define EXCEPTION_CLEAR (*env)->ExceptionClear(env) #define EXCEPTION_REPORT (*env)->ExceptionDescribe(env) #define EXCEPTION_IGNORE IFTHREW EXCEPTION_CLEAR #define EXCEPTION_WARN_IGNORE \ IFTHREW {EXCEPTION_REPORT; EXCEPTION_CLEAR;}(void)0 #define EXCEPTION_WARN_CALLBACK_THREW(STR) \ MARKER(("WARNING: " STR " MUST NOT THROW.\n")); \ (*env)->ExceptionDescribe(env) #define IFTHREW_REPORT IFTHREW EXCEPTION_REPORT #define IFTHREW_CLEAR IFTHREW EXCEPTION_CLEAR /** To be used for cases where we're _really_ not expecting an exception, e.g. looking up well-defined Java class members. */ #define EXCEPTION_IS_FATAL(MSG) IFTHREW {\ EXCEPTION_REPORT; EXCEPTION_CLEAR; \ (*env)->FatalError(env, MSG); \ } /** Helpers for extracting pointers from jobjects, noting that the corresponding Java interfaces have already done the type-checking. */ #define PtrGet_sqlite3(OBJ) NativePointerHolder_get(env,OBJ,&S3NphRefs.sqlite3) #define PtrGet_sqlite3_stmt(OBJ) NativePointerHolder_get(env,OBJ,&S3NphRefs.sqlite3_stmt) #define PtrGet_sqlite3_value(OBJ) NativePointerHolder_get(env,OBJ,&S3NphRefs.sqlite3_value) #define PtrGet_sqlite3_context(OBJ) NativePointerHolder_get(env,OBJ,&S3NphRefs.sqlite3_context) /* Helpers for Java value reference management. */ static inline jobject new_global_ref(JNIEnv * const env, jobject const v){ return v ? (*env)->NewGlobalRef(env, v) : NULL; } static inline void delete_global_ref(JNIEnv * const env, jobject const v){ if(v) (*env)->DeleteGlobalRef(env, v); } static inline void delete_local_ref(JNIEnv * const env, jobject const v){ if(v) (*env)->DeleteLocalRef(env, v); } #define REF_G(VAR) new_global_ref(env, (VAR)) #define REF_L(VAR) (*env)->NewLocalRef(env, VAR) #define UNREF_G(VAR) delete_global_ref(env,(VAR)) #define UNREF_L(VAR) delete_local_ref(env,(VAR)) /** Keys for use with S3JniGlobal_nph_cache(). */ typedef struct S3NphRef S3NphRef; struct S3NphRef { const int index /* index into S3JniGlobal.nph[] */; const char * const zName /* Full Java name of the class */; }; /** Keys for each concrete NativePointerHolder subclass. These are to be used with S3JniGlobal_nph_cache() and friends. These are initialized on-demand by S3JniGlobal_nph_cache(). */ static const struct { const S3NphRef sqlite3; const S3NphRef sqlite3_stmt; const S3NphRef sqlite3_context; const S3NphRef sqlite3_value; const S3NphRef OutputPointer_Int32; const S3NphRef OutputPointer_Int64; const S3NphRef OutputPointer_sqlite3; const S3NphRef OutputPointer_sqlite3_stmt; const S3NphRef OutputPointer_sqlite3_value; #ifdef SQLITE_ENABLE_FTS5 const S3NphRef OutputPointer_String; const S3NphRef OutputPointer_ByteArray; const S3NphRef Fts5Context; const S3NphRef Fts5ExtensionApi; const S3NphRef fts5_api; const S3NphRef fts5_tokenizer; const S3NphRef Fts5Tokenizer; #endif } S3NphRefs = { #define NREF(INDEX, JAVANAME) { INDEX, "org/sqlite/jni/" JAVANAME } NREF(0, "sqlite3"), NREF(1, "sqlite3_stmt"), NREF(2, "sqlite3_context"), NREF(3, "sqlite3_value"), NREF(4, "OutputPointer$Int32"), NREF(5, "OutputPointer$Int64"), NREF(6, "OutputPointer$sqlite3"), NREF(7, "OutputPointer$sqlite3_stmt"), NREF(8, "OutputPointer$sqlite3_value"), #ifdef SQLITE_ENABLE_FTS5 NREF(9, "OutputPointer$String"), NREF(10, "OutputPointer$ByteArray"), NREF(11, "Fts5Context"), NREF(12, "Fts5ExtensionApi"), NREF(13, "fts5_api"), NREF(14, "fts5_tokenizer"), NREF(15, "Fts5Tokenizer") #endif #undef NREF }; /** Create a trivial JNI wrapper for (int CName(void)). */ #define WRAP_INT_VOID(JniNameSuffix,CName) \ JDECL(jint,JniNameSuffix)(JENV_CSELF){ \ return (jint)CName(); \ } /** Create a trivial JNI wrapper for (int CName(int)). */ #define WRAP_INT_INT(JniNameSuffix,CName) \ JDECL(jint,JniNameSuffix)(JENV_CSELF, jint arg){ \ return (jint)CName((int)arg); \ } /* ** Create a trivial JNI wrapper for (const mutf8_string * ** CName(void)). This is only valid for functions which are known to ** return ASCII or text which is equivalent in UTF-8 and MUTF-8. */ #define WRAP_MUTF8_VOID(JniNameSuffix,CName) \ JDECL(jstring,JniNameSuffix)(JENV_CSELF){ \ return (*env)->NewStringUTF( env, CName() ); \ } /** Create a trivial JNI wrapper for (int CName(sqlite3_stmt*)). */ #define WRAP_INT_STMT(JniNameSuffix,CName) \ JDECL(jint,JniNameSuffix)(JENV_CSELF, jobject jpStmt){ \ jint const rc = (jint)CName(PtrGet_sqlite3_stmt(jpStmt)); \ EXCEPTION_IGNORE /* squelch -Xcheck:jni */; \ return rc; \ } /** Create a trivial JNI wrapper for (int CName(sqlite3_stmt*,int)). */ #define WRAP_INT_STMT_INT(JniNameSuffix,CName) \ JDECL(jint,JniNameSuffix)(JENV_CSELF, jobject pStmt, jint n){ \ return (jint)CName(PtrGet_sqlite3_stmt(pStmt), (int)n); \ } /** Create a trivial JNI wrapper for (jstring CName(sqlite3_stmt*,int)). */ #define WRAP_STR_STMT_INT(JniNameSuffix,CName) \ JDECL(jstring,JniNameSuffix)(JENV_CSELF, jobject pStmt, jint ndx){ \ return s3jni_utf8_to_jstring(env, \ CName(PtrGet_sqlite3_stmt(pStmt), (int)ndx), \ -1); \ } /** Create a trivial JNI wrapper for (int CName(sqlite3*)). */ #define WRAP_INT_DB(JniNameSuffix,CName) \ JDECL(jint,JniNameSuffix)(JENV_CSELF, jobject pDb){ \ return (jint)CName(PtrGet_sqlite3(pDb)); \ } /** Create a trivial JNI wrapper for (int64 CName(sqlite3*)). */ #define WRAP_INT64_DB(JniNameSuffix,CName) \ JDECL(jlong,JniNameSuffix)(JENV_CSELF, jobject pDb){ \ return (jlong)CName(PtrGet_sqlite3(pDb)); \ } /** Create a trivial JNI wrapper for (int CName(sqlite3_value*)). */ #define WRAP_INT_SVALUE(JniNameSuffix,CName) \ JDECL(jint,JniNameSuffix)(JENV_CSELF, jobject jpSValue){ \ return (jint)CName(PtrGet_sqlite3_value(jpSValue)); \ } /* Helpers for jstring and jbyteArray. */ #define s3jni_jstring_to_mutf8(ARG) (*env)->GetStringUTFChars(env, ARG, NULL) #define s3jni_mutf8_release(ARG,VAR) if(VAR) (*env)->ReleaseStringUTFChars(env, ARG, VAR) #define s3jni_jbytearray_bytes(ARG) (*env)->GetByteArrayElements(env,ARG, NULL) #define s3jni_jbytearray_release(ARG,VAR) if(VAR) (*env)->ReleaseByteArrayElements(env, ARG, VAR, JNI_ABORT) enum { /* ** Size of the NativePointerHolder cache. Need enough space for ** (only) the library's NativePointerHolder types, a fixed count ** known at build-time. If we add more than this a fatal error will ** be triggered with a reminder to increase this. This value needs ** to be exactly the number of entries in the S3NphRefs object. The ** index field of those entries are the keys for this particular ** cache. */ NphCache_SIZE = sizeof(S3NphRefs) / sizeof(S3NphRef) }; /* ** Cache entry for NativePointerHolder subclasses and OutputPointer ** types. */ typedef struct S3JniNphClass S3JniNphClass; struct S3JniNphClass { volatile const S3NphRef * pRef /* Entry from S3NphRefs. */; jclass klazz /* global ref to the concrete ** NativePointerHolder subclass represented by ** zClassName */; volatile jmethodID midCtor /* klazz's no-arg constructor. Used by ** new_NativePointerHolder_object(). */; volatile jfieldID fidValue /* NativePointerHolder.nativePointer or ** OutputPointer.T.value */; volatile jfieldID fidAggCtx /* sqlite3_context::aggregateContext. Used only ** by the sqlite3_context binding. */; }; /** State for various hook callbacks. */ typedef struct S3JniHook S3JniHook; struct S3JniHook{ jobject jObj /* global ref to Java instance */; jmethodID midCallback /* callback method. Signature depends on ** jObj's type */; }; /* ** Per-(sqlite3*) state for various JNI bindings. This state is ** allocated as needed, cleaned up in sqlite3_close(_v2)(), and ** recycled when possible. */ typedef struct S3JniDb S3JniDb; struct S3JniDb { sqlite3 *pDb /* The associated db handle */; jobject jDb /* A global ref of the output object which gets returned from sqlite3_open(_v2)(). We need this in order to have an object to pass to routines like sqlite3_collation_needed()'s callback, or else we have to dynamically create one for that purpose, which would be fine except that it would be a different instance (and maybe even a different class) than the one the user may expect to receive. */; char * zMainDbName /* Holds the string allocated on behalf of SQLITE_DBCONFIG_MAINDBNAME. */; struct { S3JniHook busyHandler; S3JniHook collation; S3JniHook collationNeeded; S3JniHook commit; S3JniHook progress; S3JniHook rollback; S3JniHook trace; S3JniHook update; S3JniHook auth; #ifdef SQLITE_ENABLE_PREUPDATE_HOOK S3JniHook preUpdate; #endif } hooks; #ifdef SQLITE_ENABLE_FTS5 jobject jFtsApi /* global ref to s3jni_fts5_api_from_db() */; #endif S3JniDb * pNext /* Next entry in the available/free list */; S3JniDb * pPrev /* Previous entry in the available/free list */; }; /* ** Cache for per-JNIEnv (i.e. per-thread) data. */ typedef struct S3JniEnv S3JniEnv; struct S3JniEnv { JNIEnv *env /* env in which this cache entry was created */; /* ** pdbOpening is used to coordinate the Java/DB connection of a ** being-open()'d db in the face of auto-extensions. "The problem" ** is that auto-extensions run before we can bind the C db to its ** Java representation, but auto-extensions require that binding. We ** handle this as follows: ** ** - In the JNI side of sqlite3_open(), allocate the Java side of ** that connection and set pdbOpening to point to that ** object. ** ** - Call sqlite3_open(), which triggers the auto-extension ** handler. That handler uses pdbOpening to connect the native ** db handle which it receives with pdbOpening. ** ** - When sqlite3_open() returns, check whether pdbOpening->pDb is ** NULL. If it isn't, auto-extension handling set it up. If it ** is, complete the Java/C binding unless sqlite3_open() returns ** a NULL db, in which case free pdbOpening. */ S3JniDb * pdbOpening; S3JniEnv * pPrev /* Previous entry in the linked list */; S3JniEnv * pNext /* Next entry in the linked list */; }; /* ** State for proxying sqlite3_auto_extension() in Java. */ typedef struct S3JniAutoExtension S3JniAutoExtension; struct S3JniAutoExtension { jobject jObj /* Java object */; jmethodID midFunc /* xEntryPoint() callback */; }; /* ** If true, modifying S3JniGlobal.metrics is protected by a mutex, ** else it isn't. */ #ifdef SQLITE_DEBUG #define S3JNI_METRICS_MUTEX 1 #else #define S3JNI_METRICS_MUTEX 0 #endif /* ** Global state, e.g. caches and metrics. */ typedef struct S3JniGlobalType S3JniGlobalType; struct S3JniGlobalType { /* ** According to: https://developer.ibm.com/articles/j-jni/ ** ** > A thread can get a JNIEnv by calling GetEnv() using the JNI ** invocation interface through a JavaVM object. The JavaVM object ** itself can be obtained by calling the JNI GetJavaVM() method ** using a JNIEnv object and can be cached and shared across ** threads. Caching a copy of the JavaVM object enables any thread ** with access to the cached object to get access to its own ** JNIEnv when necessary. */ JavaVM * jvm; /* Cache of Java refs/IDs for NativePointerHolder subclasses. ** Initialized on demand. */ S3JniNphClass nph[NphCache_SIZE]; /* ** Cache of per-thread state. */ struct { S3JniEnv * aHead /* Linked list of in-use instances */; S3JniEnv * aFree /* Linked list of free instances */; sqlite3_mutex * mutex /* mutex for aHead and aFree as well for first-time inits of nph members. */; void const * locker /* env mutex is held on this object's behalf. Used only for sanity checking. */; } envCache; struct { S3JniDb * aUsed /* Linked list of in-use instances */; S3JniDb * aFree /* Linked list of free instances */; sqlite3_mutex * mutex /* mutex for aUsed and aFree */; void const * locker /* perDb mutex is held on this object's behalf. Unlike envCache.locker, we cannot always have this set to the current JNIEnv object. Used only for sanity checking. */; } perDb; #ifdef SQLITE_ENABLE_SQLLOG struct { S3JniHook sqllog /* sqlite3_config(SQLITE_CONFIG_SQLLOG) callback */; } hooks; #endif /* ** Refs to global classes and methods. Obtained during static init ** and never released. */ struct { jclass cObj /* global ref to java.lang.Object */; jclass cLong /* global ref to java.lang.Long */; jclass cString /* global ref to java.lang.String */; jobject oCharsetUtf8 /* global ref to StandardCharset.UTF_8 */; jmethodID ctorLong1 /* the Long(long) constructor */; jmethodID ctorStringBA /* the String(byte[],Charset) constructor */; jmethodID stringGetBytes /* the String.getBytes(Charset) method */; } g /* refs to global Java state */; #ifdef SQLITE_ENABLE_FTS5 struct { volatile jobject jFtsExt /* Global ref to Java singleton for the Fts5ExtensionApi instance. */; struct { jfieldID fidA /* Fts5Phrase::a member */; jfieldID fidB /* Fts5Phrase::b member */; } jPhraseIter; } fts5; #endif /* Internal metrics. */ struct { volatile unsigned envCacheHits; volatile unsigned envCacheMisses; volatile unsigned envCacheAllocs; volatile unsigned nMutexEnv /* number of times envCache.mutex was entered for a S3JniEnv operation. */; volatile unsigned nMutexEnv2 /* number of times envCache.mutex was entered for a S3JniNphClass operation. */; volatile unsigned nMutexPerDb /* number of times perDb.mutex was entered */; volatile unsigned nMutexAutoExt /* number of times autoExt.mutex was entered */; volatile unsigned nDestroy /* xDestroy() calls across all types */; volatile unsigned nPdbAlloc /* Number of S3JniDb alloced. */; volatile unsigned nPdbRecycled /* Number of S3JniDb reused. */; struct { /* Number of calls for each type of UDF callback. */ volatile unsigned nFunc; volatile unsigned nStep; volatile unsigned nFinal; volatile unsigned nValue; volatile unsigned nInverse; } udf; unsigned nMetrics /* Total number of mutex-locked metrics increments. */; #if S3JNI_METRICS_MUTEX sqlite3_mutex * mutex; #endif } metrics; /** The list of bound auto-extensions (Java-side: org.sqlite.jni.AutoExtension objects). */ struct { S3JniAutoExtension *pExt /* Head of the auto-extension list */; int nAlloc /* number of entries allocated for pExt, as distinct from the number of active entries. */; int nExt /* number of active entries in pExt. */; sqlite3_mutex * mutex /* mutex for manipulation/traversal of pExt */; } autoExt; }; static S3JniGlobalType S3JniGlobal = {}; #define SJG S3JniGlobal /* Increments *p, possibly protected by a mutex. */ #if S3JNI_METRICS_MUTEX static void s3jni_incr( volatile unsigned int * const p ){ sqlite3_mutex * const m = SJG.metrics.mutex; sqlite3_mutex_enter(m); ++SJG.metrics.nMetrics; ++(*p); sqlite3_mutex_leave(m); } #else #define s3jni_incr(PTR) ++(*(PTR)) #endif /* Helpers for working with specific mutexes. */ #define MUTEX_ENV_ASSERT_LOCKED \ assert( 0 != SJG.envCache.locker && "Misuse of S3JniGlobal.envCache.mutex" ) #define MUTEX_ENV_ASSERT_LOCKER \ assert( (env) == SJG.envCache.locker && "Misuse of S3JniGlobal.envCache.mutex" ) #define MUTEX_ENV_ASSERT_NOTLOCKER \ assert( (env) != SJG.envCache.locker && "Misuse of S3JniGlobal.envCache.mutex" ) #define MUTEX_ENV_ENTER \ MUTEX_ENV_ASSERT_NOTLOCKER; \ /*MARKER(("Entering ENV mutex@%p %s.\n", env));*/ \ sqlite3_mutex_enter( SJG.envCache.mutex ); \ ++SJG.metrics.nMutexEnv; \ SJG.envCache.locker = env #define MUTEX_ENV_LEAVE \ /*MARKER(("Leaving ENV mutex @%p %s.\n", env));*/ \ MUTEX_ENV_ASSERT_LOCKER; \ SJG.envCache.locker = 0; \ sqlite3_mutex_leave( SJG.envCache.mutex ) #define MUTEX_EXT_ENTER \ /*MARKER(("Entering autoExt mutex@%p %s.\n", env));*/ \ sqlite3_mutex_enter( SJG.autoExt.mutex ); \ ++SJG.metrics.nMutexAutoExt #define MUTEX_EXT_LEAVE \ /*MARKER(("Leaving autoExt mutex@%p %s.\n", env));*/ \ sqlite3_mutex_leave( SJG.autoExt.mutex ) #define MUTEX_NPH_ENTER \ MUTEX_ENV_ASSERT_NOTLOCKER; \ /*MARKER(("Entering NPH mutex@%p %s.\n", env));*/ \ sqlite3_mutex_enter( SJG.envCache.mutex ); \ ++SJG.metrics.nMutexEnv2; \ SJG.envCache.locker = env #define MUTEX_NPH_LEAVE \ /*MARKER(("Leaving NPH mutex @%p %s.\n", env));*/ \ MUTEX_ENV_ASSERT_LOCKER; \ SJG.envCache.locker = 0; \ sqlite3_mutex_leave( SJG.envCache.mutex ) #define MUTEX_PDB_ENTER \ /*MARKER(("Entering PerDb mutex@%p %s.\n", env));*/ \ sqlite3_mutex_enter( SJG.perDb.mutex ); \ ++SJG.metrics.nMutexPerDb; \ SJG.perDb.locker = env; #define MUTEX_PDB_LEAVE \ /*MARKER(("Leaving PerDb mutex@%p %s.\n", env));*/ \ SJG.perDb.locker = 0; \ sqlite3_mutex_leave( SJG.perDb.mutex ) #define s3jni_oom_check(VAR) if(!(VAR)) s3jni_oom(env) static inline void s3jni_oom(JNIEnv * const env){ (*env)->FatalError(env, "Out of memory.") /* does not return */; } /** sqlite3_malloc() proxy which fails fatally on OOM. This should only be used for routines which manage global state and have no recovery strategy for OOM. For sqlite3 API which can reasonably |
︙ | ︙ | |||
555 556 557 558 559 560 561 | /** Fetches the S3JniGlobal.envCache row for the given env, allocing a row if needed. When a row is allocated, its state is initialized insofar as possible. Calls (*env)->FatalError() if allocation of an entry fails. That's hypothetically possible but "shouldn't happen." */ | < | | > > | > | | | | < | < < | < | | < < < | < < < < < < < < < < < < < < < < < < < < < < < < < < < < < | > > > | | | | | > | > > > > > > > > > > > > > > > > | | | | | | | | | | | < | | | | | | | | | | | | | | | | | < | | | | | | | | | | | | | | | | | | | | < < < > | | | | | | | | | | | | | | | < | | > | < < | | | | < | > | | | | | | | | < | | < | < < < > | | | | | | | > > > < < < | | < < < < | < < < < < < < < < < < < < < < < < < | < | | < | < < < < < < < < < < < < < < < < < < < < | | | < < < | > > | > > | | | < < | | < < < < < < < | | < < < | | | | | < < | | | < | | < < | < < < < | < | | < < | < > > | < < < > | < < < < < > < < < < < < < < < | < < < | | | | | > > > > | | > > > | | | | | < < < < < < < < | < | < < < < < < < | | | | | | < | < < < < < < | | < < < < < < < > | | | | | > | | < < | > < | > | | | < > < < < < < < < < < < < < < | | < < | | > | | < | | | < < < < | < | | > > | | < < < < < < | | | | > | < < > > < | < < < < < < < < < < < < < < | < < < | | | < < < < < < < < | | | | | > > | | < < < < | < < < | | | > > | | | | | | < < < > > | < < < < | | | | | | | | | | | | | | | | | < | | | > | < < < < | < < < < < | < < < < > | < | | | | | | | > | | | | | | | | | < < | | > | < < < | | < < < > | > | | > | | > > | | > | | > > > > > | < | | > > > > > | | | | > > > > > > > > > > > > > > > > > > | | > | | | > > | | > < | | > > > > > > > > | < > < | > | > | | < < | < | < < < | < < < < < | < < < < < < < < < < < < < < < < < < < < < < < < < < < < | < > | > > > > > < > > > > > | | | | | | | | | | | | < < < | | < < > | < < < < | | < < < < < > < < | > | | | | | > > > < < > > < < | > | | < | 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 | /** Fetches the S3JniGlobal.envCache row for the given env, allocing a row if needed. When a row is allocated, its state is initialized insofar as possible. Calls (*env)->FatalError() if allocation of an entry fails. That's hypothetically possible but "shouldn't happen." */ static S3JniEnv * S3JniGlobal_env_cache(JNIEnv * const env){ struct S3JniEnv * row; MUTEX_ENV_ENTER; row = SJG.envCache.aHead; for( ; row; row = row->pNext ){ if( row->env == env ){ s3jni_incr( &SJG.metrics.envCacheHits ); MUTEX_ENV_LEAVE; return row; } } s3jni_incr( &SJG.metrics.envCacheMisses ); row = SJG.envCache.aFree; if( row ){ assert(!row->pPrev); SJG.envCache.aFree = row->pNext; if( row->pNext ) row->pNext->pPrev = 0; }else{ row = s3jni_malloc(env, sizeof(S3JniEnv)); s3jni_incr( &SJG.metrics.envCacheAllocs ); } memset(row, 0, sizeof(*row)); row->pNext = SJG.envCache.aHead; if(row->pNext) row->pNext->pPrev = row; SJG.envCache.aHead = row; row->env = env; MUTEX_ENV_LEAVE; return row; } /* ** This function is NOT part of the sqlite3 public API. It is strictly ** for use by the sqlite project's own Java/JNI bindings. ** ** For purposes of certain hand-crafted JNI function bindings, we ** need a way of reporting errors which is consistent with the rest of ** the C API, as opposed to throwing JS exceptions. To that end, this ** internal-use-only function is a thin proxy around ** sqlite3ErrorWithMessage(). The intent is that it only be used from ** JNI bindings such as sqlite3_prepare_v2/v3(), and definitely not ** from client code. ** ** Returns err_code. */ static int s3jni_db_error(sqlite3* const db, int err_code, const char * const zMsg){ if( db!=0 ){ if( 0==zMsg ){ sqlite3Error(db, err_code); }else{ const int nMsg = sqlite3Strlen30(zMsg); sqlite3_mutex_enter(sqlite3_db_mutex(db)); sqlite3ErrorWithMsg(db, err_code, "%.*s", nMsg, zMsg); sqlite3_mutex_leave(sqlite3_db_mutex(db)); } } return err_code; } /* ** Creates a new jByteArray of length nP, copies p's contents into it, and ** returns that byte array (NULL on OOM). */ static jbyteArray s3jni_new_jbyteArray(JNIEnv * const env, const unsigned char * const p, int nP){ jbyteArray jba = (*env)->NewByteArray(env, (jint)nP); if(jba){ (*env)->SetByteArrayRegion(env, jba, 0, (jint)nP, (const jbyte*)p); } return jba; } /* ** Returns the current JNIEnv object. Fails fatally if it cannot find ** it. */ static JNIEnv * s3jni_get_env(void){ JNIEnv * env = 0; if( (*SJG.jvm)->GetEnv(SJG.jvm, (void **)&env, JNI_VERSION_1_8) ){ fprintf(stderr, "Fatal error: cannot get current JNIEnv.\n"); abort(); } return env; } /* Declares local var env = s3jni_get_env(). */ #define LocalJniGetEnv JNIEnv * const env = s3jni_get_env() /* ** Uses the java.lang.String(byte[],Charset) constructor to create a ** new String from UTF-8 string z. n is the number of bytes to ** copy. If n<0 then sqlite3Strlen30() is used to calculate it. ** ** Returns NULL if z is NULL or on OOM, else returns a new jstring ** owned by the caller. ** ** Sidebar: this is a painfully inefficient way to convert from ** standard UTF-8 to a Java string, but JNI offers only algorithms for ** working with MUTF-8, not UTF-8. */ static jstring s3jni_utf8_to_jstring(JNIEnv * const env, const char * const z, int n){ jstring rv = NULL; if( 0==n || (n<0 && z && !z[0]) ){ /* Fast-track the empty-string case via the MUTF-8 API. We could hypothetically do this for any strings where n<4 and z is NUL-terminated and none of z[0..3] are NUL bytes. */ rv = (*env)->NewStringUTF(env, ""); }else if( z ){ jbyteArray jba; if( n<0 ) n = sqlite3Strlen30(z); jba = s3jni_new_jbyteArray(env, (unsigned const char *)z, (jsize)n); if( jba ){ rv = (*env)->NewObject(env, SJG.g.cString, SJG.g.ctorStringBA, jba, SJG.g.oCharsetUtf8); UNREF_L(jba); } } return rv; } /* ** Converts the given java.lang.String object into a NUL-terminated ** UTF-8 C-string by calling jstr.getBytes(StandardCharset.UTF_8). ** Returns NULL if jstr is NULL or on allocation error. If jstr is not ** NULL and nLen is not NULL then nLen is set to the length of the ** returned string, not including the terminating NUL. If jstr is not ** NULL and it returns NULL, this indicates an allocation error. In ** that case, if nLen is not NULL then it is either set to 0 (if ** fetching of jstr's bytes fails to allocate) or set to what would ** have been the length of the string had C-string allocation ** succeeded. ** ** The returned memory is allocated from sqlite3_malloc() and ** ownership is transferred to the caller. */ static char * s3jni_jstring_to_utf8(JNIEnv * const env, jstring jstr, int *nLen){ jbyteArray jba; jsize nBa; char *rv; if(!jstr) return 0; jba = (*env)->CallObjectMethod(env, jstr, SJG.g.stringGetBytes, SJG.g.oCharsetUtf8); if( (*env)->ExceptionCheck(env) || !jba /* order of these checks is significant for -Xlint:jni */ ) { EXCEPTION_REPORT; if( nLen ) *nLen = 0; return 0; } nBa = (*env)->GetArrayLength(env, jba); if( nLen ) *nLen = (int)nBa; rv = sqlite3_malloc( nBa + 1 ); if( rv ){ (*env)->GetByteArrayRegion(env, jba, 0, nBa, (jbyte*)rv); rv[nBa] = 0; } UNREF_L(jba); return rv; } /* ** Expects to be passed a pointer from sqlite3_column_text16() or ** sqlite3_value_text16() and a byte-length value from ** sqlite3_column_bytes16() or sqlite3_value_bytes16(). It creates a ** Java String of exactly half that character length, returning NULL ** if !p or (*env)->NewString() fails. */ static jstring s3jni_text16_to_jstring(JNIEnv * const env, const void * const p, int nP){ return p ? (*env)->NewString(env, (const jchar *)p, (jsize)(nP/2)) : NULL; } /* ** Requires jx to be a Throwable. Calls its toString() method and ** returns its value converted to a UTF-8 string. The caller owns the ** returned string and must eventually sqlite3_free() it. Returns 0 ** if there is a problem fetching the info or on OOM. ** ** Design note: we use toString() instead of getMessage() because the ** former includes the exception type's name: ** ** Exception e = new RuntimeException("Hi"); ** System.out.println(e.toString()); // java.lang.RuntimeException: Hi ** System.out.println(e.getMessage()); // Hi */ static char * s3jni_exception_error_msg(JNIEnv * const env, jthrowable jx ){ jmethodID mid; jstring msg; char * zMsg; jclass const klazz = (*env)->GetObjectClass(env, jx); mid = (*env)->GetMethodID(env, klazz, "toString", "()Ljava/lang/String;"); UNREF_L(klazz); IFTHREW{ EXCEPTION_REPORT; EXCEPTION_CLEAR; return 0; } msg = (*env)->CallObjectMethod(env, jx, mid); IFTHREW{ EXCEPTION_REPORT; EXCEPTION_CLEAR; return 0; } zMsg = s3jni_jstring_to_utf8(env, msg, 0); UNREF_L(msg); return zMsg; } /* ** Extracts the current JNI exception, sets ps->pDb's error message to ** its message string, and clears the exception. If errCode is non-0, ** it is used as-is, else SQLITE_ERROR is assumed. If there's a ** problem extracting the exception's message, it's treated as ** non-fatal and zDfltMsg is used in its place. ** ** This must only be called if a JNI exception is pending. ** ** Returns errCode unless it is 0, in which case SQLITE_ERROR is ** returned. */ static int s3jni_db_exception(JNIEnv * const env, S3JniDb * const ps, int errCode, const char *zDfltMsg){ jthrowable const ex = (*env)->ExceptionOccurred(env); if( 0==errCode ) errCode = SQLITE_ERROR; if( ex ){ char * zMsg; EXCEPTION_CLEAR; zMsg = s3jni_exception_error_msg(env, ex); s3jni_db_error(ps->pDb, errCode, zMsg ? zMsg : zDfltMsg); sqlite3_free(zMsg); UNREF_L(ex); } return errCode; } /* ** Extracts the (void xDestroy()) method from jObj and applies it to ** jObj. If jObj is NULL, this is a no-op. The lack of an xDestroy() ** method is silently ignored and any exceptions thrown by xDestroy() ** trigger a warning to stdout or stderr and then the exception is ** suppressed. */ static void s3jni_call_xDestroy(JNIEnv * const env, jobject jObj){ if(jObj){ jclass const klazz = (*env)->GetObjectClass(env, jObj); jmethodID method = (*env)->GetMethodID(env, klazz, "xDestroy", "()V"); UNREF_L(klazz); if(method){ s3jni_incr( &SJG.metrics.nDestroy ); (*env)->CallVoidMethod(env, jObj, method); IFTHREW{ EXCEPTION_WARN_CALLBACK_THREW("xDestroy() callback"); EXCEPTION_CLEAR; } }else{ /* Non-fatal. */ EXCEPTION_CLEAR; } } } /* ** Removes any Java references from s and clears its state. If ** doXDestroy is true and s->jObj is not NULL, s->jObj's ** s is passed to s3jni_call_xDestroy() before any references are ** cleared. It is legal to call this when the object has no Java ** references. */ static void S3JniHook_unref(JNIEnv * const env, S3JniHook * const s, int doXDestroy){ if(doXDestroy && s->jObj){ s3jni_call_xDestroy(env, s->jObj); } UNREF_G(s->jObj); memset(s, 0, sizeof(*s)); } /* ** Clears s's state and moves it to the free-list. */ static void S3JniDb_set_aside(JNIEnv * env, S3JniDb * const s){ if(s){ MUTEX_PDB_ENTER; assert(s->pPrev != s); assert(s->pNext != s); assert(s->pPrev ? (s->pPrev!=s->pNext) : 1); if(s->pNext) s->pNext->pPrev = s->pPrev; if(s->pPrev) s->pPrev->pNext = s->pNext; else if(SJG.perDb.aUsed == s){ assert(!s->pPrev); SJG.perDb.aUsed = s->pNext; } sqlite3_free( s->zMainDbName ); #define UNHOOK(MEMBER,XDESTROY) S3JniHook_unref(env, &s->hooks.MEMBER, XDESTROY) UNHOOK(trace, 0); UNHOOK(progress, 0); UNHOOK(commit, 0); UNHOOK(rollback, 0); UNHOOK(update, 0); UNHOOK(auth, 0); #ifdef SQLITE_ENABLE_PREUPDATE_HOOK UNHOOK(preUpdate, 0); #endif UNHOOK(collation, 1); UNHOOK(collationNeeded, 1); UNHOOK(busyHandler, 1); #undef UNHOOK UNREF_G(s->jDb); memset(s, 0, sizeof(S3JniDb)); s->pNext = SJG.perDb.aFree; if(s->pNext) s->pNext->pPrev = s; SJG.perDb.aFree = s; MUTEX_PDB_LEAVE; } } /* ** Uncache any state for the given JNIEnv, clearing all Java ** references the cache owns. Returns true if env was cached and false ** if it was not found in the cache. */ static int S3JniGlobal_env_uncache(JNIEnv * const env){ struct S3JniEnv * row; MUTEX_ENV_ASSERT_LOCKED; row = SJG.envCache.aHead; for( ; row; row = row->pNext ){ if( row->env == env ){ break; } } if( !row ){ return 0; } if( row->pNext ) row->pNext->pPrev = row->pPrev; if( row->pPrev ) row->pPrev->pNext = row->pNext; if( SJG.envCache.aHead == row ){ assert( !row->pPrev ); SJG.envCache.aHead = row->pNext; } memset(row, 0, sizeof(S3JniEnv)); row->pNext = SJG.envCache.aFree; if( row->pNext ) row->pNext->pPrev = row; SJG.envCache.aFree = row; return 1; } /* ** Searches the NativePointerHolder cache for the given combination of ** args. It returns a cache entry with its klazz member set. ** ** It is up to the caller to populate the other members of the ** returned object if needed, taking care to lock the population with ** MUTEX_NPH_ENTER/LEAVE. ** ** This simple cache catches >99% of searches in the current ** (2023-07-31) tests. */ static S3JniNphClass * S3JniGlobal_nph_cache(JNIEnv * const env, S3NphRef const* pRef){ /** According to: https://developer.ibm.com/articles/j-jni/ > ... the IDs returned for a given class don't change for the lifetime of the JVM process. But the call to get the field or method can require significant work in the JVM, because fields and methods might have been inherited from superclasses, making the JVM walk up the class hierarchy to find them. Because the IDs are the same for a given class, you should look them up once and then reuse them. Similarly, looking up class objects can be expensive, so they should be cached as well. */ S3JniNphClass * const pNC = &SJG.nph[pRef->index]; if( !pNC->pRef ){ MUTEX_NPH_ENTER; if( !pNC->pRef ){ pNC->pRef = pRef; pNC->klazz = (*env)->FindClass(env, pRef->zName); EXCEPTION_IS_FATAL("FindClass() unexpectedly threw"); pNC->klazz = REF_G(pNC->klazz); } MUTEX_NPH_LEAVE; } return pNC; } /* ** Returns the ID of the "nativePointer" field from the given ** NativePointerHolder<T> class. */ static jfieldID NativePointerHolder_getField(JNIEnv * const env, S3NphRef const* pRef){ S3JniNphClass * const pNC = S3JniGlobal_nph_cache(env, pRef); if(!pNC->fidValue){ MUTEX_NPH_ENTER; if(!pNC->fidValue){ pNC->fidValue = (*env)->GetFieldID(env, pNC->klazz, "nativePointer", "J"); EXCEPTION_IS_FATAL("Code maintenance required: missing nativePointer field."); } MUTEX_NPH_LEAVE; } return pNC->fidValue; } /* ** Sets a native ptr value in NativePointerHolder object ppOut. ** zClassName must be a static string so we can use its address ** as a cache key. */ static void NativePointerHolder_set(JNIEnv * env, jobject ppOut, const void * p, S3NphRef const* pRef){ (*env)->SetLongField(env, ppOut, NativePointerHolder_getField(env, pRef), (jlong)p); EXCEPTION_IS_FATAL("Could not set NativePointerHolder.nativePointer."); } /* ** Fetches a native ptr value from NativePointerHolder object ppOut. ** zClassName must be a static string so we can use its address as a ** cache key. This is a no-op if pObj is NULL. */ static void * NativePointerHolder_get(JNIEnv * env, jobject pObj, S3NphRef const* pRef){ if( pObj ){ void * rv = (void*)(*env)->GetLongField( env, pObj, NativePointerHolder_getField(env, pRef) ); EXCEPTION_IS_FATAL("Cannot fetch NativePointerHolder.nativePointer."); return rv; }else{ return 0; } } /* ** Extracts the new S3JniDb instance from the free-list, or allocates ** one if needed, associats it with pDb, and returns. Returns NULL on ** OOM. pDb MUST, on success of the calling operation, subsequently be ** associated with jDb via NativePointerHolder_set(). */ static S3JniDb * S3JniDb_alloc(JNIEnv * const env, sqlite3 *pDb, jobject jDb){ S3JniDb * rv; MUTEX_PDB_ENTER; if( SJG.perDb.aFree ){ rv = SJG.perDb.aFree; SJG.perDb.aFree = rv->pNext; assert(rv->pNext != rv); assert(rv->pPrev != rv); assert(rv->pPrev ? (rv->pPrev!=rv->pNext) : 1); if(rv->pNext){ assert(rv->pNext->pPrev == rv); assert(rv->pPrev ? (rv->pNext == rv->pPrev->pNext) : 1); rv->pNext->pPrev = 0; rv->pNext = 0; } s3jni_incr( &SJG.metrics.nPdbRecycled ); }else{ rv = s3jni_malloc(env, sizeof(S3JniDb)); if( rv ){ memset(rv, 0, sizeof(S3JniDb)); s3jni_incr( &SJG.metrics.nPdbAlloc ); } } if( rv ){ rv->pNext = SJG.perDb.aUsed; SJG.perDb.aUsed = rv; if(rv->pNext){ assert(!rv->pNext->pPrev); rv->pNext->pPrev = rv; } rv->jDb = REF_G(jDb); rv->pDb = pDb; } MUTEX_PDB_LEAVE; return rv; } /* ** Returns the S3JniDb object for the given db. ** ** The 3rd argument should normally only be non-0 for routines which ** are called from the C library and pass a native db handle instead of ** a Java handle. In normal usage, the 2nd argument is a Java-side sqlite3 ** object, from which the db is fished out. ** ** Returns NULL if jDb and pDb are both NULL or if there is no ** matching S3JniDb entry for pDb or the pointer fished out of jDb. */ static S3JniDb * S3JniDb_for_db(JNIEnv * const env, jobject jDb, sqlite3 *pDb){ S3JniDb * s = 0; if(jDb || pDb){ MUTEX_PDB_ENTER; s = SJG.perDb.aUsed; if(!pDb){ assert( jDb ); pDb = PtrGet_sqlite3(jDb); } for( ; pDb && s; s = s->pNext){ if(s->pDb == pDb){ break; } } MUTEX_PDB_LEAVE; } return s; } /* ** Unref any Java-side state in ax and zero out ax. */ static void S3JniAutoExtension_clear(JNIEnv * const env, S3JniAutoExtension * const ax){ if( ax->jObj ){ UNREF_G(ax->jObj); memset(ax, 0, sizeof(*ax)); } } /* ** Initializes a pre-allocated S3JniAutoExtension object. Returns ** non-0 if there is an error collecting the required state from ** jAutoExt (which must be an AutoExtension object). On error, it ** passes ax to S3JniAutoExtension_clear(). */ static int S3JniAutoExtension_init(JNIEnv *const env, S3JniAutoExtension * const ax, jobject const jAutoExt){ jclass const klazz = (*env)->GetObjectClass(env, jAutoExt); ax->midFunc = (*env)->GetMethodID(env, klazz, "xEntryPoint", "(Lorg/sqlite/jni/sqlite3;)I"); UNREF_L(klazz); EXCEPTION_WARN_IGNORE; if(!ax->midFunc){ MARKER(("Error getting xEntryPoint(sqlite3) from AutoExtension object.")); S3JniAutoExtension_clear(env, ax); return SQLITE_ERROR; } ax->jObj = REF_G(jAutoExt); return 0; } /* ** Requires that jCx be a Java-side sqlite3_context wrapper for pCx. ** This function calls sqlite3_aggregate_context() to allocate a tiny ** sliver of memory, the address of which is set in ** jCx->aggregateContext. The memory is only used as a key for ** mapping client-side results of aggregate result sets across ** calls to the UDF's callbacks. ** ** isFinal must be 1 for xFinal() calls and 0 for all others, the ** difference being that the xFinal() invocation will not allocate ** new memory if it was not already, resulting in a value of 0 ** for jCx->aggregateContext. ** ** Returns 0 on success. Returns SQLITE_NOMEM on allocation error, ** noting that it will not allocate when isFinal is true. It returns ** SQLITE_ERROR if there's a serious internal error in dealing with ** the JNI state. */ static int udf_setAggregateContext(JNIEnv * env, jobject jCx, sqlite3_context * pCx, int isFinal){ void * pAgg; int rc = 0; S3JniNphClass * const pNC = S3JniGlobal_nph_cache(env, &S3NphRefs.sqlite3_context); if(!pNC->fidAggCtx){ MUTEX_NPH_ENTER; if(!pNC->fidAggCtx){ pNC->fidAggCtx = (*env)->GetFieldID(env, pNC->klazz, "aggregateContext", "J"); EXCEPTION_IS_FATAL("Cannot get sqlite3_contex.aggregateContext member."); } MUTEX_NPH_LEAVE; } pAgg = sqlite3_aggregate_context(pCx, isFinal ? 0 : sizeof(void*)); if( pAgg || isFinal ){ (*env)->SetLongField(env, jCx, pNC->fidAggCtx, (jlong)pAgg); }else{ assert(!pAgg); rc = SQLITE_NOMEM; } return rc; } /* ** Common init for OutputPointer_set_Int32() and friends. pRef must be ** a pointer from S3NphRefs. jOut must be an instance of that ** class. If necessary, this fetches the jfieldID for jOut's [value] ** property, which must be of the type represented by the JNI type ** signature zTypeSig, and stores it in pRef's S3JniGlobal.nph entry. ** Fails fatally if the property is not found, as that presents a ** serious internal misuse. ** ** Property lookups are cached on a per-pRef basis. Do not use this ** routine with the same pRef but different zTypeSig: it will ** misbehave. */ static jfieldID setupOutputPointer(JNIEnv * const env, S3NphRef const * pRef, const char * const zTypeSig, jobject const jOut){ S3JniNphClass * const pNC = S3JniGlobal_nph_cache(env, pRef); if(!pNC->fidValue){ MUTEX_NPH_ENTER; if(!pNC->fidValue){ pNC->fidValue = (*env)->GetFieldID(env, pNC->klazz, "value", zTypeSig); EXCEPTION_IS_FATAL("setupOutputPointer() could not find OutputPointer.*.value"); } MUTEX_NPH_LEAVE; } return pNC->fidValue; } /* ** Sets the value property of the OutputPointer.Int32 jOut object to ** v. */ static void OutputPointer_set_Int32(JNIEnv * const env, jobject const jOut, int v){ jfieldID const setter = setupOutputPointer( env, &S3NphRefs.OutputPointer_Int32, "I", jOut ); (*env)->SetIntField(env, jOut, setter, (jint)v); EXCEPTION_IS_FATAL("Cannot set OutputPointer.Int32.value"); } /* ** Sets the value property of the OutputPointer.Int64 jOut object to ** v. */ static void OutputPointer_set_Int64(JNIEnv * const env, jobject const jOut, jlong v){ jfieldID const setter = setupOutputPointer( env, &S3NphRefs.OutputPointer_Int64, "J", jOut ); (*env)->SetLongField(env, jOut, setter, v); EXCEPTION_IS_FATAL("Cannot set OutputPointer.Int64.value"); } /* ** Sets the value property of the OutputPointer.sqlite3 jOut object to ** v. */ static void OutputPointer_set_sqlite3(JNIEnv * const env, jobject const jOut, jobject jDb){ jfieldID const setter = setupOutputPointer( env, &S3NphRefs.OutputPointer_sqlite3, "Lorg/sqlite/jni/sqlite3;", jOut ); (*env)->SetObjectField(env, jOut, setter, jDb); EXCEPTION_IS_FATAL("Cannot set OutputPointer.sqlite3.value"); } /* ** Sets the value property of the OutputPointer.sqlite3_stmt jOut object to ** v. */ static void OutputPointer_set_sqlite3_stmt(JNIEnv * const env, jobject const jOut, jobject jStmt){ jfieldID const setter = setupOutputPointer( env, &S3NphRefs.OutputPointer_sqlite3_stmt, "Lorg/sqlite/jni/sqlite3_stmt;", jOut ); (*env)->SetObjectField(env, jOut, setter, jStmt); EXCEPTION_IS_FATAL("Cannot set OutputPointer.sqlite3_stmt.value"); } #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* ** Sets the value property of the OutputPointer.sqlite3_value jOut object to ** v. */ static void OutputPointer_set_sqlite3_value(JNIEnv * const env, jobject const jOut, jobject jValue){ jfieldID const setter = setupOutputPointer( env, &S3NphRefs.OutputPointer_sqlite3_value, "Lorg/sqlite/jni/sqlite3_value;", jOut ); (*env)->SetObjectField(env, jOut, setter, jValue); EXCEPTION_IS_FATAL("Cannot set OutputPointer.sqlite3_value.value"); } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ #ifdef SQLITE_ENABLE_FTS5 #if 0 /* ** Sets the value property of the OutputPointer.ByteArray jOut object ** to v. */ static void OutputPointer_set_ByteArray(JNIEnv * const env, jobject const jOut, jbyteArray const v){ jfieldID const setter = setupOutputPointer( env, &S3NphRefs.OutputPointer_ByteArray, "[B", jOut ); (*env)->SetObjectField(env, jOut, setter, v); EXCEPTION_IS_FATAL("Cannot set OutputPointer.ByteArray.value"); } #endif /* ** Sets the value property of the OutputPointer.String jOut object to ** v. */ static void OutputPointer_set_String(JNIEnv * const env, jobject const jOut, jstring const v){ jfieldID const setter = setupOutputPointer( env, &S3NphRefs.OutputPointer_String, "Ljava/lang/String;", jOut ); (*env)->SetObjectField(env, jOut, setter, v); EXCEPTION_IS_FATAL("Cannot set OutputPointer.String.value"); } #endif /* SQLITE_ENABLE_FTS5 */ /* ** Returns true if eTextRep is a valid sqlite3 encoding constant, else ** returns false. */ static int encodingTypeIsValid(int eTextRep){ switch(eTextRep){ case SQLITE_UTF8: case SQLITE_UTF16: case SQLITE_UTF16LE: case SQLITE_UTF16BE: return 1; default: return 0; } } /* ** Proxy for Java-side Collation.xCompare() callbacks. */ static int CollationState_xCompare(void *pArg, int nLhs, const void *lhs, int nRhs, const void *rhs){ S3JniDb * const ps = pArg; LocalJniGetEnv; jint rc = 0; jbyteArray jbaLhs = (*env)->NewByteArray(env, (jint)nLhs); jbyteArray jbaRhs = jbaLhs ? (*env)->NewByteArray(env, (jint)nRhs) : NULL; if(!jbaRhs){ UNREF_L(jbaLhs); s3jni_db_error(ps->pDb, SQLITE_NOMEM, 0); return 0; } (*env)->SetByteArrayRegion(env, jbaLhs, 0, (jint)nLhs, (const jbyte*)lhs); (*env)->SetByteArrayRegion(env, jbaRhs, 0, (jint)nRhs, (const jbyte*)rhs); rc = (*env)->CallIntMethod(env, ps->hooks.collation.jObj, ps->hooks.collation.midCallback, jbaLhs, jbaRhs); EXCEPTION_IGNORE; UNREF_L(jbaLhs); UNREF_L(jbaRhs); return (int)rc; } /* Collation finalizer for use by the sqlite3 internals. */ static void CollationState_xDestroy(void *pArg){ S3JniDb * const ps = pArg; S3JniHook_unref( s3jni_get_env(), &ps->hooks.collation, 1 ); } /* ** State for sqlite3_result_java_object() and ** sqlite3_value_java_object(). ** ** TODO: this middle-man struct is no longer necessary. Conider ** removing it and passing around jObj itself instead. OTOH, we might ** find more state to pack in here. */ typedef struct { jobject jObj; } ResultJavaVal; /* For use with sqlite3_result/value_pointer() */ #define ResultJavaValuePtrStr "org.sqlite.jni.ResultJavaVal" /* ** Allocate a new ResultJavaVal and assign it a new global ref of ** jObj. Caller owns the returned object and must eventually pass it ** to ResultJavaVal_finalizer(). */ static ResultJavaVal * ResultJavaVal_alloc(JNIEnv * const env, jobject jObj){ ResultJavaVal * rv = sqlite3_malloc(sizeof(ResultJavaVal)); if(rv){ rv->jObj = jObj ? REF_G(jObj) : 0; } return rv; } /* ** If v is not NULL, it must point to a a ResultJavaVal object. Its ** object reference is relinquished and v is freed. */ static void ResultJavaVal_finalizer(void *v){ if(v){ ResultJavaVal * const rv = (ResultJavaVal*)v; LocalJniGetEnv; UNREF_G(rv->jObj); sqlite3_free(rv); } } /* ** Returns a new Java instance of the class named by zClassName, which ** MUST be interface-compatible with NativePointerHolder and MUST have ** a no-arg constructor. The NativePointerHolder_set() method is ** passed the new Java object and pNative. Hypothetically returns NULL ** if Java fails to allocate, but the JNI docs are not entirely clear ** on that detail. ** ** Always use a static pointer from the S3NphRefs struct for the 2nd ** argument so that we can use pRef->index as an O(1) cache key. */ static jobject new_NativePointerHolder_object(JNIEnv * const env, S3NphRef const * pRef, const void * pNative){ jobject rv = 0; S3JniNphClass * const pNC = S3JniGlobal_nph_cache(env, pRef); if(!pNC->midCtor){ MUTEX_NPH_ENTER; if(!pNC->midCtor){ pNC->midCtor = (*env)->GetMethodID(env, pNC->klazz, "<init>", "()V"); EXCEPTION_IS_FATAL("Cannot find constructor for class."); } MUTEX_NPH_LEAVE; } rv = (*env)->NewObject(env, pNC->klazz, pNC->midCtor); EXCEPTION_IS_FATAL("No-arg constructor threw."); s3jni_oom_check(rv); if(rv) NativePointerHolder_set(env, rv, pNative, pRef); return rv; } static inline jobject new_sqlite3_wrapper(JNIEnv * const env, sqlite3 *sv){ return new_NativePointerHolder_object(env, &S3NphRefs.sqlite3, sv); } static inline jobject new_sqlite3_context_wrapper(JNIEnv * const env, sqlite3_context *sv){ return new_NativePointerHolder_object(env, &S3NphRefs.sqlite3_context, sv); } static inline jobject new_sqlite3_stmt_wrapper(JNIEnv * const env, sqlite3_stmt *sv){ return new_NativePointerHolder_object(env, &S3NphRefs.sqlite3_stmt, sv); } static inline jobject new_sqlite3_value_wrapper(JNIEnv * const env, sqlite3_value *sv){ return new_NativePointerHolder_object(env, &S3NphRefs.sqlite3_value, sv); } /* ** Type IDs for SQL function categories. */ enum UDFType { UDF_SCALAR = 1, UDF_AGGREGATE, UDF_WINDOW, UDF_UNKNOWN_TYPE/*for error propagation*/ }; typedef void (*udf_xFunc_f)(sqlite3_context*,int,sqlite3_value**); typedef void (*udf_xStep_f)(sqlite3_context*,int,sqlite3_value**); typedef void (*udf_xFinal_f)(sqlite3_context*); /*typedef void (*udf_xValue_f)(sqlite3_context*);*/ /*typedef void (*udf_xInverse_f)(sqlite3_context*,int,sqlite3_value**);*/ /** State for binding Java-side UDFs. */ typedef struct S3JniUdf S3JniUdf; struct S3JniUdf { jobject jObj /* SQLFunction instance */; char * zFuncName /* Only for error reporting and debug logging */; enum UDFType type; /** Method IDs for the various UDF methods. */ jmethodID jmidxFunc; jmethodID jmidxStep; jmethodID jmidxFinal; jmethodID jmidxValue; jmethodID jmidxInverse; }; static S3JniUdf * S3JniUdf_alloc(JNIEnv * const env, jobject jObj){ S3JniUdf * const s = sqlite3_malloc(sizeof(S3JniUdf)); if(s){ const char * zFSI = /* signature for xFunc, xStep, xInverse */ "(Lorg/sqlite/jni/sqlite3_context;[Lorg/sqlite/jni/sqlite3_value;)V"; const char * zFV = /* signature for xFinal, xValue */ "(Lorg/sqlite/jni/sqlite3_context;)V"; jclass const klazz = (*env)->GetObjectClass(env, jObj); memset(s, 0, sizeof(S3JniUdf)); s->jObj = REF_G(jObj); #define FGET(FuncName,FuncType,Field) \ s->Field = (*env)->GetMethodID(env, klazz, FuncName, FuncType); \ if(!s->Field) (*env)->ExceptionClear(env) FGET("xFunc", zFSI, jmidxFunc); FGET("xStep", zFSI, jmidxStep); FGET("xFinal", zFV, jmidxFinal); FGET("xValue", zFV, jmidxValue); FGET("xInverse", zFSI, jmidxInverse); #undef FGET UNREF_L(klazz); if(s->jmidxFunc) s->type = UDF_SCALAR; else if(s->jmidxStep && s->jmidxFinal){ s->type = s->jmidxValue ? UDF_WINDOW : UDF_AGGREGATE; }else{ s->type = UDF_UNKNOWN_TYPE; } } return s; } static void S3JniUdf_free(S3JniUdf * s){ LocalJniGetEnv; if(env){ //MARKER(("UDF cleanup: %s\n", s->zFuncName)); s3jni_call_xDestroy(env, s->jObj); UNREF_G(s->jObj); } sqlite3_free(s->zFuncName); sqlite3_free(s); } static void S3JniUdf_finalizer(void * s){ //MARKER(("UDF finalizer @ %p\n", s)); |
︙ | ︙ | |||
1697 1698 1699 1700 1701 1702 1703 | jobjectArray jargv; } udf_jargs; /** Converts the given (cx, argc, argv) into arguments for the given UDF, placing the result in the final argument. Returns 0 on success, SQLITE_NOMEM on allocation error. | < < < < | > > > > > > > > > > | > | | | > > > > | > > > | < | > > | | | < | | | > > > > > > > | | | | | | | | | > | < > | | | | | | > | | | > > | > | > | > | > | | | > > > > > > > > > > > > > > | < | | < | > | < | < < | < > | < < | < < | | < < < | > | | > > > > > > > | | > > > > > > | | | | | | | | | | < < < | > | < > < | > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | | > > > | > > | < < < > | < < < < < < | | | | < < < < < < | | < < | | > | | | < < | | > > > > > > > | | < > | | | | | | | < | | > | | > | < < | | < < | | > > > > | | | > > > > > > | > > | < < | < | < > | | | > < < < < | | | < | < | | | | < | | | | < | | > < < < < < | | < < | | | | | < | | | | > | 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 | jobjectArray jargv; } udf_jargs; /** Converts the given (cx, argc, argv) into arguments for the given UDF, placing the result in the final argument. Returns 0 on success, SQLITE_NOMEM on allocation error. */ static int udf_args(JNIEnv *env, sqlite3_context * const cx, int argc, sqlite3_value**argv, jobject * jCx, jobjectArray *jArgv){ jobjectArray ja = 0; jobject jcx = new_sqlite3_context_wrapper(env, cx); jint i; *jCx = 0; *jArgv = 0; if(!jcx) goto error_oom; ja = (*env)->NewObjectArray(env, argc, SJG.g.cObj, NULL); if(!ja) goto error_oom; for(i = 0; i < argc; ++i){ jobject jsv = new_sqlite3_value_wrapper(env, argv[i]); if(!jsv) goto error_oom; (*env)->SetObjectArrayElement(env, ja, i, jsv); UNREF_L(jsv)/*array has a ref*/; } *jCx = jcx; *jArgv = ja; return 0; error_oom: sqlite3_result_error_nomem(cx); UNREF_L(jcx); UNREF_L(ja); return SQLITE_NOMEM; } /* ** Must be called immediately after a Java-side UDF callback throws. ** If translateToErr is true then it sets the exception's message in ** the result error using sqlite3_result_error(). If translateToErr is ** false then it emits a warning that the function threw but should ** not do so. In either case, it clears the exception state. ** ** Returns SQLITE_NOMEM if an allocation fails, else SQLITE_ERROR. In ** the latter case it calls sqlite3_result_error_nomem(). */ static int udf_report_exception(JNIEnv * const env, int translateToErr, sqlite3_context * cx, const char *zFuncName, const char *zFuncType ){ jthrowable const ex = (*env)->ExceptionOccurred(env); int rc = SQLITE_ERROR; assert(ex && "This must only be called when a Java exception is pending."); if( translateToErr ){ char * zMsg; char * z; EXCEPTION_CLEAR; zMsg = s3jni_exception_error_msg(env, ex); z = sqlite3_mprintf("Client-defined SQL function %s.%s() threw: %s", zFuncName ? zFuncName : "<unnamed>", zFuncType, zMsg ? zMsg : "Unknown exception" ); sqlite3_free(zMsg); if( z ){ sqlite3_result_error(cx, z, -1); sqlite3_free(z); }else{ sqlite3_result_error_nomem(cx); rc = SQLITE_NOMEM; } }else{ MARKER(("Client-defined SQL function %s.%s() threw. " "It should not do that.\n", zFuncName ? zFuncName : "<unnamed>", zFuncType)); (*env)->ExceptionDescribe( env ); EXCEPTION_CLEAR; } return rc; } /* ** Sets up the state for calling a Java-side xFunc/xStep/xInverse() ** UDF, calls it, and returns 0 on success. */ static int udf_xFSI(sqlite3_context* const pCx, int argc, sqlite3_value** const argv, S3JniUdf * const s, jmethodID xMethodID, const char * const zFuncType){ LocalJniGetEnv; udf_jargs args = {0,0}; int rc = udf_args(env, pCx, argc, argv, &args.jcx, &args.jargv); //MARKER(("UDF::%s.%s()\n", s->zFuncName, zFuncType)); if(rc) return rc; if( UDF_SCALAR != s->type ){ rc = udf_setAggregateContext(env, args.jcx, pCx, 0); } if( 0 == rc ){ (*env)->CallVoidMethod(env, s->jObj, xMethodID, args.jcx, args.jargv); IFTHREW{ rc = udf_report_exception(env, 'F'==zFuncType[1]/*xFunc*/, pCx, s->zFuncName, zFuncType); } } UNREF_L(args.jcx); UNREF_L(args.jargv); return rc; } /* ** Sets up the state for calling a Java-side xFinal/xValue() UDF, ** calls it, and returns 0 on success. */ static int udf_xFV(sqlite3_context* cx, S3JniUdf * s, jmethodID xMethodID, const char *zFuncType){ LocalJniGetEnv; jobject jcx = new_sqlite3_context_wrapper(env, cx); int rc = 0; int const isFinal = 'F'==zFuncType[1]/*xFinal*/; //MARKER(("%s.%s() cx = %p\n", s->zFuncName, zFuncType, cx)); if(!jcx){ if( isFinal ) sqlite3_result_error_nomem(cx); return SQLITE_NOMEM; } //MARKER(("UDF::%s.%s()\n", s->zFuncName, zFuncType)); if( UDF_SCALAR != s->type ){ rc = udf_setAggregateContext(env, jcx, cx, isFinal); } if( 0 == rc ){ (*env)->CallVoidMethod(env, s->jObj, xMethodID, jcx); IFTHREW{ rc = udf_report_exception(env, isFinal, cx, s->zFuncName, zFuncType); } } UNREF_L(jcx); return rc; } /* Proxy for C-to-Java xFunc. */ static void udf_xFunc(sqlite3_context* cx, int argc, sqlite3_value** argv){ S3JniUdf * const s = (S3JniUdf*)sqlite3_user_data(cx); s3jni_incr( &SJG.metrics.udf.nFunc ); udf_xFSI(cx, argc, argv, s, s->jmidxFunc, "xFunc"); } /* Proxy for C-to-Java xStep. */ static void udf_xStep(sqlite3_context* cx, int argc, sqlite3_value** argv){ S3JniUdf * const s = (S3JniUdf*)sqlite3_user_data(cx); s3jni_incr( &SJG.metrics.udf.nStep ); udf_xFSI(cx, argc, argv, s, s->jmidxStep, "xStep"); } /* Proxy for C-to-Java xFinal. */ static void udf_xFinal(sqlite3_context* cx){ S3JniUdf * const s = (S3JniUdf*)sqlite3_user_data(cx); s3jni_incr( &SJG.metrics.udf.nFinal ); udf_xFV(cx, s, s->jmidxFinal, "xFinal"); } /* Proxy for C-to-Java xValue. */ static void udf_xValue(sqlite3_context* cx){ S3JniUdf * const s = (S3JniUdf*)sqlite3_user_data(cx); s3jni_incr( &SJG.metrics.udf.nValue ); udf_xFV(cx, s, s->jmidxValue, "xValue"); } /* Proxy for C-to-Java xInverse. */ static void udf_xInverse(sqlite3_context* cx, int argc, sqlite3_value** argv){ S3JniUdf * const s = (S3JniUdf*)sqlite3_user_data(cx); s3jni_incr( &SJG.metrics.udf.nInverse ); udf_xFSI(cx, argc, argv, s, s->jmidxInverse, "xInverse"); } //////////////////////////////////////////////////////////////////////// // What follows is the JNI/C bindings. They are in alphabetical order // except for this macro-generated subset which are kept together // (alphabetized) here at the front... //////////////////////////////////////////////////////////////////////// WRAP_INT_STMT(1bind_1parameter_1count, sqlite3_bind_parameter_count) WRAP_INT_DB(1changes, sqlite3_changes) WRAP_INT64_DB(1changes64, sqlite3_changes64) WRAP_INT_STMT(1clear_1bindings, sqlite3_clear_bindings) WRAP_INT_STMT_INT(1column_1bytes, sqlite3_column_bytes) WRAP_INT_STMT_INT(1column_1bytes16, sqlite3_column_bytes16) WRAP_INT_STMT(1column_1count, sqlite3_column_count) WRAP_STR_STMT_INT(1column_1decltype, sqlite3_column_decltype) WRAP_STR_STMT_INT(1column_1name, sqlite3_column_name) WRAP_STR_STMT_INT(1column_1database_1name, sqlite3_column_database_name) WRAP_STR_STMT_INT(1column_1origin_1name, sqlite3_column_origin_name) WRAP_STR_STMT_INT(1column_1table_1name, sqlite3_column_table_name) WRAP_INT_STMT_INT(1column_1type, sqlite3_column_type) WRAP_INT_STMT(1data_1count, sqlite3_data_count) WRAP_INT_DB(1error_1offset, sqlite3_error_offset) WRAP_INT_DB(1extended_1errcode, sqlite3_extended_errcode) WRAP_MUTF8_VOID(1libversion, sqlite3_libversion) WRAP_INT_VOID(1libversion_1number, sqlite3_libversion_number) #ifdef SQLITE_ENABLE_PREUPDATE_HOOK WRAP_INT_DB(1preupdate_1blobwrite, sqlite3_preupdate_blobwrite) WRAP_INT_DB(1preupdate_1count, sqlite3_preupdate_count) WRAP_INT_DB(1preupdate_1depth, sqlite3_preupdate_depth) #endif WRAP_INT_INT(1sleep, sqlite3_sleep) WRAP_MUTF8_VOID(1sourceid, sqlite3_sourceid) WRAP_INT_VOID(1threadsafe, sqlite3_threadsafe) WRAP_INT_DB(1total_1changes, sqlite3_total_changes) WRAP_INT64_DB(1total_1changes64, sqlite3_total_changes64) WRAP_INT_SVALUE(1value_1bytes, sqlite3_value_bytes) WRAP_INT_SVALUE(1value_1bytes16, sqlite3_value_bytes16) WRAP_INT_SVALUE(1value_1encoding, sqlite3_value_encoding) WRAP_INT_SVALUE(1value_1frombind, sqlite3_value_frombind) WRAP_INT_SVALUE(1value_1nochange, sqlite3_value_nochange) WRAP_INT_SVALUE(1value_1numeric_1type, sqlite3_value_numeric_type) WRAP_INT_SVALUE(1value_1subtype, sqlite3_value_subtype) WRAP_INT_SVALUE(1value_1type, sqlite3_value_type) #undef WRAP_INT64_DB #undef WRAP_INT_DB #undef WRAP_INT_INT #undef WRAP_INT_STMT #undef WRAP_INT_STMT_INT #undef WRAP_INT_SVALUE #undef WRAP_INT_VOID #undef WRAP_MUTF8_VOID #undef WRAP_STR_STMT_INT /* Central auto-extension handler. */ static int s3jni_run_java_auto_extensions(sqlite3 *pDb, const char **pzErr, const struct sqlite3_api_routines *ignored){ int rc = 0; unsigned i, go = 1; JNIEnv * env = 0; S3JniDb * ps; S3JniEnv * jc; if( 0==SJG.autoExt.nExt ) return 0; env = s3jni_get_env(); jc = S3JniGlobal_env_cache(env); ps = jc->pdbOpening; if( !ps ){ MARKER(("Unexpected arrival of null S3JniDb in auto-extension runner.\n")); *pzErr = sqlite3_mprintf("Unexpected arrival of null S3JniDb in auto-extension runner."); return SQLITE_ERROR; } jc->pdbOpening = 0; assert( !ps->pDb && "it's still being opened" ); ps->pDb = pDb; assert( ps->jDb ); NativePointerHolder_set(env, ps->jDb, pDb, &S3NphRefs.sqlite3); for( i = 0; go && 0==rc; ++i ){ S3JniAutoExtension ax = {0,0} /* We need a copy of the auto-extension object, with our own ** local reference to it, to avoid a race condition with another ** thread manipulating the list during the call and invaliding ** what ax points to. */; MUTEX_EXT_ENTER; if( i >= SJG.autoExt.nExt ){ go = 0; }else{ ax.jObj = REF_L(SJG.autoExt.pExt[i].jObj); ax.midFunc = SJG.autoExt.pExt[i].midFunc; } MUTEX_EXT_LEAVE; if( ax.jObj ){ rc = (*env)->CallIntMethod(env, ax.jObj, ax.midFunc, ps->jDb); IFTHREW { jthrowable const ex = (*env)->ExceptionOccurred(env); char * zMsg; EXCEPTION_CLEAR; zMsg = s3jni_exception_error_msg(env, ex); UNREF_L(ex); *pzErr = sqlite3_mprintf("auto-extension threw: %s", zMsg); sqlite3_free(zMsg); if( !rc ) rc = SQLITE_ERROR; } UNREF_L(ax.jObj); } } return rc; } JDECL(jint,1auto_1extension)(JENV_CSELF, jobject jAutoExt){ static int once = 0; int i; S3JniAutoExtension * ax; int rc = 0; if( !jAutoExt ) return SQLITE_MISUSE; MUTEX_EXT_ENTER; for( i = 0; i < SJG.autoExt.nExt; ++i ){ /* Look for match or first empty slot. */ ax = &SJG.autoExt.pExt[i]; if( ax->jObj && (*env)->IsSameObject(env, ax->jObj, jAutoExt) ){ MUTEX_EXT_LEAVE; return 0 /* this as a no-op. */; } } if(i == SJG.autoExt.nExt ){ assert( SJG.autoExt.nExt <= SJG.autoExt.nAlloc ); if( SJG.autoExt.nExt == SJG.autoExt.nAlloc ){ unsigned n = 1 + SJG.autoExt.nAlloc; S3JniAutoExtension * const aNew = sqlite3_realloc( SJG.autoExt.pExt, n * sizeof(S3JniAutoExtension) ); if( !aNew ){ rc = SQLITE_NOMEM; }else{ SJG.autoExt.pExt = aNew; ++SJG.autoExt.nAlloc; } } if( 0==rc ){ ax = &SJG.autoExt.pExt[SJG.autoExt.nExt]; rc = S3JniAutoExtension_init(env, ax, jAutoExt); assert( rc ? 0==ax->jObj : 0!=ax->jObj ); } } if( 0==rc ){ if( 0==once && ++once ){ rc = sqlite3_auto_extension( (void(*)(void))s3jni_run_java_auto_extensions ); if( rc ){ assert( ax ); S3JniAutoExtension_clear(env, ax); } } if( 0==rc ){ ++SJG.autoExt.nExt; } } MUTEX_EXT_LEAVE; return rc; } JDECL(jint,1bind_1blob)(JENV_CSELF, jobject jpStmt, jint ndx, jbyteArray baData, jint nMax){ jbyte * const pBuf = baData ? s3jni_jbytearray_bytes(baData) : 0; int const rc = sqlite3_bind_blob(PtrGet_sqlite3_stmt(jpStmt), (int)ndx, pBuf, (int)nMax, SQLITE_TRANSIENT); s3jni_jbytearray_release(baData,pBuf); return (jint)rc; } JDECL(jint,1bind_1double)(JENV_CSELF, jobject jpStmt, jint ndx, jdouble val){ return (jint)sqlite3_bind_double(PtrGet_sqlite3_stmt(jpStmt), (int)ndx, (double)val); } JDECL(jint,1bind_1int)(JENV_CSELF, jobject jpStmt, jint ndx, jint val){ return (jint)sqlite3_bind_int(PtrGet_sqlite3_stmt(jpStmt), (int)ndx, (int)val); } JDECL(jint,1bind_1int64)(JENV_CSELF, jobject jpStmt, jint ndx, jlong val){ return (jint)sqlite3_bind_int64(PtrGet_sqlite3_stmt(jpStmt), (int)ndx, (sqlite3_int64)val); } JDECL(jint,1bind_1null)(JENV_CSELF, jobject jpStmt, jint ndx){ return (jint)sqlite3_bind_null(PtrGet_sqlite3_stmt(jpStmt), (int)ndx); } JDECL(jint,1bind_1parameter_1index)(JENV_CSELF, jobject jpStmt, jbyteArray jName){ int rc = 0; jbyte * const pBuf = s3jni_jbytearray_bytes(jName); if(pBuf){ rc = sqlite3_bind_parameter_index(PtrGet_sqlite3_stmt(jpStmt), (const char *)pBuf); s3jni_jbytearray_release(jName, pBuf); } return rc; } JDECL(jint,1bind_1text)(JENV_CSELF, jobject jpStmt, jint ndx, jbyteArray baData, jint nMax){ jbyte * const pBuf = baData ? s3jni_jbytearray_bytes(baData) : 0; int const rc = sqlite3_bind_text(PtrGet_sqlite3_stmt(jpStmt), (int)ndx, (const char *)pBuf, (int)nMax, SQLITE_TRANSIENT); s3jni_jbytearray_release(baData, pBuf); return (jint)rc; } JDECL(jint,1bind_1text16)(JENV_CSELF, jobject jpStmt, jint ndx, jbyteArray baData, jint nMax){ jbyte * const pBuf = baData ? s3jni_jbytearray_bytes(baData) : 0; int const rc = sqlite3_bind_text16(PtrGet_sqlite3_stmt(jpStmt), (int)ndx, pBuf, (int)nMax, SQLITE_TRANSIENT); s3jni_jbytearray_release(baData, pBuf); return (jint)rc; } JDECL(jint,1bind_1zeroblob)(JENV_CSELF, jobject jpStmt, jint ndx, jint n){ return (jint)sqlite3_bind_zeroblob(PtrGet_sqlite3_stmt(jpStmt), (int)ndx, (int)n); } JDECL(jint,1bind_1zeroblob64)(JENV_CSELF, jobject jpStmt, jint ndx, jlong n){ return (jint)sqlite3_bind_zeroblob(PtrGet_sqlite3_stmt(jpStmt), (int)ndx, (sqlite3_uint64)n); } /* Central C-to-Java busy handler proxy. */ static int s3jni_busy_handler(void* pState, int n){ S3JniDb * const ps = (S3JniDb *)pState; int rc = 0; if( ps->hooks.busyHandler.jObj ){ LocalJniGetEnv; rc = (*env)->CallIntMethod(env, ps->hooks.busyHandler.jObj, ps->hooks.busyHandler.midCallback, (jint)n); IFTHREW{ EXCEPTION_WARN_CALLBACK_THREW("sqlite3_busy_handler() callback"); rc = s3jni_db_exception(env, ps, SQLITE_ERROR, "sqlite3_busy_handler() callback threw."); } } return rc; } JDECL(jint,1busy_1handler)(JENV_CSELF, jobject jDb, jobject jBusy){ S3JniDb * const ps = S3JniDb_for_db(env, jDb, 0); int rc = 0; if(!ps) return (jint)SQLITE_NOMEM; if(jBusy){ S3JniHook * const pHook = &ps->hooks.busyHandler; if(pHook->jObj && (*env)->IsSameObject(env, pHook->jObj, jBusy)){ /* Same object - this is a no-op. */ return 0; } jclass klazz; S3JniHook_unref(env, pHook, 1); pHook->jObj = REF_G(jBusy); klazz = (*env)->GetObjectClass(env, jBusy); pHook->midCallback = (*env)->GetMethodID(env, klazz, "xCallback", "(I)I"); UNREF_L(klazz); IFTHREW { S3JniHook_unref(env, pHook, 0); rc = SQLITE_ERROR; } if(rc){ return rc; } }else{ S3JniHook_unref(env, &ps->hooks.busyHandler, 1); } return jBusy ? sqlite3_busy_handler(ps->pDb, s3jni_busy_handler, ps) : sqlite3_busy_handler(ps->pDb, 0, 0); } JDECL(jint,1busy_1timeout)(JENV_CSELF, jobject jDb, jint ms){ S3JniDb * const ps = S3JniDb_for_db(env, jDb, 0); if( ps ){ S3JniHook_unref(env, &ps->hooks.busyHandler, 1); return sqlite3_busy_timeout(ps->pDb, (int)ms); } return SQLITE_MISUSE; } JDECL(jboolean,1cancel_1auto_1extension)(JENV_CSELF, jobject jAutoExt){ S3JniAutoExtension * ax; jboolean rc = JNI_FALSE; int i; MUTEX_EXT_ENTER; /* This algo mirrors the one in the core. */ for( i = SJG.autoExt.nExt-1; i >= 0; --i ){ ax = &SJG.autoExt.pExt[i]; if( ax->jObj && (*env)->IsSameObject(env, ax->jObj, jAutoExt) ){ S3JniAutoExtension_clear(env, ax); /* Move final entry into this slot. */ --SJG.autoExt.nExt; *ax = SJG.autoExt.pExt[SJG.autoExt.nExt]; memset(&SJG.autoExt.pExt[SJG.autoExt.nExt], 0, sizeof(S3JniAutoExtension)); assert(! SJG.autoExt.pExt[SJG.autoExt.nExt].jObj ); rc = JNI_TRUE; break; } } MUTEX_EXT_LEAVE; return rc; } /* Wrapper for sqlite3_close(_v2)(). */ static jint s3jni_close_db(JNIEnv * const env, jobject jDb, int version){ int rc = 0; S3JniDb * ps = 0; assert(version == 1 || version == 2); ps = S3JniDb_for_db(env, jDb, 0); if(ps){ rc = 1==version ? (jint)sqlite3_close(ps->pDb) : (jint)sqlite3_close_v2(ps->pDb); if( 0==rc ){ S3JniDb_set_aside(env, ps) /* MUST come after close() because of ps->trace. */; NativePointerHolder_set(env, jDb, 0, &S3NphRefs.sqlite3); } } return (jint)rc; } JDECL(jint,1close_1v2)(JENV_CSELF, jobject pDb){ return s3jni_close_db(env, pDb, 2); } JDECL(jint,1close)(JENV_CSELF, jobject pDb){ return s3jni_close_db(env, pDb, 1); } /* ** Assumes z is an array of unsigned short and returns the index in ** that array of the first element with the value 0. */ static unsigned int s3jni_utf16_strlen(void const * z){ unsigned int i = 0; const unsigned short * p = z; while( p[i] ) ++i; return i; } /* Central C-to-Java sqlite3_collation_needed16() hook impl. */ static void s3jni_collation_needed_impl16(void *pState, sqlite3 *pDb, int eTextRep, const void * z16Name){ S3JniDb * const ps = pState; LocalJniGetEnv; unsigned int const nName = s3jni_utf16_strlen(z16Name); jstring jName = (*env)->NewString(env, (jchar const *)z16Name, nName); IFTHREW{ s3jni_db_error(ps->pDb, SQLITE_NOMEM, 0); EXCEPTION_CLEAR; }else{ (*env)->CallVoidMethod(env, ps->hooks.collationNeeded.jObj, ps->hooks.collationNeeded.midCallback, ps->jDb, (jint)eTextRep, jName); IFTHREW{ s3jni_db_exception(env, ps, 0, "sqlite3_collation_needed() callback threw"); } UNREF_L(jName); } } JDECL(jint,1collation_1needed)(JENV_CSELF, jobject jDb, jobject jHook){ S3JniDb * const ps = S3JniDb_for_db(env, jDb, 0); jclass klazz; jobject pOld = 0; jmethodID xCallback; S3JniHook * const pHook = &ps->hooks.collationNeeded; int rc; if( !ps ) return SQLITE_MISUSE; pOld = pHook->jObj; if(pOld && jHook && (*env)->IsSameObject(env, pOld, jHook)){ return 0; } if( !jHook ){ UNREF_G(pOld); memset(pHook, 0, sizeof(S3JniHook)); sqlite3_collation_needed(ps->pDb, 0, 0); return 0; } klazz = (*env)->GetObjectClass(env, jHook); xCallback = (*env)->GetMethodID(env, klazz, "xCollationNeeded", "(Lorg/sqlite/jni/sqlite3;ILjava/lang/String;)I"); UNREF_L(klazz); IFTHREW { rc = s3jni_db_exception(env, ps, SQLITE_MISUSE, "Cannot not find matching callback on " "collation-needed hook object."); }else{ pHook->midCallback = xCallback; pHook->jObj = REF_G(jHook); UNREF_G(pOld); rc = sqlite3_collation_needed16(ps->pDb, ps, s3jni_collation_needed_impl16); } return rc; } JDECL(jbyteArray,1column_1blob)(JENV_CSELF, jobject jpStmt, jint ndx){ sqlite3_stmt * const pStmt = PtrGet_sqlite3_stmt(jpStmt); void const * const p = sqlite3_column_blob(pStmt, (int)ndx); int const n = p ? sqlite3_column_bytes(pStmt, (int)ndx) : 0; if( 0==p ) return NULL; else{ jbyteArray const jba = (*env)->NewByteArray(env, n); (*env)->SetByteArrayRegion(env, jba, 0, n, (const jbyte *)p); return jba; } } JDECL(jdouble,1column_1double)(JENV_CSELF, jobject jpStmt, jint ndx){ return (jdouble)sqlite3_column_double(PtrGet_sqlite3_stmt(jpStmt), (int)ndx); } JDECL(jint,1column_1int)(JENV_CSELF, jobject jpStmt, jint ndx){ return (jint)sqlite3_column_int(PtrGet_sqlite3_stmt(jpStmt), (int)ndx); } JDECL(jlong,1column_1int64)(JENV_CSELF, jobject jpStmt, jint ndx){ return (jlong)sqlite3_column_int64(PtrGet_sqlite3_stmt(jpStmt), (int)ndx); } JDECL(jbyteArray,1column_1text_1utf8)(JENV_CSELF, jobject jpStmt, jint ndx){ sqlite3_stmt * const stmt = PtrGet_sqlite3_stmt(jpStmt); const int n = sqlite3_column_bytes(stmt, (int)ndx); const unsigned char * const p = sqlite3_column_text(stmt, (int)ndx); return p ? s3jni_new_jbyteArray(env, p, n) : NULL; } JDECL(jstring,1column_1text16)(JENV_CSELF, jobject jpStmt, jint ndx){ sqlite3_stmt * const stmt = PtrGet_sqlite3_stmt(jpStmt); const int n = sqlite3_column_bytes16(stmt, (int)ndx); const void * const p = sqlite3_column_text16(stmt, (int)ndx); return s3jni_text16_to_jstring(env, p, n); } JDECL(jobject,1column_1value)(JENV_CSELF, jobject jpStmt, jint ndx){ sqlite3_value * const sv = sqlite3_column_value(PtrGet_sqlite3_stmt(jpStmt), (int)ndx); return new_sqlite3_value_wrapper(env, sv); } static int s3jni_commit_rollback_hook_impl(int isCommit, S3JniDb * const ps){ LocalJniGetEnv; int rc = isCommit ? (int)(*env)->CallIntMethod(env, ps->hooks.commit.jObj, ps->hooks.commit.midCallback) : (int)((*env)->CallVoidMethod(env, ps->hooks.rollback.jObj, ps->hooks.rollback.midCallback), 0); IFTHREW{ EXCEPTION_CLEAR; rc = s3jni_db_error(ps->pDb, SQLITE_ERROR, "hook callback threw."); } return rc; } static int s3jni_commit_hook_impl(void *pP){ return s3jni_commit_rollback_hook_impl(1, pP); } static void s3jni_rollback_hook_impl(void *pP){ (void)s3jni_commit_rollback_hook_impl(0, pP); } static jobject s3jni_commit_rollback_hook(int isCommit, JNIEnv * const env, jobject jDb, jobject jHook){ S3JniDb * const ps = S3JniDb_for_db(env, jDb, 0); jclass klazz; jobject pOld = 0; jmethodID xCallback; S3JniHook * const pHook = isCommit ? &ps->hooks.commit : &ps->hooks.rollback; if(!ps){ s3jni_db_error(ps->pDb, SQLITE_NOMEM, 0); return 0; } pOld = pHook->jObj; if(pOld && jHook && (*env)->IsSameObject(env, pOld, jHook)){ |
︙ | ︙ | |||
2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 | else sqlite3_rollback_hook(ps->pDb, 0, 0); return pOld; } klazz = (*env)->GetObjectClass(env, jHook); xCallback = (*env)->GetMethodID(env, klazz, isCommit ? "xCommitHook" : "xRollbackHook", isCommit ? "()I" : "()V"); IFTHREW { EXCEPTION_REPORT; EXCEPTION_CLEAR; s3jni_db_error(ps->pDb, SQLITE_ERROR, "Cannot not find matching callback on " "hook object."); }else{ | > | 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 | else sqlite3_rollback_hook(ps->pDb, 0, 0); return pOld; } klazz = (*env)->GetObjectClass(env, jHook); xCallback = (*env)->GetMethodID(env, klazz, isCommit ? "xCommitHook" : "xRollbackHook", isCommit ? "()I" : "()V"); UNREF_L(klazz); IFTHREW { EXCEPTION_REPORT; EXCEPTION_CLEAR; s3jni_db_error(ps->pDb, SQLITE_ERROR, "Cannot not find matching callback on " "hook object."); }else{ |
︙ | ︙ | |||
2339 2340 2341 2342 2343 2344 2345 | JDECL(jobject,1commit_1hook)(JENV_CSELF,jobject jDb, jobject jHook){ return s3jni_commit_rollback_hook(1, env, jDb, jHook); } JDECL(jstring,1compileoption_1get)(JENV_CSELF, jint n){ | | > | | > > > > > > > > > > > > > > | > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | < < > > | | | > | | | < | | | | | | 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 | JDECL(jobject,1commit_1hook)(JENV_CSELF,jobject jDb, jobject jHook){ return s3jni_commit_rollback_hook(1, env, jDb, jHook); } JDECL(jstring,1compileoption_1get)(JENV_CSELF, jint n){ return (*env)->NewStringUTF( env, sqlite3_compileoption_get(n) ) /* We know these to be ASCII, so MUTF-8 is fine. */; } JDECL(jboolean,1compileoption_1used)(JENV_CSELF, jstring name){ const char *zUtf8 = s3jni_jstring_to_mutf8(name); const jboolean rc = 0==sqlite3_compileoption_used(zUtf8) ? JNI_FALSE : JNI_TRUE; s3jni_mutf8_release(name, zUtf8); return rc; } /* ** sqlite3_config(SQLITE_CONFIG_...) wrapper for a small subset of ** options. */ JDECL(jint,1config__I)(JENV_CSELF, jint n){ switch(n){ case SQLITE_CONFIG_SINGLETHREAD: case SQLITE_CONFIG_MULTITHREAD: case SQLITE_CONFIG_SERIALIZED: return sqlite3_config( n ); default: return SQLITE_MISUSE; } } #ifdef SQLITE_ENABLE_SQLLOG /* C-to-Java SQLITE_CONFIG_SQLLOG wrapper. */ static void s3jni_config_sqllog(void *ignored, sqlite3 *pDb, const char *z, int op){ jobject jArg0 = 0; jstring jArg1 = 0; LocalJniGetEnv; S3JniDb * const ps = S3JniDb_for_db(env, 0, pDb); S3JniHook * const hook = &SJG.hooks.sqllog; if( !ps || !hook->jObj ) return; jArg0 = REF_L(ps->jDb); switch(op){ case 0: /* db opened */ case 1: /* SQL executed */ jArg1 = s3jni_utf8_to_jstring(env, z, -1); break; case 2: /* db closed */ break; default: (*env)->FatalError(env, "Unhandled 4th arg to SQLITE_CONFIG_SQLLOG."); break; } (*env)->CallVoidMethod(env, hook->jObj, hook->midCallback, jArg0, jArg1, op); IFTHREW{ EXCEPTION_WARN_CALLBACK_THREW("SQLITE_CONFIG_SQLLOG callback"); EXCEPTION_CLEAR; } UNREF_L(jArg0); UNREF_L(jArg1); } //! Requirement of SQLITE_CONFIG_SQLLOG. void sqlite3_init_sqllog(void){ sqlite3_config( SQLITE_CONFIG_SQLLOG, s3jni_config_sqllog, 0 ); } #endif /* sqlite3_config(SQLITE_CONFIG_SQLLOG) wrapper. */ JDECL(jint,1config__Lorg_sqlite_jni_SQLLog_2)(JENV_CSELF, jobject jLog){ #ifdef SQLITE_ENABLE_SQLLOG S3JniHook tmpHook; S3JniHook * const hook = &tmpHook; S3JniHook * const hookOld = & SJG.hooks.sqllog; jclass klazz; int rc = 0; if( !jLog ){ S3JniHook_unref(env, hookOld, 0); return 0; } if( hookOld->jObj && (*env)->IsSameObject(env, jLog, hookOld->jObj) ){ return 0; } klazz = (*env)->GetObjectClass(env, jLog); hook->midCallback = (*env)->GetMethodID(env, klazz, "xSqllog", "(Lorg/sqlite/jni/sqlite3;" "Ljava/lang/String;" "I)V"); UNREF_L(klazz); if( !hook->midCallback ){ EXCEPTION_WARN_IGNORE; S3JniHook_unref(env, hook, 0); return SQLITE_ERROR; } hook->jObj = REF_G(jLog); rc = sqlite3_config( SQLITE_CONFIG_SQLLOG, s3jni_config_sqllog, 0 ); if( rc ){ S3JniHook_unref(env, hook, 0); }else{ S3JniHook_unref(env, hookOld, 0); *hookOld = *hook; } return rc; #else MARKER(("Warning: built without SQLITE_ENABLE_SQLLOG.\n")); return SQLITE_MISUSE; #endif } JDECL(jobject,1context_1db_1handle)(JENV_CSELF, jobject jpCx){ sqlite3 * const pDb = sqlite3_context_db_handle(PtrGet_sqlite3_context(jpCx)); S3JniDb * const ps = pDb ? S3JniDb_for_db(env, 0, pDb) : 0; return ps ? ps->jDb : 0; } JDECL(jint,1create_1collation)(JENV_CSELF, jobject jDb, jstring name, jint eTextRep, jobject oCollation){ int rc; const char *zName; jclass klazz; S3JniDb * const ps = S3JniDb_for_db(env, jDb, 0); S3JniHook * const pHook = ps ? &ps->hooks.collation : 0; if( !pHook ) return SQLITE_MISUSE; klazz = (*env)->GetObjectClass(env, oCollation); pHook->midCallback = (*env)->GetMethodID(env, klazz, "xCompare", "([B[B)I"); UNREF_L(klazz); IFTHREW{ UNREF_L(klazz); return s3jni_db_error(ps->pDb, SQLITE_ERROR, "Could not get xCompare() method for object."); } zName = s3jni_jstring_to_mutf8(name); rc = sqlite3_create_collation_v2(ps->pDb, zName, (int)eTextRep, ps, CollationState_xCompare, CollationState_xDestroy); s3jni_mutf8_release(name, zName); if( 0==rc ){ pHook->jObj = REF_G(oCollation); }else{ S3JniHook_unref(env, pHook, 1); } return (jint)rc; } JDECL(jint,1create_1function)(JENV_CSELF, jobject jDb, jstring jFuncName, jint nArg, jint eTextRep, jobject jFunctor){ S3JniUdf * s = 0; int rc; sqlite3 * const pDb = PtrGet_sqlite3(jDb); char * zFuncName = 0; if( !encodingTypeIsValid(eTextRep) ){ return s3jni_db_error(pDb, SQLITE_FORMAT, "Invalid function encoding option."); } s = S3JniUdf_alloc(env, jFunctor); if( !s ) return SQLITE_NOMEM; else if( UDF_UNKNOWN_TYPE==s->type ){ rc = s3jni_db_error(pDb, SQLITE_MISUSE, "Cannot unambiguously determine function type."); S3JniUdf_free(s); goto error_cleanup; } zFuncName = s3jni_jstring_to_utf8(env,jFuncName,0); if(!zFuncName){ rc = SQLITE_NOMEM; S3JniUdf_free(s); goto error_cleanup; } if( UDF_WINDOW == s->type ){ rc = sqlite3_create_window_function(pDb, zFuncName, nArg, eTextRep, s, |
︙ | ︙ | |||
2432 2433 2434 2435 2436 2437 2438 | assert( UDF_AGGREGATE == s->type ); xStep = udf_xStep; xFinal = udf_xFinal; } rc = sqlite3_create_function_v2(pDb, zFuncName, nArg, eTextRep, s, xFunc, xStep, xFinal, S3JniUdf_finalizer); } | < < < < < < | | > < < < < < | | < > | | > > | | 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 | assert( UDF_AGGREGATE == s->type ); xStep = udf_xStep; xFinal = udf_xFinal; } rc = sqlite3_create_function_v2(pDb, zFuncName, nArg, eTextRep, s, xFunc, xStep, xFinal, S3JniUdf_finalizer); } error_cleanup: sqlite3_free(zFuncName); /* on sqlite3_create_function() error, s will be destroyed via ** create_function(), so we're not leaking s. */ return (jint)rc; } /* sqlite3_db_config() for (int,const char *) */ JDECL(int,1db_1config__Lorg_sqlite_jni_sqlite3_2ILjava_lang_String_2)( JENV_CSELF, jobject jDb, jint op, jstring jStr ){ S3JniDb * const ps = S3JniDb_for_db(env, jDb, 0); int rc; char *zStr; switch( (ps && jStr) ? op : 0 ){ case SQLITE_DBCONFIG_MAINDBNAME: zStr = s3jni_jstring_to_utf8(env, jStr, 0); if( zStr ){ rc = sqlite3_db_config(ps->pDb, (int)op, zStr); if( rc ){ sqlite3_free( zStr ); }else{ sqlite3_free( ps->zMainDbName ); ps->zMainDbName = zStr; } }else{ rc = SQLITE_NOMEM; } break; default: rc = SQLITE_MISUSE; } return rc; } /* sqlite3_db_config() for (int,int*) */ /* ** ACHTUNG: openjdk v19 creates a different mangled name for this ** function than openjdk v8 does. We account for that by exporting ** both versions of the name. */ JDECL(jint,1db_1config__Lorg_sqlite_jni_sqlite3_2IILorg_sqlite_jni_OutputPointer_Int32_2)( JENV_CSELF, jobject jDb, jint op, jint onOff, jobject jOut ){ S3JniDb * const ps = S3JniDb_for_db(env, jDb, 0); int rc; switch( ps ? op : 0 ){ case SQLITE_DBCONFIG_ENABLE_FKEY: case SQLITE_DBCONFIG_ENABLE_TRIGGER: case SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER: case SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION: case SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE: |
︙ | ︙ | |||
2519 2520 2521 2522 2523 2524 2525 | } default: rc = SQLITE_MISUSE; } return (jint)rc; } | | | | | | | < | | | 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 | } default: rc = SQLITE_MISUSE; } return (jint)rc; } /* ** This is a workaround for openjdk v19 (and possibly others) encoding ** this function's name differently than JDK v8 does. If we do not ** install both names for this function then Java will not be able to ** find the function in both environments. */ JDECL(jint,1db_1config__Lorg_sqlite_jni_sqlite3_2IILorg_sqlite_jni_OutputPointer_00024Int32_2)( JENV_CSELF, jobject jDb, jint op, jint onOff, jobject jOut ){ return JFuncName(1db_1config__Lorg_sqlite_jni_sqlite3_2IILorg_sqlite_jni_OutputPointer_Int32_2)( env, jKlazz, jDb, op, onOff, jOut ); } JDECL(jstring,1db_1filename)(JENV_CSELF, jobject jDb, jstring jDbName){ S3JniDb * const ps = S3JniDb_for_db(env, jDb, 0); char *zDbName; jstring jRv = 0; int nStr = 0; if( !ps || !jDbName ){ return 0; } zDbName = s3jni_jstring_to_utf8(env, jDbName, &nStr); if( zDbName ){ char const * zRv = sqlite3_db_filename(ps->pDb, zDbName); sqlite3_free(zDbName); if( zRv ){ jRv = s3jni_utf8_to_jstring(env, zRv, -1); } } return jRv; } JDECL(jint,1db_1status)(JENV_CSELF, jobject jDb, jint op, jobject jOutCurrent, |
︙ | ︙ | |||
2575 2576 2577 2578 2579 2580 2581 | JDECL(jint,1errcode)(JENV_CSELF, jobject jpDb){ sqlite3 * const pDb = PtrGet_sqlite3(jpDb); return pDb ? sqlite3_errcode(pDb) : SQLITE_MISUSE; } JDECL(jstring,1errmsg)(JENV_CSELF, jobject jpDb){ sqlite3 * const pDb = PtrGet_sqlite3(jpDb); | < | | | < | | | 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 | JDECL(jint,1errcode)(JENV_CSELF, jobject jpDb){ sqlite3 * const pDb = PtrGet_sqlite3(jpDb); return pDb ? sqlite3_errcode(pDb) : SQLITE_MISUSE; } JDECL(jstring,1errmsg)(JENV_CSELF, jobject jpDb){ sqlite3 * const pDb = PtrGet_sqlite3(jpDb); return pDb ? s3jni_utf8_to_jstring(env, sqlite3_errmsg(pDb), -1) : 0; } JDECL(jstring,1errstr)(JENV_CSELF, jint rcCode){ return (*env)->NewStringUTF(env, sqlite3_errstr((int)rcCode)) /* We know these values to be plain ASCII, so pose no MUTF-8 ** incompatibility */; } JDECL(jstring,1expanded_1sql)(JENV_CSELF, jobject jpStmt){ sqlite3_stmt * const pStmt = PtrGet_sqlite3_stmt(jpStmt); jstring rv = 0; if( pStmt ){ char * zSql = sqlite3_expanded_sql(pStmt); s3jni_oom_check(zSql); if( zSql ){ rv = s3jni_utf8_to_jstring(env, zSql, -1); sqlite3_free(zSql); } } return rv; } JDECL(jboolean,1extended_1result_1codes)(JENV_CSELF, jobject jpDb, |
︙ | ︙ | |||
2615 2616 2617 2618 2619 2620 2621 | } JDECL(jint,1finalize)(JENV_CSELF, jobject jpStmt){ int rc = 0; sqlite3_stmt * const pStmt = PtrGet_sqlite3_stmt(jpStmt); if( pStmt ){ rc = sqlite3_finalize(pStmt); | | > > > > > > > > > > > > > > | | | > > | > > > | | > > > | | | > | < < | > > > | < | | | | | | | | | | | | > | < < < | < < < < | < | | > > > | < | < > | < < | < < | < | | < < < | < | | 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 | } JDECL(jint,1finalize)(JENV_CSELF, jobject jpStmt){ int rc = 0; sqlite3_stmt * const pStmt = PtrGet_sqlite3_stmt(jpStmt); if( pStmt ){ rc = sqlite3_finalize(pStmt); NativePointerHolder_set(env, jpStmt, 0, &S3NphRefs.sqlite3_stmt); } return rc; } JDECL(void,1interrupt)(JENV_CSELF, jobject jpDb){ sqlite3 * const pDb = PtrGet_sqlite3(jpDb); if( pDb ) sqlite3_interrupt(pDb); } JDECL(jboolean,1is_1interrupted)(JENV_CSELF, jobject jpDb){ int rc = 0; sqlite3 * const pDb = PtrGet_sqlite3(jpDb); if( pDb ){ rc = sqlite3_is_interrupted(pDb); } return rc ? JNI_TRUE : JNI_FALSE; } JDECL(jlong,1last_1insert_1rowid)(JENV_CSELF, jobject jpDb){ return (jlong)sqlite3_last_insert_rowid(PtrGet_sqlite3(jpDb)); } /* Pre-open() code common to sqlite3_open(_v2)(). */ static int s3jni_open_pre(JNIEnv * const env, S3JniEnv **jc, jstring jDbName, char **zDbName, S3JniDb ** ps){ int rc = 0; jobject jDb = 0; *jc = S3JniGlobal_env_cache(env); if(!*jc){ rc = SQLITE_NOMEM; goto end; } *zDbName = jDbName ? s3jni_jstring_to_utf8(env, jDbName, 0) : 0; if(jDbName && !*zDbName){ rc = SQLITE_NOMEM; goto end; } jDb = new_sqlite3_wrapper(env, 0); if( !jDb ){ sqlite3_free(*zDbName); *zDbName = 0; rc = SQLITE_NOMEM; goto end; } *ps = S3JniDb_alloc(env, 0, jDb); if(*ps){ (*jc)->pdbOpening = *ps; }else{ UNREF_L(jDb); rc = SQLITE_NOMEM; } end: return rc; } /* ** Post-open() code common to both the sqlite3_open() and ** sqlite3_open_v2() bindings. ps->jDb must be the ** org.sqlite.jni.sqlite3 object which will hold the db's native ** pointer. theRc must be the result code of the open() op. If ** *ppDb is NULL then ps is set aside and its state cleared, ** else ps is associated with *ppDb. If *ppDb is not NULL then ** ps->jDb is stored in jOut (an OutputPointer.sqlite3 instance). ** ** Returns theRc. */ static int s3jni_open_post(JNIEnv * const env, S3JniEnv * const jc, S3JniDb * ps, sqlite3 **ppDb, jobject jOut, int theRc){ jc->pdbOpening = 0; if(*ppDb){ assert(ps->jDb); if( 0==ps->pDb ){ ps->pDb = *ppDb; NativePointerHolder_set(env, ps->jDb, *ppDb, &S3NphRefs.sqlite3); }else{ assert( ps->pDb == *ppDb /* set up via s3jni_run_java_auto_extensions() */); } }else{ S3JniDb_set_aside(env, ps); ps = 0; } OutputPointer_set_sqlite3(env, jOut, ps ? ps->jDb : 0); return theRc; } JDECL(jint,1open)(JENV_CSELF, jstring strName, jobject jOut){ sqlite3 * pOut = 0; char *zName = 0; S3JniDb * ps = 0; S3JniEnv * jc = 0; int rc; rc = s3jni_open_pre(env, &jc, strName, &zName, &ps); if( 0==rc ){ rc = sqlite3_open(zName, &pOut); rc = s3jni_open_post(env, jc, ps, &pOut, jOut, rc); assert(rc==0 ? pOut!=0 : 1); sqlite3_free(zName); } return (jint)rc; } JDECL(jint,1open_1v2)(JENV_CSELF, jstring strName, jobject jOut, jint flags, jstring strVfs){ sqlite3 * pOut = 0; char *zName = 0; S3JniDb * ps = 0; S3JniEnv * jc = 0; char *zVfs = 0; int rc = s3jni_open_pre(env, &jc, strName, &zName, &ps); if( 0==rc && strVfs ){ zVfs = s3jni_jstring_to_utf8(env, strVfs, 0); if( !zVfs ){ rc = SQLITE_NOMEM; } } if( 0==rc ){ rc = sqlite3_open_v2(zName, &pOut, (int)flags, zVfs); } rc = s3jni_open_post(env, jc, ps, &pOut, jOut, rc); assert(rc==0 ? pOut!=0 : 1); sqlite3_free(zName); sqlite3_free(zVfs); return (jint)rc; } /* Proxy for the sqlite3_prepare[_v2/3]() family. */ static jint sqlite3_jni_prepare_v123(int prepVersion, JNIEnv * const env, jclass self, jobject jDb, jbyteArray baSql, jint nMax, jint prepFlags, jobject jOutStmt, jobject outTail){ sqlite3_stmt * pStmt = 0; jobject jStmt = 0; const char * zTail = 0; jbyte * const pBuf = s3jni_jbytearray_bytes(baSql); int rc = SQLITE_ERROR; assert(prepVersion==1 || prepVersion==2 || prepVersion==3); if( !pBuf ){ rc = baSql ? SQLITE_MISUSE : SQLITE_NOMEM; goto end; } jStmt = new_sqlite3_stmt_wrapper(env, 0); |
︙ | ︙ | |||
2770 2771 2772 2773 2774 2775 2776 | (int)nMax, (unsigned int)prepFlags, &pStmt, &zTail); break; default: assert(0 && "Invalid prepare() version"); } end: | | | > | | | 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 | (int)nMax, (unsigned int)prepFlags, &pStmt, &zTail); break; default: assert(0 && "Invalid prepare() version"); } end: s3jni_jbytearray_release(baSql,pBuf); if( 0==rc ){ if( 0!=outTail ){ /* Noting that pBuf is deallocated now but its address is all we need for ** what follows... */ assert(zTail ? ((void*)zTail>=(void*)pBuf) : 1); assert(zTail ? (((int)((void*)zTail - (void*)pBuf)) >= 0) : 1); OutputPointer_set_Int32(env, outTail, (int)(zTail ? (zTail - (const char *)pBuf) : 0)); } if( pStmt ){ NativePointerHolder_set(env, jStmt, pStmt, &S3NphRefs.sqlite3_stmt); }else{ /* Happens for comments and whitespace. */ UNREF_L(jStmt); jStmt = 0; } }else{ UNREF_L(jStmt); jStmt = 0; } |
︙ | ︙ | |||
2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 | } JDECL(jint,1prepare_1v3)(JNIEnv * const env, jclass self, jobject jDb, jbyteArray baSql, jint nMax, jint prepFlags, jobject jOutStmt, jobject outTail){ return sqlite3_jni_prepare_v123(3, env, self, jDb, baSql, nMax, prepFlags, jOutStmt, outTail); } static int s3jni_progress_handler_impl(void *pP){ S3JniDb * const ps = (S3JniDb *)pP; | > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | | | | | | > | | | < < | > > > | | | > > | | < > > > | | 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 | } JDECL(jint,1prepare_1v3)(JNIEnv * const env, jclass self, jobject jDb, jbyteArray baSql, jint nMax, jint prepFlags, jobject jOutStmt, jobject outTail){ return sqlite3_jni_prepare_v123(3, env, self, jDb, baSql, nMax, prepFlags, jOutStmt, outTail); } /* ** Impl for C-to-Java of the callbacks for both sqlite3_update_hook() ** and sqlite3_preupdate_hook(). The differences are that for ** update_hook(): ** ** - pDb is NULL ** - iKey1 is the row ID ** - iKey2 is unused */ static void s3jni_updatepre_hook_impl(void * pState, sqlite3 *pDb, int opId, const char *zDb, const char *zTable, sqlite3_int64 iKey1, sqlite3_int64 iKey2){ S3JniDb * const ps = pState; LocalJniGetEnv; jstring jDbName; jstring jTable; S3JniHook * pHook; const int isPre = 0!=pDb; pHook = isPre ? #ifdef SQLITE_ENABLE_PREUPDATE_HOOK &ps->hooks.preUpdate #else 0 #endif : &ps->hooks.update; assert( pHook ); jDbName = s3jni_utf8_to_jstring(env, zDb, -1); jTable = jDbName ? s3jni_utf8_to_jstring(env, zTable, -1) : 0; IFTHREW { EXCEPTION_CLEAR; s3jni_db_error(ps->pDb, SQLITE_NOMEM, 0); }else{ assert( pHook->jObj ); assert( pHook->midCallback ); assert( ps->jDb ); #ifdef SQLITE_ENABLE_PREUPDATE_HOOK if( isPre ) (*env)->CallVoidMethod(env, pHook->jObj, pHook->midCallback, ps->jDb, (jint)opId, jDbName, jTable, (jlong)iKey1, (jlong)iKey2); else #endif (*env)->CallVoidMethod(env, pHook->jObj, pHook->midCallback, (jint)opId, jDbName, jTable, (jlong)iKey1); IFTHREW{ EXCEPTION_WARN_CALLBACK_THREW("sqlite3_(pre)update_hook() callback"); s3jni_db_exception(env, ps, 0, "sqlite3_(pre)update_hook() callback threw"); } } UNREF_L(jDbName); UNREF_L(jTable); } #ifdef SQLITE_ENABLE_PREUPDATE_HOOK static void s3jni_preupdate_hook_impl(void * pState, sqlite3 *pDb, int opId, const char *zDb, const char *zTable, sqlite3_int64 iKey1, sqlite3_int64 iKey2){ return s3jni_updatepre_hook_impl(pState, pDb, opId, zDb, zTable, iKey1, iKey2); } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ static void s3jni_update_hook_impl(void * pState, int opId, const char *zDb, const char *zTable, sqlite3_int64 nRowid){ return s3jni_updatepre_hook_impl(pState, NULL, opId, zDb, zTable, nRowid, 0); } #ifndef SQLITE_ENABLE_PREUPDATE_HOOK /* We need no-op impls for preupdate_{count,depth,blobwrite}() */ JDECL(int,1preupdate_1blobwrite)(JENV_CSELF, jobject jDb){ return SQLITE_MISUSE; } JDECL(int,1preupdate_1count)(JENV_CSELF, jobject jDb){ return SQLITE_MISUSE; } JDECL(int,1preupdate_1depth)(JENV_CSELF, jobject jDb){ return SQLITE_MISUSE; } #endif /* !SQLITE_ENABLE_PREUPDATE_HOOK */ /* ** JNI wrapper for both sqlite3_update_hook() and ** sqlite3_preupdate_hook() (if isPre is true). */ static jobject s3jni_updatepre_hook(JNIEnv * env, int isPre, jobject jDb, jobject jHook){ S3JniDb * const ps = S3JniDb_for_db(env, jDb, 0); jclass klazz; jobject pOld = 0; jmethodID xCallback; S3JniHook * pHook = ps ? ( isPre ? #ifdef SQLITE_ENABLE_PREUPDATE_HOOK &ps->hooks.preUpdate #else 0 #endif : &ps->hooks.update) : 0; if(!pHook){ return 0; } pOld = pHook->jObj; if( pOld && jHook && (*env)->IsSameObject(env, pOld, jHook) ){ return pOld; } if( !jHook ){ if( pOld ){ jobject tmp = REF_L(pOld); UNREF_G(pOld); pOld = tmp; } memset(pHook, 0, sizeof(S3JniHook)); #ifdef SQLITE_ENABLE_PREUPDATE_HOOK if( isPre ) sqlite3_preupdate_hook(ps->pDb, 0, 0); else #endif sqlite3_update_hook(ps->pDb, 0, 0); return pOld; } klazz = (*env)->GetObjectClass(env, jHook); xCallback = isPre ? (*env)->GetMethodID(env, klazz, "xPreUpdate", "(Lorg/sqlite/jni/sqlite3;" "I" "Ljava/lang/String;" "Ljava/lang/String;" "JJ)V") : (*env)->GetMethodID(env, klazz, "xUpdateHook", "(ILjava/lang/String;Ljava/lang/String;J)V"); UNREF_L(klazz); IFTHREW { EXCEPTION_CLEAR; s3jni_db_error(ps->pDb, SQLITE_ERROR, "Cannot not find matching callback on " "(pre)update hook object."); }else{ pHook->midCallback = xCallback; pHook->jObj = REF_G(jHook); #ifdef SQLITE_ENABLE_PREUPDATE_HOOK if( isPre ) sqlite3_preupdate_hook(ps->pDb, s3jni_preupdate_hook_impl, ps); else #endif sqlite3_update_hook(ps->pDb, s3jni_update_hook_impl, ps); if(pOld){ jobject tmp = REF_L(pOld); UNREF_G(pOld); pOld = tmp; } } return pOld; } JDECL(jobject,1preupdate_1hook)(JENV_CSELF, jobject jDb, jobject jHook){ #ifdef SQLITE_ENABLE_PREUPDATE_HOOK return s3jni_updatepre_hook(env, 1, jDb, jHook); #else return NULL; #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ } /* Impl for sqlite3_preupdate_{new,old}(). */ static int s3jni_preupdate_newold(JNIEnv * const env, int isNew, jobject jDb, jint iCol, jobject jOut){ #ifdef SQLITE_ENABLE_PREUPDATE_HOOK sqlite3_value * pOut = 0; sqlite3 * const pDb = PtrGet_sqlite3(jDb); int rc; int (*fOrig)(sqlite3*,int,sqlite3_value**) = isNew ? sqlite3_preupdate_new : sqlite3_preupdate_old; rc = fOrig(pDb, (int)iCol, &pOut); if( 0==rc ){ jobject pWrap = new_sqlite3_value_wrapper(env, pOut); if( pWrap ){ OutputPointer_set_sqlite3_value(env, jOut, pWrap); UNREF_L(pWrap); }else{ rc = SQLITE_NOMEM; } } return rc; #else return SQLITE_MISUSE; #endif } JDECL(jint,1preupdate_1new)(JENV_CSELF, jobject jDb, jint iCol, jobject jOut){ return s3jni_preupdate_newold(env, 1, jDb, iCol, jOut); } JDECL(jint,1preupdate_1old)(JENV_CSELF, jobject jDb, jint iCol, jobject jOut){ return s3jni_preupdate_newold(env, 0, jDb, iCol, jOut); } /* Central C-to-Java sqlite3_progress_handler() proxy. */ static int s3jni_progress_handler_impl(void *pP){ S3JniDb * const ps = (S3JniDb *)pP; LocalJniGetEnv; int rc = (int)(*env)->CallIntMethod(env, ps->hooks.progress.jObj, ps->hooks.progress.midCallback); IFTHREW{ rc = s3jni_db_exception(env, ps, rc, "sqlite3_progress_handler() callback threw"); } return rc; } JDECL(void,1progress_1handler)(JENV_CSELF,jobject jDb, jint n, jobject jProgress){ S3JniDb * ps = S3JniDb_for_db(env, jDb, 0); jclass klazz; jmethodID xCallback; if( n<1 || !jProgress ){ if(ps){ UNREF_G(ps->hooks.progress.jObj); memset(&ps->hooks.progress, 0, sizeof(ps->hooks.progress)); } sqlite3_progress_handler(ps->pDb, 0, 0, 0); return; } if(!ps){ s3jni_db_error(ps->pDb, SQLITE_NOMEM, 0); return; } klazz = (*env)->GetObjectClass(env, jProgress); xCallback = (*env)->GetMethodID(env, klazz, "xCallback", "()I"); UNREF_L(klazz); IFTHREW { EXCEPTION_CLEAR; s3jni_db_error(ps->pDb, SQLITE_ERROR, "Cannot not find matching xCallback() on " "ProgressHandler object."); }else{ UNREF_G(ps->hooks.progress.jObj); ps->hooks.progress.midCallback = xCallback; ps->hooks.progress.jObj = REF_G(jProgress); sqlite3_progress_handler(ps->pDb, (int)n, s3jni_progress_handler_impl, ps); } } JDECL(jint,1reset)(JENV_CSELF, jobject jpStmt){ int rc = 0; sqlite3_stmt * const pStmt = PtrGet_sqlite3_stmt(jpStmt); if( pStmt ){ rc = sqlite3_reset(pStmt); } return rc; } /* Clears all entries from S3JniGlobal.autoExt. */ static void s3jni_reset_auto_extension(JNIEnv *env){ int i; MUTEX_EXT_ENTER; for( i = 0; i < SJG.autoExt.nExt; ++i ){ S3JniAutoExtension_clear( env, &SJG.autoExt.pExt[i] ); } SJG.autoExt.nExt = 0; MUTEX_EXT_LEAVE; } JDECL(void,1reset_1auto_1extension)(JENV_CSELF){ s3jni_reset_auto_extension(env); } /* sqlite3_result_text/blob() and friends. */ static void result_blob_text(int asBlob, int as64, int eTextRep/*only for (asBlob=0)*/, JNIEnv * const env, sqlite3_context *pCx, jbyteArray jBa, jlong nMax){ if(jBa){ jbyte * const pBuf = s3jni_jbytearray_bytes(jBa); jsize nBa = (*env)->GetArrayLength(env, jBa); if( nMax>=0 && nBa>(jsize)nMax ){ nBa = (jsize)nMax; /** From the sqlite docs: > If the 3rd parameter to any of the sqlite3_result_text* |
︙ | ︙ | |||
2948 2949 2950 2951 2952 2953 2954 | break; case SQLITE_UTF16BE: sqlite3_result_text16be(pCx, (const char *)pBuf, (int)nBa, SQLITE_TRANSIENT); break; } } | | | 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 | break; case SQLITE_UTF16BE: sqlite3_result_text16be(pCx, (const char *)pBuf, (int)nBa, SQLITE_TRANSIENT); break; } } s3jni_jbytearray_release(jBa, pBuf); } }else{ sqlite3_result_null(pCx); } } JDECL(void,1result_1blob)(JENV_CSELF, jobject jpCx, jbyteArray jBa, jint nMax){ |
︙ | ︙ | |||
2971 2972 2973 2974 2975 2976 2977 | sqlite3_result_double(PtrGet_sqlite3_context(jpCx), v); } JDECL(void,1result_1error)(JENV_CSELF, jobject jpCx, jbyteArray baMsg, int eTextRep){ const char * zUnspecified = "Unspecified error."; jsize const baLen = (*env)->GetArrayLength(env, baMsg); | | | | 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 | sqlite3_result_double(PtrGet_sqlite3_context(jpCx), v); } JDECL(void,1result_1error)(JENV_CSELF, jobject jpCx, jbyteArray baMsg, int eTextRep){ const char * zUnspecified = "Unspecified error."; jsize const baLen = (*env)->GetArrayLength(env, baMsg); jbyte * const pjBuf = baMsg ? s3jni_jbytearray_bytes(baMsg) : NULL; switch(pjBuf ? eTextRep : SQLITE_UTF8){ case SQLITE_UTF8: { const char *zMsg = pjBuf ? (const char *)pjBuf : zUnspecified; sqlite3_result_error(PtrGet_sqlite3_context(jpCx), zMsg, (int)baLen); break; } case SQLITE_UTF16: { const void *zMsg = pjBuf ? (const void *)pjBuf : (const void *)zUnspecified; sqlite3_result_error16(PtrGet_sqlite3_context(jpCx), zMsg, (int)baLen); break; } default: sqlite3_result_error(PtrGet_sqlite3_context(jpCx), "Invalid encoding argument passed " "to sqlite3_result_error().", -1); break; } s3jni_jbytearray_release(baMsg,pjBuf); } JDECL(void,1result_1error_1code)(JENV_CSELF, jobject jpCx, jint v){ sqlite3_result_error_code(PtrGet_sqlite3_context(jpCx), v ? (int)v : SQLITE_ERROR); } JDECL(void,1result_1error_1nomem)(JENV_CSELF, jobject jpCx){ |
︙ | ︙ | |||
3017 3018 3019 3020 3021 3022 3023 | sqlite3_result_int64(PtrGet_sqlite3_context(jpCx), (sqlite3_int64)v); } JDECL(void,1result_1java_1object)(JENV_CSELF, jobject jpCx, jobject v){ if(v){ ResultJavaVal * const rjv = ResultJavaVal_alloc(env, v); if(rjv){ | | | | > | > | > | > | > | | | | | < | < | | > | | > < < | | < > | | > > > | > > < | | | < | | | 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 | sqlite3_result_int64(PtrGet_sqlite3_context(jpCx), (sqlite3_int64)v); } JDECL(void,1result_1java_1object)(JENV_CSELF, jobject jpCx, jobject v){ if(v){ ResultJavaVal * const rjv = ResultJavaVal_alloc(env, v); if(rjv){ sqlite3_result_pointer(PtrGet_sqlite3_context(jpCx), rjv, ResultJavaValuePtrStr, ResultJavaVal_finalizer); }else{ sqlite3_result_error_nomem(PtrGet_sqlite3_context(jpCx)); } }else{ sqlite3_result_null(PtrGet_sqlite3_context(jpCx)); } } JDECL(void,1result_1null)(JENV_CSELF, jobject jpCx){ sqlite3_result_null(PtrGet_sqlite3_context(jpCx)); } JDECL(void,1result_1text)(JENV_CSELF, jobject jpCx, jbyteArray jBa, jint nMax){ return result_blob_text(0, 0, SQLITE_UTF8, env, PtrGet_sqlite3_context(jpCx), jBa, nMax); } JDECL(void,1result_1text64)(JENV_CSELF, jobject jpCx, jbyteArray jBa, jlong nMax, jint eTextRep){ return result_blob_text(0, 1, eTextRep, env, PtrGet_sqlite3_context(jpCx), jBa, nMax); } JDECL(void,1result_1value)(JENV_CSELF, jobject jpCx, jobject jpSVal){ sqlite3_result_value(PtrGet_sqlite3_context(jpCx), PtrGet_sqlite3_value(jpSVal)); } JDECL(void,1result_1zeroblob)(JENV_CSELF, jobject jpCx, jint v){ sqlite3_result_zeroblob(PtrGet_sqlite3_context(jpCx), (int)v); } JDECL(jint,1result_1zeroblob64)(JENV_CSELF, jobject jpCx, jlong v){ return (jint)sqlite3_result_zeroblob64(PtrGet_sqlite3_context(jpCx), (sqlite3_int64)v); } JDECL(jobject,1rollback_1hook)(JENV_CSELF, jobject jDb, jobject jHook){ return s3jni_commit_rollback_hook(0, env, jDb, jHook); } /* sqlite3_set_authorizer() callback proxy. */ static int s3jni_xAuth(void* pState, int op,const char*z0, const char*z1, const char*z2,const char*z3){ S3JniDb * const ps = pState; LocalJniGetEnv; S3JniHook const * const pHook = &ps->hooks.auth; jstring const s0 = z0 ? s3jni_utf8_to_jstring(env, z0, -1) : 0; jstring const s1 = z1 ? s3jni_utf8_to_jstring(env, z1, -1) : 0; jstring const s2 = z2 ? s3jni_utf8_to_jstring(env, z2, -1) : 0; jstring const s3 = z3 ? s3jni_utf8_to_jstring(env, z3, -1) : 0; int rc; assert( pHook->jObj ); rc = (*env)->CallIntMethod(env, pHook->jObj, pHook->midCallback, (jint)op, s0, s1, s3, s3); IFTHREW{ rc = s3jni_db_exception(env, ps, rc, "sqlite3_set_authorizer() callback"); } UNREF_L(s0); UNREF_L(s1); UNREF_L(s2); UNREF_L(s3); return rc; } JDECL(jint,1set_1authorizer)(JENV_CSELF,jobject jDb, jobject jHook){ S3JniDb * const ps = S3JniDb_for_db(env, jDb, 0); S3JniHook * const pHook = ps ? &ps->hooks.auth : 0; if( !ps ) return SQLITE_MISUSE; else if( !jHook ){ S3JniHook_unref(env, pHook, 0); return (jint)sqlite3_set_authorizer( ps->pDb, 0, 0 ); }else{ int rc = 0; jclass klazz; if( pHook->jObj ){ if( (*env)->IsSameObject(env, pHook->jObj, jHook) ){ /* Same object - this is a no-op. */ return 0; } S3JniHook_unref(env, pHook, 0); } pHook->jObj = REF_G(jHook); klazz = (*env)->GetObjectClass(env, jHook); pHook->midCallback = (*env)->GetMethodID(env, klazz, "xAuth", "(I" "Ljava/lang/String;" "Ljava/lang/String;" "Ljava/lang/String;" "Ljava/lang/String;" ")I"); UNREF_L(klazz); IFTHREW { S3JniHook_unref(env, pHook, 0); return s3jni_db_error(ps->pDb, SQLITE_ERROR, "Error setting up Java parts of authorizer hook."); } rc = sqlite3_set_authorizer(ps->pDb, s3jni_xAuth, ps); if( rc ) S3JniHook_unref(env, pHook, 0); return rc; } } JDECL(void,1set_1last_1insert_1rowid)(JENV_CSELF, jobject jpDb, jlong rowId){ sqlite3_set_last_insert_rowid(PtrGet_sqlite3_context(jpDb), (sqlite3_int64)rowId); } JDECL(jint,1status)(JENV_CSELF, jint op, jobject jOutCurrent, jobject jOutHigh, jboolean reset ){ int iCur = 0, iHigh = 0; int rc = sqlite3_status( op, &iCur, &iHigh, reset ); if( 0==rc ){ OutputPointer_set_Int32(env, jOutCurrent, iCur); OutputPointer_set_Int32(env, jOutHigh, iHigh); } return (jint)rc; } JDECL(jint,1status64)(JENV_CSELF, jint op, jobject jOutCurrent, jobject jOutHigh, jboolean reset ){ sqlite3_int64 iCur = 0, iHigh = 0; int rc = sqlite3_status64( op, &iCur, &iHigh, reset ); if( 0==rc ){ OutputPointer_set_Int64(env, jOutCurrent, iCur); OutputPointer_set_Int64(env, jOutHigh, iHigh); } return (jint)rc; } static int s3jni_strlike_glob(int isLike, JNIEnv *const env, jbyteArray baG, jbyteArray baT, jint escLike){ int rc = 0; jbyte * const pG = s3jni_jbytearray_bytes(baG); jbyte * const pT = pG ? s3jni_jbytearray_bytes(baT) : 0; s3jni_oom_check(pT); /* Note that we're relying on the byte arrays having been NUL-terminated on the Java side. */ rc = isLike ? sqlite3_strlike((const char *)pG, (const char *)pT, (unsigned int)escLike) : sqlite3_strglob((const char *)pG, (const char *)pT); s3jni_jbytearray_release(baG, pG); s3jni_jbytearray_release(baT, pT); return rc; } JDECL(jint,1strglob)(JENV_CSELF, jbyteArray baG, jbyteArray baT){ return s3jni_strlike_glob(0, env, baG, baT, 0); } JDECL(jint,1strlike)(JENV_CSELF, jbyteArray baG, jbyteArray baT, jint escChar){ return s3jni_strlike_glob(1, env, baG, baT, escChar); } JDECL(jint,1shutdown)(JENV_CSELF){ s3jni_reset_auto_extension(env); MUTEX_ENV_ENTER; while( SJG.envCache.aHead ){ S3JniGlobal_env_uncache( SJG.envCache.aHead->env ); } MUTEX_ENV_LEAVE; /* Do not clear S3JniGlobal.jvm: it's legal to call sqlite3_initialize() again to restart the lib. */ return sqlite3_shutdown(); } JDECL(jstring,1sql)(JENV_CSELF, jobject jpStmt){ sqlite3_stmt * const pStmt = PtrGet_sqlite3_stmt(jpStmt); jstring rv = 0; if( pStmt ){ const char * zSql = 0; zSql = sqlite3_sql(pStmt); rv = s3jni_utf8_to_jstring(env, zSql, -1); s3jni_oom_check(rv); } return rv; } JDECL(jint,1step)(JENV_CSELF,jobject jStmt){ int rc = SQLITE_MISUSE; sqlite3_stmt * const pStmt = PtrGet_sqlite3_stmt(jStmt); if(pStmt){ rc = sqlite3_step(pStmt); } return rc; } static int s3jni_trace_impl(unsigned traceflag, void *pC, void *pP, void *pX){ S3JniDb * const ps = (S3JniDb *)pC; LocalJniGetEnv; jobject jX = NULL /* the tracer's X arg */; jobject jP = NULL /* the tracer's P arg */; jobject jPUnref = NULL /* potentially a local ref to jP */; int rc; int createStmt = 0; switch(traceflag){ case SQLITE_TRACE_STMT: jX = s3jni_utf8_to_jstring(env, (const char *)pX, -1); if(!jX) return SQLITE_NOMEM; /*MARKER(("TRACE_STMT@%p SQL=%p / %s\n", pP, jX, (const char *)pX));*/ createStmt = 1; break; case SQLITE_TRACE_PROFILE: jX = (*env)->NewObject(env, SJG.g.cLong, SJG.g.ctorLong1, (jlong)*((sqlite3_int64*)pX)); // hmm. ^^^ (*pX) really is zero. // MARKER(("profile time = %llu\n", *((sqlite3_int64*)pX))); if(!jX) return SQLITE_NOMEM; createStmt = 1; break; case SQLITE_TRACE_ROW: |
︙ | ︙ | |||
3247 3248 3249 3250 3251 3252 3253 | jP = jPUnref = new_sqlite3_stmt_wrapper(env, pP); if(!jP){ UNREF_L(jX); return SQLITE_NOMEM; } } assert(jP); | | | < | > | > < | | > | < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < | < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < | 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 | jP = jPUnref = new_sqlite3_stmt_wrapper(env, pP); if(!jP){ UNREF_L(jX); return SQLITE_NOMEM; } } assert(jP); rc = (int)(*env)->CallIntMethod(env, ps->hooks.trace.jObj, ps->hooks.trace.midCallback, (jint)traceflag, jP, jX); IFTHREW{ EXCEPTION_WARN_CALLBACK_THREW("sqlite3_trace_v2() callback"); rc = s3jni_db_exception(env, ps, SQLITE_ERROR, "sqlite3_trace_v2() callback threw."); } UNREF_L(jPUnref); UNREF_L(jX); return rc; } JDECL(jint,1trace_1v2)(JENV_CSELF,jobject jDb, jint traceMask, jobject jTracer){ S3JniDb * const ps = S3JniDb_for_db(env, jDb, 0); jclass klazz; if( !traceMask || !jTracer ){ if(ps){ S3JniHook_unref(env, &ps->hooks.trace, 0); } return (jint)sqlite3_trace_v2(ps->pDb, 0, 0, 0); } if(!ps) return SQLITE_NOMEM; klazz = (*env)->GetObjectClass(env, jTracer); ps->hooks.trace.midCallback = (*env)->GetMethodID(env, klazz, "xCallback", "(ILjava/lang/Object;Ljava/lang/Object;)I"); UNREF_L(klazz); IFTHREW { EXCEPTION_CLEAR; return s3jni_db_error(ps->pDb, SQLITE_ERROR, "Cannot not find matching xCallback() on Tracer object."); } ps->hooks.trace.jObj = REF_G(jTracer); return sqlite3_trace_v2(ps->pDb, (unsigned)traceMask, s3jni_trace_impl, ps); } JDECL(jobject,1update_1hook)(JENV_CSELF, jobject jDb, jobject jHook){ return s3jni_updatepre_hook(env, 0, jDb, jHook); } JDECL(jbyteArray,1value_1blob)(JENV_CSELF, jobject jpSVal){ sqlite3_value * const sv = PtrGet_sqlite3_value(jpSVal); int const nLen = sqlite3_value_bytes(sv); const jbyte * pBytes = sqlite3_value_blob(sv); |
︙ | ︙ | |||
3395 3396 3397 3398 3399 3400 3401 | } JDECL(jlong,1value_1int64)(JENV_CSELF, jobject jpSVal){ return (jlong) sqlite3_value_int64(PtrGet_sqlite3_value(jpSVal)); } JDECL(jobject,1value_1java_1object)(JENV_CSELF, jobject jpSVal){ | | > < < < < < < < | > | | | | | 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 | } JDECL(jlong,1value_1int64)(JENV_CSELF, jobject jpSVal){ return (jlong) sqlite3_value_int64(PtrGet_sqlite3_value(jpSVal)); } JDECL(jobject,1value_1java_1object)(JENV_CSELF, jobject jpSVal){ ResultJavaVal * const rv = sqlite3_value_pointer(PtrGet_sqlite3_value(jpSVal), ResultJavaValuePtrStr); return rv ? rv->jObj : NULL; } JDECL(jbyteArray,1value_1text_1utf8)(JENV_CSELF, jobject jpSVal){ sqlite3_value * const sv = PtrGet_sqlite3_value(jpSVal); int const n = sqlite3_value_bytes(sv); const unsigned char * const p = sqlite3_value_text(sv); return p ? s3jni_new_jbyteArray(env, p, n) : 0; } static jbyteArray value_text16(int mode, JNIEnv * const env, jobject jpSVal){ sqlite3_value * const sv = PtrGet_sqlite3_value(jpSVal); int const nLen = sqlite3_value_bytes16(sv); jbyteArray jba; const jbyte * pBytes; switch(mode){ case SQLITE_UTF16: pBytes = sqlite3_value_text16(sv); break; case SQLITE_UTF16LE: pBytes = sqlite3_value_text16le(sv); break; case SQLITE_UTF16BE: pBytes = sqlite3_value_text16be(sv); break; default: assert(!"not possible"); return NULL; } jba = pBytes ? (*env)->NewByteArray(env, (jsize)nLen) |
︙ | ︙ | |||
3465 3466 3467 3468 3469 3470 3471 | "unavailable" #endif "." ); puts("sizeofs:"); #define SO(T) printf("\tsizeof(" #T ") = %u\n", (unsigned)sizeof(T)) SO(void*); | > > | | | | < | < | | > > > > > > > > > > > > > | | | 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 | "unavailable" #endif "." ); puts("sizeofs:"); #define SO(T) printf("\tsizeof(" #T ") = %u\n", (unsigned)sizeof(T)) SO(void*); SO(jmethodID); SO(jfieldID); SO(S3JniEnv); SO(S3JniHook); SO(S3JniDb); SO(S3NphRefs); printf("\t(^^^ %u NativePointerHolder subclasses)\n", (unsigned)NphCache_SIZE); SO(S3JniGlobal); SO(S3JniAutoExtension); SO(S3JniUdf); printf("Cache info:\n"); printf("\tJNIEnv cache: %u allocs, %u misses, %u hits\n", SJG.metrics.envCacheAllocs, SJG.metrics.envCacheMisses, SJG.metrics.envCacheHits); printf("Mutex entry:" "\n\tenv %u" "\n\tnph inits %u" "\n\tperDb %u" "\n\tautoExt %u list accesses" "\n\tmetrics %u\n", SJG.metrics.nMutexEnv, SJG.metrics.nMutexEnv2, SJG.metrics.nMutexPerDb, SJG.metrics.nMutexAutoExt, SJG.metrics.nMetrics); printf("S3JniDb: %u alloced (*%u = %u bytes), %u recycled\n", SJG.metrics.nPdbAlloc, (unsigned) sizeof(S3JniDb), (unsigned)(SJG.metrics.nPdbAlloc * sizeof(S3JniDb)), SJG.metrics.nPdbRecycled); puts("Java-side UDF calls:"); #define UDF(T) printf("\t%-8s = %u\n", "x" #T, SJG.metrics.udf.n##T) UDF(Func); UDF(Step); UDF(Final); UDF(Value); UDF(Inverse); #undef UDF printf("xDestroy calls across all callback types: %u\n", SJG.metrics.nDestroy); #undef SO } //////////////////////////////////////////////////////////////////////// // End of the sqlite3_... API bindings. Next up, FTS5... //////////////////////////////////////////////////////////////////////// #ifdef SQLITE_ENABLE_FTS5 |
︙ | ︙ | |||
3513 3514 3515 3516 3517 3518 3519 | #define JDECLFtsApi(ReturnType,Suffix) \ JNIEXPORT ReturnType JNICALL \ JFuncNameFtsApi(Suffix) #define JDECLFtsTok(ReturnType,Suffix) \ JNIEXPORT ReturnType JNICALL \ JFuncNameFtsTok(Suffix) | | | | | < < | | < > > | > > | | | | < < | < < | | < | | | > > > > | | > > > > | | | 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 | #define JDECLFtsApi(ReturnType,Suffix) \ JNIEXPORT ReturnType JNICALL \ JFuncNameFtsApi(Suffix) #define JDECLFtsTok(ReturnType,Suffix) \ JNIEXPORT ReturnType JNICALL \ JFuncNameFtsTok(Suffix) #define PtrGet_fts5_api(OBJ) NativePointerHolder_get(env,OBJ,&S3NphRefs.fts5_api) #define PtrGet_fts5_tokenizer(OBJ) NativePointerHolder_get(env,OBJ,&S3NphRefs.fts5_tokenizer) #define PtrGet_Fts5Context(OBJ) NativePointerHolder_get(env,OBJ,&S3NphRefs.Fts5Context) #define PtrGet_Fts5Tokenizer(OBJ) NativePointerHolder_get(env,OBJ,&S3NphRefs.Fts5Tokenizer) #define Fts5ExtDecl Fts5ExtensionApi const * const fext = s3jni_ftsext() /** State for binding Java-side FTS5 auxiliary functions. */ typedef struct { jobject jObj /* functor instance */; jobject jUserData /* 2nd arg to JNI binding of xCreateFunction(), ostensibly the 3rd arg to the lib-level xCreateFunction(), except that we necessarily use that slot for a Fts5JniAux instance. */; char * zFuncName /* Only for error reporting and debug logging */; jmethodID jmid /* callback member's method ID */; } Fts5JniAux; static void Fts5JniAux_free(Fts5JniAux * const s){ LocalJniGetEnv; if(env){ /*MARKER(("FTS5 aux function cleanup: %s\n", s->zFuncName));*/ s3jni_call_xDestroy(env, s->jObj); UNREF_G(s->jObj); UNREF_G(s->jUserData); } sqlite3_free(s->zFuncName); sqlite3_free(s); } static void Fts5JniAux_xDestroy(void *p){ if(p) Fts5JniAux_free(p); } static Fts5JniAux * Fts5JniAux_alloc(JNIEnv * const env, jobject jObj){ Fts5JniAux * s = sqlite3_malloc(sizeof(Fts5JniAux)); if(s){ jclass klazz; memset(s, 0, sizeof(Fts5JniAux)); s->jObj = REF_G(jObj); klazz = (*env)->GetObjectClass(env, jObj); s->jmid = (*env)->GetMethodID(env, klazz, "xFunction", "(Lorg/sqlite/jni/Fts5ExtensionApi;" "Lorg/sqlite/jni/Fts5Context;" "Lorg/sqlite/jni/sqlite3_context;" "[Lorg/sqlite/jni/sqlite3_value;)V"); UNREF_L(klazz); IFTHREW{ EXCEPTION_REPORT; EXCEPTION_CLEAR; Fts5JniAux_free(s); s = 0; } } return s; } static inline Fts5ExtensionApi const * s3jni_ftsext(void){ return &sFts5Api/*singleton from sqlite3.c*/; } static inline jobject new_Fts5Context_wrapper(JNIEnv * const env, Fts5Context *sv){ return new_NativePointerHolder_object(env, &S3NphRefs.Fts5Context, sv); } static inline jobject new_fts5_api_wrapper(JNIEnv * const env, fts5_api *sv){ return new_NativePointerHolder_object(env, &S3NphRefs.fts5_api, sv); } /** Returns a per-JNIEnv global ref to the Fts5ExtensionApi singleton instance, or NULL on OOM. */ static jobject s3jni_getFts5ExensionApi(JNIEnv * const env){ if( !SJG.fts5.jFtsExt ){ jobject pNPH = new_NativePointerHolder_object( env, &S3NphRefs.Fts5ExtensionApi, s3jni_ftsext() ); MUTEX_ENV_ENTER; if( pNPH ){ if( !SJG.fts5.jFtsExt ){ SJG.fts5.jFtsExt = REF_G(pNPH); } UNREF_L(pNPH); } MUTEX_ENV_LEAVE; } return SJG.fts5.jFtsExt; } /* ** Return a pointer to the fts5_api instance for database connection ** db. If an error occurs, return NULL and leave an error in the ** database handle (accessible using sqlite3_errcode()/errmsg()). */ static fts5_api *s3jni_fts5_api_from_db(sqlite3 *db){ fts5_api *pRet = 0; sqlite3_stmt *pStmt = 0; if( SQLITE_OK==sqlite3_prepare(db, "SELECT fts5(?1)", -1, &pStmt, 0) ){ sqlite3_bind_pointer(pStmt, 1, (void*)&pRet, "fts5_api_ptr", NULL); sqlite3_step(pStmt); } sqlite3_finalize(pStmt); return pRet; } JDECLFtsApi(jobject,getInstanceForDb)(JENV_CSELF,jobject jDb){ S3JniDb * const ps = S3JniDb_for_db(env, jDb, 0); jobject rv = 0; if(!ps) return 0; else if(ps->jFtsApi){ rv = ps->jFtsApi; }else{ fts5_api * const pApi = s3jni_fts5_api_from_db(ps->pDb); if( pApi ){ |
︙ | ︙ | |||
3658 3659 3660 3661 3662 3663 3664 | jobject jOut){ Fts5ExtDecl; const char *pz = 0; int pn = 0; int rc = fext->xColumnText(PtrGet_Fts5Context(jCtx), (int)iCol, &pz, &pn); if( 0==rc ){ | < | | | | < > > < < | > | | | > > > > | < | | | | | | 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 | jobject jOut){ Fts5ExtDecl; const char *pz = 0; int pn = 0; int rc = fext->xColumnText(PtrGet_Fts5Context(jCtx), (int)iCol, &pz, &pn); if( 0==rc ){ jstring jstr = pz ? s3jni_utf8_to_jstring(env, pz, pn) : 0; if( pz ){ if( jstr ){ OutputPointer_set_String(env, jOut, jstr); UNREF_L(jstr)/*jOut has a reference*/; }else{ rc = SQLITE_NOMEM; } } } return (jint)rc; } JDECLFtsXA(jint,xColumnTotalSize)(JENV_OSELF,jobject jCtx, jint iCol, jobject jOut64){ Fts5ExtDecl; sqlite3_int64 nOut = 0; int const rc = fext->xColumnTotalSize(PtrGet_Fts5Context(jCtx), (int)iCol, &nOut); if( 0==rc && jOut64 ) OutputPointer_set_Int64(env, jOut64, (jlong)nOut); return (jint)rc; } /* ** Proxy for fts5_extension_function instances plugged in via ** fts5_api::xCreateFunction(). */ static void s3jni_fts5_extension_function(Fts5ExtensionApi const *pApi, Fts5Context *pFts, sqlite3_context *pCx, int argc, sqlite3_value **argv){ Fts5JniAux * const pAux = pApi->xUserData(pFts); jobject jpCx = 0; jobjectArray jArgv = 0; jobject jpFts = 0; jobject jFXA; int rc; LocalJniGetEnv; assert(pAux); jFXA = s3jni_getFts5ExensionApi(env); if( !jFXA ) goto error_oom; jpFts = new_Fts5Context_wrapper(env, pFts); if(!jpFts) goto error_oom; rc = udf_args(env, pCx, argc, argv, &jpCx, &jArgv); if(rc) goto error_oom; (*env)->CallVoidMethod(env, pAux->jObj, pAux->jmid, jFXA, jpFts, jpCx, jArgv); IFTHREW{ udf_report_exception(env, 1, pCx, pAux->zFuncName, "xFunction"); } UNREF_L(jpFts); UNREF_L(jpCx); UNREF_L(jArgv); return; error_oom: assert( !jArgv ); assert( !jpCx ); UNREF_L(jpFts); sqlite3_result_error_nomem(pCx); return; } JDECLFtsApi(jint,xCreateFunction)(JENV_OSELF, jstring jName, jobject jUserData, jobject jFunc){ fts5_api * const pApi = PtrGet_fts5_api(jSelf); int rc; char const * zName; Fts5JniAux * pAux; assert(pApi); zName = s3jni_jstring_to_mutf8(jName); if(!zName) return SQLITE_NOMEM; pAux = Fts5JniAux_alloc(env, jFunc); if( pAux ){ rc = pApi->xCreateFunction(pApi, zName, pAux, s3jni_fts5_extension_function, Fts5JniAux_xDestroy); }else{ rc = SQLITE_NOMEM; } if( 0==rc ){ pAux->jUserData = jUserData ? REF_G(jUserData) : 0; pAux->zFuncName = sqlite3_mprintf("%s", zName) /* OOM here is non-fatal. Ignore it. */; } s3jni_mutf8_release(jName, zName); return (jint)rc; } typedef struct S3JniFts5AuxData S3JniFts5AuxData; /* ** TODO: this middle-man struct is no longer necessary. Conider ** removing it and passing around jObj itself instead. */ struct S3JniFts5AuxData { jobject jObj; }; static void S3JniFts5AuxData_xDestroy(void *x){ if(x){ S3JniFts5AuxData * const p = x; if(p->jObj){ LocalJniGetEnv; s3jni_call_xDestroy(env, p->jObj); UNREF_G(p->jObj); } sqlite3_free(x); } } JDECLFtsXA(jobject,xGetAuxdata)(JENV_OSELF,jobject jCtx, jboolean bClear){ Fts5ExtDecl; jobject rv = 0; S3JniFts5AuxData * const pAux = fext->xGetAuxdata(PtrGet_Fts5Context(jCtx), bClear); if(pAux){ if(bClear){ if( pAux->jObj ){ rv = REF_L(pAux->jObj); UNREF_G(pAux->jObj); } /* Note that we do not call xDestroy() in this case. */ |
︙ | ︙ | |||
3812 3813 3814 3815 3816 3817 3818 | } JDECLFtsXA(jint,xPhraseCount)(JENV_OSELF,jobject jCtx){ Fts5ExtDecl; return (jint)fext->xPhraseCount(PtrGet_Fts5Context(jCtx)); } | < < < < < < < < < < < < < < < | | | > | | | | | > | | | < < | < < | < < | | < | < < | | < | < < | | | | | > < > | 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 | } JDECLFtsXA(jint,xPhraseCount)(JENV_OSELF,jobject jCtx){ Fts5ExtDecl; return (jint)fext->xPhraseCount(PtrGet_Fts5Context(jCtx)); } /* Copy the 'a' and 'b' fields from pSrc to Fts5PhraseIter object jIter. */ static void s3jni_phraseIter_NToJ(JNIEnv *const env, Fts5PhraseIter const * const pSrc, jobject jIter){ S3JniGlobalType * const g = &S3JniGlobal; assert(g->fts5.jPhraseIter.fidA); (*env)->SetLongField(env, jIter, g->fts5.jPhraseIter.fidA, (jlong)pSrc->a); EXCEPTION_IS_FATAL("Cannot set Fts5PhraseIter.a field."); (*env)->SetLongField(env, jIter, g->fts5.jPhraseIter.fidB, (jlong)pSrc->b); EXCEPTION_IS_FATAL("Cannot set Fts5PhraseIter.b field."); } /* Copy the 'a' and 'b' fields from Fts5PhraseIter object jIter to pDest. */ static void s3jni_phraseIter_JToN(JNIEnv *const env, jobject jIter, Fts5PhraseIter * const pDest){ S3JniGlobalType * const g = &S3JniGlobal; assert(g->fts5.jPhraseIter.fidA); pDest->a = (const unsigned char *)(*env)->GetLongField(env, jIter, g->fts5.jPhraseIter.fidA); EXCEPTION_IS_FATAL("Cannot get Fts5PhraseIter.a field."); pDest->b = (const unsigned char *)(*env)->GetLongField(env, jIter, g->fts5.jPhraseIter.fidB); EXCEPTION_IS_FATAL("Cannot get Fts5PhraseIter.b field."); } JDECLFtsXA(jint,xPhraseFirst)(JENV_OSELF,jobject jCtx, jint iPhrase, jobject jIter, jobject jOutCol, jobject jOutOff){ Fts5ExtDecl; Fts5PhraseIter iter; int rc, iCol = 0, iOff = 0; rc = fext->xPhraseFirst(PtrGet_Fts5Context(jCtx), (int)iPhrase, &iter, &iCol, &iOff); if( 0==rc ){ OutputPointer_set_Int32(env, jOutCol, iCol); OutputPointer_set_Int32(env, jOutOff, iOff); s3jni_phraseIter_NToJ(env, &iter, jIter); } return rc; } JDECLFtsXA(jint,xPhraseFirstColumn)(JENV_OSELF,jobject jCtx, jint iPhrase, jobject jIter, jobject jOutCol){ Fts5ExtDecl; Fts5PhraseIter iter; int rc, iCol = 0; rc = fext->xPhraseFirstColumn(PtrGet_Fts5Context(jCtx), (int)iPhrase, &iter, &iCol); if( 0==rc ){ OutputPointer_set_Int32(env, jOutCol, iCol); s3jni_phraseIter_NToJ(env, &iter, jIter); } return rc; } JDECLFtsXA(void,xPhraseNext)(JENV_OSELF,jobject jCtx, jobject jIter, jobject jOutCol, jobject jOutOff){ Fts5ExtDecl; Fts5PhraseIter iter; int iCol = 0, iOff = 0; s3jni_phraseIter_JToN(env, jIter, &iter); fext->xPhraseNext(PtrGet_Fts5Context(jCtx), &iter, &iCol, &iOff); OutputPointer_set_Int32(env, jOutCol, iCol); OutputPointer_set_Int32(env, jOutOff, iOff); s3jni_phraseIter_NToJ(env, &iter, jIter); } JDECLFtsXA(void,xPhraseNextColumn)(JENV_OSELF,jobject jCtx, jobject jIter, jobject jOutCol){ Fts5ExtDecl; Fts5PhraseIter iter; int iCol = 0; s3jni_phraseIter_JToN(env, jIter, &iter); fext->xPhraseNextColumn(PtrGet_Fts5Context(jCtx), &iter, &iCol); OutputPointer_set_Int32(env, jOutCol, iCol); s3jni_phraseIter_NToJ(env, &iter, jIter); } JDECLFtsXA(jint,xPhraseSize)(JENV_OSELF,jobject jCtx, jint iPhrase){ Fts5ExtDecl; return (jint)fext->xPhraseSize(PtrGet_Fts5Context(jCtx), (int)iPhrase); } /* State for use with xQueryPhrase() and xTokenize(). */ struct s3jni_xQueryPhraseState { Fts5ExtensionApi const * fext; S3JniEnv const * jc; jmethodID midCallback; jobject jCallback; jobject jFcx; /* State for xTokenize() */ struct { const char * zPrev; int nPrev; jbyteArray jba; } tok; }; static int s3jni_xQueryPhrase(const Fts5ExtensionApi *xapi, Fts5Context * pFcx, void *pData){ /* TODO: confirm that the Fts5Context passed to this function is guaranteed to be the same one passed to xQueryPhrase(). If it's not, we'll have to create a new wrapper object on every call. */ struct s3jni_xQueryPhraseState const * s = pData; LocalJniGetEnv; int rc = (int)(*env)->CallIntMethod(env, s->jCallback, s->midCallback, SJG.fts5.jFtsExt, s->jFcx); IFTHREW{ EXCEPTION_WARN_CALLBACK_THREW("xQueryPhrase() callback"); EXCEPTION_CLEAR; rc = SQLITE_ERROR; } return rc; } JDECLFtsXA(jint,xQueryPhrase)(JENV_OSELF,jobject jFcx, jint iPhrase, jobject jCallback){ Fts5ExtDecl; S3JniEnv * const jc = S3JniGlobal_env_cache(env); struct s3jni_xQueryPhraseState s; jclass klazz = jCallback ? (*env)->GetObjectClass(env, jCallback) : NULL; if( !klazz ) return SQLITE_MISUSE; s.jc = jc; s.jCallback = jCallback; s.jFcx = jFcx; s.fext = fext; s.midCallback = (*env)->GetMethodID(env, klazz, "xCallback", "(Lorg.sqlite.jni.Fts5ExtensionApi;" "Lorg.sqlite.jni.Fts5Context;)I"); UNREF_L(klazz); EXCEPTION_IS_FATAL("Could not extract xQueryPhraseCallback.xCallback method."); return (jint)fext->xQueryPhrase(PtrGet_Fts5Context(jFcx), iPhrase, &s, s3jni_xQueryPhrase); } JDECLFtsXA(jint,xRowCount)(JENV_OSELF,jobject jCtx, jobject jOut64){ |
︙ | ︙ | |||
3990 3991 3992 3993 3994 3995 3996 | Fts5ExtDecl; return (jlong)fext->xRowid(PtrGet_Fts5Context(jCtx)); } JDECLFtsXA(int,xSetAuxdata)(JENV_OSELF,jobject jCtx, jobject jAux){ Fts5ExtDecl; int rc; | | | | | < | < | < > < | | > | | | > < > | | | | | | | 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 | Fts5ExtDecl; return (jlong)fext->xRowid(PtrGet_Fts5Context(jCtx)); } JDECLFtsXA(int,xSetAuxdata)(JENV_OSELF,jobject jCtx, jobject jAux){ Fts5ExtDecl; int rc; S3JniFts5AuxData * pAux; pAux = sqlite3_malloc(sizeof(*pAux)); if(!pAux){ if(jAux){ /* Emulate how xSetAuxdata() behaves when it cannot alloc ** its auxdata wrapper. */ s3jni_call_xDestroy(env, jAux); } return SQLITE_NOMEM; } pAux->jObj = REF_G(jAux); rc = fext->xSetAuxdata(PtrGet_Fts5Context(jCtx), pAux, S3JniFts5AuxData_xDestroy); return rc; } /* xToken() impl for xTokenize(). */ static int s3jni_xTokenize_xToken(void *p, int tFlags, const char* z, int nZ, int iStart, int iEnd){ int rc; LocalJniGetEnv; struct s3jni_xQueryPhraseState * const s = p; jbyteArray jba; if( s->tok.zPrev == z && s->tok.nPrev == nZ ){ jba = s->tok.jba; }else{ if(s->tok.jba){ UNREF_L(s->tok.jba); } s->tok.zPrev = z; s->tok.nPrev = nZ; s->tok.jba = (*env)->NewByteArray(env, (jint)nZ); if( !s->tok.jba ) return SQLITE_NOMEM; jba = s->tok.jba; (*env)->SetByteArrayRegion(env, jba, 0, (jint)nZ, (const jbyte*)z); } rc = (int)(*env)->CallIntMethod(env, s->jCallback, s->midCallback, (jint)tFlags, jba, (jint)iStart, (jint)iEnd); return rc; } /* ** Proxy for Fts5ExtensionApi.xTokenize() and ** fts5_tokenizer.xTokenize() */ static jint s3jni_fts5_xTokenize(JENV_OSELF, S3NphRef const *pRef, jint tokFlags, jobject jFcx, jbyteArray jbaText, jobject jCallback){ Fts5ExtDecl; S3JniEnv * const jc = S3JniGlobal_env_cache(env); struct s3jni_xQueryPhraseState s; int rc = 0; jbyte * const pText = jCallback ? s3jni_jbytearray_bytes(jbaText) : 0; jsize nText = pText ? (*env)->GetArrayLength(env, jbaText) : 0; jclass const klazz = jCallback ? (*env)->GetObjectClass(env, jCallback) : NULL; if( !klazz ) return SQLITE_MISUSE; memset(&s, 0, sizeof(s)); s.jc = jc; s.jCallback = jCallback; s.jFcx = jFcx; s.fext = fext; s.midCallback = (*env)->GetMethodID(env, klazz, "xToken", "(I[BII)I"); UNREF_L(klazz); IFTHREW { EXCEPTION_REPORT; EXCEPTION_CLEAR; s3jni_jbytearray_release(jbaText, pText); return SQLITE_ERROR; } s.tok.jba = REF_L(jbaText); s.tok.zPrev = (const char *)pText; s.tok.nPrev = (int)nText; if( pRef == &S3NphRefs.Fts5ExtensionApi ){ rc = fext->xTokenize(PtrGet_Fts5Context(jFcx), (const char *)pText, (int)nText, &s, s3jni_xTokenize_xToken); }else if( pRef == &S3NphRefs.fts5_tokenizer ){ fts5_tokenizer * const pTok = PtrGet_fts5_tokenizer(jSelf); rc = pTok->xTokenize(PtrGet_Fts5Tokenizer(jFcx), &s, tokFlags, (const char *)pText, (int)nText, s3jni_xTokenize_xToken); }else{ (*env)->FatalError(env, "This cannot happen. Maintenance required."); } if(s.tok.jba){ assert( s.tok.zPrev ); UNREF_L(s.tok.jba); } s3jni_jbytearray_release(jbaText, pText); return (jint)rc; } JDECLFtsXA(jint,xTokenize)(JENV_OSELF,jobject jFcx, jbyteArray jbaText, jobject jCallback){ return s3jni_fts5_xTokenize(env, jSelf, &S3NphRefs.Fts5ExtensionApi, 0, jFcx, jbaText, jCallback); } JDECLFtsTok(jint,xTokenize)(JENV_OSELF,jobject jFcx, jint tokFlags, jbyteArray jbaText, jobject jCallback){ return s3jni_fts5_xTokenize(env, jSelf, &S3NphRefs.Fts5Tokenizer, tokFlags, jFcx, jbaText, jCallback); } JDECLFtsXA(jobject,xUserData)(JENV_OSELF,jobject jFcx){ Fts5ExtDecl; Fts5JniAux * const pAux = fext->xUserData(PtrGet_Fts5Context(jFcx)); |
︙ | ︙ | |||
4279 4280 4281 4282 4283 4284 4285 | } JNIEXPORT jint JNICALL Java_org_sqlite_jni_tester_SQLTester_strglob( JENV_CSELF, jbyteArray baG, jbyteArray baT ){ int rc = 0; | | | < > | | | 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 | } JNIEXPORT jint JNICALL Java_org_sqlite_jni_tester_SQLTester_strglob( JENV_CSELF, jbyteArray baG, jbyteArray baT ){ int rc = 0; jbyte * const pG = s3jni_jbytearray_bytes(baG); jbyte * const pT = pG ? s3jni_jbytearray_bytes(baT) : 0; s3jni_oom_check(pT); /* Note that we're relying on the byte arrays having been NUL-terminated on the Java side. */ rc = !SQLTester_strnotglob((const char *)pG, (const char *)pT); s3jni_jbytearray_release(baG, pG); s3jni_jbytearray_release(baT, pT); return rc; } static int SQLTester_auto_extension(sqlite3 *pDb, const char **pzErr, const struct sqlite3_api_routines *ignored){ sqlite3_create_function(pDb, "dup", 1, SQLITE_UTF8, &SQLTester, |
︙ | ︙ | |||
4312 4313 4314 4315 4316 4317 4318 | #endif /* S3JNI_ENABLE_SQLTester */ //////////////////////////////////////////////////////////////////////// // End of SQLTester bindings. Start of lower-level bits. //////////////////////////////////////////////////////////////////////// | | | | | | > > | > > | | | | | | < < < < < < < | 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 | #endif /* S3JNI_ENABLE_SQLTester */ //////////////////////////////////////////////////////////////////////// // End of SQLTester bindings. Start of lower-level bits. //////////////////////////////////////////////////////////////////////// /* ** Uncaches the current JNIEnv from the S3JniGlobal state, clearing any ** resources owned by that cache entry and making that slot available ** for re-use. It is important that the Java-side decl of this ** function be declared as synchronous. */ JNIEXPORT jboolean JNICALL Java_org_sqlite_jni_SQLite3Jni_uncacheJniEnv(JENV_CSELF){ int rc; MUTEX_ENV_ENTER; rc = S3JniGlobal_env_uncache(env); MUTEX_ENV_LEAVE; return rc ? JNI_TRUE : JNI_FALSE; } /* ** Called during static init of the SQLite3Jni class to sync certain ** compile-time constants to Java-space. ** ** This routine is part of the reason why we have to #include ** sqlite3.c instead of sqlite3.h. */ JNIEXPORT void JNICALL Java_org_sqlite_jni_SQLite3Jni_init(JENV_CSELF){ enum JType { JTYPE_INT, JTYPE_BOOL }; typedef struct { const char *zName; enum JType jtype; int value; } ConfigFlagEntry; const ConfigFlagEntry aLimits[] = { {"SQLITE_MAX_ALLOCATION_SIZE", JTYPE_INT, SQLITE_MAX_ALLOCATION_SIZE}, {"SQLITE_LIMIT_LENGTH", JTYPE_INT, SQLITE_LIMIT_LENGTH}, {"SQLITE_MAX_LENGTH", JTYPE_INT, SQLITE_MAX_LENGTH}, {"SQLITE_LIMIT_SQL_LENGTH", JTYPE_INT, SQLITE_LIMIT_SQL_LENGTH}, {"SQLITE_MAX_SQL_LENGTH", JTYPE_INT, SQLITE_MAX_SQL_LENGTH}, {"SQLITE_LIMIT_COLUMN", JTYPE_INT, SQLITE_LIMIT_COLUMN}, {"SQLITE_MAX_COLUMN", JTYPE_INT, SQLITE_MAX_COLUMN}, |
︙ | ︙ | |||
4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 | {"SQLITE_LIMIT_TRIGGER_DEPTH", JTYPE_INT, SQLITE_LIMIT_TRIGGER_DEPTH}, {"SQLITE_MAX_TRIGGER_DEPTH", JTYPE_INT, SQLITE_MAX_TRIGGER_DEPTH}, {"SQLITE_LIMIT_WORKER_THREADS", JTYPE_INT, SQLITE_LIMIT_WORKER_THREADS}, {"SQLITE_MAX_WORKER_THREADS", JTYPE_INT, SQLITE_MAX_WORKER_THREADS}, {0,0} }; jfieldID fieldId; const ConfigFlagEntry * pConfFlag; memset(&S3JniGlobal, 0, sizeof(S3JniGlobal)); | > > > > > | | | > > | > > > > > | > > > | > > > > > > | > > > > > > > > > > > | > > > > > > > > > | > > > > > > | > > > > > > > > < | 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 | {"SQLITE_LIMIT_TRIGGER_DEPTH", JTYPE_INT, SQLITE_LIMIT_TRIGGER_DEPTH}, {"SQLITE_MAX_TRIGGER_DEPTH", JTYPE_INT, SQLITE_MAX_TRIGGER_DEPTH}, {"SQLITE_LIMIT_WORKER_THREADS", JTYPE_INT, SQLITE_LIMIT_WORKER_THREADS}, {"SQLITE_MAX_WORKER_THREADS", JTYPE_INT, SQLITE_MAX_WORKER_THREADS}, {0,0} }; jfieldID fieldId; jclass klazz; const ConfigFlagEntry * pConfFlag; if( 0==sqlite3_threadsafe() ){ (*env)->FatalError(env, "sqlite3 was not built with SQLITE_THREADSAFE."); return; } memset(&S3JniGlobal, 0, sizeof(S3JniGlobal)); if( (*env)->GetJavaVM(env, &SJG.jvm) ){ (*env)->FatalError(env, "GetJavaVM() failure shouldn't be possible."); return; } /* Grab references to various global classes and objects... */ SJG.g.cObj = REF_G((*env)->FindClass(env,"java/lang/Object")); EXCEPTION_IS_FATAL("Error getting reference to Object class."); SJG.g.cLong = REF_G((*env)->FindClass(env,"java/lang/Long")); EXCEPTION_IS_FATAL("Error getting reference to Long class."); SJG.g.ctorLong1 = (*env)->GetMethodID(env, SJG.g.cLong, "<init>", "(J)V"); EXCEPTION_IS_FATAL("Error getting reference to Long constructor."); SJG.g.cString = REF_G((*env)->FindClass(env,"java/lang/String")); EXCEPTION_IS_FATAL("Error getting reference to String class."); SJG.g.ctorStringBA = (*env)->GetMethodID(env, SJG.g.cString, "<init>", "([BLjava/nio/charset/Charset;)V"); EXCEPTION_IS_FATAL("Error getting reference to String(byte[],Charset) ctor."); SJG.g.stringGetBytes = (*env)->GetMethodID(env, SJG.g.cString, "getBytes", "(Ljava/nio/charset/Charset;)[B"); EXCEPTION_IS_FATAL("Error getting reference to String.getBytes(Charset)."); { /* StandardCharsets.UTF_8 */ jfieldID fUtf8; klazz = (*env)->FindClass(env,"java/nio/charset/StandardCharsets"); EXCEPTION_IS_FATAL("Error getting reference to StandardCharsets class."); fUtf8 = (*env)->GetStaticFieldID(env, klazz, "UTF_8", "Ljava/nio/charset/Charset;"); EXCEPTION_IS_FATAL("Error getting StandardCharsets.UTF_8 field."); SJG.g.oCharsetUtf8 = REF_G((*env)->GetStaticObjectField(env, klazz, fUtf8)); EXCEPTION_IS_FATAL("Error getting reference to StandardCharsets.UTF_8."); UNREF_L(klazz); } #ifdef SQLITE_ENABLE_FTS5 klazz = (*env)->FindClass(env, "org/sqlite/jni/Fts5PhraseIter"); EXCEPTION_IS_FATAL("Error getting reference to org.sqlite.jni.Fts5PhraseIter."); SJG.fts5.jPhraseIter.fidA = (*env)->GetFieldID(env, klazz, "a", "J"); EXCEPTION_IS_FATAL("Cannot get Fts5PhraseIter.a field."); SJG.fts5.jPhraseIter.fidB = (*env)->GetFieldID(env, klazz, "b", "J"); EXCEPTION_IS_FATAL("Cannot get Fts5PhraseIter.b field."); UNREF_L(klazz); #endif SJG.envCache.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); s3jni_oom_check( SJG.envCache.mutex ); SJG.perDb.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); s3jni_oom_check( SJG.perDb.mutex ); SJG.autoExt.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); s3jni_oom_check( SJG.autoExt.mutex ); #if S3JNI_METRICS_MUTEX SJG.metrics.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); s3jni_oom_check( SJG.metrics.mutex ); #endif sqlite3_shutdown() /* So that it becomes legal for Java-level code to call ** sqlite3_config(), if it's ever implemented. */; /* Set up static "consts" of the SQLite3Jni class. */ for( pConfFlag = &aLimits[0]; pConfFlag->zName; ++pConfFlag ){ char const * zSig = (JTYPE_BOOL == pConfFlag->jtype) ? "Z" : "I"; fieldId = (*env)->GetStaticFieldID(env, jKlazz, pConfFlag->zName, zSig); EXCEPTION_IS_FATAL("Missing an expected static member of the SQLite3Jni class."); assert(fieldId); switch(pConfFlag->jtype){ case JTYPE_INT: (*env)->SetStaticIntField(env, jKlazz, fieldId, (jint)pConfFlag->value); break; case JTYPE_BOOL: (*env)->SetStaticBooleanField(env, jKlazz, fieldId, pConfFlag->value ? JNI_TRUE : JNI_FALSE); break; } EXCEPTION_IS_FATAL("Seting a static member of the SQLite3Jni class failed."); } } |
Changes to ext/jni/src/c/sqlite3-jni.h.
︙ | ︙ | |||
839 840 841 842 843 844 845 846 847 848 849 850 851 852 | * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_bind_text * Signature: (Lorg/sqlite/jni/sqlite3_stmt;I[BI)I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1bind_1text (JNIEnv *, jclass, jobject, jint, jbyteArray, jint); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_bind_zeroblob * Signature: (Lorg/sqlite/jni/sqlite3_stmt;II)I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1bind_1zeroblob (JNIEnv *, jclass, jobject, jint, jint); | > > > > > > > > | 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 | * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_bind_text * Signature: (Lorg/sqlite/jni/sqlite3_stmt;I[BI)I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1bind_1text (JNIEnv *, jclass, jobject, jint, jbyteArray, jint); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_bind_text16 * Signature: (Lorg/sqlite/jni/sqlite3_stmt;I[BI)I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1bind_1text16 (JNIEnv *, jclass, jobject, jint, jbyteArray, jint); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_bind_zeroblob * Signature: (Lorg/sqlite/jni/sqlite3_stmt;II)I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1bind_1zeroblob (JNIEnv *, jclass, jobject, jint, jint); |
︙ | ︙ | |||
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 | * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_column_table_name * Signature: (Lorg/sqlite/jni/sqlite3_stmt;I)Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1column_1table_1name (JNIEnv *, jclass, jobject, jint); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_column_text16 * Signature: (Lorg/sqlite/jni/sqlite3_stmt;I)Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1column_1text16 (JNIEnv *, jclass, jobject, jint); | > > > > > > > > < < < < < < < < | 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 | * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_column_table_name * Signature: (Lorg/sqlite/jni/sqlite3_stmt;I)Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1column_1table_1name (JNIEnv *, jclass, jobject, jint); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_column_text_utf8 * Signature: (Lorg/sqlite/jni/sqlite3_stmt;I)[B */ JNIEXPORT jbyteArray JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1column_1text_1utf8 (JNIEnv *, jclass, jobject, jint); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_column_text16 * Signature: (Lorg/sqlite/jni/sqlite3_stmt;I)Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1column_1text16 (JNIEnv *, jclass, jobject, jint); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_column_type * Signature: (Lorg/sqlite/jni/sqlite3_stmt;I)I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1column_1type (JNIEnv *, jclass, jobject, jint); |
︙ | ︙ | |||
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 | * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_compileoption_used * Signature: (Ljava/lang/String;)Z */ JNIEXPORT jboolean JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1compileoption_1used (JNIEnv *, jclass, jstring); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_create_collation * Signature: (Lorg/sqlite/jni/sqlite3;Ljava/lang/String;ILorg/sqlite/jni/Collation;)I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1create_1collation (JNIEnv *, jclass, jobject, jstring, jint, jobject); | > > > > > > > > > > > > > > > > | 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 | * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_compileoption_used * Signature: (Ljava/lang/String;)Z */ JNIEXPORT jboolean JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1compileoption_1used (JNIEnv *, jclass, jstring); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_config * Signature: (I)I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1config__I (JNIEnv *, jclass, jint); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_config * Signature: (Lorg/sqlite/jni/SQLLog;)I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1config__Lorg_sqlite_jni_SQLLog_2 (JNIEnv *, jclass, jobject); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_create_collation * Signature: (Lorg/sqlite/jni/sqlite3;Ljava/lang/String;ILorg/sqlite/jni/Collation;)I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1create_1collation (JNIEnv *, jclass, jobject, jstring, jint, jobject); |
︙ | ︙ | |||
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 | * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_initialize * Signature: ()I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1initialize (JNIEnv *, jclass); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_last_insert_rowid * Signature: (Lorg/sqlite/jni/sqlite3;)J */ JNIEXPORT jlong JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1last_1insert_1rowid (JNIEnv *, jclass, jobject); | > > > > > > > > > > > > > > > > | 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 | * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_initialize * Signature: ()I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1initialize (JNIEnv *, jclass); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_interrupt * Signature: (Lorg/sqlite/jni/sqlite3;)V */ JNIEXPORT void JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1interrupt (JNIEnv *, jclass, jobject); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_is_interrupted * Signature: (Lorg/sqlite/jni/sqlite3;)Z */ JNIEXPORT jboolean JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1is_1interrupted (JNIEnv *, jclass, jobject); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_last_insert_rowid * Signature: (Lorg/sqlite/jni/sqlite3;)J */ JNIEXPORT jlong JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1last_1insert_1rowid (JNIEnv *, jclass, jobject); |
︙ | ︙ | |||
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 | * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_prepare_v3 * Signature: (Lorg/sqlite/jni/sqlite3;[BIILorg/sqlite/jni/OutputPointer/sqlite3_stmt;Lorg/sqlite/jni/OutputPointer/Int32;)I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1prepare_1v3 (JNIEnv *, jclass, jobject, jbyteArray, jint, jint, jobject, jobject); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_progress_handler * Signature: (Lorg/sqlite/jni/sqlite3;ILorg/sqlite/jni/ProgressHandler;)V */ JNIEXPORT void JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1progress_1handler (JNIEnv *, jclass, jobject, jint, jobject); | > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 | * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_prepare_v3 * Signature: (Lorg/sqlite/jni/sqlite3;[BIILorg/sqlite/jni/OutputPointer/sqlite3_stmt;Lorg/sqlite/jni/OutputPointer/Int32;)I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1prepare_1v3 (JNIEnv *, jclass, jobject, jbyteArray, jint, jint, jobject, jobject); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_preupdate_blobwrite * Signature: (Lorg/sqlite/jni/sqlite3;)I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1preupdate_1blobwrite (JNIEnv *, jclass, jobject); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_preupdate_count * Signature: (Lorg/sqlite/jni/sqlite3;)I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1preupdate_1count (JNIEnv *, jclass, jobject); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_preupdate_depth * Signature: (Lorg/sqlite/jni/sqlite3;)I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1preupdate_1depth (JNIEnv *, jclass, jobject); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_preupdate_hook * Signature: (Lorg/sqlite/jni/sqlite3;Lorg/sqlite/jni/PreUpdateHook;)Lorg/sqlite/jni/PreUpdateHook; */ JNIEXPORT jobject JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1preupdate_1hook (JNIEnv *, jclass, jobject, jobject); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_preupdate_new * Signature: (Lorg/sqlite/jni/sqlite3;ILorg/sqlite/jni/OutputPointer/sqlite3_value;)I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1preupdate_1new (JNIEnv *, jclass, jobject, jint, jobject); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_preupdate_old * Signature: (Lorg/sqlite/jni/sqlite3;ILorg/sqlite/jni/OutputPointer/sqlite3_value;)I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1preupdate_1old (JNIEnv *, jclass, jobject, jint, jobject); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_progress_handler * Signature: (Lorg/sqlite/jni/sqlite3;ILorg/sqlite/jni/ProgressHandler;)V */ JNIEXPORT void JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1progress_1handler (JNIEnv *, jclass, jobject, jint, jobject); |
︙ | ︙ | |||
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 | * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_result_text64 * Signature: (Lorg/sqlite/jni/sqlite3_context;[BJI)V */ JNIEXPORT void JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1result_1text64 (JNIEnv *, jclass, jobject, jbyteArray, jlong, jint); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_status * Signature: (ILorg/sqlite/jni/OutputPointer/Int32;Lorg/sqlite/jni/OutputPointer/Int32;Z)I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1status (JNIEnv *, jclass, jint, jobject, jobject, jboolean); | > > > > > > > > | 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 | * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_result_text64 * Signature: (Lorg/sqlite/jni/sqlite3_context;[BJI)V */ JNIEXPORT void JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1result_1text64 (JNIEnv *, jclass, jobject, jbyteArray, jlong, jint); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_shutdown * Signature: ()I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1shutdown (JNIEnv *, jclass); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_status * Signature: (ILorg/sqlite/jni/OutputPointer/Int32;Lorg/sqlite/jni/OutputPointer/Int32;Z)I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1status (JNIEnv *, jclass, jint, jobject, jobject, jboolean); |
︙ | ︙ | |||
1631 1632 1633 1634 1635 1636 1637 | * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_value_java_object * Signature: (Lorg/sqlite/jni/sqlite3_value;)Ljava/lang/Object; */ JNIEXPORT jobject JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1value_1java_1object (JNIEnv *, jclass, jobject); | < < < < < < < < | 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 | * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_value_java_object * Signature: (Lorg/sqlite/jni/sqlite3_value;)Ljava/lang/Object; */ JNIEXPORT jobject JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1value_1java_1object (JNIEnv *, jclass, jobject); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_value_text_utf8 * Signature: (Lorg/sqlite/jni/sqlite3_value;)[B */ JNIEXPORT jbyteArray JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1value_1text_1utf8 (JNIEnv *, jclass, jobject); |
︙ | ︙ | |||
1711 1712 1713 1714 1715 1716 1717 | * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_value_subtype * Signature: (Lorg/sqlite/jni/sqlite3_value;)I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1value_1subtype (JNIEnv *, jclass, jobject); | < < < < < < < < | 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 | * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_value_subtype * Signature: (Lorg/sqlite/jni/sqlite3_value;)I */ JNIEXPORT jint JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1value_1subtype (JNIEnv *, jclass, jobject); /* * Class: org_sqlite_jni_SQLite3Jni * Method: sqlite3_do_something_for_developer * Signature: ()V */ JNIEXPORT void JNICALL Java_org_sqlite_jni_SQLite3Jni_sqlite3_1do_1something_1for_1developer (JNIEnv *, jclass); |
︙ | ︙ |
Changes to ext/jni/src/org/sqlite/jni/AutoExtension.java.
︙ | ︙ | |||
10 11 12 13 14 15 16 | ** ************************************************************************* ** This file is part of the JNI bindings for the sqlite3 C API. */ package org.sqlite.jni; /** | | > | | < | > > > > > > > > > | | 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | ** ************************************************************************* ** This file is part of the JNI bindings for the sqlite3 C API. */ package org.sqlite.jni; /** A callback for use with the sqlite3_auto_extension() family of APIs. */ public interface AutoExtension { /** Must function as described for a sqlite3_auto_extension() callback, with the caveat that the signature is shorter. AutoExtensions may throw and the exception's error message will be set as the db's error string. Tips for implementations: - Opening a database from an auto-extension handler will lead to an endless recursion of the auto-handler triggering itself indirectly for each newly-opened database. - If this routine is stateful, it may be useful to make the overridden method synchronized. - Results are undefined if db is closed by an auto-extension. */ int xEntryPoint(sqlite3 db); } |
Changes to ext/jni/src/org/sqlite/jni/Fts5.java.
︙ | ︙ | |||
23 24 25 26 27 28 29 | */ public final class Fts5 { /* Not used */ private Fts5(){} //! Callback type for use with xTokenize() variants public static interface xTokenizeCallback { | | | 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | */ public final class Fts5 { /* Not used */ private Fts5(){} //! Callback type for use with xTokenize() variants public static interface xTokenizeCallback { int xToken(int tFlags, byte[] txt, int iStart, int iEnd); } public static final int FTS5_TOKENIZE_QUERY = 0x0001; public static final int FTS5_TOKENIZE_PREFIX = 0x0002; public static final int FTS5_TOKENIZE_DOCUMENT = 0x0004; public static final int FTS5_TOKENIZE_AUX = 0x0008; public static final int FTS5_TOKEN_COLOCATED = 0x0001; |
︙ | ︙ |
Changes to ext/jni/src/org/sqlite/jni/Fts5ExtensionApi.java.
︙ | ︙ | |||
19 20 21 22 23 24 25 | FAR FROM COMPLETE and the feasibility of binding this to Java is still undetermined. This might be removed. */ public final class Fts5ExtensionApi extends NativePointerHolder<Fts5ExtensionApi> { //! Only called from JNI private Fts5ExtensionApi(){} | | | | | | | | | | | | | | | | | | | | | | | | 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | FAR FROM COMPLETE and the feasibility of binding this to Java is still undetermined. This might be removed. */ public final class Fts5ExtensionApi extends NativePointerHolder<Fts5ExtensionApi> { //! Only called from JNI private Fts5ExtensionApi(){} private final int iVersion = 2; /* Callback type for used by xQueryPhrase(). */ public static interface xQueryPhraseCallback { int xCallback(Fts5ExtensionApi fapi, Fts5Context cx); } /** Returns the singleton instance of this class. */ public static native Fts5ExtensionApi getInstance(); public native int xColumnCount(@NotNull Fts5Context fcx); public native int xColumnSize(@NotNull Fts5Context cx, int iCol, @NotNull OutputPointer.Int32 pnToken); public native int xColumnText(@NotNull Fts5Context cx, int iCol, @NotNull OutputPointer.String txt); public native int xColumnTotalSize(@NotNull Fts5Context fcx, int iCol, @NotNull OutputPointer.Int64 pnToken); public native Object xGetAuxdata(@NotNull Fts5Context cx, boolean clearIt); public native int xInst(@NotNull Fts5Context cx, int iIdx, @NotNull OutputPointer.Int32 piPhrase, @NotNull OutputPointer.Int32 piCol, @NotNull OutputPointer.Int32 piOff); public native int xInstCount(@NotNull Fts5Context fcx, @NotNull OutputPointer.Int32 pnInst); public native int xPhraseCount(@NotNull Fts5Context fcx); public native int xPhraseFirst(@NotNull Fts5Context cx, int iPhrase, @NotNull Fts5PhraseIter iter, @NotNull OutputPointer.Int32 iCol, @NotNull OutputPointer.Int32 iOff); public native int xPhraseFirstColumn(@NotNull Fts5Context cx, int iPhrase, @NotNull Fts5PhraseIter iter, @NotNull OutputPointer.Int32 iCol); public native void xPhraseNext(@NotNull Fts5Context cx, @NotNull Fts5PhraseIter iter, @NotNull OutputPointer.Int32 iCol, @NotNull OutputPointer.Int32 iOff); public native void xPhraseNextColumn(@NotNull Fts5Context cx, @NotNull Fts5PhraseIter iter, @NotNull OutputPointer.Int32 iCol); public native int xPhraseSize(@NotNull Fts5Context fcx, int iPhrase); public native int xQueryPhrase(@NotNull Fts5Context cx, int iPhrase, @NotNull xQueryPhraseCallback callback); public native int xRowCount(@NotNull Fts5Context fcx, @NotNull OutputPointer.Int64 nRow); public native long xRowid(@NotNull Fts5Context cx); /* Note that the JNI binding lacks the C version's xDelete() callback argument. Instead, if pAux has an xDestroy() method, it is called if the FTS5 API finalizes the aux state (including if allocation of storage for the auxdata fails). Any reference to pAux held by the JNI layer will be relinquished regardless of whether pAux has an xDestroy() method. */ public native int xSetAuxdata(@NotNull Fts5Context cx, @Nullable Object pAux); public native int xTokenize(@NotNull Fts5Context cx, @NotNull byte[] pText, @NotNull Fts5.xTokenizeCallback callback); public native Object xUserData(Fts5Context cx); //^^^ returns the pointer passed as the 3rd arg to the C-level // fts5_api::xCreateFunction(). } |
Changes to ext/jni/src/org/sqlite/jni/NativePointerHolder.java.
︙ | ︙ | |||
24 25 26 27 28 29 30 | function signature. These objects do not _own_ the pointer they refer to. They are intended simply to communicate that pointer between C and Java. */ public class NativePointerHolder<ContextType> { //! Only set from JNI, where access permissions don't matter. | | | 24 25 26 27 28 29 30 31 32 33 | function signature. These objects do not _own_ the pointer they refer to. They are intended simply to communicate that pointer between C and Java. */ public class NativePointerHolder<ContextType> { //! Only set from JNI, where access permissions don't matter. private volatile long nativePointer = 0; public final long getNativePointer(){ return nativePointer; } } |
Changes to ext/jni/src/org/sqlite/jni/OutputPointer.java.
︙ | ︙ | |||
32 33 34 35 36 37 38 39 40 41 42 43 44 45 | assert( null==out.get() ); ``` With the minor exception that the primitive types permit direct access to the object's value via the `value` property, whereas the JNI-level opaque types do not permit client-level code to set that property. */ public final class OutputPointer { /** Output pointer for use with routines, such as sqlite3_open(), which return a database handle via an output pointer. These pointers can only be set by the JNI layer, not by client-level | > > > | 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | assert( null==out.get() ); ``` With the minor exception that the primitive types permit direct access to the object's value via the `value` property, whereas the JNI-level opaque types do not permit client-level code to set that property. Warning: do not share instances of these classes across threads. Doing so may lead to corrupting sqlite3-internal state. */ public final class OutputPointer { /** Output pointer for use with routines, such as sqlite3_open(), which return a database handle via an output pointer. These pointers can only be set by the JNI layer, not by client-level |
︙ | ︙ | |||
78 79 80 81 82 83 84 85 86 87 88 89 90 91 | //! Equivalent to calling get() then clear(). public final org.sqlite.jni.sqlite3_stmt take(){ final org.sqlite.jni.sqlite3_stmt v = value; value = null; return v; } } /** Output pointer for use with native routines which return integers via output pointers. */ public static final class Int32 { /** | > > > > > > > > > > > > > > > > > > > > > > | 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | //! Equivalent to calling get() then clear(). public final org.sqlite.jni.sqlite3_stmt take(){ final org.sqlite.jni.sqlite3_stmt v = value; value = null; return v; } } /** Output pointer for use with routines, such as sqlite3_prepupdate_new(), which return a sqlite3_value handle via an output pointer. These pointers can only be set by the JNI layer, not by client-level code. */ public static final class sqlite3_value { private org.sqlite.jni.sqlite3_value value; //! Initializes with a null value. public sqlite3_value(){value = null;} //! Sets the current value to null. public void clear(){value = null;} //! Returns the current value. public final org.sqlite.jni.sqlite3_value get(){return value;} //! Equivalent to calling get() then clear(). public final org.sqlite.jni.sqlite3_value take(){ final org.sqlite.jni.sqlite3_value v = value; value = null; return v; } } /** Output pointer for use with native routines which return integers via output pointers. */ public static final class Int32 { /** |
︙ | ︙ |
Added ext/jni/src/org/sqlite/jni/PreUpdateHook.java.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | /* ** 2023-08-23 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file is part of the JNI bindings for the sqlite3 C API. */ package org.sqlite.jni; /** A callback for use with sqlite3_preupdate_hook(). */ public interface PreUpdateHook { /** Must function as described for the sqlite3_preupdate_hook(). callback, with the slight signature change. Must not throw. Any exceptions may emit debugging messages and will be suppressed. */ void xPreUpdate(sqlite3 db, int op, String dbName, String dbTable, long iKey1, long iKey2 ); } |
Changes to ext/jni/src/org/sqlite/jni/SQLFunction.java.
︙ | ︙ | |||
17 18 19 20 21 22 23 | SQLFunction is used in conjunction with the sqlite3_create_function() JNI-bound API to give that native code access to the callback functions needed in order to implement SQL functions in Java. This class is not used by itself, but is a marker base class. The three UDF types are modelled by the inner classes Scalar, | | | | | | > > | | 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | SQLFunction is used in conjunction with the sqlite3_create_function() JNI-bound API to give that native code access to the callback functions needed in order to implement SQL functions in Java. This class is not used by itself, but is a marker base class. The three UDF types are modelled by the inner classes Scalar, Aggregate<T>, and Window<T>. Most simply, clients may subclass those, or create anonymous classes from them, to implement UDFs. Clients are free to create their own classes for use with UDFs, so long as they conform to the public interfaces defined by those three classes. The JNI layer only actively relies on the SQLFunction base class and the method names and signatures used by the UDF callback interfaces. */ public abstract class SQLFunction { /** PerContextState assists aggregate and window functions in managing their accumulator state across calls to the UDF's callbacks. If a given aggregate or window function is called multiple times in a single SQL statement, e.g. SELECT MYFUNC(A), MYFUNC(B)..., then the clients need some way of knowing which call is which so that they can map their state between their various UDF callbacks and reset it via xFinal(). This class takes care of such |
︙ | ︙ | |||
92 93 94 95 96 97 98 | return null==h ? null : h.value; } } //! Subclass for creating scalar functions. public static abstract class Scalar extends SQLFunction { | > | > > > > | > > > > > | > > | 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | return null==h ? null : h.value; } } //! Subclass for creating scalar functions. public static abstract class Scalar extends SQLFunction { /** As for the xFunc() argument of the C API's sqlite3_create_function(). If this function throws, it is translated into an sqlite3_result_error(). */ public abstract void xFunc(sqlite3_context cx, sqlite3_value[] args); /** Optionally override to be notified when the UDF is finalized by SQLite. */ public void xDestroy() {} } /** SQLFunction Subclass for creating aggregate functions. Its T is the data type of its "accumulator" state, an instance of which is intended to be be managed using the getAggregateState() and takeAggregateState() methods. */ public static abstract class Aggregate<T> extends SQLFunction { /** As for the xStep() argument of the C API's sqlite3_create_function(). If this function throws, the exception is not propagated and a warning might be emitted to a debugging channel. */ public abstract void xStep(sqlite3_context cx, sqlite3_value[] args); /** As for the xFinal() argument of the C API's sqlite3_create_function(). If this function throws, it is translated into an sqlite3_result_error(). */ public abstract void xFinal(sqlite3_context cx); /** Optionally override to be notified when the UDF is finalized by SQLite. */ public void xDestroy() {} |
︙ | ︙ | |||
159 160 161 162 163 164 165 | Window<T> inherits from Aggregate<T> and each instance is required to implement the inherited abstract methods from that class. See Aggregate<T> for information on managing the UDF's invocation-specific state. */ public static abstract class Window<T> extends Aggregate<T> { | > | > > > > > | > > | 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | Window<T> inherits from Aggregate<T> and each instance is required to implement the inherited abstract methods from that class. See Aggregate<T> for information on managing the UDF's invocation-specific state. */ public static abstract class Window<T> extends Aggregate<T> { /** As for the xInverse() argument of the C API's sqlite3_create_window_function(). If this function throws, the exception is not propagated and a warning might be emitted to a debugging channel. */ public abstract void xInverse(sqlite3_context cx, sqlite3_value[] args); /** As for the xValue() argument of the C API's sqlite3_create_window_function(). See xInverse() for the fate of any exceptions this throws. */ public abstract void xValue(sqlite3_context cx); } } |
Added ext/jni/src/org/sqlite/jni/SQLLog.java.
> > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | /* ** 2023-08-23 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file is part of the JNI bindings for the sqlite3 C API. */ package org.sqlite.jni; /** A callback for use with sqlite3_config(SQLLog). */ public interface SQLLog { /** Must function as described for sqlite3_config(SQLITE_CONFIG_SQLLOG) callback, with the slight signature change. */ void xSqllog(sqlite3 db, String msg, int msgType ); } |
Changes to ext/jni/src/org/sqlite/jni/SQLite3Jni.java.
︙ | ︙ | |||
78 79 80 81 82 83 84 | Java's `String.getBytes(StandardCharsets.UTF_8)` performs the proper conversion in Java, and there are no JNI C APIs for that conversion (JNI's `NewStringUTF()` requires its input to be in MUTF-8). The known consequences and limitations this discrepancy places on the SQLite3 JNI binding include: | | | < < < < < < < < < < < < > | | 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | Java's `String.getBytes(StandardCharsets.UTF_8)` performs the proper conversion in Java, and there are no JNI C APIs for that conversion (JNI's `NewStringUTF()` requires its input to be in MUTF-8). The known consequences and limitations this discrepancy places on the SQLite3 JNI binding include: - Any functions which return state from a database take extra care to perform proper conversion, at the cost of efficiency. - C functions which take C-style strings without a length argument require special care when taking input from Java. In particular, Java strings converted to byte arrays for encoding purposes are not NUL-terminated, and conversion to a Java byte array must be careful to add one. Functions which take a length do not require this so long as the length is provided. Search the SQLite3Jni class for "\0" for many examples. - Similarly, C-side code which deals with strings which might not be NUL-terminated (e.g. while tokenizing in FTS5-related code) cannot use JNI's new-string functions to return them to Java because none of those APIs take a string-length argument. Such cases must return byte arrays instead of strings. |
︙ | ︙ | |||
129 130 131 132 133 134 135 | private static native void init(); /** Each thread which uses the SQLite3 JNI APIs should call uncacheJniEnv() when it is done with the library - either right before it terminates or when it is finished using the SQLite API. This will clean up any cached per-JNIEnv info. Calling into the | | < < < < < < < < < | > | | | | 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | private static native void init(); /** Each thread which uses the SQLite3 JNI APIs should call uncacheJniEnv() when it is done with the library - either right before it terminates or when it is finished using the SQLite API. This will clean up any cached per-JNIEnv info. Calling into the library will re-initialize the cache on demand. This process does _not_ close any databases or finalize any prepared statements because their ownership does not depend on a given thread. For proper library behavior, and to avoid C-side leaks, be sure to finalize all statements and close all databases before calling this function. Calling this from the main application thread is not strictly required but is "polite." Additional threads must call this before ending or they will leak cache entries in the C heap, which in turn may keep numerous Java-side global references active. |
︙ | ︙ | |||
169 170 171 172 173 174 175 | // grouped by category. /** Functions almost as documented for the C API, with these exceptions: | | | | < < < < < < > | < | < < > > > < < > > | > > | < < < < | | | | | | < | | | > > > > > > > > > > > > > > > > > > > > | > > > > > > | > > > > > > > > > > > > > > > > | | | | > > > | > | | | < | | < < < < < | | | | | | | | | | | | | | | | | | 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 | // grouped by category. /** Functions almost as documented for the C API, with these exceptions: - The callback interface is is shorter because of cross-language differences. Specifically, 3rd argument to the C auto-extension callback interface is unnecessary here. The C API docs do not specifically say so, if the list of auto-extensions is manipulated from an auto-extension, it is undefined which, if any, auto-extensions will subsequently execute for the current database. See the AutoExtension class docs for more information. */ public static native int sqlite3_auto_extension(@NotNull AutoExtension callback); /** Results are undefined if data is not null and n<0 || n>=data.length. */ public static native int sqlite3_bind_blob( @NotNull sqlite3_stmt stmt, int ndx, @Nullable byte[] data, int n ); public static int sqlite3_bind_blob( @NotNull sqlite3_stmt stmt, int ndx, @Nullable byte[] data ){ return (null==data) ? sqlite3_bind_null(stmt, ndx) : sqlite3_bind_blob(stmt, ndx, data, data.length); } public static native int sqlite3_bind_double( @NotNull sqlite3_stmt stmt, int ndx, double v ); public static native int sqlite3_bind_int( @NotNull sqlite3_stmt stmt, int ndx, int v ); public static native int sqlite3_bind_int64( @NotNull sqlite3_stmt stmt, int ndx, long v ); public static native int sqlite3_bind_null( @NotNull sqlite3_stmt stmt, int ndx ); public static native int sqlite3_bind_parameter_count( @NotNull sqlite3_stmt stmt ); /** Requires that paramName be a NUL-terminated UTF-8 string. */ public static native int sqlite3_bind_parameter_index( @NotNull sqlite3_stmt stmt, byte[] paramName ); public static int sqlite3_bind_parameter_index( @NotNull sqlite3_stmt stmt, @NotNull String paramName ){ final byte[] utf8 = (paramName+"\0").getBytes(StandardCharsets.UTF_8); return sqlite3_bind_parameter_index(stmt, utf8); } /** Works like the C-level sqlite3_bind_text() but assumes SQLITE_TRANSIENT for the final C API parameter. Results are undefined if data is not null and maxBytes>=data.length. If maxBytes is negative then results are undefined if data is not null and does not contain a NUL byte. */ private static native int sqlite3_bind_text( @NotNull sqlite3_stmt stmt, int ndx, @Nullable byte[] data, int maxBytes ); /** Converts data, if not null, to a UTF-8-encoded byte array and binds it as such, returning the result of the C-level sqlite3_bind_null() or sqlite3_bind_text(). */ public static int sqlite3_bind_text( @NotNull sqlite3_stmt stmt, int ndx, @Nullable String data ){ if(null == data) return sqlite3_bind_null(stmt, ndx); final byte[] utf8 = data.getBytes(StandardCharsets.UTF_8); return sqlite3_bind_text(stmt, ndx, utf8, utf8.length); } /** Requires that data be null or in UTF-8 encoding. */ public static int sqlite3_bind_text( @NotNull sqlite3_stmt stmt, int ndx, @Nullable byte[] data ){ return (null == data) ? sqlite3_bind_null(stmt, ndx) : sqlite3_bind_text(stmt, ndx, data, data.length); } /** Identical to the sqlite3_bind_text() overload with the same signature but requires that its input be encoded in UTF-16 in platform byte order. */ private static native int sqlite3_bind_text16( @NotNull sqlite3_stmt stmt, int ndx, @Nullable byte[] data, int maxBytes ); /** Converts its string argument to UTF-16 and binds it as such, returning the result of the C-side function of the same name. The 3rd argument may be null. */ public static int sqlite3_bind_text16( @NotNull sqlite3_stmt stmt, int ndx, @Nullable String data ){ if(null == data) return sqlite3_bind_null(stmt, ndx); final byte[] bytes = data.getBytes(StandardCharsets.UTF_16); return sqlite3_bind_text16(stmt, ndx, bytes, bytes.length); } /** Requires that data be null or in UTF-16 encoding in platform byte order. Returns the result of the C-level sqlite3_bind_null() or sqlite3_bind_text(). */ public static int sqlite3_bind_text16( @NotNull sqlite3_stmt stmt, int ndx, @Nullable byte[] data ){ return (null == data) ? sqlite3_bind_null(stmt, ndx) : sqlite3_bind_text16(stmt, ndx, data, data.length); } public static native int sqlite3_bind_zeroblob( @NotNull sqlite3_stmt stmt, int ndx, int n ); public static native int sqlite3_bind_zeroblob64( @NotNull sqlite3_stmt stmt, int ndx, long n ); /** As for the C-level function of the same name, with a BusyHandler instance in place of a callback function. Pass it a null handler to clear the busy handler. */ public static native int sqlite3_busy_handler( @NotNull sqlite3 db, @Nullable BusyHandler handler ); public static native int sqlite3_busy_timeout( @NotNull sqlite3 db, int ms ); public static native boolean sqlite3_cancel_auto_extension( @NotNull AutoExtension ax ); public static native int sqlite3_changes( @NotNull sqlite3 db ); public static native long sqlite3_changes64( @NotNull sqlite3 db ); public static native int sqlite3_clear_bindings( @NotNull sqlite3_stmt stmt ); public static native int sqlite3_close( @Nullable sqlite3 db ); public static native int sqlite3_close_v2( @Nullable sqlite3 db ); public static native byte[] sqlite3_column_blob( @NotNull sqlite3_stmt stmt, int ndx ); public static native int sqlite3_column_bytes( @NotNull sqlite3_stmt stmt, int ndx ); public static native int sqlite3_column_bytes16( @NotNull sqlite3_stmt stmt, int ndx ); public static native int sqlite3_column_count( @NotNull sqlite3_stmt stmt ); public static native double sqlite3_column_double( @NotNull sqlite3_stmt stmt, int ndx ); public static native int sqlite3_column_int( @NotNull sqlite3_stmt stmt, int ndx ); public static native long sqlite3_column_int64( @NotNull sqlite3_stmt stmt, int ndx ); public static native String sqlite3_column_name( @NotNull sqlite3_stmt stmt, int ndx ); public static native String sqlite3_column_database_name( @NotNull sqlite3_stmt stmt, int ndx ); /** Column counterpart of sqlite3_value_java_object(). */ public static Object sqlite3_column_java_object( |
︙ | ︙ | |||
381 382 383 384 385 386 387 | public static <T> T sqlite3_column_java_casted( @NotNull sqlite3_stmt stmt, int ndx, @NotNull Class<T> type ){ final Object o = sqlite3_column_java_object(stmt, ndx); return type.isInstance(o) ? (T)o : null; } | | | > | < | | < | > > | > > | | | 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 | public static <T> T sqlite3_column_java_casted( @NotNull sqlite3_stmt stmt, int ndx, @NotNull Class<T> type ){ final Object o = sqlite3_column_java_object(stmt, ndx); return type.isInstance(o) ? (T)o : null; } public static native String sqlite3_column_origin_name( @NotNull sqlite3_stmt stmt, int ndx ); public static native String sqlite3_column_table_name( @NotNull sqlite3_stmt stmt, int ndx ); /** Returns the given column's contents as UTF-8-encoded (not MUTF-8) text. Returns null if the C-level sqlite3_column_text() returns NULL. */ public static native byte[] sqlite3_column_text_utf8( @NotNull sqlite3_stmt stmt, int ndx ); public static String sqlite3_column_text( @NotNull sqlite3_stmt stmt, int ndx ){ final byte[] ba = sqlite3_column_text_utf8(stmt, ndx); return ba==null ? null : new String(ba, StandardCharsets.UTF_8); } public static native String sqlite3_column_text16( @NotNull sqlite3_stmt stmt, int ndx ); // The real utility of this function is questionable. // /** // Returns a Java value representation based on the value of // sqlite_value_type(). For integer types it returns either Integer |
︙ | ︙ | |||
443 444 445 446 447 448 449 | // default: break; // } // } // sqlite3_value_free(v); // return rv; // } | | | | | | > > > > > > > > > > > > > > > > > > > > > > > > > | | | | | | | | | | | | | | | | > > > > > > > > > > > > > > > > > > > | | | < < < < < < | > > > > > > > > > > > > > > | > > > > > > > > > > > | > | | | 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 | // default: break; // } // } // sqlite3_value_free(v); // return rv; // } public static native int sqlite3_column_type( @NotNull sqlite3_stmt stmt, int ndx ); public static native sqlite3_value sqlite3_column_value( @NotNull sqlite3_stmt stmt, int ndx ); /** This functions like C's sqlite3_collation_needed16() because Java's string type is compatible with that interface. */ public static native int sqlite3_collation_needed( @NotNull sqlite3 db, @Nullable CollationNeeded callback ); /** Returns the db handle passed to sqlite3_open() or sqlite3_open_v2(), as opposed to a new wrapper object. */ public static native sqlite3 sqlite3_context_db_handle( @NotNull sqlite3_context cx ); public static native CommitHook sqlite3_commit_hook( @NotNull sqlite3 db, @Nullable CommitHook hook ); public static native String sqlite3_compileoption_get( int n ); public static native boolean sqlite3_compileoption_used( @NotNull String optName ); /* ** Works like in the C API with the exception that it only supports ** the following subset of configution flags: ** ** - SQLITE_CONFIG_SINGLETHREAD ** - SQLITE_CONFIG_MULTITHREAD ** - SQLITE_CONFIG_SERIALIZED ** ** Others may be added in the future. It returns SQLITE_MISUSE if ** given an argument it does not handle. */ public static native int sqlite3_config(int op); /* ** If the native library was built with SQLITE_ENABLE_SQLLOG defined ** then this acts as a proxy for C's ** sqlite3_config(SQLITE_ENABLE_SQLLOG,...). This sets or clears the ** logger. If installation of a logger fails, any previous logger is ** retained. ** ** If not built with SQLITE_ENABLE_SQLLOG defined, this returns ** SQLITE_MISUSE. */ public static native int sqlite3_config( @Nullable SQLLog logger ); public static native int sqlite3_create_collation( @NotNull sqlite3 db, @NotNull String name, int eTextRep, @NotNull Collation col ); /** The Java counterpart to the C-native sqlite3_create_function(), sqlite3_create_function_v2(), and sqlite3_create_window_function(). Which one it behaves like depends on which methods the final argument implements. See SQLFunction's inner classes (Scalar, Aggregate<T>, and Window<T>) for details. */ public static native int sqlite3_create_function( @NotNull sqlite3 db, @NotNull String functionName, int nArg, int eTextRep, @NotNull SQLFunction func ); public static native int sqlite3_data_count( @NotNull sqlite3_stmt stmt ); public static native String sqlite3_db_filename( @NotNull sqlite3 db, @NotNull String dbName ); /** Overload for sqlite3_db_config() calls which take (int,int*) variadic arguments. Returns SQLITE_MISUSE if op is not one of the SQLITE_DBCONFIG_... options which uses this call form. */ public static native int sqlite3_db_config( @NotNull sqlite3 db, int op, int onOff, @Nullable OutputPointer.Int32 out ); /** Overload for sqlite3_db_config() calls which take a (const char*) variadic argument. As of SQLite3 v3.43 the only such option is SQLITE_DBCONFIG_MAINDBNAME. Returns SQLITE_MISUSE if op is not SQLITE_DBCONFIG_MAINDBNAME, but that set of options may be extended in future versions. */ public static native int sqlite3_db_config( @NotNull sqlite3 db, int op, @NotNull String val ); public static native int sqlite3_db_status( @NotNull sqlite3 db, int op, @NotNull OutputPointer.Int32 pCurrent, @NotNull OutputPointer.Int32 pHighwater, boolean reset ); public static native int sqlite3_errcode(@NotNull sqlite3 db); public static native String sqlite3_expanded_sql(@NotNull sqlite3_stmt stmt); public static native int sqlite3_extended_errcode(@NotNull sqlite3 db); public static native boolean sqlite3_extended_result_codes( @NotNull sqlite3 db, boolean onoff ); public static native String sqlite3_errmsg(@NotNull sqlite3 db); public static native String sqlite3_errstr(int resultCode); /** Note that the offset values assume UTF-8-encoded SQL. */ public static native int sqlite3_error_offset(@NotNull sqlite3 db); public static native int sqlite3_finalize(@NotNull sqlite3_stmt stmt); public static native int sqlite3_initialize(); /** Design note/FIXME: we have a problem vis-a-vis 'synchronized' here: we specifically want other threads to be able to cancel a long-running thread, but this routine requires access to C-side global state which does not have a mutex. Making this function synchronized would make it impossible for a long-running job to be cancelled from another thread. The mutexing problem here is not within the core lib or Java, but within the cached data held by the JNI binding. The cache holds per-thread state, used by all but a tiny fraction of the JNI binding layer, and access to that state needs to be mutex-protected. */ public static native void sqlite3_interrupt(@NotNull sqlite3 db); //! See sqlite3_interrupt() for threading concerns. public static native boolean sqlite3_is_interrupted(@NotNull sqlite3 db); public static native long sqlite3_last_insert_rowid(@NotNull sqlite3 db); public static native String sqlite3_libversion(); public static native int sqlite3_libversion_number(); /** Works like its C counterpart and makes the native pointer of the underling (sqlite3*) object available via ppDb.getNativePointer(). That pointer is necessary for looking up the JNI-side native, but clients need not pay it any heed. Passing the object to sqlite3_close() or sqlite3_close_v2() will clear that pointer mapping. Recall that even if opening fails, the output pointer might be non-null. Any error message about the failure will be in that object and it is up to the caller to sqlite3_close() that db handle. */ public static native int sqlite3_open( @Nullable String filename, @NotNull OutputPointer.sqlite3 ppDb ); /** Convenience overload which returns its db handle directly. The returned object might not have been successfully opened: use sqlite3_errcode() to check whether it is in an error state. Ownership of the returned value is passed to the caller, who must eventually pass it to sqlite3_close() or sqlite3_close_v2(). */ public static sqlite3 sqlite3_open(@Nullable String filename){ final OutputPointer.sqlite3 out = new OutputPointer.sqlite3(); sqlite3_open(filename, out); return out.take(); }; public static native int sqlite3_open_v2( @Nullable String filename, @NotNull OutputPointer.sqlite3 ppDb, int flags, @Nullable String zVfs ); /** Has the same semantics as the sqlite3-returning sqlite3_open() but uses sqlite3_open_v2() instead of sqlite3_open(). */ public static sqlite3 sqlite3_open_v2(@Nullable String filename, int flags, @Nullable String zVfs){ final OutputPointer.sqlite3 out = new OutputPointer.sqlite3(); sqlite3_open_v2(filename, out, flags, zVfs); return out.take(); }; /** The sqlite3_prepare() family of functions require slightly different signatures than their native counterparts, but (A) they retain functionally equivalent semantics and (B) overloading allows us to install several convenience forms. All of them which take their SQL in the form of a byte[] require that it be in UTF-8 encoding unless explicitly noted otherwise. The forms which take a "tail" output pointer return (via that output object) the index into their SQL byte array at which the end of the first SQL statement processed by the call was found. That's fundamentally how the C APIs work but making use of that value requires more copying of the input SQL into consecutively smaller arrays in order to consume all of it. (There is an example of doing that in this project's Tester1 class.) For that vast majority of uses, that capability is not necessary, however, and overloads are provided which gloss over that. */ private static native int sqlite3_prepare( @NotNull sqlite3 db, @NotNull byte[] sqlUtf8, int maxBytes, @NotNull OutputPointer.sqlite3_stmt outStmt, @Nullable OutputPointer.Int32 pTailOffset ); public static int sqlite3_prepare( @NotNull sqlite3 db, @NotNull byte[] sqlUtf8, |
︙ | ︙ | |||
635 636 637 638 639 640 641 | @NotNull sqlite3 db, @NotNull String sql, @NotNull OutputPointer.sqlite3_stmt outStmt ){ final byte[] utf8 = sql.getBytes(StandardCharsets.UTF_8); return sqlite3_prepare(db, utf8, utf8.length, outStmt, null); } | > > > > > > > > > > > > > > > > > > > > | | 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 | @NotNull sqlite3 db, @NotNull String sql, @NotNull OutputPointer.sqlite3_stmt outStmt ){ final byte[] utf8 = sql.getBytes(StandardCharsets.UTF_8); return sqlite3_prepare(db, utf8, utf8.length, outStmt, null); } /** Convenience overload which returns its statement handle directly, or null on error or when reading only whitespace or comments. sqlite3_errcode() can be used to determine whether there was an error or the input was empty. Ownership of the returned object is passed to the caller, who must eventually pass it to sqlite3_finalize(). */ public static sqlite3_stmt sqlite3_prepare( @NotNull sqlite3 db, @NotNull String sql ){ final OutputPointer.sqlite3_stmt out = new OutputPointer.sqlite3_stmt(); sqlite3_prepare(db, sql, out); return out.take(); } /** See sqlite3_prepare() for details about the slight API differences from the C API. */ private static native int sqlite3_prepare_v2( @NotNull sqlite3 db, @NotNull byte[] sqlUtf8, int maxBytes, @NotNull OutputPointer.sqlite3_stmt outStmt, @Nullable OutputPointer.Int32 pTailOffset ); public static int sqlite3_prepare_v2( @NotNull sqlite3 db, @NotNull byte[] sqlUtf8, |
︙ | ︙ | |||
664 665 666 667 668 669 670 | @NotNull sqlite3 db, @NotNull String sql, @NotNull OutputPointer.sqlite3_stmt outStmt ){ final byte[] utf8 = sql.getBytes(StandardCharsets.UTF_8); return sqlite3_prepare_v2(db, utf8, utf8.length, outStmt, null); } | > > > > > > > > > > > > | | 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 | @NotNull sqlite3 db, @NotNull String sql, @NotNull OutputPointer.sqlite3_stmt outStmt ){ final byte[] utf8 = sql.getBytes(StandardCharsets.UTF_8); return sqlite3_prepare_v2(db, utf8, utf8.length, outStmt, null); } /** Works identically to the sqlite3_stmt-returning sqlite3_prepare() but uses sqlite3_prepare_v2(). */ public static sqlite3_stmt sqlite3_prepare_v2( @NotNull sqlite3 db, @NotNull String sql ){ final OutputPointer.sqlite3_stmt out = new OutputPointer.sqlite3_stmt(); sqlite3_prepare_v2(db, sql, out); return out.take(); } private static native int sqlite3_prepare_v3( @NotNull sqlite3 db, @NotNull byte[] sqlUtf8, int maxBytes, int prepFlags, @NotNull OutputPointer.sqlite3_stmt outStmt, @Nullable OutputPointer.Int32 pTailOffset ); public static int sqlite3_prepare_v3( @NotNull sqlite3 db, @NotNull byte[] sqlUtf8, int prepFlags, |
︙ | ︙ | |||
693 694 695 696 697 698 699 | @NotNull sqlite3 db, @NotNull String sql, int prepFlags, @NotNull OutputPointer.sqlite3_stmt outStmt ){ final byte[] utf8 = sql.getBytes(StandardCharsets.UTF_8); return sqlite3_prepare_v3(db, utf8, utf8.length, prepFlags, outStmt, null); } | > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | | | | | | 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 | @NotNull sqlite3 db, @NotNull String sql, int prepFlags, @NotNull OutputPointer.sqlite3_stmt outStmt ){ final byte[] utf8 = sql.getBytes(StandardCharsets.UTF_8); return sqlite3_prepare_v3(db, utf8, utf8.length, prepFlags, outStmt, null); } /** Works identically to the sqlite3_stmt-returning sqlite3_prepare() but uses sqlite3_prepare_v3(). */ public static sqlite3_stmt sqlite3_prepare_v3( @NotNull sqlite3 db, @NotNull String sql, int prepFlags ){ final OutputPointer.sqlite3_stmt out = new OutputPointer.sqlite3_stmt(); sqlite3_prepare_v3(db, sql, prepFlags, out); return out.take(); } /** If the C API was built with SQLITE_ENABLE_PREUPDATE_HOOK defined, this acts as a proxy for C's sqlite3_preupdate_blobwrite(), else it returns SQLITE_MISUSE with no side effects. */ public static native int sqlite3_preupdate_blobwrite(@NotNull sqlite3 db); /** If the C API was built with SQLITE_ENABLE_PREUPDATE_HOOK defined, this acts as a proxy for C's sqlite3_preupdate_count(), else it returns SQLITE_MISUSE with no side effects. */ public static native int sqlite3_preupdate_count(@NotNull sqlite3 db); /** If the C API was built with SQLITE_ENABLE_PREUPDATE_HOOK defined, this acts as a proxy for C's sqlite3_preupdate_depth(), else it returns SQLITE_MISUSE with no side effects. */ public static native int sqlite3_preupdate_depth(@NotNull sqlite3 db); /** If the C API was built with SQLITE_ENABLE_PREUPDATE_HOOK defined, this acts as a proxy for C's sqlite3_preupdate_hook(), else it returns null with no side effects. */ public static native PreUpdateHook sqlite3_preupdate_hook(@NotNull sqlite3 db, @Nullable PreUpdateHook hook); /** If the C API was built with SQLITE_ENABLE_PREUPDATE_HOOK defined, this acts as a proxy for C's sqlite3_preupdate_new(), else it returns SQLITE_MISUSE with no side effects. */ public static native int sqlite3_preupdate_new(@NotNull sqlite3 db, int col, @NotNull OutputPointer.sqlite3_value out); /** Convenience wrapper for the 3-arg sqlite3_preupdate_new() which returns null on error. */ public static sqlite3_value sqlite3_preupdate_new(@NotNull sqlite3 db, int col){ final OutputPointer.sqlite3_value out = new OutputPointer.sqlite3_value(); sqlite3_preupdate_new(db, col, out); return out.take(); } /** If the C API was built with SQLITE_ENABLE_PREUPDATE_HOOK defined, this acts as a proxy for C's sqlite3_preupdate_old(), else it returns SQLITE_MISUSE with no side effects. */ public static native int sqlite3_preupdate_old(@NotNull sqlite3 db, int col, @NotNull OutputPointer.sqlite3_value out); /** Convenience wrapper for the 3-arg sqlite3_preupdate_old() which returns null on error. */ public static sqlite3_value sqlite3_preupdate_old(@NotNull sqlite3 db, int col){ final OutputPointer.sqlite3_value out = new OutputPointer.sqlite3_value(); sqlite3_preupdate_old(db, col, out); return out.take(); } public static native void sqlite3_progress_handler( @NotNull sqlite3 db, int n, @Nullable ProgressHandler h ); //TODO??? void *sqlite3_preupdate_hook(...) and friends public static native int sqlite3_reset(@NotNull sqlite3_stmt stmt); /** Works like the C API except that it has no side effects if auto extensions are currently running. (The JNI-level list of extensions cannot be manipulated while it is being traversed.) */ public static native void sqlite3_reset_auto_extension(); public static native void sqlite3_result_double( @NotNull sqlite3_context cx, double v ); /** The main sqlite3_result_error() impl of which all others are proxies. eTextRep must be one of SQLITE_UTF8 or SQLITE_UTF16 and msg must be encoded correspondingly. Any other eTextRep value results in the C-level sqlite3_result_error() being called with a complaint about the invalid argument. */ private static native void sqlite3_result_error( @NotNull sqlite3_context cx, @Nullable byte[] msg, int eTextRep ); public static void sqlite3_result_error( @NotNull sqlite3_context cx, @NotNull byte[] utf8 ){ |
︙ | ︙ | |||
762 763 764 765 766 767 768 | public static void sqlite3_result_error16( @NotNull sqlite3_context cx, @NotNull Exception e ){ sqlite3_result_error16(cx, e.getMessage()); } | | | | | | | | | 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 | public static void sqlite3_result_error16( @NotNull sqlite3_context cx, @NotNull Exception e ){ sqlite3_result_error16(cx, e.getMessage()); } public static native void sqlite3_result_error_toobig( @NotNull sqlite3_context cx ); public static native void sqlite3_result_error_nomem( @NotNull sqlite3_context cx ); public static native void sqlite3_result_error_code( @NotNull sqlite3_context cx, int c ); public static native void sqlite3_result_null( @NotNull sqlite3_context cx ); public static native void sqlite3_result_int( @NotNull sqlite3_context cx, int v ); public static native void sqlite3_result_int64( @NotNull sqlite3_context cx, long v ); /** Binds the SQL result to the given object, or sqlite3_result_null() if o is null. Use sqlite3_value_java_object() or sqlite3_column_java_object() to fetch it. This is implemented in terms of sqlite3_result_pointer(), but that function is not exposed to JNI because its 3rd argument must be a constant string (the library does not copy it), which we cannot implement cross-language here unless, in the JNI layer, we allocate such strings and store them somewhere for long-term use (leaking them more likely than not). Even then, passing around a pointer via Java like that has little practical use. Note that there is no sqlite3_bind_java_object() counterpart. */ public static native void sqlite3_result_java_object( @NotNull sqlite3_context cx, @NotNull Object o ); public static void sqlite3_result_set( @NotNull sqlite3_context cx, @NotNull Integer v ){ sqlite3_result_int(cx, v); |
︙ | ︙ | |||
860 861 862 863 864 865 866 | public static void sqlite3_result_set( @NotNull sqlite3_context cx, @Nullable String v ){ sqlite3_result_text(cx, v); } | | | | | | | | 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 | public static void sqlite3_result_set( @NotNull sqlite3_context cx, @Nullable String v ){ sqlite3_result_text(cx, v); } public static native void sqlite3_result_value( @NotNull sqlite3_context cx, @NotNull sqlite3_value v ); public static native void sqlite3_result_zeroblob( @NotNull sqlite3_context cx, int n ); public static native int sqlite3_result_zeroblob64( @NotNull sqlite3_context cx, long n ); private static native void sqlite3_result_blob( @NotNull sqlite3_context cx, @Nullable byte[] blob, int maxLen ); public static void sqlite3_result_blob( @NotNull sqlite3_context cx, @Nullable byte[] blob ){ sqlite3_result_blob(cx, blob, (int)(null==blob ? 0 : blob.length)); } /** Binds the given text using C's sqlite3_result_blob64() unless: - blob is null ==> sqlite3_result_null() - blob is too large ==> sqlite3_result_error_toobig() If maxLen is larger than blob.length, it is truncated to that value. If it is negative, results are undefined. */ private static native void sqlite3_result_blob64( @NotNull sqlite3_context cx, @Nullable byte[] blob, long maxLen ); public static void sqlite3_result_blob64( @NotNull sqlite3_context cx, @Nullable byte[] blob ){ sqlite3_result_blob64(cx, blob, (long)(null==blob ? 0 : blob.length)); } private static native void sqlite3_result_text( @NotNull sqlite3_context cx, @Nullable byte[] text, int maxLen ); public static void sqlite3_result_text( @NotNull sqlite3_context cx, @Nullable byte[] text ){ sqlite3_result_text(cx, text, null==text ? 0 : text.length); |
︙ | ︙ | |||
934 935 936 937 938 939 940 | - text is too large ==> sqlite3_result_error_toobig() - The `encoding` argument has an invalid value ==> sqlite3_result_error_code() with SQLITE_FORMAT If maxLength (in bytes, not characters) is larger than text.length, it is silently truncated to text.length. If it is | | > | > > > > > | > > | | 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 | - text is too large ==> sqlite3_result_error_toobig() - The `encoding` argument has an invalid value ==> sqlite3_result_error_code() with SQLITE_FORMAT If maxLength (in bytes, not characters) is larger than text.length, it is silently truncated to text.length. If it is negative, results are undefined. If text is null, the following arguments are ignored. */ private static native void sqlite3_result_text64( @NotNull sqlite3_context cx, @Nullable byte[] text, long maxLength, int encoding ); /** Cleans up all per-JNIEnv and per-db state managed by the library, as well as any registered auto-extensions, then calls the C-native sqlite3_shutdown(). */ public static synchronized native int sqlite3_shutdown(); public static native int sqlite3_status( int op, @NotNull OutputPointer.Int32 pCurrent, @NotNull OutputPointer.Int32 pHighwater, boolean reset ); public static native int sqlite3_status64( int op, @NotNull OutputPointer.Int64 pCurrent, @NotNull OutputPointer.Int64 pHighwater, boolean reset ); /** Sets the current UDF result to the given bytes, which are assumed be encoded in UTF-16 using the platform's byte order. |
︙ | ︙ | |||
1002 1003 1004 1005 1006 1007 1008 | public static void sqlite3_result_text16be( @NotNull sqlite3_context cx, @NotNull String text ){ final byte[] b = text.getBytes(StandardCharsets.UTF_16BE); sqlite3_result_text64(cx, b, b.length, SQLITE_UTF16BE); } | | | | | | | | | | | | | | | | | | | | | | | | | | | < | < | < | > | > | | | | | | | | < < < < < < | < < < < < | 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 | public static void sqlite3_result_text16be( @NotNull sqlite3_context cx, @NotNull String text ){ final byte[] b = text.getBytes(StandardCharsets.UTF_16BE); sqlite3_result_text64(cx, b, b.length, SQLITE_UTF16BE); } public static native RollbackHook sqlite3_rollback_hook( @NotNull sqlite3 db, @Nullable RollbackHook hook ); //! Sets or unsets (if auth is null) the current authorizer. public static native int sqlite3_set_authorizer( @NotNull sqlite3 db, @Nullable Authorizer auth ); public static native void sqlite3_set_last_insert_rowid( @NotNull sqlite3 db, long rowid ); public static native int sqlite3_sleep(int ms); public static native String sqlite3_sourceid(); public static native String sqlite3_sql(@NotNull sqlite3_stmt stmt); public static native int sqlite3_step(@NotNull sqlite3_stmt stmt); /** Internal impl of the public sqlite3_strglob() method. Neither argument may be NULL and both _MUST_ be NUL-terminated. */ private static native int sqlite3_strglob( @NotNull byte[] glob, @NotNull byte[] txt ); public static int sqlite3_strglob( @NotNull String glob, @NotNull String txt ){ return sqlite3_strglob( (glob+"\0").getBytes(StandardCharsets.UTF_8), (txt+"\0").getBytes(StandardCharsets.UTF_8) ); } /** Internal impl of the public sqlite3_strlike() method. Neither argument may be NULL and both _MUST_ be NUL-terminated. */ private static native int sqlite3_strlike( @NotNull byte[] glob, @NotNull byte[] txt, int escChar ); public static int sqlite3_strlike( @NotNull String glob, @NotNull String txt, char escChar ){ return sqlite3_strlike( (glob+"\0").getBytes(StandardCharsets.UTF_8), (txt+"\0").getBytes(StandardCharsets.UTF_8), (int)escChar ); } public static native int sqlite3_threadsafe(); public static native int sqlite3_total_changes(@NotNull sqlite3 db); public static native long sqlite3_total_changes64(@NotNull sqlite3 db); /** Works like C's sqlite3_trace_v2() except that the 3rd argument to that function is elided here because the roles of that functions' 3rd and 4th arguments are encapsulated in the final argument to this function. Unlike the C API, which is documented as always returning 0, this implementation returns SQLITE_NOMEM if allocation of per-db mapping state fails and SQLITE_ERROR if the given callback object cannot be processed propertly (i.e. an internal error). */ public static native int sqlite3_trace_v2( @NotNull sqlite3 db, int traceMask, @Nullable Tracer tracer ); public static native UpdateHook sqlite3_update_hook( sqlite3 db, UpdateHook hook ); public static native byte[] sqlite3_value_blob(@NotNull sqlite3_value v); public static native int sqlite3_value_bytes(@NotNull sqlite3_value v); public static native int sqlite3_value_bytes16(@NotNull sqlite3_value v); public static native double sqlite3_value_double(@NotNull sqlite3_value v); public static native sqlite3_value sqlite3_value_dupe( @NotNull sqlite3_value v ); public static native int sqlite3_value_encoding(@NotNull sqlite3_value v); public static native void sqlite3_value_free(@Nullable sqlite3_value v); public static native int sqlite3_value_int(@NotNull sqlite3_value v); public static native long sqlite3_value_int64(@NotNull sqlite3_value v); /** If the given value was set using sqlite3_result_java_value() then this function returns that object, else it returns null. It is up to the caller to inspect the object to determine its type, and cast it if necessary. */ public static native Object sqlite3_value_java_object( @NotNull sqlite3_value v ); /** A variant of sqlite3_value_java_object() which returns the fetched object cast to T if the object is an instance of the given Class. It returns null in all other cases. */ @SuppressWarnings("unchecked") public static <T> T sqlite3_value_java_casted(@NotNull sqlite3_value v, @NotNull Class<T> type){ final Object o = sqlite3_value_java_object(v); return type.isInstance(o) ? (T)o : null; } /** Returns the given value as UTF-8-encoded bytes, or null if the underlying C API returns null for sqlite3_value_text(). */ public static native byte[] sqlite3_value_text_utf8(@NotNull sqlite3_value v); public static String sqlite3_value_text(@NotNull sqlite3_value v){ final byte[] ba = sqlite3_value_text_utf8(v); return null==ba ? null : new String(ba, StandardCharsets.UTF_8); } public static native byte[] sqlite3_value_text16(@NotNull sqlite3_value v); public static native byte[] sqlite3_value_text16le(@NotNull sqlite3_value v); public static native byte[] sqlite3_value_text16be(@NotNull sqlite3_value v); public static native int sqlite3_value_type(@NotNull sqlite3_value v); public static native int sqlite3_value_numeric_type(@NotNull sqlite3_value v); public static native int sqlite3_value_nochange(@NotNull sqlite3_value v); public static native int sqlite3_value_frombind(@NotNull sqlite3_value v); public static native int sqlite3_value_subtype(@NotNull sqlite3_value v); /** This is NOT part of the public API. It exists solely as a place to hook in arbitrary C-side code during development and testing of this library. */ public static native void sqlite3_do_something_for_developer(); ////////////////////////////////////////////////////////////////////// // SQLITE_... constants follow... // version info public static final int SQLITE_VERSION_NUMBER = sqlite3_libversion_number(); public static final String SQLITE_VERSION = sqlite3_libversion(); public static final String SQLITE_SOURCE_ID = sqlite3_sourceid(); // access public static final int SQLITE_ACCESS_EXISTS = 0; public static final int SQLITE_ACCESS_READWRITE = 1; public static final int SQLITE_ACCESS_READ = 2; // authorizer public static final int SQLITE_DENY = 1; |
︙ | ︙ |
Changes to ext/jni/src/org/sqlite/jni/Tester1.java.
︙ | ︙ | |||
11 12 13 14 15 16 17 18 | ************************************************************************* ** This file contains a set of tests for the sqlite3 JNI bindings. */ package org.sqlite.jni; import static org.sqlite.jni.SQLite3Jni.*; import java.nio.charset.StandardCharsets; import java.util.Arrays; | > > > > > > > > > > > > > > > | > > > > > > > > > > > > > > > > > | < | | > > | < < | > | > | | | | | > > > > > | | > > | | > | > > | | > > > > > > > > | | | | > > | | | > | < > | < < < | | | | | | > | 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | ************************************************************************* ** This file contains a set of tests for the sqlite3 JNI bindings. */ package org.sqlite.jni; import static org.sqlite.jni.SQLite3Jni.*; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** An annotation for Tester1 tests which we do not want to run in reflection-driven test mode because either they are not suitable for multi-threaded threaded mode or we have to control their execution order. */ @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @java.lang.annotation.Target({java.lang.annotation.ElementType.METHOD}) @interface ManualTest{} public class Tester1 implements Runnable { //! True when running in multi-threaded mode. private static boolean mtMode = false; //! True to sleep briefly between tests. private static boolean takeNaps = false; //! True to shuffle the order of the tests. private static boolean shuffle = false; //! True to dump the list of to-run tests to stdout. private static boolean listRunTests = false; //! True to squelch all out() and outln() output. private static boolean quietMode = false; //! Total number of runTests() calls. private static int nTestRuns = 0; //! List of test*() methods to run. private static List<java.lang.reflect.Method> testMethods = null; //! List of exceptions collected by run() private static List<Exception> listErrors = new ArrayList<>(); private static final class Metrics { //! Number of times createNewDb() (or equivalent) is invoked. volatile int dbOpen = 0; } private Integer tId; Tester1(Integer id){ tId = id; } static final Metrics metrics = new Metrics(); public synchronized static void outln(){ if( !quietMode ){ System.out.println(""); } } public synchronized static void outln(Object val){ if( !quietMode ){ System.out.print(Thread.currentThread().getName()+": "); System.out.println(val); } } public synchronized static void out(Object val){ if( !quietMode ){ System.out.print(val); } } @SuppressWarnings("unchecked") public synchronized static void out(Object... vals){ if( !quietMode ){ System.out.print(Thread.currentThread().getName()+": "); for(Object v : vals) out(v); } } @SuppressWarnings("unchecked") public synchronized static void outln(Object... vals){ if( !quietMode ){ out(vals); out("\n"); } } static volatile int affirmCount = 0; public synchronized static void affirm(Boolean v, String comment){ ++affirmCount; if( false ) assert( v /* prefer assert over exception if it's enabled because the JNI layer sometimes has to suppress exceptions, so they might be squelched on their way back to the top. */); if( !v ) throw new RuntimeException(comment); } public static void affirm(Boolean v){ affirm(v, "Affirmation failed."); } @ManualTest /* because testing this for threading is pointless */ private void test1(){ affirm(sqlite3_libversion_number() == SQLITE_VERSION_NUMBER); affirm(SQLITE_MAX_LENGTH > 0); affirm(SQLITE_MAX_TRIGGER_DEPTH>0); } static sqlite3 createNewDb(){ final OutputPointer.sqlite3 out = new OutputPointer.sqlite3(); int rc = sqlite3_open(":memory:", out); ++metrics.dbOpen; sqlite3 db = out.take(); if( 0!=rc ){ final String msg = null==db ? sqlite3_errstr(rc) : sqlite3_errmsg(db); sqlite3_close(db); throw new RuntimeException("Opening db failed: "+msg); } affirm( null == out.get() ); affirm( 0 != db.getNativePointer() ); rc = sqlite3_busy_timeout(db, 2000); affirm( 0 == rc ); return db; } static void execSql(sqlite3 db, String[] sql){ execSql(db, String.join("", sql)); } static int execSql(sqlite3 db, boolean throwOnError, String sql){ OutputPointer.Int32 oTail = new OutputPointer.Int32(); final byte[] sqlUtf8 = sql.getBytes(StandardCharsets.UTF_8); int pos = 0, n = 1; byte[] sqlChunk = sqlUtf8; int rc = 0; sqlite3_stmt stmt = null; final OutputPointer.sqlite3_stmt outStmt = new OutputPointer.sqlite3_stmt(); while(pos < sqlChunk.length){ if(pos > 0){ sqlChunk = Arrays.copyOfRange(sqlChunk, pos, sqlChunk.length); } if( 0==sqlChunk.length ) break; rc = sqlite3_prepare_v2(db, sqlChunk, outStmt, oTail); |
︙ | ︙ | |||
123 124 125 126 127 128 129 | if( 0!=rc && throwOnError){ throw new RuntimeException("db op failed with rc=" +rc+": "+sqlite3_errmsg(db)); } return rc; } | | | | > | > > | > > > | | | > > > > > > > | | > | > > > | 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 | if( 0!=rc && throwOnError){ throw new RuntimeException("db op failed with rc=" +rc+": "+sqlite3_errmsg(db)); } return rc; } static void execSql(sqlite3 db, String sql){ execSql(db, true, sql); } static sqlite3_stmt prepare(sqlite3 db, boolean throwOnError, String sql){ final OutputPointer.sqlite3_stmt outStmt = new OutputPointer.sqlite3_stmt(); int rc = sqlite3_prepare(db, sql, outStmt); if( throwOnError ){ affirm( 0 == rc ); } final sqlite3_stmt rv = outStmt.take(); affirm( null == outStmt.get() ); if( throwOnError ){ affirm( 0 != rv.getNativePointer() ); } return rv; } static sqlite3_stmt prepare(sqlite3 db, String sql){ return prepare(db, true, sql); } private void showCompileOption(){ int i = 0; String optName; outln("compile options:"); for( ; null != (optName = sqlite3_compileoption_get(i)); ++i){ outln("\t"+optName+"\t (used="+ sqlite3_compileoption_used(optName)+")"); } } private void testOpenDb1(){ final OutputPointer.sqlite3 out = new OutputPointer.sqlite3(); int rc = sqlite3_open(":memory:", out); ++metrics.dbOpen; sqlite3 db = out.get(); affirm(0 == rc); affirm(0 < db.getNativePointer()); sqlite3_db_config(db, SQLITE_DBCONFIG_DEFENSIVE, 1, null) /* This function has different mangled names in jdk8 vs jdk19, and this call is here to ensure that the build fails if it cannot find both names. */; // These interrupt checks are only to make sure that the JNI binding // has the proper exported symbol names. They don't actually test // anything useful. affirm( !sqlite3_is_interrupted(db) ); sqlite3_interrupt(db); affirm( sqlite3_is_interrupted(db) ); sqlite3_close_v2(db); affirm(0 == db.getNativePointer()); } private void testOpenDb2(){ final OutputPointer.sqlite3 out = new OutputPointer.sqlite3(); int rc = sqlite3_open_v2(":memory:", out, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, null); ++metrics.dbOpen; affirm(0 == rc); sqlite3 db = out.get(); affirm(0 < db.getNativePointer()); sqlite3_close_v2(db); affirm(0 == db.getNativePointer()); } private void testPrepare123(){ sqlite3 db = createNewDb(); int rc; final OutputPointer.sqlite3_stmt outStmt = new OutputPointer.sqlite3_stmt(); rc = sqlite3_prepare(db, "CREATE TABLE t1(a);", outStmt); affirm(0 == rc); sqlite3_stmt stmt = outStmt.take(); affirm(0 != stmt.getNativePointer()); rc = sqlite3_step(stmt); if( SQLITE_DONE != rc ){ outln("step failed ??? ",rc, " ",sqlite3_errmsg(db)); } affirm(SQLITE_DONE == rc); sqlite3_finalize(stmt); affirm(0 == stmt.getNativePointer()); { /* Demonstrate how to use the "zTail" option of sqlite3_prepare() family of functions. */ OutputPointer.Int32 oTail = new OutputPointer.Int32(); |
︙ | ︙ | |||
232 233 234 235 236 237 238 239 240 241 | rc = sqlite3_prepare_v3(db, "INSERT INTO t2(a) VALUES(1),(2),(3)", SQLITE_PREPARE_NORMALIZE, outStmt); affirm(0 == rc); stmt = outStmt.get(); affirm(0 != stmt.getNativePointer()); sqlite3_finalize(stmt); affirm(0 == stmt.getNativePointer() ); sqlite3_close_v2(db); } | > > > > > > > > > > | | 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | rc = sqlite3_prepare_v3(db, "INSERT INTO t2(a) VALUES(1),(2),(3)", SQLITE_PREPARE_NORMALIZE, outStmt); affirm(0 == rc); stmt = outStmt.get(); affirm(0 != stmt.getNativePointer()); sqlite3_finalize(stmt); affirm(0 == stmt.getNativePointer() ); affirm( 0==sqlite3_errcode(db) ); stmt = sqlite3_prepare(db, "intentional error"); affirm( null==stmt ); affirm( 0!=sqlite3_errcode(db) ); affirm( 0==sqlite3_errmsg(db).indexOf("near \"intentional\"") ); sqlite3_finalize(stmt); stmt = sqlite3_prepare(db, "/* empty input*/\n-- comments only"); affirm( null==stmt ); affirm( 0==sqlite3_errcode(db) ); sqlite3_close_v2(db); } private void testBindFetchInt(){ sqlite3 db = createNewDb(); execSql(db, "CREATE TABLE t(a)"); sqlite3_stmt stmt = prepare(db, "INSERT INTO t(a) VALUES(:a);"); affirm(1 == sqlite3_bind_parameter_count(stmt)); final int paramNdx = sqlite3_bind_parameter_index(stmt, ":a"); affirm(1 == paramNdx); |
︙ | ︙ | |||
282 283 284 285 286 287 288 | } sqlite3_finalize(stmt); affirm(total1 == total2); sqlite3_close_v2(db); affirm(0 == db.getNativePointer()); } | | | 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 | } sqlite3_finalize(stmt); affirm(total1 == total2); sqlite3_close_v2(db); affirm(0 == db.getNativePointer()); } private void testBindFetchInt64(){ sqlite3 db = createNewDb(); execSql(db, "CREATE TABLE t(a)"); sqlite3_stmt stmt = prepare(db, "INSERT INTO t(a) VALUES(?);"); long total1 = 0; for(long i = 0xffffffff; i < 0xffffffff + 3; ++i ){ total1 += i; sqlite3_bind_int64(stmt, 1, i); |
︙ | ︙ | |||
304 305 306 307 308 309 310 | total2 += sqlite3_column_int64(stmt, 0); } sqlite3_finalize(stmt); affirm(total1 == total2); sqlite3_close_v2(db); } | | | 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 | total2 += sqlite3_column_int64(stmt, 0); } sqlite3_finalize(stmt); affirm(total1 == total2); sqlite3_close_v2(db); } private void testBindFetchDouble(){ sqlite3 db = createNewDb(); execSql(db, "CREATE TABLE t(a)"); sqlite3_stmt stmt = prepare(db, "INSERT INTO t(a) VALUES(?);"); double total1 = 0; for(double i = 1.5; i < 5.0; i = i + 1.0 ){ total1 += i; sqlite3_bind_double(stmt, 1, i); |
︙ | ︙ | |||
329 330 331 332 333 334 335 | } affirm(4 == counter); sqlite3_finalize(stmt); affirm(total2<=total1+0.01 && total2>=total1-0.01); sqlite3_close_v2(db); } | | > > | > | | | 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 | } affirm(4 == counter); sqlite3_finalize(stmt); affirm(total2<=total1+0.01 && total2>=total1-0.01); sqlite3_close_v2(db); } private void testBindFetchText(){ sqlite3 db = createNewDb(); execSql(db, "CREATE TABLE t(a)"); sqlite3_stmt stmt = prepare(db, "INSERT INTO t(a) VALUES(?);"); String[] list1 = { "hell🤩", "w😃rld", "!" }; int rc; int n = 0; for( String e : list1 ){ rc = (0==n) ? sqlite3_bind_text(stmt, 1, e) : sqlite3_bind_text16(stmt, 1, e); affirm(0 == rc); rc = sqlite3_step(stmt); affirm(SQLITE_DONE==rc); sqlite3_reset(stmt); } sqlite3_finalize(stmt); stmt = prepare(db, "SELECT a FROM t ORDER BY a DESC;"); StringBuilder sbuf = new StringBuilder(); n = 0; while( SQLITE_ROW == sqlite3_step(stmt) ){ String txt = sqlite3_column_text16(stmt, 0); //outln("txt = "+txt); sbuf.append( txt ); ++n; } sqlite3_finalize(stmt); affirm(3 == n); affirm("w😃rldhell🤩!".equals(sbuf.toString())); sqlite3_close_v2(db); } private void testBindFetchBlob(){ sqlite3 db = createNewDb(); execSql(db, "CREATE TABLE t(a)"); sqlite3_stmt stmt = prepare(db, "INSERT INTO t(a) VALUES(?);"); byte[] list1 = { 0x32, 0x33, 0x34 }; int rc = sqlite3_bind_blob(stmt, 1, list1); affirm( 0==rc ); rc = sqlite3_step(stmt); |
︙ | ︙ | |||
387 388 389 390 391 392 393 | } sqlite3_finalize(stmt); affirm(1 == n); affirm(total == 0x32 + 0x33 + 0x34); sqlite3_close_v2(db); } | | > | | 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 | } sqlite3_finalize(stmt); affirm(1 == n); affirm(total == 0x32 + 0x33 + 0x34); sqlite3_close_v2(db); } private void testSql(){ sqlite3 db = createNewDb(); sqlite3_stmt stmt = prepare(db, "SELECT 1"); affirm( "SELECT 1".equals(sqlite3_sql(stmt)) ); sqlite3_finalize(stmt); stmt = prepare(db, "SELECT ?"); sqlite3_bind_text(stmt, 1, "hell😃"); affirm( "SELECT 'hell😃'".equals(sqlite3_expanded_sql(stmt)) ); sqlite3_finalize(stmt); sqlite3_close(db); } private void testCollation(){ final sqlite3 db = createNewDb(); execSql(db, "CREATE TABLE t(a); INSERT INTO t(a) VALUES('a'),('b'),('c')"); final ValueHolder<Boolean> xDestroyCalled = new ValueHolder<>(false); final Collation myCollation = new Collation() { private String myState = "this is local state. There is much like it, but this is mine."; @Override |
︙ | ︙ | |||
468 469 470 471 472 473 474 475 476 477 | } affirm(3 == counter); sqlite3_finalize(stmt); affirm(!xDestroyCalled.value); rc = sqlite3_collation_needed(db, null); affirm( 0 == rc ); sqlite3_close_v2(db); affirm(xDestroyCalled.value); } | > > | < < < | | 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 | } affirm(3 == counter); sqlite3_finalize(stmt); affirm(!xDestroyCalled.value); rc = sqlite3_collation_needed(db, null); affirm( 0 == rc ); sqlite3_close_v2(db); affirm( 0 == db.getNativePointer() ); affirm(xDestroyCalled.value); } @ManualTest /* because threading is meaningless here */ private void testToUtf8(){ /** https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html Let's ensure that we can convert to standard UTF-8 in Java code (noting that the JNI native API has no way to do this). */ final byte[] ba = "a \0 b".getBytes(StandardCharsets.UTF_8); affirm( 5 == ba.length /* as opposed to 6 in modified utf-8 */); } private void testStatus(){ final OutputPointer.Int64 cur64 = new OutputPointer.Int64(); final OutputPointer.Int64 high64 = new OutputPointer.Int64(); final OutputPointer.Int32 cur32 = new OutputPointer.Int32(); final OutputPointer.Int32 high32 = new OutputPointer.Int32(); final sqlite3 db = createNewDb(); execSql(db, "create table t(a); insert into t values(1),(2),(3)"); |
︙ | ︙ | |||
513 514 515 516 517 518 519 | affirm( 0 == rc ); affirm( cur32.value > 0 ); affirm( high32.value == 0 /* always 0 for SCHEMA_USED */ ); sqlite3_close_v2(db); } | | | 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 | affirm( 0 == rc ); affirm( cur32.value > 0 ); affirm( high32.value == 0 /* always 0 for SCHEMA_USED */ ); sqlite3_close_v2(db); } private void testUdf1(){ final sqlite3 db = createNewDb(); // These ValueHolders are just to confirm that the func did what we want... final ValueHolder<Boolean> xDestroyCalled = new ValueHolder<>(false); final ValueHolder<Integer> xFuncAccum = new ValueHolder<>(0); // Create an SQLFunction instance using one of its 3 subclasses: // Scalar, Aggregate, or Window: |
︙ | ︙ | |||
557 558 559 560 561 562 563 | affirm(1 == n); affirm(6 == xFuncAccum.value); affirm( !xDestroyCalled.value ); sqlite3_close_v2(db); affirm( xDestroyCalled.value ); } | > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | | 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 | affirm(1 == n); affirm(6 == xFuncAccum.value); affirm( !xDestroyCalled.value ); sqlite3_close_v2(db); affirm( xDestroyCalled.value ); } private void testUdfThrows(){ final sqlite3 db = createNewDb(); final ValueHolder<Integer> xFuncAccum = new ValueHolder<>(0); SQLFunction funcAgg = new SQLFunction.Aggregate<Integer>(){ @Override public void xStep(sqlite3_context cx, sqlite3_value[] args){ /** Throwing from here should emit loud noise on stdout or stderr but the exception is supressed because we have no way to inform sqlite about it from these callbacks. */ //throw new RuntimeException("Throwing from an xStep"); } @Override public void xFinal(sqlite3_context cx){ throw new RuntimeException("Throwing from an xFinal"); } }; int rc = sqlite3_create_function(db, "myagg", 1, SQLITE_UTF8, funcAgg); affirm(0 == rc); affirm(0 == xFuncAccum.value); sqlite3_stmt stmt = prepare(db, "SELECT myagg(1)"); rc = sqlite3_step(stmt); sqlite3_finalize(stmt); affirm( 0 != rc ); affirm( sqlite3_errmsg(db).indexOf("an xFinal") > 0 ); SQLFunction funcSc = new SQLFunction.Scalar(){ @Override public void xFunc(sqlite3_context cx, sqlite3_value[] args){ throw new RuntimeException("Throwing from an xFunc"); } }; rc = sqlite3_create_function(db, "mysca", 0, SQLITE_UTF8, funcSc); affirm(0 == rc); affirm(0 == xFuncAccum.value); stmt = prepare(db, "SELECT mysca()"); rc = sqlite3_step(stmt); sqlite3_finalize(stmt); affirm( 0 != rc ); affirm( sqlite3_errmsg(db).indexOf("an xFunc") > 0 ); rc = sqlite3_create_function(db, "mysca", 1, -1, funcSc); affirm( SQLITE_FORMAT==rc, "invalid encoding value." ); sqlite3_close_v2(db); } private void testUdfJavaObject(){ final sqlite3 db = createNewDb(); final ValueHolder<sqlite3> testResult = new ValueHolder<>(db); final SQLFunction func = new SQLFunction.Scalar(){ public void xFunc(sqlite3_context cx, sqlite3_value args[]){ sqlite3_result_java_object(cx, testResult.value); } }; |
︙ | ︙ | |||
586 587 588 589 590 591 592 | ++n; } sqlite3_finalize(stmt); affirm( 1 == n ); sqlite3_close_v2(db); } | | | 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 | ++n; } sqlite3_finalize(stmt); affirm( 1 == n ); sqlite3_close_v2(db); } private void testUdfAggregate(){ final sqlite3 db = createNewDb(); final ValueHolder<Boolean> xFinalNull = // To confirm that xFinal() is called with no aggregate state // when the corresponding result set is empty. new ValueHolder<>(false); SQLFunction func = new SQLFunction.Aggregate<Integer>(){ @Override |
︙ | ︙ | |||
648 649 650 651 652 653 654 | sqlite3_finalize(stmt); execSql(db, "SELECT myfunc(1) WHERE 0"); affirm(xFinalNull.value); sqlite3_close_v2(db); } | | | 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 | sqlite3_finalize(stmt); execSql(db, "SELECT myfunc(1) WHERE 0"); affirm(xFinalNull.value); sqlite3_close_v2(db); } private void testUdfWindow(){ final sqlite3 db = createNewDb(); /* Example window function, table, and results taken from: https://sqlite.org/windowfunctions.html#udfwinfunc */ final SQLFunction func = new SQLFunction.Window<Integer>(){ private void xStepInverse(sqlite3_context cx, int v){ this.getAggregateState(cx,0).value += v; |
︙ | ︙ | |||
705 706 707 708 709 710 711 | } } sqlite3_finalize(stmt); affirm( 5 == n ); sqlite3_close_v2(db); } | | | | | | | 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 | } } sqlite3_finalize(stmt); affirm( 5 == n ); sqlite3_close_v2(db); } private void listBoundMethods(){ if(false){ final java.lang.reflect.Field[] declaredFields = SQLite3Jni.class.getDeclaredFields(); outln("Bound constants:\n"); for(java.lang.reflect.Field field : declaredFields) { if(java.lang.reflect.Modifier.isStatic(field.getModifiers())) { outln("\t",field.getName()); } } } final java.lang.reflect.Method[] declaredMethods = SQLite3Jni.class.getDeclaredMethods(); final java.util.List<String> funcList = new java.util.ArrayList<>(); for(java.lang.reflect.Method m : declaredMethods){ if((m.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0){ final String name = m.getName(); if(name.startsWith("sqlite3_")){ funcList.add(name); } } } int count = 0; java.util.Collections.sort(funcList); for(String n : funcList){ ++count; outln("\t",n,"()"); } outln(count," functions named sqlite3_*."); } private void testTrace(){ final sqlite3 db = createNewDb(); final ValueHolder<Integer> counter = new ValueHolder<>(0); /* Ensure that characters outside of the UTF BMP survive the trip from Java to sqlite3 and back to Java. (At no small efficiency penalty.) */ final String nonBmpChar = "😃"; sqlite3_trace_v2( |
︙ | ︙ | |||
785 786 787 788 789 790 791 | execSql(db, "SELECT coalesce(null,null,'"+nonBmpChar+"'); "+ "SELECT 'w"+nonBmpChar+"orld'"); affirm( 6 == counter.value ); sqlite3_close_v2(db); affirm( 7 == counter.value ); } | > | > | 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 | execSql(db, "SELECT coalesce(null,null,'"+nonBmpChar+"'); "+ "SELECT 'w"+nonBmpChar+"orld'"); affirm( 6 == counter.value ); sqlite3_close_v2(db); affirm( 7 == counter.value ); } @ManualTest /* because threads inherently break this test */ private void testBusy(){ final String dbName = "_busy-handler.db"; final OutputPointer.sqlite3 outDb = new OutputPointer.sqlite3(); final OutputPointer.sqlite3_stmt outStmt = new OutputPointer.sqlite3_stmt(); int rc = sqlite3_open(dbName, outDb); ++metrics.dbOpen; affirm( 0 == rc ); final sqlite3 db1 = outDb.get(); execSql(db1, "CREATE TABLE IF NOT EXISTS t(a)"); rc = sqlite3_open(dbName, outDb); |
︙ | ︙ | |||
835 836 837 838 839 840 841 | final java.io.File f = new java.io.File(dbName); f.delete(); }catch(Exception e){ /* ignore */ } } | | | | 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 | final java.io.File f = new java.io.File(dbName); f.delete(); }catch(Exception e){ /* ignore */ } } private void testProgress(){ final sqlite3 db = createNewDb(); final ValueHolder<Integer> counter = new ValueHolder<>(0); sqlite3_progress_handler(db, 1, new ProgressHandler(){ public int xCallback(){ ++counter.value; return 0; } }); execSql(db, "SELECT 1; SELECT 2;"); affirm( counter.value > 0 ); int nOld = counter.value; sqlite3_progress_handler(db, 0, null); execSql(db, "SELECT 1; SELECT 2;"); affirm( nOld == counter.value ); sqlite3_close_v2(db); } private void testCommitHook(){ final sqlite3 db = createNewDb(); final ValueHolder<Integer> counter = new ValueHolder<>(0); final ValueHolder<Integer> hookResult = new ValueHolder<>(0); final CommitHook theHook = new CommitHook(){ public int xCommitHook(){ ++counter.value; return hookResult.value; |
︙ | ︙ | |||
902 903 904 905 906 907 908 | hookResult.value = SQLITE_ERROR; int rc = execSql(db, false, "BEGIN; update t set a='j' where a='i'; COMMIT;"); affirm( SQLITE_CONSTRAINT == rc ); affirm( 6 == counter.value ); sqlite3_close_v2(db); } | | > | 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 | hookResult.value = SQLITE_ERROR; int rc = execSql(db, false, "BEGIN; update t set a='j' where a='i'; COMMIT;"); affirm( SQLITE_CONSTRAINT == rc ); affirm( 6 == counter.value ); sqlite3_close_v2(db); } private void testUpdateHook(){ final sqlite3 db = createNewDb(); final ValueHolder<Integer> counter = new ValueHolder<>(0); final ValueHolder<Integer> expectedOp = new ValueHolder<>(0); final UpdateHook theHook = new UpdateHook(){ @SuppressWarnings("unchecked") @Override public void xUpdateHook(int opId, String dbName, String tableName, long rowId){ ++counter.value; if( 0!=expectedOp.value ){ affirm( expectedOp.value == opId ); } } }; |
︙ | ︙ | |||
951 952 953 954 955 956 957 | affirm( newHook == oldHook ); expectedOp.value = SQLITE_UPDATE; execSql(db, "update t set a='i' where a='h'"); affirm( 6 == counter.value ); sqlite3_close_v2(db); } | > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | | 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 | affirm( newHook == oldHook ); expectedOp.value = SQLITE_UPDATE; execSql(db, "update t set a='i' where a='h'"); affirm( 6 == counter.value ); sqlite3_close_v2(db); } /** This test is functionally identical to testUpdateHook(), only with a different callback type. */ private synchronized void testPreUpdateHook(){ if( !sqlite3_compileoption_used("ENABLE_PREUPDATE_HOOK") ){ //outln("Skipping testPreUpdateHook(): no pre-update hook support."); return; } final sqlite3 db = createNewDb(); final ValueHolder<Integer> counter = new ValueHolder<>(0); final ValueHolder<Integer> expectedOp = new ValueHolder<>(0); final PreUpdateHook theHook = new PreUpdateHook(){ @SuppressWarnings("unchecked") @Override public void xPreUpdate(sqlite3 db, int opId, String dbName, String dbTable, long iKey1, long iKey2 ){ ++counter.value; switch( opId ){ case SQLITE_UPDATE: affirm( 0 < sqlite3_preupdate_count(db) ); affirm( null != sqlite3_preupdate_new(db, 0) ); affirm( null != sqlite3_preupdate_old(db, 0) ); break; case SQLITE_INSERT: affirm( null != sqlite3_preupdate_new(db, 0) ); break; case SQLITE_DELETE: affirm( null != sqlite3_preupdate_old(db, 0) ); break; default: break; } if( 0!=expectedOp.value ){ affirm( expectedOp.value == opId ); } } }; PreUpdateHook oldHook = sqlite3_preupdate_hook(db, theHook); affirm( null == oldHook ); expectedOp.value = SQLITE_INSERT; execSql(db, "CREATE TABLE t(a); INSERT INTO t(a) VALUES('a'),('b'),('c')"); affirm( 3 == counter.value ); expectedOp.value = SQLITE_UPDATE; execSql(db, "update t set a='d' where a='c';"); affirm( 4 == counter.value ); oldHook = sqlite3_preupdate_hook(db, theHook); affirm( theHook == oldHook ); expectedOp.value = SQLITE_DELETE; execSql(db, "DELETE FROM t where a='d'"); affirm( 5 == counter.value ); oldHook = sqlite3_preupdate_hook(db, null); affirm( theHook == oldHook ); execSql(db, "update t set a='e' where a='b';"); affirm( 5 == counter.value ); oldHook = sqlite3_preupdate_hook(db, null); affirm( null == oldHook ); final PreUpdateHook newHook = new PreUpdateHook(){ @Override public void xPreUpdate(sqlite3 db, int opId, String dbName, String tableName, long iKey1, long iKey2){ } }; oldHook = sqlite3_preupdate_hook(db, newHook); affirm( null == oldHook ); execSql(db, "update t set a='h' where a='a'"); affirm( 5 == counter.value ); oldHook = sqlite3_preupdate_hook(db, theHook); affirm( newHook == oldHook ); expectedOp.value = SQLITE_UPDATE; execSql(db, "update t set a='i' where a='h'"); affirm( 6 == counter.value ); sqlite3_close_v2(db); } private void testRollbackHook(){ final sqlite3 db = createNewDb(); final ValueHolder<Integer> counter = new ValueHolder<>(0); final RollbackHook theHook = new RollbackHook(){ public void xRollbackHook(){ ++counter.value; } }; |
︙ | ︙ | |||
989 990 991 992 993 994 995 | /** If FTS5 is available, runs FTS5 tests, else returns with no side effects. If it is available but loading of the FTS5 bits fails, it throws. */ @SuppressWarnings("unchecked") | > > | | | | 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 | /** If FTS5 is available, runs FTS5 tests, else returns with no side effects. If it is available but loading of the FTS5 bits fails, it throws. */ @SuppressWarnings("unchecked") @ManualTest /* because the Fts5 parts are not yet known to be thread-safe */ private void testFts5() throws Exception { if( !sqlite3_compileoption_used("ENABLE_FTS5") ){ //outln("SQLITE_ENABLE_FTS5 is not set. Skipping FTS5 tests."); return; } Exception err = null; try { Class t = Class.forName("org.sqlite.jni.TesterFts5"); java.lang.reflect.Constructor ctor = t.getConstructor(); ctor.setAccessible(true); |
︙ | ︙ | |||
1017 1018 1019 1020 1021 1022 1023 | if( null != err ){ outln("Exception: "+err); err.printStackTrace(); throw err; } } | | | 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 | if( null != err ){ outln("Exception: "+err); err.printStackTrace(); throw err; } } private void testAuthorizer(){ final sqlite3 db = createNewDb(); final ValueHolder<Integer> counter = new ValueHolder<>(0); final ValueHolder<Integer> authRc = new ValueHolder<>(0); final Authorizer auth = new Authorizer(){ public int xAuth(int op, String s0, String s1, String s2, String s3){ ++counter.value; //outln("xAuth(): "+s0+" "+s1+" "+s2+" "+s3); |
︙ | ︙ | |||
1039 1040 1041 1042 1043 1044 1045 | authRc.value = SQLITE_DENY; int rc = execSql(db, false, "UPDATE t SET a=2"); affirm( SQLITE_AUTH==rc ); // TODO: expand these tests considerably sqlite3_close(db); } | > > | | 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 | authRc.value = SQLITE_DENY; int rc = execSql(db, false, "UPDATE t SET a=2"); affirm( SQLITE_AUTH==rc ); // TODO: expand these tests considerably sqlite3_close(db); } @ManualTest/* because multiple threads legitimately make these results unpredictable */ private synchronized void testAutoExtension(){ final ValueHolder<Integer> val = new ValueHolder<>(0); final ValueHolder<String> toss = new ValueHolder<>(null); final AutoExtension ax = new AutoExtension(){ public synchronized int xEntryPoint(sqlite3 db){ ++val.value; if( null!=toss.value ){ throw new RuntimeException(toss.value); |
︙ | ︙ | |||
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 | rc = sqlite3_auto_extension( ax ); affirm( 0==rc ); // Must not add a new entry rc = sqlite3_auto_extension( ax ); affirm( 0==rc ); sqlite3_close( createNewDb() ); affirm( 3==val.value ); affirm( sqlite3_cancel_auto_extension(ax) ); affirm( !sqlite3_cancel_auto_extension(ax) ); sqlite3_close(createNewDb()); | > > > > > > > > | | > > > > > > > > > > > > > > > > > > > > > > > > > > > > | > > > > > > > | > > | | > > > > | > > > > | > | | > > > | > | < > | | | | > | > > | > | > | > > | > | > > > > > > > > > > > > > > > > > > | > > > > > > > > > > > > | > > | > | > | > > | > > | | | > > | > > | > > | > > > > > | > > > | > > > > | | > > > > > > > > > > > > > > > > > > > > > | > > > > > > > > > > > > > > > > | > > > > > > > > > > > > > > > > > | > > > > | > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | | | > > | > | | | | 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 | rc = sqlite3_auto_extension( ax ); affirm( 0==rc ); // Must not add a new entry rc = sqlite3_auto_extension( ax ); affirm( 0==rc ); sqlite3_close( createNewDb() ); affirm( 3==val.value ); sqlite3 db = createNewDb(); affirm( 4==val.value ); execSql(db, "ATTACH ':memory' as foo"); affirm( 4==val.value, "ATTACH uses the same connection, not sub-connections." ); sqlite3_close(db); db = null; affirm( sqlite3_cancel_auto_extension(ax) ); affirm( !sqlite3_cancel_auto_extension(ax) ); sqlite3_close(createNewDb()); affirm( 4==val.value ); rc = sqlite3_auto_extension( ax ); affirm( 0==rc ); Exception err = null; toss.value = "Throwing from AutoExtension."; try{ sqlite3_close(createNewDb()); }catch(Exception e){ err = e; } affirm( err!=null ); affirm( err.getMessage().indexOf(toss.value)>0 ); toss.value = null; val.value = 0; final AutoExtension ax2 = new AutoExtension(){ public synchronized int xEntryPoint(sqlite3 db){ ++val.value; return 0; } }; rc = sqlite3_auto_extension( ax2 ); affirm( 0 == rc ); sqlite3_close(createNewDb()); affirm( 2 == val.value ); affirm( sqlite3_cancel_auto_extension(ax) ); affirm( !sqlite3_cancel_auto_extension(ax) ); sqlite3_close(createNewDb()); affirm( 3 == val.value ); rc = sqlite3_auto_extension( ax ); affirm( 0 == rc ); sqlite3_close(createNewDb()); affirm( 5 == val.value ); affirm( sqlite3_cancel_auto_extension(ax2) ); affirm( !sqlite3_cancel_auto_extension(ax2) ); sqlite3_close(createNewDb()); affirm( 6 == val.value ); rc = sqlite3_auto_extension( ax2 ); affirm( 0 == rc ); sqlite3_close(createNewDb()); affirm( 8 == val.value ); sqlite3_reset_auto_extension(); sqlite3_close(createNewDb()); affirm( 8 == val.value ); affirm( !sqlite3_cancel_auto_extension(ax) ); affirm( !sqlite3_cancel_auto_extension(ax2) ); sqlite3_close(createNewDb()); affirm( 8 == val.value ); } @ManualTest /* because we only want to run this test manually */ private void testSleep(){ out("Sleeping briefly... "); sqlite3_sleep(600); outln("Woke up."); } private void nap() throws InterruptedException { if( takeNaps ){ Thread.sleep(java.util.concurrent.ThreadLocalRandom.current().nextInt(3, 17), 0); } } @ManualTest /* because we only want to run this test on demand */ private void testFail(){ affirm( false, "Intentional failure." ); } private void runTests(boolean fromThread) throws Exception { if(false) showCompileOption(); List<java.lang.reflect.Method> mlist = testMethods; affirm( null!=mlist ); if( shuffle ){ mlist = new ArrayList<>( testMethods.subList(0, testMethods.size()) ); java.util.Collections.shuffle(mlist); } if( listRunTests ){ synchronized(this.getClass()){ if( !fromThread ){ out("Initial test"," list: "); for(java.lang.reflect.Method m : testMethods){ out(m.getName()+" "); } outln(); outln("(That list excludes some which are hard-coded to run.)"); } out("Running"," tests: "); for(java.lang.reflect.Method m : mlist){ out(m.getName()+" "); } outln(); } } testToUtf8(); test1(); for(java.lang.reflect.Method m : mlist){ nap(); try{ m.invoke(this); }catch(java.lang.reflect.InvocationTargetException e){ outln("FAILURE: ",m.getName(),"(): ", e.getCause()); throw e; } } if( !fromThread ){ testBusy(); if( !mtMode ){ testAutoExtension() /* threads rightfully muck up these results */; testFts5(); } } synchronized( this.getClass() ){ ++nTestRuns; } } public void run() { try { runTests(0!=this.tId); }catch(Exception e){ synchronized( listErrors ){ listErrors.add(e); } }finally{ affirm( SQLite3Jni.uncacheJniEnv() ); affirm( !SQLite3Jni.uncacheJniEnv() ); } } /** Runs the basic sqlite3 JNI binding sanity-check suite. CLI flags: -q|-quiet: disables most test output. -t|-thread N: runs the tests in N threads concurrently. Default=1. -r|-repeat N: repeats the tests in a loop N times, each one consisting of the -thread value's threads. -shuffle: randomizes the order of most of the test functions. -naps: sleep small random intervals between tests in order to add some chaos for cross-thread contention. -list-tests: outputs the list of tests being run, minus some which are hard-coded. This is noisy in multi-threaded mode. -fail: forces an exception to be thrown during the test run. Use with -shuffle to make its appearance unpredictable. -v: emit some developer-mode info at the end. */ public static void main(String[] args) throws Exception { Integer nThread = null; boolean doSomethingForDev = false; Integer nRepeat = 1; boolean forceFail = false; boolean sqlLog = false; boolean squelchTestOutput = false; for( int i = 0; i < args.length; ){ String arg = args[i++]; if(arg.startsWith("-")){ arg = arg.replaceFirst("-+",""); if(arg.equals("v")){ doSomethingForDev = true; //listBoundMethods(); }else if(arg.equals("t") || arg.equals("thread")){ nThread = Integer.parseInt(args[i++]); }else if(arg.equals("r") || arg.equals("repeat")){ nRepeat = Integer.parseInt(args[i++]); }else if(arg.equals("shuffle")){ shuffle = true; }else if(arg.equals("list-tests")){ listRunTests = true; }else if(arg.equals("fail")){ forceFail = true; }else if(arg.equals("sqllog")){ sqlLog = true; }else if(arg.equals("naps")){ takeNaps = true; }else if(arg.equals("q") || arg.equals("quiet")){ squelchTestOutput = true; }else{ throw new IllegalArgumentException("Unhandled flag:"+arg); } } } { // Build list of tests to run from the methods named test*(). testMethods = new ArrayList<>(); for(final java.lang.reflect.Method m : Tester1.class.getDeclaredMethods()){ final String name = m.getName(); if( name.equals("testFail") ){ if( forceFail ){ testMethods.add(m); } }else if( !m.isAnnotationPresent( ManualTest.class ) ){ if( name.startsWith("test") ){ testMethods.add(m); } } } } if( sqlLog ){ if( sqlite3_compileoption_used("ENABLE_SQLLOG") ){ int rc = sqlite3_config( new SQLLog() { @Override public void xSqllog(sqlite3 db, String msg, int op){ switch(op){ case 0: outln("Opening db: ",db); break; case 1: outln(db,": ",msg); break; case 2: outln("Closing db: ",db); break; } } }); affirm( 0==rc ); }else{ outln("WARNING: -sqllog is not active because library was built ", "without SQLITE_ENABLE_SQLLOG."); } } quietMode = squelchTestOutput; outln("If you just saw warning messages regarding CallStaticObjectMethod, ", "you are very likely seeing the side effects of a known openjdk8 ", "bug. It is unsightly but does not affect the library."); final long timeStart = System.currentTimeMillis(); int nLoop = 0; affirm( 0==sqlite3_config( SQLITE_CONFIG_SINGLETHREAD ), "Could not switch to single-thread mode." ); affirm( 0==sqlite3_config( SQLITE_CONFIG_MULTITHREAD ), "Could not switch to multithread mode." ); affirm( 0==sqlite3_config( SQLITE_CONFIG_SERIALIZED ), "Could not switch to serialized threading mode." ); outln("libversion_number: ", sqlite3_libversion_number(),"\n", sqlite3_libversion(),"\n",SQLITE_SOURCE_ID); outln("Running ",nRepeat," loop(s) with ",nThread," thread(s) each."); if( takeNaps ) outln("Napping between tests is enabled."); for( int n = 0; n < nRepeat; ++n ){ if( nThread==null || nThread<=1 ){ new Tester1(0).runTests(false); continue; } Tester1.mtMode = true; final ExecutorService ex = Executors.newFixedThreadPool( nThread ); //final List<Future<?>> futures = new ArrayList<>(); ++nLoop; out((1==nLoop ? "" : " ")+nLoop); for( int i = 0; i < nThread; ++i ){ ex.submit( new Tester1(i), i ); } ex.shutdown(); try{ ex.awaitTermination(nThread*200, java.util.concurrent.TimeUnit.MILLISECONDS); ex.shutdownNow(); }catch (InterruptedException ie){ ex.shutdownNow(); Thread.currentThread().interrupt(); } if( !listErrors.isEmpty() ){ quietMode = false; outln("TEST ERRORS:"); Exception err = null; for( Exception e : listErrors ){ e.printStackTrace(); if( null==err ) err = e; } if( null!=err ) throw err; } } outln(); quietMode = false; final long timeEnd = System.currentTimeMillis(); outln("Tests done. Metrics across ",nTestRuns," total iteration(s):"); outln("\tAssertions checked: ",affirmCount); outln("\tDatabases opened: ",metrics.dbOpen); if( doSomethingForDev ){ sqlite3_do_something_for_developer(); } sqlite3_shutdown(); int nMethods = 0; int nNatives = 0; final java.lang.reflect.Method[] declaredMethods = SQLite3Jni.class.getDeclaredMethods(); for(java.lang.reflect.Method m : declaredMethods){ int mod = m.getModifiers(); if( 0!=(mod & java.lang.reflect.Modifier.STATIC) ){ final String name = m.getName(); if(name.startsWith("sqlite3_")){ ++nMethods; if( 0!=(mod & java.lang.reflect.Modifier.NATIVE) ){ ++nNatives; } } } } outln("\tSQLite3Jni.sqlite3_*() methods: "+ nNatives+" native methods and "+ (nMethods - nNatives)+" Java impls"); outln("\tTotal test time = " +(timeEnd - timeStart)+"ms"); } } |
Changes to ext/jni/src/org/sqlite/jni/TesterFts5.java.
︙ | ︙ | |||
68 69 70 71 72 73 74 | execSql(db, "select myaux(ft,a,b) from ft;"); affirm( 2==xFuncCount.value ); affirm( !xDestroyCalled.value ); sqlite3_close_v2(db); affirm( xDestroyCalled.value ); } | | < | | > | > | | < < | > | | > > | 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | execSql(db, "select myaux(ft,a,b) from ft;"); affirm( 2==xFuncCount.value ); affirm( !xDestroyCalled.value ); sqlite3_close_v2(db); affirm( xDestroyCalled.value ); } public TesterFts5(boolean verbose){ if(verbose){ final long timeStart = System.currentTimeMillis(); final int oldAffirmCount = Tester1.affirmCount; test1(); final int affirmCount = Tester1.affirmCount - oldAffirmCount; final long timeEnd = System.currentTimeMillis(); outln("FTS5 Tests done. Assertions checked = ",affirmCount, ", Total time = ",(timeEnd - timeStart),"ms"); }else{ test1(); } } public TesterFts5(){ this(false); } } |
Changes to ext/jni/src/org/sqlite/jni/sqlite3_context.java.
︙ | ︙ | |||
15 16 17 18 19 20 21 | /** sqlite3_context instances are used in conjunction with user-defined SQL functions (a.k.a. UDFs). */ public final class sqlite3_context extends NativePointerHolder<sqlite3_context> { /** | | < | 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | /** sqlite3_context instances are used in conjunction with user-defined SQL functions (a.k.a. UDFs). */ public final class sqlite3_context extends NativePointerHolder<sqlite3_context> { /** Only set by the JNI layer. */ private long aggregateContext = 0; /** getAggregateContext() corresponds to C's sqlite3_aggregate_context(), with a slightly different interface to account for cross-language differences. It serves the same |
︙ | ︙ |
Changes to ext/jni/src/org/sqlite/jni/tester/SQLTester.java.
︙ | ︙ | |||
246 247 248 249 250 251 252 | static int iStartEmoji = 0; private static String nextStartEmoji(){ return startEmoji[iStartEmoji++ % nStartEmoji]; } public void runTests() throws Exception { | | | | | | | | 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | static int iStartEmoji = 0; private static String nextStartEmoji(){ return startEmoji[iStartEmoji++ % nStartEmoji]; } public void runTests() throws Exception { final long tStart = System.currentTimeMillis(); for(String f : listInFiles){ reset(); ++nTestFile; final TestScript ts = new TestScript(f); outln(nextStartEmoji(), " starting [",f,"]"); boolean threw = false; final long timeStart = System.currentTimeMillis(); try{ ts.run(this); }catch(SQLTesterException e){ threw = true; outln("🔥EXCEPTION: ",e.getClass().getSimpleName(),": ",e.getMessage()); ++nAbortedScript; if( keepGoing ) outln("Continuing anyway becaure of the keep-going option."); else if( e.isFatal() ) throw e; }finally{ final long timeEnd = System.currentTimeMillis(); outln("🏁",(threw ? "❌" : "✅")," ",nTest," test(s) in ", (timeEnd-timeStart),"ms."); //ts.getFilename()); } } final long tEnd = System.currentTimeMillis(); outln("Total run-time: ",(tEnd-tStart),"ms"); Util.unlink(initialDbName); } private StringBuilder clearBuffer(StringBuilder b){ b.setLength(0);; return b; } |
︙ | ︙ |