Reset PostgreSQL database.
(host: str = None, port: str = None, user: str = None, database: str = None)
| 143 | |
| 144 | |
| 145 | def reset_postgresql(host: str = None, port: str = None, user: str = None, database: str = None): |
| 146 | """Reset PostgreSQL database.""" |
| 147 | conn = get_pg_connection_details() |
| 148 | |
| 149 | # Override with provided parameters |
| 150 | if host: |
| 151 | conn["host"] = host |
| 152 | if port: |
| 153 | conn["port"] = port |
| 154 | if user: |
| 155 | conn["user"] = user |
| 156 | if database: |
| 157 | conn["database"] = database |
| 158 | |
| 159 | log_info(f"Resetting PostgreSQL database: {conn['database']} on {conn['host']}:{conn['port']}") |
| 160 | |
| 161 | # Check if database exists |
| 162 | check_cmd = [ |
| 163 | "psql", |
| 164 | "-h", |
| 165 | conn["host"], |
| 166 | "-p", |
| 167 | conn["port"], |
| 168 | "-U", |
| 169 | conn["user"], |
| 170 | "-lqt", |
| 171 | ] |
| 172 | try: |
| 173 | result = run_command(check_cmd, check=False) |
| 174 | if conn["database"] not in result.stdout: |
| 175 | log_warning(f"Database {conn['database']} does not exist") |
| 176 | return |
| 177 | except Exception as e: |
| 178 | log_warning(f"Could not check if database exists: {e}") |
| 179 | |
| 180 | # Try to drop and recreate database (cleanest approach) |
| 181 | log_info("Attempting to drop and recreate database...") |
| 182 | |
| 183 | # First, terminate any active connections to the database |
| 184 | log_info("Terminating active database connections...") |
| 185 | terminate_sql = f""" |
| 186 | SELECT pg_terminate_backend(pid) |
| 187 | FROM pg_stat_activity |
| 188 | WHERE datname = '{conn["database"]}' AND pid <> pg_backend_pid(); |
| 189 | """ |
| 190 | terminate_cmd = [ |
| 191 | "psql", |
| 192 | "-h", |
| 193 | conn["host"], |
| 194 | "-p", |
| 195 | conn["port"], |
| 196 | "-U", |
| 197 | conn["user"], |
| 198 | "-d", |
| 199 | "postgres", |
| 200 | "-c", |
| 201 | terminate_sql, |
| 202 | ] |
no test coverage detected