Flask-SQLAlchemy check if table exists in database Flask-SQLAlchemy check if table exists in database database database

Flask-SQLAlchemy check if table exists in database


I used these methods. Looking at the model like you did only tells you what SHOULD be in the database.

import sqlalchemy as sadef database_is_empty():    table_names = sa.inspect(engine).get_table_names()    is_empty = table_names == []    print('Db is empty: {}'.format(is_empty))    return is_emptydef table_exists(name):    ret = engine.dialect.has_table(engine, name)    print('Table "{}" exists: {}'.format(name, ret))    return ret

There may be a simpler method than this:

def model_exists(model_class):    engine = db.get_engine(bind=model_class.__bind_key__)    return model_class.metadata.tables[model_class.__tablename__].exists(engine)


SQL Alchemy's recommended way to check for the presence of a table is to create an inspector object and use its has_table() method.The following example was copied from sqlalchemy.engine.reflection.Inspector.has_table, with the addition of an SQLite engine (in memory) to make it reproducible:

In [17]: from sqlalchemy import create_engine, inspect    ...: from sqlalchemy import MetaData, Table, Column, Text    ...: engine = create_engine('sqlite://')    ...: meta = MetaData()    ...: meta.bind = engine    ...: user_table = Table('user', meta, Column("first_name", Text))    ...: user_table.create()    ...: inspector = inspect(engine)    ...: inspector.has_table('user')Out[17]: True

You can also use the user_table metadata element name to check if it exists as such:

inspector.has_table(user_table.name)