{"record":{"id":"0b5d966bb3e1f72b","repo":"Graphify-Labs/graphify","slug":"could-not-connect-to-postgresql-msg","errorCode":null,"errorMessage":"could not connect to PostgreSQL: {msg}","messagePattern":"could not connect to PostgreSQL: (.+?)","errorType":"exception","errorClass":"ConnectionError","httpStatus":null,"severity":"error","filePath":"graphify/pg_introspect.py","lineNumber":27,"sourceCode":"\n\ndef introspect_postgres(dsn: str | None = None) -> dict:\n    \"\"\"Connect to PostgreSQL, reconstruct DDL, and extract via extract_sql().\"\"\"\n    try:\n        import psycopg\n    except ModuleNotFoundError:\n        raise ImportError(\n            \"psycopg is required for --postgres. \"\n            \"Install with: pip install 'graphifyy[postgres]'\"\n        )\n\n    try:\n        conn = psycopg.connect(dsn or \"\")  # empty string = PG* env vars\n    except psycopg.OperationalError as exc:\n        # Sanitize: strip the DSN/credentials that psycopg may embed in the\n        # OperationalError message (e.g. \"connection to server … failed: …\\nDETAIL: …\")\n        msg = str(exc).split(\"\\n\")[0]\n        raise ConnectionError(f\"could not connect to PostgreSQL: {msg}\") from None\n\n    try:\n        conn.execute(\"SET TRANSACTION ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE\")\n\n        # 1. Query tables\n        with conn.cursor() as cur:\n            cur.execute(\"\"\"\n                SELECT table_schema, table_name, table_type\n                FROM information_schema.tables\n                WHERE table_schema NOT IN ('pg_catalog', 'information_schema')\n                ORDER BY table_schema, table_name;\n            \"\"\")\n            tables = cur.fetchall()\n\n            # 2. Query views\n            cur.execute(\"\"\"\n                SELECT table_schema, table_name, view_definition\n                FROM information_schema.views","sourceCodeStart":9,"sourceCodeEnd":45,"githubUrl":"https://github.com/Graphify-Labs/graphify/blob/7fe58b0b0f3873be9a21c30106b8b8527c353aa6/graphify/pg_introspect.py#L9-L45","documentation":"ConnectionError raised when psycopg.connect() fails with OperationalError. graphify deliberately sanitizes the message to its first line (dropping DETAIL lines) because psycopg OperationalErrors can embed the full DSN with credentials; `from None` suppresses the chain so the DSN never leaks into tracebacks/logs.","triggerScenarios":"psycopg.connect(dsn or '') raises OperationalError at pg_introspect.py:22-27 - unreachable host, wrong port, auth failure, nonexistent database, or missing PG* env vars when dsn is empty (empty string means 'use libpq environment').","commonSituations":"Wrong or expired DB passwords; security-group/firewall blocks between the runner and RDS/CloudSQL; PGDATABASE/PGUSER unset so libpq defaults to the OS user and fails; SSL requirements on the server rejecting the connection; localhost vs socket path confusion.","solutions":["Read the first line of the message - it names host/port/reason without credentials; fix whichever it reports (DNS, auth, firewall).","If relying on PG* vars, confirm PGHOST/PGUSER/PGDATABASE/PGPASSWORD are all set in the graphify process.","Test independently: psql with the same DSN - if psql also fails, fix at the infrastructure level.","For SSL-required servers, add ?sslmode=require to the DSN."],"exampleFix":"# before\n$ graphify extract --postgres   # ConnectionError: could not connect to PostgreSQL: ...\n\n# after - check env/DSN, then test with psql first\n$ psql \"postgresql://user:pass@db.internal:5432/app\" -c 'select 1'\n$ graphify extract --postgres --dsn \"postgresql://user:pass@db.internal:5432/app\"","handlingStrategy":"validation","validationCode":"import psycopg\n\ndef can_connect(dsn):\n    try:\n        conn = psycopg.connect(dsn or \"\", connect_timeout=5)\n        conn.close()\n        return True\n    except psycopg.OperationalError:\n        return False\n\nif not can_connect(dsn):\n    raise SystemExit(\"PostgreSQL unreachable - check DSN/PG* env and network\")","typeGuard":null,"tryCatchPattern":"try:\n    schema = introspect_postgres(dsn)\nexcept ConnectionError as exc:\n    if \"could not connect\" in str(exc):\n        raise SystemExit(f\"DB connectivity problem: {exc}\") from exc\n    raise","preventionTips":["Keep DSNs out of logs - this sanitizer exists because leaks were a real risk; preserve that in your own wrappers.","Use connect_timeout in preflight checks so hangs do not stall pipelines.","For cloud DBs, verify security groups/VPC peering before blaming credentials."],"tags":["postgres","database","network","connection"],"backgroundTag":null,"analyzedSha":"7fe58b0b0f3873be9a21c30106b8b8527c353aa6","analyzedAt":"2026-08-14T19:23:21.323Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}