Skip to content

feat: add SurrealDB driver adapter and provider support#29367

Open
Mikefluff wants to merge 9 commits intoprisma:mainfrom
Mikefluff:feat/surrealdb-support
Open

feat: add SurrealDB driver adapter and provider support#29367
Mikefluff wants to merge 9 commits intoprisma:mainfrom
Mikefluff:feat/surrealdb-support

Conversation

@Mikefluff
Copy link

@Mikefluff Mikefluff commented Mar 22, 2026

Summary

  • Add new @prisma/adapter-surrealdb package — full driver adapter with SurrealQL-aware query execution, type conversion, and error mapping
  • Register surrealdb as a first-class provider across the TypeScript codebase: Provider, SchemaProvider, ConnectorType, MappedError, query interpreter, tracing, user-facing errors, raw query mapper, CLI init, migrate, internals
  • Add Docker Compose SurrealDB service for local development and testing
  • Add functional test infrastructure: provider enum, adapter mapping, env vars, client setup

This is the TypeScript side of SurrealDB support. Requires corresponding changes in prisma-engines for PSL parser (surrealdb provider), query compiler (SurrealQL generation via quaint visitor), and schema engine (DEFINE TABLE/FIELD DDL).

New package: @prisma/adapter-surrealdb

  • PrismaSurrealDbAdapterFactory — accepts URL string or Surreal client instance
  • PrismaSurrealDbAdapter — implements SqlDriverAdapter with supportsRelationJoins: false
  • SurrealDbTransactionBEGIN TRANSACTION / COMMIT / CANCEL TRANSACTION (no savepoints)
  • Type inference from JS values (SurrealDB doesn't return column type metadata)
  • Error mapping: socket errors, TLS, auth, unique constraints, table/column not found

Files changed (28 modified + 10 new)

  • packages/adapter-surrealdb/ — new adapter package (10 files)
  • packages/driver-adapter-utils/src/types.ts — Provider + MappedError + officialPrismaAdapters
  • packages/client-engine-runtime/ — schema, tracing, interpreter, user-facing errors
  • packages/client/ — raw query mapper, test infrastructure
  • packages/generator/, packages/internals/, packages/migrate/, packages/cli/
  • docker/docker-compose.yml, .db.env, tsconfig.build.bundle.json

Note: .github/workflows/test-template.yml changes (adding adapter-surrealdb CI job) need to be committed separately with a token that has the workflow scope.

Test plan

  • pnpm test in packages/adapter-surrealdb — 11/11 error mapping tests pass
  • Conversion tests pass (require pnpm build from root for workspace resolution)
  • Full pnpm build from root
  • Functional tests with SurrealDB Docker container
  • E2E test with real SurrealDB instance

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added SurrealDB support: a new adapter with query/execute, transactions, connection handling, and an exported adapter entrypoint.
  • Tests

    • Added unit and functional tests covering conversions, error handling, CRUD and type compatibility for SurrealDB.
  • Chores

    • Added local SurrealDB service and TEST_FUNCTIONAL_SURREALDB_URI env var; updated CLI, schema/provider lists, runtime mappings, package manifest and build/config to enable the provider.

Add full SurrealDB integration to Prisma including:
- New `@prisma/adapter-surrealdb` package with SurrealQL-aware adapter
  (factory, adapter, queryable, transaction classes)
- Type conversion layer (JS value inference → ColumnTypeEnum)
- Error mapping (SurrealDB errors → MappedError kinds)
- Provider registration across the entire TypeScript codebase:
  Provider type, SchemaProvider, ConnectorType, MappedError,
  query interpreter, tracing, user-facing errors, raw query mapper,
  CLI init, migrate, internals, test infrastructure
- Docker Compose SurrealDB service
- Functional test infrastructure (providers, env vars, client setup)

Note: .github/workflows/test-template.yml changes need to be committed
separately with a token that has the `workflow` scope.

This is the TypeScript side of SurrealDB support. Requires corresponding
changes in prisma-engines for PSL parser, query compiler (SurrealQL
generation), and schema engine (DEFINE TABLE/FIELD DDL).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@CLAassistant
Copy link

CLAassistant commented Mar 22, 2026

CLA assistant check
All committers have signed the CLA.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 22, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Adds a new SurrealDB adapter package with runtime adapter/factory, conversion and error-mapping utilities, tests, Docker and env entries for functional tests, and registers surrealdb across CLI, runtime types, generator, migrate, and test infra. All changes are additive.

Changes

Cohort / File(s) Summary
SurrealDB Adapter Core
packages/adapter-surrealdb/src/surrealdb.ts, packages/adapter-surrealdb/src/index.ts
New SqlDriverAdapterFactory and SqlDriverAdapter for SurrealDB: connection parsing, connect/sign-in/use, queryRaw/executeRaw, transactions, executeScript, getConnectionInfo, and disposal semantics.
Conversion & Error Mapping
packages/adapter-surrealdb/src/conversion.ts, packages/adapter-surrealdb/src/errors.ts
Added value/argument conversion helpers (inferColumnType, objectToRow, mapArg) and driver error normalization (convertDriverError) with mapping for socket/TLS and SurrealDB message patterns.
Adapter Package & Build
packages/adapter-surrealdb/package.json, packages/adapter-surrealdb/helpers/build.ts, packages/adapter-surrealdb/tsconfig*.json
New package manifest, build helper entrypoint, and TS build/config files; exports, scripts, dependencies and path alias added for build and local resolution.
Adapter Tests
packages/adapter-surrealdb/src/__tests__/*
Vitest suites for conversion, error mapping, and basic adapter construction/shape.
Runtime & Types Registration
packages/driver-adapter-utils/src/types.ts, packages/client-engine-runtime/src/schema.ts, packages/generator/src/configuration.ts
Registered surrealdb in Provider/Connector unions, added MappedError variant, and included adapter in official adapters list.
Runtime Integration
packages/client-engine-runtime/src/*, packages/client/src/runtime/core/raw-query/rawQueryArgsMapper.ts
Integrated surrealdb into chunk-size logic, OTEL mapping, user-facing error handling, and raw-query argument serialization.
Functional Test Integration
packages/client/tests/functional/_utils/*, packages/client/tests/functional/surrealdb-*/**
Added Providers.SURREALDB / AdapterProviders.JS_SURREALDB, wiring test env variable TEST_FUNCTIONAL_SURREALDB_URI, adapter instantiation, test matrices, and multiple SurrealDB functional test suites (CRUD, types).
CLI & Credentials
packages/cli/src/Init.ts, packages/internals/src/convertCredentials.ts
CLI datasource providers allowlist, default port/URL generation, and protocol↔connector mapping extended to support surrealdb.
Migrate / Test Helpers
packages/migrate/src/__tests__/*, packages/migrate/src/utils/ensureDatabaseExists.ts
Test-matrix typing adjusted, surrealdbOnly matrix added, conditional test skip env support, and SurrealDB pretty-provider mapping added.
Docker / Env / TS Path
docker/docker-compose.yml, .db.env, tsconfig.build.bundle.json
Added SurrealDB Docker service (surrealdb:v3.0.4, port 8000, creds root:root, healthcheck), TEST_FUNCTIONAL_SURREALDB_URI env var, and TS path alias for @prisma/adapter-surrealdb.

Possibly related issues

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 54.17% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: add SurrealDB driver adapter and provider support' directly and accurately describes the main changes—adding a new SurrealDB adapter and registering it across the Prisma codebase.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Mikefluff added a commit to Mikefluff/prisma-engines that referenced this pull request Mar 22, 2026
Full SurrealDB integration across the Rust codebase:

**PSL Parser:**
- `Flavour::SurrealDb` variant in datamodel connector
- `SurrealDbDatamodelConnector` implementing `Connector` trait
  (no native types, no FK constraints, `relationMode = "prisma"`)
- Feature flag `surrealdb` in psl-core and psl

**Query Compiler (quaint):**
- `SqlFamily::SurrealDb` variant with all match arms
- `AdapterProvider::SurrealDb` in external connector
- SurrealQL visitor (~540 lines) with key differences from SQL:
  - `$1`, `$2` placeholders (PostgreSQL-style)
  - `DELETE table` without FROM keyword
  - `LIMIT ... START` instead of `LIMIT ... OFFSET`
  - `RETURN` instead of `RETURNING`
  - `string::concat()` instead of `||`
- Query compiler dispatch for SurrealDB
- Wasm build configuration (build.sh, Makefile)

**Schema Engine:**
- `SurrealDbDialect` implementing `SqlDialect`
- `SurrealDbConnector` implementing `SqlConnector` (external adapter only)
- `SurrealDbRenderer` — DDL generation:
  `DEFINE TABLE SCHEMAFULL`, `DEFINE FIELD ON TABLE TYPE`,
  `DEFINE INDEX ON TABLE FIELDS UNIQUE`, `REMOVE TABLE/FIELD/INDEX`
- `SurrealDbSchemaCalculatorFlavour`, `SurrealDbSchemaDifferFlavour`,
  `SurrealDbDestructiveChangeCheckerFlavour`
- `SurrealDbIntrospectionFlavour`
- Migrations table using SurrealQL (`DEFINE TABLE _prisma_migrations`)

**Verification:**
- `cargo check` passes for all 6 affected crates
- 7/7 quaint SurrealQL visitor tests pass

Companion PR: prisma/prisma#29367

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 12

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docker/docker-compose.yml`:
- Around line 245-256: The SurrealDB service uses the floating image tag
"surrealdb/surrealdb:latest" which can cause non-reproducible builds; update the
surrealdb service's image field to a specific versioned tag (e.g., replace
:latest with a known semver or SHA) so the image is pinned, then document or add
a comment with the chosen version and rationale; look for the surrealdb service
block and change the image string accordingly.

In `@packages/adapter-surrealdb/package.json`:
- Around line 37-40: Update the "surrealdb" dependency in package.json from
"^1.0.0" to "^2.0.0" (i.e., change the value for the surrealdb entry under
"dependencies"); before committing, review SurrealDB 2.0.x changelog for
breaking changes and run adapter tests/compile against the new surrealdb API to
fix any incompatibilities in code that references SurrealDB client
methods/classes.

In `@packages/adapter-surrealdb/src/conversion.ts`:
- Around line 126-132: The code currently returns new Date(arg) and uses
atob(...) without validating input; update the conversion logic around arg and
argType.scalarType so that for 'datetime' you construct the Date, check
isNaN(date.getTime()) and throw a descriptive Error (or return a controlled
failure) on invalid dates, and for 'bytes' wrap the atob call in a try/catch (or
pre-validate with a base64 regex) and throw a descriptive Error if decoding
fails before calling Uint8Array.from; reference the existing arg and
argType.scalarType checks in conversion.ts and ensure the thrown errors include
the invalid input context.
- Around line 8-11: Add a short JSDoc/comment to the inferColumnType function
documenting the null/undefined inference strategy: state that inferColumnType
returns ColumnTypeEnum.Text for null or undefined as a conservative fallback,
explain that this is ambiguous when first-row values are null and may lead to
incorrect column typing, and note recommended mitigations (e.g., scanning
additional rows before inferring, providing an explicit schema override, or
treating nulls as unknown). Reference the inferColumnType function and the use
of ColumnTypeEnum.Text so reviewers can find and understand the rationale and
suggested safeguards.

In `@packages/adapter-surrealdb/src/errors.ts`:
- Around line 125-127: The isSurrealDbError type guard is too broad (it matches
any Error); tighten it to detect SurrealDbError-specific shape by checking a
discriminant or unique property (e.g., check (error as SurrealDbError).code !==
undefined or (error as SurrealDbError).name === 'SurrealDbError' or another
property that exists on SurrealDbError), or if the guard is intentionally meant
as a catch‑all, add a clear JSDoc comment stating that intent; update the
isSurrealDbError function and/or the SurrealDbError type so the guard reliably
distinguishes SurrealDbError from generic Error.

In `@packages/adapter-surrealdb/src/index.ts`:
- Line 1: Add an inline documentation comment for the new public export so the
package API is documented: above the export statement that re-exports
PrismaSurrealDbAdapterFactory as PrismaSurrealDb, add a concise doc comment
describing what PrismaSurrealDb represents (that it is a factory/adapter for
SurrealDB integration with Prisma), any important usage notes or return/behavior
expectations, and mark it as public API; ensure the comment appears immediately
above the export of PrismaSurrealDb so tooling and generated docs pick it up.

In `@packages/adapter-surrealdb/src/surrealdb.ts`:
- Line 1: Remove the file-wide "/* eslint-disable
`@typescript-eslint/require-await` */" and instead apply the rule only where
necessary: either make the methods comply (remove unnecessary async or add
awaited calls) or place an inline disable comment directly above the specific
async methods that legitimately do not await (e.g., the dispose method and any
other functions named with async in the file). Replace the top-of-file disable
with per-method comments like "/* eslint-disable-next-line
`@typescript-eslint/require-await` */" immediately before the affected function
declarations (or refactor the functions to remove async) to limit the scope.
- Around line 24-27: Replace the exported type alias PrismaSurrealDbOptions with
an exported interface of the same name that defines the same optional properties
(namespace?: string, database?: string); update any references (imports/uses) to
PrismaSurrealDbOptions if needed to ensure the symbol remains exported and
compatible. Ensure the interface is exported (export interface
PrismaSurrealDbOptions { namespace?: string; database?: string; }) and run type
checks to confirm no changes are required where the type alias was previously
used.
- Around line 201-221: The connect() method can leak the Surreal client if
client.connect() or client.use() throws; update connect() so that when
this.#externalClient is not provided you create the Surreal instance and then
wrap the connect/use calls in a try/catch/finally (or try with a cleanup on
error) to ensure client.close() is called on any failure before rethrowing the
error, but keep the current behavior of not closing externally provided clients
when this.#externalClient is set and return PrismaSurrealDbAdapter as before.
- Around line 147-161: The startTransaction method ignores the _isolationLevel
parameter; update startTransaction to respect or at least surface non-default
isolation requests: detect if _isolationLevel is provided, map it to SurrealDB's
supported isolation syntax or set it on the TransactionOptions object
(referencing startTransaction, TransactionOptions, and SurrealDbTransaction),
and include it when issuing the BEGIN TRANSACTION (or pass it into the
SurrealDbTransaction constructor); if SurrealDB does not support configurable
isolation levels, log a clear warning when _isolationLevel is non-default and/or
document the limitation instead of silently ignoring the parameter.
- Around line 86-101: The performIO method builds bindings with numeric keys
which SurrealDB does not accept; change it to produce a bindings object with the
exact named parameter keys used in the SQL (e.g., "$userId", "$email") before
calling this.client.query. Use the SqlQuery data (inspect argTypes or add param
name metadata to SqlQuery if missing) and map each mappedArgs[i] to a binding
key that matches the placeholder in sql (prefix with "$" or use the
argTypes[i].name), update the bindings construction in performIO (and keep using
mapArg for value conversion), then call this.client.query(sql, bindings);
preserve the existing error handling via this.onError.

In `@packages/migrate/src/__tests__/__helpers__/conditionalTests.ts`:
- Line 20: The test matrix currently enables surrealdb unconditionally (the
allProviders/conditionalTests entry "surrealdb: true"), which makes CI brittle;
update the provider matrix so surrealdb is only enabled when an env flag is set
(e.g., process.env.RUN_SURREALDB or similar) or add a skip guard check in the
conditionalTests helper so surrealdb is skipped by default; locate the
allProviders/conditionalTests symbol and replace the unconditional "surrealdb:
true" with a conditional expression that reads an environment variable (or adds
surrealdb to the existing skip list) so CI runs remain controllable.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 8d016443-5499-4a0b-a5aa-15340c8efb17

📥 Commits

Reviewing files that changed from the base of the PR and between 33667c3 and 179debe.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (27)
  • .db.env
  • docker/docker-compose.yml
  • packages/adapter-surrealdb/helpers/build.ts
  • packages/adapter-surrealdb/package.json
  • packages/adapter-surrealdb/src/__tests__/conversion.test.ts
  • packages/adapter-surrealdb/src/__tests__/errors.test.ts
  • packages/adapter-surrealdb/src/conversion.ts
  • packages/adapter-surrealdb/src/errors.ts
  • packages/adapter-surrealdb/src/index.ts
  • packages/adapter-surrealdb/src/surrealdb.ts
  • packages/adapter-surrealdb/tsconfig.build.json
  • packages/adapter-surrealdb/tsconfig.json
  • packages/cli/src/Init.ts
  • packages/client-engine-runtime/src/interpreter/query-interpreter.ts
  • packages/client-engine-runtime/src/schema.ts
  • packages/client-engine-runtime/src/tracing.ts
  • packages/client-engine-runtime/src/user-facing-error.ts
  • packages/client/src/runtime/core/raw-query/rawQueryArgsMapper.ts
  • packages/client/tests/functional/_utils/providers.ts
  • packages/client/tests/functional/_utils/setupTestSuiteClient.ts
  • packages/client/tests/functional/_utils/setupTestSuiteEnv.ts
  • packages/driver-adapter-utils/src/types.ts
  • packages/generator/src/configuration.ts
  • packages/internals/src/convertCredentials.ts
  • packages/migrate/src/__tests__/__helpers__/conditionalTests.ts
  • packages/migrate/src/utils/ensureDatabaseExists.ts
  • tsconfig.build.bundle.json

- Pin SurrealDB Docker image to v3.0.4 (was :latest)
- Update surrealdb npm dependency to ^2.0.0 (was ^1.0.0)
- Add input validation for datetime/bytes in conversion.ts
- Add null type inference comment in inferColumnType
- Simplify isSurrealDbError guard + add intent comment
- Add doc comment for PrismaSurrealDb export
- Replace file-wide eslint-disable with per-method comments
- Use interface instead of type for PrismaSurrealDbOptions
- Add try/catch cleanup in connect() to prevent client leak
- Add isolation level limitation comment in startTransaction
- Add TEST_SKIP_SURREALDB guard in conditionalTests

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

♻️ Duplicate comments (1)
packages/migrate/src/__tests__/__helpers__/conditionalTests.ts (1)

13-22: ⚠️ Potential issue | 🟠 Major

Keep surrealdb out of allProviders until the engine side lands.

noDriverAdapters reuses allProviders, so Line 20 opts every default migrate matrix into SurrealDB immediately. The PR objectives still call out pending prisma-engines parser/query-compiler/schema-engine work, so this starts exercising an unsupported provider before that dependency is merged.

♻️ One way to keep SurrealDB opt-in for now
 export const allProviders = {
   mysql: true,
   postgres: true,
   sqlite: true,
   mongodb: true,
   cockroachdb: true,
   sqlserver: true,
-  surrealdb: true,
   d1: true,
-} satisfies Record<SupportedProviders, true>
+} satisfies Matrix['providers']
+
+export const surrealdbOnly = {
+  providers: { surrealdb: true },
+} satisfies Matrix
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/migrate/src/__tests__/__helpers__/conditionalTests.ts` around lines
13 - 22, allProviders currently includes "surrealdb" which causes tests (via
noDriverAdapters reusing allProviders) to opt into SurrealDB prematurely; remove
the surrealdb entry from the allProviders object (or set it to false) so
SurrealDB is not enabled by default, and if you need opt-in test coverage add a
separate optInProviders list or explicit flag used by tests to include
"surrealdb" until the prisma-engines work lands; update references to
allProviders/noDriverAdapters to use the new opt-in mechanism if necessary.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/adapter-surrealdb/src/conversion.ts`:
- Around line 109-110: The conversion logic in conversion.ts currently
JSON.stringify()s all objects except Uint8Array, which corrupts ArrayBuffer
values (they become "{}"); update the check around the variable value so
ArrayBuffer and ArrayBufferViews are excluded from JSON.stringify — detect them
via value instanceof ArrayBuffer and ArrayBuffer.isView(value) (or equivalent)
and let them pass through/be handled as binary (consistent with inferColumnType
classifying Bytes) instead of being serialized to JSON.

In `@packages/adapter-surrealdb/src/errors.ts`:
- Around line 14-43: Add a documentation comment for the exported function
convertDriverError describing its purpose as the adapter's error-translation
boundary, inputs and possible output shapes, and behavior for different error
kinds (socket, TLS, SurrealDB, generic Error, and rethrowing unknown values);
place the comment immediately above the convertDriverError declaration and
reference the returned DriverAdapterErrorObject and the helper predicates
mapSocketError, isSocketError, isTlsError, isSurrealDbError, and
mapSurrealDbError so callers understand which error classes are converted and
what callers can expect.

In `@packages/adapter-surrealdb/src/surrealdb.ts`:
- Around line 22-25: Add JSDoc-style documentation comments for the exported
types: PrismaSurrealDbOptions (describe purpose and optional namespace/database
properties), PrismaSurrealDbAdapter (describe adapter role and key
methods/contract), and PrismaSurrealDbAdapterFactory (describe factory signature
and return value). Update the module’s other exported items in the 138-186 range
in the same way—provide one-line description of each export, expected
inputs/outputs and any important behaviour or invariants. Keep comments concise,
use standard /** ... */ format, and ensure the documented symbols
(PrismaSurrealDbOptions, PrismaSurrealDbAdapter, PrismaSurrealDbAdapterFactory)
match the exact exported names.
- Around line 204-225: connect() currently passes this.#url directly into new
Surreal().connect(), which ignores embedded credentials; parse the datasource
URL (this.#url) to extract username and password and supply them to the Surreal
client (either via connect() options or by calling client.signin()) before
opening the connection; update the branch that creates new Surreal() in
connect() to parse credentials, call client.connect(parsedUrlWithoutCredentials)
and then authenticate with the extracted credentials, ensuring the
external-client branch that returns new
PrismaSurrealDbAdapter(this.#externalClient, ...) remains unchanged.
- Around line 139-143: The constructor currently declares TypeScript private
parameters for options and release; refactor them to native private fields by
adding class-level declarations `#options?: PrismaSurrealDbOptions` and
`#release?: () => Promise<void>` and remove `private readonly` from the
constructor parameter list, then assign the incoming arguments to these fields
inside the constructor (e.g., this.#options = options; this.#release =
release;). Update usages in methods `getConnectionInfo()` and `dispose()` to
reference `this.#options` and `this.#release` respectively. Ensure imports/types
remain unchanged and preserve existing behavior and types.

---

Duplicate comments:
In `@packages/migrate/src/__tests__/__helpers__/conditionalTests.ts`:
- Around line 13-22: allProviders currently includes "surrealdb" which causes
tests (via noDriverAdapters reusing allProviders) to opt into SurrealDB
prematurely; remove the surrealdb entry from the allProviders object (or set it
to false) so SurrealDB is not enabled by default, and if you need opt-in test
coverage add a separate optInProviders list or explicit flag used by tests to
include "surrealdb" until the prisma-engines work lands; update references to
allProviders/noDriverAdapters to use the new opt-in mechanism if necessary.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: e5ec9eb3-f59a-4674-b188-93492dd84914

📥 Commits

Reviewing files that changed from the base of the PR and between 179debe and ae9e0e9.

📒 Files selected for processing (7)
  • docker/docker-compose.yml
  • packages/adapter-surrealdb/package.json
  • packages/adapter-surrealdb/src/conversion.ts
  • packages/adapter-surrealdb/src/errors.ts
  • packages/adapter-surrealdb/src/index.ts
  • packages/adapter-surrealdb/src/surrealdb.ts
  • packages/migrate/src/__tests__/__helpers__/conditionalTests.ts

Mikefluff and others added 2 commits March 22, 2026 00:01
SurrealDB v3 requires parameter names to start with a letter.
The query compiler generates $p1, $p2, so bindings must use
matching keys: { p1: value, p2: value }.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Fix ArrayBuffer corruption in normalizeValue (was JSON.stringify'd to "{}")
- Add doc comments for convertDriverError, PrismaSurrealDbOptions,
  PrismaSurrealDbAdapter, PrismaSurrealDbAdapterFactory
- Refactor PrismaSurrealDbAdapter to use native private fields (#options, #release)
- Parse credentials from datasource URL before connecting (extract user:pass,
  call client.signin(), connect without credentials in URL)
- Remove surrealdb from allProviders (opt-in until prisma-engines lands),
  add surrealdbOnly matrix helper

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/adapter-surrealdb/src/conversion.ts`:
- Around line 128-130: The list-handling branch in mapArg incorrectly passes the
same argType (with arity 'list') to recursive calls; change the recursive call
inside the Array.isArray(arg) && argType.arity === 'list' branch to call mapArg
for each element with argType modified to arity: 'scalar' (e.g., create a
shallow copy of argType with arity set to 'scalar') so nested arrays are not
reinterpreted as lists and inner elements get scalar conversions (reference:
mapArg and argType).

In `@packages/adapter-surrealdb/src/surrealdb.ts`:
- Around line 221-240: connectUrl can remain with the surrealdb:// scheme when
no credentials are present, causing WebSocket connection failures; ensure the
scheme is normalized to ws:// or wss:// regardless of credentials by converting
the original this.#url (and the parsed URL) to the appropriate ws(s) scheme.
Update the parsing block around parseable/parsed/connectUrl so that after
constructing parseable (and after any credential removal) you always set
connectUrl to the parsed.toString() with the protocol replaced: use wss:// if
the original this.#url starts with surrealdbs:// (or preserve a trailing "s" if
present), otherwise use ws://; keep username/password decoding and removal logic
intact (symbols: this.#url, parseable, parsed, username, password, connectUrl).

In `@packages/migrate/src/__tests__/__helpers__/conditionalTests.ts`:
- Around line 24-26: Add a JSDoc/doc comment above the exported surrealdbOnly
constant describing that it is a test matrix helper which restricts providers to
only the SurrealDB provider, note that it satisfies the Matrix type, and include
a brief one-line usage example or intent (e.g., "Use in tests to run only
against the SurrealDB provider"). Keep the comment consistent with other
exported helper docs in the repo (short description, mention it's exported, and
any expected shape if helpful).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 3ea3da0d-87d1-4345-b935-7077f3296051

📥 Commits

Reviewing files that changed from the base of the PR and between ae9e0e9 and b37ca19.

📒 Files selected for processing (4)
  • packages/adapter-surrealdb/src/conversion.ts
  • packages/adapter-surrealdb/src/errors.ts
  • packages/adapter-surrealdb/src/surrealdb.ts
  • packages/migrate/src/__tests__/__helpers__/conditionalTests.ts

Mikefluff and others added 3 commits March 22, 2026 00:15
- Fix mapArg list recursion: pass arity 'scalar' to inner elements
- Always normalize surrealdb:// to ws:// (not only when credentials present)
- Add doc comment for surrealdbOnly matrix helper

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Functional tests (packages/client/tests/functional/):
- surrealdb-crud/: 27 tests covering full CRUD lifecycle
  - Create single, create with relations
  - FindMany, findUnique, findFirst, with include/select
  - Update, updateMany, upsert (existing + new)
  - Delete, deleteMany
  - Count, aggregate (avg/min/max)
  - Interactive transactions
  - Filtering: contains, startsWith, in, NOT
  - Ordering: asc, desc
  - Pagination: take + skip
  - Nullable fields: create with null, filter by null

- surrealdb-types/: 10 tests covering type system
  - All scalar types: Boolean, Int, BigInt, Float, String, DateTime, Json
  - Special characters / injection prevention (quotes, backslash, unicode)
  - Unique constraints (enforced + findUnique by unique field)
  - Compound IDs (@@id([tenantId, itemId]))
  - Boundary values (max Int, empty JSON)

Adapter unit tests (packages/adapter-surrealdb/):
- surrealdb.test.ts: 5 tests covering factory construction, provider
  name, adapter name, URL parsing, options interface

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Standalone e2e test project matching the pattern of existing adapter e2e
tests (adapter-d1-itx-error, etc.):

- package.json with @prisma/adapter-surrealdb + surrealdb SDK deps
- prisma/schema.prisma with surrealdb provider, User + Post models
- prisma.config.ts with surrealdb:// datasource URL
- _steps.ts: install → generate → db push → jest
- tests/main.ts: 16 e2e tests covering:
  - Create (single + nested relations)
  - Read (findMany, findUnique, findFirst, include, select, ordering, pagination)
  - Update (single + upsert existing + upsert new)
  - Aggregate (count)
  - Transactions (interactive)
  - Delete (single + deleteMany)
  - Full cleanup in afterAll

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/adapter-surrealdb/src/__tests__/surrealdb.test.ts`:
- Line 13: Remove the non-informative inline comments that restate test intent
(e.g. the comment string "// Type-level test: ensure the interface shape is
correct" and the similar comment around line 30) from the test file so the tests
read self‑documenting; if there is important context or rationale to preserve,
move that explanation into a brief higher‑level comment above the relevant
describe/test block explaining the "why", otherwise delete the inline comments
from the test cases (look for the exact comment text mentioned to locate them).
- Line 31: Tests mix CommonJS require with ESM imports; update each test that
does "const { PrismaSurrealDb } = require('../index')" (and the three other
similar require usages) to use dynamic ESM import via "const { PrismaSurrealDb }
= await import('../index')" and mark those test callbacks async so you can await
the import; ensure all tests use the same pattern as the existing async import
in the file to keep module loading consistent.

In `@packages/client/tests/functional/surrealdb-crud/tests.ts`:
- Around line 9-12: Remove the redundant banner-style section comments (e.g.,
the "CREATE" banner and other repeated "========" blocks) throughout the tests
file; delete those comment blocks that only restate structure (the ones around
CRUD sections) so the test file contains only meaningful inline comments
explaining why, not what; ensure no test code or descriptions are removed and
run tests to confirm formatting changes didn't affect behavior.
- Around line 13-312: Many tests share and mutate global state (e.g., records
created via prisma.user.create in tests like "create a single user", "create a
user with a related post", and mutate/update/delete tests), causing cascade
failures; make each test independent by either (a) creating its own unique test
data (use a unique email suffix or timestamp in each test when calling
prisma.user.create / prisma.user.upsert) and cleaning it up at the end of that
same test (call prisma.user.delete or prisma.user.deleteMany for that email), or
(b) add a setup/teardown hook (beforeEach/afterEach) that resets relevant tables
with prisma.user.deleteMany({ where: { email: { contains: 'test-suffix' } } })
or truncates the test dataset so tests like "update a single user", "delete a
single user", "findUnique by email", "aggregate - avg, min, max", and
transaction tests operate on isolated records; apply the same pattern for
related entities (posts) created via posts.create in the "create a user with a
related post" test.

In `@packages/client/tests/functional/surrealdb-types/tests.ts`:
- Around line 9-11: Remove the redundant banner comment blocks (the repeated "//
============================================================" and the section
title comments like "// ALL SCALAR TYPES") that appear before test groups (e.g.,
the block at the top and the similar blocks around lines with the text blocks
for 59-61, 83-85, 108-110, 137-139, 173-175); leave the existing test case names
and descriptions intact (they already describe the tests), so simply delete
those banner comment lines to reduce noise and keep tests lean.
- Around line 99-106: The test "unique field findUnique" is order-dependent
because it assumes a record inserted by "unique constraint enforced"; make it
independent by creating or upserting the required record inside the test itself
before calling prisma.uniqueTest.findUnique. Specifically, add a setup step in
the test that uses prisma.uniqueTest.create or prisma.uniqueTest.upsert (with
where: { code: 'ALPHA' } and data: { code: 'ALPHA', value: 1 }) to ensure the
record exists, then run the existing findUnique/assertions; this guarantees the
test no longer depends on prior tests.
- Around line 92-97: The test currently uses a generic rejects.toThrow() for
prisma.uniqueTest.create; change it to assert the Prisma error name and code
instead. Replace the expect(...).rejects.toThrow() with an assertion like await
expect(prisma.uniqueTest.create(...)).rejects.toMatchObject({ name:
'PrismaClientKnownRequestError', code: '<EXPECTED_CODE>' }) (use the actual
Prisma error code for the unique constraint, e.g. 'P2002'), so the test checks
both result.name and result.code rather than any thrown error.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: f68a320c-b731-4e76-857a-6c576b5c9423

📥 Commits

Reviewing files that changed from the base of the PR and between fa3432e and a858bd7.

📒 Files selected for processing (7)
  • packages/adapter-surrealdb/src/__tests__/surrealdb.test.ts
  • packages/client/tests/functional/surrealdb-crud/_matrix.ts
  • packages/client/tests/functional/surrealdb-crud/prisma/_schema.ts
  • packages/client/tests/functional/surrealdb-crud/tests.ts
  • packages/client/tests/functional/surrealdb-types/_matrix.ts
  • packages/client/tests/functional/surrealdb-types/prisma/_schema.ts
  • packages/client/tests/functional/surrealdb-types/tests.ts


describe('PrismaSurrealDbOptions interface', () => {
test('accepts namespace and database', () => {
// Type-level test: ensure the interface shape is correct
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Remove non-informative inline comments.

These comments restate what the tests already say and don’t provide decision/context-level “why”.

As per coding guidelines "Avoid adding useless code comments that do not add new information. Only write inline comments explaining Why (context, background, GitHub issues, decisions), not What or How."

Also applies to: 30-30

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/adapter-surrealdb/src/__tests__/surrealdb.test.ts` at line 13,
Remove the non-informative inline comments that restate test intent (e.g. the
comment string "// Type-level test: ensure the interface shape is correct" and
the similar comment around line 30) from the test file so the tests read
self‑documenting; if there is important context or rationale to preserve, move
that explanation into a brief higher‑level comment above the relevant
describe/test block explaining the "why", otherwise delete the inline comments
from the test cases (look for the exact comment text mentioned to locate them).

Mikefluff and others added 2 commits March 22, 2026 00:39
- Remove inline comments restating test intent (coding guidelines)
- Replace require() with await import() for consistent ESM loading
- Remove all banner section comments (========)
- Make every test independent with beforeEach cleanup (deleteMany)
- Each test creates its own data with unique emails
- Fix unique constraint assertion: use result.name + result.code
  instead of generic toThrow() (per functional test guidelines)
- Make findUnique test independent by creating its own record

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add JSDoc comments to all functions, classes, and type guards:
- conversion.ts: isIsoDateTime, isIsoDate, isUuid, normalizeValue
- errors.ts: mapSurrealDbError, extractName, isSurrealDbError,
  mapSocketError, isSocketError, isTlsError
- surrealdb.ts: SurrealDbQueryable, SurrealDbTransaction

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants