Home » Mysql » SQL Alchemy – Getting a list of tables

SQL Alchemy – Getting a list of tables

Posted by: admin November 1, 2017 Leave a comment

Questions:

I couldn’t find any information about this in the documentation, but how can I get a list of tables created in SQLAlchemy?

I used the class method to create the tables.

Answers:

All of the tables are collected in the tables attribute of the sqlalchemy MetaData object. to just get a list of the names of those tables:

>>> metadata.tables.keys()
['posts', 'comments', 'users']

If you’re using the declarative extension, then you probably aren’t managing the metadata yourself. Fortunately, the metadata is still present on the baseclass,

>>> Base = sqlalchemy.ext.declarative.declarative_base()
>>> Base.metadata
MetaData(None)

If you are trying to figure out what tables are present in your database, even among the ones you haven’t even told sqlalchemy about yet, then you can use table reflection. sqlalchemy will then inspect the database and update the metadata with all of the missing tables.

>>> metadata.reflect(engine)

Questions:
Answers:

There is a method in engine object to fetch the list of tables name. engine.table_names()

Questions:
Answers:

I was looking for something like this:

    from sqlalchemy import create_engine
    eng = create_engine('mysql+pymysql://root:[email protected]:3306', pool_recycle=3600)
    q = eng.execute('SHOW TABLES')

    available_tables = q.fetchall()

It does an execute and returns all of the tables.

update:

Postgres:

eng = create_engine('postgresql+psycopg2://root:[email protected]/
q = eng.execute('SELECT * FROM pg_catalog.pg_tables')

Questions:
Answers:

The metadata object that you created the tables with has that in a dictionary.

metadata.tables.keys()

Questions:
Answers:
from sqlalchemy import create_engine
engine = create_engine('postgresql://use:[email protected]/DBname')
print (engine.table_names())

Questions:
Answers:

Reflecting All Tables at Once allows you to retrieve hidden table names too. I created some temporary tables and they showed up with

meta = MetaData()
meta.reflect(bind=myengine)
for table in reversed(meta.sorted_tables):
    print table

Reference http://docs.sqlalchemy.org/en/latest/core/reflection.html

Questions:
Answers:

I’m solving same problem and found this post. After some try run, I would suggest use below to list all tables: (mentioned by zerocog)

metadata = MetaData()
metadata.reflect(bind=engine)
for table in metadata.sorted_tables:
    print(table)

This is useful for direct table handling and I feel is recommended.

And use below code to get table names:

for table_name in engine.table_names():
    print(table_name)

“metadata.tables” provides a Dict for table name and Table object. which would also be useful for quick query.