rudb_bind/statement.rs
1//! From an `Ast` to a `Bound`, which is a statement rather than a query.
2//!
3//! A `SELECT` binds to a [`Plan`] and nothing else, and that is why [`bind`](crate::bind) can hand
4//! one back. `CREATE TABLE`, `DROP TABLE` and `INSERT` are not plans and are deliberately not being
5//! made into plans. A `Node::CreateTable` would be a node with no columns, no rows, no cost and no
6//! reason to be pushed past anything, which is to say a node the optimizer has to be told to leave
7//! alone and the executor has to special case at the root. `spec/09-optimizer.md` section 9.1 says
8//! every node in a plan produces rows, and a DDL statement does not, so it goes beside the plan and
9//! not inside it.
10//!
11//! What each variant carries is the statement with every name and type already resolved, so the
12//! thing that runs it does catalog calls and nothing else. An `INSERT` in particular arrives with
13//! a plan whose output is exactly the target's columns in the target's order and the target's
14//! types, with the casts and the nulls for unmentioned columns already in it, so appending is a
15//! loop over chunks.
16
17use rudb_catalog::{Catalog, Entry, QualifiedName, duplicate_check, same_name};
18use rudb_common::{Error, Field, LogicalType, Result, Session, Value};
19use rudb_parse::ast::{self, Ast};
20use rudb_parse::{NONE, deparse, parse_ast};
21use rudb_plan::{Expr, ExprRef, Node, Plan};
22
23use crate::binder::Binder;
24use crate::parameters::Parameters;
25
26/// One statement, bound.
27///
28/// Not `#[non_exhaustive]`. A new variant here is a new kind of statement, and the compiler
29/// pointing at every place that has to decide what to do with it is the whole value of the enum.
30#[derive(Debug)]
31pub enum Bound {
32 /// A query, which is the only one of these that produces rows.
33 Query(Plan),
34 /// `CREATE TABLE`.
35 CreateTable(CreateTable),
36 /// `CREATE VIEW`.
37 CreateView(CreateView),
38 /// `DROP TABLE` or `DROP VIEW`.
39 DropTable(DropTable),
40 /// `INSERT INTO`.
41 Insert(Insert),
42 /// `SET name = value`, or `RESET name`, which is the same thing with no value.
43 Setting(Setting),
44 /// Flushes a persistent database snapshot.
45 Checkpoint,
46 /// `EXPLAIN` over a query, holding the plan of the query rather than the query.
47 ///
48 /// The same `Plan` a [`Bound::Query`] would have carried, bound the same way and by the same
49 /// code. What makes it an explain is that the layer above optimizes it and prints it instead
50 /// of running it, which is the point: a plan that was built differently because somebody asked
51 /// to see it is not the plan that runs.
52 ///
53 /// With `analyze` set the layer above runs it as well and prints what happened on it. Still the
54 /// same plan, for the same reason.
55 Explain { plan: Plan, analyze: bool },
56}
57
58/// A bound `SET` or `RESET`.
59///
60/// The value is a [`Value`] rather than an expression, because every setting there is takes a
61/// string or a number and nothing that runs one wants a plan. What a setting does with the value it
62/// gets is the setting's own business and is decided a layer up, since the binder has no idea what
63/// settings exist.
64///
65/// The narrow part of that is that the value has to already be a constant. `SET threads = 2 + 2` is
66/// four in DuckDB and is refused here, because folding it needs the expression rewriter and the
67/// rewriter is two layers above the binder. Nothing writes arithmetic in a `SET` and the refusal
68/// says what it is, so this waits for a reason to move.
69#[derive(Debug)]
70pub struct Setting {
71 /// The setting name, as written.
72 pub name: String,
73 /// The scope word, if one was written.
74 pub scope: ast::Scope,
75 /// The value, or `None` for a `RESET`.
76 pub value: Option<Value>,
77 /// Whether the statement was written as a bare `PRAGMA name`, which carries its value in it.
78 pub pragma: bool,
79}
80
81/// A bound `CREATE TABLE`.
82#[derive(Debug)]
83pub struct CreateTable {
84 /// The full name the table gets.
85 pub name: QualifiedName,
86 /// The columns, in order, with the types already resolved. For a `CREATE TABLE AS` these are
87 /// the query's output types under whatever names the statement or the query gave them.
88 pub columns: Vec<Field>,
89 /// The query to fill it from, for a `CREATE TABLE AS`.
90 pub source: Option<Plan>,
91 /// Whether an existing table of that name is left alone rather than being an error.
92 pub if_not_exists: bool,
93 /// Whether an existing table of that name is dropped first.
94 pub or_replace: bool,
95}
96
97/// A bound `CREATE VIEW`.
98///
99/// The body is the text that was written rather than the plan it bound to. It was bound once on the
100/// way through here, which is what refuses a view over a table that is not there, and the plan that
101/// came out of that is then thrown away, because a view follows the tables underneath it and a plan
102/// cannot. See [`rudb_catalog::View`].
103#[derive(Debug)]
104pub struct CreateView {
105 /// The full name the view gets.
106 pub name: QualifiedName,
107 /// The body, as written.
108 pub sql: String,
109 /// The whole statement written back out, which is what `duckdb_views()` reports as `sql`.
110 ///
111 /// Written here because this is the last place the tree is in reach. See
112 /// [`rudb_catalog::View::statement`] for what the column is and why it is not the text.
113 pub statement: String,
114 /// The column names the statement gave, which rename a prefix of what the body produces.
115 pub aliases: Vec<String>,
116 /// Whether an existing entry of that name is left alone rather than being an error.
117 pub if_not_exists: bool,
118 /// Whether an existing entry of that name is dropped first.
119 pub or_replace: bool,
120 /// The columns binding the body produced, after the alias list was applied.
121 ///
122 /// Worked out here because this is where the body is bound, and carried to the catalog because
123 /// that is where `duckdb_columns()` and `duckdb_views()` read it from. See the doc on
124 /// `rudb_catalog::View` for why the catalog keeps a list it will have to refresh later.
125 pub columns: Vec<Field>,
126}
127
128/// A bound `DROP TABLE` or `DROP VIEW`.
129#[derive(Debug)]
130pub struct DropTable {
131 /// The tables or views to drop, already resolved. With `IF EXISTS` a name that does not resolve
132 /// is not in here at all, which is what makes running this a sequence of drops that cannot
133 /// fail for being missing. Dropping one of these as the wrong type still can, because `DROP
134 /// TABLE IF EXISTS v` where `v` is a view is an error in DuckDB and was measured to be one.
135 pub names: Vec<QualifiedName>,
136 /// Which of the two the statement said it was dropping.
137 pub kind: Entry,
138}
139
140/// A bound `INSERT`.
141#[derive(Debug)]
142pub struct Insert {
143 /// The table to append to.
144 pub name: QualifiedName,
145 /// The rows to append. The output is the table's columns, in the table's order, with the
146 /// table's types, so nothing between here and the append has a decision left to make.
147 pub source: Plan,
148}
149
150/// Binds one parsed statement against a catalog.
151///
152/// # Errors
153///
154/// If the script does not hold exactly one statement, if a name does not resolve, if a type does
155/// not work out, or if the statement uses something that is not bound yet.
156pub fn bind_statement(ast: &Ast, catalog: &Catalog) -> Result<Bound> {
157 bind_statement_with(ast, catalog, &Parameters::new(), &Session::new())
158}
159
160/// Binds one parsed statement against a catalog, with values for its parameters and its settings.
161///
162/// This is the prepared statement path. The statement is parsed once and bound once per set of
163/// values, so a parameter is a constant by the time the plan exists and everything after the binder
164/// sees an ordinary query. That is why there is no parameter in `rudb_plan::Expr`.
165///
166/// # Errors
167///
168/// Everything [`bind_statement`] reports, plus an error for a parameter that was given no value.
169pub fn bind_statement_with(
170 ast: &Ast,
171 catalog: &Catalog,
172 parameters: &Parameters,
173 session: &Session,
174) -> Result<Bound> {
175 let statement = match ast.statements.as_slice() {
176 [statement] => *statement,
177 [] => return Err(Error::binder("no statement to bind")),
178 _ => return Err(Error::not_implemented("a script of more than one statement")),
179 };
180 match statement {
181 ast::Statement::Query(query) => {
182 let mut binder = Binder::with(catalog, parameters, session);
183 let (root, _) = binder.bind_query(ast, query)?;
184 Ok(Bound::Query(finish(binder, root)?))
185 }
186 ast::Statement::CreateTable(index) => {
187 create_table(ast, catalog, parameters, session, index)
188 }
189 ast::Statement::CreateView(index) => create_view(ast, catalog, parameters, session, index),
190 ast::Statement::DropTable(index) => drop_table(ast, catalog, index),
191 ast::Statement::Insert(index) => insert(ast, catalog, parameters, session, index),
192 ast::Statement::Set(index) | ast::Statement::Reset(index) => {
193 setting(ast, catalog, parameters, session, index)
194 }
195 ast::Statement::Checkpoint => Ok(Bound::Checkpoint),
196 ast::Statement::Explain { query, analyze } => {
197 let mut binder = Binder::with(catalog, parameters, session);
198 let (root, _) = binder.bind_query(ast, query)?;
199 Ok(Bound::Explain { plan: finish(binder, root)?, analyze })
200 }
201 }
202}
203
204/// Parses and binds one statement, which is the whole front end in one call.
205///
206/// # Errors
207///
208/// Anything the parser or the binder reports.
209pub fn bind_statement_sql(sql: &str, catalog: &Catalog) -> Result<Bound> {
210 let ast = parse_ast(sql)?;
211 bind_statement(&ast, catalog)
212}
213
214/// Roots a binder's plan and checks it.
215fn finish(binder: Binder<'_>, root: rudb_plan::NodeRef) -> Result<Plan> {
216 let mut plan = binder.into_plan();
217 plan.set_root(root);
218 plan.validate()?;
219 Ok(plan)
220}
221
222fn create_table(
223 ast: &Ast,
224 catalog: &Catalog,
225 parameters: &Parameters,
226 session: &Session,
227 index: ast::CreateTableRef,
228) -> Result<Bound> {
229 let written = ast.create_table(index);
230 if written.temporary {
231 // A temporary table lives in the `temp` catalog and is dropped when the connection goes,
232 // and there is neither a `temp` catalog nor a connection yet. Making one in `memory` that
233 // never goes away would answer a later `SELECT` with rows DuckDB would not have.
234 return Err(Error::not_implemented("CREATE TEMPORARY TABLE"));
235 }
236 let parts: Vec<&str> = ast.name(written.name).collect();
237 let name = catalog.resolve_for_create(&parts)?;
238 let defs = ast.column_defs(written.columns);
239 let (columns, source) = if written.query == NONE {
240 let mut columns = Vec::with_capacity(defs.len());
241 for def in defs {
242 let text = ast.string(def.ty);
243 if text.is_empty() {
244 return Err(Error::binder(format!(
245 "Column \"{}\" was declared without a type",
246 ast.string(def.name)
247 )));
248 }
249 let ty = LogicalType::parse(text)?;
250 let column = ast.string(def.name);
251 columns.push(if def.not_null {
252 Field::required(column, ty)
253 } else {
254 Field::new(column, ty)
255 });
256 }
257 (columns, None)
258 } else {
259 let mut binder = Binder::with(catalog, parameters, session);
260 let (root, scope) = binder.bind_query(ast, written.query)?;
261 if defs.len() > scope.len() {
262 // DuckDB's sentence, typo and all. A column list shorter than the query is fine and
263 // renames a prefix, so only this direction is an error.
264 return Err(Error::binder("Target table has more colum names than query result."));
265 }
266 let mut columns = Vec::with_capacity(scope.len());
267 for (at, column) in scope.columns.iter().enumerate() {
268 let named = match defs.get(at) {
269 Some(def) => ast.string(def.name).to_string(),
270 None => column.name.clone(),
271 };
272 columns.push(Field::new(named, column.ty.clone()));
273 }
274 if defs.is_empty() {
275 deduplicate(&mut columns);
276 }
277 (columns, Some(finish(binder, root)?))
278 };
279 duplicate_check(&columns)?;
280 Ok(Bound::CreateTable(CreateTable {
281 name,
282 columns,
283 source,
284 if_not_exists: written.if_not_exists,
285 or_replace: written.or_replace,
286 }))
287}
288
289/// Renames the columns a query repeated, which is what makes `CREATE TABLE t AS SELECT 1 AS a, 2 AS
290/// a` a table rather than an error.
291///
292/// A query is allowed to produce two columns of one name and `SELECT 1 AS a, 2 AS a` prints two
293/// columns called `a`, so a statement that turns a query into a table has to decide what to do with
294/// that, and DuckDB renames rather than refusing. The suffix is `_1`, then `_2`, counting up until
295/// the name is free, so a query that already has an `a_1` in it pushes the renamed column to `a_2`
296/// rather than colliding with it.
297///
298/// This only runs when the statement wrote no column list. With a list, even a short one, duckdb
299/// v1.4.1 takes the names as they come and a repeat is an error, so `CREATE TABLE t (z) AS SELECT 1
300/// AS a, 2 AS a` is a table of `z` and `a` and adding a third `a` to that query is a refusal.
301fn deduplicate(columns: &mut [Field]) {
302 for at in 0..columns.len() {
303 let taken = |name: &str, upto: usize, columns: &[Field]| {
304 columns[..upto].iter().any(|held| same_name(&held.name, name))
305 };
306 if !taken(&columns[at].name, at, columns) {
307 continue;
308 }
309 let mut suffix = 1;
310 let mut candidate = format!("{}_{suffix}", columns[at].name);
311 while taken(&candidate, at, columns) {
312 suffix += 1;
313 candidate = format!("{}_{suffix}", columns[at].name);
314 }
315 columns[at].name = candidate;
316 }
317}
318
319/// Binds a `CREATE VIEW`, which means binding the body and then throwing the plan away.
320///
321/// Throwing it away is the point. The body is bound here so that a view over a table that is not
322/// there is refused now rather than at the first select, and so that the column list can be checked
323/// against what the body actually produces. What the catalog keeps is the text, because a view
324/// follows the tables underneath it and a plan is a photograph of the day it was built.
325fn create_view(
326 ast: &Ast,
327 catalog: &Catalog,
328 parameters: &Parameters,
329 session: &Session,
330 index: ast::CreateViewRef,
331) -> Result<Bound> {
332 let written = ast.create_view(index);
333 if written.temporary {
334 // Same reason as a temporary table: there is no `temp` catalog and no connection for one to
335 // belong to, and a view in `memory` that never goes away is not the thing that was asked
336 // for.
337 return Err(Error::not_implemented("CREATE TEMPORARY VIEW"));
338 }
339 let parts: Vec<&str> = ast.name(written.name).collect();
340 let name = catalog.resolve_for_create(&parts)?;
341 let aliases: Vec<String> = ast.name(written.columns).map(str::to_string).collect();
342
343 let mut binder = Binder::with(catalog, parameters, session);
344 let (_, mut scope) = binder.bind_query(ast, written.query)?;
345 if aliases.len() > scope.len() {
346 return Err(Error::binder("More VIEW aliases than columns in query result"));
347 }
348 if !aliases.is_empty() {
349 let written: Vec<&str> = aliases.iter().map(String::as_str).collect();
350 scope.rename(&written, "unnamed_subquery")?;
351 }
352
353 Ok(Bound::CreateView(CreateView {
354 name,
355 sql: ast.string(written.sql).to_string(),
356 statement: deparse::create_view(ast, index),
357 aliases,
358 if_not_exists: written.if_not_exists,
359 or_replace: written.or_replace,
360 columns: scope.fields(),
361 }))
362}
363
364fn drop_table(ast: &Ast, catalog: &Catalog, index: ast::DropTableRef) -> Result<Bound> {
365 let written = ast.drop_table(index);
366 let kind = if written.view { Entry::View } else { Entry::Table };
367 let mut names = Vec::new();
368 for &name in ast.name_list(written.names) {
369 let parts: Vec<&str> = ast.name(name).collect();
370 // The statement said which of the two it meant, so a name that is not there is a missing
371 // one of those and not a missing table.
372 match catalog.resolve_as(&parts, kind) {
373 Ok(resolved) => names.push(resolved),
374 Err(error) if written.if_exists => drop(error),
375 Err(error) => return Err(error),
376 }
377 }
378 Ok(Bound::DropTable(DropTable { names, kind }))
379}
380
381/// Binds a `SET` or a `RESET`, which is resolving its value and nothing else.
382///
383/// The name is not checked here. The binder knows what tables exist and has no idea what settings
384/// exist, since a setting is a knob on the engine rather than an entry in a catalog, and a version
385/// of this that held the list would be the binder holding a copy of something it cannot enforce.
386fn setting(
387 ast: &Ast,
388 catalog: &Catalog,
389 parameters: &Parameters,
390 session: &Session,
391 index: ast::SettingRef,
392) -> Result<Bound> {
393 let written = ast.setting(index);
394 let name = ast.string(written.name).to_string();
395 let value = if written.value == NONE {
396 None
397 } else {
398 let mut binder = Binder::with(catalog, parameters, session);
399 let bound = binder.bind_setting_value(ast, written.value)?;
400 let Expr::Constant(value) = *binder.plan().expr(bound) else {
401 return Err(Error::not_implemented(format!(
402 "a value for {name} that is not a constant"
403 )));
404 };
405 Some(binder.plan().value(value).clone())
406 };
407 Ok(Bound::Setting(Setting { name, scope: written.scope, value, pragma: written.pragma }))
408}
409
410fn insert(
411 ast: &Ast,
412 catalog: &Catalog,
413 parameters: &Parameters,
414 session: &Session,
415 index: ast::InsertRef,
416) -> Result<Bound> {
417 let written = ast.insert(index);
418 let parts: Vec<&str> = ast.name(written.name).collect();
419 let name = catalog.resolve(&parts)?;
420 if catalog.entry(&name)? == Entry::View {
421 // The binary's sentence, article and all. A view has no rows of its own to append to, and
422 // an updatable view is a rule about rewriting the insert that neither database has.
423 return Err(Error::catalog(format!("{} is not an table", name.table)));
424 }
425 let fields: Vec<Field> = catalog.table(&name)?.columns().to_vec();
426
427 // Which table column each source column lands in. Without a column list that is the first n
428 // columns in order, and with one it is whatever the list says, which is also the check that
429 // the list names columns the table has and names none of them twice.
430 let targets: Vec<usize> = if written.columns.is_empty() {
431 (0..fields.len()).collect()
432 } else {
433 let mut targets = Vec::new();
434 for column in ast.name(written.columns) {
435 let at = fields.iter().position(|field| same_name(&field.name, column)).ok_or_else(
436 || {
437 Error::binder(format!(
438 "Table \"{}\" does not have a column named \"{column}\"",
439 name.table
440 ))
441 },
442 )?;
443 if targets.contains(&at) {
444 return Err(Error::binder(format!(
445 "Column \"{column}\" is named twice in the same INSERT"
446 )));
447 }
448 targets.push(at);
449 }
450 targets
451 };
452
453 let mut binder = Binder::with(catalog, parameters, session);
454 let (root, scope) = binder.bind_query(ast, written.source)?;
455 if scope.len() != targets.len() {
456 return Err(Error::binder(format!(
457 "Table \"{}\" has {} columns but {} values were supplied",
458 name.table,
459 targets.len(),
460 scope.len()
461 )));
462 }
463
464 // The projection that makes the source look exactly like the table. Every column the statement
465 // did not name becomes a null of the column's own type, so the append never has to know that a
466 // column list was written at all.
467 let mut exprs: Vec<ExprRef> = Vec::with_capacity(fields.len());
468 let mut names = Vec::with_capacity(fields.len());
469 for (at, field) in fields.iter().enumerate() {
470 let expr = match targets.iter().position(|&target| target == at) {
471 Some(from) => {
472 let column = &scope.columns[from];
473 let expr =
474 binder.plan_mut().add_expr(Expr::Column(column.binding), column.ty.clone());
475 binder.checked_cast_to(expr, &field.ty, false)?
476 }
477 None => {
478 // A typed null rather than `add_constant`, which would give it the null type and
479 // make the column's type depend on whether a row happened to be inserted into it.
480 let value = binder.plan_mut().add_value(Value::Null);
481 binder.plan_mut().add_expr(Expr::Constant(value), field.ty.clone())
482 }
483 };
484 exprs.push(expr);
485 let interned = binder.plan_mut().intern(&field.name);
486 names.push(interned);
487 }
488 let exprs = binder.plan_mut().add_expr_list(&exprs);
489 let names = binder.plan_mut().add_name_list(&names);
490 let index = binder.fresh_index();
491 let root = binder.plan_mut().add_node(Node::Project { input: root, index, exprs, names });
492 Ok(Bound::Insert(Insert { name, source: finish(binder, root)? }))
493}