prisma-driver-adapter-implementation

โดย prisma

คู่มืออ้างอิงฉบับสมบูรณ์สำหรับการนำไดรเวอร์อะแดปเตอร์ Prisma v7 ไปใช้งาน พร้อมรายละเอียดวงจรชีวิตของธุรกรรม การแมปข้อผิดพลาด และการแปลงชนิดข้อมูล ครอบคลุมอินเทอร์เฟซที่จำเป็นสี่รายการ ได้แก่ SqlDriverAdapter, Transaction, SqlMigrationAwareDriverAdapterFactory และ SqlQueryable พร้อมลายเซ็นเมธอดแบบเต็มและข้อกำหนดวงจรชีวิต Transaction commit() และ rollback() เป็นเพียงฮุควงจรชีวิตเท่านั้น Prisma จะส่ง SQL ผ่าน executeRaw ไม่ใช่ผ่านเมธอดเหล่านี้ รวมถึงการแมปอาร์กิวเมนต์ (string→int/bigint/float, base64→bytes)...

npx skills add https://github.com/prisma/skills --skill prisma-driver-adapter-implementation

Prisma SQL Driver Adapter Implementation

Use this guide with the exact @prisma/driver-adapter-utils version installed by the target Prisma release. Driver adapters are a protocol boundary: type-compatible code can still corrupt values, leak connections, or break transactions.

When to Apply

  • Implementing SqlDriverAdapterFactory, SqlMigrationAwareDriverAdapterFactory, SqlDriverAdapter, or Transaction
  • Adding nested-transaction/savepoint support
  • Mapping driver values, column metadata, bind arguments, or database errors
  • Debugging P2039, transaction leaks, shadow-database failures, or adapter-specific query behavior

Contract snapshot

interface SqlDriverAdapterFactory extends AdapterInfo {
  connect(): Promise<SqlDriverAdapter>
}

interface SqlMigrationAwareDriverAdapterFactory extends SqlDriverAdapterFactory {
  connectToShadowDb(): Promise<SqlDriverAdapter>
}

interface SqlDriverAdapter extends AdapterInfo {
  queryRaw(query: SqlQuery): Promise<SqlResultSet>
  executeRaw(query: SqlQuery): Promise<number>
  executeScript(script: string): Promise<void>
  startTransaction(isolationLevel?: IsolationLevel): Promise<Transaction>
  getConnectionInfo?(): ConnectionInfo
  dispose(): Promise<void>
}

interface Transaction extends AdapterInfo {
  readonly options: { usePhantomQuery: boolean }
  queryRaw(query: SqlQuery): Promise<SqlResultSet>
  executeRaw(query: SqlQuery): Promise<number>
  commit(): Promise<void>
  rollback(): Promise<void>
  createSavepoint?(name: string): Promise<void>
  rollbackToSavepoint?(name: string): Promise<void>
  releaseSavepoint?(name: string): Promise<void>
}

IsolationLevel currently includes READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SNAPSHOT, and SERIALIZABLE; validate what the concrete database supports.

Priority rules

PriorityRuleImpact
CRITICALOne dedicated connection per transactionPrevents interleaving and leaks
CRITICALcommit/rollback are lifecycle cleanup hooksPrevents duplicate COMMIT/ROLLBACK
CRITICALSavepoints live on Transaction, not adapter-global depthMakes nested scopes connection-local
CRITICALPreserve original database error code/messageEnables useful P2039 fallback
HIGHMap arguments and result metadata exactlyPrevents silent value corruption
HIGHShadow databases are isolated and always cleaned upMakes Migrate safe
HIGHDispose only resources the adapter ownsPrevents shutting down caller-owned pools

Query implementation

SqlQuery contains sql, args, and parallel argTypes. Map each argument using both value and ArgType; do not discard type/arity information. Execute in the driver's array/tuple row mode so column order is stable.

class ExampleQueryable {
  readonly provider = 'postgres' as const
  readonly adapterName = '@acme/adapter-example'

  constructor(protected readonly connection: DriverConnection) {}

  async queryRaw(query: SqlQuery): Promise<SqlResultSet> {
    try {
      const result = await this.connection.query({
        text: query.sql,
        values: query.args.map((value, index) =>
          mapArg(value, query.argTypes[index]),
        ),
        rowMode: 'array',
      })

      return {
        columnNames: result.fields.map((field) => field.name),
        columnTypes: result.fields.map(mapColumnType),
        rows: result.rows,
      }
    } catch (error) {
      throwAdapterError(error)
    }
  }

  async executeRaw(query: SqlQuery): Promise<number> {
    try {
      const result = await this.connection.execute(
        query.sql,
        query.args.map((value, index) => mapArg(value, query.argTypes[index])),
      )
      return result.rowsAffected ?? 0
    } catch (error) {
      throwAdapterError(error)
    }
  }
}

Result mapping

Return columnNames, columnTypes, and rows with identical lengths/order. Map driver metadata to ColumnTypeEnum deliberately:

  • signed integer widths to Int32/Int64; preserve 64-bit values without JS number truncation
  • decimal/numeric to Numeric using the representation expected by Prisma
  • binary to Uint8Array/Bytes
  • date-only, time-only, and timestamp to Date, Time, and DateTime
  • UUID, JSON, enum, arrays, and provider-specific unknown values to their explicit types
  • unsupported native types to DriverAdapterError({ kind: 'UnsupportedNativeDataType', type })

Test null, empty arrays, array element types, big integers, decimals, byte arrays, JSON, dates, and user-defined/unknown native types.

Script execution

executeScript must execute a migration script as the provider expects. Prefer the driver's native multi-statement/script facility or a real SQL parser. Naively splitting on ; breaks functions, triggers, quoted strings, and dialect-specific blocks.

Transaction protocol

startTransaction must acquire one dedicated connection, start the database transaction, apply the requested isolation level, and return a Transaction bound to that same connection. If setup fails, release it immediately.

async startTransaction(level?: IsolationLevel): Promise<Transaction> {
  const connection = await this.pool.acquire()
  try {
    const tx = new ExampleTransaction(connection, () => connection.release())
    await tx.executeRaw({ sql: 'BEGIN', args: [], argTypes: [] })
    if (level) {
      await tx.executeRaw({
        sql: `SET TRANSACTION ISOLATION LEVEL ${validateLevel(level)}`,
        args: [],
        argTypes: [],
      })
    }
    return tx
  } catch (error) {
    connection.release(error)
    throwAdapterError(error)
  }
}

Commit and rollback

Prisma coordinates the SQL COMMIT/ROLLBACK through executeRaw. The transaction object's commit() and rollback() methods are lifecycle hooks: detach listeners and release the dedicated connection exactly once. They must not issue a second SQL commit/rollback.

class ExampleTransaction extends ExampleQueryable implements Transaction {
  readonly options = { usePhantomQuery: false }
  #closed = false

  constructor(connection: DriverConnection, private readonly release: () => void) {
    super(connection)
  }

  async commit() { this.finish() }
  async rollback() { this.finish() }

  private finish() {
    if (this.#closed) return
    this.#closed = true
    this.release()
  }

  async createSavepoint(name: string) {
    await this.control(`SAVEPOINT ${safeSavepoint(name)}`)
  }

  async rollbackToSavepoint(name: string) {
    await this.control(`ROLLBACK TO SAVEPOINT ${safeSavepoint(name)}`)
  }

  async releaseSavepoint(name: string) {
    await this.control(`RELEASE SAVEPOINT ${safeSavepoint(name)}`)
  }

  private async control(sql: string) {
    await this.executeRaw({ sql, args: [], argTypes: [] })
  }
}

Implement the optional savepoint methods only where the provider supports them. Validate/quote savepoint identifiers. For providers whose savepoints are intentionally no-ops, document and test that limitation.

Never keep transaction depth on the shared adapter. Parallel transactions make adapter-global depth incorrect; nested state belongs to the returned transaction connection and Prisma's savepoint calls.

Error mapping

Wrap recognized driver failures in DriverAdapterError. Map known conditions to MappedError kinds such as constraint violations, authentication/reachability, missing table/column/database, timeouts, closed transactions, invalid input, value range, and write conflicts.

For database errors, preserve originalCode and originalMessage even when falling back to the provider-specific raw variant:

import {
  DriverAdapterError,
  type Error as DriverAdapterErrorObject,
  type MappedError,
} from '@prisma/driver-adapter-utils'

function convertDriverError(error: DatabaseError): DriverAdapterErrorObject {
  return {
    originalCode: String(error.code),
    originalMessage: error.message,
    ...mapKnownOrRaw(error),
  }
}

function mapKnownOrRaw(error: DatabaseError): MappedError {
  if (error.code === '23505') {
    return { kind: 'UniqueConstraintViolation', constraint: parsedConstraint(error) }
  }
  return {
    kind: 'postgres',
    code: String(error.code ?? 'N/A'),
    severity: error.severity ?? 'N/A',
    message: error.message,
    detail: error.detail,
    column: error.column,
    hint: error.hint,
  }
}

function throwAdapterError(error: unknown): never {
  if (!isDatabaseError(error)) throw error
  throw new DriverAdapterError(convertDriverError(error))
}

Prisma uses preserved original details when an unmapped driver error becomes P2039. Do not replace every unknown exception with a fabricated GenericJs id; rethrow genuinely unexpected non-driver errors so programming bugs remain visible.

Factory, ownership, and shadow database

  • connect() returns a fresh usable adapter connection/pool wrapper.
  • Track whether the factory created the pool. dispose() closes owned pools and only detaches listeners from caller-owned pools unless an explicit option transfers ownership.
  • Implement SqlMigrationAwareDriverAdapterFactory only when connectToShadowDb() can create an isolated shadow database, connect to it, and drop it during disposal/failure cleanup.
  • Never point the shadow adapter at the primary database. Quote generated identifiers and use cryptographically unique names.
  • getConnectionInfo() should accurately report schemaName, maxBindValues when applicable, and supportsRelationJoins.

Verification checklist

  • Typecheck against the exact target @prisma/driver-adapter-utils version
  • queryRaw preserves column order, types, nulls, and precision
  • executeRaw reports affected rows correctly
  • executeScript handles provider-specific multi-statement syntax
  • Concurrent interactive transactions use distinct dedicated connections
  • Success commits and releases once; failure rolls back and releases once
  • Nested transaction tests exercise create/rollback/release savepoint hooks
  • Unsupported isolation levels fail as InvalidIsolationLevel
  • Known constraints map to structured errors
  • Unmapped database errors retain original code/message and surface useful P2039
  • Dispose ownership is tested for internal and external pools
  • Shadow database creation, use, failure cleanup, and disposal are isolated
  • Run Prisma Client integration/E2E tests, not only adapter unit tests

Source references

Skills เพิ่มเติมจาก prisma

prisma-cli-migrate-reset
prisma
prisma migrate reset
official
prisma-cli-validate
prisma
ตรวจสอบความถูกต้องของ Prisma อ้างอิงเมื่อใช้ฟีเจอร์ Prisma นี้
official
prisma-next-extension-upgrade
prisma
Upgrade Prisma Next in your extension. Bumps every `@prisma-next/*` dependency to the requested target (or npm `latest`), runs the per-transition upgrade…
official
adr-review
prisma
ตรวจสอบ ADR หนึ่งรายการขึ้นไปด้วยมุมมองใหม่ (ในฐานะสมาชิกทีมที่ไม่มีบริบทมาก่อน) ระบุปัญหาเชิงเนื้อหาและโครงสร้าง จากนั้นเขียนใหม่ ใช้เมื่อ...
official
prisma-next-upgrade
prisma
Upgrade Prisma Next in your app. Bumps every `@prisma-next/*` dependency from the version pinned in the lockfile to the requested target (or npm `latest`),…
official
prisma-cli
prisma
คู่มืออ้างอิงที่สมบูรณ์สำหรับคำสั่ง ตัวเลือก และขั้นตอนการทำงานของ Prisma CLI ครอบคลุมการตั้งค่า การย้ายฐานข้อมูล และการดำเนินการกับฐานข้อมูล ประกอบด้วยคำสั่งมากกว่า 20 คำสั่งที่จัดลำดับตามความสำคัญ: การตั้งค่า (init), การสร้าง (generate), การพัฒนา (dev), การดำเนินการกับฐานข้อมูล (db pull/push/seed/execute) และการย้ายฐานข้อมูล (migrate dev/deploy/reset/status/diff/resolve) รวมถึงการเปลี่ยนแปลงใน Prisma 7.x: ไฟล์กำหนดค่า prisma.config.ts ใหม่, แฟล็กที่ถูกยกเลิก (--skip-generate, --skip-seed, --schema, --url) และรายละเอียด...
official
prisma-client-api
prisma
เอกสารอ้างอิง API ของ Prisma Client อย่างสมบูรณ์สำหรับการค้นหาโมเดล การดำเนินการ CRUD การกรอง ความสัมพันธ์ และธุรกรรม ครอบคลุมวิธีการค้นหาโมเดล 17 วิธี รวมถึง findUnique, findMany, create, update, delete, upsert และการดำเนินการแบบกลุ่มพร้อมตัวแปรผลลัพธ์ มีตัวเลือกการค้นหาสำหรับปรับแต่งผลลัพธ์: select, include, omit, orderBy, take, skip, cursor และ distinct รวมถึงตัวดำเนินการกรองแบบสเกลาร์และตรรกะ (equals, in, contains, startsWith, lt, gt) พร้อมตัวกรองความสัมพันธ์ (some,...)
official
prisma-compute
prisma
Prisma Compute deployment and hosting guide. Use whenever the user mentions Prisma Compute, `prisma.compute.ts`, `defineComputeConfig`, deploying or hosting a Prisma app, `@prisma/cli app deploy`, `compute:deploy`, `create-prisma --deploy`, `PRISMA_SERVICE_TOKEN`, `auth workspace`, Compute apps/deployments/build logs/domains, `@prisma/cli agent install`, localhost vs `0.0.0.0`, deploy port binding, or framework deploy readiness for Hono, Elysia, Next.js, TanStack Start, Astro, Nuxt, Svelte,...
developmentdevopsofficial