Skip to main content

utopia_query/schema/
mongodb.rs

1//! [`MongoDb`]: the MongoDB schema, whose statements are JSON commands.
2
3use php_std::json::{self, Flags};
4use php_std::{Array, ArrayKey, Str, Value};
5
6use super::column::{self, Column};
7use super::enums::ColumnType;
8use super::feature;
9use super::index::IndexOptions;
10use super::table::{self, Table};
11use super::{Schema, base};
12use crate::builder::{AnyBuilder, Executor, Statement};
13use crate::error::{Error, Result};
14
15/// The MongoDB schema: collections with `$jsonSchema` validators, indexes,
16/// views and databases as JSON commands (`{"command": "createCollection", ...}`).
17///
18/// ```
19/// use utopia_query::schema::{MongoDb, Schema};
20///
21/// let mut users = MongoDb::new().table("users");
22/// users.string("email", 255);
23/// users.integer("age").nullable();
24/// assert_eq!(
25///     users.create()?.query,
26///     r#"{"command":"createCollection","collection":"users","validator":{"$jsonSchema":{"bsonType":"object","properties":{"email":{"bsonType":"string"},"age":{"bsonType":"int"}},"required":["email"]}}}"#
27/// );
28/// # Ok::<(), utopia_query::Error>(())
29/// ```
30///
31/// ```php
32/// use Utopia\Query\Schema\MongoDB;
33///
34/// $users = (new MongoDB())->table('users');
35/// $users->string('email');
36/// $users->integer('age')->nullable();
37/// echo $users->create()->query, "\n";
38/// ```
39///
40/// PHP: `Utopia\Query\Schema\MongoDB`.
41#[derive(Clone, Default)]
42pub struct MongoDb {
43    executor: Option<Executor>,
44}
45
46impl std::fmt::Debug for MongoDb {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        f.debug_struct("MongoDb").field("executor", &self.executor.is_some()).finish()
49    }
50}
51
52fn key(name: &str) -> ArrayKey {
53    ArrayKey::normalize(Str::from(name))
54}
55
56fn string(s: &str) -> Value {
57    Value::Str(Str::from(s))
58}
59
60/// An array of `(key, value)` entries, keys as PHP normalises them.
61fn map<'a>(entries: impl IntoIterator<Item = (&'a str, Value)>) -> Value {
62    let mut array = Array::default();
63    for (k, v) in entries {
64        array.set(key(k), v);
65    }
66    Value::Array(array)
67}
68
69fn encode(value: &Value, flags: Flags) -> Result<String> {
70    json::encode(value, flags | Flags::THROW_ON_ERROR, json::DEFAULT_DEPTH)
71        .map_err(|e| Error::query(e.message().to_owned()))
72}
73
74impl MongoDb {
75    /// A MongoDB schema without an executor.
76    ///
77    /// PHP: `new MongoDB()`.
78    pub fn new() -> Self {
79        MongoDb::default()
80    }
81
82    fn command(&self, value: &Value, flags: Flags) -> Result<Statement> {
83        Ok(base::statement(self, encode(value, flags)?, Vec::new()))
84    }
85
86    /// The `$jsonSchema` validator of `table`'s columns (enum values listed
87    /// when `enums`), or `None` without columns.
88    fn validator(&self, table: &Table<Self>, enums: bool) -> Result<Option<Value>> {
89        let columns = table.columns();
90        if columns.is_empty() {
91            return Ok(None);
92        }
93        let mut properties = Array::default();
94        let mut required = Vec::new();
95        for column in columns {
96            let c = &column.def;
97            let mut property = Array::default();
98            property.set(key("bsonType"), string(&self.compile_column_type(column)?));
99            if let Some(comment) = &c.comment {
100                property.set(key("description"), string(comment));
101            }
102            if enums && c.kind == ColumnType::Enum && !c.enum_values.is_empty() {
103                let values = c.enum_values.iter().map(|v| string(v)).collect();
104                property.set(key("enum"), Value::Array(Array::from_list(values)));
105            }
106            properties.set(key(&c.name), Value::Array(property));
107            if !c.nullable && c.default.is_none() {
108                required.push(string(&c.name));
109            }
110        }
111        let mut schema = vec![("bsonType", string("object")), ("properties", Value::Array(properties))];
112        if !required.is_empty() {
113            schema.push(("required", Value::Array(Array::from_list(required))));
114        }
115        Ok(Some(map([("$jsonSchema", map(schema))])))
116    }
117
118    fn collection_command(&self, command: &str, table: &Table<Self>, enums: bool) -> Result<Statement> {
119        let mut entries = vec![("command", string(command)), ("collection", string(table.name()))];
120        if let Some(validator) = self.validator(table, enums)? {
121            entries.push(("validator", validator));
122        }
123        self.command(&map(entries), Flags::UNESCAPED_SLASHES)
124    }
125}
126
127impl Schema for MongoDb {
128    fn executor(&self) -> Option<&Executor> {
129        self.executor.as_ref()
130    }
131
132    fn set_executor(&mut self, executor: Executor) -> &mut Self {
133        self.executor = Some(executor);
134        self
135    }
136
137    /// Identifiers are used as they are.
138    fn quote(&self, identifier: &str) -> Result<String> {
139        Ok(identifier.to_owned())
140    }
141
142    fn quote_literal(&self, identifier: &str) -> Result<String> {
143        Ok(identifier.to_owned())
144    }
145
146    /// The BSON type.
147    fn compile_column_type(&self, column: &Column<Self>) -> Result<String> {
148        Ok(match column.def.kind {
149            ColumnType::String | ColumnType::Varchar | ColumnType::Relationship => "string",
150            ColumnType::Text | ColumnType::MediumText | ColumnType::LongText => "string",
151            ColumnType::TinyInteger
152            | ColumnType::SmallInteger
153            | ColumnType::Integer
154            | ColumnType::BigInteger
155            | ColumnType::Id
156            | ColumnType::Serial
157            | ColumnType::BigSerial
158            | ColumnType::SmallSerial => "int",
159            ColumnType::Float | ColumnType::Double => "double",
160            ColumnType::Decimal => "decimal",
161            ColumnType::Boolean => "bool",
162            ColumnType::Datetime | ColumnType::Timestamp => "date",
163            ColumnType::Json | ColumnType::Object => "object",
164            ColumnType::Binary => "binData",
165            ColumnType::Enum => "string",
166            ColumnType::Point | ColumnType::Linestring | ColumnType::Polygon => "object",
167            ColumnType::Uuid | ColumnType::Uuid7 => "string",
168            ColumnType::Vector | ColumnType::Array | ColumnType::Tuple => "array",
169        }
170        .to_owned())
171    }
172
173    fn compile_auto_increment(&self) -> &'static str {
174        ""
175    }
176
177    /// `createCollection` with a `$jsonSchema` validator.
178    fn compile_create(&self, table: &Table<Self>, _if_not_exists: bool) -> Result<Statement> {
179        self.collection_command("createCollection", table, true)
180    }
181
182    /// `collMod` with the new validator.
183    fn compile_alter(&self, table: &Table<Self>) -> Result<Statement> {
184        self.collection_command("collMod", table, false)
185    }
186
187    fn compile_drop(&self, name: &str, _if_exists: bool) -> Result<Statement> {
188        self.command(&map([("command", string("drop")), ("collection", string(name))]), Flags::NONE)
189    }
190
191    fn compile_rename(&self, from: &str, to: &str) -> Result<Statement> {
192        self.command(
193            &map([("command", string("renameCollection")), ("from", string(from)), ("to", string(to))]),
194            Flags::NONE,
195        )
196    }
197
198    /// `deleteMany` with an empty filter.
199    fn compile_truncate(&self, name: &str) -> Result<Statement> {
200        self.command(
201            &map([
202                ("command", string("deleteMany")),
203                ("collection", string(name)),
204                ("filter", Value::Object(Array::default())),
205            ]),
206            Flags::NONE,
207        )
208    }
209
210    /// `createIndex` with `1` / `-1` keys (from the orders) and `unique`.
211    fn create_index(&self, table: &str, name: &str, columns: &[&str], options: &IndexOptions) -> Result<Statement> {
212        let mut keys = Array::default();
213        for column in columns {
214            let order = options.orders.iter().rev().find(|(c, _)| c == column).map(|(_, o)| o);
215            let direction = match order {
216                Some(order) if order.eq_ignore_ascii_case("desc") => -1,
217                _ => 1,
218            };
219            keys.set(key(column), Value::Int(direction));
220        }
221        let mut index = vec![("key", Value::Array(keys)), ("name", string(name))];
222        if options.unique {
223            index.push(("unique", Value::Bool(true)));
224        }
225        self.command(
226            &map([("command", string("createIndex")), ("collection", string(table)), ("index", map(index))]),
227            Flags::UNESCAPED_SLASHES,
228        )
229    }
230
231    fn drop_index(&self, table: &str, name: &str) -> Result<Statement> {
232        self.command(
233            &map([("command", string("dropIndex")), ("collection", string(table)), ("index", string(name))]),
234            Flags::NONE,
235        )
236    }
237}
238
239impl column::Comment for MongoDb {}
240impl table::Serial for MongoDb {}
241
242impl feature::Views for MongoDb {
243    /// `createView` over the source collection and pipeline of the
244    /// builder's command.
245    fn create_view(&self, name: &str, query: &mut dyn AnyBuilder) -> Result<Statement> {
246        let built = query.build()?;
247        let op =
248            json::decode(built.query.as_bytes(), Some(true), json::DEFAULT_DEPTH, Flags::NONE).unwrap_or(Value::Null);
249        if matches!(op, Value::Null) {
250            return Err(Error::Validation("Cannot parse query for MongoDB view creation.".into()));
251        }
252        let field = |name: &str| match &op {
253            Value::Array(a) => a.get_str(name).filter(|v| !matches!(v, Value::Null)).cloned(),
254            _ => None,
255        };
256        let command = map([
257            ("command", string("createView")),
258            ("view", string(name)),
259            ("source", field("collection").unwrap_or_else(|| string(""))),
260            ("pipeline", field("pipeline").unwrap_or(Value::Array(Array::default()))),
261        ]);
262        Ok(base::statement(self, encode(&command, Flags::UNESCAPED_SLASHES)?, built.bindings))
263    }
264
265    fn drop_view(&self, name: &str) -> Result<Statement> {
266        self.command(&map([("command", string("drop")), ("collection", string(name))]), Flags::NONE)
267    }
268}
269
270impl feature::Databases for MongoDb {
271    fn create_database(&self, name: &str) -> Result<Statement> {
272        self.command(&map([("command", string("createDatabase")), ("database", string(name))]), Flags::NONE)
273    }
274
275    fn drop_database(&self, name: &str) -> Result<Statement> {
276        self.command(&map([("command", string("dropDatabase")), ("database", string(name))]), Flags::NONE)
277    }
278}
279
280impl feature::AnalyzeTable for MongoDb {
281    fn analyze_table(&self, table: &str) -> Result<Statement> {
282        self.command(&map([("command", string("collStats")), ("collection", string(table))]), Flags::NONE)
283    }
284}