Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alembic create_table, check if table exists

I have an alembic upgrade script that creates a table, however I don't want it to create the table if it already exists.

According to the alembic doc, I can pass in keyword args to op.create_tables that are acceptable to sqlalchemy.schema.table, so I'm using the keep_existing keyword:

op.create_table('foo_model',
  sa.Column('foo_id', sa.Integer(), nullable=False),
  sa.Column('foo_str', sa.String(length=255), nullable=True),
  sa.PrimaryKeyConstraint('foo_id'),
  keep_existing= True
  )

However I'm still getting the table already exists error.

sqlalchemy.exc.InternalError: (InternalError) (1050, u"Table 'foo_model' already exists") '\nCREATE TABLE foo_model (\n\tfoo_id INTEGER NOT NULL AUTO_INCREMENT, \n\tfoo_str VARCHAR(255), \n\tPRIMARY KEY (foo_id)\n)\n\n' ()
like image 815
mingxiao Avatar asked Jul 08 '15 17:07

mingxiao


People also ask

How do you know if a snowflake table exists?

How to check whether a table (or view) exists, and the current user has access to it? SELECT EXISTS ( SELECT FROM information_schema. tables WHERE table_schema = 'schema_name' AND table_name = 'table_name' );

How do I check if a table exists in Python using SQL?

or in Python using psycopg2 : cur. execute( """ SELECT COUNT(*) = 1 FROM pg_tables WHERE tablename = 'my_table'; """ ) exists = cur. fetchone()[0] print(exists) True if exists is False: # table does not exist ...

How do you check tables in Python?

SELECT tableName FROM sqlite_master WHERE type='table' AND tableName='STUDENT'; Then use the fetchall() method on that variable to generate a list of tables containing the name of the that is found. If the list is empty then the table does not exist in the database.

How do I get rid of migration in alembic?

There's currently no command to delete migrations from your versions directory, so if you want to completely wipe away all trace of your bad migration, you'll need to delete the version file (like 4c009570237e_add_widget_table.py ) manually.


1 Answers

You can get the list of existing tables like this:

from sqlalchemy.engine.reflection import Inspector

conn = op.get_bind()
inspector = Inspector.from_engine(conn)
tables = inspector.get_table_names()

and then check if table already exists or not

if table_name not in tables:
   op.create_table()
like image 92
Pindaari Avatar answered Oct 06 '22 01:10

Pindaari