Skip to content

Instantly share code, notes, and snippets.

@ZenithClown
Last active December 12, 2023 08:51
Show Gist options
  • Save ZenithClown/5336102f2b5270afa04d65a9924dee6b to your computer and use it in GitHub Desktop.
Save ZenithClown/5336102f2b5270afa04d65a9924dee6b to your computer and use it in GitHub Desktop.
A single file utility function that works as a wrapper for the "tabulate" module in python to print a table fetched using a SQL query.
# -*- encoding: utf-8 -*-
"""
A Utility Function to Print Tables fetched using a SQL Query
SQL query is used to fetch records from a table, and the utility
function can be used to print the table in the terminal in a fancy
format using the `tabulate` library. The function simply works as a
wrapper and all other functionalities are controlled externally.
! This code does not come with additional documentations, but can be
cloned/added to `PYTHONPATH` using the following:
```shell
$ https://gist.github.com/ZenithClown/5336102f2b5270afa04d65a9924dee6b tabulate_
$ export PYTHONPATH="${PYTHONPATH}:tabulate_"
```
Finally, the function can be used from python to output to terminal
using:
```python
from tabulate_ import tabulate_
# import and define con/cur object, and pass as params
tbl = "dbo.myTable"
data = con.execute(f"SELECT TOP 10 * FROM {tbl}").fetchall()
tabulate_(data, table = tbl, con = con, tablefmt = "pretty")
```
@author: Debmalya Pramanik
@version: v0.0.1
"""
from typing import Iterable
from tabulate import tabulate
def tabulate_(data : Iterable[list] or Iterable[tuple], table : str, headers : Iterable = None, **kwargs) -> None:
"""
A Wrapper of the Original `tabulate.tabulate()` for SQL Query
The wrapper accepts all the arguments as in the original function,
however most of them is available as keyword arguments into the
function and is internally called. Additionally, the following
arguments are required:
:type table: str
:param table: Name of the table from which the data is fetched.
:type headers: list
:param headers: If a connection object is provided (`con`) then
the headers is internally defined by
`con.execute(PRAGMA <table>)`, else mnually
provide the headers. In case of `None` the header
is printed as defaulted by `tabulate.tabulate()`
function. Defaults to None.
"""
con = kwargs.get("con", None)
if con and not headers:
# table schema can be fetched from different database
# MSSQL: https://stackoverflow.com/a/1054988/6623589
# __db_type = kwargs.get("DB_TYPE", "MSSQL") # TODO: define for others
tblShema, tblName = table.split(".")
statement = f"SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '{tblShema}' AND TABLE_NAME = '{tblName}';"
headers = [row[3] for row in con.execute(statement).fetchall()]
print(tabulate(
data, headers,
tablefmt = kwargs.get("tablefmt", "psql"), # changed from default
floatfmt = kwargs.get("floatfmt", "g"),
numalign = kwargs.get("numalign", "default"),
stralign = kwargs.get("stralign", "default"),
missingval = kwargs.get("missingval", ""),
showindex = kwargs.get("showindex", "default"),
disable_numparse = kwargs.get("disable_numparse", False),
colalign = kwargs.get("colalign", None),
maxcolwidths = kwargs.get("maxcolwidths", None)
))
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment