Skip to main content

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