Prisma Next

repository·main·Indexed 13 days ago

https://github.com/prisma/prisma

A TypeScript rewrite of Prisma ORM designed for extensibility, composability, and native AI-agent compatibility. It features a structured environment for AI agents to drive database schema changes and queries using specialized 'skills', and includes tools like the lsp-playground for PSL diagnostics and formatting.

Tokens
795.1K
Snippets
1.6K
Records
3.1K
Agent score
96%

What's inside Prisma Next

  1. What is @internal/ts-render?

    main

    Note: @internal/ts-render is an internal package and an implementation detail of prisma-next. It is published only to support the prisma-next runtime. Its API is unstable and may change without notice.

    Do not depend on this package directly; install prisma-next instead.

    This package provides TypeScript source-text rendering utilities used by Prisma Next components that need to emit hand-editable .ts files, such as the Postgres and Mongo migration-authoring surfaces.

  2. Overview of Prisma Next architecture patterns

    main

    The Prisma Next codebase follows a set of established structural shapes known as architecture patterns. This catalogue serves as the single source of truth for recurring structural decisions, distinguishing them from one-time decisions (ADRs), tactical rules (Cursor rules), or subsystem-specific guides (Reference docs).

    Pattern Selection Guide

    Use the following table to identify the correct pattern for your current task:

    PatternUse this when...
    Frozen-class AST + visitorYou have a tree with many kinds and many consumers, and you want every consumer to break loudly when a new kind is added.
    JSON-canonical / class-in-memory round-tripYou're writing data to disk that another process will read back, and you want the on-disk form to be diffable, greppable, and hashable.
    Three-layer polymorphic IRAn IR crosses the framework/target boundary and targets need to add kinds the framework cannot anticipate (e.g., Postgres-only, Mongo-only).
    SPI at the lowest consuming layerA lower layer needs to call into a higher-layer implementation, and pnpm lint:deps would otherwise force a circular import.
    Interface + factory functionYou're building a stateful service (registry, runtime, adapter, driver) and consumers should never see the implementation class.
    Adapter SPI for target-specific behaviourThe framework needs target-specific behaviour (dialect, capabilities, error mapping) and you can't write if (target === 'postgres').
    Capability gatingA feature is target-optional or target-varying (e.g., RETURNING, LATERAL, prepared statements), and the framework needs to check before relying on it.
    Package layeringYou're creating a new package, adding an import, or reaching for "shared utilities" and need to know where it belongs.
    Authoring warning sinkA target pack or lowering helper needs to surface a non-fatal, batchable advisory to the user, and the emitter cannot see the flush boundary.
  3. Overview of @internal/sql-relational-core

    main

    The @internal/sql-relational-core package provides the foundational primitives for building relational SQL queries in Prisma Next. It serves as a shared layer for different SQL query lanes (DSL, ORM, and Raw SQL).

    Core Responsibilities:

    • Schema Builder: Creates typed table and column builders from contracts.
    • Column Builders: Provides column accessors with operation methods attached based on typeId.
    • Parameter Helpers: Creates parameter placeholders for query building.
    • Operations Registry: Attaches registered operations as methods on column builders.
    • Type Definitions: Defines TypeScript types for column builders, operations, and projections.
    • AST Types: Defines the Abstract Syntax Tree structures for queries.
  4. Overview of Prisma Next Architectural Decision Records (ADRs)

    main

    The Prisma Next prototype architecture is documented through a series of Architectural Decision Records (ADRs). These records are categorized into four main domains:

    1. Core Architecture: Focuses on fundamental design principles like migrations as contract transitions, immutable plans, and the 'Thin Core Fat Targets' approach where target-specific behavior is pushed to adapters.
    2. Contract & Schema: Covers how schemas are authored (PSL-first or TS-first), how types are emitted (TypeScript declarations only), and how deterministic naming and canonicalization rules ensure stable contract hashing.
    3. Query System: Details the unified Plan model, the raw SQL escape hatch, result typing rules, and specific implementation patterns like the state-machine pattern for typed DSL builders.
    4. Runtime & Execution: (Details in subsequent segments) covers how queries are executed and managed at runtime.
  5. Overview of the Drive Judge + Live-Experiment Harness

    main

    The Drive Judge + Live-Experiment Harness is a system designed to provide correctness signals and facilitate A/B testing for skill bundles. It operates through a layered architecture where foundation slices generate instrumented runs, a judge calibrates against those runs to provide correctness scores, and an experiment engine uses those scores to run A/B tests and catch regressions in CI.

    Core Components

    1. Scorecard and Trace Inputs: Provides a two-tier scorecard for diagnostics. It includes an honest not computable verdict when correctness signals are missing and expands the trace vocabulary to include token usage and external correctness feeds.
    2. Golden-Case Harness: A tool that produces natively-instrumented runs on demand using canonical Drive briefs and acceptance sets. This serves as the primary corpus generator for calibrating the judge.
    3. LLM Judge: A calibrated Tier-1 correctness signal. It scores mechanical, requirement, and intent correctness, classifies failure modes (F1–F9 + scope traps), and classifies operator turns. It requires a corpus of $\ge$ 10–20 instrumented runs for calibration.
    4. Run Setup (run-setup): Handles reproducible run production. It isolates a checkout at a pinned base, overlays/materializes a specified skill bundle, spawns the orchestrator, and collects the run's trace and agent-only diff.
    5. Experiment Engine: The A/B testing component. It allows operators to A/B two skill versions, aggregates results, and provides a composite ranker: E[wallclock|CORRECT]/P(CORRECT). It also provides a CI regression gate.
  6. Understand the @prisma/orm-family-sql package structure

    main

    @prisma/orm-family-sql is the core domain for SQL-based databases in Prisma Next. It provides the shared SQL contract surface, schema Intermediate Representation (IR), query lanes, SQL builder, and the SQL runtime used by all SQL targets like Postgres and SQLite.

    How to install

    • Application Developers: Do not install this package directly. Instead, install the specific SQL facade for your database (e.g., @prisma/orm-postgres or @prisma/orm-sqlite). These facades include @prisma/orm-family-sql as an exact-pinned dependency.
    • Extension Authors / Decomposed Installs: If you are building extensions or performing decomposed installs against the SQL family, you may import this package directly.
  7. Use @internal/psl-parser for PSL parsing and symbol resolution

    main

    The @internal/psl-parser package provides a reusable parser for Prisma Schema Language (PSL). It is designed for use in a provider-based authoring model where a provider needs to transform PSL source into a machine-readable format.

    The typical workflow for a PSL provider is:

    1. Call parse(schema) to obtain a Concrete Syntax Tree (CST) (DocumentAst) and a SourceFile.
    2. Call buildSymbolTable(...) using the parsed CST to obtain a scope-aware SymbolTable.
    3. Return the resulting contract and diagnostics to the framework emit pipeline.

    Note: This package handles syntax, structure, and spans. It does not perform semantic normalization, file I/O, or emit contract IR/files (like contract.json).

    ```ts
    // Conceptual workflow for a PSL provider
    const { document, sourceFile, diagnostics: parseDiagnostics } = parse(schema);
    
    const { symbolTable, diagnostics: symbolDiagnostics } = buildSymbolTable({
      document,
      sourceFile,
      scalarTypes,
      pslBlockDescriptors
    });
    
    // Combine diagnostics and return to framework
    // Result<Contract, ContractSourceDiagnostics>
    ```埋
  8. Scope of functional and integration testing for Prisma

    main

    Prisma's testing strategy focuses on exercising public APIs. The primary scope includes:

    Prisma Client

    • Functional Tests: Core query/write methods, batching, transactions, filters, relations, scalars/types, extensions, and observability.
    • Regressions: Self-contained reproductions of GitHub issues.
    • Legacy Integration: Specific error cases and native-type/referential-action scenarios not covered by functional suites.

    Migration and CLI

    • Migrate Package: Command classes like MigrateDev, MigrateDiff, DbPush, MigrateDeploy, and DbPull against fixture projects.
    • CLI Commands: Core commands such as format, validate, generate, status, and init.

    Engines (Query and Schema)

    • Query Engine: GraphQL/JSON-protocol queries and writes, including raw SQL, relation-link matrices, and regression repros.
    • Schema Engine: JSON-RPC surfaces for migrations (applyMigrations, createMigration, diff, schemaPush, evaluateDataLoss) and introspection (introspect).
    • CLI: Black-box testing of the schema-engine CLI via JSON-RPC-over-stdio.

    Supported Databases

    Testing is targeted at Postgres (PGlite) and MongoDB (memory-server). Tests exclusive to unsupported providers (e.g., SQLite, MySQL, MSSQL, CockroachDB, Cloudflare D1) are considered out of scope for the current porting effort.

  9. Understand @internal/mongo-wire responsibilities

    main

    The @internal/mongo-wire package provides the wire-level command and result types used for MongoDB operations within the Prisma ecosystem. It defines the structure of commands sent to the database and the shapes of the results returned by drivers.

    It manages two primary categories of types:

    1. Wire commands: Typed, frozen command classes for write and aggregation operations. These include:
      • InsertOneWireCommand
      • InsertManyWireCommand
      • UpdateOneWireCommand
      • UpdateManyWireCommand
      • DeleteOneWireCommand
      • DeleteManyWireCommand
      • FindOneAndUpdateWireCommand
      • FindOneAndDeleteWireCommand
      • AggregateWireCommand
    2. Result types: The shapes returned by drivers after command execution, such as InsertOneResult, InsertManyResult, UpdateOneResult, UpdateManyResult, DeleteOneResult, and DeleteManyResult.
  10. Prisma Migrate and CLI Engine Capabilities

    main

    The Prisma Migrate engine provides several core capabilities for managing database schemas and migrations. Key operations include:

    • Migration Management: Applying migrations (applyMigrations), creating new migrations (createMigration), and marking migrations as applied or rolled back (markMigrationApplied, markMigrationRolledBack).
    • Database Operations: Creating databases (createDatabase), executing raw SQL scripts (dbExecute), and checking connection validity (ensureConnectionValidity).
    • Schema Synchronization: Pushing schema changes directly to the database (schemaPush) and detecting drift between the schema and the database (devDiagnostic).
    • Diagnostics and Safety: Evaluating potential data loss before schema changes (evaluateDataLoss), diagnosing migration history (diagnoseMigrationHistory), and retrieving the database version (getDatabaseVersion).