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