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