Skip to content

Commit c91b8a3

Browse files
committed
We got tables!
1 parent fda003c commit c91b8a3

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

loaf/__init__.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
# A Python module for effortless database usage.
22

33
import pymysql, psycopg2, psycopg2.extras, sqlite3, datetime, socket, configparser
4+
from rich.table import Table
5+
from rich import print as rprint
46

57
cursors = ["DEFAULT", "DICTIONARY"]
68
modes = ["MySQL", "PostgreSQL", "SQLite"]
@@ -170,6 +172,40 @@ def call(self, procedure, args=[], rollback_on_error=None):
170172
# Return the result.
171173
return self.cursor.fetchall()
172174

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+
173209
### EASY FUNCTIONS ###
174210

175211
# A quick SELECT query.
@@ -285,6 +321,8 @@ def currentTimestamp(self):
285321
def parse(value):
286322
if value in [None, "", "NULL"]:
287323
return "NULL"
324+
if isinstance(value, int):
325+
return str(value)
288326
if isinstance(value, datetime.date):
289327
return value.strftime("%Y-%m-%d")
290328
return "'" + str(value).replace("'", "''") + "'"

0 commit comments

Comments
 (0)