Форум программистов, компьютерный форум, киберфорум
C++
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.83/6: Рейтинг темы: голосов - 6, средняя оценка - 4.83
1186 / 542 / 78
Регистрация: 01.07.2009
Сообщений: 3,517
1

Внутренняя организация базы данных

19.05.2012, 15:52. Показов 1216. Ответов 8
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Нужно написать небольшую консольную бд на с++, хотел бы посмотреть реальные примеры. Подкиньте парочку посмотреть пожалуйста
В инете конечно полно примеров БД на visual c++ (mfc например), но там ведь не очень честные бд - там львиная доля работы сделана библиотеками MS и там достаточно было лишь выбрать что мы хотим создать БД да слегка заполнить всё. Мне же нужен какой-то пример где есть все этапы разработки. До этого мне читали проектирование БД, а практика проводилась в MS Access так что сам я пока что бд не программировал.
Моя бд не должна быть слишком навороченной, ей предстоит всего-то создавать таблички (и записи конечно), удалять их. Искать записи ... это в принципе всё что требуется, по желанию можно будет расширить. В общем мне нужна бд где я смогу посмотреть на примере как организовывают хранение таблиц с информацией разных типов (char, int, double, date).
Или же хоть так на словах подскажите по теме пожалуйста, но лучше если будет пример

Добавлено через 18 часов 21 минуту
Не поверю что никто не писал бд на с++, вот не поверю и всё. Поделитесь знаниями в этой области пожалуйста Ато возникают вопросы как то же создание таблицы делать, нас ведь могут попросить создать таблицу как с двумя полями так и с 5 например, а типы то разные. Не знаю вот как правильно извратиться чтобы обработать это условие.

Добавлено через 4 часа 11 минут
Вот же беда. Раз никто не хочет делиться своей какой-либо старой бд то подскажите хоть как реализовать таблицы пожалуйста.
Задача: сделать поддержку SQL (очень примитивную). Тоесть моя бд должна поддерживать такой минимальный набор команд:
SQL
1
2
3
4
5
6
7
8
9
10
11
12
13
CREATE TABLE TEST(X INTEGER, Y VARCHAR(255));
CREATE TABLE TEST2(A INTEGER, B VARCHAR(255));
INSERT INTO TEST VALUES(1, "abcde");
INSERT INTO TEST VALUES(2, "defgh");
INSERT INTO TEST VALUES(4, "tersf");
INSERT INTO TEST2 VALUES(2, "abcde");
INSERT INTO TEST2 VALUES(3, "defgh");
INSERT INTO TEST2 VALUES(4, "tersf");
SELECT X FROM TEST;
SELECT X, Y FROM TEST;
SELECT * FROM TEST;
SELECT * FROM TEST,TEST2 WHERE X=A;
DELETE TABLE TEST;
Тоесть я должен как-то создавать таблицы с n полями. Но как мне реализовать это создание таблицы с n полями? Сделать шаблонный класс столбецТаблицы и при вызове CREATE создавать n объектов этого класса столбецТаблицы? Но как это сделать когда я заранее не знаю ни сколько таблиц мне подсунут ни их типы. Распарсить команду не проблема, но как дальше поступить с созданием таблицы ...что-то не могу придумать. Подскажите как в таких случаях делают.
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
19.05.2012, 15:52
Ответы с готовыми решениями:

Использование псевдопеременных: bd (3,5) = s, где bd - база данных, s - элемент базы данных, тогда с 3 по 5 элементы базы данных заменить на элемент s.
всем доброго времени суток! есть у меня класс bd, массив элементов этого класса table, а вот сам...

Организация базы данных
Приветствую всех и каждого! Перейду сразу к делу. Цель: создать приложение (сервер-клиенты)...

Организация базы данных
Возник такой вот вопрос Есть один проект где есть пользователи со всей структурой таблиц для них,...

Организация базы данных
Всем прив ) Подскажите пожалуйста как правильно сделать базу. У меня есть магазин в котором ххх...

8
В астрале
Эксперт С++
8049 / 4806 / 655
Регистрация: 24.06.2010
Сообщений: 10,562
19.05.2012, 18:36 2
Лучший ответ Сообщение было отмечено как решение

Решение

Вот писал когда-то... Это первый вариант того, что было. Затем допиливал, но сейчас этого варианта на руках нет. Может на работе остался - посмотрю.

code
C++
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
#include <vector>
#include <string>
#include <boost/any.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string.hpp>
#include <sstream>
#include <stdexcept>
#include <iostream>
#include <typeinfo>
#include <limits>
 
 
namespace my
{
    enum types_ {int_, string_, other_};
 
    class Holder
    {
    public:
        template<class T>
        Holder(const T& value, types_ type = other_):value_(value), type_name_(value_.type().name()), type_(type)
        {
        }
        const boost::any& getValue() const {return value_;}
        template<class T>
        void setValue(const T& val) {value_ = val;}
        void setType(const types_& tp) {type_ = tp;}
        const types_& getType() const {return type_;}
        const std::string& getSTDType() const {return type_name_;}
        std::string to_string(const types_& tp) const
        {
            std::string result;
            if (tp == string_)
            {
                result = boost::any_cast<std::string>(value_);
            }
            else if (tp == int_)
            {
                int val = boost::any_cast<int>(value_);
                result = boost::lexical_cast<std::string>(val);
            }
            else
            {
                throw std::runtime_error("Unknown type");
            }
            return result;
        }
        int to_int(const types_& tp) const
        {
            int val = 0;
            if (tp == int_)
            {
                val = boost::any_cast<int>(value_);
            }
            else if (tp == string_)
            {
                std::string result = boost::any_cast<std::string>(value_);
                try
                {
                    val = boost::lexical_cast<int>(result);
                }
                catch(const boost::bad_lexical_cast& e)
                {
                    throw std::runtime_error(std::string("Not integer in string: ") + e.what());
                }
            }
            else
            {
                throw std::runtime_error("Unknown type");
            }
            return val;
        }
        static boost::any from_string(const std::string& string)
        {
            int value = 0;
            try
            {
                value = boost::lexical_cast<int>(string);
            }
            catch (const boost::bad_lexical_cast& e)
            {
                return boost::any(string);
            }
            return boost::any(value);
        }
        static types_ type_from_string(const std::string& string)
        {
            types_ tp;
            if (string == "number")
            {
                tp = int_;
            }
            else if (string == "string")
            {
                tp = string_;
            }
            else
            {
                throw std::runtime_error("Unexpected type");
            }
            return tp;
        }
        static Holder value_from_type(const types_& tp)
        {
            Holder hld(0);
            if (tp == int_)
            {
                hld = Holder(0);
            }
            else if (tp == string_)
            {
                hld = Holder(std::string());
            }
            else
            {
                throw std::runtime_error("Unexpected type");
            }
            return hld;
        }
    private:
        boost::any value_;
        std::string type_name_;
        types_ type_;
    };
 
    class Table
    {
    public:
        typedef std::vector<Holder> Data;
        typedef std::vector<Data> TableData;
 
        explicit Table(const std::string& tbl_name):table_name_(tbl_name)
        {
        }
 
        const std::string& getName() const {return table_name_;}
 
        void create(const std::vector<std::string>& plhs, const std::vector<types_>& tps)
        {
            auto plh_iter = plhs.begin();
            auto tp_iter = tps.begin();
            Data dt;
            for(; plh_iter != plhs.end(); ++plh_iter, ++tp_iter)
            {
                dt.push_back(Holder(*plh_iter, *tp_iter));
            }
            matrix_.push_back(dt);
        }
 
        void insert(const std::vector<std::string>& plhs, const std::vector<boost::any>& values)
        {
            if (plhs.empty())
            {
                insert_(values);
            }
            else
            {
                insert_(plhs, values);
            }
        }
        
        std::string select(const std::vector<std::string>& plhs, const std::vector<std::string>& cond_plhs,
                    const std::vector<std::string>& conds, const std::vector<boost::any>& cond_vals)
        {
            std::string result;
            if (plhs.empty() && cond_plhs.empty())
            {
                result = select_();
            }
            else if (cond_plhs.empty())
            {
                result = select_(plhs);
            }
            else if (plhs.empty())
            {
                result = select_(cond_plhs, conds, cond_vals);
            }
            else
            {
                result = select_(plhs, cond_plhs, conds, cond_vals);
            }
            if ((plhs.empty() && result == select_headers()) || (!plhs.empty() && result == select_headers(plhs)) || result.empty())
            {
                result = "\nNo data fetched\n\n";
            }
            return result;
        }
 
        void add_alter(const std::vector<std::string>& plhs, const std::vector<types_>& types)
        {
            add_alter_(plhs, types);
        }
        
        void drop_alter(const std::vector<std::string>& plhs)
        {
            drop_alter_(plhs);
        }
 
        void alter(const std::vector<std::string>& plhs, const std::vector<types_>& types)
        {
            alter_(plhs, types);
        }
        
        void truncate()
        {
            check_table_empty();
            for (auto iter = matrix_.begin() + 1; iter != matrix_.end();)
            {
                matrix_.erase(iter);
            }
        }
        void update(const std::vector<std::string>& plhs, const std::vector<boost::any>& values, 
                    const std::vector<std::string>& cond_plhs, const std::vector<std::string>& opers,
                    const std::vector<boost::any>& cond_values)
        {
            check_table_empty();
            if (cond_plhs.empty())
            {
                update_(plhs, values);
            }
            else
            {
                update_(plhs, values, cond_plhs, opers, cond_values);
            }
        }
    private:
        std::string table_name_;
        TableData matrix_;
 
        std::string select_()
        {
            check_table_empty();
            std::ostringstream ost;
            ost << select_headers();
            std::for_each(matrix_.begin() + 1, matrix_.end(), [&ost, matrix_](const Data& dt)
            {
                auto iter = matrix_[0].begin();
                std::for_each(dt.begin(), dt.end(), [&ost, &iter](const Holder& hld)
                {
                    ost << hld.to_string(iter->getType()) << '\t';
                    ++iter;
                });
                ost << '\n';
            });
            return ost.str();
        }
 
        std::string select_(const std::vector<std::string>& plhs)
        {
            check_table_empty();
            std::ostringstream ost;
            ost << select_headers(plhs);
            std::for_each(matrix_.begin() + 1, matrix_.end(), [&ost, &matrix_, &plhs](const Data& dt)
            {
                auto iter = matrix_[0].begin();
                auto plh_iter = plhs.begin();
                std::for_each(dt.begin(), dt.end(), [&ost, &iter, &plh_iter, &plhs](const Holder& hld)
                {
                    if (iter->to_string(string_) == *plh_iter)
                    {
                        ost << hld.to_string(iter->getType()) << '\t';
                        ++plh_iter;
                    }
                    ++iter;
                });
                ost << '\n';
            });
            return ost.str();
        }
 
        std::string select_(const std::vector<std::string>& condition_placeholders, 
                           const std::vector<std::string>& conditions,
                           const std::vector<boost::any>& cond_values)
        {
            check_table_empty();
            std::ostringstream ost;
            ost << select_headers();
            std::for_each(matrix_.begin() + 1, matrix_.end(), [&condition_placeholders, &conditions, &cond_values, &ost, this]
                                                        (const Data& dt)
            {
                if (where(dt, condition_placeholders, conditions, cond_values))
                {
                    auto iter = matrix_[0].begin();
                    std::for_each(dt.begin(), dt.end(), [&ost, &iter](const Holder& hld)
                    {
                        ost << hld.to_string(iter->getType()) << '\t';
                        ++iter;
                    });
                    ost << '\n';
                }
            });
            return ost.str();
        }
        
        std::string select_(const std::vector<std::string>& plhs, 
                           const std::vector<std::string>& condition_plhs,
                           const std::vector<std::string>& conditions,
                           const std::vector<boost::any>& cond_values)
        {
            check_table_empty();
            std::ostringstream ost;
            ost << select_headers(plhs);
            std::for_each(matrix_.begin() + 1, matrix_.end(), [&plhs, &condition_plhs, &conditions, &cond_values, &ost, this]
                                                              (const Data& dt)
            {
                if (where(dt, condition_plhs, conditions, cond_values))
                {
                    auto iter = matrix_[0].begin();
                    auto plh_iter = plhs.begin();
                    std::for_each(dt.begin(), dt.end(), [&ost, &iter, &plh_iter](const Holder& hld)
                    {
                        if (*plh_iter == iter->to_string(string_))
                        {
                            ost << hld.to_string(iter->getType()) << '\t';
                            ++plh_iter;
                        }
                        ++iter;
                    });
                    ost << '\n';
                }
            });
            return ost.str();
        }
 
        void insert_(const std::vector<boost::any>& values)
        {
            check_table_empty();
            Data dt;
            auto iterator = matrix_[0].begin();
            for (auto iter = values.begin(); iter != values.end(); ++iter, ++iterator)
            {
                if (iterator->getType() == int_)
                {
                    dt.push_back(boost::any_cast<int>(*iter));
                }
                else
                {
                    dt.push_back(*iter);
                }
            }
            matrix_.push_back(dt);
        }
        
        void insert_(const std::vector<std::string>& plhs, const std::vector<boost::any>& values)
        {
            check_table_empty();
            Data dt;
            auto plh_iter = plhs.begin();
            auto val_iter = values.begin();
            for(auto iter = matrix_[0].begin(); iter != matrix_[0].end(); ++iter)
            {
                if (iter->to_string(string_) == *plh_iter)
                {
                    dt.push_back(*val_iter);
                    ++val_iter;
                    ++plh_iter;
                }
                else
                {
                    dt.push_back(Holder::value_from_type(iter->getType()));
                }
            }
            matrix_.push_back(dt);
        }
        
        void add_alter_(const std::vector<std::string>& plhs, const std::vector<types_>& types)
        {
            auto pl_iter = plhs.begin();
            auto tp_iter = types.begin();
            for (; pl_iter != plhs.end(); ++pl_iter, ++tp_iter)
            {
                add_alter_one_(*pl_iter, *tp_iter);
            }
        }
        
        void add_alter_one_(const std::string& plh, const types_& type)
        {
            if (matrix_.empty())
            {
                matrix_.push_back(Data());
            }
            auto iter = matrix_[0].insert(matrix_[0].end(), Holder(plh, type));
            for (auto iter_ = matrix_.begin() + 1; iter_ != matrix_.end(); ++iter_)
            {
                iter_->push_back(Holder::value_from_type(iter->getType()));
            }
        }
        
        void drop_alter_(const std::vector<std::string>& plhs)
        {
            check_table_empty();
            auto pl_iter = plhs.begin();
            for (auto iter = matrix_[0].begin(); iter != matrix_[0].end();)
            {
                if (iter->to_string(string_) == *pl_iter)
                {
                    size_t idx = std::distance(matrix_[0].begin(), iter);
                    for (auto itr = matrix_.begin() + 1; itr != matrix_.end(); ++itr)
                    {
                        itr->erase(itr->begin() + idx); 
                    }
                    iter = matrix_[0].erase(iter);
                    ++pl_iter;
                }
                else
                {
                    ++iter;
                }
            }
            if (select_headers() == "\n\n\n")
            {
                matrix_.clear();
            }
        }
        
        void alter_(const std::vector<std::string>& plhs, const std::vector<types_>& types)
        {
            check_table_empty();
            auto pl_iter = plhs.begin();
            auto tp_iter = types.begin();
            for (auto iter = matrix_[0].begin(); iter != matrix_[0].end(); ++iter)
            {
                if (iter->to_string(string_) == *pl_iter)
                {
                    size_t idx = std::distance(matrix_[0].begin(), iter);
                    for (auto itr = matrix_.begin() + 1; itr != matrix_.end(); ++itr)
                    {
                        if (*tp_iter == string_)
                        {
                            try
                            {
                                (itr->begin() + idx)->setValue((itr->begin() + idx)->to_string(iter->getType()));
                            }
                            catch(const std::exception& e)
                            {
                                (itr->begin() + idx)->setValue(std::string());
                            }
                        }
                        else if (*tp_iter == int_)
                        {
                            try
                            {
                                (itr->begin() + idx)->setValue((itr->begin() + idx)->to_int(iter->getType()));
                            }
                            catch (const std::exception& e)
                            {
                                (itr->begin() + idx)->setValue(0);
                            }
                        }
                        else
                        {
                            throw std::runtime_error("Unexpected type");
                        }
                    }
                    iter->setType(*tp_iter);
                    ++tp_iter;
                    ++pl_iter;
                }
            }
        }
        
        void update_(const std::vector<std::string>& plhs, const std::vector<boost::any>& values)
        {
            std::for_each(matrix_.begin() + 1, matrix_.end(), [&plhs, &values, &matrix_](Data& dt)
            {
                auto iter = matrix_[0].begin();
                auto pl_iter = plhs.begin();
                auto val_iter = values.begin();
                std::for_each(dt.begin(), dt.end(), [&iter, &pl_iter, &val_iter](Holder& hld)
                {
                    if (iter->to_string(string_) == *pl_iter)
                    {
                        hld.setValue(*val_iter);
                        ++pl_iter;
                        ++val_iter;
                    }
                    ++iter;
                });
            });
        }
        
        void update_(const std::vector<std::string>& plhs, const std::vector<boost::any>& values, 
                    const std::vector<std::string>& cond_plhs, const std::vector<std::string>& cond_opers,
                    const std::vector<boost::any>& cond_values)
        {
            std::for_each(matrix_.begin() + 1, matrix_.end(), [&plhs, &values, &cond_plhs, &cond_opers, &cond_values, this]
                                                              (Data& dt)
            {
                if (where(dt, cond_plhs, cond_opers, cond_values))
                {
                    auto pl_iter = plhs.begin();
                    auto val_iter = values.begin();
                    auto iter = matrix_[0].begin();
                    std::for_each(dt.begin(), dt.end(), [&pl_iter, &val_iter, &iter](Holder& hld)
                    {
                        if (iter->to_string(string_) == *pl_iter)
                        {
                            hld.setValue(*val_iter);
                            ++pl_iter;
                            ++val_iter;
                        }
                        ++iter;
                    });
                }
            });
        }
 
        std::string select_headers() const
        {
            std::ostringstream ost;
            ost << '\n';
            std::for_each(matrix_[0].begin(), matrix_[0].end(), [&ost](const Holder& hld)                 
            {
                ost << hld.to_string(string_) << '\t';
            });
            ost << "\n\n";
            return ost.str();
        }
 
        std::string select_headers(const std::vector<std::string>& plhs) const
        {
            std::ostringstream ost;
            ost << '\n';
            auto iter = plhs.begin();
            auto end_iter = plhs.end();
            std::for_each(matrix_[0].begin(), matrix_[0].end(), [&ost, &iter, &end_iter](const Holder& hld)
            {
                if (iter != end_iter)
                {
                    if (hld.to_string(string_) == *iter)
                    {
                        ost << hld.to_string(string_) << '\t';
                        ++iter;
                    }
                }
            });
            ost << "\n\n";
            return ost.str();
        }
 
        bool where(const Data& dt,
                   const std::vector<std::string>& condition_plhs,
                   const std::vector<std::string>& conditions,
                   const std::vector<boost::any>& cond_values)
        {
            bool flg = true;
            auto intern_plh_iter = matrix_[0].begin();
            auto cond_plh_iter = condition_plhs.begin();
            auto cond_iter = conditions.begin();
            auto cond_val_iter = cond_values.begin();
            auto data_iter = dt.begin();
            for (; intern_plh_iter != matrix_[0].end(); ++intern_plh_iter, ++data_iter)
            {
                if (cond_plh_iter == condition_plhs.end())
                {
                    break;
                }
                if (*cond_plh_iter == intern_plh_iter->to_string(string_))
                {
                    if (intern_plh_iter->getType() == string_)
                    {
                        if (!compare(data_iter->to_string(string_), *cond_iter, boost::any_cast<std::string>(*cond_val_iter)))
                        {
                            flg = false;
                        }
                    }
                    else if (intern_plh_iter->getType() == int_)
                    {
                        if (!compare(data_iter->to_int(int_), *cond_iter, boost::any_cast<int>(*cond_val_iter)))
                        {
                            flg = false;
                        }
                    }
                    if (flg == false)
                    {
                        return flg;
                    }
                    ++cond_plh_iter;
                    ++cond_iter;
                    ++cond_val_iter;
                }
            }
            return flg;
        }
 
        template<class T>
        bool compare(const T& first, const std::string& oper, const T& second)
        {
            bool flg = false;
            if (oper == "=")
            {
                flg = first == second;
            }
            else if (oper == "!=")
            {
                flg = first != second;
            }
            else if (oper == "<")
            {
                flg = first < second;
            }
            else if (oper == ">")
            {
                flg = first > second;
            }
            else if (oper == "<=")
            {
                flg = first <= second;
            }
            else if (oper == ">=")
            {
                flg = first >= second;
            }
            else
            {
                throw std::runtime_error("Only simple conditions allowed");
            }
            return flg;
        }
 
        void check_table_empty()
        {
            if (matrix_.empty())
            {
                throw std::runtime_error("Table is empty");
            }
        }
    };
    
    struct TableCmpByTblName
    {
    public:
        TableCmpByTblName(const std::string& tbl_name):
            table_name(tbl_name)
        {
        }
        bool operator () (const Table& tbl)
        {
            return table_name == tbl.getName();
        }
    private:
        std::string table_name;
    };
 
    class DataBase
    {
        enum commands_enum {create_, insert_, delete_, select_};
    public:
        DataBase()
        {
        }
        void create_tbl(const std::string& tbl_name, const std::vector<std::string>& plhs, 
                    const std::vector<types_>& tps)
        {
            check_table_exist(tbl_name);
            auto iter = db.insert(db.end(), Table(tbl_name));
            iter->create(plhs, tps);
        }
        void insert(const std::string& tbl_name, const std::vector<std::string>& plhs, 
                    const std::vector<boost::any>& values)
        {
            check_db_empty();
            auto iter = find_table_by_name(tbl_name);
            iter->insert(plhs, values);
        }
        std::string select(const std::string& tbl_name, const std::vector<std::string>& plhs,
                           const std::vector<std::string>& condition_placeholders,
                           const std::vector<std::string>& conditions,
                           const std::vector<boost::any>& cond_values)
        {
            check_db_empty();
            auto iter = find_table_by_name(tbl_name);
            return iter->select(plhs, condition_placeholders, conditions, cond_values);
        }
        void add_alter(const std::string& tbl_name, const std::vector<std::string>& plhs, const std::vector<types_>& types)
        {
            check_db_empty();
            auto iter = find_table_by_name(tbl_name);
            iter->add_alter(plhs, types);
        }
        void drop_alter(const std::string& tbl_name, const std::vector<std::string>& plhs)
        {
            check_db_empty();
            auto iter = find_table_by_name(tbl_name);
            iter->drop_alter(plhs);
        }
        void alter(const std::string& tbl_name, const std::vector<std::string>& plhs, const std::vector<types_>& types)
        {
            check_db_empty();
            auto iter = find_table_by_name(tbl_name);
            iter->alter(plhs, types);
        }
        void drop(const std::string& tbl_name)
        {
            check_db_empty();
            auto iter = find_table_by_name(tbl_name);
            db.erase(iter);
        }
        void truncate(const std::string& tbl_name)
        {
            check_db_empty();
            auto iter = find_table_by_name(tbl_name);
            iter->truncate();
        }
        void update(const std::string& tbl_name, const std::vector<std::string>& plhs, const std::vector<boost::any>& values,
                    const std::vector<std::string>& cond_plhs, const std::vector<std::string>& cond_opers, 
                    const std::vector<boost::any>& cond_values)
        {
            check_db_empty();
            auto iter = find_table_by_name(tbl_name);
            iter->update(plhs, values, cond_plhs, cond_opers, cond_values);
        }
    private:
        std::vector<Table> db;
        std::vector<Table>::iterator find_table_by_name(const std::string& tbl_name)
        {
            std::vector<Table>::iterator iter = std::find_if(db.begin(), db.end(), TableCmpByTblName(tbl_name));
            if (iter == db.end())
            {
                throw std::logic_error("Table doesn`t exist");
            }
            return iter;
        }
        void check_db_empty() const
        {
            if (db.size() == 0)
            {
                throw std::logic_error("Database is empty");
            }
        }
        void check_table_exist(const std::string& tbl_name)
        {
            try
            {
                find_table_by_name(tbl_name);
            }
            catch(const std::logic_error& e)
            {
                return;
            }
            throw std::runtime_error("Table is allready exist");
        }
    };
}
 
static my::DataBase DataBase_;
 
class Program
{
public:
    static void process(const std::string& comm_string, std::ostream& os = std::cout)
    {
        Program prog;
        if (comm_string.empty())
        {
            prog.help();
            throw std::runtime_error("Command string shouldn`t be empty");
        }
        try
        {
            const std::string delims = " ,:";
            std::vector<std::string> commands;
            boost::algorithm::split(commands, comm_string, boost::is_any_of(delims), boost::token_compress_on);
            std::string table_name;
            std::vector<std::string> plhs;
            std::vector<boost::any> values;
            if (commands.at(0) == "create")
            {
                prog.create(commands);
            }
            else if (commands.at(0) == "insert")
            {
                prog.insert(commands);
            }
            else if (commands.at(0) == "select")
            {
                os << prog.select(commands) << '\n';
            }
            else if (commands.at(0) == "help")
            {
                prog.help();
            }
            else if (commands.at(0) == "alter")
            {
                prog.alter(commands);
            }
            else if (commands.at(0) == "drop")
            {
                prog.drop(commands);
            }
            else if (commands.at(0) == "truncate")
            {
                prog.truncate(commands);
            }
            else if (commands.at(0) == "update")
            {
                prog.update(commands);
            }
            else
            {
                prog.help();
                throw std::runtime_error("Sorry. Unimplemented ability");
            }
        }
        catch (const std::out_of_range& e)
        {
            throw std::runtime_error(std::string("Wrong command") + "\n" + comm_string);
        }
        catch (const std::exception& e)
        {
            throw std::runtime_error(std::string(e.what()) + "\n" + comm_string);
        }
    }
private:
    void create(const std::vector<std::string>& commands)
    {
        if (commands.size() < 4)
        {
            throw std::runtime_error("Wrong create command");
        }
        std::string table_name = commands.at(1);
        std::vector<std::string> plhs;
        std::vector<my::types_> tps;
        for (std::vector<std::string>::const_iterator iter = commands.begin() + 2; iter != commands.end();)
        {
            plhs.push_back(*iter);
            ++iter;
            tps.push_back(my::Holder::type_from_string(*iter));
            ++iter;
        }
        DataBase_.create_tbl(table_name, plhs, tps);
    }
    void insert(const std::vector<std::string>& commands)
    {
        if (commands.at(1) != "into" || commands.size() < 5)
        {
            throw std::runtime_error("Wrong insert command");
        }
        std::string table_name = commands.at(2);
        auto iter = commands.begin() + 2;
        std::vector<std::string> plhs;
        if (*(++iter) != "values")
        {
            for (; *iter != "values"; ++iter)
            {
                plhs.push_back(*iter);
            }
        }
        if (*iter != "values")
        {
            throw std::runtime_error("Wrong insert command");
        }
        ++iter;
        std::vector<boost::any> values;
        for(; iter != commands.end(); ++iter)
        {
            values.push_back(my::Holder::from_string(*iter));
        }
        DataBase_.insert(table_name, plhs, values);
    }
 
    std::string select(const std::vector<std::string>& commands) const
    {
        if (commands.size() < 4)
        {
            throw std::runtime_error("Wrong select command");
        }
        std::vector<std::string> plhs;
        auto iter = commands.begin() + 1;
        if (*iter != "*")
        {
            for (; *iter != "from"; ++iter)
            {
                plhs.push_back(*iter);
            }
            ++iter;
        }
        else
        {
            iter += 2;
        }
        std::string table_name = *iter;
        std::vector<std::string> cond_plhs;
        std::vector<std::string> opers;
        std::vector<boost::any> cond_values;
        ++iter;
        if (iter != commands.end() && *iter == "where")
        {
            ++iter;
            for (; iter != commands.end();)
            {
                cond_plhs.push_back(*iter);
                ++iter;
                opers.push_back(*iter);
                ++iter;
                cond_values.push_back(my::Holder::from_string(*iter));
                ++iter;
            }
        }
        return DataBase_.select(table_name, plhs, cond_plhs, opers,
                     cond_values);
    }
    void alter(const std::vector<std::string>& commands)
    {
        if (commands.size() < 4)
        {
            throw std::runtime_error("Wrong alter command");
        }
        std::string table_name = commands.at(1);
        std::vector<std::string> plhs;
        std::vector<my::types_> types;
        if (commands.at(2) == "add")
        {
            for (auto iter = commands.begin() + 3; iter != commands.end();)
            {
                plhs.push_back(*iter);
                ++iter;
                types.push_back(my::Holder::type_from_string(*iter));
                ++iter;
            }
            DataBase_.add_alter(table_name, plhs, types);
        }
        else if (commands.at(2) == "drop")
        {
            plhs = std::vector<std::string>(commands.begin() + 3, commands.end());
            DataBase_.drop_alter(table_name, plhs);
        }
        else if (commands.at(2) == "alter")
        {
            for (auto iter = commands.begin() + 3; iter != commands.end();)
            {
                plhs.push_back(*iter);
                ++iter;
                types.push_back(my::Holder::type_from_string(*iter));
                ++iter;
            }
            DataBase_.alter(table_name, plhs, types);
        }
    }
    void drop(const std::vector<std::string>& commands)
    {
        if (commands.size() < 2)
        {
            throw std::runtime_error("Wrond drop command");
        }
        std::string table_name = commands.at(1);
        DataBase_.drop(table_name);
    }
    void truncate(const std::vector<std::string>& commands)
    {
        if (commands.size() < 2)
        {
            throw std::runtime_error("Wrong truncate command");
        }
        std::string table_name = commands.at(1);
        DataBase_.truncate(table_name);
    }
    void update(const std::vector<std::string>& commands)
    {
        if (commands.size() < 6)
        {
            throw std::runtime_error("Wrong update command");
        }
        std::string table_name = commands.at(1);
        if (commands.at(2) != "set")
        {
            throw std::runtime_error("Wrong update command");
        }
        std::vector<std::string> plhs;
        std::vector<boost::any> values;
        std::vector<std::string> cond_plhs;
        std::vector<std::string> cond_opers;
        std::vector<boost::any> cond_values;
        auto iter = commands.begin() + 3;
        for (; iter != commands.end() && *iter != "where";)
        {
            plhs.push_back(*iter);
            ++iter;
            if (*iter != "=")
            {
                throw std::runtime_error("Wrong update command");
            }
            ++iter;
            values.push_back(my::Holder::from_string(*iter));
            ++iter;
        }
        if (iter != commands.end() && *iter == "where")
        {
            ++iter;
            for (; iter != commands.end();)
            {
                cond_plhs.push_back(*iter);
                ++iter;
                cond_opers.push_back(*iter);
                ++iter;
                cond_values.push_back(my::Holder::from_string(*iter));
                ++iter;
            }
        }
        DataBase_.update(table_name, plhs, values, cond_plhs, cond_opers, cond_values);
    }
    void help()
    {
        std::cout << "----------------HELP-------------------\n\n";
        std::cout << "Simple database 1.0\n";
        std::cout << "Commands: create, insert, select, alter, drop, update, truncate\n";
        std::cout << "Examples of usage\n";
        std::cout << "Example of create: create tbl1 id:number, name:string\n";
        std::cout << "Command create table named tbl1 with fields id with type number and name with type string\n";
        std::cout << "Example of insert: insert into tbl1 values 1, a\n";
        std::cout << "Command insert in table named tbl1 value 1 in id and a in name\n";
        std::cout << "Example of insert: insert into tbl1 id values 1\n";
        std::cout << "Command insert in table named tbl1 values 1 in id and null in name (for string null is empty string)\n";
        std::cout << "Example of select: select * from tbl1\n";
        std::cout << "Command select values from all fields of tbl1\n";
        std::cout << "Example of select: select * from tbl1 where id = 1\n";
        std::cout << "Command select values from all fields of tbl1 where value of field id = 1\n";
        std::cout << "Example of select: select id from tbl1 where name = a\n";
        std::cout << "Command select values from field if of tbl1 where values of field name = a\n";
        std::cout << "Example of alter: alter tbl1 add value:string\n";
        std::cout << "Command add to table field value with type string\n";
        std::cout << "Example of alter: alter tbl1 drop value\n";
        std::cout << "Command drop from table column named values\n";
        std::cout << "Example of alter: alter tbl1 alter value:number\n";
        std::cout << "Command change type of field value to number\n";
        std::cout << "Example of drop: drop tbl1\n";
        std::cout << "Command drop all table. After this command table is destroyed\n";
        std::cout << "Example of truncate: truncate tbl1\n";
        std::cout << "Command drop all values in the table\n";
        std::cout << "Example of update: update tbl1 set id = 1\n";
        std::cout << "Command set value of field named id in 1 in all table\n";
        std::cout << "Example of update: update tbl1 set id = 1 where name = a\n";
        std::cout << "Command set value of field named id in 1 if value of field name in this row = a\n";
        std::cout << "IN THIS VERSION SPACES IN CONDITIONS FOR WHERE ARE OBLIGATORY\n";
        std::cout << "Thanks. Good luck\n";
        std::cout << "----------------------------------------\n\n";
    }
    static my::DataBase DataBase_;
};
 
my::DataBase Program::DataBase_;
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include "db.hpp"
 
int main()
{
    std::string comm;
    while (std::cout << "Enter command\n" && std::getline(std::cin, comm) && (comm != "exit" && comm != "quit"))
    {
        try
        {
            Program::process(comm);
        }
        catch(const std::runtime_error& e)
        {
            std::cerr << "ProgError: " << e.what() << '\n';
        }
    }
}
3
1186 / 542 / 78
Регистрация: 01.07.2009
Сообщений: 3,517
20.05.2012, 00:36  [ТС] 3
Блин, boost, а его нельзя использовать, а именно от него вижу использованы RTTI механизми, с помощью которых подозреваю и делалось всё. Я то тоже увидев задание сразу же подумал "и как же это реализовать то, ведь нужен RTTI механизм который позволит создавать объекты передавая строку с указанием типа". Есть ещё какие-то хитрые идеи как это сделать не выходя за рамки си++?
У меня возникала безумная идея распарсивать строку и потом делать что-то типа
C++
1
2
3
4
if(string=="INTEGER")
 BD->Add(Table<int>);
else if(string=="DOUBLE")
 BD->Add(Table<double);
быдлокод конечно, но ничего лучше в голову не лезет. Это ещё как подумаю что это нужно запоминать какие типы подсунули да контролировать что вместо int при добавлении данных не сунут double или string ... Эх, плохо когда просят сделать что-то и ограничивают в возможностях. По-моему неправильно это когда говорят (не прямым текстом конечно) "да так хорошую бд любой дурак сделает, а ты напиши нам плохую, которая никуда не годится, но сам, и не выходи за рамки с++. STL так уж и быть разрешаем тебе, радуйся. Весь год не разрешали же, а тут пользуйся всласть." Но что поделать, таковое задание. Может у кого есть идеи получше? Ещё думаю может как-то применить typeinfo что в с++, ато больше ведь толком механизмов RTTI у с++ и нету.

Добавлено через 4 минуты
*Мне ещё SQL не читали (вот будут с осени), что должно сделать SELECT ? Я понимаю что выбрать что-то как-то и, вероятно, распечатать, но можно чуть подробнее по коду в этом моём примере (на вики я уже ходил), до булевой алгебры опускаться не надо, а так в двух словах что будет делать это:
SQL
1
2
3
4
SELECT X FROM TEST;
SELECT X, Y FROM TEST;
SELECT * FROM TEST;
SELECT * FROM TEST,TEST2 WHERE X=A;
0
Каратель
Эксперт С++
6609 / 4028 / 401
Регистрация: 26.03.2010
Сообщений: 9,273
Записей в блоге: 1
20.05.2012, 02:57 4
Лучший ответ Сообщение было отмечено как решение

Решение

Цитата Сообщение от Gepar Посмотреть сообщение
что должно сделать SELECT ?
произвести отбор/выборку данных

Цитата Сообщение от Gepar Посмотреть сообщение
SELECT X FROM TEST
выбрать поле Х из таблицы TEST (будут выбраны все записи)
Цитата Сообщение от Gepar Посмотреть сообщение
SELECT X, Y FROM TEST;
выбрать поля Х, Y из таблицы TEST (будут выбраны все записи)
Цитата Сообщение от Gepar Посмотреть сообщение
SELECT * FROM TEST
выбрать ВСЕ поля из из таблицы TEST (будут выбраны все записи)
Цитата Сообщение от Gepar Посмотреть сообщение
SELECT * FROM TEST,TEST2 WHERE X=A;
выбрать ВСЕ поля из из таблицы TEST (будут выбраны все записи у которых значение поля X равно А)

Добавлено через 1 минуту

Не по теме:

Цитата Сообщение от Gepar Посмотреть сообщение
Распарсить команду не проблема
но тем неменее многие СУБД не в состоянии указать точную ошибку при неправильном запросе;)



Добавлено через 5 минут
Цитата Сообщение от Gepar Посмотреть сообщение
и потом делать что-то типа
вот и реализуй - базовый тип от которого наследуються тип целого, строки и т.д.

Добавлено через 1 минуту
Цитата Сообщение от Gepar Посмотреть сообщение
а контролировать что вместо int при добавлении данных не сунут double или string ...
примитивно, но...
http://www.cplusplus.com/refer... m/putback/
0
1186 / 542 / 78
Регистрация: 01.07.2009
Сообщений: 3,517
20.05.2012, 14:49  [ТС] 5
Цитата Сообщение от Jupiter Посмотреть сообщение
но тем неменее многие СУБД не в состоянии указать точную ошибку при неправильном запросе
Хороший парсер всегда проблема. Но тут просят чего-то простенького. Наверное будет даже достаточно вывода "unknown command" если что-то не будет получаться распарсить, но это потом, у меня главного нет: не знаю как же сделать основную структуру с столбцами таблиц. Мне тут ещё одну глупую, но рабочую, идею подкинули: завести таблицу сразу с 4мя типами и флагом каким-нибудь что именно мы сейчас храним. Что-то типа:
C++
1
2
3
4
5
6
7
struct Table
{
char* VARCHAR;
int INTEGER;
string DATE;
double DOUBLE;
};
Теоретически можно даже использовать эти ээээ... не структуры, не поля, а третье, вылетело из головы ключевое слово для них ... чтобы экономить память, но это уже наверное излишнее. Такой вариант вполне позволит сделать бд (ага, быдлокод чистейшей воды, но работать будет). Но мне такой вариант совсем не нравиться.
Кстати об одном из полей - о дате: есть в с++ в STL может что-то хитрое для работы с ним? Мне лень самому писать класс Data/ использовать старый написанный когда-то класс Дата. В с++ есть что-то удобное чтобы можно было проверять правильную ли дату задают ну и чтобы хранить какую-то дату в виде поля таблицы. Я помню в си было пару вещиц, но они такие неудобные были и работали через пень-колоду. Мне что-то гибкое надо и 100% работающее и независящее от того на какой ос это всё запускать будут.
*Я кстати не вижу чтобы задавали ключевые поля. Наверное не буду добавлять возможности это делать, чего самому себе задание усложнять.

Добавлено через 4 минуты
Цитата Сообщение от Jupiter Посмотреть сообщение
примитивно, но...
Не, не в этом плане. Я в том плане что после того как создали мы таблицу с типами int, double, char, char то нужно же ещё парсить что суют то что надо и в правильной последовательности, значит ещё надо держать где-то те типы с которыми создана бд, а потом сверяться что подсовывают те же типы. Именно с этим проблема. Так то оно обычно просто cin>>a>>b>>c>>d if (cin.fail) вы ввели фигню, пробуйте ещё раз.
0
В астрале
Эксперт С++
8049 / 4806 / 655
Регистрация: 24.06.2010
Сообщений: 10,562
20.05.2012, 14:54 6
Gepar, Там буст юзается только для any. Реализовать свой any проще простого. Достаточно посмотреть исходник бустовский) Да split, который тоже реализовать не проблема. В данном варианте нету сейва/лоада, которые сделаны через boost::serialization (вот это уже самому реализовать не столь просто).

Про даты. В стандарте нету удобств для работы с датами, но етесно есть в бусте.
1
В астрале
Эксперт С++
8049 / 4806 / 655
Регистрация: 24.06.2010
Сообщений: 10,562
22.05.2012, 16:51 7
Лучший ответ Сообщение было отмечено как решение

Решение

Вот так это выглядит сейчас. Не трогал уже довольно давно. Парсер у меня не компилится. Разберусь в чем дело потом.

Код базы
C++
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
#include <vector>
#include <string>
#include <map>
#include <boost/any.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/base_object.hpp>
#include <boost/serialization/split_member.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include <boost/function.hpp>
#include <sstream>
#include <stdexcept>
#include <iostream>
#include <typeinfo>
#include <limits>
//#include "parser.hpp"
 
 
namespace serialization = boost::serialization;
namespace archive = boost::archive;
 
namespace my_serialization
{
 
class Base
{
public:
    explicit Base(const std::string& type):type_(type)
    {
    }
    virtual ~Base() 
    {
    }
    std::string getType() const {return type_;}
    virtual std::string asString() const = 0;
    virtual boost::any asAny() const = 0;
    virtual bool empty() const = 0;
    friend class serialization::access;
private:
    template<class Arch>
    void serialize(Arch& ar, const unsigned int version = 0)
    {
        ar & type_;
    }
    std::string type_;
};
 
template<class T>
class Template:public Base
{
public:
    explicit Template(const T& value = T()):Base(typeid(T).name()), value_(value)
    {
    }
    virtual ~Template()
    {
    }
    virtual std::string asString() const 
    {
        return boost::lexical_cast<std::string>(value_);
    }
    virtual boost::any asAny() const 
    {
        return value_;
    }
    virtual bool empty() const 
    {
       return value_ == T();
    }
    friend class serialization::access;
private:
    template<class Arch>
    void serialize(Arch& ar, const unsigned int version = 0)
    {
        ar & serialization::base_object<Base>(*this);
        ar & value_;
    }
    T value_;
};
 
}
 
namespace my
{
    enum types_ {int_, string_, other_};
    typedef boost::shared_ptr<my_serialization::Base> value_pointer;
    class Holder
    {
    public:
        Holder()
        {
        }
        template<class T>
        Holder(const T& value, types_ type = other_, bool not_null = false):
            value_(new my_serialization::Template<T>(value)), type_(type), not_null_(not_null)
        {
        }
        const boost::any getValue() const 
        {
            return value_->asAny();
        }
        template<class T>
        void setValue(const T& val) 
        {
            value_ = value_pointer(new my_serialization::Template<T>(val));
        }
        void setType(const types_& tp) 
        {
           type_ = tp;
        }
        const types_& getType() const 
        {
           return type_;
        }
        bool notNull() const 
        {
           return not_null_;
        }
        void setNotNull(bool nn) 
        {
           not_null_ = nn;
        }
        bool empty() const 
        {
           return value_->empty();
        }
        std::string to_string() const
        {
            return value_->asString();
        }
        int to_int() const
        {
            int val = 0;
            std::string value = value_->asString();
            try
            {
                val = boost::lexical_cast<int>(value);
            }
            catch (const std::exception& e)
            {
                throw std::runtime_error("Not integer in string");
            }
            return val;
        }
        static boost::any from_string(const std::string& string)
        {
            int value = 0;
            try
            {
                value = boost::lexical_cast<int>(string);
            }
            catch (const boost::bad_lexical_cast& e)
            {
                return boost::any(string);
            }
            return boost::any(value);
        }
        static types_ type_from_string(const std::string& string)
        {
            types_ tp;
            if (string == "number")
            {
                tp = int_;
            }
            else if (string == "string")
            {
                tp = string_;
            }
            else
            {
                throw std::runtime_error("Unexpected type");
            }
            return tp;
        }
        static Holder value_from_type(const types_& tp)
        {
            Holder hld(0);
            if (tp == int_)
            { 
                hld = Holder(0, tp);
            }
            else if (tp == string_)
            {
                hld = Holder(std::string(), tp);
            }
            else
            {
                throw std::runtime_error("Unexpected type");
            }
            return hld;
        }
        static std::string string_from_type(const types_& tp)
        {
            std::string result;
            if (tp == int_)
            {
                result = "number";
            }
            else if (tp == string_)
            {
                result = "string";
            }
            else
            {
            }
            return result;
        }
        static std::string string_from_bool(bool value)
        {
            std::string result;
            if (value == true)
            {
                result = "not null";
            }
            return result;
        }
        friend class boost::serialization::access;
    private:
        template<class Arch>
        void serialize(Arch& ar, const unsigned int version = 0)
        {
            ar & type_;
            ar & value_;
            ar & not_null_;
        }
        value_pointer value_;
        types_ type_;
        bool not_null_;
    };
 
    class Table
    {
    public:
        typedef std::vector<Holder> Data;
        typedef std::vector<Data> TableData;
        Table()
        {
        }
        explicit Table(const std::string& tbl_name):table_name_(tbl_name)
        {
        }
 
        const std::string& getName() const {return table_name_;}
 
        void create(const std::vector<std::string>& plhs, const std::vector<types_>& tps,
                    const std::list<bool>& nulls)
        {
            auto plh_iter = plhs.begin();
            auto tp_iter = tps.begin();
            auto null_iter = nulls.begin();
            Data dt;
            for(; plh_iter != plhs.end(); ++plh_iter, ++tp_iter, ++null_iter)
            {
                dt.push_back(Holder(*plh_iter, *tp_iter, *null_iter));
            }
            matrix_.push_back(dt);
        }
 
        void insert(const std::vector<std::string>& plhs, const std::vector<boost::any>& values)
        {
            if (plhs.empty())
            {
                insert_(values);
            }
            else
            {
                insert_(plhs, values);
            }
        }
        
        std::string select(const std::vector<std::string>& plhs, const std::vector<std::string>& cond_plhs,
                    const std::vector<std::string>& conds, const std::vector<boost::any>& cond_vals,
                    const std::vector<std::string>& and_ors)
        {
            std::string result;
            if (plhs.empty() && cond_plhs.empty())
            {
                result = select_();
            }
            else if (cond_plhs.empty())
            {
                result = select_(plhs);
            }
            else if (plhs.empty())
            {
                result = select_(cond_plhs, conds, cond_vals, and_ors);
            }
            else
            {
                result = select_(plhs, cond_plhs, conds, cond_vals, and_ors);
            }
            if ((plhs.empty() && result == select_headers()) || (!plhs.empty() && result == select_headers(plhs)) || result.empty())
            {
                result = "\nNo data fetched\n\n";
            }
            return result;
        }
 
        void add_alter(const std::vector<std::string>& plhs, const std::vector<types_>& types,
                       const std::list<bool>& not_nulls)
        {
            add_alter_(plhs, types, not_nulls);
        }
        
        void drop_alter(const std::vector<std::string>& plhs)
        {
            drop_alter_(plhs);
        }
 
        void alter(const std::vector<std::string>& plhs, const std::vector<types_>& types,
                   const std::list<bool>& not_nulls)
        {
            alter_(plhs, types, not_nulls);
        }
        
        void truncate()
        {
            check_table_empty();
            for (auto iter = matrix_.begin() + 1; iter != matrix_.end();)
            {
                iter = matrix_.erase(iter);
            }
        }
        void update(const std::vector<std::string>& plhs, const std::vector<boost::any>& values, 
                    const std::vector<std::string>& cond_plhs, const std::vector<std::string>& opers,
                    const std::vector<boost::any>& cond_values, const std::vector<std::string>& conds)
        {
            check_table_empty();
            if (cond_plhs.empty())
            {
                update_(plhs, values);
            }
            else
            {
                update_(plhs, values, cond_plhs, opers, cond_values, conds);
            }
        }
 
        void desc(std::ostringstream& os)
        {
            std::for_each(matrix_[0].begin(), matrix_[0].end(), [&os](const Holder& hld)
            {
                os << hld.to_string() << '\t' << Holder::string_from_type(hld.getType()) 
                   << '\t' << Holder::string_from_bool(hld.notNull()) << '\n';
            });
        }
 
        void delete_(const std::vector<std::string>& cond_plhs, const std::vector<std::string>& cond_opers, 
                     const std::vector<boost::any>& cond_values, const std::vector<std::string>& conds)
        {
           if (cond_plhs.empty())
           {
               delete_impl();
           }
           else
           {
               delete_impl(cond_plhs, cond_opers, cond_values, conds);
           }
        }
 
        friend class boost::serialization::access;
    private:
        template<class Archive>
        void save(Archive& ar, const unsigned int version) const
        {
            size_t size = matrix_.size();
            ar & size;
            for (auto iter = matrix_.begin(); iter != matrix_.end(); ++iter)
            {
                ar & *iter;
            }
            ar & table_name_;
        }
        template<class Archive>
        void load(Archive& ar, const unsigned int version)
        {
            size_t size = 0;
            ar & size;
            for (size_t i = 0; i < size; ++i)
            {
                Data dt;
                ar & dt;
                matrix_.push_back(dt);
            }
            ar & table_name_;
        }
        BOOST_SERIALIZATION_SPLIT_MEMBER()
        std::string table_name_;
        TableData matrix_;
 
        std::string select_()
        {
            check_table_empty();
            std::ostringstream ost;
            ost << select_headers();
            std::for_each(matrix_.begin() + 1, matrix_.end(), [&ost, matrix_](const Data& dt)
            {
                auto iter = matrix_[0].begin();
                std::for_each(dt.begin(), dt.end(), [&ost, &iter](const Holder& hld)
                {
                    ost << hld.to_string() << '\t';
                    ++iter;
                });
                ost << '\n';
            });
            return ost.str();
        }
 
        std::string select_(const std::vector<std::string>& plhs)
        {
            check_table_empty();
            std::ostringstream ost;
            ost << select_headers(plhs);
            std::for_each(matrix_.begin() + 1, matrix_.end(), [&ost, &matrix_, &plhs](const Data& dt)
            {
                auto iter = matrix_[0].begin();
                auto plh_iter = plhs.begin();
                std::for_each(dt.begin(), dt.end(), [&ost, &iter, &plh_iter, &plhs](const Holder& hld)
                {
                    if (iter->to_string() == *plh_iter)
                    {
                        ost << hld.to_string() << '\t';
                        ++plh_iter;
                    }
                    ++iter;
                });
                ost << '\n';
            });
            return ost.str();
        }
 
        std::string select_(const std::vector<std::string>& condition_placeholders, 
                           const std::vector<std::string>& conditions,
                           const std::vector<boost::any>& cond_values,
                           const std::vector<std::string>& conds) 
        {
            check_table_empty();
            std::ostringstream ost;
            ost << select_headers();
            std::for_each(matrix_.begin() + 1, matrix_.end(), [&condition_placeholders, &conds, &conditions, &cond_values, &ost, this] 
                  (const Data& dt)
            {
                if (where(dt, condition_placeholders, conditions, cond_values, conds))
                {
                    auto iter = matrix_[0].begin();
                    std::for_each(dt.begin(), dt.end(), [&ost, &iter](const Holder& hld)
                    {
                        ost << hld.to_string() << '\t';
                        ++iter;
                    });
                    ost << '\n';
                }
            });
            return ost.str();
        }
        
        std::string select_(const std::vector<std::string>& plhs, 
                           const std::vector<std::string>& condition_plhs,
                           const std::vector<std::string>& conditions,
                           const std::vector<boost::any>& cond_values,
                           const std::vector<std::string>& conds)
        {
            check_table_empty();
            std::ostringstream ost;
            ost << select_headers(plhs);
            std::for_each(matrix_.begin() + 1, matrix_.end(), [&plhs, conds, &condition_plhs, &conditions, &cond_values, &ost, this]
                                                              (const Data& dt)
            {
                if (where(dt, condition_plhs, conditions, cond_values, conds))
                {
                    auto iter = matrix_[0].begin();
                    auto plh_iter = plhs.begin();
                    std::for_each(dt.begin(), dt.end(), [&ost, &iter, &plh_iter](const Holder& hld)
                    {
                        if (*plh_iter == iter->to_string())
                        {
                            ost << hld.to_string() << '\t';
                            ++plh_iter;
                        }
                        ++iter;
                    });
                    ost << '\n';
                }
            });
            return ost.str();
        }
 
        void insert_(const std::vector<boost::any>& values)
        {
            check_table_empty();
            Data dt;
            auto iterator = matrix_[0].begin();
            for (auto iter = values.begin(); iter != values.end(); ++iter, ++iterator)
            {
                std::string value = boost::any_cast<std::string>(*iter);
                if (iterator->getType() == int_)
                {
                    int val = boost::lexical_cast<int>(value);
                    dt.push_back(Holder(val, iterator->getType()));
                }
                else
                {
                    dt.push_back(Holder(value, iterator->getType()));
                }
            }
            matrix_.push_back(dt);
        }
        
        void insert_(const std::vector<std::string>& plhs, const std::vector<boost::any>& values)
        {
            check_table_empty();
            Data dt;
            auto plh_iter = plhs.begin();
            auto val_iter = values.begin();
            for(auto iter = matrix_[0].begin(); iter != matrix_[0].end(); ++iter)
            {
                if (iter->to_string() == *plh_iter)
                {
                    std::string value = boost::any_cast<std::string>(*val_iter);
                    if (iter->getType() == int_)
                    {
                        int val = boost::lexical_cast<int>(value);
                        dt.push_back(Holder(val, iter->getType()));
                    }
                    else if(iter->getType() == string_)
                    {
                        dt.push_back(Holder(value, iter->getType()));
                    }
                    else
                    {
                    }
                    ++val_iter;
                    ++plh_iter;
                }
                else
                {
                    if (iter->notNull())
                    {
                        throw std::runtime_error("Cannot insert null value in table");
                    }
                    dt.push_back(Holder::value_from_type(iter->getType()));
                }
            }
            matrix_.push_back(dt);
        }
        
        void add_alter_(const std::vector<std::string>& plhs, const std::vector<types_>& types,
                        const std::list<bool>& not_nulls)
        {
            auto pl_iter = plhs.begin();
            auto tp_iter = types.begin();
            auto null_iter = not_nulls.begin();
            for (; pl_iter != plhs.end(); ++pl_iter, ++tp_iter, ++null_iter)
            {
                add_alter_one_(*pl_iter, *tp_iter, *null_iter);
            }
        }
        
        void add_alter_one_(const std::string& plh, const types_& type, bool not_null)
        {
            if (matrix_.empty())
            {
                matrix_.push_back(Data());
            }
            if (not_null && select_() != select_headers())
            {
                throw std::runtime_error("Table should be empty for add not null field");
            }
            auto iter = matrix_[0].insert(matrix_[0].end(), Holder(plh, type, not_null));
            for (auto iter_ = matrix_.begin() + 1; iter_ != matrix_.end(); ++iter_)
            {
                iter_->push_back(Holder::value_from_type(iter->getType()));
            }
        }
        
        void drop_alter_(const std::vector<std::string>& plhs)
        {
            check_table_empty();
            auto pl_iter = plhs.begin();
            for (auto iter = matrix_[0].begin(); iter != matrix_[0].end();)
            {
                if (iter->to_string() == *pl_iter)
                {
                    size_t idx = std::distance(matrix_[0].begin(), iter);
                    for (auto itr = matrix_.begin() + 1; itr != matrix_.end(); ++itr)
                    {
                        itr->erase(itr->begin() + idx); 
                    }
                    iter = matrix_[0].erase(iter);
                    ++pl_iter;
                }
                else
                {
                    ++iter;
                }
            }
            if (select_headers() == "\n\n\n")
            {
                matrix_.clear();
            }
        }
        
        void check_not_nulls(const Data::iterator& iter)
        {
            size_t idx = std::distance(matrix_[0].begin(), iter);
            for (auto itr = matrix_.begin() + 1; itr != matrix_.end(); ++itr)
            {
               if ((itr->begin() + idx)->empty())
               {
                  throw std::runtime_error("Can` t set not null spec to field because there are null values in table");
               }
            }
        }
 
        void alter_(const std::vector<std::string>& plhs, const std::vector<types_>& types,
                    const std::list<bool>& not_nulls)
        {
            check_table_empty();
            auto pl_iter = plhs.begin();
            auto tp_iter = types.begin();
            auto null_iter = not_nulls.begin();
            for (auto iter = matrix_[0].begin(); iter != matrix_[0].end(); ++iter)
            {
                if (iter->to_string() == *pl_iter)
                {
                    if (*null_iter)
                    {
                        check_not_nulls(iter);
                        iter->setNotNull(*null_iter);
                    }
                    size_t idx = std::distance(matrix_[0].begin(), iter);
                    for (auto itr = matrix_.begin() + 1; itr != matrix_.end(); ++itr)
                    {
                        if (*tp_iter == string_)
                        {
                            try
                            {
                                (itr->begin() + idx)->setValue((itr->begin() + idx)->to_string());
                            }
                            catch(const std::exception& e)
                            {
                                (itr->begin() + idx)->setValue(std::string());
                                iter->setNotNull(false);
                            }
                        }
                        else if (*tp_iter == int_)
                        {
                            try
                            {
                                (itr->begin() + idx)->setValue((itr->begin() + idx)->to_int());
                                if (*null_iter)
                                {
                                   (itr->begin() + idx)->setNotNull(true);
                                }
                            }
                            catch (const std::exception& e)
                            {
                                (itr->begin() + idx)->setValue(0);
                                iter->setNotNull(false);
                            }
                        }
                        (itr->begin() + idx)->setType(*tp_iter);
                    }
                    iter->setType(*tp_iter);
                    ++tp_iter;
                    ++pl_iter;
                    ++null_iter;
                }
            }
        }
        
        void update_(const std::vector<std::string>& plhs, const std::vector<boost::any>& values)
        {
            std::for_each(matrix_.begin() + 1, matrix_.end(), [&plhs, &values, &matrix_](Data& dt)
            {
                auto iter = matrix_[0].begin();
                auto pl_iter = plhs.begin();
                auto val_iter = values.begin();
                std::for_each(dt.begin(), dt.end(), [&iter, &pl_iter, &val_iter](Holder& hld)
                {
                    if (iter->to_string() == *pl_iter)
                    {
                        std::string value = boost::any_cast<std::string>(*val_iter);
                        if (iter->getType() == int_)
                        {
                            int val = boost::lexical_cast<int>(value);
                            hld.setValue(val);
                        }
                        else if (iter->getType() == string_)
                        {
                            hld.setValue(value);
                        }
                        else
                        {
                        }
                        hld.setType(iter->getType());
                        ++pl_iter;
                        ++val_iter;
                    }
                    ++iter;
                });
            });
        }
        
        void update_(const std::vector<std::string>& plhs, const std::vector<boost::any>& values, 
                    const std::vector<std::string>& cond_plhs, const std::vector<std::string>& cond_opers,
                    const std::vector<boost::any>& cond_values, const std::vector<std::string>& conds)
        {
            std::for_each(matrix_.begin() + 1, matrix_.end(), [&plhs, &conds, &values, &cond_plhs, &cond_opers, &cond_values, this]
                                                              (Data& dt)
            {
                if (where(dt, cond_plhs, cond_opers, cond_values, conds))
                {
                    auto pl_iter = plhs.begin();
                    auto val_iter = values.begin();
                    auto iter = matrix_[0].begin();
                    std::for_each(dt.begin(), dt.end(), [&pl_iter, &val_iter, &iter](Holder& hld)
                    {
                        if (iter->to_string() == *pl_iter)
                        {
                            std::string value = boost::any_cast<std::string>(*val_iter);
                            if (iter->getType() == int_)
                            {
                                int val = boost::lexical_cast<int>(value);
                                hld.setValue(val);
                            }
                            else if(iter->getType() == string_)
                            {
                                hld.setValue(value);
                            }
                            else
                            {
                            }
                            ++pl_iter;
                            ++val_iter;
                        }
                        ++iter;
                    });
                }
            });
        }
 
        std::string select_headers() const
        {
            std::ostringstream ost;
            ost << '\n';
            std::for_each(matrix_[0].begin(), matrix_[0].end(), [&ost](const Holder& hld)                 
            {
                ost << hld.to_string() << '\t';
            });
            ost << "\n\n";
            return ost.str();
        }
 
        std::string select_headers(const std::vector<std::string>& plhs) const
        {
            std::ostringstream ost;
            ost << '\n';
            auto iter = plhs.begin();
            auto end_iter = plhs.end();
            std::for_each(matrix_[0].begin(), matrix_[0].end(), [&ost, &iter, &end_iter](const Holder& hld)
            {
                if (iter != end_iter)
                {
                    if (hld.to_string() == *iter)
                    {
                        ost << hld.to_string() << '\t';
                        ++iter;
                    }
                }
            });
            ost << "\n\n";
            return ost.str();
        }
 
        void delete_impl()
        {
           check_table_empty();
           for (auto iter = matrix_.begin() + 1; iter != matrix_.end();)
           {
               iter = matrix_.erase(iter);
           };
        }
        
        void delete_impl(const std::vector<std::string>& cond_plhs, const std::vector<std::string>& cond_opers,
                         const std::vector<boost::any>& cond_values, const std::vector<std::string>& conds)
        {
           for (auto iter = matrix_.begin() + 1; iter != matrix_.end();)
           {
               if (where(*iter, cond_plhs, cond_opers, cond_values, conds))
               {
                  iter = matrix_.erase(iter);
               }
               else
               {
                  ++iter;
               }
           }
        }
 
        bool where(const Data& dt,
                   const std::vector<std::string>& condition_plhs,
                   const std::vector<std::string>& conditions,
                   const std::vector<boost::any>& cond_values,
                   const std::vector<std::string>& conds)
        {
            bool flg = true;
            bool first = true;
            auto intern_plh_iter = matrix_[0].begin();
            auto cond_plh_iter = condition_plhs.begin();
            auto cond_iter = conditions.begin();
            auto cond_val_iter = cond_values.begin();
            auto or_and_iter = conds.begin();
            auto data_iter = dt.begin();
            for (; intern_plh_iter != matrix_[0].end(); ++intern_plh_iter, ++data_iter)
            {
                if (*cond_plh_iter == intern_plh_iter->to_string())
                {
                    std::string cond_value = boost::any_cast<std::string>(*cond_val_iter);
                    if (intern_plh_iter->getType() == string_)
                    {
                        std::string value = boost::any_cast<std::string>(data_iter->getValue());
                        if (!compare(value, *cond_iter, cond_value))
                        {
                            flg = false;
                        }
                        else
                        {
                            flg = true;
                        }
                    }
                    else if (intern_plh_iter->getType() == int_)
                    {
                        int val = boost::any_cast<int>(data_iter->getValue());
                        int cond_val = boost::lexical_cast<int>(cond_value);
                        if (!compare(val, *cond_iter, cond_val))
                        {
                            flg = false;    
                        }
                        else
                        {
                            flg = true;
                        }
                    }
                    if (or_and_iter == conds.end())
                    {
                        break;
                    }
                    if (*or_and_iter == "and")
                    {
                        if (!flg)
                        {
                            break;
                        }
                        flg = flg && flg;
                    }
                    else if (*or_and_iter == "or")
                    {
                        if (flg)
                        {
                            break;
                        }
                        flg = flg || flg;
                    }
                    ++cond_plh_iter;
                    ++cond_iter;
                    ++cond_val_iter;
                    if (!first)
                    {
                        ++or_and_iter;
                    }
                    if (first)
                    {
                        first = false;
                    }
                }
            }
            return flg;
        }
 
        template<class T>
        bool compare(const T& first, const std::string& oper, const T& second)
        {
            bool flg = false;
            if (oper == "=")
            {
                flg = first == second;
            }
            else if (oper == "!=")
            {
                flg = first != second;
            }
            else if (oper == "<")
            {
                flg = first < second;
            }
            else if (oper == ">")
            {
                flg = first > second;
            }
            else if (oper == "<=")
            {
                flg = first <= second;
            }
            else if (oper == ">=")
            {
                flg = first >= second;
            }
            return flg;
        }
 
        void check_table_empty()
        {
            if (matrix_.empty())
            {
                throw std::runtime_error("Table is empty");
            }
        }
    };
    
    struct TableCmpByTblName
    {
    public:
        TableCmpByTblName(const std::string& tbl_name):
            table_name(tbl_name)
        {
        }
        bool operator () (const Table& tbl)
        {
            return table_name == tbl.getName();
        }
    private:
        std::string table_name;
    };
 
    class DataBase
    {
    public:
        DataBase()
        {
        }
        explicit DataBase(const std::string& name):db_name(name)
        {
        }
        const std::string& getName() const {return db_name;}
        const std::vector<Table>& getDB() const {return db;}
        std::string show() const 
        {
            std::ostringstream ost;
            ost << "\nTables in database " << db_name << "\n";
            check_db_empty();
            for (auto iter = db.begin(); iter != db.end(); ++iter)
            {
                ost << iter->getName() << '\n';
            }
            ost << '\n';
            return ost.str();
        }
        std::string desc(const std::string& tbl_name)
        {
            std::ostringstream ost;
            ost << "\nField" << '\t'
                << "Type" << '\t'
                << "Null?" << "\n\n";
            auto iter = find_table_by_name(tbl_name);
            iter->desc(ost);
            ost << "\n";
            return ost.str();
        }
        void create_tbl(const std::string& tbl_name, const std::vector<std::string>& plhs, 
                    const std::vector<types_>& tps, const std::list<bool>& nulls)
        {
            check_table_exist(tbl_name);
            auto iter = db.insert(db.end(), Table(tbl_name));
            iter->create(plhs, tps, nulls);
        }
        void insert(const std::string& tbl_name, const std::vector<std::string>& plhs, 
                    const std::vector<boost::any>& values)
        {
            check_db_empty();
            auto iter = find_table_by_name(tbl_name);
            iter->insert(plhs, values);
        }
        std::string select(const std::string& tbl_name, const std::vector<std::string>& plhs,
                           const std::vector<std::string>& condition_placeholders,
                           const std::vector<std::string>& conditions,
                           const std::vector<boost::any>& cond_values,
                           const std::vector<std::string>& conds)
        {
            check_db_empty();
            auto iter = find_table_by_name(tbl_name);
            return iter->select(plhs, condition_placeholders, conditions, cond_values, conds);
        }
        void add_alter(const std::string& tbl_name, const std::vector<std::string>& plhs, const std::vector<types_>& types,
                       const std::list<bool>& nulls)
        {
            check_db_empty();
            auto iter = find_table_by_name(tbl_name);
            iter->add_alter(plhs, types, nulls);
        }
        void drop_alter(const std::string& tbl_name, const std::vector<std::string>& plhs)
        {
            check_db_empty();
            auto iter = find_table_by_name(tbl_name);
            iter->drop_alter(plhs);
        }
        void alter(const std::string& tbl_name, const std::vector<std::string>& plhs, const std::vector<types_>& types,
                   const std::list<bool>& nulls)
        {
            check_db_empty();
            auto iter = find_table_by_name(tbl_name);
            iter->alter(plhs, types, nulls);
        }
        void drop(const std::string& tbl_name)
        {
            check_db_empty();
            auto iter = find_table_by_name(tbl_name);
            db.erase(iter);
        }
        void truncate(const std::string& tbl_name)
        {
            check_db_empty();
            auto iter = find_table_by_name(tbl_name);
            iter->truncate();
        }
        void update(const std::string& tbl_name, const std::vector<std::string>& plhs, const std::vector<boost::any>& values,
                    const std::vector<std::string>& cond_plhs, const std::vector<std::string>& cond_opers, 
                    const std::vector<boost::any>& cond_values, const std::vector<std::string>& conds)
        {
            check_db_empty();
            auto iter = find_table_by_name(tbl_name);
            iter->update(plhs, values, cond_plhs, cond_opers, cond_values, conds);
        }
        void push_back(const Table& tbl)
        {
            db.push_back(tbl);
        }
        void delete_(const std::string& tbl_name, const std::vector<std::string>& cond_plhs, const std::vector<std::string>& cond_opers,
                     const std::vector<boost::any>& cond_values, const std::vector<std::string>& conds)
        {
           check_db_empty();
           auto iter = find_table_by_name(tbl_name);
           iter->delete_(cond_plhs, cond_opers, cond_values, conds);
        }
        friend class boost::serialization::access;
    private:
        template<class Archive>
        void serialize(Archive& ar, const unsigned int version)
        {
            ar & db;
            ar & db_name;
        }
        std::vector<Table> db;
        std::string db_name;
        std::vector<Table>::iterator find_table_by_name(const std::string& tbl_name)
        {
            std::vector<Table>::iterator iter = std::find_if(db.begin(), db.end(), TableCmpByTblName(tbl_name));
            if (iter == db.end())
            {
                throw std::logic_error("Table doesn`t exist");
            }
            return iter;
        }
        void check_db_empty() const
        {
            if (db.size() == 0)
            {
                throw std::logic_error("Database is empty");
            }
        }
        void check_table_exist(const std::string& tbl_name)
        {
            try
            {
                find_table_by_name(tbl_name);
            }
            catch(const std::logic_error& e)
            {
                return;
            }
            throw std::runtime_error("Table is allready exist");
        }
    };
}
 
void save(const my::Table& tbl, const boost::filesystem::path& f_path)
{
    boost::filesystem::ofstream ofs(f_path);
    boost::archive::text_oarchive oarch(ofs);
    oarch.register_type(static_cast<my_serialization::Template<std::string>*>(0));
    oarch.register_type(static_cast<my_serialization::Template<int>*>(0));
    oarch << tbl;
}
 
void load(my::Table& tbl, const boost::filesystem::path& f_path)
{
    boost::filesystem::ifstream ifs(f_path);
    boost::archive::text_iarchive iarch(ifs);
    iarch.register_type(static_cast<my_serialization::Template<std::string>*>(0));
    iarch.register_type(static_cast<my_serialization::Template<int>*>(0));
    iarch >> tbl;
}
 
void save_base(const my::DataBase& DataBase_)
{
    boost::filesystem::path path(boost::filesystem::current_path());
    path /= "storage/";
    path /= DataBase_.getName();
    if (boost::filesystem::exists(path))
    {
        boost::filesystem::remove_all(path);
    }
    boost::filesystem::create_directories(path);
    for (auto iter = DataBase_.getDB().begin(); iter != DataBase_.getDB().end(); ++iter)
    {
        boost::filesystem::path temp_path = path;
        temp_path /= iter->getName();
        save(*iter, temp_path);
    }
}
 
void load_base(my::DataBase& DataBase_)
{
    boost::filesystem::path path(boost::filesystem::current_path() / "storage/");
    if (!boost::filesystem::exists(path))
    {
        return;
    }
    for (auto dir_iter = boost::filesystem::recursive_directory_iterator(path);
        dir_iter != boost::filesystem::recursive_directory_iterator(); ++dir_iter)
    {
        if (!boost::filesystem::is_directory(dir_iter->path()))
        {
            break;
        }
        boost::filesystem::directory_entry& dir_entr = *dir_iter;
        for (auto d_iter = boost::filesystem::directory_iterator(dir_entr.path()); 
            d_iter != boost::filesystem::directory_iterator(); ++d_iter)
        {
            my::Table tbl;
            load(tbl, d_iter->path());
            DataBase_.push_back(tbl);
        }
    }
}
 
class Program
{
public:
    Program()
    {
        functions = 
        {
            std::make_pair("create", &Program::create),
            std::make_pair("insert", &Program::insert),
            std::make_pair("select", &Program::select),
            std::make_pair("help", &Program::help),
            std::make_pair("alter", &Program::alter),
            std::make_pair("drop", &Program::drop),
            std::make_pair("truncate", &Program::truncate),
            std::make_pair("delete", &Program::delete_),
            std::make_pair("update", &Program::update),
            std::make_pair("show", &Program::show),
            std::make_pair("desc", &Program::desc),
            std::make_pair("describe", &Program::desc),
            std::make_pair("quit", &Program::quit),
            std::make_pair("exit", &Program::quit)
        };
    }
    static bool process(const std::string& command, my::DataBase& DataBase_, std::ostream& os = std::cout)
    {
        Program prog;
        try
        {
            std::vector<std::string> commands = Parser()(command);
            functions[commands.at(0)](&prog, commands, DataBase_);
            if (commands.at(0) == "quit" || commands.at(0) == "exit")
            {
                return true;
            }
        }
        catch (const Parser_Error& e)
        {
        }
        catch (const std::out_of_range& e)
        {
            std::cout << "ERROR: " << e.what() << std::endl;
            //throw std::runtime_error(std::string("Wrong command") + "\n" + comm_string);
        }
        catch (const std::exception& e)
        {
            std::cout << "ERROR: " << e.what() << std::endl;
            //throw std::runtime_error(std::string(e.what()) + "\n" + comm_string);
        }
        return false;
    }
private:
    
    static std::map<std::string, boost::function<void(Program*, const std::vector<std::string>&, my::DataBase&)>> functions;
 
    void create(const std::vector<std::string>& commands, my::DataBase& DataBase_)
    {
        std::copy(commands.begin(), commands.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
        std::string table_name = commands.at(1);
        std::vector<std::string> plhs;
        std::vector<my::types_> tps;
        std::list<bool> nulls;
        for (std::vector<std::string>::const_iterator iter = commands.begin() + 2; iter != commands.end();)
        {
            plhs.push_back(*iter);
            ++iter;
            tps.push_back(my::Holder::type_from_string(*iter));
            ++iter;
            if (*iter == "not null")
            {
                nulls.push_back(true);
            }
            else
            {
                nulls.push_back(false);
            }
            ++iter;
        }
        DataBase_.create_tbl(table_name, plhs, tps, nulls);
    }
    
    void insert(const std::vector<std::string>& commands, my::DataBase& DataBase_)
    {
        std::string table_name = commands.at(2);
        auto iter = commands.begin() + 2;
        std::vector<std::string> plhs;
        if (*(++iter) != "values")
        {
            for (; *iter != "values"; ++iter)
            {
                plhs.push_back(*iter);
            }
        }
        ++iter;
        std::vector<boost::any> values;
        for(; iter != commands.end(); ++iter)
        {
            values.push_back(*iter);
        }
        DataBase_.insert(table_name, plhs, values);
    }
    void select(const std::vector<std::string>& commands, my::DataBase& DataBase_) const
    {
        std::vector<std::string> plhs;
        auto iter = commands.begin() + 1;
        if (*iter != "*")
        {
            for (; *iter != "from"; ++iter)
            {
                plhs.push_back(*iter);
            }
            ++iter;
        }
        else
        {
            iter += 2;
        }
        std::string table_name = *iter;
        std::vector<std::string> cond_plhs;
        std::vector<std::string> opers;
        std::vector<boost::any> cond_values;
        std::vector<std::string> conds;
        ++iter;
        if (iter != commands.end() && *iter == "where")
        {
            ++iter;
            for (; iter != commands.end();)
            {
                cond_plhs.push_back(*iter);
                ++iter;
                opers.push_back(*iter);
                ++iter;
                cond_values.push_back(*iter);
                ++iter;
                if (iter != commands.end())
                {
                    conds.push_back(*iter);
                    ++iter;
                }
            }
        }
        std::cout << DataBase_.select(table_name, plhs, cond_plhs, opers,
                     cond_values, conds) << std::endl;
    }
    void alter(const std::vector<std::string>& commands, my::DataBase& DataBase_)
    {
        std::string table_name = commands.at(1);
        std::vector<std::string> plhs;
        std::vector<my::types_> types;
        std::list<bool> not_nulls;
        if (commands.at(2) == "add")
        {
            for (auto iter = commands.begin() + 3; iter != commands.end();)
            {
                plhs.push_back(*iter);
                ++iter;
                types.push_back(my::Holder::type_from_string(*iter));
                ++iter;
                if (*iter == "not null")
                {
                    not_nulls.push_back(true);
                }
                else
                {
                    not_nulls.push_back(false);
                }
                ++iter;
            }
            DataBase_.add_alter(table_name, plhs, types, not_nulls);
        }
        else if (commands.at(2) == "drop")
        {
            plhs = std::vector<std::string>(commands.begin() + 3, commands.end());
            DataBase_.drop_alter(table_name, plhs);
        }
        else if (commands.at(2) == "alter")
        {
            for (auto iter = commands.begin() + 3; iter != commands.end();)
            {
                plhs.push_back(*iter);
                ++iter;
                types.push_back(my::Holder::type_from_string(*iter));
                ++iter;
                if (*iter == "not null")
                {
                    not_nulls.push_back(true);
                }
                else
                {
                    not_nulls.push_back(false);
                }
                ++iter;
            }
            DataBase_.alter(table_name, plhs, types, not_nulls);
        }
    }
    void drop(const std::vector<std::string>& commands, my::DataBase& DataBase_)
    {
        std::string table_name = commands.at(1);
        DataBase_.drop(table_name);
    }
    void truncate(const std::vector<std::string>& commands, my::DataBase& DataBase_)
    {
        std::string table_name = commands.at(1);
        DataBase_.truncate(table_name);
    }
    void update(const std::vector<std::string>& commands, my::DataBase& DataBase_)
    {
        std::string table_name = commands.at(1);
        std::vector<std::string> plhs;
        std::vector<boost::any> values;
        std::vector<std::string> cond_plhs;
        std::vector<std::string> cond_opers;
        std::vector<boost::any> cond_values;
        std::vector<std::string> conds;
        auto iter = commands.begin() + 3;
        for (; iter != commands.end() && *iter != "where";)
        {
            plhs.push_back(*iter);
            ++iter;
            ++iter;
            values.push_back(*iter);
            ++iter;
        }
        if (iter != commands.end() && *iter == "where")
        {
            ++iter;
            for (; iter != commands.end();)
            {
                cond_plhs.push_back(*iter);
                ++iter;
                cond_opers.push_back(*iter);
                ++iter;
                cond_values.push_back(*iter);
                ++iter;
                if (iter != commands.end())
                {
                    conds.push_back(*iter);
                    ++iter;
                }
            }
        }
        DataBase_.update(table_name, plhs, values, cond_plhs, cond_opers, cond_values, conds);
    }
    
    void show(const std::vector<std::string>&, const my::DataBase& DataBase_)
    {
        std::cout << DataBase_.show() << std::endl;
    }
    
    void desc(const std::vector<std::string>& commands, my::DataBase& DataBase_)
    {
        std::string table_name = commands.at(1);
        my::DataBase base = const_cast<my::DataBase&>(DataBase_);
        std::cout << base.desc(table_name) << std::endl;
    }
   
    void delete_(const std::vector<std::string>& commands, my::DataBase& DataBase_)
    {
        std::string table_name = commands.at(2);
        auto iter = commands.begin() + 3;
        std::vector<boost::any> cond_values;
        std::vector<std::string> cond_plhs;
        std::vector<std::string> cond_opers;
        std::vector<std::string> conds;
        if (iter != commands.end() && *iter == "where")
        {
           ++iter;
           for (; iter != commands.end();)
           {
               cond_plhs.push_back(*iter);
               ++iter;
               cond_opers.push_back(*iter);
               ++iter;
               cond_values.push_back(*iter);
               ++iter;
               if (iter != commands.end())
               {
                   conds.push_back(*iter);
                   ++iter;
               }
           }
        }
        DataBase_.delete_(table_name, cond_plhs, cond_opers, cond_values, conds);
    }
 
    void help(const std::vector<std::string>&, my::DataBase&)
    {
        std::cout << "----------------HELP-------------------\n\n";
        std::cout << "Simple database 1.0\n";
        std::cout << "Commands: create, insert, select, alter, drop, update, truncate\n";
        std::cout << "Examples of usage\n";
        std::cout << "Example of create: create tbl1 id:number, name:string\n";
        std::cout << "Command create table named tbl1 with fields id with type number and name with type string\n";
        std::cout << "Example of insert: insert into tbl1 values 1, a\n";
        std::cout << "Command insert in table named tbl1 value 1 in id and a in name\n";
        std::cout << "Example of insert: insert into tbl1 id values 1\n";
        std::cout << "Command insert in table named tbl1 values 1 in id and null in name (for string null is empty string)\n";
        std::cout << "Example of select: select * from tbl1\n";
        std::cout << "Command select values from all fields of tbl1\n";
        std::cout << "Example of select: select * from tbl1 where id = 1\n";
        std::cout << "Command select values from all fields of tbl1 where value of field id = 1\n";
        std::cout << "Example of select: select id from tbl1 where name = a\n";
        std::cout << "Command select values from field if of tbl1 where values of field name = a\n";
        std::cout << "Example of alter: alter tbl1 add value:string\n";
        std::cout << "Command add to table field value with type string\n";
        std::cout << "Example of alter: alter tbl1 drop value\n";
        std::cout << "Command drop from table column named values\n";
        std::cout << "Example of alter: alter tbl1 alter value:number\n";
        std::cout << "Command change type of field value to number\n";
        std::cout << "Example of drop: drop tbl1\n";
        std::cout << "Command drop all table. After this command table is destroyed\n";
        std::cout << "Example of truncate: truncate tbl1\n";
        std::cout << "Command drop all values in the table\n";
        std::cout << "Example of update: update tbl1 set id = 1\n";
        std::cout << "Command set value of field named id in 1 in all table\n";
        std::cout << "Example of update: update tbl1 set id = 1 where name = a\n";
        std::cout << "Command set value of field named id in 1 if value of field name in this row = a\n";
        std::cout << "IN THIS VERSION SPACES IN CONDITIONS FOR WHERE ARE OBLIGATORY\n";
        std::cout << "Thanks. Good luck\n";
        std::cout << "----------------------------------------\n\n";
    }
    
    void quit(const std::vector<std::string>&, my::DataBase& DataBase_)
    {
        save_base(DataBase_);
    }
};
 
std::map<std::string, boost::function<void(Program*, const std::vector<std::string>&, my::DataBase&)>> Program::functions;

Парсер

C++
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
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/spirit/include/phoenix_statement.hpp>
#include <boost/bind.hpp>
 
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
 
namespace fusion = boost::fusion;
namespace phoenix = boost::phoenix;
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
 
void push_tokens(std::vector<std::string>& tokens, const std::vector<std::string>& values)
{
    tokens.insert(tokens.end(), values.begin(), values.end());
}
 
void push_token(std::vector<std::string>& tokens, const std::string& val)
{
    tokens.push_back(val);
}
 
/* Grammar
 *
 * Expr : PrimaryCommand
 * PrimaryCommand : InsertCommand | SelectCommand | CreateCommand | DeleteCommand | AlterCommand | TruncateCommand |
 * UpdateCommand | DescCommand | ShowCommand | DropCommand | QuitCommand | HelpCommand
 * InsertCommand : insert into Name ([Names]) values (Values);
 * SelectCommand : select Names | * from Name [Conditions];
 * CreateCommand : create Name (Names and Types);
 * DeleteCommand : delete from Name [Conditions];
 * AlterCommand : alter Name Alter_add | Alter_drop | Alter_alter;
 * TruncateCommand : truncate Name;
 * UpdateCommand : update Name set Names and Values [Conditions];
 * DescCommand : desc | describe Name
 * ShowCommand : show Name
 * DropCommand : drop Name
 * Help : help
 * QuitCommand : quit | exit
 * Names : Name +[, Name]
 * Name : name of table, variable ect
 * Conditions : where Condition +[Cond Condition];
 * Condition : Name Oper Value
 * Oper : = | <= | >= | != | < | >
 * Value : value
 * Cond : and | or
 * Types : Type +[, Type]
 * Type : number | string
 * Not_null : not null | " "
 * Name and Type : Name Type Not_null
 * Names and Types : Name and Type +[, Name and Type]
 * Name and Value : Name = Value
 * Names and Values : Name and Value +[, Name and Value]
 *
*/
 
template<typename Iterator>
struct sql_grammar:qi::grammar<Iterator, std::vector<std::string>(), qi::locals<std::string>, ascii::space_type>
{
    sql_grammar(std::ostringstream& os):sql_grammar::base_type(root, "sql"), stream(os)
    {
        using qi::lit;
        using qi::lexeme;
        using qi::on_error;
        using qi::fail;
        using qi::omit;
        using ascii::char_;
        using ascii::string;
 
        using phoenix::construct;
        using phoenix::val;
        using phoenix::push_back;
        
        type = string("number") | string("string");
        name = lexeme[+(char_("a-zA-Z0-9_"))];
        not_null_spec = string("not null") | string("");
        value = lexeme[+(char_("a-zA-Z0-9_"))];
        oper = string("=") | string("!=") | string("<=") | string(">=") | string("<") | string(">");
        cond = string("and") | string("or");
 
        names = name [push_back(qi::_val, qi::_1)]
            > -(+(omit[char_(',')] > name [push_back(qi::_val, qi::_1)]))
        ;
 
        name_and_type = name [push_back(qi::_val, qi::_1)]
            > type [push_back(qi::_val, qi::_1)]
            > not_null_spec [push_back(qi::_val, qi::_1)]
        ;
 
        name_and_value = name [push_back(qi::_val, qi::_1)]
            > string("=") [push_back(qi::_val, qi::_1)]
            > value [push_back(qi::_val, qi::_1)]
        ;
 
        names_and_values = name_and_value [boost::bind(&push_tokens, ref(tokens), _1)]
            > -(+(omit[char_(',')] > name_and_value [boost::bind(&push_tokens, ref(tokens), _1)]))
        ;
 
        names_and_types = name_and_type [boost::bind(&push_tokens, ref(tokens), _1)]
            > -(+(omit[char_(',')] > name_and_type [boost::bind(&push_tokens, ref(tokens), _1)]))
        ;
        
        values = value [push_back(qi::_val, qi::_1)]
            > -(+(omit[char_(',')]> value [push_back(qi::_val, qi::_1)]))
        ;
        
        condition = name [push_back(qi::_val, qi::_1)]
            > oper [push_back(qi::_val, qi::_1)]
            > value [push_back(qi::_val, qi::_1)]
        ;
 
        conditions = condition [boost::bind(&push_tokens, ref(tokens), _1)]
            > -(+(cond [boost::bind(&push_token, ref(tokens), _1)]
            > condition [boost::bind(&push_tokens, ref(tokens), _1)]))
        ;
 
        where = string("where") [boost::bind(&push_token, ref(tokens), _1)]
            > conditions;
        
        alter_add = string("add") [boost::bind(&push_token, ref(tokens), _1)]
            > names_and_types
        ;
 
        alter_drop = string("drop") [boost::bind(&push_token, ref(tokens), _1)]
            > names [boost::bind(&push_tokens, ref(tokens), _1)]
        ;
 
        alter_alter = string("alter") [boost::bind(&push_token, ref(tokens), _1)]
            > names_and_types
        ;
 
        create = string("create") [boost::bind(&push_token, ref(tokens), _1)]
            > name [boost::bind(&push_token, ref(tokens), _1)]
            > omit[char_('(')] > names_and_types > omit[char_(')')]
            > omit[char_(';')]
        ;
 
        insert = string("insert") [boost::bind(&push_token, ref(tokens), _1)]
            > string("into") [boost::bind(&push_token, ref(tokens), _1)]
            > name [boost::bind(&push_token, ref(tokens), _1)]
            > -(omit[char_('(')] > names [boost::bind(&push_tokens, ref(tokens), _1)] > omit[char_(')')])
            > string("values") [boost::bind(&push_token, ref(tokens), _1)]
            > omit[char_('(')] > values [boost::bind(&push_tokens, ref(tokens), _1)] > omit[char_(')')]
            > omit[char_(';')]
        ;
        
        select = string("select") [boost::bind(&push_token, ref(tokens), _1)]
            > (names [boost::bind(&push_tokens, ref(tokens), _1)] | string("*") [boost::bind(&push_token, ref(tokens), _1)])
            > string("from") [boost::bind(&push_token, ref(tokens), _1)]
            > name [boost::bind(&push_token, ref(tokens), _1)]
            > -where
            > omit[char_(';')]
        ;
 
        delete_ = string("delete") [boost::bind(&push_token, ref(tokens), _1)]
            > string("from") [boost::bind(&push_token, ref(tokens), _1)]
            > name [boost::bind(&push_token, ref(tokens), _1)]
            > -where
            > omit[char_(';')]
        ;
        
        update = string("update") [boost::bind(&push_token, ref(tokens), _1)]
            > name [boost::bind(&push_token, ref(tokens), _1)]
            > string("set") [boost::bind(&push_token, ref(tokens), _1)]
            > names_and_values
            > -where
            > omit[char_(';')]
        ;
        
        alter = string("alter") [boost::bind(&push_token, ref(tokens), _1)]
            > name [boost::bind(&push_token, ref(tokens), _1)]
            > (alter_add | alter_drop | alter_alter)
            > omit[char_(';')]
        ;
        
        truncate = string("truncate") [boost::bind(&push_token, ref(tokens), _1)]
            > name [boost::bind(&push_token, ref(tokens), _1)]
            > omit[char_(';')]
        ;
        
        drop = string("drop") [boost::bind(&push_token, ref(tokens), _1)]
            > name [boost::bind(&push_token, ref(tokens), _1)]
            > omit[char_(';')]
        ;
        
        desc = (string("desc") | string("describe")) [boost::bind(&push_token, ref(tokens), _1)]
            > name [boost::bind(&push_token, ref(tokens), _1)]
            > -omit[char_(';')]
        ;
 
        show = (string("show")) [boost::bind(&push_token, ref(tokens), _1)]
            > -omit[char_(';')]
        ;
 
        quit = (string("quit") | string("exit")) [boost::bind(&push_token, ref(tokens), _1)]
            > -omit[char_(';')]
        ;
 
        help = string("help") [boost::bind(&push_token, ref(tokens), _1)]
            > -omit[char_(';')]
        ;
 
        root = create | insert | select | delete_ | update | alter | truncate
            | drop | desc | show | quit | help;
        
        root.name("expression");
        create.name("create command");
        table_name_for_create.name("table name");
        name_and_type.name("name and type");
        names_and_types.name("names and types");
        type.name("value type");
        name.name("name");
        names.name("names");
        insert.name("insert command");
        value.name("value");
        values.name("values");
        select.name("select command");
        cond.name("cond");
        condition.name("condition");
        conditions.name("conditions");
        where.name("where");
        delete_.name("delete");
        name_and_value.name("name and value");
        names_and_values.name("names and values");
        alter_add.name("alter add command");
        alter_drop.name("alter drop command");
        alter_alter.name("alter alter command");
        alter.name("alter command");
        truncate.name("truncate command");
        drop.name("drop command");
        desc.name("describe command");
        show.name("show command");
        quit.name("quit command");
        help.name("help command");
 
        on_error<fail>
        (
           root,
           stream << val("Error! Expected ")
           << qi::_4
           << val(" here: \"")
           << construct<std::string>(qi::_3, qi::_2)
           << val("\"")
           << std::endl
        );
    }
    
    qi::rule<Iterator, std::vector<std::string>(), qi::locals<std::string>, ascii::space_type> root;
    qi::rule<Iterator, std::vector<std::string>(), ascii::space_type> names_and_types, name_and_type, names,
        create, values, insert, select, where, conditions, condition, delete_, names_and_values, name_and_value,
        update, alter_add, alter_drop, alter_alter, alter, truncate, drop, desc, show, quit, help;
    qi::rule<Iterator, std::string(), ascii::space_type> table_name_for_create, type, name, not_null_spec, value,
        oper, cond;
 
    const std::vector<std::string> get_tokens() const {return tokens;}
private:
    std::ostringstream stream;
    std::vector<std::string> tokens;
};
 
class Parser_Error:public std::runtime_error
{
public:
    Parser_Error(const std::string& msg):std::runtime_error(msg)
    {
    }
};
 
class Parser
{
public:
    std::vector<std::string> operator() (const std::string& text, std::ostringstream& os)
    {
        std::string::const_iterator begin = text.begin();
        std::string::const_iterator end = text.end();
        sql_grammar<std::string::const_iterator> grammar(os);
        std::vector<std::string> temp;
        bool r = false;
        r = phrase_parse(begin, end, grammar, ascii::space, temp);
        if (r && begin == end)
        {
            return grammar.get_tokens();
        }
        else
        {
            std::cout << os.str() << std::endl;
            throw Parser_Error("Parser error");
        }
    }
};


Добавлено через 7 часов 51 минуту
Пофиксил парсер. Со стримом буду думать что делать.

парсер
C++
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
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/spirit/include/phoenix_statement.hpp>
#include <boost/bind.hpp>
 
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
 
namespace fusion = boost::fusion;
namespace phoenix = boost::phoenix;
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
 
void push_tokens(std::vector<std::string>& tokens, const std::vector<std::string>& values)
{
    tokens.insert(tokens.end(), values.begin(), values.end());
}
 
void push_token(std::vector<std::string>& tokens, const std::string& val)
{
    tokens.push_back(val);
}
 
/* Grammar
 *
 * Expr : PrimaryCommand
 * PrimaryCommand : InsertCommand | SelectCommand | CreateCommand | DeleteCommand | AlterCommand | TruncateCommand |
 * UpdateCommand | DescCommand | ShowCommand | DropCommand | QuitCommand | HelpCommand
 * InsertCommand : insert into Name ([Names]) values (Values);
 * SelectCommand : select Names | * from Name [Conditions];
 * CreateCommand : create Name (Names and Types);
 * DeleteCommand : delete from Name [Conditions];
 * AlterCommand : alter Name Alter_add | Alter_drop | Alter_alter;
 * TruncateCommand : truncate Name;
 * UpdateCommand : update Name set Names and Values [Conditions];
 * DescCommand : desc | describe Name
 * ShowCommand : show Name
 * DropCommand : drop Name
 * Help : help
 * QuitCommand : quit | exit
 * Names : Name +[, Name]
 * Name : name of table, variable ect
 * Conditions : where Condition +[Cond Condition];
 * Condition : Name Oper Value
 * Oper : = | <= | >= | != | < | >
 * Value : value
 * Cond : and | or
 * Types : Type +[, Type]
 * Type : number | string
 * Not_null : not null | " "
 * Name and Type : Name Type Not_null
 * Names and Types : Name and Type +[, Name and Type]
 * Name and Value : Name = Value
 * Names and Values : Name and Value +[, Name and Value]
 *
*/
 
template<typename Iterator>
struct sql_grammar:qi::grammar<Iterator, std::vector<std::string>(), qi::locals<std::string>, ascii::space_type>
{
    sql_grammar():sql_grammar::base_type(root, "sql")
    {
        using qi::lit;
        using qi::lexeme;
        using qi::on_error;
        using qi::fail;
        using qi::omit;
        using qi::as_string;
        using qi::eps;
        using ascii::char_;
        using ascii::string;
 
        using phoenix::construct;
        using phoenix::val;
        using phoenix::push_back;
        
        type = string("number") | string("string");
        name = lexeme[+char_("a-zA-Z0-9_")];
        not_null_spec = string("not null") | string("");
        value = lexeme[+char_("a-zA-Z0-9_")];
        oper = string("=") | string("!=") | string("<=") | string(">=") | string("<") | string(">");
        cond = string("and") | string("or");
        aster = string("*");
 
        names = name > *(lit(",") > name);
        name_and_type = name > type > not_null_spec;
        name_and_value = name > string("=") > value;
        names_and_values = name_and_value > *(lit(",") > name_and_value);
        names_and_types = name_and_type > *(lit(",") > name_and_type);
        values = value > -(+(lit(",") > value));
        condition = name > oper > value;
        conditions = condition > *(cond > condition);
        where = string("where") > conditions;
        alter_add = string("add") > names_and_types;
        alter_drop = string("drop") > names;
        alter_alter = string("alter") > names_and_types;
 
        create = string("create") > name
            > lit("(") > names_and_types > lit(")") > lit(";");
 
        insert = string("insert") > string("into") > name
            > -(lit("(") > names > lit(")")) > string("values")
            > lit("(") > values > lit(")") > lit(";");
        
        select = string("select") > (names | aster) > string("from")
            > name > -where > lit(";");
 
        delete_ = string("delete") > string("from") > name
            > -where > lit(";");
        
        update = string("update") > name > string("set")
            > names_and_values > -where > lit(";");
        
        alter = string("alter") > name
            > (alter_add | alter_drop | alter_alter) > lit(";");
        
        truncate = string("truncate") > name > lit(";");
        drop = string("drop") > name > lit(";");
        desc = (string("desc") | string("describe")) > name > -lit(";");
        show = (string("show")) > -lit(";");
        quit = (string("quit") | string("exit")) > -lit(";");
        help = string("help") > -lit(";");
 
        root = create | insert | select | delete_ | update | alter | truncate
            | drop | desc | show | quit | help;
        
        root.name("expression");
        create.name("create command");
        name_and_type.name("name and type");
        names_and_types.name("names and types");
        type.name("value type");
        name.name("name");
        names.name("names");
        insert.name("insert command");
        value.name("value");
        values.name("values");
        select.name("select command");
        cond.name("cond");
        condition.name("condition");
        conditions.name("conditions");
        where.name("where");
        delete_.name("delete");
        name_and_value.name("name and value");
        names_and_values.name("names and values");
        alter_add.name("alter add command");
        alter_drop.name("alter drop command");
        alter_alter.name("alter alter command");
        alter.name("alter command");
        truncate.name("truncate command");
        drop.name("drop command");
        desc.name("describe command");
        show.name("show command");
        quit.name("quit command");
        help.name("help command");
 
        /*on_error<fail>
        (
           root,
           stream << val("Error! Expected ")
           << qi::_4
           << val(" here: \"")
           << construct<std::string>(qi::_3, qi::_2)
           << val("\"")
           << std::endl
        );*/
      auto function = [&stream_]
      (
         const fusion::vector<Iterator, const Iterator&, const Iterator&, const boost::spirit::info&>& pars,
         const typename sql_grammar::base_type::start_type::context_type&, const qi::error_handler_result&
      )
      {
         stream_ << "Error! Expected: " << fusion::at_c<3>(pars) << " here: \""
         << std::string(fusion::at_c<2>(pars), fusion::at_c<1>(pars)) << "\"" << std::endl;
      };
      on_error<fail>
      (
         root, function
      );
    }
    
    std::string get_error() const
    {
       std::string result = stream_.str();
       stream_.clear();
       return result;
    }
 
    qi::rule<Iterator, std::vector<std::string>(), qi::locals<std::string>, ascii::space_type> root;
    qi::rule<Iterator, std::vector<std::string>(), ascii::space_type> names_and_types, name_and_type, names,
        create, values, insert, select, where, conditions, condition, delete_, names_and_values, name_and_value,
        update, alter_add, alter_drop, alter_alter, alter, truncate, drop, desc, show, quit, help;
    qi::rule<Iterator, std::string(), ascii::space_type> type, name, not_null_spec, value,
        oper, cond, aster;
private:
    mutable std::ostringstream stream_;
};
 
template<typename Iterator>
std::ostream& operator << (std::ostream& os, const sql_grammar<Iterator>& grammar)
{
   os << grammar.get_error();
   return os;
}
 
class Parser_Error:public std::runtime_error
{
public:
    Parser_Error(const std::string& msg):std::runtime_error(msg)
    {
    }
};
 
class Parser
{
public:
    std::vector<std::string> operator() (const std::string& text)
    {
        std::string::const_iterator begin = text.begin();
        std::string::const_iterator end = text.end();
        sql_grammar<std::string::const_iterator> grammar;
        std::vector<std::string> temp;
        bool r = false;
        r = phrase_parse(begin, end, grammar, ascii::space, temp);
        if (r && begin == end)
        {
           return temp;
        }
        else
        {
            std::cout << grammar.get_error() << std::endl;
            throw Parser_Error("Parser error");
        }
    }
};
3
1186 / 542 / 78
Регистрация: 01.07.2009
Сообщений: 3,517
03.06.2012, 22:08  [ТС] 8
Написал создание таблиц и вставку данных в бд, а вот на SELECT застрял.
Это кошмар какой-то пытаться распарсить и обработать это:
SQL
1
2
SELECT * FROM TEST
SELECT * FROM TEST,TEST2 WHERE X=A;
Это же блин 100500 возможных вариантов: Может быть *, может быть имя одного из полей и тогда нужно шарить по всем таблицам искать это имя, потом может быть разный оператор сравнения (=, !=, <,>,>=,<= ), потом ещё нужно учесть что поля нужно сравнивать по разному же, а если учесть что WHERE может быть, а может не быть. Несколько таблиц может быть надо соединять, а может и не надо, а если надо то нужно ещё как-то их соединить и исключить повторы ... тупой SELECT.
0
В астрале
Эксперт С++
8049 / 4806 / 655
Регистрация: 24.06.2010
Сообщений: 10,562
03.06.2012, 23:46 9
Gepar, Ну без join-а у меня в коде все реализовано, не столь уж и сложно. А вот с join-ом - да. Трудно.
0
03.06.2012, 23:46
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
03.06.2012, 23:46
Помогаю со студенческими работами здесь

Организация базы данных
Доброе время суток! Хочу создать интернет магазин для себя и уменя возник вопрс по организации базы...

Внутренняя организация ОС
Помогите ответить на вопрос &quot;Внутренняя организация ОС на примере Windows&quot; Мне самому интересно...

Правильная организация базы данных
Добрый вечер уважаемый форум. Изучаю php путем создания своей небольшой игры. Сейчас добрался до...

Организация базы данных соревнований
Здравствуйте! В данный момент переписываю свою программу с Delphi на C#, и возникла идея...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
9
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru