Last active
May 8, 2024 15:59
-
-
Save Muazzeem/e388ee3e6854c561c07e7778cd73fdbe to your computer and use it in GitHub Desktop.
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
from sqlalchemy import MetaData, Table, text | |
from sqlalchemy.orm import scoped_session | |
from sqlalchemy import create_engine, URL | |
from sqlalchemy.ext.declarative import declarative_base | |
from sqlalchemy.orm import sessionmaker | |
connection_cred = { | |
'username':'postgres', | |
'password': '', | |
'host':'', | |
'database': '' | |
} | |
db_url = URL.create( | |
"postgresql+psycopg2", | |
**connection_cred | |
) | |
engine = create_engine(db_url) | |
session_factory = sessionmaker(bind=engine) | |
session = scoped_session(session_factory) | |
Base = declarative_base() | |
metadata = MetaData() | |
metadata.reflect(engine) | |
table_with_count = {} | |
for table in metadata.tables.values(): | |
table = Table(table.name, metadata, autoload=True, autoload_with=engine) | |
select_query = table.select() | |
with engine.connect() as conn: | |
row_count = conn.execute(text('''SELECT COUNT(*) FROM "{}";'''.format(table.name))).scalar() | |
table_with_count[table.name] = row_count | |
for key in sorted(table_with_count): | |
print(key, table_with_count[key]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment