kevy_sql/plan.rs
1//! `plan` — compile a schema and report **every** query's fate, instead
2//! of stopping at the first one that cannot be served.
3//!
4//! [`compile`](crate::compile) is the build-time entry: one unservable
5//! view is a compile error, which is right when the output is commands
6//! you are about to apply. A migration plan is the other shape. The
7//! person reading it arrived with a schema and forty queries and wants
8//! one answer — *which of these work here, and what do the rest need?*
9//! Stopping at the first refusal answers that one fortieth of the way.
10//!
11//! The line between the two failure kinds is deliberate:
12//!
13//! * **A DDL error is still fatal.** If `CREATE TABLE` does not parse
14//! there is no schema, and a plan against no schema is a fiction.
15//! * **A view that cannot be served is an entry, not an error** — that
16//! is precisely what the plan exists to report. The refusal text
17//! already names the `CREATE INDEX` that would fix it, so it is
18//! carried verbatim rather than restated worse.
19
20use crate::{QueryCard, SqlError, lex, parse, schema, viewplan};
21
22/// Whether a declared query can be served, and by what.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub enum Served {
25 /// Served by declared access paths, named.
26 Yes {
27 /// The `table.column` paths this query rides, in argv order.
28 paths: Vec<String>,
29 /// The `VIEW.CREATE` argv, when the engine can hold the whole
30 /// query as a view.
31 view: Option<Vec<String>>,
32 /// The runtime template, when it is a card instead.
33 card: Option<QueryCard>,
34 },
35 /// Not served, with the compiler's own refusal — which names the
36 /// alternative rather than only saying no.
37 No {
38 /// The refusal, verbatim.
39 reason: String,
40 },
41}
42
43impl Served {
44 /// Whether this query can be served as declared.
45 pub fn is_served(&self) -> bool {
46 matches!(self, Served::Yes { .. })
47 }
48}
49
50/// One query's row in the plan.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct PlanEntry {
53 /// The view name.
54 pub name: String,
55 /// The table it reads.
56 pub table: String,
57 /// 1-based source line, so a refusal points back at the SQL.
58 pub line: u32,
59 /// The verdict.
60 pub served: Served,
61}
62
63/// A migration plan: what to declare, and what becomes of each query.
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct Plan {
66 /// `TABLE.DECLARE` argv per table, declaration order.
67 pub declares: Vec<Vec<String>>,
68 /// Every `CREATE VIEW`, served or not, declaration order.
69 pub queries: Vec<PlanEntry>,
70 /// Honest-mapping notes, as [`crate::Compilation::notes`].
71 pub notes: Vec<String>,
72 /// Tables (and stray indexes) that could NOT be declared:
73 /// `(name, named reason)`. The charter's migration bar reads
74 /// "every type either moved or named" — this is the named half.
75 pub dropped: Vec<(String, String)>,
76}
77
78impl Plan {
79 /// How many queries cannot be served as declared.
80 pub fn unserved(&self) -> usize {
81 self.queries.iter().filter(|q| !q.served.is_served()).count()
82 }
83}
84
85/// Plan a whole SQL file: DDL becomes declarations, each `CREATE VIEW`
86/// becomes an entry saying whether it can be served and by what.
87///
88/// Errors only on the schema itself — a file whose DDL does not parse
89/// has no plan. A view that cannot be served comes back as an entry.
90pub fn plan(sql: &str) -> Result<Plan, SqlError> {
91 let toks = lex::lex(sql)?;
92 let stmts = parse::parse_script(&toks)?;
93 let ((tables, views, mut notes), dropped) = schema::build_lenient(&stmts);
94 let declares: Vec<Vec<String>> = tables.iter().map(schema::declare_argv).collect();
95 let mut queries = Vec::with_capacity(views.len());
96 for v in &views {
97 let served = match tables.iter().find(|t| t.name == v.table) {
98 None => Served::No {
99 reason: match dropped.iter().find(|(n, _)| *n == v.table) {
100 Some((_, why)) => {
101 format!("its table '{}' was not declarable — {why}", v.table)
102 }
103 None => format!(
104 "FROM unknown table '{}' — CREATE TABLE it first (this compiler is whole-file: declare, then view)",
105 v.table
106 ),
107 },
108 },
109 Some(t) => match viewplan::plan_view(v, t, &mut notes) {
110 Ok(viewplan::Planned::View(argv)) => {
111 Served::Yes { paths: paths_in(&argv, &t.name), view: Some(argv), card: None }
112 }
113 Ok(viewplan::Planned::Card(card)) => Served::Yes {
114 paths: paths_in(&card.argv, &t.name),
115 view: None,
116 card: Some(card),
117 },
118 Err(e) => Served::No { reason: e.message },
119 },
120 };
121 queries.push(PlanEntry {
122 name: v.name.clone(),
123 table: v.table.clone(),
124 line: v.line,
125 served,
126 });
127 }
128 Ok(Plan { declares, queries, notes, dropped })
129}
130
131/// The declared paths an argv rides, read off the argv rather than
132/// re-derived: both `VIEW.CREATE` and `IDX.QUERY` name their paths as
133/// `table.column`, so there is nothing here to infer.
134fn paths_in(argv: &[String], table: &str) -> Vec<String> {
135 let prefix = format!("{table}.");
136 let mut out: Vec<String> = Vec::new();
137 for a in argv {
138 if a.starts_with(&prefix) && !out.contains(a) {
139 out.push(a.clone());
140 }
141 }
142 out
143}