Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sstream>
- const string DayNumbers[] = {"MON", "TUE", "WEN", "THU", "FRI", "SAT", "SUN"};
- const string __ALL_DATA_FILENAME("__ALL_DATA.dbase");
- //----------------------------------------------------------------------------//
- // какие-то базовые структуры //
- @@ -30,6 +29,13 @@ WeekDay GetDayFromString(string s) {
- return MON;//костыль для строгого компилятора
- }
- string to_string(int num) {
- stringstream ss;
- ss << num;
- return ss.str();
- }
- //----------------------------------------------------------------------------//
- // структуры, представляющие запрос в памяти //
- //----------------------------------------------------------------------------//
- @@ -113,51 +119,10 @@ bool CheckCondition(LessonInfo record, Cond condition) {//проверка, уд
- }
- //----------------------------------------------------------------------------//
- // класс для хранения записей //
- // сама база данных //
- //----------------------------------------------------------------------------//
- RecordsContainer::~RecordsContainer() {}
- RecordsContainer::RecordsContainer():
- recs_(),
- recs_n_(0),
- teachers_(),
- groups_(),
- rooms_(),
- days_(),
- times_(),
- subjects_()
- {}
- RecordsContainer::RecordsContainer(string filename):
- recs_(),
- recs_n_(),
- teachers_(),
- groups_(),
- rooms_(),
- days_(),
- times_(),
- subjects_() {
- //импорт из файла...
- }
- RecordsContainer::RecordsContainer(RecordsContainer& other, SearchConditions conds):
- recs_(),
- recs_n_(other.Size()),
- teachers_(),
- groups_(),
- rooms_(),
- days_(),
- times_(),
- subjects_()
- {
- IndicesList indlist = other.SelectByConditionList(conds);
- for(IndicesList::iterator it = indlist.begin(); it != indlist.end(); it++) {
- AddRecord(**it);
- }
- }
- IndicesList RecordsContainer::SelectByCondition(Cond condition) {
- IndicesList Database::SelectByCondition(Cond condition) {
- IndicesList res;
- //здесь должно быть нечто объёмное
- //отчасти похоже на checkcondition(), но сложнее
- @@ -186,7 +151,7 @@ template<typename T> list<T> IntersectionOfLists(list<T> a, list<T> b) {
- return res;
- }
- IndicesList RecordsContainer::SelectByConditionList(SearchConditions cond_list) {
- IndicesList Database::SelectByConditionList(SearchConditions cond_list) {
- if (cond_list.begin() == cond_list.end()) {//если условий нет -- возвращаем все записи
- IndicesList all;
- @@ -226,7 +191,7 @@ template<typename T> void RemoveFromMapList (map<T,IndicesList>& data, T key, Db
- }
- }
- void RecordsContainer::AddRecord(LessonInfo rec) {
- void Database::AddRecord(LessonInfo rec) {
- recs_.push_back(rec);
- recs_n_++;
- DbIndex index = recs_.end();
- @@ -239,7 +204,7 @@ void RecordsContainer::AddRecord(LessonInfo rec) {
- AddToMapList(subjects_, rec.subject_, index);
- }
- void RecordsContainer::RemoveRecord(DbIndex index) {
- void Database::RemoveRecord(DbIndex index) {
- RemoveFromMapList(teachers_, index->teacher_, index);
- RemoveFromMapList( groups_, index->group_, index);
- RemoveFromMapList( rooms_, index->room_, index);
- @@ -251,28 +216,24 @@ void RecordsContainer::RemoveRecord(DbIndex index) {
- recs_n_--;
- }
- void RecordsContainer::RemoveRecords(const SearchConditions conds) {
- void Database::RemoveRecords(const SearchConditions conds) {
- IndicesList blacklist = SelectByConditionList(conds);
- for(IndicesList::iterator it = blacklist.begin(); it != blacklist.end(); it++) {
- RemoveRecord(*it);
- }
- }
- void RecordsContainer::SaveToFile(string filename) const {
- void Database::SaveToFile(string filename) const {
- //запись в файл...
- }
- //----------------------------------------------------------------------------//
- // основные классы //
- //----------------------------------------------------------------------------//
- Database::Database(string filename):
- data_(filename),
- filename_(filename)
- {}
- Database::Database(string filename) {
- //загрузка из файла
- }
- Database::~Database() {
- SaveToFile();
- SaveToFile(filename_);
- }
- void Database::ImplementInsert (const SearchConditions& sc) {
- @@ -287,15 +248,15 @@ void Database::ImplementInsert (const SearchConditions& sc) {
- SetInfo(rec, *it);//помещает в запись информацию из условия
- }
- data_.AddRecord(rec);
- AddRecord(rec);
- }
- int Database::ImplementRemove (const SearchConditions& sc) {//возвращает число удалённых записей
- int res = data_.Size();
- int res = Size();
- data_.RemoveRecords(sc);
- RemoveRecords(sc);
- return res - data_.Size();
- return res - Size();
- }
- string Database::ImplementPrint (const SearchConditions& sc) {//возвращает напечатанную таблицу
- @@ -337,36 +298,22 @@ string Database::HandleQuery(const string& query, Session& s){
- return ImplementCommand(parse(query), s);
- }
- void Database::SaveToFile() const {
- data_.SaveToFile(filename_);
- }
- Session::~Session() {}
- Session::Session():
- selection_()
- {}
- //----------------------------------------------------------------------------//
- // парсер и т.д. //
- //----------------------------------------------------------------------------//
- int Database::ImplementSelect (const SearchConditions& sc, Session& s) {
- s.selection_ = RecordsContainer(data_, sc);
- s.SetSelection(SelectByConditionList(sc));
- }
- int Database::ImplementReselect(const SearchConditions& sc, Session& s) {
- s.selection_ = RecordsContainer(s.selection_, sc);
- IndicesList old_selection = s.GetSelection();
- s.SetSelection(IntersectionOfLists(old_selection,
- SelectByConditionList(sc))
- );
- }
- string to_string(int num) {
- stringstream ss;
- ss << num;
- return ss.str();
- }
- Command parse(const string& query) {
- Command res;
- //растаскивание строчки на кусочки...
- @@ -26,6 +26,7 @@ struct LessonInfo {
- };
- WeekDay GetDayFromString(string s);
- string to_string(int num);//дубликат на всякий случай
- //----------------------------------------------------------------------------//
- // структуры, представляющие запрос в памяти (``синтаксический анализ'') //
- //----------------------------------------------------------------------------//
- @@ -69,12 +70,26 @@ void SetInfo(LessonInfo& record, Cond cond_data);
- bool CheckCondition(LessonInfo record, Cond condition);
- //проверка, удовлетворяет ли запись условию (нужна для реализации Insert)
- //----------------------------------------------------------------------------//
- // класс для хранения записей //
- //----------------------------------------------------------------------------//
- typedef list<LessonInfo>::iterator DbIndex;
- typedef list<DbIndex> IndicesList;
- //----------------------------------------------------------------------------//
- // сессия //
- //----------------------------------------------------------------------------//
- class Session {
- private:
- IndicesList selection_;
- public:
- ~Session() {}
- Session() {}
- IndicesList GetSelection() const {return selection_;}
- void SetSelection(IndicesList s) {selection_ = s;}
- };
- //----------------------------------------------------------------------------//
- // сама база данных //
- //----------------------------------------------------------------------------//
- template<typename T> list<T> IntersectionOfLists(list<T> a, list<T> b);
- @@ -85,7 +100,9 @@ template<typename T> void AddToMapList (map<T,IndicesList>& data, T key, DbIndex
- template<typename T> void RemoveFromMapList (map<T,IndicesList>& data, T key, DbIndex index);
- //обратная операция
- class RecordsContainer {
- class Database {
- private:
- list<LessonInfo> recs_;
- int recs_n_;
- @@ -102,45 +119,23 @@ class RecordsContainer {
- IndicesList SelectByConditionList(SearchConditions conds);
- //возвращает список всех записей, удовл. данным условиям
- public:
- ~RecordsContainer();
- RecordsContainer();
- RecordsContainer(string filename);//конструктор из файла (запускает LoadFromFile)
- RecordsContainer(RecordsContainer& other, SearchConditions conds);
- //создаёт новую базу -- выборку из записей, удовл. данным условиям
- string filename_;
- void AddRecord(LessonInfo rec);
- void RemoveRecord(DbIndex index);
- void RemoveRecords(SearchConditions conds);
- void SaveToFile(string filename) const;
- int Size() const {return recs_n_;}
- };
- //----------------------------------------------------------------------------//
- // основные классы //
- //----------------------------------------------------------------------------//
- class Session {
- friend class Database;//даёт методам класса Database доступ к selection_
- private:
- RecordsContainer selection_;
- // возможно, что-то ещё добавится
- public:
- ~Session();
- Session();
- };
- class Database {
- private:
- RecordsContainer data_;
- string filename_;
- //возвращают число выбранных записей
- int ImplementSelect (const SearchConditions& sc, Session& s);
- int ImplementReselect(const SearchConditions& sc, Session& s);
- //редиректы на соотв. методы для RecordsContainer
- //редиректы на соотв. методы для Database
- void ImplementInsert (const SearchConditions& sc);
- int ImplementRemove (const SearchConditions& sc);
- @@ -149,6 +144,7 @@ class Database {
- //перенаправляет на обработчики; формирует ответ на запрос
- string ImplementCommand(const Command& t, Session& s);
- public:
- ~Database();
- Database(string filename);
- @@ -157,8 +153,6 @@ class Database {
- string HandleQuery(const string& query, Session& s);
- };
- //----------------------------------------------------------------------------//
- // парсер и т.д. //
- //----------------------------------------------------------------------------//
- Vylegzhanin_FE/R4/test.cpp
- @@ -4,5 +4,6 @@
- int main() {
- Session s;
- Database db("test.dbase");
- db.HandleQuery("foo", s);
- string query("foo");
- db.HandleQuery(query, s);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement