sift-query-core 0.1.0

Backend-independent query model and strict parameter parser for SiftQuery
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use super::{ScopeLimits, validate_conditions, validate_predicates};
use crate::{
    Condition, CustomOperator, FieldId, FieldKind, FieldRef, IntoScalarValue, Operator, ParamError,
    PredicateArena, PredicatePhase, RowPhaseKind, ScalarValue, SearchEntity, ServerScope,
};
use std::marker::PhantomData;

pub struct ServerScopeBuilder<E: SearchEntity> {
    conditions: Vec<Condition>,
    limits: ScopeLimits,
    error: Option<ParamError>,
    _entity: PhantomData<fn() -> E>,
}

impl<E: SearchEntity> ServerScope<E> {
    #[must_use]
    pub fn new() -> ServerScopeBuilder<E> {
        Self::builder(ScopeLimits::default())
    }

    #[must_use]
    pub fn builder(limits: ScopeLimits) -> ServerScopeBuilder<E> {
        ServerScopeBuilder {
            conditions: Vec::new(),
            limits,
            error: None,
            _entity: PhantomData,
        }
    }

    pub fn all(scopes: impl IntoIterator<Item = Self>) -> Result<Self, ParamError> {
        Self::all_with_limits(scopes, ScopeLimits::default())
    }

    pub fn any(scopes: impl IntoIterator<Item = Self>) -> Result<Self, ParamError> {
        Self::any_with_limits(scopes, ScopeLimits::default())
    }

    pub fn all_with_limits(
        scopes: impl IntoIterator<Item = Self>,
        limits: ScopeLimits,
    ) -> Result<Self, ParamError> {
        Self::combine(scopes, true, limits)
    }

    pub fn any_with_limits(
        scopes: impl IntoIterator<Item = Self>,
        limits: ScopeLimits,
    ) -> Result<Self, ParamError> {
        Self::combine(scopes, false, limits)
    }

    fn combine(
        scopes: impl IntoIterator<Item = Self>,
        and: bool,
        limits: ScopeLimits,
    ) -> Result<Self, ParamError> {
        let scopes = scopes.into_iter().collect::<Vec<_>>();
        if scopes.is_empty() {
            return Err(ParamError::InvalidValue {
                field: "server scope".to_owned(),
                reason: "scope composition must not be empty".to_owned(),
            });
        }
        if scopes
            .iter()
            .any(|scope| scope.schema_fingerprint != E::META.schema_fingerprint)
        {
            return Err(ParamError::UnknownField(
                "entity schema mismatch".to_owned(),
            ));
        }
        validate_predicates(scopes.iter().map(|scope| &scope.predicate), limits)?;
        let field_access = scopes
            .iter()
            .skip(1)
            .fold(scopes[0].field_access.clone(), |access, scope| {
                access.intersect(&scope.field_access)
            });
        let predicates = scopes.into_iter().map(|scope| scope.predicate);
        Ok(Self {
            predicate: if and {
                PredicateArena::combine_and(predicates)
            } else {
                PredicateArena::combine_or(predicates)
            },
            schema_fingerprint: E::META.schema_fingerprint,
            field_access,
            _entity: PhantomData,
        })
    }
}

impl<E: SearchEntity> ServerScopeBuilder<E> {
    #[must_use]
    pub fn eq<T: IntoScalarValue, K: RowPhaseKind>(
        self,
        field: FieldRef<E, T, K>,
        value: T,
    ) -> Self {
        self.push_condition(
            field.id(),
            Operator::Eq,
            vec![value.into_scalar_value()],
            false,
        )
    }

    #[must_use]
    pub fn ne<T: IntoScalarValue, K: RowPhaseKind>(
        self,
        field: FieldRef<E, T, K>,
        value: T,
    ) -> Self {
        self.push_condition(
            field.id(),
            Operator::Ne,
            vec![value.into_scalar_value()],
            false,
        )
    }

    #[must_use]
    pub fn gt<T: IntoScalarValue, K: RowPhaseKind>(
        self,
        field: FieldRef<E, T, K>,
        value: T,
    ) -> Self {
        self.push_condition(
            field.id(),
            Operator::Gt,
            vec![value.into_scalar_value()],
            false,
        )
    }

    #[must_use]
    pub fn ge<T: IntoScalarValue, K: RowPhaseKind>(
        self,
        field: FieldRef<E, T, K>,
        value: T,
    ) -> Self {
        self.push_condition(
            field.id(),
            Operator::Ge,
            vec![value.into_scalar_value()],
            false,
        )
    }

    #[must_use]
    pub fn lt<T: IntoScalarValue, K: RowPhaseKind>(
        self,
        field: FieldRef<E, T, K>,
        value: T,
    ) -> Self {
        self.push_condition(
            field.id(),
            Operator::Lt,
            vec![value.into_scalar_value()],
            false,
        )
    }

    #[must_use]
    pub fn le<T: IntoScalarValue, K: RowPhaseKind>(
        self,
        field: FieldRef<E, T, K>,
        value: T,
    ) -> Self {
        self.push_condition(
            field.id(),
            Operator::Le,
            vec![value.into_scalar_value()],
            false,
        )
    }

    #[must_use]
    pub fn between<T: IntoScalarValue, K: RowPhaseKind>(
        self,
        field: FieldRef<E, T, K>,
        lower: T,
        upper: T,
    ) -> Self {
        self.push_condition(
            field.id(),
            Operator::Between,
            vec![lower.into_scalar_value(), upper.into_scalar_value()],
            false,
        )
    }

    #[must_use]
    pub fn in_list<T, K, I>(self, field: FieldRef<E, T, K>, values: I) -> Self
    where
        T: IntoScalarValue,
        K: RowPhaseKind,
        I: IntoIterator<Item = T>,
    {
        self.push_condition(
            field.id(),
            Operator::InList,
            values
                .into_iter()
                .map(IntoScalarValue::into_scalar_value)
                .collect(),
            false,
        )
    }

    #[must_use]
    pub fn is_null<T, K: RowPhaseKind>(self, field: FieldRef<E, T, K>) -> Self {
        self.push_condition(field.id(), Operator::IsNull, Vec::new(), false)
    }

    #[must_use]
    pub fn is_not_null<T, K: RowPhaseKind>(self, field: FieldRef<E, T, K>) -> Self {
        self.push_condition(field.id(), Operator::NotNull, Vec::new(), false)
    }

    #[must_use]
    pub fn starts_with<K: RowPhaseKind>(
        self,
        field: FieldRef<E, String, K>,
        value: impl Into<String>,
    ) -> Self {
        self.push_condition(
            field.id(),
            Operator::StartWith,
            vec![ScalarValue::Text(value.into())],
            false,
        )
    }

    #[must_use]
    pub fn contains<K: RowPhaseKind>(
        self,
        field: FieldRef<E, String, K>,
        value: impl Into<String>,
    ) -> Self {
        self.push_condition(
            field.id(),
            Operator::Contain,
            vec![ScalarValue::Text(value.into())],
            false,
        )
    }

    #[must_use]
    pub fn contains_ignore_case<K: RowPhaseKind>(
        self,
        field: FieldRef<E, String, K>,
        value: impl Into<String>,
    ) -> Self {
        self.push_condition(
            field.id(),
            Operator::Contain,
            vec![ScalarValue::Text(value.into())],
            true,
        )
    }

    #[must_use]
    pub fn custom<T, K, I>(
        self,
        field: FieldRef<E, T, K>,
        operator: CustomOperator,
        values: I,
    ) -> Self
    where
        T: IntoScalarValue,
        K: RowPhaseKind,
        I: IntoIterator<Item = T>,
    {
        self.custom_values(field, operator, values)
    }

    /// Applies a server-owned operator whose input type may differ from the field.
    #[must_use]
    pub fn custom_values<T, K: RowPhaseKind, V: IntoScalarValue>(
        self,
        field: FieldRef<E, T, K>,
        operator: CustomOperator,
        values: impl IntoIterator<Item = V>,
    ) -> Self {
        self.push_condition(
            field.id(),
            Operator::Custom(operator),
            values
                .into_iter()
                .map(IntoScalarValue::into_scalar_value)
                .collect(),
            false,
        )
    }

    /// Adds a trusted correlated `EXISTS` relation filter. The operator must
    /// have been created with [`CustomOperator::exists`].
    #[must_use]
    pub fn exists<T, K: RowPhaseKind, V: IntoScalarValue>(
        self,
        field: FieldRef<E, T, K>,
        operator: CustomOperator,
        values: impl IntoIterator<Item = V>,
    ) -> Self {
        if !operator.is_exists() {
            return self.push_error(ParamError::InvalidValue {
                field: "exists".to_owned(),
                reason: "operator must be declared with CustomOperator::exists".to_owned(),
            });
        }
        self.custom_values(field, operator, values)
    }

    /// Adds a trusted correlated `NOT EXISTS` relation filter. The operator
    /// must have been created with [`CustomOperator::not_exists`].
    #[must_use]
    pub fn not_exists<T, K: RowPhaseKind, V: IntoScalarValue>(
        self,
        field: FieldRef<E, T, K>,
        operator: CustomOperator,
        values: impl IntoIterator<Item = V>,
    ) -> Self {
        if !operator.is_not_exists() {
            return self.push_error(ParamError::InvalidValue {
                field: "not_exists".to_owned(),
                reason: "operator must be declared with CustomOperator::not_exists".to_owned(),
            });
        }
        self.custom_values(field, operator, values)
    }

    fn push_error(mut self, error: ParamError) -> Self {
        if self.error.is_none() {
            self.error = Some(error);
        }
        self
    }

    fn push_condition(
        mut self,
        field: FieldId,
        operator: Operator,
        values: Vec<ScalarValue>,
        ignore_case: bool,
    ) -> Self {
        if self.error.is_some() {
            return self;
        }
        let Some(meta) = E::META.field(field) else {
            self.error = Some(ParamError::UnknownField(format!("#{}", field.0)));
            return self;
        };
        if meta.kind == FieldKind::Aggregate
            || !operator.accepts_field_type(meta.value_type)
            || values
                .iter()
                .any(|value| value.value_type() != operator.input_type(meta.value_type))
        {
            self.error = Some(ParamError::InvalidValue {
                field: meta.public_name.to_owned(),
                reason: "scope field type or phase mismatch".to_owned(),
            });
        } else if !operator.accepts_arity(values.len()) {
            self.error = Some(ParamError::WrongArity {
                field: meta.public_name.to_owned(),
                operator: operator.short_name(),
                expected: operator.expected_arity(),
                actual: values.len(),
            });
        } else if ignore_case
            && (meta.value_type != crate::ValueType::Text || !operator.supports_ignore_case())
        {
            self.error = Some(ParamError::IgnoreCaseNotAllowed(
                meta.public_name.to_owned(),
            ));
        } else {
            if let Some(error) = values.iter().find_map(|value| value.validate().err()) {
                self.error = Some(error);
                return self;
            }
            self.conditions.push(Condition {
                field,
                operator,
                values,
                ignore_case,
                phase: PredicatePhase::Row,
            });
        }
        self
    }

    pub fn build(self) -> Result<ServerScope<E>, ParamError> {
        if let Some(error) = self.error {
            return Err(error);
        }
        if self.conditions.is_empty() {
            return Err(ParamError::InvalidValue {
                field: "server scope".to_owned(),
                reason: "empty scope must use ServerScope::unrestricted() explicitly".to_owned(),
            });
        }
        validate_conditions(self.conditions.iter(), self.limits)?;
        Ok(ServerScope {
            predicate: PredicateArena::combine_and(
                self.conditions
                    .into_iter()
                    .map(PredicateArena::from_condition),
            ),
            schema_fingerprint: E::META.schema_fingerprint,
            field_access: crate::FieldAccessPolicy::unrestricted(),
            _entity: PhantomData,
        })
    }
}