diff --git a/app.py b/app.py index ea09530..7ccc617 100644 --- a/app.py +++ b/app.py @@ -219,15 +219,24 @@ def run_sql_query(container_name: str, query: str) -> dict: """ Execute a SQL query inside a database container using docker exec. Supports Postgres and MySQL/MariaDB. + Infers the database name from the Dokku container name. """ try: + # Infer DB name: dokku.postgres.my-service -> my-service + # Dokku services follow the naming: dokku.. + parts = container_name.split(".", 2) + db_name = parts[2] if len(parts) >= 3 else None + if "postgres" in container_name: # Postgres: use psql with CSV-like output - # -A: unaligned, -F: separator, -t: tuples only (no headers) -> let's keep headers for now - cmd = [DOCKER, "exec", container_name, "psql", "-U", "postgres", "-c", query, "-A", "-F", ","] + # Target the specific database using -d + db_arg = ["-d", db_name] if db_name else [] + cmd = [DOCKER, "exec", container_name, "psql", "-U", "postgres"] + db_arg + ["-c", query, "-A", "-F", ","] elif "mysql" in container_name or "mariadb" in container_name: # MySQL: use mysql with tab-separated output - cmd = [DOCKER, "exec", container_name, "mysql", "-u", "root", "-e", query, "-B"] + # Target the specific database by passing its name + db_arg = [db_name] if db_name else [] + cmd = [DOCKER, "exec", container_name, "mysql", "-u", "root", "-e", query, "-B"] + db_arg else: return {"error": "Unsupported database type"}