跳到主内容
智客 ZICQ

技能库 智客分类:Agent 工作流 prisma-driver-adapter-implementation

Prisma Driver Adapter Implementation

Prisma ORM 7 SQL 驱动适配器工作所需的引用 。 在执行或修改适配器时使用,添加数据库驱动程序,或触摸 SqlDriverAdapter, 交易, 保存点, 结果映射, 或 DriverAdapterError 行为 。 覆盖当前交易生命周期,可选保存点钩子,原始数据库-错误保存,以及验证.

296590 安装量

官方网址:skills.sh

技能介绍

先看中文介绍;官方 description 原文单独保留,不改写 SKILL.md。

做什么

Prisma ORM 7 SQL 驱动程序适配器工作所需的参考

何时用

执行或修改适配器,添加数据库驱动程序,或触摸 SqlDriverAdapter, 交易, 保存点, 结果映射, 或 DriverAdapterError 行为 。 覆盖当前交易生命周期、可选保存点钩子、原始数据库-错误保存和核查

代理如何加载

按 Agent Skills 渐进披露:启动时只加载 name 与 description(约 100 token);任务匹配后才读入整份 SKILL.md 正文;scripts/、references/、assets/ 仅在需要时再读。 本文件正文结构:Prisma SQL Driver Adapter Implementation、When to Apply、Contract snapshot、Priority rules、Query implementation、Result mapping。

文件分析

文件分析:这是一份仅含 SKILL.md 的指令型技能,代理激活后整份正文进入上下文。

官方 description(原文)

Required reference for Prisma ORM 7 SQL driver adapter work. Use when implementing or modifying adapters, adding database drivers, or touching SqlDriverAdapter, Transaction, savepoint, result mapping, or DriverAdapterError behavior. Covers current transaction lifecycle, optional savepoint hooks, original database-error preservation, and verification.

Prisma SQL Driver Adapter ImplementationWhen to ApplyContract snapshotPriority rulesQuery implementationResult mappingScript executionTransaction protocolCommit and rollbackError mappingFactory, ownership, and shadow databaseVerification checklist

· 许可:MIT

来源分类:skills.sh agent-skill

SKILL.md 与 Agent 调用

官方规范 ↗
name
prisma-driver-adapter-implementation
description
Required reference for Prisma ORM 7 SQL driver adapter work. Use when implementing or modifying adapters, adding database drivers, or touching SqlDriverAdapter, Transaction, savepoint, result mapping, or DriverAdapterError behavior. Covers current transaction lifecycle, optional savepoint hooks, original database-error preservation, and verification.
许可
MIT
  1. 发现技能客户端向 Agent 提供名称与描述目录。
  2. 匹配与调用用户指定或任务匹配后,载入 SKILL.md 指令。
  3. 按需加载按步骤读取参考文档、使用脚本与素材。

具体调用语法与可用工具以目标 Agent 客户端为准。 查看调用机制说明 ↗

安装这个技能

Skills CLI ↗

先选择目标 Agent 和安装范围,保留技能包的附属文件,安装后检查客户端能否发现该技能。

交给 Agent 安装

复制安装指令给支持 Agent Skills 的代理,确认其中的目标目录与客户端匹配。

把 Agent Skill「prisma-driver-adapter-implementation」安装到我的项目:SKILL.md 原文与官方 description 见 https://zicq.com/zh/skills/skl-02ae1c40e6136788-Prisma-%E9%A9%B1%E5%8A%A8%E9%80%82%E5%BA%94%E5%99%A8%E6%89%A7%E8%A1%8C.html
请存为 .cursor/skills/prisma-driver-adapter-implementation/SKILL.md 或 .claude/skills/prisma-driver-adapter-implementation/SKILL.md,frontmatter 的 name 与 description 保持原样,不要改写。

GitHub 完整包 ↗

终端安装 · Skills CLI

需要 Node.js 与 npx。先查看仓库技能列表,确认实际名称。

npx skills add 'https://github.com/prisma/skills' --list

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

CLI 会交互选择目标 Agent,默认安装到项目;用户级安装使用 -g。先通过查看命令核对仓库内容,再用 npx skills list 检查已安装技能。

阅读排版
--- name: prisma-driver-adapter-implementation description: Required reference for Prisma ORM 7 SQL driver adapter work. Use when implementing or modifying adapters, adding database drivers, or touching SqlDriverAdapter, Transaction, savepoint, result mapping, or DriverAdapterError behavior. Covers current transaction lifecycle, optional savepoint hooks, original database-error preservation, and verification. license: MIT metadata: author: prisma version: "7.9.1" --- # 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 ```typescript interface SqlDriverAdapterFactory extends AdapterInfo { connect(): Promise } interface SqlMigrationAwareDriverAdapterFactory extends SqlDriverAdapterFactory { connectToShadowDb(): Promise } interface SqlDriverAdapter extends AdapterInfo { queryRaw(query: SqlQuery): Promise executeRaw(query: SqlQuery): Promise executeScript(script: string): Promise startTransaction(isolationLevel?: IsolationLevel): Promise getConnectionInfo?(): ConnectionInfo dispose(): Promise } interface Transaction extends AdapterInfo { readonly options: { usePhantomQuery: boolean } queryRaw(query: SqlQuery): Promise executeRaw(query: SqlQuery): Promise commit(): Promise rollback(): Promise createSavepoint?(name: string): Promise rollbackToSavepoint?(name: string): Promise releaseSavepoint?(name: string): Promise } ``` `IsolationLevel` currently includes `READ UNCOMMITTED`, `READ COMMITTED`, `REPEATABLE READ`, `SNAPSHOT`, and `SERIALIZABLE`; validate what the concrete database supports. ## Priority rules | Priority | Rule | Impact | |----------|------|--------| | CRITICAL | One dedicated connection per transaction | Prevents interleaving and leaks | | CRITICAL | `commit`/`rollback` are lifecycle cleanup hooks | Prevents duplicate COMMIT/ROLLBACK | | CRITICAL | Savepoints live on `Transaction`, not adapter-global depth | Makes nested scopes connection-local | | CRITICAL | Preserve original database error code/message | Enables useful `P2039` fallback | | HIGH | Map arguments and result metadata exactly | Prevents silent value corruption | | HIGH | Shadow databases are isolated and always cleaned up | Makes Migrate safe | | HIGH | Dispose only resources the adapter owns | Prevents 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. ```typescript class ExampleQueryable { readonly provider = 'postgres' as const readonly adapterName = '@acme/adapter-example' constructor(protected readonly connection: DriverConnection) {} async queryRaw(query: SqlQuery): Promise { 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 { 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. ```typescript async startTransaction(level?: IsolationLevel): Promise { 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. ```typescript 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: ```typescript 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 - [Driver adapter interfaces](https://github.com/prisma/prisma/blob/v7/packages/driver-adapter-utils/src/types.ts) - [PostgreSQL adapter transaction implementation](https://github.com/prisma/prisma/blob/v7/packages/adapter-pg/src/pg.ts) - [PostgreSQL adapter error mapping](https://github.com/prisma/prisma/blob/v7/packages/adapter-pg/src/errors.ts)

相关技能

Agent 工作流

Skill Creator

创造有效技能指南。 当用户想创造出新的技能(或更新现有的技能),以专业知识,工作流程,或工具集成来扩展克洛德的能力时,应该使用这种技能.

Agent 工作流

Clawdhub

使用ClawdHub CLI搜索,安装,更新并发布从taladhub.com的代理技能. 需要获取苍蝇上的新技能时使用,将安装的技能同步到最新版本或特定版本,或者发布 npm-instainddhub CLI 的新/更新的技能文件夹.

Agent 工作流

Agent Team Orchestration

管弦乐团多代理团队,任务设定周期,交接协议,审查工作流程. 使用时间: (1)建立2+特派员队伍,具有不同专业,(2)确定任务路线和生命周期(收录框_ spec_建设_审查_完成),(3)在特派员之间制定交接协议,(4)建立审查和质量关口,(5)管理特派员之间的交流和文物共享.

Agent 工作流

Superpowers

Spec-first,TDD,子代理驱动的软件开发工作流程. 当:(1)构建任何新功能或应用——触发脑暴_计划_子代理执行回路,(2)调试出一个bug或测试失败——触发系统性的根起过程,(3)用户说"让我们构建","帮助我计划","我想添加X",或"这个被打破",(4)完成一个功…