Skip to main content

risingwave_frontend/binder/
insert.rs

1// Copyright 2022 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::{HashMap, HashSet};
16
17use anyhow::Context;
18use itertools::Itertools;
19use risingwave_common::acl::AclMode;
20use risingwave_common::catalog::{ColumnCatalog, Schema, TableVersionId};
21use risingwave_common::types::DataType;
22use risingwave_common::util::iter_util::ZipEqFast;
23use risingwave_pb::expr::expr_node::Type as ExprType;
24use risingwave_pb::plan_common::DefaultColumnDesc;
25use risingwave_pb::plan_common::column_desc::GeneratedOrDefaultColumn;
26use risingwave_sqlparser::ast::{Ident, ObjectName, Query, SelectItem};
27
28use super::BoundQuery;
29use super::statement::RewriteExprsRecursive;
30use crate::binder::{Binder, Clause};
31use crate::catalog::TableId;
32use crate::error::{ErrorCode, Result, RwError};
33use crate::expr::{Expr, ExprImpl, FunctionCall, InputRef};
34use crate::handler::privilege::ObjectCheckItem;
35use crate::user::UserId;
36use crate::utils::ordinal;
37
38#[derive(Debug, Clone)]
39pub struct BoundInsert {
40    /// Id of the table to perform inserting.
41    pub table_id: TableId,
42
43    /// Version id of the table.
44    pub table_version_id: TableVersionId,
45
46    /// Name of the table to perform inserting.
47    pub table_name: String,
48
49    /// All visible columns of the table, used as the output schema of `Insert` plan node if
50    /// `RETURNING` is specified.
51    pub table_visible_columns: Vec<ColumnCatalog>,
52
53    /// Owner of the table to perform inserting.
54    pub owner: UserId,
55
56    // An optional column index of row ID. If the primary key is specified by the user,
57    // this will be `None`.
58    pub row_id_index: Option<usize>,
59
60    /// User defined columns in which to insert
61    /// Is equal to [0, 2, 1] for insert statement
62    /// create table t1 (v1 int, v2 int, v3 int); insert into t1 (v1, v3, v2) values (5, 6, 7);
63    /// Empty if user does not define insert columns
64    pub column_indices: Vec<usize>,
65
66    /// Columns that user fails to specify
67    /// Will set to default value (current null)
68    pub default_columns: Vec<(usize, ExprImpl)>,
69
70    pub source: BoundQuery,
71
72    /// Used as part of an extra `Project` when the column types of the query does not match
73    /// those of the table. This does not include a simple `VALUE`. See comments in code for
74    /// details.
75    pub cast_exprs: Vec<ExprImpl>,
76
77    // used for the 'RETURNING" keyword to indicate the returning items and schema
78    // if the list is empty and the schema is None, the output schema will be a INT64 as the
79    // affected row cnt
80    pub returning_list: Vec<ExprImpl>,
81
82    pub returning_schema: Option<Schema>,
83}
84
85impl RewriteExprsRecursive for BoundInsert {
86    fn rewrite_exprs_recursive(&mut self, rewriter: &mut impl crate::expr::ExprRewriter) {
87        self.source.rewrite_exprs_recursive(rewriter);
88
89        let new_cast_exprs = std::mem::take(&mut self.cast_exprs)
90            .into_iter()
91            .map(|expr| rewriter.rewrite_expr(expr))
92            .collect::<Vec<_>>();
93        self.cast_exprs = new_cast_exprs;
94
95        let new_returning_list = std::mem::take(&mut self.returning_list)
96            .into_iter()
97            .map(|expr| rewriter.rewrite_expr(expr))
98            .collect::<Vec<_>>();
99        self.returning_list = new_returning_list;
100    }
101}
102
103impl Binder {
104    pub(super) fn bind_insert(
105        &mut self,
106        name: ObjectName,
107        cols_to_insert_by_user: Vec<Ident>,
108        source: Query,
109        returning_items: Vec<SelectItem>,
110    ) -> Result<BoundInsert> {
111        let (schema_name, table_name) = Self::resolve_schema_qualified_name(&self.db_name, &name)?;
112        // bind insert table
113        self.context.clause = Some(Clause::Insert);
114        let bound_table = self.bind_table_for_dml(schema_name.as_deref(), &table_name, true)?;
115        let table_catalog = &bound_table.table_catalog;
116        self.check_privilege(
117            ObjectCheckItem::new(
118                table_catalog.owner,
119                AclMode::Insert,
120                table_name.clone(),
121                table_catalog.id,
122            ),
123            table_catalog.database_id,
124        )?;
125
126        let has_user_specified_columns = !cols_to_insert_by_user.is_empty();
127        let table_id = table_catalog.id;
128        let owner = table_catalog.owner;
129        let table_version_id = table_catalog.version_id().expect("table must be versioned");
130        let table_visible_columns = table_catalog
131            .columns()
132            .iter()
133            .filter(|c| !c.is_hidden())
134            .cloned()
135            .collect_vec();
136        let (cols_to_insert_in_table, row_id_index) = table_catalog.columns_to_insert();
137        let cols_to_insert_in_table = cols_to_insert_in_table
138            .map(|(column, _)| column.clone())
139            .collect_vec();
140        // Reorder default columns based on `cols_to_insert_in_table`.
141        let default_columns_from_catalog = cols_to_insert_in_table
142            .iter()
143            .enumerate()
144            .filter_map(|(idx, col)| {
145                if let Some(GeneratedOrDefaultColumn::DefaultColumn(DefaultColumnDesc {
146                    expr,
147                    ..
148                })) = col.column_desc.generated_or_default_column.as_ref()
149                {
150                    Some((
151                        idx,
152                        ExprImpl::from_expr_proto(expr.as_ref().unwrap())
153                            .expect("expr in default columns corrupted"),
154                    ))
155                } else {
156                    None
157                }
158            })
159            .collect::<HashMap<_, _>>();
160
161        let generated_column_names = table_catalog
162            .generated_column_names()
163            .collect::<HashSet<_>>();
164
165        let check_generated_insert_violation = |bound_column_nums: Option<usize>| -> Result<()> {
166            let generated_column_name = if let Some(column_num) = bound_column_nums {
167                table_catalog
168                    .first_generated_column()
169                    .and_then(|(index, column_name)| {
170                        (column_num > index).then_some(column_name.to_owned())
171                    })
172            } else {
173                cols_to_insert_by_user
174                    .iter()
175                    .map(|col| col.real_value())
176                    .find(|col_name| generated_column_names.contains(col_name.as_str()))
177            };
178
179            if let Some(column_name) = generated_column_name {
180                return Err(ErrorCode::InsertViolation(format!(
181                    "cannot insert a non-DEFAULT value into column \"{0}\"\n  DETAIL: Column \"{0}\" is a generated column.",
182                    column_name
183                ))
184                .into());
185            }
186
187            Ok(())
188        };
189
190        if has_user_specified_columns {
191            check_generated_insert_violation(None)?;
192        }
193
194        if !generated_column_names.is_empty() && !returning_items.is_empty() {
195            return Err(RwError::from(ErrorCode::BindError(
196                "`RETURNING` clause is not supported for tables with generated columns".to_owned(),
197            )));
198        }
199
200        let (returning_list, fields) = self.bind_returning_list(returning_items)?;
201        let is_returning = !returning_list.is_empty();
202
203        let (mut col_indices_to_insert, default_column_indices) = get_col_indices_to_insert(
204            &cols_to_insert_in_table,
205            &cols_to_insert_by_user,
206            &table_name,
207        )?;
208        // Collect the types of columns explicitly specified by the user.
209        let expected_types: Vec<DataType> = col_indices_to_insert
210            .iter()
211            .map(|idx| cols_to_insert_in_table[*idx].data_type().clone())
212            .collect();
213
214        // Collect the nullable of columns explicitly specified by the user.
215        let nullables: Vec<(bool, &str)> = col_indices_to_insert
216            .iter()
217            .map(|idx| {
218                (
219                    cols_to_insert_in_table[*idx].nullable(),
220                    cols_to_insert_in_table[*idx].name(),
221                )
222            })
223            .collect();
224
225        // When the column types of `source` query do not match `expected_types`,
226        // casting is needed.
227        //
228        // In PG, when the `source` is a `VALUES` without order / limit / offset, special treatment
229        // is given and it is NOT equivalent to assignment cast over potential implicit cast inside.
230        // For example, the following is valid:
231        //
232        // ```sql
233        //   create table t (v1 time);
234        //   insert into t values (timestamp '2020-01-01 01:02:03'), (time '03:04:05');
235        // ```
236        //
237        // But the followings are not:
238        //
239        // ```sql
240        //   values (timestamp '2020-01-01 01:02:03'), (time '03:04:05');
241        //   insert into t values (timestamp '2020-01-01 01:02:03'), (time '03:04:05') limit 1;
242        // ```
243        //
244        // Because `timestamp` can cast to `time` in assignment context, but no casting between them
245        // is allowed implicitly.
246        //
247        // In this case, assignment cast should be used directly in `VALUES`, suppressing its
248        // internal implicit cast.
249        // In other cases, the `source` query is handled on its own and assignment cast is done
250        // afterwards.
251        let bound_query;
252        let cast_exprs;
253        let all_nullable = nullables.iter().all(|(nullable, _)| *nullable);
254
255        let bound_column_nums = match source.as_simple_values() {
256            None => {
257                bound_query = self.bind_query(&source)?;
258                if !has_user_specified_columns {
259                    check_generated_insert_violation(Some(bound_query.schema().len()))?;
260                }
261                let actual_types = bound_query.data_types();
262                let type_match = expected_types == actual_types;
263                cast_exprs = if all_nullable && type_match {
264                    vec![]
265                } else {
266                    let mut cast_exprs = actual_types
267                        .into_iter()
268                        .enumerate()
269                        .map(|(i, t)| InputRef::new(i, t).into())
270                        .collect();
271                    if !type_match {
272                        cast_exprs = Self::cast_on_insert(&expected_types, cast_exprs)?
273                    }
274                    if !all_nullable {
275                        cast_exprs =
276                            Self::check_not_null(&nullables, cast_exprs, table_name.as_str())?
277                    }
278                    cast_exprs
279                };
280                bound_query.schema().len()
281            }
282            Some(values) => {
283                let values_len = values
284                    .0
285                    .first()
286                    .expect("values list should not be empty")
287                    .len();
288                if !has_user_specified_columns {
289                    check_generated_insert_violation(Some(values_len))?;
290                }
291                let mut values = self.bind_values(values, Some(&expected_types))?;
292                // let mut bound_values = values.clone();
293
294                if !all_nullable {
295                    values.rows = values
296                        .rows
297                        .into_iter()
298                        .map(|vec| Self::check_not_null(&nullables, vec, table_name.as_str()))
299                        .try_collect()?;
300                }
301
302                bound_query = BoundQuery::with_values(values);
303                cast_exprs = vec![];
304                values_len
305            }
306        };
307
308        let num_target_cols = if has_user_specified_columns {
309            cols_to_insert_by_user.len()
310        } else {
311            cols_to_insert_in_table.len()
312        };
313
314        let (err_msg, default_column_indices) = match num_target_cols.cmp(&bound_column_nums) {
315            std::cmp::Ordering::Equal => (None, default_column_indices),
316            std::cmp::Ordering::Greater => {
317                if has_user_specified_columns {
318                    // e.g. insert into t (v1, v2) values (7)
319                    (
320                        Some("INSERT has more target columns than expressions"),
321                        vec![],
322                    )
323                } else {
324                    // e.g. create table t (a int, b real)
325                    //      insert into t values (7)
326                    // this kind of usage is fine, null values will be provided
327                    // implicitly.
328                    (None, col_indices_to_insert.split_off(bound_column_nums))
329                }
330            }
331            std::cmp::Ordering::Less => {
332                // e.g. create table t (a int, b real)
333                //      insert into t (v1) values (7, 13)
334                // or   insert into t values (7, 13, 17)
335                (
336                    Some("INSERT has more expressions than target columns"),
337                    vec![],
338                )
339            }
340        };
341        if let Some(msg) = err_msg {
342            return Err(RwError::from(ErrorCode::BindError(msg.to_owned())));
343        }
344
345        let default_columns = default_column_indices
346            .into_iter()
347            .map(|i| {
348                let column = &cols_to_insert_in_table[i];
349                let expr = default_columns_from_catalog
350                    .get(&i)
351                    .cloned()
352                    .unwrap_or_else(|| ExprImpl::literal_null(column.data_type().clone()));
353
354                let expr = if column.nullable() {
355                    expr
356                } else {
357                    FunctionCall::new_unchecked(
358                        ExprType::CheckNotNull,
359                        vec![
360                            expr,
361                            ExprImpl::literal_varchar(column.name().to_owned()),
362                            ExprImpl::literal_varchar(table_name.clone()),
363                        ],
364                        column.data_type().clone(),
365                    )
366                    .into()
367                };
368
369                (i, expr)
370            })
371            .collect_vec();
372
373        let insert = BoundInsert {
374            table_id,
375            table_version_id,
376            table_name,
377            table_visible_columns,
378            owner,
379            row_id_index,
380            column_indices: col_indices_to_insert,
381            default_columns,
382            source: bound_query,
383            cast_exprs,
384            returning_list,
385            returning_schema: if is_returning {
386                Some(Schema { fields })
387            } else {
388                None
389            },
390        };
391        Ok(insert)
392    }
393
394    /// Cast a list of `exprs` to corresponding `expected_types` IN ASSIGNMENT CONTEXT. Make sure
395    /// you understand the difference of implicit, assignment and explicit cast before reusing it.
396    pub(super) fn cast_on_insert(
397        expected_types: &[DataType],
398        exprs: Vec<ExprImpl>,
399    ) -> Result<Vec<ExprImpl>> {
400        let msg = match expected_types.len().cmp(&exprs.len()) {
401            std::cmp::Ordering::Less => "INSERT has more expressions than target columns",
402            _ => {
403                let expr_len = exprs.len();
404                return exprs
405                    .into_iter()
406                    .zip_eq_fast(expected_types.iter().take(expr_len))
407                    .enumerate()
408                    .map(|(i, (e, t))| {
409                        let res = e.cast_assign(t);
410                        if expr_len > 1 {
411                            res.with_context(|| {
412                                format!("failed to cast the {} column", ordinal(i + 1))
413                            })
414                            .map_err(Into::into)
415                        } else {
416                            res.map_err(Into::into)
417                        }
418                    })
419                    .try_collect();
420            }
421        };
422        Err(ErrorCode::BindError(msg.into()).into())
423    }
424
425    /// Add not null check for the columns that are not nullable.
426    pub(super) fn check_not_null(
427        nullables: &Vec<(bool, &str)>,
428        exprs: Vec<ExprImpl>,
429        table_name: &str,
430    ) -> Result<Vec<ExprImpl>> {
431        let msg = match nullables.len().cmp(&exprs.len()) {
432            std::cmp::Ordering::Less => "INSERT has more expressions than target columns",
433            _ => {
434                let expr_len = exprs.len();
435                return exprs
436                    .into_iter()
437                    .zip_eq_fast(nullables.iter().take(expr_len))
438                    .map(|(expr, (nullable, col_name))| {
439                        if !nullable {
440                            let return_type = expr.return_type();
441                            let check_not_null = FunctionCall::new_unchecked(
442                                ExprType::CheckNotNull,
443                                vec![
444                                    expr,
445                                    ExprImpl::literal_varchar((*col_name).to_owned()),
446                                    ExprImpl::literal_varchar(table_name.to_owned()),
447                                ],
448                                return_type,
449                            );
450                            // let res = expr.cast_assign(t.clone());
451                            Ok(check_not_null.into())
452                        } else {
453                            Ok(expr)
454                        }
455                    })
456                    .try_collect();
457            }
458        };
459        Err(ErrorCode::BindError(msg.into()).into())
460    }
461}
462
463/// # Parameters
464/// - `cols_to_insert_in_table`: the list of columns that are visible and non-generated
465///
466/// - `cols_to_insert_by_user`:
467///   The list of column identifiers explicitly specified by the user
468///   in the INSERT statement.
469///
470/// - `table_name`: The name of the target table.
471///
472/// # Return
473/// - `(col_indices_to_insert, default_column_indices)`
474///
475///   - `col_indices_to_insert`:
476///     Column indices corresponding to user-specified columns in the INSERT statement,
477///     preserving the user-defined order.
478///
479///   - `default_column_indices`:
480///     Column indices of remaining columns in the target table that are not explicitly
481///     provided by the user and should be filled with DEFAULT values.
482fn get_col_indices_to_insert(
483    cols_to_insert_in_table: &[ColumnCatalog],
484    cols_to_insert_by_user: &[Ident],
485    table_name: &str,
486) -> Result<(Vec<usize>, Vec<usize>)> {
487    if cols_to_insert_by_user.is_empty() {
488        return Ok(((0..cols_to_insert_in_table.len()).collect(), vec![]));
489    }
490
491    let mut col_indices_to_insert: Vec<usize> = Vec::new();
492
493    // Build a map from column name to column index in the table catalog
494    let col_name_to_idx: HashMap<String, usize> = cols_to_insert_in_table
495        .iter()
496        .enumerate()
497        .map(|(idx, col)| (col.name().to_owned(), idx))
498        .collect();
499
500    let mut seen = HashSet::with_capacity(cols_to_insert_by_user.len());
501    for col_name in cols_to_insert_by_user {
502        let col_name = col_name.real_value();
503        if !seen.insert(col_name.clone()) {
504            return Err(RwError::from(ErrorCode::BindError(
505                "Column specified more than once".to_owned(),
506            )));
507        }
508
509        let idx = col_name_to_idx.get(&col_name).ok_or_else(|| {
510            RwError::from(ErrorCode::BindError(format!(
511                "Column {} not found in table {}",
512                col_name, table_name
513            )))
514        })?;
515
516        col_indices_to_insert.push(*idx);
517    }
518
519    // columns that are in the target table but not in the provided target columns
520    let default_column_indices = if col_indices_to_insert.len() != cols_to_insert_in_table.len() {
521        cols_to_insert_in_table
522            .iter()
523            .enumerate()
524            .filter_map(|(idx, col)| {
525                let column_name = col.name();
526                (!seen.contains(column_name)).then_some(idx)
527            })
528            .collect()
529    } else {
530        vec![]
531    };
532
533    Ok((col_indices_to_insert, default_column_indices))
534}