Skip to main content

ironwork_rt/lir/
sql.rs

1//! EXEC SQL (lir.md §9.7): the program's statement table, which the SQL runtime reads. WHENEVER is
2//! not in it: lowering emits it as `Cond::Sql` branches after the op.
3
4use super::{AbendId, PlaceId, SymId};
5use crate::sql::{HostType, fingerprint};
6use crate::{codec_enum, codec_struct};
7
8/// One EXEC SQL block, declarative ones included; `Program.sql[k − 1]` has ordinal k. `P` and `S`
9/// are the executor's handles to a data item and to text: the LIR's ids by default, the walker's
10/// own references in the interpreter.
11#[derive(Clone, Debug, PartialEq, Eq)]
12pub struct SqlEntry<P = PlaceId, S = SymId> {
13    pub ordinal: u32,
14    /// The command word the call record and the EXEC messages name.
15    pub verb: S,
16    pub statement: SqlStatement<P, S>,
17    /// What a `Database` call receives, `?` for each input; empty for a declaration.
18    pub text: S,
19    pub fingerprint: u32,
20    /// Set on the OPEN of a cursor declared WITH HOLD, and on no other entry.
21    pub with_hold: bool,
22}
23
24/// The typed statement with its host variables resolved and each OPEN given its DECLARE's inputs.
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub enum SqlStatement<P = PlaceId, S = SymId> {
27    Query { inputs: Vec<HostPlace<P>>, into: Vec<HostPlace<P>> },
28    Change { delete: bool, inputs: Vec<HostPlace<P>>, current_of: Option<S> },
29    Open { cursor: S, inputs: Vec<HostPlace<P>> },
30    Fetch { cursor: S, into: Vec<HostPlace<P>> },
31    Close { cursor: S },
32    Commit,
33    Rollback,
34    /// WHENEVER, DECLARE CURSOR, INCLUDE and the other declarations: no op.
35    Declaration,
36    /// Abends EXEC, naming it, when reached.
37    Unsupported(S),
38}
39
40/// A host variable, or one member of a host structure at `member`'s offset and length. The
41/// indicator comes with the offset of this member's element in it.
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub struct HostPlace<P = PlaceId> {
44    pub var: P,
45    pub member: Option<(u32, u32)>,
46    /// Never a structure. An item with no SQL type keeps the walker's EXEC abend.
47    pub ty: Result<HostType, AbendId>,
48    pub indicator: Option<(P, u32)>,
49}
50
51/// The SQLCA fields the program declares, or its own SQLCODE and SQLSTATE, in the order filled.
52#[derive(Clone, Debug, Default, PartialEq, Eq)]
53pub struct Sqlca<P = PlaceId> {
54    pub fields: Vec<(SqlcaField, P, HostType)>,
55}
56
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub enum SqlcaField {
59    CaId,
60    CaBc,
61    Code,
62    ErrMl,
63    ErrMc,
64    ErrP,
65    State,
66    /// SQLERRD(n), n from 1 to 6.
67    ErrD(u8),
68    /// SQLWARN0 to SQLWARNA as 0 to 10.
69    Warn(u8),
70}
71
72codec_struct!(SqlEntry { ordinal, verb, statement, text, fingerprint, with_hold });
73codec_enum!(SqlStatement {
74    Query { inputs, into } = 0,
75    Change { delete, inputs, current_of } = 1,
76    Open { cursor, inputs } = 2,
77    Fetch { cursor, into } = 3,
78    Close { cursor } = 4,
79    Commit = 5,
80    Rollback = 6,
81    Declaration = 7,
82    Unsupported(what) = 8,
83});
84codec_struct!(HostPlace { var, member, ty, indicator } check host_place_valid);
85codec_struct!(Sqlca { fields } check sqlca_valid);
86codec_enum!(SqlcaField {
87    CaId = 0,
88    CaBc = 1,
89    Code = 2,
90    ErrMl = 3,
91    ErrMc = 4,
92    ErrP = 5,
93    State = 6,
94    ErrD(n) = 7,
95    Warn(n) = 8,
96});
97
98/// `crate::sql::read` and `write` take a structure's members one by one, never the structure.
99fn not_a_structure(ty: &HostType) -> Result<(), String> {
100    match ty {
101        HostType::Structure(_) => Err("a host structure where lowering gives its members".into()),
102        _ => Ok(()),
103    }
104}
105
106fn host_place_valid(place: &HostPlace) -> Result<(), String> {
107    place.ty.as_ref().map_or(Ok(()), not_a_structure)
108}
109
110fn sqlca_valid(sqlca: &Sqlca) -> Result<(), String> {
111    for (field, _, ty) in &sqlca.fields {
112        match *field {
113            SqlcaField::ErrD(n) if !(1..=6).contains(&n) => return Err(format!("SQLERRD({n}) is not an SQLCA field")),
114            SqlcaField::Warn(n) if n > 10 => return Err(format!("SQLWARN{n} is not an SQLCA field")),
115            _ => not_a_structure(ty)?,
116        }
117    }
118    Ok(())
119}
120
121/// load-module.md §7: ordinals run from 1, each fingerprint is its text's, and only the OPEN of a
122/// cursor declared WITH HOLD says so.
123pub(super) fn table_valid(table: &[SqlEntry], symbols: &[String]) -> Result<(), String> {
124    let symbol = |id: SymId| symbols.get(id as usize).ok_or_else(|| format!("symbol {id} of a table of {}", symbols.len()));
125    for (k, entry) in (1u32..).zip(table) {
126        if entry.ordinal != k {
127            return Err(format!("SQL entry {k} has ordinal {}", entry.ordinal));
128        }
129        let text = symbol(entry.text)?;
130        if entry.fingerprint != fingerprint(text) {
131            return Err(format!("SQL entry {k} has fingerprint {:08X}, not its text's {:08X}", entry.fingerprint, fingerprint(text)));
132        }
133        let held = match &entry.statement {
134            SqlStatement::Open { cursor, .. } => text.starts_with(&format!("DECLARE {} CURSOR WITH HOLD FOR ", symbol(*cursor)?)),
135            _ => false,
136        };
137        if entry.with_hold != held {
138            return Err(format!("SQL entry {k} has WITH HOLD {} for its text", if entry.with_hold { "set" } else { "clear" }));
139        }
140    }
141    Ok(())
142}