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, 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;
24
25/// One statement, bound.
26///
27/// Not `#[non_exhaustive]`. A new variant here is a new kind of statement, and the compiler
28/// pointing at every place that has to decide what to do with it is the whole value of the enum.
29#[derive(Debug)]
30pub enum Bound {
31    /// A query, which is the only one of these that produces rows.
32    Query(Plan),
33    /// `CREATE TABLE`.
34    CreateTable(CreateTable),
35    /// `DROP TABLE`.
36    DropTable(DropTable),
37    /// `INSERT INTO`.
38    Insert(Insert),
39}
40
41/// A bound `CREATE TABLE`.
42#[derive(Debug)]
43pub struct CreateTable {
44    /// The full name the table gets.
45    pub name: QualifiedName,
46    /// The columns, in order, with the types already resolved. For a `CREATE TABLE AS` these are
47    /// the query's output types under whatever names the statement or the query gave them.
48    pub columns: Vec<Field>,
49    /// The query to fill it from, for a `CREATE TABLE AS`.
50    pub source: Option<Plan>,
51    /// Whether an existing table of that name is left alone rather than being an error.
52    pub if_not_exists: bool,
53    /// Whether an existing table of that name is dropped first.
54    pub or_replace: bool,
55}
56
57/// A bound `DROP TABLE`.
58#[derive(Debug)]
59pub struct DropTable {
60    /// The tables to drop, already resolved. With `IF EXISTS` a name that does not resolve is not
61    /// in here at all, which is what makes running this a sequence of drops that cannot fail.
62    pub names: Vec<QualifiedName>,
63}
64
65/// A bound `INSERT`.
66#[derive(Debug)]
67pub struct Insert {
68    /// The table to append to.
69    pub name: QualifiedName,
70    /// The rows to append. The output is the table's columns, in the table's order, with the
71    /// table's types, so nothing between here and the append has a decision left to make.
72    pub source: Plan,
73}
74
75/// Binds one parsed statement against a catalog.
76///
77/// # Errors
78///
79/// If the script does not hold exactly one statement, if a name does not resolve, if a type does
80/// not work out, or if the statement uses something that is not bound yet.
81pub fn bind_statement(ast: &Ast, catalog: &Catalog) -> Result<Bound> {
82    let statement = match ast.statements.as_slice() {
83        [statement] => *statement,
84        [] => return Err(Error::binder("no statement to bind")),
85        _ => return Err(Error::not_implemented("a script of more than one statement")),
86    };
87    match statement {
88        ast::Statement::Query(query) => {
89            let mut binder = Binder::new(catalog);
90            let (root, _) = binder.bind_query(ast, query)?;
91            Ok(Bound::Query(finish(binder, root)?))
92        }
93        ast::Statement::CreateTable(index) => create_table(ast, catalog, index),
94        ast::Statement::DropTable(index) => drop_table(ast, catalog, index),
95        ast::Statement::Insert(index) => insert(ast, catalog, index),
96    }
97}
98
99/// Parses and binds one statement, which is the whole front end in one call.
100///
101/// # Errors
102///
103/// Anything the parser or the binder reports.
104pub fn bind_statement_sql(sql: &str, catalog: &Catalog) -> Result<Bound> {
105    let ast = parse_ast(sql)?;
106    bind_statement(&ast, catalog)
107}
108
109/// Roots a binder's plan and checks it.
110fn finish(binder: Binder<'_>, root: rudb_plan::NodeRef) -> Result<Plan> {
111    let mut plan = binder.into_plan();
112    plan.set_root(root);
113    plan.validate()?;
114    Ok(plan)
115}
116
117fn create_table(ast: &Ast, catalog: &Catalog, index: ast::CreateTableRef) -> Result<Bound> {
118    let written = ast.create_table(index);
119    if written.temporary {
120        // A temporary table lives in the `temp` catalog and is dropped when the connection goes,
121        // and there is neither a `temp` catalog nor a connection yet. Making one in `memory` that
122        // never goes away would answer a later `SELECT` with rows DuckDB would not have.
123        return Err(Error::not_implemented("CREATE TEMPORARY TABLE"));
124    }
125    if written.if_not_exists && written.or_replace {
126        return Err(Error::binder("OR REPLACE cannot be used together with IF NOT EXISTS"));
127    }
128    let parts: Vec<&str> = ast.name(written.name).collect();
129    let name = catalog.resolve_for_create(&parts)?;
130    let defs = ast.column_defs(written.columns);
131    let (columns, source) = if written.query == NONE {
132        let mut columns = Vec::with_capacity(defs.len());
133        for def in defs {
134            let text = ast.string(def.ty);
135            if text.is_empty() {
136                return Err(Error::binder(format!(
137                    "Column \"{}\" was declared without a type",
138                    ast.string(def.name)
139                )));
140            }
141            let ty = LogicalType::parse(text)?;
142            let column = ast.string(def.name);
143            columns.push(if def.not_null {
144                Field::required(column, ty)
145            } else {
146                Field::new(column, ty)
147            });
148        }
149        (columns, None)
150    } else {
151        let mut binder = Binder::new(catalog);
152        let (root, scope) = binder.bind_query(ast, written.query)?;
153        if defs.len() > scope.len() {
154            // DuckDB's sentence, typo and all. A column list shorter than the query is fine and
155            // renames a prefix, so only this direction is an error.
156            return Err(Error::binder("Target table has more colum names than query result."));
157        }
158        let mut columns = Vec::with_capacity(scope.len());
159        for (at, column) in scope.columns.iter().enumerate() {
160            let named = match defs.get(at) {
161                Some(def) => ast.string(def.name).to_string(),
162                None => column.name.clone(),
163            };
164            columns.push(Field::new(named, column.ty.clone()));
165        }
166        if defs.is_empty() {
167            deduplicate(&mut columns);
168        }
169        (columns, Some(finish(binder, root)?))
170    };
171    duplicate_check(&columns)?;
172    Ok(Bound::CreateTable(CreateTable {
173        name,
174        columns,
175        source,
176        if_not_exists: written.if_not_exists,
177        or_replace: written.or_replace,
178    }))
179}
180
181/// Renames the columns a query repeated, which is what makes `CREATE TABLE t AS SELECT 1 AS a, 2 AS
182/// a` a table rather than an error.
183///
184/// A query is allowed to produce two columns of one name and `SELECT 1 AS a, 2 AS a` prints two
185/// columns called `a`, so a statement that turns a query into a table has to decide what to do with
186/// that, and DuckDB renames rather than refusing. The suffix is `_1`, then `_2`, counting up until
187/// the name is free, so a query that already has an `a_1` in it pushes the renamed column to `a_2`
188/// rather than colliding with it.
189///
190/// This only runs when the statement wrote no column list. With a list, even a short one, duckdb
191/// v1.4.1 takes the names as they come and a repeat is an error, so `CREATE TABLE t (z) AS SELECT 1
192/// AS a, 2 AS a` is a table of `z` and `a` and adding a third `a` to that query is a refusal.
193fn deduplicate(columns: &mut [Field]) {
194    for at in 0..columns.len() {
195        let taken = |name: &str, upto: usize, columns: &[Field]| {
196            columns[..upto].iter().any(|held| same_name(&held.name, name))
197        };
198        if !taken(&columns[at].name, at, columns) {
199            continue;
200        }
201        let mut suffix = 1;
202        let mut candidate = format!("{}_{suffix}", columns[at].name);
203        while taken(&candidate, at, columns) {
204            suffix += 1;
205            candidate = format!("{}_{suffix}", columns[at].name);
206        }
207        columns[at].name = candidate;
208    }
209}
210
211fn drop_table(ast: &Ast, catalog: &Catalog, index: ast::DropTableRef) -> Result<Bound> {
212    let written = ast.drop_table(index);
213    let mut names = Vec::new();
214    for &name in ast.name_list(written.names) {
215        let parts: Vec<&str> = ast.name(name).collect();
216        match catalog.resolve(&parts) {
217            Ok(resolved) => names.push(resolved),
218            Err(error) if written.if_exists => drop(error),
219            Err(error) => return Err(error),
220        }
221    }
222    Ok(Bound::DropTable(DropTable { names }))
223}
224
225fn insert(ast: &Ast, catalog: &Catalog, index: ast::InsertRef) -> Result<Bound> {
226    let written = ast.insert(index);
227    let parts: Vec<&str> = ast.name(written.name).collect();
228    let name = catalog.resolve(&parts)?;
229    let fields: Vec<Field> = catalog.table(&name)?.columns().to_vec();
230
231    // Which table column each source column lands in. Without a column list that is the first n
232    // columns in order, and with one it is whatever the list says, which is also the check that
233    // the list names columns the table has and names none of them twice.
234    let targets: Vec<usize> = if written.columns.is_empty() {
235        (0..fields.len()).collect()
236    } else {
237        let mut targets = Vec::new();
238        for column in ast.name(written.columns) {
239            let at = fields.iter().position(|field| same_name(&field.name, column)).ok_or_else(
240                || {
241                    Error::binder(format!(
242                        "Table \"{}\" does not have a column named \"{column}\"",
243                        name.table
244                    ))
245                },
246            )?;
247            if targets.contains(&at) {
248                return Err(Error::binder(format!(
249                    "Column \"{column}\" is named twice in the same INSERT"
250                )));
251            }
252            targets.push(at);
253        }
254        targets
255    };
256
257    let mut binder = Binder::new(catalog);
258    let (root, scope) = binder.bind_query(ast, written.source)?;
259    if scope.len() != targets.len() {
260        return Err(Error::binder(format!(
261            "Table \"{}\" has {} columns but {} values were supplied",
262            name.table,
263            targets.len(),
264            scope.len()
265        )));
266    }
267
268    // The projection that makes the source look exactly like the table. Every column the statement
269    // did not name becomes a null of the column's own type, so the append never has to know that a
270    // column list was written at all.
271    let mut exprs: Vec<ExprRef> = Vec::with_capacity(fields.len());
272    let mut names = Vec::with_capacity(fields.len());
273    for (at, field) in fields.iter().enumerate() {
274        let expr = match targets.iter().position(|&target| target == at) {
275            Some(from) => {
276                let column = &scope.columns[from];
277                let expr =
278                    binder.plan_mut().add_expr(Expr::Column(column.binding), column.ty.clone());
279                binder.cast_to(expr, &field.ty)
280            }
281            None => {
282                // A typed null rather than `add_constant`, which would give it the null type and
283                // make the column's type depend on whether a row happened to be inserted into it.
284                let value = binder.plan_mut().add_value(Value::Null);
285                binder.plan_mut().add_expr(Expr::Constant(value), field.ty.clone())
286            }
287        };
288        exprs.push(expr);
289        let interned = binder.plan_mut().intern(&field.name);
290        names.push(interned);
291    }
292    let exprs = binder.plan_mut().add_expr_list(&exprs);
293    let names = binder.plan_mut().add_name_list(&names);
294    let index = binder.fresh_index();
295    let root = binder.plan_mut().add_node(Node::Project { input: root, index, exprs, names });
296    Ok(Bound::Insert(Insert { name, source: finish(binder, root)? }))
297}