oneiriq-surql 0.2.2

Code-first database toolkit for SurrealDB - schema definitions, migrations, query building, and typed CRUD (Rust port of oneiriq-surql). Published as the `oneiriq-surql` crate; imported as `use surql::...`.
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
//! Functional query-builder helpers and shared types.
//!
//! Port of `surql/query/helpers.py`. Provides standalone constructor
//! functions that each return a fresh [`Query`] pre-populated for a common
//! operation, plus the [`ReturnFormat`] and [`VectorDistanceType`] enums
//! shared with [`builder`](super::builder).

use std::collections::BTreeMap;
use std::fmt;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::error::Result;

use super::builder::Query;

/// Return format for `CREATE`, `UPDATE`, `UPSERT`, `DELETE` operations.
///
/// Controls what the server sends back after a mutation. Mirrors the
/// `RETURN ...` clause.
///
/// ## Examples
///
/// ```
/// use surql::query::helpers::ReturnFormat;
/// assert_eq!(ReturnFormat::Diff.to_surql(), "DIFF");
/// assert_eq!(ReturnFormat::None.to_surql(), "NONE");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum ReturnFormat {
    /// `RETURN NONE`
    None,
    /// `RETURN DIFF`
    Diff,
    /// `RETURN FULL`
    Full,
    /// `RETURN BEFORE`
    Before,
    /// `RETURN AFTER`
    After,
}

impl ReturnFormat {
    /// Render as SurrealQL keyword (`NONE` / `DIFF` / `FULL` / `BEFORE` / `AFTER`).
    pub fn to_surql(self) -> &'static str {
        match self {
            Self::None => "NONE",
            Self::Diff => "DIFF",
            Self::Full => "FULL",
            Self::Before => "BEFORE",
            Self::After => "AFTER",
        }
    }
}

impl fmt::Display for ReturnFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.to_surql())
    }
}

/// Distance metric used by vector similarity operators and functions.
///
/// The uppercase spelling (via [`VectorDistanceType::to_surql`]) is used
/// inside the `<|k,METRIC|>` / `<|k,METRIC,threshold|>` MTREE operator, and
/// the lowercase spelling (via [`VectorDistanceType::as_func_suffix`]) is
/// used for `vector::similarity::<metric>(...)` function calls — matching
/// the Python port's behaviour.
///
/// ## Examples
///
/// ```
/// use surql::query::helpers::VectorDistanceType;
/// assert_eq!(VectorDistanceType::Cosine.to_surql(), "COSINE");
/// assert_eq!(VectorDistanceType::Cosine.as_func_suffix(), "cosine");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum VectorDistanceType {
    /// Cosine similarity.
    Cosine,
    /// Euclidean distance.
    Euclidean,
    /// Manhattan (L1) distance.
    Manhattan,
    /// Minkowski distance.
    Minkowski,
    /// Chebyshev (L-infinity) distance.
    Chebyshev,
    /// Hamming distance.
    Hamming,
    /// Jaccard distance.
    Jaccard,
    /// Pearson correlation.
    Pearson,
    /// Mahalanobis distance.
    Mahalanobis,
}

impl VectorDistanceType {
    /// Uppercase keyword used inside the `<|k,METRIC|>` MTREE operator.
    pub fn to_surql(self) -> &'static str {
        match self {
            Self::Cosine => "COSINE",
            Self::Euclidean => "EUCLIDEAN",
            Self::Manhattan => "MANHATTAN",
            Self::Minkowski => "MINKOWSKI",
            Self::Chebyshev => "CHEBYSHEV",
            Self::Hamming => "HAMMING",
            Self::Jaccard => "JACCARD",
            Self::Pearson => "PEARSON",
            Self::Mahalanobis => "MAHALANOBIS",
        }
    }

    /// Lowercase suffix used for `vector::similarity::<suffix>(...)` calls.
    pub fn as_func_suffix(self) -> &'static str {
        match self {
            Self::Cosine => "cosine",
            Self::Euclidean => "euclidean",
            Self::Manhattan => "manhattan",
            Self::Minkowski => "minkowski",
            Self::Chebyshev => "chebyshev",
            Self::Hamming => "hamming",
            Self::Jaccard => "jaccard",
            Self::Pearson => "pearson",
            Self::Mahalanobis => "mahalanobis",
        }
    }
}

impl fmt::Display for VectorDistanceType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.to_surql())
    }
}

/// Convenience alias for the data map passed to `INSERT` / `UPDATE` /
/// `UPSERT` / `RELATE`.
///
/// Uses [`BTreeMap`] so that serialized key order is deterministic, which
/// matches the Python implementation's reliance on `dict` insertion order
/// for stable query output in tests.
pub type DataMap = BTreeMap<String, Value>;

// ---------------------------------------------------------------------------
// Standalone constructors
// ---------------------------------------------------------------------------

/// Create a `SELECT` query. Pass `None` for `SELECT *`.
///
/// ## Examples
///
/// ```
/// use surql::query::helpers::select;
///
/// let q = select(None);
/// assert_eq!(q.to_surql_or_panic_with_table("user"), "SELECT * FROM user");
/// ```
pub fn select(fields: Option<Vec<String>>) -> Query {
    Query::new().select(fields)
}

/// Add a `FROM <table>` clause to an existing query.
pub fn from_table(query: Query, table: impl Into<String>) -> Result<Query> {
    query.from_table(table)
}

/// Add a WHERE condition to an existing query. Accepts a string condition.
pub fn where_(query: Query, condition: impl Into<String>) -> Query {
    query.where_str(condition)
}

/// Add an `ORDER BY <field> <direction>` clause to an existing query.
///
/// `direction` must be `"ASC"` or `"DESC"` (case-insensitive).
pub fn order_by(
    query: Query,
    field: impl Into<String>,
    direction: impl Into<String>,
) -> Result<Query> {
    query.order_by(field, direction)
}

/// Add a `LIMIT n` clause to an existing query.
pub fn limit(query: Query, n: i64) -> Result<Query> {
    query.limit(n)
}

/// Add a `START n` (offset) clause to an existing query.
pub fn offset(query: Query, n: i64) -> Result<Query> {
    query.offset(n)
}

/// Create an `INSERT` query (renders as `CREATE <table> CONTENT {...}`).
pub fn insert(table: impl Into<String>, data: DataMap) -> Result<Query> {
    Query::new().insert(table, data)
}

/// Create an `UPDATE` query.
pub fn update(target: impl Into<String>, data: DataMap) -> Result<Query> {
    Query::new().update(target, data)
}

/// Create an `UPSERT` query.
pub fn upsert(target: impl Into<String>, data: DataMap) -> Result<Query> {
    Query::new().upsert(target, data)
}

/// Create a `DELETE` query.
pub fn delete(target: impl Into<String>) -> Result<Query> {
    Query::new().delete(target)
}

/// Create a `RELATE` query:
/// `RELATE <from>-><edge_table>-><to> [CONTENT {...}]`.
pub fn relate(
    edge_table: impl Into<String>,
    from_record: impl Into<String>,
    to_record: impl Into<String>,
    data: Option<DataMap>,
) -> Result<Query> {
    Query::new().relate(edge_table, from_record, to_record, data)
}

/// Create a vector similarity search query.
///
/// Convenience wrapper for `SELECT ... FROM <table> WHERE <field> <|k,METRIC|> [..]`.
pub fn vector_search_query(
    table: impl Into<String>,
    field: impl Into<String>,
    vector: Vec<f64>,
    k: i64,
    distance: VectorDistanceType,
    fields: Option<Vec<String>>,
    threshold: Option<f64>,
) -> Result<Query> {
    Query::new()
        .select(fields)
        .from_table(table)?
        .vector_search(field, vector, k, distance, threshold)
}

/// Create a vector similarity search query that also projects the score.
///
/// Combines [`Query::similarity_score`] with [`Query::vector_search`].
#[allow(clippy::too_many_arguments)]
pub fn similarity_search_query(
    table: impl Into<String>,
    field: impl Into<String>,
    vector: Vec<f64>,
    k: i64,
    distance: VectorDistanceType,
    threshold: Option<f64>,
    fields: Option<Vec<String>>,
    alias: impl Into<String>,
) -> Result<Query> {
    let target_field: String = field.into();
    Query::new()
        .select(fields)
        .from_table(table)?
        .similarity_score(&target_field, &vector, distance, alias)
        .vector_search(target_field, vector, k, distance, threshold)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn return_format_to_surql() {
        assert_eq!(ReturnFormat::None.to_surql(), "NONE");
        assert_eq!(ReturnFormat::Diff.to_surql(), "DIFF");
        assert_eq!(ReturnFormat::Full.to_surql(), "FULL");
        assert_eq!(ReturnFormat::Before.to_surql(), "BEFORE");
        assert_eq!(ReturnFormat::After.to_surql(), "AFTER");
    }

    #[test]
    fn return_format_display_matches_surql() {
        assert_eq!(ReturnFormat::Diff.to_string(), "DIFF");
    }

    #[test]
    fn vector_distance_uppercase() {
        assert_eq!(VectorDistanceType::Cosine.to_surql(), "COSINE");
        assert_eq!(VectorDistanceType::Euclidean.to_surql(), "EUCLIDEAN");
        assert_eq!(VectorDistanceType::Manhattan.to_surql(), "MANHATTAN");
        assert_eq!(VectorDistanceType::Minkowski.to_surql(), "MINKOWSKI");
        assert_eq!(VectorDistanceType::Chebyshev.to_surql(), "CHEBYSHEV");
        assert_eq!(VectorDistanceType::Hamming.to_surql(), "HAMMING");
        assert_eq!(VectorDistanceType::Jaccard.to_surql(), "JACCARD");
        assert_eq!(VectorDistanceType::Pearson.to_surql(), "PEARSON");
        assert_eq!(VectorDistanceType::Mahalanobis.to_surql(), "MAHALANOBIS");
    }

    #[test]
    fn vector_distance_func_suffix_is_lowercase() {
        assert_eq!(VectorDistanceType::Cosine.as_func_suffix(), "cosine");
        assert_eq!(VectorDistanceType::Euclidean.as_func_suffix(), "euclidean");
    }

    #[test]
    fn select_helper_is_star_by_default() {
        let q = select(None).from_table("user").unwrap();
        assert_eq!(q.to_surql().unwrap(), "SELECT * FROM user");
    }

    #[test]
    fn select_helper_projects_fields() {
        let q = select(Some(vec!["name".into(), "email".into()]))
            .from_table("user")
            .unwrap();
        assert_eq!(q.to_surql().unwrap(), "SELECT name, email FROM user");
    }

    #[test]
    fn from_table_helper_sets_table() {
        let q = from_table(select(None), "user").unwrap();
        assert_eq!(q.to_surql().unwrap(), "SELECT * FROM user");
    }

    #[test]
    fn where_helper_adds_condition() {
        let q = where_(select(None).from_table("user").unwrap(), "age > 18");
        assert_eq!(q.to_surql().unwrap(), "SELECT * FROM user WHERE (age > 18)");
    }

    #[test]
    fn order_by_helper() {
        let q = order_by(select(None).from_table("user").unwrap(), "name", "ASC").unwrap();
        assert_eq!(
            q.to_surql().unwrap(),
            "SELECT * FROM user ORDER BY name ASC"
        );
    }

    #[test]
    fn limit_helper() {
        let q = limit(select(None).from_table("user").unwrap(), 10).unwrap();
        assert_eq!(q.to_surql().unwrap(), "SELECT * FROM user LIMIT 10");
    }

    #[test]
    fn offset_helper_renders_start() {
        let q = offset(select(None).from_table("user").unwrap(), 20).unwrap();
        assert_eq!(q.to_surql().unwrap(), "SELECT * FROM user START 20");
    }

    #[test]
    fn insert_helper_constructs_query() {
        let mut data = DataMap::new();
        data.insert("name".into(), Value::String("Alice".into()));
        let q = insert("user", data).unwrap();
        let sql = q.to_surql().unwrap();
        assert!(sql.starts_with("CREATE user CONTENT"));
        assert!(sql.contains("name: 'Alice'"));
    }

    #[test]
    fn update_helper_constructs_query() {
        let mut data = DataMap::new();
        data.insert("status".into(), Value::String("active".into()));
        let q = update("user:alice", data).unwrap();
        assert_eq!(
            q.to_surql().unwrap(),
            "UPDATE user:alice SET status = 'active'"
        );
    }

    #[test]
    fn upsert_helper_constructs_query() {
        let mut data = DataMap::new();
        data.insert("status".into(), Value::String("active".into()));
        let q = upsert("user:alice", data).unwrap();
        assert_eq!(
            q.to_surql().unwrap(),
            "UPSERT user:alice CONTENT {status: 'active'}"
        );
    }

    #[test]
    fn delete_helper_constructs_query() {
        let q = delete("user:alice").unwrap();
        assert_eq!(q.to_surql().unwrap(), "DELETE user:alice");
    }

    #[test]
    fn relate_helper_constructs_query() {
        let q = relate("likes", "user:alice", "post:123", None).unwrap();
        assert_eq!(q.to_surql().unwrap(), "RELATE user:alice->likes->post:123");
    }

    #[test]
    fn vector_search_query_helper() {
        let q = vector_search_query(
            "documents",
            "embedding",
            vec![0.1, 0.2, 0.3],
            10,
            VectorDistanceType::Cosine,
            None,
            Some(0.7),
        )
        .unwrap();
        let sql = q.to_surql().unwrap();
        assert!(sql.starts_with("SELECT * FROM documents"));
        assert!(sql.contains("embedding <|10,COSINE,0.7|>"));
    }
}