fraiseql-db 2.2.0

Database abstraction layer for FraiseQL v2
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
//! WHERE clause to SQL string generator for fraiseql-wire.
//!
//! Converts FraiseQL's WHERE clause AST to SQL predicates that can be used
//! with fraiseql-wire's `where_sql()` method.

use fraiseql_error::{FraiseQLError, Result};
use serde_json::Value;

use crate::{WhereClause, WhereOperator};

/// Maximum allowed byte length for a string value embedded in a raw SQL query.
///
/// Applies to SQL fragments assembled via string escaping (e.g. LIKE patterns,
/// JSON path keys). Regular parameterized query paths are unaffected.
/// 64 KiB is generous for any realistic filter value while blocking DoS inputs.
const MAX_SQL_VALUE_BYTES: usize = 65_536;

/// Generates SQL WHERE clause strings from AST.
///
/// # Note on continued existence
///
/// This generator embeds values as escaped string literals rather than using
/// bind parameters.  It is intentionally retained for the **FraiseQL Wire
/// Adapter** (`fraiseql_wire_adapter`), which constructs raw SQL strings for
/// the wire protocol — a context where parameterized queries are not available.
///
/// **Do not use this in new production code.**  All other query paths must use
/// [`GenericWhereGenerator`](crate::GenericWhereGenerator) which produces
/// parameterized SQL (`$1`, `?`, etc.) and is safe by design.
#[doc(hidden)]
pub struct WhereSqlGenerator;

impl WhereSqlGenerator {
    /// Convert WHERE clause AST to SQL string.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// // fraiseql-db can be used directly or via `fraiseql_core::db` (re-export).
    /// use fraiseql_db::{WhereClause, WhereOperator, where_sql_generator::WhereSqlGenerator};
    /// use serde_json::json;
    ///
    /// let clause = WhereClause::Field {
    ///     path: vec!["status".to_string()],
    ///     operator: WhereOperator::Eq,
    ///     value: json!("active"),
    /// };
    ///
    /// let sql = WhereSqlGenerator::to_sql(&clause).unwrap();
    /// assert_eq!(sql, "data->>'status' = 'active'");
    /// ```
    ///
    /// # Errors
    ///
    /// Returns `FraiseQLError::Validation` if the clause contains an unsupported
    /// operator or an invalid value for the given operator.
    pub fn to_sql(clause: &WhereClause) -> Result<String> {
        match clause {
            WhereClause::Field {
                path,
                operator,
                value,
            } => Self::generate_field_predicate(path, operator, value),
            WhereClause::And(clauses) => {
                if clauses.is_empty() {
                    return Ok("TRUE".to_string());
                }
                let parts: Result<Vec<_>> = clauses.iter().map(Self::to_sql).collect();
                Ok(format!("({})", parts?.join(" AND ")))
            },
            WhereClause::Or(clauses) => {
                if clauses.is_empty() {
                    return Ok("FALSE".to_string());
                }
                let parts: Result<Vec<_>> = clauses.iter().map(Self::to_sql).collect();
                Ok(format!("({})", parts?.join(" OR ")))
            },
            WhereClause::Not(clause) => {
                let inner = Self::to_sql(clause)?;
                Ok(format!("NOT ({})", inner))
            },
            WhereClause::NativeField {
                column,
                operator,
                value,
                ..
            } => {
                // Wire adapter: use native column name directly with escaped literal value.
                // Cast suffix is omitted — wire protocol assembles raw SQL without bind params.
                let escaped_col = Self::escape_sql_string(column)?;
                let col_expr = format!("\"{escaped_col}\"");
                let sql_op = Self::operator_to_sql(operator)?;
                let val_sql = Self::value_to_sql(value, operator)?;
                Ok(format!("{col_expr} {sql_op} {val_sql}"))
            },
        }
    }

    fn generate_field_predicate(
        path: &[String],
        operator: &WhereOperator,
        value: &Value,
    ) -> Result<String> {
        let json_path = Self::build_json_path(path)?;
        let sql = if operator == &WhereOperator::IsNull {
            let is_null = value.as_bool().unwrap_or(true);
            if is_null {
                format!("{json_path} IS NULL")
            } else {
                format!("{json_path} IS NOT NULL")
            }
        } else {
            let sql_op = Self::operator_to_sql(operator)?;
            let sql_value = Self::value_to_sql(value, operator)?;
            format!("{json_path} {sql_op} {sql_value}")
        };
        Ok(sql)
    }

    fn build_json_path(path: &[String]) -> Result<String> {
        if path.is_empty() {
            return Ok("data".to_string());
        }

        if path.len() == 1 {
            // Simple path: data->>'field'
            // SECURITY: Escape field name to prevent SQL injection
            let escaped = Self::escape_sql_string(&path[0])?;
            Ok(format!("data->>'{}'", escaped))
        } else {
            // Nested path: data#>'{a,b,c}'->>'d'
            // SECURITY: Escape all field names to prevent SQL injection
            let nested = &path[..path.len() - 1];
            let last = &path[path.len() - 1];

            // Escape all nested components
            let escaped_nested: Vec<String> =
                nested.iter().map(|n| Self::escape_sql_string(n)).collect::<Result<Vec<_>>>()?;
            let nested_path = escaped_nested.join(",");
            let escaped_last = Self::escape_sql_string(last)?;
            Ok(format!("data#>'{{{}}}'->>'{}'", nested_path, escaped_last))
        }
    }

    fn operator_to_sql(operator: &WhereOperator) -> Result<&'static str> {
        Ok(match operator {
            // Comparison
            WhereOperator::Eq => "=",
            WhereOperator::Neq => "!=",
            WhereOperator::Gt => ">",
            WhereOperator::Gte => ">=",
            WhereOperator::Lt => "<",
            WhereOperator::Lte => "<=",

            // Containment
            WhereOperator::In => "= ANY",
            WhereOperator::Nin => "!= ALL",

            // String operations
            WhereOperator::Contains => "LIKE",
            WhereOperator::Icontains => "ILIKE",
            WhereOperator::Startswith => "LIKE",
            WhereOperator::Istartswith => "ILIKE",
            WhereOperator::Endswith => "LIKE",
            WhereOperator::Iendswith => "ILIKE",
            WhereOperator::Like => "LIKE",
            WhereOperator::Ilike => "ILIKE",
            WhereOperator::Nlike => "NOT LIKE",
            WhereOperator::Nilike => "NOT ILIKE",
            WhereOperator::Regex => "~",
            WhereOperator::Iregex => "~*",
            WhereOperator::Nregex => "!~",
            WhereOperator::Niregex => "!~*",

            // Array operations
            WhereOperator::ArrayContains => "@>",
            WhereOperator::ArrayContainedBy => "<@",
            WhereOperator::ArrayOverlaps => "&&",

            // These operators require special handling
            WhereOperator::IsNull => {
                return Err(FraiseQLError::Internal {
                    message: "IsNull should be handled separately".to_string(),
                    source:  None,
                });
            },
            WhereOperator::LenEq
            | WhereOperator::LenGt
            | WhereOperator::LenLt
            | WhereOperator::LenGte
            | WhereOperator::LenLte
            | WhereOperator::LenNeq => {
                return Err(FraiseQLError::Internal {
                    message: format!(
                        "Array length operators not yet supported in fraiseql-wire: {operator:?}"
                    ),
                    source:  None,
                });
            },

            // Vector operations not supported
            WhereOperator::L2Distance
            | WhereOperator::CosineDistance
            | WhereOperator::L1Distance
            | WhereOperator::HammingDistance
            | WhereOperator::InnerProduct
            | WhereOperator::JaccardDistance => {
                return Err(FraiseQLError::Internal {
                    message: format!(
                        "Vector operations not supported in fraiseql-wire: {operator:?}"
                    ),
                    source:  None,
                });
            },

            // Full-text search operators not supported yet
            WhereOperator::Matches
            | WhereOperator::PlainQuery
            | WhereOperator::PhraseQuery
            | WhereOperator::WebsearchQuery => {
                return Err(FraiseQLError::Internal {
                    message: format!(
                        "Full-text search operators not yet supported in fraiseql-wire: {operator:?}"
                    ),
                    source:  None,
                });
            },

            // Network operators not supported yet
            WhereOperator::IsIPv4
            | WhereOperator::IsIPv6
            | WhereOperator::IsPrivate
            | WhereOperator::IsPublic
            | WhereOperator::IsLoopback
            | WhereOperator::InSubnet
            | WhereOperator::ContainsSubnet
            | WhereOperator::ContainsIP
            | WhereOperator::Overlaps
            | WhereOperator::StrictlyContains
            | WhereOperator::AncestorOf
            | WhereOperator::DescendantOf
            | WhereOperator::MatchesLquery
            | WhereOperator::MatchesLtxtquery
            | WhereOperator::MatchesAnyLquery
            | WhereOperator::DepthEq
            | WhereOperator::DepthNeq
            | WhereOperator::DepthGt
            | WhereOperator::DepthGte
            | WhereOperator::DepthLt
            | WhereOperator::DepthLte
            | WhereOperator::Lca
            | WhereOperator::Extended(_) => {
                return Err(FraiseQLError::Internal {
                    message: format!(
                        "Advanced operators not yet supported in fraiseql-wire: {operator:?}"
                    ),
                    source:  None,
                });
            },
        })
    }

    fn value_to_sql(value: &Value, operator: &WhereOperator) -> Result<String> {
        match (value, operator) {
            (Value::Null, _) => Ok("NULL".to_string()),
            (Value::Bool(b), _) => Ok(b.to_string()),
            (Value::Number(n), _) => Ok(n.to_string()),

            // String operators with wildcards
            (Value::String(s), WhereOperator::Contains | WhereOperator::Icontains) => {
                Ok(format!("'%{}%'", Self::escape_sql_string(s)?))
            },
            (Value::String(s), WhereOperator::Startswith | WhereOperator::Istartswith) => {
                Ok(format!("'{}%'", Self::escape_sql_string(s)?))
            },
            (Value::String(s), WhereOperator::Endswith | WhereOperator::Iendswith) => {
                Ok(format!("'%{}'", Self::escape_sql_string(s)?))
            },

            // Regular strings
            (Value::String(s), _) => Ok(format!("'{}'", Self::escape_sql_string(s)?)),

            // Arrays (for IN operator)
            (Value::Array(arr), WhereOperator::In | WhereOperator::Nin) => {
                let values: Result<Vec<_>> =
                    arr.iter().map(|v| Self::value_to_sql(v, &WhereOperator::Eq)).collect();
                Ok(format!("ARRAY[{}]", values?.join(", ")))
            },

            // Array operations
            (
                Value::Array(_),
                WhereOperator::ArrayContains
                | WhereOperator::ArrayContainedBy
                | WhereOperator::ArrayOverlaps,
            ) => {
                // SECURITY: Serialize to JSON string and escape single quotes to prevent
                // SQL injection. The serde_json serializer handles internal escaping, and
                // we escape single quotes for the SQL string literal context.
                let json_str =
                    serde_json::to_string(value).map_err(|e| FraiseQLError::Internal {
                        message: format!("Failed to serialize JSON for array operator: {e}"),
                        source:  None,
                    })?;
                if json_str.len() > MAX_SQL_VALUE_BYTES {
                    return Err(FraiseQLError::Validation {
                        message: format!(
                            "JSONB value exceeds maximum allowed size for SQL embedding \
                             ({} bytes, limit is {} bytes)",
                            json_str.len(),
                            MAX_SQL_VALUE_BYTES
                        ),
                        path:    None,
                    });
                }
                let escaped = json_str.replace('\'', "''");
                Ok(format!("'{}'::jsonb", escaped))
            },

            _ => Err(FraiseQLError::Internal {
                message: format!(
                    "Unsupported value type for operator: {value:?} with {operator:?}"
                ),
                source:  None,
            }),
        }
    }

    fn escape_sql_string(s: &str) -> Result<String> {
        if s.len() > MAX_SQL_VALUE_BYTES {
            return Err(FraiseQLError::Validation {
                message: format!(
                    "String value exceeds maximum allowed size for SQL embedding \
                     ({} bytes, limit is {} bytes)",
                    s.len(),
                    MAX_SQL_VALUE_BYTES
                ),
                path:    None,
            });
        }
        Ok(s.replace('\'', "''"))
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable
mod tests {
    use serde_json::json;

    use super::*;

    #[test]
    fn test_simple_equality() {
        let clause = WhereClause::Field {
            path:     vec!["status".to_string()],
            operator: WhereOperator::Eq,
            value:    json!("active"),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).unwrap();
        assert_eq!(sql, "data->>'status' = 'active'");
    }

    #[test]
    fn test_nested_path() {
        let clause = WhereClause::Field {
            path:     vec!["user".to_string(), "email".to_string()],
            operator: WhereOperator::Eq,
            value:    json!("test@example.com"),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).unwrap();
        assert_eq!(sql, "data#>'{user}'->>'email' = 'test@example.com'");
    }

    #[test]
    fn test_icontains() {
        let clause = WhereClause::Field {
            path:     vec!["name".to_string()],
            operator: WhereOperator::Icontains,
            value:    json!("john"),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).unwrap();
        assert_eq!(sql, "data->>'name' ILIKE '%john%'");
    }

    #[test]
    fn test_startswith() {
        let clause = WhereClause::Field {
            path:     vec!["email".to_string()],
            operator: WhereOperator::Startswith,
            value:    json!("admin"),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).unwrap();
        assert_eq!(sql, "data->>'email' LIKE 'admin%'");
    }

    #[test]
    fn test_and_clause() {
        let clause = WhereClause::And(vec![
            WhereClause::Field {
                path:     vec!["status".to_string()],
                operator: WhereOperator::Eq,
                value:    json!("active"),
            },
            WhereClause::Field {
                path:     vec!["age".to_string()],
                operator: WhereOperator::Gte,
                value:    json!(18),
            },
        ]);

        let sql = WhereSqlGenerator::to_sql(&clause).unwrap();
        assert_eq!(sql, "(data->>'status' = 'active' AND data->>'age' >= 18)");
    }

    #[test]
    fn test_or_clause() {
        let clause = WhereClause::Or(vec![
            WhereClause::Field {
                path:     vec!["type".to_string()],
                operator: WhereOperator::Eq,
                value:    json!("admin"),
            },
            WhereClause::Field {
                path:     vec!["type".to_string()],
                operator: WhereOperator::Eq,
                value:    json!("moderator"),
            },
        ]);

        let sql = WhereSqlGenerator::to_sql(&clause).unwrap();
        assert_eq!(sql, "(data->>'type' = 'admin' OR data->>'type' = 'moderator')");
    }

    #[test]
    fn test_not_clause() {
        let clause = WhereClause::Not(Box::new(WhereClause::Field {
            path:     vec!["deleted".to_string()],
            operator: WhereOperator::Eq,
            value:    json!(true),
        }));

        let sql = WhereSqlGenerator::to_sql(&clause).unwrap();
        assert_eq!(sql, "NOT (data->>'deleted' = true)");
    }

    #[test]
    fn test_is_null() {
        let clause = WhereClause::Field {
            path:     vec!["deleted_at".to_string()],
            operator: WhereOperator::IsNull,
            value:    json!(true),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).unwrap();
        assert_eq!(sql, "data->>'deleted_at' IS NULL");
    }

    #[test]
    fn test_is_not_null() {
        let clause = WhereClause::Field {
            path:     vec!["updated_at".to_string()],
            operator: WhereOperator::IsNull,
            value:    json!(false),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).unwrap();
        assert_eq!(sql, "data->>'updated_at' IS NOT NULL");
    }

    #[test]
    fn test_in_operator() {
        let clause = WhereClause::Field {
            path:     vec!["status".to_string()],
            operator: WhereOperator::In,
            value:    json!(["active", "pending", "approved"]),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).unwrap();
        assert_eq!(sql, "data->>'status' = ANY ARRAY['active', 'pending', 'approved']");
    }

    #[test]
    fn test_sql_injection_prevention() {
        let clause = WhereClause::Field {
            path:     vec!["name".to_string()],
            operator: WhereOperator::Eq,
            value:    json!("'; DROP TABLE users; --"),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).unwrap();
        assert_eq!(sql, "data->>'name' = '''; DROP TABLE users; --'");
        // Single quotes are escaped to ''
    }

    #[test]
    fn test_numeric_comparison() {
        let clause = WhereClause::Field {
            path:     vec!["price".to_string()],
            operator: WhereOperator::Gt,
            value:    json!(99.99),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).unwrap();
        assert_eq!(sql, "data->>'price' > 99.99");
    }

    #[test]
    fn test_boolean_value() {
        let clause = WhereClause::Field {
            path:     vec!["published".to_string()],
            operator: WhereOperator::Eq,
            value:    json!(true),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).unwrap();
        assert_eq!(sql, "data->>'published' = true");
    }

    #[test]
    fn test_empty_and_clause() {
        let clause = WhereClause::And(vec![]);
        let sql = WhereSqlGenerator::to_sql(&clause).unwrap();
        assert_eq!(sql, "TRUE");
    }

    #[test]
    fn test_empty_or_clause() {
        let clause = WhereClause::Or(vec![]);
        let sql = WhereSqlGenerator::to_sql(&clause).unwrap();
        assert_eq!(sql, "FALSE");
    }

    #[test]
    fn test_complex_nested_condition() {
        let clause = WhereClause::And(vec![
            WhereClause::Field {
                path:     vec!["type".to_string()],
                operator: WhereOperator::Eq,
                value:    json!("article"),
            },
            WhereClause::Or(vec![
                WhereClause::Field {
                    path:     vec!["status".to_string()],
                    operator: WhereOperator::Eq,
                    value:    json!("published"),
                },
                WhereClause::And(vec![
                    WhereClause::Field {
                        path:     vec!["status".to_string()],
                        operator: WhereOperator::Eq,
                        value:    json!("draft"),
                    },
                    WhereClause::Field {
                        path:     vec!["author".to_string(), "role".to_string()],
                        operator: WhereOperator::Eq,
                        value:    json!("admin"),
                    },
                ]),
            ]),
        ]);

        let sql = WhereSqlGenerator::to_sql(&clause).unwrap();
        assert_eq!(
            sql,
            "(data->>'type' = 'article' AND (data->>'status' = 'published' OR (data->>'status' = 'draft' AND data#>'{author}'->>'role' = 'admin')))"
        );
    }

    #[test]
    fn test_sql_injection_in_field_name_simple() {
        // Test that malicious field names are escaped to prevent SQL injection
        let clause = WhereClause::Field {
            path:     vec!["name'; DROP TABLE users; --".to_string()],
            operator: WhereOperator::Eq,
            value:    json!("value"),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).unwrap();
        // Field name should be escaped with doubled single quotes
        // Result: data->>'name''; DROP TABLE users; --' = 'value'
        // The doubled '' prevents the quote from closing the string
        assert!(sql.contains("''")); // Escaped quotes present
        // The SQL structure should be: identifier->>'field' operator value
        // With escaping, DROP TABLE becomes part of the field string, not executable
        assert!(sql.contains("data->>'"));
        assert!(sql.contains("= 'value'")); // Proper value comparison
    }

    #[test]
    fn test_sql_injection_prevention_in_array_operator() {
        // SECURITY: Ensure JSON injection in array operators is escaped
        let clause = WhereClause::Field {
            path:     vec!["tags".to_string()],
            operator: WhereOperator::ArrayContains,
            value:    json!(["normal", "'; DROP TABLE users; --"]),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).unwrap();
        // The JSON serializer will escape the inner quotes, and we escape SQL single quotes.
        // The result should be a properly escaped JSONB literal, not executable SQL.
        assert!(sql.contains("::jsonb"), "Must produce valid JSONB cast");
        // Verify the value is inside a JSON string (double-quoted), not a raw SQL string.
        // serde_json serializes this as: ["normal","'; DROP TABLE users; --"]
        // After SQL escaping: ["normal","''; DROP TABLE users; --"]
        // The single quote inside the JSON value is doubled for SQL safety.
        assert!(
            sql.contains("''"),
            "Single quotes inside JSON values must be doubled for SQL safety"
        );
    }

    #[test]
    fn test_sql_injection_in_nested_field_name() {
        // Test that malicious nested field names are also escaped
        let clause = WhereClause::Field {
            path:     vec![
                "user".to_string(),
                "role'; DROP TABLE users; --".to_string(),
            ],
            operator: WhereOperator::Eq,
            value:    json!("admin"),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).unwrap();
        // Both simple and nested path components should be escaped
        assert!(sql.contains("''")); // Escaped quotes present
        assert!(sql.contains("data#>'{")); // Nested path syntax
    }

    #[test]
    fn escape_sql_string_rejects_oversized_input() {
        let large = "a".repeat(MAX_SQL_VALUE_BYTES + 1);
        let result = WhereSqlGenerator::escape_sql_string(&large);
        assert!(matches!(result, Err(FraiseQLError::Validation { .. })));
    }

    #[test]
    fn escape_sql_string_accepts_exactly_max_bytes() {
        let at_limit = "a".repeat(MAX_SQL_VALUE_BYTES);
        WhereSqlGenerator::escape_sql_string(&at_limit).unwrap_or_else(|e| {
            panic!("expected Ok for string at exactly MAX_SQL_VALUE_BYTES: {e}")
        });
    }

    #[test]
    fn escape_sql_string_escapes_single_quotes() {
        let result = WhereSqlGenerator::escape_sql_string("it's").unwrap();
        assert_eq!(result, "it''s");
    }

    #[test]
    fn value_to_sql_rejects_oversized_string_value() {
        let large = "a".repeat(MAX_SQL_VALUE_BYTES + 1);
        let clause = WhereClause::Field {
            path:     vec!["name".to_string()],
            operator: WhereOperator::Eq,
            value:    json!(large),
        };
        assert!(matches!(
            WhereSqlGenerator::to_sql(&clause),
            Err(FraiseQLError::Validation { .. })
        ));
    }

    #[test]
    fn value_to_sql_rejects_oversized_jsonb_value() {
        // Build an array large enough to exceed MAX_SQL_VALUE_BYTES when serialized
        let large_element = "a".repeat(MAX_SQL_VALUE_BYTES);
        let clause = WhereClause::Field {
            path:     vec!["tags".to_string()],
            operator: WhereOperator::ArrayContains,
            value:    json!([large_element]),
        };
        assert!(matches!(
            WhereSqlGenerator::to_sql(&clause),
            Err(FraiseQLError::Validation { .. })
        ));
    }
}