Last active
July 26, 2023 00:54
-
-
Save monkut/b54c528a1dac4025ca2a047ed55d479a to your computer and use it in GitHub Desktop.
create drop tables commands for django (zappa raw_command) for resetting database
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
def create_drop_tables_raw_command(tables: list[str]) -> str: | |
"""Get list of tables using the 'manage sqlflush' command. This will create the DROP TABLE command for resetting the database""" | |
django_migrations_table = "django_migrations" | |
if django_migrations_table not in tables: | |
print(f"-- '{django_migrations_table}' not given, adding to tables!") | |
tables.append(django_migrations_table) | |
statements = ["from django.db import connection"] | |
statements.append("cursor = connection.cursor()") | |
drop_table_sql = ["BEGIN;"] | |
for table in tables: | |
sql = f"DROP TABLE {table} CASCADE;" | |
drop_table_sql.append(sql) | |
drop_table_sql.append("COMMIT;") | |
drop_sql_command = f"cursor.execute('''{''.join(drop_table_sql)}''')" | |
statements.append(drop_sql_command) | |
return ";".join(statements) | |
command = create_drop_tables_raw_command(list(tables)) | |
print(command) | |
def get_list_tables_command(): | |
statements = ["from django.db import connection"] | |
statements.append("cursor = connection.cursor()") | |
list_tables_sql = "select table_name from information_schema.tables" | |
command = f"cursor.execute('''{list_tables_sql}''')" | |
statements.append(command) | |
command = "results = [r[0] for r in cursor.fetchall() if r[0].startswith('django_')]" | |
statements.append(command) | |
statements.append("print(results)") | |
return ";".join(statements) | |
print(get_list_tables_command()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment