Skip to content

Native PostGIS Support for Prisma - #29365

Closed
lh0x00 wants to merge 6 commits into
prisma:mainfrom
lh0x00:feature/support-postgis-features
Closed

lh0x00 wants to merge 6 commits into
prisma:mainfrom
lh0x00:feature/support-postgis-features

Conversation

@lh0x00

@lh0x00 lh0x00 commented Mar 20, 2026 •

Copy link
Copy Markdown

Native PostGIS Support for Prisma

Summary

This PR adds native PostGIS support to Prisma. You get geometry types in your schema. You get type-safe filters and ordering. No more raw SQL for spatial queries.

Dependencies:

What's New

Define geometry fields in your schema:

model Location {
  id       Int      @id @default(autoincrement())
  name     String
  position Geometry(Point, 4326)?
}

Query with native filters:

// Within 1km radius
const nearby = await prisma.location.findMany({
  where: { position: { near: { point: [13.4, 52.5], maxDistance: 1000 } } }
})

// Sort by distance
const sorted = await prisma.location.findMany({
  orderBy: { position: { distanceFrom: { point: [13.4, 52.5], direction: 'asc' } } },
  take: 10
})

Create with type safety:

await prisma.location.create({
  data: {
    name: 'Berlin',
    position: { type: 'Point', coordinates: [13.4, 52.5], srid: 4326 }
  }
})
// Returns GeoJSON: { type: 'Point', coordinates: [13.4, 52.5], srid: 4326 }

What You Get

Geometry types: Point, LineString, Polygon, Multi*, GeometryCollection

Filters: near (radius), within (containment), intersects (overlap)
Ordering: distanceFrom (sort by distance)

Plus: CRUD, introspection, migrations, null handling, custom SRIDs, $queryRaw support

Quick Examples

Restaurant finder - 5km radius, sorted by distance:

const nearby = await prisma.restaurant.findMany({
  where: { location: { near: { point: [-73.98, 40.74], maxDistance: 5000 } } },
  orderBy: { location: { distanceFrom: { point: [-73.98, 40.74], direction: 'asc' } } },
  take: 10
})

Delivery zones - Check if address is in service area:

const zones = await prisma.zone.findMany({
  where: {
    boundary: {
      intersects: {
        geometry: { type: 'Point', coordinates: [2.35, 48.85] }
      }
    }
  }
})
const canDeliver = zones.length > 0

Activity tracking - Find routes passing through a park:

const activities = await prisma.activity.findMany({
  where: {
    route: {
      intersects: {
        geometry: {
          type: 'Polygon',
          coordinates: [[[-122.42, 37.77], [-122.42, 37.78], [-122.41, 37.78], [-122.41, 37.77], [-122.42, 37.77]]]
        }
      }
    }
  }
})

TypeScript types:

import { Prisma } from '@prisma/client'

const point: Prisma.InputGeometry = {
  type: 'Point',
  coordinates: [13.4, 52.5],
  srid: 4326
}

const location = await prisma.location.findUnique({ where: { id: 1 } })
// location.position is Prisma.Geometry | null

Testing

147 tests covering the full stack—all passing.

38 TypeScript e2e, 15 Rust SQL snapshots, 8 Rust graph builders, 86 adapter unit tests. Covers CRUD, filters, ordering, edge cases, null handling, polygon holes, custom SRIDs, and sub-meter precision.

pnpm --filter @prisma/client test:functional:code --adapter js_pg postgis
cd prisma-engines && cargo test geometry
> @prisma/[email protected] test:functional:code [~]/prisma/packages/client
> dotenv -e ../../.db.env -- tsx helpers/functional-test/run-tests.ts --no-types --adapter js_pg_postgis postgis

Prisma schema loaded from tests/functional/postgis/.generated/postgis.test (provider=postgresql, provider=postgresql)/prisma/schema.prisma.
Prisma schema loaded from tests/functional/postgis/.generated/postgis.test (provider=postgresql, provider=postgresql)/prisma/schema.prisma.
 PASS  tests/functional/postgis/test.ts (53.012 s)
  postgis.test (provider=postgresql, provider=postgresql)
    ✓ basic Point geometry CRUD (560 ms)
    ✓ LineString geometry operations (29 ms)
    ✓ Polygon geometry operations (21 ms)
    ✓ SRID handling (4326, 3857) (26 ms)
    ✓ $queryRaw with PostGIS functions (ST_GeomFromText, ST_AsEWKB) (23 ms)
    ✓ null geometry handling (19 ms)
    ✓ round-trip serialization (36 ms)
    ✓ $queryRaw returns geometry objects (17 ms)
    ✓ geometry filter: near (ST_DWithin) (245 ms)
    ✓ geometry filter: within polygon (ST_Within) (31 ms)
    ✓ geometry filter: intersects with GeoJSON (ST_Intersects) (29 ms)
    ✓ geometry orderBy: distanceFrom (ST_Distance) (56 ms)
    ✓ geometry filter with custom SRID (28 ms)
    ✓ combined geometry filters and orderBy (39 ms)
    ✓ NOT filter: exclude points near location (31 ms)
    ✓ OR filter: multiple spatial conditions (31 ms)
    ✓ Polygon with hole (interior ring) (21 ms)
    ✓ within filter: point in polygon with hole (41 ms)
    ✓ LineString with many points (18 ms)
    ✓ intersects: LineString crosses polygon (51 ms)
    ✓ near filter: no results when too far (29 ms)
    ✓ within filter: empty results when outside (18 ms)
    ✓ orderBy: distance desc (farthest first) (30 ms)
    ✓ filter + orderBy + limit (28 ms)
    ✓ update geometry: change point location (31 ms)
    ✓ update geometry to null (34 ms)
    ✓ findFirst with geometry filter (43 ms)
    ✓ count with geometry filter (54 ms)
    ✓ delete with geometry filter (25 ms)
    ✓ Polygon boundary: exactly on edge (12 ms)
    ✓ near filter with very small distance (16 ms)
    ✓ geometry filter combined with scalar filter (15 ms)
    ✓ orderBy with null geometries (14 ms)
    ✓ multiple geometries on same model (17 ms)
    ✓ projected coordinates: SRID 3857 distance calculation (18 ms)
    ✓ select specific fields with geometry filter (18 ms)
    ✓ Polygon intersects with another polygon (26 ms)
    ✓ extremely close points: sub-meter precision (35 ms)

Test Suites: 1 passed, 1 total
Tests:       38 passed, 38 total
Snapshots:   0 total
Time:        54.03 s

---

> @prisma/[email protected] test [~]/prisma/packages/adapter-pg
> vitest run spatial-optimizer


 RUN  v4.0.18 [~]/prisma/packages/adapter-pg

 ✓ src/__tests__/spatial-optimizer.test.ts (6 tests) 3ms
   ✓ withSpatialOptimization (6)
     ✓ detects PostgreSQL 16 and applies optimization 2ms
     ✓ skips optimization for PostgreSQL 17+ 0ms
     ✓ skips optimization for PostgreSQL 15 and earlier 0ms
     ✓ caches version detection for performance 0ms
     ✓ handles version detection errors gracefully 0ms
     ✓ handles malformed version strings gracefully 0ms

 Test Files  1 passed (1)
      Tests  6 passed (6)
   Start at  13:46:04
   Duration  97ms (transform 22ms, setup 0ms, import 33ms, tests 3ms, environment 0ms)

How It Works

Schema parser understands Geometry(Point, 4326). Generator creates type-safe APIs. Runtime serializes GeoJSON. SQL builder compiles filters to PostGIS functions.

SRID 4326 gets geography casting for accurate meters. Projected SRIDs use planar geometry.

Generated SQL:

-- Radius search (meters)
ST_DWithin("position"::geography, ST_SetSRID(ST_MakePoint(13.4, 52.5), 4326)::geography, 1000)

-- Containment
ST_Within("position", ST_GeomFromText('POLYGON((0 0, 0 10, 10 10, 10 0, 0 0))', 4326))

-- Distance sorting
ORDER BY ST_Distance(CAST("position" AS geography), CAST(ST_SetSRID(ST_MakePoint(0, 0), 4326) AS geography))

Documentation

See prisma/web#7685 for the full documentation PR.

Added: Complete geometry field guide with setup, filters, ordering, TypeScript types, real-world examples, and performance tips.

Migration from Unsupported

// Before
model Location {
  position Unsupported("geometry(Point, 4326)")?
}

// After
model Location {
  position Geometry(Point, 4326)?
}

Run prisma generate. Done. Same GeoJSON format, but now you get native filters instead of raw SQL.

Breaking Changes

None. New feature, fully backward compatible.

PostgreSQL 16 Performance Helper

Added withSpatialOptimization() helper in @prisma/adapter-pg that auto-detects PG16 and optimizes spatial queries (fixing 40-50x slowdown caused by query planner bug). Works transparently with all geometry filters. Details in docs. Thanks to @BrenoRev for the real-world testing and original workaround.

~

If you find this useful, a reaction or follow at github.com/lh0x00 would mean a lot—it genuinely motivates me to keep building cool stuff like this.

Thanks for reviewing! Feel free to drop ideas or edge cases in the comments.

@CLAassistant

CLAassistant commented Mar 20, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@coderabbitai

coderabbitai Bot commented Mar 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 22c72bb9-256f-45e8-8148-4080860f06f0

📥 Commits

Reviewing files that changed from the base of the PR and between 25f9ba6 and a4acec8.

📒 Files selected for processing (1)
  • AGENTS.md

Summary by CodeRabbit

  • New Features

    • PostGIS geometry support: Point, LineString, Polygon and geometry arrays
    • Spatial query operators and geometry field operations
    • Automatic PostGIS extension setup and geometry type discovery
    • Spatial query optimization for PostgreSQL 16
    • Geometry types exposed in client/runtime typings and JSON protocol
  • Tests

    • Expanded functional and unit tests covering geometry serialization, parsing, performance, and PostGIS integration
  • Chores / Docs

    • Docker and env updates for PostGIS testing; docs and test guidance updated

Walkthrough

Adds a paragraph to AGENTS.md clarifying the sequencing and intended use of setupTestSuite database hooks (beforeDbPushCallback, afterForceResetCallback, alterStatementCallback) and how TEST_REUSE_DATABASE=true affects beforeDbPushCallback.

Changes

Docs & Formatting

Cohort / File(s) Summary
AGENTS DB hook paragraph
AGENTS.md
Added a paragraph documenting the sequencing/scope of setupTestSuite DB hook callbacks (beforeDbPushCallback, afterForceResetCallback, alterStatementCallback) and how TEST_REUSE_DATABASE=true affects beforeDbPushCallback.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 29.73% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and accurately summarizes the main feature added: native PostGIS support for Prisma. It is concise, specific, and directly reflects the primary change in the changeset.
Description check ✅ Passed The description comprehensively relates to the changeset, covering objectives, examples, test results, implementation details, migration guidance, and dependencies. It provides meaningful context about the PostGIS support feature.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

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

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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.

@lh0x00 lh0x00 mentioned this pull request Mar 20, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 20

🤖 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-pg/src/__tests__/test-utils.ts`:
- Around line 7-15: The isGeometry type guard currently checks for the presence
of 'coordinates' but not its shape; update the isGeometry function to also
validate that (value as { coordinates: unknown }).coordinates is an array (e.g.,
using Array.isArray) so the guard more accurately narrows to Geometry; keep the
existing checks for object, non-null, 'type' and that type is string, and add
the Array.isArray check for 'coordinates' to tighten validation in tests.

In `@packages/adapter-pg/src/__tests__/wkb-performance.test.ts`:
- Around line 144-157: The test "memory usage stable after many parse
operations" is flaky because V8 GC is non-deterministic; update the test around
parseWKB/createLineStringWKB/MEMORY_ITERATIONS to explicitly invoke global.gc()
(guarded with if (typeof global.gc === 'function')) before measuring heapBefore
and again before measuring heapAfter, and update test docs to require running
node with --expose-gc; alternatively if you don't want GC control, remove the
deltaPerOp assertion and keep the loop as a benchmark or increase the tolerance
threshold.
- Around line 176-180: The test uses .length on UTF-8 strings (parserSize,
serializerSize, totalSourceChars) but compares to a byte target (targetBytes);
change the measurement to bytes by computing Buffer.byteLength(...) for the
parser and serializer sources (or read files as buffers) so parserSize and
serializerSize represent byte counts and totalSourceChars (rename if desired) is
compared correctly to targetBytes; update references to parserSize,
serializerSize, totalSourceChars and targetBytes accordingly.
- Around line 183-198: The test 'reports compiled bundle size when built'
currently returns early when dist files (distIndexJs/distIndexMjs) are missing
which makes the test silently pass; change the behavior to explicitly skip or
fail the test instead: detect existence of distIndexJs and distIndexMjs and call
test.skip with a clear message if missing (or throw/assert with a descriptive
message) so CI shows a skipped/failed test rather than a silent pass, and keep
the subsequent checks on cjsSize and esmSize (variables distIndexJs,
distIndexMjs, cjsSize, esmSize) unchanged.

In `@packages/adapter-pg/src/__tests__/wkb-serializer.test.ts`:
- Around line 7-35: Add a test that verifies round-trip
serialization/deserialization of a 3D Point (with Z) using the existing
serializeWKB and parseWKB helpers so the WKB serializer handles [number, number,
number] coordinates; create a new test similar to the existing Point tests that
constructs a point with coordinates like [1.5, 2.5, 10.0] typed as [number,
number, number], calls serializeWKB(point) and parseWKB(wkb), and asserts parsed
equals the original point to cover Z coordinate handling in the Point type.

In `@packages/adapter-pg/src/conversion.ts`:
- Around line 442-466: Add a brief inline comment in
tryWkbFromUtf8JsonGeometryBytes explaining the endian byte check: note that
bytes[0] being 0 or 1 indicates little/big-endian WKB, whereas valid UTF‑8 JSON
always starts with '{' (0x7B) or '[' (0x5B) and thus cannot begin with
0x00/0x01; this clarifies why the condition `endian === 0 || endian === 1` can
safely distinguish WKB from JSON before attempting text decoding and JSON.parse.
Include the comment immediately above or next to the `const endian = bytes[0]` /
`if (endian === 0 || endian === 1)` lines and keep it short and focused.
- Around line 520-522: In mapArg where it special-cases argType.scalarType ===
'geometry' and returns a string as-is, add a short inline comment stating that
the string is expected to be WKB hex (already-serialized), matching the behavior
in registerGeometryParser which does Buffer.from(wkb, 'hex'); also add/adjust a
unit test to cover this passthrough case (string WKB hex) to prevent
regressions. Ensure the comment references the WKB hex expectation and that
GeoJSON text is not accepted here.

In `@packages/adapter-pg/src/pg.ts`:
- Around line 263-286: The query in async `#queryGeometryOIDs` is restricted to
the 'public' namespace so it misses PostGIS types installed in other schemas;
update the SQL to either remove the typnamespace filter so it selects
typname/oid from pg_type across all schemas, or (preferable) join
pg_extension/pg_namespace to locate the extension namespace for 'postgis' and
filter typnamespace = pg_extension.extnamespace for that schema; keep the rest
of the logic intact (mapGeometryTypeName, registerGeometryType,
registerGeometryParser, and GEOMETRY_OID_CACHE behavior) so OIDs are registered
regardless of where PostGIS types live.

In `@packages/adapter-pg/src/wkb-primitives.ts`:
- Around line 107-109: The WKBParseError is being constructed with ringCount as
the wkbType argument; change the error construction to pass the actual WKB type
(the variable/field that holds the current geometry type, e.g., wkbType or
this.#wkbType) as the wkbType parameter and leave ringCount as the value
argument so the call becomes WKBParseError('Invalid ring count', ringCount,
<actualWkbType>, this.#offset) (match the constructor signature used elsewhere
such as the similar fix near line 92).
- Around line 91-93: The check that throws new WKBParseError('Invalid coordinate
count', count, this.#offset) passes the coordinate count where wkbType should
go; update the throw in the coordinate-count validation inside the WKB parsing
routine to call WKBParseError with the actual WKB type (e.g. this.#wkbType or
the parser's wkbType field) and the offset (this.#offset), and include the
invalid count in the error message or as additional context (or alternatively
throw a more specific error type) so the error contains correct wkbType, offset,
and the invalid count.

In `@packages/adapter-pg/src/wkb-serializer.ts`:
- Around line 6-19: Create a small helper to extract the geometry type string
and use it in both getWKBType and calculateGeometrySize to remove duplicated
casting logic; e.g., add a function like extractGeometryType(geometry: Geometry
| unknown): string that returns (geometry as { type: string }).type (or a safe
fallback) and replace the inline casts in the error branches of getWKBType and
calculateGeometrySize to call extractGeometryType for the error message.

In `@packages/client-engine-runtime/src/json-protocol.ts`:
- Line 12: The GeometryTaggedValue type uses a too-broad value: object; update
it to a concrete geometry type by either importing the Geometry type from
driver-adapter-utils and replacing value: object with value: Geometry, or define
an inline shape such as value: { type: string; coordinates: unknown; srid?:
number } to match the expected geometry structure; update the export type
GeometryTaggedValue accordingly and add the necessary import for
driver-adapter-utils if you choose that option.

In `@packages/client-generator-js/src/utils/common.ts`:
- Around line 22-31: The needsNamespace function currently hardcodes scalar type
checks instead of reusing the needNamespace lookup object; update needsNamespace
to consult the existing needNamespace map for scalar fields (e.g., use
needNamespace[field.type] or Object.prototype.hasOwnProperty.call(needNamespace,
field.type)) after confirming field.kind === 'scalar', so you remove the
duplicated list and rely on the single source of truth defined in needNamespace;
adjust any truthiness logic accordingly to preserve the original boolean result.

In `@packages/client-generator-ts/src/TSClient/Input.ts`:
- Around line 54-55: Replace the incorrect input type for geometry scalars:
inside the mapping that handles t.location === 'scalar' and
t.type.startsWith('geometry(') (in
packages/client-generator-ts/src/TSClient/Input.ts), change
namedInputType('runtime.Geometry') to namedInputType('runtime.InputGeometry') so
input fields use runtime.InputGeometry consistent with JSOutputTypeToInputType
and tests.

In `@packages/client-generator-ts/src/typedSql/mapTypes.ts`:
- Line 13: The geometry mapping currently uses the strict runtime type for both
directions; change the input-side mapping to use the more permissive
InputGeometry type. Replace the input mapping that references
ts.namedType('$runtime.Geometry') with ts.namedType('$runtime.InputGeometry')
(keep ts.namedType('$runtime.Geometry') for outputs), mirroring the existing
decimal/decimalIn pattern so input parameters accept readonly/loose coordinate
shapes; update the const/places that define or reference geometry (the geometry
mapping and any input mapping spots around lines where geometry is used)
accordingly.

In `@packages/client/src/runtime/core/jsonProtocol/serializeJsonQuery.ts`:
- Around line 268-277: The current isGeometry type guard is too permissive and
misses GeometryCollection; update the isGeometry(value) function to (1) tighten
the check by validating value.type is one of the GeoJSON geometry type strings
(e.g.,
"Point","LineString","Polygon","MultiPoint","MultiLineString","MultiPolygon","GeometryCollection")
and (2) accept either a coordinates array for non-GeometryCollection types or a
geometries array for "GeometryCollection", preserving optional srid handling;
also apply the same tightened guard where a duplicate geometry-detection check
exists later in the file (the second isGeometry-like conditional) so both
serialization branches correctly detect GeoJSON geometries.

In `@packages/client/src/runtime/core/types/exported/Geometry.ts`:
- Line 1: The file name Geometry.ts violates the project's kebab-case rule;
rename the file to geometry.ts and update all imports that reference Geometry.ts
to point to geometry.ts (ensure you update any relative import paths that
re-export the types Geometry, InputGeometry, LineString, Point, Polygon from
'@prisma/driver-adapter-utils'); also verify this directory doesn't
intentionally use PascalCase and adjust any tooling or index re-exports to the
new filename to avoid case-sensitive filesystem breaks.

In `@packages/client/tests/functional/postgis/test.ts`:
- Around line 21-25: The CREATE DATABASE SQL is built via string interpolation
using dbName (in the client.query call that issues `CREATE DATABASE ...`), which
risks injection; change this to safely quote or parameterize the identifier:
either use a proper identifier-quoting helper (e.g., pg-format's
format.ident(dbName)) when composing the CREATE DATABASE statement or
validate/sanitize dbName against a safe pattern (e.g., /^[A-Za-z0-9_]+$/) and
then quote it, and replace the interpolated `CREATE DATABASE
"${dbName.replace(/"/g, '""')}"` with one of these safe approaches so
client.query is called with a properly escaped identifier (or a validated name)
instead of raw string interpolation.

In `@packages/driver-adapter-utils/src/Geometry.ts`:
- Around line 37-46: The docstring for InputGeometry is inconsistent with its
type: it claims the type "allows undefined and read-only properties" but
InputGeometry's fields (type, coordinates, srid) do not include undefined;
update the code to make them consistent by either 1) adjusting the type
InputGeometry to allow undefined (e.g., make fields possibly undefined where
intended) or 2) simpler—update the docstring to remove mention of "undefined"
and state that only read-only properties are allowed; reference the
InputGeometry type to apply the change.

In `@packages/json-protocol/src/index.ts`:
- Line 60: The TaggedValue declarations are currently declared as type aliases
but should be converted to interfaces; replace each type alias
(GeometryTaggedValue, DateTaggedValue, DecimalTaggedValue, BytesTaggedValue,
BigIntTaggedValue, FieldRefTaggedValue, EnumTaggedValue, JsonTaggedValue,
RawTaggedValue, PlaceholderTaggedValue) with an exported interface that
preserves the same shape (e.g., { $type: 'X'; value: ... }) so consumers see
identical runtime typings; update any references/imports if necessary to use the
new interface names and ensure the file compiles with the same exported symbols.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2943b085-60bc-4726-ad5c-249014be2a02

📥 Commits

Reviewing files that changed from the base of the PR and between 33667c3 and 45a0b7b.

📒 Files selected for processing (59)
  • .db.env
  • .envrc
  • .prettierignore
  • AGENTS.md
  • docker/README.md
  • docker/postgis-test.yml
  • packages/adapter-pg/src/__tests__/conversion.test.ts
  • packages/adapter-pg/src/__tests__/test-utils.ts
  • packages/adapter-pg/src/__tests__/wkb-parser.test.ts
  • packages/adapter-pg/src/__tests__/wkb-performance.test.ts
  • packages/adapter-pg/src/__tests__/wkb-serializer.test.ts
  • packages/adapter-pg/src/conversion.ts
  • packages/adapter-pg/src/errors.ts
  • packages/adapter-pg/src/pg.ts
  • packages/adapter-pg/src/wkb-parser.ts
  • packages/adapter-pg/src/wkb-primitives.ts
  • packages/adapter-pg/src/wkb-serializer.ts
  • packages/cli/src/utils/simpleDebounce.ts
  • packages/client-engine-runtime/src/interpreter/data-mapper.ts
  • packages/client-engine-runtime/src/interpreter/serialize-sql.test.ts
  • packages/client-engine-runtime/src/interpreter/serialize-sql.ts
  • packages/client-engine-runtime/src/json-protocol.test.ts
  • packages/client-engine-runtime/src/json-protocol.ts
  • packages/client-engine-runtime/src/query-plan.ts
  • packages/client-generator-js/src/TSClient/Input.ts
  • packages/client-generator-js/src/TSClient/Output.ts
  • packages/client-generator-js/src/TSClient/SelectIncludeOmit.ts
  • packages/client-generator-js/src/TSClient/common.ts
  • packages/client-generator-js/src/typedSql/mapTypes.ts
  • packages/client-generator-js/src/utils/common.ts
  • packages/client-generator-ts/src/TSClient/Input.ts
  • packages/client-generator-ts/src/TSClient/Output.ts
  • packages/client-generator-ts/src/TSClient/SelectIncludeOmit.ts
  • packages/client-generator-ts/src/TSClient/common.ts
  • packages/client-generator-ts/src/typedSql/mapTypes.ts
  • packages/client-generator-ts/src/utils/common.ts
  • packages/client/scripts/default-index.d.ts
  • packages/client/src/__tests__/buffer-small.test.ts
  • packages/client/src/__tests__/deserializeRawResults.test.ts
  • packages/client/src/__tests__/integration/__helpers__/sanitizeEvents.ts
  • packages/client/src/runtime/core/jsonProtocol/serializeJsonQuery.ts
  • packages/client/src/runtime/core/types/exported/Geometry.ts
  • packages/client/src/runtime/core/types/exported/index.ts
  • packages/client/src/runtime/utils/deserializeRawResults.ts
  • packages/client/tests/functional/_utils/getTestSuitePlan.ts
  • packages/client/tests/functional/_utils/providers.ts
  • packages/client/tests/functional/_utils/setupTestSuiteClient.ts
  • packages/client/tests/functional/_utils/setupTestSuiteEnv.ts
  • packages/client/tests/functional/_utils/setupTestSuiteMatrix.ts
  • packages/client/tests/functional/_utils/types.ts
  • packages/client/tests/functional/postgis/_matrix.ts
  • packages/client/tests/functional/postgis/prisma/_schema.ts
  • packages/client/tests/functional/postgis/test.ts
  • packages/driver-adapter-utils/src/Geometry.ts
  • packages/driver-adapter-utils/src/const.ts
  • packages/driver-adapter-utils/src/index.ts
  • packages/driver-adapter-utils/src/types.ts
  • packages/generator/src/typedSql.ts
  • packages/json-protocol/src/index.ts
💤 Files with no reviewable changes (3)
  • packages/cli/src/utils/simpleDebounce.ts
  • packages/client/scripts/default-index.d.ts
  • packages/client/src/tests/integration/helpers/sanitizeEvents.ts

Comment thread packages/json-protocol/src/index.ts Resolved
@lh0x00

lh0x00 commented Mar 21, 2026

Copy link
Copy Markdown
Author

It's already available for data generation, with unit tests and related features. I'm working on making it support native queries!

@lh0x00 lh0x00 changed the title [WIP] add PostGIS support for Prisma Native PostGIS Support for Prisma Mar 21, 2026
@lh0x00

lh0x00 commented Mar 21, 2026

Copy link
Copy Markdown
Author

Hi @dulmandakh @jacek-prisma @sorenbs, please review my PR, thank you.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (3)
packages/adapter-pg/src/__tests__/wkb-performance.test.ts (2)

169-180: 🧹 Nitpick | 🔵 Trivial

Source size check uses character count, not byte count.

readFileSync(..., 'utf-8').length returns character count. For ASCII source files this matches byte count, but the variable name targetBytes suggests byte comparison. Consider using Buffer.byteLength() or reading without encoding for consistency.

♻️ Optional fix for consistency
       if (existsSync(parserPath)) {
-        parserSize = readFileSync(parserPath, 'utf-8').length
+        parserSize = readFileSync(parserPath).length
       }
       if (existsSync(serializerPath)) {
-        serializerSize = readFileSync(serializerPath, 'utf-8').length
+        serializerSize = readFileSync(serializerPath).length
       }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/adapter-pg/src/__tests__/wkb-performance.test.ts` around lines 169 -
180, The test currently measures source size using character counts (parserSize
and serializerSize computed via readFileSync(..., 'utf-8').length) but compares
against targetBytes; change the measurement to byte length for consistency by
using Buffer.byteLength(fileContents, 'utf8') or reading the files as raw
buffers and using .length for parserPath and serializerPath, then compute
totalSourceBytes (instead of totalSourceChars) and assert that totalSourceBytes
is lessThan targetBytes while keeping the same expect checks for non-zero sizes;
update the variable names (parserSize, serializerSize, totalSourceChars) to
reflect bytes to avoid confusion.

183-198: 🧹 Nitpick | 🔵 Trivial

Test silently passes when dist files are missing.

When dist/index.js or dist/index.mjs don't exist, the test returns early without any assertions, falsely passing in CI. Consider skipping explicitly.

♻️ Proposed fix using test context
-    test('reports compiled bundle size when built', () => {
+    test('reports compiled bundle size when built', ({ skip }) => {
       const __dirname = dirname(fileURLToPath(import.meta.url))
       const pkgRoot = join(__dirname, '..', '..')
       const distIndexJs = join(pkgRoot, 'dist', 'index.js')
       const distIndexMjs = join(pkgRoot, 'dist', 'index.mjs')

       if (!existsSync(distIndexJs) || !existsSync(distIndexMjs)) {
+        skip()
         return
       }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/adapter-pg/src/__tests__/wkb-performance.test.ts` around lines 183 -
198, The test "reports compiled bundle size when built" currently returns early
if dist/index.js or dist/index.mjs are missing, causing a silent pass; replace
the early return with an explicit assertion or skip so CI fails clearly: remove
the if (!existsSync(distIndexJs) || !existsSync(distIndexMjs)) { return } block
and instead assert the files exist (e.g.,
expect(existsSync(distIndexJs)).toBe(true) and
expect(existsSync(distIndexMjs)).toBe(true)) or call test.skip with a clear
message when missing, keeping the rest of the size checks (cjsSize/esmSize)
unchanged; locate the logic inside the test named 'reports compiled bundle size
when built' and update there.
packages/client/src/runtime/core/jsonProtocol/serializeJsonQuery.ts (1)

358-360: ⚠️ Potential issue | 🟠 Major

Don't auto-tag every GeoJSON-shaped object as geometry.

serializeArgumentsValue() has no field-type check here, so a Json field containing { type: 'Point', coordinates: [...] } will now be rewritten into a { $type: 'Geometry' } protocol marker. That is a breaking change for existing GeoJSON-in-JSON payloads; this needs to be gated on a geometry-typed argument path, not value shape alone.

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

In `@packages/client/src/runtime/core/jsonProtocol/serializeJsonQuery.ts` around
lines 358 - 360, serializeArgumentsValue currently converts any object matching
GeoJSON shape (isGeometry) into a { $type: 'Geometry' } marker regardless of the
argument's declared field type, which wrongly rewrites Json-typed fields; change
the logic so the isGeometry branch only runs when the argument path/type
indicates a geometry-typed field (e.g., check the argument metadata or fieldType
for 'Geometry' or use the existing argumentPath/schema lookup used elsewhere in
serializeArgumentsValue) and leave objects in Json fields untouched;
specifically, update serializeArgumentsValue to consult the argument's declared
type before applying isGeometry and only inject the $type marker for true
geometry-typed arguments.
🤖 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-pg/src/pg.ts`:
- Around line 209-210: Transactions can bypass PostGIS OID initialization
because only PrismaPgAdapter.queryRaw() calls `#initializeGeometryTypes`(), while
PgTransaction inherits PgQueryable.queryRaw() unchanged; ensure geometry
OIDs/parsers are initialized before any transaction runs queries by invoking
`#initializeGeometryTypes`() from the shared query entrypoint or at transaction
creation. Concretely, either move the call to this.#initializeGeometryTypes()
into the common query path used by both PrismaPgAdapter and PgTransaction (e.g.,
PgQueryable.queryRaw), or call this.#initializeGeometryTypes() when
constructing/returning a PgTransaction (the factory that returns PgTransaction
instances), and keep references to PrismaPgAdapter, PgQueryable.queryRaw,
PgTransaction, `#initializeGeometryTypes`, and fieldToColumnType to locate and
update the code.
- Around line 263-290: The current `#queryGeometryOIDs` caches a permanent
initialized state regardless of success or failure, preventing retries; change
it so you only set GEOMETRY_OID_CACHE.set(cacheKey, true) when you actually
register at least one OID (i.e., after the for-loop if result.rows yielded any
entries), and remove the catch-path cache write (do not set false on exception);
on errors either leave the cache untouched or explicitly delete any existing
entry so discovery can be retried later; keep registerGeometryType and
registerGeometryParser calls unchanged and use result.rows length or a local
counter to decide whether to cache success.

In `@packages/client-generator-js/src/utils/common.ts`:
- Around line 3-5: Add a short documentation comment above the exported function
isGeometryScalarTypeRef explaining that it returns true for DMMF OutputTypeRef
objects that represent Prisma's native geometry scalar types (it checks location
=== 'scalar' and that type starts with "geometry("), describe the expected shape
of the ref parameter (Pick<DMMF.OutputTypeRef, 'location' | 'type'>), and note
that the "geometry(" prefix indicates a native geometry scalar in the DMMF to
make call sites clearer.

In `@packages/client/src/runtime/core/jsonProtocol/serializeJsonQuery.ts`:
- Around line 292-297: GeometryCollection is only half-wired: update the
geometry-input detection and unwrapping so GeometryCollection values are treated
like other geometries. In serializeJsonQuery/isGeometryInput (the branch
currently checking v.type === 'GeometryCollection' and
Array.isArray(v.geometries')), ensure you accept GeometryCollection as a
Geometry input and/or normalize its shape so unwrapGeometryBindingArg can
process it; alternatively, extend unwrapGeometryBindingArg to handle type ===
'GeometryCollection' by reading the geometries array (instead of coordinates)
and returning the same WKB-ready shape that other
GEOMETRY_TYPES_WITH_COORDINATES produce. Reference isGeometry(),
isGeometryInput(), unwrapGeometryBindingArg(), and the 'GeometryCollection' type
when making the change.

In `@packages/client/tests/functional/postgis/test.ts`:
- Around line 5-6: The tests use Prisma.InputGeometry and Prisma.Geometry but
only import PrismaClient; update the import to also bring in the Prisma
namespace as a type (e.g., import type { PrismaClient, Prisma as PrismaNamespace
} from './generated/prisma/client') and then add a declaration for the runtime
identifier expected by the tests (e.g., declare const Prisma: PrismaNamespace;)
so references to Prisma.InputGeometry and Prisma.Geometry resolve; change the
import that currently only references PrismaClient and add the new declaration
for PrismaNamespace/Prisma.

---

Duplicate comments:
In `@packages/adapter-pg/src/__tests__/wkb-performance.test.ts`:
- Around line 169-180: The test currently measures source size using character
counts (parserSize and serializerSize computed via readFileSync(...,
'utf-8').length) but compares against targetBytes; change the measurement to
byte length for consistency by using Buffer.byteLength(fileContents, 'utf8') or
reading the files as raw buffers and using .length for parserPath and
serializerPath, then compute totalSourceBytes (instead of totalSourceChars) and
assert that totalSourceBytes is lessThan targetBytes while keeping the same
expect checks for non-zero sizes; update the variable names (parserSize,
serializerSize, totalSourceChars) to reflect bytes to avoid confusion.
- Around line 183-198: The test "reports compiled bundle size when built"
currently returns early if dist/index.js or dist/index.mjs are missing, causing
a silent pass; replace the early return with an explicit assertion or skip so CI
fails clearly: remove the if (!existsSync(distIndexJs) ||
!existsSync(distIndexMjs)) { return } block and instead assert the files exist
(e.g., expect(existsSync(distIndexJs)).toBe(true) and
expect(existsSync(distIndexMjs)).toBe(true)) or call test.skip with a clear
message when missing, keeping the rest of the size checks (cjsSize/esmSize)
unchanged; locate the logic inside the test named 'reports compiled bundle size
when built' and update there.

In `@packages/client/src/runtime/core/jsonProtocol/serializeJsonQuery.ts`:
- Around line 358-360: serializeArgumentsValue currently converts any object
matching GeoJSON shape (isGeometry) into a { $type: 'Geometry' } marker
regardless of the argument's declared field type, which wrongly rewrites
Json-typed fields; change the logic so the isGeometry branch only runs when the
argument path/type indicates a geometry-typed field (e.g., check the argument
metadata or fieldType for 'Geometry' or use the existing argumentPath/schema
lookup used elsewhere in serializeArgumentsValue) and leave objects in Json
fields untouched; specifically, update serializeArgumentsValue to consult the
argument's declared type before applying isGeometry and only inject the $type
marker for true geometry-typed arguments.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 6ed7de16-b101-4fed-a54b-f4d9bec60575

📥 Commits

Reviewing files that changed from the base of the PR and between 45a0b7b and cdd08bc.

📒 Files selected for processing (13)
  • packages/adapter-pg/src/__tests__/wkb-performance.test.ts
  • packages/adapter-pg/src/pg.ts
  • packages/adapter-pg/src/wkb-primitives.ts
  • packages/adapter-pg/src/wkb-serializer.ts
  • packages/client-engine-runtime/src/json-protocol.ts
  • packages/client-generator-js/src/TSClient/Input.ts
  • packages/client-generator-js/src/typedSql/mapTypes.ts
  • packages/client-generator-js/src/utils/common.ts
  • packages/client-generator-ts/src/TSClient/Input.ts
  • packages/client-generator-ts/src/typedSql/mapTypes.ts
  • packages/client/src/runtime/core/jsonProtocol/serializeJsonQuery.ts
  • packages/client/tests/functional/postgis/_matrix.ts
  • packages/client/tests/functional/postgis/test.ts

Comment thread packages/adapter-pg/src/pg.ts Resolved
Comment thread packages/adapter-pg/src/pg.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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-pg/src/__tests__/spatial-optimizer.test.ts`:
- Line 10: The test mock for the Prisma transaction currently passes the outer
mockPrisma into the transaction callback which can hide bugs; change the
$transaction mock (the vi.fn defined for $transaction) to invoke the callback
with a distinct transactional client object (e.g., mockTransactionPrisma)
instead of mockPrisma, and update both occurrences where $transaction is
defined/used (the vi.fn and the other instance around the same test) so the
transaction callback receives and tests against the separate transactional
client to ensure production code uses the provided transaction client rather
than the outer client.

In `@packages/adapter-pg/src/conversion.ts`:
- Around line 439-467: The code in tryWkbFromUtf8JsonGeometryBytes currently
sniffs arbitrary Bytes payloads by decoding and JSON-parsing them; instead only
convert when the bytes unmistakably represent the JSON-protocol geometry
wrapper. Change tryWkbFromUtf8JsonGeometryBytes (and the similar branches noted)
to first check for the specific JSON-protocol geometry discriminator token
expected by unwrapGeometryBindingArg (i.e. the exact wrapper/key string that
identifies a geometry binding) in the raw UTF-8 bytes/text before calling
JSON.parse or unwrapGeometryBindingArg, and bail out (return null) for any
payload that does not contain that discriminator so ordinary Bytes are left
unchanged.
- Around line 409-417: The type-guard isGeometryInput currently rejects
GeometryCollection because it checks only for a coordinates property; update
isGeometryInput to accept either a coordinates array OR a geometries array so
GeometryCollections pass validation, extend the Geometry union/type to include
GeometryCollection (shape with type: "GeometryCollection" and geometries:
Geometry[]), and implement full WKB support in serializeWKB and parseWKB by
handling WKB type 7: in serializeWKB, write the GeometryCollection header and
recursively serialize each geometry in the geometries array into the collection
payload; in parseWKB, detect type 7, read the number of geometries and
recursively parse each child geometry into the geometries array. Ensure
byte-order and recursive calls reuse existing WKB helper functions so
encoding/decoding matches other geometry types.

In `@packages/adapter-pg/src/spatial-optimizer.ts`:
- Around line 23-24: Remove or trim inline "what/how" comments that simply
restate code (e.g., the "Check cache first" comment above the
versionCache.get(prisma) call and similar comments near variables like cached
and other blocks around the noted ranges); keep only rationale/context comments
that explain non-obvious decisions or link to issues. Locate the comments around
the versionCache.get(prisma) usage and the other listed regions (30-31, 34-35,
40-41, 90-91, 94-95, 98-101, 104-105) and either delete them or convert them
into short "why" comments that provide context or references, leaving the code
(functions/classes) and variable names unchanged.
- Around line 44-47: The catch block that probes the Postgres version is
incorrectly writing a permanent false into versionCache
(versionCache.set(prisma, false)) on any error; instead, do not cache a negative
result on exception — remove the cache write from the catch, optionally log the
error, and let the absence of a cache entry allow future probes in the
version-detection routine (the try/catch around the probe that uses versionCache
and the prisma key) to retry later or set the cache only when the probe
succeeds.
- Around line 82-89: The withSpatialOptimization function currently types the
operation callback as (client: PrismaClientLike) => Promise<T>, which prevents
callers from accessing generated model delegates; change the signature to
preserve the concrete client type by making the function generic over the client
(e.g., add a type parameter like C extends PrismaClientLike), accept prisma: C,
and type operation as (client: C) => Promise<T> so callers get full PrismaClient
types while keeping the existing behavior of withSpatialOptimization and
PrismaClientLike.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 67baf9a3-0f44-4f00-920a-4dfead94014b

📥 Commits

Reviewing files that changed from the base of the PR and between cdd08bc and 4931422.

📒 Files selected for processing (4)
  • packages/adapter-pg/src/__tests__/spatial-optimizer.test.ts
  • packages/adapter-pg/src/conversion.ts
  • packages/adapter-pg/src/index.ts
  • packages/adapter-pg/src/spatial-optimizer.ts

Comment thread packages/adapter-pg/src/conversion.ts Resolved
Comment thread packages/adapter-pg/src/conversion.ts Resolved
Comment thread packages/adapter-pg/src/conversion.ts Resolved
@lh0x00

lh0x00 commented Apr 2, 2026

Copy link
Copy Markdown
Author

hi @jacek-prisma @sorenbs , I hope you'll take the time to look through it.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

♻️ Duplicate comments (2)
packages/adapter-pg/src/pg.ts (2)

300-305: ⚠️ Potential issue | 🔴 Critical

Transactions still skip geometry initialization.

This guard only covers PrismaPgAdapter.queryRaw(). PgTransaction still inherits PgQueryable.queryRaw(), so if the first geometry read happens inside a transaction, fieldToColumnType() falls back to Text and no parser is registered for that OID. Move the initialization into the shared query path, or initialize before returning PgTransaction.

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

In `@packages/adapter-pg/src/pg.ts` around lines 300 - 305, The geometry OID
initialization is only done in PrismaPgAdapter.queryRaw, so PgTransaction (which
uses PgQueryable.queryRaw) can run queries before initialization and mis-detect
geometry types; fix by moving the initialization check into the shared query
entry used by both adapter and transactions (e.g., into PgQueryable.queryRaw or
a private helper like ensureGeometryOIDsInitialized called from both queryRaw
implementations), or call this.#initializeGeometryTypes() (guarded by
this.#geometryOIDsInitialized) immediately before creating/returning a
PgTransaction instance so transactions never run uninitialized; update
references to `#initializeGeometryTypes`, `#geometryOIDsInitialized`,
PgQueryable.queryRaw and PgTransaction to ensure the init is always performed
exactly once before any query path executes.

239-267: ⚠️ Potential issue | 🟠 Major

Do not mark initialization complete on misses or transient failures.

Because Line 245 checks only has(cacheKey) and Line 264 always flips #geometryOIDsInitialized, both an empty result set and any temporary catalog/query error become permanent for this adapter/process. After one early miss, later CREATE EXTENSION postgis will never be rediscovered until restart. Return a success flag from #queryGeometryOIDs() and only set the cache/instance flag after at least one OID is registered.

Also applies to: 293-297

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

In `@packages/adapter-pg/src/pg.ts` around lines 239 - 267, The init path
currently treats any cache miss or transient query error as success by setting
`#geometryOIDsInitialized` and inserting a cache key; modify `#queryGeometryOIDs` to
return a boolean success (true if at least one OID was registered), only write
into GEOMETRY_OID_CACHE and set the instance flag `#geometryOIDsInitialized` when
that boolean is true, and make `#initializeGeometryTypes` await existingPromise
and only mark initialized when the promise resolves true; also remove/avoid
inserting a cache key on failure and apply the same pattern used around the
duplicate block (lines ~293-297) so transient errors or empty results do not
permanently disable discovery of later CREATE EXTENSION postgis.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@AGENTS.md`:
- Around line 27-30: Update the adapter list that currently includes `js_pg`,
`js_neon`, `js_libsql`, `js_planetscale`, `js_d1`, `js_better_sqlite3`,
`js_mssql`, `js_mariadb`, `js_pg_cockroachdb` to also include `js_pg_postgis` so
the "Run specific adapter" example supports the PostGIS adapter; ensure the
example command remains in the same format (e.g., `pnpm --filter `@prisma/client`
test:functional:code --adapter js_pg_postgis <pattern>`) and add `js_pg_postgis`
alongside the other adapter tokens.

In `@packages/adapter-pg/src/pg.ts`:
- Around line 209-214: registerGeometryType/registerGeometryParser currently
write to module-global maps keyed only by numeric OID which causes
cross-database OID collisions; change their storage to be scoped by the same
per-database key used by GEOMETRY_OID_CACHE/CACHE_INIT_PROMISES (the DB identity
string built in connectToShadowDb). Replace the flat maps with a top-level
Map<dbKey, Map<oid, ...>> (or Map<dbKey, Set<oid>> depending on stored value),
update registerGeometryType/registerGeometryParser and any lookups in
conversion.ts to read/write via that dbKey, and ensure any initialization code
that seeds GEOMETRY_OID_CACHE uses the same dbKey so each adapter only
registers/parses geometry OIDs for its own database.
- Around line 273-281: The current SQL in the discovery query inside
packages/adapter-pg/src/pg.ts (the block that selects typname, oid from pg_type)
can match non-PostGIS user types named like geometry/point/polygon; update the
query to restrict to the PostGIS extension namespace by joining pg_extension (or
filtering pg_type.typnamespace = pg_extension.extnamespace) and require extname
= 'postgis' instead of allowing any object in public; modify the SELECT WHERE
clause that references pg_type, pg_namespace and pg_extension so it only returns
types whose typnamespace equals the extnamespace for extname='postgis', ensuring
only PostGIS-provided type OIDs are discovered.

---

Duplicate comments:
In `@packages/adapter-pg/src/pg.ts`:
- Around line 300-305: The geometry OID initialization is only done in
PrismaPgAdapter.queryRaw, so PgTransaction (which uses PgQueryable.queryRaw) can
run queries before initialization and mis-detect geometry types; fix by moving
the initialization check into the shared query entry used by both adapter and
transactions (e.g., into PgQueryable.queryRaw or a private helper like
ensureGeometryOIDsInitialized called from both queryRaw implementations), or
call this.#initializeGeometryTypes() (guarded by this.#geometryOIDsInitialized)
immediately before creating/returning a PgTransaction instance so transactions
never run uninitialized; update references to `#initializeGeometryTypes`,
`#geometryOIDsInitialized`, PgQueryable.queryRaw and PgTransaction to ensure the
init is always performed exactly once before any query path executes.
- Around line 239-267: The init path currently treats any cache miss or
transient query error as success by setting `#geometryOIDsInitialized` and
inserting a cache key; modify `#queryGeometryOIDs` to return a boolean success
(true if at least one OID was registered), only write into GEOMETRY_OID_CACHE
and set the instance flag `#geometryOIDsInitialized` when that boolean is true,
and make `#initializeGeometryTypes` await existingPromise and only mark
initialized when the promise resolves true; also remove/avoid inserting a cache
key on failure and apply the same pattern used around the duplicate block (lines
~293-297) so transient errors or empty results do not permanently disable
discovery of later CREATE EXTENSION postgis.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 6f4c1394-1069-4df9-9189-67e0547852d5

📥 Commits

Reviewing files that changed from the base of the PR and between 4931422 and 25f9ba6.

📒 Files selected for processing (3)
  • AGENTS.md
  • packages/adapter-pg/src/pg.ts
  • packages/client/tests/functional/_utils/setupTestSuiteClient.ts

Comment thread AGENTS.md
Comment on lines +27 to 30
- DB hooks in `setupTestSuite` options (`packages/client/tests/functional/_utils/types.ts`): `beforeDbPushCallback` runs before `db push`. With `TEST_REUSE_DATABASE=true`, the harness adds `--force-reset`, so anything done only in `beforeDbPushCallback` can be undone by the reset; use `afterForceResetCallback` for SQL/setup that must run after reset and before the schema push (e.g. `CREATE EXTENSION postgis`). `alterStatementCallback` supplies SQL executed via `db execute` only after a successful push—it cannot install types required during the push itself.
- Run specific adapter: `pnpm --filter @prisma/client test:functional:code --adapter js_pg <pattern>` (adapters: `js_pg`, `js_neon`, `js_libsql`, `js_planetscale`, `js_d1`, `js_better_sqlite3`, `js_mssql`, `js_mariadb`, `js_pg_cockroachdb`).
- For error assertions, use `result.name === 'PrismaClientKnownRequestError'` and `result.code` (not `instanceof`).
- Use `idForProvider(provider)` from `_utils/idForProvider` for portable ID field definitions.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Update the adapter example list to include js_pg_postgis.

The lifecycle-hook guidance is solid, but the adjacent “Run specific adapter” list is missing the new PostGIS adapter, which can mislead contributors running targeted tests.

📝 Suggested doc patch
-  - Run specific adapter: `pnpm --filter `@prisma/client` test:functional:code --adapter js_pg <pattern>` (adapters: `js_pg`, `js_neon`, `js_libsql`, `js_planetscale`, `js_d1`, `js_better_sqlite3`, `js_mssql`, `js_mariadb`, `js_pg_cockroachdb`).
+  - Run specific adapter: `pnpm --filter `@prisma/client` test:functional:code --adapter js_pg <pattern>` (adapters: `js_pg`, `js_pg_postgis`, `js_neon`, `js_libsql`, `js_planetscale`, `js_d1`, `js_better_sqlite3`, `js_mssql`, `js_mariadb`, `js_pg_cockroachdb`).
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- DB hooks in `setupTestSuite` options (`packages/client/tests/functional/_utils/types.ts`): `beforeDbPushCallback` runs before `db push`. With `TEST_REUSE_DATABASE=true`, the harness adds `--force-reset`, so anything done only in `beforeDbPushCallback` can be undone by the reset; use `afterForceResetCallback` for SQL/setup that must run after reset and before the schema push (e.g. `CREATE EXTENSION postgis`). `alterStatementCallback` supplies SQL executed via `db execute` only after a successful push—it cannot install types required during the push itself.
- Run specific adapter: `pnpm --filter @prisma/client test:functional:code --adapter js_pg <pattern>` (adapters: `js_pg`, `js_neon`, `js_libsql`, `js_planetscale`, `js_d1`, `js_better_sqlite3`, `js_mssql`, `js_mariadb`, `js_pg_cockroachdb`).
- For error assertions, use `result.name === 'PrismaClientKnownRequestError'` and `result.code` (not `instanceof`).
- Use `idForProvider(provider)` from `_utils/idForProvider` for portable ID field definitions.
- DB hooks in `setupTestSuite` options (`packages/client/tests/functional/_utils/types.ts`): `beforeDbPushCallback` runs before `db push`. With `TEST_REUSE_DATABASE=true`, the harness adds `--force-reset`, so anything done only in `beforeDbPushCallback` can be undone by the reset; use `afterForceResetCallback` for SQL/setup that must run after reset and before the schema push (e.g. `CREATE EXTENSION postgis`). `alterStatementCallback` supplies SQL executed via `db execute` only after a successful push—it cannot install types required during the push itself.
- Run specific adapter: `pnpm --filter `@prisma/client` test:functional:code --adapter js_pg <pattern>` (adapters: `js_pg`, `js_pg_postgis`, `js_neon`, `js_libsql`, `js_planetscale`, `js_d1`, `js_better_sqlite3`, `js_mssql`, `js_mariadb`, `js_pg_cockroachdb`).
- For error assertions, use `result.name === 'PrismaClientKnownRequestError'` and `result.code` (not `instanceof`).
- Use `idForProvider(provider)` from `_utils/idForProvider` for portable ID field definitions.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@AGENTS.md` around lines 27 - 30, Update the adapter list that currently
includes `js_pg`, `js_neon`, `js_libsql`, `js_planetscale`, `js_d1`,
`js_better_sqlite3`, `js_mssql`, `js_mariadb`, `js_pg_cockroachdb` to also
include `js_pg_postgis` so the "Run specific adapter" example supports the
PostGIS adapter; ensure the example command remains in the same format (e.g.,
`pnpm --filter `@prisma/client` test:functional:code --adapter js_pg_postgis
<pattern>`) and add `js_pg_postgis` alongside the other adapter tokens.

Comment on lines +209 to +214
// Module-level singleton cache shared across all adapter instances.
// PostGIS type OIDs are database-specific but stable within a single database.
const GEOMETRY_OID_CACHE = new Map<string, boolean>()

// Track ongoing initialization promises to avoid concurrent queries to same database.
const CACHE_INIT_PROMISES = new Map<string, Promise<void>>()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Keep geometry OID registrations scoped to a database, not the process.

The cache key is database-specific, but registerGeometryType() and registerGeometryParser() in packages/adapter-pg/src/conversion.ts:392-407 write to module-global maps keyed only by numeric OID. Once one adapter registers an OID as geometry, another adapter talking to a different database can misclassify its unrelated UDT with the same OID. connectToShadowDb() in this file already creates that multi-database path.

Also applies to: 287-290

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

In `@packages/adapter-pg/src/pg.ts` around lines 209 - 214,
registerGeometryType/registerGeometryParser currently write to module-global
maps keyed only by numeric OID which causes cross-database OID collisions;
change their storage to be scoped by the same per-database key used by
GEOMETRY_OID_CACHE/CACHE_INIT_PROMISES (the DB identity string built in
connectToShadowDb). Replace the flat maps with a top-level Map<dbKey, Map<oid,
...>> (or Map<dbKey, Set<oid>> depending on stored value), update
registerGeometryType/registerGeometryParser and any lookups in conversion.ts to
read/write via that dbKey, and ensure any initialization code that seeds
GEOMETRY_OID_CACHE uses the same dbKey so each adapter only registers/parses
geometry OIDs for its own database.

Comment on lines +273 to +281
sql: `
SELECT typname, oid FROM pg_type
WHERE typname = ANY($1::text[])
AND typnamespace IN (
SELECT oid FROM pg_namespace
WHERE nspname = 'public' OR oid = (
SELECT extnamespace FROM pg_extension WHERE extname = 'postgis'
)
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Restrict discovery to the PostGIS extension namespace.

pg_type also contains table row types, domains, and other user-defined types. A public table or domain named geometry/point/polygon will match this query, so discovery can register the wrong OID and mark initialization successful even when PostGIS is absent. Join pg_extension and filter to the postgis namespace instead of scanning all of public.

Suggested query shape
-          SELECT typname, oid FROM pg_type 
-          WHERE typname = ANY($1::text[])
-            AND typnamespace IN (
-              SELECT oid FROM pg_namespace 
-              WHERE nspname = 'public' OR oid = (
-                SELECT extnamespace FROM pg_extension WHERE extname = 'postgis'
-              )
-            )
+          SELECT t.typname, t.oid
+          FROM pg_type t
+          JOIN pg_extension e ON e.extname = 'postgis'
+          WHERE t.typname = ANY($1::text[])
+            AND t.typnamespace = e.extnamespace
+            AND t.typtype = 'b'
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
sql: `
SELECT typname, oid FROM pg_type
WHERE typname = ANY($1::text[])
AND typnamespace IN (
SELECT oid FROM pg_namespace
WHERE nspname = 'public' OR oid = (
SELECT extnamespace FROM pg_extension WHERE extname = 'postgis'
)
)
sql: `
SELECT t.typname, t.oid
FROM pg_type t
JOIN pg_extension e ON e.extname = 'postgis'
WHERE t.typname = ANY($1::text[])
AND t.typnamespace = e.extnamespace
AND t.typtype = 'b'
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/adapter-pg/src/pg.ts` around lines 273 - 281, The current SQL in the
discovery query inside packages/adapter-pg/src/pg.ts (the block that selects
typname, oid from pg_type) can match non-PostGIS user types named like
geometry/point/polygon; update the query to restrict to the PostGIS extension
namespace by joining pg_extension (or filtering pg_type.typnamespace =
pg_extension.extnamespace) and require extname = 'postgis' instead of allowing
any object in public; modify the SELECT WHERE clause that references pg_type,
pg_namespace and pg_extension so it only returns types whose typnamespace equals
the extnamespace for extname='postgis', ensuring only PostGIS-provided type OIDs
are discovered.

@AnthonyDreams

Copy link
Copy Markdown

hi @jacek-prisma @sorenbs , I hope you'll take the time to look through it.

@elrhourha

Copy link
Copy Markdown

hi @jacek-prisma @sorenbs , I hope you'll take the time to look through it.

peterzen added a commit to opencupid/opencupid that referenced this pull request Apr 13, 2026
## Summary

- Add composite B-tree indexes on `(lat, lon)` for both `Profile` and
`Post` tables — improves performance for bounding-box and nearby queries
used by map clustering, browse, and posts endpoints
- Delete deprecated `BrowseService` (zero callers since cluster endpoint
replaced `/browse/bounds`)
- Delete `ProfileMatchService.findSocialProfilesInBounds()` (only caller
was `BrowseService`)
- Clean up associated tests and mocks (-187 lines)

Immediate performance win while PostGIS integration is tracked
separately in #1289 (blocked on
[prisma/orm#29365](prisma/orm#29365)).

## Test plan

- [x] `pnpm test` passes (pre-existing flaky timeout in
`interaction.service.extended.spec.ts` unrelated)
- [x] `pnpm type-check` passes
- [x] Affected test files run green:
`profileMatch_social.service.spec.ts`, `findProfile.route.spec.ts`,
`findProfile.cluster.route.spec.ts`, `browse.route.spec.ts`
- [ ] Verify migration applies cleanly on production deploy

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
@lh0x00

lh0x00 commented May 12, 2026

Copy link
Copy Markdown
Author

Hmm, maybe the PR for this feature was overlooked by the team?

@vitzalt

vitzalt commented May 14, 2026

Copy link
Copy Markdown

Please can someone from the Prisma team explain the status of this feature?

The docs are already live:
https://www.prisma.io/docs/orm/prisma-client/special-fields-and-types/working-with-geometry-fields
https://www.prisma.io/docs/orm/prisma-schema/postgresql-extensions#postgis-extension-for-spatial-data

These were merged in on 1st April with this PR:
prisma/web#7685

But the actual feature (ie this PR) has not been merged in.

As a consequence of this, I've just spent a lot of time planning work around this documentation, and then debugging why my PostGIS setup and fields are not working as expected. I've then had to go in circles around a handful of tickets that have been open for literal years trying to understand what the status and plan for this feature actually is.

Please can you give us a clear status and roadmap?

Ie, should I put my work on hold until this feature is actually merged in, or should I invest a lot of time and effort into doing my work without the PostGIS extension, even though the docs say I can use it now?

@lh0x00 Thank you so much for all your hard work on this.

@lh0x00

lh0x00 commented May 14, 2026

Copy link
Copy Markdown
Author

This feature includes multiple PRs, but only the document PRs have been merged; the implementations in prisma/prisma-engines#5797 #29365 have not yet been merged.

@lh0x00

lh0x00 commented May 14, 2026

Copy link
Copy Markdown
Author

I'm so tired of waiting for a review; it seems like it's been forgotten? I'm still using the internally published fork from PRs.

@jannis6023

Copy link
Copy Markdown

@lh0x00 is there a way that you share or publish a forked package in the meantime? We are right now developing on a project where we would insanely need this feature - and people like you build them - and prisma team does not merge?!

Thanks a lot for your work in advance!

@coderabbitai

coderabbitai Bot commented May 15, 2026

Copy link
Copy Markdown
Contributor

CodeRabbit chat interactions are restricted to organization members for this repository. Ask an organization member to interact with CodeRabbit, or set chat.allow_non_org_members: true in your configuration.

@onuralpbicer-lapis

Copy link
Copy Markdown

These were merged in on 1st April with this PR: prisma/web#7685

At this point, maybe they did it as an April Fool's joke but forgot to revert it after...

@lh0x00 Amazing incredible work on this, really hope it gets merged otherwise we'll need to evaluate other ORMs...

@mirencar-tech

Copy link
Copy Markdown

Can someone tell me when this feature will be available? Our team really needs it

@theevann

Copy link
Copy Markdown

I need this too !

@tensordreams
tensordreams changed the base branch from main to v7 July 21, 2026 12:07
@tensordreams
tensordreams changed the base branch from v7 to main July 21, 2026 15:13
@tensordreams

Copy link
Copy Markdown
Contributor

Hi @lh0x00 — thanks for this, and apologies for the slow reply.

We're clearing the open PR backlog ahead of moving this codebase to a v7 branch, with the Prisma Next rewrite taking over main.

We are closing this one: it depends on prisma-engines#5797, which has not merged, and touches 60+ files across both generators, the runtime and adapter-pg.

The interest in this from the community is clear, and none of the above is a judgement on the idea — only on what can be landed in the time remaining.

Thanks for the time you put into it.

peterzen pushed a commit to peterzen/prisma that referenced this pull request Jul 21, 2026
Upstream closed prisma#29365 pending the v7 move; record that context.
Engines PR 5797 merged cleanly onto engines main locally and its own suites
pass; PSL syntax is Geometry/Geography scalars with @db native attributes and
DMMF renders plain type names, so update the generator-detection and
functional-schema tasks accordingly.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01E98o3t78osNBksFjbT4Srx
peterzen pushed a commit to peterzen/prisma that referenced this pull request Jul 21, 2026
Squash-port of the community PostGIS PR onto the v7 codebase, minus the
PR's unrelated drive-by edits (eslint comment removals, .prettierignore)
and its AGENTS.md hunk. Conflicted files (.prettierignore, AGENTS.md)
resolved by keeping main's versions. v7 corrections land as follow-up
commits.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01E98o3t78osNBksFjbT4Srx
@lh0x00

lh0x00 commented Aug 7, 2026

Copy link
Copy Markdown
Author

Since this PR hasn't merged, I've published the same PostGIS fork to npm as @vertexa/prisma, @vertexa/prisma-client, and @vertexa/prisma-adapter-pg (v7.8.6) — drop-in
replacements that add Geometry/Geography scalar types, near/within/intersects spatial
filters, distanceFrom ordering, and automatic GeoJSON ↔ EWKB serialization.

npm install @vertexa/prisma @vertexa/prisma-client @vertexa/prisma-adapter-pg

{
  "pnpm": {
    "overrides": {
      "@prisma/client": "npm:@vertexa/[email protected]",
      "@prisma/adapter-pg": "npm:@vertexa/[email protected]"
    }
  }
}
model Location {
  id       Int      @id @default(autoincrement())
  name     String
  position Geometry(Point, 4326)?
}
const nearby = await prisma.location.findMany({
  where: { position: { near: { point: [13.4, 52.5], maxDistance: 1000 } } },
  orderBy: { position: { distanceFrom: { point: [13.4, 52.5], direction: 'asc' } } },
  take: 10,
})

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.

10 participants