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