{"record":{"id":"f9a404b4e2d6ce7f","repo":"BerriAI/litellm","slug":"database-not-connected-connect-a-database-to-your","errorCode":null,"errorMessage":"Database not connected. Connect a database to your proxy - https://docs.litellm.ai/docs/simple_proxy#managing-auth---virtual-keys","messagePattern":"Database not connected\\. Connect a database to your proxy - https://docs\\.litellm\\.ai/docs/simple_proxy#managing-auth---virtual-keys","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"litellm/integrations/cloudzero/database.py","lineNumber":35,"sourceCode":"# CHANGELOG: 2025-01-19 - Initial database module for LiteLLM data extraction (erik.peterson)\n\n\"\"\"Database connection and data extraction for LiteLLM.\"\"\"\n\nfrom datetime import datetime\nfrom typing import Any, Final\n\nimport polars as pl\n\n\nclass LiteLLMDatabase:\n    \"\"\"Handle LiteLLM PostgreSQL database connections and queries.\"\"\"\n\n    def _ensure_prisma_client(self):\n        from litellm.proxy.proxy_server import prisma_client\n\n        \"\"\"Ensure prisma client is available.\"\"\"\n        if prisma_client is None:\n            raise Exception(\n                \"Database not connected. Connect a database to your proxy - https://docs.litellm.ai/docs/simple_proxy#managing-auth---virtual-keys\"\n            )\n        return prisma_client\n\n    async def get_usage_data(\n        self,\n        limit: int | None = None,\n        start_time_utc: datetime | None = None,\n        end_time_utc: datetime | None = None,\n    ) -> pl.DataFrame:\n        \"\"\"Retrieve usage data from LiteLLM daily user spend table.\"\"\"\n        client: Final = self._ensure_prisma_client()\n\n        # Query to get user spend data with team information. Use parameter binding to\n        # avoid SQL injection from user-supplied timestamps or limits.\n        query = \"\"\"\n        SELECT\n            dus.id,","sourceCodeStart":17,"sourceCodeEnd":53,"githubUrl":"https://github.com/BerriAI/litellm/blob/77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8/litellm/integrations/cloudzero/database.py#L17-L53","documentation":"LiteLLM's CloudZero integration reads usage rows from the proxy's PostgreSQL spend tables through the Prisma client stored on litellm.proxy.proxy_server.prisma_client. LiteLLMDatabase._ensure_prisma_client() raises this generic Exception when that module-global is None, meaning the proxy was never started with a database connected. Every CloudZero usage export fails until the proxy has initialized its Prisma connection.","triggerScenarios":"Awaiting LiteLLMDatabase().get_usage_data() in a process where the LiteLLM proxy was never started with DATABASE_URL set (prisma_client stays None); running the CloudZero export as a standalone script that imports litellm but never boots the proxy server; calling the export before the proxy's DB connection has finished initializing.","commonSituations":"Fresh deployment missing the DATABASE_URL env var; export job split from the proxy runtime so no proxy state exists in-process; typo'd or unset DATABASE_URL letting the proxy start DB-less; litellm version drift changing when prisma_client is populated.","solutions":["Set DATABASE_URL on the proxy (export DATABASE_URL=postgresql://user:pass@host:5432/litellm) and restart it so prisma_client is created","Or put the Postgres URL under the database: key of the proxy config YAML and start with litellm --config config.yaml","If exporting from a separate process, query the LiteLLM_DailyUserSpend table directly over Postgres instead of relying on the in-process prisma_client","Before exporting, assert the client exists: from litellm.proxy.proxy_server import prisma_client; if prisma_client is None: fail with a config error"],"exampleFix":"# before: export runs in a bare process with no proxy\nfrom litellm.integrations.cloudzero.database import LiteLLMDatabase\ndf = await LiteLLMDatabase().get_usage_data()  # Exception: Database not connected...\n\n# after: proxy started with a database first\n# export DATABASE_URL=postgresql://user:pass@host:5432/litellm\n# litellm --config config.yaml   (config contains database url)\nfrom litellm.proxy.proxy_server import prisma_client\nassert prisma_client is not None, \"start the proxy with DATABASE_URL before exporting\"\ndf = await LiteLLMDatabase().get_usage_data()","handlingStrategy":"validation","validationCode":"from litellm.proxy.proxy_server import prisma_client\n\nif prisma_client is None:\n    raise RuntimeError(\"LiteLLM proxy has no database; set DATABASE_URL before running the CloudZero export\")\n\ndf = await LiteLLMDatabase().get_usage_data(limit=1000)","typeGuard":null,"tryCatchPattern":"try:\n    df = await db.get_usage_data(...)\nexcept Exception as e:\n    if 'Database not connected' in str(e):\n        raise RuntimeError('start proxy with DATABASE_URL set') from e\n    raise","preventionTips":["Always set DATABASE_URL in the proxy deployment environment","Gate export jobs on a proxy health endpoint that reports database status","Fail startup checks when prisma_client is None after proxy boot"],"tags":["litellm","cloudzero","prisma","postgres","database","configuration"],"backgroundTag":"database-not-connected","analyzedSha":"77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8","analyzedAt":"2026-08-18T11:44:31.656Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}