def drop_empty_create_table(model): """ Drop an empty table (if it exists) and then create a table """ table_name = model._meta.db_table if model.table_exists(): query = "SELECT CASE WHEN EXISTS (SELECT 1 FROM {}) THEN True ELSE False END".format( table_name) result = db.execute_sql(query).fetchall() if result and result[0] and result[0][0]: logger.error( '%s table already exists and has data, cant be dropped', table_name) raise Exception('Table already exists and has data') else: try: model.drop_table() logger.info('%s table dropped', table_name) model.create_table() logger.info('%s table created', table_name) except Exception as e: db.rollback() logger.error('%s: %s', type(e).__name__, e) else: model.create_table() logger.info('%s table created', table_name)
def rename_column(model, old_column_name, new_column_name): """ Add column to table if it doesn't exist """ table_name = model._meta.db_table if model.table_exists(): try: migrate( migrator.rename_column(table_name, old_column_name, new_column_name)) logger.info('%s column is renamed to %s', old_column_name, new_column_name) except Exception as e: db.rollback() logger.error('%s: %s', (type(e).__name__, e)) else: logger.error('No table with name %s found', table_name)
def add_column(model, column_name, field): """ Add column to table if it doesn't exist """ table_name = model._meta.db_table if model.table_exists(): query = "SELECT True FROM information_schema.columns WHERE table_name='{}' and column_name='{}'".format( table_name, column_name) result = db.execute_sql(query).fetchall() if result and result[0] and result[0][0]: logger.info('%s column is already in the table %s', column_name, table_name) else: try: migrate(migrator.add_column(table_name, column_name, field)) logger.info('%s column is added to the table %s', column_name, table_name) except Exception as e: db.rollback() logger.error('%s: %s', type(e).__name__, e) else: logger.error('No table with name %s found', table_name)
def delete_column(model, column_name): """ Delete column from table if it exist """ table_name = model._meta.db_table if model.table_exists(): query = "SELECT True FROM information_schema.columns WHERE table_name='{}' and column_name='{}'".format( table_name, column_name) a = db.execute_sql(query).fetchall() if a and a[0] and a[0][0]: try: migrate(migrator.drop_column(table_name, column_name)) logger.info('%s column is removed from the table %s', column_name, table_name) except Exception as e: db.rollback() logger.error('%s: %s', type(e).__name__, e) raise e else: logger.info('%s column is not present in the table %s', column_name, table_name) else: logger.error('No table with name %s found', table_name)