2 ========================================================================
4 This directory houses a Java Native Interface (JNI) binding for the
5 sqlite3 API. If you are reading this from the distribution ZIP file,
6 links to resources in the canonical source tree will note work. The
7 canonical copy of this file can be browsed at:
9 <https://sqlite.org/src/doc/trunk/ext/jni/README.md>
11 Technical support is available in the forum:
13 <https://sqlite.org/forum>
16 > **FOREWARNING:** this subproject is very much in development and
17 subject to any number of changes. Please do not rely on any
18 information about its API until this disclaimer is removed. The JNI
19 bindings released with version 3.43 are a "tech preview." Once
20 finalized, strong backward compatibility guarantees will apply.
22 Project goals/requirements:
24 - A [1-to-1(-ish) mapping of the C API](#1to1ish) to Java via JNI,
25 insofar as cross-language semantics allow for. A closely-related
26 goal is that [the C documentation](https://sqlite.org/c3ref/intro.html)
27 should be usable as-is, insofar as possible, for the JNI binding.
29 - Support Java as far back as version 8 (2014).
31 - Environment-independent. Should work everywhere both Java
34 - No 3rd-party dependencies beyond the JDK. That includes no
35 build-level dependencies for specific IDEs and toolchains. We
36 welcome the addition of build files for arbitrary environments
37 insofar as they neither interfere with each other nor become
38 a maintenance burden for the sqlite developers.
42 - Creation of high-level OO wrapper APIs. Clients are free to create
43 them off of the C-style API.
45 - Virtual tables are unlikely to be supported due to the amount of
46 glue code needed to fit them into Java.
48 - Support for mixed-mode operation, where client code accesses SQLite
49 both via the Java-side API and the C API via their own native
50 code. Such cases would be a minefield of potential mis-interactions
51 between this project's JNI bindings and mixed-mode client code.
55 -----------------------------------------------------------------------
58 import org.sqlite.jni.*;
59 import static org.sqlite.jni.CApi.*;
63 final sqlite3 db = sqlite3_open(":memory:");
65 final int rc = sqlite3_errcode(db);
68 System.out.print("Error opening db: "+sqlite3_errmsg(db));
70 System.out.print("Error opening db: rc="+rc);
74 // ... else use the db ...
76 // ALWAYS close databases using sqlite3_close() or sqlite3_close_v2()
77 // when done with them. All of their active statement handles must
78 // first have been passed to sqlite3_finalize().
85 ========================================================================
87 The canonical builds assumes a Linux-like environment and requires:
90 - A JDK supporting Java 8 or higher
91 - A modern C compiler. gcc and clang should both work.
96 $ export JAVA_HOME=/path/to/jdk/root
102 The jar distribution can be created with `make jar`, but note that it
103 does not contain the binary DLL file. A different DLL is needed for
104 each target platform.
108 One-to-One(-ish) Mapping to C
109 ========================================================================
111 This JNI binding aims to provide as close to a 1-to-1 experience with
112 the C API as cross-language semantics allow. Interface changes are
113 necessarily made where cross-language semantics do not allow a 1-to-1,
114 and judiciously made where a 1-to-1 mapping would be unduly cumbersome
115 to use in Java. In all cases, this binding makes every effort to
116 provide semantics compatible with the C API documentation even if the
117 interface to those semantics is slightly different. Any cases which
118 deviate from those semantics (either removing or adding semantics) are
121 Where it makes sense to do so for usability, Java-side overloads are
122 provided which accept or return data in alternative forms or provide
123 sensible default argument values. In all such cases they are thin
124 proxies around the corresponding C APIs and do not introduce new
127 In a few cases, Java-specific capabilities have been added in
128 new APIs, all of which have "_java" somewhere in their names.
131 - `sqlite3_result_java_object()`
132 - `sqlite3_column_java_object()`
133 - `sqlite3_value_java_object()`
135 which, as one might surmise, collectively enable the passing of
136 arbitrary Java objects from user-defined SQL functions through to the
140 Golden Rule: Garbage Collection Cannot Free SQLite Resources
141 ------------------------------------------------------------------------
143 It is important that all databases and prepared statement handles get
144 cleaned up by client code. A database cannot be closed if it has open
145 statement handles. `sqlite3_close()` fails if the db cannot be closed
146 whereas `sqlite3_close_v2()` recognizes that case and marks the db as
147 a "zombie," pending finalization when the library detects that all
148 pending statements have been closed. Be aware that Java garbage
149 collection _cannot_ close a database or finalize a prepared statement.
150 Those things require explicit API calls.
152 Classes for which it is sensible support Java's `AutoCloseable`
153 interface so can be used with try-with-resources constructs.
156 Golden Rule #2: _Never_ Throw from Callbacks (Unless...)
157 ------------------------------------------------------------------------
159 All routines in this API, barring explicitly documented exceptions,
160 retain C-like semantics. For example, they are not permitted to throw
161 or propagate exceptions and must return error information (if any) via
162 result codes or `null`. The only cases where the C-style APIs may
163 throw is through client-side misuse, e.g. passing in a null where it
164 may cause a `NullPointerException`. The APIs clearly mark function
165 parameters which should not be null, but does not generally actively
166 defend itself against such misuse. Some C-style APIs explicitly accept
167 `null` as a no-op for usability's sake, and some of the JNI APIs
168 deliberately return an error code, instead of segfaulting, when passed
171 Client-defined callbacks _must never throw exceptions_ unless _very
172 explitly documented_ as being throw-safe. Exceptions are generally
173 reserved for higher-level bindings which are constructed to
174 specifically deal with them and ensure that they do not leak C-level
175 resources. In some cases, callback handlers are permitted to throw, in
176 which cases they get translated to C-level result codes and/or
177 messages. If a callback which is not permitted to throw throws, its
178 exception may trigger debug output but will otherwise be suppressed.
180 The reason some callbacks are permitted to throw and others not is
181 because all such callbacks act as proxies for C function callback
182 interfaces and some of those interfaces have no error-reporting
183 mechanism. Those which are capable of propagating errors back through
184 the library convert exceptions from callbacks into corresponding
185 C-level error information. Those which cannot propagate errors
186 necessarily suppress any exceptions in order to maintain the C-style
187 semantics of the APIs.
190 Unwieldy Constructs are Re-mapped
191 ------------------------------------------------------------------------
193 Some constructs, when modelled 1-to-1 from C to Java, are unduly
194 clumsy to work with in Java because they try to shoehorn C's way of
195 doing certain things into Java's wildly different ways. The following
196 subsections cover those, starting with a verbose explanation and
197 demonstration of where such changes are "really necessary"...
199 ### Custom Collations
201 A prime example of where interface changes for Java are necessary for
202 usability is [registration of a custom
203 collation](https://sqlite.org/c3ref/create_collation.html):
207 int sqlite3_create_collation(sqlite3 * db, const char * name, int eTextRep,
209 int (*xCompare)(void*,int,void const *,int,void const *));
211 int sqlite3_create_collation_v2(sqlite3 * db, const char * name, int eTextRep,
213 int (*xCompare)(void*,int,void const *,int,void const *),
214 void (*xDestroy)(void*));
217 The `pUserData` object is optional client-defined state for the
218 `xCompare()` and/or `xDestroy()` callback functions, both of which are
219 passed that object as their first argument. That data is passed around
220 "externally" in C because that's how C models the world. If we were to
221 bind that part as-is to Java, the result would be awkward to use (^Yes,
226 int sqlite3_create_collation(sqlite3 db, String name, int eTextRep,
227 Object pUserData, xCompareType xCompare);
229 int sqlite3_create_collation_v2(sqlite3 db, String name, int eTextRep,
231 xCompareType xCompare, xDestroyType xDestroy);
234 The awkwardness comes from (A) having two distinctly different objects
235 for callbacks and (B) having their internal state provided separately,
236 which is ill-fitting in Java. For the sake of usability, C APIs which
237 follow that pattern use a slightly different Java interface:
240 int sqlite3_create_collation(sqlite3 db, String name, int eTextRep,
241 SomeCallbackType collation);
244 Where the `Collation` class has an abstract `call()` method and
245 no-op `xDestroy()` method which can be overridden if needed, leading to
246 a much more Java-esque usage:
249 int rc = sqlite3_create_collation(db, "mycollation", SQLITE_UTF8, new SomeCallbackType(){
251 // Required comparison function:
252 @Override public int call(byte[] lhs, byte[] rhs){ ... }
254 // Optional finalizer function:
255 @Override public void xDestroy(){ ... }
257 // Optional local state:
258 private String localState1 =
259 "This is local state. There are many like it, but this one is mine.";
260 private MyStateType localState2 = new MyStateType();
267 - It is possible to bind in call-scope-local state via closures, if
268 desired, as opposed to packing it into the Collation object.
270 - No capabilities of the C API are lost or unduly obscured via the
271 above API reshaping, so power users need not make any compromises.
273 - In the specific example above, `sqlite3_create_collation_v2()`
274 becomes superfluous because the provided interface effectively
275 provides both the v1 and v2 interfaces, the difference being that
276 overriding the `xDestroy()` method effectively gives it v2
280 ### User-defined SQL Functions (a.k.a. UDFs)
282 The [`sqlite3_create_function()`](https://sqlite.org/c3ref/create_function.html)
283 family of APIs make heavy use of function pointers to provide
284 client-defined callbacks, necessitating interface changes in the JNI
285 binding. The Java API has only one core function-registration function:
288 int sqlite3_create_function(sqlite3 db, String funcName, int nArgs,
289 int encoding, SQLFunction func);
292 > Design question: does the encoding argument serve any purpose in
293 Java? That's as-yet undetermined. If not, it will be removed.
295 `SQLFunction` is not used directly, but is instead instantiated via
296 one of its three subclasses:
298 - `ScalarFunction` implements simple scalar functions using but a
300 - `AggregateFunction` implements aggregate functions using two
302 - `WindowFunction` implements window functions using four
305 Search [`Tester1.java`](/file/ext/jni/src/org/sqlite/jni/capi/Tester1.java) for
306 `SQLFunction` for how it's used.
308 Reminder: see the disclaimer at the top of this document regarding the
309 in-flux nature of this API.
313 Various APIs which accept callbacks, e.g. `sqlite3_trace_v2()` and
314 `sqlite3_update_hook()`, use interfaces similar to those shown above.
315 Despite the changes in signature, the JNI layer makes every effort to
316 provide the same semantics as the C API documentation suggests.