crewAIInc/crewAI · error · ValueError
Database URI is required for PostgreSQL loader
Error message
Database URI is required for PostgreSQL loader
What it means
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.
Source
Thrown at lib/crewai-tools/src/crewai_tools/rag/loaders/postgres_loader.py:30
class PostgresLoader(BaseLoader):
"""Loader for PostgreSQL database content."""
def load(self, source: SourceContent, **kwargs: Any) -> LoaderResult: # type: ignore[override]
"""Load content from a PostgreSQL database table.
Args:
source: SQL query (e.g., "SELECT * FROM table_name")
**kwargs: Additional arguments including db_uri
Returns:
LoaderResult with database content
"""
metadata = kwargs.get("metadata", {})
db_uri = metadata.get("db_uri")
if not db_uri:
raise ValueError("Database URI is required for PostgreSQL loader")
query = source.source
parsed = urlparse(db_uri)
if parsed.scheme not in ["postgresql", "postgres", "postgresql+psycopg2"]:
raise ValueError(f"Invalid PostgreSQL URI scheme: {parsed.scheme}")
connection_params = {
"host": parsed.hostname or "localhost",
"port": parsed.port or 5432,
"user": parsed.username,
"password": parsed.password,
"database": parsed.path.lstrip("/") if parsed.path else None,
"cursor_factory": RealDictCursor,
}
if not connection_params["database"]:
raise ValueError("Database name is required in the URI")View on GitHub (pinned to 754d7323be)
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.
Example fix
# before
result = loader.load(source_content) # ValueError: Database URI is required
# after
result = loader.load(
source_content,
metadata={"db_uri": "postgresql://user:pass@localhost:5432/mydb"},
) Defensive patterns
Strategy: validation
Validate before calling
def build_pg_kwargs(db_uri: str) -> dict:
if not db_uri:
raise ValueError("db_uri must be a non-empty postgresql:// URI")
return {"metadata": {"db_uri": db_uri}} Try / catch
try:
result = pg_loader.load(src, metadata={"db_uri": db_uri})
except ValueError as e:
if "Database URI is required" in str(e):
raise ConfigError("pg loader called without metadata['db_uri']") from e
raise Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- Database name is required in the URI
- PostgreSQL database error: {e}
- Project name cannot be empty
- Project name '{name}' produces invalid folder name '{folder_
- Failed to initialize {self.config.provider} embedding servic
AI-assisted analysis of crewAIInc/crewAI@754d7323be (2026-08-15).
Data as JSON: /api/errors/faeb3794e055ea7d.
Report an issue: GitHub.