aboutsummaryrefslogtreecommitdiff
path: root/odb/relational/schema.hxx
blob: d1842e47494150434754d41dcf7b8bec4884d857 (plain)
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
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
// file      : odb/relational/schema.hxx
// copyright : Copyright (c) 2009-2018 Code Synthesis Tools CC
// license   : GNU GPL v3; see accompanying LICENSE file

#ifndef ODB_RELATIONAL_SCHEMA_HXX
#define ODB_RELATIONAL_SCHEMA_HXX

#include <set>
#include <vector>
#include <cassert>

#include <odb/emitter.hxx>
#include <odb/relational/common.hxx>
#include <odb/relational/context.hxx>

namespace relational
{
  namespace schema
  {
    typedef std::set<qname> table_set;

    struct common: virtual context
    {
      typedef ::emitter emitter_type;

      common (emitter_type& e, ostream& os, schema_format f)
          : e_ (e), os_ (os), format_ (f) {}

      void
      pre_statement ()
      {
        e_.pre ();
        diverge (os_);
      }

      void
      post_statement ()
      {
        restore ();
        e_.post ();
      }

      emitter_type&
      emitter () const
      {
        return e_;
      }

      ostream&
      stream () const
      {
        return os_;
      }

    public:
      // Find an entity corresponding to the drop node in alter_table.
      //
      template <typename T, typename D>
      T&
      find (D& d)
      {
        using sema_rel::model;
        using sema_rel::changeset;
        using sema_rel::table;
        using sema_rel::alter_table;

        alter_table& at (dynamic_cast<alter_table&> (d.scope ()));
        changeset& cs (dynamic_cast<changeset&> (at.scope ()));
        model& bm (cs.base_model ());
        table* bt (bm.find<table> (at.name ()));
        assert (bt != 0);
        T* b (bt->find<T> (d.name ()));
        assert (b != 0);
        return *b;
      }

    protected:
      emitter_type& e_;
      ostream& os_;
      schema_format format_;
    };

    //
    // Drop.
    //

    // Only used in migration.
    //
    struct drop_column: trav_rel::drop_column, common
    {
      typedef drop_column base;

      drop_column (common const& c, bool* first = 0)
          : common (c),
            first_ (first != 0 ? *first : first_data_),
            first_data_ (true)
      {
      }

      drop_column (drop_column const& c)
          : root_context (), // @@ -Wextra
            context (),
            common (c),
            first_ (&c.first_ != &c.first_data_ ? c.first_ : first_data_),
            first_data_ (c.first_data_)
      {
      }

      virtual void
      drop_header ()
      {
        // By default ADD COLUMN though some databases use just ADD.
        //
        os << "DROP COLUMN ";
      }

      virtual void
      traverse (sema_rel::drop_column& dc)
      {
        if (first_)
          first_ = false;
        else
          os << ",";

        os << endl
           << "  ";
        drop_header ();
        os << quote_id (dc.name ());
      }

    protected:
      bool& first_;
      bool first_data_;
    };

    // Normally only used in migration but some databases use it as a
    // base to also drop foreign keys in schema.
    //
    struct drop_foreign_key: trav_rel::foreign_key,
                             trav_rel::drop_foreign_key,
                             trav_rel::add_foreign_key, // Override.
                             common
    {
      typedef drop_foreign_key base;

      // Schema constructor.
      //
      drop_foreign_key (common const& c, table_set& dropped, bool* first = 0)
          : common (c),
            dropped_ (&dropped),
            first_ (first != 0 ? *first : first_data_),
            first_data_ (true)
      {
      }

      // Migration constructor.
      //
      drop_foreign_key (common const& c, bool* first = 0)
          : common (c),
            dropped_ (0),
            first_ (first != 0 ? *first : first_data_),
            first_data_ (true)
      {
      }

      drop_foreign_key (drop_foreign_key const& c)
          : root_context (), // @@ -Wextra
            context (),
            common (c),
            dropped_ (c.dropped_),
            first_ (&c.first_ != &c.first_data_ ? c.first_ : first_data_),
            first_data_ (c.first_data_)
      {
      }

      virtual void
      drop_header ()
      {
        os << "DROP CONSTRAINT ";
      }

      virtual void
      traverse (sema_rel::foreign_key& fk)
      {
        // If the table which we reference is droped before us, then
        // we need to drop the constraint first. Similarly, if the
        // referenced table is not part if this model, then assume
        // it is dropped before us. In migration we always do this
        // first.
        //
        sema_rel::table& t (dynamic_cast<sema_rel::table&> (fk.scope ()));

        if (dropped_ != 0)
        {
          sema_rel::qname const& rt (fk.referenced_table ());
          sema_rel::model& m (dynamic_cast<sema_rel::model&> (t.scope ()));

          if (dropped_->find (rt) == dropped_->end () &&
              m.find (rt) != m.names_end ())
            return;
        }

        drop (t, fk);
      }

      virtual void
      drop (sema_rel::table& t, sema_rel::foreign_key& fk)
      {
        // When generating schema we would need to check if the key exists.
        // So this implementation will need to be customize on the per-
        // database level.
        //
        pre_statement ();

        os << "ALTER TABLE " << quote_id (t.name ()) << endl
           << "  ";
        drop_header ();
        os << quote_id (fk.name ()) << endl;

        post_statement ();
      }

      virtual void
      traverse (sema_rel::drop_foreign_key& dfk)
      {
        if (first_)
          first_ = false;
        else
          os << ",";

        os << endl;
        drop (dfk);
      }

      virtual void
      drop (sema_rel::drop_foreign_key& dfk)
      {
        os << "  ";
        drop_header ();
        os << quote_id (dfk.name ());
      }

    protected:
      table_set* dropped_;
      bool& first_;
      bool first_data_;
    };

    // Currently only used in migration.
    //
    struct drop_index: trav_rel::drop_index, common
    {
      typedef drop_index base;

      enum index_type {unique, non_unique, all};

      drop_index (common const& c, index_type t = all)
          : common (c), type_ (t) {}

      virtual void
      traverse (sema_rel::drop_index& di)
      {
        // Find the index we are dropping in the base model.
        //
        traverse (find<sema_rel::index> (di));
      }

      virtual void
      traverse (sema_rel::index& in)
      {
        if (type_ == unique &&
            in.type ().find ("UNIQUE") == string::npos &&
            in.type ().find ("unique") == string::npos)
          return;

        if (type_ == non_unique && (
              in.type ().find ("UNIQUE") != string::npos ||
              in.type ().find ("unique") != string::npos))
          return;

        pre_statement ();
        drop (in);
        post_statement ();
      }

      virtual string
      name (sema_rel::index& in)
      {
        return quote_id (in.name ());
      }

      virtual void
      drop (sema_rel::index& in)
      {
        os << "DROP INDEX " << name (in) << endl;
      }

    protected:
      index_type type_;
    };

    struct drop_table: trav_rel::table,
                       trav_rel::drop_table,
                       trav_rel::add_table,   // Override.
                       trav_rel::alter_table, // Override.
                       common
    {
      typedef drop_table base;

      drop_table (emitter_type& e, ostream& os, schema_format f)
          : common (e, os, f) {}

      virtual void
      drop (sema_rel::table& t, bool migration)
      {
        pre_statement ();
        os << "DROP TABLE " << (migration ? "" : "IF EXISTS ") <<
          quote_id (t.name ()) << endl;
        post_statement ();
      }

      virtual void
      delete_ (sema_rel::qname const& rtable,
               sema_rel::qname const& dtable,
               sema_rel::primary_key& rkey,
               sema_rel::primary_key& dkey)
      {
        pre_statement ();

        // This might not be the most efficient way for every database.
        //
        os << "DELETE FROM " << quote_id (rtable) << endl
           << "  WHERE EXISTS (SELECT 1 FROM " << quote_id (dtable) << endl
           << "    WHERE ";

        for (size_t i (0); i != rkey.contains_size (); ++i)
        {
          if (i != 0)
            os << endl
               << "      AND ";

          os << quote_id (rtable) << "." <<
            quote_id (rkey.contains_at (i).column ().name ()) << " = " <<
            quote_id (dtable) << "." <<
            quote_id (dkey.contains_at (i).column ().name ());
        }

        os << ")" << endl;

        post_statement ();
      }

      virtual void
      traverse (sema_rel::table& t, bool migration)
      {
        // By default drop foreign keys referencing tables that would
        // have already been dropped on the first pass.
        //
        if (pass_ == 1)
        {
          // Drop constraints. In migration this is always done on pass 1.
          //
          if (migration)
          {
            instance<drop_foreign_key> dfk (*this);
            trav_rel::unames n (*dfk);
            names (t, n);
          }
          else
          {
            dropped_.insert (t.name ()); // Add it before to cover self-refs.

            instance<drop_foreign_key> dfk (*this, dropped_);
            trav_rel::unames n (*dfk);
            names (t, n);
          }
        }
        else
        {
          if (migration && t.extra ()["kind"] == "polymorphic derived object")
          {
            // If we are dropping a polymorphic derived object, then we
            // also have to clean the base tables. Note that this won't
            // trigger cascade deletion since we have dropped all the
            // keys on pass 1. But we still need to do this in the base
            // to root order in order not to trigger other cascades.
            //
            using sema_rel::model;
            using sema_rel::table;
            using sema_rel::primary_key;
            using sema_rel::foreign_key;

            model& m (dynamic_cast<model&> (t.scope ()));

            table* p (&t);
            do
            {
              // The polymorphic link is the first primary key.
              //
              for (table::names_iterator i (p->names_begin ());
                   i != p->names_end (); ++i)
              {
                if (foreign_key* fk = dynamic_cast<foreign_key*> (
                      &i->nameable ()))
                {
                  p = m.find<table> (fk->referenced_table ());
                  assert (p != 0); // Base table should be there.
                  break;
                }
              }

              primary_key& rkey (*p->find<primary_key> (""));
              primary_key& dkey (*t.find<primary_key> (""));
              assert (rkey.contains_size () == dkey.contains_size ());
              delete_ (p->name (), t.name (), rkey, dkey);
            }
            while (p->extra ()["kind"] != "polymorphic root object");
          }

          drop (t, migration);
        }
      }

      virtual void
      traverse (sema_rel::table& t)
      {
        traverse (t, false);
      }

      virtual void
      traverse (sema_rel::drop_table& dt)
      {
        using sema_rel::model;
        using sema_rel::changeset;
        using sema_rel::table;

        // Find the table we are dropping in the base model.
        //
        changeset& cs (dynamic_cast<changeset&> (dt.scope ()));
        model& bm (cs.base_model ());
        table* t (bm.find<table> (dt.name ()));
        assert (t != 0);
        traverse (*t, true);
      }

      using table::names;

      void
      pass (unsigned short p)
      {
        pass_ = p;
      }

    protected:
      unsigned short pass_;
      table_set dropped_;
    };

    struct drop_model: trav_rel::model, common
    {
      typedef drop_model base;

      drop_model (emitter_type& e, ostream& os, schema_format f)
          : common (e, os, f)
      {
      }

      virtual void
      traverse (sema_rel::model& m)
      {
        // Traverse named entities in the reverse order. This way we
        // drop them in the order opposite to creating.
        //
        for (sema_rel::model::names_iterator begin (m.names_begin ()),
               end (m.names_end ()); begin != end;)
          dispatch (*--end);
      }

      void
      pass (unsigned short p)
      {
        pass_ = p;
      }

    protected:
      unsigned short pass_;
    };

    //
    // Create.
    //

    struct create_column: trav_rel::column,
                          trav_rel::add_column,
                          trav_rel::alter_column, // Override.
                          common
    {
      typedef create_column base;

      create_column (common const& c,
                     bool override_null = true,
                     bool* first = 0)
          : common (c),
            override_null_ (override_null),
            first_ (first != 0 ? *first : first_data_),
            first_data_ (true)
      {
      }

      create_column (create_column const& c)
          : root_context (), // @@ -Wextra
            context (),
            common (c),
            override_null_ (c.override_null_),
            first_ (&c.first_ != &c.first_data_ ? c.first_ : first_data_),
            first_data_ (c.first_data_)
      {
      }

      virtual void
      traverse (sema_rel::column& c)
      {
        if (first_)
          first_ = false;
        else
          os << ",";

        os << endl
           << "  ";
        create (c);
      }

      virtual void
      add_header ()
      {
        // By default ADD COLUMN though some databases use just ADD.
        //
        os << "ADD COLUMN ";
      }

      virtual void
      traverse (sema_rel::add_column& ac)
      {
        if (first_)
          first_ = false;
        else
          os << ",";

        os << endl
           << "  ";
        add_header ();
        create (ac);
      }

      virtual void
      create (sema_rel::column& c)
      {
        using sema_rel::column;

        // See if this column is (part of) a primary key.
        //
        sema_rel::primary_key* pk (0);

        for (column::contained_iterator i (c.contained_begin ());
             i != c.contained_end ();
             ++i)
        {
          if ((pk = dynamic_cast<sema_rel::primary_key*> (&i->key ())))
            break;
        }

        os << quote_id (c.name ()) << " ";

        type (c, pk != 0 && pk->auto_ ());
        constraints (c, pk);

        if (!c.options ().empty ())
          os << " " << c.options ();
      }

      virtual void
      constraints (sema_rel::column& c, sema_rel::primary_key* pk)
      {
        null (c);

        if (!c.default_ ().empty ())
          os << " DEFAULT " << c.default_ ();

        // If this is a single-column primary key, generate it inline.
        //
        if (pk != 0 && pk->contains_size () == 1)
          primary_key ();

        if (pk != 0 && pk->auto_ ())
          auto_ (*pk);
      }

      virtual void
      type (sema_rel::column& c, bool /*auto*/)
      {
        os << c.type ();
      }

      virtual void
      null (sema_rel::column& c)
      {
        bool n (c.null ());

        // If we are adding a new column that doesn't allow NULL nor has
        // a default value, add it as NULL. Later, after migration, we
        // will convert it to NOT NULL.
        //
        if (override_null_ && c.is_a<sema_rel::add_column> () &&
            !n && c.default_ ().empty ())
          n = true;

        // Specify both cases explicitly for better readability,
        // especially in ALTER COLUMN clauses.
        //
        os << (n ? " NULL" : " NOT NULL");
      }

      virtual void
      primary_key ()
      {
        os << " PRIMARY KEY";
      }

      virtual void
      auto_ (sema_rel::primary_key&)
      {
      }

    protected:
      bool override_null_; // Override NOT NULL in add_column.
      bool& first_;
      bool first_data_;
      bool add_;
    };

    struct create_primary_key: trav_rel::primary_key, common
    {
      typedef create_primary_key base;

      create_primary_key (common const& c): common (c) {}

      virtual void
      traverse (sema_rel::primary_key& pk)
      {
        // Single-column primary keys are generated inline in the
        // column declaration.
        //
        if (pk.contains_size () == 1)
          return;

        // We will always follow a column.
        //
        os << "," << endl;

        create (pk);
      }

      virtual void
      create (sema_rel::primary_key& pk)
      {
        using sema_rel::primary_key;

        // By default we create unnamed primary key constraint.
        //

        os << "  PRIMARY KEY (";

        for (primary_key::contains_iterator i (pk.contains_begin ());
             i != pk.contains_end ();
             ++i)
        {
          if (i != pk.contains_begin ())
            os << "," << endl
               << "               ";

          os << quote_id (i->column ().name ());
        }

        os << ")";
      }
    };

    struct create_foreign_key: trav_rel::foreign_key,
                               trav_rel::add_foreign_key,
                               common
    {
      typedef create_foreign_key base;

      // Schema constructor, pass 1.
      //
      create_foreign_key (common const& c, table_set& created, bool* first = 0)
          : common (c),
            created_ (&created),
            first_ (first != 0 ? *first : first_data_),
            first_data_ (true)
      {
      }

      // Schema constructor, pass 2 and migration constructor.
      //
      create_foreign_key (common const& c, bool* first = 0)
          : common (c),
            created_ (0),
            first_ (first != 0 ? *first : first_data_),
            first_data_ (true)
      {
      }

      create_foreign_key (create_foreign_key const& c)
          : root_context (), // @@ -Wextra
            context (),
            common (c),
            created_ (c.created_),
            first_ (&c.first_ != &c.first_data_ ? c.first_ : first_data_),
            first_data_ (c.first_data_)
      {
      }

      virtual void
      traverse (sema_rel::foreign_key& fk)
      {
        if (created_ != 0)
        {
          // Pass 1.
          //
          // If the referenced table has already been defined, do the
          // foreign key definition in the table definition. Otherwise
          // postpone it until pass 2 where we do it via ALTER TABLE.
          //
          if (created_->find (fk.referenced_table ()) != created_->end ())
          {
            traverse_create (fk);
            fk.set (db.string () + "-fk-defined", true); // Mark it as defined.
          }
        }
        else
        {
          // Pass 2.
          //
          if (!fk.count (db.string () + "-fk-defined"))
            traverse_add (fk);
        }
      }

      virtual void
      traverse_create (sema_rel::foreign_key& fk)
      {
        if (first_)
          first_ = false;
        else
          os << ",";

        os << endl
           << "  CONSTRAINT ";
        create (fk);
      }

      virtual void
      traverse_add (sema_rel::foreign_key& fk)
      {
        if (first_)
          first_ = false;
        else
          os << ",";

        os << endl;
        add (fk);
      }

      virtual void
      traverse (sema_rel::add_foreign_key& afk)
      {
        traverse_add (afk);
      }

      virtual void
      add_header ()
      {
        os << "ADD CONSTRAINT ";
      }

      virtual void
      add (sema_rel::foreign_key& fk)
      {
        os << "  ";
        add_header ();
        create (fk);
      }

      virtual void
      create (sema_rel::foreign_key& fk)
      {
        using sema_rel::foreign_key;

        os << name (fk) << endl
           << "    FOREIGN KEY (";

        for (foreign_key::contains_iterator i (fk.contains_begin ());
             i != fk.contains_end ();
             ++i)
        {
          if (i != fk.contains_begin ())
            os << "," << endl
               << "                 ";

          os << quote_id (i->column ().name ());
        }

        string tn (table_name (fk));
        string tn_pad (tn.size (), ' ');

        os << ")" << endl
           << "    REFERENCES " << tn << " (";

        foreign_key::columns const& refs (fk.referenced_columns ());
        for (foreign_key::columns::const_iterator i (refs.begin ());
             i != refs.end ();
             ++i)
        {
          if (i != refs.begin ())
            os << "," << endl
               << "                 " << tn_pad;

          os << quote_id (*i);
        }

        os << ")";

        if (fk.on_delete () != foreign_key::no_action)
          on_delete (fk.on_delete ());

        if (!fk.not_deferrable ())
          deferrable (fk.deferrable ());
      }

      virtual string
      name (sema_rel::foreign_key& fk)
      {
        return quote_id (fk.name ());
      }

      virtual string
      table_name (sema_rel::foreign_key& fk)
      {
        return quote_id (fk.referenced_table ());
      }

      virtual void
      on_delete (sema_rel::foreign_key::action_type a)
      {
        using sema_rel::foreign_key;

        switch (a)
        {
        case foreign_key::no_action:
          break;
        case foreign_key::cascade:
          {
            os << endl
               << "    ON DELETE CASCADE";
            break;
          }
        case foreign_key::set_null:
          {
            os << endl
               << "    ON DELETE SET NULL";
            break;
          }
        }
      }

      virtual void
      deferrable (sema_rel::deferrable d)
      {
        os << endl
           << "    DEFERRABLE INITIALLY " << d;
      }

    protected:
      table_set* created_;
      bool& first_;
      bool first_data_;
    };

    struct create_index: trav_rel::index, common
    {
      typedef create_index base;

      enum index_type {unique, non_unique, all};

      create_index (common const& c, index_type t = all)
          : common (c), type_ (t) {}

      virtual void
      traverse (sema_rel::index& in)
      {
        if (type_ == unique &&
            in.type ().find ("UNIQUE") == string::npos &&
            in.type ().find ("unique") == string::npos)
          return;

        if (type_ == non_unique && (
              in.type ().find ("UNIQUE") != string::npos ||
              in.type ().find ("unique") != string::npos))
          return;

        pre_statement ();
        create (in);
        post_statement ();
      }

      virtual string
      name (sema_rel::index& in)
      {
        return quote_id (in.name ());
      }

      virtual string
      table_name (sema_rel::index& in)
      {
        return quote_id (static_cast<sema_rel::table&> (in.scope ()).name ());
      }

      virtual void
      columns (sema_rel::index& in)
      {
        using sema_rel::index;

        for (index::contains_iterator i (in.contains_begin ());
             i != in.contains_end ();
             ++i)
        {
          if (in.contains_size () > 1)
          {
            if (i != in.contains_begin ())
              os << ",";

            os << endl
               << "    ";
          }

          os << quote_id (i->column ().name ());

          if (!i->options ().empty ())
            os << ' ' << i->options ();
        }
      }

      virtual void
      create (sema_rel::index& in)
      {
        // Default implementation that ignores the method.
        //
        os << "CREATE ";

        if (!in.type ().empty ())
          os << in.type () << ' ';

        os << "INDEX " << name (in) << endl
           << "  ON " << table_name (in) << " (";

        columns (in);

        os << ")" << endl;

        if (!in.options ().empty ())
          os << ' ' << in.options () << endl;
      }

    protected:
      index_type type_;
    };

    struct create_table: trav_rel::table,
                         trav_rel::alter_table, // Override.
                         common
    {
      typedef create_table base;

      using trav_rel::table::names;

      create_table (emitter_type& e, ostream& os, schema_format f)
          : common (e, os, f) {}

      virtual void
      create_pre (sema_rel::qname const& table)
      {
        os << "CREATE TABLE " << quote_id (table) << " (";
      }

      virtual void
      create_post (sema_rel::table& t)
      {
        os << ")" << endl;

        if (!t.options ().empty ())
          os << " " << t.options () << endl;
      }

      virtual void
      create (sema_rel::table& t)
      {
        pre_statement ();
        create_pre (t.name ());

        instance<create_column> c (*this);
        instance<create_primary_key> pk (*this);

        // We will always follow a column, so set first to false.
        //
        bool f (false); // (Im)perfect forwarding.
        bool* pf (&f);  // (Im)perfect forwarding.
        instance<create_foreign_key> fk (*this, created_, pf);

        trav_rel::unames n;
        n >> c;
        n >> pk;
        n >> fk;

        names (t, n);

        create_post (t);
        post_statement ();

        // Create indexes.
        //
        {
          instance<create_index> in (*this);
          trav_rel::unames n (*in);
          names (t, n);
        }
      }

      // See if there are any undefined foreign keys that we need to
      // add with ALTER TABLE.
      //
      bool
      check_undefined_fk (sema_rel::table& t)
      {
        for (sema_rel::table::names_iterator i (t.names_begin ());
             i != t.names_end (); ++i)
        {
          if (i->nameable ().is_a<sema_rel::foreign_key> () &&
              !i->nameable ().count (db.string () + "-fk-defined"))
            return true;
        }
        return false;
      }

      virtual void
      traverse (sema_rel::table& t)
      {
        // By default add foreign keys referencing tables that haven't
        // yet been defined on the second pass.
        //
        if (pass_ == 1)
        {
          // In migration we always add foreign keys on pass 2.
          //
          if (!t.is_a<sema_rel::add_table> ())
            created_.insert (t.name ()); // Add it before to cover self-refs.

          create (t);
        }
        else
        {
          // Add undefined foreign keys.
          //
          if (check_undefined_fk (t))
          {
            pre_statement ();
            os << "ALTER TABLE " << quote_id (t.name ());

            instance<create_foreign_key> cfk (*this);
            trav_rel::unames n (*cfk);
            names (t, n);
            os << endl;

            post_statement ();
          }
        }
      }

      void
      pass (unsigned short p)
      {
        pass_ = p;
      }

    protected:
      unsigned short pass_;
      table_set created_;
    };

    struct create_model: trav_rel::model, common
    {
      typedef create_model base;

      create_model (emitter_type& e, ostream& os, schema_format f)
          : common (e, os, f) {}

      void
      pass (unsigned short p)
      {
        pass_ = p;
      }

    protected:
      unsigned short pass_;
    };

    //
    // Alter.
    //

    struct alter_column: trav_rel::alter_column,
                         trav_rel::add_column,
                         common
    {
      typedef alter_column base;

      alter_column (common const& c, bool pre, bool* first = 0)
          : common (c),
            pre_ (pre),
            first_ (first != 0 ? *first : first_data_),
            first_data_ (true),
            fl_ (false),
            def_ (c, fl_)
      {
      }

      alter_column (alter_column const& c)
          : root_context (), // @@ -Wextra
            context (),
            common (c),
            pre_ (c.pre_),
            first_ (&c.first_ != &c.first_data_ ? c.first_ : first_data_),
            first_data_ (c.first_data_),
            fl_ (false),
            def_ (c, fl_)
      {
      }

      virtual void
      alter_header ()
      {
        os << "ALTER COLUMN ";
      }

      virtual void
      alter (sema_rel::column& c)
      {
        // By default use the whole definition.
        //
        def_->create (c);
      }

      virtual void
      traverse (sema_rel::column& c)
      {
        // Relax (NULL) in pre and tighten (NOT NULL) in post.
        //
        if (pre_ != c.null ())
          return;

        if (first_)
          first_ = false;
        else
          os << ",";

        os << endl
           << "  ";
        alter_header ();
        alter (c);
      }

      virtual void
      traverse (sema_rel::alter_column& ac)
      {
        assert (ac.null_altered ());
        traverse (static_cast<sema_rel::column&> (ac));
      }

      virtual void
      traverse (sema_rel::add_column& ac)
      {
        // We initially add NOT NULL columns without default values as
        // NULL. Now, after the migration, we convert them to NOT NULL.
        //
        if (!ac.null () && ac.default_ ().empty ())
          traverse (static_cast<sema_rel::column&> (ac));
      }

    protected:
      bool pre_;
      bool& first_;
      bool first_data_;
      bool fl_; // (Im)perfect forwarding.
      instance<create_column> def_;
    };

    struct alter_table_common: trav_rel::alter_table, common
    {
      alter_table_common (emitter_type& e, ostream& os, schema_format f)
          : common (e, os, f) {}

      template <typename T>
      T*
      check (sema_rel::alter_table& at)
      {
        for (sema_rel::alter_table::names_iterator i (at.names_begin ());
             i != at.names_end (); ++i)
        {
          if (T* x = dynamic_cast<T*> (&i->nameable ()))
            return x;
        }
        return 0;
      }

      sema_rel::column*
      check_alter_column_null (sema_rel::alter_table& at, bool v)
      {
        for (sema_rel::alter_table::names_iterator i (at.names_begin ());
             i != at.names_end (); ++i)
        {
          using sema_rel::add_column;
          using sema_rel::alter_column;

          if (alter_column* ac = dynamic_cast<alter_column*> (&i->nameable ()))
          {
            if (ac->null_altered () && ac->null () == v)
              return ac;
          }

          // If we are testing for NOT NULL, also look for new columns that
          // we initially add as NULL and later convert to NOT NULL.
          //
          if (!v)
          {
            if (add_column* ac = dynamic_cast<add_column*> (&i->nameable ()))
            {
              if (!ac->null () && ac->default_ ().empty ())
                return ac;
            }
          }
        }
        return 0;
      }

      void
      pass (unsigned short p)
      {
        pass_ = p;
      }

    protected:
      unsigned short pass_;
    };

    struct alter_table_pre: alter_table_common
    {
      typedef alter_table_pre base;

      alter_table_pre (emitter_type& e, ostream& os, schema_format f)
          : alter_table_common (e, os, f) {}

      // Check if there will be any clauses in ALTER TABLE.
      //
      using alter_table_common::check;

      virtual bool
      check (sema_rel::alter_table& at)
      {
        // If changing the below test, make sure to also update tests
        // in database-specific code.
        //
        return
          check<sema_rel::drop_foreign_key> (at) ||
          check<sema_rel::add_column> (at) ||
          check_alter_column_null (at, true);
      }

      virtual void
      alter (sema_rel::alter_table& at)
      {
        // By default we generate all the alterations in a single ALTER TABLE
        // statement. Quite a few databases don't support this.
        //
        pre_statement ();
        os << "ALTER TABLE " << quote_id (at.name ());

        bool f (true);  // Shared first flag.
        bool* pf (&f);  // (Im)perfect forwarding.
        bool tl (true); // (Im)perfect forwarding.
        instance<create_column> cc (*this, tl, pf);
        instance<alter_column> ac (*this, tl, pf);
        instance<drop_foreign_key> dfk (*this, pf);
        trav_rel::unames n;
        n >> cc;
        n >> ac;
        n >> dfk;
        names (at, n);
        os << endl;

        post_statement ();
      }

      virtual void
      traverse (sema_rel::alter_table& at)
      {
        if (pass_ == 1)
        {
          // Drop unique indexes.
          //
          {
            drop_index::index_type it (drop_index::unique);
            instance<drop_index> in (*this, it);
            trav_rel::unames n (*in);
            names (at, n);
          }

          if (check (at))
            alter (at);
        }
        else
        {
          // Add non-unique indexes.
          //
          {
            create_index::index_type it (create_index::non_unique);
            instance<create_index> in (*this, it);
            trav_rel::unames n (*in);
            names (at, n);
          }
        }
      }
    };

    struct changeset_pre: trav_rel::changeset, common
    {
      typedef changeset_pre base;

      changeset_pre (emitter_type& e, ostream& os, schema_format f)
          : common (e, os, f) {}

      void
      pass (unsigned short p)
      {
        pass_ = p;
      }

    protected:
      unsigned short pass_;
    };

    struct alter_table_post: alter_table_common
    {
      typedef alter_table_post base;

      alter_table_post (emitter_type& e, ostream& os, schema_format f)
          : alter_table_common (e, os, f) {}

      // Check if there will be any clauses in ALTER TABLE.
      //
      using alter_table_common::check;

      virtual bool
      check (sema_rel::alter_table& at)
      {
        // If changing the below test, make sure to also update tests
        // in database-specific code.
        //
        return
          check<sema_rel::add_foreign_key> (at) ||
          check<sema_rel::drop_column> (at) ||
          check_alter_column_null (at, false);
      }

      virtual void
      alter (sema_rel::alter_table& at)
      {
        // By default we generate all the alterations in a single ALTER TABLE
        // statement. Quite a few databases don't support this.
        //
        pre_statement ();
        os << "ALTER TABLE " << quote_id (at.name ());

        bool f (true); // Shared first flag.
        bool* pf (&f); // (Im)perfect forwarding.
        bool fl (false); // (Im)perfect forwarding.
        instance<drop_column> dc (*this, pf);
        instance<alter_column> ac (*this, fl, pf);
        instance<create_foreign_key> fk (*this, pf);

        trav_rel::unames n;
        n >> dc;
        n >> ac;
        n >> fk;
        names (at, n);
        os << endl;

        post_statement ();
      }

      virtual void
      traverse (sema_rel::alter_table& at)
      {
        if (pass_ == 1)
        {
          // Drop non-unique indexes.
          //
          {
            drop_index::index_type it (drop_index::non_unique);
            instance<drop_index> in (*this, it);
            trav_rel::unames n (*in);
            names (at, n);
          }
        }
        else
        {
          if (check (at))
            alter (at);

          // Add unique indexes.
          //
          {
            create_index::index_type it (create_index::unique);
            instance<create_index> in (*this, it);
            trav_rel::unames n (*in);
            names (at, n);
          }
        }
      }
    };

    struct changeset_post: trav_rel::changeset, common
    {
      typedef changeset_post base;

      changeset_post (emitter_type& e, ostream& os, schema_format f)
          : common (e, os, f) {}

      virtual void
      traverse (sema_rel::changeset& m)
      {
        // Traverse named entities in the reverse order. This way we
        // drop them in the order opposite to creating.
        //
        for (sema_rel::changeset::names_iterator begin (m.names_begin ()),
               end (m.names_end ()); begin != end;)
          dispatch (*--end);
      }

      void
      pass (unsigned short p)
      {
        pass_ = p;
      }

    protected:
      unsigned short pass_;
    };

    //
    // Schema version table.
    //

    struct version_table: common
    {
      typedef version_table base;

      version_table (emitter_type& e, ostream& os, schema_format f)
          : common (e, os, f),
            table_ (options.schema_version_table ()[db]),
            qt_ (quote_id (table_)),
            qs_ (quote_string (options.schema_name ()[db])),
            qn_ (quote_id ("name")),
            qv_ (quote_id ("version")),
            qm_ (quote_id ("migration"))
      {
      }

      // Create the version table if it doesn't exist.
      //
      virtual void
      create_table () {}

      // Remove the version entry. Called after the DROP statements.
      //
      virtual void
      drop ()
      {
        pre_statement ();

        os << "DELETE FROM " << qt_ << endl
           << "  WHERE " << qn_ << " = " << qs_ << endl;

        post_statement ();
      }

      // Set the version. Called after the CREATE statements.
      //
      virtual void
      create (sema_rel::version) {}

      // Set the version and migration state to true. Called after
      // the pre migration statements.
      //
      virtual void
      migrate_pre (sema_rel::version v)
      {
        pre_statement ();

        os << "UPDATE " << qt_ << endl
           << "  SET " << qv_ << " = " << v << ", " << qm_ << " = 1" << endl
           << "  WHERE " << qn_ << " = " << qs_ << endl;

        post_statement ();
      }

      // Set migration state to false. Called after the post migration
      // statements.
      //
      virtual void
      migrate_post ()
      {
        pre_statement ();

        os << "UPDATE " << qt_ << endl
           << "  SET " << qm_ << " = 0" << endl
           << "  WHERE " << qn_ << " = " << qs_ << endl;

        post_statement ();
      }

    protected:
      sema_rel::qname table_;
      string qt_; // Quoted table.
      string qs_; // Quoted schema name string.
      string qn_; // Quoted name column.
      string qv_; // Quoted version column.
      string qm_; // Quoted migration column.
    };

    //
    // SQL output.
    //

    struct sql_emitter: emitter, virtual context
    {
      typedef sql_emitter base;

      virtual void
      pre ()
      {
        first_ = true;
      }

      virtual void
      line (const std::string& l)
      {
        if (first_ && !l.empty ())
          first_ = false;
        else
          os << endl;

        os << l;
      }

      virtual void
      post ()
      {
        if (!first_) // Ignore empty statements.
          os << ';' << endl
             << endl;
      }

    protected:
      bool first_;
    };

    struct sql_file: virtual context
    {
      typedef sql_file base;

      virtual void
      prologue ()
      {
      }

      virtual void
      epilogue ()
      {
      }
    };
  }
}

#endif // ODB_RELATIONAL_SCHEMA_HXX