Skip to content

API overview

Only the types you are expected to use directly are listed. Anything in an internal package is implementation detail and may change.

quackjvm-core

io.quackjvm.core.Quack - the entry point

A DuckDB database and everything quackjvm does with it, behind one object that owns the connections, so the code using it never holds one. Thread-safe. Each call borrows a pooled connection and gives it back, on failure as well as success. Helpers that keep a connection for life (the catalog, the guard, vector search) get sharedConnection(), which borrows per statement: a DuckDB connection runs one query at a time, and a quick query behind a slow one on a shared connection waited 1,136 ms, against 0 ms on its own (CoreConnectionFacts).

method notes
static Quack open(path), inMemory() A file, created if absent; or memory only.
static Builder builder(path) .settings(properties), .history(location), .metrics(quackMetrics), .connections(idle), .readOnly(true), then .open(). DuckDB settings are applied and the history attached once, at open. A null path is in memory.
DatabaseInUse Thrown by open when another process holds the file: getPath(), holderPid(). DuckDB lets one process write a file or any number read it (readOnly(true)), never both. Every other failure to open is a plain IllegalStateException.
static Quack on(DuckDBConnection) A database the program already has open. Works on connections duplicated from the one given, and never uses or closes that one.
Rows query(sql, params...), Rows query(MeasureQuery) Run at the terminal method; each borrows a connection for that.
int execute(sql, params...) A statement that changes something; rows changed.
createTable(name, layout), long write(name, layout, objects) A table with a column per field, keyed on the first; objects written in one transaction, replacing any under the same key.
create(MeasureTable...), create(SparseTable) Their tables, the refresh ledger, and their history tables if there is a history. Safe to call again.
boolean commit(MeasureRefresh) In a transaction of its own; false if the id was committed before.
MeasureHistory history(), MeasureQuery asOf(measure, at) The history given at open (refuses if none); a measure query as of a point, to pass to query.
Shipped ship(measures...), Exported export(measure, location) Run their own transactions against the live database and the history.
T register(root -> ...) Something registered on the database itself, such as a function or a table function, seen on every connection. One at a time; an AutoCloseable result is closed with the database.
void inTransaction(Tx.Work), T fromTransaction(Tx.Result<T>) One connection; committed when the work returns, rolled back when it throws. Not retried on a conflict.
Connection sharedConnection() Borrows a pooled connection for each statement and gives it back: for a helper that keeps a connection for life. Safe across threads; holds no transaction; closing it does nothing.
Connection connection() The way down: a pooled connection of the caller's own until closed; closing gives it back with anything uncommitted rolled back.

io.quackjvm.core.Tx

One transaction, used by the thread that opened it and only until the work returns: query, execute, write, createTable, commit(MeasureRefresh), create, inTransaction (more work in the same transaction - DuckDB has no savepoints) and connection() (closing it does nothing; committing, rolling back or turning auto-commit on is refused). It has no ship, export, compact or prune: those run transactions of their own against two databases, and DuckDB writes to only one attached database per transaction.

Every class below keeps its connection-taking methods. They are the lower level: for code with a pool of its own, the CQEngine plugin, and tests.

io.quackjvm.core.layout.ColumnarLayout<O>

How to shred an object into one typed DuckDB column per field, and how to rebuild it from a row.

method notes
static <R> ColumnarLayout<R> ofRecord(Class<R>) Columns from the record's components; objects rebuilt through the canonical constructor.
static <O> ColumnarLayout<O> reflective(Class<O>) Columns from every non-static, non-transient instance field. Objects are allocated without a constructor and the fields written reflectively. Records are delegated to ofRecord.
static <O> Builder<O> builder(Class<O>) Explicit columns: .column(name, type, accessor) repeatedly, then .rowFactory(values -> ...) and .build(). A row factory is mandatory.
List<Column<O, ?>> getColumns() Each Column has getName(), getType() and getValue(object).
O createObject(Object[] values) Rebuilds an object from column values in column order.

Every column type must be one DuckDB understands; an unsupported type is rejected when the layout is built, not at the first insert.

io.quackjvm.core.duckdb.DuckDBTypes

The Java-to-DuckDB type mapping, and the conversions either way.

  • sqlTypeFor(Class) / isSupported(Class) - the column type for a Java type.
  • toSqlValue(Object), bind(PreparedStatement, index, value), append(DuckDBAppender, value, javaType).
  • readerFor(Class) / read(ResultSet, index, Class).

Supported: the primitive wrappers, String, Character, BigInteger, BigDecimal (scale 10), UUID, byte[], enums, java.util.Date, the java.sql date and time types, and LocalDate, LocalTime, LocalDateTime, Instant, OffsetDateTime.

Two conversions worth knowing: enums are stored as ordinal() in an INTEGER column, which preserves Java's natural ordering for them but makes stored data sensitive to the declaration order of the constants; and all date and time values are normalised to java.time types so that a value written through a prepared statement and the same value written through the Appender are identical in the database.

io.quackjvm.core.duckdb.ColumnDef

One column: new ColumnDef(name, javaType), then getName(), getJavaType(), getSqlType(), toDdl(). The SQL type is derived from the Java type at construction, so an unsupported type fails here.

io.quackjvm.core.duckdb.TableWriter

Writes rows into a table, choosing its strategy by batch size: batches at or below DEFAULT_APPENDER_THRESHOLD (16) go through a JDBC batch of prepared inserts; larger ones are streamed through a per-connection temporary staging table using DuckDB's Appender, in chunks of DEFAULT_STAGING_CHUNK_ROWS (131,072) so that memory stays bounded.

new TableWriter(tableName, columns, orReplace, appenderThreshold [, stagingChunkRows])

The table's first column is treated as the key column.

method notes
createTable(Connection, boolean primaryKeyOnKeyColumn) CREATE TABLE IF NOT EXISTS.
WriteResult write(Connection, Iterator<Object[]> rows, boolean deleteExistingKeys) Rows are column values in column order. WriteResult has public rowsWritten and rowsReplaced.
AppenderHandle openAppender(Connection) A long-lived appender for streaming inserts: appendRow(Object[]), flush(), close(). Constraint violations surface at flush time.
count, clear, dropTable, tableExists, deleteKeys(Connection, Iterable<?>)
validateSchema(Connection) Checks an existing table's columns against this writer's, with a message naming both.

Gotcha. orReplace and primaryKeyOnKeyColumn have to agree: INSERT OR REPLACE needs a unique or primary key to conflict on, so orReplace = true over a table created without one fails at the first write with a binder error from DuckDB.

io.quackjvm.core.sql.SqlQuery / SqlRow / JoinPair

static Stream<SqlRow> SqlQuery.stream(Connection connection, String sql, Object... parameters)

The stream takes ownership of the connection and closes it, the statement and the result set when the stream is closed. Give it a connection you are willing to lose - for a DuckDB in-memory database, ((DuckDBConnection) root).duplicate() yields another connection to the same database.

SqlRow addresses columns by name or by 1-based position: get, getString, getLong, getDouble, getColumnNames, toArray. One SqlRow is reused for every row of a result, as a view over the cursor, so a row kept beyond the iteration must be copied with toArray().

JoinPair<L, R> is a record of left() and right().

io.quackjvm.core.sql.Rows

Typed results without writing a ResultSet loop. Rows.of(connection, sql, parameters...) builds one; nothing runs until you ask for a shape, and the shape decides how the result is read.

method notes
<T> T scalar(Class<T>) One value from one row. Throws if the query returns no row.
<T> Optional<T> scalarOptional(Class<T>) The same, when no row is a legitimate answer.
<T> List<T> list(Class<T>) The first column of every row.
<T> void forEachValue(Class<T>, Consumer<T>) The streaming form of list.
<T> List<T> records(Class<T>) A record per row; components are matched to the selected columns by position, not by name.
<T> void forEachRecord(Class<T>, Consumer<T>) The streaming form of records.
long count() Wraps the query in a count(*) rather than reading and discarding rows.
void forEachRow(Consumer<SqlRow>) Raw rows, for a dynamic shape such as a PIVOT.
Stream<SqlRow> stream() Holds a connection; must be closed.
Rows timeout(Duration) Cancels the query if it is still running, or still being read, after this long, and throws QueryTimedOut. The connection is usable afterwards. Returns a copy.

Every method except stream() closes the connection, statement and result set itself.

It reads. A statement that returns no rows - DROP, COPY ... TO, ATTACH, SET - is refused before it runs, with an IllegalStateException starting "Not run:"; so is more than one statement, because DuckDB's driver runs all but the last while preparing them. Run those with execute. Anything that returns rows runs, INSERT ... RETURNING included: this guards against mistakes in your own SQL. For SQL you did not write, use GuardedQuery in quackjvm-agent.

scalar and scalarOptional deliberately read through JDBC: setting up a columnar export costs more than reading one value. list, records and the forEach forms use Arrow when it is available. This is decided per call, not configured.

Rows takes ownership of the connection it is given, as SqlQuery does — pass a duplicate(). DuckDBDatabase.query(...) handles that for you and is the usual way in.

io.quackjvm.core.page.Pages / Page / PageKey

A query read a page at a time, found from the row next to it rather than counted from the start.

Pages pages = Pages.of(quack, "SELECT * FROM message WHERE session = ?", id).orderBy("ts", "id").size(50);
Page page = pages.last();   pages.before(page.firstKey());   pages.after(page.lastKey());
pages.around(PageKey.of(ts, id), 25);   pages.count();   pages.position(key);   pages.at(position);
page.rows();   page.as(layout);   page.hasBefore();   page.hasAfter();

See Paging and journals.

io.quackjvm.core.journal.Journal<O>

An application's own records, appended, updated while they stream in, paged, searched and deleted.

Journal<Message> j = Journal.builder(quack, "message", ColumnarLayout.ofRecord(Message.class))
        .index("session", "ts").searchable("text").migrate(2, "ALTER TABLE message ADD COLUMN cost DOUBLE").open();
j.append(m);   j.update(id, Map.of("text", soFar));   j.get(id);   j.search("connection refused", 20);
j.pages("session = ?", id).orderBy("ts", "id");   j.version();
j.delete(id);   j.deleteWhere("session = ?", id);
// keys of several columns, numbered in a group: .keyColumns("chat", "seq").sequence("seq").within("chat")
j.appendAndGet(m).seq();   j.get(PageKey.of(chat, seq));

See Paging and journals.

io.quackjvm.core.duckdb.NestedType

Columns that hold more than one value. Usually you never name this: a record's own types are enough.

record Doc(Integer id, List<String> tags, Map<String, Integer> counts, Owner owner, float[] embedding) {}
ColumnarLayout.ofRecord(Doc.class);       // VARCHAR[], MAP(VARCHAR, INTEGER), STRUCT(...), FLOAT[]

ColumnarLayout.builder(Doc.class)
        .listColumn("tags", String.class, Doc::tags)
        .vectorColumn("embedding", 768, Doc::embedding)    // FLOAT[768]
  • Written through the appender - no Arrow, no extra dependency - and read back by Rows.records.
  • One level of nesting; a list of structs is refused when the layout is built.
  • FLOAT[768] at 20,000 rows a second, 59 MB/s (DuckDB 2.0; 85 MB/s on 1.5).

See Nested types.

io.quackjvm.core.arrow.ArrowSupport

Whether the Arrow read path is usable, and why not if it is not.

  • boolean isAvailable() — Arrow classes on the classpath and the JVM flag set.
  • String getUnavailableReason() — which of those is missing.
  • String getRequiredJvmFlag() — --add-opens=java.base/java.nio=ALL-UNNAMED.

Arrow is optional: with org.apache.arrow:arrow-vector, arrow-c-data and arrow-memory-unsafe present, reads go through columnar batches (about 10x faster on wide results); without them everything falls back to JDBC rows automatically.

ArrowResult.of(PreparedStatement, batchSize) and ArrowObjectReader<O> are the lower-level entry points, for reading batches or rebuilding objects from them directly.

io.quackjvm.core.duckdb.ConnectionPool and Connections

ConnectionPool(DuckDBConnection root, int maxIdle) hands out connections duplicated from one root connection: borrow(), release(Connection), close(). Connections.duckDB(Connection) unwraps a DuckDBConnection from a pooled or proxied connection; Connections.managed(...) wraps one so that close() returns it to a pool.

quackjvm-agent

For SQL and data the application does not write itself - an AI agent, a user, another service. Depends only on quackjvm-core. Each helper takes a Quack as well as a connection: the guard, the catalog and vector search borrow a connection per query through quack.sharedConnection(), and what is registered on the database - a live table, a Java function - goes through quack.register(root -> ...), which closes it with the database.

io.quackjvm.agent.guard.GuardedQuery / QueryPolicy / Hardening

Runs SQL that came from somewhere you do not control.

GuardedQuery guard = GuardedQuery.on(quack, QueryPolicy.readOnly()      // or on(connection, ...)
        .timeout(Duration.ofSeconds(2))
        .maxRows(50));

GuardedResult result = guard.run(sql);   // QueryRejected (QueryFailed if DuckDB could not run it) / QueryTimedOut / ResultTruncated
String why = guard.whyRejected(sql);     // null when it would be allowed
guard.run(sql, cancelSignal);            // QueryCancelled once cancelSignal.cancel() is called
guard.run(sql, CancelSignal.from(stop::get));   // or once a flag you have turns true, polled every 50 ms
guard.store(sql, "db", "table", signal);         // the whole result into a new table; returns its row count
  • QueryPolicy.readOnly() - five seconds, ten thousand rows, eight megabytes, EXPLAIN allowed; timeout, maxRows, maxBytes, allowExplain, allowUnverified(PIVOT), hardening and whenOver(Over.REFUSE | Over.TRUNCATE) return copies. Under TRUNCATE the rows that fit come back and GuardedResult.isTruncated() says there were more.
  • The statement is checked by DuckDB's parser (json_serialize_sql), never by preparing it - with this driver, preparing a multi-statement string executes all but the last.
  • Hardening.DATABASE takes file, extension and network access away from the whole database, irreversibly; Hardening.apply(quack) does it to a Quack's. Hardening.openSandbox() opens a separate Quack that starts that way, and Hardening.sandbox() a bare connection to one.
  • Hardening.options().allowedFolders(...).tempFolder(...).memoryLimit(...).threads(...) locks a database down except for the folders named: .properties() to open it that way, Hardening.apply(quack, options) once open. An allowed folder can be written as well as read, and so can the temp folder, which must hold nothing but DuckDB's own files. .allowedFiles(...) lets in single files (DuckDB's allowed_paths), as a session does for a file table's cache.
  • GuardedResult carries columns, SQL types, rows, elapsed time, an estimated byte count, and toText() for something that reads text.

See Guarding queries.

io.quackjvm.agent.catalog.Catalog

What is in the database, and what it means.

Catalog catalog = Catalog.of(connection);

List<TableInfo> tables = catalog.tables();
TableInfo car = catalog.describe("car", layout);   // layout optional: fills in Java types
Profile profile = catalog.profile("car", 5);       // SUMMARIZE + row count + 5 rows

catalog.describeColumn("car", "price", "what it sold for", "USD");
catalog.apply("car", layout);                      // writes everything the layout says
  • TableInfo / ColumnInfo / Profile / ColumnProfile are records, each with toText().
  • Descriptions and units are stored as DuckDB comments - COMMENT ON - not in a registry of ours.
  • describe reads metadata only: 2 ms whatever the table holds. profile is a full scan: 279 ms at ten million rows.

catalog.examples(table) writes ready-made queries from a table's columns. Each QueryExamples.Example has a title and SQL, covering a count, a summary, a range and percentiles, counts by a group column, rows over time, a search, families of numbered columns with COLUMNS('^cpu_[0-9]+$'), examples for logs, and joins to tables that share a column. catalog.examples(table, profile.distinctValues()) chooses a group column with few values.

See Catalog.

io.quackjvm.agent.session.QuerySession

Named tables in one hardened, in-memory database, added and dropped at runtime.

QuerySession session = QuerySession.open(Hardening.options().tempFolder(temp), QueryPolicy.readOnly());
String name = session.register(Path.of("/data/readings-2026.csv"));   // "readings_2026"; lets its folder in
session.register("recent", "SELECT * FROM readings_2026 WHERE id > 100");
session.register("note", () -> notes, ColumnarLayout.ofRecord(Note.class));   // live objects
session.register("app_log", fileTable);              // a FileTable, its cache attached; joins the others
session.alias("t", name);
session.run(sql, CancelSignal.from(stop::get));      // or run(sql), or run(sql, signal, policy)
session.allowFolders(List.of(folder));               // reopens if needed, keeping every table
session.names(); session.aliases(); session.examples("t"); session.profile("t"); session.unregister("recent");
ResultWindow w = session.window(sql, signal);    // the whole result, read with w.rows(first, n); w.sort(column, asc)
QuerySession.tableName(Path.of("Readings 2026-Q4.tsv"), taken);   // "readings_2026_q4"

See Query sessions.

io.quackjvm.agent.file.FileTable / FileTables / RowSource / RowParser / LineSource

A big file and the application's parser turned into a table, kept on disk and up to date as the file grows.

FileTable t = FileTables.builder(path, columns, LineSource.of(path), parser)
        .cacheDir(dir).roomLimit(5L << 30).version("viewer-3").threads(8).blockSize(8192)
        .lazyColumns(true).maxNewColumnsPerQuery(64).inMemoryBelow(100L << 20)
        .function("label_time", String.class, Long.class, Integer.class, (ms, g) -> label(ms, g)).open();
t.update(signal, progress);          // appends what was written since; reloads a replaced file
t.query(sql, policy, signal);        // stores the columns it reads first, when they are lazy
t.whyNot(sql);   t.rowsLoaded();   t.storedColumns();   t.close();
t.function("label_time", String.class, Long.class, Integer.class, fn);   // adds or replaces one
FileTables.size(dir);   FileTables.clear(dir, keep);   FileTables.trim(dir, limit);

See File tables.

io.quackjvm.agent.catalog.QueryColumns

Which columns of which tables a query reads, without running it - for filling a lazy column cache with just what a query needs.

try (QueryColumns planner = QueryColumns.of(quack)) {          // or of(connection)
    QueryColumns.Read read = planner.read(sql, parameters...);
    read.isKnown() ? read.columns() : read.reason();            // {t=[metric_9, host, metric_7]}
}
  • Planned in a database of its own, in memory, with no file access, holding empty copies of the source's tables and views; refresh() copies them again. The query is never run.
  • A table counted but not read (count(*)) maps to an empty set. A query it cannot answer - more than one statement, a PIVOT, a file, a table outside main - says why: assume every column.
  • 6,000 columns: the planner is made in 82 ms, a three-column query answered in 3 ms, SELECT * in 158 ms.

See Catalog.

io.quackjvm.agent.live.LiveTables / LiveTable

Java objects queried as a table, with no load step.

LiveTable table = LiveTables.register(connection, "car", cars, ColumnarLayout.ofRecord(Car.class));
LiveTables.snapshot(connection, "car", cars, layout);          // a copy, for one consistent state
LiveTables.register(connection, "car", () -> cache.rows(), layout);   // whatever is current
table.unregister();
  • A DuckDB table function plus a view, so SQL says car. Projection pushdown is on; the scan is single-threaded.
  • UUID, byte[] and LocalTime are refused at registration - DuckDB's Java chunk writer cannot write them in 1.5.5 or 2.0.
  • 1,000,000 objects: join to 200,000 stored rows in 44.6 ms, against 784 ms to load them first.

See Live tables.

io.quackjvm.agent.udf.Udfs

A Java method called from SQL.

Udfs.register(connection, "region_of", String.class, String.class, Countries::regionOf);
Udfs.register(connection, "with_tax", Double.class, Double.class, Double.class, (p, r) -> p * (1 + r));
Udfs.registerNullable(connection, "or_unknown", String.class, String.class, t -> t == null ? "?" : t);
Udfs.registerDouble(connection, "vat", (double price) -> price * 1.2);   // no boxing
  • One, two or three arguments. register answers a null argument with a null result without calling the method; registerNullable passes nulls through.
  • UUID, byte[] and LocalTime are refused at registration - DuckDB's Java vectors cannot carry them in 1.5.5 or 2.0.
  • 2,000,000 rows of price * 1.2: 0.7 ns a row in SQL, 8.8 ns unboxed, 8.4 ns boxed (DuckDB 2.0).

See Java functions in SQL.

io.quackjvm.agent.vector.VectorSearch

The rows whose vector is nearest a given one.

VectorSearch search = VectorSearch.on(connection, "note", "embedding").identifiedBy("id");
List<VectorSearch.Match> nearest = search.topK(query, 10, "topic = ?", "weather");
String sql = search.sql(query, 10, null);
String whyNoIndex = search.createIndex();     // null when an HNSW index was created
  • Metric.COSINE (default), EUCLIDEAN or INNER_PRODUCT, all built in - no extension, no network.
  • The column must be a fixed-size array; a FLOAT[] is refused, pointing at vectorColumn.
  • Exact top-10: 19.0 ms over 10,000 x 768, 101.8 ms over 100,000 x 768, 35.3 ms over 1,000,000 x 128.

See Vector similarity.

quackjvm-cqengine

io.quackjvm.cqengine.persistence.DuckDBPersistence<O, A>

A CQEngine Persistence, and the entry point for a single collection.

Factory methods, all taking the primary key SimpleAttribute first:

method storage
onPrimaryKey(pk) / onPrimaryKeyInMemory(pk) in memory (native memory, not the Java heap)
onPrimaryKeyInFile(pk, File) a DuckDB file
onPrimaryKeyInTempFile(pk) a temporary file, reported by getFile()
onPrimaryKeyInFileWithProperties(pk, File, Properties) a file, with extra DuckDB settings
builder(pk) everything below

Builder options: database(DuckDBDatabase), collectionName(String), file(File), tempFile(), inMemory(), columnarLayout(ColumnarLayout<O>), objectCacheSize(int), appenderThreshold(int), stagingChunkRows(int), memoryLimit(String), serializeWrites(boolean), maxPooledConnections(int), property(name, value), properties(Properties), build().

Without a columnarLayout each object is serialized into a single BLOB, which needs no mapping code but hides the object's fields from SQL and from joins. With one, each field is a real typed column, which compresses far better and is what sql(...), join(...) and pushed-down existsIn need.

Other methods worth knowing:

method notes
DuckDBBulkWriter<O> bulkWriter() see below
long getBytesUsed() the size of the whole database - shared, if several collections share it
File getFile() null for an in-memory database
void optimize() rewrites each index table ordered by value so DuckDB can skip blocks. Worth calling after a bulk load; it is not cheap
void analyze() DuckDB's ANALYZE
void compact() checkpoints and reclaims space
void expand(long) a no-op, present only so code written against CQEngine's SQLite persistence still compiles
void close() closes the database if this persistence created it

Concurrency. One DuckDB database is opened and each CQEngine request borrows a connection from a pool. Reads run concurrently under DuckDB's MVCC. Writes are serialised against each other by default, because two DuckDB transactions modifying one table concurrently make one of them fail; serializeWrites(false) turns that off for applications which coordinate their own writes.

io.quackjvm.cqengine.persistence.DuckDBIndexedCollection<O, A>

new DuckDBIndexedCollection<>(persistence) - an ordinary ConcurrentIndexedCollection except that it translates a whole query, including existsIn nested inside it, into one SQL statement rather than letting CQEngine intersect the branches in Java. Anything it cannot translate is handed back to CQEngine unchanged, so results never depend on the push-down.

io.quackjvm.cqengine.persistence.DuckDBDatabase

One DuckDB database shared by any number of collections, which is what makes joins possible.

  • inMemory(), inFile(File), or builder() with file, memoryLimit, property, properties, serializeWrites, maxPooledConnections.
  • collection(pkAttribute) returns a CollectionBuilder with name(String), columnarLayout(...), objectCacheSize(int), appenderThreshold(int), stagingChunkRows(int), and then either build() (a registered DuckDBIndexedCollection) or buildPersistence() (the persistence alone, for your own IndexedCollection). Give two collections of the same type different names; the default name is the object type's simple name in lower case.
  • <L, R> Join<L, R> join(left, right) - see below.
  • Rows query(String, Object...) - arbitrary SQL over the collections, returned as typed values. The usual way in; see Rows above and Aggregates.
  • Stream<SqlRow> sql(String, Object...) - the same SQL as a raw row stream. The stream holds a connection and must be closed.
  • String table(collection), String column(collection, attribute), List<String> columns(collection)
  • the names to use in sql(...), checked rather than guessed.
  • String describe() - every collection, its SQL name and its columns. Print it when writing a query.
  • register(collection, persistence) - only needed for a collection built outside collection(...).
  • getBytesUsed(), getFile(), isClosed(), compact(), optimize(), close().

Each collection is stored in a table named cq_<name>, with a view named <name> over it, which is what sql(...) and table(...) use. Indexes live in cqidx_<name>_<attribute>.

io.quackjvm.cqengine.query.Join<L, R>

From database.join(left, right):

on(leftAttribute, rightAttribute), whereLeft(Query<L>), whereRight(Query<R>), then either Stream<JoinPair<L, R>> stream() or long count(). The stream holds a connection and must be closed; count() answers without materialising any objects. An object whose join attribute holds several values appears once per match, as in SQL.

io.quackjvm.cqengine.index.DuckDBIndex

An index stored in DuckDB as a two-column (objectKey, value) table - the DuckDB counterpart of CQEngine's DiskIndex.

  • DuckDBIndex.onAttribute(attribute) - the usual choice.
  • DuckDBIndex.onAttributeWithArtIndex(attribute) - additionally builds DuckDB ART indexes over the columns. Faster lookups into a very large index table, at several times the disk and memory; worth it only where lookups are both frequent and latency-critical.
  • DuckDBIndex.onAttributeWithSuffix(attribute, tableNameSuffix, artIndexes) - when two indexes on the same attribute must coexist in one file.

Supports equal, between, greaterThan, lessThan, in, has, stringStartsWith and existsIn. Enum attributes index normally here; CQEngine's own SQLite indexes reject them.

The index is created and populated when it is added to the collection, and reused as it stands if the database already contains it.

io.quackjvm.cqengine.persistence.DuckDBBulkWriter<O>

From persistence.bulkWriter(). Keeps one DuckDB Appender open per table:

try (DuckDBBulkWriter<Event> writer = persistence.bulkWriter()) {
    while (records.hasNext()) {
        writer.add(toEvent(records.next()));
    }
}   // flushed and closed here

add(O), addAll(Iterable<? extends O>), flush(), getObjectsWritten(), close().

What it asks of you:

  • The objects must be new. Rows are appended, not merged, so a primary key which is already stored fails at the next flush. Use IndexedCollection.update to replace existing objects.
  • The collection is inconsistent until a flush. Each table flushes independently, so a query running during a session can see an object which is not yet in every index.
  • Add your indexes first. The writer appends to the index tables which exist when it opens.
  • One thread. A writer is not thread-safe and holds the write lock for its lifetime, so other writers wait. Readers are never blocked.

io.quackjvm.cqengine.DuckDBFlags

BULK_IMPORT tells a bulk write that every object is new, so the delete-before-insert which makes addAll idempotent can be skipped. It has the same flag value as CQEngine's SQLiteIndexFlags.BULK_IMPORT, so existing code using that flag already gets this behaviour.

QueryOptions options = new QueryOptions();
FlagsEnabled.forQueryOptions(options).add(DuckDBFlags.BULK_IMPORT);
collection.update(Collections.emptyList(), manyObjects, options);

DuckDBFlags.isBulkImport(QueryOptions) reports whether it is set.

If a primary key is in fact already present the write fails on the primary key constraint rather than replacing silently: the flag is an assertion, not a hint.

io.quackjvm.cqengine.serialization.KryoPojoSerializer

The default serializer for BLOB storage, used when no ColumnarLayout is given and the object type's @PersistenceConfig does not name a PojoSerializer of its own.