/// A row's typed accessors, by column name (issue gabla108/louise#145 §2). Errors name
/// the column and the wanted and found types. Values may be in text or
/// binary format (the field's format code); each accessor reads both.
import std/bytes
import std/dec as decs
import std/float as floats
import std/list
import std/result
import std/string
import std/time.{type Timestamp}
import binary
import client.{type Row, Row}
import numeric
import protocol.{type Field}
import uuid
/// The value of column `name` as text. `Error` on no such column; `None`
/// is SQL `NULL`.
pub fn text :: row: Row name: String -> Result, String>
{
use (found, _) <- result.try (column row name)
match found
{ None -> Ok(None)
, Some(b) -> match bytes.to_string b
{ Ok(s) -> Ok(Some(s)), Error(e) -> Error("column {name}: {e}") }
}
}
/// The value of column `name` as an `Int`.
pub fn int :: row: Row name: String -> Result , String>
{
use (found, field) <- result.try (column row name)
match found
{ None -> Ok(None)
, Some(b) -> if field.format == 1
{
// Binary: big-endian, the width by type.
match field.type_oid
{ 21 -> Ok(Some(binary.i16_at b 0)) // int2
, 23 -> Ok(Some(binary.i32_at b 0)) // int4
, 20 -> Ok(Some(binary.i64_at b 0)) // int8
, _ ->
Error("column {name}: a binary integer of type oid {field.type_oid}")
}
}
else
{
match bytes.to_string b
{ Ok(s) ->
string.to_int s
|> result.map fn n { Some(n) }
|> result.map_error fn e { "column {name}: {e}" }
, Error(e) -> Error("column {name}: {e}")
}
}
}
}
/// The value of column `name` as a `Float`.
pub fn float :: row: Row name: String -> Result , String>
{
use (found, field) <- result.try (column row name)
match found
{ None -> Ok(None)
, Some(b) -> if field.format == 1
{
match field.type_oid
{ 700 -> Ok(Some(binary.f32_at b 0)) // float4
, 701 -> Ok(Some(binary.f64_at b 0)) // float8
, _ -> Error("column {name}: a binary float of type oid {field.type_oid}")
}
}
else
{
match bytes.to_string b
{ Ok(s) ->
floats.parse s
|> result.map fn f { Some(f) }
|> result.map_error fn e { "column {name}: {e}" }
, Error(e) -> Error("column {name}: {e}")
}
}
}
}
/// The value of column `name` as a `Bool`.
pub fn bool :: row: Row name: String -> Result , String>
{
use (found, field) <- result.try (column row name)
match found
{ None -> Ok(None)
, Some(b) -> // One byte, read in place ('t'/'f' in text, 1/0 in binary).
match (field.format == 1, bytes.length b == 1, bytes.read_u8 b 0)
{ (True, True, 0) -> Ok(Some(False))
, (True, True, 1) -> Ok(Some(True))
, (True, _, _) -> Error("column {name}: not a binary bool")
, (False, True, 116) -> Ok(Some(True)) // t
, (False, True, 102) -> Ok(Some(False)) // f
, (False, _, _) -> Error("column {name}: not a bool")
}
}
}
/// The value of column `name` as bytes (binary `bytea` is the raw bytes;
/// text is the `\x` hex form, decoded).
pub fn bytea :: row: Row name: String -> Result , String>
{
use (found, field) <- result.try (column row name)
match found
{ None -> Ok(None)
, Some(b) -> if field.format == 1
{
Ok(Some(b))
}
else
{
match bytes.to_string b
{ Ok
( s
) -> if string.starts_with s "\\x"
{
use decoded <-
result.try
( unhex (string_tail s 2)
|> result.map_error fn e { "column {name}: {e}" }
)
Ok(Some(decoded))
}
else
{
Error("column {name}: bytea not in hex form")
}
, Error(e) -> Error("column {name}: {e}")
}
}
}
}
/// The value of column `name` as a `uuid.Uuid`.
pub fn uuid :: row: Row name: String -> Result , String>
{
use (found, field) <- result.try (column row name)
match found
{ None -> Ok(None)
, Some(b) -> if field.format == 1
{
match uuid.from_bytes b
{ Some(id) -> Ok(Some(id))
, None -> Error("column {name}: not 16 bytes of uuid")
}
}
else
{
use s <- result.try (text_of name b)
match uuid.from_rfc s
{ Some(id) -> Ok(Some(id)), None -> Error("column {name}: not a UUID") }
}
}
}
/// The value of column `name` as a `time.Timestamp`. PostgreSQL's text is
/// nearly RFC 3339; its `+00` zone suffix becomes `+00:00`. Binary is
/// microseconds since 2000-01-01 UTC.
pub fn timestamptz :: row: Row name: String -> Result , String>
{
use (found, field) <- result.try (column row name)
match found
{ None -> Ok(None)
, Some(b) -> if field.format == 1
{
let micros = binary.i64_at b 0
Ok(Some(time.from_unix_ns ((micros + 946684800000000) * 1000)))
}
else
{
use s <- result.try (text_of name b)
time.parse (rfc3339 s)
|> result.map fn t { Some(t) }
|> result.map_error fn e { "column {name}: {e}" }
}
}
}
/// The value of column `name` as a `decs.Dec` (PostgreSQL `NUMERIC`,
/// OID 1700). Past 18 places the value rounds half-even (the rule of
/// `std/dec`); NaN, an infinity, or an out-of-range value is an `Error`.
pub fn dec :: row: Row name: String -> Result , String>
{
use (found, field) <- result.try (column row name)
match found
{ None -> Ok(None)
, Some(b) -> if field.format == 1
{
if field.type_oid == 1700
{
numeric.to_dec b
|> result.map fn d { Some(d) }
|> result.map_error fn e { "column {name}: {e}" }
}
else
{
Error("column {name}: a binary numeric of type oid {field.type_oid}")
}
}
else
{
match bytes.to_string b
{ Ok(s) ->
decs.parse s
|> result.map fn d { Some(d) }
|> result.map_error fn e { "column {name}: {e}" }
, Error(e) -> Error("column {name}: {e}")
}
}
}
}
// ---- helpers --------------------------------------------------------------------
/// The column's raw value and its field, by name.
fn column :: row: Row name: String -> Result<(Option, Field), String>
{
let Row(columns, values) = row
match find columns values name
{ None -> Error("no column named {name}"), Some(found) -> Ok(found) }
}
/// The value and its field, walking the columns and values together.
fn find ::
columns: List
values: List>
name: String
-> Option<(Option, Field)>
{
match (columns, values)
{ ([f, ..fs], [v, ..vs]) -> if f.name == name
{
Some((v, f))
}
else
{
find fs vs name
}
, _ -> None
}
}
/// The bytes as text, or an error naming the column.
fn text_of :: name: String b: Bytes -> Result
{
match bytes.to_string b
{ Ok(s) -> Ok(s), Error(e) -> Error("column {name}: {e}") }
}
/// PostgreSQL's timestamptz text is nearly RFC 3339: a `+00` zone suffix
/// becomes `+00:00`.
fn rfc3339 :: s: String -> String
{
let b = bytes.from_string s
match bytes.get b (bytes.length b - 3)
{ Some(43) -> s <> ":00" // +
, Some(45) -> s <> ":00" // -
, _ -> s
}
}
/// `s` without its first `n` characters (ASCII prefixes).
fn string_tail :: s: String n: Int -> String
{
let b = bytes.from_string s
match bytes.to_string (bytes.slice b n (bytes.length b))
{ Ok(t) -> t, Error(_) -> s }
}
/// The bytes of a hex string (both cases), decoded pairwise into one
/// buffer — not per-byte lists, which cost ~77 bytes per byte on a large
/// `bytea` (issue gabla108/louise#311).
fn unhex :: hex: String -> Result
{
let b = bytes.from_string hex
unhex_loop b 0 (bytes.builder_with_capacity (bytes.length b / 2))
}
fn unhex_loop :: b: Bytes at: Int acc: bytes.Builder -> Result
{
if at >= bytes.length b
{
Ok(bytes.build acc)
}
else if at + 1 >= bytes.length b
{
Error("odd hex length")
}
else
{
use hi <- result.try (hex_value (bytes.read_u8 b at))
use lo <- result.try (hex_value (bytes.read_u8 b (at + 1)))
unhex_loop b (at + 2) (bytes.append_byte acc (hi * 16 + lo))
}
}
fn hex_value :: c: Int -> Result
{
if c >= 48 && c <= 57
{
Ok(c - 48)
}
else if c >= 65 && c <= 70
{
Ok(c - 65 + 10)
}
else if c >= 97 && c <= 102
{
Ok(c - 97 + 10)
}
else
{
Error("not a hex digit")
}
}
// ---- tests ------------------------------------------------------------------------
import std/test.{assert, assert_equal}
@test
fn unhex_decodes_both_cases_and_rejects_bad_input ::
{
assert (unhex "" == Ok(bytes.empty ())) "empty"
assert
(unhex "deadbeef" == Ok(bytes.from_list [222, 173, 190, 239]))
"lowercase"
assert
(unhex "DEADBEEF" == Ok(bytes.from_list [222, 173, 190, 239]))
"uppercase"
assert
(unhex "00010f10ff" == Ok(bytes.from_list [0, 1, 15, 16, 255]))
"digits"
assert (unhex "abc" == Error("odd hex length")) "odd length"
assert (unhex "zz" == Error("not a hex digit")) "not hex"
}
@test
fn unhex_decodes_a_large_string_in_one_pass ::
{
// 200_000 bytes as 400_000 hex chars: a per-byte-lists decode would not
// fit the test budget (issue gabla108/louise#311).
let text =
bytes.build_string
( list.fold
(list.range 1 200_000)
(bytes.builder_with_capacity 400_000)
fn b i
{
let b = bytes.append_string b (hex_pair (i % 251 / 16))
bytes.append_string b (hex_pair (i % 251 % 16))
}
)
match unhex text
{ Error(e) -> panic e
, Ok(decoded) ->
{
assert_equal (bytes.length decoded) 200_000
assert_equal (bytes.read_u8 decoded 0) 1
assert_equal (bytes.read_u8 decoded 199_999) (200_000 % 251)
}
}
}
/// A nibble as a hex character (the test's encoder).
fn hex_pair :: d: Int -> String
{
match d
{ 10 -> "a"
, 11 -> "b"
, 12 -> "c"
, 13 -> "d"
, 14 -> "e"
, 15 -> "f"
, _ -> "{d}"
}
}