Repository navigation
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (1)
Summary by CodeRabbit
WalkthroughAdds 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. ChangesDocs & Formatting
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
✨ Simplify 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.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (59)
.db.env.envrc.prettierignoreAGENTS.mddocker/README.mddocker/postgis-test.ymlpackages/adapter-pg/src/__tests__/conversion.test.tspackages/adapter-pg/src/__tests__/test-utils.tspackages/adapter-pg/src/__tests__/wkb-parser.test.tspackages/adapter-pg/src/__tests__/wkb-performance.test.tspackages/adapter-pg/src/__tests__/wkb-serializer.test.tspackages/adapter-pg/src/conversion.tspackages/adapter-pg/src/errors.tspackages/adapter-pg/src/pg.tspackages/adapter-pg/src/wkb-parser.tspackages/adapter-pg/src/wkb-primitives.tspackages/adapter-pg/src/wkb-serializer.tspackages/cli/src/utils/simpleDebounce.tspackages/client-engine-runtime/src/interpreter/data-mapper.tspackages/client-engine-runtime/src/interpreter/serialize-sql.test.tspackages/client-engine-runtime/src/interpreter/serialize-sql.tspackages/client-engine-runtime/src/json-protocol.test.tspackages/client-engine-runtime/src/json-protocol.tspackages/client-engine-runtime/src/query-plan.tspackages/client-generator-js/src/TSClient/Input.tspackages/client-generator-js/src/TSClient/Output.tspackages/client-generator-js/src/TSClient/SelectIncludeOmit.tspackages/client-generator-js/src/TSClient/common.tspackages/client-generator-js/src/typedSql/mapTypes.tspackages/client-generator-js/src/utils/common.tspackages/client-generator-ts/src/TSClient/Input.tspackages/client-generator-ts/src/TSClient/Output.tspackages/client-generator-ts/src/TSClient/SelectIncludeOmit.tspackages/client-generator-ts/src/TSClient/common.tspackages/client-generator-ts/src/typedSql/mapTypes.tspackages/client-generator-ts/src/utils/common.tspackages/client/scripts/default-index.d.tspackages/client/src/__tests__/buffer-small.test.tspackages/client/src/__tests__/deserializeRawResults.test.tspackages/client/src/__tests__/integration/__helpers__/sanitizeEvents.tspackages/client/src/runtime/core/jsonProtocol/serializeJsonQuery.tspackages/client/src/runtime/core/types/exported/Geometry.tspackages/client/src/runtime/core/types/exported/index.tspackages/client/src/runtime/utils/deserializeRawResults.tspackages/client/tests/functional/_utils/getTestSuitePlan.tspackages/client/tests/functional/_utils/providers.tspackages/client/tests/functional/_utils/setupTestSuiteClient.tspackages/client/tests/functional/_utils/setupTestSuiteEnv.tspackages/client/tests/functional/_utils/setupTestSuiteMatrix.tspackages/client/tests/functional/_utils/types.tspackages/client/tests/functional/postgis/_matrix.tspackages/client/tests/functional/postgis/prisma/_schema.tspackages/client/tests/functional/postgis/test.tspackages/driver-adapter-utils/src/Geometry.tspackages/driver-adapter-utils/src/const.tspackages/driver-adapter-utils/src/index.tspackages/driver-adapter-utils/src/types.tspackages/generator/src/typedSql.tspackages/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
|
It's already available for data generation, with unit tests and related features. I'm working on making it support native queries! |
|
Hi @dulmandakh @jacek-prisma @sorenbs, please review my PR, thank you. |
There was a problem hiding this comment.
Actionable comments posted: 5
♻️ Duplicate comments (3)
packages/adapter-pg/src/__tests__/wkb-performance.test.ts (2)
169-180: 🧹 Nitpick | 🔵 TrivialSource size check uses character count, not byte count.
readFileSync(..., 'utf-8').lengthreturns character count. For ASCII source files this matches byte count, but the variable nametargetBytessuggests byte comparison. Consider usingBuffer.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 | 🔵 TrivialTest silently passes when dist files are missing.
When
dist/index.jsordist/index.mjsdon'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 | 🟠 MajorDon't auto-tag every GeoJSON-shaped object as geometry.
serializeArgumentsValue()has no field-type check here, so aJsonfield 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
📒 Files selected for processing (13)
packages/adapter-pg/src/__tests__/wkb-performance.test.tspackages/adapter-pg/src/pg.tspackages/adapter-pg/src/wkb-primitives.tspackages/adapter-pg/src/wkb-serializer.tspackages/client-engine-runtime/src/json-protocol.tspackages/client-generator-js/src/TSClient/Input.tspackages/client-generator-js/src/typedSql/mapTypes.tspackages/client-generator-js/src/utils/common.tspackages/client-generator-ts/src/TSClient/Input.tspackages/client-generator-ts/src/typedSql/mapTypes.tspackages/client/src/runtime/core/jsonProtocol/serializeJsonQuery.tspackages/client/tests/functional/postgis/_matrix.tspackages/client/tests/functional/postgis/test.ts
There was a problem hiding this comment.
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
📒 Files selected for processing (4)
packages/adapter-pg/src/__tests__/spatial-optimizer.test.tspackages/adapter-pg/src/conversion.tspackages/adapter-pg/src/index.tspackages/adapter-pg/src/spatial-optimizer.ts
|
hi @jacek-prisma @sorenbs , I hope you'll take the time to look through it. |
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (2)
packages/adapter-pg/src/pg.ts (2)
300-305:⚠️ Potential issue | 🔴 CriticalTransactions still skip geometry initialization.
This guard only covers
PrismaPgAdapter.queryRaw().PgTransactionstill inheritsPgQueryable.queryRaw(), so if the first geometry read happens inside a transaction,fieldToColumnType()falls back toTextand no parser is registered for that OID. Move the initialization into the shared query path, or initialize before returningPgTransaction.🤖 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 | 🟠 MajorDo 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, laterCREATE EXTENSION postgiswill 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
📒 Files selected for processing (3)
AGENTS.mdpackages/adapter-pg/src/pg.tspackages/client/tests/functional/_utils/setupTestSuiteClient.ts
| - 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. |
There was a problem hiding this comment.
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.
| - 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.
| // 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>>() |
There was a problem hiding this comment.
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.
| 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' | ||
| ) | ||
| ) |
There was a problem hiding this comment.
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.
| 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.
|
hi @jacek-prisma @sorenbs , I hope you'll take the time to look through it. |
|
hi @jacek-prisma @sorenbs , I hope you'll take the time to look through it. |
## 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]>
|
Hmm, maybe the PR for this feature was overlooked by the team? |
|
Please can someone from the Prisma team explain the status of this feature? The docs are already live: These were merged in on 1st April with this PR: 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. |
|
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. |
|
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. |
|
@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! |
|
CodeRabbit chat interactions are restricted to organization members for this repository. Ask an organization member to interact with CodeRabbit, or set |
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... |
|
Can someone tell me when this feature will be available? Our team really needs it |
|
I need this too ! |
|
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 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. |
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
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
|
Since this PR hasn't merged, I've published the same PostGIS fork to npm as npm install {
"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,
}) |
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:
Query with native filters:
Create with type safety:
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,
$queryRawsupportQuick Examples
Restaurant finder - 5km radius, sorted by distance:
Delivery zones - Check if address is in service area:
Activity tracking - Find routes passing through a park:
TypeScript types:
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.
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:
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
UnsupportedRun
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-pgthat 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.