|
1 | 1 | # A Python module for effortless database usage.
|
2 | 2 |
|
3 | 3 | import pymysql, psycopg2, psycopg2.extras, sqlite3, datetime, socket, configparser
|
| 4 | +from rich.table import Table |
| 5 | +from rich import print as rprint |
4 | 6 |
|
5 | 7 | cursors = ["DEFAULT", "DICTIONARY"]
|
6 | 8 | modes = ["MySQL", "PostgreSQL", "SQLite"]
|
@@ -170,6 +172,40 @@ def call(self, procedure, args=[], rollback_on_error=None):
|
170 | 172 | # Return the result.
|
171 | 173 | return self.cursor.fetchall()
|
172 | 174 |
|
| 175 | + ### PRINT FUNCTIONS ### |
| 176 | + |
| 177 | + # Prints the result of a query as a rich table. The 'data' argument can be a tuple or a dictionary. |
| 178 | + def print(self, data, title=None): |
| 179 | + # If the data is a dictionary, convert it to a tuple. |
| 180 | + if type(data) == dict: |
| 181 | + data = tuple(data.items()) |
| 182 | + # If the data is a tuple, convert it to a list. This is done because the Rich library doesn't support tuples. |
| 183 | + if type(data) == tuple: |
| 184 | + data = list(data) |
| 185 | + # If the data is a list, convert it to a table. |
| 186 | + if type(data) == list: |
| 187 | + table = Table(title=title) |
| 188 | + # If the data is a list of tuples, convert it to a table. |
| 189 | + if type(data[0]) == tuple: |
| 190 | + for i in range(len(data[0])): |
| 191 | + table.add_column(data[0][i]) |
| 192 | + for i in range(1, len(data)): |
| 193 | + table.add_row(*data[i]) |
| 194 | + # If the data is a list of dictionaries, convert it to a table. |
| 195 | + elif type(data[0]) == dict: |
| 196 | + for i in data[0].keys(): |
| 197 | + table.add_column(i) |
| 198 | + for i in data: |
| 199 | + # Parse the values to strings. Then add the rows. |
| 200 | + values = [] |
| 201 | + for j in i.values(): |
| 202 | + values.append(parse(j)) |
| 203 | + table.add_row(*values) |
| 204 | + # Print the table. |
| 205 | + rprint(table) |
| 206 | + else: |
| 207 | + raise Exception("Invalid data type.") |
| 208 | + |
173 | 209 | ### EASY FUNCTIONS ###
|
174 | 210 |
|
175 | 211 | # A quick SELECT query.
|
@@ -285,6 +321,8 @@ def currentTimestamp(self):
|
285 | 321 | def parse(value):
|
286 | 322 | if value in [None, "", "NULL"]:
|
287 | 323 | return "NULL"
|
| 324 | + if isinstance(value, int): |
| 325 | + return str(value) |
288 | 326 | if isinstance(value, datetime.date):
|
289 | 327 | return value.strftime("%Y-%m-%d")
|
290 | 328 | return "'" + str(value).replace("'", "''") + "'"
|
0 commit comments