postgleam
A PostgreSQL driver for Gleam, implementing the wire protocol in Gleam.
import postgleam
import postgleam/config
import postgleam/decode
pub fn main() {
let assert Ok(cfg) = config.from_url("postgres://app:secret@localhost/app")
let assert Ok(conn) = postgleam.connect(cfg)
let assert Ok(response) =
postgleam.query_with(
conn,
"SELECT id, name FROM users WHERE active = $1",
[postgleam.bool(True)],
{
use id <- decode.element(0, decode.int)
use name <- decode.element(1, decode.text)
decode.success(#(id, name))
},
)
postgleam.disconnect(conn)
}
A Connection is one PostgreSQL session owned by an actor. It runs one
request at a time; use postgleam/pool to run queries concurrently.
Types
A connection handle backed by an OTP actor.
pub opaque type Connection
A query parameter value. None is SQL NULL.
pub type Param =
option.Option(value.Value)
Result from a decoded query.
pub type Response(a) {
Response(rows: List(a), count: Int, tag: String)
}
Constructors
-
Response(rows: List(a), count: Int, tag: String)
Why a transaction did not commit.
pub type TransactionError(e) {
RolledBack(e)
TransactionFailed(error.Error)
}
Constructors
-
RolledBack(e)The function returned
Error(e); the transaction was rolled back. -
TransactionFailed(error.Error)BEGIN, COMMIT or ROLLBACK itself failed.
Values
pub fn array(
val: List(option.Option(value.Value)),
) -> option.Option(value.Value)
Create an array parameter from a list of optional values.
postgleam.array([Some(value.Integer(1)), Some(value.Integer(2)), None])
pub fn bit_string(
bit_count: Int,
data: BitArray,
) -> option.Option(value.Value)
Create a bit string parameter (bit count + data bytes).
pub fn box(
x1: Float,
y1: Float,
x2: Float,
y2: Float,
) -> option.Option(value.Value)
Create a box parameter (upper-right and lower-left corners).
pub fn bytea(val: BitArray) -> option.Option(value.Value)
Create a bytea (binary data) parameter.
pub fn circle(
x: Float,
y: Float,
radius: Float,
) -> option.Option(value.Value)
Create a circle parameter (center x, center y, radius).
pub fn close(
conn: Connection,
name: String,
) -> Result(Nil, error.Error)
Close a prepared statement.
pub fn connect(
config: config.Config,
) -> Result(Connection, error.Error)
Connect to PostgreSQL. The connection is owned by a new actor process linked to the caller.
pub fn copy_in(
conn: Connection,
sql: String,
data: List(BitArray),
) -> Result(String, error.Error)
Bulk insert with COPY. sql is a COPY ... FROM STDIN statement and
data the rows in COPY text format (each ending with \n).
Returns the command tag (e.g. "COPY 1000").
pub fn copy_out(
conn: Connection,
sql: String,
) -> Result(List(BitArray), error.Error)
Bulk export with COPY. sql is a COPY ... TO STDOUT statement.
pub fn date(val: Int) -> option.Option(value.Value)
Create a date parameter (days since 2000-01-01).
pub fn execute(
conn: Connection,
prepared: connection.PreparedStatement,
params: List(option.Option(value.Value)),
) -> Result(connection.ExtendedQueryResult, error.Error)
Execute a previously prepared statement.
pub fn float(val: Float) -> option.Option(value.Value)
Create a float parameter (float4, float8).
pub fn inet(
family: Int,
address: BitArray,
netmask: Int,
) -> option.Option(value.Value)
Create an inet/cidr parameter (family, address bytes, netmask). Family: 2 for IPv4, 3 for IPv6.
pub fn int(val: Int) -> option.Option(value.Value)
Create an integer parameter (int2, int4, int8).
pub fn interval(
microseconds: Int,
days: Int,
months: Int,
) -> option.Option(value.Value)
Create an interval parameter (microseconds, days, months).
pub fn jsonpath(val: String) -> option.Option(value.Value)
Create a JSONPath parameter.
pub fn line(
a: Float,
b: Float,
c: Float,
) -> option.Option(value.Value)
Create a line parameter (Ax + By + C = 0).
pub fn lseg(
x1: Float,
y1: Float,
x2: Float,
y2: Float,
) -> option.Option(value.Value)
Create a line segment parameter (two endpoints).
pub fn macaddr(val: BitArray) -> option.Option(value.Value)
Create a macaddr parameter (6-byte binary).
pub fn macaddr8(val: BitArray) -> option.Option(value.Value)
Create a macaddr8 parameter (8-byte binary).
pub fn money(val: Int) -> option.Option(value.Value)
Create a money parameter (int64 cents).
pub fn notify(
conn: Connection,
channel: String,
payload: String,
) -> Result(Nil, error.Error)
Send a LISTEN/NOTIFY notification. Receive them with postgleam/listener.
pub fn nullable(
val: option.Option(a),
to_param: fn(a) -> option.Option(value.Value),
) -> option.Option(value.Value)
Create a nullable parameter from an Option value.
postgleam.nullable(Some("hello"), postgleam.text)
// => Some(value.Text("hello"))
postgleam.nullable(None, postgleam.text)
// => None
pub fn numeric(val: String) -> option.Option(value.Value)
Create a numeric/decimal parameter (string representation).
pub fn path(
closed: Bool,
points: List(#(Float, Float)),
) -> option.Option(value.Value)
Create a path parameter (closed/open flag + list of points).
pub fn point(x: Float, y: Float) -> option.Option(value.Value)
Create a point parameter (x, y).
pub fn polygon(
vertices: List(#(Float, Float)),
) -> option.Option(value.Value)
Create a polygon parameter (list of vertices).
pub fn prepare(
conn: Connection,
name: String,
sql: String,
) -> Result(connection.PreparedStatement, error.Error)
Prepare a named statement for later execute.
pub fn query(
conn: Connection,
sql: String,
params: List(option.Option(value.Value)),
) -> Result(connection.ExtendedQueryResult, error.Error)
Execute a parameterized query (extended protocol, binary format). The statement is prepared once per connection and cached.
pub fn query_batch(
conn: Connection,
sql: String,
param_sets: List(List(option.Option(value.Value))),
) -> Result(List(connection.ExtendedQueryResult), error.Error)
Execute the same statement with several parameter sets in one pipeline (one network round trip). Returns one result per parameter set.
pub fn query_fold(
conn: Connection,
sql: String,
params: List(option.Option(value.Value)),
chunk_size: Int,
decoder: decode.RowDecoder(a),
initial: acc,
f: fn(acc, a) -> acc,
) -> Result(acc, error.Error)
Fold over a query’s rows without loading them all into memory. Rows are
fetched chunk_size at a time; f runs inside the connection’s actor,
so it should be quick and must not use this connection.
pub fn query_one(
conn: Connection,
sql: String,
params: List(option.Option(value.Value)),
decoder: decode.RowDecoder(a),
) -> Result(a, error.Error)
Execute a query and decode the first row. Errors if there are no rows.
pub fn query_with(
conn: Connection,
sql: String,
params: List(option.Option(value.Value)),
decoder: decode.RowDecoder(a),
) -> Result(Response(a), error.Error)
Execute a parameterized query and decode each row with decoder.
pub fn simple_query(
conn: Connection,
sql: String,
) -> Result(List(connection.SimpleQueryResult), error.Error)
Execute a simple (text protocol) query. Use for DDL and multi-statement scripts; values come back as text.
pub fn time(val: Int) -> option.Option(value.Value)
Create a time parameter (microseconds since midnight).
pub fn timestamp(val: Int) -> option.Option(value.Value)
Create a timestamp parameter (microseconds since 2000-01-01 00:00:00).
pub fn timestamptz(val: Int) -> option.Option(value.Value)
Create a timestamptz parameter (microseconds since 2000-01-01 00:00:00 UTC).
pub fn timetz(
microseconds: Int,
tz_offset: Int,
) -> option.Option(value.Value)
Create a timetz parameter (microseconds since midnight, tz offset in seconds).
pub fn transaction(
conn: Connection,
f: fn(Connection) -> Result(a, e),
) -> Result(a, TransactionError(e))
Run f in a transaction: BEGIN, then COMMIT if f returns Ok or
ROLLBACK if it returns Error. Nested calls are not supported (use
SAVEPOINT yourself); with a pool, use pool.transaction.
pub fn uuid(val: BitArray) -> option.Option(value.Value)
Create a UUID parameter (16-byte binary).
pub fn uuid_string(
val: String,
) -> Result(option.Option(value.Value), Nil)
Create a UUID parameter from a string like “550e8400-e29b-41d4-a716-446655440000”. Errors if the string is not a valid UUID (it never silently becomes NULL).