|
| 1 | +import sqlite3 |
| 2 | +from typing import Self |
| 3 | +from functools import cache, reduce |
| 4 | +from sql_formatter.core import format_sql |
| 5 | +from sys import getsizeof |
| 6 | +import math |
| 7 | +from psutil import virtual_memory |
| 8 | +import customtkinter |
| 9 | +from .event_handler import EventHandler |
| 10 | +from ..utils import QUERY_ERROR_NONE_OBJECT |
| 11 | + |
| 12 | + |
| 13 | +class SQLEventHandler(EventHandler): |
| 14 | + """Handler for SQL events.""" |
| 15 | + |
| 16 | + MAX_PAGE_COUNT: int = 10 |
| 17 | + queries: list[str] = [] |
| 18 | + query_index: int = 0 |
| 19 | + |
| 20 | + @cache |
| 21 | + def __new__(cls, *args, **kwargs) -> Self: |
| 22 | + """ |
| 23 | + Create a new instance of SQLEventHandler class. |
| 24 | + Implements the Singleton pattern. |
| 25 | + """ |
| 26 | + return super().__new__(cls) |
| 27 | + |
| 28 | + def __init__( |
| 29 | + self, query: str, cursor: sqlite3.Cursor, result_label: customtkinter.CTkLabel |
| 30 | + ) -> None: |
| 31 | + """ |
| 32 | + Initialize the SQLEventHandler instance. |
| 33 | + If the singleton query has not been created, it initializes the attributes accordingly. |
| 34 | +
|
| 35 | + :param query: The SQL query. |
| 36 | + :type query: str |
| 37 | + :param cursor: The cursor for executing the query. |
| 38 | + :type cursor: sqlite3.Cursor |
| 39 | + :param result_label: The label to display the result. |
| 40 | + :type result_label: customtkinter.CTkLabel |
| 41 | + """ |
| 42 | + if not hasattr(self, "_query"): |
| 43 | + self._query: str = query |
| 44 | + self._cursor: sqlite3.Cursor = cursor |
| 45 | + self._result_label: customtkinter.CTkLabel = result_label |
| 46 | + self.__col_len: int = 0 |
| 47 | + self.__row_len: int = 0 |
| 48 | + self.__total_size: int = 0 |
| 49 | + self.queries.append(format_sql(query, max_len=1000000000)) |
| 50 | + self.query_index += 1 |
| 51 | + |
| 52 | + @property |
| 53 | + def get_query(self) -> str: |
| 54 | + """ |
| 55 | + Get the SQL query. |
| 56 | +
|
| 57 | + :return: The SQL query. otherwise None. |
| 58 | + :rtype: str| None |
| 59 | + """ |
| 60 | + if not sqlite3.complete_statement(self._query): |
| 61 | + return QUERY_ERROR_NONE_OBJECT |
| 62 | + return self._query |
| 63 | + |
| 64 | + @property |
| 65 | + def get_query_result_itr(self) -> sqlite3.Cursor | None: |
| 66 | + """ |
| 67 | +
|
| 68 | + Get the iterator for executing the SQL query. |
| 69 | +
|
| 70 | + :return: Iterator for executing the SQL query. Returns None if there is an error. |
| 71 | + :rtype: sqlite3.Cursor or None |
| 72 | + :raise KeyError: Raised in a specific error condition. |
| 73 | + """ |
| 74 | + try: |
| 75 | + return self._cursor.execute(self.get_query) |
| 76 | + except (sqlite3.ProgrammingError, AttributeError) as error: |
| 77 | + print(error) |
| 78 | + return QUERY_ERROR_NONE_OBJECT |
| 79 | + |
| 80 | + @staticmethod |
| 81 | + def _sizeof_row(row: list[tuple]) -> int: |
| 82 | + """ |
| 83 | + Calculate the size of a row in bytes. |
| 84 | +
|
| 85 | + :param row: List of tuples representing a row. |
| 86 | + :type row: list[tuple] |
| 87 | + :return: Size of the row in bytes. |
| 88 | + :rtype: int |
| 89 | + """ |
| 90 | + return reduce(getsizeof, [str(atr) for atr in row]) |
| 91 | + |
| 92 | + @property |
| 93 | + def row_len(self) -> int: |
| 94 | + """ |
| 95 | + Get the length of the rows. |
| 96 | +
|
| 97 | + If the row length attribute is not set, it returns the length calculated from the result set. |
| 98 | +
|
| 99 | + :return: Length of the rows. |
| 100 | + :rtype: int |
| 101 | + """ |
| 102 | + return self.__row_len or len(self) |
| 103 | + |
| 104 | + @cache |
| 105 | + def __len__(self) -> int: |
| 106 | + """ |
| 107 | + Get the total number of rows in the result set. |
| 108 | +
|
| 109 | + This method iterates through the result set obtained from the query execution and counts the rows. It also |
| 110 | + calculates the total size of the result set. |
| 111 | +
|
| 112 | + :return: Total number of rows in the result set. |
| 113 | + :rtype: int |
| 114 | + :raise KeyError: Raised in a specific error condition. |
| 115 | + """ |
| 116 | + try: |
| 117 | + row_itr: sqlite3.Cursor = self.get_query_result_itr |
| 118 | + row: list[tuple] = next(row_itr) |
| 119 | + self.__col_len = len(row) |
| 120 | + self.__total_size += self._sizeof_row(row) |
| 121 | + for row_count, row in enumerate(row_itr): |
| 122 | + self.__total_size += self._sizeof_row(row) |
| 123 | + self.__row_len = row_count + 1 |
| 124 | + return self.__row_len |
| 125 | + except (sqlite3.ProgrammingError, StopIteration, TypeError) as error: |
| 126 | + return 0 |
| 127 | + |
| 128 | + @property |
| 129 | + @cache |
| 130 | + def col_len(self) -> int: |
| 131 | + """ |
| 132 | + Get the total number of columns in the result set. |
| 133 | +
|
| 134 | + This method returns the number of columns in the result set. |
| 135 | +
|
| 136 | + :return: Total number of columns in the result set. |
| 137 | + :rtype: int |
| 138 | +
|
| 139 | + """ |
| 140 | + return self.__col_len |
| 141 | + |
| 142 | + @property |
| 143 | + def divaded_itrs(self) -> tuple[sqlite3.Cursor]: |
| 144 | + """ |
| 145 | + Divide the result set into multiple cursors. |
| 146 | +
|
| 147 | + This method divides the result set into multiple cursors based on the available memory and the size of the result set. |
| 148 | + It calculates the number of pages and rows per page, then creates cursors accordingly. |
| 149 | +
|
| 150 | + :return: Tuple of cursors representing the divided result set. |
| 151 | + :rtype: tuple[sqlite3.Cursor] |
| 152 | + :raise KeyError: Raised in a specific error condition. |
| 153 | + """ |
| 154 | + len(self) |
| 155 | + avaible_memory: int = int(virtual_memory()[1]) |
| 156 | + |
| 157 | + page_count: int = max( |
| 158 | + min( |
| 159 | + math.ceil(self.__total_size // (avaible_memory / 4.0)), |
| 160 | + self.MAX_PAGE_COUNT, |
| 161 | + ), |
| 162 | + 1, |
| 163 | + ) |
| 164 | + row_count: int = self.__total_size // page_count |
| 165 | + |
| 166 | + try: |
| 167 | + itrs: sqlite3.Cursor = [ |
| 168 | + self.get_query_result_itr for _ in range(page_count) |
| 169 | + ] |
| 170 | + except TypeError: |
| 171 | + return QUERY_ERROR_NONE_OBJECT |
| 172 | + |
| 173 | + try: |
| 174 | + for current_page, itr in enumerate(itrs[1:], 1): |
| 175 | + for _ in range(current_page * row_count): |
| 176 | + next(itr) |
| 177 | + except IndexError: |
| 178 | + return itrs |
| 179 | + |
| 180 | + return itrs |
| 181 | + |
| 182 | + def handle(self) -> tuple[sqlite3.Cursor]: |
| 183 | + """ |
| 184 | + Handle the SQL query result. |
| 185 | +
|
| 186 | + This method retrieves the divided iterators of the SQL query result using the `divaded_itrs` method and returns them. |
| 187 | +
|
| 188 | + :return: Tuple of cursors representing the divided result set. |
| 189 | + :rtype: tuple |
| 190 | +
|
| 191 | + """ |
| 192 | + return self.divaded_itrs |
0 commit comments