ruvector-postgres 2.0.5

High-performance PostgreSQL vector database extension v2 - pgvector drop-in replacement with 230+ SQL functions, SIMD acceleration, Flash Attention, GNN layers, hybrid search, multi-tenancy, self-healing, and self-learning capabilities
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
// SPARQL Abstract Syntax Tree (AST) types
//
// Provides type-safe representation of SPARQL 1.1 queries following
// the W3C specification: https://www.w3.org/TR/sparql11-query/

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Complete SPARQL query or update
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SparqlQuery {
    /// Base IRI for relative IRI resolution
    pub base: Option<Iri>,
    /// PREFIX declarations
    pub prefixes: HashMap<String, Iri>,
    /// The query form (SELECT, CONSTRUCT, ASK, DESCRIBE) or update operation
    pub body: QueryBody,
}

impl SparqlQuery {
    pub fn new(body: QueryBody) -> Self {
        Self {
            base: None,
            prefixes: HashMap::new(),
            body,
        }
    }

    pub fn with_base(mut self, base: Iri) -> Self {
        self.base = Some(base);
        self
    }

    pub fn with_prefix(mut self, prefix: impl Into<String>, iri: Iri) -> Self {
        self.prefixes.insert(prefix.into(), iri);
        self
    }
}

impl Default for SparqlQuery {
    fn default() -> Self {
        Self::new(QueryBody::Select(SelectQuery::default()))
    }
}

/// Query body - either a query form or update operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum QueryBody {
    Select(SelectQuery),
    Construct(ConstructQuery),
    Ask(AskQuery),
    Describe(DescribeQuery),
    Update(Vec<UpdateOperation>),
}

/// Query form type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum QueryForm {
    Select,
    Construct,
    Ask,
    Describe,
}

/// SELECT query
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SelectQuery {
    /// Result variables or expressions
    pub projection: Projection,
    /// Dataset clauses (FROM, FROM NAMED)
    pub dataset: Vec<DatasetClause>,
    /// WHERE clause graph pattern
    pub where_clause: GraphPattern,
    /// Solution modifiers
    pub modifier: SolutionModifier,
    /// VALUES clause for inline data
    pub values: Option<ValuesClause>,
}

impl Default for SelectQuery {
    fn default() -> Self {
        Self {
            projection: Projection::All,
            dataset: Vec::new(),
            where_clause: GraphPattern::Empty,
            modifier: SolutionModifier::default(),
            values: None,
        }
    }
}

/// Projection in SELECT clause
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Projection {
    /// SELECT * - all variables
    All,
    /// SELECT DISTINCT ...
    Distinct(Vec<ProjectionVar>),
    /// SELECT REDUCED ...
    Reduced(Vec<ProjectionVar>),
    /// SELECT var1 var2 ...
    Variables(Vec<ProjectionVar>),
}

/// Variable or expression in projection
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectionVar {
    pub expression: Expression,
    pub alias: Option<String>,
}

impl ProjectionVar {
    pub fn variable(name: impl Into<String>) -> Self {
        Self {
            expression: Expression::Variable(name.into()),
            alias: None,
        }
    }

    pub fn expr_as(expr: Expression, alias: impl Into<String>) -> Self {
        Self {
            expression: expr,
            alias: Some(alias.into()),
        }
    }
}

/// CONSTRUCT query
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConstructQuery {
    /// Template for constructing triples
    pub template: Vec<TriplePattern>,
    /// Dataset clauses
    pub dataset: Vec<DatasetClause>,
    /// WHERE clause
    pub where_clause: GraphPattern,
    /// Solution modifiers
    pub modifier: SolutionModifier,
}

impl Default for ConstructQuery {
    fn default() -> Self {
        Self {
            template: Vec::new(),
            dataset: Vec::new(),
            where_clause: GraphPattern::Empty,
            modifier: SolutionModifier::default(),
        }
    }
}

/// ASK query
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AskQuery {
    /// Dataset clauses
    pub dataset: Vec<DatasetClause>,
    /// WHERE clause
    pub where_clause: GraphPattern,
}

impl Default for AskQuery {
    fn default() -> Self {
        Self {
            dataset: Vec::new(),
            where_clause: GraphPattern::Empty,
        }
    }
}

/// DESCRIBE query
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DescribeQuery {
    /// Resources to describe
    pub resources: Vec<VarOrIri>,
    /// Dataset clauses
    pub dataset: Vec<DatasetClause>,
    /// Optional WHERE clause
    pub where_clause: Option<GraphPattern>,
}

impl Default for DescribeQuery {
    fn default() -> Self {
        Self {
            resources: Vec::new(),
            dataset: Vec::new(),
            where_clause: None,
        }
    }
}

/// Dataset clause (FROM / FROM NAMED)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatasetClause {
    pub iri: Iri,
    pub named: bool,
}

/// VALUES clause for inline data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValuesClause {
    pub variables: Vec<String>,
    pub bindings: Vec<Vec<Option<RdfTerm>>>,
}

/// Graph pattern - the WHERE clause body
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum GraphPattern {
    /// Empty pattern
    Empty,
    /// Basic Graph Pattern - set of triple patterns
    Bgp(Vec<TriplePattern>),
    /// Join of patterns (implicit AND)
    Join(Box<GraphPattern>, Box<GraphPattern>),
    /// Left outer join (OPTIONAL)
    LeftJoin(Box<GraphPattern>, Box<GraphPattern>, Option<Expression>),
    /// Union of patterns (UNION)
    Union(Box<GraphPattern>, Box<GraphPattern>),
    /// Filter (FILTER)
    Filter(Box<GraphPattern>, Expression),
    /// Named graph (GRAPH)
    Graph(VarOrIri, Box<GraphPattern>),
    /// Service (FEDERATED query)
    Service(Iri, Box<GraphPattern>, bool),
    /// MINUS pattern
    Minus(Box<GraphPattern>, Box<GraphPattern>),
    /// EXISTS or NOT EXISTS
    Exists(Box<GraphPattern>, bool),
    /// BIND assignment
    Bind(Expression, String, Box<GraphPattern>),
    /// GROUP BY aggregation
    Group(
        Box<GraphPattern>,
        Vec<GroupCondition>,
        Vec<(Aggregate, String)>,
    ),
    /// Subquery
    SubSelect(Box<SelectQuery>),
    /// VALUES inline data
    Values(ValuesClause),
}

/// Triple pattern
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TriplePattern {
    pub subject: TermOrVariable,
    pub predicate: PropertyPath,
    pub object: TermOrVariable,
}

impl TriplePattern {
    pub fn new(subject: TermOrVariable, predicate: PropertyPath, object: TermOrVariable) -> Self {
        Self {
            subject,
            predicate,
            object,
        }
    }

    /// Simple triple pattern with IRI predicate
    pub fn simple(subject: TermOrVariable, predicate: Iri, object: TermOrVariable) -> Self {
        Self {
            subject,
            predicate: PropertyPath::Iri(predicate),
            object,
        }
    }
}

/// Term or variable in triple pattern
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TermOrVariable {
    Term(RdfTerm),
    Variable(String),
    BlankNode(String),
}

impl TermOrVariable {
    pub fn var(name: impl Into<String>) -> Self {
        Self::Variable(name.into())
    }

    pub fn iri(iri: Iri) -> Self {
        Self::Term(RdfTerm::Iri(iri))
    }

    pub fn literal(value: impl Into<String>) -> Self {
        Self::Term(RdfTerm::Literal(Literal::simple(value)))
    }

    pub fn blank(id: impl Into<String>) -> Self {
        Self::BlankNode(id.into())
    }
}

/// Variable or IRI
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum VarOrIri {
    Variable(String),
    Iri(Iri),
}

/// Property path expression
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PropertyPath {
    /// Simple IRI predicate
    Iri(Iri),
    /// Variable predicate
    Variable(String),
    /// Inverse path (^path)
    Inverse(Box<PropertyPath>),
    /// Sequence path (path1/path2)
    Sequence(Box<PropertyPath>, Box<PropertyPath>),
    /// Alternative path (path1|path2)
    Alternative(Box<PropertyPath>, Box<PropertyPath>),
    /// Zero or more (*path)
    ZeroOrMore(Box<PropertyPath>),
    /// One or more (+path)
    OneOrMore(Box<PropertyPath>),
    /// Zero or one (?path)
    ZeroOrOne(Box<PropertyPath>),
    /// Negated property set (!(path1|path2))
    NegatedPropertySet(Vec<Iri>),
    /// Fixed length path {n}
    FixedLength(Box<PropertyPath>, usize),
    /// Range length path {n,m}
    RangeLength(Box<PropertyPath>, usize, Option<usize>),
}

/// RDF term
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum RdfTerm {
    /// IRI reference
    Iri(Iri),
    /// Literal value
    Literal(Literal),
    /// Blank node
    BlankNode(String),
}

impl RdfTerm {
    pub fn iri(value: impl Into<String>) -> Self {
        Self::Iri(Iri::new(value))
    }

    pub fn literal(value: impl Into<String>) -> Self {
        Self::Literal(Literal::simple(value))
    }

    pub fn typed_literal(value: impl Into<String>, datatype: Iri) -> Self {
        Self::Literal(Literal::typed(value, datatype))
    }

    pub fn lang_literal(value: impl Into<String>, lang: impl Into<String>) -> Self {
        Self::Literal(Literal::language(value, lang))
    }

    pub fn blank(id: impl Into<String>) -> Self {
        Self::BlankNode(id.into())
    }

    /// Check if this is an IRI
    pub fn is_iri(&self) -> bool {
        matches!(self, Self::Iri(_))
    }

    /// Check if this is a literal
    pub fn is_literal(&self) -> bool {
        matches!(self, Self::Literal(_))
    }

    /// Check if this is a blank node
    pub fn is_blank_node(&self) -> bool {
        matches!(self, Self::BlankNode(_))
    }
}

/// IRI (Internationalized Resource Identifier)
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Iri(pub String);

impl Iri {
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Common RDF namespace IRIs
    pub fn rdf_type() -> Self {
        Self::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")
    }

    pub fn rdfs_label() -> Self {
        Self::new("http://www.w3.org/2000/01/rdf-schema#label")
    }

    pub fn rdfs_comment() -> Self {
        Self::new("http://www.w3.org/2000/01/rdf-schema#comment")
    }

    pub fn xsd_string() -> Self {
        Self::new("http://www.w3.org/2001/XMLSchema#string")
    }

    pub fn xsd_integer() -> Self {
        Self::new("http://www.w3.org/2001/XMLSchema#integer")
    }

    pub fn xsd_decimal() -> Self {
        Self::new("http://www.w3.org/2001/XMLSchema#decimal")
    }

    pub fn xsd_double() -> Self {
        Self::new("http://www.w3.org/2001/XMLSchema#double")
    }

    pub fn xsd_boolean() -> Self {
        Self::new("http://www.w3.org/2001/XMLSchema#boolean")
    }

    pub fn xsd_date() -> Self {
        Self::new("http://www.w3.org/2001/XMLSchema#date")
    }

    pub fn xsd_datetime() -> Self {
        Self::new("http://www.w3.org/2001/XMLSchema#dateTime")
    }
}

/// RDF Literal
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Literal {
    /// Lexical form (string value)
    pub value: String,
    /// Optional language tag
    pub language: Option<String>,
    /// Datatype IRI (defaults to xsd:string)
    pub datatype: Iri,
}

impl Literal {
    /// Simple string literal
    pub fn simple(value: impl Into<String>) -> Self {
        Self {
            value: value.into(),
            language: None,
            datatype: Iri::xsd_string(),
        }
    }

    /// Typed literal
    pub fn typed(value: impl Into<String>, datatype: Iri) -> Self {
        Self {
            value: value.into(),
            language: None,
            datatype,
        }
    }

    /// Language-tagged literal
    pub fn language(value: impl Into<String>, lang: impl Into<String>) -> Self {
        Self {
            value: value.into(),
            language: Some(lang.into()),
            datatype: Iri::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"),
        }
    }

    /// Integer literal
    pub fn integer(value: i64) -> Self {
        Self::typed(value.to_string(), Iri::xsd_integer())
    }

    /// Decimal literal
    pub fn decimal(value: f64) -> Self {
        Self::typed(value.to_string(), Iri::xsd_decimal())
    }

    /// Double literal
    pub fn double(value: f64) -> Self {
        Self::typed(value.to_string(), Iri::xsd_double())
    }

    /// Boolean literal
    pub fn boolean(value: bool) -> Self {
        Self::typed(if value { "true" } else { "false" }, Iri::xsd_boolean())
    }

    /// Try to parse as integer
    pub fn as_integer(&self) -> Option<i64> {
        self.value.parse().ok()
    }

    /// Try to parse as double
    pub fn as_double(&self) -> Option<f64> {
        self.value.parse().ok()
    }

    /// Try to parse as boolean
    pub fn as_boolean(&self) -> Option<bool> {
        match self.value.as_str() {
            "true" | "1" => Some(true),
            "false" | "0" => Some(false),
            _ => None,
        }
    }
}

/// SPARQL expression
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Expression {
    /// Variable reference
    Variable(String),
    /// Constant term
    Term(RdfTerm),
    /// Binary operation
    Binary(Box<Expression>, BinaryOp, Box<Expression>),
    /// Unary operation
    Unary(UnaryOp, Box<Expression>),
    /// Function call
    Function(FunctionCall),
    /// Aggregate function
    Aggregate(Aggregate),
    /// IN expression
    In(Box<Expression>, Vec<Expression>),
    /// NOT IN expression
    NotIn(Box<Expression>, Vec<Expression>),
    /// EXISTS subquery
    Exists(Box<GraphPattern>),
    /// NOT EXISTS subquery
    NotExists(Box<GraphPattern>),
    /// Conditional (IF)
    If(Box<Expression>, Box<Expression>, Box<Expression>),
    /// COALESCE
    Coalesce(Vec<Expression>),
    /// BOUND test
    Bound(String),
    /// isIRI test
    IsIri(Box<Expression>),
    /// isBlank test
    IsBlank(Box<Expression>),
    /// isLiteral test
    IsLiteral(Box<Expression>),
    /// isNumeric test
    IsNumeric(Box<Expression>),
    /// REGEX pattern matching
    Regex(Box<Expression>, Box<Expression>, Option<Box<Expression>>),
    /// LANG function
    Lang(Box<Expression>),
    /// DATATYPE function
    Datatype(Box<Expression>),
    /// STR function
    Str(Box<Expression>),
    /// IRI constructor
    Iri(Box<Expression>),
}

impl Expression {
    pub fn var(name: impl Into<String>) -> Self {
        Self::Variable(name.into())
    }

    pub fn term(t: RdfTerm) -> Self {
        Self::Term(t)
    }

    pub fn literal(value: impl Into<String>) -> Self {
        Self::Term(RdfTerm::literal(value))
    }

    pub fn integer(value: i64) -> Self {
        Self::Term(RdfTerm::Literal(Literal::integer(value)))
    }

    pub fn binary(left: Expression, op: BinaryOp, right: Expression) -> Self {
        Self::Binary(Box::new(left), op, Box::new(right))
    }

    pub fn unary(op: UnaryOp, expr: Expression) -> Self {
        Self::Unary(op, Box::new(expr))
    }

    pub fn and(left: Expression, right: Expression) -> Self {
        Self::binary(left, BinaryOp::And, right)
    }

    pub fn or(left: Expression, right: Expression) -> Self {
        Self::binary(left, BinaryOp::Or, right)
    }

    pub fn eq(left: Expression, right: Expression) -> Self {
        Self::binary(left, BinaryOp::Eq, right)
    }

    pub fn neq(left: Expression, right: Expression) -> Self {
        Self::binary(left, BinaryOp::NotEq, right)
    }

    pub fn lt(left: Expression, right: Expression) -> Self {
        Self::binary(left, BinaryOp::Lt, right)
    }

    pub fn gt(left: Expression, right: Expression) -> Self {
        Self::binary(left, BinaryOp::Gt, right)
    }
}

/// Binary operators
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BinaryOp {
    // Logical
    And,
    Or,
    // Comparison
    Eq,
    NotEq,
    Lt,
    LtEq,
    Gt,
    GtEq,
    // Arithmetic
    Add,
    Sub,
    Mul,
    Div,
    // String
    SameTerm,
    LangMatches,
}

/// Unary operators
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum UnaryOp {
    Not,
    Plus,
    Minus,
}

/// Function call
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FunctionCall {
    pub name: String,
    pub args: Vec<Expression>,
}

impl FunctionCall {
    pub fn new(name: impl Into<String>, args: Vec<Expression>) -> Self {
        Self {
            name: name.into(),
            args,
        }
    }
}

/// Aggregate function
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Aggregate {
    Count {
        expr: Option<Box<Expression>>,
        distinct: bool,
    },
    Sum {
        expr: Box<Expression>,
        distinct: bool,
    },
    Avg {
        expr: Box<Expression>,
        distinct: bool,
    },
    Min {
        expr: Box<Expression>,
    },
    Max {
        expr: Box<Expression>,
    },
    GroupConcat {
        expr: Box<Expression>,
        separator: Option<String>,
        distinct: bool,
    },
    Sample {
        expr: Box<Expression>,
    },
}

/// Filter expression
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Filter {
    pub expression: Expression,
}

impl Filter {
    pub fn new(expression: Expression) -> Self {
        Self { expression }
    }
}

/// Solution modifier
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SolutionModifier {
    pub order_by: Vec<OrderCondition>,
    pub limit: Option<usize>,
    pub offset: Option<usize>,
    pub having: Option<Expression>,
}

impl SolutionModifier {
    pub fn with_limit(mut self, limit: usize) -> Self {
        self.limit = Some(limit);
        self
    }

    pub fn with_offset(mut self, offset: usize) -> Self {
        self.offset = Some(offset);
        self
    }

    pub fn with_order(mut self, conditions: Vec<OrderCondition>) -> Self {
        self.order_by = conditions;
        self
    }

    pub fn with_having(mut self, expr: Expression) -> Self {
        self.having = Some(expr);
        self
    }
}

/// ORDER BY condition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrderCondition {
    pub expression: Expression,
    pub ascending: bool,
}

impl OrderCondition {
    pub fn asc(expr: Expression) -> Self {
        Self {
            expression: expr,
            ascending: true,
        }
    }

    pub fn desc(expr: Expression) -> Self {
        Self {
            expression: expr,
            ascending: false,
        }
    }
}

/// GROUP BY condition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum GroupCondition {
    Variable(String),
    Expression(Expression, Option<String>),
}

// ============================================================================
// SPARQL Update Operations
// ============================================================================

/// SPARQL Update operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum UpdateOperation {
    /// INSERT DATA { triples }
    InsertData(InsertData),
    /// DELETE DATA { triples }
    DeleteData(DeleteData),
    /// DELETE { pattern } INSERT { pattern } WHERE { pattern }
    Modify(Modify),
    /// LOAD <iri> INTO GRAPH <iri>
    Load {
        source: Iri,
        destination: Option<Iri>,
        silent: bool,
    },
    /// CLEAR GRAPH <iri>
    Clear { target: GraphTarget, silent: bool },
    /// CREATE GRAPH <iri>
    Create { graph: Iri, silent: bool },
    /// DROP GRAPH <iri>
    Drop { target: GraphTarget, silent: bool },
    /// COPY source TO destination
    Copy {
        source: GraphTarget,
        destination: GraphTarget,
        silent: bool,
    },
    /// MOVE source TO destination
    Move {
        source: GraphTarget,
        destination: GraphTarget,
        silent: bool,
    },
    /// ADD source TO destination
    Add {
        source: GraphTarget,
        destination: GraphTarget,
        silent: bool,
    },
}

/// INSERT DATA operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InsertData {
    pub quads: Vec<Quad>,
}

/// DELETE DATA operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeleteData {
    pub quads: Vec<Quad>,
}

/// DELETE/INSERT with WHERE
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Modify {
    pub with_graph: Option<Iri>,
    pub delete_pattern: Option<Vec<QuadPattern>>,
    pub insert_pattern: Option<Vec<QuadPattern>>,
    pub using: Vec<DatasetClause>,
    pub where_pattern: GraphPattern,
}

/// Quad (triple with optional graph)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Quad {
    pub subject: RdfTerm,
    pub predicate: Iri,
    pub object: RdfTerm,
    pub graph: Option<Iri>,
}

/// Quad pattern (for DELETE/INSERT templates)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QuadPattern {
    pub subject: TermOrVariable,
    pub predicate: VarOrIri,
    pub object: TermOrVariable,
    pub graph: Option<VarOrIri>,
}

/// Graph target for management operations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum GraphTarget {
    Default,
    Named(Iri),
    All,
    AllNamed,
}

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

    #[test]
    fn test_rdf_term_creation() {
        let iri = RdfTerm::iri("http://example.org/resource");
        assert!(iri.is_iri());

        let lit = RdfTerm::literal("hello");
        assert!(lit.is_literal());

        let blank = RdfTerm::blank("b0");
        assert!(blank.is_blank_node());
    }

    #[test]
    fn test_literal_parsing() {
        let int_lit = Literal::integer(42);
        assert_eq!(int_lit.as_integer(), Some(42));

        let double_lit = Literal::double(3.14);
        assert!((double_lit.as_double().unwrap() - 3.14).abs() < 0.001);

        let bool_lit = Literal::boolean(true);
        assert_eq!(bool_lit.as_boolean(), Some(true));
    }

    #[test]
    fn test_expression_builder() {
        let expr = Expression::and(
            Expression::eq(Expression::var("x"), Expression::integer(10)),
            Expression::gt(Expression::var("y"), Expression::integer(5)),
        );

        match expr {
            Expression::Binary(_, BinaryOp::And, _) => (),
            _ => panic!("Expected AND expression"),
        }
    }

    #[test]
    fn test_triple_pattern() {
        let pattern = TriplePattern::simple(
            TermOrVariable::var("s"),
            Iri::rdf_type(),
            TermOrVariable::iri(Iri::new("http://example.org/Person")),
        );

        assert!(matches!(pattern.subject, TermOrVariable::Variable(_)));
        assert!(matches!(pattern.predicate, PropertyPath::Iri(_)));
    }
}