utopia_query/classifier/mod.rs
1//! Statement classifiers: whether a wire protocol message reads, writes or
2//! controls a transaction, so a proxy can route it to a replica or the
3//! primary.
4//!
5//! A classifier does not parse: the SQL classifiers read the leading keyword
6//! (skipping whitespace, comments and quoted literals), and the MongoDB
7//! classifier reads the first key of an `OP_MSG` command document. For a
8//! structural parse of SQL, see [`crate::ast`].
9//!
10//! Every classifier implements [`Classifier`]; the SQL ones also implement
11//! [`Sql`], which classifies bare SQL text and holds the shared keyword logic.
12//! Messages are bytes (`&[u8]`), as they arrive on the wire.
13//!
14//! PHP: `Utopia\Query\Classifier`, `Utopia\Query\Classifier\*`.
15//!
16//! | PHP | Rust |
17//! |---|---|
18//! | `Classifier` (interface), `classify()` | [`Classifier`], [`Classifier::classify`] |
19//! | `Classifier\SQL` (abstract), `classifySQL()`, `extractKeyword()` | [`Sql`], [`Sql::classify_sql`], [`Sql::extract_keyword`] |
20//! | `Classifier\MySQL` | [`MySql`] |
21//! | `Classifier\PostgreSQL` | [`PostgreSql`] |
22//! | `Classifier\MongoDB` | [`MongoDb`] |
23//! | `Type` | [`crate::Type`] |
24//!
25//! ```
26//! use utopia_query::Type;
27//! use utopia_query::classifier::{Classifier, PostgreSql, Sql};
28//!
29//! let classifier = PostgreSql;
30//! assert_eq!(classifier.classify(b"Q\x00\x00\x00\x0dSELECT 1\x00"), Type::Read);
31//! assert_eq!(classifier.classify_sql(b"/* hint */ insert into t values (1)"), Type::Write);
32//! assert_eq!(classifier.extract_keyword(b" begin;"), b"BEGIN");
33//! ```
34//!
35//! ```php
36//! use Utopia\Query\Classifier\PostgreSQL;
37//! use Utopia\Query\Type;
38//!
39//! $classifier = new PostgreSQL();
40//! var_dump($classifier->classify("Q\x00\x00\x00\x0dSELECT 1\x00") === Type::Read); // bool(true)
41//! var_dump($classifier->classifySQL('/* hint */ insert into t values (1)') === Type::Write); // bool(true)
42//! echo $classifier->extractKeyword(' begin;'), "\n"; // BEGIN
43//! ```
44
45mod mongodb;
46mod mysql;
47mod postgresql;
48mod sql;
49
50pub use mongodb::MongoDb;
51pub use mysql::MySql;
52pub use postgresql::PostgreSql;
53pub use sql::Sql;
54
55use crate::Type;
56
57/// Classifies a raw wire protocol message as a read, a write, a
58/// transaction statement or unknown. Implement it to route another protocol.
59///
60/// PHP: `Utopia\Query\Classifier`.
61pub trait Classifier {
62 /// The classification of the raw message `data`.
63 ///
64 /// PHP: `Classifier::classify()`.
65 fn classify(&self, data: &[u8]) -> Type;
66}