use crate::ast::CreateView;
use crate::declared::{self, Declared};
use crate::lex::{Tok, lex};
use crate::parse::P;
use crate::schema::Table;
use crate::{DeclarationError, QueryCard, SqlError, ValType, parse_view, viewplan};
pub fn select_card(declarations: &[Vec<String>], select: &str) -> Result<QueryCard, SqlError> {
let v = parse_one_select(select)?;
let tables = declarations
.iter()
.map(|argv| declared::read(argv).map_err(|e| SqlError::at(v.line, v.col, e.to_string())))
.collect::<Result<Vec<Declared>, SqlError>>()?;
let Some(d) = tables.iter().find(|d| d.table.name == v.table) else {
return Err(SqlError::at(
v.line,
v.col,
format!(
"FROM unknown table '{}' \u{2014} TABLE.LIST enumerates the declared tables",
v.table
),
));
};
let card = viewplan::card_for(&v, &d.table)?;
if let Some(p) = card.params.first() {
return Err(SqlError::at(
v.line,
v.col,
format!(
"${} is a query-card parameter \u{2014} sql run takes literal values; `sql compile` makes cards",
p.n
),
));
}
Ok(card)
}
fn parse_one_select(select: &str) -> Result<CreateView, SqlError> {
let toks = lex(select)?;
let mut p = P::new(&toks);
let t = p.peek();
let (line, col) = (t.line, t.col);
p.expect_kw("select", "\u{2014} sql run takes one SELECT")?;
let v = parse_view::parse_select_body(&mut p, "select".into(), line, col)?;
while p.eat_sym(';') {}
if !matches!(p.peek().tok, Tok::Eof) {
return Err(
p.err_here("expected the end of the SELECT \u{2014} sql run takes one statement")
);
}
Ok(v)
}
pub fn table_ddl(declaration: &[String]) -> Result<String, DeclarationError> {
let d = declared::read(declaration)?;
let t = &d.table;
let mut out = String::new();
let mut lost: Vec<String> = Vec::new();
if d.prefix != format!("{}:", t.name) {
lost.push(format!("PREFIX {}", d.prefix));
}
out.push_str(&format!("CREATE TABLE {} (\n", ident(&t.name)?));
let mut lines = Vec::new();
for (c, ty) in &t.columns {
let pk = if *c == t.pk { " PRIMARY KEY" } else { "" };
lines.push(format!(" {} {}{pk}", ident(c)?, sql_type(*ty)));
}
out.push_str(&lines.join(",\n"));
out.push_str("\n);\n");
indexes(t, &mut out)?;
orderpaths(t, &mut out, &mut lost)?;
lost.extend(d.beyond_sql.iter().map(|words| words.join(" ")));
for clause in lost {
out.push_str(&format!("-- not carried by SQL: {clause}\n"));
}
Ok(out)
}
fn indexes(t: &Table, out: &mut String) -> Result<(), DeclarationError> {
for ix in &t.indexes {
let unique = if ix.unique { "UNIQUE " } else { "" };
out.push_str(&format!(
"CREATE {unique}INDEX ON {} ({})",
ident(&t.name)?,
ident(&ix.column)?
));
if !ix.values.is_empty() {
out.push_str(&format!(" INCLUDE ({})", idents(&ix.values)?));
}
out.push_str(";\n");
}
Ok(())
}
fn orderpaths(t: &Table, out: &mut String, lost: &mut Vec<String>) -> Result<(), DeclarationError> {
for op in &t.orderpaths {
if let [(c, true)] = op.on.as_slice() {
let stmt = format!(
"CREATE INDEX {} ON {} ({} DESC);\n",
ident(&op.name)?,
ident(&t.name)?,
ident(c)?
);
out.push_str(&stmt);
continue;
}
if op.on.len() < 2 {
let on: Vec<String> = op
.on
.iter()
.map(|(c, desc)| if *desc { format!("{c} DESC") } else { c.clone() })
.collect();
lost.push(format!("ORDERPATH {} ON {}", op.name, on.join(" THEN ")));
continue;
}
let cols = op
.on
.iter()
.map(|(c, desc)| Ok(format!("{}{}", ident(c)?, if *desc { " DESC" } else { "" })))
.collect::<Result<Vec<String>, DeclarationError>>()?
.join(", ");
out.push_str(&format!(
"CREATE INDEX {} ON {} ({cols});\n",
ident(&op.name)?,
ident(&t.name)?
));
}
Ok(())
}
fn sql_type(ty: ValType) -> &'static str {
match ty {
ValType::I64 => "bigint",
ValType::F64 => "double precision",
ValType::Str => "text",
_ => unreachable!("a declared column is i64, f64 or str"),
}
}
fn ident(name: &str) -> Result<String, DeclarationError> {
let bare = name.bytes().next().is_some_and(|b| b.is_ascii_lowercase() || b == b'_')
&& name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_');
if bare {
Ok(name.to_string())
} else if name.contains('"') {
Err(DeclarationError::Unspellable(name.to_string()))
} else {
Ok(format!("\"{name}\""))
}
}
fn idents(names: &[String]) -> Result<String, DeclarationError> {
Ok(names
.iter()
.map(|n| ident(n))
.collect::<Result<Vec<String>, DeclarationError>>()?
.join(", "))
}
#[cfg(test)]
#[path = "run_tests.rs"]
mod tests;