DEV Community

Shubham Vernekar
Shubham Vernekar

Posted on

Stop AI Agents from Hallucinating Database Schemas: Prisma ORM Connector for Cognee

Autonomous AI coding agents such as Claude Code, Cursor, Devin, and GitHub Copilot are increasingly trusted to write database migrations, backend services, and API controllers. But when developers ask an agent to "add a feature that filters orders by organization role", they can encounter a common problem: database schema hallucination.

For example:

  • The agent invents field names, calling user.organizationId when the actual field is user.org_id.
  • It hallucinates relationships that do not exist between tables.
  • It invents enum variants or overlooks foreign key constraints.
  • It produces code that looks syntactically correct but fails at runtime.

Why does this happen?

Large language models (LLMs) generate responses based on learned patterns and the context available to them. Without reliable access to the application's actual database schema, they may generate plausible-looking but incorrect code.

In modern full-stack engineering, the schema.prisma file defines Prisma models, relations, field types, constraints, enums, and indexes.

What if AI coding agents could retrieve this schema information instead of guessing?

As part of Mergetober, I worked on a Prisma Schema Data-Source Connector for Cognee, intended to make Prisma schema information available through a structured knowledge graph and memory pipeline.

In this article, I'll explain why Prisma schema context matters, how the connector is designed, and how developers can use a schema-ingestion workflow to give AI agents more reliable database context.


1. Why Prisma Schemas?

Prisma is an ORM used across the TypeScript, Node.js, and web development ecosystem.

A typical schema.prisma file defines several kinds of information that are essential for generating correct database code:

  • Models and scalar fields: Types such as String, Int, Boolean, and DateTime, along with optional fields (?) and list fields ([]).
  • Primary keys and attributes: @id, @default(uuid()), @unique, and @updatedAt.
  • Relational mappings: Relations and foreign key declarations such as @relation(fields: [authorId], references: [id]).
  • Enums and custom types: Allowed values for roles, statuses, and permissions.

For example:

enum Role {
  USER
  ADMIN
  OWNER
}
Enter fullscreen mode Exit fullscreen mode
  • Documentation comments: Triple-slash comments (///) that describe models and fields.

If an AI agent does not have access to the actual schema, it might invent an enum value, use an incorrect field name, or misunderstand a relationship.

Pasting an entire 2,000-line schema into every prompt is one possible workaround, but it can consume context-window space and make relevant details harder to retrieve.

A better approach is to structure, index, and retrieve schema information when it is needed.


2. Introducing Cognee: Structured Knowledge for AI Agents

Cognee is an open-source framework for building AI memory systems using structured knowledge and retrieval.

The idea behind integrating Prisma with Cognee is to make database schema information easier to retrieve when an AI coding agent needs it.

A schema-aware workflow can support:

  • Schema entities: Represent models and enums as distinct pieces of information.
  • Relationship context: Preserve relationships between models where supported by the ingestion pipeline.
  • Semantic retrieval: Search for relevant models, fields, and relationships using natural-language questions.
  • Reduced guesswork: Provide schema context before an agent generates ORM calls, queries, or backend services.

For example, a developer could ask:

Which model links Users to Organizations, and which field is used as the foreign key?

The system can retrieve relevant schema information and provide it to the agent as supporting context.

The goal is to ground code generation in the application's actual schema rather than relying on the model's assumptions alone.


3. Architectural Overview: The Prisma Connector

The connector is located in cognee-community/packages/connector/prisma.

The conceptual architecture looks like this:

schema.prisma File
        |
        v
Prisma Schema Connector (cognee-community)
        |
        v
Extract Models, Relations, Enums and Documentation
        |
        v
Cognee Ingestion Pipeline (dlt resource)
        |
        v
Knowledge Graph + Vector Retrieval
        |
        v
AI Coding Agent (Cursor, Devin, Claude Code)
        |
        v
Schema-Grounded ORM Code
Enter fullscreen mode Exit fullscreen mode

3.1. Deterministic Primary Keys

A connector can use stable identifiers to distinguish models and enums:

prisma:model:{model_name}
prisma:enum:{enum_name}
Enter fullscreen mode Exit fullscreen mode

Stable identifiers help track schema entities across repeated imports. However, identifier stability alone does not guarantee idempotent synchronization; the ingestion and storage layers must also handle updates, renamed entities, and duplicate records correctly.

3.2. Full-Snapshot Synchronization

Database schemas evolve rapidly. Developers add models, rename fields, change relationships, and remove obsolete definitions.

A snapshot-based synchronization strategy, such as write_disposition="replace", may help keep indexed schema information aligned with the current source file.

However, verify the actual cleanup behavior before assuming that deleted models are automatically removed from every graph and vector index.

3.3. Rich, Agent-Friendly Schema Representations

A connector can represent schema information in a structured, human-readable format:

Model: User
Description: Active user account
Fields:
  - id: String @id @default(uuid())
  - email: String @unique
  - role: Role (default: USER)
  - orgId: String
Relations:
  - organization: Organization (optional)
  - posts: Post[] (one-to-many)
Enter fullscreen mode Exit fullscreen mode

This is an illustrative representation. The actual fields, relationships, and formatting depend on the source schema and connector implementation.


4. Step-by-Step: Ingesting schema.prisma into Cognee

The following workflow illustrates the intended integration. Verify the package name, import path, function arguments, and supported APIs against the actual connector implementation before running the example.

Step 1: Install Dependencies

If the connector is published under the package name shown below, install it using:

pip install cognee cognee-community-connector-prisma
Enter fullscreen mode Exit fullscreen mode

If the connector is available only through a GitHub branch or pull request, follow the repository's installation instructions instead.

Step 2: Prepare Your Schema

Locate your Prisma schema file:

my-project/
├── prisma/
│   └── schema.prisma
└── index_schema.py
Enter fullscreen mode Exit fullscreen mode

Your schema may be located elsewhere depending on your project configuration.

Step 3: Ingest and Search Schema Memory

The following Python script assumes that the connector exposes prisma_schema_source() and that the installed Cognee version supports the APIs shown.

import asyncio
import cognee

from cognee_community_connector_prisma import (
    prisma_schema_source,
)


async def main():
    # Step 1: Load schema.prisma.
    print("Loading schema.prisma into Cognee...")

    source = prisma_schema_source(
        schema_path="./prisma/schema.prisma"
    )

    # Step 2: Ingest the schema.
    await cognee.remember(
        source,
        dataset_name="database_schema",
    )

    # Step 3: Build the knowledge representation.
    print("Processing schema knowledge...")

    await cognee.cognify(
        dataset_name="database_schema",
    )

    # Step 4: Query schema memory.
    print("Searching database schema...")

    results = await cognee.search(
        "Which model links Users to Organizations, "
        "and which field is used as the foreign key?",
        dataset_name="database_schema",
    )

    for result in results:
        print(result)


if __name__ == "__main__":
    asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

Implementation notes:

  • Verify that the connector exposes prisma_schema_source() with a schema_path argument.
  • Confirm that the installed Cognee version supports the shown ingestion, processing, and search interfaces.
  • Configure any required LLM, embedding, and storage providers according to Cognee's documentation.
  • Test retrieval against known models, fields, and relationships from your schema.
  • Treat retrieved schema information as supporting context, not a guarantee of correct generated code.

This is an illustrative integration pattern, not a verified, drop-in script until the connector's actual APIs have been checked.


5. Result: More Reliable, Schema-Grounded Database Queries

With schema-aware retrieval, an AI coding agent can first retrieve relevant model definitions and use them to construct a query.

For example:

const usersInOrg = await prisma.user.findMany({
  where: {
    orgId: organizationId,
    role: "ADMIN",
  },
  include: {
    organization: true,
  },
});
Enter fullscreen mode Exit fullscreen mode

Important: This query is valid only if the actual Prisma schema defines orgId, the ADMIN enum value, and the organization relation as shown. If the schema uses different field names or relationships, the query must be adapted accordingly.

The goal is to help AI agents use the real schema instead of inventing fields or relationships.

To evaluate whether this approach works, compare generated code with and without retrieved schema context.

Potential evaluation metrics include:

  • Field-name accuracy.
  • Model and relationship accuracy.
  • Enum-value validity.
  • Type correctness.
  • Successful Prisma type checking.
  • Query execution against a test database.
  • Frequency of unsupported fields and relations.

Testing representative database tasks can help measure whether schema retrieval improves the reliability of AI-generated code.


6. Open-Source Pull Request and References

This work is part of my exploration of open-source tools that can make AI-assisted software development more reliable.

Check the repository and pull request for the connector's current implementation, installation instructions, and contribution status.


Top comments (0)