oak-sql 0.0.11

SQL database query language parser with support for standard SQL syntax and database operations.
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
use crate::{SqlElementType, SqlLanguage, SqlParser, ast, ast::*, lexer::token_type::SqlTokenType};
use oak_core::{Builder, BuilderCache, GreenNode, OakDiagnostics, OakError, Parser, Range, RedNode, RedTree, SourceText, TextEdit, builder::BuildOutput, source::Source};
use std::sync::Arc;

mod build_expression_tree;

/// AST builder for SQL.
///
/// This builder is responsible for converting the generic syntax tree (green/red trees)
/// into a strongly-typed SQL Abstract Syntax Tree (AST). It implements the [`Builder`]
/// trait, allowing it to be used within the Oak incremental parsing framework.
///
/// # Usage
///
/// ```rust
/// use oak_core::{Builder, source::SourceText};
/// use oak_sql::{SqlBuilder, SqlLanguage};
///
/// let config = SqlLanguage::default();
/// let builder = SqlBuilder::new(&config);
/// // ... use builder to build AST from source
/// ```
#[derive(Clone)]
pub struct SqlBuilder<'config> {
    config: &'config SqlLanguage,
}

impl<'config> SqlBuilder<'config> {
    /// Creates a new `SqlBuilder` with the specified language configuration.
    pub fn new(config: &'config SqlLanguage) -> Self {
        Self { config }
    }
}

impl<'config> Builder<SqlLanguage> for SqlBuilder<'config> {
    /// Builds the SQL AST from the source text and edits.
    ///
    /// This is the main entry point for the builder. It performs the following steps:
    /// 1. Initializes a [`SqlParser`] with the current configuration.
    /// 2. Executes the parser to produce a [`RedTree`] (Concrete Syntax Tree).
    /// 3. Converts the resulting green tree into a typed [`SqlRoot`] AST.
    /// 4. Handles incremental updates by passing `edits` to the parser.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use oak_core::{Builder, ParseSession, source::SourceText};
    /// use oak_sql::{SqlBuilder, SqlLanguage};
    ///
    /// let config = SqlLanguage::default();
    /// let builder = SqlBuilder::new(&config);
    /// let mut cache = ParseSession::default();
    /// let source = "SELECT * FROM users";
    /// let output = builder.build(&source, &[], &mut cache);
    ///
    /// if let Ok(root) = output.result {
    ///     assert_eq!(root.statements.len(), 1);
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if parsing fails or if the CST cannot be lowered to a valid AST.
    fn build<'a, S: Source + ?Sized>(&self, source: &S, edits: &[TextEdit], cache: &'a mut impl BuilderCache<SqlLanguage>) -> BuildOutput<SqlLanguage> {
        let parser = SqlParser::new(self.config);
        let parse_result = parser.parse(source, edits, cache);
        let OakDiagnostics { result, diagnostics } = parse_result;

        match result {
            Ok(green_tree) => {
                let source_text = SourceText::new(source.get_text_in((0..source.length()).into()).into_owned());
                match self.build_root(green_tree, &source_text) {
                    Ok(ast_root) => OakDiagnostics { result: Ok(ast_root), diagnostics },
                    Err(build_error) => {
                        let mut diagnostics = diagnostics;
                        diagnostics.push(build_error.clone());
                        OakDiagnostics { result: Err(build_error), diagnostics }
                    }
                }
            }
            Err(parse_error) => OakDiagnostics { result: Err(parse_error), diagnostics },
        }
    }
}

impl<'config> SqlBuilder<'config> {
    /// Builds the root SQL AST node from a green tree.
    ///
    /// This method performs the "lowering" phase where it traverses the untyped [`GreenNode`]
    /// tree and constructs a structured [`SqlRoot`]. It maps each top-level child node
    /// to its corresponding SQL statement type (SELECT, INSERT, etc.).
    pub(crate) fn build_root<'a>(&self, green_tree: &'a GreenNode<'a, SqlLanguage>, source: &SourceText) -> Result<SqlRoot, OakError> {
        let root_node = RedNode::new(green_tree, 0);
        let mut statements = Vec::new();

        for child in root_node.children() {
            if let RedTree::Node(n) = child {
                let res = match n.green.kind {
                    SqlElementType::SelectStatement => self.build_select_statement(n, source).map(SqlStatement::Select),
                    SqlElementType::InsertStatement => self.build_insert_statement(n, source).map(SqlStatement::Insert),
                    SqlElementType::UpdateStatement => self.build_update_statement(n, source).map(SqlStatement::Update),
                    SqlElementType::DeleteStatement => self.build_delete_statement(n, source).map(SqlStatement::Delete),
                    SqlElementType::CreateStatement => self.build_create_statement(n, source).map(SqlStatement::Create),
                    SqlElementType::DropStatement => self.build_drop_statement(n, source).map(SqlStatement::Drop),
                    SqlElementType::AlterStatement => self.build_alter_statement(n, source).map(SqlStatement::Alter),
                    _ => continue,
                };

                match res {
                    Ok(stmt) => statements.push(stmt),
                    Err(e) => {
                        statements.push(SqlStatement::Error { message: Arc::from(e.to_string()), span: n.span() });
                    }
                }
            }
        }

        Ok(SqlRoot { statements, span: root_node.span() })
    }

    /// Builds a `SELECT` statement AST node.
    fn build_select_statement<'a>(&self, node: RedNode<'a, SqlLanguage>, source: &SourceText) -> Result<SelectStatement, OakError> {
        let mut items = Vec::new();
        let mut from = None;
        let mut joins = Vec::new();
        let mut expr = None;
        let mut group_by = None;
        let mut having = None;
        let mut order_by = None;
        let mut limit = None;

        let mut where_found = false;

        for child in node.children() {
            match child {
                RedTree::Node(n) => match n.green.kind {
                    SqlElementType::SelectItem => items.push(self.build_select_item(n, source)?),
                    SqlElementType::TableName => from = Some(self.build_table_name(n, source)?),
                    SqlElementType::JoinClause => joins.push(self.build_join_clause(n, source)?),
                    SqlElementType::GroupByClause => group_by = Some(self.build_group_by_clause(n, source)?),
                    SqlElementType::HavingClause => having = Some(self.build_having_clause(n, source)?),
                    SqlElementType::OrderByClause => order_by = Some(self.build_order_by_clause(n, source)?),
                    SqlElementType::LimitClause => limit = Some(self.build_limit_clause(n, source)?),
                    SqlElementType::Expression => {
                        if where_found && expr.is_none() {
                            expr = Some(self.build_expression(n, source)?);
                        }
                    }
                    _ => {}
                },
                RedTree::Leaf(t) => {
                    if t.kind == SqlTokenType::Where {
                        where_found = true;
                    }
                }
            }
        }

        Ok(SelectStatement { items, from, joins, expr, group_by, having, order_by, limit, span: node.span() })
    }

    /// Builds a select item (column or expression) for a `SELECT` statement.
    fn build_select_item<'a>(&self, node: RedNode<'a, SqlLanguage>, source: &SourceText) -> Result<SelectItem, OakError> {
        let mut expr = None;
        let mut alias = None;
        let mut is_star = false;

        for child in node.children() {
            match child {
                RedTree::Leaf(t) => match t.kind {
                    SqlTokenType::Star => is_star = true,
                    SqlTokenType::Identifier_ => {
                        if expr.is_none() {
                            expr = Some(Expression::Identifier(Identifier { name: self.get_text(t.span.clone(), source), span: t.span.clone() }));
                        }
                        else {
                            alias = Some(Identifier { name: self.get_text(t.span.clone(), source), span: t.span.clone() });
                        }
                    }
                    _ => {}
                },
                RedTree::Node(n) => match n.green.kind {
                    SqlElementType::Expression => expr = Some(self.build_expression(n, source)?),
                    SqlElementType::Identifier => {
                        if expr.is_none() {
                            expr = Some(Expression::Identifier(self.build_identifier(n, source)?));
                        }
                        else {
                            alias = Some(self.build_identifier(n, source)?);
                        }
                    }
                    SqlElementType::Alias => alias = Some(self.build_identifier(n, source)?),
                    _ => {}
                },
            }
        }

        if is_star { Ok(SelectItem::Star { span: node.span() }) } else { Ok(SelectItem::Expression { expr: expr.ok_or_else(|| OakError::custom_error("Missing expression in select item"))?, alias, span: node.span() }) }
    }

    /// Builds an `INSERT` statement AST node.
    fn build_insert_statement<'a>(&self, node: RedNode<'a, SqlLanguage>, source: &SourceText) -> Result<InsertStatement, OakError> {
        let mut table_name = None;
        let mut columns = Vec::new();
        let mut values = Vec::new();

        for child in node.children() {
            if let RedTree::Node(n) = child {
                match n.green.kind {
                    SqlElementType::TableName => table_name = Some(self.build_table_name(n, source)?),
                    SqlElementType::ColumnName => {
                        for sub in n.children() {
                            match sub {
                                RedTree::Node(sn) if sn.green.kind == SqlElementType::Identifier => {
                                    columns.push(self.build_identifier(sn, source)?);
                                }
                                RedTree::Leaf(st) if st.kind == SqlTokenType::Identifier_ => {
                                    columns.push(Identifier { name: self.get_text(st.span.clone(), source), span: st.span.clone() });
                                }
                                _ => {}
                            }
                        }
                    }
                    SqlElementType::ValueList => {
                        self.collect_expressions(n, source, &mut values)?;
                    }
                    _ => {}
                }
            }
        }

        Ok(InsertStatement { table_name: table_name.ok_or_else(|| OakError::custom_error("Missing table name in INSERT"))?, columns, values, span: node.span() })
    }

    /// Collects expressions from a node into a vector.
    fn collect_expressions<'a>(&self, node: RedNode<'a, SqlLanguage>, source: &SourceText, out: &mut Vec<Expression>) -> Result<(), OakError> {
        for child in node.children() {
            if let RedTree::Node(n) = child {
                match n.green.kind {
                    SqlElementType::Expression => out.push(self.build_expression(n, source)?),
                    SqlElementType::Identifier => out.push(Expression::Identifier(self.build_identifier(n, source)?)),
                    SqlElementType::ValueList => self.collect_expressions(n, source, out)?,
                    _ => {}
                }
            }
        }
        Ok(())
    }

    /// Builds an `UPDATE` statement AST node.
    fn build_update_statement<'a>(&self, node: RedNode<'a, SqlLanguage>, source: &SourceText) -> Result<UpdateStatement, OakError> {
        let mut table_name: Option<TableName> = None;
        let mut assignments = Vec::new();
        let mut selection = None;

        for child in node.children() {
            match child {
                RedTree::Leaf(t) => match t.kind {
                    SqlTokenType::Set => {}
                    SqlTokenType::Identifier_ => {
                        if table_name.is_none() {
                            let ident = Identifier { name: self.get_text(t.span.clone(), source), span: t.span.clone() };
                            table_name = Some(TableName { name: ident, span: t.span.clone() });
                        }
                    }
                    _ => {}
                },
                RedTree::Node(n) => match n.green.kind {
                    SqlElementType::TableName => table_name = Some(self.build_table_name(n, source)?),
                    SqlElementType::Assignment => assignments.push(self.build_assignment(n, source)?),
                    SqlElementType::Expression => selection = Some(self.build_expression(n, source)?),
                    _ => {}
                },
            }
        }

        Ok(UpdateStatement { table_name: table_name.ok_or_else(|| OakError::custom_error("Missing table name in UPDATE"))?, assignments, selection, span: node.span() })
    }

    /// Builds an assignment (column = expression) for an `UPDATE` statement.
    fn build_assignment<'a>(&self, node: RedNode<'a, SqlLanguage>, source: &SourceText) -> Result<Assignment, OakError> {
        let mut column = None;
        let mut value = None;

        for child in node.children() {
            if let RedTree::Node(n) = child {
                match n.green.kind {
                    SqlElementType::ColumnName => column = Some(self.build_identifier(n, source)?),
                    SqlElementType::Expression => value = Some(self.build_expression(n, source)?),
                    _ => {}
                }
            }
        }

        Ok(Assignment { column: column.ok_or_else(|| OakError::custom_error("Missing column in assignment"))?, value: value.ok_or_else(|| OakError::custom_error("Missing value in assignment"))?, span: node.span() })
    }

    /// Builds a `DELETE` statement AST node.
    fn build_delete_statement<'a>(&self, node: RedNode<'a, SqlLanguage>, source: &SourceText) -> Result<DeleteStatement, OakError> {
        let mut table_name = None;
        let mut selection = None;

        for child in node.children() {
            match child {
                RedTree::Leaf(t) => {
                    if t.kind == SqlTokenType::From {
                        // skip
                    }
                }
                RedTree::Node(n) => match n.green.kind {
                    SqlElementType::TableName => table_name = Some(self.build_table_name(n, source)?),
                    SqlElementType::Expression => selection = Some(self.build_expression(n, source)?),
                    _ => {}
                },
            }
        }

        Ok(DeleteStatement { table_name: table_name.ok_or_else(|| OakError::custom_error("Missing table name in DELETE"))?, selection, span: node.span() })
    }

    /// Builds a `CREATE` statement AST node.
    fn build_create_statement<'a>(&self, node: RedNode<'a, SqlLanguage>, source: &SourceText) -> Result<CreateStatement, OakError> {
        let mut object_type = CreateObjectType::Table;
        let mut name = None;
        let mut if_not_exists = false;
        let mut columns = Vec::new();
        let mut query = None;
        let mut table_name = None;
        let mut index_columns = Vec::new();
        let mut unique = false;

        for child in node.children() {
            match child {
                RedTree::Leaf(t) => match t.kind {
                    SqlTokenType::Table => object_type = CreateObjectType::Table,
                    SqlTokenType::View => object_type = CreateObjectType::View,
                    SqlTokenType::Index => object_type = CreateObjectType::Index,
                    SqlTokenType::Database => object_type = CreateObjectType::Database,
                    SqlTokenType::Exists => if_not_exists = true,
                    SqlTokenType::Unique => unique = true,
                    _ => {
                        if object_type == CreateObjectType::Index && name.is_some() && table_name.is_some() && t.kind == SqlTokenType::Identifier_ {
                            index_columns.push(ast::Identifier { name: self.get_text(t.span.clone(), source), span: t.span.clone() });
                        }
                    }
                },
                RedTree::Node(n) => match n.green.kind {
                    SqlElementType::TableName => {
                        if object_type == CreateObjectType::Index && name.is_some() {
                            table_name = Some(self.build_table_name(n, source)?);
                        }
                        else {
                            name = Some(self.build_identifier(n, source)?);
                        }
                    }
                    SqlElementType::Identifier => {
                        if object_type == CreateObjectType::Index && name.is_some() && table_name.is_none() {
                            table_name = Some(ast::TableName { name: self.build_identifier(n, source)?, span: n.span() });
                        }
                        else if name.is_none() {
                            name = Some(self.build_identifier(n, source)?);
                        }
                        else if object_type == CreateObjectType::Index {
                            index_columns.push(self.build_identifier(n, source)?);
                        }
                    }
                    SqlElementType::ColumnDefinition => {
                        columns.push(self.build_column_definition(n, source)?);
                    }
                    SqlElementType::SelectStatement => {
                        query = Some(self.build_select_statement(n, source)?);
                    }
                    _ => {}
                },
            }
        }

        let body = match object_type {
            CreateObjectType::Table => CreateBody::Table { columns, span: node.span() },
            CreateObjectType::View => CreateBody::View { query: Box::new(query.ok_or_else(|| OakError::custom_error("Missing query in CREATE VIEW"))?), span: node.span() },
            CreateObjectType::Index => CreateBody::Index { table_name: table_name.ok_or_else(|| OakError::custom_error("Missing table name in CREATE INDEX"))?, columns: index_columns, unique, span: node.span() },
            CreateObjectType::Database => CreateBody::Database { span: node.span() },
        };

        let result = CreateStatement { object_type, name: name.ok_or_else(|| OakError::custom_error("Missing name in CREATE"))?, if_not_exists, body, span: node.span() };
        Ok(result)
    }

    fn build_column_definition<'a>(&self, node: RedNode<'a, SqlLanguage>, source: &SourceText) -> Result<ColumnDefinition, OakError> {
        let mut name = None;
        let mut data_type_str = String::new();
        let mut constraints = Vec::new();

        // Use a flag to track if we are currently parsing the data type
        let mut parsing_data_type = false;

        for child in node.children() {
            match child {
                RedTree::Node(n) => match n.green.kind {
                    SqlElementType::ColumnName | SqlElementType::Identifier => {
                        if name.is_none() {
                            name = Some(self.build_identifier(n, source)?);
                            parsing_data_type = true;
                        }
                        else if parsing_data_type {
                            if !data_type_str.is_empty() {
                                data_type_str.push(' ');
                            }
                            data_type_str.push_str(self.get_text(n.span(), source).trim());
                        }
                    }
                    _ => {}
                },
                RedTree::Leaf(t) => {
                    match t.kind {
                        SqlTokenType::Primary => {
                            constraints.push(ColumnConstraint::PrimaryKey { span: t.span.clone() });
                            parsing_data_type = false;
                        }
                        SqlTokenType::Key => {
                            // Part of PRIMARY KEY, stop parsing data type if we haven't already
                            parsing_data_type = false;
                        }
                        SqlTokenType::Not => {
                            constraints.push(ColumnConstraint::NotNull { span: t.span.clone() });
                            parsing_data_type = false;
                        }
                        SqlTokenType::Null => {
                            // Check if NOT NULL was just added
                            let mut is_not_null = false;
                            if let Some(ColumnConstraint::NotNull { .. }) = constraints.last() {
                                is_not_null = true;
                            }

                            if !is_not_null {
                                constraints.push(ColumnConstraint::Nullable { span: t.span.clone() });
                            }
                            parsing_data_type = false;
                        }
                        SqlTokenType::Unique => {
                            constraints.push(ColumnConstraint::Unique { span: t.span.clone() });
                            parsing_data_type = false;
                        }
                        SqlTokenType::AutoIncrement => {
                            constraints.push(ColumnConstraint::AutoIncrement { span: t.span.clone() });
                            parsing_data_type = false;
                        }
                        SqlTokenType::Default => {
                            parsing_data_type = false;
                            // The expression follows Default token in column definition
                            if let Some(expr_node) = self.find_next_node_in_parent(node.clone(), SqlElementType::Expression, t.span.end) {
                                constraints.push(ColumnConstraint::Default(self.build_expression(expr_node, source)?, t.span.clone()));
                            }
                        }
                        SqlTokenType::Check => {
                            parsing_data_type = false;
                            // The expression follows Check token in column definition
                            if let Some(expr_node) = self.find_next_node_in_parent(node.clone(), SqlElementType::Expression, t.span.end) {
                                constraints.push(ColumnConstraint::Check(self.build_expression(expr_node, source)?, t.span.clone()));
                            }
                        }
                        _ if parsing_data_type => {
                            if !data_type_str.is_empty() {
                                data_type_str.push(' ');
                            }
                            data_type_str.push_str(self.get_text(t.span.clone(), source).trim());
                        }
                        _ => {}
                    }
                }
            }
        }

        Ok(ColumnDefinition { name: name.ok_or_else(|| OakError::custom_error("Missing name in column definition"))?, data_type: Arc::from(data_type_str), constraints, span: node.span() })
    }

    /// Helper to find the next node of a specific kind after a certain position
    fn find_next_node_in_parent<'a>(&self, parent: RedNode<'a, SqlLanguage>, kind: SqlElementType, after_pos: usize) -> Option<RedNode<'a, SqlLanguage>> {
        for child in parent.children() {
            if let RedTree::Node(n) = child {
                if n.green.kind == kind && n.span().start >= after_pos {
                    return Some(n);
                }
            }
        }
        None
    }

    fn build_drop_statement<'a>(&self, node: RedNode<'a, SqlLanguage>, source: &SourceText) -> Result<DropStatement, OakError> {
        let mut object_type = DropObjectType::Table;
        let mut name = None;
        let mut if_exists = false;

        for child in node.children() {
            match child {
                RedTree::Leaf(t) => match t.kind {
                    SqlTokenType::Table => object_type = DropObjectType::Table,
                    SqlTokenType::View => object_type = DropObjectType::View,
                    SqlTokenType::Index => object_type = DropObjectType::Index,
                    SqlTokenType::Database => object_type = DropObjectType::Database,
                    SqlTokenType::Exists => if_exists = true,
                    _ => {}
                },
                RedTree::Node(n) => {
                    if n.green.kind == SqlElementType::TableName || n.green.kind == SqlElementType::Identifier {
                        name = Some(self.build_identifier(n, source)?);
                    }
                }
            }
        }

        let result = DropStatement { object_type, name: name.ok_or_else(|| OakError::custom_error("Missing name in DROP"))?, if_exists, span: node.span() };
        Ok(result)
    }

    fn build_alter_statement<'a>(&self, node: RedNode<'a, SqlLanguage>, source: &SourceText) -> Result<AlterStatement, OakError> {
        let mut table_name = None;
        let mut action = None;

        for child in node.children() {
            if let RedTree::Node(n) = child {
                if n.green.kind == SqlElementType::TableName {
                    table_name = Some(self.build_table_name(n, source)?);
                }
                else if n.green.kind == SqlElementType::AlterAction {
                    action = Some(self.build_alter_action(n, source)?);
                }
            }
        }

        let result = AlterStatement { table_name: table_name.ok_or_else(|| OakError::custom_error("Missing table name in ALTER"))?, action, span: node.span() };
        Ok(result)
    }

    fn build_alter_action<'a>(&self, node: RedNode<'a, SqlLanguage>, source: &SourceText) -> Result<ast::AlterAction, OakError> {
        use SqlTokenType::*;
        let mut is_add = false;
        let mut is_drop = false;
        let mut is_rename = false;
        let mut identifier: Option<ast::Identifier> = None;
        let mut data_type_tokens = Vec::new();

        for child in node.children() {
            match child {
                RedTree::Leaf(t) => match t.kind {
                    Add => is_add = true,
                    Drop => is_drop = true,
                    Rename => is_rename = true,
                    Identifier_ => {
                        if identifier.is_none() {
                            identifier = Some(ast::Identifier { name: self.get_text(t.span.clone(), source), span: t.span.clone() });
                        }
                        else if is_add {
                            data_type_tokens.push(t.span.clone());
                        }
                    }
                    LeftParen | RightParen | NumberLiteral | Comma | Int | Integer | Varchar | Char | Text | Date | Time | Timestamp | Decimal | Float | Double | Boolean => {
                        if is_add && identifier.is_some() {
                            data_type_tokens.push(t.span.clone());
                        }
                    }
                    _ => {}
                },
                RedTree::Node(n) if n.green.kind == SqlElementType::Identifier => {
                    identifier = Some(self.build_identifier(n, source)?);
                }
                _ => {}
            }
        }

        let data_type = if data_type_tokens.is_empty() {
            None
        }
        else {
            let start = data_type_tokens[0].start;
            let end = data_type_tokens.last().unwrap().end;
            Some(self.get_text(Range { start, end }, source))
        };

        if is_add {
            Ok(ast::AlterAction::AddColumn { name: identifier.ok_or_else(|| OakError::custom_error("Missing column name in ALTER TABLE ADD"))?, data_type, span: node.span() })
        }
        else if is_drop {
            Ok(ast::AlterAction::DropColumn { name: identifier.ok_or_else(|| OakError::custom_error("Missing column name in ALTER TABLE DROP"))?, span: node.span() })
        }
        else if is_rename {
            Ok(ast::AlterAction::RenameTo { new_name: identifier.ok_or_else(|| OakError::custom_error("Missing new name in ALTER TABLE RENAME"))?, span: node.span() })
        }
        else {
            Err(OakError::custom_error("Unknown ALTER action"))
        }
    }

    fn build_table_name<'a>(&self, node: RedNode<'a, SqlLanguage>, source: &SourceText) -> Result<TableName, OakError> {
        let mut name = None;
        for child in node.children() {
            match child {
                RedTree::Leaf(t) if t.kind == SqlTokenType::Identifier_ => {
                    name = Some(Identifier { name: self.get_text(t.span.clone(), source), span: t.span.clone() });
                }
                RedTree::Node(n) if n.green.kind == SqlElementType::Identifier => {
                    name = Some(self.build_identifier(n, source)?);
                }
                _ => {}
            }
        }
        Ok(TableName { name: name.ok_or_else(|| OakError::custom_error("Missing table name"))?, span: node.span() })
    }

    fn build_identifier<'a>(&self, node: RedNode<'a, SqlLanguage>, source: &SourceText) -> Result<Identifier, OakError> {
        Ok(Identifier { name: self.get_text(node.span(), source), span: node.span() })
    }

    fn build_join_clause<'a>(&self, node: RedNode<'a, SqlLanguage>, source: &SourceText) -> Result<JoinClause, OakError> {
        let mut join_type = JoinType::Inner;
        let mut table = None;
        let mut on = None;

        for child in node.children() {
            match child {
                RedTree::Leaf(t) => match t.kind {
                    SqlTokenType::Inner => join_type = JoinType::Inner,
                    SqlTokenType::Left => join_type = JoinType::Left,
                    SqlTokenType::Right => join_type = JoinType::Right,
                    SqlTokenType::Full => join_type = JoinType::Full,
                    _ => {}
                },
                RedTree::Node(n) => match n.green.kind {
                    SqlElementType::TableName => table = Some(self.build_table_name(n, source)?),
                    SqlElementType::Expression => on = Some(self.build_expression(n, source)?),
                    _ => {}
                },
            }
        }

        Ok(JoinClause { join_type, table: table.ok_or_else(|| OakError::custom_error("Missing table in JOIN"))?, on, span: node.span() })
    }

    fn build_group_by_clause<'a>(&self, node: RedNode<'a, SqlLanguage>, source: &SourceText) -> Result<GroupByClause, OakError> {
        let mut columns = Vec::new();
        for child in node.children() {
            if let RedTree::Node(n) = child {
                if n.green.kind == SqlElementType::Expression {
                    columns.push(self.build_expression(n, source)?);
                }
            }
        }
        Ok(GroupByClause { columns, span: node.span() })
    }

    fn build_having_clause<'a>(&self, node: RedNode<'a, SqlLanguage>, source: &SourceText) -> Result<HavingClause, OakError> {
        let mut condition = None;
        for child in node.children() {
            if let RedTree::Node(n) = child {
                if n.green.kind == SqlElementType::Expression {
                    condition = Some(self.build_expression(n, source)?);
                }
            }
        }
        Ok(HavingClause { condition: condition.ok_or_else(|| OakError::custom_error("Missing condition in HAVING"))?, span: node.span() })
    }

    fn build_order_by_clause<'a>(&self, node: RedNode<'a, SqlLanguage>, source: &SourceText) -> Result<OrderByClause, OakError> {
        let mut items = Vec::new();
        let mut current_expr: Option<(Expression, Range<usize>)> = None;

        for child in node.children() {
            match child {
                RedTree::Node(n) => {
                    if n.green.kind == SqlElementType::Expression {
                        if let Some((expr, span)) = current_expr.take() {
                            items.push(OrderByItem { expr, direction: OrderDirection::Asc, span });
                        }
                        current_expr = Some((self.build_expression(n.clone(), source)?, n.span()));
                    }
                }
                RedTree::Leaf(t) => match t.kind {
                    SqlTokenType::Asc => {
                        if let Some((expr, span)) = current_expr.take() {
                            let total_span = Range { start: span.start, end: t.span.end };
                            items.push(OrderByItem { expr, direction: OrderDirection::Asc, span: total_span });
                        }
                    }
                    SqlTokenType::Desc => {
                        if let Some((expr, span)) = current_expr.take() {
                            let total_span = Range { start: span.start, end: t.span.end };
                            items.push(OrderByItem { expr, direction: OrderDirection::Desc, span: total_span });
                        }
                    }
                    _ => {}
                },
            }
        }

        if let Some((expr, span)) = current_expr {
            items.push(OrderByItem { expr, direction: OrderDirection::Asc, span });
        }

        Ok(OrderByClause { items, span: node.span() })
    }

    fn build_limit_clause<'a>(&self, node: RedNode<'a, SqlLanguage>, source: &SourceText) -> Result<LimitClause, OakError> {
        let mut limit = None;
        let mut offset = None;

        for child in node.children() {
            if let RedTree::Leaf(t) = child {
                if t.kind == SqlTokenType::NumberLiteral {
                    let expr = Expression::Literal(Literal::Number(self.get_text(t.span.clone(), source), t.span.clone()));
                    if limit.is_none() {
                        limit = Some(expr);
                    }
                    else {
                        offset = Some(expr);
                    }
                }
            }
            else if let RedTree::Node(n) = child {
                if n.green.kind == SqlElementType::Expression {
                    let expr = self.build_expression(n, source)?;
                    if limit.is_none() {
                        limit = Some(expr);
                    }
                    else {
                        offset = Some(expr);
                    }
                }
            }
        }

        Ok(LimitClause { limit: limit.ok_or_else(|| OakError::custom_error("Missing limit value"))?, offset, span: node.span() })
    }

    fn get_text(&self, span: core::range::Range<usize>, source: &SourceText) -> Arc<str> {
        Arc::from(source.get_text_in(span))
    }

    fn map_binary_op(&self, kind: SqlTokenType) -> Option<BinaryOperator> {
        match kind {
            SqlTokenType::Plus => Some(BinaryOperator::Plus),
            SqlTokenType::Minus => Some(BinaryOperator::Minus),
            SqlTokenType::Star => Some(BinaryOperator::Star),
            SqlTokenType::Slash => Some(BinaryOperator::Slash),
            SqlTokenType::Equal => Some(BinaryOperator::Equal),
            SqlTokenType::NotEqual => Some(BinaryOperator::NotEqual),
            SqlTokenType::Less => Some(BinaryOperator::Less),
            SqlTokenType::LessEqual => Some(BinaryOperator::LessEqual),
            SqlTokenType::Greater => Some(BinaryOperator::Greater),
            SqlTokenType::GreaterEqual => Some(BinaryOperator::GreaterEqual),
            SqlTokenType::And => Some(BinaryOperator::And),
            SqlTokenType::Or => Some(BinaryOperator::Or),
            _ => None,
        }
    }

    fn map_unary_op(&self, kind: SqlTokenType) -> Option<UnaryOperator> {
        match kind {
            SqlTokenType::Plus => Some(UnaryOperator::Plus),
            SqlTokenType::Minus => Some(UnaryOperator::Minus),
            SqlTokenType::Not => Some(UnaryOperator::Not),
            _ => None,
        }
    }

    fn build_statement<'a>(&self, node: RedNode<'a, SqlLanguage>, source: &SourceText) -> Result<SqlStatement, OakError> {
        match node.green.kind {
            SqlElementType::SelectStatement => Ok(SqlStatement::Select(self.build_select_statement(node, source)?)),
            SqlElementType::InsertStatement => Ok(SqlStatement::Insert(self.build_insert_statement(node, source)?)),
            SqlElementType::UpdateStatement => Ok(SqlStatement::Update(self.build_update_statement(node, source)?)),
            SqlElementType::DeleteStatement => Ok(SqlStatement::Delete(self.build_delete_statement(node, source)?)),
            SqlElementType::CreateStatement => Ok(SqlStatement::Create(self.build_create_statement(node, source)?)),
            SqlElementType::DropStatement => Ok(SqlStatement::Drop(self.build_drop_statement(node, source)?)),
            SqlElementType::AlterStatement => Ok(SqlStatement::Alter(self.build_alter_statement(node, source)?)),
            _ => Err(OakError::custom_error("Unknown statement type")),
        }
    }
}