qusql-parse 0.4.0

Parser for sql
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
use alloc::boxed::Box;

use crate::{
    SString, Span, Spanned, Statement,
    expression::{Expression, PRIORITY_MAX, parse_expression_unreserved},
    keywords::Keyword,
    lexer::Token,
    parser::{ParseError, Parser},
    qualified_name::parse_qualified_name_unreserved,
};

/// Parse result for `SHOW TABLES` variants
///
/// ```
/// # use qusql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, Statement, Issues};
/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);
/// let sql = "SHOW EXTENDED TABLES FROM test_db LIKE 't%';";
/// let mut issues = Issues::new(sql);
/// let mut stmts = parse_statements(sql, &mut issues, &options);
/// # assert!(issues.is_ok(), "{}", issues);
/// match stmts.pop() {
///     Some(Statement::ShowTables(s)) => {
///         // inspect s.extended, s.db, s.pattern, etc.
///     }
///     _ => panic!("expected ShowTables"),
/// }
/// ```
#[derive(Clone, Debug)]
pub struct ShowTables<'a> {
    pub show_span: Span,
    pub tables_span: Span,
    pub extended: Option<Span>,
    pub full: Option<Span>,
    pub db: Option<crate::QualifiedName<'a>>,
    pub like: Option<SString<'a>>,
    pub where_expr: Option<Expression<'a>>,
}

impl<'a> Spanned for ShowTables<'a> {
    fn span(&self) -> Span {
        self.show_span
            .join_span(&self.tables_span)
            .join_span(&self.extended)
            .join_span(&self.full)
            .join_span(&self.db)
            .join_span(&self.like)
            .join_span(&self.where_expr)
    }
}

fn parse_show_tables<'a>(
    parser: &mut Parser<'a, '_>,
    show_span: Span,
    extended: Option<Span>,
    full: Option<Span>,
) -> Result<ShowTables<'a>, ParseError> {
    let tables_span = parser.consume_keyword(Keyword::TABLES)?;

    // optional FROM or IN db_name
    let mut db = None;
    match &parser.token {
        Token::Ident(_, Keyword::FROM) => {
            parser.consume_keyword(Keyword::FROM)?;
            // Only restrict LIKE and WHERE, which can follow the db name
            let q = parse_qualified_name_unreserved(parser)?;
            db = Some(q);
        }
        Token::Ident(_, Keyword::IN) => {
            parser.consume_keyword(Keyword::IN)?;
            let q = parse_qualified_name_unreserved(parser)?;
            db = Some(q);
        }
        _ => {}
    }

    // optional LIKE or WHERE
    let like = if parser.skip_keyword(Keyword::LIKE).is_some() {
        Some(parser.consume_string()?)
    } else {
        None
    };
    let where_expr = if like.is_none() && parser.skip_keyword(Keyword::WHERE).is_some() {
        Some(parse_expression_unreserved(parser, PRIORITY_MAX)?)
    } else {
        None
    };

    Ok(ShowTables {
        show_span,
        tables_span,
        extended,
        full,
        db,
        like,
        where_expr,
    })
}

/// Parse result for `SHOW DATABASES`
///
/// ```
/// # use qusql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, Statement, Issues};
/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);
/// let sql = "SHOW DATABASES;";
/// let mut issues = Issues::new(sql);
/// let mut stmts = parse_statements(sql, &mut issues, &options);
/// # assert!(issues.is_ok(), "{}", issues);
/// match stmts.pop() {
///     Some(Statement::ShowDatabases(_)) => {}
///     _ => panic!("expected ShowDatabases"),
/// }
/// ```
#[derive(Clone, Debug)]
pub struct ShowDatabases {
    pub show_span: Span,
    pub databases_span: Span,
}

impl Spanned for ShowDatabases {
    fn span(&self) -> Span {
        self.show_span.clone().join_span(&self.databases_span)
    }
}

fn parse_show_databases<'a>(
    parser: &mut Parser<'a, '_>,
    show_span: Span,
) -> Result<ShowDatabases, ParseError> {
    let databases_span = parser.consume_keyword(Keyword::DATABASES)?;
    Ok(ShowDatabases {
        show_span,
        databases_span,
    })
}

/// Parse result for `SHOW PROCESSLIST` / `SHOW FULL PROCESSLIST`
///
/// ```
/// # use qusql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, Statement, Issues};
/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);
/// let sql = "SHOW FULL PROCESSLIST;";
/// let mut issues = Issues::new(sql);
/// let mut stmts = parse_statements(sql, &mut issues, &options);
/// # assert!(issues.is_ok(), "{}", issues);
/// match stmts.pop() {
///     Some(Statement::ShowProcessList(_)) => {}
///     _ => panic!("expected ShowProcessList"),
/// }
/// ```

#[derive(Clone, Debug)]
pub struct ShowProcessList {
    pub show_span: Span,
    pub process_span: Span,
}

impl Spanned for ShowProcessList {
    fn span(&self) -> Span {
        self.show_span.clone().join_span(&self.process_span)
    }
}

fn parse_show_processlist<'a>(
    parser: &mut Parser<'a, '_>,
    show_span: Span,
    _full: Option<Span>,
) -> Result<ShowProcessList, ParseError> {
    match &parser.token {
        Token::Ident(_, Keyword::PROCESSLIST) => {
            let process_span = parser.consume_keyword(Keyword::PROCESSLIST)?;
            Ok(ShowProcessList {
                show_span,
                process_span,
            })
        }
        Token::Ident(_, Keyword::PROCESS) => {
            let process_span = parser.consume_keyword(Keyword::PROCESS)?;
            Ok(ShowProcessList {
                show_span,
                process_span,
            })
        }
        _ => parser.expected_failure("'PROCESS' | 'PROCESSLIST'"),
    }
}

/// Parse result for `SHOW VARIABLES`
///
/// ```
/// # use qusql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, Statement, Issues};
/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);
/// let sql = "SHOW VARIABLES LIKE 'max_%';";
/// let mut issues = Issues::new(sql);
/// let mut stmts = parse_statements(sql, &mut issues, &options);
/// # assert!(issues.is_ok(), "{}", issues);
/// match stmts.pop() {
///     Some(Statement::ShowVariables(s)) => {
///         // s.pattern contains the LIKE expression
///     }
///     _ => panic!("expected ShowVariables"),
/// }
/// ```
#[derive(Clone, Debug)]
pub struct ShowVariables<'a> {
    pub show_span: Span,
    pub variables_span: Span,
    pub global_span: Option<Span>,
    pub session_span: Option<Span>,
    pub like: Option<SString<'a>>,
    pub where_expr: Option<Expression<'a>>,
}

impl<'a> Spanned for ShowVariables<'a> {
    fn span(&self) -> Span {
        self.show_span
            .join_span(&self.variables_span)
            .join_span(&self.global_span)
            .join_span(&self.session_span)
            .join_span(&self.like)
            .join_span(&self.where_expr)
    }
}

fn parse_show_variables<'a>(
    parser: &mut Parser<'a, '_>,
    show_span: Span,
    global_span: Option<Span>,
    session_span: Option<Span>,
) -> Result<ShowVariables<'a>, ParseError> {
    let variables_span = parser.consume_keyword(Keyword::VARIABLES)?;
    let like = if parser.skip_keyword(Keyword::LIKE).is_some() {
        Some(parser.consume_string()?)
    } else {
        None
    };
    let where_expr = if parser.skip_keyword(Keyword::WHERE).is_some() {
        Some(parse_expression_unreserved(parser, PRIORITY_MAX)?)
    } else {
        None
    };
    Ok(ShowVariables {
        show_span,
        variables_span,
        global_span,
        session_span,
        like,
        where_expr,
    })
}

/// Parse result for `SHOW STATUS`
///
/// ```
/// # use qusql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, Statement, Issues};
/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);
/// let sql = "SHOW STATUS LIKE 'Threads%';";
/// let mut issues = Issues::new(sql);
/// let mut stmts = parse_statements(sql, &mut issues, &options);
/// # assert!(issues.is_ok(), "{}", issues);
/// match stmts.pop() {
///     Some(Statement::ShowStatus(_)) => {}
///     _ => panic!("expected ShowStatus"),
/// }
/// ```
#[derive(Clone, Debug)]
pub struct ShowStatus<'a> {
    pub show_span: Span,
    pub status_span: Span,
    pub global_span: Option<Span>,
    pub session_span: Option<Span>,
    pub like: Option<SString<'a>>,
    pub where_expr: Option<Expression<'a>>,
}

impl<'a> Spanned for ShowStatus<'a> {
    fn span(&self) -> Span {
        self.show_span
            .join_span(&self.status_span)
            .join_span(&self.like)
            .join_span(&self.where_expr)
    }
}

fn parse_show_status<'a>(
    parser: &mut Parser<'a, '_>,
    show_span: Span,
    global_span: Option<Span>,
    session_span: Option<Span>,
) -> Result<ShowStatus<'a>, ParseError> {
    let status_span = parser.consume_keyword(Keyword::STATUS)?;
    let like = if parser.skip_keyword(Keyword::LIKE).is_some() {
        Some(parser.consume_string()?)
    } else {
        None
    };
    let where_expr = if parser.skip_keyword(Keyword::WHERE).is_some() {
        Some(parse_expression_unreserved(parser, PRIORITY_MAX)?)
    } else {
        None
    };
    Ok(ShowStatus {
        show_span,
        status_span,
        global_span,
        session_span,
        like,
        where_expr,
    })
}

/// Parse result for `SHOW COLUMNS` / `SHOW FIELDS`
///
/// ```
/// # use qusql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, Statement, Issues};
/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);
/// let sql = "SHOW COLUMNS FROM `my_table` LIKE 'id%';";
/// let mut issues = Issues::new(sql);
/// let mut stmts = parse_statements(sql, &mut issues, &options);
/// # assert!(issues.is_ok(), "{}", issues);
/// match stmts.pop() {
///     Some(Statement::ShowColumns(c)) => {
///         // c.table contains the table name
///     }
///     _ => panic!("expected ShowColumns"),
/// }
/// ```
#[derive(Clone, Debug)]
pub struct ShowColumns<'a> {
    pub show_span: Span,
    pub columns_span: Span,
    pub extended: Option<Span>,
    pub full: Option<Span>,
    pub table: Option<crate::QualifiedName<'a>>,
    pub db: Option<crate::QualifiedName<'a>>,
    pub like: Option<SString<'a>>,
    pub where_expr: Option<Expression<'a>>,
}

impl<'a> Spanned for ShowColumns<'a> {
    fn span(&self) -> Span {
        self.show_span
            .join_span(&self.columns_span)
            .join_span(&self.table)
            .join_span(&self.db)
            .join_span(&self.like)
            .join_span(&self.where_expr)
    }
}

fn parse_show_columns<'a>(
    parser: &mut Parser<'a, '_>,
    show_span: Span,
    extended: Option<Span>,
    full: Option<Span>,
) -> Result<ShowColumns<'a>, ParseError> {
    let columns_span = match &parser.token {
        Token::Ident(_, Keyword::COLUMNS) => parser.consume_keyword(Keyword::COLUMNS)?,
        _ => parser.consume_keyword(Keyword::FIELDS)?,
    };
    let mut table = None;
    let mut db = None;
    // Restrict LIKE and WHERE after table/db names
    if parser.skip_keyword(Keyword::FROM).is_some() || parser.skip_keyword(Keyword::IN).is_some() {
        let q = parse_qualified_name_unreserved(parser)?;
        table = Some(q);
    }
    // optional second FROM/IN specifying database: SHOW COLUMNS FROM tbl FROM db
    if table.is_some() {
        match &parser.token {
            Token::Ident(_, Keyword::FROM) => {
                parser.consume_keyword(Keyword::FROM)?;
                let q = parse_qualified_name_unreserved(parser)?;
                db = Some(q);
            }
            Token::Ident(_, Keyword::IN) => {
                parser.consume_keyword(Keyword::IN)?;
                let q = parse_qualified_name_unreserved(parser)?;
                db = Some(q);
            }
            _ => {}
        }
    }
    let like = if parser.skip_keyword(Keyword::LIKE).is_some() {
        Some(parser.consume_string()?)
    } else {
        None
    };
    let where_expr = if like.is_none() && parser.skip_keyword(Keyword::WHERE).is_some() {
        Some(parse_expression_unreserved(parser, PRIORITY_MAX)?)
    } else {
        None
    };
    Ok(ShowColumns {
        show_span,
        columns_span,
        extended,
        full,
        table,
        db,
        like,
        where_expr,
    })
}

/// Parse result for `SHOW CHARACTER SET` / `SHOW CHARSET`
///
/// ```
/// # use qusql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, Statement, Issues};
/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);
/// let sql = "SHOW CHARACTER SET WHERE Charset LIKE 'utf%';";
/// let mut issues = Issues::new(sql);
/// let mut stmts = parse_statements(sql, &mut issues, &options);
/// # assert!(issues.is_ok(), "{}", issues);
/// match stmts.pop() {
///     Some(Statement::ShowCharacterSet(s)) => {
///         // s.where_expr contains the WHERE expression; s.pattern contains the LIKE pattern when used directly
///     }
///     _ => panic!("expected ShowCharacterSet"),
/// }
/// ```
#[derive(Clone, Debug)]
pub struct ShowCharacterSet<'a> {
    pub show_span: Span,
    pub character_span: Option<Span>,
    pub set_span: Span,
    pub like: Option<SString<'a>>,
    pub where_expr: Option<Expression<'a>>,
}

impl<'a> Spanned for ShowCharacterSet<'a> {
    fn span(&self) -> Span {
        self.show_span
            .join_span(&self.character_span)
            .join_span(&self.set_span)
            .join_span(&self.like)
            .join_span(&self.where_expr)
    }
}

fn parse_show_character_set<'a>(
    parser: &mut Parser<'a, '_>,
    show_span: Span,
) -> Result<ShowCharacterSet<'a>, ParseError> {
    // Accept either: SHOW CHARSET ...  or SHOW CHARACTER SET ...
    let mut character_span: Option<Span> = None;
    let set_span = match &parser.token {
        Token::Ident(_, Keyword::CHARSET) => parser.consume_keyword(Keyword::CHARSET)?,
        Token::Ident(_, Keyword::CHARACTER) => {
            character_span = Some(parser.consume_keyword(Keyword::CHARACTER)?);
            parser.consume_keyword(Keyword::SET)?
        }
        _ => return parser.expected_failure("'CHARSET' | 'CHARACTER'"),
    };

    let mut like: Option<SString<'a>> = None;
    let mut where_expr: Option<Expression<'a>> = None;
    if parser.skip_keyword(Keyword::LIKE).is_some() {
        like = Some(parser.consume_string()?);
    } else if parser.skip_keyword(Keyword::WHERE).is_some() {
        where_expr = Some(parse_expression_unreserved(parser, PRIORITY_MAX)?);
    }

    Ok(ShowCharacterSet {
        show_span,
        character_span,
        set_span,
        like,
        where_expr,
    })
}

/// Parse result for `SHOW CREATE TABLE`
///
/// ```
/// # use qusql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, Statement, Issues};
/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);
/// let sql = "SHOW CREATE TABLE my_table;";
/// let mut issues = Issues::new(sql);
/// let mut stmts = parse_statements(sql, &mut issues, &options);
/// # assert!(issues.is_ok(), "{}", issues);
/// match stmts.pop() {
///     Some(Statement::ShowCreateTable(s)) => {
///         // s.table contains the table name
///     }
///     _ => panic!("expected ShowCreateTable"),
/// }
/// ```
#[derive(Clone, Debug)]
pub struct ShowCreateTable<'a> {
    pub show_span: Span,
    pub create_span: Span,
    pub object_span: Span,
    pub table: crate::QualifiedName<'a>,
}

impl<'a> Spanned for ShowCreateTable<'a> {
    fn span(&self) -> Span {
        self.show_span
            .join_span(&self.create_span)
            .join_span(&self.object_span)
            .join_span(&self.table)
    }
}

/// Parse result for `SHOW CREATE DATABASE`
///
/// ```
/// # use qusql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, Statement, Issues};
/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);
/// let sql = "SHOW CREATE DATABASE my_db;";
/// let mut issues = Issues::new(sql);
/// let mut stmts = parse_statements(sql, &mut issues, &options);
/// # assert!(issues.is_ok(), "{}", issues);
/// match stmts.pop() {
///     Some(Statement::ShowCreateDatabase(s)) => {
///         // s.db contains the database name
///     }
///     _ => panic!("expected ShowCreateDatabase"),
/// }
/// ```
#[derive(Clone, Debug)]
pub struct ShowCreateDatabase<'a> {
    pub show_span: Span,
    pub create_span: Span,
    pub object_span: Span,
    pub db: crate::QualifiedName<'a>,
}

impl<'a> Spanned for ShowCreateDatabase<'a> {
    fn span(&self) -> Span {
        self.show_span
            .join_span(&self.create_span)
            .join_span(&self.object_span)
            .join_span(&self.db)
    }
}

/// Parse result for `SHOW CREATE VIEW`
///
/// ```
/// # use qusql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, Statement, Issues};
/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);
/// let sql = "SHOW CREATE VIEW my_view;";
/// let mut issues = Issues::new(sql);
/// let mut stmts = parse_statements(sql, &mut issues, &options);
/// # assert!(issues.is_ok(), "{}", issues);
/// match stmts.pop() {
///     Some(Statement::ShowCreateView(s)) => {
///         // s.view contains the view name
///     }
///     _ => panic!("expected ShowCreateView"),
/// }
/// ```
#[derive(Clone, Debug)]
pub struct ShowCreateView<'a> {
    pub show_span: Span,
    pub create_span: Span,
    pub object_span: Span,
    pub view: crate::QualifiedName<'a>,
}

impl<'a> Spanned for ShowCreateView<'a> {
    fn span(&self) -> Span {
        self.show_span
            .join_span(&self.create_span)
            .join_span(&self.object_span)
            .join_span(&self.view)
    }
}

fn parse_show_create<'a>(
    parser: &mut Parser<'a, '_>,
    show_span: Span,
) -> Result<crate::Statement<'a>, ParseError> {
    let create_span = parser.consume_keyword(Keyword::CREATE)?;
    match &parser.token {
        Token::Ident(_, Keyword::TABLE) => {
            let object_span = parser.consume_keyword(Keyword::TABLE)?;
            let table = parse_qualified_name_unreserved(parser)?;
            Ok(crate::Statement::ShowCreateTable(Box::new(
                ShowCreateTable {
                    show_span,
                    create_span,
                    object_span,
                    table,
                },
            )))
        }
        Token::Ident(_, Keyword::DATABASE) => {
            let object_span = parser.consume_keyword(Keyword::DATABASE)?;
            let db = parse_qualified_name_unreserved(parser)?;
            Ok(crate::Statement::ShowCreateDatabase(Box::new(
                ShowCreateDatabase {
                    show_span,
                    create_span,
                    object_span,
                    db,
                },
            )))
        }
        Token::Ident(_, Keyword::VIEW) => {
            let object_span = parser.consume_keyword(Keyword::VIEW)?;
            let view = parse_qualified_name_unreserved(parser)?;
            Ok(crate::Statement::ShowCreateView(Box::new(ShowCreateView {
                show_span,
                create_span,
                object_span,
                view,
            })))
        }
        _ => parser.expected_failure("'TABLE' | 'DATABASE' | 'VIEW'"),
    }
}

/// Parse result for `SHOW COLLATION`
///
/// ```
/// # use qusql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, Statement, Issues};
/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);
/// let sql = "SHOW COLLATION LIKE 'utf%';";
/// let mut issues = Issues::new(sql);
/// let mut stmts = parse_statements(sql, &mut issues, &options);
/// # assert!(issues.is_ok(), "{}", issues);
/// match stmts.pop() {
///     Some(Statement::ShowCollation(s)) => {
///         // s.pattern contains the LIKE string
///     }
///     _ => panic!("expected ShowCollation"),
/// }
/// ```
#[derive(Clone, Debug)]
pub struct ShowCollation<'a> {
    pub show_span: Span,
    pub collation_span: Span,
    pub like: Option<SString<'a>>,
    pub where_expr: Option<Expression<'a>>,
}

impl<'a> Spanned for ShowCollation<'a> {
    fn span(&self) -> Span {
        self.show_span
            .join_span(&self.collation_span)
            .join_span(&self.like)
            .join_span(&self.where_expr)
    }
}

fn parse_show_collation<'a>(
    parser: &mut Parser<'a, '_>,
    show_span: Span,
) -> Result<ShowCollation<'a>, ParseError> {
    let collation_span = parser.consume_keyword(Keyword::COLLATION)?;
    let mut like: Option<SString<'a>> = None;
    let mut where_expr: Option<Expression<'a>> = None;
    if parser.skip_keyword(Keyword::LIKE).is_some() {
        like = Some(parser.consume_string()?);
    } else if parser.skip_keyword(Keyword::WHERE).is_some() {
        where_expr = Some(parse_expression_unreserved(parser, PRIORITY_MAX)?);
    }
    Ok(ShowCollation {
        show_span,
        collation_span,
        like,
        where_expr,
    })
}

/// Parse result for `SHOW ENGINES`
///
/// ```
/// # use qusql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, Statement, Issues};
/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);
/// let sql = "SHOW ENGINES;";
/// let mut issues = Issues::new(sql);
/// let mut stmts = parse_statements(sql, &mut issues, &options);
/// # assert!(issues.is_ok(), "{}", issues);
/// match stmts.pop() {
///     Some(Statement::ShowEngines(s)) => {
///         // s.engines_span is present
///     }
///     _ => panic!("expected ShowEngines"),
/// }
/// ```
#[derive(Clone, Debug)]
pub struct ShowEngines {
    pub show_span: Span,
    pub engines_span: Span,
}

impl Spanned for ShowEngines {
    fn span(&self) -> Span {
        self.show_span.join_span(&self.engines_span)
    }
}

fn parse_show_engines<'a>(
    parser: &mut Parser<'a, '_>,
    show_span: Span,
) -> Result<ShowEngines, ParseError> {
    let engines_span = parser.consume_keyword(Keyword::ENGINES)?;
    Ok(ShowEngines {
        show_span,
        engines_span,
    })
}

pub(crate) fn parse_show<'a>(
    parser: &mut Parser<'a, '_>,
) -> Result<crate::Statement<'a>, ParseError> {
    let show_span = parser.consume_keyword(Keyword::SHOW)?;
    // parse optional modifiers EXTENDED, FULL, GLOBAL and SESSION (either or both) before dispatch
    let mut extended: Option<Span> = None;
    let mut full: Option<Span> = None;
    let mut global: Option<Span> = None;
    let mut session: Option<Span> = None;
    loop {
        match &parser.token {
            Token::Ident(_, Keyword::EXTENDED) => extended = Some(parser.consume()),
            Token::Ident(_, Keyword::FULL) => full = Some(parser.consume()),
            Token::Ident(_, Keyword::GLOBAL) => global = Some(parser.consume()),
            Token::Ident(_, Keyword::SESSION) => session = Some(parser.consume()),
            _ => break,
        }
    }

    let stmt = match &parser.token {
        Token::Ident(_, Keyword::TABLES) => Statement::ShowTables(Box::new(parse_show_tables(parser, show_span, extended.clone(), full.clone())?)),
        Token::Ident(_, Keyword::CREATE) => parse_show_create(parser, show_span)?,
        Token::Ident(_, Keyword::DATABASES) => Statement::ShowDatabases(Box::new(parse_show_databases(parser, show_span)?)),
        Token::Ident(_, Keyword::PROCESSLIST | Keyword::PROCESS) => {
            Statement::ShowProcessList(Box::new(parse_show_processlist(parser, show_span, full.clone())?))
        }
        Token::Ident(_, Keyword::VARIABLES) => Statement::ShowVariables(Box::new(parse_show_variables(parser, show_span, global.clone(), session.clone())?)),
        Token::Ident(_, Keyword::STATUS) => Statement::ShowStatus(Box::new(parse_show_status(parser, show_span, global.clone(), session.clone())?)),
        Token::Ident(_, Keyword::COLUMNS | Keyword::FIELDS) => {
            Statement::ShowColumns(Box::new(parse_show_columns(parser, show_span, extended.clone(), full.clone())?))
        }
        Token::Ident(_, Keyword::CHARSET | Keyword::CHARACTER) => {
            Statement::ShowCharacterSet(Box::new(parse_show_character_set(parser, show_span)?))
        }
            Token::Ident(_, Keyword::COLLATION) => Statement::ShowCollation(Box::new(parse_show_collation(parser, show_span)?)),
            Token::Ident(_, Keyword::ENGINES) => Statement::ShowEngines(Box::new(parse_show_engines(parser, show_span)?)),
        _ if parser.options.dialect.is_postgresql() => {
            // PostgreSQL: SHOW <parameter_name> — consume the parameter name as-is
            let var_span = parser.consume_plain_identifier_unreserved()?;
            Statement::ShowVariables(Box::new(ShowVariables {
                show_span: show_span.clone(),
                variables_span: var_span.span(),
                global_span: global.clone(),
                session_span: session.clone(),
                like: None,
                where_expr: None,
            }))
        }
        _ => return parser.expected_failure("'TABLES' | 'DATABASES' | 'PROCESS' | 'PROCESSLIST' | 'VARIABLES' | 'STATUS' | 'COLUMNS' | 'FIELDS' | 'CHARSET' | 'CHARACTER' | 'COLLATION' | 'ENGINES'"),
    };

    // Emit warnings for modifiers not supported by the particular SHOW variant
    if let Some(span) = &extended {
        match &stmt {
            crate::Statement::ShowTables(_) => {}
            crate::Statement::ShowColumns(_) => {}
            _ => {
                parser.warn(
                    "Modifier EXTENDED not supported for this SHOW variant",
                    span,
                );
            }
        }
    }

    if let Some(span) = &full {
        match &stmt {
            crate::Statement::ShowTables(_) => {}
            crate::Statement::ShowProcessList(_) => {}
            crate::Statement::ShowColumns(_) => {}
            _ => {
                parser.warn("Modifier FULL not supported for this SHOW variant", span);
            }
        }
    }

    if let Some(span) = &global {
        match &stmt {
            crate::Statement::ShowStatus(_) => {}
            crate::Statement::ShowVariables(_) => {}
            _ => {
                parser.warn("Modifier GLOBAL not supported for this SHOW variant", span);
            }
        }
    }

    if let Some(span) = &session {
        match &stmt {
            crate::Statement::ShowStatus(_) => {}
            crate::Statement::ShowVariables(_) => {}
            _ => {
                parser.warn("Modifier SESSION not supported for this SHOW variant", span);
            }
        }
    }

    Ok(stmt)
}