use crate::{QueryCard, SqlError, lex, parse, schema, viewplan};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Served {
Yes {
paths: Vec<String>,
view: Option<Vec<String>>,
card: Option<QueryCard>,
},
No {
reason: String,
},
}
impl Served {
pub fn is_served(&self) -> bool {
matches!(self, Served::Yes { .. })
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlanEntry {
pub name: String,
pub table: String,
pub line: u32,
pub served: Served,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Plan {
pub declares: Vec<Vec<String>>,
pub queries: Vec<PlanEntry>,
pub notes: Vec<String>,
pub dropped: Vec<(String, String)>,
}
impl Plan {
pub fn unserved(&self) -> usize {
self.queries.iter().filter(|q| !q.served.is_served()).count()
}
}
pub fn plan(sql: &str) -> Result<Plan, SqlError> {
let toks = lex::lex(sql)?;
let stmts = parse::parse_script(&toks)?;
let ((tables, views, mut notes), dropped) = schema::build_lenient(&stmts);
let declares: Vec<Vec<String>> = tables.iter().map(schema::declare_argv).collect();
let mut queries = Vec::with_capacity(views.len());
for v in &views {
let served = match tables.iter().find(|t| t.name == v.table) {
None => Served::No {
reason: match dropped.iter().find(|(n, _)| *n == v.table) {
Some((_, why)) => {
format!("its table '{}' was not declarable — {why}", v.table)
}
None => format!(
"FROM unknown table '{}' — CREATE TABLE it first (this compiler is whole-file: declare, then view)",
v.table
),
},
},
Some(t) => match viewplan::plan_view(v, t, &mut notes) {
Ok(viewplan::Planned::View(argv)) => {
Served::Yes { paths: paths_in(&argv, &t.name), view: Some(argv), card: None }
}
Ok(viewplan::Planned::Card(card)) => Served::Yes {
paths: paths_in(&card.argv, &t.name),
view: None,
card: Some(card),
},
Err(e) => Served::No { reason: e.message },
},
};
queries.push(PlanEntry {
name: v.name.clone(),
table: v.table.clone(),
line: v.line,
served,
});
}
Ok(Plan { declares, queries, notes, dropped })
}
fn paths_in(argv: &[String], table: &str) -> Vec<String> {
let prefix = format!("{table}.");
let mut out: Vec<String> = Vec::new();
for a in argv {
if a.starts_with(&prefix) && !out.contains(a) {
out.push(a.clone());
}
}
out
}