interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / ext / jni / README.md

319 lines · 12387 bytes Raw Blame History Rendered
1SQLite3 via JNI
2========================================================================
3
4This directory houses a Java Native Interface (JNI) binding for the
5sqlite3 API. If you are reading this from the distribution ZIP file,
6links to resources in the canonical source tree will note work. The
7canonical copy of this file can be browsed at:
8
9 <https://sqlite.org/src/doc/trunk/ext/jni/README.md>
10
11Technical support is available in the forum:
12
13 <https://sqlite.org/forum>
14
15
16> **FOREWARNING:** the JNI subproject is experimental and subject to
17 any number of changes. This API is "feature-complete", with only a
18 few difficult-to-reach corners of the C API not represented here,
19 but it is not a supported deliverable of the project so does not
20 have same backward compatibility guarantees which the C APIs
21 do. That said: the [C-style API](#1to1ish) is especially resistent
22 to compatibility breakage because it's designed to be as close to
23 the C API as feasible.
24
25Project goals/requirements:
26
27- A [1-to-1(-ish) mapping of the C API](#1to1ish) to Java via JNI,
28 insofar as cross-language semantics allow for. A closely-related
29 goal is that [the C documentation](https://sqlite.org/c3ref/intro.html)
30 should be usable as-is, insofar as possible, for the JNI binding.
31
32- Support Java as far back as version 8 (2014).
33
34- Environment-independent. Should work everywhere both Java
35 and SQLite3 do.
36
37- No 3rd-party dependencies beyond the JDK. That includes no
38 build-level dependencies for specific IDEs and toolchains. We
39 welcome the addition of build files for arbitrary environments
40 insofar as they neither interfere with each other nor become
41 a maintenance burden for the sqlite developers.
42
43Non-goals:
44
45- Creation of high-level OO wrapper APIs. Clients are free to create
46 them off of the C-style API.
47
48- Virtual tables are unlikely to be supported due to the amount of
49 glue code needed to fit them into Java.
50
51- Support for mixed-mode operation, where client code accesses SQLite
52 both via the Java-side API and the C API via their own native
53 code. Such cases would be a minefield of potential mis-interactions
54 between this project's JNI bindings and mixed-mode client code.
55
56
57Hello World
58-----------------------------------------------------------------------
59
60```java
61import org.sqlite.jni.*;
62import static org.sqlite.jni.CApi.*;
63
64...
65
66final sqlite3 db = sqlite3_open(":memory:");
67try {
68 final int rc = sqlite3_errcode(db);
69 if( 0 != rc ){
70 if( null != db ){
71 System.out.print("Error opening db: "+sqlite3_errmsg(db));
72 }else{
73 System.out.print("Error opening db: rc="+rc);
74 }
75 ... handle error ...
76 }
77 // ... else use the db ...
78}finally{
79 // ALWAYS close databases using sqlite3_close() or sqlite3_close_v2()
80 // when done with them. All of their active statement handles must
81 // first have been passed to sqlite3_finalize().
82 sqlite3_close_v2(db);
83}
84```
85
86
87Building
88========================================================================
89
90The canonical builds assumes a Linux-like environment and requires:
91
92- GNU Make
93- A JDK supporting Java 8 or higher
94- A modern C compiler. gcc and clang should both work.
95
96Put simply:
97
98```console
99$ export JAVA_HOME=/path/to/jdk/root
100$ make
101$ make test
102$ make clean
103```
104
105The jar distribution can be created with `make jar`, but note that it
106does not contain the binary DLL file. A different DLL is needed for
107each target platform.
108
109
110<a id='1to1ish'></a>
111One-to-One(-ish) Mapping to C
112========================================================================
113
114This JNI binding aims to provide as close to a 1-to-1 experience with
115the C API as cross-language semantics allow. Interface changes are
116necessarily made where cross-language semantics do not allow a 1-to-1,
117and judiciously made where a 1-to-1 mapping would be unduly cumbersome
118to use in Java. In all cases, this binding makes every effort to
119provide semantics compatible with the C API documentation even if the
120interface to those semantics is slightly different. Any cases which
121deviate from those semantics (either removing or adding semantics) are
122clearly documented.
123
124Where it makes sense to do so for usability, Java-side overloads are
125provided which accept or return data in alternative forms or provide
126sensible default argument values. In all such cases they are thin
127proxies around the corresponding C APIs and do not introduce new
128semantics.
129
130In a few cases, Java-specific capabilities have been added in
131new APIs, all of which have "_java" somewhere in their names.
132Examples include:
133
134- `sqlite3_result_java_object()`
135- `sqlite3_column_java_object()`
136- `sqlite3_value_java_object()`
137
138which, as one might surmise, collectively enable the passing of
139arbitrary Java objects from user-defined SQL functions through to the
140caller.
141
142
143Golden Rule: Garbage Collection Cannot Free SQLite Resources
144------------------------------------------------------------------------
145
146It is important that all databases and prepared statement handles get
147cleaned up by client code. A database cannot be closed if it has open
148statement handles. `sqlite3_close()` fails if the db cannot be closed
149whereas `sqlite3_close_v2()` recognizes that case and marks the db as
150a "zombie," pending finalization when the library detects that all
151pending statements have been closed. Be aware that Java garbage
152collection _cannot_ close a database or finalize a prepared statement.
153Those things require explicit API calls.
154
155Classes for which it is sensible support Java's `AutoCloseable`
156interface so can be used with try-with-resources constructs.
157
158
159Golden Rule #2: _Never_ Throw from Callbacks (Unless...)
160------------------------------------------------------------------------
161
162All routines in this API, barring explicitly documented exceptions,
163retain C-like semantics. For example, they are not permitted to throw
164or propagate exceptions and must return error information (if any) via
165result codes or `null`. The only cases where the C-style APIs may
166throw is through client-side misuse, e.g. passing in a null where it
167may cause a `NullPointerException`. The APIs clearly mark function
168parameters which should not be null, and it internally uses the
169`SQLITE_API_ARMOR` mechanism to help product against such misuse. Some
170C-style APIs explicitly accept `null` as a no-op for usability's sake,
171and some of the JNI APIs deliberately return an error code, instead of
172segfaulting, when passed a `null`. There are no known cases where it
173will misuse memory if passed a `null` or out-of-range value from
174client code.
175
176Client-defined callbacks _must never throw exceptions_ unless _very
177explicitly documented_ as being throw-safe. Exceptions are generally
178reserved for higher-level bindings which are constructed to
179specifically deal with them and ensure that they do not leak C-level
180resources. In some cases, callback handlers are permitted to throw, in
181which cases they get translated to C-level result codes and/or
182messages. If a callback which is not permitted to throw throws, its
183exception may trigger debug output but will otherwise be suppressed.
184
185The reason some callbacks are permitted to throw and others not is
186because all such callbacks act as proxies for C function callback
187interfaces and some of those interfaces have no error-reporting
188mechanism. Those which are capable of propagating errors back through
189the library convert exceptions from callbacks into corresponding
190C-level error information. Those which cannot propagate errors
191necessarily suppress any exceptions in order to maintain the C-style
192semantics of the APIs.
193
194
195Unwieldy Constructs are Re-mapped
196------------------------------------------------------------------------
197
198Some constructs, when modelled 1-to-1 from C to Java, are unduly
199clumsy to work with in Java because they try to shoehorn C's way of
200doing certain things into Java's wildly different ways. The following
201subsections cover those, starting with a verbose explanation and
202demonstration of where such changes are "really necessary" for
203usability's sake...
204
205### Custom Collations
206
207A prime example of where interface changes for Java are necessary for
208usability is [registration of a custom
209collation](https://sqlite.org/c3ref/create_collation.html):
210
211```c
212// C:
213int sqlite3_create_collation(sqlite3 * db, const char * name, int eTextRep,
214 void *pUserData,
215 int (*xCompare)(void*,int,void const *,int,void const *));
216
217int sqlite3_create_collation_v2(sqlite3 * db, const char * name, int eTextRep,
218 void *pUserData,
219 int (*xCompare)(void*,int,void const *,int,void const *),
220 void (*xDestroy)(void*));
221```
222
223The `pUserData` object is optional client-defined state for the
224`xCompare()` and/or `xDestroy()` callback functions, both of which are
225passed that object as their first argument. That data is passed around
226"externally" in C because that's how C models the world. If we were to
227bind that part as-is to Java, the result would be awkward to use (^Yes,
228we tried this.):
229
230```java
231// Java:
232int sqlite3_create_collation(sqlite3 db, String name, int eTextRep,
233 Object pUserData, xCompareType xCompare);
234
235int sqlite3_create_collation_v2(sqlite3 db, String name, int eTextRep,
236 Object pUserData,
237 xCompareType xCompare, xDestroyType xDestroy);
238```
239
240The awkwardness comes from (A) having two distinctly different objects
241for callbacks and (B) having their internal state provided separately,
242which is ill-fitting in Java. For the sake of usability, C APIs which
243follow that pattern use a slightly different Java interface:
244
245```java
246int sqlite3_create_collation(sqlite3 db, String name, int eTextRep,
247 SomeCallbackType collation);
248```
249
250Where the `Collation` class has an abstract `call()` method and
251no-op `xDestroy()` method which can be overridden if needed, leading to
252a much more Java-esque usage:
253
254```java
255int rc = sqlite3_create_collation(db, "mycollation", SQLITE_UTF8, new SomeCallbackType(){
256
257 // Required comparison function:
258 @Override public int call(byte[] lhs, byte[] rhs){ ... }
259
260 // Optional finalizer function:
261 @Override public void xDestroy(){ ... }
262
263 // Optional local state:
264 private String localState1 =
265 "This is local state. There are many like it, but this one is mine.";
266 private MyStateType localState2 = new MyStateType();
267 ...
268});
269```
270
271Noting that:
272
273- It is possible to bind in call-scope-local state via closures, if
274 desired, as opposed to packing it into the Collation object.
275
276- No capabilities of the C API are lost or unduly obscured via the
277 above API reshaping, so power users need not make any compromises.
278
279- In the specific example above, `sqlite3_create_collation_v2()`
280 becomes superfluous because the provided interface effectively
281 provides both the v1 and v2 interfaces, the difference being that
282 overriding the `xDestroy()` method effectively gives it v2
283 semantics.
284
285
286### User-defined SQL Functions (a.k.a. UDFs)
287
288The [`sqlite3_create_function()`](https://sqlite.org/c3ref/create_function.html)
289family of APIs make heavy use of function pointers to provide
290client-defined callbacks, necessitating interface changes in the JNI
291binding. The Java API has only one core function-registration function:
292
293```java
294int sqlite3_create_function(sqlite3 db, String funcName, int nArgs,
295 int flags, SQLFunction func);
296```
297
298`SQLFunction` is not used directly, but is instead instantiated via
299one of its three subclasses:
300
301- `ScalarFunction` implements simple scalar functions using but a
302 single callback.
303- `AggregateFunction` implements aggregate functions using two
304 callbacks.
305- `WindowFunction` implements window functions using four
306 callbacks.
307
308Search [`Tester1.java`](/file/ext/jni/src/org/sqlite/jni/capi/Tester1.java) for
309`SQLFunction` for how it's used.
310
311Reminder: see the disclaimer at the top of this document regarding the
312in-flux nature of this API.
313
314### And so on...
315
316Various APIs which accept callbacks, e.g. `sqlite3_trace_v2()` and
317`sqlite3_update_hook()`, use interfaces similar to those shown above.
318Despite the changes in signature, the JNI layer makes every effort to
319provide the same semantics as the C API documentation describes.