1use super::host::{self, COLUMN_COUNT, TRUNCATED, Warnings};
6use super::{Answer, Call, Database, Outcome, Session};
7use crate::abend::Abend;
8use crate::host::Host;
9use crate::lir::{AbendId, HostPlace, SqlEntry, SqlStatement, Sqlca};
10use crate::vocab::Pos;
11
12type R<T> = Result<T, Abend>;
13
14const DEADLOCK: i32 = -911;
16
17pub trait SqlHost<'w, P: Copy, S>: Host<P> {
19 fn session(&mut self) -> Option<&mut Session<'w>>;
21 fn in_task(&self) -> bool;
23 fn program_id(&self) -> String;
24 fn text(&self, text: &S) -> String;
25 fn place_pos(&self, place: P) -> Pos;
27 fn untyped(&mut self, abend: AbendId) -> Abend;
29}
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub struct Ran {
34 pub sqlcode: i32,
35 pub warned: bool,
37}
38
39fn session<'a, 'w: 'a, P: Copy + 'a, S: 'a>(x: &'a mut impl SqlHost<'w, P, S>) -> &'a mut Session<'w> {
40 x.session().expect("a database is attached")
41}
42
43pub fn run<'w, P: Copy, S>(x: &mut impl SqlHost<'w, P, S>, entry: &SqlEntry<P, S>, sqlca: &Sqlca<P>, pos: Pos) -> R<Option<Ran>> {
45 let verb = x.text(&entry.verb);
46 let refused = |why: String| Abend { code: "EXEC".into(), message: format!("EXEC SQL {verb} was reached: {why}"), pos, file: None };
47 if x.session().is_none() {
48 return Err(refused("no database is attached to the run".into()));
49 }
50 let (program, text, ordinal) = (x.program_id(), x.text(&entry.text), entry.ordinal);
51 let mut warnings = Warnings::default();
52 let mut outcome = match &entry.statement {
53 SqlStatement::Query { inputs, into } => match host::inputs(x, inputs)? {
54 Err(e) => Outcome::error(e.code, e.state),
55 Ok(values) => {
56 let answer = database(x, &Call { program: &program, ordinal, verb: &verb, cursor: None, text: &text, inputs: &values }, |db, c| db.execute(c), pos)?;
57 single_row(x, answer, into, &mut warnings)?
58 }
59 },
60 SqlStatement::Change { delete, inputs, current_of } => {
61 let current_of = current_of.as_ref().map(|c| x.text(c));
62 let position = current_of.as_deref().map(|c| session(x).cursor(&program, c).map(|c| c.positioned));
63 match (position, host::inputs(x, inputs)?) {
64 (Some(None), _) => Outcome::error(-507, "24501"),
65 (Some(Some(false)), _) => Outcome::error(-508, "24504"),
66 (_, Err(e)) => Outcome::error(e.code, e.state),
67 (_, Ok(values)) => {
68 let mut answer = database(x, &Call { program: &program, ordinal, verb: &verb, cursor: current_of.as_deref(), text: &text, inputs: &values }, |db, c| db.execute(c), pos)?;
69 if current_of.is_none() && answer.sqlcode == 0 && answer.affected == 0 {
71 answer = Outcome::error(100, "02000");
72 }
73 if let (Some(c), true, true) = (¤t_of, *delete, answer.sqlcode >= 0)
74 && let Some(open) = session(x).cursor(&program, c)
75 {
76 open.positioned = false;
77 }
78 answer
79 }
80 }
81 }
82 SqlStatement::Open { cursor, inputs } => {
83 let cursor = x.text(cursor);
84 if session(x).cursor(&program, &cursor).is_some() {
85 Outcome::error(-502, "24502")
86 } else {
87 match host::inputs(x, inputs)? {
88 Err(e) => Outcome::error(e.code, e.state),
89 Ok(values) => {
90 let answer = database(x, &Call { program: &program, ordinal, verb: "OPEN", cursor: Some(&cursor), text: &text, inputs: &values }, |db, c| db.open(c), pos)?;
91 if answer.sqlcode >= 0 {
92 session(x).opened(&program, &cursor, entry.with_hold);
93 }
94 answer
95 }
96 }
97 }
98 }
99 SqlStatement::Fetch { cursor, into } => {
100 let cursor = x.text(cursor);
101 if session(x).cursor(&program, &cursor).is_none() {
102 Outcome::error(-501, "24501")
103 } else {
104 let answer = database(x, &Call { program: &program, ordinal, verb: "FETCH", cursor: Some(&cursor), text: &text, inputs: &[] }, |db, c| db.fetch(c), pos)?;
105 if answer.rows.len() > 1 {
106 return Err(Abend { code: "SQL".into(), message: format!("the database answered FETCH {cursor} with {} rows", answer.rows.len()), pos, file: None });
107 }
108 let on_row = answer.sqlcode >= 0 && answer.rows.len() == 1;
109 if let Some(open) = session(x).cursor(&program, &cursor) {
110 open.positioned = on_row;
111 }
112 let fetched = single_row(x, answer, into, &mut warnings)?;
113 Outcome { affected: i64::from(on_row), ..fetched }
114 }
115 }
116 SqlStatement::Close { cursor } => {
117 let cursor = x.text(cursor);
118 if session(x).cursor(&program, &cursor).is_none() {
119 Outcome::error(-501, "24501")
120 } else {
121 let answer = database(x, &Call { program: &program, ordinal, verb: "CLOSE", cursor: Some(&cursor), text: &text, inputs: &[] }, |db, c| db.close(c), pos)?;
122 if answer.sqlcode >= 0 {
123 session(x).closed(&program, &cursor);
124 }
125 answer
126 }
127 }
128 SqlStatement::Commit if x.in_task() => Outcome::error(-925, "2D521"),
129 SqlStatement::Rollback if x.in_task() => Outcome::error(-926, "2D521"),
130 SqlStatement::Commit => {
131 let answer = database(x, &Call { program: &program, ordinal, verb: "COMMIT", cursor: None, text: &text, inputs: &[] }, |db, c| db.commit(c), pos)?;
132 if answer.sqlcode >= 0 {
133 session(x).committed();
134 }
135 answer
136 }
137 SqlStatement::Rollback => {
138 let answer = database(x, &Call { program: &program, ordinal, verb: "ROLLBACK", cursor: None, text: &text, inputs: &[] }, |db, c| db.rollback(c), pos)?;
139 if answer.sqlcode >= 0 {
140 session(x).rolled_back();
141 }
142 answer
143 }
144 SqlStatement::Declaration => return Ok(None),
145 SqlStatement::Unsupported(what) => return Err(refused(format!("ironwork for COBOL does not run {}", x.text(what)))),
146 };
147 if outcome.sqlcode == DEADLOCK {
148 session(x).rolled_back();
149 }
150 warnings[0] = warnings[1..].iter().any(|&w| w);
151 if outcome.sqlcode == 0 && outcome.sqlstate == "00000" {
152 if warnings[TRUNCATED] {
153 outcome.sqlstate = "01004".into();
154 } else if warnings[COLUMN_COUNT] {
155 outcome.sqlstate = "01503".into();
156 }
157 }
158 host::sqlca(x, sqlca, &outcome, &warnings);
159 Ok(Some(Ran { sqlcode: outcome.sqlcode, warned: warnings[0] }))
160}
161
162fn database<'w, P: Copy, S>(x: &mut impl SqlHost<'w, P, S>, call: &Call, run: impl FnOnce(&mut dyn Database, &Call) -> Answer, pos: Pos) -> R<Outcome> {
164 let session = session(x);
165 session.pending |= !matches!(call.verb, "COMMIT" | "ROLLBACK");
166 run(&mut *session.database, call).map_err(|a| Abend { code: a.code.into(), message: a.message, pos, file: None })
167}
168
169fn single_row<'w, P: Copy, S>(x: &mut impl SqlHost<'w, P, S>, answer: Outcome, into: &[HostPlace<P>], warnings: &mut Warnings) -> R<Outcome> {
171 if answer.sqlcode < 0 {
172 return Ok(answer);
173 }
174 Ok(match answer.rows.len() {
175 0 => Outcome::error(100, "02000"),
176 1 => match host::assign(x, into, &answer.rows[0], warnings)? {
177 Ok(()) => answer,
178 Err(e) => Outcome::error(e.code, e.state),
179 },
180 _ => Outcome::error(-811, "21000"),
181 })
182}