utopia_query/hook.rs
1//! Hooks: code a builder runs while compiling, to scope every query
2//! ([`Filter`], [`JoinFilter`]) or map attribute names to columns
3//! ([`Attribute`]). [`Tenant`] and [`Map`] are the hooks the library ships.
4//!
5//! PHP: `Utopia\Query\Hook`, `Hook\Filter`, `Hook\Attribute`, `Hook\Join\Filter`, `Hook\Write`.
6//!
7//! | PHP | Rust |
8//! |---|---|
9//! | `Hook` (a marker interface) | [`Hook`] (what [`Builder::add_hook`](crate::builder::Builder::add_hook) takes) |
10//! | `Hook\Filter` | [`Filter`] |
11//! | `Hook\Attribute` | [`Attribute`] |
12//! | `Hook\Join\Filter` | [`JoinFilter`] |
13//! | `Hook\Join\Condition` | [`JoinCondition`] |
14//! | `Hook\Join\Placement` | [`Placement`] |
15//! | `Hook\Write` | [`Write`] |
16//! | `Hook\Filter\Tenant` | [`Tenant`] |
17//! | `Hook\Attribute\Map` | [`Map`] |
18
19use std::collections::HashMap;
20use std::sync::Arc;
21
22use crate::builder::{Condition, JoinType};
23use crate::error::{Error, Result};
24use crate::value::{Array, IntoValues, Value};
25
26/// Adds a condition to the `WHERE` of every query on a table (tenancy,
27/// permissions).
28///
29/// PHP: `Utopia\Query\Hook\Filter`.
30pub trait Filter: Send + Sync {
31 /// The condition for `table` (the alias when the query has one).
32 fn filter(&self, table: &str) -> Result<Condition>;
33}
34
35/// Maps an attribute name to the column it is stored in.
36///
37/// PHP: `Utopia\Query\Hook\Attribute`.
38pub trait Attribute: Send + Sync {
39 /// The column for `attribute`.
40 fn resolve(&self, attribute: &str) -> Result<String>;
41}
42
43/// Scopes a joined table: a condition for the join, placed in its `ON` or in
44/// the `WHERE`, or nothing.
45///
46/// PHP: `Utopia\Query\Hook\Join\Filter`.
47pub trait JoinFilter: Send + Sync {
48 /// The condition for joining `table` (its alias when it has one) with `join_type`.
49 fn filter_join(&self, table: &str, join_type: JoinType) -> Result<Option<JoinCondition>>;
50}
51
52/// Decorates rows before they are written and observes writes, for the
53/// database layer.
54///
55/// PHP: `Utopia\Query\Hook\Write`.
56pub trait Write: Send + Sync {
57 /// The row to write.
58 fn decorate_row(&self, row: Array, metadata: &Array) -> Result<Array>;
59 /// After rows were created.
60 fn after_create(&self, table: &str, metadata: &Array, context: &Value) -> Result<()>;
61 /// After a row was updated.
62 fn after_update(&self, table: &str, metadata: &Array, context: &Value) -> Result<()>;
63 /// After a batch update.
64 fn after_batch_update(&self, table: &str, update_data: &Array, metadata: &Array, context: &Value) -> Result<()>;
65 /// After rows were deleted.
66 fn after_delete(&self, table: &str, ids: &Array, context: &Value) -> Result<()>;
67}
68
69/// A hook a builder accepts: one object may filter, resolve attributes and
70/// filter joins at once (as [`Tenant`] filters both tables and joins).
71///
72/// PHP: `Utopia\Query\Hook`, whose implementations a builder sorts by the
73/// interfaces they implement.
74#[derive(Clone, Default)]
75pub struct Hook {
76 /// The filter part.
77 pub filter: Option<Arc<dyn Filter>>,
78 /// The attribute part.
79 pub attribute: Option<Arc<dyn Attribute>>,
80 /// The join filter part.
81 pub join_filter: Option<Arc<dyn JoinFilter>>,
82}
83
84impl Hook {
85 /// A hook that only filters.
86 pub fn filter(filter: impl Filter + 'static) -> Self {
87 Hook { filter: Some(Arc::new(filter)), ..Hook::default() }
88 }
89
90 /// A hook that only resolves attributes.
91 pub fn attribute(attribute: impl Attribute + 'static) -> Self {
92 Hook { attribute: Some(Arc::new(attribute)), ..Hook::default() }
93 }
94
95 /// A hook that only filters joins.
96 pub fn join_filter(join_filter: impl JoinFilter + 'static) -> Self {
97 Hook { join_filter: Some(Arc::new(join_filter)), ..Hook::default() }
98 }
99}
100
101impl From<Tenant> for Hook {
102 /// Tenant filters both tables and joins.
103 fn from(tenant: Tenant) -> Self {
104 let tenant = Arc::new(tenant);
105 Hook { filter: Some(tenant.clone()), attribute: None, join_filter: Some(tenant) }
106 }
107}
108
109impl From<Map> for Hook {
110 /// Map resolves attributes.
111 fn from(map: Map) -> Self {
112 Hook::attribute(map)
113 }
114}
115
116/// Where a join filter's condition goes.
117///
118/// PHP: `Utopia\Query\Hook\Join\Placement`.
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub enum Placement {
121 /// In the join's `ON`.
122 On,
123 /// In the query's `WHERE`.
124 Where,
125}
126
127impl Placement {
128 /// The case name.
129 pub fn name(self) -> &'static str {
130 match self {
131 Placement::On => "On",
132 Placement::Where => "Where",
133 }
134 }
135}
136
137/// A join filter's condition and where it goes.
138///
139/// PHP: `Utopia\Query\Hook\Join\Condition`.
140#[derive(Debug, Clone, PartialEq)]
141pub struct JoinCondition {
142 /// The condition.
143 pub condition: Condition,
144 /// Where it goes (PHP's default is `Where`).
145 pub placement: Placement,
146}
147
148impl JoinCondition {
149 /// A condition placed as given.
150 pub fn new(condition: Condition, placement: Placement) -> Self {
151 JoinCondition { condition, placement }
152 }
153}
154
155/// Scopes every query, and every joined table, to tenants: `column IN (?, ...)`
156/// (in a left or right join's `ON`, elsewhere in the `WHERE`).
157///
158/// PHP: `Utopia\Query\Hook\Filter\Tenant`.
159///
160/// ```
161/// use utopia_query::builder::MySql;
162/// use utopia_query::hook::Tenant;
163///
164/// let statement = MySql::new().from("docs", "").add_hook(Tenant::new(["7"], "tenant_id")?)?.build()?;
165/// assert_eq!(statement.query, "SELECT * FROM `docs` WHERE tenant_id IN (?)");
166/// # Ok::<(), utopia_query::Error>(())
167/// ```
168///
169/// ```php
170/// use Utopia\Query\Builder\MySQL;
171/// use Utopia\Query\Hook\Filter\Tenant;
172///
173/// echo (new MySQL())->from('docs')->addHook(new Tenant(['7']))->build()->query, "\n"; // SELECT * FROM `docs` WHERE tenant_id IN (?)
174/// ```
175#[derive(Debug, Clone, PartialEq)]
176pub struct Tenant {
177 tenant_ids: Vec<Value>,
178 column: String,
179}
180
181impl Tenant {
182 /// Scopes to `tenant_ids` on `column` (PHP's default is `tenant_id`),
183 /// which must be a plain identifier (letters, digits, `_` and `.`, not
184 /// starting with a digit).
185 pub fn new(tenant_ids: impl IntoValues, column: impl Into<String>) -> Result<Self> {
186 let column = column.into();
187 if !is_column_name(&column) {
188 return Err(Error::InvalidArgument(format!("Invalid column name: {column}")));
189 }
190 Ok(Tenant { tenant_ids: tenant_ids.into_values().values().cloned().collect(), column })
191 }
192}
193
194/// `/^[a-zA-Z_][a-zA-Z0-9_.]*$/D`.
195pub(crate) fn is_column_name(name: &str) -> bool {
196 let bytes = name.as_bytes();
197 match bytes.split_first() {
198 Some((first, rest)) => {
199 (first.is_ascii_alphabetic() || *first == b'_')
200 && rest.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'_' || *b == b'.')
201 }
202 None => false,
203 }
204}
205
206impl Filter for Tenant {
207 /// `column IN (?, ...)` with the tenant ids, or `1 = 0` for none.
208 fn filter(&self, _table: &str) -> Result<Condition> {
209 if self.tenant_ids.is_empty() {
210 return Ok(Condition::new("1 = 0", Vec::new()));
211 }
212 let placeholders = vec!["?"; self.tenant_ids.len()].join(", ");
213 Ok(Condition::new(format!("{} IN ({placeholders})", self.column), self.tenant_ids.clone()))
214 }
215}
216
217impl JoinFilter for Tenant {
218 /// The same condition: in the `ON` of left and right joins (so unmatched
219 /// rows survive), in the `WHERE` otherwise.
220 fn filter_join(&self, table: &str, join_type: JoinType) -> Result<Option<JoinCondition>> {
221 let condition = self.filter(table)?;
222 let placement = match join_type {
223 JoinType::Left | JoinType::Right => Placement::On,
224 _ => Placement::Where,
225 };
226 Ok(Some(JoinCondition::new(condition, placement)))
227 }
228}
229
230/// Maps attribute names to columns through a table; other names stay as they are.
231///
232/// PHP: `Utopia\Query\Hook\Attribute\Map`.
233///
234/// ```
235/// use utopia_query::hook::{Attribute, Map};
236///
237/// let map = Map::new([("$id", "_uid")]);
238/// assert_eq!(map.resolve("$id")?, "_uid");
239/// assert_eq!(map.resolve("name")?, "name");
240/// # Ok::<(), utopia_query::Error>(())
241/// ```
242///
243/// ```php
244/// use Utopia\Query\Hook\Attribute\Map;
245///
246/// $map = new Map(['$id' => '_uid']);
247/// echo $map->resolve('$id'), "\n"; // _uid
248/// echo $map->resolve('name'), "\n"; // name
249/// ```
250#[derive(Debug, Clone, PartialEq, Default)]
251pub struct Map {
252 map: HashMap<String, String>,
253}
254
255impl Map {
256 /// A map from attribute names to columns.
257 pub fn new<K: Into<String>, V: Into<String>>(map: impl IntoIterator<Item = (K, V)>) -> Self {
258 Map { map: map.into_iter().map(|(k, v)| (k.into(), v.into())).collect() }
259 }
260}
261
262impl Attribute for Map {
263 /// The mapped column, or the attribute itself.
264 fn resolve(&self, attribute: &str) -> Result<String> {
265 Ok(self.map.get(attribute).cloned().unwrap_or_else(|| attribute.to_owned()))
266 }
267}