|
| 1 | +from __future__ import annotations |
| 2 | +from typing import Union, TypeVar, TYPE_CHECKING, overload |
| 3 | +from pythonicMySQL.mysqlclient import CLIENT |
| 4 | +from pythonicMySQL.constructor.column import columns |
| 5 | +from dataclasses import is_dataclass |
| 6 | + |
| 7 | + |
| 8 | +T = TypeVar("T") |
| 9 | + |
| 10 | + |
| 11 | +class Table: |
| 12 | + |
| 13 | + def __init__(self, database: str, table: str, python_type: T): |
| 14 | + self._validate_dataclass(python_type) |
| 15 | + self.python_type = python_type |
| 16 | + self.database = database |
| 17 | + self.table = table |
| 18 | + |
| 19 | + @staticmethod |
| 20 | + def _validate_dataclass(obj): |
| 21 | + if not is_dataclass(obj): |
| 22 | + raise ValueError("Object must be a dataclass") |
| 23 | + |
| 24 | + def to_mysql_dict(self, obj, remove_id: bool = False) -> dict: |
| 25 | + self._validate_dataclass(obj) |
| 26 | + columns_ = columns(obj) |
| 27 | + mysql_dict = {} |
| 28 | + for key, value in obj.__dict__.items(): |
| 29 | + matching = [column for column in columns_ if column.name == key] |
| 30 | + if matching: |
| 31 | + mysql_dict[key] = matching[0].mysql_type.convert_to_mysql(value) |
| 32 | + if remove_id: |
| 33 | + id_column = [column for column in columns_ if column.primary] |
| 34 | + mysql_dict.pop(id_column[0].name, '') |
| 35 | + return mysql_dict |
| 36 | + |
| 37 | + def insert(self, obj: T, update_if_exists=False, commit: bool = True): |
| 38 | + if update_if_exists and len([column for column in columns(obj) if column.unique]) == 0: |
| 39 | + raise AssertionError("You cannot use update_if_exists when there are no unique keys") |
| 40 | + return CLIENT.insert(self.database, self.table, self.to_mysql_dict(obj), |
| 41 | + update_if_duplicate_key=update_if_exists, commit=commit) |
| 42 | + |
| 43 | + def update(self, mysql_id: int, obj: T, commit=True): |
| 44 | + return CLIENT.update(self.database, self.table, mysql_id=mysql_id, dictionary=self.to_mysql_dict(obj, True), |
| 45 | + commit=commit) |
| 46 | + |
| 47 | + def select(self, ascending: bool = True, limit: int = None, offset: int = 0, where: Union[dict, str] = " "): |
| 48 | + response = CLIENT.select(self.database, self.table, |
| 49 | + ascending=ascending, limit=limit, offset=offset, where=where) |
| 50 | + data = response.data |
| 51 | + result = [] |
| 52 | + for row in data: |
| 53 | + insertion_object = {} |
| 54 | + for key, value in row.items(): |
| 55 | + matching = [column for column in columns(self.python_type) if column.name == key] |
| 56 | + if matching: |
| 57 | + insertion_object[key] = matching[0].mysql_type.convert_to_python(value) |
| 58 | + result.append(self.python_type(**insertion_object)) |
| 59 | + return result |
| 60 | + |
| 61 | + @overload |
| 62 | + def get_item(self, _id: int): |
| 63 | + ... |
| 64 | + |
| 65 | + @overload |
| 66 | + def get_item(self, column: str, value: object): |
| 67 | + ... |
| 68 | + |
| 69 | + def get_item(self, *args): |
| 70 | + """Gets first row corresponding to the search. Raises error if there are none.""" |
| 71 | + if isinstance(args[0], int): |
| 72 | + return self.select(limit=1, where={"id": args[0]})[0] |
| 73 | + else: |
| 74 | + return self.select(limit=1, where={args[0]: args[1]})[0] |
| 75 | + |
| 76 | + def __iter__(self): |
| 77 | + return iter(self.select()) |
| 78 | + |
| 79 | + def __len__(self): |
| 80 | + return CLIENT.get_number_of_rows(self.database, self.table) |
| 81 | + |
| 82 | + |
| 83 | + |
| 84 | +# |
| 85 | + |
| 86 | +# @overload |
| 87 | +# def table(_database: str, _table: str) -> object: ... |
| 88 | +# |
| 89 | +# def table(*, cls: Optional = None, mysql_connection: mysql.connector.connection.MySQLConnection = None, database: str = None, |
| 90 | +# table: str = None, object_type = None, |
| 91 | +# ascending: bool = True, limit: int = None, offset: int = 0, where: Union[dict, str] = " "): |
| 92 | +# |
| 93 | +# def wrap(cls): |
| 94 | +# |
| 95 | +# setattr(cls, "teuuw", 4) |
| 96 | +# cls.hi = lambda : print("hello") |
| 97 | +# return cls |
| 98 | +# |
| 99 | +# return wrap |
| 100 | +# |
| 101 | +# |
| 102 | +# @table |
| 103 | +# class Songs: |
| 104 | +# |
| 105 | +# def __init__(self): |
| 106 | +# self.h = 3 |
| 107 | +# |
| 108 | +# |
| 109 | +# song = Songs() |
| 110 | + |
| 111 | +# |
| 112 | +# |
| 113 | +# class Table: |
| 114 | +# |
| 115 | +# object_type = None |
| 116 | +# client = None |
| 117 | +# |
| 118 | +# def __init__(self, mysql_connection: mysql.connector.connection.MySQLConnection, |
| 119 | +# database: str, table: str, object_type: MySQLObject.__class__, ascending: bool = True, limit: int = None, offset: int = 0, |
| 120 | +# where: Union[dict, str] = " "): |
| 121 | +# self.ascending = ascending |
| 122 | +# self.limit = limit |
| 123 | +# self.offset = offset |
| 124 | +# self.where = where |
| 125 | +# self.__class__.client = Client(mysql_connection) |
| 126 | +# self.client = self.__class__.client |
| 127 | +# self.__class__.object_type = object_type |
| 128 | +# self.table = table |
| 129 | +# self.database = database |
| 130 | +# |
| 131 | +# def validate_columns(self): |
| 132 | +# mysql_description = self.client.describe_columns(self.database, self.table).fetchall() |
| 133 | +# assigned_columns = self.__class__.object_type.COLUMNS + Column.id_column() |
| 134 | +# for desc in mysql_description: |
| 135 | +# if desc["Field"] not in [column.name for column in assigned_columns]: |
| 136 | +# raise ValueError("Columns do not match") |
| 137 | +# |
| 138 | +# def create(self): |
| 139 | +# columns = [Column.id_column()] + self.object_type.COLUMNS |
| 140 | +# descriptions = [column.description for column in columns] |
| 141 | +# return self.client.create_table(self.database, self.table, descriptions) |
| 142 | +# |
| 143 | +# def update_columns(self): |
| 144 | +# columns = [Column.id_column()] + self.object_type.COLUMNS |
| 145 | +# descriptions = [column.description for column in columns] |
| 146 | +# self.__class__.client.update_table_columns(self.database, self.table, descriptions) |
| 147 | +# |
| 148 | +# def get(self) -> List[MySQLObject]: |
| 149 | +# result = self.client.select(self.database, self.table, |
| 150 | +# ascending=self.ascending, limit=self.limit, offset=self.offset, where=self.where) |
| 151 | +# response = SQLResponse(result) |
| 152 | +# data = response.data |
| 153 | +# result = [] |
| 154 | +# for item in data: |
| 155 | +# id_ = item.pop(Column.ID_COLUMN_NAME) |
| 156 | +# obj = self.__class__.object_type(**item) |
| 157 | +# obj.mysql_row_id = id_ |
| 158 | +# result.append(obj) |
| 159 | +# return result |
| 160 | +# |
| 161 | +# def insert(self, obj: MySQLObject, update_if_duplicate_key: bool = True, commit=True) -> OneDMLSQLResponse: |
| 162 | +# cursor = self.client.insert(self.database, self.table, obj.as_mysql_dict(), |
| 163 | +# update_if_duplicate_key=update_if_duplicate_key, commit=commit) |
| 164 | +# return OneDMLSQLResponse(cursor) |
| 165 | +# |
| 166 | +# def update(self, obj: MySQLObject, commit=True) -> OneDMLSQLResponse: |
| 167 | +# cursor = self.client.update(self.database, self.table, obj.mysql_row_id, obj.as_mysql_dict(), commit=commit) |
| 168 | +# response = OneDMLSQLResponse(cursor) |
| 169 | +# return response |
| 170 | +# |
| 171 | +# def __getitem__(self, item: Union[tuple, int]) -> MySQLObject: |
| 172 | +# if isinstance(item, tuple) and len(item) == 2: |
| 173 | +# result = self.client.select(self.database, self.table, where={item[0]: item[1]}) |
| 174 | +# elif isinstance(item, int): |
| 175 | +# result = self.client.select(self.database, self.table, where={"id": item}) |
| 176 | +# else: |
| 177 | +# raise KeyError |
| 178 | +# if len(result) == 1: |
| 179 | +# return result[0] |
| 180 | +# else: |
| 181 | +# raise KeyError |
| 182 | +# |
| 183 | +# def __iter__(self): |
| 184 | +# return iter(self.get()) |
0 commit comments