sql-ddl-to-json-schema 0.2.1

Parse MySQL and MariaDB DDL into a compact table model and JSON Schema draft-07 documents
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
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
//! ALTER TABLE grammar rules.

use serde_json::{json, Map, Value};

use crate::lexer::TokenKind;

use super::common::{
    column_definitions, index_column_list, index_options, o_default_value, one_of_keywords,
    p_column_reference, p_index_type, ws_or_equals,
};
use super::create_table::{p_create_table_options, s_eos};
use super::datatypes::o_datatype;
use super::helpers::{s_identifier, s_number};
use super::stream::Stream;

/// Parse `P_ALTER_TABLE`.
pub fn p_alter_table(s: &mut Stream) -> Option<Value> {
    let save = s.pos();
    if s.eat_keyword("ALTER").is_none() || !s.ws1() {
        return None;
    }
    // ONLINE __.
    let sp = s.pos();
    if s.eat_keyword("ONLINE").is_some() && s.ws1() {
    } else {
        s.set(sp);
    }
    // IGNORE __.
    let sp = s.pos();
    if s.eat_keyword("IGNORE").is_some() && s.ws1() {
    } else {
        s.set(sp);
    }
    if s.eat_keyword("TABLE").is_none() || !s.ws1() {
        s.set(save);
        return None;
    }
    let table = match s_identifier(s) {
        Some(t) => t,
        None => {
            s.set(save);
            return None;
        }
    };
    if !s.ws1() {
        s.set(save);
        return None;
    }
    // WAIT n __ | NOWAIT __.
    let sp = s.pos();
    if s.eat_keyword("WAIT").is_some() && s.ws1() && s_number(s).is_some() && s.ws1() {
    } else {
        s.set(sp);
        let sp2 = s.pos();
        if s.eat_keyword("NOWAIT").is_some() && s.ws1() {
        } else {
            s.set(sp2);
        }
    }
    let first = p_alter_table_specs(s)?;
    let mut specs = vec![first];
    loop {
        let sp = s.pos();
        s.ws0();
        if s.eat(&TokenKind::Comma).is_none() {
            s.set(sp);
            break;
        }
        s.ws0();
        match p_alter_table_specs(s) {
            Some(spec) => specs.push(spec),
            None => {
                s.set(sp);
                break;
            }
        }
    }
    if !s_eos(s) {
        s.set(save);
        return None;
    }
    Some(json!({
        "id": "P_ALTER_TABLE",
        "def": { "table": table, "specs": specs }
    }))
}

/// Parse `P_ALTER_TABLE_SPECS`. Tries table options, then a spec.
fn p_alter_table_specs(s: &mut Stream) -> Option<Value> {
    let save = s.pos();
    // Table options first, matching source alternative order.
    if let Some(opts) = p_create_table_options(s) {
        return Some(json!({
            "id": "P_ALTER_TABLE_SPECS",
            "def": { "tableOptions": opts }
        }));
    }
    s.set(save);
    if let Some(spec) = o_alter_table_spec(s) {
        return Some(json!({
            "id": "P_ALTER_TABLE_SPECS",
            "def": { "spec": spec }
        }));
    }
    s.set(save);
    None
}

/// Wrap an alter spec alternative.
fn wrap(def: Value) -> Value {
    json!({ "id": "O_ALTER_TABLE_SPEC", "def": def })
}

/// Parse `O_ALTER_TABLE_SPEC`. Tries alternatives in source order.
fn o_alter_table_spec(s: &mut Stream) -> Option<Value> {
    let rules: &[fn(&mut Stream) -> Option<Value>] = &[
        add_column,
        add_columns,
        add_index,
        add_primary_key,
        add_unique_key,
        add_fulltext,
        add_spatial,
        add_foreign_key,
        algorithm,
        set_default,
        drop_default,
        change_column,
        modify_column,
        convert_to_charset,
        enable_keys,
        disable_keys,
        discard_tablespace,
        import_tablespace,
        // Specific DROP forms come before the generic column drop so a keyword
        // like INDEX or PRIMARY is not read as a column name.
        drop_index,
        drop_primary_key,
        drop_foreign_key,
        drop_column,
        force,
        change_lock,
        order_by,
        rename_index,
        rename,
        with_validation,
        without_validation,
        add_period_for_system_time,
    ];
    for rule in rules {
        let save = s.pos();
        if let Some(v) = rule(s) {
            return Some(wrap(v));
        }
        s.set(save);
    }
    None
}

/// Consume `COLUMN __` when `consume` is set. The caller has already consumed
/// the leading whitespace. Returns whether the branch matched.
///
/// The source optional `( COLUMN __ )?` prefers its absent branch, so callers
/// try `consume = false` first and only retry with `consume = true` when the
/// rest of the rule cannot parse.
fn opt_column_branch(s: &mut Stream, consume: bool) -> bool {
    if !consume {
        return true;
    }
    let save = s.pos();
    if s.eat_keyword("COLUMN").is_some() && s.ws1() {
        true
    } else {
        s.set(save);
        false
    }
}

/// Optional `__ COLUMN`. The caller has not consumed the leading whitespace and
/// consumes its own `__` after. Used by ADD column rules.
fn opt_ws_column(s: &mut Stream) {
    let save = s.pos();
    if s.ws1() && s.eat_keyword("COLUMN").is_some() {
    } else {
        s.set(save);
    }
}

/// Optional `__ ident`.
fn opt_ws_ident(s: &mut Stream) -> Option<String> {
    let save = s.pos();
    if s.ws1() {
        if let Some(id) = s_identifier(s) {
            return Some(id);
        }
    }
    s.set(save);
    None
}

/// Optional `__ P_INDEX_TYPE`.
fn opt_index_type(s: &mut Stream) -> Option<Value> {
    let save = s.pos();
    if s.ws1() {
        if let Some(it) = p_index_type(s) {
            return Some(it);
        }
    }
    s.set(save);
    None
}

/// Optional `CONSTRAINT [ident]? __` prefix followed by `next`.
///
/// Returns Some(name-or-empty) when a constraint keyword was present, else None.
/// An empty string means present but unnamed, which the source treats as
/// undefined. The optional name is only kept when `next` follows it, mirroring
/// how the source backtracks when the name would swallow the type keyword.
fn opt_constraint(s: &mut Stream, next: &str) -> Option<String> {
    let save = s.pos();
    s.eat_keyword("CONSTRAINT")?;
    // Try with a name.
    let with_name = s.pos();
    if s.ws1() {
        if let Some(n) = s_identifier(s) {
            if s.ws1() && peek_keyword(s, next) {
                return Some(n);
            }
        }
    }
    // Retry without a name.
    s.set(with_name);
    if !s.ws1() {
        s.set(save);
        return None;
    }
    Some(String::new())
}

/// Whether the next token is the given keyword, without consuming it.
fn peek_keyword(s: &Stream, name: &str) -> bool {
    matches!(
        s.peek(),
        Some(crate::lexer::Token { kind: crate::lexer::TokenKind::Keyword(k), .. }) if k == name
    )
}

/// Optional trailing position: FIRST or AFTER ident.
fn opt_position(s: &mut Stream) -> Option<Value> {
    let save = s.pos();
    if s.ws1() {
        if s.eat_keyword("FIRST").is_some() {
            return Some(json!({ "after": Value::Null }));
        }
        let asave = s.pos();
        if s.eat_keyword("AFTER").is_some() && s.ws1() {
            if let Some(id) = s_identifier(s) {
                return Some(json!({ "after": id }));
            }
        }
        s.set(asave);
    }
    s.set(save);
    None
}

/// Optional `__ P_COLUMN_REFERENCE`.
fn opt_reference(s: &mut Stream) -> Option<Value> {
    let save = s.pos();
    if s.ws1() {
        if let Some(r) = p_column_reference(s) {
            return Some(r);
        }
    }
    s.set(save);
    None
}

fn add_column(s: &mut Stream) -> Option<Value> {
    s.eat_keyword("ADD")?;
    opt_ws_column(s);
    if !s.ws1() {
        return None;
    }
    let name = s_identifier(s)?;
    if !s.ws1() {
        return None;
    }
    let datatype = o_datatype(s)?;
    let column_definition = column_definitions(s);
    let reference = opt_reference(s);
    let position = opt_position(s);

    let mut def = Map::new();
    def.insert("action".into(), Value::String("addColumn".into()));
    def.insert("name".into(), Value::String(name));
    def.insert("datatype".into(), datatype);
    def.insert("columnDefinition".into(), Value::Array(column_definition));
    insert_position(&mut def, position);
    if let Some(r) = reference {
        def.insert("reference".into(), r);
    }
    Some(Value::Object(def))
}

fn add_columns(s: &mut Stream) -> Option<Value> {
    s.eat_keyword("ADD")?;
    opt_ws_column(s);
    s.ws0();
    s.eat(&TokenKind::LParens)?;
    s.ws0();
    // First column.
    let first = add_columns_item(s)?;
    let mut columns = vec![first];
    loop {
        let sp = s.pos();
        s.ws0();
        if s.eat(&TokenKind::Comma).is_none() {
            s.set(sp);
            break;
        }
        s.ws0();
        match add_columns_item(s) {
            Some(c) => columns.push(c),
            None => {
                s.set(sp);
                break;
            }
        }
    }
    s.ws0();
    s.eat(&TokenKind::RParens)?;
    Some(json!({
        "action": "addColumns",
        "columns": columns
    }))
}

fn add_columns_item(s: &mut Stream) -> Option<Value> {
    let name = s_identifier(s)?;
    if !s.ws1() {
        return None;
    }
    let datatype = o_datatype(s)?;
    let column_definition = column_definitions(s);
    let reference = opt_reference(s);
    let mut obj = Map::new();
    obj.insert("name".into(), Value::String(name));
    obj.insert("datatype".into(), datatype);
    obj.insert("columnDefinition".into(), Value::Array(column_definition));
    if let Some(r) = reference {
        obj.insert("reference".into(), r);
    }
    Some(Value::Object(obj))
}

fn add_index(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("ADD").is_none() || !s.ws1() {
        return None;
    }
    one_of_keywords(s, &["INDEX", "KEY"])?;
    let name = opt_ws_ident(s);
    let index = opt_index_type(s);
    let columns = index_column_list(s)?;
    let options = index_options(s);

    let mut def = Map::new();
    def.insert("action".into(), Value::String("addIndex".into()));
    insert_name_or_null(&mut def, name);
    insert_index_or_null(&mut def, index);
    def.insert("columns".into(), Value::Array(columns));
    def.insert("options".into(), Value::Array(options));
    Some(Value::Object(def))
}

fn add_primary_key(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("ADD").is_none() || !s.ws1() {
        return None;
    }
    let constraint = opt_constraint(s, "PRIMARY");
    if s.eat_keyword("PRIMARY").is_none() || !s.ws1() || s.eat_keyword("KEY").is_none() {
        return None;
    }
    let index = opt_index_type(s);
    let columns = index_column_list(s)?;
    let options = index_options(s);

    let mut def = Map::new();
    def.insert("action".into(), Value::String("addPrimaryKey".into()));
    insert_constraint_name(&mut def, constraint);
    insert_index_or_null(&mut def, index);
    def.insert("columns".into(), Value::Array(columns));
    def.insert("options".into(), Value::Array(options));
    Some(Value::Object(def))
}

fn add_unique_key(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("ADD").is_none() || !s.ws1() {
        return None;
    }
    let constraint = opt_constraint(s, "UNIQUE");
    s.eat_keyword("UNIQUE")?;
    // Optional __ INDEX | __ KEY.
    let sp = s.pos();
    if s.ws1() && one_of_keywords(s, &["INDEX", "KEY"]).is_some() {
    } else {
        s.set(sp);
    }
    // The index identifier is parsed but not used for the name here. The name
    // comes from the constraint prefix. The source applies the index/key
    // workaround to this identifier, which has no observable effect since it is
    // not read afterward.
    let _index_ident = opt_ws_ident(s);
    let index = opt_index_type(s);
    let columns = index_column_list(s)?;
    let options = index_options(s);

    let mut def = Map::new();
    def.insert("action".into(), Value::String("addUniqueKey".into()));
    insert_constraint_name(&mut def, constraint);
    insert_index_or_null(&mut def, index);
    def.insert("columns".into(), Value::Array(columns));
    def.insert("options".into(), Value::Array(options));
    Some(Value::Object(def))
}

fn add_fulltext(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("ADD").is_none() || !s.ws1() || s.eat_keyword("FULLTEXT").is_none() {
        return None;
    }
    let sp = s.pos();
    if s.ws1() && one_of_keywords(s, &["INDEX", "KEY"]).is_some() {
    } else {
        s.set(sp);
    }
    let mut name = opt_ws_ident(s);
    let columns = index_column_list(s)?;
    let options = index_options(s);

    if let Some(n) = &name {
        let lower = n.to_lowercase();
        if lower == "index" || lower == "key" {
            name = None;
        }
    }

    let mut def = Map::new();
    def.insert("action".into(), Value::String("addFulltextIndex".into()));
    match name {
        Some(n) => {
            def.insert("name".into(), Value::String(n));
        }
        None => {
            def.insert("name".into(), Value::Null);
        }
    }
    def.insert("columns".into(), Value::Array(columns));
    def.insert("options".into(), Value::Array(options));
    Some(Value::Object(def))
}

fn add_spatial(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("ADD").is_none() || !s.ws1() || s.eat_keyword("SPATIAL").is_none() {
        return None;
    }
    let sp = s.pos();
    if s.ws1() && one_of_keywords(s, &["INDEX", "KEY"]).is_some() {
    } else {
        s.set(sp);
    }
    let mut name = opt_ws_ident(s);
    let columns = index_column_list(s)?;
    let options = index_options(s);

    if let Some(n) = &name {
        let lower = n.to_lowercase();
        if lower == "index" || lower == "key" {
            name = None;
        }
    }

    let mut def = Map::new();
    def.insert("action".into(), Value::String("addSpatialIndex".into()));
    match name {
        Some(n) => {
            def.insert("name".into(), Value::String(n));
        }
        None => {
            def.insert("name".into(), Value::Null);
        }
    }
    def.insert("columns".into(), Value::Array(columns));
    def.insert("options".into(), Value::Array(options));
    Some(Value::Object(def))
}

fn add_foreign_key(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("ADD").is_none() || !s.ws1() {
        return None;
    }
    let constraint = opt_constraint(s, "FOREIGN");
    if s.eat_keyword("FOREIGN").is_none() || !s.ws1() || s.eat_keyword("KEY").is_none() {
        return None;
    }
    let _index_name = opt_ws_ident(s);
    let columns = index_column_list(s)?;
    s.ws0();
    let reference = p_column_reference(s)?;

    let mut def = Map::new();
    def.insert("action".into(), Value::String("addForeignKey".into()));
    insert_constraint_name(&mut def, constraint);
    def.insert("columns".into(), Value::Array(columns));
    def.insert("reference".into(), reference);
    Some(Value::Object(def))
}

fn algorithm(s: &mut Stream) -> Option<Value> {
    s.eat_keyword("ALGORITHM")?;
    if !ws_or_equals(s) {
        return None;
    }
    let v = one_of_keywords(s, &["DEFAULT", "INPLACE", "COPY"])?;
    Some(json!({ "action": "changeAlgorithm", "algorithm": v }))
}

/// Try a rule body with COLUMN absent, then with COLUMN consumed.
///
/// The absent branch is only accepted when the statement can continue after it,
/// meaning the next token is a comma or the end of the statement. This mirrors
/// how the source keeps only the parse that consumes the whole statement.
fn try_both_column<F>(s: &mut Stream, body: F) -> Option<Value>
where
    F: Fn(&mut Stream, bool) -> Option<Value>,
{
    let save = s.pos();
    if let Some(v) = body(s, false) {
        if statement_can_continue(s) {
            return Some(v);
        }
    }
    s.set(save);
    let v = body(s, true);
    if v.is_none() {
        s.set(save);
    }
    v
}

/// Whether the current position can end an alter spec: a comma or the end of
/// statement (optional whitespace then a semicolon or end of input).
fn statement_can_continue(s: &Stream) -> bool {
    let mut pos = s.pos();
    // Skip whitespace tokens.
    while let Some(crate::lexer::Token {
        kind: crate::lexer::TokenKind::Ws,
        ..
    }) = s.at(pos)
    {
        pos += 1;
    }
    match s.at(pos) {
        None => true,
        Some(t) => matches!(
            t.kind,
            crate::lexer::TokenKind::Comma | crate::lexer::TokenKind::Semicolon
        ),
    }
}

fn set_default(s: &mut Stream) -> Option<Value> {
    try_both_column(s, set_default_body)
}

fn set_default_body(s: &mut Stream, consume_column: bool) -> Option<Value> {
    if s.eat_keyword("ALTER").is_none() || !s.ws1() {
        return None;
    }
    if !opt_column_branch(s, consume_column) {
        return None;
    }
    let column = s_identifier(s)?;
    if !s.ws1() || s.eat_keyword("SET").is_none() || !s.ws1() || s.eat_keyword("DEFAULT").is_none()
    {
        return None;
    }
    if !s.ws1() {
        return None;
    }
    let value = o_default_value(s)?;
    Some(json!({
        "action": "setDefaultColumnValue",
        "column": column,
        "value": value
    }))
}

fn drop_default(s: &mut Stream) -> Option<Value> {
    try_both_column(s, drop_default_body)
}

fn drop_default_body(s: &mut Stream, consume_column: bool) -> Option<Value> {
    if s.eat_keyword("ALTER").is_none() || !s.ws1() {
        return None;
    }
    if !opt_column_branch(s, consume_column) {
        return None;
    }
    let column = s_identifier(s)?;
    if !s.ws1() || s.eat_keyword("DROP").is_none() || !s.ws1() || s.eat_keyword("DEFAULT").is_none()
    {
        return None;
    }
    Some(json!({
        "action": "dropDefaultColumnValue",
        "column": column
    }))
}

fn change_column(s: &mut Stream) -> Option<Value> {
    try_both_column(s, change_column_body)
}

fn change_column_body(s: &mut Stream, consume_column: bool) -> Option<Value> {
    if s.eat_keyword("CHANGE").is_none() || !s.ws1() {
        return None;
    }
    if !opt_column_branch(s, consume_column) {
        return None;
    }
    let column = s_identifier(s)?;
    if !s.ws1() {
        return None;
    }
    let new_name = s_identifier(s)?;
    if !s.ws1() {
        return None;
    }
    let datatype = o_datatype(s)?;
    let column_definition = column_definitions(s);
    let reference = opt_reference(s);
    let position = opt_position(s);

    let mut def = Map::new();
    def.insert("action".into(), Value::String("changeColumn".into()));
    def.insert("column".into(), Value::String(column));
    def.insert("newName".into(), Value::String(new_name));
    def.insert("datatype".into(), datatype);
    def.insert("columnDefinition".into(), Value::Array(column_definition));
    insert_position(&mut def, position);
    if let Some(r) = reference {
        def.insert("reference".into(), r);
    }
    Some(Value::Object(def))
}

fn modify_column(s: &mut Stream) -> Option<Value> {
    try_both_column(s, modify_column_body)
}

fn modify_column_body(s: &mut Stream, consume_column: bool) -> Option<Value> {
    if s.eat_keyword("MODIFY").is_none() || !s.ws1() {
        return None;
    }
    if !opt_column_branch(s, consume_column) {
        return None;
    }
    let column = s_identifier(s)?;
    if !s.ws1() {
        return None;
    }
    let datatype = o_datatype(s)?;
    let column_definition = column_definitions(s);
    let reference = opt_reference(s);
    let position = opt_position(s);

    let mut def = Map::new();
    def.insert("action".into(), Value::String("changeColumn".into()));
    def.insert("column".into(), Value::String(column));
    // newName is undefined for MODIFY. JSON drops undefined, so leave it out.
    def.insert("datatype".into(), datatype);
    def.insert("columnDefinition".into(), Value::Array(column_definition));
    insert_position(&mut def, position);
    if let Some(r) = reference {
        def.insert("reference".into(), r);
    }
    Some(Value::Object(def))
}

fn convert_to_charset(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("CONVERT").is_none() || !s.ws1() || s.eat_keyword("TO").is_none() || !s.ws1() {
        return None;
    }
    // (CHARACTER SET | CHARSET).
    let matched = {
        let save = s.pos();
        if s.eat_keyword("CHARACTER").is_some() && s.ws1() && s.eat_keyword("SET").is_some() {
            true
        } else {
            s.set(save);
            s.eat_keyword("CHARSET").is_some()
        }
    };
    if !matched || !s.ws1() {
        return None;
    }
    let charset = super::helpers::o_string_or_ident(s)?;
    // Optional COLLATE collation.
    let mut collate: Option<String> = None;
    let sp = s.pos();
    if s.ws1() && s.eat_keyword("COLLATE").is_some() && s.ws1() {
        if let Some(c) = super::helpers::o_string_or_ident(s) {
            collate = Some(c);
        } else {
            s.set(sp);
        }
    } else {
        s.set(sp);
    }
    let mut def = Map::new();
    def.insert(
        "action".into(),
        Value::String("convertToCharacterSet".into()),
    );
    def.insert("charset".into(), Value::String(charset));
    // collate is a failed optional (null) when absent.
    def.insert(
        "collate".into(),
        collate.map(Value::String).unwrap_or(Value::Null),
    );
    Some(Value::Object(def))
}

fn enable_keys(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("ENABLE").is_some() && s.ws1() && s.eat_keyword("KEYS").is_some() {
        return Some(json!({ "action": "enableKeys" }));
    }
    None
}

fn disable_keys(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("DISABLE").is_some() && s.ws1() && s.eat_keyword("KEYS").is_some() {
        return Some(json!({ "action": "disableKeys" }));
    }
    None
}

fn discard_tablespace(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("DISCARD").is_some() && s.ws1() && s.eat_keyword("TABLESPACE").is_some() {
        return Some(json!({ "action": "discardTablespace" }));
    }
    None
}

fn import_tablespace(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("IMPORT").is_some() && s.ws1() && s.eat_keyword("TABLESPACE").is_some() {
        return Some(json!({ "action": "importTablespace" }));
    }
    None
}

fn drop_column(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("DROP").is_none() || !s.ws1() {
        return None;
    }
    // COLUMN __.
    let sp = s.pos();
    if s.eat_keyword("COLUMN").is_some() && s.ws1() {
    } else {
        s.set(sp);
    }
    // IF EXISTS __.
    let sp = s.pos();
    if s.eat_keyword("IF").is_some() && s.ws1() && s.eat_keyword("EXISTS").is_some() && s.ws1() {
    } else {
        s.set(sp);
    }
    let column = s_identifier(s)?;
    Some(json!({ "action": "dropColumn", "column": column }))
}

fn drop_index(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("DROP").is_none() || !s.ws1() {
        return None;
    }
    if one_of_keywords(s, &["INDEX", "KEY"]).is_none() || !s.ws1() {
        return None;
    }
    let index = s_identifier(s)?;
    Some(json!({ "action": "dropIndex", "index": index }))
}

fn drop_primary_key(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("DROP").is_some()
        && s.ws1()
        && s.eat_keyword("PRIMARY").is_some()
        && s.ws1()
        && s.eat_keyword("KEY").is_some()
    {
        return Some(json!({ "action": "dropPrimaryKey" }));
    }
    None
}

fn drop_foreign_key(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("DROP").is_none() || !s.ws1() {
        return None;
    }
    if s.eat_keyword("FOREIGN").is_none() || !s.ws1() || s.eat_keyword("KEY").is_none() || !s.ws1()
    {
        return None;
    }
    let key = s_identifier(s)?;
    Some(json!({ "action": "dropForeignKey", "key": key }))
}

fn force(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("FORCE").is_some() {
        return Some(json!({ "action": "force" }));
    }
    None
}

fn change_lock(s: &mut Stream) -> Option<Value> {
    s.eat_keyword("LOCK")?;
    if !ws_or_equals(s) {
        return None;
    }
    let v = one_of_keywords(s, &["DEFAULT", "NONE", "SHARED", "EXCLUSIVE"])?;
    Some(json!({ "action": "changeLock", "lock": v }))
}

fn order_by(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("ORDER").is_none() || !s.ws1() || s.eat_keyword("BY").is_none() || !s.ws1() {
        return None;
    }
    let first = s_identifier(s)?;
    let mut columns = vec![Value::String(first)];
    loop {
        let sp = s.pos();
        s.ws0();
        if s.eat(&TokenKind::Comma).is_none() {
            s.set(sp);
            break;
        }
        s.ws0();
        match s_identifier(s) {
            Some(c) => columns.push(Value::String(c)),
            None => {
                s.set(sp);
                break;
            }
        }
    }
    Some(json!({ "action": "orderBy", "columns": columns }))
}

fn rename_index(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("RENAME").is_none() || !s.ws1() {
        return None;
    }
    if one_of_keywords(s, &["INDEX", "KEY"]).is_none() || !s.ws1() {
        return None;
    }
    let index = s_identifier(s)?;
    if !s.ws1() || s.eat_keyword("TO").is_none() || !s.ws1() {
        return None;
    }
    let new_name = s_identifier(s)?;
    Some(json!({
        "action": "renameIndex",
        "index": index,
        "newName": new_name
    }))
}

fn rename(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("RENAME").is_none() || !s.ws1() {
        return None;
    }
    // TO __ | AS __.
    let sp = s.pos();
    if (s.eat_keyword("TO").is_some() || s.eat_keyword("AS").is_some()) && s.ws1() {
    } else {
        s.set(sp);
    }
    let new_name = s_identifier(s)?;
    Some(json!({ "action": "rename", "newName": new_name }))
}

fn with_validation(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("WITH").is_some() && s.ws1() && s.eat_keyword("VALIDATION").is_some() {
        return Some(json!({ "action": "withValidation" }));
    }
    None
}

fn without_validation(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("WITHOUT").is_some() && s.ws1() && s.eat_keyword("VALIDATION").is_some() {
        return Some(json!({ "action": "withoutValidation" }));
    }
    None
}

fn add_period_for_system_time(s: &mut Stream) -> Option<Value> {
    if s.eat_keyword("ADD").is_none() || !s.ws1() || s.eat_keyword("PERIOD").is_none() || !s.ws1() {
        return None;
    }
    if s.eat_keyword("FOR").is_none() || !s.ws1() || s.eat_keyword("SYSTEM_TIME").is_none() {
        return None;
    }
    s.ws0();
    s.eat(&TokenKind::LParens)?;
    s.ws0();
    let start = s_identifier(s)?;
    s.ws0();
    s.eat(&TokenKind::Comma)?;
    s.ws0();
    let end = s_identifier(s)?;
    s.ws0();
    s.eat(&TokenKind::RParens)?;
    Some(json!({
        "action": "addPeriodForSystemTime",
        "startColumnName": start,
        "endColumnName": end
    }))
}

/// Insert a constraint name into a spec. The source stores `name: d[2]` where
/// the constraint optional yields null when absent and an empty name when the
/// prefix is present but unnamed. Both serialize as null.
fn insert_constraint_name(def: &mut Map<String, Value>, constraint: Option<String>) {
    let value = match constraint {
        Some(name) if !name.is_empty() => Value::String(name),
        _ => Value::Null,
    };
    def.insert("name".into(), value);
}

/// Insert an optional index type, storing null when absent.
fn insert_index_or_null(def: &mut Map<String, Value>, index: Option<Value>) {
    def.insert("index".into(), index.unwrap_or(Value::Null));
}

/// Insert an optional name, storing null when absent.
fn insert_name_or_null(def: &mut Map<String, Value>, name: Option<String>) {
    def.insert(
        "name".into(),
        name.map(Value::String).unwrap_or(Value::Null),
    );
}

/// Insert an optional position, storing null when absent.
fn insert_position(def: &mut Map<String, Value>, position: Option<Value>) {
    def.insert("position".into(), position.unwrap_or(Value::Null));
}