Beispiel #1
0
def remd(dbcontent, name_, table, id_):
    if id_ and (not (str(type(id_)) in [
            "<class 'str'>", "<class 'int'>", "<class 'float'>"
    ])):
        event_log(
            "Error! Expecting id_ to be of type string or int or float in function drop",
            name_)
        return [], "Expecting id_ to be of type string or int or float in function drop"
    if not (str(type(table)) in ["<class 'str'>", "<class 'list'>"]):
        event_log(
            "Error! Expecting table to be of type string or list in function drop",
            name_)
        return [], "Expecting table to be of type string or list in function drop"
    try:
        if str(type(table)) == "<class 'str'>":
            if id_:
                del dbcontent[table][id_]
                event_log(
                    "Successfully dropped id_ {} in table {} in DB {}".format(
                        id_, table, name_), name_)
            else:
                del dbcontent[table]
                event_log(
                    "Successfully dropped table {} in DB {}".format(
                        table, name_), name_)
        else:
            for i in table:
                del dbcontent[i]
        return dbcontent, None
    except Exception as e:
        event_log(
            "There was an error droping table {} in DB {} - {}".format(
                table, name_, str(e)), name_)
        return {}, str(e)
Beispiel #2
0
 def exists(self, table=None, id_=None):
     res, error = exist(self.__name, self.__data, table, id_)
     if error:
         event_log("An Error occured when checking if data exists in DB {}".format(self.__name), self.__name)
         raise Exception(error)
     event_log("Successfully checked if data exists in DB {}".format(self.__name), self.__name)
     return res
Beispiel #3
0
def dump(source, destination):
    #Ensure the destination is a string or int or float
    if not str(type(destination)) in [
            "<class 'str'>", "<class 'float'>", "<class 'int'>"
    ]:
        event_log(
            "Error! Expecting destination to be of type string or int or float in function clone",
            source)
        return {}, "Error! Expecting destination to be of type string or int or float"
    #Converts to a string incase it is a float or int
    destination = str(destination)
    if len(destination) == 0:
        event_log("Error! Destination cannot be empty in function clone",
                  source)
        return "Destination cannot be empty in function clone"
    if source == destination:
        e = "Error! destination cant be the same as source in function clone!"
        event_log(e, source)
        return e
    try:
        #Basically read and write the database stored on the disk
        with open(source + ".hashdb", "r") as db0:
            content = db0.read()
        with open(destination + ".hashdb", "w") as db1:
            db1.write(dumps(content))
        event_log(
            "Successfully cloned DB {} to {}".format(source, destination),
            source)
        return None
    except Exception as e:
        event_log(
            "There was an error cloning DB {} to {} - {}".format(
                source, destination, str(e)), source)
        return str(e)
Beispiel #4
0
def create(dbname, data={}, password=None):
    if password:
        with open(dbname + ".hashdb", "w") as db:
            db.write(encryptdb(str(data), str(password), dbname))
    else:
        with open(dbname + ".hashdb", "w") as db:
            db.write(dumps(data, indent=4))
    event_log("Successfully created new DB {}".format(dbname), dbname)
Beispiel #5
0
def close(dbname):
    try:
        event_log("Successfully disconnected from DB {}".format(dbname),
                  dbname)
        return None
    except Exception as e:
        event_log(
            "There was an error disconnecting from DB {}, Possibly due to Database Corruption - {}"
            .format(dbname, str(e)), dbname)
        return str(e)
Beispiel #6
0
 def drop(self, table=None, id=None):
     _data = dumps(self.__data)
     if (not table) and (not id_):
         event_log("Successfully dropped DB {}".format(self.__name), self.__name)
         data_ = {}
     else:
         data_, error = remd(self.__data, self.__name, table, id)
         if error:
             raise Exception(error)
     self.__dataCP = _data
     self.__data = data_
Beispiel #7
0
 def __init__(self, dbname, password=None):
     _data, self.state, error = load(dbname, password)
     if str(type(_data)) != "<class 'dict'>":
         error = "A password is required to connect to DB {}".format(dbname)
         event_log(error)
     if error:
         raise Exception(error)
     self.__data = _data
     del _data
     self.__name = str(dbname)
     self.__dataCP = dumps(self.__data)
Beispiel #8
0
def encpass(password, dbname):
	password = str(password)
	password = sha512((password + password + (password[0] * len(password))).encode()).hexdigest()
	try:
		tot = 0
		for p in range(len(password)):
			tot += ord(password[p]) * p
		tot += ord(password[0]) + ord(password[-1])
		return (tot % 512)
	except Exception as e:
		event_log("There was an error parsing given password for DB {} - {}".format(dbname, str(e)), dbname)
		return str(e)
Beispiel #9
0
 def count(self, table=None, id=None):
     if (not table) and (not id):
         event_log("Successfully retrieved count of DB {}".format(self.__name), self.__name)
         return len(self.__data.keys())
     elif (not table) and id:
         error = "Error! Can't get count of table_id without specifying table in function count"
         event_log(error, self.__name)
         raise Exception(error)
     value, error = coun(self.__name, self.__data, table, id)
     if error:
         
         raise Exception(error)
     return value
Beispiel #10
0
def remf(dbname):
    try:
        try:
            remove(dbname + ".hashdb")
        except Exception as e:
            event_log(
                "There was an error destroying DB {} - {}".format(
                    dbname, str(e)), dbname)
            return (str(e))
        except Exception as e:
            event_log(
                "There was an error destroying DB {} - {}".format(
                    dbname, str(e)), dbname)
            return (str(e))
        event_log("Successfully deleted DB {}".format(dbname), dbname)
        return None
    except Exception as e:
        event_log(
            "There was an error destroying DB {} - {}".format(dbname, str(e)),
            dbname)
        return str(e)
Beispiel #11
0
def insA(data_, dbname):
    try:
        if not data_:
            event_log("Successfully overwritten data in DB {}".format(dbname),
                      dbname)
            return {}, None
        if str(type(data_)) == "<class 'dict'>" or str(
                type(data_)) == "<class 'str'>":
            if str(type(data_)) == "<class 'str'>":
                data_ = {"data": data_}
            event_log("Successfully overwritten data in DB {}".format(dbname),
                      dbname)
            return data_, None
        else:
            event_log(
                "Expecting data_ to be of type dict or str in function overwrite",
                dbname)
            return {}, "Error! Expecting data_ to be of type dict or str"
    except Exception as e:
        event_log(
            "There was an error overwriting data in DB {} - {}".format(
                dbname, str(e)), dbname)
        return {}, str(e)
Beispiel #12
0
def tab(data_, table_, name_):
    try:
        if str(type(table_)) != "<class 'str'>":
            event_log("Expecting table to be of type str in function table",
                      dbname)
            return {}, "Error! Expecting table to be of type str"
        data_[table_] = {}
        event_log(
            "Successfully created table {} in DB {}".format(table_, name_),
            name_)
        return data_, None
    except Exception as e:
        event_log(
            "There was an error creating table {} in DB {} - {}".format(
                table_, name_, str(e)), name_)
        return {}, str(e)
Beispiel #13
0
def write(dbname, dbcontent, password=None, prettify=True):
    try:
        with open(dbname + ".hashdb", "w") as db:
            if password:
                db.write(encryptdb(str(dbcontent), str(password), dbname))
                event_log("Successfully saved DB {}".format(dbname), dbname)
            else:
                if prettify:
                    db.write(dumps(dbcontent, indent=4))
                else:
                    db.write(dumps(dbcontent))
                event_log("Successfully saved DB {}".format(dbname), dbname)
        return None
    except Exception as e:
        event_log(
            "There was an error editing DB {} - {}".format(dbname, str(e)),
            dbname)
        return str(e)
Beispiel #14
0
def remdd(name_, dbcontent, table, query_):
    if (str(type(table)) != "<class 'str'>"
            and str(type(table)) != "<class 'list'>") and table:
        event_log(
            "Error! Expecting table to be of type str or list in function delete",
            name_)
        return [], "Expecting table to be of type str or list in function delete"
    if str(type(table)) == "<class 'str'>":
        table = [table]
    if str(type(query_)) != "<class 'dict'>" and query_:
        event_log(
            "Error! Expecting query_ to be of type dict in function find",
            name_)
        return [], "Expecting query_ to be of type dict in function find"
    if (not query_) and (not table):
        del dbcontent
        return {}, None
    elif not query_:
        del dbcontent[table]
        return dbcontent, None
    try:
        if table:
            places_to_search = table
        else:
            places_to_search = list(dbcontent.keys())
        selected = []
        for places in places_to_search:
            for key in dbcontent[places]:
                present = False
                for query in query_:
                    try:
                        if "or" == query.lower() and (not present):
                            for keyy in query_[query]:
                                if dbcontent[places][key][keyy] == query_[
                                        query][keyy]:
                                    present = True
                    except:
                        pass
                    try:
                        if "or>" == query.lower() and (not present):
                            for keyy in query_[query]:
                                if dbcontent[places][key][keyy] > query_[
                                        query][keyy]:
                                    present = True
                    except:
                        pass
                    try:
                        if "or<" == query.lower() and (not present):
                            for keyy in query_[query]:
                                if dbcontent[places][key][keyy] < query_[
                                        query][keyy]:
                                    present = True
                    except:
                        pass
                if present:
                    selected.append([places, key])
                    continue
                valid = True
                for query in query_:
                    try:
                        if "and" == query.lower():
                            for keyy in query_[query]:
                                if dbcontent[places][key][keyy] != query_[
                                        query][keyy]:
                                    valid = False
                        elif "not" == query.lower():
                            try:
                                for keyy in query_[query]:
                                    if dbcontent[places][key][keyy] == query_[
                                            query][keyy]:
                                        valid = False
                            except:
                                pass
                        elif "like" == query.lower():
                            for keyy in query_[query]:
                                if not (str(query_[query][keyy]).lower(
                                ) in str(dbcontent[places][key][keyy]).lower()
                                        and str(
                                            type(dbcontent[places][key][keyy]))
                                        == "<class 'str'>"):
                                    valid = False
                        elif ">" == query:
                            for keyy in query_[query]:
                                if str(type(query_[query][keyy])) in [
                                        "<class 'float'>", "<class 'int'>"
                                ]:
                                    if float(dbcontent[places][key][keyy]
                                             ) < float(query_[query][keyy]):
                                        valid = False
                        elif "<" == query:
                            for keyy in query_[query]:
                                if str(type(query_[query][keyy])) in [
                                        "<class 'float'>", "<class 'int'>"
                                ]:
                                    if float(dbcontent[places][key][keyy]
                                             ) > float(query_[query][keyy]):
                                        valid = False
                        else:
                            if not query.lower() in "or or> or<".split(" "):
                                event_log("Error! Invalid Delete Format",
                                          name_)
                                return [], "Invalid Delete Format"
                            elif query.lower() in "or or> or<".split(" "):
                                pass
                            else:
                                valid = False
                    except:
                        valid = False
                        pass
                if valid:
                    selected.append([places, key])
        for i in selected:
            try:
                del dbcontent[i[0]][i[1]]
            except:
                pass
        event_log("Successfully Deleted data from DB {}".format(name_), name_)
        return dbcontent, None
    except Exception as e:
        return {}, str(e)
Beispiel #15
0
def load(dbname, password=None):
    if not str(type(dbname)) in [
            "<class 'str'>", "<class 'float'>", "<class 'int'>"
    ]:
        event_log(
            "Error! Expecting dbname to be of type string or int or float in function connect",
            0)
        return {}, 0, "Error! Expecting dbname to be of type string or int or float"
    dbname = str(dbname)
    try:
        res = 0
        if not path.exists(dbname + ".hashdb"):
            with open(dbname + ".hashdb", "w") as db:
                db.write("{}")
                res = 1
        if password:
            with open(dbname + ".hashdb", "r") as db:
                try:
                    dbcontent = decryptdb(db.read(), str(password), dbname)
                    dbcontent = literal_eval(
                        dbcontent.replace(": true,", ": True,").replace(
                            ": false,", ": False,"))
                    event_log("Successfully connected to DB {}".format(dbname),
                              dbname)
                except Exception as e:
                    event_log(
                        "An incorrect password was used in connecting to DB {} or the DB is corrupted"
                        .format(dbname), dbname)
                    return {}, 0, "An incorrect password was used in connecting to DB {} or the DB is corrupted".format(
                        dbname)
        else:
            with open(dbname + ".hashdb") as db:
                try:
                    dbcontent = ll(db)
                except Exception as e:
                    event_log(
                        "A password is required to connect to DB {} - {}".
                        format(dbname, str(e)), dbname)
                    return {}, 0, "A password is required to connect to DB {}".format(
                        dbname)
                db.close()

        event_log("Successfully connected to DB {}".format(dbname), dbname)
        return dbcontent, res, None
    except Exception as e:
        event_log(
            "There was an error connecting to DB {} - {}".format(
                dbname, str(e)), dbname)
        return {}, 0, str(e)
Beispiel #16
0
 def undo(self):
     self.__data = literal_eval(self.__dataCP.replace(": true,", ": True,").replace(": false,", ": False,"))
     event_log("Successfully Reversed Database Action", self.__name)
Beispiel #17
0
def ins(data, data_, table, dbname, id_):
    try:
        if str(type(data_)) != "<class 'dict'>":
            event_log("Expecting data_ to be of type dict in function insert",
                      dbname)
            return {}, "Error! Expecting data_ to be of type dict"
        if str(type(table)) != "<class 'str'>":
            event_log("Expecting table to be of type str in function insert",
                      dbname)
            return {}, "Error! Expecting table to be of type str"
        if str(type(id_)) != "<class 'str'>" and id_:
            event_log("Expecting id_ to be of type str in function insert",
                      dbname)
            return {}, "Error! Expecting id_ to be of type str"
        if not id_:
            id_ = "id_{}".format(len(data[table]))
        try:
            data[table]
        except:
            event_log("table {} does not exist in DB {}".format(table, dbname),
                      dbname)
            return {}, "table {} does not exist in DB {}".format(table, dbname)
        data[table][str(id_)] = data_
        event_log(
            "Successfully inserted data into DB {} in table {}".format(
                dbname, table), dbname)
        return data, None
    except Exception as e:
        event_log(
            "There was an error inserting data into DB {} in table {} - {} does not exist"
            .format(dbname, table, str(e)), dbname)
        return {}, str(e) + "does not exist"
Beispiel #18
0
 def get(self, table=None, id=None, sort=0):
     if table:
         error = None
         if str(type(table)) != "<class 'str'>":
             event_log("Expecting table to be of type str in function get", dbname)
             error = "Expecting table to be of type str in function get"
         if error:
             raise (error)
         try:
             if id:
                 try:
                     d = self.__data[table][id]
                     event_log("Successfully retrieved table_id {} in table {} in DB {} contents".format(id, table, self.__name), self.__name)
                 except:
                     event_log("The table_id {} does not exist in table {} in DB {}".format(id, table, self.__name), self.__name)
                     raise Exception("The table_id {} does not exist in table {} in DB {}".format(id, table, self.__name))
             else:
                 d = self.__data[table]
                 event_log("Successfully retrieved table {} in DB {} contents".format(table, self.__name), self.__name)
             data = d
             del d
         except:
             event_log("The Table {} does not exist! in DB {}".format(table, self.__name), self.__name)
             raise Exception("The Table {} does not exist! in DB {}".format(table, self.__name))
     else:
         event_log("Successfully retrieved DB {} contents".format(self.__name), self.__name)
         data = self.__data
     if int(sort) != 0:
         data2 = {}
         if int(sort) > 0:
             for i in sorted(data):
                 data2[i] = data[i]
         elif int(sort) < 0:
             for i in sorted(data)[::-1]:
                 data2[i] = data[i]
         data = data2
         del data2
     return data
Beispiel #19
0
def upd(data, data_, table, dbname, id_):
    try:
        if str(type(data_)) != "<class 'dict'>":
            event_log("Expecting data_ to be of type dict in function update",
                      dbname)
            return {}, "Error! Expecting data_ to be of type dict"
        if str(type(table)) != "<class 'str'>":
            event_log("Expecting table to be of type str in function update",
                      dbname)
            return {}, "Error! Expecting table to be of type str"
        if not str(type(id_)) in ["<class 'str'>", "<class 'int'>"]:
            event_log(
                "Expecting id_ to be of type str or int in function update",
                dbname)
            return {}, "Error! Expecting id_ to be of type str or int"
        if not data_:
            data_ = {}
        try:
            if str(type(id_)) == "<class 'int'>":
                bin_ = data[table][list(data[table].keys())[id_]]
                del bin_
                data[table][list(data[table].keys())[id_]] = data_
            else:
                bin_ = data[table][str(id_)]
                del bin_
                data[table][str(id_)] = data_
        except:
            event_log(
                "There is no table_id with {} in table {} in DB {}".format(
                    id_, table, dbname), dbname)
            return {}, "table_id {} does not exist in table {}".format(
                id_, table)
        event_log(
            "Successfully updated data into DB {} in table {} with id {}".
            format(dbname, table, id_), dbname)
        return data, None
    except Exception as e:
        event_log(
            "There was an error updating data in DB {} in table {} with id_ {} - {}"
            .format(dbname, table, id_, str(e)), dbname)
        return {}, str(e)
Beispiel #20
0
 def tables(self):
     event_log("Successfully retrieved DB {} Tables".format(self.__name), self.__name)
     return list(self.__data.keys())