|
| 1 | +// SPDX-License-Identifier: Apache-2.0 |
| 2 | + |
| 3 | +//! Plan construction for the KV engine's `VALUES`-clause insert paths |
| 4 | +//! (plain `INSERT`, `UPSERT`, and `INSERT ... ON CONFLICT DO UPDATE`). |
| 5 | +
|
| 6 | +use sqlparser::ast; |
| 7 | + |
| 8 | +use super::range_check::check_declared_int_ranges; |
| 9 | +use super::value_convert::expr_to_sql_value; |
| 10 | +use crate::error::{Result, SqlError}; |
| 11 | +use crate::planner::declared_type_coerce::{ |
| 12 | + coerce_assignments_to_declared_types, coerce_row_to_declared_types, |
| 13 | +}; |
| 14 | +use crate::types::*; |
| 15 | + |
| 16 | +/// Build a `SqlPlan::KvInsert` from a VALUES clause. Shared by plain INSERT, |
| 17 | +/// UPSERT, and `INSERT ... ON CONFLICT (key) DO UPDATE` — the three paths |
| 18 | +/// differ only in `intent` and `on_conflict_updates`, never in how entries |
| 19 | +/// are extracted from the row exprs. |
| 20 | +/// |
| 21 | +/// `pk_col` is the schema-defined primary-key column name from |
| 22 | +/// `CollectionInfo::primary_key`. When supplied, that column is used as |
| 23 | +/// the KV key regardless of whether it is named `"key"`. Falls back to |
| 24 | +/// the literal name `"key"` when `pk_col` is `None` (legacy / generic |
| 25 | +/// KV collections that use the built-in key/value column convention). |
| 26 | +pub(crate) fn build_kv_insert_plan( |
| 27 | + table_name: String, |
| 28 | + columns: &[String], |
| 29 | + rows_ast: &[Vec<ast::Expr>], |
| 30 | + intent: KvInsertIntent, |
| 31 | + mut on_conflict_updates: Vec<(String, SqlExpr)>, |
| 32 | + pk_col: Option<&str>, |
| 33 | + declared_columns: &[ColumnInfo], |
| 34 | +) -> Result<Vec<SqlPlan>> { |
| 35 | + // Positional KV insert (no column list): the key/value split below is |
| 36 | + // driven entirely by matching column *names* against `key_col_name`/ |
| 37 | + // `"ttl"`. With an empty `columns` list there is no key to bind to, so |
| 38 | + // every row would silently become an empty-keyed, empty-valued entry |
| 39 | + // (all colliding). Reject rather than corrupt. |
| 40 | + if columns.is_empty() { |
| 41 | + return Err(SqlError::PositionalKvInsertUnsupported { |
| 42 | + collection: table_name, |
| 43 | + }); |
| 44 | + } |
| 45 | + let key_col_name = pk_col.unwrap_or("key"); |
| 46 | + let key_idx = columns.iter().position(|c| c == key_col_name); |
| 47 | + let ttl_idx = columns.iter().position(|c| c == "ttl"); |
| 48 | + // When using a named primary-key column (e.g. `k STRING PRIMARY KEY`), we |
| 49 | + // store the key bytes in the KV key slot AND also keep the column in the |
| 50 | + // value map. This allows scan filters on the primary-key column (e.g. |
| 51 | + // `WHERE k = 'x'`) and projection (e.g. `SELECT k FROM ...`) to work |
| 52 | + // without teaching the KV scan handler to inspect the raw key bytes. |
| 53 | + // The only column we exclude from the value map is the built-in `"key"` |
| 54 | + // sentinel (used by raw key/value KV collections) and `"ttl"`. |
| 55 | + let exclude_from_value: std::collections::HashSet<usize> = { |
| 56 | + let mut s = std::collections::HashSet::new(); |
| 57 | + // Exclude the raw "key" sentinel column (not a named PK column). |
| 58 | + if key_col_name == "key" |
| 59 | + && let Some(idx) = key_idx |
| 60 | + { |
| 61 | + s.insert(idx); |
| 62 | + } |
| 63 | + if let Some(idx) = ttl_idx { |
| 64 | + s.insert(idx); |
| 65 | + } |
| 66 | + s |
| 67 | + }; |
| 68 | + // Resolve every row's literals once, then coerce each cell to its declared |
| 69 | + // column type. Unlike the strict, columnar, and timeseries engines, KV has |
| 70 | + // no typed write path: its engine stores the bytes it is handed and the |
| 71 | + // declared schema exists only here, in the catalog. Without this the |
| 72 | + // stored cell's type is whatever the literal happened to resolve to — a |
| 73 | + // fractional literal is an exact `Decimal`, which serializes as a msgpack |
| 74 | + // string — while `RowDescription` advertises the declared numeric type, and |
| 75 | + // the read path can only encode SQL NULL for it. See |
| 76 | + // `declared_type_coerce` for the full rationale. |
| 77 | + let mut coerced_rows: Vec<Vec<(String, SqlValue)>> = Vec::with_capacity(rows_ast.len()); |
| 78 | + for row_exprs in rows_ast { |
| 79 | + let mut row: Vec<(String, SqlValue)> = Vec::with_capacity(columns.len()); |
| 80 | + for (i, col) in columns.iter().enumerate() { |
| 81 | + let Some(expr) = row_exprs.get(i) else { break }; |
| 82 | + row.push((col.clone(), expr_to_sql_value(expr)?)); |
| 83 | + } |
| 84 | + // The key column is exempt — see `coerce_rows_to_declared_types`. |
| 85 | + coerce_row_to_declared_types(declared_columns, &mut row, Some(key_col_name))?; |
| 86 | + coerced_rows.push(row); |
| 87 | + } |
| 88 | + // KV returns early from every INSERT/UPSERT entry point, so the declared |
| 89 | + // width check lives here rather than at the call sites — otherwise a |
| 90 | + // fourth KV entry point could be added without it. It runs on the coerced |
| 91 | + // values so a literal that only becomes an integer through coercion is |
| 92 | + // still range-checked against its declared width. |
| 93 | + check_declared_int_ranges(declared_columns, &coerced_rows)?; |
| 94 | + // `ON CONFLICT DO UPDATE SET col = <literal>` writes through the same |
| 95 | + // untyped KV path as the inserted row, so its literals need the same |
| 96 | + // declared-type coercion. |
| 97 | + coerce_assignments_to_declared_types( |
| 98 | + declared_columns, |
| 99 | + &mut on_conflict_updates, |
| 100 | + Some(key_col_name), |
| 101 | + )?; |
| 102 | + |
| 103 | + let mut entries = Vec::with_capacity(coerced_rows.len()); |
| 104 | + let mut ttl_secs: u64 = 0; |
| 105 | + for row in &coerced_rows { |
| 106 | + let key_val = match key_idx.and_then(|idx| row.get(idx)) { |
| 107 | + Some((_, value)) => value.clone(), |
| 108 | + None => SqlValue::String(String::new()), |
| 109 | + }; |
| 110 | + if let Some((_, value)) = ttl_idx.and_then(|idx| row.get(idx)) { |
| 111 | + match value { |
| 112 | + SqlValue::Int(n) => ttl_secs = (*n).max(0) as u64, |
| 113 | + SqlValue::Float(f) => ttl_secs = f.max(0.0) as u64, |
| 114 | + _ => {} |
| 115 | + } |
| 116 | + } |
| 117 | + let value_cols: Vec<(String, SqlValue)> = row |
| 118 | + .iter() |
| 119 | + .enumerate() |
| 120 | + .filter(|(i, _)| !exclude_from_value.contains(i)) |
| 121 | + .map(|(_, cell)| cell.clone()) |
| 122 | + .collect(); |
| 123 | + entries.push((key_val, value_cols)); |
| 124 | + } |
| 125 | + Ok(vec![SqlPlan::KvInsert { |
| 126 | + collection: table_name, |
| 127 | + entries, |
| 128 | + ttl_secs, |
| 129 | + intent, |
| 130 | + on_conflict_updates, |
| 131 | + }]) |
| 132 | +} |
0 commit comments