コード例 #1
0
    def insert_record(self, values: Dict[str, Any]) -> None:

        new_record = [
            values.get(field.name) for field in self.fields
            if isinstance(values.get(field.name), field.type)
        ]
        if len(new_record) != len(self.fields):
            raise TypeError(f"fields' type don't match to the table" +
                            self.name)

        with open(DB_ROOT.joinpath(self.name + '.csv'), 'r') as table:
            reader = csv.reader(table)

            for row in reader:
                if row[self.key_index] == str(new_record[self.key_index]):
                    raise ValueError(
                        "The value of the key field already exists")

        with open(DB_ROOT.joinpath(self.name + '.csv'), 'a',
                  newline='') as table:
            writer = csv.writer(table)
            writer.writerow(new_record)

        self.num_rows += 1
        self.__update_backup()
コード例 #2
0
    def update_record(self, key: Any, values: Dict[str, Any]) -> None:

        with open(DB_ROOT.joinpath(self.name + '.csv'), 'r') as table:
            rows = []
            key_str = str(key)
            reader = csv.DictReader(table)

            for row in reader:
                print(row)
                if row[self.key_field_name] == key_str:
                    exist = True
                    for k, v in values.items():
                        if row.get(k):
                            row[k] = v
                        else:
                            raise KeyError("key doesn't exist")
                rows.append(row)

        if not exist:
            raise ValueError("The value of the key field doesn't exists")

        with open(DB_ROOT.joinpath(self.name + '.csv'), 'w',
                  newline='') as table:
            writer = csv.DictWriter(
                table, fieldnames=[field.name for field in self.fields])
            writer.writeheader()
            writer.writerows(rows)

        self.__update_backup()
コード例 #3
0
def test_reload_from_backup(backup_db: Path) -> None:
    """This test requires preparing the backup by calling create_db_backup()"""
    delete_files(DB_ROOT)
    DB_ROOT.rmdir()
    shutil.copytree(str(backup_db), str(DB_ROOT))
    db = DataBase()
    assert db.num_tables() == 1
    assert db.get_tables_names() == ['Students']
    students = db.get_table('Students')
    assert students.count() == 100
コード例 #4
0
    def delete_table(self, table_name: str) -> None:
        try:
            self.__tables.pop(table_name)
            try:
                os.remove(DB_ROOT.joinpath(table_name + '.csv'))
                os.remove(DB_ROOT.joinpath(table_name + '_backup.json'))
            except FileNotFoundError:
                print("something got wrong...")
        except KeyError:
            raise NameError("this table doesnt exist")

        self.__update_backup()
コード例 #5
0
def create_db_backup() -> Path:
    DB_BACKUP_ROOT.mkdir(parents=True, exist_ok=True)
    delete_files(DB_BACKUP_ROOT)
    db = DataBase()
    create_students_table(db, 100)
    for path in DB_ROOT.iterdir():
        path.rename(DB_BACKUP_ROOT / path.name)
    return DB_BACKUP_ROOT
コード例 #6
0
    def delete_records(self, criteria: List[SelectionCriteria]) -> None:
        rows = []

        with open(DB_ROOT.joinpath(self.name + '.csv'), 'r') as table:
            reader = csv.DictReader(table)

            for row in reader:
                if self.__satisfy(row, criteria):
                    self.num_rows -= 1
                else:
                    rows.append(row)

        with open(DB_ROOT.joinpath(self.name + '.csv'), 'w',
                  newline='') as table:
            writer = csv.DictWriter(
                table, fieldnames=[field.name for field in self.fields])
            writer.writeheader()
            writer.writerows(rows)

        self.__update_backup()
コード例 #7
0
    def delete_record(self, key: Any) -> None:
        rows = []
        exist = False
        with open(DB_ROOT.joinpath(self.name + '.csv'), 'r') as table:
            reader = csv.reader(table)
            for row in reader:
                if row and row[self.key_index] == str(key):
                    exist = True
                else:
                    rows.append(row)

        if not exist:
            raise ValueError("The value of the key field doesn't exists")

        with open(DB_ROOT.joinpath(self.name + '.csv'), 'w') as table:
            writer = csv.writer(table)
            writer.writerows(rows)

        self.num_rows -= 1
        self.__update_backup()
コード例 #8
0
    def query_table(self,
                    criteria: List[SelectionCriteria]) -> List[Dict[str, Any]]:
        result = []

        with open(DB_ROOT.joinpath(self.name + '.csv'), 'r') as table:
            reader = csv.DictReader(table)

            for row in reader:
                if self.__satisfy(row, criteria):
                    result.append(row)
        return result
コード例 #9
0
    def get_record(self, key: Any) -> Dict[str, Any]:

        with open(DB_ROOT.joinpath(self.name + '.csv'), 'r') as table:
            reader = csv.DictReader(table)
            key_str = str(key)

            for row in reader:
                if key_str == row.get(self.key_field_name):
                    return row

            raise ValueError("key doesn't exist")
コード例 #10
0
    def create_table(self,
                     table_name: str,
                     fields: List[DBField],
                     key_field_name: str) -> DBTable:

        if Path(DB_ROOT.joinpath(table_name + '.csv')).is_file():
            print(f" { table_name } table already exists")
            self.__reload_backup()
        else:
            exist = False

            for filed in fields:
                if filed.name == key_field_name:
                    exist = True
            if not exist:
                raise ValueError("key field does not exist")

            with open(DB_ROOT.joinpath(table_name + '.csv'), 'w', newline='') as table:
                writer = csv.writer(table)
                writer.writerow([field.name for field in fields])
        self.__tables[table_name] = DBTable(table_name, fields, key_field_name)
        self.__update_backup()
        return self.__tables[table_name]