//! Finding statement boundaries in a query buffer. //! //! `cmd+enter` runs the statement under the cursor, so we need to know where //! each statement starts and ends. Splitting on `;` is wrong — a semicolon can //! sit inside a string literal, a line comment, or a `$$`-quoted function body, //! and each of those would be cut in the wrong place. We run a real parser. //! //! gpui-component highlights with tree-sitter internally but keeps the tree //! private, so this is a second, independent parse of the same text. For a //! query buffer that cost is irrelevant. //! //! Statement ranges **exclude the terminating semicolon** — that is where the //! grammar puts the node boundary, and it is what we want, since Postgres does //! not need a trailing semicolon on a statement sent over the wire. use std::borrow::Cow; use std::ops::{ControlFlow, Range}; use serde::Deserialize; // Aliased: `tree_sitter::Parser` already owns the name `Parser` in this file, // and the two parsers are never interchangeable -- see `classify`'s doc. use sqlparser::ast::{ AlterTableOperation, ConditionalStatementBlock, ContextModifier, CopySource, CopyTarget, CreateTableOptions, Delete, Expr, Insert, Merge, ObjectName, ObjectNamePart, Query, Set, SetExpr, SetSessionParamKind, SqlOption, Statement, TableFactor, TableObject, TransactionAccessMode, TransactionMode, Update, UtilityOption, Visit, Visitor, visit_statements, }; use sqlparser::dialect::{ ClickHouseDialect, Dialect, DuckDbDialect, GenericDialect, MsSqlDialect, MySqlDialect, PostgreSqlDialect, SQLiteDialect, SnowflakeDialect, }; use sqlparser::keywords::Keyword; use sqlparser::parser::Parser as SqlParser; use sqlparser::tokenizer::{Location, Token, Tokenizer, TokenizerError, Whitespace, Word}; use tree_sitter::{Node, Parser, Tree}; use crate::db::{ BinaryLiteral, ColumnDefinition, Engine, EngineSpec, ExplainMode, ExplainPrefix, FormatDialect, IdentifierQuote, Paging, Params, ParserDialect, SkipDuplicates, SqlSpec, StatementSplit, Syntax, TypedExplain, UnreadableFloor, UpdateSpelling, }; use crate::import_rows::Value; use crate::result_grid::{NewValue, PendingRow}; mod agent; #[cfg_attr( not(test), expect( unused_imports, reason = "the agent tools (Phase 4) are the first caller" ) )] pub(crate) use agent::{AgentVerdict, Expiry, Refusal, agent_gate}; pub(crate) use agent::{ApprovalKind, approval_kind, counts_rows, creates_index_concurrently}; /// The runnable statements of a query buffer, as byte ranges into it. pub struct Buffer { statements: Vec>, } impl Buffer { /// Every dialect's buffer but SQL Server's, which [`Buffer::for_engine`] /// reads. pub fn parse(sql: &str) -> Self { Self { statements: statements_in(sql), } } /// T-SQL is read a batch at a time, the way the server reads it: `GO` /// lines are hard boundaries that are never part of a statement, `[names]` /// are quoted, a routine's body runs to the end of its batch, and a /// `BEGIN … END` block is one statement however many `;`s it holds. Sending /// the second `DELETE` of an `IF … BEGIN … END` alone runs it outside its /// `IF`. /// /// A MongoDB buffer is mongosh statements, not SQL, and `mql` reads its /// boundaries: a newline ends a statement there unless a `.` continues it. pub fn for_engine(engine: Engine, sql: &str) -> Self { let statements = match engine.syntax() { Syntax::Sql if batches_on(engine) => batches(sql) .into_iter() .flat_map(|batch| tsql_statements(sql, batch)) .collect(), Syntax::Sql => statements_in(&as_grammar_reads(engine, sql)), Syntax::Mongo => crate::mql::statements(sql), Syntax::Redis => crate::redis_cmd::statements(sql), }; Self { statements } } /// Byte ranges of each statement, in source order, trimmed of surrounding /// whitespace. Empty if the buffer holds no statements. pub fn statements(&self) -> &[Range] { &self.statements } /// Where `statement` stands in `sql`, the buffer this was parsed from: the /// statement under `cursor` if it is that one, else the first that is. /// `None` once it has been edited away. /// /// A selection is sent verbatim, so `statement` can carry what the /// buffer's ranges leave out, like its closing `;`. It is cut the way the /// buffer is before the two are compared. pub fn find( &self, engine: Engine, sql: &str, cursor: usize, statement: &str, ) -> Option> { let statement = match Buffer::for_engine(engine, statement).statements() { [only] => &statement[only.clone()], _ => statement, }; let is_it = |range: &Range| sql[range.clone()].trim() == statement.trim(); self.statement_at(cursor) .filter(is_it) .or_else(|| self.statements.iter().find(|range| is_it(range)).cloned()) } /// The statement to run for a cursor at `offset`. /// /// Inside a statement, that statement. In whitespace or a comment between /// two statements, the preceding one — you just finished typing it. Before /// the first statement, the first one. pub fn statement_at(&self, offset: usize) -> Option> { if self.statements.is_empty() { return None; } if let Some(hit) = self .statements .iter() .find(|range| range.contains(&offset) || range.end == offset) { return Some(hit.clone()); } self.statements .iter() .rev() .find(|range| range.end < offset) .or_else(|| self.statements.first()) .cloned() } } /// What a selection of several statements runs as, one submission apiece: /// every unit in `sql`, or, with a non-empty `selection`, only the ones it /// touches -- a unit partly selected still counts. /// /// **The unit is the batch on SQL Server and the statement everywhere else.** /// A `GO` line is a scope boundary there: a variable, a temp table and a /// routine's body all end with the batch that declared them, so splitting /// below one would send `DECLARE @x int` and the `SELECT @x` that reads it as /// two batches, and the second would not know the first. The other four /// engines have no such boundary -- a session carries variables, temp tables /// and an open transaction across every submission -- so there the statement /// is the unit and a semicolon is where it ends. /// /// A counted `GO` is not refused here: this answers what the units are, not /// whether they may run. `batch_counts` is the refusal. pub(crate) fn queued_statements( engine: Engine, sql: &str, selection: Option>, ) -> Vec> { let units = match batches_on(engine) { true => queued_batches(sql), false => Buffer::for_engine(engine, sql).statements().to_vec(), }; let Some(selection) = selection.filter(|sel| !sel.is_empty()) else { return units; }; units .into_iter() .filter(|range| range.start < selection.end && selection.start < range.end) .collect() } /// How many result sets one submission of `sql` is expected to return: the /// statements inside it on SQL Server, where the unit submitted is the batch, /// and one everywhere else, where the unit submitted is the statement. /// /// An expectation, not a promise. A statement returns at most one set and /// usually none, so this is an upper bound for the ordinary batch -- but a /// procedure call, a loop or a trigger can return more sets than the batch has /// statements, and there is no reading that off the text. pub(crate) fn expected_sets(engine: Engine, sql: &str) -> usize { match batches_on(engine) { true => tsql_statements(sql, 0..sql.len()).len().max(1), false => 1, } } /// One range per `GO`-separated batch, trimmed, skipping any that holds no /// statement -- a batch of nothing but comments is not a batch to send, the /// same judgement `one_batch` makes. fn queued_batches(sql: &str) -> Vec> { batches(sql) .into_iter() .filter(|batch| !tsql_statements(sql, batch.clone()).is_empty()) .filter_map(|batch| trim_range(sql, batch)) .collect() } /// A SQL Server selection's batches cut into their statements, so a run of /// reads can send each at once on a connection of its own as every other /// engine does. Only when every batch is plain reads (`plain_read`) naming no /// `@variable` and no `#temp` table, which is what a batch scopes: nothing in /// one needs another statement beside it. Like `queued_statements`, only the /// statements `selection` touches. Empty for anything else, and on every other /// engine, whose units are statements already. pub(crate) fn split_reads( engine: Engine, sql: &str, batches: &[Range], selection: Range, ) -> Vec> { let reads_alone = |batch: &str| { plain_read(engine, batch) && !tsql_scan(batch).0.iter().any(|word| { let word = &batch[word.clone()]; word.starts_with('#') || word.starts_with('@') && !word.starts_with("@@") }) }; if !batches_on(engine) || !batches.iter().all(|batch| reads_alone(&sql[batch.clone()])) { return Vec::new(); } batches .iter() .flat_map(|batch| tsql_statements(sql, batch.clone())) .filter_map(|statement| trim_range(sql, statement)) .filter(|range| range.start < selection.end && selection.start < range.end) .collect() } /// One key of an `ORDER BY`, as dbdelve reads and writes it. #[derive(Clone, Debug, PartialEq, Eq)] pub struct SortKey { /// The key exactly as it appears in the statement — `"created_at"`, `3`, /// `lower(name)`. Kept verbatim, so a key dbdelve did not write survives a /// click on some other column. pub expression: String, pub ascending: bool, } impl SortKey { pub fn new(expression: impl Into, ascending: bool) -> Self { Self { expression: expression.into(), ascending, } } fn render(&self) -> String { let direction = match self.ascending { true => "ASC", false => "DESC", }; format!("{} {direction}", self.expression) } } /// The keys of a statement's `ORDER BY`, in order. `Some(empty)` is a statement /// that could carry one and does not; `None` is a statement dbdelve cannot read /// well enough to say without guessing. pub fn order_by(engine: Engine, statement: &str) -> Option> { match engine.syntax() { Syntax::Mongo => return crate::mql::browse::order_by(statement), // A reply's order is the command's own; nothing sorts it. Syntax::Redis => return None, Syntax::Sql => {} } let sql = statement; let tree = parse(sql)?; let anchor = clause_anchor(&tree, sql)?; let Some(clause) = child_of_kind(&anchor, "order_by") else { return Some(Vec::new()); }; // `ORDER BY ALL` sorts by columns it does not name, so no key can say which. if child_of_kind(&clause, "keyword_all").is_some() { return None; } let mut cursor = clause.walk(); let keys = clause .named_children(&mut cursor) .filter(|node| node.kind() == "order_target") .filter_map(|target| { let mut cursor = target.walk(); let children: Vec<_> = target.named_children(&mut cursor).collect(); let expression = children .iter() .find(|node| node.kind() != "direction") .and_then(|node| sql.get(node.byte_range()))?; let descending = children .iter() .find(|node| node.kind() == "direction") .and_then(|node| sql.get(node.byte_range())) .is_some_and(|text| text.trim().eq_ignore_ascii_case("desc")); Some(SortKey::new(expression, !descending)) }) .collect(); Some(keys) } /// `statement` with `keys` as its `ORDER BY`, replacing the clause it already /// has and removing it when `keys` is empty. /// /// The clause is placed where it belongs rather than appended: `ORDER BY` after /// a `LIMIT` is a syntax error, and a limit that applies *before* the sort /// would order one arbitrary page of the table instead of the table. /// /// `None` when dbdelve cannot see where the clause goes — a statement it cannot /// parse cleanly, one with no `FROM`, or one that is not a query. Nothing is /// guessed at, because the alternative is handing the server a statement the /// user did not write and cannot read. pub fn with_order_by(engine: Engine, statement: &str, keys: &[SortKey]) -> Option { match engine.syntax() { Syntax::Mongo => return crate::mql::browse::with_order_by(statement, keys), Syntax::Redis => return None, Syntax::Sql => {} } let sql = statement; let tree = parse(sql)?; let anchor = clause_anchor(&tree, sql)?; let clause = match keys.is_empty() { true => String::new(), false => format!( "ORDER BY {}", keys.iter() .map(SortKey::render) .collect::>() .join(", ") ), }; // Replacing the existing clause, rather than adding a second one, is what // makes a repeated click a change of sort instead of an accumulation. if let Some(existing) = child_of_kind(&anchor, "order_by") { return Some(splice(sql, &tree, existing.byte_range(), &clause)); } if clause.is_empty() { return Some(sql.to_string()); } let insert_at = child_of_kind(&anchor, "limit") .map(|limit| limit.byte_range().start) .unwrap_or(anchor.byte_range().end); Some(splice(sql, &tree, insert_at..insert_at, &clause)) } /// [`sql_paged`] for `engine`. A MongoDB or Redis preview comes back as it /// is. pub fn paged(engine: Engine, statement: &str, key: &[String]) -> Option { match engine.syntax() { Syntax::Sql => sql_paged(engine.spec(), statement, key), Syntax::Mongo | Syntax::Redis => Some(statement.to_string()), } } /// A generated preview's page, spelled the way `spec` reads one. /// /// Every engine but SQL Server takes the `LIMIT … OFFSET …` a preview is /// generated with. T-SQL has no `LIMIT`, and the grammar the gates parse with /// has none of T-SQL's `OFFSET … FETCH`, so the preview is generated, sorted and /// checked in the one spelling and re-spelled here after the gate has read it. /// Only the `limit` node the parse tree locates is replaced, with two integers /// read out of it: nothing the user typed into a filter is touched. `OFFSET` /// needs an `ORDER BY`, and an unsorted preview is ordered by `key`, the /// columns that tell its rows apart: without a total order the server may hand /// the same row to two pages and none to another. The key follows a /// `(SELECT NULL)` that orders nothing, which is how [`unpaged`] tells it from /// a sort the user asked for, and is all there is when no key is known. A /// preview with no limit is one page already, and comes back as it is. /// /// `None` for a statement this cannot read, or whose limit it cannot. pub(crate) fn sql_paged(spec: &EngineSpec, statement: &str, key: &[String]) -> Option { if spec.sql.paging == Paging::LimitOffset { return Some(statement.to_string()); } let tree = parse(statement)?; let anchor = clause_anchor(&tree, statement)?; let Some(limit) = child_of_kind(&anchor, "limit") else { return Some(statement.to_string()); }; if spec.sql.paging == Paging::LimitOffsetByKey { // Without a key (none declared, or an expression such as `toDate(ts)`) // the page stays unordered: there is nothing honest to order it by. if child_of_kind(&anchor, "order_by").is_some() || key.is_empty() { return Some(statement.to_string()); } let order = key .iter() .map(|column| spec.quote_identifier(column)) .collect::>() .join(", "); return Some(splice( statement, &tree, limit.byte_range(), &format!("ORDER BY {order} {}", &statement[limit.byte_range()]), )); } let number = |node: tree_sitter::Node| -> Option { statement .get(child_of_kind(&node, "literal")?.byte_range())? .parse() .ok() }; let rows = number(limit)?; let offset = match child_of_kind(&limit, "offset") { Some(offset) => number(offset)?, None => 0, }; let order = match child_of_kind(&anchor, "order_by") { Some(_) => String::new(), None => { key.iter() .fold("ORDER BY (SELECT NULL)".to_string(), |order, column| { format!("{order}, {}", spec.quote_identifier(column)) }) + " " } }; Some(splice( statement, &tree, limit.byte_range(), &format!("{order}OFFSET {offset} ROWS FETCH NEXT {rows} ROWS ONLY"), )) } /// [`paged`] undone: the `LIMIT … OFFSET …` spelling back from the /// `OFFSET … FETCH` one, so the preview that runs can be read by the same /// parse that wrote it. Anything not in exactly the shape `paged` writes /// comes back unchanged. pub fn unpaged(statement: &str) -> String { let unpage = || { let (head, tail) = statement.rsplit_once(" OFFSET ")?; let (offset, tail) = tail.split_once(" ROWS FETCH NEXT ")?; let rows = tail.strip_suffix(" ROWS ONLY")?; offset.parse::().ok()?; rows.parse::().ok()?; // A sort the user asked for ends in its direction, never in a quoted // key column, so one inside a filter's string literal is left alone. let head = head .rsplit_once(" ORDER BY (SELECT NULL)") .filter(|(_, key)| key.is_empty() || (key.starts_with(", ") && key.ends_with('"'))) .map_or(head, |(head, _)| head); Some(format!("{head} LIMIT {rows} OFFSET {offset}")) }; unpage().unwrap_or_else(|| statement.to_string()) } /// [`sql_update_statement`] for `engine`. MongoDB's and Redis's edits are /// written by their own modules, and only the tests read the SQL-shaped text /// spelled with their quoting here. #[cfg(test)] pub fn update_row( engine: Engine, schema: &str, table: &str, sets: &[(&str, NewValue)], keys: &[(&str, &str)], types: &[(String, String)], ) -> Option { if engine.syntax() == Syntax::Sql { return sql_update_statement( engine.spec(), schema, table, sets, Match { keys, nulls: &[] }, UpdateSpelling::Update, types, ); } if sets.is_empty() || keys.is_empty() { return None; } let keys: Vec<(&str, NewValue)> = keys .iter() .map(|&(column, value)| (column, NewValue::Value(value.into()))) .collect(); Some(format!( "UPDATE {} SET {} WHERE {}", engine.qualified(schema, table), assignments(engine, sets, types, ", "), assignments(engine, &keys, types, " AND ") )) } /// An `INSERT` naming exactly the columns it was given, and no others. /// /// A column the caller does not pass is not mentioned in the statement at all, /// which is what leaves the server's default to apply to it. That is the whole /// reason this takes a list of columns rather than a row: a row would have a /// value for every column, and every default would be unreachable. /// /// The asymmetry with `update_row` is deliberate and worth stating: this needs /// a schema and a table but **no primary key**, because an insert has no /// existing row to name yet, where editing has to name a row that already /// exists. So a table without a primary key can be inserted into and not /// edited. /// /// An error on an empty list. The alternative is `INSERT INTO t DEFAULT /// VALUES`, a statement nobody has asked dbdelve for. pub fn insert_row( engine: Engine, schema: &str, table: &str, columns: &[(&str, Option<&str>)], types: &[(String, String)], ) -> Result { match engine.syntax() { Syntax::Sql => sql_insert_row(engine.spec(), schema, table, columns, types), Syntax::Mongo => crate::mql::insert_row(table, columns, types), Syntax::Redis => crate::redis_cmd::edit::insert_row(schema, table, columns), } } /// [`insert_row`] for a SQL engine, written from its spec alone: nothing here /// asks which engine it is, so an engine with no arm of its own writes through /// it too. The same holds for every `sql_` writer below. pub(crate) fn sql_insert_row( spec: &EngineSpec, schema: &str, table: &str, columns: &[(&str, Option<&str>)], types: &[(String, String)], ) -> Result { if columns.is_empty() { return Err("There is nothing in this row to insert.".into()); } let names: Vec = columns .iter() .map(|&(column, _)| spec.quote_identifier(column)) .collect(); let values: Vec = columns .iter() // An insert leaves a default to apply by omitting the column outright, // so the third state the grid's edits carry has nothing to mean here. .map(|&(column, value)| { sql_literal( spec, &value.map_or(NewValue::Null, |value| NewValue::Value(value.into())), type_of(types, column), ) }) .collect::>() .ok_or(UNSPELLED)?; Ok(format!( "INSERT INTO {} ({}) VALUES ({})", spec.qualified(schema, table), names.join(", "), values.join(", ") )) } /// One multi-row `INSERT` for an import chunk. `columns` holds `(name, /// data_type)`, each row its values in that order; a `None` has no SQL /// spelling, so it is an error. Every value is quoted as the engine quotes it, /// which is what the write gate's literal check relies on. pub(crate) fn insert_rows( engine: Engine, schema: &str, table: &str, columns: &[(&str, &str)], rows: &[Vec>], skip: bool, ) -> Result { match engine.syntax() { Syntax::Sql => sql_insert_rows(engine.spec(), schema, table, columns, rows, skip), Syntax::Mongo => { let names: Vec<&str> = columns.iter().map(|&(name, _)| name).collect(); crate::mql::insert_many(table, &names, rows) } Syntax::Redis => Err("Redis takes no imported rows.".into()), } } pub(crate) fn sql_insert_rows( spec: &EngineSpec, schema: &str, table: &str, columns: &[(&str, &str)], rows: &[Vec>], skip: bool, ) -> Result { let Some(&(first, _)) = columns.first() else { return Err("There is nothing in this row to insert.".into()); }; if rows.is_empty() { return Err("There are no rows to insert.".into()); } let names: Vec = columns .iter() .map(|&(name, _)| spec.quote_identifier(name)) .collect(); let mut tuples = Vec::with_capacity(rows.len()); for row in rows { let mut values = Vec::with_capacity(columns.len()); for (&(_, data_type), value) in columns.iter().zip(row) { let value = value.ok_or("A value is missing from a row to insert.")?; let new = match value { Value::Null => NewValue::Null, Value::Bool(b) => NewValue::Value(spec.sql.boolean_literal.spelled(*b).into()), Value::Json(json) => NewValue::Value(json.to_string().into()), Value::Text(text) | Value::Number(text) | Value::Date { text, .. } => { NewValue::Value(text.clone().into()) } }; values.push(sql_literal(spec, &new, Some(data_type)).ok_or(UNSPELLED)?); } tuples.push(format!("({})", values.join(", "))); } // ponytail: Stop and Skip only. Update-existing-row is deferred: Postgres cannot spell ON CONFLICT (pk) DO UPDATE under the pinned grammar, MySQL's matches any unique key, SQL Server and Snowflake would need MERGE. let tail = match (skip, spec.sql.skip_duplicates) { (false, _) => String::new(), (true, SkipDuplicates::OnConflictDoNothing { .. }) => " ON CONFLICT DO NOTHING".into(), (true, SkipDuplicates::OnDuplicateKey) => { let first = spec.quote_identifier(first); format!(" ON DUPLICATE KEY UPDATE {first} = {first}") } (true, SkipDuplicates::None) => { return Err("This engine cannot skip rows that already exist.".into()); } }; Ok(format!( "INSERT INTO {} ({}) VALUES {}{tail}", spec.qualified(schema, table), names.join(", "), tuples.join(",\n") )) } /// An `INSERT` naming every column an insert supplies, each value the engine's /// own parameter placeholder: a template for the user's code, put on the /// clipboard and never run. `None` on MongoDB, which has no placeholders, and /// with no such columns. pub fn insert_template( engine: Engine, schema: &str, table: &str, columns: &[ColumnDefinition], ) -> Option { match engine.syntax() { Syntax::Sql => sql_insert_template(engine.spec(), schema, table, columns), Syntax::Mongo | Syntax::Redis => None, } } pub(crate) fn sql_insert_template( spec: &EngineSpec, schema: &str, table: &str, columns: &[ColumnDefinition], ) -> Option { let placeholder: fn(usize) -> String = match spec.sql.params { Params::Question => |_| "?".into(), Params::Dollar => |n| format!("${n}"), Params::AtP => |n| format!("@p{n}"), }; let names: Vec = columns .iter() .filter(|column| !spec.generates(column)) .map(|column| spec.quote_identifier(&column.name)) .collect(); if names.is_empty() { return None; } let values: Vec = (1..=names.len()).map(placeholder).collect(); Some(format!( "INSERT INTO {} ({}) VALUES ({});", spec.qualified(schema, table), names.join(", "), values.join(", ") )) } #[cfg(test)] pub fn delete_row( engine: Engine, schema: &str, table: &str, keys: &[(&str, &str)], types: &[(String, String)], ) -> Option { delete_row_matching(engine, schema, table, keys, &[], types) } /// One row's `DELETE`: every column in `keys` matched, and nothing else. /// /// One row per statement. Multi-row deletion by predicate is cut: deleting /// several rows is one `DELETE` per row, each naming its own key, in a reviewed /// draft ([`draft_batch`]) inside the `BEGIN`/`COMMIT` multi-row edits use on /// the engines that commit each statement alone, never one statement with a /// predicate covering several. /// /// `None` on an empty key list. A `DELETE` with no `WHERE` empties the table, so /// it must not be possible to produce one: a caller that has lost the row's key /// gets nothing to run rather than something that runs. /// /// `null_keys` are the columns of a row named by every value that read NULL, /// matched with `IS NULL`. pub fn delete_row_matching( engine: Engine, schema: &str, table: &str, keys: &[(&str, &str)], null_keys: &[&str], types: &[(String, String)], ) -> Option { match engine.syntax() { Syntax::Sql => sql_delete_row( engine.spec(), schema, table, Match { keys, nulls: null_keys, }, types, ), Syntax::Mongo => crate::mql::delete_row(table, keys, types).ok(), Syntax::Redis => crate::redis_cmd::edit::delete_row(schema, table, keys, types).ok(), } } pub(crate) fn sql_delete_row( spec: &EngineSpec, schema: &str, table: &str, row: Match, types: &[(String, String)], ) -> Option { Some(format!( "DELETE FROM {} WHERE {}", spec.qualified(schema, table), sql_match(spec, row, types)? )) } /// The columns a statement names a row by: the values the server sent, and the /// columns that were NULL, which `=` does not find and so are matched with /// `IS NULL`. `nulls` is only ever filled for an engine that names a row by /// every value. #[derive(Clone, Copy)] pub(crate) struct Match<'a> { pub keys: &'a [(&'a str, &'a str)], pub nulls: &'a [&'a str], } /// The `WHERE` of a one-row statement, or `None` when it would name no row, or /// when the engine's `match_value` cannot spell one of the values. fn sql_match(spec: &EngineSpec, row: Match, types: &[(String, String)]) -> Option { if row.keys.is_empty() && row.nulls.is_empty() { return None; } let Some(term) = spec.hooks.match_value else { let keys: Vec<(&str, NewValue)> = row .keys .iter() .map(|&(column, value)| (column, NewValue::Value(value.into()))) .collect(); let mut terms = Vec::new(); if !keys.is_empty() { terms.push(sql_assignments(spec, &keys, types, " AND ")?); } terms.extend( row.nulls .iter() .map(|column| format!("{} IS NULL", spec.quote_identifier(column))), ); return Some(terms.join(" AND ")); }; let valued = row .keys .iter() .map(|&(column, value)| (column, Some(value))); let nulls = row.nulls.iter().map(|&column| (column, None)); valued .chain(nulls) .map(|(column, value)| term(column, value, type_of(types, column).unwrap_or_default())) .collect::>>() .map(|terms| terms.join(" AND ")) } /// Whether `sql` is a statement dbdelve could have written: one or more `UPDATE`s, /// a single `INSERT` of literals, a single `DELETE` naming one row, a draft of /// several of those (one-row `INSERT`s and `DELETE`s among them, see /// [`draft_sequence`]), or a lone transaction bracket, and nothing else at all. /// /// The one gate every dbdelve-generated statement passes before anything runs, /// and the code half of hard rule 1 — dbdelve never writes a `DROP` or a /// `TRUNCATE`, whatever the user asked for, and writes a `DELETE` only as a /// conjunction of equalities over distinct, unqualified columns. A whitelist, /// because a blocklist of keywords is only a list of the spellings someone /// thought of. /// /// A draft's `DELETE`s are each one named row, and the draft is reviewed in full /// before it runs: hard rule 1 admits a `DELETE` only as the deletion of one /// named row, however many a reviewed draft holds. /// /// The delete's shape is read out of the parse tree rather than trusted because /// `delete_row` produced it. A gate that trusts its caller is a comment, and the /// day the generator and the check disagree is the day this earns its keep. /// Whether the columns it names are the row's *key* is `delete_matches_key`'s /// answer, which this cannot give: no key reaches here to compare against. /// /// Named for what it admits rather than for one of the shapes, because it /// admits more than one now: a rule that lets an `INSERT` through under a name /// promising an `UPDATE` is how a whitelist quietly becomes a list of things /// nobody refused. /// /// Reads every literal as a backslash-escaping engine would, the stricter of /// the two readings. Every caller outside the tests has an engine and goes /// through [`is_generated_write_on`], which reads it as that engine does. #[cfg(test)] pub fn is_generated_write(sql: &str) -> bool { generated_write(&STRICTEST, sql) } /// The SQL every test-only gate entry reads with: literals as a /// backslash-escaping engine reads them, backticked names as an engine quoting /// with them does, and nothing an engine's spec adds. #[cfg(test)] const STRICTEST: SqlSpec = SqlSpec { backslash_escapes: true, identifier_quote: IdentifierQuote::Backtick, // The draft arm's own checks, read as strictly as the rest. drafts: true, ..SqlSpec::ANSI }; /// `spec` is the [`SqlSpec`] of the engine the statement is bound for. pub(crate) fn generated_write(spec: &SqlSpec, sql: &str) -> bool { // An exact-text whitelist rather than a parse, so nothing can ride along. if is_transaction_bracket(sql) { return true; } let Some(sql) = as_written(spec, sql) else { return false; }; let sql = sql.as_ref(); let Some(tree) = parse_gated(sql, spec) else { return false; }; let root = tree.root_node(); // Before any shape is considered, because no shape redeems either. if forbidden(root) { return false; } let Some(statements) = generated_statements(&root) else { return false; }; // Comments are tree-sitter extras and land at the root too, so anything // that is not a statement here is something dbdelve did not generate. let kinds: Vec<&str> = statements .iter() .map(|statement| match statement.kind() == "statement" { true => statement.named_child(0).map_or("", |node| node.kind()), false => "", }) .collect(); // The one place a `delete` node is tolerated, and only for the shape read // back out of the tree rather than trusted because dbdelve wrote it. if kinds == ["delete"] { return delete_key_columns(spec, sql).is_some(); } // A reviewed draft: several statements of the three kinds the grid writes, // holding at least one that a batch of updates does not, on a spec whose // grid writes one. if spec.drafts && kinds.len() > 1 && kinds .iter() .all(|kind| matches!(*kind, "update" | "insert" | "delete")) && kinds.iter().any(|kind| *kind != "update") { return draft_sequence(spec, root, &statements, &kinds, sql); } // A row named by every value is written only through a predicate the // exactly-one guard can count, so each update must be that shape too. let updates = !kinds.is_empty() && kinds.iter().all(|kind| *kind == "update") && statements.iter().all(|statement| match spec.row_terms { true => one_row_update(spec, *statement, sql).is_some(), false => literal_sets(spec, *statement, sql), }); // One insert alone, or a batch of updates. Several inserts are a draft's // and were read by the arm above. A comment anywhere refuses either: MySQL // runs `/*! … */` as SQL, and the grammar hides one inside a name or // between tokens the shape checks read only by kind, beside a set value or // in a predicate never read. ((kinds == ["insert"] && literal_insert(statements[0], sql)) || updates) && !commented(root, sql) && !deletes_anything(root) } /// Whether a submission of several `UPDATE`s, `INSERT`s and `DELETE`s is a /// draft dbdelve could have written: every statement one row, and no `DELETE` /// anywhere but in a statement of its own. /// /// Each top-level statement is read from the tree: an `INSERT` is one row of /// literals with no tail, and a `DELETE` is [`one_row_delete`] over a /// conjunction of equalities. The count of `delete` nodes, and of `DELETE` /// keywords, in the whole tree must equal the count of those statements, so one /// hidden in a CTE beside an `UPDATE` finds no statement to account for it. No /// comment is admitted anywhere (MySQL runs `/*! … */` as SQL), and not on a /// spec that names a row by every value, whose one-row guard a sequence cannot /// carry. /// /// Reads a `DELETE`'s shape and never its key or table, as the lone `DELETE` /// does: those are [`draft_deletes_match`]'s to answer. fn draft_sequence( spec: &SqlSpec, root: Node, statements: &[Node], kinds: &[&str], sql: &str, ) -> bool { if spec.row_terms || commented(root, sql) { return false; } let one_row = |statement: &Node, kind: &&str| match *kind { // As the `UPDATE` arm of a batch reads one on a spec that names rows // by key (see `updates` in `generated_write`): every set value a // literal dbdelve writes, and the predicate not read. "update" => literal_sets(spec, *statement, sql), "insert" => one_row_literal_insert(*statement, sql), _ => one_row_delete(*statement) .is_some_and(|(_, predicate)| row_columns(spec, predicate, sql).is_some()), }; let deletes = kinds.iter().filter(|kind| **kind == "delete").count(); // Both node kinds, as `deletes_anything` read them: the `delete` node and // the keyword inside it, which a spelling of `DELETE` the grammar wraps // otherwise would still carry. statements.iter().zip(kinds).all(|(s, k)| one_row(s, k)) && ["delete", "keyword_delete"] .iter() .all(|kind| count_kind(root, kind) == deletes) } /// How many nodes of `kind` the tree holds, at any depth. fn count_kind(node: Node, kind: &str) -> usize { let mut cursor = node.walk(); usize::from(node.kind() == kind) + node .children(&mut cursor) .map(|child| count_kind(child, kind)) .sum::() } /// `sql` as the write gate reads it: unchanged, except on ClickHouse, where /// each mutation spelled exactly as `sql_update_statement` writes it, /// `ALTER TABLE UPDATE WHERE

SETTINGS mutations_sync = 2`, reads as /// the `UPDATE SET WHERE

` it amounts to ([`mutation_as_dml`]), /// which keeps every byte of ``, `` and `

`. /// /// `None`, refusing the submission, for any other statement opening with /// `ALTER`, and on ClickHouse for any comment, a quoted name holding an /// escaped quote, or anything else the server's lexer may read otherwise than /// sqlparser's tokenizer ([`misread`]). The tree-sitter grammar the gate reads /// knows neither nested comments nor backslash escapes in names, which the /// server has, and DBDelve writes no comment and no escaped quote in a name. fn as_written<'sql>(spec: &SqlSpec, sql: &'sql str) -> Option> { if spec.parser_dialect != ParserDialect::ClickHouse { return Some(Cow::Borrowed(sql)); } let dialect = parser(spec.parser_dialect); let tokens = located_tokens(dialect.as_ref(), sql)?; let hidden = tokens.iter().any(|(token, range)| match token { Token::Whitespace( Whitespace::SingleLineComment { .. } | Whitespace::MultiLineComment(_), ) => true, Token::Word(word) => { word.quote_style.is_some() && escaped_quote(&sql[range.clone()], b"'\"`") } _ => false, }); if hidden || misread(sql, &tokens) { return None; } let pieces = between_semicolons(&tokens); let altered = |piece: &Range| { let first = tokens .iter() .find(|(token, range)| { range.start >= piece.start && !matches!(token, Token::Whitespace(_)) }) .map(|(token, _)| token); is_keyword(first.as_ref(), "ALTER") }; if !pieces.iter().any(altered) { return Some(Cow::Borrowed(sql)); } pieces .iter() .map(|piece| { let text = &sql[piece.clone()]; match altered(piece) { true => alter_update_as_update(spec, text).map(|dml| format!("{dml};")), false => Some(format!("{text};")), } }) .collect::>>() .map(|statements| Cow::Owned(statements.join("\n"))) } /// The `UPDATE` an `ALTER TABLE … UPDATE` amounts to, only when `statement` is /// exactly the spelling `sql_update_statement` writes for /// [`UpdateSpelling::AlterUpdate`]: one space between words, upper case, and /// `SETTINGS mutations_sync = 2` last, so the statement returns once every /// replica has the change rather than while it is still pending. fn alter_update_as_update(spec: &SqlSpec, statement: &str) -> Option { let mutation = read_mutation(spec, statement)?; let exact = format!( "ALTER TABLE {} UPDATE {} SETTINGS mutations_sync = 2", &statement[mutation.table], &statement[mutation.body] ); (mutation.updates && statement == exact).then_some(mutation.dml) } /// Whether `sql` is one lone `BEGIN`, `BEGIN TRANSACTION`, `COMMIT` or /// `ROLLBACK`, spelled as dbdelve writes it: the brackets of an import's /// transaction, which spans submissions on a connection of the import's own. /// Compared as text, so a bracket is never admitted beside anything else. pub(crate) fn is_transaction_bracket(sql: &str) -> bool { let sql = sql.trim(); let sql = sql.strip_suffix(';').unwrap_or(sql).trim(); matches!(sql, "BEGIN" | "BEGIN TRANSACTION" | "COMMIT" | "ROLLBACK") } /// Whether `statement` is one `INSERT` naming its columns, of one or more rows /// of literals, ending in nothing or in Import Rows' fixed skip clause. /// /// No subquery, function call, expression or `SELECT` source, because a value /// that computes something is a value dbdelve did not write. The skip clause is /// compared as text as well as read from the tree: `ON CONFLICT (a) DO NOTHING` /// and `ON DUPLICATE KEY UPDATE a = VALUES(a)` are real clauses nothing /// generates. fn literal_insert(statement: Node, sql: &str) -> bool { literal_insert_shape(statement, sql).is_some() } /// [`literal_insert`] for a draft's `INSERT`: one row, and nothing after it. /// A row-skipping tail is Import Rows' clause and a second row is its chunk, /// and neither is something the grid writes. fn one_row_literal_insert(statement: Node, sql: &str) -> bool { literal_insert_shape(statement, sql) == Some(InsertShape { rows: 1, tail: false, }) } /// What [`literal_insert`] admitted: how many rows of literals the statement /// holds and whether a row-skipping tail follows them. #[derive(PartialEq, Eq)] struct InsertShape { rows: usize, tail: bool, } /// The table `INSERT INTO …` names, read as [`literal_insert_shape`] reads it. fn insert_target(statement: Node) -> Option { let insert = statement .named_child(0) .filter(|node| node.kind() == "insert")?; let mut cursor = insert.walk(); let children: Vec<_> = insert.named_children(&mut cursor).collect(); match children.as_slice() { [keyword, into, target, ..] if keyword.kind() == "keyword_insert" && into.kind() == "keyword_into" && target.kind() == "object_reference" => { Some(*target) } _ => None, } } fn literal_insert_shape(statement: Node, sql: &str) -> Option { // `RETURNING` hangs beside the insert, not under it. let insert = statement .named_child(0) .filter(|_| statement.named_child_count() == 1)?; let mut cursor = insert.walk(); let children: Vec<_> = insert.named_children(&mut cursor).collect(); let [keyword, into, target, columns, values, rest @ ..] = children.as_slice() else { return None; }; let kinds = [keyword, into, target, columns, values].map(|node| node.kind()); if kinds != [ "keyword_insert", "keyword_into", "object_reference", "list", "keyword_values", ] || !plain_columns(*columns, sql) { return None; } let rows = rest.iter().take_while(|node| node.kind() == "list").count(); let (rows, tail) = rest.split_at(rows); let literal_rows = rows.iter().all(|row| { let mut cursor = row.walk(); let values: Vec<_> = row.named_children(&mut cursor).collect(); !values.is_empty() && values .iter() .all(|value| literal_value(*value, sql) || null_literal(*value, sql)) }); let last = rows.last()?; let text = sql.get(last.end_byte()..insert.end_byte())?.trim(); let tail_kinds: Vec<_> = tail.iter().map(|node| node.kind()).collect(); let skip = match tail_kinds.as_slice() { [] => text.is_empty(), [ "keyword_on", "keyword_conflict", "keyword_do", "keyword_nothing", ] => text == "ON CONFLICT DO NOTHING", [ "keyword_on", "keyword_duplicate", "keyword_key", "keyword_update", "assignment_list", ] => updates_itself(tail[4], sql) .is_some_and(|column| text == format!("ON DUPLICATE KEY UPDATE {column} = {column}")), _ => false, }; (literal_rows && skip).then_some(InsertShape { rows: rows.len(), tail: !tail.is_empty(), }) } /// A column list whose every entry is a plain or quoted name. A `"…"` name is a /// `literal` to this grammar, so the quote character is what tells it from a /// string. fn plain_columns(list: Node, sql: &str) -> bool { let mut cursor = list.walk(); let columns: Vec<_> = list.named_children(&mut cursor).collect(); !columns.is_empty() && columns.iter().all(|column| { let mut cursor = column.walk(); let named: Vec<_> = column.named_children(&mut cursor).collect(); column.kind() == "column" && matches!(named.as_slice(), [name] if name.kind() == "identifier" || (name.kind() == "literal" && sql.get(name.byte_range()).is_some_and(|text| text.starts_with('"')))) }) } /// The text of `c` when `assignments` is exactly one `c = c`, the same bare or /// backticked name on both sides, which is MySQL's spelling of doing nothing. /// Not `"c"`: under MySQL's default `sql_mode` that is a string. fn updates_itself<'sql>(assignments: Node, sql: &'sql str) -> Option<&'sql str> { let assignment = assignments .named_child(0) .filter(|_| assignments.named_child_count() == 1)?; let left = assignment.child_by_field_name("left")?; let right = assignment.child_by_field_name("right")?; let text = sql.get(left.byte_range())?; (assignment.named_child_count() == 2 && [left, right] .iter() .all(|side| side.kind() == "field" && field_name(*side, sql).is_some()) && sql.get(right.byte_range()) == Some(text)) .then_some(text) } /// Whether `sql` is a `DELETE` whose `WHERE` names exactly `keys` — nothing /// absent from the key, and nothing in the key absent from the predicate. /// /// The half of the delete admission `is_generated_write` cannot make alone: it /// has no key to compare a predicate against. This is not a second gate and /// admits nothing — it is a readout — and a caller runs both. /// /// Set equality, order-independent. A composite key matched on half of itself /// reaches every row sharing that half. /// /// Reads literals as strictly as [`is_generated_write`] does; callers outside /// the tests go through [`delete_matches_key_on`]. #[cfg(test)] pub fn delete_matches_key(sql: &str, keys: &[&str]) -> bool { delete_key_matches(&STRICTEST, sql, keys) } fn delete_key_matches(spec: &SqlSpec, sql: &str, keys: &[&str]) -> bool { let Some(columns) = as_written(spec, sql).and_then(|sql| delete_key_columns(spec, &sql)) else { return false; }; columns.len() == keys.len() && keys.iter().all(|key| columns.iter().any(|c| c == key)) } /// [`is_generated_write`] for the engine the statement is bound for. A /// MongoDB grid writes mongosh statements, so its gate is `mql`'s, which /// admits the same shapes read out of its own parse, less the transaction /// bracket and with `insertMany` for the multi-row insert. pub fn is_generated_write_on(engine: Engine, statement: &str) -> bool { match engine.syntax() { Syntax::Mongo => crate::mql::is_generated_write(statement), Syntax::Redis => crate::redis_cmd::edit::is_generated_write(statement), Syntax::Sql => generated_write(&engine.spec().sql, statement), } } /// The statements of a write [`is_generated_write_on`] admits, each as its own /// text, the transaction bracket the gate sees through dropped: for a driver /// that brackets them in a transaction of its own rather than in text. Each /// passes the gate alone too. `None` for anything the gate refuses, for a lone /// bracket, which writes no row, and for a statement the gate reads as other /// text than it is ([`as_written`]). /// /// Cut from the tree the gate reads, since the grammar holds `BEGIN; …; /// COMMIT` as one statement a splitter of the buffer would never separate. /// For MongoDB, which has no bracket, the statements are the spans of /// `mql::parse`, and each passes `mql::is_generated_write` alone as a /// one-statement write. Redis writes no batch of this shape. pub(crate) fn generated_writes(engine: Engine, sql: &str) -> Option> { generated_writes_for(engine, false, sql) } /// [`generated_writes`] for a plugin that speaks `engine`'s dialect. Its grid /// writes no reviewed draft and no row named by every value, so the shapes /// those switches admit ([`SqlSpec::drafts`], [`SqlSpec::null_terms`]) stay /// refused: they belong to the engines whose built-in grid writes them. pub(crate) fn plugin_generated_writes(engine: Engine, sql: &str) -> Option> { generated_writes_for(engine, true, sql) } fn generated_writes_for(engine: Engine, plugin: bool, sql: &str) -> Option> { match engine.syntax() { Syntax::Sql => {} Syntax::Mongo => return mongo_writes(sql), Syntax::Redis => return None, } if is_transaction_bracket(sql) { return None; } let mut own = engine.spec().sql; if plugin { own.drafts = false; own.null_terms = false; } let spec = &own; let Cow::Borrowed(text) = as_written(spec, sql)? else { return None; }; if !generated_write(spec, text) { return None; } let tree = parse_gated(text, spec)?; let statements: Vec = generated_statements(&tree.root_node())? .iter() .map(|statement| { let statement = text[statement.byte_range()].trim(); statement.strip_suffix(';').unwrap_or(statement).to_owned() }) .collect(); statements .iter() .all(|statement| !is_transaction_bracket(statement) && generated_write(spec, statement)) .then_some(statements) } /// [`generated_writes`] for MongoDB: refused where the gate refuses, and /// otherwise each statement's own text from the parse, without its `;`. fn mongo_writes(text: &str) -> Option> { if !crate::mql::is_generated_write(text) { return None; } let statements: Vec = crate::mql::parse(text) .ok()? .iter() .map(|statement| text.get(statement.span.clone()).map(str::to_owned)) .collect::>()?; statements .iter() .all(|statement| crate::mql::is_generated_write(statement)) .then_some(statements) } /// [`delete_matches_key`] for the engine the statement is bound for. pub fn delete_matches_key_on(engine: Engine, statement: &str, keys: &[&str]) -> bool { match engine.syntax() { Syntax::Mongo => crate::mql::delete_matches_key(statement, keys), Syntax::Redis => crate::redis_cmd::edit::delete_matches_key(statement, keys), Syntax::Sql => delete_key_matches(&engine.spec().sql, statement, keys), } } /// How many `DELETE`s `batch` holds, when every one of them names exactly /// `keys` on `schema.table`, every `UPDATE` does too, and every `INSERT` is /// into `schema.table`: the readout [`is_generated_write_on`] cannot give, /// because no key or table reaches it. The caller compares the count with the /// rows the user marked. /// /// A reviewed draft needs both answers. The gate reads a statement's shape and /// admits any one-row `WHERE` on any table, and an `UPDATE`'s set values but /// not its `WHERE`; this reads which columns and which table, so a statement /// on another table, an `UPDATE` with no `WHERE`, or one by half a composite /// key, is `None` here though the gate admitted it. Like /// [`delete_matches_key_on`] it is a readout and admits nothing. /// /// Kinds are read from the same parse tree the gate reads, never from the /// caller's word: a statement is a `DELETE` when the tree says so, and an /// `UPDATE` whose `WHERE` names the key is not counted. `Some(0)` for a batch /// with no `DELETE`. `None` on any `DELETE` that does not match, on anything /// the gate's parse refuses (an empty text included), and on Redis, which /// writes no draft of this shape. MongoDB's is read by /// [`crate::mql::draft_deletes_match`], whose collection is `table`. // ponytail: only a top-level `DELETE` is counted. One hidden elsewhere in the // tree is not found here, because the gate's whole-tree count of `delete` nodes // refuses it first, and a caller runs both. pub fn draft_deletes_match( engine: Engine, batch: &str, keys: &[&str], schema: &str, table: &str, ) -> Option { match engine.syntax() { Syntax::Sql => {} Syntax::Mongo => return crate::mql::draft_deletes_match(batch, keys, table), Syntax::Redis => return None, } let spec = engine.spec(); let sql = as_written(&spec.sql, batch)?; let tree = parse_gated(&sql, &spec.sql)?; let root = tree.root_node(); let relation = spec.qualified(schema, table); let mut deletes = 0; let statements = generated_statements(&root)?; if statements.is_empty() { return None; } let names_key = |predicate: Node| { row_columns(&spec.sql, predicate, &sql).is_some_and(|columns| { columns.len() == keys.len() && keys.iter().all(|key| columns.iter().any(|c| c == key)) }) }; for statement in statements { if statement.kind() != "statement" { return None; } let (target, keyed) = match statement.named_child(0).map(|node| node.kind()) { Some("delete") => { let (target, predicate) = one_row_delete(statement)?; deletes += 1; (target, names_key(predicate)) } Some("update") => { let (target, _, filter) = update_parts(statement)?; (target, names_key(predicate_of(filter)?)) } Some("insert") => (insert_target(statement)?, true), _ => return None, }; if !keyed || sql.get(target.byte_range()) != Some(relation.as_str()) { return None; } } Some(deletes) } /// `SELECT COUNT(*) FROM WHERE

` for one generated `UPDATE`, `DELETE` /// or ClickHouse `ALTER TABLE … UPDATE`: how many rows `statement` would /// write, counted with its own table and predicate, so a row named by every /// value is written only when exactly one row has those values. /// /// `` and `

` are cut from the tree the write gate reads, never from the /// generator's word, and only from a statement the gate admits whose predicate /// is a conjunction of one-row terms. `None` for anything else, and for a count /// [`is_generated_select`] does not admit: a caller that gets no guard runs /// nothing. pub fn row_guard(engine: Engine, statement: &str) -> Option { if engine.syntax() != Syntax::Sql { return None; } let spec = &engine.spec().sql; if is_transaction_bracket(statement) || !generated_write(spec, statement) { return None; } let text = as_written(spec, statement)?; let tree = parse_gated(&text, spec)?; let [one] = only_statement(&tree.root_node())?; let (table, predicate) = one_row_delete(one) .filter(|(_, predicate)| row_columns(spec, *predicate, &text).is_some()) .or_else(|| one_row_update(spec, one, &text))?; let guard = format!( "SELECT {} FROM {} WHERE {}", spec.count_all.aggregate(), text.get(table.byte_range())?, text.get(predicate.byte_range())? ); is_generated_select(engine, &guard).then_some(guard) } /// `SELECT * FROM WHERE

` for one generated `UPDATE`: the read that /// brings back the row it wrote, so the grid shows what the server now holds /// and not what was typed (a column's affinity, a default, a trigger). /// /// `` and `

` are cut from the tree the write gate reads, never from the /// generator's word, and only from a statement the gate admits whose predicate /// is a conjunction of one-row terms. A key column is never assigned, so on a /// row named by its key `

` is the update's own. A row named by every value /// is found again only by the values it now holds: each term of a column the /// `SET` assigns is replaced by that assignment's literal (`IS NULL` for a /// NULL), and a column assigned anything else that the predicate names -- a /// `DEFAULT` -- has no known value, so there is no read. `None` for anything /// else too -- more than one statement, a statement that is not an `UPDATE` -- /// and for a read [`is_generated_select`] does not admit: a caller that gets /// no read sends nothing. /// /// ClickHouse's `ALTER TABLE … UPDATE` is read as the update it is, so it has a /// read too; no Row send is made there (`Target::row_edits`). MongoDB's is the /// `find` of the `_id` ([`crate::mql::browse::row_reread`]); Redis has none. pub(crate) fn row_read(engine: Engine, statement: &str) -> Option { match engine.syntax() { Syntax::Sql => {} // An `updateOne` never changes `_id`, so the read by the `_id` the write // names finds the document it wrote. Syntax::Mongo => return crate::mql::browse::row_reread(statement), Syntax::Redis => return None, } let spec = &engine.spec().sql; if is_transaction_bracket(statement) || !generated_write(spec, statement) { return None; } let text = as_written(spec, statement)?; let tree = parse_gated(&text, spec)?; let [one] = only_statement(&tree.root_node())?; let (table, assignments, filter) = update_parts(one)?; let predicate = predicate_of(filter)?; row_columns(spec, predicate, &text)?; let read = format!( "SELECT * FROM {} WHERE {}", text.get(table.byte_range())?, held_predicate(spec, predicate, &assignments, &text)? ); is_generated_select(engine, &read).then_some(read) } /// `predicate`'s text with each term of a column `assignments` set naming the /// value that column now holds, or `None` where it holds none the statement /// spells: an assignment that is neither a literal nor `NULL`. fn held_predicate( spec: &SqlSpec, predicate: Node, assignments: &[Node], sql: &str, ) -> Option { let mut set = Vec::new(); for assignment in assignments { let mut cursor = assignment.walk(); let sides: Vec<_> = assignment.children(&mut cursor).collect(); let [left, _, right] = sides.as_slice() else { return None; }; let held = if literal_value(*right, sql) { Some(format!(" = {}", sql.get(right.byte_range())?)) } else if null_literal(*right, sql) { Some(" IS NULL".to_owned()) } else { None }; // An assignment's target is an `identifier` where a predicate's column // is a `field` or a `literal`, so it is unquoted from its own text. let target = sql.get(left.byte_range())?; let column = match target.chars().next()? { quote @ ('"' | '`') => unquote(target, quote), _ => target.to_owned(), }; set.push((column, held)); } let mut terms = Vec::new(); conjuncts(predicate, &mut terms); let (start, end) = (predicate.start_byte(), predicate.end_byte()); let (mut text, mut at) = (String::new(), start); for term in terms { let mut named = Vec::new(); if !equality_columns(spec, term, sql, &mut named) { return None; } let Some((_, held)) = set.iter().find(|(column, _)| named.contains(column)) else { continue; }; let mut cursor = term.walk(); let left = term.children(&mut cursor).next()?; text.push_str(sql.get(at..left.end_byte())?); text.push_str(held.as_deref()?); at = term.end_byte(); } text.push_str(sql.get(at..end)?); Some(text) } /// The terms of a conjunction, in the order they are written. fn conjuncts<'tree>(node: Node<'tree>, terms: &mut Vec>) { let mut cursor = node.walk(); let children: Vec<_> = node.children(&mut cursor).collect(); match children.as_slice() { [left, operator, right] if node.kind() == "binary_expression" && operator.kind() == "keyword_and" => { conjuncts(*left, terms); conjuncts(*right, terms); } _ => terms.push(node), } } /// The table one generated `INSERT`, `UPDATE` or `DELETE` writes, one entry /// per dotted part of its name with the quoting taken off, as `engine`'s /// dialect reads it. `None` for anything else, or for more than one table. pub(crate) fn written_table(engine: Engine, statement: &str) -> Option> { use sqlparser::ast::FromTable; let dialect = dialect(engine)?; let mut statements = SqlParser::parse_sql(dialect.as_ref(), statement).ok()?; let one = statements.pop().filter(|_| statements.is_empty())?; let relation = |factor: &TableFactor| match factor { TableFactor::Table { name, .. } => Some(name.clone()), _ => None, }; let name: ObjectName = match &one { Statement::Insert(Insert { table: TableObject::TableName(name), .. }) => name.clone(), Statement::Update(Update { table, .. }) if table.joins.is_empty() => { relation(&table.relation)? } Statement::Delete(Delete { tables, from, .. }) if tables.is_empty() => { let (FromTable::WithFromKeyword(from) | FromTable::WithoutKeyword(from)) = from; match from.as_slice() { [only] if only.joins.is_empty() => relation(&only.relation)?, _ => return None, } } _ => return None, }; name.0 .iter() .map(|part| part.as_ident().map(|ident| ident.value.clone())) .collect() } /// `SELECT * FROM WHERE

LIMIT 2` for one generated `UPDATE` or one-row /// `DELETE`: the read of the row it writes, taken inside the apply's /// transaction before any write so the row can be compared with the one the /// user read, and bounded at the two rows that prove it ambiguous. /// /// Cut as [`row_read`] is, from the tree the write gate reads and never from /// the generator's word, and returned only when [`is_generated_select`] admits /// it. Unlike [`row_guard`], an `UPDATE`'s assignments are not inspected: a /// `DEFAULT` among them is no reason to leave the row unread. `None` for an /// `INSERT`, which has no row to read, for a bracket, for more than one /// statement, for a `DELETE` or `UPDATE` whose `WHERE` is not a conjunction of /// one-row terms, and for Redis: a caller that gets no read sends /// nothing, so a draft whose write has no re-read is not reviewed. MongoDB's is /// the `find` of the `_id` the write names ([`crate::mql::browse::row_reread`]); /// Redis has none. pub(crate) fn row_reread(engine: Engine, statement: &str) -> Option { match engine.syntax() { Syntax::Sql => {} Syntax::Mongo => return crate::mql::browse::row_reread(statement), Syntax::Redis => return None, } let spec = &engine.spec().sql; if is_transaction_bracket(statement) || !generated_write(spec, statement) { return None; } let text = as_written(spec, statement)?; let tree = parse_gated(&text, spec)?; let [one] = only_statement(&tree.root_node())?; let (table, predicate) = one_row_delete(one) .or_else(|| { let (table, _, filter) = update_parts(one)?; Some((table, predicate_of(filter)?)) }) .filter(|(_, predicate)| row_columns(spec, *predicate, &text).is_some())?; // Two rows already prove the predicate names more than one, so no more // are read: a table holding a million copies of the row is not loaded // whole before the apply refuses it. let (table, predicate) = ( text.get(table.byte_range())?, text.get(predicate.byte_range())?, ); // SQL Server's is re-spelled by its arm after the gate, as a preview is // (`paged`): the grammar reads `LIMIT`, and none of T-SQL's paging. let read = format!("SELECT * FROM {table} WHERE {predicate} LIMIT 2"); is_generated_select(engine, &read).then_some(read) } /// Whether `sql` is a `SELECT` dbdelve could have written: exactly one root /// statement, a query, with nothing destructive anywhere under it. /// /// The filter bar is a trust boundary. Everywhere else a statement is either /// wholly the user's or wholly dbdelve's; a filter is the user's text spliced /// into dbdelve's statement, so this is what makes `id = 1; DROP TABLE t` /// structurally impossible rather than merely unlikely. It also guards the /// filters dbdelve writes for itself. /// /// Not the second gate `AGENTS.md` rule 2 forbids. That rule governs the one /// path by which the grid writes, and `is_generated_write` remains its only /// gate; this guards a path that did not previously admit user text at all, /// and it admits no write -- a statement reaching it must be a query. Neither /// is a way around the other, and no generated statement passes through both. /// /// Exactly one root statement rather than `generated_statements`' view through /// a transaction: a preview never brackets anything, so seeing through /// brackets here would only widen what is accepted. pub fn is_generated_select(engine: Engine, sql: &str) -> bool { match engine.syntax() { Syntax::Mongo => return crate::mql::browse::is_generated_read(sql), Syntax::Redis => return crate::redis_cmd::browse::is_generated_read(sql), Syntax::Sql => {} } let Some(tree) = parse_gated(sql, &engine.spec().sql) else { return false; }; let root = tree.root_node(); let mut cursor = root.walk(); // Comments are tree-sitter extras and land at the root too, so anything // that is not the one statement is something dbdelve did not generate. let children: Vec<_> = root.named_children(&mut cursor).collect(); let [statement] = children.as_slice() else { return false; }; let mut cursor = statement.walk(); // A `select` among the statement's own children, not its first: `WITH` // puts `keyword_with` and the cte ahead of the outer query's select, the // same level `select_anchor` reads it back from. A write hides its select // inside its own `insert` or `update` node, so none reaches this level. statement.kind() == "statement" && statement .named_children(&mut cursor) .any(|node| node.kind() == "select") && !forbidden(root) && !deletes_anything(root) } /// The statements to check, seeing through the transaction that brackets a /// batch on an engine which does not make one submission atomic by itself. /// /// The brackets are verified rather than assumed. A `BEGIN` without its /// `COMMIT` would leave the session in an open transaction, and putting a user /// in that state without them having written it is exactly what this gate /// exists to prevent. fn generated_statements<'tree>(root: &Node<'tree>) -> Option>> { let mut cursor = root.walk(); let children: Vec<_> = root.named_children(&mut cursor).collect(); let [transaction] = children.as_slice() else { return Some(children); }; if transaction.kind() != "transaction" { return Some(children); } let mut cursor = transaction.walk(); let mut bracketed: Vec<_> = transaction.named_children(&mut cursor).collect(); // `BEGIN TRANSACTION`, which is how T-SQL has to spell it: the grammar // hangs the second word beside the first. if bracketed.get(1).map(|node| node.kind()) == Some("keyword_transaction") { bracketed.remove(1); } match bracketed.as_slice() { [begin, statements @ .., commit] if begin.kind() == "keyword_begin" && commit.kind() == "keyword_commit" => { Some(statements.to_vec()) } _ => None, } } #[cfg(test)] fn assignments( engine: Engine, columns: &[(&str, NewValue)], types: &[(String, String)], separator: &str, ) -> String { columns .iter() .map(|(column, value)| { format!( "{} = {}", engine.quote_identifier(column), literal(engine, value, type_of(types, column)) ) }) .collect::>() .join(separator) } fn sql_assignments( spec: &EngineSpec, columns: &[(&str, NewValue)], types: &[(String, String)], separator: &str, ) -> Option { columns .iter() .map(|(column, value)| { let literal = sql_literal(spec, value, type_of(types, column))?; Some(format!("{} = {literal}", spec.quote_identifier(column))) }) .collect::>>() .map(|terms| terms.join(separator)) } fn type_of<'a>(types: &'a [(String, String)], column: &str) -> Option<&'a str> { types .iter() .find(|(name, _)| name == column) .map(|(_, data_type)| data_type.as_str()) } #[cfg(test)] fn literal(engine: Engine, value: &NewValue, data_type: Option<&str>) -> String { match value { NewValue::Value(value) => engine.quote_value(value, data_type), NewValue::Null => "NULL".to_string(), NewValue::Default => "DEFAULT".to_string(), NewValue::Bytes(bytes) => engine.binary_literal(bytes).unwrap_or_default(), } } /// What a value with no literal on the engine is refused with. const UNSPELLED: &str = "A value has no literal on this engine."; /// A value as it goes into a statement: quoted, or one of the two keywords that /// stand for there being no value to quote. Unquoted is the only way to write /// either — `'NULL'` and `'DEFAULT'` are the words, and a user who typed one of /// them into a cell meant the word. Bytes are the engine's literal of them, /// `None` where it has none. fn sql_literal(spec: &EngineSpec, value: &NewValue, data_type: Option<&str>) -> Option { match value { NewValue::Value(value) => Some(spec.quote_value(value, data_type)), NewValue::Null => Some("NULL".to_string()), NewValue::Default => Some("DEFAULT".to_string()), NewValue::Bytes(bytes) => spec.binary_literal(bytes), } } /// `DROP` and `TRUNCATE`, anywhere in the tree and under every spelling. Never /// admitted, by any shape, for any reason. /// /// The grammar offers no `drop` or `truncate` node to look for. `DROP TABLE` is /// `drop_table`, one of thirteen `drop_*` siblings, and `TRUNCATE t` is a bare /// `statement` holding a `keyword_truncate` with no wrapper node at all. The /// keyword is the one part every spelling of either has. fn forbidden(node: tree_sitter::Node) -> bool { let mut cursor = node.walk(); matches!(node.kind(), "keyword_drop" | "keyword_truncate") || node.children(&mut cursor).any(forbidden) } /// Any `delete` at all, anywhere in the tree, not only at the root. /// `WITH x AS (DELETE FROM t RETURNING *) UPDATE …` is a real statement shape /// whose root child is an `update` node, so the whitelist alone would let it /// through. fn deletes_anything(node: tree_sitter::Node) -> bool { let mut cursor = node.walk(); matches!(node.kind(), "delete" | "keyword_delete") || node.children(&mut cursor).any(deletes_anything) } /// The columns a single-row `DELETE`'s `WHERE` names, read out of the parse /// tree, or `None` for anything that is not exactly that shape. /// /// Exactly one root statement whose named children are `["delete", "from"]` — /// which is where the grammar puts them, with the `where` under the `from` — /// and whose `WHERE` is a conjunction of equality predicates over distinct, /// unqualified columns against single-quoted literals. A CTE beside the delete, /// a `RETURNING`, a `LIMIT`, an `OR`, a subquery, a function call, a qualified /// column or a second statement all change that child list or that expression /// tree, and so all arrive here as `None`. /// /// On an engine that names a row by every value (`row_terms`), a term may also /// be `toString() = '…'` or ` IS NULL`, and under `null_terms` /// ` IS NULL` alone ([`equality_columns`]). /// /// `sql` is as [`as_written`] gives it. fn delete_key_columns(spec: &SqlSpec, sql: &str) -> Option> { let tree = parse_gated(sql, spec)?; let root = tree.root_node(); if forbidden(root) { return None; } let [statement] = only_statement(&root)?; let (_, predicate) = one_row_delete(statement)?; row_columns(spec, predicate, sql) } /// The root's one child, when it is a statement. fn only_statement<'tree>(root: &Node<'tree>) -> Option<[Node<'tree>; 1]> { let mut cursor = root.walk(); let children: Vec<_> = root.named_children(&mut cursor).collect(); match children.as_slice() { [statement] if statement.kind() == "statement" => Some([*statement]), _ => None, } } /// The table and the predicate of `DELETE FROM WHERE

`, and nothing /// else in `statement`. fn one_row_delete(statement: Node) -> Option<(Node, Node)> { let mut cursor = statement.walk(); let parts: Vec<_> = statement.named_children(&mut cursor).collect(); let [delete, from] = parts.as_slice() else { return None; }; if delete.kind() != "delete" || from.kind() != "from" { return None; } let mut cursor = from.walk(); let inside: Vec<_> = from.named_children(&mut cursor).collect(); let [keyword, relation, filter] = inside.as_slice() else { return None; }; if keyword.kind() != "keyword_from" || relation.kind() != "object_reference" { return None; } Some((*relation, predicate_of(*filter)?)) } /// The table, the assignments and the `where` node of `UPDATE SET … WHERE …` /// and nothing else in `statement`: no alias, `FROM` or `RETURNING`. What the /// assignments hold, and what the `where` holds, are the callers' to read. fn update_parts<'tree>( statement: Node<'tree>, ) -> Option<(Node<'tree>, Vec>, Node<'tree>)> { let mut cursor = statement.walk(); let parts: Vec<_> = statement.named_children(&mut cursor).collect(); let [update] = parts.as_slice() else { return None; }; if update.kind() != "update" { return None; } let mut cursor = update.walk(); let inside: Vec<_> = update.named_children(&mut cursor).collect(); let [keyword, relation, set, assignments @ .., filter] = inside.as_slice() else { return None; }; let mut cursor = relation.walk(); let table: Vec<_> = relation.named_children(&mut cursor).collect(); let [table] = table.as_slice() else { return None; }; if keyword.kind() != "keyword_update" || relation.kind() != "relation" || table.kind() != "object_reference" || set.kind() != "keyword_set" || assignments.is_empty() { return None; } Some((*table, assignments.to_vec(), *filter)) } /// The table and the predicate of `UPDATE SET = , … WHERE

` /// where each `` is a literal or `NULL` and no column is set twice, and /// nothing else in `statement`: no alias, `FROM`, `RETURNING` or expression. fn one_row_update<'tree>( spec: &SqlSpec, statement: Node<'tree>, sql: &str, ) -> Option<(Node<'tree>, Node<'tree>)> { let (table, assignments, filter) = update_parts(statement)?; let mut columns = Vec::new(); for assignment in &assignments { let mut cursor = assignment.walk(); let sides: Vec<_> = assignment.children(&mut cursor).collect(); let [left, equals, right] = sides.as_slice() else { return None; }; if assignment.kind() != "assignment" || equals.kind() != "=" || !(literal_value(*right, sql) || null_literal(*right, sql)) { return None; } columns.push(column_name(spec, *left, sql)?); } distinct(&columns)?; let predicate = predicate_of(filter)?; row_columns(spec, predicate, sql)?; Some((table, predicate)) } /// The predicate of a `where` node holding nothing but `WHERE

`. fn predicate_of(filter: Node) -> Option { let mut cursor = filter.walk(); let clause: Vec<_> = filter.named_children(&mut cursor).collect(); match clause.as_slice() { [keyword, predicate] if filter.kind() == "where" && keyword.kind() == "keyword_where" => { Some(*predicate) } _ => None, } } /// The columns `predicate` names, when it is a conjunction of one-row terms /// over distinct columns. fn row_columns(spec: &SqlSpec, predicate: Node, sql: &str) -> Option> { let mut columns = Vec::new(); if !equality_columns(spec, predicate, sql, &mut columns) { return None; } distinct(&columns)?; Some(columns) } /// A column named twice is a predicate dbdelve never writes, and reading it as /// a one-column key would call a half-matched composite key a whole one. fn distinct(columns: &[String]) -> Option<()> { let unique = columns.iter().collect::>(); (unique.len() == columns.len()).then_some(()) } /// Walks a conjunction, pushing the column each `=` predicate names. False the /// moment anything else appears — an `OR`, another operator, a parenthesized /// group, a subquery, a function call. /// /// Under `row_terms`, two more terms name a column: `toString() = '…'` /// (the server's own text of a value no literal matches exactly, a float or a /// `DateTime64`) and ` IS NULL`; under `null_terms` the second alone, /// which is how a row with a NULL cell is named by every value. Nothing else: /// not `IS NOT NULL`, not a second argument to `toString` (a time zone changes /// its text), not any other function. fn equality_columns( spec: &SqlSpec, node: tree_sitter::Node, sql: &str, columns: &mut Vec, ) -> bool { if node.kind() != "binary_expression" { return false; } let mut cursor = node.walk(); let children: Vec<_> = node.children(&mut cursor).collect(); let [left, operator, right] = children.as_slice() else { return false; }; let column = match operator.kind() { "keyword_and" => { return equality_columns(spec, *left, sql, columns) && equality_columns(spec, *right, sql, columns); } "=" if literal_value(*right, sql) => match left.kind() { "invocation" if spec.row_terms && quoted(*right, sql) => stringified(spec, *left, sql), _ => column_name(spec, *left, sql), }, "keyword_is" if (spec.row_terms || spec.null_terms) && null_literal(*right, sql) => { column_name(spec, *left, sql) } _ => None, }; match column { Some(column) => { columns.push(column); true } None => false, } } /// The column of `toString()`, spelled exactly so: one argument, a /// bare or quoted unqualified column, the function's own name unquoted and /// unqualified. fn stringified(spec: &SqlSpec, invocation: Node, sql: &str) -> Option { let mut cursor = invocation.walk(); let parts: Vec<_> = invocation.children(&mut cursor).collect(); let [function, open, argument, close] = parts.as_slice() else { return None; }; let mut cursor = argument.walk(); let value: Vec<_> = argument.children(&mut cursor).collect(); let [value] = value.as_slice() else { return None; }; let kinds = (function.kind(), open.kind(), argument.kind(), close.kind()); if kinds != ("object_reference", "(", "term", ")") || sql.get(function.byte_range()) != Some("toString") { return None; } column_name(spec, *value, sql) } fn null_literal(node: Node, sql: &str) -> bool { node.kind() == "literal" && sql .get(node.byte_range()) .is_some_and(|text| text.eq_ignore_ascii_case("NULL")) } fn quoted(node: Node, sql: &str) -> bool { sql.get(node.byte_range()) .is_some_and(|text| text.starts_with('\'')) } /// A single-quoted literal and nothing else. `"other"` is a `literal` to this /// grammar too, and matching a column against a column is not naming a row. /// `N'…'` is SQL Server's single-quoted literal, and `0x…` its binary one, /// which is never quoted. /// /// Exactly one token: the grammar reads `'1' '2'` as one `literal`, and every /// engine concatenates adjacent strings, so a quote inside must be doubled. /// /// Not `NULL`: `WHERE id = NULL` matches no row, so only an insert admits it, /// and beside this rather than through it. fn literal_value(node: Node, sql: &str) -> bool { let Some(value) = sql.get(node.byte_range()) else { return false; }; let quoted = value .strip_prefix(['N', 'n']) .unwrap_or(value) .strip_prefix('\'') .and_then(|rest| rest.strip_suffix('\'')) .is_some_and(|inner| inner.replace("''", "").find('\'').is_none()); let hex = value.strip_prefix("0x").is_some_and(|digits| { !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_hexdigit()) }); node.kind() == "literal" && (quoted || hex) } /// Whether every value an `UPDATE` sets is one dbdelve writes: a literal /// [`literal_value`] reads, `NULL`, `DEFAULT`, or the engine's own literal of /// bytes. A function call, a concatenation, a subquery or another column is a /// value dbdelve did not write. The predicate is not read here. fn literal_sets(spec: &SqlSpec, statement: Node, sql: &str) -> bool { let Some(update) = statement.named_child(0) else { return false; }; let mut cursor = update.walk(); let assignments: Vec<_> = update .named_children(&mut cursor) .filter(|node| node.kind() == "assignment") .collect(); !assignments.is_empty() && assignments.iter().all(|assignment| { assignment .child_by_field_name("right") .is_some_and(|value| { literal_value(value, sql) || null_literal(value, sql) || default_keyword(value, sql) || bytes_literal(spec, value, sql) }) }) } /// `DEFAULT`, which this grammar reads as a column of that name. fn default_keyword(node: Node, sql: &str) -> bool { node.kind() == "field" && sql.get(node.byte_range()) == Some("DEFAULT") } /// The engine's literal of bytes ([`BinaryLiteral`]), as a set value only, /// so never a deleted row's key or an inserted value. Hex digits in pairs between the quotes and /// nothing else, so nothing in it can end it early, and in an escape string /// no backslash but the one that opens `\x`. The grammar reads `X'00' 'aa'` /// as one literal, which is why the text and not the node is checked. fn bytes_literal(spec: &SqlSpec, node: Node, sql: &str) -> bool { let Some(text) = sql .get(node.byte_range()) .filter(|_| node.kind() == "literal") else { return false; }; let digits = match spec.binary_literal { Some(BinaryLiteral::EscapeString) => text.strip_prefix(r"E'\\x"), Some(BinaryLiteral::XQuoted) => text.strip_prefix("X'"), // Read by `literal_value`, which admits it as a binary key too. Some(BinaryLiteral::ZeroX) | None => None, }; digits .and_then(|rest| rest.strip_suffix('\'')) .is_some_and(|digits| { digits.len() % 2 == 0 && digits.bytes().all(|byte| byte.is_ascii_hexdigit()) }) } /// A comment anywhere under `node`. The grammar reads MySQL's `#` comment as /// an operator running to the end of the line, so that counts too. fn commented(node: Node, sql: &str) -> bool { let mut cursor = node.walk(); matches!(node.kind(), "comment" | "marginalia") || (node.kind() == "op_other" && sql .get(node.byte_range()) .is_some_and(|text| text.starts_with('#'))) || node .children(&mut cursor) .any(|child| commented(child, sql)) } /// [`parse`] for a gate, refusing a statement holding a string or a quoted /// name the grammar ends somewhere `spec`'s server does not. /// /// The grammar ends a string at the first lone quote whatever precedes it; an /// engine where a backslash escapes reads `\'` as part of the string. /// Everything between would be string to the gate and SQL to the engine, in /// any arm, so the check is on every literal in the tree rather than on the /// values one arm reads. Either quote character, because MySQL reads `"…"` as /// a string with the same escapes, and `quote_literal` doubles every backslash /// on these engines, so nothing it writes has an odd run. /// /// The grammar reads a backticked name on every engine, up to the next /// backtick, and only MySQL, MariaDB and ClickHouse quote with one: Postgres /// lexes a backtick as an operator character, so `` `x; DELETE FROM t; --` `` /// is one name to the gate and a second statement to the server. Where it is /// the quote, a doubled one is an escaped one, which the grammar reads as one /// name ending and the next beginning: `` `x``y` `` reads as table `x` aliased /// `y`, and `x` is the table a row guard cut from that tree would count. /// ClickHouse escapes with a backslash inside one, which the grammar reads raw, /// so a backslash there is refused as well: whether or not it ends the name /// early, the gate would read a name other than the one the server matches. fn parse_gated(sql: &str, spec: &SqlSpec) -> Option { let tree = parse(sql)?; (!misread_node(spec, tree.root_node(), sql)).then_some(tree) } fn misread_node(spec: &SqlSpec, node: Node, sql: &str) -> bool { let text = sql.get(node.byte_range()).unwrap_or_default(); let misread = match node.kind() { "literal" => spec.backslash_escapes && escaped_quote(text, b"'\""), "identifier" if text.starts_with('`') => { spec.identifier_quote != IdentifierQuote::Backtick || sql[node.end_byte()..].starts_with('`') || (spec.identifier_backslash_escapes && text.contains('\\')) } _ => false, }; let mut cursor = node.walk(); misread || node .children(&mut cursor) .any(|child| misread_node(spec, child, sql)) } /// Whether `text` holds one of `quotes` after an odd run of backslashes. fn escaped_quote(text: &str, quotes: &[u8]) -> bool { let bytes = text.as_bytes(); bytes.iter().enumerate().any(|(at, byte)| { quotes.contains(byte) && bytes[..at] .iter() .rev() .take_while(|&&b| b == b'\\') .count() % 2 == 1 }) } /// The unqualified column a predicate's left side names, unquoted. /// /// To this grammar a double quote opens a **string**: a bare or backticked name /// arrives as a `field`, but `"id"` arrives as a `literal` indistinguishable by /// kind from `'id'`, so the quote character is what tells them apart. That /// matters because Postgres and SQLite quote identifiers with `"`, which is /// what `delete_row` writes on both. /// The column `node` names: a bare or backticked name, or a `"…"` one, which /// this grammar reads as a `literal`, except on a spec where `"…"` is a string /// ([`SqlSpec::double_quoted_strings`]), whose `WHERE "id" = 'id'` holds on /// every row. fn column_name(spec: &SqlSpec, node: tree_sitter::Node, sql: &str) -> Option { let text = sql.get(node.byte_range())?; match node.kind() { "field" => field_name(node, sql), "literal" if text.starts_with('"') && !spec.double_quoted_strings => { Some(unquote(text, '"')) } _ => None, } } /// [`column_name`] of a `field`: a bare or backticked name. fn field_name(node: tree_sitter::Node, sql: &str) -> Option { let text = sql.get(node.byte_range())?; // `t.id` puts an `object_reference` under the field beside the // identifier. A qualified column is not one this reads. let mut cursor = node.walk(); let named: Vec<_> = node.named_children(&mut cursor).collect(); let [identifier] = named.as_slice() else { return None; }; (node.kind() == "field" && identifier.kind() == "identifier").then(|| unquote(text, '`')) } fn unquote(text: &str, quote: char) -> String { let doubled = [quote, quote].iter().collect::(); match text.strip_prefix(quote).and_then(|t| t.strip_suffix(quote)) { Some(inner) => inner.replace(&doubled, "e.to_string()), None => text.to_string(), } } fn parse(sql: &str) -> Option { let mut parser = Parser::new(); parser .set_language(&tree_sitter_sequel::LANGUAGE.into()) .ok()?; let tree = parser.parse(sql, None)?; // A statement the grammar could not read whole is a statement whose clause // boundaries are unknown, and splicing against a guess would corrupt SQL // the user wrote. `NULLS FIRST` and `FOR UPDATE` land here today. (!tree.root_node().has_error()).then_some(tree) } /// The node whose children carry `ORDER BY` and `LIMIT`: the query's outermost /// `FROM`. A subquery's own clauses hang under its `subquery` node instead, so /// looking only at this node's children cannot reach into one by accident. fn clause_anchor<'tree>(tree: &'tree Tree, sql: &str) -> Option> { let root = tree.root_node(); let mut cursor = root.walk(); let statements: Vec<_> = root .named_children(&mut cursor) .filter(|node| STATEMENT_KINDS.contains(&node.kind())) .collect(); // One statement, or there is no telling which one the rows came from. let [statement] = statements[..] else { return None; }; // `BEGIN; …; COMMIT` and `DO $$…$$` are runnable but not queries. if statement.kind() != "statement" || sql.get(statement.byte_range()).is_none() { return None; } let mut cursor = statement.walk(); let children: Vec<_> = statement.named_children(&mut cursor).collect(); // The grammar hangs an `EXPLAIN`'s payload off the same statement node, so // the `select` and `from` below belong to the explained query rather than to // anything the result describes. Its rows are a plan -- one text column, // whose order is the tree's shape -- so there is nothing to sort by, and a // spliced `ORDER BY` would silently re-plan a different query than the one // the user asked about. if children.iter().any(|node| node.kind() == "keyword_explain") { return None; } // A `UNION` puts the whole query's `ORDER BY` after its last branch, so its // clauses hang under the set operation rather than the statement. if let Some(set_operation) = children.iter().find(|node| node.kind() == "set_operation") { let mut cursor = set_operation.walk(); let branches: Vec<_> = set_operation.named_children(&mut cursor).collect(); return select_anchor(&branches); } select_anchor(&children) } /// The `from` of a query, and only of a query. /// /// The grammar gives `DELETE FROM t` the same `from` child a `SELECT` has, so a /// `from` alone is not evidence that a sort belongs here — and writing one into /// a `DELETE` is what hard rule 1 forbids outright. A `select` beside it is the /// evidence. `WITH` leaves the outer query's `select` and `from` at this level /// too, beside the cte, so a CTE still sorts. fn select_anchor<'tree>(children: &[tree_sitter::Node<'tree>]) -> Option> { if !children.iter().any(|node| node.kind() == "select") { return None; } children.iter().rfind(|node| node.kind() == "from").copied() } fn child_of_kind<'tree>( node: &tree_sitter::Node<'tree>, kind: &str, ) -> Option> { let mut cursor = node.walk(); node.named_children(&mut cursor) .find(|child| child.kind() == kind) } /// `sql` with `range` replaced by `clause`, tidying only the seam. /// /// Only the whitespace either side of the splice point is touched. Collapsing /// runs of spaces across the whole statement instead would rewrite string /// literals, quoted identifiers and the user's indentation — a silent edit to /// what the statement means, which is the one thing this module must not do. /// /// The seam is a newline when what comes before it ends in a `--` comment, /// which would otherwise run on over the clause and everything after it. The /// tree says whether it is one: a `--` inside a string is not, and a newline /// there would move the `ORDER BY (SELECT NULL)` that [`unpaged`] reads back /// after a space. fn splice(sql: &str, tree: &Tree, range: Range, clause: &str) -> String { let head = sql[..range.start].trim_end(); let tail = sql[range.end..].trim_start(); let after_comment = head .len() .checked_sub(1) .and_then(|last| tree.root_node().descendant_for_byte_range(last, head.len())) .is_some_and(|node| node.kind() == "comment"); let mut spliced = String::with_capacity(head.len() + clause.len() + tail.len() + 2); spliced.push_str(head); for part in [clause, tail] { if part.is_empty() { continue; } if !spliced.is_empty() { let seam = match after_comment && spliced.len() == head.len() { true => '\n', false => ' ', }; spliced.push(seam); } spliced.push_str(part); } spliced } /// The grammar declares exactly these three as the root's statement children. /// Filtering on them is not optional: comments are tree-sitter *extras*, so /// `comment` and `marginalia` also land at the root, and sending one of those /// to the server returns an empty response the user cannot explain. const STATEMENT_KINDS: [&str; 3] = ["statement", "block", "transaction"]; fn collect_statements(tree: &Tree, sql: &str) -> Vec> { let root = tree.root_node(); let mut cursor = root.walk(); let mut statements: Vec> = Vec::new(); // Whether a `;` has closed the statement before this node. Read off the // tree's own `;` tokens rather than off the text between nodes, where one // inside a comment would look the same and is not a separator. let mut separated = true; // Whether the last statement began as text the grammar could not read and // has not reached its `;` yet, so what follows is still part of it. let mut unread = false; for node in root.children(&mut cursor) { if node.kind() == ";" { separated = true; unread = false; continue; } // Whatever the grammar could not read lands in a sibling ERROR node. if node.is_error() { // It can swallow the `;` that ends it -- and whole statements // after that, readable ones included -- so it is cut at its own // separators before anything is made of it. let (pieces, closed) = unread_pieces(sql, node.byte_range()); let mut opened = false; for (index, piece) in pieces.into_iter().enumerate() { // After a statement with no `;` between, the first piece is // that statement's tail. Dropping it would send the head alone, // and the head of a half-typed `DELETE … WHERE` is an // unqualified DELETE. The tail was typed into this statement, // so it goes to the server with it and the server is what // explains the problem. if index == 0 && !separated && let Some(last) = statements.last_mut() { last.end = piece.end; continue; } // Otherwise it is a statement of its own. The grammar is one // dialect's worth of SQL and the servers speak four: `PRAGMA`, // `CALL`, `LISTEN` and `USE` are all statements it has never // heard of, and a buffer holding only one of them used to hold // "no statement to run". Whether it is valid is the server's to // say (hard rule 1 cuts both ways: not rewritten, and not // withheld either). statements.push(piece); opened = true; } separated = closed; unread = (unread || opened) && !closed; continue; } if !STATEMENT_KINDS.contains(&node.kind()) { continue; } // The rest of a statement whose opening the grammar could not read: // `GRANT SELECT ON t TO r` parses as an unread `GRANT` and then a // `SELECT ON t`, and sending the second without the first runs a // statement nobody wrote. if unread && !separated && let Some(last) = statements.last_mut() { if let Some(merged) = trim_range(sql, last.start..node.byte_range().end) { *last = merged; } continue; } if let Some(range) = trim_range(sql, node.byte_range()) { statements.push(range); separated = false; unread = false; } } statements } /// Text the grammar could not read, cut at the `;`s that separate statements /// in it, and whether the last piece was closed by one. /// /// A scan rather than a split, because the text is unparsed by definition and /// a `;` inside a string, a quoted name, a comment or a dollar-quoted body /// separates nothing: cutting a function body at its first `;` would send the /// server half a `CREATE FUNCTION`. /// /// ponytail: standard SQL only. MySQL's `#` line comments and backslash /// escapes are not read, so a `;` inside one of those splits a statement the /// server then rejects. Reading them would break Postgres, where `#` is an /// operator and `\` is not an escape -- the fix is a dialect here, not a /// bigger scanner, and it can wait for someone who hits it. fn unread_pieces(sql: &str, range: Range) -> (Vec>, bool) { let text = sql.get(range.clone()).unwrap_or_default(); let bytes = text.as_bytes(); let mut pieces = Vec::new(); let mut start = 0; let mut index = 0; let mut closed = false; while index < bytes.len() { let rest = &text[index..]; index += match bytes[index] { b';' => { pieces.extend(trim_range(sql, range.start + start..range.start + index)); start = index + 1; 1 } quote @ (b'\'' | b'"' | b'`') => { // A doubled quote is an escaped one, and reads here as one // string ending and another beginning, which comes to the same. 1 + rest[1..] .find(quote as char) .map_or(rest.len() - 1, |end| end + 1) } b'-' if rest.starts_with("--") => rest.find('\n').unwrap_or(rest.len()), // From past the `/*`, or `/*/` would read as a whole comment. b'/' if rest.starts_with("/*") => { rest[2..].find("*/").map_or(rest.len(), |end| end + 4) } b'$' => { // `$$` or `$tag$`, closed by the same marker. let tag = rest[1..] .find('$') .filter(|end| { rest[1..1 + end] .chars() .all(|c| c.is_alphanumeric() || c == '_') }) .map(|end| &rest[..end + 2]); match tag { Some(tag) => rest[tag.len()..] .find(tag) .map_or(rest.len(), |end| end + 2 * tag.len()), None => 1, } } // Byte-wise scan, char-wise slicing: advancing one byte past a // multi-byte character would leave `index` mid-character and the // next `&text[index..]` panics. _ => rest.chars().next().map_or(1, char::len_utf8), }; } match trim_range(sql, range.start + start..range.end) { Some(tail) => pieces.push(tail), None => closed = !pieces.is_empty() || text.trim_end().ends_with(';'), } (pieces, closed) } fn trim_range(sql: &str, range: Range) -> Option> { let slice = sql.get(range.clone())?; let leading = slice.len() - slice.trim_start().len(); let trailing = slice.len() - slice.trim_end().len(); let trimmed = (range.start + leading)..(range.end - trailing); (!trimmed.is_empty()).then_some(trimmed) } /// `sql` blanked, byte for byte, wherever the engine's tokenizer reads a /// comment or a string the grammar would read otherwise: a `#` or `//` /// comment, and the inside of a literal or quoted name holding a backslash. /// /// The grammar knows only `--` comments and doubled quotes. On MySQL a `'` in /// `# don't` or the `\'` of `'O\'Brien'` opened a string it never closed, so /// every `;` after it separated nothing and the rest of the buffer ran as one /// statement. Blanked to the same length, every range still points into `sql`. fn as_grammar_reads(engine: Engine, sql: &str) -> Cow<'_, str> { let Some(dialect) = dialect(engine) else { return Cow::Borrowed(sql); }; // A buffer still being typed may stop tokenizing at an open quote; what // came before it is blanked all the same. let (tokens, _) = located_prefix(dialect.as_ref(), sql); let mut masked: Option> = None; for (token, range) in tokens { let text = &sql[range.clone()]; // A token's span is trusted only where the text under it is that // token: inside a MySQL `/*! … */` the tokenizer places what it // expands at the comment's own start, and blanking there would open // the comment up instead. let blank = match token { Token::Whitespace(Whitespace::SingleLineComment { prefix, .. }) if prefix != "--" && text.starts_with(prefix.as_str()) => { range } Token::Whitespace(_) => continue, _ if text.contains('\\') => match quoted_interior(text) { Some(inside) => range.start + inside.start..range.start + inside.end, None => continue, }, _ => continue, }; let bytes = masked.get_or_insert_with(|| sql.as_bytes().to_vec()); for byte in &mut bytes[blank] { if *byte != b'\n' { *byte = b' '; } } } // Every byte of a span is overwritten, continuation bytes included, and // spans begin and end on characters, so what is left is still UTF-8. match masked.map(String::from_utf8) { Some(Ok(masked)) => Cow::Owned(masked), _ => Cow::Borrowed(sql), } } /// Inside the quotes of a literal or quoted name spelled `'…'`, `"…"` or /// `` `…` ``, after a prefix like `E`, `N` or `_utf8`. `None` for anything /// else, a `$$` body among them, whose delimiters are not one quote. fn quoted_interior(text: &str) -> Option> { let quote = text.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))?; let close = text[quote..].chars().next()?; (matches!(close, '\'' | '"' | '`') && text.len() >= quote + 2 && text.ends_with(close)) .then(|| quote + 1..text.len() - 1) } fn statements_in(sql: &str) -> Vec> { let mut parser = Parser::new(); parser .set_language(&tree_sitter_sequel::LANGUAGE.into()) .ok() .and_then(|_| parser.parse(sql, None)) .map(|tree| collect_statements(&tree, sql)) .unwrap_or_default() } /// The bare words of T-SQL text, and where its `[bracketed]` names are: what is /// left once strings, quoted names and comments are stepped over, so a `GO`, a /// `BEGIN` or an `END` inside one of those is not read as a keyword. /// /// ponytail: block comments are read flat. T-SQL nests them, so an `END` /// after the inner `*/` of `/* /* */ END */` counts; nobody has written one. fn tsql_scan(text: &str) -> (Vec>, Vec>) { let is_word = |c: char| c.is_alphanumeric() || matches!(c, '_' | '@' | '#' | '$'); let (mut words, mut brackets) = (Vec::new(), Vec::new()); let mut index = 0; while let Some(c) = text[index..].chars().next() { let rest = &text[index..]; index += match c { // A doubled quote reads as one string ending and another beginning. '\'' | '"' => 1 + rest[1..].find(c).map_or(rest.len() - 1, |end| end + 1), '[' => { // `]]` is an escaped `]`, not the end of the name. let mut end = 1; loop { match rest[end..].find(']') { Some(found) if rest[end + found + 1..].starts_with(']') => end += found + 2, Some(found) => break end += found + 1, None => break end = rest.len(), } } brackets.push(index..index + end); end } '-' if rest.starts_with("--") => rest.find('\n').unwrap_or(rest.len()), '/' if rest.starts_with("/*") => rest[2..].find("*/").map_or(rest.len(), |end| end + 4), c if is_word(c) => { let len = rest.find(|c| !is_word(c)).unwrap_or(rest.len()); words.push(index..index + len); len } c => c.len_utf8(), }; } (words, brackets) } /// SQL Server's `GO` lines: the word alone on its line, give or take a repeat /// count and a trailing comment. `GO` is sqlcmd's and SSMS's batch separator, /// never T-SQL, and the server reads one sent to it as a column alias. fn go_lines(sql: &str) -> Vec<(Range, Option)> { let (words, _) = tsql_scan(sql); words .into_iter() .filter(|word| sql[word.clone()].eq_ignore_ascii_case("go")) .filter_map(|word| { let start = sql[..word.start].rfind('\n').map_or(0, |at| at + 1); let end = sql[word.end..] .find('\n') .map_or(sql.len(), |at| word.end + at); if !sql[start..word.start].trim().is_empty() { return None; } let tail = sql[word.end..end].trim_start(); let digits = tail.len() - tail.trim_start_matches(|c: char| c.is_ascii_digit()).len(); let rest = tail[digits..].trim(); if !(rest.is_empty() || rest.starts_with("--")) { return None; } // A count too big to read is still a count, never a plain `GO`. let count = (digits > 0).then(|| tail[..digits].parse().unwrap_or(u64::MAX)); Some((start..end, count)) }) .collect() } /// Whether `engine` reads a buffer as `GO`-separated batches. fn batches_on(engine: Engine) -> bool { engine.syntax() == Syntax::Sql && engine.spec().sql.statement_split == StatementSplit::Batches } /// The text between `GO` lines. fn batches(sql: &str) -> Vec> { let mut batches = Vec::new(); let mut start = 0; for (line, _) in go_lines(sql) { batches.push(start..line.start); start = line.end; } batches.push(start..sql.len()); batches } /// One batch's statements. The grammar finds the boundaries, reading each /// `[name]` as a `"name"` of the same length so a `;` or a `'` inside one /// separates nothing and every offset still points into `sql`. Then what T-SQL /// holds together is put back together: a routine's body to the end of the /// batch, and a `BEGIN … END` block (`CASE … END` counted too, as it closes on /// the same word) whole. fn tsql_statements(sql: &str, batch: Range) -> Vec> { let text = &sql[batch.clone()]; let (words, brackets) = tsql_scan(text); let mut masked = text.as_bytes().to_vec(); for bracket in brackets { masked[bracket.clone()].fill(b'_'); masked[bracket.start] = b'"'; if text[bracket.clone()].ends_with(']') { masked[bracket.end - 1] = b'"'; } } // Every byte of a bracket is overwritten, continuation bytes included, so // what is left is still UTF-8. let masked = String::from_utf8(masked).unwrap_or_else(|_| text.to_string()); let word = |index: usize| { words .get(index) .map(|range| text[range.clone()].to_ascii_uppercase()) }; let mut depth = 0usize; let mut depths = Vec::with_capacity(words.len()); for (index, range) in words.iter().enumerate() { match (word(index).as_deref(), word(index + 1).as_deref()) { ( Some("BEGIN"), Some("TRAN" | "TRANSACTION" | "DISTRIBUTED" | "DIALOG" | "CONVERSATION"), ) => {} (Some("END"), Some("CONVERSATION")) => {} (Some("BEGIN" | "CASE"), _) => depth += 1, (Some("END"), _) => depth = depth.saturating_sub(1), _ => {} } depths.push((range.end, depth)); } let depth_at = |offset: usize| match depths.partition_point(|(end, _)| *end <= offset) { 0 => 0, after => depths[after - 1].1, }; let routine = |start: usize| { let first = words.partition_point(|range| range.start < start); let mut opening = (first..first + 4).filter_map(word); let object = match (opening.next().as_deref(), opening.next().as_deref()) { (Some("CREATE"), Some("OR")) => opening.nth(1), (Some("CREATE" | "ALTER"), object) => object.map(str::to_string), _ => None, }; matches!( object.as_deref(), Some("PROC" | "PROCEDURE" | "FUNCTION" | "TRIGGER") ) }; let mut statements: Vec> = Vec::new(); for statement in statements_in(&masked) { match statements.last_mut() { Some(last) if routine(last.start) || depth_at(last.end) > 0 => last.end = statement.end, _ => statements.push(statement), } } statements .into_iter() .map(|range| batch.start + range.start..batch.start + range.end) .collect() } /// What of `sql` to send to SQL Server: the one batch it holds, without the /// `GO` lines around it. More than one batch, or a batch asked to run more than /// once, is refused rather than sent as text the server cannot read. pub(crate) fn one_batch(engine: Engine, sql: &str) -> Result<&str, String> { if !batches_on(engine) { return Ok(sql); } batch_counts(engine, sql)?; // A batch of nothing but comments is not a second batch. let mut batches = batches(sql) .into_iter() .filter(|batch| !tsql_statements(sql, batch.clone()).is_empty()) .filter_map(|batch| trim_range(sql, batch)); match (batches.next(), batches.next()) { (_, Some(_)) => Err("The selection holds more than one batch separated by GO, \ and dbdelve sends one batch at a time." .into()), (batch, None) => Ok(batch.map_or("", |batch| &sql[batch])), } } /// Refused when any `GO` in `sql` carries a count. The count repeats its /// batch, and running it once is not what the buffer says; a selection run a /// batch at a time has to refuse it for the reason a single one does. pub(crate) fn batch_counts(engine: Engine, sql: &str) -> Result<(), String> { if !batches_on(engine) { return Ok(()); } for (_, count) in go_lines(sql) { count.map_or(Ok(()), repeats)?; } Ok(()) } /// Refused when the `GO` that ends the batch holding `offset` carries a count: /// running the statement under the cursor once would quietly drop it. pub(crate) fn batch_repeats(engine: Engine, sql: &str, offset: usize) -> Result<(), String> { if !batches_on(engine) { return Ok(()); } match go_lines(sql) .into_iter() .find(|(line, _)| line.start >= offset) { Some((_, Some(count))) => repeats(count), _ => Ok(()), } } fn repeats(count: u64) -> Result<(), String> { match count { 1 => Ok(()), _ => Err(format!( "GO {count} repeats its batch, and dbdelve runs a batch once." )), } } /// Every pending row as one `UPDATE`, joined into a single string. /// /// All-or-nothing, which each engine reaches differently, and /// `SqlSpec::transaction_opening` is where that per-engine answer lives. Postgres /// runs one submission as a single implicit transaction and needs nothing; /// MySQL and SQLite commit every statement on its own, so a batch of more than /// one is bracketed — in the statement text itself, where the user can read, /// edit and undo it, because dbdelve does not open a transaction behind anyone's /// back. /// /// An error when there is nothing to apply, and an error — rather than a /// shorter batch — when any one row cannot be written: a partial apply is not /// the change the user made, and dbdelve would have no way to say which part of /// it ran. pub(crate) fn update_batch(engine: Engine, rows: &[PendingRow]) -> Result { match engine.syntax() { Syntax::Sql => sql_update_batch(engine.spec(), rows), Syntax::Mongo => crate::mql::update_batch(rows), Syntax::Redis => crate::redis_cmd::edit::update_batch(rows), } } pub(crate) fn sql_update_batch(spec: &EngineSpec, rows: &[PendingRow]) -> Result { if rows.is_empty() { return Err(NO_EDITS.into()); } let statements = update_statements(spec, rows).ok_or(NO_KEY)?; Ok(bracketed(spec, statements.join("\n"), statements.len())) } const NO_EDITS: &str = "There are no edits to apply."; const NO_KEY: &str = "dbdelve cannot name an edited row by its primary key."; fn borrowed(pairs: &[(String, String)]) -> Vec<(&str, &str)> { pairs .iter() .map(|(column, value)| (column.as_str(), value.as_str())) .collect() } fn borrowed_sets(pairs: &[(String, NewValue)]) -> Vec<(&str, NewValue)> { pairs .iter() .map(|(column, value)| (column.as_str(), value.clone())) .collect() } fn borrowed_names(names: &[String]) -> Vec<&str> { names.iter().map(String::as_str).collect() } /// Each row's `UPDATE`, or `None` when any row cannot be named by its key. /// /// Terminated, not separated: the last statement carries its semicolon too, so /// appending to a buffer cannot fuse it onto whatever the user writes next. fn update_statements(spec: &EngineSpec, rows: &[PendingRow]) -> Option> { rows.iter() .map(|row| { sql_update_statement( spec, &row.schema, &row.table, &borrowed_sets(&row.sets), Match { keys: &borrowed(&row.keys), nulls: &borrowed_names(&row.null_keys), }, row.update, &row.types, ) .map(|statement| format!("{statement};")) }) .collect() } /// `batch` inside the engine's own transaction words, when it holds more than /// one statement. Postgres has no words: one submission is already atomic /// there. fn bracketed(spec: &EngineSpec, batch: String, statements: usize) -> String { let opening = spec.sql.transaction_opening().filter(|_| statements > 1); match opening { Some(start) => format!("{start};\n{batch}\nCOMMIT;"), None => batch, } } /// A marked row, named by the key it was fetched with: what the grid hands over /// for a draft's `DELETE`. `null_keys` are the columns of a row named by every /// value that read NULL, as on [`PendingRow`]. pub(crate) struct DraftDelete { pub schema: String, pub table: String, pub keys: Vec<(String, String)>, pub null_keys: Vec, pub types: Vec<(String, String)>, } /// An added row's touched cells, which is every column its `INSERT` names: an /// untouched column is left out, so the server's default applies to it. `None` /// is `NULL`. pub(crate) struct DraftInsert { pub schema: String, pub table: String, pub columns: Vec<(String, Option)>, pub types: Vec<(String, String)>, } /// A draft's `DELETE`s, `UPDATE`s and `INSERT`s as one string, in that order, /// each group in the order given. /// /// Brackets as [`update_batch`] has them, from the engine's own words: more /// than one statement. Postgres writes none. /// /// An error when the draft is empty, and when any row cannot be written, so a /// draft is never sent shorter than it was made. MongoDB's is written by /// [`crate::mql::draft_batch`], which has no bracket. A draft that adds or deletes rows is not written for Redis, /// which never offers one. /// /// The text is not trusted for being written here: the apply passes it through /// [`is_generated_write_on`] and [`draft_deletes_match`] before it is shown. // ponytail: the order is fixed, deletes then updates then inserts, and not // dependency-sorted. A parent marked above its child under an immediate // foreign key, an existing row re-pointed at a new parent, and a two-row unique // swap fail with the server's own error; the bracket rolls the batch back and // the draft is kept. The upgrade is ordering by the relation's keys. pub(crate) fn draft_batch( engine: Engine, deletes: &[DraftDelete], updates: &[PendingRow], inserts: &[DraftInsert], ) -> Result { match engine.syntax() { Syntax::Sql => sql_draft_batch(engine.spec(), deletes, updates, inserts), Syntax::Mongo => crate::mql::draft_batch(deletes, updates, inserts), Syntax::Redis => { Err("A draft that adds or deletes rows is not written for this engine.".into()) } } } /// [`draft_batch`] for a spec of its own, which `src/sql_snapshots` writes. pub(crate) fn sql_draft_batch( spec: &EngineSpec, deletes: &[DraftDelete], updates: &[PendingRow], inserts: &[DraftInsert], ) -> Result { if deletes.is_empty() && updates.is_empty() && inserts.is_empty() { return Err(NO_EDITS.into()); } let mut statements = Vec::new(); for row in deletes { let statement = sql_delete_row( spec, &row.schema, &row.table, Match { keys: &borrowed(&row.keys), nulls: &borrowed_names(&row.null_keys), }, &row.types, ) .ok_or(NO_KEY)?; statements.push(format!("{statement};")); } statements.extend(update_statements(spec, updates).ok_or(NO_KEY)?); for row in inserts { let columns: Vec<(&str, Option<&str>)> = row .columns .iter() .map(|(column, value)| (column.as_str(), value.as_deref())) .collect(); let statement = sql_insert_row(spec, &row.schema, &row.table, &columns, &row.types)?; statements.push(format!("{statement};")); } Ok(bracketed(spec, statements.join("\n"), statements.len())) } /// One row's `UPDATE`: every column in `sets` assigned, every column in `keys` /// matched. /// /// Values go in as literals and are never cast. Postgres applies the target /// column's assignment cast, so `'123'` lands in an `int4` exactly as `123` /// would, and SQLite applies the column's type affinity to the same effect. A /// cast dbdelve chose for itself could only ever be the wrong one. A cleared cell /// is therefore the empty string, and the keywords are [`NewValue`]'s arms of /// their own: three different writes, which is the whole point of spelling two /// of them as something other than a value. Bytes are the engine's literal of /// them, and `None` where it has none. /// /// `keys` carries plain values, because a row identified by a `NULL` is a row /// `=` does not find; the caller drops such a row before it gets here. /// /// `types` names each column's type where it is known, for the engine whose /// literal depends on it (`EngineSpec::quote_value`). A column missing from it is /// quoted the way any value is. /// /// `None` when either list is empty. A statement with no `WHERE` rewrites every /// row in the table and one with no `SET` is not a statement at all, so a caller /// that has lost the row's key gets nothing to run rather than something that /// runs. fn sql_update_statement( spec: &EngineSpec, schema: &str, table: &str, sets: &[(&str, NewValue)], row: Match, update: UpdateSpelling, types: &[(String, String)], ) -> Option { if sets.is_empty() { return None; } let table = spec.qualified(schema, table); let assignments = sql_assignments(spec, sets, types, ", ")?; let predicate = sql_match(spec, row, types)?; Some(match update { UpdateSpelling::Update => format!("UPDATE {table} SET {assignments} WHERE {predicate}"), UpdateSpelling::AlterUpdate => format!( "ALTER TABLE {table} UPDATE {assignments} WHERE {predicate} SETTINGS mutations_sync = 2" ), }) } /// A run at the front of the history, and its statement there only once /// however many times it has been run: a query run five times is one row to /// recall, not five rows to read past. The same rule `store::history` reads /// the file by, so what is held matches what the next launch reads back: a /// run's outcome replaces its start, and the outcome of a run older than the /// one held changes nothing, since two runs of one statement can land in /// either order. pub(crate) fn remember_statement( history: &mut Vec, entry: crate::store::HistoryEntry, ) { if history .iter() .any(|past| past.sql == entry.sql && past.at > entry.at) { return; } history.retain(|past| past.sql != entry.sql); history.insert(0, entry); history.truncate(crate::store::HISTORY_DEPTH); } /// dbdelve's statement appended to the buffer the user is writing in. /// /// The terminator is the whole subtlety: an unterminated statement with an /// `UPDATE` appended to it becomes one statement, and the next `cmd+enter` /// would send both as one. dbdelve is writing here because the user asked it to, /// so the boundary of what they wrote has to survive the ask. pub(crate) fn appended_statement(engine: Engine, buffer: &str, statement: &str) -> String { let text = buffer.trim_end(); if text.is_empty() { return statement.to_string(); } // A Redis command ends with its line, and a `;` would join its last word. if engine.syntax() == Syntax::Redis { return format!("{text}\n\n{statement}"); } format!("{}\n\n{statement}", terminated(text)) } fn terminated(text: &str) -> String { let mut parser = Parser::new(); let end = parser .set_language(&tree_sitter_sequel::LANGUAGE.into()) .ok() .and_then(|_| parser.parse(text, None)) .and_then(|tree| { let root = tree.root_node(); let mut cursor = root.walk(); root.children(&mut cursor) .filter(|node| !matches!(node.kind(), "comment" | "marginalia")) .last() .map(|node| node.end_byte()) }); match end { Some(end) if !text[..end].ends_with(';') => format!("{};{}", &text[..end], &text[end..]), _ => text.to_string(), } } /// What a connection is allowed to do, and what a statement needs in order to /// run. One enum for both, because they are the same three-rung ladder and two /// types would be the same three values under different names. /// /// **Variant order is load-bearing**: `Ord` derives from it, and the whole mode /// check is `required <= allowed`. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Deserialize)] #[serde(rename_all = "kebab-case")] pub(crate) enum Mode { ReadOnly, /// What a profile written before modes existed reads back as -- which is /// what it has always been connecting as. #[default] ReadWrite, Full, } impl Mode { pub(crate) const ALL: [Mode; 3] = [Mode::ReadOnly, Mode::ReadWrite, Mode::Full]; pub(crate) fn next(self) -> Mode { match self { Mode::ReadOnly => Mode::ReadWrite, Mode::ReadWrite => Mode::Full, Mode::Full => Mode::ReadOnly, } } pub(crate) fn label(self) -> &'static str { match self { Mode::ReadOnly => "Read-only", Mode::ReadWrite => "Read-write", Mode::Full => "Full", } } /// How a mode is written to `profiles.toml`: a name rather than a number, /// so the file stays readable and a build that drops a mode still reads /// something it can name in a message. pub(crate) fn slug(self) -> &'static str { match self { Mode::ReadOnly => "read-only", Mode::ReadWrite => "read-write", Mode::Full => "full", } } /// `None` for a slug this build does not have. The caller decides what to do /// with that -- `restore_profile` reads it as Read-only rather than refusing /// the profile, let alone the file it came in. pub(crate) fn from_slug(slug: &str) -> Option { Mode::ALL.into_iter().find(|mode| mode.slug() == slug) } } /// Why a statement needs Full. Carried so the confirmation can name what it is /// about to do, and so a "don't ask again" tick knows what it is silencing. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Destructive { Drop, Truncate, UnfilteredDelete, /// dbdelve could not parse it, so it cannot say what it does. Unreadable, } impl Destructive { const SUPPRESSIBLE: [Destructive; 3] = [ Destructive::Drop, Destructive::Truncate, Destructive::UnfilteredDelete, ]; /// How the confirmation and the picker name a kind. pub(crate) fn label(self) -> &'static str { match self { Destructive::Drop => "DROP", Destructive::Truncate => "TRUNCATE", Destructive::UnfilteredDelete => "DELETE without WHERE", // Unreachable by construction, and the three things that make it so // are worth naming because breaking any one of them lands here: // `gate` answers RunOnce for an unreadable statement and never // Confirm, `suppressible` keeps it out of `confirmed` going in, and // `from_slug` keeps it out coming back off disk. Destructive::Unreadable => unreachable!("an unreadable statement is never named"), } } /// How a silenced kind is written to `profiles.toml`. pub(crate) fn slug(self) -> &'static str { match self { Destructive::Drop => "drop", Destructive::Truncate => "truncate", Destructive::UnfilteredDelete => "unfiltered-delete", Destructive::Unreadable => "unreadable", } } /// `None` for anything that has no business in a silenced list -- a slug this /// build does not have, and `unreadable`, which §5.3 says is never /// suppressible however it got written there. pub(crate) fn from_slug(slug: &str) -> Option { Destructive::SUPPRESSIBLE .into_iter() .find(|kind| kind.slug() == slug) } /// Whether a "don't ask again" tick may silence this kind on a connection. /// Never for `Unreadable`: that would silence an open-ended set -- every /// future typo, every `DO` block -- on one decision about one of them. /// Running those unasked is a separate, app-wide opt-in (`gate_own_run`), /// whose box says that is what it covers. pub(crate) fn suppressible(self) -> bool { !matches!(self, Destructive::Unreadable) } } // No `Default`: it would inherit `Mode`'s, handing out a Read-write verdict to // anyone who reached for it. A verdict is something `classify` concludes. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Verdict { pub(crate) mode: Mode, /// **Every** destructive kind the submission carries, in the order it /// carries them -- not just the first. Suppression is per kind (spec §6), /// so a single slot let one silenced kind mask another: /// `DROP TABLE a; TRUNCATE TABLE b` with DROP silenced ran both, and /// nobody was ever asked about the TRUNCATE. pub(crate) destructive: Vec, } impl Verdict { pub(crate) const READ: Self = Self { mode: Mode::ReadOnly, destructive: Vec::new(), }; pub(crate) const WRITE: Self = Self { mode: Mode::ReadWrite, destructive: Vec::new(), }; pub(crate) const FULL: Self = Self { mode: Mode::Full, destructive: Vec::new(), }; pub(crate) fn destroys(kind: Destructive) -> Self { Self { mode: Mode::Full, destructive: vec![kind], } } /// The more restrictive of two verdicts: the higher mode, and the union of /// what they destroy. A kind only ever arrives with `Mode::Full`, so taking /// the union never smuggles a destructive kind under a lower mode. /// `Unreadable` is the exception, and `classify` returns it alone. pub(crate) fn max(mut self, other: Self) -> Self { self.mode = self.mode.max(other.mode); for kind in other.destructive { if !self.destructive.contains(&kind) { self.destructive.push(kind); } } self } } /// Whether `sql` can be put in an Explain mode, and why not when it cannot. pub(crate) fn explainable(engine: Engine, sql: &str) -> Result<(), String> { match engine.syntax() { Syntax::Mongo => crate::mql::explainable(sql), // The server refuses what it cannot explain, and says so. Syntax::Sql | Syntax::Redis => Ok(()), } } /// The Explain mode of a statement the user typed as an `EXPLAIN` themselves, /// so its answer is shown as a plan rather than as rows. Read off the words in /// front of the statement explained, never off the statement itself. /// /// `None` wherever the answer is a shape `explain::parse` does not read: /// MySQL's traditional `EXPLAIN` and both of MariaDB's are tables, SQLite's /// bare `EXPLAIN` is bytecode, and a `FORMAT` other than text or tree is JSON, /// XML or YAML. Those stay in the grid, where they are at least legible. pub(crate) fn typed_explain(engine: Engine, sql: &str) -> Option { if engine.syntax() == Syntax::Redis { return None; } let Some(dialect) = dialect(engine) else { return crate::mql::typed_explain(sql); }; let tokens = Tokenizer::new(dialect.as_ref(), sql).tokenize().ok()?; let mut tokens = tokens .iter() .filter(|token| !matches!(token, Token::Whitespace(_))) .peekable(); let word = |token: Option<&&Token>, word: &str| matches!(token, Some(Token::Word(found)) if found.value.eq_ignore_ascii_case(word)); if !word(tokens.next().as_ref(), "EXPLAIN") { return None; } match engine.spec().sql.typed_explain { TypedExplain::Postgres if tokens.next_if(|token| **token == Token::LParen).is_some() => { let mut mode = ExplainMode::Plan; loop { let name = tokens.next()?; let argument: Vec = std::iter::from_fn(|| { tokens.next_if(|token| !matches!(token, Token::Comma | Token::RParen)) }) .map(|token| token.to_string().trim_matches('\'').to_ascii_lowercase()) .collect(); if word(Some(&name), "ANALYZE") || word(Some(&name), "ANALYSE") { let off = matches!( argument.as_slice(), [value] if ["false", "off", "0", "no"].contains(&value.as_str()) ); mode = if off { ExplainMode::Plan } else { ExplainMode::Analyze }; } if word(Some(&name), "FORMAT") && argument != ["text"] { return None; } if tokens.next()? == &Token::RParen { return Some(mode); } } } TypedExplain::Postgres => Some( match word(tokens.peek(), "ANALYZE") || word(tokens.peek(), "ANALYSE") { true => ExplainMode::Analyze, false => ExplainMode::Plan, }, ), TypedExplain::MySql => { let analyze = tokens .next_if(|token| word(Some(token), "ANALYZE")) .is_some(); let tree = match tokens.next_if(|token| word(Some(token), "FORMAT")) { Some(_) => tokens.next()? == &Token::Eq && word(tokens.next().as_ref(), "TREE"), None => analyze, }; tree.then_some(match analyze { true => ExplainMode::Analyze, false => ExplainMode::Plan, }) } TypedExplain::Sqlite => (word(tokens.next().as_ref(), "QUERY") && word(tokens.next().as_ref(), "PLAN")) .then_some(ExplainMode::Plan), TypedExplain::None => None, } } /// The lowest mode that may run `sql`, and what makes it dangerous if anything /// does. /// /// Parses with `sqlparser` rather than the tree-sitter parse the rest of this /// module uses. The two do different jobs: tree-sitter is error-tolerant and /// finds statement boundaries in a buffer someone is still typing into; /// this needs a typed statement, and would rather refuse than guess. pub(crate) fn classify(engine: Engine, sql: &str) -> Verdict { parsed(engine, sql).verdict } /// What one parse of a submission says: the verdict [`classify`] returns, and /// what the same parse knows that a `Verdict` drops. Read once, so the human's /// gate and the agent's cannot judge two different readings of one text. struct Parsed { verdict: Verdict, /// How many statements the parse that was judged produced, MariaDB's /// executable comments expanded, so a statement a comment carries is /// counted. statements: usize, /// Whether any statement the walk reached is a `DELETE`, whatever its /// shape: top level, a CTE's body, under `EXPLAIN ANALYZE`, in an `IF` or a /// scripting block, a ClickHouse mutation that amounts to one. On MongoDB /// and Redis it is whether any statement or command removes data, which /// those engines' own readers decide. removes: bool, /// Whether any `ALTER TABLE` the walk reached carries an operation other /// than `ADD COLUMN`. alters: bool, /// Whether any statement the parse judged leaves its session changed: a /// transaction bracket, a `SET`, a `USE`, a temporary table, a temporary /// view, a variable target, a savepoint. Read off the statements themselves, never off /// [`leaves`], which says nothing on an engine that keeps no session and /// also flags plain reads of what the session holds. session: bool, /// Whether any statement is one a server-side script runs from: a Redis /// `EVAL` or `FCALL` (the read-only forms too), `SCRIPT LOAD`, `FUNCTION /// LOAD`, a MongoDB `$where`, `$function` or `$accumulator`. SQL leaves it /// false: its functions are the deny-list's. scripts: bool, /// Whether any statement is one that returns credentials, password hashes, /// the user's privileges or other clients' details (D-27): the Redis /// commands `CONFIG GET`, `CLIENT LIST`, `ACL LIST` and `ACL GETUSER`, a /// MongoDB `currentOp` in any spelling (the command, the `$currentOp` stage /// and the `db.currentOp()` helper) and `connectionStatus` asked for its /// privileges. SQL leaves it false. discloses: bool, /// Whether a Redis line splits but is a command the editor never sends /// (`MONITOR`, `SELECT`): [`classify`] rates it a read because it is never /// sent, so only this tells it from a read that is. unsent: bool, /// Whether any statement the judged parse holds calls a function the /// engine's built-in list does not name, in any clause, in `FROM` or under /// `EXPLAIN`. The agent path reads it; the human path never does, except /// through Generic's raise in [`parsed`]. unlisted_call: bool, /// What a Redis command schedules beyond itself, read by /// [`crate::redis_cmd::expiry`]. Other engines leave it `None`. Only the /// agent path reads it. expiry: Option, } impl Parsed { /// A verdict and a count, for the readings that look at no tree. fn counted(verdict: Verdict, statements: usize) -> Self { Self { verdict, statements, removes: false, alters: false, session: false, scripts: false, discloses: false, unsent: false, unlisted_call: false, expiry: None, } } /// The more restrictive of two readings of one text: the higher verdict, /// the larger count, and every flag either sets. fn merged(self, other: Self) -> Self { Self { verdict: self.verdict.max(other.verdict), statements: self.statements.max(other.statements), removes: self.removes || other.removes, alters: self.alters || other.alters, session: self.session || other.session, scripts: self.scripts || other.scripts, discloses: self.discloses || other.discloses, unsent: self.unsent || other.unsent, unlisted_call: self.unlisted_call || other.unlisted_call, expiry: self.expiry.or(other.expiry), } } fn read(reading: Reading, statements: &[Statement], unlisted_call: bool) -> Self { Self { verdict: reading.verdict, statements: statements.len(), removes: reading.removes, alters: reading.alters, session: statements.iter().any(changes_session), scripts: false, discloses: false, unsent: false, unlisted_call, expiry: None, } } } /// Whether `statement`, or a statement it holds in an `IF` branch or a /// scripting block, leaves its session changed. [`Leaves::add`] answers for /// every kind it knows; it is not changed, because the queue of the user's /// own statements reads it. This adds what an agent cannot be allowed to do /// unseen and the queue does not care about: a savepoint, which brackets a /// transaction an agent has no way to end, and a session change inside a /// branch, and a `SELECT ... INTO` a temporary table or variable that sits /// under a set operation or in parentheses, where [`Leaves::add`] looks only at /// a bare `SELECT`. /// /// A temporary view is added for a reason of its own. It is searched ahead of /// the permanent schema (Postgres's `pg_temp`, SQLite's `temp`), so it shadows /// a table of the same name for every later statement on the session, and a /// write approved after it would hit the view, not the table the human read. fn changes_session(statement: &Statement) -> bool { match statement { Statement::Savepoint { .. } | Statement::ReleaseSavepoint { .. } | Statement::Rollback { savepoint: Some(_), .. } => true, Statement::If(branching) => std::iter::once(&branching.if_block) .chain(&branching.elseif_blocks) .chain(&branching.else_block) .flat_map(ConditionalStatementBlock::statements) .any(changes_session), Statement::StartTransaction { statements, .. } if !statements.is_empty() => { statements.iter().any(changes_session) } Statement::CreateView(view) if view.temporary => true, Statement::Query(query) if selects_into_session(&query.body) => true, _ => { let mut leaves = Leaves::default(); leaves.add(statement); leaves != Leaves::default() } } } /// Whether a `SELECT ... INTO` anywhere in `body` makes a temporary table or /// a variable that lasts the session. It restates the predicate [`Leaves::add`] /// applies to a bare `SELECT`: [`Leaves::add`] reads only that one shape and is /// left as it is because the user's queue reads it, so a set operation or /// parentheses would otherwise hide the target from the agent's gate. fn selects_into_session(body: &SetExpr) -> bool { match body { SetExpr::Select(select) => select.into.as_ref().is_some_and(|into| { into.temporary || into .targets .iter() .any(|target| target.to_string().starts_with(['#', '@'])) }), SetExpr::Query(query) => selects_into_session(&query.body), SetExpr::SetOperation { left, right, .. } => { selects_into_session(left) || selects_into_session(right) } _ => false, } } /// A [`Verdict`] and what the walk that reached it saw that a verdict drops. /// One walk answers for the human's gate and the agent's, so what the agent is /// refused for comes from the tree the verdict was read off, never from the /// text: `classify` keeps only the verdict, and every record of it is unmoved. #[derive(Debug)] struct Reading { verdict: Verdict, removes: bool, alters: bool, } impl Reading { const READ: Self = Self { verdict: Verdict::READ, removes: false, alters: false, }; /// The more restrictive of two readings: [`Verdict::max`] of the verdicts, /// and either flag set by either. fn max(self, other: Self) -> Self { Self { verdict: self.verdict.max(other.verdict), removes: self.removes || other.removes, alters: self.alters || other.alters, } } } impl From for Reading { fn from(verdict: Verdict) -> Self { Self { verdict, removes: false, alters: false, } } } /// [`classify`]'s reading of `sql`, with everything the parse knew. /// /// A comment MySQL or MariaDB runs only from a server version on /// (`/*!50000 … */`, `/*M!100100 … */`) runs or not by a version DBDelve does /// not know here, so the submission is read once for every version range the /// comments split it into ([`versioned_comments`]): each comment run from its /// floor on, ignored below it. The submission needs what the most demanding /// reading needs, so `/*!99999 EXPLAIN */ DELETE FROM t`, a read to a server /// that runs the comment and a delete to one that does not, is the delete. fn parsed(engine: Engine, sql: &str) -> Parsed { let Some(dialect) = dialect(engine) else { return parsed_as_run(engine, sql); }; if engine.spec().sql.parser_dialect != ParserDialect::MySql { return parsed_as_run(engine, sql); } let comments = versioned_comments(dialect.as_ref(), sql); if comments.is_empty() { return parsed_as_run(engine, sql); } let mut floors: Vec = comments.iter().map(|comment| comment.floor).collect(); floors.sort_unstable(); floors.dedup(); let whole = parsed_as_run(engine, sql); if floors.len() > MAX_VERSION_FLOORS { return whole.merged(Parsed::counted(unreadable_verdict(engine), 0)); } let mut merged = whole; for floor in floors { // A server just below `floor`: every comment from it on is a comment. let mut below = sql.to_string(); for comment in comments.iter().filter(|comment| comment.floor >= floor) { below.replace_range(comment.bang..comment.bang + 1, " "); } merged = merged.merged(parsed_as_run(engine, &below)); } merged } /// How many distinct version floors [`parsed`] reads a submission under /// before it stops and calls it unreadable: one parse each, so a text built to /// carry thousands would cost thousands of parses. const MAX_VERSION_FLOORS: usize = 16; /// An executable comment the server runs only from a version on. struct VersionedComment { /// The byte offset of its `!`, which a space in its place turns into a /// comment every server ignores. bang: usize, /// The version it names, the digits as written. floor: u64, } /// Every `/*!NNNNN … */` and `/*M!NNNNN … */` in `sql`, as `dialect`'s lexer /// finds them, so a marker inside a literal or a plain comment is not one. /// /// sqlparser's MySQL tokenizer replaces a `/*! … */` with the tokens of its /// body, placed from where the comment opens, so a token that starts at a /// `/*!` in the text is the first of such a comment's body; one whose body is /// empty leaves none, and runs nothing either way. MariaDB's `/*M! … */` stays /// a comment token. Any digits after `/*!` are a floor; after `/*M!`, only five /// or more are ([`executable_body`]). fn versioned_comments(dialect: &dyn Dialect, sql: &str) -> Vec { let digits_at = |at: usize| { // Every byte counted is one ASCII digit, so the slice is on boundaries. let digits = sql.get(at..).map_or("", |rest| { &rest[..rest.bytes().take_while(u8::is_ascii_digit).count()] }); (digits.len(), digits.parse::().unwrap_or(u64::MAX)) }; let mut comments: Vec = Vec::new(); for (token, range) in located_prefix(dialect, sql).0 { let opening = &sql.as_bytes()[range.start..]; let comment = match token { Token::Whitespace(Whitespace::MultiLineComment(text)) if text .get(..2) .is_some_and(|marker| marker.eq_ignore_ascii_case("M!")) => { let (digits, floor) = digits_at(range.start + 4); (digits >= 5).then_some(VersionedComment { bang: range.start + 3, floor, }) } Token::Whitespace(Whitespace::MultiLineComment(_)) => None, _ if opening.starts_with(b"/*!") => { let (digits, floor) = digits_at(range.start + 3); (digits > 0).then_some(VersionedComment { bang: range.start + 2, floor, }) } _ => None, }; if let Some(comment) = comment && comments.last().is_none_or(|last| last.bang != comment.bang) { comments.push(comment); } } comments } /// [`parsed`] for one reading of which executable comments run: every /// `/*! … */` and `/*M! … */` still in `sql` is run. fn parsed_as_run(engine: Engine, sql: &str) -> Parsed { if engine.syntax() == Syntax::Redis { return Parsed { session: crate::redis_cmd::leaves(sql) != Leaves::default(), removes: crate::redis_cmd::removes(sql), scripts: crate::redis_cmd::runs_script(sql), discloses: crate::redis_cmd::discloses(sql), // Where a line does not split, `classify` has already said // `Unreadable`, which the agent path asks first. unsent: crate::redis_cmd::parse(sql).is_err(), expiry: crate::redis_cmd::expiry(sql), ..Parsed::counted( crate::redis_cmd::classify(sql), crate::redis_cmd::statements(sql).len(), ) }; } let Some(dialect) = dialect(engine) else { return Parsed { removes: crate::mql::removes(sql), scripts: crate::mql::runs_script(sql), discloses: crate::mql::discloses(sql), ..Parsed::counted(crate::mql::classify(sql), crate::mql::statements(sql).len()) }; }; if engine.spec().sql.explain_analyze == Some(ExplainPrefix::Analyze) && let Some(explain) = mariadb_analyze_as_explain(dialect.as_ref(), sql) { return parsed(engine, &explain); } if let Some(american) = analyse_as_analyze(dialect.as_ref(), sql) { return parsed(engine, &american); } let spec = engine.spec(); let calls = calls_verdict(engine, dialect.as_ref(), sql); if spec.sql.unreadable_floor == UnreadableFloor::FirstKeyword { let read = by_statement(engine, dialect.as_ref(), sql); return Parsed { verdict: raised(engine, sql, read.verdict).max(calls), ..read }; } // All or nothing: one statement it cannot read makes the whole submission // one it cannot vouch for. let parser_dialect = spec.sql.parser_dialect; // MySQL ignores a `/*M! … */` that MariaDB runs, and a MySQL profile may // point at either server, so on MySQL the submission is read both ways -- // expanded below ([`executed_tokens`]), and here as MySQL runs it, with the // comment ignored -- and held unreadable as well. MariaDB reads it expanded // only, which is what it runs. let calls = match engine == Engine::MySql && runs_mariadb_comment(dialect.as_ref(), sql) { true => { let ignored = SqlParser::parse_sql(dialect.as_ref(), sql).map_or(Verdict::READ, |statements| { statements .iter() .map(|statement| spec_verdict(spec, statement).verdict) .fold(Verdict::READ, Verdict::max) }); calls.max(unreadable_verdict(engine)).max(ignored) } false => calls, }; // An unreadable verdict carries what the calls in it need as well. let unreadable = || Parsed::counted(unreadable_verdict(engine).max(calls.clone()), 0); if parser_dialect == ParserDialect::Generic && lexes_apart(dialect.as_ref(), sql) || !ends_line_comments_as_sqlparser_does(parser_dialect) && line_comment_past_carriage_return(dialect.as_ref(), sql) { return unreadable(); } let parsed = match executed_tokens(engine, dialect.as_ref(), sql) { // The derived stream is read here and goes no further: the driver is // handed `sql`, exactly as typed. Some(tokens) => tokens.ok().and_then(|tokens| { SqlParser::new(dialect.as_ref()) .with_tokens(tokens) .parse_statements() .ok() }), None => SqlParser::parse_sql(dialect.as_ref(), sql) .or_else(|error| { match db2_spelled(dialect.as_ref(), sql) .filter(|_| parser_dialect == ParserDialect::Generic) { Some(respelled) => SqlParser::parse_sql(dialect.as_ref(), &respelled), None => Err(error), } }) .ok(), }; let Some(statements) = parsed else { return unreadable(); }; // An empty or comment-only string parses to no statements at all. There is // nothing there to be dangerous, and a dialog over nothing is noise -- but // only when the grammar agrees there is nothing, so a range it finds that // the typed parser skipped is refused rather than run silently. if statements.is_empty() && grammar_finds_more_than_comments(engine, dialect.as_ref(), sql) { return unreadable(); } let unlisted_call = statements .iter() .any(|statement| calls_unlisted_function(engine, statement)); let calls = match engine.reads_only_listed_calls() && unlisted_call { true => calls.max(Verdict::WRITE), false => calls, }; let reading = statements .iter() .map(|statement| spec_verdict(engine.spec(), statement)) .fold(Reading::READ, Reading::max); let read = Parsed::read(reading, &statements, unlisted_call); Parsed { verdict: raised(engine, sql, read.verdict).max(calls), ..read } } /// `verdict`, raised by what the whole text says on its own, whichever of /// [`classify`]'s two readings produced it: a call to a function the engine /// denies, or a server-wide `SET`. Both paths go through here, so an engine /// read statement by statement is held to the same rule as one read as a whole. fn raised(engine: Engine, sql: &str, verdict: Verdict) -> Verdict { // Raised, never replaced: the statements above may already need more. if calls_denied_function(engine, sql) || sets_server_wide(engine, sql) { verdict.max(Verdict::WRITE) } else { verdict } } /// What a submission `classify` cannot vouch for is: unreadable, and runnable /// once. The mode is the lowest one it may be run once in -- Read-only where the /// server holds Read-only to reads, otherwise nothing stops what it turns out /// to write, so Read-only may not run it at all. One construction, so a parse /// error and the zero-statement cross-check cannot drift apart. fn unreadable_verdict(engine: Engine) -> Verdict { Verdict { mode: if engine.holds_read_only() { Mode::ReadOnly } else { Mode::ReadWrite }, destructive: vec![Destructive::Unreadable], } } /// Whether the grammar finds a statement range in `sql` that holds more than /// whitespace, semicolons and comments *to `sqlparser`'s own lexer*, for a /// submission `sqlparser` read as no statement at all. /// /// The two parsers disagree on comment-only text, and nearly always because the /// grammar is one standard dialect: it reads a MySQL or Snowflake `#` line /// comment as a statement, and an inner `*/` of a nested comment as a leftover. /// A range is divergent only when the lexer of the engine's own dialect finds a /// real token in it, which is what clears every line comment a dialect has /// without a comment stripper of ours. Leftovers of a nested block comment on /// the two dialects that nest (`*/` lexes as operators) stay refused: rare, and /// the conservative side. A range the lexer cannot read counts as divergent. fn grammar_finds_more_than_comments(engine: Engine, dialect: &dyn Dialect, sql: &str) -> bool { Buffer::for_engine(engine, sql) .statements() .iter() .any(|range| holds_a_token(dialect, &sql[range.clone()])) } /// Whether `text` holds a token to the dialect's own lexer that is neither /// whitespace, a comment nor a `;`. A range it cannot read counts as holding /// one. fn holds_a_token(dialect: &dyn Dialect, text: &str) -> bool { Tokenizer::new(dialect, text) .tokenize() .map_or(true, |tokens| { tokens .iter() .any(|token| !matches!(token, Token::Whitespace(_) | Token::SemiColon)) }) } /// `sql` as the server will read it, for a dialect whose server runs the text /// of a MariaDB-only executable comment (`/*M!100100 … */`): the tokens, with /// each such comment replaced by the tokens of what it holds. `None` where /// there is nothing to expand, so every other submission is read as it always /// was. /// /// The server inlines the comment's text into its neighbours rather than /// running it as a statement of its own, so a fragment (`INTO @y`) belongs to /// the statement around it and a comment followed by a bare statement fuses /// with it into one the server rejects. Expanding in the token stream and /// parsing once reads exactly that, names the destructive kind the inner /// statement carries, and cannot recurse. The one space after each expansion /// keeps two words from fusing into one that neither text holds. /// /// MySQL ignores the marker, and a MySQL profile may point at a MariaDB server /// that runs it, so on MySQL [`parsed`] also reads the submission with the /// comment ignored and holds it unreadable: the expansion alone would take /// `DELETE FROM t /*M! WHERE 1 = 0 */` for a filtered delete when MySQL /// deletes every row. The `/*!` form needs no help here, the pinned tokenizer /// expands it itself. /// /// Never returned beyond [`classify`] and [`calls_denied_function`]: the /// statement DBDelve sends is the statement the user typed. fn executed_tokens( engine: Engine, dialect: &dyn Dialect, sql: &str, ) -> Option, TokenizerError>> { if engine.spec().sql.parser_dialect != ParserDialect::MySql { return None; } let tokens = Tokenizer::new(dialect, sql).tokenize().ok()?; if !tokens.iter().any(|token| executable_body(token).is_some()) { return None; } let mut expanded = Vec::with_capacity(tokens.len()); for token in tokens { match executable_body(&token) { Some(body) => match Tokenizer::new(dialect, body).tokenize() { Ok(inner) => { expanded.extend(inner); expanded.push(Token::Whitespace(Whitespace::Space)); } Err(error) => return Some(Err(error)), }, None => expanded.push(token), } } Some(Ok(expanded)) } /// The text the server runs out of a comment token, when it is a MariaDB-only /// executable comment: `M!`, then a version of no digits or of five or more, /// then the code. One to four digits are not a version, and the server reads /// them as part of a comment it then rejects, so they stay a comment here. /// /// Matched on bytes, as ASCII, because the comment is arbitrary user text: a /// multi-byte character straight after the marker or where the digits end must /// not be split, and a full-width digit is not a version digit. fn executable_body(token: &Token) -> Option<&str> { let Token::Whitespace(Whitespace::MultiLineComment(comment)) = token else { return None; }; let rest = comment .get(..2) .filter(|marker| marker.eq_ignore_ascii_case("M!")) .map(|_| &comment[2..])?; let digits = rest.bytes().take_while(u8::is_ascii_digit).count(); // Every byte counted is one ASCII digit, so `digits` is a character boundary. (!(1..=4).contains(&digits)).then(|| &rest[digits..]) } /// `sql` with what Db2 reads and sqlparser's Generic dialect does not spelled /// so sqlparser reads it, for classifying only: a statement's trailing /// isolation clause, `WITH UR`, `CS`, `RS` or `RR`, blanked out, and a /// statement opening with `VALUES` respelled `SELECT`, so `VALUES 1, 2` is /// read by the expressions it evaluates. Every other token keeps its place. /// `None` when there is neither, or `sql` does not tokenize. fn db2_spelled(dialect: &dyn Dialect, sql: &str) -> Option { let tokens = located_tokens(dialect, sql)?; let words: Vec<&(Token, Range)> = tokens .iter() .filter(|(token, _)| !matches!(token, Token::Whitespace(_))) .collect(); // A span is checked against its text as well as its token: one after // Generic's `/*! … */` expansion points at the wrong text. let spelled = |(token, range): &(Token, Range), keyword: &str| { is_keyword(Some(&token), keyword) && sql .get(range.clone()) .is_some_and(|text| text.eq_ignore_ascii_case(keyword)) }; let mut respelled = sql.to_string(); let mut changed = false; for statement in words.split(|(token, _)| *token == Token::SemiColon) { if let Some(first) = statement.first() && spelled(first, "VALUES") { respelled.replace_range(first.1.clone(), "SELECT"); changed = true; } if let [.., with, level] = statement && spelled(with, "WITH") && ["UR", "CS", "RS", "RR"] .iter() .any(|isolation| spelled(level, isolation)) { for (_, range) in [with, level] { respelled.replace_range(range.clone(), &" ".repeat(range.len())); } changed = true; } } changed.then_some(respelled) } /// Whether `statement` calls, anywhere in it, a function that is not on /// `engine`'s [`SqlSpec::builtin_functions`]: a scalar or aggregate call, or a /// function in `FROM`. A function can write whatever its body does, and nothing /// in the call says. Two readers act on that: on Generic, which holds nothing /// ([`Engine::holds_read_only`]), the human path raises an unlisted call to a /// write; on every engine the agent path asks before one runs at Read-write /// and Full. /// /// Only a bare, unquoted name is matched against the list: `s.upper(x)` and /// `"UPPER"(x)` may name a function of the user's. An overload of a listed /// name the user created with other argument types (Postgres's /// `public.abs(text)` whose body inserts) still reads, since the server picks /// it by its arguments' types, which SQL alone cannot resolve. That is /// accepted: Read-only guards against the user's mistakes, not a schema built /// to trap it. /// /// ponytail: the ceiling is what the text does not show. Postgres field /// notation (`t.f` calls `f(t)` with no parenthesis, and telling it from a /// column takes the catalog), a view, policy, rule, cast or operator that /// calls a function, and a listed name the connected server's version lacks, /// which a user function can take. The upgrade path is a catalog lookup on the /// live connection. fn calls_unlisted_function(engine: Engine, statement: &Statement) -> bool { struct Calls(Engine); impl Visitor for Calls { type Break = (); fn pre_visit_expr(&mut self, expr: &Expr) -> ControlFlow<()> { match expr { Expr::Function(function) if !listed(self.0, &function.name) => { ControlFlow::Break(()) } _ => ControlFlow::Continue(()), } } fn pre_visit_table_factor(&mut self, factor: &TableFactor) -> ControlFlow<()> { match factor { TableFactor::Table { name, args: Some(_), .. } | TableFactor::Function { name, .. } if !listed(self.0, name) => { ControlFlow::Break(()) } _ => ControlFlow::Continue(()), } } } statement.visit(&mut Calls(engine)).is_break() } /// Whether `name` is one bare, unquoted word on `engine`'s built-in list. /// Case is folded unless the server tells names apart by it. fn listed(engine: Engine, name: &ObjectName) -> bool { let sql = &engine.spec().sql; let [ObjectNamePart::Identifier(ident)] = name.0.as_slice() else { return false; }; if ident.quote_style.is_some() { return false; } let folded = match sql.case_sensitive_functions { true => ident.value.clone(), false => ident.value.to_ascii_lowercase(), }; sql.builtin_functions .lines() .any(|line| !line.starts_with('#') && line == folded) } /// What a submission's calls do that its tree does not show, read off its /// tokens wherever they stand, so a call in a statement sqlparser cannot read /// counts too: /// /// - a call no read-only hold stops ([`HOLD_IGNORING_CALLS`]) needs Full; /// - advancing a sequence (`nextval(…)`, `setval(…)`, `NEXT VALUE FOR s`, /// Db2's `NEXTVAL FOR s`, and `s.NEXTVAL` where [`advances_by_name`]) is a /// write: Postgres lets a temporary sequence advance in a read-only /// transaction, and Generic holds nothing; /// - a `set_config` that may lift the read-only hold ([`READ_ONLY_SETTINGS`]) /// is a write. One naming another setting by a plain literal is left alone; /// any other first argument might name the hold. fn calls_verdict(engine: Engine, dialect: &dyn Dialect, sql: &str) -> Verdict { let parser_dialect = engine.spec().sql.parser_dialect; // The calls the server will run, so one inside an executable comment // counts, as it does for [`calls_denied_function`]. let tokens: Vec = match executed_tokens(engine, dialect, sql) { Some(Ok(tokens)) => tokens, _ => located_prefix(dialect, sql) .0 .into_iter() .map(|(token, _)| token) .collect(), }; let tokens: Vec<&Token> = tokens .iter() .filter(|token| !matches!(token, Token::Whitespace(_))) .collect(); let bare = |at: usize, name: &str| matches!(tokens.get(at), Some(Token::Word(word)) if word.quote_style.is_none() && word.value.eq_ignore_ascii_case(name)); let keyword = |at: usize, name: &str| is_keyword(tokens.get(at), name); let called = |at: usize| tokens.get(at + 1) == Some(&&Token::LParen); let call_name = |at: usize| match tokens.get(at) { Some(Token::Word(word)) if called(at) => Some(word.value.to_ascii_lowercase()), _ => None, }; let ignores_hold = (0..tokens.len()) .any(|at| call_name(at).is_some_and(|name| HOLD_IGNORING_CALLS.contains(&name.as_str()))); if ignores_hold { return Verdict::FULL; } let advances = (0..tokens.len()).any(|at| { call_name(at).is_some_and(|name| name == "nextval" || name == "setval") || keyword(at, "NEXT") && keyword(at + 1, "VALUE") && keyword(at + 2, "FOR") || keyword(at, "NEXTVAL") && keyword(at + 1, "FOR") || advances_by_name(parser_dialect) && tokens.get(at) == Some(&&Token::Period) && bare(at + 1, "NEXTVAL") }); let lifts_hold = (0..tokens.len()).any(|at| { call_name(at).as_deref() == Some("set_config") && !matches!( tokens.get(at + 2..at + 4), Some([Token::SingleQuotedString(name), Token::Comma]) if !READ_ONLY_SETTINGS.contains(&name.to_ascii_lowercase().as_str()) ) }); match advances || lifts_hold { true => Verdict::WRITE, false => Verdict::READ, } } /// Whether the servers read in `dialect` advance a sequence by the name /// `s.NEXTVAL`, where anywhere else it is a column: Db2's and Oracle's, which /// Generic stands for, and Snowflake's. MariaDB spells it so only under /// `sql_mode=ORACLE`, a session setting this cannot see, so there it is read /// as the column it is by default. fn advances_by_name(dialect: ParserDialect) -> bool { matches!(dialect, ParserDialect::Generic | ParserDialect::Snowflake) } /// Calls that act outside the transaction they run in, so no read-only hold /// stops them: signalling another backend, reloading or rotating the server's /// configuration and logs, writing the server's files, and running a /// statement down another connection with dblink. const HOLD_IGNORING_CALLS: &[&str] = &[ "pg_terminate_backend", "pg_cancel_backend", "pg_reload_conf", "pg_rotate_logfile", "pg_promote", "pg_switch_wal", "pg_create_restore_point", "pg_file_write", "pg_file_rename", "pg_file_unlink", "lo_import", "lo_export", "dblink", "dblink_exec", "dblink_send_query", ]; /// The settings that hold a session to reads: Postgres's /// `default_transaction_read_only` and `transaction_read_only`, MySQL's and /// MariaDB's `transaction_read_only` and its older name `tx_read_only`. const READ_ONLY_SETTINGS: &[&str] = &[ "default_transaction_read_only", "transaction_read_only", "tx_read_only", ]; /// Whether a `SET` may lift the read-only hold: an assignment to one of /// [`READ_ONLY_SETTINGS`] that is not plainly on (`DEFAULT` is whatever the /// server was started with), or a transaction characteristic of `READ WRITE`. fn set_lifts_hold(set: &Set) -> bool { let lifts = |name: &ObjectName, values: &[Expr]| { let name = name.to_string().to_ascii_lowercase(); let setting = name .rsplit('.') .next() .unwrap_or(&name) .trim_start_matches('@') .trim_matches(['"', '`']); let on = matches!( values, [value] if ["on", "true", "1", "yes"] .contains(&value.to_string().trim_matches('\'').to_ascii_lowercase().as_str()) ); READ_ONLY_SETTINGS.contains(&setting) && !on }; match set { Set::SingleAssignment { variable, values, .. } => lifts(variable, values), Set::ParenthesizedAssignments { variables, .. } => { variables.iter().any(|variable| lifts(variable, &[])) } Set::MultipleAssignments { assignments } => assignments .iter() .any(|assignment| lifts(&assignment.name, std::slice::from_ref(&assignment.value))), Set::SetTransaction { modes, .. } => grants_write(modes), _ => false, } } /// Whether a server whose lexer is not known, as Generic's is not, could /// split `sql` otherwise than sqlparser's Generic tokenizer: a `/*` inside a /// comment, which the tokenizer nests and a server may not, so /// `/* /* */ DELETE FROM t -- */` is one comment to one and a `DELETE` to the /// other; MySQL's `/*! … */` and MariaDB's `/*M! … */`, which they run; a backslash in a literal or a /// quoted name, which ends it a byte later on a server where it escapes; a /// token opening with `$`, a dollar-quoted string or placeholder to the /// tokenizer and a name to Db2, so `$$; DELETE FROM t --$$` hides a `DELETE` /// Db2 runs. A `--` comment a lone carriage return runs through, which /// psqlODBC ends there, is [`line_comment_past_carriage_return`]'s. /// /// Generic's tokenizer replaces a `/*! … */` with the tokens inside it, so no /// comment token is left to see, and those tokens' spans are placed as if the /// `/*!` and any version were not there, so their text is the wrong slice of /// `sql`. The comment is caught instead by the hole it leaves: every other /// token's span picks up where the last one ended, and the tokens of an /// expanded comment never cover its own `*/`. fn lexes_apart(dialect: &dyn Dialect, sql: &str) -> bool { let (tokens, whole) = located_prefix(dialect, sql); let mut end = 0; tokens.iter().any(|(token, range)| { let after_a_hole = std::mem::replace(&mut end, range.end) != range.start; after_a_hole || match token { Token::Whitespace(Whitespace::MultiLineComment(comment)) => { comment.contains("/*") || comment.starts_with('!') || comment.starts_with("M!") } Token::Whitespace(_) => false, Token::DollarQuotedString(_) => true, Token::Placeholder(placeholder) if placeholder.starts_with('$') => true, _ => { let text = &sql[range.clone()]; text.starts_with('$') || text.contains('\\') } } }) || whole && end != sql.len() } /// Whether `sql` holds MariaDB's `/*M! … */`, which MariaDB runs and /// sqlparser's MySQL tokenizer keeps as a comment, unlike the `/*! … */` it /// reads the inside of. MySQL ignores it, and a MySQL profile may well point /// at a MariaDB server, so on MySQL it is unreadable. Either spelling of the /// marker counts, whatever follows it. fn runs_mariadb_comment(dialect: &dyn Dialect, sql: &str) -> bool { located_prefix(dialect, sql).0.iter().any(|(token, _)| { matches!( token, Token::Whitespace(Whitespace::MultiLineComment(comment)) if comment.get(..2).is_some_and(|marker| marker.eq_ignore_ascii_case("M!")) ) }) } /// Whether the servers read in `dialect` end a `--` comment where sqlparser's /// tokenizer does: Postgres's dialect stops at a carriage return as Postgres /// does, and MySQL, MariaDB, SQLite and Turso, like the tokenizer elsewhere, /// run on to a newline. DuckDB's own tokenizer stops at a carriage return, and /// Snowflake's and SQL Server's are not known to agree. fn ends_line_comments_as_sqlparser_does(dialect: ParserDialect) -> bool { matches!( dialect, ParserDialect::PostgreSql | ParserDialect::MySql | ParserDialect::Sqlite ) } /// Whether any `--` comment in `sql` runs on past a carriage return. fn line_comment_past_carriage_return(dialect: &dyn Dialect, sql: &str) -> bool { located_prefix(dialect, sql).0.iter().any(|(token, _)| { matches!( token, Token::Whitespace(Whitespace::SingleLineComment { comment, .. }) if carriage_return_inside(comment) ) }) } /// Whether a `--` comment's text runs on past a carriage return, where a /// server that ends the comment there reads the rest as SQL. fn carriage_return_inside(comment: &str) -> bool { comment.trim_end_matches('\r').contains('\r') } /// [`classify`] where the floor under an unreadable statement is its first /// keyword. Each statement between the tokenizer's `;`s is read on its own: by /// its tree where sqlparser reads it, as the `UPDATE` or `DELETE` a mutation /// amounts to ([`mutation_as_dml`]), and by [`first_keyword_verdict`] /// otherwise. One that cannot be read leaves the whole submission /// `Unreadable`, at the highest mode any statement in it needs. /// /// The server's lexer and sqlparser's tokenizer agree on what is a comment /// (`--` to a newline, `/* */` nested) and where a literal ends, so the first /// word read here is the one the server runs. Where the two may part ways /// ([`misread`]), a word the server runs may be one the tokenizer never saw, /// so the submission needs Full. A tokenizer error is placed by the words it /// read before the error, and at Read-write at least. fn by_statement(engine: Engine, dialect: &dyn Dialect, sql: &str) -> Parsed { let spec = engine.spec(); let (tokens, whole) = located_prefix(dialect, sql); // What the tokenizer stopped at is unread, so anything there [`misread`] // might have caught counts as caught. let unread = &sql[tokens.last().map_or(0, |(_, range)| range.end)..]; let misread = misread(sql, &tokens) || !whole && (unread.contains("//") || unread.contains(|c: char| matches!(c, '#' | '$' | '\\') || !c.is_ascii())); let trusted = whole && !misread; let mut unreadable = !trusted; let mut counted = 0; let mut session = false; let mut unlisted_call = false; let reading = between_semicolons(&tokens) .into_iter() .map(|range| { // A character the tokenizer does not know may be a space to the // server, so the words either side of it count as neighbours. let words: Vec<&Token> = tokens .iter() .filter(|(token, at)| { range.contains(&at.start) && !matches!(token, Token::Whitespace(_) | Token::Char(_)) }) .map(|(token, _)| token) .collect(); let text = &sql[range]; let parsed = match trusted { false => None, true => match mutation_as_dml(spec, text) { Some(dml) => SqlParser::parse_sql(dialect, &dml).ok(), None => SqlParser::parse_sql(dialect, text).ok(), }, }; let reading = match parsed { Some(statements) => { counted += statements.len(); session |= statements.iter().any(changes_session); unlisted_call |= statements .iter() .any(|statement| calls_unlisted_function(engine, statement)); statements .iter() .map(|statement| spec_verdict(spec, statement)) .fold(Reading::READ, Reading::max) } None => { // A range it could not read is still a statement. counted += 1; unreadable = true; first_keyword_verdict(&words).into() } }; reading.max(words_verdict(&words).into()) }) .fold(Reading::READ, Reading::max); let floor = match (misread, whole) { (true, _) => Mode::Full, (false, false) => Mode::ReadWrite, (false, true) => unreadable_verdict(engine).mode, }; let verdict = match unreadable { true => Verdict { mode: reading.verdict.mode.max(floor), destructive: vec![Destructive::Unreadable], }, false => reading.verdict, }; Parsed { verdict, removes: reading.removes, alters: reading.alters, session, unlisted_call, ..Parsed::counted(Verdict::READ, counted) } } /// Whether the server's lexer may read `tokens` otherwise than sqlparser's /// tokenizer did, so that a word one of them sees is hidden from the other: /// /// - a character the tokenizer does not know: the server skips Unicode spaces /// it does not (a zero-width space), and reads curly quotes as quotes; /// - a `#`, `$` or `//` outside a literal: the server starts a comment at /// `# `, `#!` and `//`, and keeps a `$` inside a bare word, so `a$$` is one /// word to it and a word and the start of a dollar-quoted string to the /// tokenizer; /// - a quoted identifier the server ends elsewhere: it escapes a quote with a /// backslash and the tokenizer does not, so ``` `a\`` ``` ends there for /// the server and runs on for the tokenizer; /// - a `--` comment a carriage return runs through, in case the server ends /// it there. fn misread(sql: &str, tokens: &[(Token, Range)]) -> bool { tokens.iter().any(|(token, range)| { // Read off the source rather than the next token: `//*` is a slash // and an unended comment to the tokenizer, which stops there. matches!(token, Token::Div) && sql[range.end..].starts_with('/') || misread_token(token, &sql[range.clone()]) }) } /// [`misread`] for one token, `text` in the source. fn misread_token(token: &Token, text: &str) -> bool { match token { Token::Char(_) => true, Token::Whitespace(Whitespace::SingleLineComment { comment, .. }) => { carriage_return_inside(comment) } Token::Whitespace(_) | Token::SingleQuotedString(_) | Token::NationalStringLiteral(_) | Token::HexStringLiteral(_) => false, Token::Word(word) if word.quote_style.is_some() => !quoted_whole(text), _ => text.contains(['#', '$']), } } /// Whether the server reads `text`, a quoted name as the tokenizer cut it, as /// one quoted name ending where the tokenizer's does: a backslash escapes the /// byte after it, and a doubled quote is a quote. fn quoted_whole(text: &str) -> bool { let bytes = text.as_bytes(); let Some("e) = bytes.first() else { return false; }; let mut at = 1; while at < bytes.len() { match bytes[at] { b'\\' => at += 2, byte if byte == quote && bytes.get(at + 1) == Some("e) => at += 2, byte if byte == quote => return at + 1 == bytes.len(), _ => at += 1, } } false } /// Whether `token` is the unquoted keyword `keyword`. fn is_keyword(token: Option<&&Token>, keyword: &str) -> bool { matches!(token, Some(Token::Word(word)) if word.quote_style.is_none() && word.value.eq_ignore_ascii_case(keyword)) } /// The first words of the statements that only read or change the session. /// The server's `readonly=2` refuses any write and any change to `readonly` /// itself, so one of these runs once on confirmation even in Read-only. const FLOOR_READS: &[&str] = &[ "SELECT", "WITH", "SHOW", "DESCRIBE", "DESC", "EXISTS", "EXPLAIN", "CHECK", "WATCH", "USE", "SET", ]; /// The first words of DDL, access control and server control, `BACKUP` and /// `RESTORE` among them: `readonly=2` stops neither. const FLOOR_FULL: &[&str] = &[ "ALTER", "CREATE", "REPLACE", "DROP", "TRUNCATE", "RENAME", "EXCHANGE", "ATTACH", "DETACH", "UNDROP", "MOVE", "OPTIMIZE", "SYSTEM", "KILL", "GRANT", "REVOKE", "BACKUP", "RESTORE", ]; /// The mode a statement sqlparser cannot read needs, by its first word /// (`words` holds no whitespace or comment). A first word in neither list, or /// a first token that is no word at all, fails closed: Read-write, so /// Read-only refuses it. An `INSERT INTO FUNCTION` is [`words_verdict`]'s. fn first_keyword_verdict(words: &[&Token]) -> Verdict { let first = |list: &[&str]| list.iter().any(|word| is_keyword(words.first(), word)); if first(FLOOR_READS) { Verdict::READ } else if first(FLOOR_FULL) { Verdict::FULL } else { Verdict::WRITE } } /// What a statement's words say, read or not, that its tree or first word /// does not: /// /// - `INTO OUTFILE` writes a file, and `INTO [TABLE] FUNCTION` writes through /// a table function to a URL, a file or another server; /// - `PARALLEL WITH` runs a second statement beside the first; /// - `ON CLUSTER` runs the statement on every server of the cluster (a read's /// `JOIN … ON cluster = …` is left alone); /// - `SET DEFAULT ROLE` changes a user's stored roles, not the session. fn words_verdict(words: &[&Token]) -> Verdict { let at = |index: usize, keyword: &str| is_keyword(words.get(index), keyword); let reads = FLOOR_READS.iter().any(|word| at(0, word)); let full = at(0, "SET") && at(1, "DEFAULT") && at(2, "ROLE") || (0..words.len()).any(|index| { at(index, "OUTFILE") || at(index, "PARALLEL") && at(index + 1, "WITH") || at(index, "INTO") && (at(index + 1, "FUNCTION") || at(index + 1, "TABLE") && at(index + 2, "FUNCTION")) || !reads && at(index, "ON") && at(index + 1, "CLUSTER") }); match full { true => Verdict::FULL, false => Verdict::READ, } } /// [`statement_verdict`], raised by what the engine's spec says of it: a /// `CREATE TABLE` on a table engine outside the spec's `local_table_engines` /// keeps its rows somewhere else, a URL, a file or another server, so it needs /// Full. fn spec_verdict(spec: &EngineSpec, statement: &Statement) -> Reading { let reading = statement_verdict(&spec.sql, statement); let (Some(local), Statement::CreateTable(create)) = (spec.sql.local_table_engines, statement) else { return reading; }; let options = match &create.table_options { CreateTableOptions::None => &[][..], CreateTableOptions::With(options) | CreateTableOptions::Options(options) | CreateTableOptions::Plain(options) | CreateTableOptions::TableProperties(options) => options, }; let listed = |name: &str| local.contains(&name); let elsewhere = options.iter().any(|option| match option { SqlOption::NamedParenthesizedList(list) if list.key.value.eq_ignore_ascii_case("ENGINE") => { !list.name.as_ref().is_some_and(|name| listed(&name.value)) } SqlOption::KeyValue { key, .. } => key.value.eq_ignore_ascii_case("ENGINE"), _ => false, }); match elsewhere { true => reading.max(Verdict::FULL.into()), false => reading, } } /// A ClickHouse mutation spelled as the statement it amounts to: /// `ALTER TABLE t UPDATE … WHERE …` as `UPDATE t SET … WHERE …`, and /// `ALTER TABLE t DELETE WHERE …` as `DELETE FROM t WHERE …`, each with at most /// a trailing `SETTINGS mutations_sync = n`, which is dropped. The text between /// is kept exactly as written. /// /// `None` for anything else after `ALTER`: a second command, `ON CLUSTER`, /// `IN PARTITION`, any other setting, a token the server may read otherwise /// ([`misread`]), or a spelling that does not then read as exactly one `UPDATE` /// or `DELETE` with a `WHERE`. And on every dialect but ClickHouse's, which has /// no mutations. pub(crate) fn mutation_as_dml(spec: &EngineSpec, sql: &str) -> Option { read_mutation(&spec.sql, sql).map(|mutation| mutation.dml) } /// [`mutation_as_dml`]'s reading of a mutation, with where its parts lie in /// the text it was read from. struct Mutation { dml: String, updates: bool, table: Range, /// From the word after `UPDATE` or `DELETE` to the end of the `WHERE`. body: Range, } fn read_mutation(spec: &SqlSpec, sql: &str) -> Option { if spec.parser_dialect != ParserDialect::ClickHouse { return None; } let dialect = parser(spec.parser_dialect); let tokens = located_tokens(dialect.as_ref(), sql)?; if misread(sql, &tokens) { return None; } let mut words: Vec<(&Token, Range)> = tokens .iter() .filter(|(token, _)| !matches!(token, Token::Whitespace(_))) .map(|(token, range)| (token, range.clone())) .collect(); if matches!(words.last(), Some((Token::SemiColon, _))) { words.pop(); } let keyword = |at: usize, keyword: &str| is_keyword(words.get(at).map(|(token, _)| token), keyword); if !keyword(0, "ALTER") || !keyword(1, "TABLE") { return None; } let mut at = 2; loop { if !matches!(words.get(at), Some((Token::Word(_), _))) { return None; } at += 1; match words.get(at) { Some((Token::Period, _)) => at += 1, _ => break, } } let table_range = words[2].1.start..words[at - 1].1.end; let table = &sql[table_range.clone()]; let mut end = words.len(); if end >= at + 4 && keyword(end - 4, "SETTINGS") && keyword(end - 3, "mutations_sync") && matches!(words[end - 2].0, Token::Eq) && matches!(words[end - 1].0, Token::Number(..)) { end -= 4; } let body = &words[at..end]; let updates = keyword(at, "UPDATE"); if !updates && !keyword(at, "DELETE") { return None; } // A comma outside brackets after the `WHERE` starts a second command. let mut depth = 0i32; let mut filter = None; for (index, (token, _)) in body.iter().enumerate() { match token { Token::LParen | Token::LBracket | Token::LBrace => depth += 1, Token::RParen | Token::RBracket | Token::RBrace => depth -= 1, Token::Comma if depth == 0 && filter.is_some() => return None, Token::SemiColon => return None, _ if is_keyword(Some(token), "PARTITION") || is_keyword(Some(token), "SETTINGS") => { return None; } _ if depth == 0 && filter.is_none() && is_keyword(Some(token), "WHERE") => { filter = Some(index); } _ => {} } } let filter = filter?; let body_range = body.get(1)?.1.start..body.last()?.1.end; let rest = &sql[body_range.clone()]; let dml = match updates { true if filter > 1 => format!("UPDATE {table} SET {rest}"), false if filter == 1 => format!("DELETE FROM {table} {rest}"), _ => return None, }; let statements = SqlParser::parse_sql(dialect.as_ref(), &dml).ok()?; let plain = match statements.as_slice() { [Statement::Update(update)] => { updates && update.table.joins.is_empty() && update.from.is_none() && update.selection.is_some() && update.returning.is_none() && update.output.is_none() && update.or.is_none() && update.order_by.is_empty() && update.limit.is_none() } [Statement::Delete(delete)] => { !updates && delete.tables.is_empty() && delete.using.is_none() && delete.selection.is_some() && delete.returning.is_none() && delete.output.is_none() && delete.order_by.is_empty() && delete.limit.is_none() } _ => false, }; plain.then_some(Mutation { dml, updates, table: table_range, body: body_range, }) } /// The `sqlparser` dialect an engine's SQL is read in; `None` for MongoDB /// and Redis, which are not SQL. fn dialect(engine: Engine) -> Option> { (engine.syntax() == Syntax::Sql).then(|| parser(engine.spec().sql.parser_dialect)) } fn parser(dialect: ParserDialect) -> Box { match dialect { ParserDialect::Generic => Box::new(GenericDialect {}), ParserDialect::PostgreSql => Box::new(PostgreSqlDialect {}), ParserDialect::MySql => Box::new(MySqlDialect {}), ParserDialect::Sqlite => Box::new(SQLiteDialect {}), ParserDialect::DuckDb => Box::new(DuckDbDialect {}), ParserDialect::Snowflake => Box::new(SnowflakeDialect {}), ParserDialect::MsSql => Box::new(MsSqlDialect {}), ParserDialect::ClickHouse => Box::new(ClickHouseDialect {}), } } /// MariaDB's `ANALYZE ` respelled as the `EXPLAIN ANALYZE` sqlparser /// reads, so it is classified by the statement it runs, as MySQL's is. /// /// Only a statement that opens with a DML keyword qualifies. `ANALYZE TABLE t` /// is a write sqlparser already reads, and would turn into an `EXPLAIN` of the /// query `TABLE t`; anything else this does not recognise stays unreadable. fn mariadb_analyze_as_explain(dialect: &dyn Dialect, sql: &str) -> Option { let tokens = Tokenizer::new(dialect, sql).tokenize().ok()?; let mut tokens = tokens .iter() .filter(|token| !matches!(token, Token::Whitespace(_))) .peekable(); let keyword = |token: Option<&Token>| match token { Some(Token::Word(word)) => Some(word.keyword), _ => None, }; if keyword(tokens.next()) != Some(Keyword::ANALYZE) { return None; } if keyword(tokens.peek().copied()) == Some(Keyword::FORMAT) { tokens.next(); if tokens.next() != Some(&Token::Eq) || keyword(tokens.next()) != Some(Keyword::JSON) { return None; } } let statement = tokens.next()?; let dml = *statement == Token::LParen || matches!( keyword(Some(statement)), Some( Keyword::SELECT | Keyword::WITH | Keyword::INSERT | Keyword::REPLACE | Keyword::UPDATE | Keyword::DELETE ) ); dml.then(|| format!("EXPLAIN {sql}")) } /// Postgres's `EXPLAIN ANALYSE `, which runs the statement as /// `EXPLAIN ANALYZE` does, respelled as the `ANALYZE` sqlparser reads so it is /// classified by the statement it runs. The two words are the same length, so /// every other token keeps its place. fn analyse_as_analyze(dialect: &dyn Dialect, sql: &str) -> Option { let tokens = located_tokens(dialect, sql)?; let mut words = tokens .iter() .filter(|(token, _)| !matches!(token, Token::Whitespace(_))); let (first, _) = words.next()?; let (second, range) = words.next()?; let is = |token: &Token, keyword: &str| is_keyword(Some(&token), keyword); // The slice is checked as well as the token: a span after Generic's // `/*! … */` expansion points at the wrong text. let spelled = sql .get(range.clone()) .is_some_and(|text| text.eq_ignore_ascii_case("ANALYSE")); (is(first, "EXPLAIN") && is(second, "ANALYSE") && spelled) .then(|| format!("{}ANALYZE{}", &sql[..range.start], &sql[range.end..])) } /// Whether `sql` can run again just to reload the rows it produced. A grid is /// reloaded by re-running the statement behind it, and one that writes -- /// `INSERT … RETURNING` traces to its table like any select -- would write /// again. A statement `classify` cannot read is not vouched for either. pub(crate) fn rerunnable(engine: Engine, sql: &str) -> bool { let verdict = classify(engine, sql); verdict.mode == Mode::ReadOnly && verdict.destructive.is_empty() } /// Whether the last statement of `sql` answers with rows: a query, or a /// write with a `RETURNING`. DuckDB answers a command with a result set too, /// a single `Count` or `Success` column, which only the statement tells apart /// from a query's own column of that name. /// /// duckdb-rs keeps the type DuckDB gives a prepared statement to itself, so /// it is read off the text: the last statement alone, so an earlier one the /// grammar cannot read does not hide it, and by its first word where the /// grammar cannot read it either -- DuckDB has queries of its own, `TABLE t` /// or `PIVOT`, as well as commands. A word not known as a command reads as a /// query, since showing a command's count as a row costs less than dropping /// a query's rows. pub(crate) fn answers_with_rows(engine: Engine, sql: &str) -> bool { let Some(dialect) = dialect(engine) else { return false; }; let Some(tokens) = located_tokens(dialect.as_ref(), sql) else { return true; }; let Some(last) = between_semicolons(&tokens).pop() else { return false; }; match SqlParser::parse_sql(dialect.as_ref(), &sql[last.clone()]) { Ok(statements) => statements.last().is_some_and(statement_answers_with_rows), Err(_) => !tokens .iter() .filter(|(_, range)| last.contains(&range.start)) .find_map(|(token, _)| match token { Token::Word(word) => Some(word), _ => None, }) .is_some_and(|word| { COMMAND_WORDS .iter() .any(|command| word.value.eq_ignore_ascii_case(command)) }), } } /// The first words of the statements DuckDB answers with a `Count` or a /// `Success` of its own. const COMMAND_WORDS: &[&str] = &[ "ABORT", "ALTER", "ANALYZE", "ATTACH", "BEGIN", "CHECKPOINT", "COMMENT", "COMMIT", "COPY", "CREATE", "DEALLOCATE", "DELETE", "DETACH", "DROP", "END", "EXPORT", "FORCE", "IMPORT", "INSERT", "INSTALL", "LOAD", "MERGE", "PREPARE", "RESET", "ROLLBACK", "SET", "START", "TRUNCATE", "UPDATE", "USE", "VACUUM", ]; fn statement_answers_with_rows(statement: &Statement) -> bool { match statement { Statement::Query(query) => query_answers_with_rows(query), Statement::Insert(Insert { returning, .. }) | Statement::Update(Update { returning, .. }) | Statement::Delete(Delete { returning, .. }) => returning.is_some(), Statement::Merge(Merge { output, .. }) => output.is_some(), _ => false, } } /// A query answers with rows unless its body is a write a `WITH` leads: /// `WITH s AS (…) INSERT INTO t SELECT * FROM s` parses as a query. fn query_answers_with_rows(query: &Query) -> bool { match query.body.as_ref() { SetExpr::Insert(statement) | SetExpr::Update(statement) | SetExpr::Delete(statement) | SetExpr::Merge(statement) => statement_answers_with_rows(statement), SetExpr::Query(query) => query_answers_with_rows(query), _ => true, } } /// Whether a submission may be stopped part way once its rows pass the limit: /// a read, and the only statement in it. Stopping one statement of several /// ends the rest with it -- a `COMMIT` behind a `SELECT` never runs, a `SET` /// before it is rolled back with the implicit transaction -- and the rows on /// screen are not the last statement's. A SQL Server batch is several /// statements in one submission wherever the user did not separate them. /// /// Both parsers have to count one: the grammar reads `BEGIN; …; COMMIT` as a /// single transaction block. And it must leave the session alone: a Postgres /// cancel aborts the implicit transaction a `set_config` or advisory lock /// lives in, so such a read is drained rather than stopped. pub(crate) fn stoppable(engine: Engine, sql: &str) -> bool { let parsed_alone = match dialect(engine) { Some(dialect) => SqlParser::parse_sql(dialect.as_ref(), sql) .is_ok_and(|statements| statements.len() == 1), None => true, }; rerunnable(engine, sql) && parsed_alone && Buffer::for_engine(engine, sql).statements().len() == 1 && !touches_session(engine, sql) } /// The one table a query's rows are rows of, read off the statement for an /// engine whose driver does not say which table a result column came from. #[derive(Debug, PartialEq, Eq)] pub(crate) struct TableRead { /// The name as written, one entry per dotted part. pub(crate) table: Vec, pub(crate) columns: Vec, } /// One entry of a [`TableRead`]'s select list. #[derive(Debug, PartialEq, Eq)] pub(crate) enum Projected { /// A `*`, which stands for every column of the table in its own order. Every, /// A bare or table-qualified name, as written. Column(String), /// Anything else, which names no column a write could land on. Computed, } /// Why a statement's rows are not one table's rows, as [`table_read_or_why`] /// finds it. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Unread { /// Nothing the grammar reads whole. Unparsed, /// A statement other than a query. NotAQuery, /// A `WITH` beside the select. With, /// A set operation, `VALUES` or a parenthesised query. NotOneSelect, /// A `SETTINGS` clause on the query. Settings, /// A `FORMAT` clause on the query. Format, Distinct, /// `GROUP BY`, `HAVING`, a window or `QUALIFY`. Grouped, /// `ORDER BY … WITH FILL` or `INTERPOLATE`. Filled, /// A join, or a second relation in `FROM`. Join, ArrayJoin, /// No `FROM`, a subquery or a table function in it. NotATable, /// A `*` with a modifier, or a select item that is not a column. Projection, /// Anything else the plain select does not have. Other, } impl Unread { /// Why rows read this way cannot be written back, in the user's words. pub(crate) fn reason(self) -> &'static str { match self { Self::Unparsed => { "DBDelve cannot read this statement whole, so it cannot tell which table its rows \ are from." } Self::NotAQuery => "Only the rows of a SELECT can be edited.", Self::With => "These rows are read through WITH, so they cannot be edited.", Self::NotOneSelect => { "These rows are not from one SELECT of a table, so they cannot be edited." } Self::Settings => { "A SETTINGS clause can change how values are shown, so rows read with one cannot \ be edited." } Self::Format => "Rows read in a FORMAT of their own cannot be edited.", Self::Distinct => "DISTINCT merges identical rows, so these rows cannot be edited.", Self::Grouped => "Grouped rows are not rows of the table, so they cannot be edited.", Self::Filled => { "WITH FILL adds rows the table does not hold, so these rows cannot be edited." } Self::Join => "These rows come from a join, so they cannot be edited.", Self::ArrayJoin => { "ARRAY JOIN repeats a row once for each element, so these rows cannot be edited." } Self::NotATable => "These rows are not read from a table, so they cannot be edited.", Self::Projection => { "Only rows selected as the table's own columns, or *, can be edited." } Self::Other => "DBDelve edits the rows of a plain SELECT of one table only.", } } } /// Whether each name a [`TableRead`] holds was written quoted, which says /// whether the server folds its case: one entry per part of the table's name, /// and one per entry of the select list, `false` for all but a /// [`Projected::Column`]. #[derive(Debug, Default, PartialEq, Eq)] pub(crate) struct Quoting { pub(crate) table: Vec, pub(crate) columns: Vec, } /// [`TableRead`] for the last statement of `sql`, when it is a plain select of /// one table: no join, subquery, table function, CTE, set operation, /// `DISTINCT`, grouping or window clause, and no table alias renaming the /// columns. Every one of those makes a result row something other than one /// row of the table, or a column something other than the column it names, /// so each refuses rather than being read past. pub(crate) fn table_read(engine: Engine, sql: &str) -> Option { table_read_or_why(engine, sql).ok().map(|(read, _)| read) } /// [`table_read`], with the names the select list reads as something other /// than a column: an alias given by `AS` (`SELECT a AS b` gives `b`) and the /// first part of a name it takes for the table's (`t` of `t.a`). A column of /// the table by one of those names makes the reading ambiguous on an engine /// that resolves a name to more than one thing. Or what refused it. A /// `Computed` item refuses nothing here; that is the caller's to decide. pub(crate) fn table_read_or_why( engine: Engine, sql: &str, ) -> Result<(TableRead, Vec), Unread> { table_read_quoted(engine, sql).map(|(read, shadows, _)| (read, shadows)) } /// [`table_read_or_why`], and which of the names it read were quoted. pub(crate) fn table_read_quoted( engine: Engine, sql: &str, ) -> Result<(TableRead, Vec, Quoting), Unread> { use sqlparser::ast::{ GroupByExpr, JoinOperator, ObjectName, OrderByKind, SelectFlavor, SelectItem, SelectItemQualifiedWildcardKind, TableFactor, WildcardAdditionalOptions, }; let dialect = dialect(engine).ok_or(Unread::Unparsed)?; let statement = SqlParser::parse_sql(dialect.as_ref(), sql) .map_err(|_| Unread::Unparsed)? .pop() .ok_or(Unread::Unparsed)?; let Statement::Query(query) = statement else { return Err(Unread::NotAQuery); }; let Query { with, body, order_by, locks, for_clause, settings, format_clause, pipe_operators, .. } = *query; if with.is_some() { return Err(Unread::With); } if settings.is_some() { return Err(Unread::Settings); } if format_clause.is_some() { return Err(Unread::Format); } if order_by.as_ref().is_some_and(|order_by| { order_by.interpolate.is_some() || matches!(&order_by.kind, OrderByKind::Expressions(by) if by.iter().any(|by| by.with_fill.is_some())) }) { return Err(Unread::Filled); } if for_clause.is_some() || !locks.is_empty() || !pipe_operators.is_empty() { return Err(Unread::Other); } let SetExpr::Select(select) = *body else { return Err(Unread::NotOneSelect); }; if select.distinct.is_some() { return Err(Unread::Distinct); } if !matches!(&select.group_by, GroupByExpr::Expressions(by, with) if by.is_empty() && with.is_empty()) || select.having.is_some() || !select.named_window.is_empty() || select.qualify.is_some() { return Err(Unread::Grouped); } let plain = select.select_modifiers.is_none() && select.top.is_none() && select.exclude.is_none() && select.into.is_none() && select.lateral_views.is_empty() && select.connect_by.is_empty() && select.cluster_by.is_empty() && select.distribute_by.is_empty() && select.sort_by.is_empty() && select.value_table_mode.is_none(); if !plain { return Err(Unread::Other); } let from = match select.from.as_slice() { [from] => from, [] => return Err(Unread::NotATable), _ => return Err(Unread::Join), }; if let Some(join) = from.joins.first() { return Err(match join.join_operator { JoinOperator::ArrayJoin | JoinOperator::LeftArrayJoin | JoinOperator::InnerArrayJoin => Unread::ArrayJoin, _ => Unread::Join, }); } let TableFactor::Table { name, alias, args: None, with_hints, version: None, with_ordinality: false, partitions, json_path: None, index_hints, .. } = &from.relation else { return Err(Unread::NotATable); }; if !with_hints.is_empty() || !partitions.is_empty() || !index_hints.is_empty() || alias .as_ref() .is_some_and(|alias| !alias.columns.is_empty()) { return Err(Unread::Other); } let parts = |name: &ObjectName| -> Option> { name.0 .iter() .map(|part| part.as_ident().map(|ident| ident.value.clone())) .collect() }; let table = parts(name).ok_or(Unread::NotATable)?; let mut quoting = Quoting { table: name .0 .iter() .map(|part| { part.as_ident() .is_some_and(|ident| ident.quote_style.is_some()) }) .collect(), columns: Vec::with_capacity(select.projection.len().max(1)), }; // Once aliased, the table is named by its alias alone. Unaliased, by any // tail of the name it was written with. let qualifiers: Vec<&[String]> = match alias { Some(alias) => vec![std::slice::from_ref(&alias.name.value)], None => (0..table.len()).map(|from| &table[from..]).collect(), }; // ClickHouse's names are case-sensitive: beside a table aliased `t`, // `T.x` is a field of a column `T`. let exact = engine.spec().sql.parser_dialect == ParserDialect::ClickHouse; let qualifies = |written: &[String]| { qualifiers.iter().any(|qualifier| { qualifier.len() == written.len() && qualifier.iter().zip(written).all(|(a, b)| { if exact { a == b } else { a.eq_ignore_ascii_case(b) } }) }) }; let bare = |options: &WildcardAdditionalOptions| { options.opt_ilike.is_none() && options.opt_exclude.is_none() && options.opt_except.is_none() && options.opt_replace.is_none() && options.opt_rename.is_none() && options.opt_alias.is_none() }; let mut shadows = Vec::new(); let mut column = |expr: &Expr| match expr { Expr::Identifier(ident) => ( Projected::Column(ident.value.clone()), ident.quote_style.is_some(), ), Expr::CompoundIdentifier(idents) => match idents.split_last() { Some((last, qualifier)) if qualifies( &qualifier .iter() .map(|ident| ident.value.clone()) .collect::>(), ) => { shadows.push(qualifier[0].value.clone()); ( Projected::Column(last.value.clone()), last.quote_style.is_some(), ) } // A struct's field, read off a column of the table. _ => (Projected::Computed, false), }, _ => (Projected::Computed, false), }; let mut columns = Vec::with_capacity(select.projection.len().max(1)); let mut aliases = Vec::new(); if select.projection.is_empty() && select.flavor == SelectFlavor::FromFirstNoSelect { columns.push(Projected::Every); quoting.columns.push(false); } for item in &select.projection { let (projected, quoted) = match item { SelectItem::Wildcard(options) if bare(options) => (Projected::Every, false), SelectItem::QualifiedWildcard( SelectItemQualifiedWildcardKind::ObjectName(name), options, ) if bare(options) && parts(name).is_some_and(|name| qualifies(&name)) => { aliases.extend(parts(name).and_then(|name| name.into_iter().next())); (Projected::Every, false) } SelectItem::UnnamedExpr(expr) => column(expr), SelectItem::ExprWithAlias { expr, alias } => { let (projected, quoted) = column(expr); if !matches!(&projected, Projected::Column(name) if *name == alias.value) { aliases.push(alias.value.clone()); } (projected, quoted) } _ => return Err(Unread::Projection), }; columns.push(projected); quoting.columns.push(quoted); } aliases.extend(shadows); Ok((TableRead { table, columns }, aliases, quoting)) } /// Every unquoted word of `sql`, in order, outside strings and comments; `None` /// where the tokenizer cannot read it. pub(crate) fn bare_words(engine: Engine, sql: &str) -> Option> { let dialect = dialect(engine)?; let tokens = Tokenizer::new(dialect.as_ref(), sql).tokenize().ok()?; Some( tokens .into_iter() .filter_map(|token| match token { Token::Word(word) if word.quote_style.is_none() => Some(word.value), _ => None, }) .collect(), ) } /// Whether `sql` is nothing but queries that only read: no `SET`, `USE`, /// transaction control, declaration or `SELECT … INTO`, no call that reads or /// changes what only its session holds, and nothing `classify` cannot read. /// Such a submission leaves its session as it found it, and reads the same on /// another session to the same server as on this one, bar what this one /// already holds that a fresh one would not. pub(crate) fn plain_read(engine: Engine, sql: &str) -> bool { let queries_only = match dialect(engine) { Some(dialect) => SqlParser::parse_sql(dialect.as_ref(), sql).is_ok_and(|statements| { statements .iter() .all(|statement| matches!(statement, Statement::Query(_))) }), None => true, }; queries_only && rerunnable(engine, sql) && !touches_session(engine, sql) } /// Calls whose answer or effect belongs to the session they run on: a /// sequence's value, a session variable, an advisory or named lock, the last /// identity inserted. const SESSION_FUNCTIONS: &[&str] = &[ "nextval", "currval", "setval", "lastval", "set_config", "last_insert_id", "get_lock", "release_lock", "release_all_locks", "scope_identity", "sp_getapplock", "sp_releaseapplock", ]; /// Whether a query calls one of [`SESSION_FUNCTIONS`], an advisory lock, reads /// `@@IDENTITY` or assigns a variable with `:=`. Read off the tokens whatever /// the engine, so a call anywhere in the statement counts, and a column that /// merely shares a name keeps its statement in turn, the conservative side. fn touches_session(engine: Engine, sql: &str) -> bool { let Some(dialect) = dialect(engine) else { return false; }; let Ok(tokens) = Tokenizer::new(dialect.as_ref(), sql).tokenize() else { return true; }; let mut tokens = tokens .iter() .filter(|token| !matches!(token, Token::Whitespace(_))) .peekable(); while let Some(token) = tokens.next() { match token { Token::Assignment => return true, Token::Word(word) => { let name = word.value.to_lowercase(); let called = tokens.peek() == Some(&&Token::LParen); if name == "@@identity" || called && (SESSION_FUNCTIONS.contains(&name.as_str()) || name.starts_with("pg_advisory") || name.starts_with("pg_try_advisory")) { return true; } } _ => {} } } false } /// Names an engine can spell as a member with no call at all, which the period /// arm of [`calls_denied_function`] reads as the call it stands for. A call is /// always followed by a parenthesis, so the arm is needed only for such a /// spelling, and the project knows one: Snowflake's sequence pseudo-column, /// `seq.nextval`. Any other listed name after a period is an ordinary column /// reference and stays a read. The list is one long because that is how many /// such spellings are known; another goes here, with a corpus case beside the /// `member form` one in `hardening.rs`. const MEMBER_FORMS: &[&str] = &["nextval"]; /// Whether a query calls one of the engine's `denied_functions`, wherever the /// call sits: the parser puts one in four different nodes (scalar, table, /// `LATERAL` table and `TABLE(..)` position), so the tokens are read instead. /// Only the last word before the parenthesis is compared, so a schema-qualified /// call counts, and a word on [`MEMBER_FORMS`] straight after a period counts /// without one. A column that merely shares a listed name is a read unless the /// name is on that list or is followed by a parenthesis, which is how a /// column called `query` on DuckDB is a read and `FROM query(..)` is not. /// /// Separate from [`SESSION_FUNCTIONS`], which answers what the session keeps; /// this answers whether Read-only may run the call. A name may be on both. /// /// A call the list does not name stays a read: a user-defined function keeps /// its statement. A denied call carried as text inside another function is /// seen only because that other function is itself listed, since the scan /// compares names and never reads what a string says. The list is therefore /// best-effort inside a `SELECT`, and a name missing from it is not a small /// matter. Where an engine holds Read-only on the server, the hold refuses a /// write that goes through the executor, but not a large-object write, a file /// the server writes outside the database, or a call carried inside a carrier's /// text: the conformance scenarios run the first and last with the hold armed, /// so the list is what stops those. Where an engine has no hold, the list is /// the whole boundary. The same root cause reached the list six times: a /// spelling of a name, a sibling family of names, the functions that execute /// their text argument, one of those whose text argument the catalog does not /// name, so a shape probe over the catalog could not find it, the functions in /// an extension outside `pg_catalog` that run text they are handed, and the file /// functions a contrib extension (`adminpack`) installs into `pg_catalog`. fn calls_denied_function(engine: Engine, sql: &str) -> bool { calls_listed( engine, sql, engine.spec().sql.denied_functions, MEMBER_FORMS, ) } /// Whether `sql` calls any function on `listed`, by the scan /// [`calls_denied_function`] describes. One scan answers both lists, so the /// deny-list and the agent's egress list cannot read a call two ways. /// `member_forms` is the deny-list's period arm only: an egress name straight /// after a period is a column reference and stays a read. fn calls_listed(engine: Engine, sql: &str, listed: &[&str], member_forms: &[&str]) -> bool { // An engine that lists nothing is judged by the parse alone, as it was // before the list existed. if listed.is_empty() { return false; } let Some(dialect) = dialect(engine) else { return false; }; // The calls the server will run, so one inside an executable comment counts. let tokens = executed_tokens(engine, dialect.as_ref(), sql) .unwrap_or_else(|| Tokenizer::new(dialect.as_ref(), sql).tokenize()); let Ok(tokens) = tokens else { return true; }; // Read before the whitespace is dropped: the whitespace is what separates a // bit-and from the escape form. if escapes_an_identifier(&tokens) { return true; } let mut tokens = tokens .iter() .filter(|token| !matches!(token, Token::Whitespace(_))) .peekable(); let mut previous = None; while let Some(token) = tokens.next() { if let Token::Word(word) = token { let name = word.value.to_lowercase(); // Snowflake reads a sequence as `seq.nextval`, no call at all, so // that spelling and only that one is stopped without a // parenthesis. What the narrowing leaves: a listed name used as a // CTE name or a derived-table alias with a column list is still // followed by one and still stopped. Deciding a word's position // from the tokens would be a second parser kept in step with six // dialects by hand, so those are recorded in the corpus instead. if listed.contains(&name.as_str()) && (tokens.peek() == Some(&&Token::LParen) || (previous == Some(&Token::Period) && member_forms.contains(&name.as_str()))) { return true; } } previous = Some(token); } false } /// Whether `sql` has `SET` followed straight away by a server-wide or /// persistent scope word: `GLOBAL`, `PERSIST` or `PERSIST_ONLY`. /// /// Read from the tokens because the parser has already dropped the scope of /// `SET GLOBAL TRANSACTION ...` into the `session` flag of `SetTransaction`, /// and [`set_verdict`] rates a transaction that asks for no write access a /// read, so a server-wide change to the default access mode or isolation level /// would pass as one. Only the word straight after `SET` counts, so `SET @global` /// (a user variable), `SET @@global.x` (which [`setting_verdict`] already /// stops) and `SET LOCAL TRANSACTION` are untouched. The pair is looked for /// anywhere rather than at the start of a statement, because the parser also /// accepts a `SET` inside an `IF ... THEN` block, where the statement opens /// with something else; and it is a pair, so the order of two statements does /// not matter. /// /// What it moves, read from the corpus rather than from the intent: the /// transaction spelling whose scope the parser discarded, and two shapes that /// are not a `SET` statement. A `SELECT` of a column `set` aliased `global`, /// written with no `AS` ("ordinary identifiers spelling the scope pair, no SET /// statement"), is two adjacent unquoted words and so is raised from a read to /// a write. So is a scope word under a plain `EXPLAIN` ("server-wide /// transaction under a plain explain"), where `EXPLAIN SET ROLE other` stays a /// read because the parser sees the explained statement. Both fail towards a /// prompt, never towards a refusal or a run. The cost is accepted: telling an /// identifier from a keyword, or looking under an `EXPLAIN`, would mean reading /// statement structure from tokens the parser has already discarded. Both /// records are in `hardening_settings`. /// /// A tokenizer failure answers `false`, unlike [`calls_denied_function`]. That /// one is only asked on an engine that lists a function; this is asked on every /// SQL engine, and a submission the tokenizer cannot read is already refused by /// name as unreadable. Raising here would fold a write into that verdict and /// move every record that says so. fn sets_server_wide(engine: Engine, sql: &str) -> bool { let Some(dialect) = dialect(engine) else { return false; }; // The statements the server will run, so a scope inside an executable // comment counts the way a denied call does. let tokens = executed_tokens(engine, dialect.as_ref(), sql) .unwrap_or_else(|| Tokenizer::new(dialect.as_ref(), sql).tokenize()); let Ok(tokens) = tokens else { return false; }; let words: Vec> = tokens .iter() .filter(|token| !matches!(token, Token::Whitespace(_))) .map(|token| match token { Token::Word(word) if word.quote_style.is_none() => Some(word), _ => None, }) .collect(); words.windows(2).any(|pair| { matches!( pair, [Some(set), Some(scope)] if set.value.eq_ignore_ascii_case("set") && ["global", "persist", "persist_only"] .iter() .any(|name| scope.value.eq_ignore_ascii_case(name)) ) }) } /// Whether the tokens spell an identifier as a unicode escape, `U&"..."`: an /// unquoted `U`, an ampersand and a double-quoted word, written with nothing /// between them. /// /// Postgres decodes the escape and the lexer reports the raw text, so the name /// the server calls is not the name [`calls_denied_function`] would compare. /// The form is the answer rather than the name: the escape character is /// changeable by a `UESCAPE` clause, so a decoder would be a second lexer kept /// in step with the server by hand, and a decoded name can itself be escaped. /// /// One false positive, on an engine that lists any function: a bit-and of a /// double-quoted column written with no whitespace. It fails towards a prompt, /// and a space makes it a read again. fn escapes_an_identifier(tokens: &[Token]) -> bool { tokens.windows(3).any(|window| { matches!( window, [Token::Word(prefix), Token::Ampersand, Token::Word(name)] if prefix.quote_style.is_none() && prefix.value.eq_ignore_ascii_case("u") && name.quote_style == Some('"') ) }) } /// Whether `sql` runs statements it does not show, so what they did to the /// transaction cannot be read off it: a procedure call (`CALL`, `EXEC`, /// `EXECUTE`), anywhere in it, or anything sqlparser cannot read, which /// Postgres's `DO` block and MariaDB's `BEGIN NOT ATOMIC` are. pub(crate) fn runs_unseen(engine: Engine, sql: &str) -> bool { let Some(dialect) = dialect(engine) else { return false; }; match SqlParser::parse_sql(dialect.as_ref(), sql) { Ok(statements) => visit_statements(&statements, |statement| match statement { Statement::Call(_) | Statement::Execute { .. } => ControlFlow::Break(()), _ => ControlFlow::Continue(()), }) .is_break(), Err(_) => true, } } /// What running `sql` leaves on its session that a fresh connection to the /// same profile would not have, which is what keeps a queue of reads from /// running at once on fresh ones. #[derive(Debug, Default, PartialEq, Eq)] pub(crate) struct Leaves { /// `Some(true)` when it leaves a transaction open, `Some(false)` when it /// ends one, `None` when it does neither. pub(crate) transaction: Option, /// A `SET` (MySQL's `autocommit` among them), `USE`, `PRAGMA … =`, table /// lock, temporary table or variable `SELECT … INTO`, which lasts until /// the session does, or a call [`touches_session`] finds: `set_config`, a /// lock, an `@x :=`. One that only reads what the session holds counts /// too, the conservative side. pub(crate) settings: bool, } /// [`Leaves`] for one submission of the user's. A read, a `SHOW`, an `EXPLAIN` /// or an autocommitted write leaves nothing a fresh connection would not see, /// and neither does a statement nothing can read -- bar a `SET` or `USE` the /// grammar does not know, which still changed the session if it ran. /// Snowflake and MongoDB keep nothing from one run to the next. pub(crate) fn leaves(engine: Engine, sql: &str) -> Leaves { if engine.syntax() == Syntax::Redis { return crate::redis_cmd::leaves(sql); } let mut leaves = Leaves::default(); let Some(dialect) = dialect(engine).filter(|_| !engine.spec().sql.stateless_requests) else { return leaves; }; match SqlParser::parse_sql(dialect.as_ref(), sql) { Ok(statements) => statements .iter() .for_each(|statement| leaves.add(statement)), Err(_) => { let tokens = Tokenizer::new(dialect.as_ref(), sql) .tokenize() .unwrap_or_default(); let first = tokens.iter().find_map(|token| match token { Token::Word(word) => Some(word.keyword), _ => None, }); leaves.settings = match first { Some(Keyword::SET | Keyword::USE) => true, Some(Keyword::PRAGMA) => tokens.contains(&Token::Eq), _ => false, }; } } leaves.settings |= touches_session(engine, sql); leaves } /// Whether `sql` may leave a transaction open where [`leaves`] cannot say: /// text sqlparser cannot read that names a `BEGIN` or `START TRANSACTION` /// the server may well read, or transaction control among other statements, /// which an error part way through stops short of a `COMMIT` that would end /// it. pub(crate) fn transaction_uncertain(engine: Engine, sql: &str) -> bool { let Some(dialect) = dialect(engine).filter(|_| !engine.spec().sql.stateless_requests) else { return false; }; if let Ok(statements) = SqlParser::parse_sql(dialect.as_ref(), sql) { return statements.len() > 1 && statements.iter().any(|statement| { matches!( statement, Statement::StartTransaction { has_end_keyword: false, .. } | Statement::Commit { .. } | Statement::Rollback { savepoint: None, .. } ) }); } let tokens = Tokenizer::new(dialect.as_ref(), sql) .tokenize() .unwrap_or_default(); let keywords: Vec = tokens .iter() .filter_map(|token| match token { Token::Word(word) => Some(word.keyword), _ => None, }) .collect(); keywords .iter() .enumerate() .any(|(at, keyword)| match keyword { Keyword::BEGIN => true, Keyword::START => keywords.get(at + 1) == Some(&Keyword::TRANSACTION), _ => false, }) } impl Leaves { fn add(&mut self, statement: &Statement) { match statement { // A T-SQL `BEGIN … END` block, which opens no transaction itself. Statement::StartTransaction { has_end_keyword: true, statements, .. } => statements.iter().for_each(|statement| self.add(statement)), Statement::StartTransaction { .. } => self.transaction = Some(true), // `AND CHAIN` opens the next one as it ends this one. Statement::Commit { chain, .. } | Statement::Rollback { chain, savepoint: None, } => self.transaction = Some(*chain), // Turning MySQL's `autocommit` off, or SQL Server's implicit // transactions on, leaves every later statement inside one. Statement::Set(set) => { self.settings = true; if let Some(open) = transaction_by_setting(&set.to_string()) { self.transaction = Some(open); } } Statement::Use(_) | Statement::LockTables { .. } | Statement::Pragma { is_eq: true, .. } => self.settings = true, Statement::CreateTable(table) => { self.settings |= table.temporary || table.name.to_string().starts_with('#'); } Statement::Query(query) => { if let SetExpr::Select(select) = query.body.as_ref() && let Some(into) = &select.into { self.settings |= into.temporary || into .targets .iter() .any(|target| target.to_string().starts_with(['#', '@'])); } } _ => {} } } } /// What a `SET` does to the session's transaction, read off its text: /// `Some(true)` for MySQL's `autocommit` turned off or SQL Server's /// `IMPLICIT_TRANSACTIONS` turned on, which leave the next statement inside a /// transaction, and `Some(false)` for `autocommit` turned on, which commits /// the one open. `None` for any other `SET`, or one assigning more than this. fn transaction_by_setting(set: &str) -> Option { let spelled: String = set .chars() .filter(|c| !c.is_whitespace() && *c != '@') .collect::() .to_ascii_uppercase(); let setting = spelled.strip_prefix("SET")?; let setting = setting .strip_prefix("SESSION.") .or_else(|| setting.strip_prefix("SESSION")) .or_else(|| setting.strip_prefix("LOCAL.")) .or_else(|| setting.strip_prefix("LOCAL")) .unwrap_or(setting); match setting { "AUTOCOMMIT=0" | "AUTOCOMMIT=OFF" | "AUTOCOMMIT=FALSE" => Some(true), "AUTOCOMMIT=1" | "AUTOCOMMIT=ON" | "AUTOCOMMIT=TRUE" => Some(false), "IMPLICIT_TRANSACTIONSON" => Some(true), _ => None, } } /// The lowest mode that may run one statement: what its variant earns, raised /// by whatever the `Query` it owns turns out to contain. /// /// The second half is never optional. A `Query` in any position can carry a /// data-modifying CTE, so /// `COPY (WITH x AS (DELETE FROM t RETURNING a) SELECT a FROM x) TO STDOUT` /// empties a table under a variant that reads as `COPY TO`. fn statement_verdict(spec: &SqlSpec, statement: &Statement) -> Reading { let reading = variant_verdict(spec, statement); match owned_query(statement) { Some(query) => reading.max(query_verdict(spec, query)), None => reading, } } /// The `Query` a statement owns, if it owns one. /// /// One place rather than a recursion inside each arm, so a variant added to /// `variant_verdict` inherits the CTE check instead of having to remember it. /// Four variants here already held a `Query` the classifier never looked into /// (spec §3.5), which is what that costs. fn owned_query(statement: &Statement) -> Option<&Query> { match statement { Statement::Query(query) => Some(query), Statement::Copy { source: CopySource::Query(query), .. } => Some(query), Statement::CreateTable(create) => create.query.as_deref(), Statement::CreateView(create) => Some(&create.query), Statement::Insert(insert) => insert.source.as_deref(), _ => None, } } /// What a statement's variant alone says. Never called directly: the fold in /// `statement_verdict` is the half that reads what the variant is carrying. fn variant_verdict(spec: &SqlSpec, statement: &Statement) -> Reading { match statement { // Read only as a variant. Everything dangerous a query can hold is // inside it, and `statement_verdict` folds that in. Statement::Query(_) => Reading::READ, // `EXPLAIN ANALYZE DELETE FROM t` runs the delete -- documented in // Postgres, and in MySQL since 8.0.18. dbdelve never sends it to SQLite: // `Engine::explain_prefix` returns None for that pair. Statement::Explain { analyze, options, statement, .. } => { let analyze = *analyze || options .iter() .flatten() .any(analyze_option_is_on); if analyze { statement_verdict(spec, statement) } else { Reading::READ } } Statement::ExplainTable { .. } => Reading::READ, // A Snowflake Scripting block, `BEGIN DELETE FROM t; END`, parses as the // same variant as a bare `BEGIN` with its body inside. Any exception // handler holds statements of its own, so one is not read into. Statement::StartTransaction { statements, exception, .. } if !statements.is_empty() || exception.is_some() => { if exception.is_some() { Verdict::FULL.into() } else { statements .iter() .map(|statement| statement_verdict(spec, statement)) .fold(Reading::READ, Reading::max) } } // A transaction opened read-write overrides the session's Read-only hold // for that transaction, with no `SET` at all (Postgres spells it `BEGIN // READ WRITE`). Below the scripting-block guard so a block keeps being // read by what it holds. Statement::StartTransaction { modes, .. } if grants_write(modes) => Verdict::WRITE.into(), Statement::Set(set) => set_verdict(spec, set).into(), // `IF … ELSE` (T-SQL's, and the `IF … END IF` Postgres, MySQL and // Snowflake parse to the same variant) is as dangerous as what it holds. // Every branch counts, since which one runs is the server's to decide, // and so does every condition, since each one runs. Statement::If(branching) => { let blocks = std::iter::once(&branching.if_block) .chain(&branching.elseif_blocks) .chain(&branching.else_block); blocks .clone() .filter_map(|block| block.condition.as_ref()) .map(|condition| condition_verdict(spec, condition)) .chain( blocks .flat_map(ConditionalStatementBlock::statements) .map(|statement| statement_verdict(spec, statement)), ) .fold(Reading::READ, Reading::max) } Statement::ShowTables { .. } | Statement::ShowCatalogs { .. } | Statement::ShowCharset { .. } | Statement::ShowCollation { .. } | Statement::ShowColumns { .. } | Statement::ShowCreate { .. } | Statement::ShowDatabases { .. } | Statement::ShowFunctions { .. } | Statement::ShowObjects { .. } | Statement::ShowProcessList { .. } | Statement::ShowSchemas { .. } | Statement::ShowStatus { .. } | Statement::ShowVariable { .. } | Statement::ShowVariables { .. } | Statement::ShowViews { .. } // A deliberate exception to the wildcard: `USE db` repoints the session // and touches no data, so refusing it in Read-only would refuse // navigation, not damage. | Statement::Use { .. } // A plain opening is a bracket, and the one that asks for write access // is the arm above this list. | Statement::StartTransaction { .. } | Statement::Commit { .. } | Statement::Rollback { .. } // Savepoints touch no data, and `ROLLBACK TO` above is already a read. | Statement::Savepoint { .. } | Statement::ReleaseSavepoint { .. } => Reading::READ, // COPY TO reads a table out to a file; COPY FROM loads rows in. Either // direction against a `PROGRAM` or a file runs on the *server*: a shell // command, or a read/write of the server's filesystem. Only the standard // streams stay inside the database. Statement::Copy { to, target, .. } => match target { CopyTarget::File { .. } | CopyTarget::Program { .. } => Verdict::FULL, _ if *to => Verdict::READ, _ => Verdict::WRITE, } .into(), // Replacing an object that holds data drops that data first: `CREATE OR // REPLACE SCHEMA s` empties every table in `s`, and `INSERT OVERWRITE` // truncates before it inserts. A replaced view, function or procedure // holds no rows, so those stay with the object they create. Statement::CreateTable(create) if create.or_replace => { Verdict::destroys(Destructive::Drop).into() } Statement::CreateSchema { or_replace: true, .. } | Statement::CreateDatabase { or_replace: true, .. } // An internal stage holds the files put into it. | Statement::CreateStage { or_replace: true, .. } => Verdict::destroys(Destructive::Drop).into(), // `INSERT INTO FUNCTION url(…)`, `s3(…)`, `file(…)`, `remote(…)` and // the rest write outside the database, as a `COPY … TO` file does. // Only ClickHouse's dialect parses one. Statement::Insert(insert) if matches!(insert.table, TableObject::TableFunction(_)) => { Verdict::FULL.into() } Statement::Insert(insert) if insert.overwrite => { Verdict::destroys(Destructive::Truncate).into() } Statement::Insert { .. } | Statement::Update { .. } | Statement::CreateTable { .. } | Statement::CreateIndex { .. } | Statement::CreateView { .. } | Statement::CreateSchema { .. } | Statement::Comment { .. } | Statement::Analyze { .. } | Statement::Vacuum { .. } => Verdict::WRITE.into(), // Every `DELETE` is flagged, filtered or not: the agent is refused all // of them, and the flag is read off the statement the walk reached, // wherever it sits. Statement::Delete(delete) => Reading { verdict: if delete.selection.is_some() { Verdict::WRITE } else { Verdict::destroys(Destructive::UnfilteredDelete) }, removes: true, alters: false, }, Statement::Drop { .. } => Verdict::destroys(Destructive::Drop).into(), Statement::Truncate { .. } => Verdict::destroys(Destructive::Truncate).into(), // One ALTER can carry several operations, so the verdict is the maximum // over them and not the first. Statement::AlterTable(alter) => Reading { verdict: alter .operations .iter() .map(alter_verdict) .fold(Verdict::WRITE, Verdict::max), removes: false, alters: alter .operations .iter() .any(|operation| !matches!(operation, AlterTableOperation::AddColumn { .. })), }, // Everything else needs Full: a statement this function has not been // taught about is one nobody has decided is safe. A statement type added // by a later crate version lands here silently, so the arm has to be the // conservative one -- `Statement` is not `#[non_exhaustive]`, and the // build will not break to ask. _ => Verdict::FULL.into(), } } /// Whether a transaction's modes ask for write access. Read on its own, not /// through the `session` flag of `SET TRANSACTION`: the parser drops the /// `SESSION` keyword from `SET SESSION TRANSACTION READ WRITE`, which is the /// spelling that disarms a Read-only hold for the rest of the session. fn grants_write(modes: &[TransactionMode]) -> bool { modes.iter().any(|mode| { matches!( mode, TransactionMode::AccessMode(TransactionAccessMode::ReadWrite) ) }) } /// The client charsets a statement can still be lexed in: the unicode family, /// Latin-1, ASCII and binary. A multibyte-trail charset such as `gbk` can have /// a trail byte that is a backslash, which moves a quote under a reader that /// still assumes `SqlSpec::backslash_escapes`, the same way the strictness mode /// does, so any other charset is stopped. const SINGLE_BYTE_CHARSETS: &[&str] = &["utf8", "utf8mb3", "utf8mb4", "latin1", "ascii", "binary"]; /// What a user's own `SET` may do on a Read-only profile. /// /// Decided by what the parser says the statement is, not by a name, wherever a /// name does not have to decide it. A role or authorization change changes who /// the session is, and a transaction mode list granting write access defeats /// the server's hold. A setting is a read only when `spec.plain_settings` names /// it: the hold's whole value is being hard to remove, so a name nobody listed /// is stopped rather than assumed harmless. Every assignment of a multi-part /// `SET` has to pass, so the verdict does not depend on their order. fn set_verdict(spec: &SqlSpec, set: &Set) -> Verdict { if set_lifts_hold(set) { return Verdict::WRITE; } match set { Set::SetRole { .. } | Set::SetSessionAuthorization(_) => Verdict::WRITE, Set::SetTransaction { modes, .. } if grants_write(modes) => Verdict::WRITE, Set::SetTransaction { .. } | Set::SetTimeZone { .. } => Verdict::READ, Set::SingleAssignment { scope, variable, values, .. } => { // T-SQL has no list of assignments, so the parser reads `SET @x = 1, // @@session.transaction_read_only = 0` as one variable with two // values, the second a comparison. A variable followed by more than // one value is not read past: the carve-out below covers a plain // assignment, not whatever was folded into it. setting_verdict(spec, *scope, variable, values.len() == 1) } Set::ParenthesizedAssignments { variables, .. } => settings_verdict( variables .iter() .map(|name| setting_verdict(spec, None, name, true)), ), Set::MultipleAssignments { assignments } => settings_verdict( assignments .iter() .map(|assignment| setting_verdict(spec, assignment.scope, &assignment.name, true)), ), Set::SetSessionParam(SetSessionParamKind::Generic(param)) => settings_verdict( param .names .iter() .map(|name| plain_setting_verdict(spec, &[name.as_str()], true)), ), Set::SetSessionParam(SetSessionParamKind::Statistics(_)) => Verdict::READ, Set::SetNames { charset_name, .. } if SINGLE_BYTE_CHARSETS.contains(&charset_name.value.to_ascii_lowercase().as_str()) => { Verdict::READ } // Everything else the parser still accepts names no setting to look up, // so nothing can have vouched for it. _ => Verdict::WRITE, } } /// The maximum over a `SET`'s assignments, and stopped when it has none. fn settings_verdict(verdicts: impl Iterator) -> Verdict { verdicts .fold(None, |most: Option, verdict| { Some(match most { Some(most) => most.max(verdict), None => verdict, }) }) .unwrap_or(Verdict::WRITE) } /// One assigned name: a user variable is session scratch space and cannot /// disarm a hold, so it stays a read; a server-wide scope never does, whatever /// the name. `variable_ok` is whether a user variable may be read as one. fn setting_verdict( spec: &SqlSpec, scope: Option, name: &ObjectName, variable_ok: bool, ) -> Verdict { if scope == Some(ContextModifier::Global) { return Verdict::WRITE; } let parts: Option> = name .0 .iter() .map(|part| match part { ObjectNamePart::Identifier(ident) => Some(ident.value.as_str()), // A name computed by a function is not a name anyone listed. ObjectNamePart::Function(_) => None, }) .collect(); match parts { Some(parts) => plain_setting_verdict(spec, &parts, variable_ok), None => Verdict::WRITE, } } /// The name's parts as written: `["@@session", "time_zone"]`, `["TIMEZONE"]`. fn plain_setting_verdict(spec: &SqlSpec, parts: &[&str], variable_ok: bool) -> Verdict { // One leading `@` is a user variable. Two is a system variable, which is // exactly what this rule exists to look at. if variable_ok && let [only] = parts && only.starts_with('@') && !only.starts_with("@@") { return Verdict::READ; } let (scope, name) = match parts { [name] => (None, *name), [scope, name] => (Some(*scope), *name), // A qualified name that is not a scope prefix names a setting an // extension defined, which no list here can have vouched for. _ => return Verdict::WRITE, }; let scope = scope.map(|scope| scope.trim_start_matches("@@").to_ascii_lowercase()); // The scope keywords that make a setting server-wide or persistent, and // the two that leave it session-local. Any other first part is not a scope. match scope.as_deref() { None | Some("session" | "local") => {} Some(_) => return Verdict::WRITE, } let name = name.trim_start_matches("@@").to_ascii_lowercase(); if spec.plain_settings.contains(&name.as_str()) { Verdict::READ } else { Verdict::WRITE } } /// Whether an `EXPLAIN (…)` option turns ANALYZE on -- which runs the statement /// for real. /// /// sqlparser only sets the `analyze` flag for the keyword form /// (`EXPLAIN ANALYZE …`); the parenthesized form lands in `options` untouched, /// so `EXPLAIN (ANALYZE TRUE) DELETE FROM t` read as a plain EXPLAIN and /// deleted the rows. Anything but an explicit off counts as on: an argument /// this does not recognise is not a reason to call a write a read. Postgres /// takes the British `ANALYSE` as the same option. fn analyze_option_is_on(option: &UtilityOption) -> bool { let name = &option.name.value; if !name.eq_ignore_ascii_case("analyze") && !name.eq_ignore_ascii_case("analyse") { return false; } match &option.arg { Some(arg) => !matches!( arg.to_string().to_ascii_lowercase().as_str(), "false" | "off" | "0" ), None => true, } } /// A CTE body can be a `DELETE`. `WITH x AS (DELETE FROM t RETURNING *) SELECT * /// FROM x` parses as `Statement::Query`, so reading only the top-level variant /// calls a statement that empties a table a read. fn query_verdict(spec: &SqlSpec, query: &Query) -> Reading { let mut reading = set_expr_verdict(spec, &query.body); if let Some(with) = &query.with { for cte in &with.cte_tables { reading = reading.max(query_verdict(spec, &cte.query)); } } reading } fn set_expr_verdict(spec: &SqlSpec, body: &SetExpr) -> Reading { match body { // `SELECT * INTO newt FROM t` is DDL wearing a select's clothes: same // variant as a read, one field apart, and it creates a table. SetExpr::Select(select) if select.into.is_some() => Verdict::WRITE.into(), SetExpr::Select(_) | SetExpr::Values(_) | SetExpr::Table(_) => Reading::READ, SetExpr::Query(query) => query_verdict(spec, query), SetExpr::SetOperation { left, right, .. } => { set_expr_verdict(spec, left).max(set_expr_verdict(spec, right)) } SetExpr::Insert(statement) | SetExpr::Update(statement) | SetExpr::Delete(statement) | SetExpr::Merge(statement) => statement_verdict(spec, statement), } } /// What evaluating an `IF`'s condition can do. Before `IF` had an arm it /// needed Full on every engine, and a condition calling a function can still /// write anything a Postgres or Snowflake function can, so everything but /// operators over names, values and subqueries keeps that verdict. A subquery /// is read like any other query. fn condition_verdict(spec: &SqlSpec, condition: &Expr) -> Reading { match condition { Expr::Identifier(_) | Expr::CompoundIdentifier(_) | Expr::Value(_) => Reading::READ, Expr::IsNull(expr) | Expr::IsNotNull(expr) | Expr::IsTrue(expr) | Expr::IsNotTrue(expr) | Expr::IsFalse(expr) | Expr::IsNotFalse(expr) | Expr::IsUnknown(expr) | Expr::IsNotUnknown(expr) | Expr::Nested(expr) | Expr::UnaryOp { expr, .. } => condition_verdict(spec, expr), Expr::BinaryOp { left, right, .. } | Expr::Like { expr: left, pattern: right, escape_char: None, .. } | Expr::ILike { expr: left, pattern: right, escape_char: None, .. } => condition_verdict(spec, left).max(condition_verdict(spec, right)), Expr::Between { expr, low, high, .. } => condition_verdict(spec, expr) .max(condition_verdict(spec, low)) .max(condition_verdict(spec, high)), Expr::InList { expr, list, .. } => list .iter() .map(|item| condition_verdict(spec, item)) .fold(condition_verdict(spec, expr), Reading::max), Expr::Exists { subquery, .. } | Expr::Subquery(subquery) => query_verdict(spec, subquery), Expr::InSubquery { expr, subquery, .. } => { condition_verdict(spec, expr).max(query_verdict(spec, subquery)) } _ => Verdict::FULL.into(), } } /// Additive is `ADD COLUMN` and nothing else. Deliberately strict: an operation /// this does not name -- and there are around sixty -- is treated as able to /// lose data, for the same reason the top-level wildcard is. fn alter_verdict(operation: &AlterTableOperation) -> Verdict { match operation { AlterTableOperation::AddColumn { .. } => Verdict::WRITE, _ => Verdict::FULL, } } /// Why the mode stopped a statement. Answered by `gate`, which decides; saying /// so is the dialog's job and lives elsewhere. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Stop { /// The connection is not allowed to run this. The mode carried is exactly /// what the statement needs -- never a higher one. Upgrade(Mode), /// Allowed, but it destroys something and this connection has not silenced /// that kind. Confirm(Destructive), /// dbdelve could not read it. Runs once on confirmation and changes nothing, /// unless the user has opted to run these unasked (`gate_own_run`). RunOnce, } /// Whether the mode stops this statement. `None` means run it. pub(crate) fn gate(verdict: &Verdict, mode: Mode, confirmed: &[Destructive]) -> Option { // Tested before the mode comparison, because it is the one verdict whose // remedy is not a mode change: every typo lands here, and asking someone to // raise a connection to Full to get a syntax error back would teach them to // live in Full. // // The one mode it can ask for is Read-write, where no server-side hold // stands behind Read-only (see `classify`). if verdict.destructive.contains(&Destructive::Unreadable) { if verdict.mode > mode { return Some(Stop::Upgrade(verdict.mode)); } return Some(Stop::RunOnce); } if verdict.mode > mode { return Some(Stop::Upgrade(verdict.mode)); } // The first kind nobody has silenced, and only that one: the dialog names a // single kind, and confirming it runs the whole submission -- so // `DROP TABLE a; TRUNCATE TABLE b` asks about the `DROP` and then runs both. // What the set buys is narrower than one confirmation per kind: it stops a // silenced kind from masking an unsilenced one, which a single slot did. // The dialog renders the submission, so what Run covers is on screen. verdict .destructive .iter() .find(|kind| !confirmed.contains(kind)) .copied() .map(Stop::Confirm) } /// `gate` for a statement the user ran, with `run_unreadable`, their app-wide /// opt-in, letting what dbdelve cannot parse through unasked. Only `RunOnce` /// gives way: an unreadable `Upgrade` is the mode check where nothing on the /// server holds Read-only, and Read-only has to keep meaning it. pub(crate) fn gate_own_run( verdict: &Verdict, mode: Mode, confirmed: &[Destructive], run_unreadable: bool, ) -> Option { gate(verdict, mode, confirmed).filter(|stop| !(run_unreadable && *stop == Stop::RunOnce)) } /// `sql` laid out over several lines: the same tokens, indented. Refused when /// the buffer holds a dollar-quoted body, which this cannot reflow safely. /// /// Token-level reformatting rather than a round trip through the `sqlparser` /// AST this module already parses with for `classify`. Regenerating a statement /// from that AST drops every comment the user wrote and quietly rewrites the /// dialect corners sqlparser only half-supports, which is hard rule 1 — dbdelve /// never rewrites SQL behind the user's back. /// /// A tokenizer is meant to be unable to do either, and sqlformat is one /// everywhere except `$$`: it tokenizes *inside* a dollar-quoted body instead of /// carrying it through whole, so `select $$hello world$$` comes back as /// `$$hello world$$` — a different value, not a different layout. Single-quoted /// literals are safe. So the rule is refuse, never guess: a buffer holding one /// is returned unformatted rather than silently edited. // // ponytail: refuses the whole buffer over one dollar quote, where splitting on // the quoted regions and formatting only the text between them would still // format the rest. Worth doing when someone is actually editing plpgsql here. // // ponytail: `FormatOptions`' `dialect` is Generic except on SQL Server, where // Generic splits `[my col]` into `[ my col ]`, another name. Postgres's dialect // is the upgrade path if its output ever looks wrong there. /// /// Each statement is reflowed on its own, and the text between statements -- /// blank lines, comments, the `;`s and SQL Server's `GO` lines -- is kept as /// written, but for two things: a statement sharing a line with the one before /// it starts a line of its own, and one indented on its line comes back flush. /// Reflowed with its batch, `GO 5` becomes a `GO` and a stray `5` on the next /// line: a count the refusal no longer sees. /// /// Statements are cut at the `;`s sqlparser reads in the engine's dialect, /// which knows MySQL's `\'` where `Buffer`'s split does not and would cut a /// literal in two. SQL Server's are `Buffer`'s, which reads batches and /// `BEGIN … END`, and T-SQL has no backslash escapes. /// /// The result must tokenize as the buffer did, whitespace aside, or it is /// refused: sqlformat respaces some tokens into others, like `[my col]` /// outside SQL Server's dialect or MySQL's `0x0A`. /// /// Err is the refusal, said to the user as it stands. A MongoDB buffer is not /// SQL, and sqlformat over it splits regexes and turns comment text into code, /// so `mql::format` lays it out instead. // // ponytail: a selection that starts partway through a line comes back with its // later lines at column 0, not under its first. Indenting them is not a plain // prefix per line here, as it is in `mql::format`: sqlformat carries a // multi-line string literal through as one token, and a prefix would edit its // value. pub(crate) fn format(engine: Engine, sql: &str) -> Result { match engine.syntax() { Syntax::Sql => {} Syntax::Mongo => return crate::mql::format(sql), Syntax::Redis => return Err("Not formatting: a Redis command is one line, as typed."), } let reader = parser(engine.spec().sql.parser_dialect); let layout = sqlformat_dialect(engine.spec().sql.format_dialect); if has_dollar_quote(sql) { return Err(DOLLAR_QUOTED); } let Some(tokens) = located_tokens(reader.as_ref(), sql) else { return Err(UNENDED); }; let statements = match batches_on(engine) { true => Buffer::for_engine(engine, sql).statements().to_vec(), false => between_semicolons(&tokens), }; let options = sqlformat::FormatOptions { dialect: layout, ..sqlformat::FormatOptions::default() }; let mut formatted = String::with_capacity(sql.len()); let mut written = 0; for (index, statement) in statements.iter().enumerate() { let gap = &sql[written..statement.start]; let gap = match gap.rfind('\n') { Some(line) if gap[line + 1..].trim().is_empty() => &gap[..=line], Some(_) => gap, None if index > 0 => { formatted += gap.trim_end(); "\n" } None => gap, }; formatted += gap; formatted += &sqlformat::format( &sql[statement.clone()], &sqlformat::QueryParams::default(), &options, ); written = statement.end; } formatted += &sql[written..]; let before = layout_free(tokens.into_iter().map(|(token, _)| token)); let after = Tokenizer::new(reader.as_ref(), &formatted) .tokenize() .ok() .map(layout_free); match after == Some(before) { true => Ok(formatted), false => Err("Not formatting: the new layout would read as different SQL."), } } fn sqlformat_dialect(dialect: FormatDialect) -> sqlformat::Dialect { match dialect { FormatDialect::Generic => sqlformat::Dialect::Generic, FormatDialect::SqlServer => sqlformat::Dialect::SQLServer, } } const DOLLAR_QUOTED: &str = "Not formatting: a dollar-quoted body would be rewritten."; const UNENDED: &str = "Not formatting: a string, quoted name or comment does not end."; /// [`format`] of the `selection` of `sql` alone. /// /// Refused when either end of the selection falls inside a word, a literal, a /// quoted name or a comment of the buffer around it: reflowed on its own, the /// piece of a literal reads as code, and its text changes with the layout. pub(crate) fn format_selection( engine: Engine, sql: &str, selection: Range, ) -> Result { let splits = match dialect(engine) { Some(reader) => { // Text past the end's line cannot change how the text up to it // reads, and a buffer can be megabytes. let line_end = sql[selection.end..] .find('\n') .map_or(sql.len(), |at| selection.end + at); let tokens = located_tokens(reader.as_ref(), &sql[..line_end]).ok_or(UNENDED)?; [selection.start, selection.end].iter().any(|&at| { tokens .iter() .any(|(token, range)| !is_layout(token) && range.start < at && at < range.end) }) } None => [selection.start, selection.end] .iter() .any(|&at| crate::mql::splits_a_token(sql, at)), }; if splits { return Err( "Not formatting: the selection starts or ends partway through a word, string or \ comment.", ); } format(engine, &sql[selection]) } /// The statements in `tokens` as the dialect's tokenizer cuts them: from the /// first token after a `;` that is neither whitespace nor a comment to the last /// one before the next `;`. fn between_semicolons(tokens: &[(Token, Range)]) -> Vec> { let mut statements = Vec::new(); let mut current: Option> = None; for (token, range) in tokens { match token { Token::SemiColon => statements.extend(current.take()), Token::Whitespace(_) => {} _ => { let start = current .as_ref() .map_or(range.start, |current| current.start); current = Some(start..range.end); } } } statements.extend(current); statements } fn is_layout(token: &Token) -> bool { matches!( token, Token::Whitespace(Whitespace::Space | Whitespace::Newline | Whitespace::Tab) ) } /// `tokens` with the whitespace between them left out, and each comment /// reduced to its words, which sqlformat respaces but never rewrites. fn layout_free(tokens: impl IntoIterator) -> Vec { let words = |text: &str| text.split_whitespace().collect::>().join(" "); tokens .into_iter() .filter(|token| !is_layout(token)) .map(|token| match token { Token::Whitespace(Whitespace::SingleLineComment { comment, prefix }) => { Token::Whitespace(Whitespace::SingleLineComment { comment: words(&comment), prefix, }) } Token::Whitespace(Whitespace::MultiLineComment(comment)) => { Token::Whitespace(Whitespace::MultiLineComment(words(&comment))) } token => token, }) .collect() } /// The tokens of `sql` with the byte range each covers. `None` when `sql` does /// not tokenize. fn located_tokens(dialect: &dyn Dialect, sql: &str) -> Option)>> { let (tokens, whole) = located_prefix(dialect, sql); whole.then_some(tokens) } /// [`located_tokens`] up to wherever the tokenizer stopped, and whether that /// was the end of `sql`. fn located_prefix(dialect: &dyn Dialect, sql: &str) -> (Vec<(Token, Range)>, bool) { let mut tokens = Vec::new(); let whole = Tokenizer::new(dialect, sql) .tokenize_with_location_into_buf(&mut tokens) .is_ok(); // Spans are lines and columns of chars, in source order, so one walk // forward through the text turns them all into byte offsets. let mut chars = sql.char_indices().peekable(); let (mut line, mut column) = (1, 1); let mut offset_of = |location: Location| { while (line, column) < (location.line, location.column) { let Some((_, c)) = chars.next() else { break; }; if c == '\n' { (line, column) = (line + 1, 1); } else { column += 1; } } chars.peek().map_or(sql.len(), |(offset, _)| *offset) }; let tokens = tokens .into_iter() .map(|token| { let start = offset_of(token.span.start); (token.token, start..offset_of(token.span.end)) }) .collect(); (tokens, whole) } /// Whether `sql` opens a `$$` or `$tag$` body anywhere. /// /// Deliberately not a parse: it answers "is this text unsafe to reflow", and /// erring towards yes only costs a refusal. The tag rule is Postgres's own, and /// it is what keeps the `$1` placeholder out -- a tag is empty or starts with a /// letter, so `$1` never reads as an opening quote. fn has_dollar_quote(sql: &str) -> bool { let bytes = sql.as_bytes(); bytes.iter().enumerate().any(|(i, &b)| { if b != b'$' { return false; } let tag = bytes[i + 1..] .iter() .take_while(|c| c.is_ascii_alphanumeric() || **c == b'_') .count(); let starts_valid = tag == 0 || !bytes[i + 1].is_ascii_digit(); starts_valid && bytes.get(i + 1 + tag) == Some(&b'$') }) } #[cfg(test)] mod tests { use super::*; #[test] fn every_engine_that_opens_a_transaction_spells_one_the_gate_reads() { use crate::db::Engine; for engine in Engine::ALL { let Some(begin) = engine.begins_transaction() else { continue; }; // The buffer gets this text and the user may run it again, so it // has to read back as a bracket rather than as a statement the // gate cannot place. assert!(is_transaction_bracket(begin), "{engine:?}: {begin}"); assert!( is_transaction_bracket(&format!("{begin};")), "{engine:?}: {begin};" ); // Transaction control runs in every mode: asking for Read-write // to end a transaction would teach people to live in Full. assert_eq!(classify(engine, begin).mode, Mode::ReadOnly, "{engine:?}"); for verb in ["COMMIT", "ROLLBACK"] { assert_eq!(classify(engine, verb).mode, Mode::ReadOnly, "{engine:?}"); } } } #[test] fn opening_a_transaction_is_not_the_same_question_as_bracketing_a_batch() { use crate::db::Engine; // The one engine the two answer differently, and the reason // `begins_transaction` exists at all: collapsing them into one method // would stop Postgres ever opening a transaction. assert_eq!(Engine::Postgres.transaction_start(), None); assert_eq!(Engine::Postgres.begins_transaction(), Some("BEGIN")); // Where neither has a transaction to offer, both say so. for engine in [Engine::MongoDb, Engine::Redis] { assert_eq!(engine.transaction_start(), None, "{engine:?}"); assert_eq!(engine.begins_transaction(), None, "{engine:?}"); } } #[test] fn ending_a_transaction_and_opening_the_next_leaves_one_open() { use crate::db::Engine; // What Commit sends while auto-commit is off. `leaves` reading the // pair as closed would leave the switch saying "off" over a session // that is autocommitting again. for engine in [Engine::Postgres, Engine::MySql, Engine::Sqlite] { let begin = engine.begins_transaction().expect("opens one"); let sent = format!("COMMIT;\n\n{begin};"); assert_eq!(leaves(engine, &sent).transaction, Some(true), "{engine:?}"); assert_eq!( leaves(engine, "COMMIT;").transaction, Some(false), "{engine:?}" ); } } #[test] fn the_mode_cycle_runs_read_only_to_full_and_back() { assert_eq!(Mode::ReadOnly.next(), Mode::ReadWrite); assert_eq!(Mode::ReadWrite.next(), Mode::Full); assert_eq!(Mode::Full.next(), Mode::ReadOnly); } #[test] fn a_grids_statement_is_found_wherever_it_stands_in_the_buffer() { let sql = "SELECT 1;\nSELECT * FROM t;\nDELETE FROM t;"; let buffer = Buffer::parse(sql); let select = sql.find("SELECT *").unwrap(); let delete = sql.find("DELETE").unwrap(); // The cursor on another statement does not make that one the grid's. let grid = buffer.statement_at(select).unwrap(); assert_eq!( buffer.find(Engine::Postgres, sql, delete, &sql[grid.clone()]), Some(grid) ); let first = buffer.statement_at(0).unwrap(); assert_eq!( buffer.find(Engine::Postgres, sql, 0, &sql[first.clone()]), Some(first) ); assert_eq!( buffer.find(Engine::Postgres, sql, delete, "SELECT * FROM u"), None ); } fn texts(sql: &str) -> Vec<&str> { Buffer::parse(sql) .statements() .iter() .map(|r| &sql[r.clone()]) .collect() } #[test] fn a_sort_goes_in_before_the_limit() { // Appended after the limit it would not parse; applied after the limit // it would sort one arbitrary thousand rows of the table. assert_eq!( with_order_by( Engine::Postgres, r#"SELECT * FROM "public"."measurements" LIMIT 1000"#, &[SortKey::new(r#""id""#, false)] ) .unwrap(), r#"SELECT * FROM "public"."measurements" ORDER BY "id" DESC LIMIT 1000"# ); } #[test] fn a_second_key_joins_the_first() { let sorted = with_order_by( Engine::Postgres, "SELECT * FROM t", &[SortKey::new(r#""a""#, true), SortKey::new("3", false)], ) .unwrap(); assert_eq!(sorted, r#"SELECT * FROM t ORDER BY "a" ASC, 3 DESC"#); assert_eq!( order_by(Engine::Postgres, &sorted).unwrap(), vec![SortKey::new(r#""a""#, true), SortKey::new("3", false)] ); } #[test] fn sorting_again_replaces_the_clause_it_wrote() { let once = with_order_by( Engine::Postgres, "SELECT * FROM t LIMIT 5", &[SortKey::new("a", true)], ) .unwrap(); let twice = with_order_by(Engine::Postgres, &once, &[SortKey::new("b", false)]).unwrap(); assert_eq!(twice, "SELECT * FROM t ORDER BY b DESC LIMIT 5"); // And clearing it leaves the statement as it was, not a hole. assert_eq!( with_order_by(Engine::Postgres, &twice, &[]).unwrap(), "SELECT * FROM t LIMIT 5" ); } #[test] fn a_key_the_user_wrote_reads_back_verbatim() { let keys = order_by( Engine::Postgres, "SELECT * FROM t ORDER BY lower(name), 2 DESC", ) .unwrap(); assert_eq!( keys, vec![SortKey::new("lower(name)", true), SortKey::new("2", false)] ); } #[test] fn a_union_sorts_at_the_end_of_the_whole_query() { assert_eq!( with_order_by( Engine::Postgres, "SELECT a FROM t UNION SELECT a FROM u LIMIT 3", &[SortKey::new("a", true)] ) .unwrap(), "SELECT a FROM t UNION SELECT a FROM u ORDER BY a ASC LIMIT 3" ); } #[test] fn a_subquerys_own_sort_is_left_alone() { // The inner ORDER BY belongs to the subquery. Reading it as the outer // query's sort would flip a clause the user wrote for another purpose. let sql = "SELECT * FROM (SELECT a FROM t ORDER BY a LIMIT 3) s"; assert_eq!(order_by(Engine::Postgres, sql).unwrap(), vec![]); assert_eq!( with_order_by(Engine::Postgres, sql, &[SortKey::new("a", false)]).unwrap(), "SELECT * FROM (SELECT a FROM t ORDER BY a LIMIT 3) s ORDER BY a DESC" ); } #[test] fn nothing_is_spliced_into_a_statement_dbdelve_cannot_read_whole() { // Every one of these is valid SQL the grammar does not cover. Guessing // where the clause goes would corrupt a statement the user wrote. for sql in [ "SELECT * FROM t ORDER BY a NULLS FIRST", "SELECT * FROM t FOR UPDATE", "SELECT * FROM t OFFSET 10 LIMIT 5", ] { assert!( order_by(Engine::Postgres, sql).is_none(), "{sql} should not be sortable" ); assert!( with_order_by(Engine::Postgres, sql, &[]).is_none(), "{sql} was spliced" ); } } #[test] fn only_a_query_takes_a_sort() { for sql in [ "UPDATE t SET a = 1", "SELECT 1", "SELECT 1; SELECT 2", "BEGIN; SELECT 1; COMMIT", "-- nothing here", ] { assert!( order_by(Engine::Postgres, sql).is_none(), "{sql} should not be sortable" ); } } #[test] fn a_plan_is_not_a_result_to_sort() { // The grammar flattens `EXPLAIN`'s payload into the statement, so the // explained query's `select` and `from` sit exactly where a sortable // statement's do. Left unguarded, a header click on the plan's one text // column spliced an `ORDER BY` into the query being explained -- which // both sorts nothing on screen and explains a different statement. for sql in [ "EXPLAIN SELECT * FROM t", "EXPLAIN ANALYZE SELECT * FROM t", "explain analyze select id from accounts where x = 1", // Already carrying a sort of its own, which is the case where a // readout looks most convincingly like a sortable grid. "EXPLAIN ANALYZE SELECT * FROM t ORDER BY a", ] { assert!( order_by(Engine::Postgres, sql).is_none(), "{sql} reported a sort" ); assert!( with_order_by(Engine::Postgres, sql, &[SortKey::new("a", true)]).is_none(), "{sql} was spliced" ); } } #[test] fn grammar_loads() { assert_eq!( texts("SELECT 1;"), vec!["SELECT 1"], "SQL grammar failed to load" ); } #[test] fn a_leading_comment_is_not_a_runnable_statement() { // Cursor at 0 in a buffer that opens with a header comment. Running the // comment returns an empty response with no error to explain it. let sql = "-- notes; about this\nSELECT 1;"; let buffer = Buffer::parse(sql); assert_eq!(&sql[buffer.statement_at(0).unwrap()], "SELECT 1"); } #[test] fn a_trailing_comment_is_not_a_runnable_statement() { let sql = "SELECT 1; -- trailing"; let buffer = Buffer::parse(sql); assert_eq!(&sql[buffer.statement_at(sql.len()).unwrap()], "SELECT 1"); } #[test] fn a_cursor_inside_a_gap_comment_selects_the_preceding_statement() { // The contract statement_at documents, which the block comment used to // win against by matching its own range. let sql = "SELECT 1;\n/* gap comment */\nSELECT 2;"; let buffer = Buffer::parse(sql); let inside = sql.find("gap").unwrap(); assert_eq!(&sql[buffer.statement_at(inside).unwrap()], "SELECT 1"); } #[test] fn a_buffer_of_only_comments_has_nothing_to_run() { assert!(Buffer::parse("-- only a comment").statement_at(0).is_none()); assert!(Buffer::parse(";;;").statement_at(0).is_none()); } #[test] fn a_statement_the_grammar_has_never_heard_of_is_still_one() { // One dialect's grammar, four servers. None of these parse, all of // them are statements, and whether they are valid is the server's say. for sql in [ "PRAGMA table_info(accounts);", "CALL refresh_totals();", "LISTEN jobs;", "USE dbdelve_dev", ] { let buffer = Buffer::parse(sql); let range = buffer.statement_at(0).unwrap_or_else(|| panic!("{sql}")); assert_eq!(&sql[range], sql.trim_end_matches(';').trim_end(), "{sql}"); } } #[test] fn an_unread_statement_between_two_others_is_neither_of_them() { // It used to be glued onto the one before it, so running the first // line ran the second as well. assert_eq!( texts("SELECT 1;\nPRAGMA table_info(accounts);\nSELECT 2;"), vec!["SELECT 1", "PRAGMA table_info(accounts)", "SELECT 2"] ); } #[test] fn a_semicolon_inside_unread_text_only_counts_where_it_separates() { // None of this parses, so the scan is all there is between a function // body and the server receiving half of it. let body = "CREATE PROCEDURE p() AS $fn$ BEGIN PERFORM 1; END $fn$"; assert_eq!(texts(&format!("{body};\nCALL p()")), vec![body, "CALL p()"]); assert_eq!( texts("PRAGMA note = 'a;b'; -- c;d\nPRAGMA other"), vec!["PRAGMA note = 'a;b'", "-- c;d\nPRAGMA other"] ); assert_eq!( texts("PRAGMA note = 1 /*/ ; */; PRAGMA other"), vec!["PRAGMA note = 1 /*/ ; */", "PRAGMA other"] ); } #[test] fn a_statement_whose_opening_is_unread_is_sent_whole() { // The grammar reads this as an unknown `GRANT`, a `SELECT ON t`, and an // unknown `TO r`. It is one statement up to its `;`. assert_eq!( texts("GRANT SELECT ON t TO r;\nSELECT 2"), vec!["GRANT SELECT ON t TO r", "SELECT 2"] ); } #[test] fn a_semicolon_in_a_comment_does_not_cut_a_tail_off_its_statement() { // The hazard the backwards merge exists for: the head of this alone is // an unqualified DELETE. let sql = "DELETE FROM t -- note; still the same statement\n WHERE !!! garbage"; assert_eq!(texts(sql), vec![sql]); } #[test] fn a_non_ascii_character_in_unread_text_is_not_a_byte() { // The scanner walks bytes and slices characters. A bare `\u{e9}` used to // leave the cursor mid-character and panic the app rather than run // anything -- quoted it was always safe, since the quote is jumped whole. assert_eq!(texts("USE caf\u{e9}_db"), vec!["USE caf\u{e9}_db"]); assert_eq!( texts("CALL refresh_totals('caf\u{e9}')"), vec!["CALL refresh_totals('caf\u{e9}')"] ); assert_eq!( texts("SELECT 1;\nUSE caf\u{e9}_db"), vec!["SELECT 1", "USE caf\u{e9}_db"] ); } #[test] fn a_transaction_block_runs_as_one_statement() { assert_eq!( texts("BEGIN; SELECT 1; COMMIT;"), vec!["BEGIN; SELECT 1; COMMIT"] ); } #[test] fn splits_simple_statements() { assert_eq!(texts("SELECT 1;\nSELECT 2;"), vec!["SELECT 1", "SELECT 2"]); } #[test] fn unterminated_final_statement_is_still_found() { assert_eq!(texts("SELECT 1;\nSELECT 2"), vec!["SELECT 1", "SELECT 2"]); } fn queued_texts<'a>(sql: &'a str, ranges: &[Range]) -> Vec<&'a str> { ranges.iter().map(|r| &sql[r.clone()]).collect() } #[test] fn a_queue_is_every_statement_with_no_selection() { let sql = "SELECT 1;\nSELECT 2;\nSELECT 3;"; let ranges = queued_statements(Engine::Postgres, sql, None); assert_eq!( queued_texts(sql, &ranges), vec!["SELECT 1", "SELECT 2", "SELECT 3"] ); } #[test] fn a_queue_includes_a_final_statement_with_no_trailing_semicolon() { let sql = "SELECT 1;\nSELECT 2"; let ranges = queued_statements(Engine::Postgres, sql, None); assert_eq!(queued_texts(sql, &ranges), vec!["SELECT 1", "SELECT 2"]); } #[test] fn a_queue_keeps_only_statements_the_selection_overlaps() { let sql = "SELECT 1;\nSELECT 2;\nSELECT 3;"; let second = sql.find("SELECT 2").unwrap(); let third = sql.find("SELECT 3").unwrap(); // Spans all of statement 2 and part of statement 3. let selection = second..third + "SELECT 3".len() / 2; let ranges = queued_statements(Engine::Postgres, sql, Some(selection)); assert_eq!(queued_texts(sql, &ranges), vec!["SELECT 2", "SELECT 3"]); } /// Issue #298: a selection of the INSERT ran every statement after it. #[test] fn a_mysql_selection_stops_at_its_last_statement_past_a_backslash_escape() { let sql = "SELECT 1;\nINSERT INTO t (a) VALUES ('O\\'Brien');\nSELECT 2;\nSELECT 3;"; let insert = sql.find("INSERT").unwrap(); let selection = insert - 3..sql.find("SELECT 2").unwrap(); let ranges = queued_statements(Engine::MySql, sql, Some(selection)); assert_eq!( queued_texts(sql, &ranges), vec!["SELECT 1", "INSERT INTO t (a) VALUES ('O\\'Brien')"] ); } #[test] fn a_mysql_hash_comment_holds_no_quote_and_no_statement() { let sql = "SELECT 1;\n# it's a comment; still one\nSELECT 2;\nSELECT 3;"; for engine in [Engine::MySql, Engine::MariaDb] { let ranges = queued_statements(engine, sql, None); assert_eq!( queued_texts(sql, &ranges), vec!["SELECT 1", "SELECT 2", "SELECT 3"], "{engine:?}" ); } } /// Blanking is for finding boundaries only: what runs is the buffer's own /// text, comment and escape included. #[test] fn a_mysql_statement_runs_with_its_comment_and_escapes_as_typed() { let sql = "SELECT 'a\\\\', \"b\\\"c\", # it's\n 2;\nSELECT 3;"; let ranges = queued_statements(Engine::MySql, sql, None); assert_eq!( queued_texts(sql, &ranges), vec!["SELECT 'a\\\\', \"b\\\"c\", # it's\n 2", "SELECT 3"] ); } #[test] fn a_backslash_in_a_dollar_quoted_body_leaves_its_delimiters_alone() { let sql = "SELECT 0;\nSELECT $$'C:\\tmp'$$;\nDELETE FROM t;"; let ranges = queued_statements(Engine::Postgres, sql, None); assert_eq!( queued_texts(sql, &ranges), vec!["SELECT 0", "SELECT $$'C:\\tmp'$$", "DELETE FROM t"] ); } /// sqlparser places what it expands from a `/*! … */` at the comment's /// own start, so blanking by those spans would open the comment up. #[test] fn a_mysql_executable_comment_stays_closed() { let sql = "SELECT 0;\nSELECT /*! # don't\n1 */;\nSELECT 2;"; let ranges = queued_statements(Engine::MySql, sql, None); assert_eq!( queued_texts(sql, &ranges), vec!["SELECT 0", "SELECT /*! # don't\n1 */", "SELECT 2"] ); } #[test] fn a_snowflake_slash_comment_holds_no_quote() { let sql = "SELECT 1;\n// don't\nSELECT 2;"; let ranges = queued_statements(Engine::Snowflake, sql, None); assert_eq!(queued_texts(sql, &ranges), vec!["SELECT 1", "SELECT 2"]); } /// Postgres reads neither: a backslash is a plain character in a standard /// string and `#` is an operator. #[test] fn a_postgres_buffer_reads_backslashes_and_hashes_as_postgres_does() { let sql = "SELECT 'a\\';\nSELECT 1 # 2;\nSELECT 3;"; let ranges = queued_statements(Engine::Postgres, sql, None); assert_eq!( queued_texts(sql, &ranges), vec!["SELECT 'a\\'", "SELECT 1 # 2", "SELECT 3"] ); } #[test] fn an_empty_selection_behaves_like_none() { let sql = "SELECT 1;\nSELECT 2;"; let empty = 3..3; assert_eq!( queued_statements(Engine::Postgres, sql, Some(empty)), queued_statements(Engine::Postgres, sql, None) ); } #[test] fn a_queue_on_sql_server_never_runs_the_go_line() { let sql = "SELECT 1;\nGO\nSELECT 2;"; let ranges = queued_statements(Engine::SqlServer, sql, None); assert_eq!(queued_texts(sql, &ranges), vec!["SELECT 1;", "SELECT 2;"]); } /// A `GO` is a scope boundary and a semicolon is not, so cutting at the /// semicolon would send the `DECLARE` and the `SELECT` that reads it as /// two batches, and the second would not know the variable. #[test] fn a_sql_server_selection_runs_a_batch_at_a_time_not_a_statement() { let sql = "DECLARE @x int = 1;\nSELECT @x;"; let ranges = queued_statements(Engine::SqlServer, sql, None); assert_eq!(queued_texts(sql, &ranges), vec![sql]); // The same text is two statements on an engine whose session carries // the declaration across submissions. assert_eq!(queued_statements(Engine::Postgres, sql, None).len(), 2); } fn split_texts(engine: Engine, sql: &str) -> Vec<&str> { let batches = queued_statements(engine, sql, Some(0..sql.len())); queued_texts(sql, &split_reads(engine, sql, &batches, 0..sql.len())) } #[test] fn a_sql_server_batch_of_plain_reads_splits_into_its_statements() { let sql = "SELECT 1 AS a;\nSELECT [b] FROM t WHERE n = '@x #y';"; assert_eq!( split_texts(Engine::SqlServer, sql), vec!["SELECT 1 AS a", "SELECT [b] FROM t WHERE n = '@x #y'"] ); assert_eq!( split_texts( Engine::SqlServer, "SELECT 1;\nGO\nSELECT 2; SELECT @@VERSION;" ), vec!["SELECT 1", "SELECT 2", "SELECT @@VERSION"] ); // Only the statements the selection touches. let batches = queued_statements(Engine::SqlServer, sql, Some(0..3)); assert_eq!(split_reads(Engine::SqlServer, sql, &batches, 0..3).len(), 1); assert!(split_texts(Engine::Postgres, "SELECT 1; SELECT 2;").is_empty()); } /// Each of these needs the rest of its batch beside it, or is no plain /// read, so the batch is sent whole as it always was. #[test] fn a_sql_server_batch_with_anything_but_plain_reads_stays_whole() { for sql in [ "DECLARE @x int = 1; SELECT @x;", "SELECT 1; SELECT @x;", "SELECT 1; SELECT * FROM #t;", "SELECT 1; SELECT * FROM ##t;", "SELECT 1; EXEC sp_who;", "SET NOCOUNT ON; SELECT 1;", "SELECT 1; IF 1 = 1 BEGIN SELECT 2; END", "BEGIN SELECT 1; SELECT 2; END", "SELECT 1;\nGO\nSELECT 2; SELECT @x;", "SELECT 1; UPDATE t SET a = 1;", ] { assert!(split_texts(Engine::SqlServer, sql).is_empty(), "{sql}"); } } /// A batch is what SQL Server is sent, so a grid is reserved per statement /// inside it; everywhere else a submission is one statement and answers /// with at most one set. #[test] fn a_sql_server_batch_expects_a_result_set_per_statement_in_it() { let sql = "SELECT 1; SELECT 2;"; assert_eq!(expected_sets(Engine::SqlServer, sql), 2); assert_eq!(expected_sets(Engine::Postgres, sql), 1); assert_eq!(expected_sets(Engine::SqlServer, "SELECT 1"), 1); assert_eq!(expected_sets(Engine::SqlServer, ""), 1); } #[test] fn a_counted_go_is_refused_rather_than_run_once() { let sql = "SELECT 1;\nGO 5\nSELECT 2;"; assert!(batch_counts(Engine::SqlServer, sql).is_err()); // A plain `GO` is a separator, not a repeat, and still runs. assert!(batch_counts(Engine::SqlServer, "SELECT 1;\nGO\nSELECT 2;").is_ok()); // Nowhere else is `GO` anything but a name. assert!(batch_counts(Engine::Postgres, sql).is_ok()); } #[test] fn semicolon_inside_a_string_literal_does_not_split() { // The case that breaks every naive splitter. assert_eq!( texts("SELECT ';' AS sep;\nSELECT 2;"), vec!["SELECT ';' AS sep", "SELECT 2"] ); } fn tsql(sql: &str) -> Vec<&str> { Buffer::for_engine(Engine::SqlServer, sql) .statements() .iter() .map(|r| &sql[r.clone()]) .collect() } #[test] fn a_t_sql_routine_runs_to_the_end_of_its_batch() { assert_eq!( tsql("CREATE PROCEDURE p AS\nSET NOCOUNT ON;\nUPDATE t SET x = 1 WHERE id = 2;"), ["CREATE PROCEDURE p AS\nSET NOCOUNT ON;\nUPDATE t SET x = 1 WHERE id = 2"] ); for opening in [ "CREATE OR ALTER FUNCTION", "ALTER PROC", "create trigger", "CREATE OR ALTER\nPROCEDURE", ] { let sql = format!("SELECT 0;\nGO\n{opening} r AS SELECT 1; SELECT 2;\nGO\nSELECT 3"); let routine = format!("{opening} r AS SELECT 1; SELECT 2"); assert_eq!( tsql(&sql), ["SELECT 0", routine.as_str(), "SELECT 3"], "{opening}" ); } } #[test] fn a_t_sql_block_is_one_statement() { let cases: &[(&str, &[&str])] = &[ ( "IF 1 = 1 BEGIN DELETE FROM t WHERE id = 1; DELETE FROM u WHERE id = 2; END", &["IF 1 = 1 BEGIN DELETE FROM t WHERE id = 1; DELETE FROM u WHERE id = 2; END"], ), ( "BEGIN TRY SELECT 1; SELECT 2; END TRY BEGIN CATCH SELECT 3; END CATCH; SELECT 4", &[ "BEGIN TRY SELECT 1; SELECT 2; END TRY BEGIN CATCH SELECT 3; END CATCH", "SELECT 4", ], ), // Nested, with a `CASE … END` inside that closes nothing else. ( "WHILE 1 = 1 BEGIN IF 1 = 1 BEGIN SELECT CASE WHEN 1 = 1 THEN 1 END; BREAK; END; \ SELECT 2; END; SELECT 3", &[ "WHILE 1 = 1 BEGIN IF 1 = 1 BEGIN SELECT CASE WHEN 1 = 1 THEN 1 END; BREAK; END; \ SELECT 2; END", "SELECT 3", ], ), // Statements, not blocks. ( "BEGIN TRAN; UPDATE t SET x = 1; COMMIT; SELECT 5", &["BEGIN TRAN; UPDATE t SET x = 1; COMMIT", "SELECT 5"], ), ( "BEGIN DISTRIBUTED TRANSACTION; SELECT 1", &["BEGIN DISTRIBUTED TRANSACTION", "SELECT 1"], ), // Keywords inside strings, comments and quoted names are not keywords. ( "SELECT 'BEGIN'; SELECT [begin], \"case\"; /* BEGIN */ SELECT 3; -- BEGIN\nSELECT 4", &[ "SELECT 'BEGIN'", "SELECT [begin], \"case\"", "SELECT 3", "SELECT 4", ], ), ]; for (sql, expected) in cases { assert_eq!(tsql(sql), *expected, "{sql}"); } } #[test] fn a_t_sql_bracketed_name_is_quoted() { assert_eq!(tsql("SELECT [a;b] FROM t"), ["SELECT [a;b] FROM t"]); assert_eq!( tsql("SELECT [it's] FROM t; DELETE FROM u WHERE id = 1"), ["SELECT [it's] FROM t", "DELETE FROM u WHERE id = 1"] ); assert_eq!( tsql("SELECT [x]]y;z], [ünï;code] FROM t; SELECT 2"), ["SELECT [x]]y;z], [ünï;code] FROM t", "SELECT 2"] ); } #[test] fn a_go_line_separates_t_sql_batches_and_is_never_sent() { let cases: &[(&str, &[&str])] = &[ ("SELECT 1\nGO", &["SELECT 1"]), ("SELECT 1;\nGO 5\nSELECT 2;", &["SELECT 1", "SELECT 2"]), ( "SELECT 1\n go -- done\nSELECT 2", &["SELECT 1", "SELECT 2"], ), // Not alone on its line, or inside a string or a comment: not a `GO`. ("SELECT 1 GO", &["SELECT 1 GO"]), ( "SELECT 'a\nGO\nb'; SELECT 2", &["SELECT 'a\nGO\nb'", "SELECT 2"], ), ("SELECT 1 /*\nGO\n*/", &["SELECT 1"]), // `/*/` opens a comment and does not close it. ("SELECT 1 /*/\nGO\n*/ AS x", &["SELECT 1 /*/\nGO\n*/ AS x"]), ( "SELECT 1 /*/ BEGIN */; DELETE FROM t WHERE id = 1; SELECT 2;", &["SELECT 1", "DELETE FROM t WHERE id = 1", "SELECT 2"], ), ("SELECT 1\nGOTO x", &["SELECT 1\nGOTO x"]), ]; for (sql, expected) in cases { assert_eq!(tsql(sql), *expected, "{sql:?}"); } } #[test] fn a_selection_is_sent_as_its_one_batch() { assert_eq!( one_batch(Engine::SqlServer, "SELECT 1\nGO\n"), Ok("SELECT 1") ); assert_eq!(one_batch(Engine::SqlServer, "GO\n"), Ok("")); assert_eq!( one_batch(Engine::SqlServer, "SELECT 1\nGO\n-- done\n"), Ok("SELECT 1") ); assert!(one_batch(Engine::SqlServer, "SELECT 1\nGO\nSELECT 2").is_err()); assert_eq!( one_batch(Engine::SqlServer, "INSERT INTO t DEFAULT VALUES\nGO 5"), Err("GO 5 repeats its batch, and dbdelve runs a batch once.".into()) ); assert_eq!( one_batch(Engine::SqlServer, "SELECT 1\nGO 1"), Ok("SELECT 1") ); assert_eq!( one_batch(Engine::Postgres, "SELECT 1\nGO"), Ok("SELECT 1\nGO") ); let sql = "INSERT INTO t DEFAULT VALUES;\nSELECT 1\nGO 3\nSELECT 2\nGO"; assert!(batch_repeats(Engine::SqlServer, sql, 0).is_err()); assert!(batch_repeats(Engine::SqlServer, sql, sql.find("SELECT 2").unwrap()).is_ok()); assert!(batch_repeats(Engine::Postgres, sql, 0).is_ok()); } #[test] fn only_sql_server_reads_t_sql_boundaries() { for sql in [ "SELECT ARRAY['a;]'] FROM t; SELECT arr[1] FROM t", "SELECT [it's] FROM t; DELETE FROM u WHERE id = 1", "SELECT `a;b` FROM t; SELECT 2", "CREATE FUNCTION f() RETURNS int AS $$ BEGIN RETURN 1; END; $$ LANGUAGE plpgsql; SELECT 1", "BEGIN SELECT 1; SELECT 2; END", "SELECT 1\nGO\nSELECT 2", ] { for engine in Engine::ALL .into_iter() .filter(|e| !matches!(e, Engine::SqlServer | Engine::MongoDb | Engine::Redis)) { assert_eq!( Buffer::for_engine(engine, sql).statements(), Buffer::parse(sql).statements(), "{engine:?}: {sql}" ); } } } #[test] fn a_mongodb_buffer_runs_by_mongosh_statements_and_read_only_fails_closed() { let buffer = "db.accounts.find({ plan: 'free' })\n .sort({ name: 1 })\ndb.accounts.deleteMany({})"; let statements = queued_statements(Engine::MongoDb, buffer, None); assert_eq!( statements .iter() .map(|range| &buffer[range.clone()]) .collect::>(), [ "db.accounts.find({ plan: 'free' })\n .sort({ name: 1 })", "db.accounts.deleteMany({})" ] ); let stopped = |statement: &str| gate(&classify(Engine::MongoDb, statement), Mode::ReadOnly, &[]); assert_eq!(stopped("db.accounts.find({ plan: 'free' })"), None); assert_eq!( stopped("db.accounts.insertOne({})"), Some(Stop::Upgrade(Mode::ReadWrite)) ); // Nothing on the server holds a Mongo session to reads, so what the // classifier cannot read is never run once in Read-only. for unreadable in [ "db.accounts.find(", "db.runCommand({ eval: 'x' })", "SELECT 1", ] { assert_eq!( stopped(unreadable), Some(Stop::Upgrade(Mode::ReadWrite)), "{unreadable}" ); } } #[test] fn dollar_quoted_body_does_not_split() { // Two semicolons live inside the function body. A `;` split would // produce four fragments, none of them runnable. let sql = "CREATE FUNCTION f() RETURNS int AS $$\n\ BEGIN\n\ RETURN 1;\n\ END;\n\ $$ LANGUAGE plpgsql;\n\ SELECT 1;"; let found = texts(sql); assert_eq!(found.len(), 2, "body was split: {found:#?}"); assert!(found[0].contains("RETURN 1;")); assert!(found[0].contains("END;")); assert_eq!(found[1], "SELECT 1"); } #[test] fn cursor_inside_a_statement_selects_it() { let sql = "SELECT 1;\nSELECT 2;"; let buffer = Buffer::parse(sql); let inside_second = sql.find("SELECT 2").unwrap() + 3; assert_eq!( &sql[buffer.statement_at(inside_second).unwrap()], "SELECT 2" ); } #[test] fn cursor_just_after_a_semicolon_selects_that_statement() { let sql = "SELECT 1;\nSELECT 2;"; let buffer = Buffer::parse(sql); let after_first = sql.find(';').unwrap() + 1; assert_eq!(&sql[buffer.statement_at(after_first).unwrap()], "SELECT 1"); } #[test] fn cursor_in_the_gap_selects_the_preceding_statement() { let sql = "SELECT 1;\n\n\nSELECT 2;"; let buffer = Buffer::parse(sql); let gap = sql.find("\n\n").unwrap() + 2; assert_eq!(&sql[buffer.statement_at(gap).unwrap()], "SELECT 1"); } #[test] fn empty_and_whitespace_buffers_yield_nothing() { assert!(Buffer::parse("").statements().is_empty()); assert!(Buffer::parse(" \n\t ").statements().is_empty()); assert!(Buffer::parse("").statement_at(0).is_none()); } #[test] fn incomplete_input_still_reports_something_runnable() { // Half-typed queries must not panic or wipe the statement list. The // dangling `FROM` is unparsable, so it stays with the statement it was // typed into and the server explains the problem. let sql = "SELECT * FROM"; let buffer = Buffer::parse(sql); assert!(buffer.statement_at(3).is_some()); assert_eq!( &sql[buffer.statement_at(sql.len()).unwrap()], "SELECT * FROM" ); } #[test] fn an_unparsable_tail_stays_with_the_statement_it_was_typed_into() { // The head of a half-typed `DELETE ... WHERE` is an unqualified // DELETE. Sending it because the grammar could not read the tail is // the worst thing this module could do, so the tail comes along and // the server is what rejects it. for sql in [ "DELETE FROM t WHERE ", "UPDATE t SET a = 1 WHERE ", "DELETE FROM t WHERE a = 'x", "SELECT 1;\nDELETE FROM t WHERE ", "GRANT SELECT ON t TO r", "SELECT 1 LIMIT 1", ] { let buffer = Buffer::parse(sql); let run = &sql[buffer.statement_at(sql.len()).unwrap()]; assert!( sql.trim_end().ends_with(run), "{sql:?} was truncated to {run:?}" ); } } #[test] fn a_whole_buffer_selection_is_found_without_its_semicolon() { let sql = "select * from accounts;\n"; let found = Buffer::for_engine(Engine::Postgres, sql).find(Engine::Postgres, sql, 0, sql); assert_eq!( found.map(|range| &sql[range]), Some("select * from accounts") ); } #[test] fn a_statement_that_is_not_a_query_takes_no_sort() { // A header click asks dbdelve to write an ORDER BY. Hard rule 1 says it // never writes a destructive statement, and the grammar gives `DELETE` // the same `from` child a `SELECT` has -- so the guard is the presence // of a `select`, not of a `from`. for sql in [ "DELETE FROM t WHERE a = 1", "DELETE FROM t WHERE a = 1 RETURNING *", "UPDATE t SET a = 1", "TRUNCATE t", "INSERT INTO t (a) VALUES (1) RETURNING *", ] { assert!( order_by(Engine::Postgres, sql).is_none(), "{sql} reported a sort" ); assert!( with_order_by(Engine::Postgres, sql, &[SortKey::new("a", true)]).is_none(), "{sql} was spliced" ); } } #[test] fn a_splice_changes_nothing_but_the_clause() { // Collapsing whitespace across the whole statement rewrites string // literals, quoted identifiers and indentation -- all of which change // what the statement means or how it reads. assert_eq!( with_order_by( Engine::Postgres, "SELECT * FROM t WHERE note LIKE 'a %' LIMIT 10", &[SortKey::new("id", true)] ) .unwrap(), "SELECT * FROM t WHERE note LIKE 'a %' ORDER BY id ASC LIMIT 10" ); assert_eq!( with_order_by( Engine::Postgres, r#"SELECT * FROM "public"."my table""#, &[SortKey::new("id", true)] ) .unwrap(), r#"SELECT * FROM "public"."my table" ORDER BY id ASC"# ); assert_eq!( with_order_by( Engine::Postgres, "SELECT *\nFROM t\nWHERE a = 1\n AND b = 2", &[SortKey::new("id", true)] ) .unwrap(), "SELECT *\nFROM t\nWHERE a = 1\n AND b = 2 ORDER BY id ASC" ); } #[test] fn a_generated_update_sets_every_column_it_was_given() { // One column and several. A missing separator between assignments is a // statement the server rejects; a missing one in the WHERE would be a // statement it accepts and applies to the wrong rows. assert_eq!( update_row( Engine::Postgres, "public", "measurements", &[("note", set("ok"))], &[("id", "7")], &[] ) .unwrap(), r#"UPDATE "public"."measurements" SET "note" = 'ok' WHERE "id" = '7'"# ); assert_eq!( update_row( Engine::Postgres, "public", "measurements", &[("note", set("ok")), ("depth", set("12"))], &[("id", "7")], &[] ) .unwrap(), r#"UPDATE "public"."measurements" SET "note" = 'ok', "depth" = '12' WHERE "id" = '7'"# ); } #[test] fn a_composite_key_matches_on_all_of_its_columns() { // Joined by OR, or with a column dropped, this updates rows the user // never edited. assert_eq!( update_row( Engine::Postgres, "app", "memberships", &[("role", set("owner"))], &[("org_id", "1"), ("user_id", "2")], &[] ) .unwrap(), r#"UPDATE "app"."memberships" SET "role" = 'owner' WHERE "org_id" = '1' AND "user_id" = '2'"# ); } #[test] fn user_data_is_quoted_rather_than_interpolated() { // An apostrophe in a value and a double quote in a column name are the // two ways a cell's contents become SQL of its own. assert_eq!( update_row( Engine::Postgres, "s", "t", &[("a", set("it's"))], &[("id", "o'hara")], &[] ) .unwrap(), r#"UPDATE "s"."t" SET "a" = 'it''s' WHERE "id" = 'o''hara'"# ); assert_eq!( update_row( Engine::Postgres, "s", r#"od"d"#, &[(r#"we"ird"#, set("x"))], &[("id", "1")], &[] ) .unwrap(), r#"UPDATE "s"."od""d" SET "we""ird" = 'x' WHERE "id" = '1'"# ); } #[test] fn a_null_goes_in_as_the_keyword_and_never_as_a_quoted_word() { // `'NULL'` is a four-letter string and `NULL` is the absence of a // value. The whole worth of the gesture is that the two differ. assert_eq!( update_row( Engine::Postgres, "public", "measurements", &[("note", NewValue::Null)], &[("id", "7")], &[] ) .unwrap(), r#"UPDATE "public"."measurements" SET "note" = NULL WHERE "id" = '7'"# ); // Mixed, on the engine whose identifier quote is its own: a NULL beside // a value must not disturb the separator between them. assert_eq!( update_row( Engine::MySql, "dbdelve_dev", "measurements", &[("note", NewValue::Null), ("depth", set("12"))], &[("id", "7")], &[] ) .unwrap(), "UPDATE `dbdelve_dev`.`measurements` SET `note` = NULL, `depth` = '12' WHERE `id` = '7'" ); // And the word itself, typed into a cell, is still a string. assert_eq!( update_row( Engine::Sqlite, "main", "measurements", &[("note", set("NULL"))], &[("id", "7")], &[] ) .unwrap(), r#"UPDATE "main"."measurements" SET "note" = 'NULL' WHERE "id" = '7'"# ); // The gate is untouched by this: `SET x = NULL` is an `update` node // like any other, and a test here is what proves it rather than hopes. let statement = update_row( Engine::Postgres, "s", "t", &[("a", NewValue::Null)], &[("id", "1")], &[], ) .unwrap(); assert!(is_generated_write(&statement), "{statement} was refused"); } #[test] fn a_default_goes_in_as_the_keyword_and_the_typed_word_stays_a_string() { // The same distinction NULL is under, and the one that makes the menu // entry worth having: quoted, `DEFAULT` is seven characters of data. assert_eq!( update_row( Engine::Postgres, "public", "measurements", &[("note", NewValue::Default)], &[("id", "7")], &[] ) .unwrap(), r#"UPDATE "public"."measurements" SET "note" = DEFAULT WHERE "id" = '7'"# ); assert_eq!( update_row( Engine::Postgres, "public", "measurements", &[("note", set("DEFAULT"))], &[("id", "7")], &[] ) .unwrap(), r#"UPDATE "public"."measurements" SET "note" = 'DEFAULT' WHERE "id" = '7'"# ); // And the gate takes it, as it takes `SET x = NULL`. let statement = update_row( Engine::Postgres, "s", "t", &[("a", NewValue::Default)], &[("id", "1")], &[], ) .unwrap(); assert!(is_generated_write(&statement), "{statement} was refused"); } #[test] fn an_update_with_nothing_to_match_on_is_refused() { // No WHERE rewrites every row in the table. It must not be possible to // produce that statement, so a caller with no key gets nothing. assert!(update_row(Engine::Postgres, "s", "t", &[("a", set("1"))], &[], &[]).is_none()); assert!(update_row(Engine::Postgres, "s", "t", &[], &[("id", "1")], &[]).is_none()); } #[test] fn a_generated_insert_names_only_the_columns_it_was_given() { // The omission is the design: a column absent from this list is absent // from the statement, so the server's default applies to it. assert_eq!( insert_row( Engine::Postgres, "public", "measurements", &[("note", Some("ok")), ("depth", None)], &[] ) .unwrap(), r#"INSERT INTO "public"."measurements" ("note", "depth") VALUES ('ok', NULL)"# ); assert_eq!( insert_row(Engine::Sqlite, "main", "t", &[("a", Some("o'hara"))], &[]).unwrap(), r#"INSERT INTO "main"."t" ("a") VALUES ('o''hara')"# ); // The engine whose identifier quote and literal escape are both its // own: a backtick doubles, and a backslash doubles before the // apostrophe after it does. assert_eq!( insert_row( Engine::MySql, "dbdelve_dev", "me`as", &[("no`te", Some(r"a\'b"))], &[] ) .unwrap(), r"INSERT INTO `dbdelve_dev`.`me``as` (`no``te`) VALUES ('a\\''b')" ); // An empty form is not `INSERT INTO t DEFAULT VALUES`, which is a // statement dbdelve has never been asked for. assert!(insert_row(Engine::Postgres, "s", "t", &[], &[]).is_err()); } #[test] fn an_insert_template_numbers_or_marks_its_placeholders_the_engines_way() { let columns = [column("id", None), column("email", None)]; assert_eq!( insert_template(Engine::Postgres, "public", "users", &columns).unwrap(), r#"INSERT INTO "public"."users" ("id", "email") VALUES ($1, $2);"# ); assert_eq!( insert_template(Engine::MySql, "app", "users", &columns).unwrap(), "INSERT INTO `app`.`users` (`id`, `email`) VALUES (?, ?);" ); assert_eq!( insert_template(Engine::SqlServer, "dbo", "users", &columns).unwrap(), r#"INSERT INTO "dbo"."users" ("id", "email") VALUES (@p1, @p2);"# ); assert_eq!( insert_template(Engine::MongoDb, "db", "users", &columns), None ); } fn column(name: &str, default: Option<&str>) -> ColumnDefinition { ColumnDefinition { name: name.into(), data_type: "integer".into(), nullable: true, default: default.map(Into::into), } } #[test] fn an_insert_template_leaves_out_what_the_server_generates() { let columns = [ column("id", Some("GENERATED ALWAYS AS IDENTITY")), column("total", Some("GENERATED ALWAYS AS ((price * qty)) STORED")), column("seq", Some("GENERATED BY DEFAULT AS IDENTITY")), column("created_at", Some("now()")), ]; assert_eq!( insert_template(Engine::Postgres, "public", "orders", &columns).unwrap(), r#"INSERT INTO "public"."orders" ("seq", "created_at") VALUES ($1, $2);"# ); let columns = [ column("id", Some("IDENTITY(1,1)")), column("total", Some("AS ([price]*[qty]) PERSISTED")), column("created_at", Some("(getdate())")), ]; assert_eq!( insert_template(Engine::SqlServer, "dbo", "orders", &columns).unwrap(), r#"INSERT INTO "dbo"."orders" ("created_at") VALUES (@p1);"# ); assert_eq!( insert_template(Engine::SqlServer, "dbo", "orders", &columns[..2]), None ); } #[test] fn a_plugin_is_not_admitted_the_draft_shapes_its_grid_never_writes() { let draft = "INSERT INTO \"s\".\"t\" (\"a\") VALUES ('1'); \ INSERT INTO \"s\".\"t\" (\"a\") VALUES ('2')"; assert!(generated_writes(Engine::Postgres, draft).is_some()); assert_eq!(plugin_generated_writes(Engine::Postgres, draft), None); let update = "UPDATE \"s\".\"t\" SET \"a\" = '1' WHERE \"id\" = '2'"; let batch = format!("BEGIN;\n{update};\nCOMMIT;"); assert!(plugin_generated_writes(Engine::Postgres, &batch).is_some()); let null = "DELETE FROM \"s\".\"t\" WHERE \"id\" = '2' AND \"b\" IS NULL"; assert!(generated_writes(Engine::Postgres, null).is_some()); assert_eq!(plugin_generated_writes(Engine::Postgres, null), None); } #[test] fn a_gated_batch_splits_into_its_writes_without_the_bracket() { let update = "UPDATE \"s\".\"t\" SET \"a\" = '1' WHERE \"id\" = '2'"; assert_eq!( generated_writes( Engine::Generic, &format!("BEGIN;\n{update};\n{update};\nCOMMIT;") ), Some(vec![update.to_owned(), update.to_owned()]) ); assert_eq!( generated_writes(Engine::Postgres, &format!("{update};")), Some(vec![update.to_owned()]) ); for sql in [ "BEGIN".to_owned(), "COMMIT;".to_owned(), "SELECT * FROM \"s\".\"t\"".to_owned(), format!("{update};\nSELECT 1;"), format!("BEGIN;\n{update};\nROLLBACK;"), format!("{update};\nCOMMIT;"), ] { assert_eq!(generated_writes(Engine::Generic, &sql), None, "{sql}"); } } #[test] fn the_gate_admits_an_insert_and_still_admits_an_update() { assert!(is_generated_write( r#"INSERT INTO "public"."t" ("a") VALUES ('1')"# )); assert!(is_generated_write("UPDATE t SET a = '1' WHERE id = '2'")); assert!(is_generated_write( "BEGIN;\nUPDATE t SET a = '1' WHERE id = '2';\n\ UPDATE t SET a = '3' WHERE id = '4';\nCOMMIT;" )); // And what the generator writes, which is the test that keeps the two // from drifting apart. let statement = insert_row( Engine::Postgres, "public", "measurements", &[("note", Some("it's fine")), ("depth", None)], &[], ) .unwrap(); assert!(is_generated_write(&statement), "{statement} was refused"); } #[test] fn the_gate_refuses_an_insert_carrying_something_else() { // One insert, alone, or one row each in a reviewed draft. A `DELETE` // riding along in a CTE is the shape an injected value takes. for sql in [ "INSERT INTO t (a) VALUES ('1'); DROP TABLE t", "INSERT INTO t (a) VALUES ('1'); TRUNCATE t", "WITH x AS (DELETE FROM t RETURNING *) INSERT INTO u (a) VALUES ('1')", "INSERT INTO t (a) VALUES ('1'), ('2'); INSERT INTO t (a) VALUES ('3')", "INSERT INTO t (a) VALUES ('1') ON CONFLICT DO NOTHING; INSERT INTO t (a) VALUES ('2')", ] { assert!(!is_generated_write(sql), "{sql} passed the gate"); } let draft = "INSERT INTO t (a) VALUES ('1'); INSERT INTO t (a) VALUES ('2')"; assert!(is_generated_write(draft), "{draft} was refused"); } #[test] fn the_gate_admits_a_multi_row_insert_of_literals() { for sql in [ "INSERT INTO \"public\".\"t\" (\"a\", \"b\") VALUES ('1', NULL),\n('2', 'x')", "INSERT INTO \"dbo\".\"t\" (\"a\", \"b\") VALUES (N'é', 0xAB),\n('2024-01-02T03:04:05.000', NULL)", "INSERT INTO `d`.`t` (`a`) VALUES ('1') ON DUPLICATE KEY UPDATE `a` = `a`", "INSERT INTO \"main\".\"t\" (\"a\") VALUES ('1') ON CONFLICT DO NOTHING", ] { assert!(is_generated_write(sql), "{sql} was refused"); } } #[test] fn the_gate_refuses_an_insert_whose_values_are_not_literals() { for sql in [ "INSERT INTO t (a) VALUES ((SELECT 1))", "INSERT INTO t (a) VALUES (now())", "INSERT INTO t (a) SELECT '1'", "INSERT INTO t (a) VALUES ('1' || '2')", "INSERT INTO t (a) VALUES (b)", "INSERT INTO t (a) VALUES (\"b\")", "INSERT INTO t (a) VALUES (1)", "INSERT INTO t VALUES ('1')", "INSERT INTO t (a) VALUES ('1') RETURNING *", "INSERT INTO t (a) DEFAULT VALUES", "REPLACE INTO t (a) VALUES ('1')", "INSERT OR REPLACE INTO t (a) VALUES ('1')", "INSERT IGNORE INTO t (a) VALUES ('1')", ] { assert!(!is_generated_write(sql), "{sql} passed the gate"); } } #[test] fn the_gate_refuses_a_conflict_clause_other_than_the_fixed_form() { for tail in [ "ON CONFLICT (a) DO NOTHING", "ON CONFLICT DO UPDATE SET a = '1'", "ON DUPLICATE KEY UPDATE a = b", "ON DUPLICATE KEY UPDATE a = '1'", "ON DUPLICATE KEY UPDATE a = a, b = b", "ON DUPLICATE KEY UPDATE a = VALUES(a)", ] { let sql = format!("INSERT INTO t (a) VALUES ('1') {tail}"); assert!(!is_generated_write(&sql), "{sql} passed the gate"); } } const SQL_ENGINES: [Engine; 8] = [ Engine::Postgres, Engine::MySql, Engine::MariaDb, Engine::Sqlite, Engine::Turso, Engine::DuckDb, Engine::Snowflake, Engine::SqlServer, ]; #[test] fn the_gate_refuses_a_comment_anywhere_in_an_insert() { // MySQL runs a `/*! … */` comment as SQL, so a comment is never inert. for sql in [ "INSERT INTO d/**/.t (a) VALUES ('1')", "INSERT INTO d/*!.u*/.t (a) VALUES ('1')", "INSERT INTO `d`/*! .u */.`t` (`a`) VALUES ('1')", "INSERT INTO d -- x\n.t (a) VALUES ('1')", "INSERT INTO d.t/**/ (a) VALUES ('1')", "INSERT /**/ INTO t (a) VALUES ('1')", "INSERT INTO t (\"a\"/**/) VALUES ('1')", "INSERT INTO t (/**/\"a\") VALUES ('1')", "INSERT INTO t (`a`/*!, b*/) VALUES ('1')", "INSERT INTO t (a) VALUES /**/ ('1')", "INSERT INTO t (a) VALUES ('1'/**/)", "INSERT INTO t (a) VALUES (/*!0x41*/'1')", "INSERT INTO t (a) VALUES ('1') ON DUPLICATE KEY UPDATE `a`/**/ = `a`", "INSERT INTO t (a) VALUES ('1') ON DUPLICATE KEY UPDATE `a` = /*!b*/`a`", "INSERT INTO t (a) VALUES ('1') ON DUPLICATE KEY UPDATE a = a/*!, b = '1'*/", "INSERT INTO t (a) VALUES ('1') ON CONFLICT DO NOTHING/**/", "INSERT INTO t (a) VALUES ('1')/**/", "INSERT INTO t (a) VALUES ('1') -- x", ] { for engine in SQL_ENGINES { assert!( !is_generated_write_on(engine, sql), "{engine:?}: {sql} passed the gate" ); } } } #[test] fn a_duplicate_key_skip_names_its_column_as_mysql_reads_a_name() { // `"a"` is a string under MySQL's default sql_mode, so `a = "a"` // assigns one. for sql in [ "INSERT INTO t (a) VALUES ('1') ON DUPLICATE KEY UPDATE \"a\" = \"a\"", "INSERT INTO t (a) VALUES ('1') ON DUPLICATE KEY UPDATE a = \"a\"", "INSERT INTO t (a) VALUES ('1') ON DUPLICATE KEY UPDATE `a` = \"a\"", ] { for engine in SQL_ENGINES { assert!( !is_generated_write_on(engine, sql), "{engine:?}: {sql} passed the gate" ); } } for sql in [ "INSERT INTO t (a) VALUES ('1') ON DUPLICATE KEY UPDATE `a` = `a`", "INSERT INTO t (a) VALUES ('1') ON DUPLICATE KEY UPDATE a = a", ] { for engine in [Engine::MySql, Engine::MariaDb] { assert!(is_generated_write_on(engine, sql), "{engine:?}: {sql}"); } } } #[test] fn the_gate_refuses_a_value_that_is_more_than_one_literal() { for sql in [ "INSERT INTO t (a) VALUES ('1' '2')", "INSERT INTO t (a) VALUES ('1'\n'2')", "INSERT INTO t (a) VALUES (N'1' '2')", "INSERT INTO t (a) VALUES ('1' N'2')", "INSERT INTO t (a) VALUES ('1''2' '3')", "INSERT INTO t (a) VALUES (0x)", "INSERT INTO t (a) VALUES (0xAB 'c')", "INSERT INTO t (a) VALUES (NULL '1')", "DELETE FROM t WHERE id = '1' '2'", ] { for engine in SQL_ENGINES { assert!( !is_generated_write_on(engine, sql), "{engine:?}: {sql} passed the gate" ); } } } #[test] fn every_literal_an_import_writes_passes_the_write_gate() { use crate::import_rows::Value; let values = [ Value::Null, Value::Bool(true), Value::Bool(false), Value::Number("-1.5e3".into()), Value::Text(String::new()), Value::Text("it's".into()), Value::Text("''".into()), Value::Text("a\\b\\".into()), Value::Text("\\'".into()), Value::Text("é /* -- */ ;".into()), Value::Text("0xAB".into()), Value::Json(serde_json::from_str(r#"{"a": "b'c"}"#).unwrap()), ]; let types = [ "text", "varchar(10)", "nvarchar(10)", "integer", "varbinary(10)", "datetime", "datetime2", "bit", ]; for engine in SQL_ENGINES { for data_type in types { let rows: Vec>> = values.iter().map(|value| vec![Some(value)]).collect(); for skip in [false, engine.skips_duplicates()] { let statement = insert_rows(engine, "s", "t", &[("a", data_type)], &rows, skip).unwrap(); assert!( is_generated_write_on(engine, &statement), "{engine:?} {data_type}: {statement}" ); } } } } #[test] fn the_gate_admits_a_lone_transaction_bracket() { for sql in [ "BEGIN", "BEGIN;", "BEGIN TRANSACTION", "COMMIT", "COMMIT;", "ROLLBACK", " ROLLBACK; ", ] { assert!(is_generated_write(sql), "{sql:?} was refused"); } } #[test] fn the_gate_refuses_a_bracket_beside_anything_else() { for sql in [ "BEGIN; INSERT INTO t (a) VALUES ('1')", "INSERT INTO t (a) VALUES ('1'); COMMIT", "COMMIT; DROP TABLE t", "ROLLBACK; COMMIT", "BEGIN; COMMIT", "begin", "START TRANSACTION", "ROLLBACK TO SAVEPOINT s", "COMMIT AND CHAIN", "BEGIN WORK", "COMMIT;;", ] { assert!(!is_generated_write(sql), "{sql:?} passed the gate"); } } #[test] fn the_gate_refuses_a_quote_a_backslash_escapes_where_the_engine_reads_one() { // The grammar ends each of these strings at the second `'`; MySQL and // Snowflake read `\'` as a quote inside it, and the rest as SQL. let probes = [ r"INSERT INTO t (a, b) VALUES ('a\', ', (SELECT password FROM users LIMIT 1)) # ')", r"INSERT INTO t (a, b) VALUES ('a\', ', sleep(5)) -- ')", r"DELETE FROM t WHERE id = 'a\' AND b = ' OR 1=1 # '", r"UPDATE t SET a = 'x\', b = ' WHERE 1=1 -- ' WHERE id = '1'", r"UPDATE t SET a = 'x\', b = ' WHERE 1=1; DROP TABLE t; -- ' WHERE id = '1'", r"UPDATE t SET a = '1' WHERE id = 'a\' OR b = ' OR 1=1 -- '", r#"UPDATE t SET a = "x\", b = " WHERE 1=1 -- " WHERE id = '1'"#, ]; for sql in probes { assert!(!is_generated_write(sql), "{sql} passed the gate"); } for engine in [Engine::MySql, Engine::MariaDb, Engine::Snowflake] { for sql in probes { assert!( !is_generated_write_on(engine, sql), "{sql} passed the gate on {engine:?}" ); } assert!(!delete_matches_key_on(engine, probes[2], &["id", "b"])); // What `quote_literal` writes there still reads as one literal. for value in [r"a\", "it's", r"it\'s", r"\\", r"\", r#"a\"b"#] { let literal = engine.quote_literal(value); for sql in [ format!("INSERT INTO t (a) VALUES ({literal})"), format!("DELETE FROM t WHERE id = {literal}"), format!("UPDATE t SET a = {literal} WHERE id = {literal}"), ] { assert!( is_generated_write_on(engine, &sql), "{sql} was refused on {engine:?}" ); } } } // A backslash is an ordinary character where the engine says so. for engine in [Engine::Postgres, Engine::Sqlite, Engine::SqlServer] { for sql in [ r"INSERT INTO t (a) VALUES ('C:\')", r"DELETE FROM t WHERE id = 'C:\'", r"UPDATE t SET a = 'C:\' WHERE id = 'C:\'", ] { assert!( is_generated_write_on(engine, sql), "{sql} was refused on {engine:?}" ); } assert!(delete_matches_key_on( engine, r"DELETE FROM t WHERE id = 'C:\'", &["id"] )); } } #[test] fn the_gate_still_refuses_a_delete_matching_null() { // `= NULL` matches no row, and NULL is a value only an insert writes. assert!(!is_generated_write("DELETE FROM t WHERE id = NULL")); assert!(!is_generated_write( "UPDATE t SET a = '1' WHERE id = '2'; DELETE FROM t WHERE id = NULL" )); } #[test] fn the_gate_accepts_an_update_and_a_batch_of_updates() { assert!(is_generated_write("UPDATE t SET a = '1' WHERE id = '2'")); assert!(is_generated_write( "UPDATE t SET a = '1' WHERE id = '2'; UPDATE t SET a = '3' WHERE id = '4'" )); } #[test] fn the_gate_accepts_a_batch_bracketed_by_a_transaction() { // What dbdelve writes for an engine that commits each statement on its // own. The brackets are part of the generated statement, so the gate // has to know the shape or it would refuse dbdelve's own output. assert!(is_generated_write( "BEGIN;\nUPDATE t SET a = '1' WHERE id = '2';\n\ UPDATE t SET a = '3' WHERE id = '4';\nCOMMIT;" )); } #[test] fn the_gate_refuses_a_transaction_it_does_not_see_closed() { // A BEGIN whose COMMIT went missing leaves the session holding an open // transaction the user never wrote, which is worse than not applying // the edit at all. for sql in [ "BEGIN;\nUPDATE t SET a = '1' WHERE id = '2';", "BEGIN;\nUPDATE t SET a = '1' WHERE id = '2';\nROLLBACK;", ] { assert!(!is_generated_write(sql), "{sql:?} passed the gate"); } } #[test] fn the_gate_refuses_a_destructive_statement_inside_the_brackets() { // Seeing through the transaction must not mean trusting what is in it. assert!(!is_generated_write( "BEGIN;\nUPDATE t SET a = '1' WHERE id = '2';\nDELETE FROM t;\nCOMMIT;" )); } #[test] fn the_gate_refuses_everything_that_is_not_a_write_dbdelve_writes() { // Hard rule 1 in code: DROP and TRUNCATE never leave dbdelve, whatever // the user asked for. SELECT is here because the gate is a whitelist -- // being harmless is not the test, being one of the shapes dbdelve // generates is. A keyed DELETE is no longer in this list because it is // one of those shapes; `delete_matches_key` is what asks whether the key // it names is the row's. for sql in [ "DROP TABLE t", "DROP VIEW v", "DROP DATABASE d", "TRUNCATE t", "TRUNCATE TABLE t", "SELECT 1", ] { assert!(!is_generated_write(sql), "{sql} passed the gate"); } } #[test] fn the_gate_refuses_a_batch_with_one_destructive_statement_in_it() { // Every statement is checked, not the first one. A DELETE appended to a // run of legitimate updates is the shape an injected value would take. assert!(!is_generated_write( "UPDATE t SET a = '1' WHERE id = '2'; DELETE FROM t; UPDATE t SET a = '3' WHERE id = '4'" )); } #[test] fn the_gate_refuses_a_destructive_statement_wrapped_in_a_cte() { // The root statement's first child here really is an `update` node, so // the whitelist passes it and only the subtree scan catches it. assert!(!is_generated_write( "WITH x AS (DELETE FROM t RETURNING *) UPDATE u SET a = '1' WHERE id = '2'" )); } #[test] fn the_gate_refuses_what_the_grammar_cannot_read_whole() { // An unreadable tree says nothing about what the statement does, and a // gate that cannot see has to refuse. The empty buffer is here because // it parses cleanly into no statements at all. for sql in [ "not sql at all !!", "UPDATE t SET a = ", "-- UPDATE t SET a = '1'", "", ] { assert!(!is_generated_write(sql), "{sql:?} passed the gate"); } } #[test] fn the_gate_accepts_what_update_row_writes() { // The one test that keeps the generator and the gate from drifting // apart: whatever quoting or clause order changes here, the statement // dbdelve builds is still one the gate can read as an UPDATE. let statement = update_row( Engine::Postgres, "public", "measurements", &[("note", set("it's fine")), ("depth", set("12"))], &[("id", "7"), ("run", "a'b")], &[], ) .unwrap(); assert!(is_generated_write(&statement), "{statement} was refused"); assert!(is_generated_write(&format!("{statement}; {statement}"))); } #[test] fn a_cte_still_takes_a_sort() { // `WITH` puts the outer SELECT and its FROM at the top level, beside // the cte. The select-child guard must not read the cte's own. assert_eq!( with_order_by( Engine::Postgres, "WITH x AS (SELECT 1 AS a) SELECT * FROM x", &[SortKey::new("a", true)] ) .unwrap(), "WITH x AS (SELECT 1 AS a) SELECT * FROM x ORDER BY a ASC" ); } #[test] fn the_select_gate_accepts_the_shape_a_preview_has() { for sql in [ r#"SELECT * FROM "public"."accounts" LIMIT 1000"#, r#"SELECT * FROM "public"."accounts" WHERE "state" = 'ok' LIMIT 1000"#, r#"SELECT * FROM "public"."accounts" WHERE "state" = 'ok' ORDER BY "id" ASC LIMIT 100 OFFSET 200"#, r#"WITH x AS (SELECT 1 AS a) SELECT * FROM x LIMIT 10"#, ] { assert!( is_generated_select(Engine::Postgres, sql), "{sql} was refused" ); } let sql = "SELECT * FROM `dbdelve_dev`.`accounts` WHERE `state` = 'ok' LIMIT 100"; assert!(is_generated_select(Engine::MySql, sql), "{sql} was refused"); } #[test] fn the_select_gate_refuses_a_filter_carrying_a_second_statement() { // The reason this gate exists. Whether each is refused for having two // roots or for not parsing is not the point -- refused is the point. for sql in [ r#"SELECT * FROM "public"."t" WHERE "id" = '1'; DROP TABLE "t" LIMIT 1000"#, r#"SELECT * FROM "public"."t" WHERE "id" = '1' LIMIT 1000; DROP TABLE "t""#, r#"SELECT * FROM "public"."t" WHERE "id" = '1'; DELETE FROM "t" LIMIT 1000"#, r#"SELECT * FROM "public"."t" WHERE "id" = '1'; TRUNCATE "t" LIMIT 1000"#, ] { assert!( !is_generated_select(Engine::Postgres, sql), "{sql} passed the gate" ); } } #[test] fn the_gates_refuse_a_backticked_name_the_server_ends_elsewhere() { // One name to the grammar; to Postgres a backtick is an operator // character, and what follows the `;` a second statement. let smuggled = r#"SELECT * FROM "t" WHERE `x; DELETE FROM t; --` LIMIT 10"#; assert!(!is_generated_select(Engine::Postgres, smuggled)); assert!(!is_generated_select(Engine::Sqlite, smuggled)); // One name to MySQL, `x` aliased `y` to the grammar. assert!(!is_generated_select( Engine::MySql, "SELECT * FROM `x``y` LIMIT 10" )); assert!(!is_generated_write_on( Engine::MySql, "UPDATE `a`.`x``y` SET `c` = '1' WHERE `id` = '2'" )); // ClickHouse escapes the second backtick, so its name ends at the // third and the `BACKUP` runs. assert!(!is_generated_select( Engine::ClickHouse, r"SELECT `a\`` PARALLEL WITH BACKUP TABLE t TO Disk('b', 'x') -- `" )); } #[test] fn the_select_gate_refuses_a_filter_that_does_not_parse() { for sql in [ r#"SELECT * FROM "public"."t" WHERE "id" = ((( LIMIT 1000"#, r#"SELECT * FROM "public"."t" WHERE "id" = 'unclosed LIMIT 1000"#, r#"SELECT * FROM "public"."t" WHERE LIMIT 1000"#, "", ] { assert!( !is_generated_select(Engine::Postgres, sql), "{sql:?} passed the gate" ); } } #[test] fn the_select_gate_refuses_a_destructive_statement_hidden_in_a_cte() { // The root's first named child here is a `select`, so the whitelist // alone passes it and only the recursive scan catches it. THIS TEST IS // LOAD-BEARING: a later task splits `destructive` apart for the DELETE // path, and this is what fails if the SELECT gate is not updated too. for sql in [ r#"WITH x AS (DELETE FROM "t" RETURNING *) SELECT * FROM x LIMIT 1000"#, r#"WITH x AS (SELECT 1 AS a) SELECT * FROM x WHERE a IN (SELECT 1); DROP TABLE "t""#, ] { assert!( !is_generated_select(Engine::Postgres, sql), "{sql} passed the gate" ); } } #[test] fn the_select_gate_admits_no_write_at_all() { // A whitelist, not a blocklist: being harmless is not the test, being // a SELECT is. for sql in [ "UPDATE t SET a = '1' WHERE id = '2'", "INSERT INTO t (a) VALUES ('1')", "DELETE FROM t WHERE a = '1'", "DROP TABLE t", "TRUNCATE t", "BEGIN; SELECT 1; COMMIT", "SELECT 1; SELECT 2", "-- SELECT * FROM t", ] { assert!( !is_generated_select(Engine::Postgres, sql), "{sql} passed the gate" ); } } #[test] fn a_generated_delete_names_the_row_and_only_the_row() { assert_eq!( delete_row( Engine::Postgres, "public", "measurements", &[("id", "7")], &[] ) .unwrap(), r#"DELETE FROM "public"."measurements" WHERE "id" = '7'"# ); // Joined by OR, or with a column dropped, this deletes rows the user // never pointed at. assert_eq!( delete_row( Engine::Postgres, "app", "memberships", &[("org_id", "1"), ("user_id", "2")], &[] ) .unwrap(), r#"DELETE FROM "app"."memberships" WHERE "org_id" = '1' AND "user_id" = '2'"# ); assert_eq!( delete_row( Engine::MySql, "dbdelve_demo", "measurements", &[("id", "7")], &[] ) .unwrap(), "DELETE FROM `dbdelve_demo`.`measurements` WHERE `id` = '7'" ); assert_eq!( delete_row(Engine::Sqlite, "main", "t", &[("id", "o'hara")], &[]).unwrap(), r#"DELETE FROM "main"."t" WHERE "id" = 'o''hara'"# ); // No WHERE empties the table, so it must not be possible to produce. assert!(delete_row(Engine::Postgres, "s", "t", &[], &[]).is_none()); } #[test] fn the_gate_admits_the_delete_dbdelve_writes_and_reads_its_key_back() { for engine in [Engine::Postgres, Engine::MySql, Engine::Sqlite] { let statement = delete_row(engine, "s", "t", &[("id", "7")], &[]).unwrap(); assert!(is_generated_write(&statement), "{statement} was refused"); assert!(delete_matches_key(&statement, &["id"]), "{statement}"); let composite = delete_row(engine, "s", "t", &[("org_id", "1"), ("user_id", "2")], &[]).unwrap(); assert!(is_generated_write(&composite), "{composite} was refused"); assert!(delete_matches_key(&composite, &["org_id", "user_id"])); // Set equality: the key is a set of columns, not a sequence. assert!(delete_matches_key(&composite, &["user_id", "org_id"])); } // A value carrying the quote character still reads back. let statement = delete_row(Engine::Postgres, "s", "t", &[("id", "o'hara")], &[]).unwrap(); assert!(is_generated_write(&statement), "{statement} was refused"); assert!(delete_matches_key(&statement, &["id"])); // A column name carrying one does not: `"we""ird"` is two adjacent // strings to this grammar and the whole statement fails to parse, so // the gate refuses dbdelve's own output. That is the safe direction -- // the row stays -- and a gate that guessed past an unreadable tree is // the unsafe one. let odd = delete_row(Engine::Postgres, "s", "t", &[(r#"we"ird"#, "x")], &[]).unwrap(); assert!(!is_generated_write(&odd), "{odd} passed the gate"); } #[test] fn sql_server_writes_a_key_the_way_its_column_type_compares() { let types = [ ("hash".to_string(), "binary".to_string()), ("code".to_string(), "varchar".to_string()), ("name".to_string(), "nvarchar".to_string()), ]; let delete = delete_row( Engine::SqlServer, "dbo", "t", &[("hash", "0x00FF"), ("code", "a'b")], &types, ) .unwrap(); assert_eq!( delete, r#"DELETE FROM "dbo"."t" WHERE "hash" = 0x00FF AND "code" = 'a''b'"# ); assert!(is_generated_write(&delete), "{delete} was refused"); assert!(delete_matches_key(&delete, &["hash", "code"])); assert_eq!(classify(Engine::SqlServer, &delete), Verdict::WRITE); let update = update_row( Engine::SqlServer, "dbo", "t", &[("name", set("李")), ("code", set("x"))], &[("hash", "0x00FF")], &types, ) .unwrap(); assert_eq!( update, r#"UPDATE "dbo"."t" SET "name" = N'李', "code" = 'x' WHERE "hash" = 0x00FF"# ); assert!(is_generated_write(&update), "{update} was refused"); assert_eq!(classify(Engine::SqlServer, &update), Verdict::WRITE); assert_eq!( insert_row( Engine::SqlServer, "dbo", "t", &[("hash", Some("0xAB"))], &types ) .unwrap(), r#"INSERT INTO "dbo"."t" ("hash") VALUES (0xAB)"# ); // A value that is not exactly a hex literal stays quoted, and a bare // number that is not one is no key the gate reads. let odd = delete_row( Engine::SqlServer, "dbo", "t", &[("hash", "0x1 OR 1=1")], &types, ) .unwrap(); assert!(odd.ends_with(r#""hash" = N'0x1 OR 1=1'"#), "{odd}"); assert!(!is_generated_write(r#"DELETE FROM t WHERE "id" = 7"#)); assert!(!is_generated_write(r#"DELETE FROM t WHERE "id" = 0x"#)); } #[test] fn a_backticked_name_is_a_column_or_table_and_never_a_value_set() { for engine in [Engine::MySql, Engine::MariaDb] { let bytes = "UPDATE `client-test`.`alerts` SET `payload` = X'00FF' WHERE `id` = '7'"; assert!(is_generated_write_on(engine, bytes), "{engine:?}"); for value in [ "`payload`", "`client-test`.`alerts`.`id`", "`0x00`", "`X'00'`", ] { let sql = format!( "UPDATE `client-test`.`alerts` SET `payload` = {value} WHERE `id` = '7'" ); assert!(!is_generated_write_on(engine, &sql), "{engine:?} {sql}"); } } } #[test] fn a_comment_anywhere_in_an_update_refuses_it() { // MySQL and MariaDB run a `/*! … */` body; Oracle and others read // `/*+ … */` as hints. Nothing dbdelve generates carries a comment. for engine in [ Engine::MySql, Engine::MariaDb, Engine::Postgres, Engine::SqlServer, ] { let plain = r#"UPDATE "s"."t" SET "a" = '0' WHERE "id" = '7'"#; assert!(is_generated_write_on(engine, plain), "{engine:?}"); for sql in [ r#"UPDATE "s"."t" SET "a" = '0' /*! + SLEEP(1) */ WHERE "id" = '7'"#, r#"UPDATE "s"."t" SET "a" = /*+ x */ '0' WHERE "id" = '7'"#, "UPDATE \"s\".\"t\" SET \"a\" = '0' -- x\n WHERE \"id\" = '7'", "UPDATE \"s\".\"t\" SET \"a\" = '0' # x\n WHERE \"id\" = '7'", r#"UPDATE "s"."t" SET "a" = '0' WHERE "id" = '7' /*! OR 1=1 */"#, r#"UPDATE "s"."t" SET "a" = '0' WHERE /*+ x */ "id" = '7'"#, "UPDATE \"s\".\"t\" SET \"a\" = '0' WHERE \"id\" = '7' -- x", "UPDATE \"s\".\"t\" SET \"a\" = '0' WHERE \"id\" = '7' # x", "UPDATE \"s\".\"t\" SET \"a\" = '0' WHERE \"id\" = '7' # x\n OR 1=1", r#"BEGIN; UPDATE "s"."t" SET "a" = '0' WHERE "id" = /*! 7 OR */ '7'; COMMIT"#, ] { assert!(!is_generated_write_on(engine, sql), "{engine:?} {sql}"); } } } #[test] fn an_update_sets_only_values_dbdelve_writes_and_bytes_in_the_engines_own_literal() { let update = |value: &str| format!(r#"UPDATE "s"."t" SET "b" = {value} WHERE "id" = '7'"#); let bytes = [ (Engine::Postgres, r"E'\\x6869'", r"E'\\x'"), (Engine::MySql, "X'6869'", "X''"), (Engine::MariaDb, "X'6869'", "X''"), (Engine::Sqlite, "X'6869'", "X''"), (Engine::Turso, "X'6869'", "X''"), (Engine::SqlServer, "0x6869", "0x00"), ]; for (engine, hi, short) in bytes { for value in [hi, short, "'x'", "NULL", "DEFAULT"] { assert!( is_generated_write_on(engine, &update(value)), "{engine:?} {value}" ); } let set = format!(r#"UPDATE "s"."t" SET "a" = 'x', "b" = {hi} WHERE "id" = '7'"#); assert!(is_generated_write_on(engine, &set), "{engine:?} {set}"); // A value that computes, whatever it computes from. for value in [ "now()", "'a' || 'b'", "(SELECT 1)", "1 + 1", "1", "'a' 'b'", "$$x$$", r#""a""#, "default", &format!("{hi} || {hi}"), &format!("({hi})"), &format!("{hi}::bytea"), &format!("{hi} 'aa'"), &format!("upper({hi})"), &format!("(SELECT {hi})"), ] { assert!( !is_generated_write_on(engine, &update(value)), "{engine:?} {value}" ); } // A value set, never a deleted row's key nor an inserted value. if engine != Engine::SqlServer { for sql in [ format!(r#"DELETE FROM "s"."t" WHERE "id" = {hi}"#), format!(r#"INSERT INTO "s"."t" ("b") VALUES ({hi})"#), ] { assert!(!is_generated_write_on(engine, &sql), "{engine:?} {sql}"); } } } // Each engine's own spelling, and nothing that only looks like one. for (engine, value) in [ (Engine::Postgres, "X'6869'"), (Engine::Postgres, r"E'\x6869'"), (Engine::Postgres, r"e'\\x6869'"), (Engine::Postgres, r"E'\\x686'"), (Engine::Postgres, r"E'\\x68\\'"), (Engine::Postgres, r"E'\\x68' || '\\'"), (Engine::Postgres, r"E'\\x6869''; DROP TABLE t; --'"), (Engine::MySql, r"E'\\x6869'"), (Engine::MySql, "x'6869'"), (Engine::MySql, "X'686'"), (Engine::MySql, "X'68 69'"), (Engine::MySql, "X'6G'"), (Engine::Sqlite, "X'6869' 'aa'"), (Engine::SqlServer, "X'6869'"), (Engine::SqlServer, "0x"), (Engine::DuckDb, "X'6869'"), (Engine::DuckDb, r"E'\\x6869'"), (Engine::Snowflake, "X'6869'"), (Engine::Generic, r"E'\\x6869'"), ] { assert!( !is_generated_write_on(engine, &update(value)), "{engine:?} {value}" ); } } #[test] fn the_gate_refuses_every_delete_that_is_not_one_named_row() { for sql in [ "DELETE FROM t", r#"DELETE FROM "public"."t""#, r#"DELETE FROM t WHERE "id" = '1' OR "id" = '2'"#, r#"DELETE FROM t WHERE "id" = '1' AND ("a" = '2' OR "b" = '3')"#, r#"DELETE FROM t WHERE "id" > '1'"#, r#"DELETE FROM t WHERE "id" <> '1'"#, r#"DELETE FROM t WHERE "id" LIKE '1%'"#, r#"DELETE FROM t WHERE "id" IS NULL"#, "DELETE FROM t WHERE id IN (SELECT id FROM u)", "DELETE FROM t WHERE id = lower('a')", "WITH x AS (SELECT 1) DELETE FROM t WHERE id = '1'", "DELETE FROM t WHERE id = '1' LIMIT 1", "DELETE FROM t WHERE id = '1' RETURNING *", "DELETE FROM t WHERE id = '1'; DROP TABLE t", "DELETE FROM t WHERE id = '1'; DELETE FROM t WHERE id = '2' OR id = '3'", "UPDATE t SET a = '1' WHERE id = '2'; DELETE FROM t", r#"DELETE FROM t WHERE "id" = "other""#, "DELETE FROM t WHERE t.id = '1'", "WITH x AS (DROP TABLE u) DELETE FROM t WHERE id = '1'", "WITH x AS (DROP TABLE u) UPDATE t SET a = '1' WHERE id = '2'", ] { assert!(!is_generated_write(sql), "{sql:?} passed the gate"); } // Each of several is one named row, which is what a reviewed draft // holds: one `DELETE` per marked row, never one predicate over several. for sql in [ "DELETE FROM t WHERE id = '1'; DELETE FROM t WHERE id = '2'", "UPDATE t SET a = '1' WHERE id = '2'; DELETE FROM t WHERE id = '3'", ] { assert!(is_generated_write(sql), "{sql:?} was refused"); } } #[test] fn a_delete_keyed_on_the_wrong_columns_is_refused_by_the_key_check() { // These are the right SHAPE -- is_generated_write admits the first two, // and must, since it has no key to compare against. delete_matches_key // is what refuses them, and a caller runs both. let wrong_column = r#"DELETE FROM "s"."t" WHERE "note" = 'x'"#; assert!(is_generated_write(wrong_column)); assert!(!delete_matches_key(wrong_column, &["id"])); let half = r#"DELETE FROM "s"."t" WHERE "org_id" = '1'"#; assert!(is_generated_write(half)); assert!(!delete_matches_key(half, &["org_id", "user_id"])); // A column named twice would read as a one-column key. This one the // shape check itself refuses, and the readout agrees. let twice = r#"DELETE FROM "s"."t" WHERE "id" = '1' AND "id" = '2'"#; assert!(!is_generated_write(twice)); assert!(!delete_matches_key(twice, &["id"])); // And a statement that is not a delete at all answers no here too. assert!(!delete_matches_key( r#"UPDATE "s"."t" SET "a" = '1' WHERE "id" = '2'"#, &["id"] )); assert!(!delete_matches_key("DROP TABLE t", &["id"])); } #[test] fn only_an_engine_naming_rows_by_every_value_reads_the_row_terms() { // `IS NULL` names a NULL cell on ClickHouse and on the six engines whose // drafts are verified; `toString` and `ALTER TABLE … UPDATE` are // ClickHouse's alone. let null_term = "DELETE FROM t WHERE c IS NULL"; let clickhouse_only = [ "DELETE FROM t WHERE toString(c) = '1.5'", "ALTER TABLE t UPDATE a = '1' WHERE b = '2' SETTINGS mutations_sync = 2", ]; let six = [ Engine::Postgres, Engine::MySql, Engine::MariaDb, Engine::Sqlite, Engine::DuckDb, Engine::SqlServer, ]; for engine in Engine::ALL { assert_eq!( is_generated_write_on(engine, null_term), engine == Engine::ClickHouse || six.contains(&engine), "{engine:?} {null_term}" ); for sql in clickhouse_only { assert_eq!( is_generated_write_on(engine, sql), engine == Engine::ClickHouse, "{engine:?} {sql}" ); } // Never `IS NOT NULL`: it names no value. assert!( !is_generated_write_on(engine, "DELETE FROM t WHERE c IS NOT NULL"), "{engine:?}" ); } } #[test] fn a_clickhouse_name_holding_a_backslash_names_no_row() { // The gate's grammar does not read a backslash inside backticks, so // such a row is refused rather than matched on a misread name. let delete = format!( "DELETE FROM t WHERE {} = '1' AND `n` IS NULL", Engine::ClickHouse.spec().quote_identifier(r"a\b") ); assert!(!is_generated_write_on(Engine::ClickHouse, &delete)); assert!(!delete_matches_key_on( Engine::ClickHouse, &delete, &[r"a\b", "n"] )); assert_eq!(row_guard(Engine::ClickHouse, &delete), None); } #[test] fn a_row_guard_counts_with_the_writes_own_table_and_predicate() { assert_eq!( row_guard( Engine::Postgres, r#"UPDATE "s"."t" SET "a" = 'x' WHERE "id" = '7';"# ) .as_deref(), Some(r#"SELECT COUNT(*) FROM "s"."t" WHERE "id" = '7'"#) ); for refused in [ "SELECT 1", "BEGIN", "INSERT INTO t (a) VALUES ('1')", "UPDATE t SET a = '1' WHERE id > '7'", "UPDATE t SET a = '1' WHERE id = '7'; UPDATE t SET a = '2' WHERE id = '8'", "DELETE FROM t WHERE id = '7' OR 1 = 1", ] { assert_eq!(row_guard(Engine::Postgres, refused), None, "{refused}"); } assert_eq!(row_guard(Engine::MongoDb, "db.t.deleteOne({_id: 1})"), None); } #[test] fn a_row_read_after_an_update_names_the_row_by_the_values_it_now_holds() { use crate::db::Target; let engines: Vec<_> = Engine::ALL .into_iter() .filter(|engine| Target::built_in(*engine).row_edits() && engine.spec().sql.null_terms) .collect(); assert_eq!(engines.len(), 6, "{engines:?}"); for engine in engines { let q = engine.spec().qualified("public", "accounts"); let (id, bird, place) = ( engine.quote_identifier("id"), engine.quote_identifier("bird"), engine.quote_identifier("place"), ); let read = |update: String| row_read(engine, &update); let select = |predicate: &str| Some(format!("SELECT * FROM {q} WHERE {predicate}")); // A key column is never assigned, so a keyed read is what it was. assert_eq!( read(format!("UPDATE {q} SET {bird} = 'x' WHERE {id} = '7'")), select(&format!("{id} = '7'")), "{engine:?}" ); // A column the `SET` assigns is read by the value it now holds. assert_eq!( read(format!( "UPDATE {q} SET {bird} = 'finch' WHERE {bird} = 'wren' AND {place} IS NULL" )), select(&format!("{bird} = 'finch' AND {place} IS NULL")), "{engine:?}" ); assert_eq!( read(format!( "UPDATE {q} SET {place} = NULL WHERE {bird} = 'wren' AND {place} = 'oak'" )), select(&format!("{bird} = 'wren' AND {place} IS NULL")), "{engine:?}" ); assert_eq!( read(format!( "UPDATE {q} SET {place} = 'elm', {bird} = NULL \ WHERE {place} IS NULL AND {bird} = 'wren'" )), select(&format!("{place} = 'elm' AND {bird} IS NULL")), "{engine:?}" ); // A column set to DEFAULT has no value to name the row by, when the // predicate names it; when it does not, the predicate stands. assert_eq!( read(format!( "UPDATE {q} SET {place} = DEFAULT WHERE {bird} = 'wren' AND {place} IS NULL" )), None, "{engine:?}" ); assert_eq!( read(format!("UPDATE {q} SET {place} = DEFAULT WHERE {id} = '7'")), select(&format!("{id} = '7'")), "{engine:?}" ); for text in [ format!( "UPDATE {q} SET {bird} = 'finch' WHERE {bird} = 'wren' AND {place} IS NULL" ), format!("UPDATE {q} SET {place} = NULL WHERE {bird} = 'wren' AND {place} = 'oak'"), ] { let read = row_read(engine, &text).expect("a read"); assert!(is_generated_select(engine, &read), "{engine:?} {read}"); } } } #[test] fn a_row_read_is_cut_from_the_gated_update() { use crate::db::Target; let engines: Vec<_> = Engine::ALL .into_iter() .filter(|engine| Target::built_in(*engine).row_edits()) .collect(); assert!(engines.len() > 1, "{engines:?}"); for engine in engines { for sets in [ vec![("name", set("wren")), ("note", set("it's"))], vec![("name", set("wren")), ("note", NewValue::Default)], vec![("name", NewValue::Null), ("note", set("x"))], ] { for keys in [vec![("id", "7")], vec![("id", "7"), ("rev", "2")]] { let row = pending_row(&sets, &keys); let update = update_batch(engine, std::slice::from_ref(&row)).unwrap(); let predicate = update .trim_end_matches(';') .rsplit_once(" WHERE ") .unwrap() .1 .to_string(); let table = engine.spec().qualified("public", "accounts"); let read = row_read(engine, &update) .unwrap_or_else(|| panic!("{engine:?} read nothing of {update}")); assert_eq!( read, format!("SELECT * FROM {table} WHERE {predicate}"), "{engine:?}" ); assert!(is_generated_select(engine, &read), "{engine:?} {read}"); } } } let engine = Engine::Postgres; let one = pending_row(&[("name", set("a"))], &[("id", "1")]); let two = pending_row(&[("name", set("b"))], &[("id", "2")]); let batch = update_batch(engine, &[one, two]).unwrap(); let delete = delete_row(engine, "public", "accounts", &[("id", "1")], &[]).unwrap(); let insert = insert_row(engine, "public", "accounts", &[("name", Some("a"))], &[]).unwrap(); for refused in [ batch.as_str(), delete.as_str(), insert.as_str(), "UPDATE t SET a = a + 1 WHERE id = 1", "UPDATE t SET a = '1' WHERE id > '7'", "SELECT * FROM t WHERE id = '7'", "BEGIN", ] { assert_eq!(row_read(engine, refused), None, "{refused}"); } } #[test] fn a_mongo_row_send_is_read_back_by_its_id() { let oid = "ObjectId('65a4f1c0ffffffffffffff03')"; let row = PendingRow { table: "accounts".into(), sets: vec![("name".into(), set("Ada"))], keys: vec![("_id".into(), oid.into())], types: vec![ ("_id".into(), "objectId".into()), ("name".into(), "string".into()), ], ..Default::default() }; let update = update_batch(Engine::MongoDb, std::slice::from_ref(&row)).unwrap(); let read = row_read(Engine::MongoDb, &update).expect("a read"); assert_eq!(Some(read.clone()), crate::mql::browse::row_reread(&update)); assert!(is_generated_select(Engine::MongoDb, &read), "{read}"); assert!(read.contains("65a4f1c0ffffffffffffff03"), "{read}"); let insert = insert_row( Engine::MongoDb, "dbdelve_dev", "accounts", &[("name", Some("Cy"))], &[("name".to_string(), "string".to_string())], ) .unwrap(); assert_eq!(row_read(Engine::MongoDb, &insert), None, "{insert}"); // A batch of two documents is read one statement at a time. let other = PendingRow { table: "accounts".into(), sets: vec![("name".into(), set("Bo"))], keys: vec![("_id".into(), "ObjectId('65a4f1c0ffffffffffffff04')".into())], types: vec![("_id".into(), "objectId".into())], ..PendingRow::default() }; let two = update_batch(Engine::MongoDb, &[row, other]).unwrap(); assert_eq!(row_read(Engine::MongoDb, &two), None, "{two}"); } #[test] fn a_row_reread_is_cut_from_the_gated_update_or_delete_and_refuses_anything_else() { use crate::db::Target; let engines: Vec<_> = Engine::ALL .into_iter() .filter(|engine| Target::built_in(*engine).row_edits()) .collect(); assert!(engines.len() > 1, "{engines:?}"); for engine in engines { let table = engine.spec().qualified("public", "accounts"); for keys in [vec![("id", "7")], vec![("id", "7"), ("rev", "2")]] { let row = pending_row(&[("name", set("wren")), ("note", NewValue::Default)], &keys); let update = update_batch(engine, std::slice::from_ref(&row)).unwrap(); let delete = delete_row(engine, "public", "accounts", &keys, &[]).unwrap(); for statement in [update, delete] { let predicate = statement .trim_end_matches(';') .rsplit_once(" WHERE ") .unwrap() .1 .to_string(); let reread = row_reread(engine, &statement) .unwrap_or_else(|| panic!("{engine:?} read nothing of {statement}")); assert_eq!( reread, format!("SELECT * FROM {table} WHERE {predicate} LIMIT 2"), "{engine:?}: two rows already prove it names more than one" ); assert!(is_generated_select(engine, &reread), "{engine:?} {reread}"); // The apply sends a draft's statements one at a time, so // the unbracketed text of one is its own single statement. assert_eq!( generated_writes(engine, &statement), Some(vec![statement.trim_end_matches(';').to_string()]), "{engine:?}" ); } } } let engine = Engine::Postgres; let one = pending_row(&[("name", set("a"))], &[("id", "1")]); let two = pending_row(&[("name", set("b"))], &[("id", "2")]); let batch = update_batch(engine, &[one, two]).unwrap(); let insert = insert_row(engine, "public", "accounts", &[("name", Some("a"))], &[]).unwrap(); for refused in [ batch.as_str(), insert.as_str(), "BEGIN", "COMMIT", "DELETE FROM t", "DELETE FROM t WHERE id > '7'", "UPDATE t SET a = a + 1 WHERE id = 1", "SELECT * FROM t WHERE id = '7'", ] { assert_eq!(row_reread(engine, refused), None, "{refused}"); } // Two statements of a bracketed batch are two rows, never one read. let bracketed = update_batch( Engine::Sqlite, &[ pending_row(&[("name", set("a"))], &[("id", "1")]), pending_row(&[("name", set("b"))], &[("id", "2")]), ], ) .unwrap(); assert_eq!(row_reread(Engine::Sqlite, &bracketed), None, "{bracketed}"); assert_eq!(row_reread(Engine::Redis, "DEL k"), None); } #[test] fn a_mongo_draft_is_written_key_checked_and_reread_through_the_sql_entry_points() { let oid = |n: u8| format!("ObjectId('65a4f1c0ffffffffffffff{n:02x}')"); let delete = |n: u8| DraftDelete { schema: "dbdelve_dev".into(), table: "accounts".into(), keys: vec![("_id".into(), oid(n))], null_keys: Vec::new(), types: vec![("_id".into(), "objectId".into())], }; let deletes = [delete(1), delete(2)]; let updates = [PendingRow { table: "accounts".into(), sets: vec![("name".into(), set("Ada"))], keys: vec![("_id".into(), oid(3))], types: vec![ ("_id".into(), "objectId".into()), ("name".into(), "string".into()), ], ..Default::default() }]; let inserts = [DraftInsert { schema: "dbdelve_dev".into(), table: "accounts".into(), columns: vec![("name".into(), Some("Cy".into()))], types: vec![("name".into(), "string".into())], }]; assert_eq!( draft_batch(Engine::MongoDb, &deletes, &updates, &inserts), crate::mql::draft_batch(&deletes, &updates, &inserts), ); let batch = draft_batch(Engine::MongoDb, &deletes, &updates, &inserts) .expect("a mongo draft is written"); assert!(is_generated_write_on(Engine::MongoDb, &batch), "{batch}"); assert_eq!( draft_deletes_match(Engine::MongoDb, &batch, &["_id"], "dbdelve_dev", "accounts"), Some(2) ); assert_eq!( draft_deletes_match(Engine::MongoDb, &batch, &["_id"], "dbdelve_dev", "other"), None, "a delete of another collection is not the marked documents'" ); let statements = generated_writes(Engine::MongoDb, &batch).expect("a draft splits"); assert_eq!(statements.len(), 4, "{statements:?}"); for (statement, method) in statements .iter() .zip(["deleteOne", "deleteOne", "updateOne", "insertOne"]) { assert!(statement.contains(method), "{statement}"); assert!(!statement.ends_with(';'), "{statement}"); assert!( is_generated_write_on(Engine::MongoDb, statement), "{statement}" ); } for (statement, wanted) in statements.iter().zip([true, true, true, false]) { assert_eq!( row_reread(Engine::MongoDb, statement), crate::mql::browse::row_reread(statement) ); assert_eq!( row_reread(Engine::MongoDb, statement).is_some(), wanted, "{statement}" ); } for refused in [ "db.getCollection(\"accounts\").deleteMany({})", "db.getCollection(\"accounts\").find({})", "db.getCollection(\"accounts\").deleteOne({_id: 1});\ndb.dropDatabase();", "SELECT 1", "", ] { assert_eq!( generated_writes(Engine::MongoDb, refused), None, "{refused}" ); } // Redis writes no draft of this shape. assert!(draft_batch(Engine::Redis, &deletes, &updates, &inserts).is_err()); assert_eq!( draft_deletes_match(Engine::Redis, &batch, &["_id"], "d", "accounts"), None ); assert_eq!(row_reread(Engine::Redis, &statements[0]), None); assert_eq!(generated_writes(Engine::Redis, &statements[0]), None); } /// `"id"` is a string on MySQL and MariaDB, so `WHERE "id" = 'id'` holds on /// every row there; ClickHouse quotes with backticks too but reads it as a /// name, as Postgres does. #[test] fn a_double_quoted_name_is_a_string_on_mysql_and_mariadb_only() { for (engine, name) in [ (Engine::MySql, false), (Engine::MariaDb, false), (Engine::Postgres, true), (Engine::ClickHouse, true), ] { let q = engine.qualified("s", "t"); let delete = format!("DELETE FROM {q} WHERE \"id\" = 'id'"); assert_eq!( is_generated_write_on(engine, &delete), name, "{engine:?}: {delete}" ); assert_eq!( delete_matches_key_on(engine, &delete, &["id"]), name, "{engine:?}: {delete}" ); if engine != Engine::ClickHouse { let id = engine.quote_identifier("id"); let insert = format!("INSERT INTO {q} ({id}) VALUES ('9')"); let draft = format!("{delete};\n{insert};"); assert_eq!( draft_deletes_match(engine, &draft, &["id"], "s", "t").is_some(), name, "{engine:?}: {draft}" ); } } } fn set(value: &str) -> NewValue { NewValue::Value(value.into()) } fn pending_row(sets: &[(&str, NewValue)], keys: &[(&str, &str)]) -> PendingRow { fn owned(pairs: &[(&str, &str)]) -> Vec<(String, String)> { pairs .iter() .map(|(column, value)| (column.to_string(), value.to_string())) .collect() } PendingRow { schema: "public".to_string(), table: "accounts".to_string(), sets: sets .iter() .map(|(column, value)| (column.to_string(), value.clone())) .collect(), keys: owned(keys), types: Vec::new(), held: Vec::new(), ..Default::default() } } fn draft_row_edit_engines() -> Vec { use crate::db::Target; let engines: Vec<_> = Engine::ALL .into_iter() .filter(|engine| Target::built_in(*engine).row_edits()) .collect(); assert!(engines.len() > 1, "{engines:?}"); engines } #[test] fn a_draft_refuses_a_hidden_delete_a_second_insert_row_and_a_comment_between_statements() { for engine in draft_row_edit_engines() { let q = engine.qualified("public", "accounts"); let id = engine.quote_identifier("id"); let name = engine.quote_identifier("Name"); let upd = format!("UPDATE {q} SET {name} = 'x' WHERE {id} = '8'"); let del = format!("DELETE FROM {q} WHERE {id} = '7'"); let ins = format!("INSERT INTO {q} ({id}) VALUES ('9')"); let cte_delete = format!("WITH d AS (DELETE FROM {q} WHERE {id} = '8' RETURNING *)"); let cases: Vec<(&str, Vec)> = vec![ ( "a CTE delete beside an update", vec![upd.clone(), format!("{cte_delete} SELECT 1")], ), ( "an update carrying a CTE delete, beside an insert", vec![ format!("{cte_delete} UPDATE {q} SET {name} = 'x' WHERE {id} = '8'"), ins.clone(), ], ), ( "an update carrying a CTE delete, beside an update", vec![ format!("{cte_delete} UPDATE {q} SET {name} = 'x' WHERE {id} = '8'"), upd.clone(), ], ), ( "a delete beside a two-row insert", vec![del.clone(), format!("{ins}, ('10')")], ), ( "a delete beside an insert from a select", vec![del.clone(), format!("INSERT INTO {q} SELECT * FROM {q}")], ), ( "a delete beside an insert returning", vec![del.clone(), format!("{ins} RETURNING *")], ), ( "a comment line between a delete and an insert", vec![del.clone(), "-- note".into(), ins.clone()], ), ( "an executable comment between a delete and an insert", vec![del.clone(), "/*! SELECT 1 */".into(), ins.clone()], ), ( "a delete matching more than its row, beside an insert", vec![format!("{del} OR 1 = 1"), ins.clone()], ), ( "a delete with no where, beside an insert", vec![format!("DELETE FROM {q}"), ins.clone()], ), ]; for (case, statements) in &cases { let body = statements .iter() .map(|statement| match statement.starts_with("--") { true => statement.clone(), false => format!("{statement};"), }) .collect::>() .join("\n"); for text in [body.clone(), format!("BEGIN;\n{body}\nCOMMIT;")] { assert!( !is_generated_write_on(engine, &text), "{engine:?} admitted {case}: {text}" ); } } let unclosed = format!("BEGIN;\n{del};\n{ins};"); assert!( !is_generated_write_on(engine, &unclosed), "{engine:?} admitted a bracket never closed: {unclosed}" ); } } fn draft_delete(id: &str) -> DraftDelete { DraftDelete { schema: "public".into(), table: "accounts".into(), keys: vec![("id".into(), id.into())], null_keys: Vec::new(), types: Vec::new(), } } fn draft_insert(id: &str, name: Option<&str>) -> DraftInsert { DraftInsert { schema: "public".into(), table: "accounts".into(), columns: vec![ ("id".into(), Some(id.into())), ("Name".into(), name.map(Into::into)), ], types: Vec::new(), } } #[test] fn a_mixed_draft_is_admitted_with_or_without_its_brackets_on_every_row_edit_engine() { for engine in draft_row_edit_engines() { let shapes = [ ( "delete, update, insert", vec![draft_delete("7")], vec![pending_row(&[("Name", set("x"))], &[("id", "8")])], vec![draft_insert("9", None)], ), ( "delete, delete", vec![draft_delete("7"), draft_delete("8")], vec![], vec![], ), ( "insert, insert", vec![], vec![], vec![draft_insert("9", None), draft_insert("10", Some("y"))], ), ( "update, insert", vec![], vec![pending_row(&[("Name", set("x"))], &[("id", "8")])], vec![draft_insert("9", None)], ), ( "delete, insert", vec![draft_delete("7")], vec![], vec![draft_insert("9", None)], ), ( "delete, update", vec![draft_delete("7")], vec![pending_row(&[("Name", set("x"))], &[("id", "8")])], vec![], ), ]; for (shape, deletes, updates, inserts) in &shapes { let batch = draft_batch(engine, deletes, updates, inserts) .unwrap_or_else(|error| panic!("{engine:?} {shape}: {error}")); assert!( is_generated_write_on(engine, &batch), "{engine:?} refused {shape}: {batch}" ); match engine.transaction_start() { Some(word) => { assert!(batch.starts_with(&format!("{word};\n")), "{batch}"); assert!(batch.ends_with("\nCOMMIT;"), "{batch}"); } None => assert!( !batch.contains("BEGIN") && !batch.contains("COMMIT"), "{engine:?} {shape}: {batch}" ), } } } // ClickHouse names a row by every value, which a sequence cannot count. let engine = Engine::ClickHouse; let typed = DraftDelete { types: vec![("id".into(), "Int32".into())], ..draft_delete("7") }; let batch = draft_batch( engine, std::slice::from_ref(&typed), &[], &[draft_insert("9", None)], ) .unwrap(); assert!(!is_generated_write_on(engine, &batch), "{batch}"); } #[test] fn a_draft_sets_bytes_in_the_engines_literal_and_no_value_a_lone_update_refuses() { for engine in draft_row_edit_engines() { let Some(literal) = engine.binary_literal(b"hi") else { continue; }; let batch = draft_batch( engine, &[draft_delete("7")], &[pending_row( &[("Name", NewValue::Bytes(b"hi".to_vec()))], &[("id", "8")], )], &[], ) .unwrap_or_else(|error| panic!("{engine:?}: {error}")); assert!(batch.contains(&literal), "{engine:?}: {batch}"); assert!(is_generated_write_on(engine, &batch), "{engine:?}: {batch}"); let q = engine.qualified("public", "accounts"); let id = engine.quote_identifier("id"); let name = engine.quote_identifier("Name"); let del = format!("DELETE FROM {q} WHERE {id} = '7';"); for value in ["now()", "'a' || 'b'", "(SELECT 1)", "'x' /*! , 1 */"] { let draft = format!("{del}\nUPDATE {q} SET {name} = {value} WHERE {id} = '8';"); assert!( !is_generated_write_on(engine, &draft), "{engine:?} admitted {value}: {draft}" ); } } } #[test] fn a_write_setting_bytes_is_cut_into_steps_and_re_read_as_any_other() { for engine in draft_row_edit_engines() { if engine.binary_literal(b"hi").is_none() { continue; } let update = pending_row(&[("Name", NewValue::Bytes(b"hi".to_vec()))], &[("id", "8")]); let lone = update_batch(engine, std::slice::from_ref(&update)) .unwrap_or_else(|error| panic!("{engine:?}: {error}")); let draft = draft_batch(engine, &[draft_delete("7")], &[update], &[]) .unwrap_or_else(|error| panic!("{engine:?}: {error}")); for (batch, steps) in [(lone, 1), (draft, 2)] { let statements = generated_writes(engine, &batch) .unwrap_or_else(|| panic!("{engine:?}: not cut: {batch}")); assert_eq!(statements.len(), steps, "{engine:?}: {batch}"); for statement in &statements { assert!( row_reread(engine, statement).is_some(), "{engine:?}: no re-read of {statement}" ); } } } } #[test] fn a_draft_batch_keeps_its_statements_recoverable_in_delete_update_insert_order() { for engine in draft_row_edit_engines() { let updates = [ pending_row(&[("Name", set("a"))], &[("id", "8")]), pending_row(&[("Name", set("b"))], &[("id", "4")]), ]; let batch = draft_batch( engine, &[draft_delete("5"), draft_delete("2")], &updates, &[draft_insert("11", Some("k")), draft_insert("10", None)], ) .unwrap(); let statements = generated_writes(engine, &batch) .unwrap_or_else(|| panic!("{engine:?} recovered nothing of {batch}")); let delete = |id| delete_row(engine, "public", "accounts", &[("id", id)], &[]).unwrap(); let insert = |id, name: Option<&str>| { insert_row( engine, "public", "accounts", &[("id", Some(id)), ("Name", name)], &[], ) .unwrap() }; let update = |row: &PendingRow| { update_batch(engine, std::slice::from_ref(row)) .unwrap() .trim_end_matches(';') .to_string() }; assert_eq!( statements, [ delete("5"), delete("2"), update(&updates[0]), update(&updates[1]), insert("11", Some("k")), insert("10", None), ], "{engine:?}: {batch}" ); for statement in &statements { assert!( is_generated_write_on(engine, statement), "{engine:?} refused alone: {statement}" ); } // One statement is never bracketed, whichever kind it is. for one in [ draft_batch(engine, &[draft_delete("5")], &[], &[]), draft_batch(engine, &[], &updates[..1], &[]), draft_batch(engine, &[], &[], &[draft_insert("11", None)]), ] { let one = one.unwrap(); assert!( !one.contains("BEGIN") && !one.contains("COMMIT") && one.ends_with(';'), "{engine:?}: {one}" ); } assert_eq!( draft_batch(engine, &[], &[], &[]), Err("There are no edits to apply.".to_string()), "{engine:?}" ); } } #[test] fn the_key_check_of_a_draft_reads_kinds_and_table_from_the_tree() { for engine in [Engine::Sqlite, Engine::Postgres, Engine::SqlServer] { let update = pending_row(&[("Name", set("x"))], &[("id", "8")]); let batch = |deletes: &[DraftDelete], updates: &[PendingRow], inserts: &[DraftInsert]| { draft_batch(engine, deletes, updates, inserts).unwrap() }; let key = |keys: &[&str], batch: &str| { draft_deletes_match(engine, batch, keys, "public", "accounts") }; let two = batch( &[draft_delete("1"), draft_delete("2")], std::slice::from_ref(&update), &[draft_insert("9", None)], ); assert_eq!(key(&["id"], &two), Some(2), "{engine:?}: {two}"); assert_eq!(key(&["Region", "id"], &two), None, "half a key: {two}"); assert_eq!(key(&["Region"], &two), None, "{two}"); let elsewhere = DraftDelete { table: "other".into(), ..draft_delete("3") }; let other = batch(&[draft_delete("1"), elsewhere], &[], &[]); assert_eq!(key(&["id"], &other), None, "{engine:?}: {other}"); let none = batch( &[], std::slice::from_ref(&update), &[draft_insert("9", None)], ); assert_eq!(key(&["id"], &none), Some(0), "{engine:?}: {none}"); assert_eq!(key(&["id"], "DELETE FROM WHERE (((;"), None); assert_eq!(key(&["id"], ""), None); // A delete whose predicate is not a one-row key is no delete to count. let (table, id) = ( engine.qualified("public", "accounts"), engine.quote_identifier("id"), ); let wide = format!( "DELETE FROM {table} WHERE {id} = '1';\nDELETE FROM {table} WHERE {id} = '1' OR 1 = 1;" ); assert_eq!(key(&["id"], &wide), None, "{engine:?}: {wide}"); } assert_eq!( draft_deletes_match( Engine::Redis, "db.t.deleteOne({_id: 1})", &["_id"], "d", "t" ), None ); } #[test] fn a_nulled_cell_reaches_the_batch_as_the_keyword() { let rows = vec![pending_row(&[("name", NewValue::Null)], &[("id", "1")])]; assert_eq!( update_batch(Engine::Postgres, &rows).unwrap(), "UPDATE \"public\".\"accounts\" SET \"name\" = NULL WHERE \"id\" = '1';" ); } #[test] fn several_pending_rows_become_one_semicolon_joined_batch() { let rows = vec![ pending_row(&[("name", set("Ada"))], &[("id", "1")]), pending_row(&[("name", set("Bo"))], &[("id", "2")]), ]; let batch = update_batch(Engine::Postgres, &rows).unwrap(); assert_eq!( batch, "UPDATE \"public\".\"accounts\" SET \"name\" = 'Ada' WHERE \"id\" = '1';\n\ UPDATE \"public\".\"accounts\" SET \"name\" = 'Bo' WHERE \"id\" = '2';" ); // The batch dbdelve builds has to pass the same gate dbdelve checks every // generated statement against, or the generator and the gate have // drifted apart. assert!(is_generated_write(&batch)); } #[test] fn an_engine_without_an_implicit_transaction_gets_explicit_brackets() { // MySQL and SQLite commit each statement on its own, so an unbracketed // batch could apply half the user's edits and report the failure of the // rest. let rows = vec![ pending_row(&[("name", set("Ada"))], &[("id", "1")]), pending_row(&[("name", set("Bo"))], &[("id", "2")]), ]; for engine in [Engine::MySql, Engine::Sqlite] { let batch = update_batch(engine, &rows).unwrap(); assert!(batch.starts_with("BEGIN;\n"), "{engine:?} {batch}"); assert!(batch.ends_with("\nCOMMIT;"), "{engine:?} {batch}"); assert!(is_generated_write(&batch), "{engine:?} {batch}"); // One statement is already atomic, so brackets round it would be // ceremony the user has to read past. let single = update_batch(engine, &rows[..1]).unwrap(); assert!(!single.contains("BEGIN"), "{engine:?} {single}"); assert!(is_generated_write(&single), "{engine:?} {single}"); } let postgres = update_batch(Engine::Postgres, &rows).unwrap(); assert!(!postgres.contains("BEGIN"), "{postgres}"); } #[test] fn a_sql_server_batch_opens_the_way_t_sql_spells_it_and_passes_the_gate() { // A bare `BEGIN` opens a statement block in T-SQL, so the brackets are // `BEGIN TRANSACTION`; the gate has to see through that spelling too. let rows = vec![ pending_row(&[("name", set("李"))], &[("id", "1")]), pending_row(&[("name", set("Bo"))], &[("id", "2")]), ]; let batch = update_batch(Engine::SqlServer, &rows).unwrap(); assert_eq!( batch, "BEGIN TRANSACTION;\n\ UPDATE \"public\".\"accounts\" SET \"name\" = N'李' WHERE \"id\" = N'1';\n\ UPDATE \"public\".\"accounts\" SET \"name\" = N'Bo' WHERE \"id\" = N'2';\n\ COMMIT;" ); assert!(is_generated_write(&batch), "{batch}"); } #[test] fn the_gate_reads_sql_server_spellings_and_refuses_what_it_always_refused() { for admitted in [ "INSERT INTO \"dbo\".\"accounts\" (\"name\") VALUES (N'x')", "DELETE FROM \"dbo\".\"accounts\" WHERE \"id\" = N'1'", "BEGIN TRANSACTION; UPDATE \"dbo\".\"a\" SET \"x\" = N'1' WHERE \"id\" = N'1'; COMMIT;", ] { assert!(is_generated_write(admitted), "{admitted}"); } assert!(delete_matches_key( "DELETE FROM \"dbo\".\"accounts\" WHERE \"id\" = N'1'", &["id"] )); for refused in [ // A transaction it cannot see closed, and one hiding a drop. "BEGIN TRANSACTION; UPDATE \"dbo\".\"a\" SET \"x\" = N'1' WHERE \"id\" = N'1';", "BEGIN TRANSACTION; DROP TABLE x; COMMIT;", // Brackets are T-SQL's own quoting and the pinned grammar's error, // which is why dbdelve never writes them. "UPDATE [dbo].[a] SET [x] = N'1' WHERE [id] = N'1'", // A national prefix on a column is still a column, not a literal. "DELETE FROM \"dbo\".\"accounts\" WHERE \"id\" = N\"other\"", ] { assert!(!is_generated_write(refused), "{refused}"); } } #[test] fn a_sql_server_preview_is_paged_with_offset_and_fetch() { let statement = |limit: &str| format!("SELECT * FROM \"dbo\".\"accounts\"{limit}"); // `OFFSET` needs an `ORDER BY`, so an unsorted page gets one that // orders nothing. assert_eq!( paged(Engine::SqlServer, &statement(" LIMIT 1000"), &[]).as_deref(), Some( "SELECT * FROM \"dbo\".\"accounts\" ORDER BY (SELECT NULL) \ OFFSET 0 ROWS FETCH NEXT 1000 ROWS ONLY" ) ); let sorted = with_order_by( Engine::SqlServer, "SELECT * FROM \"dbo\".\"accounts\" WHERE \"name\" LIKE N'%a[%]%' LIMIT 10 OFFSET 20", &[SortKey::new("\"id\"", false)], ) .unwrap(); assert!(is_generated_select(Engine::SqlServer, &sorted), "{sorted}"); assert_eq!( paged(Engine::SqlServer, &sorted, &[]).as_deref(), Some( "SELECT * FROM \"dbo\".\"accounts\" WHERE \"name\" LIKE N'%a[%]%' \ ORDER BY \"id\" DESC OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY" ) ); // Every other engine runs the statement the gate read, unchanged. for engine in Engine::ALL.into_iter().filter(|e| *e != Engine::SqlServer) { assert_eq!( paged(engine, &sorted, &[]).as_deref(), Some(sorted.as_str()), "{engine:?}" ); } // No limit is one page, which needs no `OFFSET` and so no order. assert_eq!( paged(Engine::SqlServer, &statement(""), &[]).as_deref(), Some(statement("").as_str()) ); assert_eq!(paged(Engine::SqlServer, "DELETE FROM t LIMIT 1", &[]), None); } #[test] fn an_unpaged_preview_reads_back_the_sort_it_runs_with() { let unsorted = "SELECT * FROM \"dbo\".\"accounts\" LIMIT 1000 OFFSET 0"; let sorted = with_order_by( Engine::SqlServer, unsorted, &[SortKey::new("\"id\"", false)], ) .unwrap(); for statement in [unsorted, sorted.as_str()] { let paged = paged(Engine::SqlServer, statement, &[]).unwrap(); assert_eq!( order_by(Engine::SqlServer, &paged), None, "the grammar cannot read {paged}" ); assert_eq!( order_by(Engine::SqlServer, &unpaged(&paged)), order_by(Engine::SqlServer, statement), "{paged}" ); } assert_eq!( order_by( Engine::SqlServer, &unpaged(&paged(Engine::SqlServer, &sorted, &[]).unwrap()) ), Some(vec![SortKey::new("\"id\"", false)]) ); // Not `paged`'s shape: left alone. let typed = "SELECT * FROM t ORDER BY id OFFSET 5 ROWS"; assert_eq!(unpaged(typed), typed); } #[test] fn an_unsorted_clickhouse_page_is_ordered_by_the_key() { let unsorted = "SELECT * FROM `db`.`events` WHERE `a` = 1 LIMIT 100 OFFSET 200"; let key = ["user_id".to_string(), "ts".to_string()]; let page = paged(Engine::ClickHouse, unsorted, &key).unwrap(); assert_eq!( page, "SELECT * FROM `db`.`events` WHERE `a` = 1 ORDER BY `user_id`, `ts` LIMIT 100 OFFSET 200" ); assert!(is_generated_select(Engine::ClickHouse, &page), "{page}"); // The key's order is not a sort the user chose: read from the // statement before paging, an unsorted preview has no sort keys. assert_eq!(order_by(Engine::ClickHouse, unsorted), Some(Vec::new())); assert_eq!( order_by(Engine::ClickHouse, &page).map(|k| k.len()), Some(2) ); // A sort the user asked for is the order, key or no key, and is what // the statement before paging reads back. let sorted = with_order_by(Engine::ClickHouse, unsorted, &[SortKey::new("`id`", true)]).unwrap(); assert_eq!( paged(Engine::ClickHouse, &sorted, &key).as_deref(), Some(sorted.as_str()) ); assert_eq!( order_by(Engine::ClickHouse, &sorted), Some(vec![SortKey::new("`id`", true)]) ); // No key, or a key made of an expression such as `toDate(ts)`, which // gives none: the page stays as generated. assert_eq!( paged(Engine::ClickHouse, unsorted, &[]).as_deref(), Some(unsorted) ); // No limit is one page. let whole = "SELECT * FROM `db`.`events`"; assert_eq!( paged(Engine::ClickHouse, whole, &key).as_deref(), Some(whole) ); assert_eq!( paged(Engine::ClickHouse, "DELETE FROM t LIMIT 1", &key), None ); } #[test] fn an_unsorted_sql_server_page_is_ordered_by_the_key() { let unsorted = "SELECT * FROM \"dbo\".\"order lines\" LIMIT 100 OFFSET 200"; let key = ["order_id".to_string(), "line]no".to_string()]; let page = paged(Engine::SqlServer, unsorted, &key).unwrap(); assert_eq!( page, "SELECT * FROM \"dbo\".\"order lines\" ORDER BY (SELECT NULL), \"order_id\", \ \"line]no\" OFFSET 200 ROWS FETCH NEXT 100 ROWS ONLY" ); // Read back as the unsorted preview it is, not as a sort on the key. assert_eq!(unpaged(&page), unsorted); assert_eq!( order_by(Engine::SqlServer, &unpaged(&page)), Some(Vec::new()) ); // A sort the user asked for is the order, key or no key. let sorted = with_order_by(Engine::SqlServer, unsorted, &[SortKey::new("\"id\"", true)]).unwrap(); assert_eq!( paged(Engine::SqlServer, &sorted, &key), paged(Engine::SqlServer, &sorted, &[]) ); // One inside a filter's string is the user's text, not paged's marker. let quoted = with_order_by( Engine::SqlServer, "SELECT * FROM t WHERE a = ' ORDER BY (SELECT NULL)' LIMIT 5 OFFSET 0", &[SortKey::new("a", false)], ) .unwrap(); let quoted_page = paged(Engine::SqlServer, "ed, &key).unwrap(); assert_eq!(unpaged("ed_page), quoted); } #[test] fn classify_reads_t_sql_spellings() { let cases: &[(&str, Verdict)] = &[ ("SELECT [id] FROM [dbo].[accounts]", Verdict::READ), ("SELECT TOP 10 * FROM t", Verdict::READ), ( "SELECT * FROM t ORDER BY (SELECT NULL) OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY", Verdict::READ, ), ("SELECT N'李' AS name", Verdict::READ), ( "UPDATE [dbo].[t] SET [x] = N'a' WHERE [id] = 1", Verdict::WRITE, ), ( "BEGIN TRANSACTION; UPDATE t SET x = N'1' WHERE id = N'1'; COMMIT;", Verdict::WRITE, ), ("TRUNCATE TABLE t", Verdict::destroys(Destructive::Truncate)), ("DROP TABLE [t]", Verdict::destroys(Destructive::Drop)), ( "BEGIN TRAN; DELETE FROM t; COMMIT TRAN", Verdict::destroys(Destructive::UnfilteredDelete), ), // Every branch counts: which one runs is the server's decision. ( "IF 1 = 1 SELECT 1 ELSE DELETE FROM t", Verdict::destroys(Destructive::UnfilteredDelete), ), ("IF 1 = 1 SELECT 1", Verdict::READ), ("EXEC dbo.deactivate_account 1", Verdict::FULL), ]; for (sql, verdict) in cases { assert_eq!(classify(Engine::SqlServer, sql), *verdict, "{sql}"); } } #[test] fn an_if_is_as_strict_as_its_conditions() { let cases: &[(Engine, &str, Verdict)] = &[ ( Engine::SqlServer, "IF EXISTS (SELECT 1 FROM t) SELECT 1", Verdict::READ, ), (Engine::SqlServer, "IF @x IS NULL SELECT 1", Verdict::READ), (Engine::SqlServer, "IF dbo.f() = 1 SELECT 1", Verdict::FULL), // Before `IF` had an arm it needed Full everywhere; a condition that // calls something still does, on every engine that parses one. ( Engine::Snowflake, "BEGIN IF (side_effect() = 1) THEN SELECT 1; END IF; END", Verdict::FULL, ), ( Engine::Snowflake, "BEGIN IF (1 = 1) THEN SELECT 1; END IF; END", Verdict::READ, ), ( Engine::MySql, "IF 1 = 1 THEN SELECT 1; ELSEIF f() THEN SELECT 2; END IF", Verdict::FULL, ), ( Engine::Postgres, "IF 1 = 1 THEN SELECT 1; ELSEIF 2 IN (1, 2) THEN SELECT 2; END IF", Verdict::READ, ), ]; for (engine, sql, verdict) in cases { assert_eq!(classify(*engine, sql), *verdict, "{engine:?}: {sql}"); } } #[test] fn a_row_with_no_key_to_find_it_by_refuses_the_whole_batch() { let rows = vec![ pending_row(&[("name", set("Ada"))], &[("id", "1")]), // No keys at all: update_row refuses this one, since there is // nothing to identify the row it would touch. pending_row(&[("name", set("Bo"))], &[]), ]; assert!( update_row( Engine::Postgres, "public", "accounts", &[("name", set("Bo"))], &[], &[] ) .is_none() ); assert!(update_batch(Engine::Postgres, &rows).is_err()); } #[test] fn an_empty_batch_of_rows_has_nothing_to_send() { assert!(update_batch(Engine::Postgres, &[]).is_err()); } #[test] fn an_older_runs_outcome_leaves_the_newer_run_alone() { let run = |at, ms| crate::store::HistoryEntry { sql: "SELECT 1".into(), at: Some(at), ms, ..Default::default() }; let mut history = vec![run(2, None)]; remember_statement(&mut history, run(1, Some(10))); assert_eq!(history, [run(2, None)]); remember_statement(&mut history, run(2, Some(20))); assert_eq!(history, [run(2, Some(20))]); } #[test] fn a_statement_run_again_moves_to_the_front_rather_than_doubling() { let entry = |sql: &str| crate::store::HistoryEntry { sql: sql.into(), ..Default::default() }; let mut history = vec![entry("SELECT 2"), entry("SELECT 1")]; remember_statement(&mut history, entry("SELECT 1")); assert_eq!(history, [entry("SELECT 1"), entry("SELECT 2")]); } #[test] fn a_recalled_statement_starts_on_the_line_the_cursor_is_sent_to() { // The line `recall_statement` computes, against the text it computes it // from. A cursor on the wrong line runs the wrong statement. for (buffer, recalled) in [ ("", "SELECT 1"), ("SELECT 2", "SELECT 1"), ("SELECT 2;\n", "SELECT\n 1"), ] { let appended = appended_statement(Engine::Postgres, buffer, recalled); let line = appended.lines().count() - recalled.lines().count(); assert_eq!( appended.lines().nth(line), recalled.lines().next(), "{appended:?}" ); } } #[test] fn an_unterminated_buffer_is_terminated_before_the_appended_statement() { // Without the semicolon, "SELECT 1" and "UPDATE ..." would read back // as a single statement, and cmd+enter would send both at once. assert_eq!( appended_statement(Engine::Postgres, "SELECT 1", "UPDATE t SET a = 1"), "SELECT 1;\n\nUPDATE t SET a = 1" ); } #[test] fn a_redis_buffer_takes_its_appended_command_on_a_line_of_its_own() { let appended = appended_statement(Engine::Redis, "GET a \n", "SET a 1 KEEPTTL"); assert_eq!(appended, "GET a\n\nSET a 1 KEEPTTL"); assert_eq!(crate::redis_cmd::parse(&appended).unwrap().len(), 2); } #[test] fn an_already_terminated_buffer_keeps_a_single_semicolon() { assert_eq!( appended_statement(Engine::Postgres, "SELECT 1;", "UPDATE t SET a = 1"), "SELECT 1;\n\nUPDATE t SET a = 1" ); } #[test] fn a_sort_spliced_after_a_line_comment_starts_its_own_line() { let by_name = [SortKey::new("name", true)]; for (statement, expected) in [ ( "select * from t -- recent\nlimit 10", "select * from t -- recent\nORDER BY name ASC limit 10", ), ( "select * from t -- recent\norder by id limit 10", "select * from t -- recent\nORDER BY name ASC limit 10", ), ( "select * from t /* recent */ limit 10", "select * from t /* recent */ ORDER BY name ASC limit 10", ), ( "select * from t where note = 'a--b' limit 10", "select * from t where note = 'a--b' ORDER BY name ASC limit 10", ), ] { assert_eq!( with_order_by(Engine::Sqlite, statement, &by_name).as_deref(), Some(expected) ); } assert_eq!( with_order_by( Engine::Sqlite, "select * from t -- recent\norder by id limit 10", &[] ) .as_deref(), Some("select * from t -- recent\nlimit 10") ); } #[test] fn a_comment_marker_inside_a_string_still_unpages_on_sql_server() { for value in ["'a--b'", "'a#b'"] { let preview = format!("SELECT * FROM \"t\" WHERE \"name\" = {value} LIMIT 100 OFFSET 0"); let paged = paged(Engine::SqlServer, &preview, &["id".into()]).unwrap(); assert_eq!(unpaged(&paged), preview, "{paged}"); } } #[test] fn a_trailing_comment_does_not_swallow_the_terminator() { for (buffer, expected) in [ ("SELECT 1 -- note", "SELECT 1; -- note"), ("SELECT 1 -- note;", "SELECT 1; -- note;"), ("SELECT 1 /* note */", "SELECT 1; /* note */"), ("SELECT 1; -- note", "SELECT 1; -- note"), ("SELECT 1; /* note; */", "SELECT 1; /* note; */"), ("SELECT 'a;'", "SELECT 'a;';"), ("SELECT 1;;", "SELECT 1;;"), ] { let appended = appended_statement(Engine::Postgres, buffer, "UPDATE t SET a = 1"); assert_eq!(appended, format!("{expected}\n\nUPDATE t SET a = 1")); assert_eq!( Buffer::parse(&appended).statements().len(), 2, "{appended:?}" ); } } #[test] fn an_empty_buffer_yields_just_the_statement() { assert_eq!( appended_statement(Engine::Postgres, "", "UPDATE t SET a = 1"), "UPDATE t SET a = 1" ); } #[test] fn trailing_whitespace_in_the_buffer_does_not_ragged_the_join() { assert_eq!( appended_statement(Engine::Postgres, "SELECT 1\n\n ", "UPDATE t SET a = 1"), "SELECT 1;\n\nUPDATE t SET a = 1" ); } #[test] fn classify_separates_reads_writes_and_destruction() { let cases: &[(&str, Mode, Option)] = &[ ("SELECT 1", Mode::ReadOnly, None), ("WITH x AS (SELECT 1) SELECT * FROM x", Mode::ReadOnly, None), ("SHOW TABLES", Mode::ReadOnly, None), ("EXPLAIN SELECT 1", Mode::ReadOnly, None), ("EXPLAIN ANALYZE SELECT 1", Mode::ReadOnly, None), ("", Mode::ReadOnly, None), ("-- nothing here", Mode::ReadOnly, None), // The semicolon is inside a literal, so this is one read and not a DROP. ("SELECT ';DROP TABLE t'", Mode::ReadOnly, None), ("INSERT INTO t (a) VALUES (1)", Mode::ReadWrite, None), ("UPDATE t SET a = 1 WHERE id = 2", Mode::ReadWrite, None), ("DELETE FROM t WHERE id = 2", Mode::ReadWrite, None), // A predicate that narrows nothing is still a predicate: spec §8. ("DELETE FROM t WHERE 1 = 1", Mode::ReadWrite, None), ("CREATE TABLE t (a int)", Mode::ReadWrite, None), ("CREATE INDEX i ON t (a)", Mode::ReadWrite, None), ("ALTER TABLE t ADD COLUMN c int", Mode::ReadWrite, None), ( "DELETE FROM t", Mode::Full, Some(Destructive::UnfilteredDelete), ), ( "EXPLAIN ANALYZE DELETE FROM t", Mode::Full, Some(Destructive::UnfilteredDelete), ), ("DROP TABLE t", Mode::Full, Some(Destructive::Drop)), ("TRUNCATE TABLE t", Mode::Full, Some(Destructive::Truncate)), ("ALTER TABLE t DROP COLUMN c", Mode::Full, None), ("ALTER TABLE t RENAME TO u", Mode::Full, None), // The maximum over the operations, not the first. ( "ALTER TABLE t ADD COLUMN a int, DROP COLUMN b", Mode::Full, None, ), // The case tree-sitter got wrong, kept as a regression test. ("GRANT SELECT ON t TO u", Mode::Full, None), ("REVOKE SELECT ON t FROM u", Mode::Full, None), // Opaque bodies: dbdelve cannot see what these run. ("CALL p()", Mode::Full, None), // The maximum over the statements, not the first. ( "SELECT 1; DROP TABLE t", Mode::Full, Some(Destructive::Drop), ), // Read-only: Postgres holds the session to reads, so what the gate // cannot read the server still can. ("SELCT 1", Mode::ReadOnly, Some(Destructive::Unreadable)), ( "DO $$ BEGIN NULL; END $$", Mode::ReadOnly, Some(Destructive::Unreadable), ), // A normal thing to type at a SQLite database, and the crate does not // accept it under any dialect -- spec §3.4, and the reason shape C // exists at all. ( "PRAGMA table_info(t)", Mode::ReadOnly, Some(Destructive::Unreadable), ), ]; for (sql, mode, destructive) in cases { assert_eq!( classify(Engine::Postgres, sql), Verdict { mode: *mode, destructive: destructive.iter().copied().collect(), }, "{sql}" ); } } /// The single most likely bug in the feature: this parses as `Statement::Query`, /// so a match on the top-level variant calls a table-emptying statement a read. /// Spec §3.5. #[test] fn only_a_read_is_rerun_to_reload_its_rows() { assert!(rerunnable(Engine::Postgres, "SELECT * FROM t")); for sql in [ "INSERT INTO t VALUES (1) RETURNING *", "UPDATE t SET v = 1 RETURNING *", "WITH gone AS (DELETE FROM t RETURNING *) SELECT * FROM gone", "SELEC * FROM t", ] { assert!(!rerunnable(Engine::Postgres, sql), "{sql}"); } } #[test] fn only_a_lone_read_is_stopped_at_the_limit() { for engine in [ Engine::Postgres, Engine::MySql, Engine::MariaDb, Engine::Sqlite, Engine::Snowflake, Engine::SqlServer, ] { assert!(stoppable(engine, "SELECT * FROM t"), "{engine:?}"); assert!(stoppable(engine, "SELECT * FROM t;"), "{engine:?}"); assert!( stoppable(engine, "-- the big one\nSELECT * FROM t"), "{engine:?}" ); for sql in [ "SELECT * FROM t; COMMIT", "SET x = 1; SELECT * FROM t", "BEGIN; SELECT * FROM t; COMMIT", "SELECT 1; SELECT * FROM t", "UPDATE t SET v = 1", ] { assert!(!stoppable(engine, sql), "{engine:?}: {sql}"); } } assert!(!stoppable( Engine::SqlServer, "SELECT * FROM t\nSELECT * FROM u" )); // SQL Server caps a stoppable read with `SET ROWCOUNT`, which caps a // write just the same, so nothing that writes may get through. for sql in [ "SELECT * INTO #copy FROM t", "SELECT * INTO copy FROM t", "EXEC dbo.report", "EXECUTE dbo.report 1", "dbo.report", "INSERT INTO t SELECT * FROM u", "SELECT * FROM t; DELETE FROM t", "IF 1 = 1 DELETE FROM t", "BEGIN SELECT * FROM t; DELETE FROM t END", "WITH c AS (SELECT 1 AS a) DELETE FROM t", "MERGE t USING u ON t.id = u.id WHEN MATCHED THEN DELETE;", ] { assert!(!stoppable(Engine::SqlServer, sql), "{sql}"); } assert!(stoppable( Engine::SqlServer, "WITH c AS (SELECT 1 AS a) SELECT * FROM c" )); for (engine, sql) in [ ( Engine::Postgres, "SELECT set_config('search_path', 'other', false), * FROM t", ), (Engine::Postgres, "SELECT pg_advisory_lock(1), * FROM t"), (Engine::MySql, "SELECT GET_LOCK('held', 0), t.* FROM t"), (Engine::MySql, "SELECT @n := @n + 1, t.* FROM t"), ] { assert!(!stoppable(engine, sql), "{engine:?}: {sql}"); } assert!(stoppable(Engine::MongoDb, "db.accounts.find({})")); assert!(stoppable( Engine::MongoDb, "db.accounts\n .find({})\n .sort({a: 1})" )); assert!(!stoppable( Engine::MongoDb, "db.accounts.find({})\ndb.other.find({})" )); assert!(!stoppable( Engine::MongoDb, "db.accounts.aggregate([{$out: 'copy'}])" )); } /// Every MongoDB write returns a reply grid, so a restored one is offered /// Refresh only when this holds. #[test] fn a_mongo_write_is_never_rerun_to_reload_its_reply() { for sql in [ "db.accounts.find({})", "db.accounts.aggregate([{$match: {}}])", ] { assert!(rerunnable(Engine::MongoDb, sql), "{sql}"); } for sql in [ "db.accounts.insertOne({a: 1})", "db.accounts.updateOne({_id: 1}, {$set: {a: 2}})", "db.accounts.deleteOne({_id: 1})", "db.accounts.findOneAndUpdate({_id: 1}, {$set: {a: 2}})", "db.accounts.aggregate([{$out: 'copy'}])", "db.accounts.aggregate([{$merge: 'copy'}])", "db.accounts.find({}", ] { assert!(!rerunnable(Engine::MongoDb, sql), "{sql}"); } } #[test] fn classify_sees_through_data_modifying_ctes() { let delete = "WITH x AS (DELETE FROM t RETURNING *) SELECT * FROM x"; assert_eq!( classify(Engine::Postgres, delete), Verdict { mode: Mode::Full, destructive: vec![Destructive::UnfilteredDelete], } ); let insert = "WITH x AS (INSERT INTO t (a) VALUES (1) RETURNING *) SELECT * FROM x"; assert_eq!(classify(Engine::Postgres, insert).mode, Mode::ReadWrite); let update = "WITH x AS (UPDATE t SET a = 1 WHERE id = 2 RETURNING *) SELECT * FROM x"; assert_eq!(classify(Engine::Postgres, update).mode, Mode::ReadWrite); } /// The parenthesized option list is a second spelling of ANALYZE, and it /// runs the statement just as the keyword does: live-verified on Postgres /// 18.6, where the row was gone after a classification of ReadOnly. #[test] fn classify_reads_analyze_from_the_explain_option_list() { let cases = [ "EXPLAIN (ANALYZE) DELETE FROM t", "EXPLAIN (ANALYZE TRUE, COSTS FALSE) DELETE FROM t", "EXPLAIN (COSTS FALSE, ANALYZE ON) DELETE FROM t", "EXPLAIN (analyze true) DELETE FROM t", "EXPLAIN (ANALYSE) DELETE FROM t", "EXPLAIN (ANALYSE TRUE) DELETE FROM t", "EXPLAIN (ANALYSE on) DELETE FROM t", "EXPLAIN (VERBOSE, analyse 1) DELETE FROM t", "EXPLAIN ANALYSE DELETE FROM t", "EXPLAIN ANALYSE VERBOSE DELETE FROM t", ]; for engine in [Engine::Postgres, Engine::Generic] { for sql in cases { assert_eq!( classify(engine, sql), Verdict { mode: Mode::Full, destructive: vec![Destructive::UnfilteredDelete], }, "{engine:?} {sql}" ); } for sql in [ "EXPLAIN (ANALYZE FALSE) DELETE FROM t", "EXPLAIN (ANALYZE OFF) DELETE FROM t", "EXPLAIN (ANALYSE FALSE) DELETE FROM t", "EXPLAIN (COSTS TRUE) SELECT 1", ] { assert_eq!( classify(engine, sql).mode, Mode::ReadOnly, "{engine:?} {sql}" ); } } } /// MariaDB's Explain Analyze is `ANALYZE `, which runs the /// statement just as MySQL's `EXPLAIN ANALYZE` does. #[test] fn classify_reads_mariadb_analyze_by_the_statement_it_runs() { for sql in [ "ANALYZE SELECT * FROM t", " /* why */ analyze\nselect id from accounts where x = 1", "ANALYZE FORMAT=JSON SELECT * FROM t", "ANALYZE WITH x AS (SELECT 1) SELECT * FROM x", ] { assert_eq!(classify(Engine::MariaDb, sql), Verdict::READ, "{sql}"); assert!(rerunnable(Engine::MariaDb, sql), "{sql}"); } assert_eq!( classify(Engine::MariaDb, "ANALYZE DELETE FROM t"), classify(Engine::MySql, "EXPLAIN ANALYZE DELETE FROM t"), ); assert_eq!( classify(Engine::MariaDb, "ANALYZE DELETE FROM t"), Verdict::destroys(Destructive::UnfilteredDelete), ); for sql in [ "ANALYZE UPDATE t SET a = 1 WHERE id = 2", "ANALYZE FORMAT=JSON DELETE FROM t WHERE id = 2", "ANALYZE INSERT INTO t (a) VALUES (1)", "ANALYZE SELECT 1; UPDATE t SET a = 1 WHERE id = 2", ] { assert_eq!(classify(Engine::MariaDb, sql), Verdict::WRITE, "{sql}"); } // The table-statistics statement, which only an allowlist keeps from // reading as an EXPLAIN of the query `TABLE t`. for sql in [ "ANALYZE TABLE t", "ANALYZE NO_WRITE_TO_BINLOG TABLE t", "ANALYZE LOCAL TABLE t", "ANALYZE t", "ANALYZE FORMAT=JSON TABLE t", ] { assert_eq!( classify(Engine::MariaDb, sql), classify(Engine::MySql, sql), "{sql}" ); assert!(!rerunnable(Engine::MariaDb, sql), "{sql}"); } assert_eq!( classify(Engine::MySql, "ANALYZE SELECT * FROM t").destructive, vec![Destructive::Unreadable], ); } #[test] fn a_typed_explain_is_read_from_its_leading_words() { use ExplainMode::{Analyze, Plan}; let cases = [ (Engine::Postgres, "EXPLAIN SELECT 1", Some(Plan)), (Engine::Postgres, "explain verbose select 1", Some(Plan)), (Engine::Postgres, "EXPLAIN ANALYZE SELECT 1", Some(Analyze)), ( Engine::Postgres, "EXPLAIN ANALYSE VERBOSE SELECT 1", Some(Analyze), ), ( Engine::Postgres, "-- why\nEXPLAIN ANALYZE SELECT 1", Some(Analyze), ), ( Engine::Postgres, " /* why */ explain analyze select 1", Some(Analyze), ), ( Engine::Postgres, "EXPLAIN (ANALYZE, BUFFERS) SELECT 1", Some(Analyze), ), ( Engine::Postgres, "EXPLAIN (analyze true) SELECT 1", Some(Analyze), ), ( Engine::Postgres, "EXPLAIN (COSTS FALSE, ANALYZE ON) SELECT 1", Some(Analyze), ), ( Engine::Postgres, "EXPLAIN (ANALYZE false) SELECT 1", Some(Plan), ), ( Engine::Postgres, "EXPLAIN (ANALYZE OFF, BUFFERS) SELECT 1", Some(Plan), ), ( Engine::Postgres, "EXPLAIN (FORMAT TEXT, ANALYZE) SELECT 1", Some(Analyze), ), (Engine::Postgres, "EXPLAIN (FORMAT JSON) SELECT 1", None), ( Engine::Postgres, "EXPLAIN (ANALYZE, format yaml) SELECT 1", None, ), (Engine::Postgres, "EXPLAIN (FORMAT XML) SELECT 1", None), (Engine::Postgres, "SELECT 'EXPLAIN ANALYZE'", None), (Engine::Postgres, "ANALYZE t", None), (Engine::Postgres, "-- EXPLAIN\nSELECT 1", None), (Engine::MySql, "EXPLAIN ANALYZE SELECT 1", Some(Analyze)), ( Engine::MySql, "/* why */ explain analyze select 1", Some(Analyze), ), ( Engine::MySql, "EXPLAIN ANALYZE FORMAT=TREE SELECT 1", Some(Analyze), ), (Engine::MySql, "EXPLAIN FORMAT=TREE SELECT 1", Some(Plan)), (Engine::MySql, "explain format = tree select 1", Some(Plan)), (Engine::MySql, "EXPLAIN ANALYZE FORMAT=JSON SELECT 1", None), (Engine::MySql, "EXPLAIN FORMAT=JSON SELECT 1", None), // Tabular, a shape the plan pane does not read. (Engine::MySql, "EXPLAIN SELECT 1", None), (Engine::MySql, "EXPLAIN FORMAT=TRADITIONAL SELECT 1", None), (Engine::MySql, "EXPLAIN t", None), (Engine::MySql, "DESCRIBE SELECT 1", None), (Engine::MySql, "DESC t", None), // Both of MariaDB's are tabular. (Engine::MariaDb, "EXPLAIN SELECT 1", None), (Engine::MariaDb, "ANALYZE SELECT 1", None), (Engine::MariaDb, "ANALYZE FORMAT=JSON SELECT 1", None), (Engine::MariaDb, "ANALYZE TABLE t", None), (Engine::Sqlite, "EXPLAIN QUERY PLAN SELECT 1", Some(Plan)), ( Engine::Sqlite, "-- why\nexplain query plan select 1", Some(Plan), ), // Bytecode, not a plan. (Engine::Sqlite, "EXPLAIN SELECT 1", None), (Engine::Snowflake, "EXPLAIN SELECT 1", None), (Engine::SqlServer, "EXPLAIN SELECT 1", None), (Engine::MongoDb, "db.c.find({a: 1}).explain()", Some(Plan)), ( Engine::MongoDb, "db.c.find().explain('queryPlanner')", Some(Plan), ), (Engine::MongoDb, "db.c.find().explain(false)", Some(Plan)), ( Engine::MongoDb, "db.c.find().sort({a: 1}).explain('executionStats')", Some(Analyze), ), ( Engine::MongoDb, "db.c.aggregate([]).explain(\"allPlansExecution\")", Some(Analyze), ), ( Engine::MongoDb, "db.c.countDocuments({}).explain(true)", Some(Analyze), ), (Engine::MongoDb, "// why\ndb.c.find().explain()", Some(Plan)), (Engine::MongoDb, "db.c.find()", None), (Engine::MongoDb, "db.c.find().explain(); db.c.find()", None), ]; for (engine, sql, mode) in cases { assert_eq!(typed_explain(engine, sql), mode, "{engine:?} {sql}"); } } /// `TO STDOUT` hands rows to the client; a `PROGRAM` or file target runs a /// shell command or touches the server's filesystem. Live-verified on /// Postgres 18.6: both wrote a file on the server while classifying ReadOnly. #[test] fn classify_treats_server_side_copy_targets_as_full() { assert_eq!( classify(Engine::Postgres, "COPY (SELECT 1) TO STDOUT").mode, Mode::ReadOnly ); assert_eq!( classify(Engine::Postgres, "COPY t FROM STDIN").mode, Mode::ReadWrite ); for sql in [ "COPY (SELECT 1) TO PROGRAM 'touch /tmp/x'", "COPY (SELECT 1) TO '/tmp/x'", "COPY t FROM PROGRAM 'cat /etc/passwd'", "COPY t FROM '/tmp/x'", ] { assert_eq!(classify(Engine::Postgres, sql).mode, Mode::Full, "{sql}"); } } /// Four variants own a `Query` besides `Statement::Query`, and classifying /// any of them by its variant alone runs a DELETE from the mode that /// forbids it. The first two were verified against a live Postgres: three /// rows became zero, with no dialog. Spec §3.5. #[test] fn classify_sees_a_cte_wherever_the_query_hangs() { let cases = [ "COPY (WITH x AS (DELETE FROM t RETURNING a) SELECT a FROM x) TO STDOUT", "CREATE TABLE n AS WITH x AS (DELETE FROM t RETURNING a) SELECT a FROM x", "CREATE VIEW v AS WITH x AS (DELETE FROM t RETURNING a) SELECT a FROM x", "INSERT INTO n (a) WITH x AS (DELETE FROM t RETURNING a) SELECT a FROM x", ]; for sql in cases { assert_eq!( classify(Engine::Postgres, sql), Verdict { mode: Mode::Full, destructive: vec![Destructive::UnfilteredDelete], }, "{sql}" ); } } /// `SELECT … INTO` creates a table. It is `Statement::Query` over a /// `SetExpr::Select`, so only `Select.into` tells it apart from a read. #[test] fn select_into_is_a_write() { assert_eq!( classify(Engine::Postgres, "SELECT * INTO newt FROM t").mode, Mode::ReadWrite ); assert_eq!( classify(Engine::Postgres, "SELECT * FROM t").mode, Mode::ReadOnly ); } /// Every one of these parses as the variant a plain write does, one flag /// apart, and destroys what the object held before. #[test] fn classify_calls_replacing_a_data_holding_object_destructive() { let cases: &[(Engine, &str, Destructive)] = &[ ( Engine::Snowflake, "CREATE OR REPLACE TABLE t (a int)", Destructive::Drop, ), ( Engine::Snowflake, "CREATE OR REPLACE TABLE t AS SELECT 1 AS a", Destructive::Drop, ), ( Engine::Snowflake, "CREATE OR REPLACE SCHEMA s", Destructive::Drop, ), ( Engine::Snowflake, "CREATE OR REPLACE DATABASE d", Destructive::Drop, ), ( Engine::Snowflake, "CREATE OR REPLACE STAGE st", Destructive::Drop, ), ( Engine::Snowflake, "INSERT OVERWRITE INTO t SELECT * FROM u", Destructive::Truncate, ), ]; for (engine, sql, kind) in cases { assert_eq!( classify(*engine, sql), Verdict { mode: Mode::Full, destructive: vec![*kind], }, "{sql}" ); } for sql in [ "CREATE OR REPLACE VIEW v AS SELECT 1 AS a", "CREATE TABLE t (a int)", "CREATE SCHEMA s", "INSERT INTO t SELECT * FROM u", ] { assert_eq!(classify(Engine::Snowflake, sql), Verdict::WRITE, "{sql}"); } for engine in [Engine::Postgres, Engine::MySql] { assert_eq!( classify(engine, "CREATE OR REPLACE VIEW v AS SELECT 1"), Verdict::WRITE, "{engine:?}" ); assert_eq!( classify(engine, "CREATE TABLE t (a int)"), Verdict::WRITE, "{engine:?}" ); } } fn unreadable_at(mode: Mode) -> Verdict { Verdict { mode, destructive: vec![Destructive::Unreadable], } } #[test] fn generic_reads_as_unreadable_what_a_server_it_does_not_know_could_lex_otherwise() { for sql in [ "/* /* */ DELETE FROM t -- */", "/* /* */ SELECT 1 */", "/*! DELETE FROM t */ SELECT 1", r"SELECT '\'' ; DELETE FROM t; -- '", r#"SELECT "a\" FROM t"#, ] { assert_eq!( classify(Engine::Generic, sql), unreadable_at(Mode::ReadWrite), "{sql}" ); } for (sql, verdict) in [ ("/* a comment */ SELECT 1", Verdict::READ), ("SELECT '/* not a comment */', 'a\"b'", Verdict::READ), ("DELETE FROM t WHERE a = 1 -- /* \\", Verdict::WRITE), ] { assert_eq!(classify(Engine::Generic, sql), verdict, "{sql}"); } } #[test] fn generic_reads_as_unreadable_a_dollar_quote_db2_reads_as_a_name() { for sql in [ "SELECT * FROM (SELECT 1 FROM SYSIBM.SYSDUMMY1) T(\"$$\") WHERE 1 = $$; \ DELETE FROM DELVETEST.GATE WHERE ID=1 --$$", "SELECT * FROM (SELECT 1 FROM SYSIBM.SYSDUMMY1) T(\"$$\") WHERE 1 = $$; \ DELETE FROM DELVETEST.GATE --$$", "SELECT * FROM (SELECT 1 FROM SYSIBM.SYSDUMMY1) T(\"$$\") WHERE 1 = $$;\n\ DROP TABLE DELVETEST.GATE --$$", "SELECT * FROM (SELECT 1 FROM SYSIBM.SYSDUMMY1) T(\"$A$\") WHERE 1 = $a$; \ DELETE FROM DELVETEST.GATE WHERE ID=1 --$a$", "SELECT 1 FROM SYSIBM.SYSDUMMY1 WHERE 1 = $$; \ DELETE FROM DELVETEST.GATE WHERE ID=1; SELECT 1 FROM SYSIBM.SYSDUMMY1 $$", "SELECT $1$ ; DELETE FROM t WHERE id=1; SELECT $1$", ] { assert_eq!( classify(Engine::Generic, sql), unreadable_at(Mode::ReadWrite), "{sql}" ); } for sql in [ "SELECT '$$' FROM t", "SELECT \"a$$\" FROM t", "SELECT a$$ FROM t", "SELECT * FROM V$SESSION", "SELECT 1 /* $$ */", "-- $$\nSELECT 1", ] { assert_eq!(classify(Engine::Generic, sql), Verdict::READ, "{sql}"); } } #[test] fn generic_reads_as_unreadable_any_executable_comment() { for sql in [ "/*! SELECT $$ INTO OUTFILE '/tmp/x' FROM t AS $$ */", "/*!50000 SELECT $$ INTO OUTFILE '/tmp/x' FROM t AS $$ */", "/*! SELECT $$ ; DELETE FROM t ; SELECT $$ */", "SELECT 1 FROM t WHERE 1 = /*! $$ ; DELETE FROM t ; SELECT $$ */", "/*!\nSELECT $$ ; DELETE FROM t ; SELECT $$ */", "/*! SELECT $1$ ; DELETE FROM t ; SELECT $1$ */", "/*! SELECT \"a\\\" FROM t */", "/*! SELECT 1 /* /* */ DELETE FROM t -- */ */", "/*! DELETE FROM t */", "SELECT 1 /*!99999 ; DELETE FROM t */", "SELECT 1 /*! */", "SELECT 1 /*M! INTO OUTFILE '/tmp/x' */", "SELECT 1 /*M!100100 ; DELETE FROM t */", ] { assert_eq!( classify(Engine::Generic, sql), unreadable_at(Mode::ReadWrite), "{sql:?}" ); } for sql in [ "SELECT '/*!' FROM t", "SELECT 1 -- /*! $$ */", "SELECT 1 /* ! */", "SELECT 1 /* M! */", "SELECT '/*M!' FROM t", ] { assert_eq!(classify(Engine::Generic, sql), Verdict::READ, "{sql:?}"); } } /// A versioned comment runs on a server at or past its version and is a /// comment below it, and which server is behind the profile is not known /// here: a submission asks what either reading needs, so a write hidden by /// a version is never a read. #[test] fn a_versioned_comment_is_read_both_run_and_ignored() { for engine in [Engine::MySql, Engine::MariaDb] { for sql in [ // Run, an `EXPLAIN`; ignored, a delete. "/*!99999 EXPLAIN */ DELETE FROM t", "/*M!999999 EXPLAIN */ DELETE FROM t", // Run, a filtered delete; ignored, every row. "DELETE FROM t /*!99999 WHERE 1 = 0 */", "DELETE FROM t /*M!999999 WHERE 1 = 0 */", // Two floors: between them only the first runs. "/*!50000 EXPLAIN */ /*!99999 SELECT 1; */ DELETE FROM t", ] { let verdict = classify(engine, sql); assert!( verdict.destructive.contains(&Destructive::UnfilteredDelete), "{engine:?} {sql:?}: {verdict:?}" ); } // Where the readings agree, the comment changes nothing. assert_eq!( classify(engine, "SELECT 1 /*!40101 , 2 */ FROM t"), Verdict::READ, "{engine:?}" ); assert_eq!( classify( engine, "UPDATE t SET a = 1 /*!50000 , b = 2 */ WHERE id = 1" ), Verdict::WRITE, "{engine:?}" ); // A marker in a literal or a plain comment is not a comment. for sql in ["SELECT '/*!99999' FROM t", "SELECT 1 /* !99999 x */"] { assert_eq!(classify(engine, sql), Verdict::READ, "{engine:?} {sql:?}"); } } // The agent never takes the run reading's word for it. assert!(matches!( agent_gate( Engine::MySql, "/*!99999 EXPLAIN */ DELETE FROM t", Mode::Full ), AgentVerdict::Refuse(_) )); } #[test] fn mysql_dialect_reads_as_unreadable_a_comment_mariadb_runs() { // MySQL ignores the comment, but the server behind the profile may be // a MariaDB that runs it: read both ways, and unreadable. assert_eq!( classify( Engine::MySql, "SELECT 1 /*M!100100 INTO OUTFILE '/tmp/x' */" ), unreadable_at(Mode::ReadOnly) ); // What MySQL runs is the unfiltered delete, what MariaDB runs the // filtered one; the delete is named either way. for sql in [ "DELETE FROM t /*M! WHERE 1 = 0 */", "DELETE FROM t /*M!100100 WHERE */", "SELECT 1 /*M! ; DELETE FROM t */", ] { let verdict = classify(Engine::MySql, sql); assert_eq!(verdict.mode, Mode::Full, "{sql:?}"); for kind in [Destructive::UnfilteredDelete, Destructive::Unreadable] { assert!(verdict.destructive.contains(&kind), "{sql:?}: {verdict:?}"); } assert_eq!(verdict.destructive.len(), 2, "{sql:?}: {verdict:?}"); } // MariaDB runs what the comment holds, so it is read with it. assert_eq!( classify(Engine::MariaDb, "SELECT 1 /*M! ; DELETE FROM t */"), Verdict::destroys(Destructive::UnfilteredDelete) ); // sqlparser cannot read `INTO OUTFILE`, with or without the comment. assert_eq!( classify( Engine::MariaDb, "SELECT 1 /*M!100100 INTO OUTFILE '/tmp/x' */" ), unreadable_at(Mode::ReadOnly) ); assert_eq!( classify(Engine::MariaDb, "DELETE FROM t /*M! WHERE 1 = 0 */"), Verdict::WRITE ); for engine in [Engine::MariaDb, Engine::MySql] { assert_eq!(classify(engine, "SELECT 1 /* M! */"), Verdict::READ); } } #[test] fn generic_reads_as_unreadable_a_line_comment_a_lone_carriage_return_may_end() { for sql in [ "SELECT 1 -- x\r; DELETE FROM t WHERE id=1; --", "SELECT 1\r--\r; DELETE FROM t WHERE id=1", "SELECT 1; --\rDELETE FROM t WHERE id=1", "/*\r*/--\rDELETE FROM t WHERE id=1", "SELECT 1 /* x */ --\rDELETE FROM t WHERE id=1", "-- line one\n-- line two\rDELETE FROM t WHERE id=1", "-- line one\r\n-- line two\rDELETE FROM t WHERE id=1", "-- c\rDELETE FROM t WHERE id=1", "--\rDROP TABLE t", "--\rTRUNCATE t", "--\rCREATE TABLE zz (a int)", ] { assert_eq!( classify(Engine::Generic, sql), unreadable_at(Mode::ReadWrite), "{sql:?}" ); } for sql in [ "-- c\r\nSELECT 1", "SELECT 1 -- c\r", "SELECT 1\r\nFROM t\r\n", "SELECT 1\rFROM t", ] { assert_eq!(classify(Engine::Generic, sql), Verdict::READ, "{sql:?}"); } } /// DuckDB's tokenizer ends a `--` comment at a carriage return as well as a /// newline, and sqlparser's DuckDB dialect only at a newline, so /// `SELECT 1 -- c\r; DROP TABLE t` was a read to the classifier and a /// `DROP` to the server, run with no confirmation and, with no hold behind /// DuckDB's Read-only, in Read-only too. Snowflake's and SQL Server's lexers /// are not known to agree either. Postgres's dialect already ends the /// comment where Postgres does, and MySQL, MariaDB, SQLite and Turso end it /// at a newline as sqlparser does. #[test] fn a_line_comment_a_lone_carriage_return_may_end_is_unreadable_where_lexers_part() { let parted = [ "SELECT 1 --\rDROP TABLE t", "SELECT 1 -- c\r; DELETE FROM t WHERE id = 1", "--\rDELETE FROM t WHERE id = 1", "-- one\n-- two\rTRUNCATE t", ]; let agreed = ["-- c\r\nSELECT 1", "SELECT 1 -- c\r", "SELECT 1\rFROM t"]; for engine in [ Engine::DuckDb, Engine::Snowflake, Engine::SqlServer, Engine::Generic, ] { for sql in parted { let verdict = classify(engine, sql); assert!( verdict.destructive.contains(&Destructive::Unreadable), "{engine:?} {sql:?}: {verdict:?}" ); } for sql in agreed { assert_eq!(classify(engine, sql), Verdict::READ, "{engine:?} {sql:?}"); } } assert_eq!( classify( Engine::Postgres, "SELECT 1 -- c\r; DELETE FROM t WHERE id = 1" ), Verdict::WRITE ); assert_eq!( classify(Engine::Postgres, "-- one\n-- two\rTRUNCATE t"), Verdict::destroys(Destructive::Truncate) ); for engine in [ Engine::MySql, Engine::MariaDb, Engine::Sqlite, Engine::Turso, ] { for sql in parted[1..].iter().chain(&agreed) { assert_eq!(classify(engine, sql), Verdict::READ, "{engine:?} {sql:?}"); } } } /// Postgres holds Read-only with `default_transaction_read_only`, MySQL and /// MariaDB with the session's transaction access mode. A statement that /// lifts either lifts the hold, after which the server runs any write. #[test] fn a_statement_that_lifts_the_read_only_hold_is_a_write() { let postgres = [ "SET default_transaction_read_only = off", "SET default_transaction_read_only TO off", "SET SESSION default_transaction_read_only = 'off'", "SET LOCAL default_transaction_read_only = false", "SET default_transaction_read_only = DEFAULT", "SET \"default_transaction_read_only\" = off", "SET transaction_read_only = off", "RESET default_transaction_read_only", "RESET ALL", "DISCARD ALL", "BEGIN READ WRITE", "BEGIN TRANSACTION READ WRITE", "BEGIN ISOLATION LEVEL SERIALIZABLE, READ WRITE", "START TRANSACTION READ WRITE", "SET TRANSACTION READ WRITE", "SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE", "SELECT set_config('default_transaction_read_only', 'off', false)", "SELECT set_config('TRANSACTION_READ_ONLY', 'off', true), 1", "SELECT pg_catalog.set_config('default_transaction_read_only', 'off', false)", "SELECT set_config(name, 'off', false) FROM t", "SELECT set_config('default_transaction_' || 'read_only', 'off', false)", ]; let mysql = [ "SET transaction_read_only = 0", "SET transaction_read_only = OFF", "SET @@transaction_read_only = 0", "SET @@session.transaction_read_only = OFF", "SET SESSION transaction_read_only = 0", "SET GLOBAL transaction_read_only = 0", "SET tx_read_only = 0", "SET autocommit = 1, transaction_read_only = 0", "SET transaction_read_only = DEFAULT", "START TRANSACTION READ WRITE", "SET TRANSACTION READ WRITE", "SET SESSION TRANSACTION READ WRITE", ]; let lifts = |engines: &[Engine], cases: &[&str]| { for &engine in engines { for sql in cases { assert!( classify(engine, sql).mode >= Mode::ReadWrite, "{engine:?} {sql}: {:?}", classify(engine, sql) ); } } }; lifts(&[Engine::Postgres, Engine::Generic], &postgres); lifts(&[Engine::MySql, Engine::MariaDb, Engine::Generic], &mysql); for engine in [Engine::Postgres, Engine::MySql, Engine::MariaDb] { for sql in [ "BEGIN", "START TRANSACTION READ ONLY", "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE", "SET SESSION TRANSACTION READ ONLY", ] { assert_eq!(classify(engine, sql), Verdict::READ, "{engine:?} {sql}"); } // Setting a read-only setting on is not a lift, but a setting the // engine's `plain_settings` does not list is a write whatever it // is set to ([`set_verdict`]), which is stricter. for sql in [ "SET default_transaction_read_only = on", "SET transaction_read_only = 1", ] { assert_eq!(classify(engine, sql), Verdict::WRITE, "{engine:?} {sql}"); } } assert_eq!( classify(Engine::Postgres, "SET search_path = x"), Verdict::READ ); for engine in [Engine::MySql, Engine::MariaDb] { assert_eq!( classify(engine, "SET search_path = x"), Verdict::WRITE, "{engine:?}: not a setting this engine lists as plain" ); } for sql in [ "BEGIN READ ONLY", "SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY", ] { assert_eq!(classify(Engine::Postgres, sql), Verdict::READ, "{sql}"); } // Postgres's deny-list names `set_config` whatever it sets. assert_eq!( classify( Engine::Postgres, "SELECT set_config('search_path', 'x', false)" ), Verdict::WRITE ); } /// Advancing a sequence writes, and no engine's read-only hold stops it /// for every sequence: Postgres lets a temporary one advance in a read-only /// transaction, and Db2 reached through Generic holds nothing at all. #[test] fn advancing_a_sequence_is_a_write_on_every_engine() { let engines = Engine::ALL .into_iter() .filter(|engine| engine.syntax() == Syntax::Sql); for engine in engines { for sql in [ "SELECT nextval('s')", "SELECT setval('delvetest.seq', 100)", "SELECT pg_catalog.nextval('s')", "SELECT NEXTVAL(s)", "SELECT NEXT VALUE FOR s", "SELECT next value for s FROM t", "SELECT NEXTVAL FOR s FROM t", ] { assert!( classify(engine, sql).mode >= Mode::ReadWrite, "{engine:?} {sql}: {:?}", classify(engine, sql) ); } } // `s.NEXTVAL` only where the server spells an advance that way: Db2 // and Oracle behind Generic, and Snowflake. Anywhere else, and quoted // anywhere, it is a column. for engine in [Engine::Generic, Engine::Snowflake] { for sql in [ "SELECT s.NEXTVAL FROM SYSIBM.SYSDUMMY1", "SELECT DELVETEST.SEQ.NEXTVAL FROM SYSIBM.SYSDUMMY1", "SELECT a FROM t WHERE id = s.nextval", "VALUES (DELVETEST.SEQ.NEXTVAL)", "SET DELVETEST.VV = DELVETEST.SEQ.NEXTVAL", ] { assert!( classify(engine, sql).mode >= Mode::ReadWrite, "{engine:?} {sql}: {:?}", classify(engine, sql) ); } } for (engine, sql) in [ (Engine::MySql, "SELECT t.nextval FROM t"), (Engine::SqlServer, "SELECT t.nextval FROM t"), (Engine::Generic, "SELECT t.\"NEXTVAL\" FROM t"), ] { assert_eq!(classify(engine, sql), Verdict::READ, "{engine:?} {sql}"); } // Where the deny-list names `nextval`, its member form after a period // is read as the advance, quoted or not ([`MEMBER_FORMS`]): stricter. for (engine, sql) in [ (Engine::Postgres, "SELECT t.nextval FROM t"), (Engine::Postgres, "SELECT t.\"nextval\" FROM t"), (Engine::DuckDb, "SELECT t.nextval FROM t"), (Engine::Snowflake, "SELECT t.\"NEXTVAL\" FROM t"), ] { assert_eq!(classify(engine, sql), Verdict::WRITE, "{engine:?} {sql}"); } for engine in [Engine::Postgres, Engine::Generic] { assert_eq!( classify(engine, "SELECT \"nextval\"('s')").mode, Mode::ReadWrite, "{engine:?}" ); for sql in [ "SELECT currval('s')", "SELECT nextval_at, next, value FROM t", "SELECT 'nextval(1)' FROM t", "SELECT 1 -- nextval('s')", ] { assert_eq!(classify(engine, sql), Verdict::READ, "{engine:?} {sql}"); } } } /// A read-only transaction does not stop a backend being signalled, the /// configuration reloaded, or a statement sent down another connection. #[test] fn a_call_the_read_only_hold_does_not_stop_needs_full() { for engine in [Engine::Postgres, Engine::Generic] { for sql in [ "SELECT pg_terminate_backend(123)", "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = 'x'", "SELECT pg_cancel_backend(123)", "SELECT pg_catalog.pg_reload_conf()", "SELECT dblink_exec('dbname=x', 'DELETE FROM t')", "SELECT * FROM dblink('dbname=x', 'DELETE FROM t RETURNING 1') AS r(a int)", ] { assert_eq!(classify(engine, sql).mode, Mode::Full, "{engine:?} {sql}"); } } } /// Nothing on a Generic server holds Read-only, and what a function does /// cannot be read off its call, so a call to anything but a known /// side-effect-free built-in needs Read-write there. Built-in engines keep /// reading such a call as a read, since their hold stops what it writes. #[test] fn generic_read_only_refuses_a_call_to_a_function_it_does_not_know() { for sql in [ "SELECT delvetest.upd_f()", "SELECT upd_f()", "SELECT * FROM delvetest.upd_f()", "SELECT 1 WHERE delvetest.upd_f() = 1", "VALUES (delvetest.upd_f())", "SELECT * FROM TABLE(DELVETEST.UPD_TF())", "SELECT * FROM TABLE(DELVETEST.UPD_TF()) AS T", "SELECT COUNT(*) FROM TABLE(DELVETEST.UPD_TF()) x WHERE 1=0", "WITH t AS (SELECT * FROM TABLE(DELVETEST.UPD_TF()) x) SELECT * FROM t", "SET DELVETEST.VV = (SELECT COUNT(*) FROM TABLE(DELVETEST.UPD_TF()) x)", "SELECT myschema.upper(x) FROM t", "SELECT \"UPPER\"(x) FROM t", "SELECT count(upd_f()) FROM t", "SELECT 1 FROM t ORDER BY upd_f()", "SELECT 1 FROM t GROUP BY upd_f()", "SELECT * FROM t JOIN u ON upd_f() = 1", "SELECT CAST(upd_f() AS INT)", "SELECT CASE WHEN upd_f() = 1 THEN 1 END", "SELECT * FROM t WHERE x IN (SELECT upd_f())", "SELECT * FROM t WHERE EXISTS (SELECT 1 FROM u WHERE u.a = upd_f())", "SELECT 1 UNION SELECT upd_f()", "EXPLAIN ANALYZE SELECT upd_f()", ] { assert!( classify(Engine::Generic, sql).mode >= Mode::ReadWrite, "{sql}: {:?}", classify(Engine::Generic, sql) ); } for sql in [ "SELECT count(*), upper(x), coalesce(a, b), cast(x as int), current_date, \ substr(x, 1, 2) FROM t", "SELECT max(a), min(b), sum(c), avg(d), count(DISTINCT e) FROM t GROUP BY f", "SELECT lower(name), length(name), trim(name), round(v, 2), abs(v) FROM t", "SELECT row_number() OVER (ORDER BY a), lag(a) OVER (ORDER BY a) FROM t", "SELECT current_timestamp, year(d), nullif(a, b), concat(a, b) FROM t", "SELECT * FROM t WHERE upper(x) = 'A' AND replace(y, 'a', 'b') LIKE 'c%'", "SELECT extract(year FROM d), substring(x FROM 2), position('a' IN x) FROM t", ] { assert_eq!(classify(Engine::Generic, sql), Verdict::READ, "{sql}"); } for sql in [ "SELECT delvetest.upd_f()", "SELECT * FROM TABLE(DELVETEST.UPD_TF())", ] { assert_eq!(classify(Engine::Postgres, sql), Verdict::READ, "{sql}"); } } /// Db2 ends a query with its isolation clause, `WITH UR|CS|RS|RR`, and /// takes `VALUES 1` without parentheses, neither of which sqlparser's /// Generic dialect parses. They read as what they are, and whatever else /// the submission holds is read as strictly as ever. #[test] fn generic_reads_db2_isolation_clauses_and_bare_values() { for sql in [ "SELECT * FROM t WITH UR", "SELECT a FROM t WHERE b = 1 with cs;", "SELECT a FROM t ORDER BY a FETCH FIRST 5 ROWS ONLY WITH RS", "SELECT 1 FROM t WITH RR; SELECT 2 FROM u WITH UR", "VALUES 1", "VALUES 1, 2", "values current_date", "VALUES (1, 'a'), (2, 'b')", "VALUES upper('a'); SELECT 1 FROM t WITH UR", ] { assert_eq!(classify(Engine::Generic, sql), Verdict::READ, "{sql}"); } for (sql, verdict) in [ ( "SELECT 1 FROM t WITH UR; DELETE FROM t WHERE id = 1", Verdict::WRITE, ), ("DELETE FROM t WHERE id = 1 WITH UR", Verdict::WRITE), ( "VALUES 1; DROP TABLE t", Verdict::destroys(Destructive::Drop), ), ("VALUES upd_f()", Verdict::WRITE), ("VALUES DELVETEST.SEQ.NEXTVAL", Verdict::WRITE), ("SELECT upd_f() FROM t WITH UR", Verdict::WRITE), ] { assert_eq!(classify(Engine::Generic, sql), verdict, "{sql}"); } for sql in [ "SELECT * FROM t WITH RS USE AND KEEP EXCLUSIVE LOCKS", "SELECT * FROM t WITH UR UR", "SELECT * FROM t WITH \"UR\"", "VALUES", ] { assert_eq!( classify(Engine::Generic, sql), unreadable_at(Mode::ReadWrite), "{sql}" ); } } /// The filter bar's raw text is spliced into the preview, and the preview /// goes through the same gate: a call in it is read as it is anywhere. #[test] fn a_generic_preview_filter_calling_an_unknown_function_needs_read_write() { let preview = |filter: &str| { crate::explorer::preview_sql(Engine::Generic, "DELVETEST", "INJ", filter, Some(100), 0) }; for filter in [ "ID = DELVETEST.UPD_F()", "ID IN (SELECT C FROM TABLE(DELVETEST.UPD_TF()) T)", "ID = DELVETEST.SEQ.NEXTVAL", "ID = NEXT VALUE FOR DELVETEST.SEQ", ] { let sql = preview(filter); assert!( classify(Engine::Generic, &sql).mode >= Mode::ReadWrite, "{sql}: {:?}", classify(Engine::Generic, &sql) ); } let sql = preview("upper(V) = 'A'"); assert!(is_generated_select(Engine::Generic, &sql), "{sql}"); assert_eq!(classify(Engine::Generic, &sql), Verdict::READ, "{sql}"); } #[test] fn clickhouse_reads_its_own_dialect() { let ch = Engine::ClickHouse; for sql in [ "SELECT * FROM t FINAL", "SELECT * FROM t PREWHERE a = 1", "SELECT a FROM t ARRAY JOIN arr AS a", "SELECT * FROM t LIMIT 1 BY a", "SELECT arrayMap(x -> x + 1, [1, 2])", "WITH x AS (SELECT 1) SELECT * FROM x", "SHOW TABLES", "DESCRIBE TABLE t", "DESC t", "USE analytics", "SET max_threads = 1", "SELECT number FROM system.numbers", "SELECT * FROM url('http://example.test/x.csv', CSV)", ] { assert_eq!(classify(ch, sql), Verdict::READ, "{sql}"); } for sql in [ "SELECT 1 SETTINGS readonly = 0", "SELECT 1 FORMAT JSON", "WITH 1 AS x SELECT x", "EXISTS t", "EXISTS TABLE t", "EXPLAIN PIPELINE SELECT 1", "EXPLAIN AST ALTER TABLE t DELETE WHERE 1", "CHECK TABLE t", "WATCH lv", ] { let verdict = classify(ch, sql); assert_eq!(verdict, unreadable_at(Mode::ReadOnly), "{sql}"); assert_eq!(gate(&verdict, Mode::ReadOnly, &[]), Some(Stop::RunOnce)); } // Phase 1's `SET` rule: a setting not on `plain_settings` is stopped // in Read-only, though the server's `readonly=2` would refuse this one // on its own, because the verdict does not lean on the hold. assert_eq!(classify(ch, "SET readonly = 0"), Verdict::WRITE); assert_eq!( classify(ch, "CREATE TEMPORARY TABLE t (a Int32) ENGINE = Memory"), Verdict::WRITE ); } #[test] fn clickhouse_floors_what_it_cannot_parse_by_its_first_keyword() { let ch = Engine::ClickHouse; let words = FLOOR_READS .iter() .map(|word| (*word, Mode::ReadOnly)) .chain(FLOOR_FULL.iter().map(|word| (*word, Mode::Full))) .chain([ ("INSERT", Mode::ReadWrite), ("INSERT INTO FUNCTION", Mode::Full), ("INSERT INTO TABLE FUNCTION", Mode::Full), ("insert into /* c */ function", Mode::Full), ("DELETE", Mode::ReadWrite), ("UPDATE", Mode::ReadWrite), ("FROBNICATE", Mode::ReadWrite), ("`SELECT`", Mode::ReadWrite), ("(", Mode::ReadWrite), ]); for (word, mode) in words { for word in [word.to_owned(), word.to_lowercase()] { for lead in [ "", "-- c\n", "--c\r\n", "/* c */", "/* a /* b */ c */\n", " \t\n", ] { let sql = format!("{lead}{word} ) ("); let verdict = classify(ch, &sql); // sqlparser reads any `SHOW …` as a variable to show. let expected = match word.eq_ignore_ascii_case("SHOW") { true => Verdict::READ, false => unreadable_at(mode), }; assert_eq!(verdict, expected, "{sql:?}"); let stop = match mode { Mode::ReadOnly => verdict.destructive.first().map(|_| Stop::RunOnce), mode => Some(Stop::Upgrade(mode)), }; assert_eq!(gate(&verdict, Mode::ReadOnly, &[]), stop, "{sql:?}"); } } } // A tokenizer error is placed by the words before it, at Read-write // at least. for (sql, mode) in [ ( "/* unended BACKUP TABLE t TO Disk('b', 'x')", Mode::ReadWrite, ), ("SELECT 'unended", Mode::ReadWrite), ("SELECT `unended", Mode::ReadWrite), ("BACKUP TABLE t TO Disk('b', 'x') 'unended", Mode::Full), ( "SELECT 1; RESTORE TABLE t FROM Disk('b', 'x') `", Mode::Full, ), // Where the tokenizer stops, the server may read on. ( "SELECT a$$ PARALLEL WITH BACKUP TABLE t TO Disk('b', 'x')", Mode::Full, ), ( "SELECT `a\\`` PARALLEL WITH BACKUP TABLE t TO Disk('b', 'x')", Mode::Full, ), ("SELECT 1 /* \u{e9}", Mode::Full), ] { assert_eq!(classify(ch, sql), unreadable_at(mode), "{sql:?}"); } // The server's lexer and sqlparser's tokenizer part ways on these, so // a word the server runs may be one the tokenizer never sees: each // needs Full. let backup = "BACKUP TABLE t TO Disk('backups', 'review-poc')"; let restore = "RESTORE TABLE t FROM Disk('backups', 'review-poc')"; for sql in [ // `//` and `# ` comment to the server, and hide the quote that // opens a string to the tokenizer. format!("SELECT 1 // '\nPARALLEL WITH {backup} -- '"), format!("SELECT 1 // '\nPARALLEL WITH {restore} -- '"), format!("{backup} // '"), format!("SELECT 1 //* '\nPARALLEL WITH {backup} -- '"), format!("SELECT 1 #'\nPARALLEL WITH {backup} -- '"), "# c\nSELECT 1".to_owned(), "#!c\nSELECT 1".to_owned(), // A backslash escapes the backtick for the server alone, which // then reads the doubled one as the end of the name. format!("SELECT `a\\`` PARALLEL WITH {backup} -- `"), format!("SELECT \"a\\\"\" PARALLEL WITH {backup} -- \""), // `a$$` is one bare word to the server. format!("SELECT a$$ PARALLEL WITH {backup} --$$"), format!("SELECT 1 AS a$$ PARALLEL WITH {backup} --$$"), format!("SELECT $$x$$ PARALLEL WITH {backup}"), "SELECT $1".to_owned(), // A zero-width space is a space to the server. format!("SELECT 1 PARALLEL\u{200b}WITH {backup}"), format!("\u{200b}{backup}"), "\u{200b}SELECT 1".to_owned(), "\u{feff}SELECT 1".to_owned(), "INSERT INTO\u{200b}FUNCTION file('x') VALUES (1)".to_owned(), // Curly quotes are quotes to the server. format!("SELECT \u{2018}'\u{2019} PARALLEL WITH {backup} --'"), "SELECT caf\u{e9}".to_owned(), format!("-- c\r{backup}"), ] { assert_eq!(classify(ch, &sql), unreadable_at(Mode::Full), "{sql:?}"); } assert_eq!(classify(ch, "SELECT 4 / 2"), Verdict::READ); assert_eq!(classify(ch, "SELECT 4 / /* c */ 2"), Verdict::READ); // Inside a literal or a comment, none of them matters. for sql in [ "SELECT 'a#b$c\u{200b}\u{2018}\\'' AS x", "SELECT `a#b$c\u{200b}` FROM t", "SELECT 1 /* # $ \u{200b} ` \\ */", "-- # $ \u{200b}\nSELECT 1", "SELECT 1\u{a0}FROM t", ] { assert_eq!(classify(ch, sql), Verdict::READ, "{sql:?}"); } assert_eq!( classify(ch, "INSERT INTO\u{a0}FUNCTION file('x') VALUES (1)"), Verdict::FULL ); assert_eq!(classify(ch, "-- c\r\nSELECT 1"), Verdict::READ); assert_eq!( classify(ch, "/* /* */ */ BACKUP TABLE t TO Disk('b', 'x')"), unreadable_at(Mode::Full) ); } #[test] fn clickhouse_needs_full_for_what_writes_outside_the_database() { let ch = Engine::ClickHouse; for target in [ "url('http://example.test/x', CSV, 'a Int32')", "s3('http://example.test/b/x.csv')", "s3Cluster('c', 'http://example.test/b/x.csv')", "file('x.csv', 'CSV', 'a Int32')", "hdfs('hdfs://example.test/x', 'CSV', 'a Int32')", "remote('h', db.t)", "remoteSecure('h', db.t)", "mysql('h:3306', 'db', 't', 'u', 'p')", "postgresql('h:5432', 'db', 't', 'u', 'p')", "azureBlobStorage('c', 'x')", "gcs('http://example.test/x')", "mongodb('h', 'db', 'c', 'u', 'p', 'a Int32')", "odbc('dsn', 't')", "jdbc('dsn', 't')", "db.f('x')", ] { for into in ["INTO FUNCTION", "INTO TABLE FUNCTION", "into function"] { let sql = format!("INSERT {into} {target} VALUES (1)"); assert_eq!(classify(ch, &sql), Verdict::FULL, "{sql}"); let sql = format!("INSERT {into} {target} SELECT * FROM t"); assert_eq!(classify(ch, &sql), Verdict::FULL, "{sql}"); } // Unparseable, so the floor reads the same words. let sql = format!("INSERT INTO FUNCTION {target} SETTINGS a = 1 VALUES (1)"); assert_eq!(classify(ch, &sql), unreadable_at(Mode::Full), "{sql}"); } assert_eq!( classify(ch, "INSERT INTO `function` VALUES (1)"), Verdict::WRITE ); // No other dialect reads a table function as an insert's target: // Postgres's reads a table named `FUNCTION` aliased `url`, the rest // nothing at all, and the verdict each gave before stands. let insert = "INSERT INTO FUNCTION url('http://example.test/x') VALUES (1)"; for engine in Engine::ALL .into_iter() .filter(|engine| engine.syntax() == Syntax::Sql && *engine != ch) { let dialect = dialect(engine).unwrap(); let expected = match SqlParser::parse_sql(dialect.as_ref(), insert) { Ok(statements) => { assert!( matches!( statements.as_slice(), [Statement::Insert(Insert { table: TableObject::TableName(_), .. })] ), "{engine:?}" ); Verdict::WRITE } Err(_) => Verdict { mode: match engine.holds_read_only() { true => Mode::ReadOnly, false => Mode::ReadWrite, }, destructive: vec![Destructive::Unreadable], }, }; assert_eq!(classify(engine, insert), expected, "{engine:?}"); } for sql in [ "SELECT 1 INTO OUTFILE 'x'", "select 1 into outfile 'x' format CSV", "WITH x AS (SELECT 1) SELECT * FROM x INTO OUTFILE 'y'", "INSERT INTO t SELECT 1 INTO OUTFILE 'x'", "SELECT 1 PARALLEL WITH BACKUP TABLE t TO Disk('b', 'x')", ] { assert_eq!(classify(ch, sql), unreadable_at(Mode::Full), "{sql}"); } assert_eq!(classify(ch, "SELECT outfile FROM t"), Verdict::FULL); for engine in [ "URL('http://example.test/x', CSV)", "File(CSV)", "S3('http://example.test/b/x.csv')", "SQLite('x.db', 't')", "Kafka", "mergetree", "Distributed('one_shard_cluster', 'db', 'target')", "KeeperMap('/k')", "FrobMergeTree", ] { let sql = format!("CREATE TABLE t2 (a Int32) ENGINE = {engine}"); assert_eq!(classify(ch, &sql), Verdict::FULL, "{sql}"); } assert_eq!( classify( ch, "CREATE TABLE relay (x UInt8) ENGINE = Distributed('one_shard_cluster', 'db', \ 'target') AS SELECT 1" ), Verdict::FULL ); for family in [ "", "Replacing", "Summing", "Aggregating", "Collapsing", "VersionedCollapsing", "Graphite", "Coalescing", ] { for prefix in ["", "Replicated", "Shared"] { let sql = format!( "CREATE TABLE t2 (a Int32) ENGINE = {prefix}{family}MergeTree ORDER BY a" ); assert_eq!(classify(ch, &sql), Verdict::WRITE, "{sql}"); } } // `ON CLUSTER` runs it on every server of the cluster; a join on a // column named `cluster` is still a read. for sql in [ "CREATE TABLE t2 ON CLUSTER c (a Int32) ENGINE = MergeTree ORDER BY a", "CREATE DATABASE d ON CLUSTER c", "ALTER TABLE t ON CLUSTER c ADD COLUMN b Int32", "INSERT INTO t SELECT * FROM a JOIN b ON cluster = b.c", ] { assert_eq!(classify(ch, sql).mode, Mode::Full, "{sql}"); } assert_eq!( classify(ch, "SELECT * FROM a JOIN b ON cluster = b.c"), Verdict::READ ); // `SET DEFAULT ROLE` stores a user's roles; the other `SET`s change // the session. Phase 1's `SET` rule rates a role change, and a setting // not on `plain_settings`, above Read-only whatever the server's // `readonly=2` would refuse; `max_threads` is listed and stays a read. for sql in [ "SET DEFAULT ROLE NONE TO CURRENT_USER", "SET DEFAULT ROLE r TO u", "set default role all to u", "/* c */ SET DEFAULT ROLE ALL EXCEPT r TO u", ] { assert_eq!(classify(ch, sql).mode, Mode::Full, "{sql}"); } for sql in ["SET readonly = 0", "SET ROLE r"] { assert_eq!(classify(ch, sql).mode, Mode::ReadWrite, "{sql}"); } assert_eq!(classify(ch, "SET max_threads = 1").mode, Mode::ReadOnly); assert_eq!( classify(ch, "CREATE TABLE t2 ENGINE = File(CSV) AS SELECT 1"), Verdict::FULL ); for sql in [ "CREATE TABLE t2 (a Int32) ENGINE = MergeTree ORDER BY a", "CREATE TABLE t2 (a Int32) ENGINE = ReplicatedReplacingMergeTree('/x', '{r}') ORDER BY a", "CREATE TABLE t2 (a Int32) ENGINE = Memory", "CREATE TABLE t2 (a Int32)", "CREATE TABLE t2 AS SELECT 1", ] { assert_eq!(classify(ch, sql), Verdict::WRITE, "{sql}"); } // The engine list is ClickHouse's alone: MySQL's `ENGINE =` is read as // it always was. assert_eq!( classify(Engine::MySql, "CREATE TABLE t2 (a int) ENGINE = CSV"), Verdict::WRITE ); } #[test] fn a_clickhouse_mutation_is_classified_as_the_statement_it_amounts_to() { let spec = Engine::ClickHouse.spec(); let cases: &[(&str, Option<&str>)] = &[ ( "ALTER TABLE t UPDATE a = 1 WHERE b = 2", Some("UPDATE t SET a = 1 WHERE b = 2"), ), ( "ALTER TABLE t UPDATE a = 1, b = 'x' WHERE c = 3 SETTINGS mutations_sync = 2", Some("UPDATE t SET a = 1, b = 'x' WHERE c = 3"), ), ( "ALTER TABLE `db`.`t` DELETE WHERE a IN (1, 2) SETTINGS mutations_sync = 2;", Some("DELETE FROM `db`.`t` WHERE a IN (1, 2)"), ), ( "alter table t delete /* c */ where a = 1", Some("DELETE FROM t where a = 1"), ), ( "ALTER TABLE t UPDATE a = 1 WHERE b = 2, DROP COLUMN c", None, ), ("ALTER TABLE t DELETE WHERE 1, UPDATE a = 1 WHERE 1", None), ("ALTER TABLE t ON CLUSTER c DELETE WHERE a = 1", None), ("ALTER TABLE t UPDATE a = 1 IN PARTITION p WHERE 1", None), ("ALTER TABLE t DELETE IN PARTITION p WHERE 1", None), ( "ALTER TABLE t DELETE WHERE 1 SETTINGS mutations_sync = '2'", None, ), ( "ALTER TABLE t DELETE WHERE 1 SETTINGS max_threads = 1", None, ), ( "ALTER TABLE t DELETE WHERE 1 SETTINGS mutations_sync = 2, max_threads = 1", None, ), ("ALTER TABLE t UPDATE a = 1", None), ("ALTER TABLE t DELETE WHERE 1 RETURNING *", None), ("ALTER TABLE t MODIFY COLUMN a String", None), ("ALTER TABLE t DELETE WHERE 1; DROP TABLE t", None), ( "ALTER TABLE t DELETE WHERE a = '#$\\''", Some("DELETE FROM t WHERE a = '#$\\''"), ), ("ALTER TABLE `t\\`` DELETE WHERE 1 -- `", None), ("ALTER TABLE t DELETE WHERE a = 1 # c", None), ("ALTER TABLE t DELETE WHERE a = $$x$$", None), ( "ALTER TABLE t DELETE WHERE 1 PARALLEL\u{200b}WITH DROP TABLE t", None, ), ("DELETE FROM t WHERE a = 1", None), ]; for (sql, expected) in cases { assert_eq!(mutation_as_dml(spec, sql).as_deref(), *expected, "{sql}"); let verdict = classify(Engine::ClickHouse, sql); match expected { Some(_) => assert_eq!(verdict, Verdict::WRITE, "{sql}"), // Whatever does not re-spell takes `ALTER`'s floor. None if sql.starts_with("ALTER") => assert_eq!(verdict.mode, Mode::Full, "{sql}"), None => {} } } assert_eq!( classify( Engine::ClickHouse, "ALTER TABLE t ON CLUSTER c DELETE WHERE a = 1" ), unreadable_at(Mode::Full) ); assert_eq!( classify( Engine::ClickHouse, "ALTER TABLE t UPDATE a = 1 WHERE 1, DROP COLUMN c" ), unreadable_at(Mode::Full) ); assert_eq!( classify(Engine::ClickHouse, "SELECT 1; ALTER TABLE t DELETE WHERE 1"), Verdict::WRITE ); for engine in [Engine::MySql, Engine::Postgres, Engine::DuckDb] { assert_eq!( mutation_as_dml(engine.spec(), "ALTER TABLE t DELETE WHERE a = 1"), None ); } } #[test] fn clickhouse_writes_and_several_statements_need_what_their_worst_needs() { let ch = Engine::ClickHouse; for sql in [ "INSERT INTO t SELECT * FROM s", "INSERT INTO t WITH x AS (SELECT 1) SELECT * FROM x", "WITH x AS (SELECT 1) INSERT INTO t SELECT * FROM x", "CREATE TABLE t2 AS SELECT * FROM t", "DELETE FROM t WHERE a = 1", "UPDATE t SET a = 1 WHERE b = 2", "ALTER TABLE t DELETE WHERE a = 1", ] { assert_eq!(classify(ch, sql), Verdict::WRITE, "{sql}"); } assert_eq!( classify(ch, "INSERT INTO t SETTINGS async_insert = 1 VALUES (1)"), unreadable_at(Mode::ReadWrite) ); assert_eq!( classify(ch, "DELETE FROM t ON CLUSTER c WHERE a = 1"), unreadable_at(Mode::Full) ); assert_eq!( classify(ch, "SELECT 1; DROP TABLE t"), Verdict::destroys(Destructive::Drop) ); assert_eq!( classify(ch, "SELECT 1; SELECT 1 FORMAT JSON"), unreadable_at(Mode::ReadOnly) ); assert_eq!( classify( ch, "SELECT 1 SETTINGS readonly = 0; BACKUP TABLE t TO Disk('b', 'x')" ), unreadable_at(Mode::Full) ); assert_eq!( classify(ch, "SELECT 1 FROM t; DROP TABLE t SYNC"), unreadable_at(Mode::Full) ); // `EXPLAIN` never runs its statement on ClickHouse. assert_eq!( classify(ch, "EXPLAIN INSERT INTO t SELECT 1"), Verdict::READ ); assert_eq!( classify(ch, "EXPLAIN DELETE FROM t WHERE a = 1"), Verdict::READ ); for sql in [ "SYSTEM SHUTDOWN", "KILL QUERY WHERE 1", "BACKUP TABLE t TO Disk('b', 'x')", "RESTORE TABLE t FROM Disk('b', 'x')", "REPLACE TABLE t AS SELECT 1", "ATTACH TABLE t", ] { assert_eq!(classify(ch, sql), unreadable_at(Mode::Full), "{sql}"); } assert_eq!(classify(ch, "OPTIMIZE TABLE t FINAL"), Verdict::FULL); } #[test] fn a_clickhouse_statement_is_rerun_stopped_and_kept_by_what_it_is() { let ch = Engine::ClickHouse; for sql in [ "SELECT number FROM system.numbers", "SELECT number FROM system.numbers FORMAT JSON", "SELECT number FROM system.numbers SETTINGS max_threads = 1", "SELECT * FROM t FINAL PREWHERE a = 1", ] { assert!(stoppable(ch, sql), "{sql}"); } for sql in [ "SELECT 1 FORMAT JSON", "SELECT 1 SETTINGS readonly = 0", "SELECT 1; SELECT 2", "ALTER TABLE t DELETE WHERE 1", "SELECT number FROM system.numbers INTO OUTFILE 'x'", ] { assert!(!stoppable(ch, sql), "{sql}"); } assert!(rerunnable(ch, "SELECT * FROM t LIMIT 1 BY a")); assert!(!rerunnable(ch, "SELECT 1 FORMAT JSON")); assert!(!rerunnable(ch, "ALTER TABLE t UPDATE a = 1 WHERE 1")); assert!(!rerunnable(ch, "INSERT INTO FUNCTION file('x') VALUES (1)")); assert!(plain_read(ch, "SELECT arrayMap(x -> x + 1, [1, 2])")); for sql in ["SHOW TABLES", "SET max_threads = 1", "SELECT 1 FORMAT JSON"] { assert!(!plain_read(ch, sql), "{sql}"); } let settings = |sql: &str| leaves(ch, sql).settings; for sql in [ "SET max_threads = 1", "USE analytics", "SET max_threads = 1 SETTINGS x", "CREATE TEMPORARY TABLE t (a Int32) ENGINE = Memory", ] { assert!(settings(sql), "{sql}"); } for sql in [ "SELECT 1", "SELECT 1 SETTINGS max_threads = 1", "ALTER TABLE t DELETE WHERE 1", ] { assert!(!settings(sql), "{sql}"); } assert_eq!(leaves(ch, "BEGIN").transaction, Some(true)); } /// One AST, three dialects. Two statements genuinely differ and are asserted as /// differing rather than skipped. #[test] fn classify_agrees_across_engines() { for engine in [Engine::Postgres, Engine::MySql, Engine::Sqlite] { assert_eq!( classify(engine, "SELECT 1").mode, Mode::ReadOnly, "{engine:?}" ); assert_eq!( classify(engine, "DROP TABLE t").destructive, vec![Destructive::Drop], "{engine:?}" ); assert_eq!( classify(engine, "DELETE FROM t").destructive, vec![Destructive::UnfilteredDelete], "{engine:?}" ); } // CREATE FUNCTION parses only under Postgres, where its opaque body makes // it Full outright; elsewhere it is unreadable, which is Full too but by a // different route and with a different dialog. let create_function = "CREATE FUNCTION f() RETURNS int AS $$ SELECT 1 $$"; assert_eq!( classify(Engine::Postgres, create_function), Verdict { mode: Mode::Full, destructive: Vec::new(), } ); assert_eq!( classify(Engine::MySql, create_function).destructive, vec![Destructive::Unreadable] ); // COMMENT ON is the other measured divergence: a write on Postgres, and // syntax the crate does not accept under the other two dialects. let comment = "COMMENT ON TABLE t IS 'hello'"; assert_eq!(classify(Engine::Postgres, comment).mode, Mode::ReadWrite); for engine in [Engine::MySql, Engine::Sqlite] { assert_eq!( classify(engine, comment).destructive, vec![Destructive::Unreadable], "{engine:?}" ); } } /// What `restore_profile` reads off disk. A slug this build does not have /// must be answerable, not fatal -- the alternative was one unknown value /// costing the user every connection in the file. #[test] fn a_stored_slug_this_build_cannot_read_is_answerable() { for mode in Mode::ALL { assert_eq!(Mode::from_slug(mode.slug()), Some(mode)); } assert_eq!(Mode::from_slug("read-append"), None); for kind in Destructive::SUPPRESSIBLE { assert_eq!(Destructive::from_slug(kind.slug()), Some(kind)); } assert_eq!(Destructive::from_slug("shred"), None); // Never silenceable however it got written there, which is also what // keeps `Destructive::label` from ever being asked about it. assert_eq!(Destructive::from_slug(Destructive::Unreadable.slug()), None); } #[test] fn unreadable_is_never_suppressible() { assert!(!Destructive::Unreadable.suppressible()); assert!(Destructive::Drop.suppressible()); } #[test] fn the_gate_offers_exactly_the_mode_a_statement_needs() { let write = Verdict { mode: Mode::ReadWrite, destructive: Vec::new(), }; let drop = Verdict { mode: Mode::Full, destructive: vec![Destructive::Drop], }; assert_eq!(gate(&Verdict::READ, Mode::ReadOnly, &[]), None); assert_eq!( gate(&write, Mode::ReadOnly, &[]), Some(Stop::Upgrade(Mode::ReadWrite)) ); // Full, not Read-write: offering an intermediate mode that still refuses is // a second dialog dressed as a first. assert_eq!( gate(&drop, Mode::ReadOnly, &[]), Some(Stop::Upgrade(Mode::Full)) ); assert_eq!(gate(&write, Mode::ReadWrite, &[]), None); assert_eq!( gate(&drop, Mode::Full, &[]), Some(Stop::Confirm(Destructive::Drop)) ); assert_eq!(gate(&drop, Mode::Full, &[Destructive::Drop]), None); // Per kind: silencing DROP says nothing about TRUNCATE. assert_eq!( gate(&drop, Mode::Full, &[Destructive::Truncate]), Some(Stop::Confirm(Destructive::Drop)) ); } /// One silenced kind must not mask another. With DROP silenced, /// `DROP TABLE a; TRUNCATE TABLE b` used to gate to None and run both -- /// and the TRUNCATE had never been confirmed on that connection. #[test] fn a_silenced_kind_does_not_silence_the_one_beside_it() { let both = classify(Engine::Postgres, "DROP TABLE a; TRUNCATE TABLE b"); assert_eq!( both.destructive, vec![Destructive::Drop, Destructive::Truncate] ); assert_eq!( gate(&both, Mode::Full, &[Destructive::Drop]), Some(Stop::Confirm(Destructive::Truncate)) ); // One kind at a time, in the order the submission carries them. assert_eq!( gate(&both, Mode::Full, &[]), Some(Stop::Confirm(Destructive::Drop)) ); assert_eq!( gate( &both, Mode::Full, &[Destructive::Drop, Destructive::Truncate] ), None ); } #[test] fn an_unreadable_statement_never_offers_a_mode_and_never_goes_quiet() { // Not Upgrade, in any mode: a typo must never ask to raise a connection to // Full in order to receive a syntax error. for engine in [Engine::Postgres, Engine::MySql] { let unreadable = classify(engine, "UNDROP TABLE t"); for mode in Mode::ALL { assert_eq!( gate(&unreadable, mode, &[]), Some(Stop::RunOnce), "{engine:?} {mode:?}" ); } } let unreadable = classify(Engine::Postgres, "SELCT 1"); // Not suppressible even if something contrived writes it into the list. assert_eq!( gate(&unreadable, Mode::Full, &[Destructive::Unreadable]), Some(Stop::RunOnce) ); } #[test] fn the_opt_in_runs_the_unreadable_but_never_past_the_mode() { let held = classify(Engine::Postgres, "SELCT 1"); let unheld = classify(Engine::Sqlite, "PRAGMA table_info(t)"); for mode in Mode::ALL { assert_eq!(gate_own_run(&held, mode, &[], true), None, "{mode:?}"); assert_eq!( gate_own_run(&held, mode, &[], false), gate(&held, mode, &[]) ); } assert_eq!( gate_own_run(&unheld, Mode::ReadOnly, &[], true), Some(Stop::Upgrade(Mode::ReadWrite)) ); assert_eq!(gate_own_run(&unheld, Mode::ReadWrite, &[], true), None); assert_eq!( gate_own_run( &classify(Engine::Postgres, "DROP TABLE t"), Mode::Full, &[], true ), Some(Stop::Confirm(Destructive::Drop)) ); } /// With no server-side hold behind Read-only, a statement the gate cannot /// read could write with nothing to stop it -- and each of these can. #[test] fn read_only_refuses_what_it_cannot_read_where_the_server_would_not() { let cases: &[(Engine, &str)] = &[ (Engine::Snowflake, "UNDROP TABLE t"), (Engine::Snowflake, "PUT file:///tmp/a.csv @st"), (Engine::Sqlite, "PRAGMA table_info(t)"), ]; for (engine, sql) in cases { let verdict = classify(*engine, sql); assert_eq!(verdict.destructive, vec![Destructive::Unreadable], "{sql}"); assert_eq!( gate(&verdict, Mode::ReadOnly, &[]), Some(Stop::Upgrade(Mode::ReadWrite)), "{sql}" ); for mode in [Mode::ReadWrite, Mode::Full] { assert_eq!(gate(&verdict, mode, &[]), Some(Stop::RunOnce), "{sql}"); } assert!(!rerunnable(*engine, sql), "{sql}"); } assert!(!rerunnable(Engine::Postgres, "SELCT 1")); // A scripting block parses, and is as dangerous as what it holds. assert_eq!( classify(Engine::Snowflake, "BEGIN DELETE FROM t; END").destructive, vec![Destructive::UnfilteredDelete] ); assert_eq!( classify(Engine::Snowflake, "BEGIN SELECT 1; END"), Verdict::READ ); assert_eq!(classify(Engine::Snowflake, "BEGIN"), Verdict::READ); assert_eq!( classify( Engine::Snowflake, "BEGIN SELECT 1; EXCEPTION WHEN OTHER THEN DELETE FROM t; END" ), Verdict::FULL ); // This one parses, and its opaque body makes it Full like `CALL`. assert_eq!( classify( Engine::Snowflake, "EXECUTE IMMEDIATE $$ BEGIN DELETE FROM t; END $$" ), Verdict::FULL ); } #[test] fn a_comment_the_user_wrote_survives_formatting() { // The whole reason formatting is token-level: an AST round trip would // drop this line, and the user would not get it back. let formatted = format( Engine::Postgres, "select a -- the one we care about\nfrom t", ) .unwrap(); assert!( formatted.contains("-- the one we care about"), "{formatted}" ); } // sqlformat reflows the inside of a `$$` body, which edits the literal // rather than its layout. Refusing the buffer is the only answer that keeps // hard rule 1; this is the test that catches the day that stops being true. #[test] fn a_buffer_holding_a_dollar_quoted_body_is_refused() { assert!(format(Engine::Postgres, "DO $$ BEGIN DELETE FROM t; END $$").is_err()); assert!(format(Engine::Postgres, "select $tag$ x; y $tag$").is_err()); } // A placeholder is not a quote, and reading it as one would refuse to format // every parameterised statement anybody writes. #[test] fn a_numbered_placeholder_still_formats() { assert!(format(Engine::Postgres, "select a from t where id = $1").is_ok()); } #[test] fn formatting_an_already_formatted_statement_changes_nothing() { let once = format(Engine::Postgres, "select a, b from t where x = 1").unwrap(); assert_eq!(format(Engine::Postgres, &once).unwrap(), once); } #[test] fn sql_server_formatting_keeps_bracketed_names_and_go_lines() { let sql = "select [my col] from t\nGO 5\nselect 2\ngo\n"; let formatted = format(Engine::SqlServer, sql).unwrap(); assert!(formatted.contains("[my col]"), "{formatted}"); assert!(formatted.contains("\nGO 5\n"), "{formatted}"); assert_eq!(go_lines(&formatted).len(), 2, "{formatted}"); assert_eq!(format(Engine::SqlServer, &formatted).unwrap(), formatted); } #[test] fn formatting_keeps_the_text_between_statements_as_written() { let sql = "\n select a,b from t; -- why\n\n\n-- next\nselect 2;\n"; let formatted = format(Engine::Postgres, sql).unwrap(); assert_eq!( formatted, "\nselect\n a,\n b\nfrom\n t; -- why\n\n\n-- next\nselect\n 2;\n" ); } #[test] fn statements_on_one_line_are_formatted_onto_lines_of_their_own() { assert_eq!( format(Engine::Postgres, "select 1; select 2").unwrap(), "select\n 1;\nselect\n 2" ); } // `Buffer`'s split does not read `\'`, and would cut this literal at its // `;`, or run the rest of the buffer into one statement after it. #[test] fn a_backslash_escaped_literal_keeps_its_text_and_the_lines_after_it_on_mysql() { let sql = "select 1;\n\ninsert into t values ('Don\\'t; be late');\n\n\n-- keep\nselect 3;"; assert_eq!( format(Engine::MySql, sql).unwrap(), "select\n 1;\n\ninsert into\n t\nvalues\n ('Don\\'t; be late');\n\n\n-- keep\nselect\n 3;" ); } #[test] fn an_indented_statement_comes_back_flush() { assert_eq!( format(Engine::Postgres, "select 1;\n select a from t;").unwrap(), "select\n 1;\nselect\n a\nfrom\n t;" ); } #[test] fn a_respaced_token_is_refused_rather_than_formatted() { assert!(format(Engine::Sqlite, "select [my col] from t").is_err()); assert!(format(Engine::MySql, "select 0x0A").is_err()); } #[test] fn a_selection_cutting_through_a_literal_or_comment_is_refused() { let sql = "insert into t values ('line one\nline two');\n/* a b */ select 1;"; let from = |text: &str| sql.find(text).unwrap(); // Line by line through a literal that spans two. assert!( format_selection(Engine::Postgres, sql, from("line two")..from(";\n/*")).is_err() ); assert!(format_selection(Engine::Postgres, sql, from("b */")..sql.len()).is_err()); assert!(format_selection(Engine::Postgres, sql, from("ect 1")..sql.len()).is_err()); assert_eq!( format_selection(Engine::Postgres, sql, from("/*")..sql.len()).unwrap(), "/* a b */ select\n 1;" ); } #[test] fn a_selection_inside_a_dollar_quoted_body_is_refused() { for engine in [Engine::Postgres, Engine::Snowflake] { let sql = "select $$hello world$$"; let start = sql.find("hello").unwrap(); assert!(format_selection(engine, sql, start..start + 13).is_err()); } } #[test] fn a_selection_beside_a_dollar_quoted_body_formats() { let sql = "create function f() returns int as $$ select 1 $$ language sql;\n\nselect a,b from t;"; let start = sql.find("select a").unwrap(); assert_eq!( format_selection(Engine::Postgres, sql, start..sql.len()).unwrap(), "select\n a,\n b\nfrom\n t;" ); } #[test] fn a_comment_ahead_of_an_indented_statement_stays() { assert_eq!( format(Engine::Postgres, "select 1;\n/* c */ select 2;").unwrap(), "select\n 1;\n/* c */ select\n 2;" ); } #[test] fn a_mongodb_selection_cutting_through_a_comment_is_refused() { let sql = "// old: db.t.find({a: 1})\ndb.t.find({b: 2})"; let inside = sql.find("db.t").unwrap(); let next = sql.rfind("db.t").unwrap(); assert!(format_selection(Engine::MongoDb, sql, inside..sql.len()).is_err()); assert!(format_selection(Engine::MongoDb, sql, next..sql.len()).is_ok()); } #[test] fn only_the_text_up_to_a_selection_must_tokenize() { let sql = "select 1 from t;\nselect 'unfinished"; assert!(format_selection(Engine::Postgres, sql, 0..16).is_ok()); } #[test] fn a_flat_statement_gains_line_breaks() { let formatted = format(Engine::Postgres, "select a, b from t where x = 1").unwrap(); assert!(formatted.lines().count() > 1, "{formatted}"); assert!(formatted.contains(" "), "{formatted}"); } #[test] fn a_query_calling_on_its_session_is_no_plain_read() { for (engine, statement) in [ (Engine::Postgres, "SELECT nextval('s')"), ( Engine::Postgres, "SELECT pg_catalog.currval('s'), lastval()", ), (Engine::Postgres, "SELECT setval('s', 5)"), ( Engine::Postgres, "SELECT set_config('search_path', 'x', false)", ), (Engine::Postgres, "SELECT pg_advisory_lock(1)"), (Engine::Postgres, "SELECT pg_try_advisory_xact_lock(1)"), (Engine::MySql, "SELECT @x := 1"), (Engine::MariaDb, "SELECT @n := @n + 1 FROM t"), (Engine::MySql, "SELECT LAST_INSERT_ID()"), (Engine::MySql, "SELECT GET_LOCK('a', 10)"), (Engine::MySql, "SELECT RELEASE_LOCK('a')"), (Engine::SqlServer, "SELECT SCOPE_IDENTITY()"), (Engine::SqlServer, "SELECT @@IDENTITY"), ] { assert!(!plain_read(engine, statement), "{statement}"); } assert!(plain_read(Engine::Postgres, "SELECT nextval FROM t")); assert!(plain_read(Engine::MySql, "SELECT @x, 1")); assert!(plain_read(Engine::SqlServer, "SELECT @@VERSION")); } #[test] fn an_opening_unread_or_amid_other_statements_leaves_the_transaction_uncertain() { for statement in [ "BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ WRITE DEFERRABLE", "START TRANSACTION READ ONLY NOT DEFERRABLE", "BEGIN\nselec 1", ] { assert_eq!(leaves(Engine::Postgres, statement).transaction, None); assert!( transaction_uncertain(Engine::Postgres, statement), "{statement}" ); } for statement in [ "BEGIN;\nUPDATE t SET a = 1;\nCOMMIT", "UPDATE t SET a = 1; COMMIT", ] { assert!( transaction_uncertain(Engine::Postgres, statement), "{statement}" ); } for statement in [ "BEGIN", "COMMIT", "SELECT 1", "SELECT 1; SELECT 2", "selec 1", "SELECT * FROM t START WITH a = 1 CONNECT BY PRIOR a = b", "DO $$ BEGIN NULL; END $$", ] { assert!( !transaction_uncertain(Engine::Postgres, statement), "{statement}" ); } } #[test] fn only_an_open_transaction_or_a_changed_session_is_left_behind() { let open = Leaves { transaction: Some(true), settings: false, }; let closed = Leaves { transaction: Some(false), settings: false, }; let settings = Leaves { transaction: None, settings: true, }; for (engine, statement, left) in [ (Engine::Postgres, "BEGIN", &open), (Engine::Postgres, "START TRANSACTION", &open), (Engine::MySql, "START TRANSACTION", &open), (Engine::SqlServer, "BEGIN TRANSACTION", &open), (Engine::Postgres, "COMMIT", &closed), (Engine::Postgres, "END", &closed), (Engine::MySql, "ROLLBACK", &closed), (Engine::DuckDb, "ROLLBACK", &closed), (Engine::Postgres, "COMMIT AND CHAIN", &open), ( Engine::Postgres, "BEGIN; UPDATE t SET a = 1; COMMIT", &closed, ), (Engine::Postgres, "SET search_path TO other", &settings), ( Engine::MySql, "SET autocommit = 1, transaction_read_only = 0", &settings, ), (Engine::MySql, "SET @x = 1", &settings), (Engine::MySql, "USE other", &settings), (Engine::SqlServer, "SET NOCOUNT ON", &settings), ( Engine::Postgres, "CREATE TEMPORARY TABLE t (a int)", &settings, ), (Engine::SqlServer, "CREATE TABLE #t (a int)", &settings), (Engine::SqlServer, "SELECT * INTO #t FROM s", &settings), (Engine::MySql, "SELECT 1 INTO @x", &settings), (Engine::Sqlite, "PRAGMA foreign_keys = OFF", &settings), ( Engine::Postgres, "SELECT set_config('search_path', 'other', false)", &settings, ), (Engine::Postgres, "SELECT pg_advisory_lock(1)", &settings), (Engine::MySql, "SELECT GET_LOCK('a', 10)", &settings), (Engine::MySql, "SELECT @x := 1", &settings), ] { assert_eq!(&leaves(engine, statement), left, "{statement}"); } for (engine, statement) in [ (Engine::Postgres, "SELECT 1"), (Engine::Postgres, "SHOW search_path"), (Engine::MySql, "DESCRIBE t"), (Engine::Postgres, "EXPLAIN SELECT 1"), (Engine::Postgres, "SELEC 1"), (Engine::Postgres, "INSERT INTO t VALUES (1)"), (Engine::MySql, "CREATE TABLE t (a int)"), (Engine::Postgres, "SELECT * INTO t2 FROM t"), (Engine::Postgres, "ROLLBACK TO SAVEPOINT a"), (Engine::Sqlite, "PRAGMA table_info(t)"), (Engine::Snowflake, "BEGIN"), (Engine::MongoDb, "db.a.insertOne({ x: 1 })"), ] { assert_eq!(leaves(engine, statement), Leaves::default(), "{statement}"); } } /// A row named by every value, over hostile names and values, is written /// on each of the six engines that verify as statements the gate admits, /// each read again by a read cut from it that the read gate admits too. #[test] fn a_keyless_rows_writes_with_hostile_names_and_values_pass_the_gates_and_read_back() { let engines = [ Engine::Postgres, Engine::MySql, Engine::MariaDb, Engine::Sqlite, Engine::DuckDb, Engine::SqlServer, ]; // Each hostile part alone, over an otherwise plain row, so a refusal // names what it refused. let tables = ["birds", "we\"ird", "back`tick", "it's", "dou\"\"bled"]; let columns = ["bird", "we\"ird", "back`tick", "it's", "dou\"\"bled", "[b]"]; let values = [ "wren", "we\"ird", "it's", "x''y", "back`tick", "a\\b", "a\\'b", "N'x'", ]; let (mut admitted, mut unread) = (Vec::new(), Vec::new()); for engine in engines { let schema = match engine { Engine::Sqlite => "main", Engine::SqlServer => "dbo", _ => "public", }; let cases = tables .iter() .map(|table| (*table, "bird", "wren")) .chain(columns.iter().map(|column| ("birds", *column, "wren"))) .chain(values.iter().map(|value| ("birds", "bird", *value))); for (table, column, value) in cases { let keys = [(column, value), ("place", "oak")]; let delete = delete_row_matching(engine, schema, table, &keys, &["gone"], &[]) .unwrap_or_else(|| panic!("{engine:?}: no DELETE")); let update = update_batch( engine, &[PendingRow { schema: schema.into(), table: table.into(), sets: vec![("place".into(), NewValue::Value(value.into()))], keys: keys .iter() .map(|(column, value)| (column.to_string(), value.to_string())) .collect(), null_keys: vec!["gone".into()], ..PendingRow::default() }], ) .unwrap_or_else(|error| panic!("{engine:?}: {error}")); for statement in [delete, update] { // Refusing is the gate's right: such a table is read-only. // What it admits must be read again by its own predicate. if !is_generated_write_on(engine, &statement) { assert_eq!(row_reread(engine, &statement), None, "{statement}"); continue; } admitted.push((engine, table, column, value)); let written = generated_writes(engine, &statement); let Some([one]) = written.as_deref() else { panic!("{engine:?}: not one statement: {statement}"); }; // No re-read leaves the draft unreviewed, which fails closed. let Some(reread) = row_reread(engine, one) else { unread.push(one.to_string()); continue; }; assert!(is_generated_select(engine, &reread), "{engine:?}: {reread}"); let predicate = one.trim_end_matches(';').rsplit_once(" WHERE ").unwrap().1; assert!( reread.ends_with(&format!(" WHERE {predicate} LIMIT 2")), "{engine:?}: {reread}" ); if one.starts_with("UPDATE") { let read = row_read(engine, one) .unwrap_or_else(|| panic!("{engine:?}: no read back of {one}")); assert!(is_generated_select(engine, &read), "{engine:?}: {read}"); } if matches!(engine, Engine::MySql | Engine::MariaDb) { assert_eq!( written_table(engine, one), Some(vec![schema.to_string(), table.to_string()]), "{engine:?}: {one}" ); } } } } // Every hostile value is written, admitted and read back on all six: // a value is quoted, never refused. for engine in engines { for value in values { let both = admitted .iter() .filter(|case| **case == (engine, "birds", "bird", value)) .count(); assert!(both >= 2, "{engine:?}: {value}"); } } // ponytail: the grammar splits a table name holding a doubled quote in // an `UPDATE` (not a `DELETE`), so such a draft has no re-read and is // refused at review. It fails closed; reading the name whole is the fix. assert!( unread .iter() .all(|statement| statement.contains("\"we\"\"ird\"")), "{unread:#?}" ); } /// The table a generated write names is read whole, quoting and all, so /// the apply can ask the catalog about the very table it writes. #[test] fn a_generated_writes_table_is_read_off_its_parse() { let names = |engine: Engine, statement: &str| written_table(engine, statement); let parts = |parts: &[&str]| Some(parts.iter().map(|part| part.to_string()).collect()); assert_eq!( names( Engine::MySql, "UPDATE `dev`.`we``ird` SET `a` = 'it\\'s' WHERE `id` = '1'" ), parts(&["dev", "we`ird"]) ); assert_eq!( names(Engine::MariaDb, "DELETE FROM `dev`.`t` WHERE `id` = '1'"), parts(&["dev", "t"]) ); assert_eq!( names(Engine::MySql, "INSERT INTO `dev`.`t` (`id`) VALUES ('1')"), parts(&["dev", "t"]) ); assert_eq!(names(Engine::MySql, "SELECT * FROM `dev`.`t`"), None); assert_eq!( names( Engine::MySql, "DELETE FROM `a` WHERE 1; DELETE FROM `b` WHERE 1" ), None ); } /// MySQL's `autocommit` off and SQL Server's implicit transactions on /// leave the session inside a transaction from the next statement on. #[test] fn a_set_that_leaves_every_statement_in_a_transaction_opens_one() { let left = |open| Leaves { transaction: Some(open), settings: true, }; for (engine, statement, expected) in [ (Engine::MySql, "SET autocommit = 0", left(true)), (Engine::MySql, "set autocommit=OFF", left(true)), (Engine::MySql, "SET SESSION autocommit = 0", left(true)), (Engine::MySql, "SET @@session.autocommit = 0", left(true)), (Engine::MariaDb, "SET autocommit = 0", left(true)), (Engine::MySql, "SET autocommit = 1", left(false)), ( Engine::SqlServer, "SET IMPLICIT_TRANSACTIONS ON", left(true), ), ( Engine::SqlServer, "SET IMPLICIT_TRANSACTIONS OFF", Leaves { transaction: None, settings: true, }, ), ] { assert_eq!(leaves(engine, statement), expected, "{statement}"); } } #[test] fn insert_rows_writes_one_multi_row_insert_in_each_engines_spelling() { use crate::import_rows::Value; let (one, two, it, yes, no) = ( Value::Number("1".into()), Value::Number("2".into()), Value::Text("it's".into()), Value::Bool(true), Value::Bool(false), ); let cols = [("id", "integer"), ("note", "text"), ("ok", "boolean")]; assert_eq!( insert_rows( Engine::Postgres, "public", "t", &cols, &[ vec![Some(&one), Some(&it), Some(&yes)], vec![Some(&two), Some(&Value::Null), Some(&no)] ], true ) .unwrap(), "INSERT INTO \"public\".\"t\" (\"id\", \"note\", \"ok\") VALUES ('1', 'it''s', 'true'),\n('2', NULL, 'false') ON CONFLICT DO NOTHING" ); assert_eq!( insert_rows( Engine::MySql, "d", "t", &cols[..2], &[vec![Some(&one), Some(&Value::Text("a\\b".into()))]], true ) .unwrap(), "INSERT INTO `d`.`t` (`id`, `note`) VALUES ('1', 'a\\\\b') ON DUPLICATE KEY UPDATE `id` = `id`" ); assert_eq!( insert_rows( Engine::SqlServer, "dbo", "t", &[("note", "nvarchar(10)"), ("ok", "bit")], &[vec![Some(&Value::Text("é".into())), Some(&yes)]], false ) .unwrap(), "INSERT INTO \"dbo\".\"t\" (\"note\", \"ok\") VALUES (N'é', '1')" ); assert_eq!( insert_rows( Engine::MongoDb, "db", "t", &cols[..2], &[ vec![Some(&one), Some(&Value::Text("x".into()))], vec![Some(&two), None] ], false ) .unwrap(), "db.getCollection(\"t\").insertMany([{\"id\": 1, \"note\": \"x\"},\n{\"id\": 2}])" ); } #[test] fn insert_rows_quotes_every_name() { let v = crate::import_rows::Value::Text("x".into()); assert_eq!( insert_rows( Engine::Postgres, "public", "t", &[("order", "text"), ("a\"b", "text")], &[vec![Some(&v), Some(&v)]], false ) .unwrap(), "INSERT INTO \"public\".\"t\" (\"order\", \"a\"\"b\") VALUES ('x', 'x')" ); } #[test] fn every_engines_import_statements_pass_the_write_gate_and_the_mode_check() { let v = crate::import_rows::Value::Text("x".into()); for engine in [ Engine::Postgres, Engine::MySql, Engine::MariaDb, Engine::Sqlite, Engine::Turso, Engine::DuckDb, Engine::Snowflake, Engine::SqlServer, Engine::MongoDb, ] { let statement = insert_rows( engine, "s", "t", &[("a", "text")], &[vec![Some(&v)], vec![Some(&v)]], engine.skips_duplicates(), ) .unwrap(); assert!( is_generated_write_on(engine, &statement), "{engine:?}: {statement}" ); assert_eq!( gate(&classify(engine, &statement), Mode::ReadWrite, &[]), None, "{engine:?}: {statement}" ); assert_eq!( engine.skips_duplicates(), statement.contains(" ON "), "{engine:?}" ); if let Ok(begin) = engine.all_or_nothing() { for bracket in [begin, "COMMIT", "ROLLBACK"] { assert!(is_generated_write_on(engine, bracket)); assert_eq!( gate(&classify(engine, bracket), Mode::ReadOnly, &[]), None, "{engine:?} {bracket}" ); } } } } #[test] fn a_function_the_engine_lists_stops_being_a_read() { use crate::db::Engine; let sql = "SELECT set_config('default_transaction_read_only', 'off', false)"; assert!(classify(Engine::Postgres, sql).mode > Mode::ReadOnly); assert_eq!( gate(&classify(Engine::Postgres, sql), Mode::ReadOnly, &[]), Some(Stop::Upgrade(Mode::ReadWrite)) ); assert_eq!( gate(&classify(Engine::Postgres, sql), Mode::ReadWrite, &[]), None ); } #[test] fn a_function_stays_a_read_on_an_engine_that_does_not_list_it() { use crate::db::{Engine, Syntax}; // Generic is left out: only a call to a function on its built-in list // (`src/db/functions/generic.txt`) is a read there, so any call it // does not know is a write. for engine in Engine::ALL.into_iter().filter(|engine| { engine.syntax() == Syntax::Sql && *engine != Engine::Postgres && *engine != Engine::Generic }) { assert_eq!( classify(engine, "SELECT pg_stat_reset()").mode, Mode::ReadOnly, "{engine:?}" ); // A `set_config` that may lift the read-only hold is a write on // every engine ([`calls_verdict`]), whether or not it lists it. let lift = "SELECT set_config('default_transaction_read_only', 'off', false)"; assert!(classify(engine, lift).mode >= Mode::ReadWrite, "{engine:?}"); } } #[test] fn a_listed_call_is_found_wherever_the_parser_can_put_one() { use crate::db::Engine; for sql in [ "SELECT nextval('s')", "SELECT * FROM nextval('s')", "SELECT * FROM t, LATERAL nextval('s') x", "SELECT * FROM t WHERE id = (SELECT nextval('s'))", "WITH n AS (SELECT nextval('s') AS v) SELECT v FROM n", "SELECT nextval /* c */ ('s')", ] { assert!( classify(Engine::Postgres, sql).mode > Mode::ReadOnly, "{sql}" ); } } #[test] fn a_schema_qualified_listed_call_reads_like_the_bare_one() { use crate::db::Engine; let bare = classify(Engine::Postgres, "SELECT set_config('a', 'b', false)"); let qualified = classify( Engine::Postgres, "SELECT pg_catalog.set_config('a', 'b', false)", ); assert!(bare.mode > Mode::ReadOnly); assert_eq!(bare.mode, qualified.mode); } #[test] fn a_listed_name_inside_a_literal_or_a_comment_is_not_a_call() { use crate::db::Engine; for sql in [ "SELECT 'set_config(1)'", "SELECT 1 -- set_config('a', 'b', false)", "SELECT 1 /* nextval('s') */", "SELECT set_config FROM t", ] { assert_eq!( classify(Engine::Postgres, sql).mode, Mode::ReadOnly, "{sql}" ); } } #[test] fn a_function_nobody_listed_stays_a_read_on_every_engine() { use crate::db::{Engine, Syntax}; for engine in Engine::ALL .into_iter() .filter(|engine| engine.syntax() == Syntax::Sql) { for sql in ["SELECT my_function(1)", "SELECT * FROM my_function(1)"] { // Generic SQL reads only a call to a function on its built-in // list (`src/db/functions/generic.txt`) as a read: nothing on // that server holds a function of the user's to reads. let expected = match engine { Engine::Generic => Mode::ReadWrite, _ => Mode::ReadOnly, }; assert_eq!(classify(engine, sql).mode, expected, "{engine:?}: {sql}"); } } } #[test] fn every_listed_function_stops_being_a_read_on_the_engine_that_lists_it() { use crate::db::Engine; for engine in Engine::ALL { for name in engine.spec().sql.denied_functions { let sql = format!("SELECT {name}()"); assert!( classify(engine, &sql).mode > Mode::ReadOnly, "{engine:?}: {sql}" ); } } } #[test] fn two_listed_calls_classify_the_same_whichever_comes_first() { use crate::db::Engine; let one = classify( Engine::Postgres, "SELECT nextval('s'), set_config('a', 'b', false)", ); let other = classify( Engine::Postgres, "SELECT set_config('a', 'b', false), nextval('s')", ); assert!(one.mode > Mode::ReadOnly); assert_eq!(one.mode, other.mode); assert_eq!(one.destructive, other.destructive); } #[test] fn a_lock_call_needs_more_than_read_only_on_both_mysql_engines() { use crate::db::Engine; for engine in [Engine::MySql, Engine::MariaDb] { for sql in [ "SELECT get_lock('k', 1)", "SELECT release_lock('k')", "SELECT release_all_locks()", ] { assert!( classify(engine, sql).mode > Mode::ReadOnly, "{engine:?}: {sql}" ); } for sql in ["SELECT lastval()", "SELECT last_insert_id()"] { assert_eq!( classify(engine, sql).mode, Mode::ReadOnly, "{engine:?}: {sql}" ); } } } #[test] fn a_sequence_advance_needs_more_than_read_only_only_where_sequences_exist() { use crate::db::Engine; for engine in [Engine::MariaDb, Engine::DuckDb] { for sql in ["SELECT nextval('s')", "SELECT setval('s', 1)"] { assert!( classify(engine, sql).mode > Mode::ReadOnly, "{engine:?}: {sql}" ); } } // MySQL has no sequences, but a call spelled as an advance is a write // on every engine ([`calls_verdict`]): the stricter of the two rules. assert_eq!( classify(Engine::MySql, "SELECT nextval('s')").mode, Mode::ReadWrite ); } #[test] fn a_pass_through_table_function_needs_more_than_read_only_on_sql_server() { use crate::db::Engine; for sql in [ "SELECT * FROM OPENQUERY(srv, 'SELECT 1')", "SELECT * FROM OPENROWSET('SQLNCLI', 'x', 'DELETE FROM t')", "SELECT * FROM OPENDATASOURCE('SQLNCLI', 'x')", ] { assert!( classify(Engine::SqlServer, sql).mode > Mode::ReadOnly, "{sql}" ); } } #[test] fn a_session_control_call_and_a_bare_sequence_read_need_more_than_read_only_on_snowflake() { use crate::db::Engine; for sql in [ "SELECT system$cancel_all_queries(1)", "SELECT system$cancel_query('q')", "SELECT system$abort_session(1)", "SELECT * FROM TABLE(GETNEXTVAL(seq1))", "SELECT s.nextval", "SELECT db.s.nextval FROM t", ] { assert!( classify(Engine::Snowflake, sql).mode > Mode::ReadOnly, "{sql}" ); } for sql in ["SELECT t.id FROM t", "SELECT t.nextvalue FROM t"] { assert_eq!( classify(Engine::Snowflake, sql).mode, Mode::ReadOnly, "{sql}" ); } } #[test] fn the_extension_loader_needs_more_than_read_only_on_both_sqlite_engines() { use crate::db::Engine; for engine in [Engine::Sqlite, Engine::Turso] { assert!( classify(engine, "SELECT load_extension('x')").mode > Mode::ReadOnly, "{engine:?}" ); } } #[test] fn a_file_or_url_reader_stays_a_read_on_every_engine() { use crate::db::{Engine, Syntax}; for engine in Engine::ALL .into_iter() .filter(|engine| engine.syntax() == Syntax::Sql) { for name in ["read_csv", "read_text", "pg_read_file", "load_file", "glob"] { assert!( !engine.spec().sql.denied_functions.contains(&name), "{engine:?}: {name}" ); } } } #[test] fn an_engine_not_read_as_sql_lists_no_function() { use crate::db::{Engine, Syntax}; for engine in Engine::ALL .into_iter() .filter(|engine| engine.syntax() != Syntax::Sql) { assert!(engine.spec().sql.denied_functions.is_empty(), "{engine:?}"); } } #[test] fn a_name_another_engine_lists_does_not_raise_this_engines_verdict() { use crate::db::{Engine, Syntax}; let sql_engines = || { Engine::ALL .into_iter() .filter(|engine| engine.syntax() == Syntax::Sql) }; for lister in sql_engines() { for name in lister.spec().sql.denied_functions { for engine in sql_engines() { // Generic reads any call it does not know as a write. if engine.spec().sql.denied_functions.contains(name) || engine == Engine::Generic { continue; } let sql = format!("SELECT {name}()"); // A sequence advance, a `set_config` and a call no hold // stops are read on every engine ([`calls_verdict`]). let everywhere = dialect(engine).is_some_and(|dialect| { calls_verdict(engine, dialect.as_ref(), &sql) != Verdict::READ }); if everywhere { assert!(classify(engine, &sql).mode >= Mode::ReadWrite); continue; } let verdict = classify(engine, &sql); // A dialect that cannot read the name at all is refused // for that, which is not what is under test. if verdict.destructive.is_empty() { assert_eq!(verdict.mode, Mode::ReadOnly, "{engine:?}: {name}"); } } } } } #[test] fn a_name_spelled_as_a_unicode_escape_is_read_as_a_denied_call() { use crate::db::Engine; for sql in [ // The verifier's own repro: the server decodes `\006f` to an `o`. r#"SELECT U&"set_c\006fnfig"('default_transaction_read_only', 'off', false)"#, // The same form spelling the name plainly stops on the name alone. r#"SELECT U&"set_config"('default_transaction_read_only', 'off', false)"#, r#"SELECT pg_catalog.U&"set_c\006fnfig"('a', 'b', false)"#, // The lower-case prefix is the same escape to the server. r#"SELECT u&"set_c\006fnfig"('a', 'b', false)"#, ] { assert!(is_stopped(Engine::Postgres, sql), "{sql}"); } } #[test] fn a_large_object_writer_is_stopped_and_a_large_object_reader_is_not() { use crate::db::Engine; for sql in [ "SELECT lo_from_bytea(1, 'abc'::bytea)", "SELECT lo_put(1, 0, 'abc'::bytea)", "SELECT lo_creat(-1)", "SELECT lowrite(0, 'abc'::bytea)", "SELECT lo_truncate(0, 1)", "SELECT lo_truncate64(0, 1)", ] { assert!(is_stopped(Engine::Postgres, sql), "{sql}"); } for sql in ["SELECT lo_get(1)", "SELECT loread(0, 10)"] { // Generic reads only a known side-effect-free built-in as a read. for engine in sql_engines().filter(|engine| *engine != Engine::Generic) { assert!(is_plain_read(engine, sql), "{engine:?}: {sql}"); } } } #[test] fn every_stat_reset_call_is_stopped_on_postgres() { use crate::db::Engine; for sql in [ "SELECT pg_stat_reset()", "SELECT pg_stat_reset_shared('bgwriter')", "SELECT pg_stat_reset_single_table_counters(1)", "SELECT pg_stat_reset_single_function_counters(1)", "SELECT pg_stat_reset_slru('CommitTs')", "SELECT pg_stat_reset_replication_slot('s')", ] { assert!(is_stopped(Engine::Postgres, sql), "{sql}"); } } #[test] fn a_spaced_bit_and_of_a_quoted_column_is_still_a_read() { for engine in sql_engines() { for sql in [ r#"SELECT U & "x" FROM t"#, "SELECT U\n&\t\"x\" FROM t", r#"SELECT U/**/&"x" FROM t"#, "SELECT U&x FROM t", ] { assert!(is_plain_read(engine, sql), "{engine:?}: {sql}"); } } } #[test] fn an_engine_that_lists_no_function_never_reads_the_escaped_spelling_as_a_call() { use crate::db::Engine; let sql = r#"SELECT U&"set_c\006fnfig"('a', 'b', false)"#; let listing_nothing: Vec<_> = Engine::ALL .into_iter() .filter(|engine| engine.spec().sql.denied_functions.is_empty()) .collect(); // Every SQL engine lists something, so the engines asked are the two // whose requests are not SQL. The assertion fails if that changes, // rather than letting the loop below pass over nothing. assert!(!listing_nothing.is_empty()); for engine in listing_nothing { assert!(!calls_denied_function(engine, sql), "{engine:?}"); } } #[test] fn an_empty_or_comment_only_submission_is_unmoved_by_the_escaped_spelling_rule() { for engine in sql_engines() { for sql in ["", " ", "-- U&\"x\"", "/* U&\"x\" */"] { assert!(is_plain_read(engine, sql), "{engine:?}: {sql:?}"); } } } #[test] fn an_escaped_call_and_a_plain_denied_call_classify_the_same_whichever_comes_first() { use crate::db::Engine; let one = classify( Engine::Postgres, r#"SELECT U&"set_c\006fnfig"('a', 'b', false), nextval('s')"#, ); let other = classify( Engine::Postgres, r#"SELECT nextval('s'), U&"set_c\006fnfig"('a', 'b', false)"#, ); assert!(one.mode > Mode::ReadOnly); assert_eq!(one.mode, other.mode); assert_eq!(one.destructive, other.destructive); } /// The eight engines whose requests are SQL, which is where a `SET` means /// something to `classify`. fn sql_engines() -> impl Iterator { use crate::db::Syntax; crate::db::Engine::ALL .into_iter() .filter(|engine| engine.syntax() == Syntax::Sql) } /// Needs more than Read-only, and for a reason other than the parser /// having refused it: an unreadable statement says nothing about the rule. fn is_stopped(engine: crate::db::Engine, sql: &str) -> bool { let verdict = classify(engine, sql); verdict.mode > Mode::ReadOnly && !verdict.destructive.contains(&Destructive::Unreadable) } fn is_plain_read(engine: crate::db::Engine, sql: &str) -> bool { let verdict = classify(engine, sql); verdict.mode == Mode::ReadOnly && verdict.destructive.is_empty() } /// What `classify` would say for `sql` on an engine whose spec is `spec`, /// without the engine: the way to give a spec a list no engine carries. fn verdict_under(spec: &crate::db::SqlSpec, sql: &str) -> Verdict { let dialect = parser(spec.parser_dialect); SqlParser::parse_sql(dialect.as_ref(), sql) .expect("the statement parses in this dialect") .iter() .map(|statement| statement_verdict(spec, statement).verdict) .fold(Verdict::READ, Verdict::max) } fn with_plain_settings( parser_dialect: ParserDialect, plain_settings: &'static [&'static str], ) -> crate::db::SqlSpec { crate::db::SqlSpec { parser_dialect, plain_settings, ..crate::db::SqlSpec::ANSI } } #[test] fn a_role_change_and_an_authorization_change_need_more_than_read_only() { for engine in sql_engines() { for sql in [ "SET ROLE other", "SET LOCAL ROLE other", "SET SESSION AUTHORIZATION other", ] { assert!(is_stopped(engine, sql), "{engine:?}: {sql}"); assert_eq!( gate(&classify(engine, sql), Mode::ReadOnly, &[]), Some(Stop::Upgrade(Mode::ReadWrite)), "{engine:?}: {sql}" ); assert_eq!( gate(&classify(engine, sql), Mode::ReadWrite, &[]), None, "{engine:?}: {sql}" ); } } } #[test] fn a_write_access_mode_needs_more_than_read_only_in_every_spelling() { use crate::db::Engine; for engine in sql_engines() { for sql in [ "SET TRANSACTION READ WRITE", "SET SESSION TRANSACTION READ WRITE", "SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE", "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE, READ WRITE", "START TRANSACTION READ WRITE", "BEGIN TRANSACTION READ WRITE", ] { assert!(is_stopped(engine, sql), "{engine:?}: {sql}"); } } // The two dialects whose `BEGIN` opens a scripting block do not read // the bare spelling as a transaction at all. for engine in sql_engines().filter(|e| !matches!(e, Engine::Snowflake | Engine::SqlServer)) { assert!(is_stopped(engine, "BEGIN READ WRITE"), "{engine:?}"); } } #[test] fn a_read_access_mode_and_an_isolation_level_stay_reads() { for engine in sql_engines() { for sql in [ "SET TRANSACTION READ ONLY", "SET SESSION TRANSACTION READ ONLY", "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE", "START TRANSACTION READ ONLY", ] { assert!(is_plain_read(engine, sql), "{engine:?}: {sql}"); } } } #[test] fn transaction_brackets_stay_reads() { for engine in sql_engines() { for sql in [ "BEGIN", "START TRANSACTION", "COMMIT", "ROLLBACK", "SAVEPOINT a", "RELEASE SAVEPOINT a", "BEGIN; SELECT 1; COMMIT", ] { assert!(is_plain_read(engine, sql), "{engine:?}: {sql}"); } } } #[test] fn a_server_wide_scope_needs_more_than_read_only_whatever_the_name() { use crate::db::Engine; for engine in sql_engines() { assert!( is_stopped(engine, "SET GLOBAL time_zone = 'UTC'"), "{engine:?}" ); } for engine in [Engine::MySql, Engine::MariaDb, Engine::SqlServer] { assert!( is_stopped(engine, "SET @@global.time_zone = 'UTC'"), "{engine:?}" ); } } #[test] fn a_server_wide_transaction_scope_is_stopped_whatever_the_parser_dropped() { use crate::db::Engine; // The parser reads these as a transaction with no scope, and a // transaction that asks for no write access is a read, so the scope has // to come from the tokens. for engine in [Engine::MySql, Engine::MariaDb] { for sql in [ "SET GLOBAL TRANSACTION READ ONLY", "set global transaction read only", "SET GLOBAL TRANSACTION ISOLATION LEVEL SERIALIZABLE", "SET /* scope */ GLOBAL TRANSACTION READ ONLY", ] { assert!(is_stopped(engine, sql), "{engine:?}: {sql}"); } } // Wherever a dialect parses the persistent scopes they are raised the // same way; one that cannot is refused for that, as it was. for engine in sql_engines() { for sql in [ "SET PERSIST TRANSACTION READ ONLY", "SET PERSIST_ONLY TRANSACTION READ ONLY", ] { let verdict = classify(engine, sql); if !verdict.destructive.contains(&Destructive::Unreadable) { assert!(verdict.mode > Mode::ReadOnly, "{engine:?}: {sql}"); } } } // Per statement, so the order of two does not matter. for engine in sql_engines() { assert_eq!( classify(engine, "SELECT 1; SET GLOBAL TRANSACTION READ ONLY"), classify(engine, "SET GLOBAL TRANSACTION READ ONLY; SELECT 1"), "{engine:?}" ); } for engine in [Engine::MySql, Engine::MariaDb] { assert!( is_stopped(engine, "SELECT 1; SET GLOBAL TRANSACTION READ ONLY"), "{engine:?}" ); } // The parser also accepts the statement inside a block, where it does // not open the statement. for engine in [Engine::MySql, Engine::MariaDb, Engine::Postgres] { assert!( is_stopped( engine, "IF 1 = 1 THEN SET GLOBAL TRANSACTION READ ONLY; END IF" ), "{engine:?}" ); } } #[test] fn a_session_scope_and_a_variable_that_begins_with_the_scope_word_stay_reads() { use crate::db::Engine; for engine in [Engine::MySql, Engine::MariaDb] { for sql in [ "SET SESSION TRANSACTION READ ONLY", "SET TRANSACTION READ ONLY", "SET LOCAL TRANSACTION READ ONLY", "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE", "SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE", "SET @global = 1", "SET @globally = 1", ] { assert!(is_plain_read(engine, sql), "{engine:?}: {sql}"); } // The two spellings that already named the scope keep their verdict. for sql in [ "SET GLOBAL max_execution_time = 1", "SET @@global.time_zone = 'UTC'", ] { assert!(is_stopped(engine, sql), "{engine:?}: {sql}"); } } for engine in sql_engines() { for sql in ["BEGIN", "START TRANSACTION", "SELECT 1 AS global"] { assert!(is_plain_read(engine, sql), "{engine:?}: {sql}"); } } } #[test] fn a_submission_the_tokenizer_cannot_read_is_not_raised_by_the_scope_rule() { for engine in sql_engines() { // Refused by name already; raising it would fold a write into the // unreadable verdict. assert_eq!( classify(engine, "SET GLOBAL TRANSACTION READ ONLY; SELECT 'x"), classify(engine, "SELECT 'x"), "{engine:?}" ); for sql in ["", "-- nothing here", "/* nor here */"] { assert!(is_plain_read(engine, sql), "{engine:?}: {sql:?}"); } } } #[test] fn a_user_variable_stays_a_read_and_a_doubled_at_session_setting_does_not() { use crate::db::Engine; for engine in [Engine::MySql, Engine::MariaDb, Engine::SqlServer] { assert!(is_plain_read(engine, "SET @x = 1"), "{engine:?}"); assert!( is_stopped(engine, "SET @@session.transaction_read_only = 0"), "{engine:?}" ); assert!( is_stopped(engine, "SET @@transaction_read_only = OFF"), "{engine:?}" ); } } #[test] fn reordering_the_assignments_of_one_set_does_not_change_its_verdict() { use crate::db::Engine; for engine in [Engine::MySql, Engine::MariaDb, Engine::SqlServer] { let hold_last = classify(engine, "SET @x = 1, @@session.transaction_read_only = 0"); let hold_first = classify(engine, "SET @@session.transaction_read_only = 0, @x = 1"); assert!( is_stopped(engine, "SET @x = 1, @@session.transaction_read_only = 0"), "{engine:?}" ); assert_eq!(hold_last, hold_first, "{engine:?}"); let unknown_last = classify(engine, "SET @x = 1, y = 2"); let unknown_first = classify(engine, "SET y = 2, @x = 1"); assert!(is_stopped(engine, "SET y = 2, @x = 1"), "{engine:?}"); assert_eq!(unknown_last, unknown_first, "{engine:?}"); } // T-SQL has no list of assignments, and its parse folds the second one // into the first as a value, so only the MySQL family reads this one. for engine in [Engine::MySql, Engine::MariaDb] { assert!(is_plain_read(engine, "SET @x = 1, @y = 2"), "{engine:?}"); } } #[test] fn a_setting_on_no_list_needs_more_than_read_only_on_every_engine() { for engine in sql_engines() { assert!(is_stopped(engine, "SET x = 1"), "{engine:?}"); assert!(is_stopped(engine, "SET x = 1, y = 2"), "{engine:?}"); } } #[test] fn a_set_nested_in_a_block_reaches_the_verdict_it_has_alone() { use crate::db::Engine; for engine in sql_engines() { // A plain EXPLAIN runs nothing, so only the analysing one carries // the verdict of what it explains. assert!( is_stopped(engine, "EXPLAIN ANALYZE SET ROLE other"), "{engine:?}" ); assert!( is_plain_read(engine, "EXPLAIN SET ROLE other"), "{engine:?}" ); let (conditional, scripting) = match engine { Engine::SqlServer => ( Some("IF 1 = 1 SET ROLE other"), Some("BEGIN SET ROLE other; END"), ), Engine::Snowflake => ( Some("IF 1 = 1 THEN SET ROLE other; END IF"), Some("BEGIN SET ROLE other; END"), ), // No conditional block to nest a statement in: the `IF` is the // first word of a statement `sqlparser` cannot read, rated // Read-write and unreadable, so it is no verdict to compare. // Below, it is held above Read-only by that rating instead. Engine::ClickHouse => (None, None), _ => (Some("IF 1 = 1 THEN SET ROLE other; END IF"), None), }; for sql in conditional.into_iter().chain(scripting) { assert_eq!( classify(engine, sql), classify(engine, "SET ROLE other"), "{engine:?}: {sql}" ); assert!(is_stopped(engine, sql), "{engine:?}: {sql}"); } } for engine in sql_engines().filter(|e| { !matches!( e, Engine::Snowflake | Engine::SqlServer | Engine::ClickHouse ) }) { assert!( is_stopped(engine, "IF 1 = 1 THEN SET x = 1; END IF"), "{engine:?}" ); } assert_eq!( classify(Engine::ClickHouse, "IF 1 = 1 THEN SET x = 1; END IF"), unreadable_at(Mode::ReadWrite) ); assert!(is_stopped( Engine::Snowflake, "BEGIN START TRANSACTION READ WRITE; END" )); assert!(is_plain_read(Engine::Snowflake, "BEGIN COMMIT; END")); } #[test] fn a_setting_on_the_allow_list_is_found_at_any_nesting_depth() { let postgres = with_plain_settings(ParserDialect::PostgreSql, &["search_path"]); let snowflake = with_plain_settings(ParserDialect::Snowflake, &["search_path"]); for sql in [ "SET search_path TO other", "IF 1 = 1 THEN SET search_path TO other; END IF", "EXPLAIN ANALYZE SET search_path TO other", ] { assert_eq!(verdict_under(&postgres, sql), Verdict::READ, "{sql}"); } assert_eq!( verdict_under(&snowflake, "BEGIN SET search_path TO other; END"), Verdict::READ ); for sql in [ "SET x = 1", "IF 1 = 1 THEN SET x = 1; END IF", "EXPLAIN ANALYZE SET x = 1", ] { assert_eq!(verdict_under(&postgres, sql), Verdict::WRITE, "{sql}"); } assert_eq!( verdict_under(&snowflake, "BEGIN SET x = 1; END"), Verdict::WRITE ); } #[test] fn a_setting_name_is_normalised_before_the_allow_list_is_asked() { let mysql = with_plain_settings(ParserDialect::MySql, &["time_zone"]); for sql in [ "SET time_zone = 'UTC'", "SET TIME_ZONE = 'UTC'", "SET SESSION time_zone = 'UTC'", "SET @@time_zone = 'UTC'", "SET @@session.time_zone = 'UTC'", "SET @@SESSION.Time_Zone = 'UTC'", "SET LOCAL time_zone = 'UTC'", ] { assert_eq!(verdict_under(&mysql, sql), Verdict::READ, "{sql}"); } // The server-wide scope wins over an allow-list hit, however it is // spelled. for sql in [ "SET GLOBAL time_zone = 'UTC'", "SET @@global.time_zone = 'UTC'", "SET @@GLOBAL.time_zone = 'UTC'", ] { assert_eq!(verdict_under(&mysql, sql), Verdict::WRITE, "{sql}"); } // One name off the list stops the whole statement, in either order. for sql in [ "SET time_zone = 'UTC', y = 2", "SET y = 2, time_zone = 'UTC'", ] { assert_eq!(verdict_under(&mysql, sql), Verdict::WRITE, "{sql}"); } assert_eq!( verdict_under(&mysql, "SET time_zone = 'UTC', @x = 1"), Verdict::READ ); } #[test] fn an_allow_listed_name_on_an_engine_with_an_empty_list_is_stopped() { let listed = with_plain_settings(ParserDialect::PostgreSql, &["search_path"]); let empty = with_plain_settings(ParserDialect::PostgreSql, &[]); let sql = "SET search_path TO other"; assert_eq!(verdict_under(&listed, sql), Verdict::READ); assert_eq!(verdict_under(&empty, sql), Verdict::WRITE); } #[test] fn a_set_the_parser_accepts_without_an_assignment_is_stopped() { use crate::db::Engine; // Accepted by the pinned parser, and carries no setting name to look // up, so the allow-list has nothing to say and the default decides. assert!(is_stopped(Engine::MySql, "SET NAMES DEFAULT")); assert!(is_stopped(Engine::Postgres, "SET NAMES DEFAULT")); } #[test] fn an_engine_with_a_session_to_set_lists_its_settings_and_the_rest_list_none() { use crate::db::Engine; for engine in [ Engine::Postgres, Engine::MySql, Engine::MariaDb, Engine::DuckDb, Engine::SqlServer, Engine::ClickHouse, ] { assert!(!engine.spec().sql.plain_settings.is_empty(), "{engine:?}"); } // SQLite and Turso configure through `PRAGMA`, which is already Full, // and Snowflake's requests keep no session for a `SET` to change. for engine in [Engine::Sqlite, Engine::Turso, Engine::Snowflake] { assert!(engine.spec().sql.plain_settings.is_empty(), "{engine:?}"); for sql in [ "SET search_path TO other", "SET timezone = 'UTC'", "SET x = 1", ] { assert!(is_stopped(engine, sql), "{engine:?}: {sql}"); } } } #[test] fn clickhouse_reads_its_listed_settings_and_stops_the_rest() { use crate::sql_snapshots::hardening::set_statement; let ch = Engine::ClickHouse; assert_eq!(classify(ch, "SET max_threads = 1").mode, Mode::ReadOnly); // `readonly` is what the driver's per-request hold is made of, and `x` // is on no list: neither is left for the server's `readonly=2` to // refuse. for sql in ["SET readonly = 0", "SET x = 1"] { assert!(is_stopped(ch, sql), "{sql}"); } for name in ch.spec().sql.plain_settings { let sql = set_statement(ch, name); assert!(is_plain_read(ch, &sql), "{sql}"); } } #[test] fn the_raise_reaches_a_statement_read_by_its_first_keyword() { let ch = Engine::ClickHouse; // ClickHouse is read statement by statement, a path that once returned // before the raise: a scope pair the text spells, here as identifiers, // is rated above Read-only on every SQL engine, this one included. assert!(classify(ch, "SELECT t.set global FROM t").mode >= Mode::ReadWrite); // A statement `sqlparser` cannot read keeps its first keyword's rating // and stays unreadable, at the mode the one construction gives. let verdict = classify(ch, "SELECT garbage ) ("); assert!(verdict.destructive.contains(&Destructive::Unreadable)); assert_eq!(verdict.mode, unreadable_verdict(ch).mode); } #[test] fn every_allow_listed_setting_stays_a_read_on_its_engine_unless_server_wide() { use crate::sql_snapshots::hardening::set_statement; for engine in sql_engines() { for name in engine.spec().sql.plain_settings { let sql = set_statement(engine, name); assert!(is_plain_read(engine, &sql), "{engine:?}: {sql}"); let global = format!("SET GLOBAL {name} = 1"); assert!(is_stopped(engine, &global), "{engine:?}: {global}"); } } } #[test] fn a_setting_left_off_every_list_is_stopped_on_the_engine_that_has_it() { use crate::sql_snapshots::hardening::{EXCLUDED_SETTINGS, set_statement}; for (engine, names) in EXCLUDED_SETTINGS { for name in *names { let sql = set_statement(*engine, name); assert!(is_stopped(*engine, &sql), "{engine:?}: {sql}"); // The name is stopped because nothing listed it, so a list // that gained it would be the regression. assert!( !engine .spec() .sql .plain_settings .contains(&name.to_ascii_lowercase().as_str()), "{engine:?}: {name}" ); } } } #[test] fn navigation_and_comfort_settings_stay_reads_where_the_engine_has_them() { use crate::db::Engine; for (engine, sql) in [ (Engine::Postgres, "SET search_path TO other"), (Engine::Postgres, "SET SESSION search_path = other"), (Engine::Postgres, "SET LOCAL statement_timeout = 1000"), (Engine::Postgres, "SET timezone = 'UTC'"), (Engine::Postgres, "SET TIMEZONE TO 'UTC'"), (Engine::MySql, "SET autocommit = 0"), (Engine::MySql, "SET time_zone = 'UTC'"), (Engine::MySql, "SET @@session.time_zone = 'UTC'"), (Engine::MySql, "SET SESSION max_execution_time = 1000"), (Engine::MariaDb, "SET autocommit = 0"), (Engine::DuckDb, "SET threads = 2"), (Engine::DuckDb, "SET search_path = 'main'"), (Engine::SqlServer, "SET NOCOUNT ON"), (Engine::SqlServer, "SET ROWCOUNT 10"), (Engine::SqlServer, "SET STATISTICS IO ON"), ] { assert!(is_plain_read(engine, sql), "{engine:?}: {sql}"); } } #[test] fn the_two_mysql_family_servers_name_their_timeout_and_isolation_differently() { use crate::db::Engine; assert!(is_plain_read(Engine::MySql, "SET max_execution_time = 1")); assert!(is_stopped(Engine::MySql, "SET max_statement_time = 1")); assert!(is_plain_read(Engine::MariaDb, "SET max_statement_time = 1")); assert!(is_stopped(Engine::MariaDb, "SET max_execution_time = 1")); // MariaDB still answers to the older isolation-level spelling. assert!(is_plain_read(Engine::MariaDb, "SET tx_isolation = 'x'")); assert!(is_stopped(Engine::MySql, "SET tx_isolation = 'x'")); assert!(is_plain_read( Engine::MySql, "SET transaction_isolation = 'x'" )); assert!(is_plain_read( Engine::MariaDb, "SET transaction_isolation = 'x'" )); } #[test] fn the_one_way_configuration_ratchets_on_the_embedded_analytics_engine_are_stopped() { use crate::db::Engine; // Once off, DBDelve's own CSV, Parquet and Excel opening stays off for // the rest of the session, and a locked configuration refuses every // later `SET`. for sql in [ "SET enable_external_access = false", "SET lock_configuration = true", ] { assert!(is_stopped(Engine::DuckDb, sql), "{sql}"); } } #[test] fn a_charset_that_cannot_swallow_a_backslash_stays_a_read() { use crate::db::Engine; for engine in [Engine::MySql, Engine::MariaDb] { for charset in [ "utf8mb4", "UTF8MB4", "utf8mb3", "utf8", "latin1", "ascii", "binary", ] { let sql = format!("SET NAMES {charset}"); assert!(is_plain_read(engine, &sql), "{engine:?}: {sql}"); } assert!( is_plain_read(engine, "SET NAMES utf8mb4 COLLATE utf8mb4_bin"), "{engine:?}" ); for charset in ["gbk", "big5", "sjis", "cp932", "gb18030", "ucs2", "utf16"] { let sql = format!("SET NAMES {charset}"); assert!(is_stopped(engine, &sql), "{engine:?}: {sql}"); } assert!(is_stopped(engine, "SET NAMES DEFAULT"), "{engine:?}"); } } /// The engines whose server runs the marker, so `classify` expands it: /// MariaDB alone. MySQL shares the dialect and ignores the marker, and is /// pinned by [`on_mysql_an_executable_comment_is_ignored_and_unreadable`]. fn marker_engines() -> impl Iterator { [crate::db::Engine::MariaDb].into_iter() } /// Every input the MariaDB tests above read, on MySQL: MySQL ignores the /// comment and a MySQL profile may point at a MariaDB server that runs it, /// so the verdict holds both readings and is unreadable on top. It is never /// looser than MariaDB's, so nothing MariaDB would run escapes on MySQL. #[test] fn on_mysql_an_executable_comment_is_ignored_and_unreadable() { use crate::db::Engine; for sql in [ "/*M!100100 DROP TABLE t */", "/*M!DROP TABLE t */", "/*M!100100DROP TABLE t */", "/*m!100100 DROP TABLE t */", "/*M!100100 TRUNCATE TABLE t */", "/*M!100100 DELETE FROM t */", "/*M!100100 INSERT INTO t VALUES (1) */", "/*M!100100 SELECT 1 */", "SELECT 1; /*M!100100 DROP TABLE t */", "/*M!100100 SET SESSION TRANSACTION READ WRITE */", "/*M!100100 SET SESSION transaction_read_only = 0 */", "/*M!100100 SET GLOBAL read_only = 0 */", "SELECT 1 /*M!100100 INTO @y */ FROM t", "SELECT 2 /*M!100100 +1 */", "/*M!100100 SELECT get_lock('k', 1) */", "/*M!100100 DROP TABLE t */ SELECT 1", "/*M!1234 DROP TABLE t */", "/*M!*/", "DELETE FROM t /*M! WHERE 1 = 0 */", "INSERT INTO t VALUES (1) /*M!100100 , (2) */", ] { let mysql = classify(Engine::MySql, sql); let mariadb = classify(Engine::MariaDb, sql); assert!( mysql.destructive.contains(&Destructive::Unreadable), "{sql}: {mysql:?}" ); assert!(mysql.mode >= mariadb.mode, "{sql}: {mysql:?} {mariadb:?}"); for kind in &mariadb.destructive { assert!(mysql.destructive.contains(kind), "{sql}: {mysql:?}"); } } // A marker that is not a comment token is no marker. for sql in [ "SELECT '/*M!100100 DROP TABLE t */'", "-- /*M!100100 DROP TABLE t */\nSELECT 1", "# /*M!100100 DROP TABLE t */\nSELECT 1", ] { assert!(is_plain_read(Engine::MySql, sql), "{sql}"); } } fn destroys_as(engine: crate::db::Engine, sql: &str, kind: Destructive) -> bool { classify(engine, sql) == Verdict::destroys(kind) } fn is_unreadable(engine: crate::db::Engine, sql: &str) -> bool { classify(engine, sql).destructive == [Destructive::Unreadable] } #[test] fn a_comment_the_server_executes_is_judged_by_the_statement_it_holds() { for engine in marker_engines() { for sql in [ "/*M!100100 DROP TABLE t */", "/*M!DROP TABLE t */", "/*M!100100DROP TABLE t */", "/*M!10010 DROP TABLE t */", "/*M!100100\nDROP TABLE t */", ] { assert!( destroys_as(engine, sql, Destructive::Drop), "{engine:?}: {sql}" ); } assert!( destroys_as( engine, "/*M!100100 TRUNCATE TABLE t */", Destructive::Truncate ), "{engine:?}" ); assert!( destroys_as( engine, "/*M!100100 DELETE FROM t */", Destructive::UnfilteredDelete ), "{engine:?}" ); assert!( is_stopped(engine, "/*M!100100 INSERT INTO t VALUES (1) */"), "{engine:?}" ); assert!( is_plain_read(engine, "/*M!100100 SELECT 1 */"), "{engine:?}" ); } } #[test] fn a_comment_the_server_executes_after_a_statement_is_judged_the_same_way() { for engine in marker_engines() { for sql in [ "SELECT 1; /*M!100100 DROP TABLE t */", "SELECT 1;\n/*M!100100 DROP TABLE t */", ] { assert!( destroys_as(engine, sql, Destructive::Drop), "{engine:?}: {sql}" ); } assert!( is_stopped( engine, "SELECT 1; /*M!100100 SET SESSION TRANSACTION READ WRITE */" ), "{engine:?}" ); } } #[test] fn a_comment_the_server_executes_cannot_disarm_the_read_only_hold() { for engine in marker_engines() { for sql in [ "/*M!100100 SET SESSION TRANSACTION READ WRITE */", "/*M!100100 SET SESSION transaction_read_only = 0 */", "/*M!100100 SET GLOBAL read_only = 0 */", ] { assert!(is_stopped(engine, sql), "{engine:?}: {sql}"); } } } #[test] fn a_fragment_in_a_comment_the_server_executes_belongs_to_the_statement_around_it() { for engine in marker_engines() { assert!( is_stopped(engine, "SELECT 1 /*M!100100 INTO @y */ FROM t"), "{engine:?}" ); assert!( is_plain_read(engine, "SELECT 2 /*M!100100 +1 */"), "{engine:?}" ); } } #[test] fn a_comment_the_server_executes_fused_with_a_bare_statement_is_unreadable() { // The server inlines the comment into its neighbours, so the two run as // one statement it rejects. for engine in marker_engines() { assert!( is_unreadable(engine, "/*M!100100 DROP TABLE t */ SELECT 1"), "{engine:?}" ); } } #[test] fn a_denied_call_in_a_comment_the_server_executes_is_stopped() { for engine in marker_engines() { assert!( is_stopped(engine, "/*M!100100 SELECT get_lock('k', 1) */"), "{engine:?}" ); } } #[test] fn a_version_the_server_reads_as_part_of_a_plain_comment_stays_one() { for engine in marker_engines() { assert!( is_plain_read(engine, "/*M!1234 DROP TABLE t */"), "{engine:?}" ); } } #[test] fn a_marker_that_is_not_a_comment_token_is_left_alone() { for engine in marker_engines() { for sql in [ "SELECT '/*M!100100 DROP TABLE t */'", "-- /*M!100100 DROP TABLE t */\nSELECT 1", "# /*M!100100 DROP TABLE t */\nSELECT 1", ] { assert!(is_plain_read(engine, sql), "{engine:?}: {sql}"); } } } #[test] fn a_dialect_that_does_not_expand_the_marker_is_not_affected_by_it() { use crate::db::Engine; // MySQL holds the marker unreadable (see the test above). Generic // cannot tell which server runs it, so any `/*M!` makes the submission // one it may lex otherwise (`lexes_apart`). for engine in sql_engines().filter(|engine| { !marker_engines().any(|marker| marker == *engine) && *engine != Engine::MySql && *engine != Engine::Generic }) { assert!( is_plain_read(engine, "/*M!100100 DROP TABLE t */"), "{engine:?}" ); } } #[test] fn an_executable_comment_that_cannot_be_read_is_unreadable() { for engine in marker_engines() { for sql in [ "/*M!100100 DROP TABLE t", "/*M!100100 /*M!100100 SELECT 7 */ */", // The version no server reaches, which opens every dump file. "/*M!999999\\- enable the sandbox mode */", ] { assert!(is_unreadable(engine, sql), "{engine:?}: {sql}"); } } } #[test] fn a_multi_byte_character_in_an_executable_comment_cannot_split_it() { for engine in marker_engines() { assert!( is_plain_read(engine, "/*M!100100 SELECT 'é' */"), "{engine:?}" ); for sql in [ "/*M!100100é DROP TABLE t */", "/*M!é DROP TABLE t */", "/*M!100100 DROP TABLE t */", ] { assert!(is_unreadable(engine, sql), "{engine:?}: {sql}"); } } } #[test] fn nothing_and_a_lone_empty_executable_comment_are_silent_reads() { use crate::db::Engine; for engine in sql_engines() { for sql in ["", " \n\t"] { assert!(is_plain_read(engine, sql), "{engine:?}: {sql:?}"); } // MySQL holds any marker unreadable, and Generic any comment that // opens with one, since neither knows the server runs nothing. match engine { Engine::MySql | Engine::Generic => { assert!(is_unreadable(engine, "/*M!*/"), "{engine:?}") } _ => assert!(is_plain_read(engine, "/*M!*/"), "{engine:?}"), } } } #[test] fn a_hash_line_comment_stays_a_silent_read_where_the_dialect_lexes_it_as_a_comment() { use crate::db::Engine; for engine in [Engine::MySql, Engine::MariaDb, Engine::Snowflake] { for sql in ["# a note", "# a note\n", "/* a */ # a note"] { assert!(is_plain_read(engine, sql), "{engine:?}: {sql:?}"); } } } #[test] fn a_nested_block_comment_leaves_residue_the_tokenizer_reads_as_code() { use crate::db::Engine; // Both dialects nest, and the grammar does not, so what follows the // inner close is a range the lexer reads as operators. Rare, and the // conservative side. for engine in [Engine::Postgres, Engine::SqlServer] { for sql in ["/* /* n */ */", "/* /* n */ DROP TABLE t */"] { assert!(is_unreadable(engine, sql), "{engine:?}: {sql}"); } } } #[test] fn the_cross_check_and_a_parse_error_refuse_with_one_verdict() { use crate::db::Engine; // One engine that holds Read-only on the server and one that does not, // since the mode an unreadable verdict may run in depends on it. for engine in [Engine::Postgres, Engine::SqlServer] { assert_eq!( classify(engine, "/* /* n */ */"), classify(engine, "SELECT FROM WHERE ("), "{engine:?}" ); } assert_ne!( classify(Engine::Postgres, "SELECT FROM WHERE (").mode, classify(Engine::SqlServer, "SELECT FROM WHERE (").mode ); } /// What the Run action submits for a non-empty selection: the branch of /// `Workspace::sql_to_run` that reads the selection. That method needs a /// GPUI `Entity`, so this composes the same three pure /// pieces it does, and a change there has to be mirrored here. /// /// `None` is "there is no statement to run". fn submitted_for_selection( engine: crate::db::Engine, buffer: &str, selection: Range, ) -> Option> { assert!(!selection.is_empty()); // The editor's selection is a byte range into the buffer. Slicing off a // character boundary would panic, which is what the offsets named in // the tests below rule out. assert!( buffer.is_char_boundary(selection.start) && buffer.is_char_boundary(selection.end), "{engine:?}: {selection:?}" ); match one_batch(engine, &buffer[selection]) { Ok(batch) if batch.trim().is_empty() => None, Ok(batch) => Some(Ok(batch.to_string())), Err(message) => Some(Err(message)), } } /// The answer to `HARD-07`, "does a shipped route submit text that reaches /// the executable-comment shapes?": **yes**, and it is established rather /// than unknown. /// /// Run on a non-empty editor selection that holds one statement or none /// sends the selection to the driver verbatim, on every engine but SQL /// Server, where only the `GO` lines around the batch are removed /// (`sql_to_run`, through `one_batch`). Two shapes reach the classifier /// through it, both on a Read-only profile against a MariaDB server: /// /// 1. the user selects `/*M!100100 ... */` alone, and the splitter finds /// no statement in it, so nothing cuts it down; /// 2. the user selects one statement with an executable comment inside it, /// and the comment rides in the statement's range, since a token /// follows it. /// /// Before plan 01-04 the typed parser read both as a comment, and /// `classify` called the first a plain read. On a live MariaDB 11.4 that /// text, `SET SESSION TRANSACTION READ WRITE`, disarmed the server's own /// read-only hold, after which an `INSERT` succeeded. This test pins the /// closed hole through the route rather than through `classify` alone. /// /// The buffer is `"-- café\n/*M!100100 SET SESSION TRANSACTION READ WRITE /// */\nSELECT 1;\n"`. The `é` is two bytes, so byte offsets and character /// offsets differ, and the selection is bytes `9..57`: byte 9 follows the /// newline that ends the first line and byte 57 is the end of `*/`. Both /// fall on character boundaries, so the slice cannot panic. #[test] fn a_selection_of_only_an_executable_comment_reaches_the_classifier_whole() { let buffer = "-- café\n/*M!100100 SET SESSION TRANSACTION READ WRITE */\nSELECT 1;\n"; let selection = 9..57; let comment = "/*M!100100 SET SESSION TRANSACTION READ WRITE */"; assert_eq!(&buffer[selection.clone()], comment); for engine in sql_engines() { let found = queued_statements(engine, buffer, Some(selection.clone())); assert!(found.len() <= 1, "{engine:?}: {found:?}"); // SQL Server reads its buffer a batch at a time and trims the one // it sends, so what it submits is not the selection byte for byte. if batches_on(engine) { continue; } let submitted = submitted_for_selection(engine, buffer, selection.clone()) .unwrap_or_else(|| panic!("{engine:?}: a selection that holds text submits it")) .unwrap_or_else(|message| panic!("{engine:?}: {message}")); assert_eq!(submitted, comment, "{engine:?}"); } for engine in marker_engines() { let verdict = classify(engine, comment); assert!(is_stopped(engine, comment), "{engine:?}"); assert!( gate(&verdict, Mode::ReadOnly, &[]).is_some(), "{engine:?}: a Read-only profile lets the release through" ); } // MySQL ignores the comment, and the human confirms it all the same. let verdict = classify(crate::db::Engine::MySql, comment); assert!(verdict.destructive.contains(&Destructive::Unreadable)); assert!(gate(&verdict, Mode::ReadOnly, &[]).is_some()); } /// The second reachable shape: one selected statement with the comment /// inside it. The buffer is `"SELECT 'é' /*M!100100 INTO @y */ FROM t;\n"` /// and the selection is bytes `0..41`, the statement and its `;`. Byte 41 /// is the end of the `;`, a character boundary, and the `é` makes the /// range one byte longer than the 40 characters in it. #[test] fn a_selection_with_an_executable_comment_inside_a_statement_carries_it_to_the_classifier() { let buffer = "SELECT 'é' /*M!100100 INTO @y */ FROM t;\n"; let selection = 0..41; assert_eq!( &buffer[selection.clone()], "SELECT 'é' /*M!100100 INTO @y */ FROM t;" ); for engine in sql_engines() { let found = queued_statements(engine, buffer, Some(selection.clone())); assert_eq!(found.len(), 1, "{engine:?}: {found:?}"); assert!( buffer[found[0].clone()].contains("/*M!100100 INTO @y */"), "{engine:?}: the comment travels inside the statement's range" ); if batches_on(engine) { continue; } let submitted = submitted_for_selection(engine, buffer, selection.clone()) .unwrap_or_else(|| panic!("{engine:?}: a selection that holds text submits it")) .unwrap_or_else(|message| panic!("{engine:?}: {message}")); assert_eq!(submitted, &buffer[selection.clone()], "{engine:?}"); } let submitted = &buffer[selection.clone()]; for engine in marker_engines() { assert!(is_stopped(engine, submitted), "{engine:?}"); assert!( gate(&classify(engine, submitted), Mode::ReadOnly, &[]).is_some(), "{engine:?}" ); } // MySQL ignores the comment, and the human confirms it all the same. let verdict = classify(crate::db::Engine::MySql, submitted); assert!(verdict.destructive.contains(&Destructive::Unreadable)); assert!(gate(&verdict, Mode::ReadOnly, &[]).is_some()); } /// An empty selection does not take the selection branch: `sql_to_run` /// falls through to the statement under the cursor, so the whole-selection /// answer above says nothing about it. Here the cursor sits inside the /// comment, byte 20, and the statement it runs is `SELECT 1`, not the /// comment: the splitter has no statement for a comment on its own. #[test] fn an_empty_selection_runs_the_statement_at_the_cursor_and_not_the_selection() { let buffer = "-- café\n/*M!100100 SET SESSION TRANSACTION READ WRITE */\nSELECT 1;\n"; for engine in sql_engines() { // An empty selection is no selection to `queued_statements`. assert_eq!( queued_statements(engine, buffer, Some(20..20)), queued_statements(engine, buffer, None), "{engine:?}" ); if batches_on(engine) { continue; } let range = Buffer::for_engine(engine, buffer) .statement_at(20) .unwrap_or_else(|| panic!("{engine:?}: the buffer holds a statement")); assert_eq!(&buffer[range], "SELECT 1", "{engine:?}"); } } /// A selection of only whitespace holds nothing to run: `sql_to_run` /// returns no statement and the Run action says so. #[test] fn a_selection_of_only_whitespace_submits_nothing() { let buffer = "SELECT 1;\n \t\n"; // Bytes 10..13 are the space, the tab and the newline after the first // line, all one byte wide. let selection = 10..13; assert_eq!(&buffer[selection.clone()], " \t\n"); for engine in sql_engines() { assert!( submitted_for_selection(engine, buffer, selection.clone()).is_none(), "{engine:?}" ); } } }