Skip to content
jolt-langPublic

About

Database wrapper for Postgres and SQLite

Resources

Stars

4 stars

Watchers

0 watching

Forks

Latest commit

 

History

101 Commits

Folders and files

Repository files navigation

jdbc.core for jolt

A SQLite and PostgreSQL database library for jolt (Clojure on Chez Scheme). It binds the system libsqlite3 and libpq directly through jolt.ffi — jolt's foreign-function interface — and runs the real clojure.jdbc on top of them, plus a small next.jdbc surface. No jolt built-in, no JVM: the native binding lives here, and the API is the published library rather than a copy of it.

jdbc.core is clojure.jdbc itself. This library supplies the java.sql surface it drives (db.jdbc-shim) over the native drivers, so its own documentation and semantics apply as written.

(require '[db.jdbc])                                       ; registers the shim, once
(require '[jdbc.core :as jdbc])
(with-open [conn (jdbc/connection "sqlite::memory:")]      ; or "postgres://user:pw@host/db"
  (jdbc/execute! conn "create table p (id integer primary key, name text)")
  (jdbc/insert! conn :p {:name "ada"})                     ; -> (1), one result per row
  (jdbc/fetch conn ["select * from p where name = ?" "ada"]))

Require db.jdbc once before jdbc.core, and before anything else that pulls it in. It has to be loaded first because clojure.jdbc's namespaces resolve the java.sql constants as they compile, and it is what points connection construction at the native drivers instead of DriverManager.

fetch/fetch-one, execute!, insert!/insert-multi!/update!/delete!, prepared-statement, and atomic (transactions with nested savepoints) are supported on both backends. Queries are strings or sqlvecs ([sql & params], JDBC ? placeholders — rewritten to $N for postgres).

Generated keys depend on the driver. SQLite and PostgreSQL come back through RETURNING, since neither has a JDBC generated-keys channel. {:returning true} (or :all) asks for the whole row, which is what postgres' own driver gives; a sequence of column names asks for those. Without it there are no generated keys to report, so insert! falls back to the update count, exactly as clojure.jdbc does on a driver that has none. A driver registered with :returning? false (MySQL, say) can report an :insert-id instead, and its generated keys answer {:GENERATED_KEY n}, Connector/J's name, holding the first id of a multi-row INSERT.

insert! with {:returning [:id]} answers ({:id 1}). next.jdbc's execute! and execute-one! honour :return-keys: a RETURNING driver answers the row (RETURNING *, or the names when it is a vector), and any other driver answers {:GENERATED_KEY n} when the statement made an id. next.jdbc.sql/insert! asks for keys unless told otherwise, so it answers the generated keys map, the whole inserted row on SQLite and PostgreSQL, as next.jdbc does; {:return-keys false} gives {:next.jdbc/update-count 1} instead.

next.jdbc.sql has upstream's full surface: query, insert!, insert-multi!, update!, delete!, find-by-keys, aggregate-by-keys and get-by-id, with the builders in next.jdbc.sql.builder. Each takes a connection, a datasource or a db-spec, and the upstream options: :columns (including [col alias] and ["expr" alias]), :order-by, :suffix, :table-fn / :column-fn, :batch, and the pagination options :top, :limit, :offset and :fetch. Upstream writes those in SQL Server, MySQL or ANSI syntax; here they all become LIMIT/OFFSET, which both SQLite and PostgreSQL accept, so any of them works on either backend. Only one of :top, :limit and :fetch can be given at a time.

Batches compile their statement once. next.jdbc/execute-batch! and JDBC PreparedStatement.executeBatch bind each parameter group to one prepared statement; on PostgreSQL with libpq 14 or newer the executions are pipelined, so a batch costs one round trip per 500 groups instead of one per row (older libpq still prepares once, but waits on each row). Outside a transaction a batch runs in one of its own, so it lands whole or not at all; inside one it joins it. insert-multi! with :batch writes multi-row INSERTs sized to the parameter limit and runs them as one such batch.

Migratus

migratus runs on the next.jdbc surface here, but two of its dependencies have to be replaced. Its next.jdbc would shadow this library's, so exclude it, and clojure.tools.logging from Maven fails at load with "Valid logging implementation could not be found", so override it with jolt-lang/logging, which provides the same namespace:

{:deps {io.github.jolt-lang/db {:git/url "https://github.com/jolt-lang/db" :git/sha "..."}
        migratus/migratus {:git/url "https://github.com/yogthos/migratus"
                           :git/sha "fbc7e90d48b7b11bf83c498883fa5e7fcde3720d" ; 1.6.9
                           :exclusions [com.github.seancorfield/next.jdbc]}
        org.clojure/tools.logging {:git/url "https://github.com/jolt-lang/logging"
                                   :git/tag "v0.0.2" :git/sha "ec6747e55583118d881faf4ab41e68d7e587ce4c"}}}

Pass migratus a :connection-uri such as "jdbc:sqlite:app.db" or a postgres:// uri.

Binary values

A byte array parameter binds as a SQLite blob / postgres bytea, and those columns read back as byte arrays. The bytes round-trip exactly, so embedded NULs, non-UTF-8 bytes, and empty payloads all survive.

(jdbc/execute! conn "create table doc (id integer primary key, body blob)")
(jdbc/insert! conn :doc {:body (byte-array [0 255 65])})
(:body (jdbc/fetch-one conn "select body from doc"))   ; -> byte array

On postgres a byte array is sent in binary with its type given as bytea, so it does not depend on the statement offering a bytea column for the server to infer one from. ["select ? as c" (byte-array [1 2])] binds a bytea and reads back as bytes rather than inferring text.

next.jdbc surface

The next.jdbc namespace carries the upstream calling conventions over the same drivers: get-datasource / get-connection, execute! / execute-one! (rows for a result set, {:next.jdbc/update-count n} otherwise), plan (a reducible over the rows), execute-batch! (one SQL across a seq of parameter groups, answering per-group update counts), and with-transaction with its options map (:isolation, :read-only, :rollback-only). On postgres :isolation runs the transaction at that level. sqlite has only SERIALIZABLE and READ UNCOMMITTED, so like its JDBC driver it runs READ COMMITTED and REPEATABLE READ as SERIALIZABLE. Every operation takes a connection, a datasource, or a db-spec; a datasource or spec opens a connection owned by that call. Rows are unqualified lower-cased keyword maps — the drivers cannot see table names, so upstream's qualified default is not reproducible, and next.jdbc.result-set builder markers are accepted and ignored.

A datasource is db.datasource: an explicit open-datasource / acquire / release / close-datasource lifecycle over the drivers. It is a connection factory, not a pool — pooling can grow behind the same surface later, and this library deliberately does not emulate HikariCP.

PostgreSQL value model

Typed columns normalize to conventional values on the way out: uuid columns read as uuids, numeric as bigdec (it used to go through parse-double, losing precision), date/time/timestamp/timestamptz as java.time values (LocalDate/LocalTime/LocalDateTime/OffsetDateTime — a deliberate divergence from JDBC's java.sql.Timestamp, which jolt does not model), and arrays of the common element types as vectors (quoting, NULL elements and nesting honoured). A value the parser cannot read — postgres infinity, say — keeps its text form rather than throwing on a read path.

Parameters: uuids and temporal values bind as their text form and postgres infers the type; a vector binds as an array literal, which pairs with a cast at the use site (?::text[]). SQLite stores anything it does not know as text.

Errors

Database errors satisfy (catch java.sql.SQLException ...), so code written against the JDBC contract works unchanged. Migratus depends on this: its table-exists? probe catches SQLException to decide whether it still needs to create schema_migrations. Errors raised by the drivers themselves also carry :jdbc/sql-error true in their ex-data.

A driver that knows the failure's SQLState and vendor error code puts them in that same ex-data as :jdbc/sql-state (a string) and :jdbc/error-code (an int), and getSQLState and getErrorCode answer them, on SQLException and on the BatchUpdateException a batch raises. Without them those answer nil and 0. SQLite and PostgreSQL don't send them yet.

Registering a driver

Vendor dispatch goes through a registry in db.jdbc-shim. SQLite and PostgreSQL are registered through it, and a driver in another library can register the same way. (register-driver! vendor-kw driver-map) adds the driver, and registering the same vendor again replaces it. A uri string is matched against each driver's :uri-prefixes in registration order, after one leading jdbc: comes off. A dbspec map is matched on :subprotocol, :vendor or :dbtype against :vendor-names, lower-cased.

key shape
:uri-prefixes vector of strings, matched against the uri
:vendor-names set of lower-case strings
:connect (fn [uri-or-spec-map] handle); a failure throws ex-info with {:jdbc/sql-error true}
:close (fn [handle] nil)
:query-raw (fn [handle sql params] {:labels [..] :rows [[..]]})
:update (fn [handle sql params] count)
:execute-any (fn [handle sql params] {:labels :rows :count})
:execute-batch (fn [handle sql groups] [{:labels :rows :count} ...])
:max-params (fn [handle] n)
:product-name string, what getDatabaseProductName answers
:isolation int, the java.sql.Connection isolation constant reported before anyone sets one
:returning? boolean, whether generated keys come back through RETURNING
:class-names optional, driver class names that Class/forName should find
:read-only? optional, (fn [handle] bool), the initial isReadOnly (default false)
:set-read-only! optional, (fn [handle bool] nil); it may throw to refuse
:set-schema! optional, (fn [handle schema] nil); without it setSchema does nothing
:set-isolation! optional, (fn [handle level in-transaction?] nil), called with one of 1, 2, 4, 8; without it the level is only recorded
:get-isolation optional, (fn [handle] level); without it getTransactionIsolation answers the last level set, or :isolation
(db.jdbc-shim/register-driver! :mydb
  {:uri-prefixes ["mydb:"] :vendor-names #{"mydb"} :product-name "MyDB"
   :isolation 4 :returning? false :max-params (fn [h] 65535)
   :connect my/connect :close my/close :query-raw my/query-raw
   :update my/update :execute-any my/execute-any :execute-batch my/execute-batch})

Layout

  • db.sqlite / db.pg — the native drivers (jolt.ffi bindings).
  • db.jdbc-shim — the java.sql surface clojure.jdbc drives, over those drivers.
  • db.jdbc — the entry point: loads the shim, then clojure.jdbc on top of it.
  • jdbc.core — clojure.jdbc itself, pulled in as a dependency.
  • next.jdbc (+ .sql/.prepare/.result-set/.transaction) — the next.jdbc surface migratus and similar tools use.

Requirements

jolt v0.8.0 or newer on PATH; the system libsqlite3 (preinstalled on macOS and most Linux distros). PostgreSQL support additionally needs libpq at runtime.

The version floor is not cosmetic, and deps.edn declares it as :jolt/min-version "0.8.0". In jolt 0.8.0 jolt.ffi/write takes the value before the offset, and the native bindings here are written that way. An older runtime reads the same call with the two integers swapped, so it writes to the wrong place instead of failing.

The shim also needs three host fixes that landed in v0.7.3: with-open on a reify, a parenthesised (Class/FIELD) reading the field, and a protocol extended to a library-declared class actually dispatching. On a jolt older than that, this library fails at load or at the first connection.

Test

jolt -M:test                                   # sqlite
JOLT_TEST_PG_URI=postgres://... jolt -M:test   # also runs the postgres suite

About

Database wrapper for Postgres and SQLite

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages