skybase 0.1.11

The Open-Source Backend & Developer Platform for the AT Protocol (Firebase for ATProto, powered by skyauth)
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
//! Type-safe SQLite JSON1 query builder for AT Protocol records.
//!
//! Provides fluent construction of queries filtering by collection NSID, author DID,
//! JSON1 field expressions (`where_json`), custom ordering, and pagination.

use serde::{Deserialize, Serialize};

use crate::error::{Result, SkybaseError};
use crate::index::store::{RecordRow, RecordStore};

/// Comparison operators for JSON field queries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum QueryOp {
    /// Equality (`=`). Checks equality with the extracted JSON value.
    Eq,
    /// Inequality (`!=`). Checks inequality with the extracted JSON value.
    Ne,
    /// Greater than (`>`). Lexicographical for strings, numerical for numbers.
    Gt,
    /// Greater than or equal to (`>=`).
    Gte,
    /// Less than (`<`).
    Lt,
    /// Less than or equal to (`<=`).
    Lte,
    /// Substring search within a string field (`LIKE %value%`).
    ///
    /// Wildcard characters (`%`, `_`, `\`) in the value are automatically escaped
    /// using `\` as the escape character for literal substring matching.
    Contains,
    /// Pattern matching using SQL `LIKE` syntax.
    ///
    /// Unlike [`Contains`](Self::Contains), wildcard characters (`%`, `_`) in the value
    /// are NOT escaped and are evaluated directly by SQLite.
    Like,
}

/// Sort direction for query result ordering.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SortDirection {
    /// Ascending order (lowest to highest, A-Z, 0-9).
    Asc,
    /// Descending order (highest to lowest, Z-A, 9-0).
    Desc,
}

impl SortDirection {
    /// Returns the SQL keyword for this direction.
    #[must_use]
    pub fn as_sql(&self) -> &'static str {
        match self {
            Self::Asc => "ASC",
            Self::Desc => "DESC",
        }
    }
}

#[derive(Debug, Clone)]
enum OrderClause {
    Column(&'static str, SortDirection),
    JsonPath(String, SortDirection),
}

#[derive(Debug, Clone)]
struct WhereJsonClause {
    field_path: String,
    op: QueryOp,
    value: serde_json::Value,
}

/// Fluent query builder for searching records stored in SQLite.
pub struct QueryBuilder<'a> {
    store: &'a RecordStore,
    collection: String,
    did: Option<String>,
    where_json_clauses: Vec<WhereJsonClause>,
    order_by_clauses: Vec<OrderClause>,
    limit: Option<u32>,
    offset: Option<u32>,
    include_deleted: bool,
}

impl<'a> QueryBuilder<'a> {
    /// Creates a new query builder scoped to a target ATProto collection NSID.
    pub fn new(store: &'a RecordStore, collection: impl Into<String>) -> Self {
        Self {
            store,
            collection: collection.into(),
            did: None,
            where_json_clauses: Vec::new(),
            order_by_clauses: Vec::new(),
            limit: None,
            offset: None,
            include_deleted: false,
        }
    }

    /// Filters records by author DID (`did:plc:...` or `did:web:...`).
    #[must_use]
    pub fn did(mut self, did: impl Into<String>) -> Self {
        self.did = Some(did.into());
        self
    }

    /// Adds a filter condition on a JSON field within `record_json`.
    ///
    /// Paths can be supplied as `text`, `subject.author`, or `$.rating`.
    /// They will be normalized to SQLite JSONPath format (`$.<path>`).
    #[must_use]
    pub fn where_json(
        mut self,
        field_path: &str,
        op: QueryOp,
        value: impl Into<serde_json::Value>,
    ) -> Self {
        self.where_json_clauses.push(WhereJsonClause {
            field_path: field_path.to_string(),
            op,
            value: value.into(),
        });
        self
    }

    /// Specifies sort order by column name or JSON field path.
    ///
    /// Known canonical columns: `indexed_at`, `uri`, `did`, `collection`, `rkey`, `cid`.
    /// Any other field name is treated as a JSON path within `record_json`.
    #[must_use]
    pub fn order_by(mut self, field: &str, direction: SortDirection) -> Self {
        let clause = match field {
            "indexed_at" => OrderClause::Column("indexed_at", direction),
            "uri" => OrderClause::Column("uri", direction),
            "did" => OrderClause::Column("did", direction),
            "collection" => OrderClause::Column("collection", direction),
            "rkey" => OrderClause::Column("rkey", direction),
            "cid" => OrderClause::Column("cid", direction),
            other => OrderClause::JsonPath(other.to_string(), direction),
        };
        self.order_by_clauses.push(clause);
        self
    }

    /// Limits the maximum number of records returned.
    #[must_use]
    pub fn limit(mut self, limit: u32) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Skips the first `offset` matching records.
    #[must_use]
    pub fn offset(mut self, offset: u32) -> Self {
        self.offset = Some(offset);
        self
    }

    /// Controls whether soft-deleted records (`is_deleted = 1`) are included in results.
    /// Defaults to `false` (only active records returned).
    #[must_use]
    pub fn include_deleted(mut self, include: bool) -> Self {
        self.include_deleted = include;
        self
    }

    /// Compiles the query into parameterized SQL and parameter values.
    ///
    /// # Errors
    /// Returns [`SkybaseError::Index`] if collection is empty or if any JSON path is malformed.
    pub fn build_sql(&self) -> Result<(String, Vec<rusqlite::types::Value>)> {
        let coll = self.collection.trim();
        if coll.is_empty() {
            return Err(SkybaseError::Index("Collection cannot be empty".into()));
        }

        let mut sql = String::with_capacity(256);
        sql.push_str("SELECT uri, cid, did, collection, rkey, record_json, indexed_at, is_deleted FROM records WHERE collection = ?");

        let mut params = Vec::new();
        params.push(rusqlite::types::Value::Text(coll.to_string()));

        if !self.include_deleted {
            sql.push_str(" AND is_deleted = 0");
        }

        if let Some(ref did) = self.did {
            let trimmed_did = did.trim();
            sql.push_str(" AND did = ?");
            params.push(rusqlite::types::Value::Text(trimmed_did.to_string()));
        }

        for clause in &self.where_json_clauses {
            let path = normalize_json_path(&clause.field_path)?;
            params.push(rusqlite::types::Value::Text(path));

            match clause.op {
                QueryOp::Eq if clause.value.is_null() => {
                    sql.push_str(" AND json_extract(record_json, ?) IS NULL");
                }
                QueryOp::Ne if clause.value.is_null() => {
                    sql.push_str(" AND json_extract(record_json, ?) IS NOT NULL");
                }
                QueryOp::Eq => {
                    sql.push_str(" AND json_extract(record_json, ?) = ?");
                    params.push(json_to_sqlite_value(&clause.value));
                }
                QueryOp::Ne => {
                    sql.push_str(" AND json_extract(record_json, ?) IS NOT ?");
                    params.push(json_to_sqlite_value(&clause.value));
                }
                QueryOp::Gt => {
                    sql.push_str(" AND json_extract(record_json, ?) > ?");
                    params.push(json_to_sqlite_value(&clause.value));
                }
                QueryOp::Gte => {
                    sql.push_str(" AND json_extract(record_json, ?) >= ?");
                    params.push(json_to_sqlite_value(&clause.value));
                }
                QueryOp::Lt => {
                    sql.push_str(" AND json_extract(record_json, ?) < ?");
                    params.push(json_to_sqlite_value(&clause.value));
                }
                QueryOp::Lte => {
                    sql.push_str(" AND json_extract(record_json, ?) <= ?");
                    params.push(json_to_sqlite_value(&clause.value));
                }
                QueryOp::Contains => {
                    sql.push_str(
                        " AND json_extract(record_json, ?) LIKE ('%' || ? || '%') ESCAPE '\\'",
                    );
                    let val = match &clause.value {
                        serde_json::Value::String(s) => {
                            rusqlite::types::Value::Text(escape_like_literal(s))
                        }
                        other => json_to_sqlite_value(other),
                    };
                    params.push(val);
                }
                QueryOp::Like => {
                    sql.push_str(" AND json_extract(record_json, ?) LIKE ?");
                    params.push(json_to_sqlite_value(&clause.value));
                }
            }
        }

        if !self.order_by_clauses.is_empty() {
            sql.push_str(" ORDER BY ");
            for (idx, order) in self.order_by_clauses.iter().enumerate() {
                if idx > 0 {
                    sql.push_str(", ");
                }
                match order {
                    OrderClause::Column(col_name, direction) => {
                        sql.push_str(col_name);
                        sql.push(' ');
                        sql.push_str(direction.as_sql());
                    }
                    OrderClause::JsonPath(raw_path, direction) => {
                        let path = normalize_json_path(raw_path)?;
                        sql.push_str("json_extract(record_json, ?) ");
                        sql.push_str(direction.as_sql());
                        params.push(rusqlite::types::Value::Text(path));
                    }
                }
            }
        }

        match (self.limit, self.offset) {
            (Some(limit), Some(offset)) => {
                sql.push_str(" LIMIT ? OFFSET ?");
                params.push(rusqlite::types::Value::Integer(i64::from(limit)));
                params.push(rusqlite::types::Value::Integer(i64::from(offset)));
            }
            (Some(limit), None) => {
                sql.push_str(" LIMIT ?");
                params.push(rusqlite::types::Value::Integer(i64::from(limit)));
            }
            (None, Some(offset)) => {
                sql.push_str(" LIMIT -1 OFFSET ?");
                params.push(rusqlite::types::Value::Integer(i64::from(offset)));
            }
            (None, None) => {}
        }

        Ok((sql, params))
    }

    /// Executes the query and returns matching [`RecordRow`] records.
    ///
    /// # Errors
    /// Returns [`SkybaseError::Index`], [`SkybaseError::Storage`], or [`SkybaseError::Serialization`]
    /// on query or parsing failure.
    pub fn execute(self) -> Result<Vec<RecordRow>> {
        let (sql, params) = self.build_sql()?;
        self.store.query_raw(&sql, &params)
    }
}

/// Converts a [`serde_json::Value`] into a [`rusqlite::types::Value`] tailored for SQLite JSON1 comparisons.
#[must_use]
pub fn json_to_sqlite_value(val: &serde_json::Value) -> rusqlite::types::Value {
    match val {
        serde_json::Value::Null => rusqlite::types::Value::Null,
        serde_json::Value::Bool(b) => rusqlite::types::Value::Integer(if *b { 1 } else { 0 }),
        serde_json::Value::Number(num) => {
            if let Some(i) = num.as_i64() {
                rusqlite::types::Value::Integer(i)
            } else if let Some(u) = num.as_u64() {
                if let Ok(i) = i64::try_from(u) {
                    rusqlite::types::Value::Integer(i)
                } else {
                    rusqlite::types::Value::Text(num.to_string())
                }
            } else if let Some(f) = num.as_f64() {
                rusqlite::types::Value::Real(f)
            } else {
                rusqlite::types::Value::Text(num.to_string())
            }
        }
        serde_json::Value::String(s) => rusqlite::types::Value::Text(s.clone()),
        serde_json::Value::Array(_) | serde_json::Value::Object(_) => {
            rusqlite::types::Value::Text(val.to_string())
        }
    }
}

/// Normalizes a user-provided field path into canonical SQLite JSONPath syntax `$.<path>`.
///
/// # Errors
/// Returns [`SkybaseError::Index`] if `path` is empty or contains disallowed characters.
pub fn normalize_json_path(path: &str) -> Result<String> {
    let trimmed = path.trim();
    if trimmed.is_empty() {
        return Err(SkybaseError::Index(
            "JSON field path cannot be empty".into(),
        ));
    }

    let normalized = if trimmed.starts_with('$') {
        trimmed.to_string()
    } else if trimmed.starts_with('[') {
        format!("${trimmed}")
    } else {
        format!("$.{trimmed}")
    };

    validate_json_path(&normalized)?;
    Ok(normalized)
}

/// Escapes SQL `LIKE` wildcard characters (`%`, `_`, and `\`) using `\` as the escape character.
#[must_use]
pub fn escape_like_literal(s: &str) -> String {
    let mut escaped = String::with_capacity(s.len());
    for ch in s.chars() {
        if ch == '%' || ch == '_' || ch == '\\' {
            escaped.push('\\');
        }
        escaped.push(ch);
    }
    escaped
}

fn validate_json_path(path: &str) -> Result<()> {
    if path.starts_with('$') && path.len() > 1 && !path.starts_with("$.") && !path.starts_with("$[")
    {
        return Err(SkybaseError::Index(format!(
            "JSON path starting with '$' must be followed by '.' or '[', got: '{path}'"
        )));
    }
    for (idx, ch) in path.chars().enumerate() {
        if idx == 0 && ch == '$' {
            continue;
        }
        if !ch.is_ascii_alphanumeric()
            && ch != '_'
            && ch != '-'
            && ch != '.'
            && ch != '['
            && ch != ']'
        {
            return Err(SkybaseError::Index(format!(
                "Invalid character '{ch}' in JSON path '{path}'"
            )));
        }
    }
    Ok(())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, missing_docs)]
mod tests {
    use super::*;
    use crate::index::store::RecordInput;
    use serde_json::json;

    fn setup_test_store() -> RecordStore {
        let store = RecordStore::open_in_memory().unwrap();

        let r1 = RecordInput::new(
            "did:plc:alice",
            "app.bsky.feed.post",
            "post1",
            "bafyreia1",
            json!({
                "text": "Hello world from Alice!",
                "rating": 5,
                "is_published": true,
                "metadata": { "views": 100 },
                "tags": ["bluesky", "atproto"],
                "note": null
            }),
            1000,
        );

        let r2 = RecordInput::new(
            "did:plc:bob",
            "app.bsky.feed.post",
            "post2",
            "bafyreia2",
            json!({
                "text": "ATProto is the future",
                "rating": 3,
                "is_published": false,
                "metadata": { "views": 25 },
                "tags": ["atproto"],
                "note": "important"
            }),
            2000,
        );

        let r3 = RecordInput::new(
            "did:plc:alice",
            "app.bsky.feed.post",
            "post3",
            "bafyreia3",
            json!({
                "text": "Deleted post",
                "rating": 1
            }),
            3000,
        );

        store.upsert_record(&r1).unwrap();
        store.upsert_record(&r2).unwrap();
        store.upsert_record(&r3).unwrap();
        store.soft_delete_record(&r3.uri, 3000).unwrap();

        store
    }

    #[test]
    fn test_path_normalization() {
        assert_eq!(normalize_json_path("text").unwrap(), "$.text");
        assert_eq!(normalize_json_path("$.text").unwrap(), "$.text");
        assert_eq!(
            normalize_json_path("subject.author.did").unwrap(),
            "$.subject.author.did"
        );
        assert_eq!(normalize_json_path("tags[0]").unwrap(), "$.tags[0]");
        assert_eq!(normalize_json_path("$[0]").unwrap(), "$[0]");
        assert!(normalize_json_path("").is_err());
        assert!(normalize_json_path("   ").is_err());
        assert!(normalize_json_path("text; DROP TABLE records; --").is_err());
        assert!(normalize_json_path("text' OR '1'='1").is_err());
    }

    #[test]
    fn test_build_sql_basic() {
        let store = RecordStore::open_in_memory().unwrap();
        let q = store
            .query("app.bsky.feed.post")
            .did("did:plc:alice")
            .where_json("rating", QueryOp::Gte, json!(3))
            .order_by("indexed_at", SortDirection::Desc)
            .limit(10)
            .offset(5);

        let (sql, params) = q.build_sql().unwrap();
        assert!(sql.contains("WHERE collection = ?"));
        assert!(sql.contains("AND is_deleted = 0"));
        assert!(sql.contains("AND did = ?"));
        assert!(sql.contains("AND json_extract(record_json, ?) >= ?"));
        assert!(sql.contains("ORDER BY indexed_at DESC"));
        assert!(sql.contains("LIMIT ? OFFSET ?"));
        assert_eq!(params.len(), 6);
    }

    #[test]
    fn test_equality_query() {
        let store = setup_test_store();
        let rows = store
            .query("app.bsky.feed.post")
            .where_json("rating", QueryOp::Eq, json!(5))
            .execute()
            .unwrap();

        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].uri, "at://did:plc:alice/app.bsky.feed.post/post1");
    }

    #[test]
    fn test_boolean_query_matches_sqlite() {
        let store = setup_test_store();
        let rows = store
            .query("app.bsky.feed.post")
            .where_json("is_published", QueryOp::Eq, json!(true))
            .execute()
            .unwrap();

        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].uri, "at://did:plc:alice/app.bsky.feed.post/post1");

        let false_rows = store
            .query("app.bsky.feed.post")
            .where_json("is_published", QueryOp::Eq, json!(false))
            .execute()
            .unwrap();

        assert_eq!(false_rows.len(), 1);
        assert_eq!(
            false_rows[0].uri,
            "at://did:plc:bob/app.bsky.feed.post/post2"
        );
    }

    #[test]
    fn test_nested_json_lookup() {
        let store = setup_test_store();
        let rows = store
            .query("app.bsky.feed.post")
            .where_json("metadata.views", QueryOp::Eq, json!(100))
            .execute()
            .unwrap();

        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].uri, "at://did:plc:alice/app.bsky.feed.post/post1");
    }

    #[test]
    fn test_substring_contains_query() {
        let store = setup_test_store();
        let rows = store
            .query("app.bsky.feed.post")
            .where_json("text", QueryOp::Contains, json!("future"))
            .execute()
            .unwrap();

        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].uri, "at://did:plc:bob/app.bsky.feed.post/post2");
    }

    #[test]
    fn test_ordering_and_pagination() {
        let store = setup_test_store();
        let rows = store
            .query("app.bsky.feed.post")
            .order_by("indexed_at", SortDirection::Desc)
            .limit(1)
            .offset(0)
            .execute()
            .unwrap();

        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].uri, "at://did:plc:bob/app.bsky.feed.post/post2");
    }

    #[test]
    fn test_soft_delete_exclusion_and_inclusion() {
        let store = setup_test_store();

        let active_rows = store.query("app.bsky.feed.post").execute().unwrap();
        assert_eq!(active_rows.len(), 2);

        let all_rows = store
            .query("app.bsky.feed.post")
            .include_deleted(true)
            .execute()
            .unwrap();
        assert_eq!(all_rows.len(), 3);
    }

    #[test]
    fn test_null_comparisons() {
        let store = setup_test_store();

        let null_rows = store
            .query("app.bsky.feed.post")
            .where_json("note", QueryOp::Eq, serde_json::Value::Null)
            .execute()
            .unwrap();
        assert_eq!(null_rows.len(), 1);
        assert_eq!(
            null_rows[0].uri,
            "at://did:plc:alice/app.bsky.feed.post/post1"
        );

        let not_null_rows = store
            .query("app.bsky.feed.post")
            .where_json("note", QueryOp::Ne, serde_json::Value::Null)
            .execute()
            .unwrap();
        assert_eq!(not_null_rows.len(), 1);
        assert_eq!(
            not_null_rows[0].uri,
            "at://did:plc:bob/app.bsky.feed.post/post2"
        );
    }

    #[test]
    fn test_numeric_comparisons() {
        let store = setup_test_store();

        let gt_rows = store
            .query("app.bsky.feed.post")
            .where_json("rating", QueryOp::Gt, json!(3))
            .execute()
            .unwrap();
        assert_eq!(gt_rows.len(), 1);
        assert_eq!(
            gt_rows[0].uri,
            "at://did:plc:alice/app.bsky.feed.post/post1"
        );

        let lte_rows = store
            .query("app.bsky.feed.post")
            .where_json("rating", QueryOp::Lte, json!(3))
            .execute()
            .unwrap();
        assert_eq!(lte_rows.len(), 1);
        assert_eq!(lte_rows[0].uri, "at://did:plc:bob/app.bsky.feed.post/post2");
    }

    #[test]
    fn test_order_by_json_path() {
        let store = setup_test_store();
        let rows = store
            .query("app.bsky.feed.post")
            .order_by("rating", SortDirection::Asc)
            .execute()
            .unwrap();
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0].uri, "at://did:plc:bob/app.bsky.feed.post/post2");
        assert_eq!(rows[1].uri, "at://did:plc:alice/app.bsky.feed.post/post1");
    }

    #[test]
    fn test_like_query() {
        let store = setup_test_store();
        let rows = store
            .query("app.bsky.feed.post")
            .where_json("text", QueryOp::Like, "%future%")
            .execute()
            .unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].uri, "at://did:plc:bob/app.bsky.feed.post/post2");
    }

    #[test]
    fn test_contains_escapes_wildcards() {
        let store = RecordStore::open_in_memory().unwrap();
        let r1 = RecordInput::new(
            "did:plc:test",
            "app.bsky.feed.post",
            "p1",
            "cid1",
            json!({"text": "Discount is 100% off today"}),
            100,
        );
        let r2 = RecordInput::new(
            "did:plc:test",
            "app.bsky.feed.post",
            "p2",
            "cid2",
            json!({"text": "1000 items in stock"}),
            200,
        );
        store.upsert_record(&r1).unwrap();
        store.upsert_record(&r2).unwrap();

        // Searching for "100%" with Contains must find only r1, not r2
        let rows = store
            .query("app.bsky.feed.post")
            .where_json("text", QueryOp::Contains, "100%")
            .execute()
            .unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].uri, r1.uri);

        // Searching with Like without escaping "%" would match both if not anchored
        let like_rows = store
            .query("app.bsky.feed.post")
            .where_json("text", QueryOp::Like, "%100%")
            .execute()
            .unwrap();
        assert_eq!(like_rows.len(), 2);
    }

    #[test]
    fn test_validate_json_path_rejects_dollar_foo() {
        assert!(normalize_json_path("$foo").is_err());
        assert!(normalize_json_path("$.foo").is_ok());
        assert!(normalize_json_path("$[0]").is_ok());
        assert!(normalize_json_path("foo").is_ok());
        assert!(normalize_json_path("[0]").is_ok());
    }
}