{"record":{"id":"faeb3794e055ea7d","repo":"crewAIInc/crewAI","slug":"database-uri-is-required-for-postgresql-loader","errorCode":null,"errorMessage":"Database URI is required for PostgreSQL loader","messagePattern":"Database URI is required for PostgreSQL loader","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"lib/crewai-tools/src/crewai_tools/rag/loaders/postgres_loader.py","lineNumber":30,"sourceCode":"\nclass PostgresLoader(BaseLoader):\n    \"\"\"Loader for PostgreSQL database content.\"\"\"\n\n    def load(self, source: SourceContent, **kwargs: Any) -> LoaderResult:  # type: ignore[override]\n        \"\"\"Load content from a PostgreSQL database table.\n\n        Args:\n            source: SQL query (e.g., \"SELECT * FROM table_name\")\n            **kwargs: Additional arguments including db_uri\n\n        Returns:\n            LoaderResult with database content\n        \"\"\"\n        metadata = kwargs.get(\"metadata\", {})\n        db_uri = metadata.get(\"db_uri\")\n\n        if not db_uri:\n            raise ValueError(\"Database URI is required for PostgreSQL loader\")\n\n        query = source.source\n\n        parsed = urlparse(db_uri)\n        if parsed.scheme not in [\"postgresql\", \"postgres\", \"postgresql+psycopg2\"]:\n            raise ValueError(f\"Invalid PostgreSQL URI scheme: {parsed.scheme}\")\n\n        connection_params = {\n            \"host\": parsed.hostname or \"localhost\",\n            \"port\": parsed.port or 5432,\n            \"user\": parsed.username,\n            \"password\": parsed.password,\n            \"database\": parsed.path.lstrip(\"/\") if parsed.path else None,\n            \"cursor_factory\": RealDictCursor,\n        }\n\n        if not connection_params[\"database\"]:\n            raise ValueError(\"Database name is required in the URI\")","sourceCodeStart":12,"sourceCodeEnd":48,"githubUrl":"https://github.com/crewAIInc/crewAI/blob/754d7323beb2fd042e33444a115ea2d5a47193f0/lib/crewai-tools/src/crewai_tools/rag/loaders/postgres_loader.py#L12-L48","documentation":"Thrown by PGFileLoader.load when no database URI is supplied. The loader does NOT take the URI as a positional argument; it reads it from kwargs['metadata']['db_uri']. If that key is absent or empty, you get this ValueError immediately, before any connection attempt.","triggerScenarios":"Calling pg_loader.load(SourceContent(source='SELECT * FROM users')) without kwargs, or passing db_uri at the wrong level (as a top-level kwarg like load(source, db_uri=...) instead of inside metadata={'db_uri': ...}). Any falsy value (empty string, None) also triggers it.","commonSituations":"Developers assume the URI is a constructor or method parameter because that is the common psycopg/SQLAlchemy pattern; migrating code from an older loader API that accepted the URI directly; forgetting that the loader multiplexes all extras through the metadata dict.","solutions":["Pass the URI inside metadata: pg_loader.load(source_content, metadata={'db_uri': 'postgresql://user:pass@host:5432/mydb'}).","Double-check the exact key spelling — it must be 'db_uri', not 'uri', 'dsn', or 'connection_string'.","Ensure the value is a non-empty string; None or '' fails the truthiness check.","If loading via a config-driven pipeline, verify the metadata dict survives serialization into the loader call."],"exampleFix":"# before\nresult = loader.load(source_content)  # ValueError: Database URI is required\n\n# after\nresult = loader.load(\n    source_content,\n    metadata={\"db_uri\": \"postgresql://user:pass@localhost:5432/mydb\"},\n)","handlingStrategy":"validation","validationCode":"def build_pg_kwargs(db_uri: str) -> dict:\n    if not db_uri:\n        raise ValueError(\"db_uri must be a non-empty postgresql:// URI\")\n    return {\"metadata\": {\"db_uri\": db_uri}}","typeGuard":null,"tryCatchPattern":"try:\n    result = pg_loader.load(src, metadata={\"db_uri\": db_uri})\nexcept ValueError as e:\n    if \"Database URI is required\" in str(e):\n        raise ConfigError(\"pg loader called without metadata['db_uri']\") from e\n    raise","preventionTips":["Centralize loader invocation in one helper that always injects metadata['db_uri'].","Fail fast at startup if the DB URI env var is missing, not at load time.","Remember the URI travels inside the metadata dict — document this in your wrapper's docstring."],"tags":["postgres","database","rag","configuration"],"backgroundTag":null,"analyzedSha":"754d7323beb2fd042e33444a115ea2d5a47193f0","analyzedAt":"2026-08-15T04:06:56.746Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}