|
| 1 | +from dataclasses import field, fields |
| 2 | +import sqlite3 |
| 3 | +from unittest import result |
| 4 | + |
| 5 | +class CustomSqliteAction(): |
| 6 | + def __init__(self,database_name, database_table, database_fields): |
| 7 | + self.database = database_name |
| 8 | + self.table_name = database_table |
| 9 | + self.fields = database_fields |
| 10 | + |
| 11 | + self.db_conn = None |
| 12 | + self.valid_fields = None |
| 13 | + |
| 14 | + def connect_to_db(self): |
| 15 | + print('[+] Connecting to {}'.format(self.database)) |
| 16 | + db_conn = sqlite3.connect(self.database) |
| 17 | + self.db_conn = db_conn |
| 18 | + |
| 19 | + def load_table_info(self): |
| 20 | + self.valid_fields = [f_name[0] for f_name in self.fields] |
| 21 | + |
| 22 | + def table_validation(self,inserted_fields): |
| 23 | + return list(set(inserted_fields).difference(set(self.valid_fields))) |
| 24 | + |
| 25 | + def _parse_result(self,db_data): |
| 26 | + query_set = [] |
| 27 | + for data in db_data: |
| 28 | + data_dict = {k: v for k, v in zip(self.valid_fields, data)} |
| 29 | + query_set.append(data_dict) |
| 30 | + return query_set |
| 31 | + |
| 32 | + def create_table(self): |
| 33 | + sql_string = """CREATE TABLE IF NOT EXISTS {table_name} {field_string};""" |
| 34 | + field_string = "("+", ".join([" ".join(fi for fi in f) for f in self.fields])+")" |
| 35 | + sql_string = sql_string.format(table_name=self.table_name,field_string=field_string) |
| 36 | + |
| 37 | + print("[+] Creating Table {} .....\n".format(self.table_name)) |
| 38 | + cur = self.db_conn.cursor() |
| 39 | + cur.execute(sql_string) |
| 40 | + |
| 41 | + def table_exists(self): |
| 42 | + sql_string = """SELECT * FROM {}""".format(self.table_name) |
| 43 | + try: |
| 44 | + cur = self.db_conn.cursor() |
| 45 | + cur.execute(sql_string) |
| 46 | + print('[+] Connecting To Table {}\n'.format(self.table_name)) |
| 47 | + return True |
| 48 | + except sqlite3.OperationalError: |
| 49 | + print('[-] TABLE NAME {} DOES NOT EXISTS'.format(self.table_name)) |
| 50 | + return False |
| 51 | + |
| 52 | + def store_data(self,**kwargs): |
| 53 | + validation = self.table_validation(kwargs.keys()) |
| 54 | + if not validation: |
| 55 | + sql_string = """INSERT INTO {table_name} {field_string} VALUES {value_string};""" |
| 56 | + field_string = "("+", ".join([f for f in kwargs.keys()])+")" |
| 57 | + value_string = "("+ ", ".join([f"'{v}'" for v in kwargs.values()]) +")" |
| 58 | + |
| 59 | + sql_string = sql_string.format(table_name=self.table_name,field_string=field_string,value_string=value_string) |
| 60 | + cur = self.db_conn.cursor() |
| 61 | + try: |
| 62 | + cur.execute(sql_string) |
| 63 | + except sqlite3.OperationalError: |
| 64 | + print('[-] Database Syntax Error probabily because of \' in data ') |
| 65 | + self.db_conn.commit() |
| 66 | + else: |
| 67 | + print('\n[-] STORE DATA ERROR ...') |
| 68 | + print('[-] {} IS NOT VALID FIELD NAME'.format(', '.join(validation))) |
| 69 | + print('[-] CHOICES ARE {}'.format((', ').join(self.valid_fields))) |
| 70 | + |
| 71 | + def delete_data(self,**kwargs): |
| 72 | + validation = self.table_validation(kwargs.keys()) |
| 73 | + if not validation: |
| 74 | + if len(kwargs) == 1: |
| 75 | + sql_string = """DELETE FROM {table_name} WHERE {field} = '{field_id}';""" |
| 76 | + sql_string = sql_string.format(table_name=self.table_name,field=list(kwargs.keys())[0],field_id=list(kwargs.values())[0]) |
| 77 | + elif len(kwargs) > 1: |
| 78 | + inintial_string = """DELETE FROM {table_name} WHERE """.format(table_name=self.table_name) |
| 79 | + field_string = " AND ".join(["{field} = '{field_value}'".format(field=f[0],field_value=f[1]) for f in kwargs.items() ]) + ";" |
| 80 | + sql_string = inintial_string + field_string |
| 81 | + else: |
| 82 | + print('[-] At least Provide 1 Argument') |
| 83 | + return |
| 84 | + |
| 85 | + cur = self.db_conn.cursor() |
| 86 | + cur.execute(sql_string) |
| 87 | + self.db_conn.commit() |
| 88 | + print("[+] Delete Data Successfully") |
| 89 | + |
| 90 | + else: |
| 91 | + print('\n[-] DELETE DATA ERROR ...') |
| 92 | + print('[-] {} IS NOT VALID FIELD NAME'.format(', '.join(validation))) |
| 93 | + print('[-] CHOICES ARE {}'.format((', ').join(self.valid_fields))) |
| 94 | + |
| 95 | + def update_data(self,search_tuple, **kwargs): |
| 96 | + validation = self.table_validation(kwargs.keys()) |
| 97 | + if not validation: |
| 98 | + if len(kwargs) == 1: |
| 99 | + sql_string = """UPDATE {table_name} SET {field} = '{update_value}' WHERE {p_field} = {field_id};""" |
| 100 | + sql_string = sql_string.format(table_name=self.table_name, field=list(kwargs.keys())[0], update_value=list(kwargs.values())[0], p_field=search_tuple[0], field_id=search_tuple[1]) |
| 101 | + else: |
| 102 | + print('[-] Only One Upadte Argument Allowed') |
| 103 | + return |
| 104 | + cur = self.db_conn.cursor() |
| 105 | + cur.execute(sql_string) |
| 106 | + self.db_conn.commit() |
| 107 | + print("[+] Update Data Successfully") |
| 108 | + else: |
| 109 | + print('\n[-] DELETE DATA ERROR ...') |
| 110 | + print('[-] {} IS NOT VALID FIELD NAME'.format(', '.join(validation))) |
| 111 | + print('[-] CHOICES ARE {}'.format((', ').join(self.valid_fields))) |
| 112 | + |
| 113 | + def read_data(self,**kwargs): |
| 114 | + validation = self.table_validation(kwargs.keys()) |
| 115 | + if not validation: |
| 116 | + if len(kwargs) == 1: |
| 117 | + sql_string = """SELECT * FROM {table_name} WHERE {field} = '{read_value}';""" |
| 118 | + sql_string = sql_string.format(table_name=self.table_name, field=list(kwargs.keys())[0], read_value=list(kwargs.values())[0]) |
| 119 | + elif len(kwargs) > 1: |
| 120 | + inintial_string = """SELECT * FROM {table_name} WHERE """.format(table_name=self.table_name) |
| 121 | + field_string = " AND ".join(["{field} = '{read_value}'".format(field=f[0],read_value=f[1]) for f in kwargs.items() ]) + ";" |
| 122 | + sql_string = inintial_string + field_string |
| 123 | + else: |
| 124 | + print('[-] Provide At least One Argument') |
| 125 | + return |
| 126 | + |
| 127 | + cur = self.db_conn.cursor() |
| 128 | + cur.execute(sql_string) |
| 129 | + self.db_conn.commit() |
| 130 | + |
| 131 | + #FETCHING DATA |
| 132 | + result = cur.fetchall() |
| 133 | + return self._parse_result(result) |
| 134 | + else: |
| 135 | + print('\n[-] READ DATA ERROR ...') |
| 136 | + print('[-] {} IS NOT VALID FIELD NAME'.format(', '.join(validation))) |
| 137 | + print('[-] CHOICES ARE {}'.format((', ').join(self.valid_fields))) |
| 138 | + |
| 139 | + def read_all(self): |
| 140 | + #PART1 : CREATING THE SQL STRING |
| 141 | + sql_string = """SELECT * FROM {table_name};""" |
| 142 | + sql_string = sql_string.format(table_name=self.table_name) |
| 143 | + |
| 144 | + #PART2 : EXECUTING THAT CREARED STRING |
| 145 | + cur = self.db_conn.cursor() |
| 146 | + cur.execute(sql_string) |
| 147 | + self.db_conn.commit() |
| 148 | + |
| 149 | + #FETCHING DATA |
| 150 | + result = cur.fetchall() |
| 151 | + return self._parse_result(result) |
| 152 | + |
| 153 | + def load(self): |
| 154 | + self.connect_to_db() |
| 155 | + if not self.table_exists(): |
| 156 | + self.create_table() |
| 157 | + self.load_table_info() |
| 158 | + else: |
| 159 | + self.load_table_info() |
| 160 | + |
| 161 | + |
| 162 | +if __name__ == '__main__': |
| 163 | + db_file_name = 'download_queue.db' |
| 164 | + db_table = 'DownloadQueue' |
| 165 | + db_fields = [ |
| 166 | + ('id','integer','primary key','autoincrement'), |
| 167 | + ('url','text'), |
| 168 | + ('date','date'), |
| 169 | + ('status','text'), |
| 170 | + |
| 171 | + ] |
| 172 | + |
| 173 | + db_obj = CustomSqliteAction(database_name=db_file_name, database_table=db_table, database_fields=db_fields) |
| 174 | + |
| 175 | + #will create .db file if not exists |
| 176 | + #will create table if not exists |
| 177 | + db_obj.load() |
| 178 | + |
| 179 | + #let's Store Some Data |
| 180 | + #function > store_data() |
| 181 | + #you can also use python datetime object as a date field |
| 182 | + db_obj.store_data(url='https://m.youtube.com/video_id',date='2022-10-01') |
| 183 | + |
| 184 | + |
| 185 | + #let's Update Some Data |
| 186 | + #function > update_data() |
| 187 | + db_obj.update_data(search_tuple=('id','1'), url='https://google.com/video_id') |
| 188 | + |
| 189 | + |
| 190 | + #let's Read Some data |
| 191 | + #function > read_data() , read_all() |
| 192 | + |
| 193 | + #read_data() |
| 194 | + #-> will read based on single condition or multiple condition and returns python list contaning all the data |
| 195 | + print('Single Argument Search ...') |
| 196 | + data = db_obj.read_data(url='https://m.youtube.com/video_id') |
| 197 | + print(data) |
| 198 | + |
| 199 | + print('Multiple Argument Search ...') |
| 200 | + multi_con_data = db_obj.read_data(url='https://m.youtube.com/video_id',status='done') |
| 201 | + print(multi_con_data) |
| 202 | + |
| 203 | + print('Reading All Data ...') |
| 204 | + all_data = db_obj.read_all() |
| 205 | + print(all_data) |
| 206 | + |
| 207 | + #let's delete Some Data |
| 208 | + #function > delete_data() |
| 209 | + delete_id = 1 |
| 210 | + db_obj.delete_data(id=delete_id) |
| 211 | + db_obj.delete_data(url='https://m.youtube.com/video_id') |
| 212 | + db_obj.delete_data(url='https://m.youtube.com/video_id',status='done') |
0 commit comments