Skip to content

Commit 4f4bd6f

Browse files
committed
Enhance logging and error handling in configuration and command execution
1 parent 8dc93f8 commit 4f4bd6f

File tree

2 files changed

+84
-26
lines changed

2 files changed

+84
-26
lines changed

cloudsql_to_supabase/config.py

Lines changed: 31 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,50 @@
11
from dotenv import load_dotenv
22
import os
3+
from pathlib import Path
4+
import logging
35

6+
logging.basicConfig(level=logging.INFO,format='%(asctime)s - %(levelname)s - %(message)s')
7+
8+
9+
logger = logging.getLogger('cloudsql_to_supabase')
410

511
load_dotenv()
612

13+
714
CLOUDSQL_USER = os.getenv("CLOUDSQL_USER")
815
CLOUDSQL_HOST = os.getenv("CLOUDSQL_HOST")
916
CLOUDSQL_DB = os.getenv("CLOUDSQL_DB")
10-
SUPABASE_USER = os.getenv("SUPABASE_USER")
17+
CLOUDSQL_PORT = int(os.getenv("CLOUDSQL_PORT", 5432))
18+
CLOUDSQL_SSL_MODE = os.getenv("CLOUDSQL_SSL_MODE", "prefer")
19+
20+
SUPABASE_USER = os.getenv("SUPABASE_USER", "postgres")
1121
SUPABASE_HOST = os.getenv("SUPABASE_HOST")
1222
SUPABASE_DB = os.getenv("SUPABASE_DB", "postgres")
1323
SUPABASE_PASSWORD = os.getenv("SUPABASE_PASSWORD")
1424
SUPABASE_PORT = int(os.getenv("SUPABASE_PORT", 5432))
15-
OUTPUT_DUMP = "backup.sql"
16-
CLEANED_DUMP = "cleaned_backup.sql"
25+
SUPABASE_SSL_MODE = os.getenv("SUPABASE_SSL_MODE", "require")
26+
27+
OUTPUT_DIR = Path(os.getenv('OUTPUT_DIR', '.'))
28+
OUTPUT_DUMP = OUTPUT_DIR / os.getenv("OUTPUT_DUMP", "backup.sql")
29+
CLEANED_DUMP = OUTPUT_DIR / os.getenv("CLEANED_DUMP", "cleaned_backup.sql")
1730

1831

1932
def validate_config():
2033
"""
2134
Validate the configuration values.
2235
"""
23-
required_vars = [
24-
"CLOUDSQL_USER",
25-
"CLOUDSQL_HOST",
26-
"CLOUDSQL_DB",
27-
"SUPABASE_USER",
28-
"SUPABASE_HOST",
29-
"SUPABASE_DB",
30-
"SUPABASE_PASSWORD",
31-
"SUPABASE_PORT",
32-
]
33-
for var in required_vars:
34-
if not os.getenv(var):
35-
raise ValueError(f"Environment variable {var} is not set.")
36-
if not SUPABASE_PORT or SUPABASE_PORT <= 0:
37-
raise ValueError("SUPABASE_PORT must be a positive integer.")
38-
36+
required_vars = {
37+
"CLOUDSQL_USER": CLOUDSQL_USER,
38+
"CLOUDSQL_HOST": CLOUDSQL_HOST,
39+
"CLOUDSQL_DB": CLOUDSQL_DB,
40+
"SUPABASE_HOST": SUPABASE_HOST,
41+
"SUPABASE_PASSWORD": SUPABASE_PASSWORD,
42+
}
43+
44+
45+
missing = [var for var, value in required_vars.items() if not value]
46+
47+
if missing:
48+
raise ValueError(f"Missing required environment variables: {', '.join(missing)}")
49+
50+
OUTPUT_DIR.mkdir(exist_ok=True)

cloudsql_to_supabase/utils.py

Lines changed: 53 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,55 @@
11
import subprocess
2+
import shlex
3+
from typing import Dict, Optional, List, Union
4+
import logging
25

3-
def run_command(command, env=None):
4-
print(f"Running command: {command}")
5-
result = subprocess.run(command, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
6-
if result.returncode != 0:
7-
print(result.stderr.decode())
8-
raise Exception(f"Command failed with error: {result.stderr.decode()}")
9-
6+
7+
8+
logger = logging.getLogger('cloud_to_supabase.utils')
9+
10+
11+
def run_command(cmd: str, env: Optional[Dict] = None, show_output: bool = True)-> subprocess.CompletedProcess:
12+
"""
13+
Run a shell command safely with proper logging and error handling.
14+
15+
Args:
16+
cmd: Command to run
17+
env: Environment variables
18+
show_output: Whether to print command output to console
19+
20+
Returns:
21+
CompletedProcess instance
22+
"""
23+
24+
safe_cmd = cmd
25+
if "PGPASSWORD" in str(env):
26+
safe_cmd = cmd.replace(env.get('PGPASSWORD', ''), '************')
27+
logger.info(f'Running command: {safe_cmd}')
28+
29+
30+
try:
31+
args = shlex.split(cmd)
32+
result = subprocess.run(
33+
args,
34+
env=env,
35+
stdout=subprocess.PIPE,
36+
stderr=subprocess.PIPE,
37+
text=True,
38+
check=False
39+
)
40+
41+
if result.returncode != 0:
42+
logger.error(f'command failed with exit code {result.returncode}')
43+
logger.error(result.stderr)
44+
raise RuntimeError(f'command failed: {result.stderr}')
45+
46+
47+
if show_output and result.stdout:
48+
logger.info(result.stdout)
49+
50+
51+
return result
52+
53+
except Exception as e:
54+
logger.exception(f'Error executing command: {e}')
55+
raise

0 commit comments

Comments
 (0)