sqlite/db
Db
(Db)
opaque handle to a sqlite3 database connection.
Stmt
(Stmt)
opaque handle to a sqlite3 prepared statement.
db-open
(db-open [path : cstr] :)
open a SQLite3 database file, creating it if it does not exist.
| path | filesystem path to the database file |
(Result Db int) -- ok carries the Db handle; err carries 0 on failure. Use sqlite-errmsg from sqlite/error on the handle for details.
(let [r (db-open "app.db")]
(if (ok? r) (let [db (ok-val r)] ...) (println "open failed")))
Since: P2
db-close
(db-close [db : Db] :)
close a database handle opened with db-open.
| db | database handle (ok-val from db-open) |
(Result int int) -- ok carries 0, always.
(db-close db)
Since: P2
db-exec
(db-exec [^borrow db : Db sql : cstr] :)
execute a SQL statement that returns no rows.
| db | database handle | |
| sql | DDL or DML SQL string |
(Result int int) -- ok carries 0; err carries 0 on failure. Use sqlite-errmsg from sqlite/error on db for the error string.
(db-exec db "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")
Since: P2
db-prepare
(db-prepare [^borrow db : Db sql : cstr] :)
compile a SQL string into a reusable prepared statement.
| db | database handle | |
| sql | SQL string with optional ?-placeholders for parameters |
(Result Stmt int) -- ok carries the Stmt handle; err carries 0 on failure. Finalize with stmt-finalize from sqlite/stmt when done.
(let [r (db-prepare db "INSERT INTO users (name) VALUES (?)")]
(if (ok? r)
(let [stmt (ok-val r)]
(stmt-bind-text stmt 1 "Alice")
(stmt-step stmt)
(stmt-finalize stmt))
(println "prepare failed")))
Since: P2
db-query
(db-query [^borrow db : Db sql : cstr] :)
execute a SELECT and collect all rows as a list of alists.
| db | database handle | |
| sql | SELECT SQL string (no ?-placeholders; use db-prepare for parameters) |
(Result int int) -- ok carries the row cons list (an :int cell handle); err carries 0 on prepare failure. Each row is an alternating name/value alist; use row-get from sqlite/row. Rows are in reverse SQLite output order (last fetched row at list head).
(let [r (db-query db "SELECT id, name FROM users")]
(if (ok? r)
(let [rows (ok-val r)]
(for [row rows] (println (row-get row "name"))))
(println "query failed")))
Since: P2
Internal definitions
__nil-- return the empty list sentinel (0).__cons-- prepend a value to a cons list; returns new cell as :int.__db-prepare-raw-- prepare SQL; returns sqlite3_stmt* as :int (0 on failure).__ncols-- return column count for a prepared statement.__colname-dup-- return a heap-copied column name at index i as :int.__coltext-dup-- return a heap-copied column text value at index i as :int.__step-raw-- step a statement; 1=row available, 0=done, -1=error.__finalize-raw-- finalize a prepared statement.__build-row-- build an alist from the current statement row position.__collect-rows-- collect all result rows from stmt into a cons list.__db-query-rows-- build a Result wrapping the collected row alist.__db-query-err