def insert(self, *args):
        # Validate that the provided row data is correct according to the
        # columns configuration.
        # If there's any error, raise ValidationError exception.
        # Otherwise, serialize the row as a string, and write to to the
        # table's JSON file.

        if len(args) != len(self.columns):
            raise ValidationError("Invalid amount of field")

        the_row_dict = {}
        for arg, column in zip(args, self.columns):
            if not isinstance(arg, eval(column['type'])):
                raise ValidationError(
                    'Invalid type of field "{}": Given "{}", expected "{}"'.
                    format(column['name'],
                           type(arg).__name__, column['type']))
            else:
                if isinstance(arg, date):
                    the_row_dict[column['name']] = arg.isoformat()
                else:
                    the_row_dict[column['name']] = arg

        table_data = self.open_json()

        table_data['rows'].append(the_row_dict)

        self.write_json(table_data)
Beispiel #2
0
    def insert(self, *args):
        # Validate that the provided row data is correct according to the
        # columns configuration.
        # If there's any error, raise ValidationError exception.
        # Otherwise, serialize the row as a string, and write to to the
        # table's JSON file.
        # Check length, if != raise Validation
        if len(args) != len(self.columns):
            raise ValidationError('Invalid amount of fields.')
        dict_to_add = {}
        for arg, col in zip(args, self.columns):
            if type(arg).__name__ == col['type']:
                if isinstance(arg, date):
                    arg = str(arg)
                dict_to_add[col['name']] = arg
            else:
                raise ValidationError(
                    """Invalid type of field "{}": Given "{}", \
expected "{}"
""".format(col['name'],
                type(arg).__name__, col['type']))
        # Port args over to .json file
        with open(self.table_filepath, 'r+') as file:
            json_file = json.load(file)
            if len(dict_to_add) == 0:
                pass
            json_file['rows'].append(dict_to_add)
            file.seek(0)
            file.write(json.dumps(json_file))
 def insert(self, *args):
     # Validate that the provided row data is correct according to the
     # columns configuration.
     # If there's any error, raise ValidationError exception.
     # Otherwise, serialize the row as a string, and write to to the
     # table's JSON file.
     new = []
     dict1 = {}
     if len(args) != len(self.columns):
         raise ValidationError('Invalid amount of field')
     
     for arg in args:
         for col in self.columns:
             if not type(arg) == eval(col['type']):
                 raise ValidationError('Invalid type of field "{}": Given "{}", expected "{}"').format(col['name'], type(arg), col['type'])
     
     for col in self.columns:
         new.append(col['name'])
     zipped = zip(new, args)
     for k,v in zipped:
         dict1[k] = v
     with open(self.table_filepath, 'r+') as f:
         data = json.load(f)
         data['rows'].append(dict1)
         json.dumps(data, f)
Beispiel #4
0
    def insert(self, *args):
        # Validate that the provided row data is correct according to the
        # columns configuration.
        # If there's any error, raise ValidationError exception.
        # Otherwise, serialize the row as a string, and write to to the
        # table's JSON file.
        new = []
        dict1 = {}
        if len(args) != len(self.columns):
            raise ValidationError('Invalid amount of field')

        for element, col in enumerate(self.columns):
            if type(args[element]).__name__ != col['type']:
                raise ValidationError(
                    'Invalid type of field "{}": Given "{}", expected "{}"'.
                    format(col['name'],
                           type(args[element]).__name__, col['type']))

        for col in self.columns:
            new.append(col['name'])
        zipped = zip(new, args)
        for k, v in zipped:
            dict1[k] = v
        with open(self.table_filepath, 'r+') as f:
            data = json.load(f)
            data['rows'].append(dict1)
            f.seek(0)
            f.write(json.dumps(data, cls=DatetimeEncoder))
Beispiel #5
0
    def insert(self, *args):
        # Validate that the provided row data is correct according to the
        # columns configuration.
        # If there's any error, raise ValidationError exception.
        # Otherwise, serialize the row as a string, and write to to the
        # table's JSON file.

        #check if data is correct format and type
        if len(self.columns) != len(args):
            raise ValidationError('Invalid amount of field')

        to_insert = {}
        for col_type, insert_value in zip(self.columns, args):
            if type(insert_value).__name__ == col_type['type']:
                to_insert[col_type['name']] = insert_value
            else:
                raise ValidationError(
                    'Invalid type of field "{}": Given "{}", expected "{}"'.
                    format(col_type['name'],
                           type(insert_value).__name__, col_type['type']))

        with open(self.table_filepath, 'r+') as f:
            data = json.load(f)
            data['rows'].append(to_insert)
            f.seek(0)
            f.write(json.dumps(data, cls=DateTimeEncoder))
Beispiel #6
0
 def create(cls, name):
     db_filepath = os.path.join(BASE_DB_FILE_PATH, name)
     # if the db directory already exists, raise ValidationError
     # otherwise, create the proper db directory
     if os.path.exists(db_filepath):
         msg = ('Database with name "{}" already exists.'.format(name))
         raise ValidationError(msg)
     os.makedirs(db_filepath)
Beispiel #7
0
 def create(cls, name):
     filepath = os.path.join(BASE_DB_FILE_PATH, name)
     # if the db directory already exists, raise ValidationError
     # otherwise, create the proper db directory
     if os.path.exists(filepath):
         raise ValidationError()
     else:
         os.makedirs(filepath)
Beispiel #8
0
def create_database(db_name):
    """
    Creates a new DataBase object and returns the connection object
    to the brand new database.
    """
    if os.path.exists(BASE_DB_FILE_PATH + db_name):
        raise ValidationError('Database with name "{}" already exists.'.format(db_name))
    DataBase.create(db_name)
    return connect_database(db_name)
Beispiel #9
0
    def insert(self, *args):
        if len(args) != len(self.columns):
            raise ValidationError('Invalid amount of field')

        new_row = {}
        for index, column in enumerate(self.columns):
            ctype = column['type']
            atype = type(args[index]).__name__
            if ctype != atype:
                raise ValidationError(
                    'Invalid type of field "{}": Given "{}", expected "{}"'.
                    format(column['name'], atype, ctype))
            new_row[column['name']] = args[index]

        with open(self.table_filepath, 'r+') as f:
            data = json.load(f)
            data['rows'].append(new_row)
            f.seek(0)
            f.write(json.dumps(data, cls=DateTimeEncoder))
Beispiel #10
0
 def insert(self, *args):
     # Validate that the provided row data is correct according to the
     # columns configuration.
     # If there's any error, raise ValidationError exception.
     # Otherwise, serialize the row as a string, and write to to the
     # table's JSON file.
     valid, msg = self._validate_row(*args)
     if not valid:
         raise ValidationError(msg)
     row = self._format_row(*args)
     return self._insert_row(row)
Beispiel #11
0
 def create_table(self, table_name, columns):
     # Check if a table already exists with given name. If so, raise
     # ValidationError exception.
     # Otherwise, create an instance of the `Table` class and assign
     # it to the current db object.
     # Make sure to also append it to `self.tables`
     if table_name in self.tables:
         raise ValidationError('Database with name "{}" already exists.'.format(table_name))
     else:
         new_table = Table(self, table_name, columns)
         self.tables.append(new_table)
         setattr(self, new_table.name, new_table)
Beispiel #12
0
    def insert(self, *args):
        # Validate that the provided row data is correct according to the
        # columns configuration.
        # If there's any error, raise ValidationError exception.
        # Otherwise, serialize the row as a string, and write to to the
        # table's JSON file.

        if len(args) != len(self.columns):
            raise ValidationError('Invalid amount of field')

        data = {}
        for i, col in enumerate(self.columns):
            f_name = col['name']
            f_type = col['type']
            arg_type = type(args[i]).__name__
            if f_type == arg_type:
                data[f_name] = args[i]
            else:
                raise ValidationError(
                    'Invalid type of field "{}": Given "{}", expected "{}"'.
                    format(f_name, arg_type, f_type))
        self._write_row(data)
Beispiel #13
0
 def create_table(self, table_name, columns):
     # Check if a table already exists with given name. If so, raise
     # ValidationError exception.
     # Otherwise, crete an instance of the `Table` class and assign
     # it to the current db object.
     # Make sure to also append it to `self.tables`
     if table_name in self._read_tables():
         error_msg ='Table with name "{}" already exists.'.format(table_name)
         raise ValidationError(error_msg)
     else:
         table = Table(db=self, name=table_name)
         setattr(self, table_name, table)
         self.tables.append(table_name)
Beispiel #14
0
    def insert(self, *args):
        # Validate that the provided row data is correct according to the
        # columns configuration.
        # If there's any error, raise ValidationError exception.
        # Otherwise, serialize the row as a string, and write to the
        # table's JSON file.

        if len(args) != len(self.columns):
            raise ValidationError("Invalid amount of field")

        # columns_length = len(self.columns)
        # arguments_length = len(args)

        for i, item in enumerate(args):
            if type(item).__name__ != self.columns[i]['type']:
                column_name = self.columns[i]['name']
                column_type = self.columns[i]['type']
                item_type = type(item).__name__
                error_msg = 'Invalid type of field "{}": Given "{}", expected "{}"'.format(
                    column_name, item_type, column_type)
                raise ValidationError(error_msg)
        else:
            with open(self.table_filepath, 'r+') as f:
                table_data = json.load(f)
                serialized_args = []
                for each_arg in args:
                    if type(each_arg).__name__ == 'date':
                        serialized_args.append(each_arg.isoformat())
                    else:
                        serialized_args.append(each_arg)

                new_row = {}
                for idx, column in enumerate(self.columns):
                    new_row[column['name']] = serialized_args[idx]

                table_data['rows'].append(new_row)
                f.seek(0)
                f.write(json.dumps(table_data))
 def create_table(self, table_name, columns):
     # Check if a table already exists with given name. If so, raise
     # ValidationError exception.
     # Otherwise, crete an instance of the `Table` class and assign
     # it to the current db object.
     # Make sure to also append it to `self.tables`
     if hasattr(self, table_name):
         raise ValidationError("table already exists")
     elif not isinstance(columns, list):
         raise ValidationError
     else:
         new_table = Table(self, table_name, columns)
         setattr(self, table_name, new_table)
         self._read_tables()
Beispiel #16
0
    def create_table(self, table_name, columns):
        # Check if a table already exists with given name. If so, raise
        # ValidationError exception.
        # Otherwise, crete an instance of the `Table` class and assign
        # it to the current db object.
        # Make sure to also append it to `self.tables`

        #__init__(self, db, name, columns=None):

        if not os.path.isfile(os.path.join(self.db_filepath, table_name)):
            new_table = Table(self, table_name, columns)
            setattr(self, table_name, new_table)
            self.tables.append(table_name)
        else:
            raise ValidationError("Table already exists.")
Beispiel #17
0
 def create_table(self, table_name, columns):
     # Check if a table already exists with given name. If so, raise
     # ValidationError exception.
     # Otherwise, crete an instance of the `Table` class and assign
     # it to the current db object.
     # Make sure to also append it to `self.tables`
     if table_name in self.tables:
         msg = ('Table with name "{}" in DB "{}" '
                 'already exist.'.format(table_name, self.name))
         raise ValidationError(msg)
     # build new table in this database
     new_table = Table(db=self, name=table_name, columns=columns)
     # append the new table to the tables list
     self.tables.append(table_name)
     # add the table object by name to this database
     setattr(self, table_name, new_table)
     return True
Beispiel #18
0
    def create_table(self, table_name, columns):
        # Check if a table already exists with given name. If so, raise
        # ValidationError exception.
        # Otherwise, crete an instance of the `Table` class and assign
        # it to the current db object.
        # Make sure to also append it to `self.tables`
        # if not os.path.isfile(os.path.join(self.db_filepath, table_name)):
        #     table_ = Table(self, table_name, columns)
        #     setattr(self,table_name,table_)
        #     self.tables.append(table_)
        # else:
        #     raise ValidationError()

        if table_name in self.tables:
            raise ValidationError()
        else:
            table_ = Table(self, table_name, columns)
            self.tables.append(table_name)
            setattr(self, table_name, table_)
Beispiel #19
0
 def create(cls, name):
     db_filepath = os.path.join(BASE_DB_FILE_PATH, name)
     if os.path.exists(db_filepath):
         raise ValidationError(
             'Database with name "{}" already exists.'.format(name))
     os.makedirs(db_filepath)