1use crate::error::{Failure, Result};
18use crate::sql::parse::{parse, ParseLimits};
19use sqlparser::ast::Statement;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum Classification {
24 Read,
26 Change,
28 Definition,
30 Administration,
32}
33
34impl Classification {
35 #[must_use]
37 pub const fn as_str(self) -> &'static str {
38 match self {
39 Self::Read => "read",
40 Self::Change => "change",
41 Self::Definition => "definition",
42 Self::Administration => "administration",
43 }
44 }
45
46 #[must_use]
48 pub const fn is_read(self) -> bool {
49 matches!(self, Self::Read)
50 }
51}
52
53#[derive(Debug, Clone)]
55pub struct Analysis {
56 classification: Classification,
57 kind: &'static str,
58 statements: Vec<Statement>,
59}
60
61impl Analysis {
62 #[must_use]
64 pub const fn classification(&self) -> Classification {
65 self.classification
66 }
67
68 #[must_use]
72 pub const fn kind(&self) -> &'static str {
73 self.kind
74 }
75
76 #[must_use]
78 pub fn statements(&self) -> &[Statement] {
79 &self.statements
80 }
81}
82
83pub fn analyze(sql: &str, limits: ParseLimits) -> Result<Analysis> {
90 if let Some(known) = recalled(sql, limits) {
91 return Ok(known);
92 }
93 let fresh = read_fresh(sql, limits)?;
94 remember(sql, limits, &fresh);
95 Ok(fresh)
96}
97
98type Remembered = Option<(String, ParseLimits, Analysis)>;
119
120thread_local! {
121 static LAST_READ: core::cell::RefCell<Remembered> = const { core::cell::RefCell::new(None) };
122}
123
124fn recalled(sql: &str, limits: ParseLimits) -> Option<Analysis> {
126 LAST_READ.with_borrow(|held| {
127 held.as_ref().and_then(|(text, held_limits, analysis)| {
128 (text == sql && *held_limits == limits).then(|| analysis.clone())
129 })
130 })
131}
132
133fn remember(sql: &str, limits: ParseLimits, analysis: &Analysis) {
135 LAST_READ.with_borrow_mut(|held| {
136 *held = Some((sql.to_owned(), limits, analysis.clone()));
137 });
138}
139
140fn read_fresh(sql: &str, limits: ParseLimits) -> Result<Analysis> {
142 note_fresh_read();
143 let statements = parse(sql, limits)?;
144 let first = statements.first().ok_or_else(|| {
145 Failure::validation("sql.empty", "the statement is empty").with_hint("send one statement")
146 })?;
147 let (classification, kind) = read_statement(first)?;
148 Ok(Analysis {
149 classification,
150 kind,
151 statements,
152 })
153}
154
155pub fn classify(sql: &str, limits: ParseLimits) -> Result<Classification> {
161 analyze(sql, limits).map(|analysis| analysis.classification)
162}
163
164fn read_statement(statement: &Statement) -> Result<(Classification, &'static str)> {
169 if let Statement::Explain {
172 analyze: true,
173 statement: inner,
174 ..
175 } = statement
176 {
177 return read_statement(inner);
178 }
179
180 if let Some(kind) = read_kind(statement) {
181 return Ok((Classification::Read, kind));
182 }
183 if let Some(kind) = change_kind(statement) {
184 return Ok((Classification::Change, kind));
185 }
186 if let Some(kind) = definition_kind(statement) {
187 return Ok((Classification::Definition, kind));
188 }
189 if let Some(kind) = administration_kind(statement) {
190 return Ok((Classification::Administration, kind));
191 }
192
193 Err(Failure::validation(
194 "sql.unclassified",
195 "the statement has a shape this tool does not recognise",
196 )
197 .with_hint("a statement that cannot be classified is refused rather than assumed to be a read"))
198}
199
200fn read_kind(statement: &Statement) -> Option<&'static str> {
202 Some(match statement {
203 Statement::Query(_) => "select",
204 Statement::Explain { .. } => "explain",
205 Statement::ExplainTable { .. } => "describe",
206 Statement::ShowCatalogs { .. } => "show_catalogs",
207 Statement::ShowCharset(_) => "show_charset",
208 Statement::ShowCollation { .. } => "show_collation",
209 Statement::ShowColumns { .. } => "show_columns",
210 Statement::ShowCreate { .. } => "show_create",
211 Statement::ShowDatabases { .. } => "show_databases",
212 Statement::ShowFunctions { .. } => "show_functions",
213 Statement::ShowObjects(_) => "show_objects",
214 Statement::ShowProcessList { .. } => "show_process_list",
215 Statement::ShowSchemas { .. } => "show_schemas",
216 Statement::ShowStatus { .. } => "show_status",
217 Statement::ShowTables { .. } => "show_tables",
218 Statement::ShowVariable { .. } => "show_variable",
219 Statement::ShowVariables { .. } => "show_variables",
220 Statement::ShowViews { .. } => "show_views",
221 _ => return None,
222 })
223}
224
225fn change_kind(statement: &Statement) -> Option<&'static str> {
227 Some(match statement {
228 Statement::Insert(_) => "insert",
229 Statement::Update(_) => "update",
230 Statement::Delete(_) => "delete",
231 Statement::Merge(_) => "merge",
232 Statement::Copy { .. } => "copy",
233 Statement::Directory { .. } => "insert_into_directory",
234 Statement::LoadData { .. } => "load_data",
235 Statement::Unload { .. } => "unload",
236 _ => return None,
237 })
238}
239
240fn definition_kind(statement: &Statement) -> Option<&'static str> {
245 Some(match statement {
246 Statement::AlterFunction(_) => "alter_function",
247 Statement::AlterIndex { .. } => "alter_index",
248 Statement::AlterSchema(_) => "alter_schema",
249 Statement::AlterTable(_) => "alter_table",
250 Statement::AlterType(_) => "alter_type",
251 Statement::AlterView { .. } => "alter_view",
252 Statement::CreateDatabase { .. } => "create_database",
253 Statement::CreateFunction(_) => "create_function",
254 Statement::CreateIndex(_) => "create_index",
255 Statement::CreateProcedure { .. } => "create_procedure",
256 Statement::CreateSchema { .. } => "create_schema",
257 Statement::CreateSequence { .. } => "create_sequence",
258 Statement::CreateTable(_) => "create_table",
259 Statement::CreateTrigger(_) => "create_trigger",
260 Statement::CreateType { .. } => "create_type",
261 Statement::CreateView(_) => "create_view",
262 Statement::CreateVirtualTable { .. } => "create_virtual_table",
263 Statement::Drop { .. } => "drop",
264 Statement::DropFunction(_) => "drop_function",
265 Statement::DropProcedure { .. } => "drop_procedure",
266 Statement::DropTrigger(_) => "drop_trigger",
267 Statement::RenameTable(_) => "rename_table",
268 Statement::Truncate(_) => "truncate",
269 _ => return None,
270 })
271}
272
273fn administration_kind(statement: &Statement) -> Option<&'static str> {
276 Some(match statement {
277 Statement::Analyze(_) => "analyze",
278 Statement::AlterRole { .. } => "alter_role",
279 Statement::Call(_) => "call",
280 Statement::Commit { .. } => "commit",
281 Statement::CreateRole(_) => "create_role",
282 Statement::Deallocate { .. } => "deallocate",
283 Statement::Deny(_) => "deny",
284 Statement::Execute { .. } => "execute",
285 Statement::Flush { .. } => "flush",
286 Statement::Grant(_) => "grant",
287 Statement::Install { .. } => "install",
288 Statement::Kill { .. } => "kill",
289 Statement::Lock(_) => "lock",
290 Statement::LockTables { .. } => "lock_tables",
291 Statement::OptimizeTable { .. } => "optimize_table",
292 Statement::Prepare { .. } => "prepare",
293 Statement::ReleaseSavepoint { .. } => "release_savepoint",
294 Statement::Revoke(_) => "revoke",
295 Statement::Rollback { .. } => "rollback",
296 Statement::Savepoint { .. } => "savepoint",
297 Statement::Set(_) => "set",
298 Statement::StartTransaction { .. } => "start_transaction",
299 Statement::UnlockTables => "unlock_tables",
300 Statement::Use(_) => "use",
301 _ => return None,
302 })
303}
304
305#[cfg(test)]
321thread_local! {
322 static FRESH_READS: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };
323}
324
325#[cfg(test)]
330fn note_fresh_read() {
331 FRESH_READS.with(|count| count.set(count.get() + 1));
332}
333
334#[cfg(not(test))]
336const fn note_fresh_read() {}
337
338#[cfg(test)]
339mod tests {
340 use super::*;
341
342 fn kind_of(sql: &str) -> (Classification, &'static str) {
343 let analysis = analyze(sql, ParseLimits::default()).expect("recognised statement");
344 (analysis.classification(), analysis.kind())
345 }
346
347 fn readings_during(work: impl FnOnce()) -> usize {
354 let before = FRESH_READS.with(core::cell::Cell::get);
355 work();
356 FRESH_READS.with(core::cell::Cell::get) - before
357 }
358
359 #[test]
360 fn one_statement_read_twice_is_parsed_once() {
361 let sql = "SELECT 1 /* read twice */";
362 let readings = readings_during(|| {
363 let first = analyze(sql, ParseLimits::default()).expect("read");
364 let second = analyze(sql, ParseLimits::default()).expect("read");
365 assert_eq!(first.classification(), second.classification());
366 assert_eq!(first.kind(), second.kind());
367 });
368 assert_eq!(
369 readings, 1,
370 "the second reading of one statement must be served, not parsed again"
371 );
372 }
373
374 #[test]
375 fn what_is_held_is_one_statement_and_not_a_map() {
376 let one = "SELECT 1 /* held first */";
377 let other = "SELECT 2 /* held second */";
378 let readings = readings_during(|| {
379 analyze(one, ParseLimits::default()).expect("read");
380 analyze(other, ParseLimits::default()).expect("read");
381 analyze(one, ParseLimits::default()).expect("read");
382 });
383 assert_eq!(
384 readings, 3,
385 "a second statement replaces the first, so returning to it costs a reading"
386 );
387 }
388
389 #[test]
390 fn the_same_text_under_other_limits_is_read_again() {
391 let sql = "SELECT 1 /* two ceilings */";
392 let readings = readings_during(|| {
393 analyze(sql, ParseLimits::default()).expect("read");
394 analyze(sql, ParseLimits::new(4096, 0)).expect("read");
395 });
396 assert_eq!(
397 readings, 2,
398 "limits are part of what was asked, so a different ceiling is a different question"
399 );
400 }
401
402 #[test]
403 fn a_refusal_is_not_held() {
404 let sql = "SELECT FROM WHERE /* refused twice */";
405 let readings = readings_during(|| {
406 analyze(sql, ParseLimits::default()).expect_err("refused");
407 analyze(sql, ParseLimits::default()).expect_err("refused");
408 });
409 assert_eq!(
410 readings, 2,
411 "a refusal is answered once and the invocation ends, so nothing is stored for it"
412 );
413 }
414
415 #[test]
416 fn a_select_is_a_read() {
417 assert_eq!(kind_of("SELECT 1").0, Classification::Read);
418 assert_eq!(kind_of("SELECT * FROM t WHERE a = 1").1, "select");
419 }
420
421 #[test]
422 fn the_row_changing_statements_are_changes() {
423 for sql in [
424 "INSERT INTO t (a) VALUES (1)",
425 "UPDATE t SET a = 1",
426 "DELETE FROM t",
427 ] {
428 assert_eq!(kind_of(sql).0, Classification::Change, "input {sql:?}");
429 }
430 }
431
432 #[test]
433 fn the_object_changing_statements_are_definitions() {
434 for sql in [
435 "CREATE TABLE t (a INT)",
436 "DROP TABLE t",
437 "ALTER TABLE t ADD COLUMN b INT",
438 "TRUNCATE TABLE t",
439 ] {
440 assert_eq!(kind_of(sql).0, Classification::Definition, "input {sql:?}");
441 }
442 }
443
444 #[test]
445 fn the_session_and_privilege_statements_are_administration() {
446 for sql in [
447 "SET autocommit = 1",
448 "START TRANSACTION",
449 "COMMIT",
450 "ROLLBACK",
451 "USE other",
452 ] {
453 assert_eq!(
454 kind_of(sql).0,
455 Classification::Administration,
456 "input {sql:?}"
457 );
458 }
459 }
460
461 #[test]
464 fn a_destructive_statement_hidden_behind_a_comment_is_still_a_change() {
465 for sql in [
466 "/* SELECT */ DELETE FROM users",
467 "-- SELECT 1\nDELETE FROM users",
468 "DELETE /* looks harmless */ FROM users",
469 "# SELECT 1\nDELETE FROM users",
470 ] {
471 assert_eq!(kind_of(sql).0, Classification::Change, "input {sql:?}");
472 }
473 }
474
475 #[test]
476 fn a_reserved_word_inside_a_literal_does_not_change_the_decision() {
477 for sql in [
478 "SELECT 'DROP TABLE users' AS note",
479 "SELECT * FROM t WHERE note = 'DELETE FROM users'",
480 "SELECT \"CREATE TABLE x\" AS note",
481 ] {
482 assert_eq!(kind_of(sql).0, Classification::Read, "input {sql:?}");
483 }
484 }
485
486 #[test]
487 fn letter_case_does_not_change_the_decision() {
488 assert_eq!(kind_of("select 1").0, Classification::Read);
489 assert_eq!(kind_of("SeLeCt 1").0, Classification::Read);
490 assert_eq!(kind_of("delete from t").0, Classification::Change);
491 assert_eq!(kind_of("DeLeTe FrOm t").0, Classification::Change);
492 }
493
494 #[test]
495 fn a_plain_explain_is_a_read_even_over_a_destructive_statement() {
496 assert_eq!(kind_of("EXPLAIN DELETE FROM t").0, Classification::Read);
497 }
498
499 #[test]
502 fn an_explain_that_runs_the_statement_inherits_what_that_statement_does() {
503 assert_eq!(
504 kind_of("EXPLAIN ANALYZE DELETE FROM t").0,
505 Classification::Change
506 );
507 assert_eq!(kind_of("EXPLAIN ANALYZE SELECT 1").0, Classification::Read);
508 }
509
510 #[test]
511 fn an_unparsable_statement_is_refused_and_never_read_as_a_query() {
512 let failure = analyze("SELECT FROM WHERE", ParseLimits::default())
513 .expect_err("unparsable text is refused");
514 assert_eq!(failure.code(), "sql.unparsable");
515 }
516
517 #[test]
518 fn an_empty_statement_is_refused() {
519 let failure =
520 analyze(" ", ParseLimits::default()).expect_err("an empty statement is refused");
521 assert!(matches!(failure.code(), "sql.empty" | "sql.unparsable"));
522 }
523
524 #[test]
526 fn the_parsed_tree_is_exposed_for_the_guards_and_for_simulation() {
527 let analysis = analyze("SELECT 1", ParseLimits::default()).expect("read");
528 assert_eq!(analysis.statements().len(), 1);
529 assert!(analysis.classification().is_read());
530 }
531}