use crate::error::{Failure, Result};
use crate::sql::parse::{parse, ParseLimits};
use sqlparser::ast::Statement;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Classification {
Read,
Change,
Definition,
Administration,
}
impl Classification {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Read => "read",
Self::Change => "change",
Self::Definition => "definition",
Self::Administration => "administration",
}
}
#[must_use]
pub const fn is_read(self) -> bool {
matches!(self, Self::Read)
}
}
#[derive(Debug, Clone)]
pub struct Analysis {
classification: Classification,
kind: &'static str,
statements: Vec<Statement>,
}
impl Analysis {
#[must_use]
pub const fn classification(&self) -> Classification {
self.classification
}
#[must_use]
pub const fn kind(&self) -> &'static str {
self.kind
}
#[must_use]
pub fn statements(&self) -> &[Statement] {
&self.statements
}
}
pub fn analyze(sql: &str, limits: ParseLimits) -> Result<Analysis> {
if let Some(known) = recalled(sql, limits) {
return Ok(known);
}
let fresh = read_fresh(sql, limits)?;
remember(sql, limits, &fresh);
Ok(fresh)
}
type Remembered = Option<(String, ParseLimits, Analysis)>;
thread_local! {
static LAST_READ: core::cell::RefCell<Remembered> = const { core::cell::RefCell::new(None) };
}
fn recalled(sql: &str, limits: ParseLimits) -> Option<Analysis> {
LAST_READ.with_borrow(|held| {
held.as_ref().and_then(|(text, held_limits, analysis)| {
(text == sql && *held_limits == limits).then(|| analysis.clone())
})
})
}
fn remember(sql: &str, limits: ParseLimits, analysis: &Analysis) {
LAST_READ.with_borrow_mut(|held| {
*held = Some((sql.to_owned(), limits, analysis.clone()));
});
}
fn read_fresh(sql: &str, limits: ParseLimits) -> Result<Analysis> {
note_fresh_read();
let statements = parse(sql, limits)?;
let first = statements.first().ok_or_else(|| {
Failure::validation("sql.empty", "the statement is empty").with_hint("send one statement")
})?;
let (classification, kind) = read_statement(first)?;
Ok(Analysis {
classification,
kind,
statements,
})
}
pub fn classify(sql: &str, limits: ParseLimits) -> Result<Classification> {
analyze(sql, limits).map(|analysis| analysis.classification)
}
fn read_statement(statement: &Statement) -> Result<(Classification, &'static str)> {
if let Statement::Explain {
analyze: true,
statement: inner,
..
} = statement
{
return read_statement(inner);
}
if let Some(kind) = read_kind(statement) {
return Ok((Classification::Read, kind));
}
if let Some(kind) = change_kind(statement) {
return Ok((Classification::Change, kind));
}
if let Some(kind) = definition_kind(statement) {
return Ok((Classification::Definition, kind));
}
if let Some(kind) = administration_kind(statement) {
return Ok((Classification::Administration, kind));
}
Err(Failure::validation(
"sql.unclassified",
"the statement has a shape this tool does not recognise",
)
.with_hint("a statement that cannot be classified is refused rather than assumed to be a read"))
}
fn read_kind(statement: &Statement) -> Option<&'static str> {
Some(match statement {
Statement::Query(_) => "select",
Statement::Explain { .. } => "explain",
Statement::ExplainTable { .. } => "describe",
Statement::ShowCatalogs { .. } => "show_catalogs",
Statement::ShowCharset(_) => "show_charset",
Statement::ShowCollation { .. } => "show_collation",
Statement::ShowColumns { .. } => "show_columns",
Statement::ShowCreate { .. } => "show_create",
Statement::ShowDatabases { .. } => "show_databases",
Statement::ShowFunctions { .. } => "show_functions",
Statement::ShowObjects(_) => "show_objects",
Statement::ShowProcessList { .. } => "show_process_list",
Statement::ShowSchemas { .. } => "show_schemas",
Statement::ShowStatus { .. } => "show_status",
Statement::ShowTables { .. } => "show_tables",
Statement::ShowVariable { .. } => "show_variable",
Statement::ShowVariables { .. } => "show_variables",
Statement::ShowViews { .. } => "show_views",
_ => return None,
})
}
fn change_kind(statement: &Statement) -> Option<&'static str> {
Some(match statement {
Statement::Insert(_) => "insert",
Statement::Update(_) => "update",
Statement::Delete(_) => "delete",
Statement::Merge(_) => "merge",
Statement::Copy { .. } => "copy",
Statement::Directory { .. } => "insert_into_directory",
Statement::LoadData { .. } => "load_data",
Statement::Unload { .. } => "unload",
_ => return None,
})
}
fn definition_kind(statement: &Statement) -> Option<&'static str> {
Some(match statement {
Statement::AlterFunction(_) => "alter_function",
Statement::AlterIndex { .. } => "alter_index",
Statement::AlterSchema(_) => "alter_schema",
Statement::AlterTable(_) => "alter_table",
Statement::AlterType(_) => "alter_type",
Statement::AlterView { .. } => "alter_view",
Statement::CreateDatabase { .. } => "create_database",
Statement::CreateFunction(_) => "create_function",
Statement::CreateIndex(_) => "create_index",
Statement::CreateProcedure { .. } => "create_procedure",
Statement::CreateSchema { .. } => "create_schema",
Statement::CreateSequence { .. } => "create_sequence",
Statement::CreateTable(_) => "create_table",
Statement::CreateTrigger(_) => "create_trigger",
Statement::CreateType { .. } => "create_type",
Statement::CreateView(_) => "create_view",
Statement::CreateVirtualTable { .. } => "create_virtual_table",
Statement::Drop { .. } => "drop",
Statement::DropFunction(_) => "drop_function",
Statement::DropProcedure { .. } => "drop_procedure",
Statement::DropTrigger(_) => "drop_trigger",
Statement::RenameTable(_) => "rename_table",
Statement::Truncate(_) => "truncate",
_ => return None,
})
}
fn administration_kind(statement: &Statement) -> Option<&'static str> {
Some(match statement {
Statement::Analyze(_) => "analyze",
Statement::AlterRole { .. } => "alter_role",
Statement::Call(_) => "call",
Statement::Commit { .. } => "commit",
Statement::CreateRole(_) => "create_role",
Statement::Deallocate { .. } => "deallocate",
Statement::Deny(_) => "deny",
Statement::Execute { .. } => "execute",
Statement::Flush { .. } => "flush",
Statement::Grant(_) => "grant",
Statement::Install { .. } => "install",
Statement::Kill { .. } => "kill",
Statement::Lock(_) => "lock",
Statement::LockTables { .. } => "lock_tables",
Statement::OptimizeTable { .. } => "optimize_table",
Statement::Prepare { .. } => "prepare",
Statement::ReleaseSavepoint { .. } => "release_savepoint",
Statement::Revoke(_) => "revoke",
Statement::Rollback { .. } => "rollback",
Statement::Savepoint { .. } => "savepoint",
Statement::Set(_) => "set",
Statement::StartTransaction { .. } => "start_transaction",
Statement::UnlockTables => "unlock_tables",
Statement::Use(_) => "use",
_ => return None,
})
}
#[cfg(test)]
thread_local! {
static FRESH_READS: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };
}
#[cfg(test)]
fn note_fresh_read() {
FRESH_READS.with(|count| count.set(count.get() + 1));
}
#[cfg(not(test))]
const fn note_fresh_read() {}
#[cfg(test)]
mod tests {
use super::*;
fn kind_of(sql: &str) -> (Classification, &'static str) {
let analysis = analyze(sql, ParseLimits::default()).expect("recognised statement");
(analysis.classification(), analysis.kind())
}
fn readings_during(work: impl FnOnce()) -> usize {
let before = FRESH_READS.with(core::cell::Cell::get);
work();
FRESH_READS.with(core::cell::Cell::get) - before
}
#[test]
fn one_statement_read_twice_is_parsed_once() {
let sql = "SELECT 1 /* read twice */";
let readings = readings_during(|| {
let first = analyze(sql, ParseLimits::default()).expect("read");
let second = analyze(sql, ParseLimits::default()).expect("read");
assert_eq!(first.classification(), second.classification());
assert_eq!(first.kind(), second.kind());
});
assert_eq!(
readings, 1,
"the second reading of one statement must be served, not parsed again"
);
}
#[test]
fn what_is_held_is_one_statement_and_not_a_map() {
let one = "SELECT 1 /* held first */";
let other = "SELECT 2 /* held second */";
let readings = readings_during(|| {
analyze(one, ParseLimits::default()).expect("read");
analyze(other, ParseLimits::default()).expect("read");
analyze(one, ParseLimits::default()).expect("read");
});
assert_eq!(
readings, 3,
"a second statement replaces the first, so returning to it costs a reading"
);
}
#[test]
fn the_same_text_under_other_limits_is_read_again() {
let sql = "SELECT 1 /* two ceilings */";
let readings = readings_during(|| {
analyze(sql, ParseLimits::default()).expect("read");
analyze(sql, ParseLimits::new(4096, 0)).expect("read");
});
assert_eq!(
readings, 2,
"limits are part of what was asked, so a different ceiling is a different question"
);
}
#[test]
fn a_refusal_is_not_held() {
let sql = "SELECT FROM WHERE /* refused twice */";
let readings = readings_during(|| {
analyze(sql, ParseLimits::default()).expect_err("refused");
analyze(sql, ParseLimits::default()).expect_err("refused");
});
assert_eq!(
readings, 2,
"a refusal is answered once and the invocation ends, so nothing is stored for it"
);
}
#[test]
fn a_select_is_a_read() {
assert_eq!(kind_of("SELECT 1").0, Classification::Read);
assert_eq!(kind_of("SELECT * FROM t WHERE a = 1").1, "select");
}
#[test]
fn the_row_changing_statements_are_changes() {
for sql in [
"INSERT INTO t (a) VALUES (1)",
"UPDATE t SET a = 1",
"DELETE FROM t",
] {
assert_eq!(kind_of(sql).0, Classification::Change, "input {sql:?}");
}
}
#[test]
fn the_object_changing_statements_are_definitions() {
for sql in [
"CREATE TABLE t (a INT)",
"DROP TABLE t",
"ALTER TABLE t ADD COLUMN b INT",
"TRUNCATE TABLE t",
] {
assert_eq!(kind_of(sql).0, Classification::Definition, "input {sql:?}");
}
}
#[test]
fn the_session_and_privilege_statements_are_administration() {
for sql in [
"SET autocommit = 1",
"START TRANSACTION",
"COMMIT",
"ROLLBACK",
"USE other",
] {
assert_eq!(
kind_of(sql).0,
Classification::Administration,
"input {sql:?}"
);
}
}
#[test]
fn a_destructive_statement_hidden_behind_a_comment_is_still_a_change() {
for sql in [
"/* SELECT */ DELETE FROM users",
"-- SELECT 1\nDELETE FROM users",
"DELETE /* looks harmless */ FROM users",
"# SELECT 1\nDELETE FROM users",
] {
assert_eq!(kind_of(sql).0, Classification::Change, "input {sql:?}");
}
}
#[test]
fn a_reserved_word_inside_a_literal_does_not_change_the_decision() {
for sql in [
"SELECT 'DROP TABLE users' AS note",
"SELECT * FROM t WHERE note = 'DELETE FROM users'",
"SELECT \"CREATE TABLE x\" AS note",
] {
assert_eq!(kind_of(sql).0, Classification::Read, "input {sql:?}");
}
}
#[test]
fn letter_case_does_not_change_the_decision() {
assert_eq!(kind_of("select 1").0, Classification::Read);
assert_eq!(kind_of("SeLeCt 1").0, Classification::Read);
assert_eq!(kind_of("delete from t").0, Classification::Change);
assert_eq!(kind_of("DeLeTe FrOm t").0, Classification::Change);
}
#[test]
fn a_plain_explain_is_a_read_even_over_a_destructive_statement() {
assert_eq!(kind_of("EXPLAIN DELETE FROM t").0, Classification::Read);
}
#[test]
fn an_explain_that_runs_the_statement_inherits_what_that_statement_does() {
assert_eq!(
kind_of("EXPLAIN ANALYZE DELETE FROM t").0,
Classification::Change
);
assert_eq!(kind_of("EXPLAIN ANALYZE SELECT 1").0, Classification::Read);
}
#[test]
fn an_unparsable_statement_is_refused_and_never_read_as_a_query() {
let failure = analyze("SELECT FROM WHERE", ParseLimits::default())
.expect_err("unparsable text is refused");
assert_eq!(failure.code(), "sql.unparsable");
}
#[test]
fn an_empty_statement_is_refused() {
let failure =
analyze(" ", ParseLimits::default()).expect_err("an empty statement is refused");
assert!(matches!(failure.code(), "sql.empty" | "sql.unparsable"));
}
#[test]
fn the_parsed_tree_is_exposed_for_the_guards_and_for_simulation() {
let analysis = analyze("SELECT 1", ParseLimits::default()).expect("read");
assert_eq!(analysis.statements().len(), 1);
assert!(analysis.classification().is_read());
}
}