Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(ci): terminate db sessions before DROP DATABASE in hogli (#60608)

mendral-app[bot]1134feeb461d
diff --git a/tools/hogli-commands/hogli_commands/db_schema.py b/tools/hogli-commands/hogli_commands/db_schema.py
index 7f040a7a0dad..673b0d082891 100644
--- a/tools/hogli-commands/hogli_commands/db_schema.py
+++ b/tools/hogli-commands/hogli_commands/db_schema.py
@@ -154,6 +154,13 @@ def _psql_admin(sql: str) -> None:
def _recreate_database(target_db: str) -> None:
+ # Terminate any active sessions on target_db first; otherwise DROP DATABASE
+ # fails with "is being accessed by other users" when an idle connection
+ # remains open from an earlier step (e.g. on CI runners).
+ _psql_admin(
+ f"SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
+ f"WHERE datname = '{target_db}' AND pid <> pg_backend_pid();"
+ )
_psql_admin(f"DROP DATABASE IF EXISTS {target_db};")
_psql_admin(f"CREATE DATABASE {target_db};")
diff --git a/tools/hogli-commands/hogli_commands/tests/test_db_schema.py b/tools/hogli-commands/hogli_commands/tests/test_db_schema.py
index ff43bfa5151d..d79ba8525b7b 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_db_schema.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_db_schema.py
@@ -267,9 +267,15 @@ def test_restore_schema_dump_recreate_cleans_up_after_failure(tmp_path: Path, mo
db_schema.restore_schema_dump(target_db="test_posthog", recreate=True, schema_path=schema_path)
admin_sql = [command[-1] for command in commands]
+ terminate_sql = (
+ "SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
+ "WHERE datname = 'test_posthog' AND pid <> pg_backend_pid();"
+ )
assert admin_sql == [
+ terminate_sql,
"DROP DATABASE IF EXISTS test_posthog;",
"CREATE DATABASE test_posthog;",
+ terminate_sql,
"DROP DATABASE IF EXISTS test_posthog;",
"CREATE DATABASE test_posthog;",
]