{"record":{"id":"0b4bfdb80f4edaef","repo":"django/django","slug":"database-s-couldn-t-be-flushed-possible-reasons","errorCode":null,"errorMessage":"Database %s couldn't be flushed. Possible reasons:\n  * The database isn't running or isn't configured correctly.\n  * At least one of the expected database tables doesn't exist.\n  * The SQL was invalid.\nHint: Look at the output of 'django-admin sqlflush'. That's the SQL this command wasn't able to run.","messagePattern":"Database (.+?) couldn't be flushed\\. Possible reasons:\n  \\* The database isn't running or isn't configured correctly\\.\n  \\* At least one of the expected database tables doesn't exist\\.\n  \\* The SQL was invalid\\.\nHint: Look at the output of 'django-admin sqlflush'\\. That's the SQL this command wasn't able to run\\.","errorType":"console","errorClass":"CommandError","httpStatus":null,"severity":"critical","filePath":"django/core/management/commands/flush.py","lineNumber":73,"sourceCode":"            reset_sequences=reset_sequences,\n            allow_cascade=allow_cascade,\n        )\n\n        if interactive:\n            confirm = input(\"\"\"You have requested a flush of the database.\nThis will IRREVERSIBLY DESTROY all data currently in the \"%s\" database,\nand return each table to an empty state.\nAre you sure you want to do this?\n\n    Type 'yes' to continue, or 'no' to cancel: \"\"\" % connection.settings_dict[\"NAME\"])\n        else:\n            confirm = \"yes\"\n\n        if confirm == \"yes\":\n            try:\n                connection.ops.execute_sql_flush(sql_list)\n            except Exception as exc:\n                raise CommandError(\n                    \"Database %s couldn't be flushed. Possible reasons:\\n\"\n                    \"  * The database isn't running or isn't configured correctly.\\n\"\n                    \"  * At least one of the expected database tables doesn't exist.\\n\"\n                    \"  * The SQL was invalid.\\n\"\n                    \"Hint: Look at the output of 'django-admin sqlflush'. \"\n                    \"That's the SQL this command wasn't able to run.\"\n                    % (connection.settings_dict[\"NAME\"],)\n                ) from exc\n\n            # Empty sql_list may signify an empty database and post_migrate\n            # would then crash.\n            if sql_list and not inhibit_post_migrate:\n                # Emit the post migrate signal. This allows individual\n                # applications to respond as if the database had been migrated\n                # from scratch.\n                emit_post_migrate_signal(verbosity, interactive, database)\n        else:\n            self.stdout.write(\"Flush cancelled.\")","sourceCodeStart":55,"sourceCodeEnd":91,"githubUrl":"https://github.com/django/django/blob/ae25a40be07e8a749edf526df37c93e59d4a22c9/django/core/management/commands/flush.py#L55-L91","documentation":"Raised by the flush command when connection.ops.execute_sql_flush(sql_list) raises any exception (flush.py:70-81). The command generates SQL via sql_flush() (DELETE/TRUNCATE/RESET SEQUENCE statements) and runs it atomically; failure is re-raised as CommandError chaining the original via `from exc`. The hint points to `django-admin sqlflush` because that prints the exact SQL bundle that failed, letting you inspect which statement broke.","triggerScenarios":"Running `python manage.py flush` when migrations have not been applied (expected tables missing); flushing a DB the process lacks DELETE/TRUNCATE privileges on; a foreign-key constraint blocks a DELETE ordering error; the DB server is unreachable mid-command; a third-party backend producing invalid SQL.","commonSituations":"Fresh clone where someone ran `flush` before `migrate`; running flush in CI against a shared DB with restricted grants; switching DB engines (sqlite->postgres) without migrating; tables manually dropped outside Django leaving schema inconsistent.","solutions":["Run `python manage.py migrate` first so all expected tables exist, then retry flush.","Run `django-admin sqlflush` (or `python manage.py sqlflush`) and execute statements manually to find the exact failing SQL and DB error.","Check DB user grants: the role needs DELETE/TRUNCATE/ALTER SEQUENCE on the relevant tables.","Confirm the DB is reachable: `python manage.py dbshell` or check connection settings in DATABASES.","If caused by FK constraints, ensure sql_flush emits statements in the right order for your backend (report a backend bug if not)."],"exampleFix":"// before\npython manage.py flush --noinput\n// after\npython manage.py migrate\npython manage.py flush --noinput","handlingStrategy":"validation","validationCode":"from django.db import connections\nfrom django.core.management import call_command\n\nconn = connections['default']\n# Ensure schema exists before flushing\nwith conn.cursor() as cur:\n    cur.execute('SELECT 1')  # raises if DB unreachable\n# Run migrations first so expected tables exist\ncall_command('migrate', interactive=False)","typeGuard":"def db_ready_for_flush(alias='default') -> bool:\n    from django.db import connections\n    conn = connections[alias]\n    try:\n        with conn.cursor() as cur:\n            cur.execute('SELECT 1')\n        return True\n    except Exception:\n        return False","tryCatchPattern":"from django.core.management.base import CommandError\nfrom django.core.management import call_command\n\ntry:\n    call_command('flush', interactive=False)\nexcept CommandError as e:\n    # Inspect `python manage.py sqlflush` output, fix schema/grants, retry\n    logger.error('Flush failed; run `manage.py sqlflush` to inspect SQL: %s', e)\n    raise","preventionTips":["Always run `migrate` before `flush` so expected tables exist.","Grant the DB role DELETE/TRUNCATE/ALTER SEQUENCE privileges.","Never run flush against a DB you cannot afford to wipe; it is irreversible."],"tags":["django","flush","database","management-command","data-loss"],"analyzedSha":"ae25a40be07e8a749edf526df37c93e59d4a22c9","analyzedAt":"2026-08-06T21:46:51.801Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}