Add jextract module: SQLite bindings generated with jextract, FFM arenas, C strings, out-parameters, errors, upcalls, and a JMH comparison with JNI
jextract-25 early-access build (25-jextract+2-4) on JDK 25.0.5+8 against SQLite 3.45.1: 25 functions and 13 constants generated into 4 committed files (the whole header would be 83 files), a small Db wrapper, the four arena kinds used wrongly on purpose, ADDRESS vs C_POINTER zero-length vs unbounded segments and the SIGSEGV from getString on a NULL pointer, sqlite3_open out-parameter, return codes to exceptions, a sqlite3_exec upcall and the VM exit when it throws, the JDK 25 native-access warning and --illegal-native-access=deny, library loading failures, and a JMH benchmark of FFM vs hand-written JNI vs plain Java (indicative only: shared 2-CPU machine). Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b6Kg9RWSTJzyz6KP9X
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
package demo;
|
||||
|
||||
import java.lang.foreign.Arena;
|
||||
import java.lang.foreign.MemorySegment;
|
||||
import java.lang.foreign.ValueLayout;
|
||||
|
||||
/** The four arena kinds, and what each one does when you use it wrongly. Every message is real. */
|
||||
public class Arenas {
|
||||
static void show(String label, Runnable r) {
|
||||
try {
|
||||
r.run();
|
||||
System.out.println(label + " -> ok");
|
||||
} catch (Throwable t) {
|
||||
System.out.println(label + " -> " + t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
static void inThread(Runnable r) {
|
||||
Thread t = new Thread(r, "other");
|
||||
t.start();
|
||||
try {
|
||||
t.join();
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println("== confined: one owner thread");
|
||||
Arena confined = Arena.ofConfined();
|
||||
MemorySegment c = confined.allocate(8);
|
||||
c.set(ValueLayout.JAVA_LONG, 0, 42L);
|
||||
show("owner reads", () -> c.get(ValueLayout.JAVA_LONG, 0));
|
||||
inThread(() -> show("other thread reads", () -> c.get(ValueLayout.JAVA_LONG, 0)));
|
||||
inThread(() -> show("other thread closes", confined::close));
|
||||
confined.close();
|
||||
show("read after close", () -> c.get(ValueLayout.JAVA_LONG, 0));
|
||||
show("close twice", confined::close);
|
||||
|
||||
System.out.println("== shared: any thread, one close");
|
||||
Arena shared = Arena.ofShared();
|
||||
MemorySegment s = shared.allocate(8);
|
||||
s.set(ValueLayout.JAVA_LONG, 0, 7L);
|
||||
inThread(() -> show("other thread reads", () -> s.get(ValueLayout.JAVA_LONG, 0)));
|
||||
inThread(() -> show("other thread closes", shared::close));
|
||||
show("read after close", () -> s.get(ValueLayout.JAVA_LONG, 0));
|
||||
|
||||
System.out.println("== auto: the garbage collector frees it; close() is not allowed");
|
||||
Arena auto = Arena.ofAuto();
|
||||
show("allocate 8 bytes", () -> auto.allocate(8));
|
||||
show("close()", auto::close);
|
||||
|
||||
System.out.println("== global: never freed; close() is not allowed");
|
||||
show("allocate 8 bytes", () -> Arena.global().allocate(8));
|
||||
show("close()", () -> Arena.global().close());
|
||||
|
||||
System.out.println("== bounds: a segment knows its size");
|
||||
try (Arena a = Arena.ofConfined()) {
|
||||
MemorySegment four = a.allocate(4);
|
||||
show("read int at offset 0", () -> four.get(ValueLayout.JAVA_INT, 0));
|
||||
show("read int at offset 4", () -> four.get(ValueLayout.JAVA_INT, 4));
|
||||
show("read long at offset 0", () -> four.get(ValueLayout.JAVA_LONG, 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package demo;
|
||||
|
||||
import static demo.sqlite.sqlite3_h.*;
|
||||
|
||||
import demo.sqlite.sqlite3_exec$callback;
|
||||
import java.lang.foreign.Arena;
|
||||
import java.lang.foreign.MemorySegment;
|
||||
import java.lang.foreign.ValueLayout;
|
||||
|
||||
/**
|
||||
* sqlite3_exec calls a C function pointer once per result row. jextract generated an interface
|
||||
* for that pointer type; a lambda implements it, and allocate() turns the lambda into a real C function pointer.
|
||||
*/
|
||||
public class Callbacks {
|
||||
public static void main(String[] args) {
|
||||
boolean explode = args.length > 0 && args[0].equals("explode");
|
||||
try (Db db = Db.open(":memory:"); Arena arena = Arena.ofConfined()) {
|
||||
db.exec("CREATE TABLE t(id INTEGER, name TEXT)");
|
||||
db.exec("INSERT INTO t VALUES (1,'one'),(2,'two'),(3,NULL)");
|
||||
|
||||
sqlite3_exec$callback.Function onRow = (user, argc, values, names) -> {
|
||||
if (explode) {
|
||||
throw new IllegalStateException("thrown inside the callback");
|
||||
}
|
||||
// values and names are char** : argc pointers each. Read them as an array of pointers.
|
||||
MemorySegment vals = values.reinterpret((long) argc * ValueLayout.ADDRESS.byteSize());
|
||||
MemorySegment nms = names.reinterpret((long) argc * ValueLayout.ADDRESS.byteSize());
|
||||
StringBuilder sb = new StringBuilder("row:");
|
||||
for (int i = 0; i < argc; i++) {
|
||||
MemorySegment v = vals.getAtIndex(C_POINTER, i);
|
||||
String value = v.address() == 0 ? "NULL" : v.getString(0);
|
||||
sb.append(' ').append(nms.getAtIndex(C_POINTER, i).getString(0)).append('=').append(value);
|
||||
}
|
||||
System.out.println(sb);
|
||||
return 0; // non-zero would abort the query with SQLITE_ABORT
|
||||
};
|
||||
MemorySegment stub = sqlite3_exec$callback.allocate(onRow, arena); // the C function pointer
|
||||
MemorySegment errOut = arena.allocate(C_POINTER);
|
||||
int rc = sqlite3_exec(db.handle(), arena.allocateFrom("SELECT id, name FROM t"), stub, MemorySegment.NULL, errOut);
|
||||
System.out.println("sqlite3_exec returned " + rc);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package demo;
|
||||
|
||||
import static demo.sqlite.sqlite3_h.*;
|
||||
|
||||
import java.lang.foreign.Arena;
|
||||
import java.lang.foreign.MemorySegment;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A small hand-written layer over the jextract-generated {@code sqlite3_h} class.
|
||||
* Everything below the {@code public} methods is plain FFM; nothing here is generated.
|
||||
*/
|
||||
public final class Db implements AutoCloseable {
|
||||
private final MemorySegment handle; // the sqlite3* — owned by SQLite, NOT by any Arena
|
||||
|
||||
private Db(MemorySegment handle) {
|
||||
this.handle = handle;
|
||||
}
|
||||
|
||||
public static Db open(String path) {
|
||||
return open(path, SQLITE_OPEN_READWRITE() | SQLITE_OPEN_CREATE());
|
||||
}
|
||||
|
||||
public static Db open(String path, int flags) {
|
||||
// A confined arena: the two small native buffers below live exactly as long as this block.
|
||||
try (Arena arena = Arena.ofConfined()) {
|
||||
MemorySegment out = arena.allocate(C_POINTER); // room for ONE pointer: the sqlite3** out-parameter
|
||||
MemorySegment cPath = arena.allocateFrom(path); // Java String -> NUL-terminated UTF-8 C string
|
||||
int rc = sqlite3_open_v2(cPath, out, flags, MemorySegment.NULL);
|
||||
MemorySegment db = out.get(C_POINTER, 0); // read the pointer SQLite wrote
|
||||
if (rc != SQLITE_OK()) {
|
||||
// SQLite hands back a handle even on failure; it carries the message and must still be closed.
|
||||
String message = sqlite3_errmsg(db).getString(0);
|
||||
sqlite3_close(db);
|
||||
throw new SqliteException(rc, message);
|
||||
}
|
||||
return new Db(db);
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs SQL that returns no rows (DDL, INSERT...). Uses sqlite3_exec without a callback. */
|
||||
public void exec(String sql) {
|
||||
try (Arena arena = Arena.ofConfined()) {
|
||||
MemorySegment errOut = arena.allocate(C_POINTER); // char** errmsg, SQLite fills it only on failure
|
||||
int rc = sqlite3_exec(handle, arena.allocateFrom(sql), MemorySegment.NULL, MemorySegment.NULL, errOut);
|
||||
if (rc != SQLITE_OK()) {
|
||||
MemorySegment msg = errOut.get(C_POINTER, 0);
|
||||
String text = msg.address() == 0 ? errmsg() : msg.getString(0);
|
||||
sqlite3_free(msg); // this string came from sqlite3_malloc: we must free it
|
||||
throw new SqliteException(rc, text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs a SELECT and returns every row as a list of strings. */
|
||||
public List<List<String>> query(String sql) {
|
||||
try (Arena arena = Arena.ofConfined(); Stmt st = prepare(arena, sql)) {
|
||||
List<List<String>> rows = new ArrayList<>();
|
||||
int cols = sqlite3_column_count(st.ptr);
|
||||
int rc;
|
||||
while ((rc = sqlite3_step(st.ptr)) == SQLITE_ROW()) {
|
||||
List<String> row = new ArrayList<>(cols);
|
||||
for (int i = 0; i < cols; i++) {
|
||||
row.add(text(st.ptr, i));
|
||||
}
|
||||
rows.add(row);
|
||||
}
|
||||
if (rc != SQLITE_DONE()) {
|
||||
throw new SqliteException(rc, errmsg());
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
|
||||
/** Column i of the current row as a String; null for SQL NULL. */
|
||||
static String text(MemorySegment stmt, int i) {
|
||||
if (sqlite3_column_type(stmt, i) == SQLITE_NULL()) {
|
||||
return null; // sqlite3_column_text would return a NULL pointer here
|
||||
}
|
||||
return sqlite3_column_text(stmt, i).getString(0);
|
||||
}
|
||||
|
||||
/** A prepared statement. The sqlite3_stmt* belongs to SQLite, so it needs an explicit finalize. */
|
||||
public final class Stmt implements AutoCloseable {
|
||||
final MemorySegment ptr;
|
||||
|
||||
public MemorySegment ptr() {
|
||||
return ptr;
|
||||
}
|
||||
|
||||
Stmt(MemorySegment ptr) {
|
||||
this.ptr = ptr;
|
||||
}
|
||||
|
||||
public void bindInt(int index, int value) {
|
||||
check(sqlite3_bind_int(ptr, index, value));
|
||||
}
|
||||
|
||||
/** SQLITE_TRANSIENT tells SQLite to copy the bytes now, so the temporary C string may be freed straight away. */
|
||||
public void bindText(Arena arena, int index, String value) {
|
||||
check(sqlite3_bind_text(ptr, index, arena.allocateFrom(value), -1, SQLITE_TRANSIENT()));
|
||||
}
|
||||
|
||||
public boolean step() {
|
||||
int rc = sqlite3_step(ptr);
|
||||
if (rc == SQLITE_ROW()) return true;
|
||||
if (rc == SQLITE_DONE()) return false;
|
||||
throw new SqliteException(rc, errmsg());
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
sqlite3_reset(ptr);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
sqlite3_finalize(ptr);
|
||||
}
|
||||
}
|
||||
|
||||
public Stmt prepare(Arena arena, String sql) {
|
||||
MemorySegment out = arena.allocate(C_POINTER);
|
||||
int rc = sqlite3_prepare_v2(handle, arena.allocateFrom(sql), -1, out, MemorySegment.NULL);
|
||||
check(rc);
|
||||
return new Stmt(out.get(C_POINTER, 0));
|
||||
}
|
||||
|
||||
public int changes() {
|
||||
return sqlite3_changes(handle);
|
||||
}
|
||||
|
||||
public long lastInsertRowid() {
|
||||
return sqlite3_last_insert_rowid(handle);
|
||||
}
|
||||
|
||||
public String errmsg() {
|
||||
return sqlite3_errmsg(handle).getString(0);
|
||||
}
|
||||
|
||||
public MemorySegment handle() {
|
||||
return handle;
|
||||
}
|
||||
|
||||
private void check(int rc) {
|
||||
if (rc != SQLITE_OK()) {
|
||||
throw new SqliteException(rc, errmsg());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
sqlite3_close(handle);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package demo;
|
||||
|
||||
import static demo.sqlite.sqlite3_h.*;
|
||||
|
||||
/** Return codes become exceptions. Each failure below is real SQLite output. */
|
||||
public class Errors {
|
||||
static void attempt(String label, Runnable r) {
|
||||
try {
|
||||
r.run();
|
||||
System.out.println(label + " -> no error");
|
||||
} catch (SqliteException e) {
|
||||
System.out.println(label + " -> " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
attempt("open in a directory that does not exist", () -> Db.open("/no/such/dir/app.db").close());
|
||||
attempt("open a missing file read-only", () -> Db.open("/tmp/jextract-demo-missing.db", SQLITE_OPEN_READONLY()).close());
|
||||
try (Db db = Db.open(":memory:")) {
|
||||
attempt("syntax error", () -> db.exec("SELEC 1"));
|
||||
attempt("missing table", () -> db.exec("INSERT INTO ghost VALUES (1)"));
|
||||
db.exec("CREATE TABLE t(id INTEGER PRIMARY KEY, name TEXT NOT NULL)");
|
||||
attempt("NOT NULL violation", () -> db.exec("INSERT INTO t(id) VALUES (1)"));
|
||||
db.exec("INSERT INTO t VALUES (1, 'a')");
|
||||
attempt("PRIMARY KEY violation", () -> db.exec("INSERT INTO t VALUES (1, 'b')"));
|
||||
System.out.println("SQLITE_CONSTRAINT = " + SQLITE_CONSTRAINT() + ", sqlite3_errstr(19) = " + sqlite3_errstr(19).getString(0));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package demo;
|
||||
|
||||
import static demo.sqlite.sqlite3_h.*;
|
||||
|
||||
import java.lang.foreign.MemorySegment;
|
||||
|
||||
/** The smallest useful call: ask the native library which version it is. */
|
||||
public class Hello {
|
||||
public static void main(String[] args) {
|
||||
MemorySegment v = sqlite3_libversion(); // const char* -> MemorySegment
|
||||
System.out.println("sqlite3_libversion() = " + v.getString(0));
|
||||
System.out.println("returned segment byteSize = " + v.byteSize());
|
||||
System.out.println("sqlite3_libversion_number() = " + sqlite3_libversion_number());
|
||||
System.out.println("sqlite3_sourceid() = " + sqlite3_sourceid().getString(0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package demo;
|
||||
|
||||
import static demo.sqlite.sqlite3_h.*;
|
||||
|
||||
import java.lang.foreign.Arena;
|
||||
import java.lang.foreign.MemorySegment;
|
||||
|
||||
/** What sqlite3_column_text returns for a SQL NULL, and what happens if you call getString(0) on it anyway. */
|
||||
public class NullText {
|
||||
public static void main(String[] args) {
|
||||
try (Db db = Db.open(":memory:"); Arena arena = Arena.ofConfined()) {
|
||||
db.exec("CREATE TABLE t(a TEXT)");
|
||||
db.exec("INSERT INTO t VALUES (NULL)");
|
||||
try (Db.Stmt st = db.prepare(arena, "SELECT a FROM t")) {
|
||||
st.step();
|
||||
MemorySegment p = sqlite3_column_text(st.ptr(), 0);
|
||||
System.out.println("address=" + p.address() + " byteSize=" + p.byteSize() + " equals(NULL)=" + p.equals(MemorySegment.NULL));
|
||||
System.out.println("about to call getString(0) on it");
|
||||
System.out.flush();
|
||||
try {
|
||||
System.out.println("getString -> " + p.getString(0));
|
||||
} catch (Throwable t) {
|
||||
System.out.println("getString -> " + t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package demo;
|
||||
|
||||
/** A SQLite result code turned into an exception: the numeric code plus the text from sqlite3_errmsg. */
|
||||
public final class SqliteException extends RuntimeException {
|
||||
private final int code;
|
||||
|
||||
public SqliteException(int code, String message) {
|
||||
super(message + " (rc=" + code + ")");
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public int code() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package demo;
|
||||
|
||||
import java.lang.foreign.Arena;
|
||||
|
||||
/** Open a database, create a table, insert with bind parameters, read it back. */
|
||||
public class Tour {
|
||||
public static void main(String[] args) {
|
||||
try (Db db = Db.open(":memory:")) {
|
||||
db.exec("CREATE TABLE person(id INTEGER PRIMARY KEY, name TEXT NOT NULL, age INTEGER)");
|
||||
try (Arena arena = Arena.ofConfined(); Db.Stmt ins = db.prepare(arena, "INSERT INTO person(name, age) VALUES (?1, ?2)")) {
|
||||
String[] names = {"Ankur", "Asha", "Ravi"};
|
||||
int[] ages = {41, 36, 29};
|
||||
for (int i = 0; i < names.length; i++) {
|
||||
ins.bindText(arena, 1, names[i]);
|
||||
ins.bindInt(2, ages[i]);
|
||||
ins.step();
|
||||
ins.reset();
|
||||
}
|
||||
}
|
||||
System.out.println("rows changed by last statement: " + db.changes() + ", last rowid: " + db.lastInsertRowid());
|
||||
for (var row : db.query("SELECT id, name, age FROM person ORDER BY id")) {
|
||||
System.out.println(row);
|
||||
}
|
||||
db.exec("INSERT INTO person(name) VALUES ('NoAge')");
|
||||
System.out.println(db.query("SELECT name, age FROM person WHERE age IS NULL"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package demo;
|
||||
|
||||
import static demo.sqlite.sqlite3_h.*;
|
||||
|
||||
import java.lang.foreign.Arena;
|
||||
import java.lang.foreign.MemorySegment;
|
||||
import java.lang.foreign.ValueLayout;
|
||||
|
||||
/**
|
||||
* The trap that costs the first hour: a pointer you read out of memory is a zero-length segment
|
||||
* unless its layout says what it points at. jextract's C_POINTER says "unbounded chars"; plain ADDRESS does not.
|
||||
*/
|
||||
public class Trap {
|
||||
public static void main(String[] args) {
|
||||
try (Arena arena = Arena.ofConfined()) {
|
||||
MemorySegment slot = arena.allocate(ValueLayout.ADDRESS);
|
||||
slot.set(ValueLayout.ADDRESS, 0, arena.allocateFrom("hello from C land"));
|
||||
|
||||
MemorySegment viaAddress = slot.get(ValueLayout.ADDRESS, 0);
|
||||
System.out.println("ValueLayout.ADDRESS : byteSize=" + viaAddress.byteSize());
|
||||
try {
|
||||
viaAddress.getString(0);
|
||||
} catch (IndexOutOfBoundsException e) {
|
||||
System.out.println("getString(0) : IndexOutOfBoundsException, \"" + e.getMessage().substring(0, e.getMessage().indexOf(':', 22)) + "...\"");
|
||||
}
|
||||
System.out.println("reinterpret(100) : " + viaAddress.reinterpret(100).getString(0));
|
||||
|
||||
MemorySegment viaCPointer = slot.get(C_POINTER, 0);
|
||||
System.out.println("C_POINTER : byteSize=" + viaCPointer.byteSize());
|
||||
System.out.println("getString(0) : " + viaCPointer.getString(0));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// Used only by scripts/run-all.sh to test library loading with throwaway bindings (package demo.sqlite, one function).
|
||||
import static demo.sqlite.sqlite3_h.*;
|
||||
|
||||
public class V {
|
||||
public static void main(String[] a) {
|
||||
System.out.println("sqlite3_libversion() = " + sqlite3_libversion().getString(0));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user