Advertisement
Guest User

Untitled

a guest
Apr 8th, 2020
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 11.04 KB | None | 0 0
  1. #include <sstream>
  2.  
  3. const string DayNumbers[] = {"MON", "TUE", "WEN", "THU", "FRI", "SAT", "SUN"};
  4. const string __ALL_DATA_FILENAME("__ALL_DATA.dbase");
  5.  
  6. //----------------------------------------------------------------------------//
  7. //                        какие-то базовые структуры                          //
  8. @@ -30,6 +29,13 @@ WeekDay GetDayFromString(string s) {
  9.  
  10.     return MON;//костыль для строгого компилятора
  11. }
  12.  
  13. string to_string(int num) {
  14.     stringstream ss;
  15.     ss << num;
  16.     return ss.str();
  17. }
  18.  
  19. //----------------------------------------------------------------------------//
  20. //                 структуры, представляющие запрос в памяти                  //
  21. //----------------------------------------------------------------------------//
  22. @@ -113,51 +119,10 @@ bool CheckCondition(LessonInfo record, Cond condition) {//проверка, уд
  23. }
  24.  
  25. //----------------------------------------------------------------------------//
  26. //                        класс для хранения записей                          //
  27. //                        сама база данных                                    //
  28. //----------------------------------------------------------------------------//
  29. RecordsContainer::~RecordsContainer() {}
  30.  
  31. RecordsContainer::RecordsContainer():
  32.     recs_(),
  33.     recs_n_(0),
  34.     teachers_(),
  35.     groups_(),
  36.     rooms_(),
  37.     days_(),
  38.     times_(),
  39.     subjects_()
  40.     {}
  41.  
  42. RecordsContainer::RecordsContainer(string filename):
  43.     recs_(),
  44.     recs_n_(),
  45.     teachers_(),
  46.     groups_(),
  47.     rooms_(),
  48.     days_(),
  49.     times_(),
  50.     subjects_() {
  51.     //импорт из файла...
  52. }
  53.  
  54. RecordsContainer::RecordsContainer(RecordsContainer& other, SearchConditions conds):
  55.     recs_(),
  56.     recs_n_(other.Size()),
  57.     teachers_(),
  58.     groups_(),
  59.     rooms_(),
  60.     days_(),
  61.     times_(),
  62.     subjects_()
  63.     {
  64.     IndicesList indlist = other.SelectByConditionList(conds);
  65.     for(IndicesList::iterator it = indlist.begin(); it != indlist.end(); it++) {
  66.         AddRecord(**it);
  67.     }
  68. }
  69.  
  70.  
  71. IndicesList RecordsContainer::SelectByCondition(Cond condition) {
  72. IndicesList Database::SelectByCondition(Cond condition) {
  73.     IndicesList res;
  74. //здесь должно быть нечто объёмное
  75. //отчасти похоже на checkcondition(), но сложнее
  76. @@ -186,7 +151,7 @@ template<typename T> list<T> IntersectionOfLists(list<T> a, list<T> b) {
  77.     return res;
  78. }
  79.  
  80. IndicesList RecordsContainer::SelectByConditionList(SearchConditions cond_list) {
  81. IndicesList Database::SelectByConditionList(SearchConditions cond_list) {
  82.  
  83.     if (cond_list.begin() == cond_list.end()) {//если условий нет -- возвращаем все записи
  84.         IndicesList all;
  85. @@ -226,7 +191,7 @@ template<typename T> void RemoveFromMapList (map<T,IndicesList>& data, T key, Db
  86.     }
  87. }
  88.  
  89. void RecordsContainer::AddRecord(LessonInfo rec) {
  90. void Database::AddRecord(LessonInfo rec) {
  91.     recs_.push_back(rec);
  92.     recs_n_++;
  93.     DbIndex index = recs_.end();
  94. @@ -239,7 +204,7 @@ void RecordsContainer::AddRecord(LessonInfo rec) {
  95.     AddToMapList(subjects_, rec.subject_, index);
  96. }
  97.  
  98. void RecordsContainer::RemoveRecord(DbIndex index) {
  99. void Database::RemoveRecord(DbIndex index) {
  100.     RemoveFromMapList(teachers_, index->teacher_, index);
  101.     RemoveFromMapList(  groups_, index->group_,   index);
  102.     RemoveFromMapList(   rooms_, index->room_,    index);
  103. @@ -251,28 +216,24 @@ void RecordsContainer::RemoveRecord(DbIndex index) {
  104.     recs_n_--;
  105. }
  106.  
  107. void RecordsContainer::RemoveRecords(const SearchConditions conds) {
  108. void Database::RemoveRecords(const SearchConditions conds) {
  109.     IndicesList blacklist = SelectByConditionList(conds);
  110.  
  111.     for(IndicesList::iterator it = blacklist.begin(); it != blacklist.end(); it++) {
  112.         RemoveRecord(*it);
  113.     }
  114. }
  115.  
  116. void RecordsContainer::SaveToFile(string filename) const {
  117. void Database::SaveToFile(string filename) const {
  118.     //запись в файл...
  119. }
  120.  
  121. //----------------------------------------------------------------------------//
  122. //                             основные классы                                //
  123. //----------------------------------------------------------------------------//
  124. Database::Database(string filename):
  125.     data_(filename),
  126.     filename_(filename)
  127.     {}
  128. Database::Database(string filename) {
  129.     //загрузка из файла
  130. }
  131.  
  132. Database::~Database() {
  133.     SaveToFile();
  134.     SaveToFile(filename_);
  135. }
  136.  
  137. void Database::ImplementInsert  (const SearchConditions& sc) {
  138. @@ -287,15 +248,15 @@ void Database::ImplementInsert  (const SearchConditions& sc) {
  139.  
  140.         SetInfo(rec, *it);//помещает в запись информацию из условия
  141.     }
  142.     data_.AddRecord(rec);
  143.     AddRecord(rec);
  144. }
  145.  
  146. int Database::ImplementRemove  (const SearchConditions& sc) {//возвращает число удалённых записей
  147.     int res = data_.Size();
  148.     int res = Size();
  149.  
  150.     data_.RemoveRecords(sc);
  151.     RemoveRecords(sc);
  152.  
  153.     return res - data_.Size();
  154.     return res - Size();
  155. }
  156.  
  157. string Database::ImplementPrint   (const SearchConditions& sc) {//возвращает напечатанную таблицу
  158. @@ -337,36 +298,22 @@ string Database::HandleQuery(const string& query, Session& s){
  159.     return ImplementCommand(parse(query), s);
  160. }
  161.  
  162. void Database::SaveToFile() const {
  163.     data_.SaveToFile(filename_);
  164. }
  165.  
  166. Session::~Session() {}
  167. Session::Session():
  168.     selection_()
  169.     {}
  170.  
  171. //----------------------------------------------------------------------------//
  172. //                              парсер и т.д.                                 //
  173. //----------------------------------------------------------------------------//
  174. int Database::ImplementSelect  (const SearchConditions& sc, Session& s) {
  175.     s.selection_ = RecordsContainer(data_, sc);
  176.     s.SetSelection(SelectByConditionList(sc));
  177. }
  178.  
  179. int Database::ImplementReselect(const SearchConditions& sc, Session& s) {
  180.     s.selection_ = RecordsContainer(s.selection_, sc);
  181.     IndicesList old_selection = s.GetSelection();
  182.     s.SetSelection(IntersectionOfLists(old_selection,
  183.                                        SelectByConditionList(sc))
  184.                   );
  185. }
  186.  
  187.  
  188.  
  189. string to_string(int num) {
  190.     stringstream ss;
  191.     ss << num;
  192.     return ss.str();
  193. }
  194.  
  195.  
  196.  
  197. Command parse(const string& query) {
  198.     Command res;
  199.     //растаскивание строчки на кусочки...
  200.  
  201.  
  202.  
  203.  
  204.  
  205.  
  206. @@ -26,6 +26,7 @@ struct LessonInfo {
  207. };
  208.  
  209. WeekDay GetDayFromString(string s);
  210. string to_string(int num);//дубликат на всякий случай
  211. //----------------------------------------------------------------------------//
  212. //   структуры, представляющие запрос в памяти (``синтаксический анализ'')    //
  213. //----------------------------------------------------------------------------//
  214. @@ -69,12 +70,26 @@ void SetInfo(LessonInfo& record, Cond cond_data);
  215. bool CheckCondition(LessonInfo record, Cond condition);
  216. //проверка, удовлетворяет ли запись условию (нужна для реализации Insert)
  217.  
  218. //----------------------------------------------------------------------------//
  219. //                        класс для хранения записей                          //
  220. //----------------------------------------------------------------------------//
  221.  
  222. typedef list<LessonInfo>::iterator DbIndex;
  223. typedef list<DbIndex> IndicesList;
  224. //----------------------------------------------------------------------------//
  225. //                              сессия                                        //
  226. //----------------------------------------------------------------------------//
  227. class Session {
  228. private:
  229.     IndicesList selection_;
  230. public:
  231.     ~Session() {}
  232.     Session() {}
  233.     IndicesList GetSelection() const {return selection_;}
  234.     void SetSelection(IndicesList s) {selection_ = s;}
  235. };
  236.  
  237.  
  238. //----------------------------------------------------------------------------//
  239. //                        сама база данных                                    //
  240. //----------------------------------------------------------------------------//
  241.  
  242. template<typename T> list<T> IntersectionOfLists(list<T> a, list<T> b);
  243.  
  244. @@ -85,7 +100,9 @@ template<typename T> void AddToMapList (map<T,IndicesList>& data, T key, DbIndex
  245. template<typename T> void RemoveFromMapList (map<T,IndicesList>& data, T key, DbIndex index);
  246. //обратная операция
  247.  
  248. class RecordsContainer {
  249. class Database {
  250. private:
  251.  
  252.     list<LessonInfo> recs_;
  253.     int recs_n_;
  254.  
  255. @@ -102,45 +119,23 @@ class RecordsContainer {
  256.     IndicesList SelectByConditionList(SearchConditions conds);
  257.     //возвращает список всех записей, удовл. данным условиям
  258.  
  259. public:
  260.     ~RecordsContainer();
  261.     RecordsContainer();
  262.     RecordsContainer(string filename);//конструктор из файла (запускает LoadFromFile)
  263.  
  264.     RecordsContainer(RecordsContainer& other, SearchConditions conds);
  265.     //создаёт новую базу -- выборку из записей, удовл. данным условиям
  266.  
  267.     string filename_;
  268.  
  269.     void AddRecord(LessonInfo rec);
  270.     void RemoveRecord(DbIndex index);
  271.     void RemoveRecords(SearchConditions conds);
  272.     void SaveToFile(string filename) const;
  273.  
  274.     int Size() const {return recs_n_;}
  275. };
  276.  
  277. //----------------------------------------------------------------------------//
  278. //                              основные классы                               //
  279. //----------------------------------------------------------------------------//
  280. class Session {
  281.     friend class Database;//даёт методам класса Database доступ к selection_
  282. private:
  283.     RecordsContainer selection_;
  284. // возможно, что-то ещё добавится
  285. public:
  286.     ~Session();
  287.     Session();
  288. };
  289.  
  290. class Database {
  291. private:
  292.     RecordsContainer data_;
  293.     string filename_;
  294.  
  295.     //возвращают число выбранных записей
  296.     int    ImplementSelect  (const SearchConditions& sc, Session& s);
  297.     int    ImplementReselect(const SearchConditions& sc, Session& s);
  298.  
  299.     //редиректы на соотв. методы для RecordsContainer
  300.     //редиректы на соотв. методы для Database
  301.     void   ImplementInsert  (const SearchConditions& sc);
  302.     int    ImplementRemove  (const SearchConditions& sc);
  303.  
  304. @@ -149,6 +144,7 @@ class Database {
  305.  
  306.     //перенаправляет на обработчики; формирует ответ на запрос
  307.     string ImplementCommand(const Command& t, Session& s);
  308.  
  309. public:
  310.     ~Database();
  311.     Database(string filename);
  312. @@ -157,8 +153,6 @@ class Database {
  313.     string HandleQuery(const string& query, Session& s);
  314. };
  315.  
  316.  
  317.  
  318. //----------------------------------------------------------------------------//
  319. //                        парсер и т.д.                                       //
  320. //----------------------------------------------------------------------------//
  321.  
  322.  
  323.  
  324.  
  325.  
  326. Vylegzhanin_FE/R4/test.cpp
  327. @@ -4,5 +4,6 @@
  328. int main() {
  329.     Session s;
  330.     Database db("test.dbase");
  331.     db.HandleQuery("foo", s);
  332.     string query("foo");
  333.     db.HandleQuery(query, s);
  334. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement