postgres/db
Conn
(Conn)
opaque handle to a libpq PGconn connection.
db-connect
(db-connect [connstr : cstr] :)
open a connection to a PostgreSQL server.
| connstr | libpq connection string, e.g. "host=localhost dbname=mydb" |
(Result Conn int) -- ok carries the Conn handle; err carries 0 on failure.
(let [r (db-connect "host=localhost dbname=test user=postgres")]
(if (ok? r) (let [conn (ok-val r)] ...) (println "connect failed")))
Since: PG0
db-close
(db-close [conn : Conn] :)
close a connection opened with db-connect.
| conn | connection handle (ok-val from db-connect) |
(Result int int) -- ok carries 0, always.
(db-close conn)
Since: PG0
db-exec
(db-exec [^borrow conn : Conn sql : cstr] :)
execute a SQL statement that returns no rows.
| conn | connection handle | |
| sql | DDL or DML SQL string |
(Result int int) -- ok carries 0; err carries 0 on failure.
(db-exec conn "CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, name TEXT)")
Since: PG0
db-query
(db-query [^borrow conn : Conn sql : cstr] :)
execute a SELECT and return a rows handle.
| conn | connection handle | |
| sql | SELECT SQL string (no $N placeholders; use db-query-params for those) |
(Result Rows int) -- ok carries the Rows handle; err carries 0 on failure. Free the Rows with rows-free from postgres/row when done.
(let [r (db-query conn "SELECT id, name FROM users")]
(if (ok? r)
(let [rows (ok-val r)]
(println (rows-count rows))
(rows-free rows))
(println "query failed")))
Since: PG0
db-query-params
(db-query-params [^borrow conn : Conn sql : cstr params : int] :)
execute a parameterized SELECT with $1,$2,... placeholders.
| conn | connection handle | |
| sql | SELECT SQL string with $1,$2,... placeholders | |
| params | cons list of :cstr parameter values (positional, 1-indexed) |
(Result Rows int) -- ok carries the Rows handle; err carries 0 on failure. Free the Rows with rows-free from postgres/row when done.
(let [r (db-query-params conn "SELECT * FROM users WHERE name = $1"
(cons "Alice" 0))]
(if (ok? r) (let [rows (ok-val r)] ...) (println "query failed")))
Since: PG1
db-begin
(db-begin [^borrow conn : Conn] :)
begin a transaction.
| conn | connection handle |
(Result int int) -- ok carries 0; err carries 0 on failure.
(db-begin conn)
Since: PG1
db-commit
(db-commit [^borrow conn : Conn] :)
commit the current transaction.
| conn | connection handle |
(Result int int) -- ok carries 0; err carries 0 on failure.
(db-commit conn)
Since: PG1
db-rollback
(db-rollback [^borrow conn : Conn] :)
roll back the current transaction.
| conn | connection handle |
(Result int int) -- ok carries 0; err carries 0 on failure.
(db-rollback conn)
Since: PG1
Internal definitions
__nil-- return the empty list sentinel (0).__cons-- prepend a value to a cons list; returns new cell as :int.__params-count-- count the number of cells in a cons list.__params-values-- build a heap-allocated char** from a cons list of :cstr.__pq-query-params-typed-- PQexecParams; returns (Result Rows int).