heliosdb-nano 3.30.0

PostgreSQL-compatible embedded database with TDE + ZKE encryption, HNSW vector search, Product Quantization, git-like branching, time-travel queries, materialized views, row-level security, and 50+ enterprise features
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
//! RLS expression parsing and evaluation
//!
//! This module provides functionality to parse and evaluate Row-Level Security (RLS)
//! policy expressions for multi-tenant data isolation.

use crate::{Result, Error, Value, Tuple, Schema};
use crate::sql::{LogicalExpr, BinaryOperator};
use crate::tenant::TenantContext;
use sqlparser::ast::{Expr, BinaryOperator as SqlBinaryOp, UnaryOperator as SqlUnaryOp};
use sqlparser::dialect::PostgreSqlDialect;
use sqlparser::parser::Parser as SqlParser;
use std::sync::Arc;

/// RLS expression evaluator
///
/// Evaluates RLS policy expressions against tuples in a tenant context.
pub struct RLSExpressionEvaluator {
    /// The schema of the table being evaluated
    schema: Arc<Schema>,
    /// The current tenant context
    tenant_context: Option<TenantContext>,
}

impl RLSExpressionEvaluator {
    /// Create a new RLS expression evaluator
    pub fn new(schema: Arc<Schema>, tenant_context: Option<TenantContext>) -> Self {
        Self {
            schema,
            tenant_context,
        }
    }

    /// Parse an RLS expression string into a LogicalExpr
    ///
    /// # Arguments
    ///
    /// * `expr_str` - The RLS expression string (e.g., "tenant_id = current_tenant()")
    ///
    /// # Returns
    ///
    /// A LogicalExpr that can be evaluated against tuples
    pub fn parse(&self, expr_str: &str) -> Result<LogicalExpr> {
        // Parse the expression using sqlparser
        let dialect = PostgreSqlDialect {};

        // Wrap the expression in a SELECT to make it parseable
        let sql = format!("SELECT * FROM dummy WHERE {}", expr_str);

        let mut statements = SqlParser::parse_sql(&dialect, &sql)
            .map_err(|e| Error::query_execution(format!("Failed to parse RLS expression '{}': {}", expr_str, e)))?;

        if statements.len() != 1 {
            return Err(Error::query_execution("Invalid RLS expression: expected single statement"));
        }

        // Extract the WHERE clause from the SELECT statement
        let statement = statements.remove(0);

        if let sqlparser::ast::Statement::Query(query) = statement {
            if let sqlparser::ast::SetExpr::Select(select) = *query.body {
                if let Some(selection) = select.selection {
                    return self.sql_expr_to_logical(&selection);
                }
            }
        }

        Err(Error::query_execution(format!("Failed to extract WHERE clause from RLS expression: {}", expr_str)))
    }

    /// Convert a SQL expression to a LogicalExpr
    fn sql_expr_to_logical(&self, expr: &Expr) -> Result<LogicalExpr> {
        match expr {
            Expr::Identifier(ident) => Ok(LogicalExpr::Column {
                table: None,
                name: ident.value.clone(),
            }),

            Expr::CompoundIdentifier(idents) => {
                // Handle table.column references - preserve the table qualifier for JOIN disambiguation
                if idents.len() >= 2 {
                    let table_alias = idents.get(idents.len() - 2)
                        .ok_or_else(|| Error::query_execution("Invalid compound identifier"))?
                        .value.clone();
                    let column_name = idents.last()
                        .ok_or_else(|| Error::query_execution("Empty compound identifier"))?
                        .value.clone();
                    Ok(LogicalExpr::Column {
                        table: Some(table_alias),
                        name: column_name,
                    })
                } else {
                    let column_name = idents.last()
                        .ok_or_else(|| Error::query_execution("Empty compound identifier"))?
                        .value.clone();
                    Ok(LogicalExpr::Column {
                        table: None,
                        name: column_name,
                    })
                }
            }

            Expr::Value(value) => {
                Ok(LogicalExpr::Literal(self.sql_value_to_value(value)?))
            }

            Expr::BinaryOp { left, op, right } => {
                let left_expr = self.sql_expr_to_logical(left)?;
                let right_expr = self.sql_expr_to_logical(right)?;
                let logical_op = self.sql_binary_op_to_logical(op)?;

                Ok(LogicalExpr::BinaryExpr {
                    left: Box::new(left_expr),
                    op: logical_op,
                    right: Box::new(right_expr),
                })
            }

            Expr::UnaryOp { op, expr } => {
                let logical_expr = self.sql_expr_to_logical(expr)?;
                let logical_op = self.sql_unary_op_to_logical(op)?;

                Ok(LogicalExpr::UnaryExpr {
                    op: logical_op,
                    expr: Box::new(logical_expr),
                })
            }

            Expr::Function(func) => {
                let func_name = func.name.to_string().to_lowercase();

                // Extract arguments based on FunctionArguments type
                let arg_list = match &func.args {
                    sqlparser::ast::FunctionArguments::None => vec![],
                    sqlparser::ast::FunctionArguments::Subquery(_) => {
                        return Err(Error::query_execution(
                            "Subquery arguments not supported in RLS functions".to_string()
                        ));
                    }
                    sqlparser::ast::FunctionArguments::List(list) => list.args.clone(),
                };

                let args: Result<Vec<LogicalExpr>> = arg_list
                    .iter()
                    .filter_map(|arg| {
                        if let sqlparser::ast::FunctionArg::Unnamed(sqlparser::ast::FunctionArgExpr::Expr(expr)) = arg {
                            Some(self.sql_expr_to_logical(&expr))
                        } else {
                            None
                        }
                    })
                    .collect();

                Ok(LogicalExpr::ScalarFunction {
                    fun: func_name,
                    args: args?,
                })
            }

            Expr::IsNull(expr) => Ok(LogicalExpr::IsNull {
                expr: Box::new(self.sql_expr_to_logical(expr)?),
                is_null: true,
            }),

            Expr::IsNotNull(expr) => Ok(LogicalExpr::IsNull {
                expr: Box::new(self.sql_expr_to_logical(expr)?),
                is_null: false,
            }),

            _ => Err(Error::query_execution(format!(
                "Unsupported expression in RLS policy: {:?}",
                expr
            ))),
        }
    }

    /// Convert SQL binary operator to logical operator
    fn sql_binary_op_to_logical(&self, op: &SqlBinaryOp) -> Result<BinaryOperator> {
        match op {
            SqlBinaryOp::Eq => Ok(BinaryOperator::Eq),
            SqlBinaryOp::NotEq => Ok(BinaryOperator::NotEq),
            SqlBinaryOp::Lt => Ok(BinaryOperator::Lt),
            SqlBinaryOp::LtEq => Ok(BinaryOperator::LtEq),
            SqlBinaryOp::Gt => Ok(BinaryOperator::Gt),
            SqlBinaryOp::GtEq => Ok(BinaryOperator::GtEq),
            SqlBinaryOp::And => Ok(BinaryOperator::And),
            SqlBinaryOp::Or => Ok(BinaryOperator::Or),
            _ => Err(Error::query_execution(format!(
                "Unsupported binary operator in RLS: {:?}",
                op
            ))),
        }
    }

    /// Convert SQL unary operator to logical operator
    fn sql_unary_op_to_logical(&self, op: &SqlUnaryOp) -> Result<crate::sql::UnaryOperator> {
        match op {
            SqlUnaryOp::Not => Ok(crate::sql::UnaryOperator::Not),
            SqlUnaryOp::Minus => Ok(crate::sql::UnaryOperator::Minus),
            SqlUnaryOp::Plus => Ok(crate::sql::UnaryOperator::Plus),
            _ => Err(Error::query_execution(format!(
                "Unsupported unary operator in RLS: {:?}",
                op
            ))),
        }
    }

    /// Convert SQL value to internal Value
    fn sql_value_to_value(&self, value: &sqlparser::ast::Value) -> Result<Value> {
        match value {
            sqlparser::ast::Value::Number(n, _) => {
                // Try to parse as integer first, then as float
                if let Ok(i) = n.parse::<i64>() {
                    Ok(Value::Int8(i))
                } else if let Ok(f) = n.parse::<f64>() {
                    Ok(Value::Float8(f))
                } else {
                    Err(Error::query_execution(format!("Invalid number: {}", n)))
                }
            }
            sqlparser::ast::Value::SingleQuotedString(s) |
            sqlparser::ast::Value::DoubleQuotedString(s) => {
                Ok(Value::String(s.clone()))
            }
            sqlparser::ast::Value::Boolean(b) => Ok(Value::Boolean(*b)),
            sqlparser::ast::Value::Null => Ok(Value::Null),
            _ => Err(Error::query_execution(format!(
                "Unsupported value type in RLS: {:?}",
                value
            ))),
        }
    }

    /// Evaluate an RLS expression against a tuple
    ///
    /// # Arguments
    ///
    /// * `expr` - The logical expression to evaluate
    /// * `tuple` - The tuple to evaluate against
    ///
    /// # Returns
    ///
    /// `true` if the tuple satisfies the RLS policy, `false` otherwise
    pub fn evaluate(&self, expr: &LogicalExpr, tuple: &Tuple) -> Result<bool> {
        let value = self.evaluate_expr(expr, tuple)?;

        match value {
            Value::Boolean(b) => Ok(b),
            _ => Err(Error::query_execution(format!(
                "RLS expression must evaluate to boolean, got: {:?}",
                value
            ))),
        }
    }

    /// Evaluate an expression to a value
    fn evaluate_expr(&self, expr: &LogicalExpr, tuple: &Tuple) -> Result<Value> {
        match expr {
            LogicalExpr::Literal(value) => Ok(value.clone()),

            LogicalExpr::Column { name, .. } => {
                // Find column index in schema
                let index = self.schema.get_column_index(name)
                    .ok_or_else(|| Error::query_execution(format!(
                        "Column '{}' not found in schema",
                        name
                    )))?;

                // Get value from tuple
                tuple.get(index)
                    .cloned()
                    .ok_or_else(|| Error::query_execution(format!(
                        "Column index {} out of bounds in tuple",
                        index
                    )))
            }

            LogicalExpr::BinaryExpr { left, op, right } => {
                // AND/OR require short-circuit evaluation with SQL three-valued logic.
                match op {
                    BinaryOperator::And => {
                        return self.evaluate_and_short_circuit(left, right, tuple);
                    }
                    BinaryOperator::Or => {
                        return self.evaluate_or_short_circuit(left, right, tuple);
                    }
                    _ => {}
                }
                let left_val = self.evaluate_expr(left, tuple)?;
                let right_val = self.evaluate_expr(right, tuple)?;
                self.evaluate_binary_op(&left_val, op, &right_val)
            }

            LogicalExpr::UnaryExpr { op, expr } => {
                let val = self.evaluate_expr(expr, tuple)?;
                self.evaluate_unary_op(op, &val)
            }

            LogicalExpr::IsNull { expr, is_null } => {
                let val = self.evaluate_expr(expr, tuple)?;
                let is_actually_null = matches!(val, Value::Null);
                Ok(Value::Boolean(is_actually_null == *is_null))
            }

            LogicalExpr::ScalarFunction { fun, args } => {
                self.evaluate_scalar_function(fun, args, tuple)
            }

            _ => Err(Error::query_execution(format!(
                "Expression not supported in RLS: {:?}",
                expr
            ))),
        }
    }

    /// Evaluate a binary operation
    fn evaluate_binary_op(&self, left: &Value, op: &BinaryOperator, right: &Value) -> Result<Value> {
        match op {
            BinaryOperator::Eq => Ok(Value::Boolean(left == right)),
            BinaryOperator::NotEq => Ok(Value::Boolean(left != right)),

            BinaryOperator::Lt => match (left, right) {
                (Value::Int8(l), Value::Int8(r)) => Ok(Value::Boolean(l < r)),
                (Value::Int4(l), Value::Int4(r)) => Ok(Value::Boolean(l < r)),
                (Value::Int2(l), Value::Int2(r)) => Ok(Value::Boolean(l < r)),
                (Value::Float8(l), Value::Float8(r)) => Ok(Value::Boolean(l < r)),
                (Value::Float4(l), Value::Float4(r)) => Ok(Value::Boolean(l < r)),
                (Value::String(l), Value::String(r)) => Ok(Value::Boolean(l < r)),
                _ => Err(Error::query_execution(format!("Cannot compare {:?} < {:?}", left, right))),
            },

            BinaryOperator::LtEq => match (left, right) {
                (Value::Int8(l), Value::Int8(r)) => Ok(Value::Boolean(l <= r)),
                (Value::Int4(l), Value::Int4(r)) => Ok(Value::Boolean(l <= r)),
                (Value::Int2(l), Value::Int2(r)) => Ok(Value::Boolean(l <= r)),
                (Value::Float8(l), Value::Float8(r)) => Ok(Value::Boolean(l <= r)),
                (Value::Float4(l), Value::Float4(r)) => Ok(Value::Boolean(l <= r)),
                (Value::String(l), Value::String(r)) => Ok(Value::Boolean(l <= r)),
                _ => Err(Error::query_execution(format!("Cannot compare {:?} <= {:?}", left, right))),
            },

            BinaryOperator::Gt => match (left, right) {
                (Value::Int8(l), Value::Int8(r)) => Ok(Value::Boolean(l > r)),
                (Value::Int4(l), Value::Int4(r)) => Ok(Value::Boolean(l > r)),
                (Value::Int2(l), Value::Int2(r)) => Ok(Value::Boolean(l > r)),
                (Value::Float8(l), Value::Float8(r)) => Ok(Value::Boolean(l > r)),
                (Value::Float4(l), Value::Float4(r)) => Ok(Value::Boolean(l > r)),
                (Value::String(l), Value::String(r)) => Ok(Value::Boolean(l > r)),
                _ => Err(Error::query_execution(format!("Cannot compare {:?} > {:?}", left, right))),
            },

            BinaryOperator::GtEq => match (left, right) {
                (Value::Int8(l), Value::Int8(r)) => Ok(Value::Boolean(l >= r)),
                (Value::Int4(l), Value::Int4(r)) => Ok(Value::Boolean(l >= r)),
                (Value::Int2(l), Value::Int2(r)) => Ok(Value::Boolean(l >= r)),
                (Value::Float8(l), Value::Float8(r)) => Ok(Value::Boolean(l >= r)),
                (Value::Float4(l), Value::Float4(r)) => Ok(Value::Boolean(l >= r)),
                (Value::String(l), Value::String(r)) => Ok(Value::Boolean(l >= r)),
                _ => Err(Error::query_execution(format!("Cannot compare {:?} >= {:?}", left, right))),
            },

            BinaryOperator::And => Self::three_valued_and(left, right),
            BinaryOperator::Or => Self::three_valued_or(left, right),

            _ => Err(Error::query_execution(format!(
                "Operator {:?} not supported in RLS",
                op
            ))),
        }
    }

    /// Evaluate a unary operation
    fn evaluate_unary_op(&self, op: &crate::sql::UnaryOperator, val: &Value) -> Result<Value> {
        match op {
            crate::sql::UnaryOperator::Not => {
                let b = self.value_to_bool(val)?;
                Ok(Value::Boolean(!b))
            }
            crate::sql::UnaryOperator::Minus => match val {
                Value::Int8(i) => i.checked_neg()
                    .map(Value::Int8)
                    .ok_or_else(|| Error::query_execution("integer overflow: BIGINT negation")),
                Value::Int4(i) => i.checked_neg()
                    .map(Value::Int4)
                    .ok_or_else(|| Error::query_execution("integer overflow: INT negation")),
                Value::Int2(i) => i.checked_neg()
                    .map(Value::Int2)
                    .ok_or_else(|| Error::query_execution("integer overflow: SMALLINT negation")),
                Value::Float8(f) => Ok(Value::Float8(-f)),
                Value::Float4(f) => Ok(Value::Float4(-f)),
                _ => Err(Error::query_execution(format!("Cannot negate {:?}", val))),
            },
            crate::sql::UnaryOperator::Plus => Ok(val.clone()),
        }
    }

    /// Convert a value to boolean
    fn value_to_bool(&self, val: &Value) -> Result<bool> {
        match val {
            Value::Boolean(b) => Ok(*b),
            _ => Err(Error::query_execution(format!(
                "Expected boolean value, got {:?}",
                val
            ))),
        }
    }

    /// Convert a value to `Option<bool>` for SQL three-valued logic.
    fn to_tri_bool(value: &Value) -> Result<Option<bool>> {
        match value {
            Value::Boolean(b) => Ok(Some(*b)),
            Value::Null => Ok(None),
            _ => Err(Error::query_execution(format!(
                "Cannot convert {:?} to boolean", value
            ))),
        }
    }

    /// SQL three-valued AND on two already-evaluated values.
    fn three_valued_and(left: &Value, right: &Value) -> Result<Value> {
        let l = Self::to_tri_bool(left)?;
        let r = Self::to_tri_bool(right)?;
        match (l, r) {
            (Some(false), _) | (_, Some(false)) => Ok(Value::Boolean(false)),
            (Some(true), Some(true)) => Ok(Value::Boolean(true)),
            _ => Ok(Value::Null),
        }
    }

    /// SQL three-valued OR on two already-evaluated values.
    fn three_valued_or(left: &Value, right: &Value) -> Result<Value> {
        let l = Self::to_tri_bool(left)?;
        let r = Self::to_tri_bool(right)?;
        match (l, r) {
            (Some(true), _) | (_, Some(true)) => Ok(Value::Boolean(true)),
            (Some(false), Some(false)) => Ok(Value::Boolean(false)),
            _ => Ok(Value::Null),
        }
    }

    /// Short-circuit AND evaluation with SQL three-valued NULL logic.
    fn evaluate_and_short_circuit(
        &self,
        left: &LogicalExpr,
        right: &LogicalExpr,
        tuple: &Tuple,
    ) -> Result<Value> {
        let left_val = self.evaluate_expr(left, tuple)?;
        match &left_val {
            Value::Boolean(false) => Ok(Value::Boolean(false)),
            Value::Boolean(true) => {
                let right_val = self.evaluate_expr(right, tuple)?;
                match &right_val {
                    Value::Boolean(b) => Ok(Value::Boolean(*b)),
                    Value::Null => Ok(Value::Null),
                    _ => Err(Error::query_execution(format!(
                        "Cannot convert {:?} to boolean", right_val
                    ))),
                }
            }
            Value::Null => {
                let right_val = self.evaluate_expr(right, tuple)?;
                match &right_val {
                    Value::Boolean(false) => Ok(Value::Boolean(false)),
                    Value::Boolean(true) | Value::Null => Ok(Value::Null),
                    _ => Err(Error::query_execution(format!(
                        "Cannot convert {:?} to boolean", right_val
                    ))),
                }
            }
            _ => Err(Error::query_execution(format!(
                "Cannot convert {:?} to boolean", left_val
            ))),
        }
    }

    /// Short-circuit OR evaluation with SQL three-valued NULL logic.
    fn evaluate_or_short_circuit(
        &self,
        left: &LogicalExpr,
        right: &LogicalExpr,
        tuple: &Tuple,
    ) -> Result<Value> {
        let left_val = self.evaluate_expr(left, tuple)?;
        match &left_val {
            Value::Boolean(true) => Ok(Value::Boolean(true)),
            Value::Boolean(false) => {
                let right_val = self.evaluate_expr(right, tuple)?;
                match &right_val {
                    Value::Boolean(b) => Ok(Value::Boolean(*b)),
                    Value::Null => Ok(Value::Null),
                    _ => Err(Error::query_execution(format!(
                        "Cannot convert {:?} to boolean", right_val
                    ))),
                }
            }
            Value::Null => {
                let right_val = self.evaluate_expr(right, tuple)?;
                match &right_val {
                    Value::Boolean(true) => Ok(Value::Boolean(true)),
                    Value::Boolean(false) | Value::Null => Ok(Value::Null),
                    _ => Err(Error::query_execution(format!(
                        "Cannot convert {:?} to boolean", right_val
                    ))),
                }
            }
            _ => Err(Error::query_execution(format!(
                "Cannot convert {:?} to boolean", left_val
            ))),
        }
    }

    /// Evaluate a scalar function
    fn evaluate_scalar_function(&self, fun: &str, args: &[LogicalExpr], tuple: &Tuple) -> Result<Value> {
        match fun.to_lowercase().as_str() {
            "current_tenant" => {
                // Return the current tenant ID from context
                if let Some(ref context) = self.tenant_context {
                    Ok(Value::String(context.tenant_id.to_string()))
                } else {
                    Err(Error::query_execution("current_tenant() called without tenant context"))
                }
            }

            "current_setting" => {
                // current_setting('var_name')
                if args.len() != 1 {
                    return Err(Error::query_execution("current_setting() requires exactly 1 argument"));
                }

                // Evaluate the argument to get the setting name
                let setting_name_val = self.evaluate_expr(args.first().ok_or_else(|| Error::query_execution("current_setting() requires exactly 1 argument"))?, tuple)?;
                let setting_name = match setting_name_val {
                    Value::String(s) => s,
                    _ => return Err(Error::query_execution("current_setting() argument must be a string")),
                };

                // For now, we only support tenant-specific settings
                match setting_name.as_str() {
                    "app.current_tenant" => {
                        if let Some(ref context) = self.tenant_context {
                            Ok(Value::String(context.tenant_id.to_string()))
                        } else {
                            Ok(Value::Null)
                        }
                    }
                    "app.current_user" => {
                        if let Some(ref context) = self.tenant_context {
                            Ok(Value::String(context.user_id.clone()))
                        } else {
                            Ok(Value::Null)
                        }
                    }
                    _ => {
                        // Unknown setting
                        Ok(Value::Null)
                    }
                }
            }

            _ => Err(Error::query_execution(format!(
                "Function '{}' not supported in RLS expressions",
                fun
            ))),
        }
    }
}

/// Parse and evaluate an RLS expression in one call
///
/// # Arguments
///
/// * `expr_str` - The RLS expression string
/// * `tuple` - The tuple to evaluate against
/// * `schema` - The schema of the table
/// * `tenant_context` - The current tenant context
///
/// # Returns
///
/// `true` if the tuple satisfies the RLS policy, `false` otherwise
pub fn evaluate_rls_expression(
    expr_str: &str,
    tuple: &Tuple,
    schema: Arc<Schema>,
    tenant_context: Option<TenantContext>,
) -> Result<bool> {
    let evaluator = RLSExpressionEvaluator::new(schema, tenant_context);
    let expr = evaluator.parse(expr_str)?;
    evaluator.evaluate(&expr, tuple)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Column, DataType};
    use crate::tenant::IsolationMode;
    use uuid::Uuid;

    fn create_test_schema() -> Arc<Schema> {
        Arc::new(Schema::new(vec![
            Column::new("id".to_string(), DataType::Int4),
            Column::new("tenant_id".to_string(), DataType::Text),
            Column::new("name".to_string(), DataType::Text),
        ]))
    }

    fn create_test_context() -> TenantContext {
        TenantContext {
            tenant_id: Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap(),
            user_id: "user1".to_string(),
            roles: vec!["user".to_string()],
            isolation_mode: IsolationMode::SharedSchema,
        }
    }

    #[test]
    fn test_parse_simple_equality() {
        let schema = create_test_schema();
        let context = create_test_context();
        let evaluator = RLSExpressionEvaluator::new(schema, Some(context));

        let expr = evaluator.parse("tenant_id = '550e8400-e29b-41d4-a716-446655440000'").unwrap();

        match expr {
            LogicalExpr::BinaryExpr { op: BinaryOperator::Eq, .. } => {},
            _ => panic!("Expected BinaryExpr with Eq operator"),
        }
    }

    #[test]
    fn test_evaluate_tenant_match() {
        let schema = create_test_schema();
        let context = create_test_context();
        let evaluator = RLSExpressionEvaluator::new(schema, Some(context));

        let tuple = Tuple::new(vec![
            Value::Int8(1),
            Value::String("550e8400-e29b-41d4-a716-446655440000".to_string()),
            Value::String("Test".to_string()),
        ]);

        let expr = evaluator.parse("tenant_id = '550e8400-e29b-41d4-a716-446655440000'").unwrap();
        let result = evaluator.evaluate(&expr, &tuple).unwrap();

        assert!(result);
    }

    #[test]
    fn test_evaluate_tenant_mismatch() {
        let schema = create_test_schema();
        let context = create_test_context();
        let evaluator = RLSExpressionEvaluator::new(schema, Some(context));

        let tuple = Tuple::new(vec![
            Value::Int8(1),
            Value::String("different-tenant-id".to_string()),
            Value::String("Test".to_string()),
        ]);

        let expr = evaluator.parse("tenant_id = '550e8400-e29b-41d4-a716-446655440000'").unwrap();
        let result = evaluator.evaluate(&expr, &tuple).unwrap();

        assert!(!result);
    }

    #[test]
    fn test_current_tenant_function() {
        let schema = create_test_schema();
        let context = create_test_context();
        let evaluator = RLSExpressionEvaluator::new(schema, Some(context.clone()));

        let tuple = Tuple::new(vec![
            Value::Int8(1),
            Value::String(context.tenant_id.to_string()),
            Value::String("Test".to_string()),
        ]);

        let expr = evaluator.parse("tenant_id = current_tenant()").unwrap();
        let result = evaluator.evaluate(&expr, &tuple).unwrap();

        assert!(result);
    }

    #[test]
    fn test_complex_expression() {
        let schema = create_test_schema();
        let context = create_test_context();
        let evaluator = RLSExpressionEvaluator::new(schema, Some(context.clone()));

        let tuple = Tuple::new(vec![
            Value::Int8(5),
            Value::String(context.tenant_id.to_string()),
            Value::String("Test".to_string()),
        ]);

        let expr = evaluator.parse("tenant_id = current_tenant() AND id > 3").unwrap();
        let result = evaluator.evaluate(&expr, &tuple).unwrap();

        assert!(result);
    }
}