Skip to main content

ironwork_rt/sql/
mod.rs

1//! The SQL runtime: values at the database boundary, the host variables they come from and go to,
2//! and EXEC SQL statements run against the session (`run`, over the executor's `SqlHost`). It
3//! reaches storage only as a byte range and a host type, so any executor can call it.
4
5mod convert;
6mod database;
7mod dynamic;
8mod host;
9mod postgres;
10mod replay;
11mod run;
12mod sqlda;
13
14pub use convert::{ReadError, Written, read, write};
15pub use database::{Abandoned, Answer, Call, Column, ColumnType, Database, OpenCursor, Outcome, Prepared, Session};
16pub use postgres::{Postgres, Stream, Tls};
17pub use replay::{Recorder, Replay};
18pub use run::{Ran, SqlHost, run};
19
20use crate::vocab::SignClause;
21
22/// A value at the database boundary.
23#[derive(Clone, Debug, PartialEq)]
24pub enum Value {
25    Null,
26    Int(i64),
27    /// The unscaled value and its decimal places.
28    Decimal { value: i128, scale: u32 },
29    Double(f64),
30    Char(String),
31    Binary(Vec<u8>),
32}
33
34impl Value {
35    /// The value as a recording writes it, a string without its trailing blanks; NULL as nothing.
36    pub fn text(&self) -> String {
37        match self {
38            Value::Null => String::new(),
39            Value::Int(n) => n.to_string(),
40            Value::Decimal { value, scale } => Self::decimal_text(*value, *scale),
41            Value::Double(d) => d.to_string(),
42            Value::Char(s) => s.trim_end().to_owned(),
43            Value::Binary(b) => b.iter().map(|byte| format!("{byte:02X}")).collect(),
44        }
45    }
46
47    /// A decimal's text, `-1234.50` for -123450 at scale 2, as recordings and backends write it.
48    pub fn decimal_text(value: i128, scale: u32) -> String {
49        let s = scale as usize;
50        let digits = format!("{:0>width$}", value.unsigned_abs(), width = s + 1);
51        let (whole, places) = digits.split_at(digits.len() - s);
52        let sign = if value < 0 { "-" } else { "" };
53        if s == 0 { format!("{sign}{whole}") } else { format!("{sign}{whole}.{places}") }
54    }
55
56    /// A decimal from its text, its scale the count of digits after the point.
57    pub fn parse_decimal(text: &str) -> Option<Value> {
58        let (negative, digits) = match text.strip_prefix('-') {
59            Some(d) => (true, d),
60            None => (false, text.strip_prefix('+').unwrap_or(text)),
61        };
62        let (whole, places) = digits.split_once('.').unwrap_or((digits, ""));
63        if whole.is_empty() || !whole.bytes().chain(places.bytes()).all(|b| b.is_ascii_digit()) {
64            return None;
65        }
66        let magnitude: i128 = format!("{whole}{places}").parse().ok()?;
67        Some(Value::Decimal { value: if negative { -magnitude } else { magnitude }, scale: places.len() as u32 })
68    }
69}
70
71/// An SQLCODE and its SQLSTATE.
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73pub struct SqlError {
74    pub code: i32,
75    pub state: &'static str,
76}
77
78pub const NOT_ASSIGNABLE: SqlError = SqlError { code: -303, state: "42806" };
79pub const OUT_OF_RANGE: SqlError = SqlError { code: -304, state: "22003" };
80pub const NULL_WITHOUT_INDICATOR: SqlError = SqlError { code: -305, state: "22002" };
81pub const BAD_LENGTH: SqlError = SqlError { code: -311, state: "22501" };
82pub const UNCONVERTIBLE: SqlError = SqlError { code: -330, state: "22021" };
83
84/// What a host variable holds, as Db2 reads its COBOL declaration.
85#[derive(Clone, Debug, PartialEq, Eq)]
86pub enum HostType {
87    SmallInt { signed: bool },
88    Integer { signed: bool },
89    BigInt { signed: bool },
90    Decimal { digits: u32, scale: u32, signed: bool },
91    Zoned { digits: u32, scale: u32, signed: bool, sign: Option<SignClause> },
92    Real,
93    Double,
94    Char(u32),
95    VarChar(u32),
96    /// GRAPHIC: a DBCS item of this many characters.
97    Graphic(u32),
98    /// VARGRAPHIC: a 49-level halfword of DBCS characters and a 49-level DBCS item of at most this
99    /// many.
100    VarGraphic(u32),
101    /// A host structure: its members' layout items and types, in order.
102    Structure(Vec<(usize, HostType)>),
103}
104
105/// A statement's identity in a recording: 32-bit FNV-1a over its canonical text.
106pub fn fingerprint(text: &str) -> u32 {
107    text.bytes().fold(0x811c_9dc5, |h, b| (h ^ u32::from(b)).wrapping_mul(0x0100_0193))
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    #[test]
115    fn the_fingerprint_of_nothing_is_the_fnv_offset() {
116        assert_eq!(fingerprint(""), 0x811c_9dc5);
117        assert_ne!(fingerprint("COMMIT"), fingerprint("ROLLBACK"));
118    }
119}