Skip to content

Instantly share code, notes, and snippets.

@reedho
Created June 1, 2025 11:02
Show Gist options
  • Save reedho/3203c6849456d1924cced7a5122ce905 to your computer and use it in GitHub Desktop.
Save reedho/3203c6849456d1924cced7a5122ce905 to your computer and use it in GitHub Desktop.
CozoDB Clojure FFM with Coffi

TLDR;

Download and put cozodb c library into correct place, e.g.

mkdir -p ~/Library/Java/Extensions
curl -OL https://github.com/cozodb/cozo/releases/download/v0.7.6/libcozo_c-0.7.6-aarch64-apple-darwin.dylib.gz
gunzip libcozo_c-0.7.6-aarch64-apple-darwin.dylib.gz
(ns me.cozo-clj-ffi
(:require
[coffi.ffi :as ffi :refer [defcfn]]
[coffi.mem :as mem]
,))
(defcfn strlen
"strlen" [::mem/c-string] ::mem/long
native-str-len [s]
(str "The string length is: " (native-str-len s)))
(comment
(strlen "hello world!")
,)
(ffi/load-system-library "cozo_c-0.7.6-aarch64-apple-darwin")
(defcfn cozo-free-str
"cozo_free_str" [::mem/pointer] ::mem/void)
(defcfn cozo-open-db
"cozo_open_db" [::mem/c-string ::mem/c-string ::mem/c-string ::mem/pointer] ::mem/pointer
native-cozo-open-db [engine path options]
(with-open [arena (mem/confined-arena)]
(let [int-ptr (mem/alloc-instance ::mem/int arena)
error-result-ptr (native-cozo-open-db engine path options int-ptr)
,]
(if error-result-ptr
(let [msg (mem/deserialize error-result-ptr ::mem/c-string)]
(cozo-free-str error-result-ptr)
(throw (ex-info (str "ERROR: " msg) {:engine engine :path path :options options})))
(mem/read-int int-ptr)))))
(defcfn cozo-run-query
"cozo_run_query" [::mem/int ::mem/c-string ::mem/c-string ::mem/int] ::mem/c-string)
(defcfn cozo-close-db
"cozo_close_db" [::mem/int] ::mem/int
native-cozo-close-db [db-id]
(let [x (native-cozo-close-db db-id)]
(not (zero? x))))
(comment
(def dbid (cozo-open-db "rocksdb" "cozo_data" "{}"))
(cozo-run-query dbid "?[] <- [[1]]" "{}" 1)
(cozo-close-db dbid)
,)
{:paths ["src" "resources"]
:deps {org.clojure/clojure {:mvn/version "1.12.0"}
org.suskalo/coffi {:mvn/version "1.0.615"}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment