Skip to main content

utopia_query/
value.rs

1//! [`Value`]: the PHP values queries carry, and the objects among them.
2
3use php_std::json::{self, Flags};
4use php_std::{ArrayKey, Extension, Str};
5
6use crate::enums::NullsPosition;
7use crate::query::Query;
8
9/// A value a query or a statement carries: a PHP value (bytes, integers
10/// distinct from floats, ordered arrays with integer and string keys,
11/// `stdClass`), where objects are [`Object`]s.
12pub type Value = php_std::Value<Object>;
13
14/// A PHP array of [`Value`]s.
15pub type Array = php_std::Array<Object>;
16
17/// An object among a query's values.
18#[derive(Debug, Clone, PartialEq)]
19pub enum Object {
20    /// A nested query (the children of `and`, `or`, `having`, joins).
21    ///
22    /// PHP: `Utopia\Query\Query`.
23    Query(Box<Query>),
24    /// The `NULLS FIRST` / `NULLS LAST` of an order query.
25    ///
26    /// PHP: `Utopia\Query\NullsPosition`.
27    Nulls(NullsPosition),
28    /// A row read through array access, such as a document used as a cursor:
29    /// its class and its fields.
30    ///
31    /// PHP: an object implementing `ArrayAccess` (`ArrayObject`, `Utopia\Database\Document`).
32    Row {
33        /// The PHP class.
34        class: String,
35        /// The fields.
36        fields: Array,
37    },
38}
39
40impl Extension for Object {
41    /// The PHP class.
42    fn class(&self) -> &str {
43        match self {
44            Object::Query(_) => "Utopia\\Query\\Query",
45            Object::Nulls(_) => NullsPosition::PHP_CLASS,
46            Object::Row { class, .. } => class,
47        }
48    }
49
50    /// What `json_encode` writes for the object: a query has no public
51    /// properties, a row its fields.
52    fn to_array(&self) -> Array {
53        match self {
54            Object::Row { fields, .. } => fields.clone(),
55            _ => Array::default(),
56        }
57    }
58}
59
60impl From<Query> for Value {
61    /// A nested query.
62    fn from(query: Query) -> Self {
63        Value::Ext(Object::Query(Box::new(query)))
64    }
65}
66
67impl From<NullsPosition> for Value {
68    /// The enum case.
69    fn from(nulls: NullsPosition) -> Self {
70        Value::Ext(Object::Nulls(nulls))
71    }
72}
73
74/// A string value.
75pub fn string(s: impl AsRef<[u8]>) -> Value {
76    Value::Str(Str::copy_from(s.as_ref()))
77}
78
79/// A list of values.
80pub fn list<V: Into<Value>>(items: impl IntoIterator<Item = V>) -> Array {
81    Array::from_list(items.into_iter().map(Into::into).collect())
82}
83
84/// The value as PHP's `(string)` cast prints it (lossy for bytes that are not
85/// UTF-8, which PHP would keep).
86pub(crate) fn to_php_string(value: &Value) -> String {
87    match value.to_php_string() {
88        Ok(s) => String::from_utf8_lossy(s.as_bytes()).into_owned(),
89        Err(_) => String::new(),
90    }
91}
92
93/// `json_encode($value)` with `$flags`: enums encode as their value, as PHP's
94/// backed enums do.
95pub(crate) fn json_encode(value: &Value, flags: Flags) -> Result<String, json::Error> {
96    json::encode(&enums_as_values(value), flags, json::DEFAULT_DEPTH)
97}
98
99/// Backed enum cases replaced by their values (what `json_encode` writes for them).
100fn enums_as_values(value: &Value) -> Value {
101    match value {
102        Value::Ext(Object::Nulls(n)) => Value::from(n.as_str()),
103        Value::Array(a) => Value::Array(map_array(a)),
104        Value::Object(a) => Value::Object(map_array(a)),
105        other => other.clone(),
106    }
107}
108
109fn map_array(a: &Array) -> Array {
110    let mut out = Array::with_capacity(a.len());
111    for (k, v) in a.iter() {
112        out.set(k.to_owned(), enums_as_values(v));
113    }
114    out
115}
116
117/// `$a === $b` where enum cases are identical to themselves (PHP's enum
118/// cases are singletons) and other objects to nothing.
119pub(crate) fn identical(a: &Value, b: &Value) -> bool {
120    match (a, b) {
121        (Value::Ext(Object::Nulls(x)), Value::Ext(Object::Nulls(y))) => x == y,
122        (Value::Array(x), Value::Array(y)) => {
123            x.len() == y.len() && x.iter().zip(y.iter()).all(|((ka, va), (kb, vb))| ka == kb && identical(va, vb))
124        }
125        _ => a.strict_eq(b),
126    }
127}
128
129/// Something usable as one PHP value: integers, floats, booleans, strings,
130/// arrays, queries, `None` for `null`.
131pub trait IntoValue {
132    /// The value.
133    fn into_value(self) -> Value;
134}
135
136impl IntoValue for Value {
137    fn into_value(self) -> Value {
138        self
139    }
140}
141
142impl IntoValue for &Value {
143    fn into_value(self) -> Value {
144        self.clone()
145    }
146}
147
148macro_rules! into_value_int {
149    ($($t:ty),*) => {$(
150        impl IntoValue for $t {
151            fn into_value(self) -> Value {
152                Value::Int(self as i64)
153            }
154        }
155    )*};
156}
157
158into_value_int!(i8, i16, i32, i64, u8, u16, u32, isize);
159
160impl IntoValue for f64 {
161    fn into_value(self) -> Value {
162        Value::Float(self)
163    }
164}
165
166impl IntoValue for f32 {
167    fn into_value(self) -> Value {
168        Value::Float(self as f64)
169    }
170}
171
172impl IntoValue for bool {
173    fn into_value(self) -> Value {
174        Value::Bool(self)
175    }
176}
177
178impl IntoValue for &str {
179    fn into_value(self) -> Value {
180        string(self)
181    }
182}
183
184impl IntoValue for String {
185    fn into_value(self) -> Value {
186        Value::Str(Str::from(self))
187    }
188}
189
190impl IntoValue for &String {
191    fn into_value(self) -> Value {
192        string(self)
193    }
194}
195
196impl IntoValue for Str {
197    fn into_value(self) -> Value {
198        Value::Str(self)
199    }
200}
201
202impl IntoValue for Array {
203    fn into_value(self) -> Value {
204        Value::Array(self)
205    }
206}
207
208impl IntoValue for Query {
209    fn into_value(self) -> Value {
210        Value::from(self)
211    }
212}
213
214impl IntoValue for NullsPosition {
215    fn into_value(self) -> Value {
216        Value::from(self)
217    }
218}
219
220impl<T: IntoValue> IntoValue for Option<T> {
221    fn into_value(self) -> Value {
222        self.map(IntoValue::into_value).unwrap_or(Value::Null)
223    }
224}
225
226/// Something usable as a PHP array of values: a Rust array, a `Vec` or a
227/// slice of [`IntoValue`]s (a list), or an [`Array`] (keys kept).
228pub trait IntoValues {
229    /// The array.
230    fn into_values(self) -> Array;
231}
232
233impl IntoValues for Array {
234    fn into_values(self) -> Array {
235        self
236    }
237}
238
239impl<T: IntoValue, const N: usize> IntoValues for [T; N] {
240    fn into_values(self) -> Array {
241        Array::from_list(self.into_iter().map(IntoValue::into_value).collect())
242    }
243}
244
245impl<T: IntoValue> IntoValues for Vec<T> {
246    fn into_values(self) -> Array {
247        Array::from_list(self.into_iter().map(IntoValue::into_value).collect())
248    }
249}
250
251impl<T: IntoValue + Clone> IntoValues for &[T] {
252    fn into_values(self) -> Array {
253        Array::from_list(self.iter().cloned().map(IntoValue::into_value).collect())
254    }
255}
256
257/// The value as PHP's string concatenation (`'x' . $value`) writes it: arrays
258/// as `"Array"` (PHP warns), objects fail as PHP's `Error` does.
259pub(crate) fn concat(value: &Value) -> Result<std::borrow::Cow<'_, str>, crate::Error> {
260    use std::borrow::Cow;
261    match value {
262        Value::Str(s) => Ok(String::from_utf8_lossy(s.as_bytes())),
263        Value::Object(_) | Value::Ext(_) => Err(crate::Error::Engine(format!(
264            "Object of class {} could not be converted to string",
265            value.debug_type()
266        ))),
267        other => Ok(Cow::Owned(to_php_string(other))),
268    }
269}
270
271/// The key `$array[$value] = ...` writes: numeric strings as integers,
272/// `null` as `""`, booleans as `0` / `1`, floats truncated (PHP deprecates
273/// it); arrays and objects fail with PHP's `TypeError`.
274pub(crate) fn array_key(value: &Value) -> Result<ArrayKey, crate::Error> {
275    Ok(match value {
276        Value::Str(s) => ArrayKey::normalize(s.clone()),
277        Value::Int(i) => ArrayKey::Int(*i),
278        Value::Float(f) => ArrayKey::Int(php_std::format::dval_to_lval(*f)),
279        Value::Bool(b) => ArrayKey::Int(i64::from(*b)),
280        Value::Null => ArrayKey::Str(Str::EMPTY),
281        other => {
282            return Err(crate::Error::Type(format!("Cannot access offset of type {} on array", value_name(other))));
283        }
284    })
285}
286
287/// How PHP names a value's type in a `TypeError`: `true` / `false` for
288/// booleans, the class for objects, else the type (`null`, `int`, `array`).
289///
290/// PHP: `zend_zval_value_name()`.
291pub(crate) fn value_name(value: &Value) -> &str {
292    match value {
293        Value::Bool(true) => "true",
294        Value::Bool(false) => "false",
295        other => other.debug_type(),
296    }
297}
298
299/// [`concat`] as bytes (PHP strings are bytes).
300pub(crate) fn concat_bytes(value: &Value) -> Result<std::borrow::Cow<'_, [u8]>, crate::Error> {
301    use std::borrow::Cow;
302    match value {
303        Value::Str(s) => Ok(Cow::Borrowed(s.as_bytes())),
304        other => Ok(Cow::Owned(concat(other)?.into_owned().into_bytes())),
305    }
306}
307
308/// Where the library's PHP sources live in the image Appwrite runs: PHP's
309/// type errors name the file and line of the call.
310const PHP_SOURCES: &str = "/usr/src/code/packages/query/src/";
311
312/// A typed PHP parameter that a query value, of whatever type the client
313/// sent, is passed to: converts the value as PHP's coercive typing mode does
314/// ([`Param::string`]) or checks
315/// it ([`Param::array`]), failing with PHP's `TypeError`.
316///
317/// A library function's `string` parameter rejects `null`, arrays and
318/// objects; an internal function's (`str_ends_with()`) takes `null` as `""`
319/// (PHP deprecates it). Integers, floats and booleans become their
320/// `(string)` form for both.
321///
322/// PHP: the engine's parameter type check (`zend_verify_arg_type`).
323#[derive(Debug, Clone, Copy)]
324pub(crate) struct Param<'f> {
325    function: &'f str,
326    position: u8,
327    name: &'static str,
328    callee: Callee,
329}
330
331#[derive(Debug, Clone, Copy)]
332enum Callee {
333    /// A library method, called from `file` (relative to the sources) at `line`.
334    Method { file: &'static str, line: u32 },
335    /// A library closure, called by an internal function (`array_map`): PHP
336    /// names no call site.
337    Closure,
338    /// An internal PHP function.
339    Internal,
340}
341
342impl<'f> Param<'f> {
343    /// Parameter `position` (`$name`) of the library method `function`
344    /// (`Utopia\Query\Builder::resolveAndWrap`), called from `file` at `line`.
345    pub(crate) const fn method(
346        function: &'f str,
347        position: u8,
348        name: &'static str,
349        file: &'static str,
350        line: u32,
351    ) -> Self {
352        Param { function, position, name, callee: Callee::Method { file, line } }
353    }
354
355    /// Parameter `position` (`$name`) of a library closure, named as PHP names
356    /// it (`Utopia\Query\Builder::{closure:Utopia\Query\Builder::compileSelect():1362}`).
357    pub(crate) const fn closure(function: &'f str, position: u8, name: &'static str) -> Self {
358        Param { function, position, name, callee: Callee::Closure }
359    }
360
361    /// Parameter `position` (`$name`) of the internal PHP function `function`.
362    pub(crate) const fn internal(function: &'f str, position: u8, name: &'static str) -> Self {
363        Param { function, position, name, callee: Callee::Internal }
364    }
365
366    /// The string PHP passes for `value` to a `string` parameter, or its `TypeError`.
367    pub(crate) fn string<'a>(&self, value: &'a Value) -> Result<std::borrow::Cow<'a, str>, crate::Error> {
368        use std::borrow::Cow;
369        Ok(match value {
370            Value::Str(s) => String::from_utf8_lossy(s.as_bytes()),
371            Value::Null if matches!(self.callee, Callee::Internal) => Cow::Borrowed(""),
372            Value::Int(_) | Value::Float(_) | Value::Bool(_) => Cow::Owned(to_php_string(value)),
373            other => return Err(self.type_error("string", other)),
374        })
375    }
376
377    /// [`Param::string`] as bytes (PHP strings are bytes).
378    pub(crate) fn bytes<'a>(&self, value: &'a Value) -> Result<std::borrow::Cow<'a, [u8]>, crate::Error> {
379        use std::borrow::Cow;
380        match value {
381            Value::Str(s) => Ok(Cow::Borrowed(s.as_bytes())),
382            other => Ok(Cow::Owned(self.string(other)?.into_owned().into_bytes())),
383        }
384    }
385
386    /// The array `value` is, for an `array` parameter, or PHP's `TypeError`.
387    pub(crate) fn array<'a>(&self, value: &'a Value) -> Result<&'a Array, crate::Error> {
388        match value {
389            Value::Array(a) => Ok(a),
390            other => Err(self.type_error("array", other)),
391        }
392    }
393
394    /// PHP's `TypeError` for passing `value` to a parameter of type `expected`.
395    pub(crate) fn type_error(&self, expected: &str, value: &Value) -> crate::Error {
396        let mut message = format!(
397            "{}(): Argument #{} (${}) must be of type {expected}, {} given",
398            self.function,
399            self.position,
400            self.name,
401            value_name(value)
402        );
403        if let Callee::Method { file, line } = self.callee {
404            message.push_str(&format!(", called in {PHP_SOURCES}{file} on line {line}"));
405        }
406        crate::Error::Type(message)
407    }
408}