1use crate::ast::CreateView;
8use crate::declared::{self, Declared};
9use crate::lex::{Tok, lex};
10use crate::parse::P;
11use crate::schema::Table;
12use crate::{DeclarationError, QueryCard, SqlError, ValType, parse_view, viewplan};
13
14pub fn select_card(declarations: &[Vec<String>], select: &str) -> Result<QueryCard, SqlError> {
34 let v = parse_one_select(select)?;
35 let tables = declarations
36 .iter()
37 .map(|argv| declared::read(argv).map_err(|e| SqlError::at(v.line, v.col, e.to_string())))
38 .collect::<Result<Vec<Declared>, SqlError>>()?;
39 let Some(d) = tables.iter().find(|d| d.table.name == v.table) else {
40 return Err(SqlError::at(
41 v.line,
42 v.col,
43 format!(
44 "FROM unknown table '{}' \u{2014} TABLE.LIST enumerates the declared tables",
45 v.table
46 ),
47 ));
48 };
49 let card = viewplan::card_for(&v, &d.table)?;
50 if let Some(p) = card.params.first() {
51 return Err(SqlError::at(
52 v.line,
53 v.col,
54 format!(
55 "${} is a query-card parameter \u{2014} sql run takes literal values; `sql compile` makes cards",
56 p.n
57 ),
58 ));
59 }
60 Ok(card)
61}
62
63fn parse_one_select(select: &str) -> Result<CreateView, SqlError> {
64 let toks = lex(select)?;
65 let mut p = P::new(&toks);
66 let t = p.peek();
67 let (line, col) = (t.line, t.col);
68 p.expect_kw("select", "\u{2014} sql run takes one SELECT")?;
69 let v = parse_view::parse_select_body(&mut p, "select".into(), line, col)?;
70 while p.eat_sym(';') {}
71 if !matches!(p.peek().tok, Tok::Eof) {
72 return Err(
73 p.err_here("expected the end of the SELECT \u{2014} sql run takes one statement")
74 );
75 }
76 Ok(v)
77}
78
79pub fn table_ddl(declaration: &[String]) -> Result<String, DeclarationError> {
101 let d = declared::read(declaration)?;
102 let t = &d.table;
103 let mut out = String::new();
104 let mut lost: Vec<String> = Vec::new();
105 if d.prefix != format!("{}:", t.name) {
106 lost.push(format!("PREFIX {}", d.prefix));
107 }
108 out.push_str(&format!("CREATE TABLE {} (\n", ident(&t.name)?));
109 let mut lines = Vec::new();
110 for (c, ty) in &t.columns {
111 let pk = if *c == t.pk { " PRIMARY KEY" } else { "" };
112 lines.push(format!(" {} {}{pk}", ident(c)?, sql_type(*ty)));
113 }
114 out.push_str(&lines.join(",\n"));
115 out.push_str("\n);\n");
116 indexes(t, &mut out)?;
117 orderpaths(t, &mut out, &mut lost)?;
118 lost.extend(d.beyond_sql.iter().map(|words| words.join(" ")));
119 for clause in lost {
120 out.push_str(&format!("-- not carried by SQL: {clause}\n"));
121 }
122 Ok(out)
123}
124
125fn indexes(t: &Table, out: &mut String) -> Result<(), DeclarationError> {
126 for ix in &t.indexes {
127 let unique = if ix.unique { "UNIQUE " } else { "" };
128 out.push_str(&format!(
129 "CREATE {unique}INDEX ON {} ({})",
130 ident(&t.name)?,
131 ident(&ix.column)?
132 ));
133 if !ix.values.is_empty() {
134 out.push_str(&format!(" INCLUDE ({})", idents(&ix.values)?));
135 }
136 out.push_str(";\n");
137 }
138 Ok(())
139}
140
141fn orderpaths(t: &Table, out: &mut String, lost: &mut Vec<String>) -> Result<(), DeclarationError> {
144 for op in &t.orderpaths {
145 if let [(c, true)] = op.on.as_slice() {
146 let stmt = format!(
148 "CREATE INDEX {} ON {} ({} DESC);\n",
149 ident(&op.name)?,
150 ident(&t.name)?,
151 ident(c)?
152 );
153 out.push_str(&stmt);
154 continue;
155 }
156 if op.on.len() < 2 {
157 let on: Vec<String> = op
158 .on
159 .iter()
160 .map(|(c, desc)| if *desc { format!("{c} DESC") } else { c.clone() })
161 .collect();
162 lost.push(format!("ORDERPATH {} ON {}", op.name, on.join(" THEN ")));
163 continue;
164 }
165 let cols = op
166 .on
167 .iter()
168 .map(|(c, desc)| Ok(format!("{}{}", ident(c)?, if *desc { " DESC" } else { "" })))
169 .collect::<Result<Vec<String>, DeclarationError>>()?
170 .join(", ");
171 out.push_str(&format!(
172 "CREATE INDEX {} ON {} ({cols});\n",
173 ident(&op.name)?,
174 ident(&t.name)?
175 ));
176 }
177 Ok(())
178}
179
180fn sql_type(ty: ValType) -> &'static str {
181 match ty {
182 ValType::I64 => "bigint",
183 ValType::F64 => "double precision",
184 ValType::Str => "text",
185 _ => unreachable!("a declared column is i64, f64 or str"),
187 }
188}
189
190fn ident(name: &str) -> Result<String, DeclarationError> {
194 let bare = name.bytes().next().is_some_and(|b| b.is_ascii_lowercase() || b == b'_')
195 && name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_');
196 if bare {
197 Ok(name.to_string())
198 } else if name.contains('"') {
199 Err(DeclarationError::Unspellable(name.to_string()))
200 } else {
201 Ok(format!("\"{name}\""))
202 }
203}
204
205fn idents(names: &[String]) -> Result<String, DeclarationError> {
206 Ok(names
207 .iter()
208 .map(|n| ident(n))
209 .collect::<Result<Vec<String>, DeclarationError>>()?
210 .join(", "))
211}
212
213#[cfg(test)]
214#[path = "run_tests.rs"]
215mod tests;