File: mysql_table_editor.cpp

package info (click to toggle)
mysql-workbench 5.2.40%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 53,880 kB
  • sloc: cpp: 419,850; yacc: 74,784; xml: 54,510; python: 31,455; sh: 9,423; ansic: 4,736; makefile: 2,442; php: 529; java: 237
file content (1167 lines) | stat: -rw-r--r-- 35,037 bytes parent folder | download
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
/* 
 * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; version 2 of the
 * License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301  USA
 */

#include "stdafx.h"

#include "mysql_table_editor.h"
#include "grt/grt_dispatcher.h"
#include "grtdb/db_object_helpers.h"
#include "db.mysql/src/module_db_mysql.h"
#include "grt/validation_manager.h"

#include "base/string_utilities.h"

using namespace bec;
using namespace base;

MySQLTableColumnsListBE::MySQLTableColumnsListBE(MySQLTableEditorBE *owner)
  : bec::TableColumnsListBE(owner)
{
}

bool MySQLTableColumnsListBE::set_field(const NodeId &node, int column, const std::string &value)
{
  db_mysql_ColumnRef col;

  if (node.is_valid() && node[0] < real_count())
  {
    col= static_cast<MySQLTableEditorBE*>(_owner)->table()->columns().get(node[0]);
    if (!col.is_valid())
      return false;

    db_SimpleDatatypeRef columnType;
    switch ((MySQLColumnListColumns)column)
    {
    case Default:
      // If a default value is set then auto increment for a column doesn't make sense.
      if (!base::trim(value).empty())
      {
        AutoUndoEdit undo(_owner);

        bool result = TableColumnsListBE::set_field(node, column, value);
        col->autoIncrement(false);
        undo.end(
          strfmt(_("Set Default Value and Unset Auto Increment '%s.%s'"), _owner->get_name().c_str(),
            col->name().c_str()
          )
        );

        return result;
      }

      break;
    }
  }
  return TableColumnsListBE::set_field(node, column, value);
}

bool MySQLTableColumnsListBE::set_field(const ::bec::NodeId &node, int column, int value)
{
  db_mysql_ColumnRef col;
  
  if (node.is_valid() && node[0] < real_count())
  {
    col= static_cast<MySQLTableEditorBE*>(_owner)->table()->columns().get(node[0]);
    if (!col.is_valid())
      return false;

    db_SimpleDatatypeRef columnType;
    switch ((MySQLColumnListColumns)column)
    {
    case IsAutoIncrement:
      // Determine actually used column type first.
      if (col->userType().is_valid() && col->userType()->actualType().is_valid())
        columnType= col->userType()->actualType();
      else
        if (col->simpleType().is_valid() && col->simpleType()->group().is_valid())
          columnType= col->simpleType();
        
      if (columnType.is_valid() && columnType->group().is_valid())
      {
        // Allow removing the auto inc setting even for non-numeric columns so we can
        // switch that off *after* we changed the column type or for invalid/old models
        // which have an auto inc set for non-numeric columns.
        if (columnType->group()->name() == "numeric" || value == 0)
        {
          AutoUndoEdit undo(_owner);

          if (value)
          {
            // check if there's already a column with auto-increment set and unset them
            grt::ListRef<db_mysql_Column> columns(static_cast<MySQLTableEditorBE*>(_owner)->table()->columns());
            
            for (size_t c = columns.count(), i= 0; i < c; i++)
            {
              if (*columns[i]->autoIncrement() != 0 && col != columns[i])
              {
                columns[i]->autoIncrement(0);
              }
            }
          }
                    
          col->autoIncrement(value != 0);

          // If auto increment is enabled then reset any default value.
          if (col->autoIncrement() && !(*col->defaultValue()).empty())
            bec::ColumnHelper::set_default_value(col, "");

          // if this is a primary key and auto-inc was set, then we should move this to the
          // beginning of the pk index 
          if (value && *_owner->get_table()->isPrimaryKeyColumn(col))
          {
            db_IndexRef index(_owner->get_table()->primaryKey());
            size_t oindex= 0;
            bool found= false;

            for (size_t c= index->columns().count(), i= 0; i < c; i++)
            {
              if (index->columns()[i]->referencedColumn() == col)
              {
                found= true;
                oindex= i;
                break;
              }
            }
            if (found)
            {
              index->columns().reorder(oindex, 0);
            }
          }
          _owner->update_change_date();
          (*_owner->get_table()->signal_refreshDisplay())("column");
          undo.end(value ? 
            strfmt(_("Set Auto Increment '%s.%s'"), _owner->get_name().c_str(), col->name().c_str()) : 
            strfmt(_("Unset Auto Increment '%s.%s'"), _owner->get_name().c_str(), col->name().c_str()));
        }
      }
      return true;
    case IsAutoIncrementable:
      return false;
    }
  }
  return TableColumnsListBE::set_field(node, column, value);
}

bool MySQLTableColumnsListBE::get_field_grt(const ::bec::NodeId &node, int column, grt::ValueRef &value)
{
  db_mysql_ColumnRef col;
  
  if (node.is_valid())
  {
    if (node[0] < real_count())
      col= static_cast<MySQLTableEditorBE*>(_owner)->table()->columns().get(node[0]);

    switch ((MySQLColumnListColumns)column)
    {
    case IsAutoIncrement:
      if (col.is_valid())
        value= col->autoIncrement();
      else
        value= grt::IntegerRef(0);
      return true;
    case IsAutoIncrementable:
      value= grt::IntegerRef(0);
      if (col.is_valid() && col->simpleType().is_valid() && col->simpleType()->group().is_valid())
      {
        if (col->simpleType()->group()->name() == "numeric")
          value= grt::IntegerRef(1);
      }
      return true;
    case HasCharset:
      value= grt::IntegerRef(0);
      if (col.is_valid() && col->simpleType().is_valid())
      {
        if (col->simpleType()->group()->name() == "string" || col->simpleType()->group()->name() == "text"
            || col->simpleType()->name() == "ENUM")
          value= grt::IntegerRef(1);
      }
      return true;          
    }
  }
  return TableColumnsListBE::get_field_grt(node, column, value);
}

static bool can_be_timestamp(const char *value)
{
  if (*value == '\'')
    return true;
  
  // accept anything that looks like a date
  for (; *value; ++value)
    if (!(isdigit(*value) || *value == ':' || *value == '-' || *value == '.' || *value == ' '))
      return false;
  return true;
}


bec::MenuItemList MySQLTableColumnsListBE::get_popup_items_for_nodes(const std::vector<bec::NodeId> &nodes)
{
  bec::MenuItemList items = bec::TableColumnsListBE::get_popup_items_for_nodes(nodes);
  bec::MenuItem item;
  
  if (nodes.size() == 1)
  {
    grt::ListRef<db_Column> columns(static_cast<MySQLTableEditorBE*>(_owner)->table()->columns());
    const size_t idx = nodes.front()[0];

    db_ColumnRef col;
    if (idx < columns.count())
      col = columns.get(idx);

    if (col.is_valid() && col->simpleType().is_valid())
    {
      std::string type = col->simpleType()->name();
      
      if (type == "TIMESTAMP")
      {
        bool seen_current_ts = false;
        bool is_first_ts = false; // only the 1st TIMESTAMP column can have CURRENT_TIMESTAMP, unless all 
        // previous ones are set to 0 or a constant
        bool flag = false;
        
        GRTLIST_FOREACH(db_Column, columns, c)
        {
          if ((*c)->simpleType().is_valid() && (*c)->simpleType()->name() == "TIMESTAMP")
          {
            if (*c == col)
            {
              is_first_ts= !seen_current_ts;
              flag = true;
            }
            
            if (!((*c)->defaultValue() == "0" || can_be_timestamp((*c)->defaultValue().c_str())))
              seen_current_ts = true;

            // a column before some other TS column that is already marked as CURRENT_TIMESTAMP cannot become CURRENT_TS
            if (*c != col && flag && strstr((*c)->defaultValue().c_str(), "TIMESTAMP"))
              is_first_ts = false;
          }
        }

        item.caption = "Default 0";
        item.name    = "TSToolStripMenuItem";
        item.enabled = true;
        items.push_back(item);        

        item.caption = "Default CURRENT_TIMESTAMP";
        item.name    = "currentTSToolStripMenuItem";
        item.enabled = is_first_ts;
        items.push_back(item);
        
        item.caption = "Default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP";
        item.name    = "currentTSOnUpdateToolStripMenuItem";
        item.enabled = is_first_ts;
        items.push_back(item);        
      }
      else if (col->simpleType()->group()->name() == "numeric" ||
               col->simpleType()->group()->name() == "datetime")
      {
        item.caption = "Default 0";
        item.name    = "0ToolStripMenuItem";
        item.enabled = true;
        items.push_back(item);
      }
      else if (col->simpleType()->group()->name() == "string" ||
               col->simpleType()->group()->name() == "text")
      {
        item.caption = "Default ''";
        item.name    = "EmptyToolStripMenuItem";
        item.enabled = true;
        items.push_back(item);
      }
    }
  }
  return items;
}


bool MySQLTableColumnsListBE::activate_popup_item_for_nodes(const std::string &name, const std::vector<bec::NodeId> &orig_nodes)
{
  AutoUndoEdit undo(_owner);
  std::string value;
  bool changed= false;

  if (name == "TSToolStripMenuItem" || name == "0ToolStripMenuItem")
    value = "0";
  else if (name == "EmptyToolStripMenuItem")
    value = "''";
  else if (name == "currentTSToolStripMenuItem")
    value = "CURRENT_TIMESTAMP";
  else if (name == "currentTSOnUpdateToolStripMenuItem")
    value = "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP";

  if (!value.empty())
  {
    for (std::vector<bec::NodeId>::const_iterator iter= orig_nodes.begin();
         iter != orig_nodes.end(); ++iter)
    {
      if ((*iter)[0] < real_count())
      {
        db_ColumnRef col(_owner->get_table()->columns().get((*iter)[0]));
        
        if (col.is_valid())
        {
          col->defaultValue(value);
          changed= true;
        }
      }
    }
  }
  if (changed)
  {
    undo.end(_("Set Column Default"));
    _owner->do_partial_ui_refresh(TableEditorBE::RefreshColumnList);
    return true;
  }
  else
    undo.cancel();
  return TableColumnsListBE::activate_popup_item_for_nodes(name, orig_nodes);
}  

//--------------------------------------------------------------------------------


MySQLTableEditorBE::MySQLTableEditorBE(::bec::GRTManager *grtm, const db_mysql_TableRef &table, const db_mgmt_RdbmsRef &rdbms)
  : TableEditorBE(grtm, table, rdbms), _table(table), _columns(this), _partitions(this), _indexes(this)
{
}


std::vector<std::string> MySQLTableEditorBE::get_index_types()
{
  std::vector<std::string> index_types;

  index_types.push_back("INDEX");
  index_types.push_back("UNIQUE");
  index_types.push_back("FULLTEXT");
  index_types.push_back("SPATIAL");
  // these are special types for PK and FK
  index_types.push_back("PRIMARY");
//  index_types.push_back("FOREIGN");
  return index_types;
}

std::vector<std::string> MySQLTableEditorBE::get_index_storage_types()
{
  std::vector<std::string> index_types;

  index_types.push_back("BTREE");
  index_types.push_back("RTREE");
  index_types.push_back("HASH");
  
  return index_types;
}

std::vector<std::string> MySQLTableEditorBE::get_fk_action_options()
{
  std::vector<std::string> action_options;

  action_options.push_back("RESTRICT");
  action_options.push_back("CASCADE");
  action_options.push_back("SET NULL");
  action_options.push_back("NO ACTION");
  
  return action_options;
}

std::vector<std::string> MySQLTableEditorBE::get_engines_list()
{
  std::vector<std::string> engines;

  DbMySQLImpl *module= get_grt()->find_native_module<DbMySQLImpl>("DbMySQL");
  if (!module)
    throw std::runtime_error("Module DbMySQL could not be located");

  grt::ListRef<db_mysql_StorageEngine> engines_ret(module->getKnownEngines());

  for (size_t c= engines_ret.count(), i= 0; i < c; i++)
    engines.push_back(engines_ret[i]->name());

  return engines;
}

/**
 * Determines if the currently set engine supports foreign keys and reports the outcome to the caller.
 */
bool MySQLTableEditorBE::engine_supports_foreign_keys()
{
  grt::StringRef name = _table->tableEngine();
  if (name == "") // No engine set. Assume db default allows FKs.
    return true;
  
  db_mysql_StorageEngineRef engine = bec::TableHelper::get_engine_by_name(get_grt(), name);
  if (engine.is_valid())
    return engine->supportsForeignKeys() == 1;
  
  return false; // Don't know anything about this engine, so assume it doesn't support FKs.
}

static struct TableOption
{
  const char *option_name;
  const char *object_field;
  bool text;
} table_options[]= {
  {"PACK_KEYS",       "packKeys", false},
  {"PASSWORD",        "password", true},
  {"AUTO_INCREMENT",  "nextAutoInc", true},
  {"DELAY_KEY_WRITE", "delayKeyWrite", false},
  {"ROW_FORMAT",      "rowFormat", true},
  {"AVG_ROW_LENGTH",  "avgRowLength", true},
  {"MAX_ROWS",        "maxRows", true},
  {"MIN_ROWS",        "minRows", true},
  {"DATA DIRECTORY",  "tableDataDir", true},
  {"INDEX DIRECTORY", "tableIndexDir", true},
  {"UNION",           "mergeUnion", true},
  {"INSERT_METHOD",   "mergeInsert", true},
  {"ENGINE",          "tableEngine", false},
  {"CHARACTER SET",   "defaultCharacterSetName", false},
  {"COLLATE",         "defaultCollationName", false},
  {"CHECKSUM",        "checksum", false},
  {NULL, NULL, false}
};

void MySQLTableEditorBE::set_table_option_by_name(const std::string& name, const std::string& value)
{
  //g_message("%s('%s','%s')", __FUNCTION__, name.c_str(), value.c_str());
  bool found= false;

  for (size_t i= 0; table_options[i].option_name; i++)
  {
    if (name.compare(table_options[i].option_name) == 0)
    {
      if (_table.get_metaclass()->get_member_type(table_options[i].object_field).base.type == grt::IntegerType)
      {
        int ivalue= atoi(value.c_str());

        if (ivalue != *grt::IntegerRef::cast_from(_table.get_member(table_options[i].object_field)))
        {
          AutoUndoEdit undo(this);
          _table.set_member(table_options[i].object_field, grt::IntegerRef(ivalue));
          update_change_date();
          undo.end(strfmt(_("Change '%s' for '%s'"), name.c_str(), _table->name().c_str()));
        }
      }
      else
      {
        if (value != *grt::StringRef::cast_from(_table.get_member(table_options[i].object_field)))
        {
          if (table_options[i].text)
          {
            AutoUndoEdit undo(this, _table, table_options[i].object_field);

            update_change_date();
            _table.set_member(table_options[i].object_field, grt::StringRef(value));
            
            undo.end(strfmt(_("Change '%s' for '%s'"), name.c_str(), _table->name().c_str()));
          }
          else
          {
            AutoUndoEdit undo(this);
            _table.set_member(table_options[i].object_field, grt::StringRef(value));
            update_change_date();
            undo.end(strfmt(_("Change '%s' for '%s'"), name.c_str(), _table->name().c_str()));
          }

          if ("ENGINE" == name)
            bec::ValidationManager::validate_instance(_table, "chk_fk_lgc");
        }
      }
      found= true;
      break;
    }
  }

  if (found)
    return;

  if(name.compare("CHARACTER SET - COLLATE") == 0)
  { // shortcut that sets both CHARACTER SET and COLLATE separated by a - 
    if (value != get_table_option_by_name(name))
    {
      std::string charset, collation;
      parse_charset_collation(value, charset, collation);
      if (charset != *_table->defaultCharacterSetName() || collation != *_table->defaultCollationName())
      {
        RefreshUI::Blocker blocker(*this);
        AutoUndoEdit undo(this);
        set_table_option_by_name("CHARACTER SET", charset);
        set_table_option_by_name("COLLATE", collation);
        update_change_date();
        undo.end(strfmt(_("Change Charset/Collation for '%s'"), _table->name().c_str()));
      }
    }
  }
  else
    throw std::invalid_argument("Invalid option "+name);
}

std::string MySQLTableEditorBE::get_table_option_by_name(const std::string& name)
{
  if(name.compare("PACK_KEYS") == 0)
    return _table->packKeys();
  else if(name.compare("PASSWORD") == 0)
    return _table->password();
  else if(name.compare("AUTO_INCREMENT") == 0)
    return _table->nextAutoInc();
  else if(name.compare("DELAY_KEY_WRITE") == 0)
    return _table->delayKeyWrite().repr();
  else if(name.compare("ROW_FORMAT") == 0)
    return _table->rowFormat();
  else if(name.compare("AVG_ROW_LENGTH") == 0)
    return _table->avgRowLength();
  else if(name.compare("MAX_ROWS") == 0)
    return _table->maxRows();
  else if(name.compare("MIN_ROWS") == 0)
    return _table->minRows();
  else if(name.compare("CHECKSUM") == 0)
    return _table->checksum().repr();
  else if(name.compare("DATA DIRECTORY") == 0)
    return _table->tableDataDir();
  else if(name.compare("INDEX DIRECTORY") == 0)
    return _table->tableIndexDir();
  else if(name.compare("UNION") == 0)
    return _table->mergeUnion();
  else if(name.compare("INSERT_METHOD") == 0)
    return _table->mergeInsert();
  else if(name.compare("ENGINE") == 0)
    return _table->tableEngine();
  else if(name.compare("CHARACTER SET - COLLATE") == 0)
    return format_charset_collation(_table->defaultCharacterSetName().c_str(), _table->defaultCollationName().c_str());
  else if(name.compare("CHARACTER SET") == 0)
    return _table->defaultCharacterSetName();
  else if(name.compare("COLLATE") == 0)
    return _table->defaultCollationName();
  else
    throw std::invalid_argument("Invalid option "+name);
  return std::string("");
}


std::string MySQLTableEditorBE::get_all_triggers_sql() const
{
  std::string retval;

  retval.append("-- Trigger DDL Statements\n").append(
    strfmt("DELIMITER %s\n\n", _non_std_sql_delimiter.c_str())).append(
    "USE `").append(_table->owner()->name()).append("`").
    append(_non_std_sql_delimiter.c_str()).append("\n\n");

  grt::ListRef<db_mysql_Trigger> triggers= _table->triggers();
  size_t triggers_count= triggers.count();
  typedef std::map<int, db_mysql_TriggerRef> OrderedTriggers;
  typedef std::list<db_mysql_TriggerRef> UnorderedTriggers;
  OrderedTriggers ordered_triggers;
  UnorderedTriggers unordered_triggers; // triggers with duplicated sequence number. to upgrade old models smoothly, where sequence numbers are 0.

  for (size_t i= 0; i < triggers_count; ++i)
  {
    db_mysql_TriggerRef trigger= triggers.get(i);
    int sequenceNumber= trigger->sequenceNumber();
    if (ordered_triggers.find(sequenceNumber) == ordered_triggers.end())
      ordered_triggers[sequenceNumber]= trigger;
    else
      unordered_triggers.push_back(trigger);
  }

  //XXX fix parser so that it skips newlines before the trigger
  for (OrderedTriggers::iterator i= ordered_triggers.begin(), i_end= ordered_triggers.end(); i != i_end; ++i)
    retval.append(base::strip_text(i->second->sqlDefinition(), true, false)).append(_non_std_sql_delimiter).append("\n\n");

  for (UnorderedTriggers::iterator i= unordered_triggers.begin(), i_end= unordered_triggers.end(); i != i_end; ++i)
    retval.append(base::strip_text((*i)->sqlDefinition(), true, false)).append(_non_std_sql_delimiter).append("\n\n");

  return retval;
}




bool MySQLTableEditorBE::set_partition_type(const std::string &type)
{
  if (type.compare(*table()->partitionType())!=0)
  {
    if (type == "RANGE" || type == "LIST")
    {
      AutoUndoEdit undo(this);
      table()->partitionType(type);
      if (table()->partitionCount() == 0)
        table()->partitionCount(1);
      if (get_explicit_partitions())
        reset_partition_definitions(table()->partitionCount(), 
          get_explicit_subpartitions() ? *table()->subpartitionCount() : 0);
      update_change_date();
      undo.end(strfmt(_("Change Partition Type for '%s'"), get_name().c_str()));
      return true;
    }
    else if (type == "LINEAR HASH" || type == "HASH" || 
             type == "LINEAR KEY" || type == "KEY" || type == "")
    {
      AutoUndoEdit undo(this);
      table()->partitionType(type);
      if (table()->partitionCount() == 0)
        table()->partitionCount(1);
      table()->subpartitionCount(0);
      table()->subpartitionExpression("");
      table()->subpartitionType("");
      if (get_explicit_partitions())
        reset_partition_definitions(table()->partitionCount(), 0);
      update_change_date();
      undo.end(strfmt(_("Change Partition Type for '%s'"), get_name().c_str()));
      return true;
    }
  }
  return false;
}


std::string MySQLTableEditorBE::get_partition_type()
{
  return *table()->partitionType();
}


void MySQLTableEditorBE::set_partition_expression(const std::string &expr)
{
  AutoUndoEdit undo(this, table(), "partitionExpression");

  table()->partitionExpression(expr);
  
  update_change_date();
  undo.end(strfmt(_("Set Partition Expression for '%s'"), get_name().c_str()));
}


std::string MySQLTableEditorBE::get_partition_expression()
{
  return *table()->partitionExpression();
}


void MySQLTableEditorBE::set_partition_count(int count)
{
  AutoUndoEdit undo(this);
  if (count > 0)
    table()->partitionCount(count);
  else
    table()->partitionCount(1);
  if (get_explicit_partitions())
    reset_partition_definitions(table()->partitionCount(), 
                              get_explicit_partitions() ? *table()->subpartitionCount() : 0);
  update_change_date();
  undo.end(strfmt(_("Set Partition Count for '%s'"), get_name().c_str()));
}


int MySQLTableEditorBE::get_partition_count()
{
  return *table()->partitionCount();
}


bool MySQLTableEditorBE::set_subpartition_type(const std::string &type)
{
  if (*table()->partitionType() == "RANGE" || *table()->partitionType() == "LIST")
  {
    AutoUndoEdit undo(this, table(), "subpartitionType");

    table()->subpartitionType(type);
    
    update_change_date();
    undo.end(strfmt(_("Set Subpartition Type for '%s'"), get_name().c_str()));
    return true;
  }
  return false;
}


std::string MySQLTableEditorBE::get_subpartition_type()
{
  return *table()->subpartitionType();
}


bool MySQLTableEditorBE::set_subpartition_expression(const std::string &expr)
{
  if (*table()->partitionType() == "RANGE" || *table()->partitionType() == "LIST")
  {
    AutoUndoEdit undo(this, table(), "subpartitionExpression");

    table()->subpartitionExpression(expr);

    update_change_date();
    undo.end(strfmt(_("Set Subpartition Expression for '%s'"), get_name().c_str()));
    return true;
  }
  return false;
}


std::string MySQLTableEditorBE::get_subpartition_expression()
{
  return *table()->subpartitionExpression();
}


void MySQLTableEditorBE::set_subpartition_count(int count)
{
  if (*table()->partitionType() == "RANGE" || *table()->partitionType() == "LIST")
  {
    AutoUndoEdit undo(this);
    table()->subpartitionCount(count);
    if (get_explicit_subpartitions())
      reset_partition_definitions(table()->partitionCount(), table()->subpartitionCount());
    update_change_date();
    undo.end(strfmt(_("Set Subpartition Count for '%s'"), get_name().c_str()));
  }
}


int MySQLTableEditorBE::get_subpartition_count()
{
  return *table()->subpartitionCount();
}


void MySQLTableEditorBE::set_explicit_partitions(bool flag)
{
  if (flag != get_explicit_partitions())
  {
    AutoUndoEdit undo(this);
    if (flag)
    {
      if (table()->partitionCount() == 0)
      {
        table()->partitionCount(2);
      }
      reset_partition_definitions(table()->partitionCount(), table()->subpartitionCount());
    }
    else
      reset_partition_definitions(0, 0);
    update_change_date();
    undo.end(flag ? 
      strfmt(_("Manually Define Partitions for '%s'"), get_name().c_str()) :
      strfmt(_("Implicitly Define Partitions for '%s'"), get_name().c_str()));
  }
}


void MySQLTableEditorBE::set_explicit_subpartitions(bool flag)
{
  if (flag != get_explicit_subpartitions())
  {
    if (get_explicit_partitions())
    {
      AutoUndoEdit undo(this);
      if (flag)
      {
        if (table()->subpartitionCount() == 0)
        {
          table()->subpartitionCount(2);
        }
        reset_partition_definitions(table()->partitionCount(), table()->subpartitionCount());
      }
      else
        reset_partition_definitions(table()->partitionCount(), 0);
      update_change_date();
      undo.end(flag ? 
        strfmt(_("Manually Define SubPartitions for '%s'"), get_name().c_str()) :
        strfmt(_("Implicitly Define SubPartitions for '%s'"), get_name().c_str()));
    }
  }
}


bool MySQLTableEditorBE::get_explicit_partitions()
{
  return table()->partitionDefinitions().count() > 0;
}


bool MySQLTableEditorBE::get_explicit_subpartitions()
{
  return table()->partitionDefinitions().count() > 0 
    && table()->partitionDefinitions().get(0)->subpartitionDefinitions().count() > 0;
}

void MySQLTableEditorBE::reset_partition_definitions(int parts, int subparts)
{
  grt::ListRef<db_mysql_PartitionDefinition> pdefs(table()->partitionDefinitions());

  AutoUndoEdit undo(this);

  while ((int)pdefs.count() < parts)
  {
    db_mysql_PartitionDefinitionRef part(get_grt());

    part->owner(table());
    part->name(grt::StringRef::format("part%i", pdefs.count()));
    pdefs.insert(part);
  }

  while ((int)pdefs.count() > parts)
  {
    pdefs.remove(pdefs.count()-1);
  }

  for (size_t c= pdefs.count(), i= 0; i < c; i++)
  {
    grt::ListRef<db_mysql_PartitionDefinition> spdefs(pdefs[i]->subpartitionDefinitions());

    while ((int)spdefs.count() < subparts)
    {
      db_mysql_PartitionDefinitionRef part(get_grt());

      part->owner(pdefs[i]);
      part->name(grt::StringRef::format("subpart%i", i*subparts + spdefs.count()));
      spdefs.insert(part);
    }

    while ((int)spdefs.count() > subparts)
    {
      spdefs.remove(spdefs.count()-1);
    }
  }

  update_change_date();
  undo.end("Reset Partitioning");
}

static db_SimpleDatatypeRef get_simple_datatype(const db_ColumnRef &column)
{
  if (column->simpleType().is_valid())
    return column->simpleType();
  if (column->userType().is_valid())
    return column->userType()->actualType();
  return db_SimpleDatatypeRef();
}

bool MySQLTableEditorBE::check_column_referenceable_by_fk(const db_ColumnRef &column1, const db_ColumnRef &column2)
{  
  // from 5.1 manual: 
  // - Corresponding columns in the foreign key and the referenced key must have similar internal data types
  // inside InnoDB so that they can be compared without a type conversion. 
  // - The size and sign of integer types must be the same. 
  // - The length of string types need not be the same. 
  // - For nonbinary (character) string columns, the character set and collation must be the same.
  
  db_SimpleDatatypeRef stype1 = get_simple_datatype(column1);
  db_SimpleDatatypeRef stype2 = get_simple_datatype(column2);

  if (!stype1.is_valid() || !stype2.is_valid())
    return false;
  
  if (stype1 != stype2)
    return false;
  
  if (stype1->group()->name() == "numeric")
  {
    // check sign (size is already checked by previous if)
    bool unsigned1= column1->flags().get_index("UNSIGNED") != grt::BaseListRef::npos;
    bool unsigned2= column2->flags().get_index("UNSIGNED") != grt::BaseListRef::npos;

    if (unsigned1 != unsigned2)
      return false;
  }

  if (stype1->group()->name() == "string")
  {
    // check collation and charset
    if (column1->characterSetName() != column2->characterSetName() || column1->collationName() != column2->collationName())
      return false;
  }

  return true;
}

//--------------------------------------------------------------------------------


MySQLTablePartitionTreeBE::MySQLTablePartitionTreeBE(MySQLTableEditorBE *owner)
: _owner(owner)
{
}


bool MySQLTablePartitionTreeBE::set_field(const NodeId &node, int column, const std::string &value)
{
  db_mysql_PartitionDefinitionRef pdef(get_definition(node));

  if (!pdef.is_valid())
    return false;

  switch ((Columns)column)
  {
  case Name:
    if (pdef->name() != value)
    {
      AutoUndoEdit undo(_owner, pdef, "name");

      pdef->name(value);
      
      _owner->update_change_date();
      undo.end(strfmt(_("Change Partition Name for '%s'"), _owner->get_name().c_str()));
    }
    return true;

  case Value:
    if (pdef->value() != value)
    {
      AutoUndoEdit undo(_owner, pdef, "value");

      pdef->value(value);

      _owner->update_change_date();
      undo.end(strfmt(_("Change Partition Parameter for '%s'"), _owner->get_name().c_str()));
    }
    return true;

  case MinRows:
    if (pdef->minRows() != value)
    {
      AutoUndoEdit undo(_owner, pdef, "minRows");

      pdef->minRows(value);
      
      _owner->update_change_date();
      undo.end(strfmt(_("Change Partition Min Rows for '%s'"), _owner->get_name().c_str()));
    }
    return true;

  case MaxRows:
    if (pdef->maxRows() != value)
    {
      AutoUndoEdit undo(_owner, pdef, "maxRows");
      
      pdef->maxRows(value);

      _owner->update_change_date();
      undo.end(strfmt(_("Change Partition Max Rows for '%s'"), _owner->get_name().c_str()));
    }
    return true;

  case DataDirectory:
    if (pdef->dataDirectory() != value)
    {
      AutoUndoEdit undo(_owner, pdef, "dataDirectory");

      pdef->dataDirectory(value);

      _owner->update_change_date();
      undo.end(strfmt(_("Change Partition Data Directory for '%s'"), _owner->get_name().c_str()));
    }
    return true;

  case IndexDirectory:
    if (pdef->indexDirectory() != value)
    {
      AutoUndoEdit undo(_owner, pdef, "indexDirectory");

      pdef->indexDirectory(value);
      
      _owner->update_change_date();
      undo.end(strfmt(_("Change Partition Index Directory for '%s'"), _owner->get_name().c_str()));
    }
    return true;

  case Comment:
    if (pdef->comment() != value)
    {
      AutoUndoEdit undo(_owner, pdef, "comment");

      pdef->comment(value);

      _owner->update_change_date();
      undo.end(strfmt(_("Change Partition Comment for '%s'"), _owner->get_name().c_str()));
    }
    return true;
  }

  return false;
}


bool MySQLTablePartitionTreeBE::get_field_grt(const NodeId &node, int column, grt::ValueRef &value)
{
  db_mysql_PartitionDefinitionRef pdef(get_definition(node));

  if (!pdef.is_valid())
    return false;

  switch ((Columns)column)
  {
  case Name:
    value= pdef->name();
    return true;

  case Value:
    value= pdef->value();
    return true;

  case MinRows:
    value= pdef->minRows();
    return true;

  case MaxRows:
    value= pdef->maxRows();
    return true;

  case DataDirectory:
    value= pdef->dataDirectory();
    return true;

  case IndexDirectory:
    value= pdef->indexDirectory();
    return true;

  case Comment:
    value= pdef->comment();
    return true;
  }

  return false;
}


grt::Type MySQLTablePartitionTreeBE::get_field_type(const NodeId &node, int column)
{
  return grt::StringType;
}


db_mysql_PartitionDefinitionRef MySQLTablePartitionTreeBE::get_definition(const NodeId &node)
{
  if (node.depth() == 1)
  {
    if (node[0] < (int)_owner->table()->partitionDefinitions().count())
      return _owner->table()->partitionDefinitions()[node[0]];
  }
  else if (node.depth() == 2)
  {
    if (node[0] < (int)_owner->table()->partitionDefinitions().count())
    {
      db_mysql_PartitionDefinitionRef def(_owner->table()->partitionDefinitions()[node[0]]);

      if (node[1] < (int)def->subpartitionDefinitions().count())
        return def->subpartitionDefinitions()[node[1]];
    }
  }
  return db_mysql_PartitionDefinitionRef();
}



int MySQLTablePartitionTreeBE::count_children(const NodeId &parent)
{
  if (parent.depth() == 1)
  {
    db_mysql_PartitionDefinitionRef def(get_definition(parent));

    if (def.is_valid())
      return (int)def->subpartitionDefinitions().count();
  }
  else if (parent.depth() == 0)
    return _owner->table()->partitionDefinitions().count();

  return 0;
}


NodeId MySQLTablePartitionTreeBE::get_child(const NodeId &parent, int index)
{
  if (count_children(parent) > index)
    return NodeId(parent).append(index);

  throw std::logic_error("Invalid index");
}


//-------------------------------------------------------------------------------------------------

MySQLTableIndexListBE::MySQLTableIndexListBE(MySQLTableEditorBE *owner)
: IndexListBE(owner)
{
}


bool MySQLTableIndexListBE::set_field(const NodeId &node, int column, const std::string &value)
{
  if (!index_editable(get_selected_index()))
    return IndexListBE::set_field(node, column, value);

  db_mysql_IndexRef index(db_mysql_IndexRef::cast_from(get_selected_index()));

  if (!index.is_valid())
    return IndexListBE::set_field(node, column, value);

  switch (column)
  {
  case StorageType:
    if (value != *index->indexKind())
    {
      AutoUndoEdit undo(_owner, index, "indexKind");
      index->indexKind(value);
      undo.end(strfmt(_("Change Storage Type of Index '%s.%s'"), _owner->get_name().c_str(), index->name().c_str()));
    }
    return true;
  case RowBlockSize:
    if (atoi(value.c_str()) != *index->keyBlockSize())
    {
      AutoUndoEdit undo(_owner, index, "keyBlockSize");
      index->keyBlockSize(atoi(value.c_str()));
      undo.end(strfmt(_("Change Key Block Size of Index '%s.%s'"), _owner->get_name().c_str(), index->name().c_str()));
    }
    return true;
  case Parser:
    if (value != *index->withParser())
    {
      AutoUndoEdit undo(_owner, index, "withParser");
      index->withParser(value);
      undo.end(strfmt(_("Change Parser of Index '%s.%s'"), _owner->get_name().c_str(), index->name().c_str()));
    }
    return true;
  default:
    return IndexListBE::set_field(node, column, value);
  }
}


bool MySQLTableIndexListBE::get_field_grt(const NodeId &node, int column, grt::ValueRef &value)
{
  if ( node.is_valid() )
  {
    const bool existing_node = node.end() < real_count();
    
    switch (column)
    {
    case StorageType:
      value= existing_node ? db_mysql_IndexRef::cast_from(get_selected_index())->indexKind() : grt::StringRef("");
      return true;
    case RowBlockSize:
      value= existing_node ? grt::StringRef(db_mysql_IndexRef::cast_from(get_selected_index())->keyBlockSize().repr()) : grt::StringRef("");
      return true;
    case Parser:
      value= existing_node ? db_mysql_IndexRef::cast_from(get_selected_index())->withParser() : grt::StringRef("");
      return true;
    default:
      return IndexListBE::get_field_grt(node, column, value);
    }
  }
  return false;
}