Created
May 21, 2023 10:52
-
-
Save evjeny/e52021287a4e55187138cea0c344fd51 to your computer and use it in GitHub Desktop.
Print prettified tables with SQLite and SQLAlchemy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sqlite3 | |
import sqlalchemy | |
def print_formatted_table(table: list[list]): | |
column_lengths = [ | |
max(len(table[i][column_num]) for i in range(len(table))) | |
for column_num in range(len(table[0])) | |
] | |
for row in table: | |
print("|", end=" ") | |
for item, column_length in zip(row, column_lengths): | |
print(item.rjust(column_length), "|", end=" ") | |
print() | |
def print_sqlite_cursor_as_table(title: str, cursor: sqlite3.Cursor): | |
headers = [d[0] for d in cursor.description] | |
table: list[list[str]] = [headers] | |
for row in cursor.fetchall(): | |
table.append(list(map(str, row))) | |
print(title) | |
print_formatted_table(table) | |
print() | |
def print_sqlalchemy_cursor_as_table( | |
connection: sqlalchemy.Connection, | |
title: str, | |
statement: sqlalchemy.Select, | |
): | |
cursor = connection.execute(statement) | |
headers = list(cursor.keys()) | |
table: list[list[str]] = [headers] | |
for row in cursor.fetchall(): | |
table.append(list(map(str, row))) | |
print(title) | |
print_formatted_table(table) | |
print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment