audb 0.1.11

AuDB - Compile-time database application framework with gold files
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
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
//! Parser implementation for gold files
//!
//! Converts token stream from lexer into an Abstract Syntax Tree (AST).

use crate::error::{Error, Result};
use crate::parser::ast::{
    Block, ConfigBlock, CustomBlock, DataBlock, EmbeddingAnnotation, EndpointBlock, GoldFile,
    Parameter, QueryBlock, SchemaBlock, SchemaField, Value,
};
use crate::parser::lexer::{LocatedToken, Token, WinnowLexer};
use std::path::{Path, PathBuf};

/// Parser for gold files
pub struct GoldParser;

impl GoldParser {
    /// Parse a gold file from a path
    pub fn parse_file(path: &Path) -> Result<GoldFile> {
        let content = std::fs::read_to_string(path).map_err(Error::Io)?;
        Self::parse_str(&content, path)
    }

    /// Parse gold file content from a string
    pub fn parse_str(content: &str, path: &Path) -> Result<GoldFile> {
        // Tokenize first using winnow lexer
        let lexer = WinnowLexer::new(path);
        let tokens = lexer.tokenize(content)?;

        // Parse tokens into AST
        let mut parser = Parser::new(tokens, path);
        parser.parse()
    }
}

/// Internal parser state
struct Parser {
    /// Token stream
    tokens: Vec<LocatedToken>,

    /// Current position in token stream
    position: usize,

    /// File path (for error messages)
    path: PathBuf,
}

impl Parser {
    /// Create a new parser from tokens
    fn new(tokens: Vec<LocatedToken>, path: &Path) -> Self {
        Self {
            tokens,
            position: 0,
            path: path.to_path_buf(),
        }
    }

    /// Parse the token stream into a GoldFile
    fn parse(&mut self) -> Result<GoldFile> {
        let mut file = GoldFile::new();

        while !self.is_at_end() {
            // Skip comments and newlines at top level
            if self.skip_trivia() {
                continue;
            }

            if self.is_at_end() {
                break;
            }

            // Expect @ directive
            if !self.check(&Token::At) {
                return self.error("Expected '@' directive");
            }

            let block = self.parse_block()?;
            file.add_block(block);
        }

        Ok(file)
    }

    /// Parse a block (@schema, @query, @config, etc.)
    fn parse_block(&mut self) -> Result<Block> {
        self.consume(&Token::At, "Expected '@'")?;

        let directive = self.expect_identifier("Expected directive name")?;

        match directive.as_str() {
            "crud" => {
                // @crud is an annotation for @schema, parse the next @schema block with crud=true
                self.skip_trivia();
                self.consume(&Token::At, "Expected '@schema' after '@crud'")?;
                let next_directive = self.expect_identifier("Expected 'schema' after '@crud'")?;
                if next_directive != "schema" {
                    return self.error("@crud annotation can only be used with @schema");
                }
                self.parse_schema_block_with_crud(true)
            }
            "schema" => self.parse_schema_block_with_crud(false),
            "query" => self.parse_query_block(),
            "config" => self.parse_config_block(),
            "endpoint" => self.parse_endpoint_block(),
            "data" => self.parse_data_block(),
            _ => self.parse_custom_block(directive),
        }
    }

    /// Parse @schema block
    fn parse_schema_block_with_crud(&mut self, crud: bool) -> Result<Block> {
        let name = self.expect_identifier("Expected schema name")?;

        self.consume(&Token::LBrace, "Expected '{' after schema name")?;

        let mut fields = Vec::new();
        let mut format = None;
        let mut content = None;

        while !self.check(&Token::RBrace) && !self.is_at_end() {
            self.skip_trivia();

            if self.check(&Token::RBrace) {
                break;
            }

            // Check for format attribute
            if self.match_identifier("format") {
                self.consume(&Token::Equals, "Expected '=' after 'format'")?;
                format = Some(self.expect_string("Expected format string")?);
                continue;
            }

            // Check for delimiter (embedded content)
            if self.check(&Token::RawContent(String::new())) {
                content = Some(self.parse_delimited_content()?);
                continue;
            }

            // Check for @embedding annotation
            let embedding_annotation = if self.check(&Token::At) {
                self.advance(); // consume @
                if self.match_identifier("embedding") {
                    let annotation = Some(self.parse_embedding_annotation()?);
                    // Skip trivia after annotation before parsing field
                    self.skip_trivia();
                    annotation
                } else {
                    // Unknown annotation, skip it
                    self.skip_until_newline();
                    None
                }
            } else {
                None
            };

            // Parse field
            let field_name = self.expect_identifier("Expected field name")?;
            self.consume(&Token::Colon, "Expected ':' after field name")?;
            let field_type = self.expect_identifier("Expected field type")?;

            fields.push(SchemaField {
                name: field_name,
                field_type,
                nullable: false,
                default: None,
                embedding_annotation,
            });
        }

        self.consume(&Token::RBrace, "Expected '}' to close schema block")?;

        Ok(Block::Schema(SchemaBlock {
            name,
            format,
            fields,
            content,
            crud,
        }))
    }

    /// Parse @query block
    fn parse_query_block(&mut self) -> Result<Block> {
        let name = self.expect_identifier("Expected query name")?;

        // Parse parameters
        let params = self.parse_parameters()?;

        // Parse return type
        let return_type = if self.check(&Token::Arrow) {
            self.advance();
            self.expect_type("Expected return type after '->'")?
        } else {
            String::new()
        };

        self.consume(&Token::LBrace, "Expected '{' after query signature")?;

        let mut language = "hyperql".to_string();
        let mut source = String::new();

        while !self.check(&Token::RBrace) && !self.is_at_end() {
            self.skip_trivia();

            if self.check(&Token::RBrace) {
                break;
            }

            // Check for language attribute
            if self.match_identifier("language") {
                self.consume(&Token::Equals, "Expected '=' after 'language'")?;
                language = self.expect_string("Expected language string")?;
                continue;
            }

            // Check for delimiter (query source)
            if self.check(&Token::RawContent(String::new())) {
                source = self.parse_delimited_content()?;
                continue;
            }

            // Skip any other tokens
            self.advance();
        }

        self.consume(&Token::RBrace, "Expected '}' to close query block")?;

        Ok(Block::Query(QueryBlock {
            name,
            params,
            return_type,
            language,
            source,
        }))
    }

    /// Parse @config block
    fn parse_config_block(&mut self) -> Result<Block> {
        let name = self.expect_identifier("Expected config name")?;

        self.consume(&Token::LBrace, "Expected '{' after config name")?;

        let mut attributes = std::collections::HashMap::new();

        while !self.check(&Token::RBrace) && !self.is_at_end() {
            self.skip_trivia();

            if self.check(&Token::RBrace) {
                break;
            }

            let attr_name = self.expect_identifier("Expected attribute name")?;
            self.consume(&Token::Equals, "Expected '=' after attribute name")?;
            let value = self.parse_value()?;

            attributes.insert(attr_name, value);
        }

        self.consume(&Token::RBrace, "Expected '}' to close config block")?;

        Ok(Block::Config(ConfigBlock { name, attributes }))
    }

    /// Parse @endpoint block
    fn parse_endpoint_block(&mut self) -> Result<Block> {
        let method = self.expect_identifier("Expected HTTP method")?;
        let path = self.expect_string("Expected endpoint path")?;

        self.consume(&Token::LBrace, "Expected '{' after endpoint path")?;

        let mut query = String::new();
        let mut auth = false;
        let mut params = std::collections::HashMap::new();

        while !self.check(&Token::RBrace) && !self.is_at_end() {
            self.skip_trivia();

            if self.check(&Token::RBrace) {
                break;
            }

            let attr_name = self.expect_identifier("Expected attribute name")?;
            self.consume(&Token::Equals, "Expected '=' after attribute name")?;

            match attr_name.as_str() {
                "query" => {
                    query = self.expect_identifier("Expected query name")?;
                }
                "auth" => {
                    auth = self.expect_boolean("Expected boolean for auth")?;
                }
                _ => {
                    let value = self.parse_value()?;
                    if let Some(s) = value.as_string() {
                        params.insert(attr_name, s.to_string());
                    }
                }
            }
        }

        self.consume(&Token::RBrace, "Expected '}' to close endpoint block")?;

        Ok(Block::Endpoint(EndpointBlock {
            method,
            path,
            query,
            auth,
            params,
        }))
    }

    /// Parse @data block
    fn parse_data_block(&mut self) -> Result<Block> {
        let name = self.expect_identifier("Expected data block name")?;

        self.consume(&Token::LBrace, "Expected '{' after data block name")?;

        let mut format = "json".to_string();
        let mut content = String::new();

        while !self.check(&Token::RBrace) && !self.is_at_end() {
            self.skip_trivia();

            if self.check(&Token::RBrace) {
                break;
            }

            // Check for format attribute
            if self.match_identifier("format") {
                self.consume(&Token::Equals, "Expected '=' after 'format'")?;
                format = self.expect_string("Expected format string")?;
                continue;
            }

            // Check for delimiter (data content)
            if self.check(&Token::RawContent(String::new())) {
                content = self.parse_delimited_content()?;
                continue;
            }

            self.advance();
        }

        self.consume(&Token::RBrace, "Expected '}' to close data block")?;

        Ok(Block::Data(DataBlock {
            name,
            format,
            content,
        }))
    }

    /// Parse custom/unknown block
    fn parse_custom_block(&mut self, block_type: String) -> Result<Block> {
        let name = if self.check_identifier() {
            Some(self.expect_identifier("Expected block name")?)
        } else {
            None
        };

        self.consume(&Token::LBrace, "Expected '{' after block header")?;

        let mut attributes = std::collections::HashMap::new();
        let mut content = None;

        while !self.check(&Token::RBrace) && !self.is_at_end() {
            self.skip_trivia();

            if self.check(&Token::RBrace) {
                break;
            }

            // Check for delimiter (embedded content)
            if self.check(&Token::RawContent(String::new())) {
                content = Some(self.parse_delimited_content()?);
                continue;
            }

            // Parse attribute
            if self.check_identifier() {
                let attr_name = self.expect_identifier("Expected attribute name")?;
                self.consume(&Token::Equals, "Expected '=' after attribute name")?;
                let value = self.parse_value()?;
                attributes.insert(attr_name, value);
            } else {
                self.advance();
            }
        }

        self.consume(&Token::RBrace, "Expected '}' to close block")?;

        Ok(Block::Custom(CustomBlock {
            block_type,
            name,
            attributes,
            content,
        }))
    }

    /// Parse delimited content (between --- markers)
    fn parse_delimited_content(&mut self) -> Result<String> {
        // Winnow lexer produces RawContent token directly (no delimiter tokens)
        // Check if current token is RawContent
        if let Token::RawContent(content) = &self.current().token {
            let result = content.clone();
            self.advance();
            return Ok(result);
        }

        // If no RawContent token, content is empty
        Ok(String::new())
    }

    /// Parse function parameters
    fn parse_parameters(&mut self) -> Result<Vec<Parameter>> {
        if !self.check(&Token::LParen) {
            return Ok(Vec::new());
        }

        self.consume(&Token::LParen, "Expected '('")?;

        let mut params = Vec::new();

        while !self.check(&Token::RParen) && !self.is_at_end() {
            let name = self.expect_identifier("Expected parameter name")?;
            self.consume(&Token::Colon, "Expected ':' after parameter name")?;
            let param_type = self.expect_type("Expected parameter type")?;

            params.push(Parameter { name, param_type });

            if !self.check(&Token::RParen) {
                self.consume(&Token::Comma, "Expected ',' or ')' after parameter")?;
            }
        }

        self.consume(&Token::RParen, "Expected ')' to close parameters")?;

        Ok(params)
    }

    /// Parse @embedding annotation
    /// Format: @embedding(model="bge-base-en-v1.5", source_field="content", dimension=768)
    fn parse_embedding_annotation(&mut self) -> Result<EmbeddingAnnotation> {
        self.consume(&Token::LParen, "Expected '(' after @embedding")?;

        let mut model = None;
        let mut source_field = None;
        let mut dimension = None;
        let mut paradigm = None;

        while !self.check(&Token::RParen) && !self.is_at_end() {
            let key = self.expect_identifier("Expected embedding parameter name")?;
            self.consume(&Token::Equals, "Expected '=' after parameter name")?;

            match key.as_str() {
                "model" => {
                    model = Some(self.expect_string("Expected model string")?);
                }
                "source_field" => {
                    source_field = Some(self.expect_string("Expected source_field string")?);
                }
                "dimension" => {
                    dimension = Some(self.expect_integer("Expected dimension integer")?);
                }
                "paradigm" => {
                    paradigm = Some(self.expect_string("Expected paradigm string")?);
                }
                _ => {
                    return self.error(&format!("Unknown embedding parameter '{}'", key));
                }
            }

            if !self.check(&Token::RParen) {
                self.consume(&Token::Comma, "Expected ',' or ')' after parameter")?;
            }
        }

        self.consume(&Token::RParen, "Expected ')' to close @embedding")?;

        // Validate required fields (dimension is optional - will be queried from Tessera)
        let model = model.ok_or_else(|| Error::Parse {
            file: self.path.clone(),
            line: self.current().line,
            column: self.current().column,
            message: "@embedding requires 'model' parameter".to_string(),
        })?;

        let source_field = source_field.ok_or_else(|| Error::Parse {
            file: self.path.clone(),
            line: self.current().line,
            column: self.current().column,
            message: "@embedding requires 'source_field' parameter".to_string(),
        })?;

        Ok(EmbeddingAnnotation {
            model,
            source_field,
            dimension,
            paradigm,
        })
    }

    /// Parse a value (string, number, boolean, etc.)
    fn parse_value(&mut self) -> Result<Value> {
        match &self.current().token {
            Token::String(s) => {
                let val = Value::String(s.clone());
                self.advance();
                Ok(val)
            }
            Token::Integer(i) => {
                let val = Value::Integer(*i);
                self.advance();
                Ok(val)
            }
            Token::Float(f) => {
                let val = Value::Float(*f);
                self.advance();
                Ok(val)
            }
            Token::Boolean(b) => {
                let val = Value::Boolean(*b);
                self.advance();
                Ok(val)
            }
            _ => self.error("Expected value (string, number, or boolean)"),
        }
    }

    /// Parse a type (can include generics like Vec<T>)
    fn expect_type(&mut self, message: &str) -> Result<String> {
        let mut type_str = self.expect_identifier(message)?;

        // Handle generic types like Vec<User>
        if self.check(&Token::LessThan) {
            type_str.push('<');
            self.advance();
            type_str.push_str(&self.expect_type("Expected type inside generic")?);
            self.consume(&Token::GreaterThan, "Expected '>' to close generic type")?;
            type_str.push('>');
        }

        Ok(type_str)
    }

    /// Expect an identifier token
    fn expect_identifier(&mut self, message: &str) -> Result<String> {
        match &self.current().token {
            Token::Ident(s) => {
                let ident = s.clone();
                self.advance();
                Ok(ident)
            }
            _ => self.error(message),
        }
    }

    /// Expect a string token
    fn expect_string(&mut self, message: &str) -> Result<String> {
        match &self.current().token {
            Token::String(s) => {
                let string = s.clone();
                self.advance();
                Ok(string)
            }
            _ => self.error(message),
        }
    }

    /// Expect a boolean token
    fn expect_boolean(&mut self, message: &str) -> Result<bool> {
        match &self.current().token {
            Token::Boolean(b) => {
                let val = *b;
                self.advance();
                Ok(val)
            }
            _ => self.error(message),
        }
    }

    /// Expect an integer token
    fn expect_integer(&mut self, message: &str) -> Result<usize> {
        match &self.current().token {
            Token::Integer(i) => {
                let val = *i as usize;
                self.advance();
                Ok(val)
            }
            _ => self.error(message),
        }
    }

    /// Check if current token matches
    fn check(&self, token: &Token) -> bool {
        if self.is_at_end() {
            return false;
        }

        std::mem::discriminant(&self.current().token) == std::mem::discriminant(token)
    }

    /// Check if current token is an identifier
    fn check_identifier(&self) -> bool {
        matches!(self.current().token, Token::Ident(_))
    }

    /// Match and consume a specific identifier
    fn match_identifier(&mut self, name: &str) -> bool {
        if let Token::Ident(s) = &self.current().token {
            if s == name {
                self.advance();
                return true;
            }
        }
        false
    }

    /// Consume a specific token or error
    fn consume(&mut self, token: &Token, message: &str) -> Result<()> {
        if self.check(token) {
            self.advance();
            Ok(())
        } else {
            self.error(message)
        }
    }

    /// Skip comment and newline tokens (trivia)
    fn skip_trivia(&mut self) -> bool {
        let mut skipped = false;
        while matches!(
            self.current().token,
            Token::Comment(_) | Token::DocComment(_) | Token::ModuleDoc(_) | Token::Newline
        ) {
            self.advance();
            skipped = true;
        }
        skipped
    }

    /// Skip tokens until newline or end of file
    fn skip_until_newline(&mut self) {
        while !matches!(self.current().token, Token::Newline | Token::Eof) {
            self.advance();
        }
    }

    /// Get current token
    fn current(&self) -> &LocatedToken {
        if self.position >= self.tokens.len() {
            self.tokens.last().unwrap()
        } else {
            &self.tokens[self.position]
        }
    }

    /// Advance to next token
    fn advance(&mut self) {
        if !self.is_at_end() {
            self.position += 1;
        }
    }

    /// Check if at end of token stream
    fn is_at_end(&self) -> bool {
        matches!(self.current().token, Token::Eof)
    }

    /// Create an error with current location
    fn error<T>(&self, message: &str) -> Result<T> {
        let current = self.current();
        Err(Error::Parse {
            file: self.path.clone(),
            line: current.line,
            column: current.column,
            message: format!("{} (found {})", message, current.token.description()),
        })
    }
}

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

    #[test]
    fn test_parse_simple_schema() {
        let input = r#"
@schema User {
  id: EntityId
  name: String
}
"#;
        let result = GoldParser::parse_str(input, Path::new("test.au"));
        if let Err(e) = &result {
            eprintln!("Parse error: {}", e);
        }
        assert!(result.is_ok());
        let file = result.unwrap();
        assert_eq!(file.blocks.len(), 1);
        assert_eq!(file.blocks[0].block_type(), "schema");
    }

    #[test]
    fn test_parse_query() {
        let input = r#"
@query get_user(id: EntityId) -> User {
  language = "hyperql"
  ---
  SELECT * FROM users WHERE id = :id
  ---
}
"#;
        let result = GoldParser::parse_str(input, Path::new("test.au"));
        if let Err(e) = &result {
            eprintln!("Parse error: {}", e);
        }
        assert!(result.is_ok());
        let file = result.unwrap();
        assert_eq!(file.blocks.len(), 1);

        if let Block::Query(query) = &file.blocks[0] {
            assert_eq!(query.name, "get_user");
            assert_eq!(query.params.len(), 1);
            assert_eq!(query.return_type, "User");
            assert_eq!(query.language, "hyperql");
        } else {
            panic!("Expected Query block");
        }
    }

    #[test]
    fn test_parse_config() {
        let input = r#"
@config database {
  path = "./data"
  engine = "manifold"
}
"#;
        let result = GoldParser::parse_str(input, Path::new("test.au"));
        if let Err(e) = &result {
            eprintln!("Parse error: {}", e);
        }
        assert!(result.is_ok());
        let file = result.unwrap();
        assert_eq!(file.blocks.len(), 1);

        if let Block::Config(config) = &file.blocks[0] {
            assert_eq!(config.name, "database");
            assert_eq!(config.attributes.len(), 2);
        } else {
            panic!("Expected Config block");
        }
    }

    #[test]
    fn test_parse_endpoint() {
        let input = r#"
@endpoint GET "/api/users/:id" {
  query = get_user
  auth = true
}
"#;
        let result = GoldParser::parse_str(input, Path::new("test.au"));
        if let Err(e) = &result {
            eprintln!("Parse error: {}", e);
        }
        assert!(result.is_ok());
        let file = result.unwrap();
        assert_eq!(file.blocks.len(), 1);

        if let Block::Endpoint(endpoint) = &file.blocks[0] {
            assert_eq!(endpoint.method, "GET");
            assert_eq!(endpoint.path, "/api/users/:id");
            assert_eq!(endpoint.query, "get_user");
            assert!(endpoint.auth);
        } else {
            panic!("Expected Endpoint block");
        }
    }

    #[test]
    fn test_parse_multiple_blocks() {
        let input = r#"
@schema User {
  id: EntityId
  name: String
}

@query get_user(id: EntityId) -> User {
  language = "hyperql"
  ---
  SELECT * FROM users WHERE id = :id
  ---
}
"#;
        let result = GoldParser::parse_str(input, Path::new("test.au"));
        if let Err(e) = &result {
            eprintln!("Parse error: {}", e);
        }
        assert!(result.is_ok());
        let file = result.unwrap();
        assert_eq!(file.blocks.len(), 2);
    }

    #[test]
    fn test_parse_embedding_annotation() {
        let input = r#"
@schema Document {
  id: EntityId
  content: String

  @embedding(model="bge-base-en-v1.5", source_field="content", dimension=768)
  embedding: Vector
}
"#;
        let result = GoldParser::parse_str(input, Path::new("test.au"));
        if let Err(e) = &result {
            eprintln!("Parse error: {}", e);
        }
        assert!(result.is_ok());
        let file = result.unwrap();
        assert_eq!(file.blocks.len(), 1);

        if let Block::Schema(schema) = &file.blocks[0] {
            assert_eq!(schema.name, "Document");
            assert_eq!(schema.fields.len(), 3);

            // Check embedding field
            let embedding_field = &schema.fields[2];
            assert_eq!(embedding_field.name, "embedding");
            assert_eq!(embedding_field.field_type, "Vector");
            assert!(embedding_field.embedding_annotation.is_some());

            let annotation = embedding_field.embedding_annotation.as_ref().unwrap();
            assert_eq!(annotation.model, "bge-base-en-v1.5");
            assert_eq!(annotation.source_field, "content");
            assert_eq!(annotation.dimension, Some(768));
            assert!(annotation.paradigm.is_none());
        } else {
            panic!("Expected Schema block");
        }
    }

    #[test]
    fn test_parse_embedding_annotation_with_paradigm() {
        let input = r#"
@schema Document {
  id: EntityId
  content: String

  @embedding(model="colbert-v2", source_field="content", paradigm="multi-vector")
  embedding: Vector
}
"#;
        let result = GoldParser::parse_str(input, Path::new("test.au"));
        assert!(result.is_ok());
        let file = result.unwrap();

        if let Block::Schema(schema) = &file.blocks[0] {
            let embedding_field = &schema.fields[2];
            let annotation = embedding_field.embedding_annotation.as_ref().unwrap();
            assert_eq!(annotation.model, "colbert-v2");
            assert_eq!(annotation.dimension, None); // Dimension will be queried from Tessera
            assert_eq!(annotation.paradigm, Some("multi-vector".to_string()));
        } else {
            panic!("Expected Schema block");
        }
    }

    #[test]
    fn test_parse_embedding_annotation_no_dimension() {
        let input = r#"
@schema Document {
  id: EntityId
  content: String

  @embedding(model="bge-base-en-v1.5", source_field="content")
  embedding: Vector
}
"#;
        let result = GoldParser::parse_str(input, Path::new("test.au"));
        assert!(result.is_ok());
        let file = result.unwrap();

        if let Block::Schema(schema) = &file.blocks[0] {
            let embedding_field = &schema.fields[2];
            let annotation = embedding_field.embedding_annotation.as_ref().unwrap();
            assert_eq!(annotation.model, "bge-base-en-v1.5");
            assert_eq!(annotation.source_field, "content");
            assert_eq!(annotation.dimension, None); // Will be queried from Tessera
            assert_eq!(annotation.paradigm, None);
        } else {
            panic!("Expected Schema block");
        }
    }
}