glite/decode
Decoders that turn a result row into a typed value.
If you also use gleam/dynamic/decode, import this module under another
name, such as import glite/decode as row.
import glite/decode
let user = {
use id <- decode.element(0, decode.int)
use name <- decode.element(1, decode.text)
use email <- decode.element(2, decode.optional(decode.text))
decode.success(User(id:, name:, email:))
}
Types
Decodes one row, a list of column values.
pub opaque type RowDecoder(a)
Decodes one column value. The error is a short description.
pub type ValueDecoder(a) =
fn(value.Value) -> Result(a, String)
Values
pub fn blob(value: value.Value) -> Result(BitArray, String)
Binary data. Text is accepted too, as its UTF-8 bytes, because SQLite doesn’t always say which of the two a value is.
pub fn bool(value: value.Value) -> Result(Bool, String)
A boolean stored as the integer 0 or 1.
pub fn element(
index: Int,
decoder: fn(value.Value) -> Result(a, String),
next: fn(a) -> RowDecoder(b),
) -> RowDecoder(b)
Decode the column at index, counting from 0, then carry on with next.
Made for use.
pub fn fail(message: String, at column: Int) -> RowDecoder(a)
A decoder that always fails with message, reported at column. Use it
in then for a value no decoder should accept.
pub fn map(
decoder: RowDecoder(a),
with f: fn(a) -> b,
) -> RowDecoder(b)
Change a decoded value with f.
let name_length = decode.map(name_decoder, string.length)
pub fn optional(
decoder: fn(value.Value) -> Result(a, String),
) -> fn(value.Value) -> Result(option.Option(a), String)
NULL becomes None; anything else goes through decoder.
pub fn run(
decoder: RowDecoder(a),
row: List(value.Value),
at row_index: Int,
) -> Result(a, error.Error)
Run a decoder on one row. row is the row’s position in its result, used
in the error.
pub fn then(
decoder: RowDecoder(a),
next: fn(a) -> RowDecoder(b),
) -> RowDecoder(b)
Decode the row with decoder, then decode the same row again with the
decoder next picks from the result. For rows whose shape depends on a
column, such as a kind column that says which other columns are set.
use kind <- decode.then(kind_decoder)
case kind {
"circle" -> circle_decoder
_ -> square_decoder
}