Skip to content

fix: handle re-save of postgres geometric types - #11857

Merged
gioboa merged 3 commits into
typeorm:masterfrom
Cprakhar:fix/postgres-geometric-types
Jan 15, 2026
Merged

gioboa merged 3 commits into
typeorm:masterfrom
Cprakhar:fix/postgres-geometric-types

Conversation

@Cprakhar

@Cprakhar Cprakhar commented Dec 18, 2025 •

Copy link
Copy Markdown
Collaborator

Description of change

  • Normalize Postgres point/circle values on persist to avoid invalid input when re-saving hydrated objects.
    PostgresDriver.ts
    preparePersistentValue() {
        // remaining code
            } else if (columnMetadata.type === "point") {
            if (
                typeof value === "object" &&
                value.x !== undefined &&
                value.y !== undefined
            ) {
                return `(${value.x},${value.y})`
            }
            return value
        } else if (columnMetadata.type === "circle") {
            if (
                typeof value === "object" &&
                value.x !== undefined &&
                value.y !== undefined &&
                value.radius !== undefined
            ) {
                return `<(${value.x},${value.y}),${value.radius}>`
            }
            return value
        }
        // remaining code
    }
  • Add functional Postgres geometry round-trip (save and then re-save) tests for point, circle, box, line, lseg, path, polygon, and mixed cases.

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links relevant issues as Fixes #4004
  • There are new or updated tests validating the change (functional/geometric-spatial.test.ts)
  • Documentation has been updated to reflect this change (docs/docs/**.md)

Fixes #4004

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis ✅

4004 - PR Code Verified

Compliant requirements:

  • Fix the issue where reading and then saving the same entity with a point type column fails
  • Handle the case where Postgres returns point values as objects instead of strings
  • Prevent QueryFailedError when re-inserting entities with point columns
  • Support round-trip save operations for entities with point columns

Requires further human verification:

  • Verify that the fix works correctly with negative coordinates as mentioned in the original issue (-23, -23)
  • Test with various edge cases like zero values, very large numbers, and decimal precision
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Missing null checks

The point and circle normalization logic checks for object type and property existence but doesn't validate that the properties are actually numbers. Invalid values like { x: null, y: undefined } or { x: 'string', y: 5 } could produce malformed SQL strings like (null,undefined) or (string,5).

} else if (columnMetadata.type === "point") {
    if (
        typeof value === "object" &&
        value.x !== undefined &&
        value.y !== undefined
    ) {
        return `(${value.x},${value.y})`
    }
    return value
} else if (columnMetadata.type === "circle") {
    if (
        typeof value === "object" &&
        value.x !== undefined &&
        value.y !== undefined &&
        value.radius !== undefined
    ) {
        return `<(${value.x},${value.y}),${value.radius}>`
    }
    return value
Unrelated test file

This test file appears to be for testing BigInt with the In operator, which is unrelated to the geometric types issue described in the ticket. This may have been included by mistake or addresses a different issue entirely.

import "reflect-metadata"
import "../../../utils/test-setup"
import { DataSource, In } from "../../../../src"
import {
    closeTestingConnections,
    createTestingConnections,
    reloadTestingDatabases,
} from "../../../utils/test-utils"
import { Author } from "./entity/Author"
import { Book } from "./entity/Book"

describe("find options > In operator with BigInt column", () => {
    let connections: DataSource[]

    before(
        async () =>
            (connections = await createTestingConnections({
                __dirname,
            })),
    )

    beforeEach(() => reloadTestingDatabases(connections))
    after(() => closeTestingConnections(connections))

    it("should find books using In operator with bigint column", () =>
        Promise.all(
            connections.map(async (connection) => {
                // Create test data
                const author1 = connection.manager.create(Author, {
                    name: "Author 1",
                })
                const author2 = connection.manager.create(Author, {
                    name: "Author 2",
                })
                const author3 = connection.manager.create(Author, {
                    name: "Author 3",
                })

                const savedAuthor1 = await connection.manager.save(author1)
                const savedAuthor2 = await connection.manager.save(author2)
                const savedAuthor3 = await connection.manager.save(author3)

                const book1 = connection.manager.create(Book, {
                    title: "Book 1",
                    authorId: savedAuthor1.id,
                })
                const book2 = connection.manager.create(Book, {
                    title: "Book 2",
                    authorId: savedAuthor2.id,
                })
                const book3 = connection.manager.create(Book, {
                    title: "Book 3",
                    authorId: savedAuthor3.id,
                })

                await connection.manager.save([book1, book2, book3])

                // Test using findBy with In operator (this should fail with the bug)
                const booksRepository = connection.getRepository(Book)
                const authorIds = [savedAuthor1.id, savedAuthor2.id]

                console.log("Testing with authorIds:", authorIds)
                console.log("Type of authorIds[0]:", typeof authorIds[0])

                // This should work but fails with: "Validation failed for parameter '0'. Cannot convert [object Object] to a BigInt"
                const books = await booksRepository.findBy({
                    authorId: In(authorIds),
                })

                console.log("Found books:", books)
                books.should.have.lengthOf(2)
                books
                    .map((b) => b.title)
                    .should.include.members(["Book 1", "Book 2"])
            }),
        ))

    it("should find books using queryBuilder with bigint column (for comparison)", () =>
        Promise.all(
            connections.map(async (connection) => {
                // Create test data
                const author1 = connection.manager.create(Author, {
                    name: "Author 1",
                })
                const author2 = connection.manager.create(Author, {
                    name: "Author 2",
                })

                const savedAuthor1 = await connection.manager.save(author1)
                const savedAuthor2 = await connection.manager.save(author2)

                const book1 = connection.manager.create(Book, {
                    title: "Book 1",
                    authorId: savedAuthor1.id,
                })
                const book2 = connection.manager.create(Book, {
                    title: "Book 2",
                    authorId: savedAuthor2.id,
                })

                await connection.manager.save([book1, book2])

                // This should work (and it does according to the issue)
                const booksRepository = connection.getRepository(Book)
                const authorIds = [savedAuthor1.id, savedAuthor2.id]

                const books = await booksRepository
                    .createQueryBuilder("book")
                    .where("book.authorId IN (:...authorIds)", {
                        authorIds,
                    })
                    .getMany()

                books.should.have.lengthOf(2)
            }),
        ))
})
Unrelated test file

This test file is for MySQL closure table tree functionality and is completely unrelated to the Postgres geometric types issue. It should not be part of this PR.

import "reflect-metadata"
import { DataSource } from "../../../../src/data-source/DataSource"
import {
    closeTestingConnections,
    createTestingConnections,
    reloadTestingDatabases,
} from "../../../utils/test-utils"
import { expect } from "chai"
import { Category } from "./entity/Category"

// Confirms current behavior: countDescendants includes the node itself (returns 1 for leaf)
describe("mysql > tree tables > closure-table countDescendants behavior", () => {
    let connections: DataSource[]
    before(
        async () =>
            (connections = await createTestingConnections({
                entities: [Category],
                enabledDrivers: ["mysql"],
                dropSchema: true,
                schemaCreate: true,
            })),
    )
    beforeEach(() => reloadTestingDatabases(connections))
    after(() => closeTestingConnections(connections))

    it("returns 1 for a leaf node (self-reference included)", () =>
        Promise.all(
            connections.map(async (connection) => {
                const repo = connection.getTreeRepository(Category)

                const root = new Category()
                root.name = "root"
                await repo.save(root)

                const count = await repo.countDescendants(root)
                expect(count).to.equal(1)
            }),
        ))

    it("returns N for a node with N descendants", () =>
        Promise.all(
            connections.map(async (connection) => {
                const repo = connection.getTreeRepository(Category)

                const root = new Category()
                root.name = "root"

                const child = new Category()
                child.name = "child"
                child.parentCategory = root

                await repo.save(root)
                await repo.save(child)

                const count = await repo.countDescendants(root)
                expect(count).to.equal(2)
            }),
        ))
})

@pkg-pr-new

pkg-pr-new Bot commented Dec 18, 2025 •

Copy link
Copy Markdown
  • typeorm-sql-js-example

    npm i https://pkg.pr.new/typeorm/typeorm@11857
    

commit: 5124886

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Validate geometric type objects properly

Add validation for point and circle type objects to ensure they have all
required properties (x, y for point; x, y, radius for circle), and throw an
error if any are missing.

src/driver/postgres/PostgresDriver.ts [687-705]

         return DateUtils.mixedDateToDate(value)
     } else if (columnMetadata.type === "point") {
-        if (
-            typeof value === "object" &&
-            value.x !== undefined &&
-            value.y !== undefined
-        ) {
+        if (typeof value === "object" && value !== null) {
+            if (value.x === undefined || value.y === undefined) {
+                throw new TypeORMError(
+                    `Value for point column is an object but is missing "x" or "y" property.`,
+                )
+            }
             return `(${value.x},${value.y})`
         }
         return value
     } else if (columnMetadata.type === "circle") {
-        if (
-            typeof value === "object" &&
-            value.x !== undefined &&
-            value.y !== undefined &&
-            value.radius !== undefined
-        ) {
+        if (typeof value === "object" && value !== null) {
+            if (
+                value.x === undefined ||2
+                value.y === undefined ||2
+                value.radius === undefined
+            ) {
+                throw new TypeORMError(
+                    `Value for circle column is an object but is missing "x", "y", or "radius" property.`,
+                )
+            }
             return `<(${value.x},${value.y}),${value.radius}>`
         }
         return value
     } else if (
         ["json", "jsonb", ...this.spatialTypes].indexOf(
             columnMetadata.type,

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that passing incomplete objects for point or circle types would lead to runtime errors, and proposes adding explicit validation to throw a descriptive error, which significantly improves the robustness of the new feature.

Medium
  • More

@Cprakhar
Cprakhar force-pushed the fix/postgres-geometric-types branch from a5679dd to c0af26e Compare December 18, 2025 18:22
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Code Suggestions ✨

No code suggestions found for the PR.

@coveralls

coveralls commented Dec 18, 2025 •

Copy link
Copy Markdown

Coverage Status

coverage: 80.886% (+0.004%) from 80.882%
when pulling 5124886 on Cprakhar:fix/postgres-geometric-types
into 1676484 on typeorm:master.

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Code Suggestions ✨

No code suggestions found for the PR.

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks @Cprakhar great fix 👏

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Code Suggestions ✨

No code suggestions found for the PR.

@Cprakhar
Cprakhar force-pushed the fix/postgres-geometric-types branch from c442225 to 982cc52 Compare January 9, 2026 18:41
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Code Suggestions ✨

No code suggestions found for the PR.

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Code Suggestions ✨

No code suggestions found for the PR.

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code Review by Qodo (Alpha)

🐞 Bugs (1) 📘 Rule Violations (3) 📎 Requirement Gaps (0) 💡 Suggestions (0)

Grey Divider


Action Required

1. Missing hydration for point/circle types 🐞 Bug
Description
• The PR adds conversion logic in preparePersistentValue (lines 751-769) to convert point/circle
  objects to PostgreSQL string format when writing to database
• However, it does NOT add corresponding logic in prepareHydratedValue to parse the string format
  back to objects when reading from database
• The pg library returns geometric types as strings by default (e.g., '(10.5,20.3)' for point,
  '<(4,5),12>' for circle)
• Without hydration logic, the tests will fail because they expect objects: line 52 expects `{ x:
  10.5, y: 20.3 }, lines 90-94 expect { x: 4, y: 5, radius: 12 }`

correctness

Code

src/driver/postgres/PostgresDriver.ts[R751-769]

+        } else if (columnMetadata.type === "point") {
+            if (
+                typeof value === "object" &&
+                value.x !== undefined &&
+                value.y !== undefined
+            ) {
+                return `(${value.x},${value.y})`
+            }
+            return value
+        } else if (columnMetadata.type === "circle") {
+            if (
+                typeof value === "object" &&
+                value.x !== undefined &&
+                value.y !== undefined &&
+                value.radius !== undefined
+            ) {
+                return `<(${value.x},${value.y}),${value.radius}>`
+            }
+            return value
Evidence
The PR implements only half of the round-trip conversion. The preparePersistentValue method handles
object-to-string conversion for writing, but prepareHydratedValue (which handles reading from
database) has no corresponding point/circle parsing logic. This pattern is inconsistent with other
types like vector, hstore, and cube which have both write and read conversions. The existing test
file column-types-postgres.test.ts (lines 173, 179) already expects point and circle to return as
objects, proving this hydration logic should exist.

src/driver/postgres/PostgresDriver.ts[751-769]
src/driver/postgres/PostgresDriver.ts[838-968]
test/functional/spatial/postgres/geometric-spatial.test.ts[52]
test/functional/spatial/postgres/geometric-spatial.test.ts[90-94]
test/functional/database-schema/column-types/postgres/column-types-postgres.test.ts[173]
test/functional/database-schema/column-types/postgres/column-types-postgres.test.ts[179]

Agent Prompt
## Issue Description
The PR adds object-to-string conversion for point and circle types in `preparePersistentValue` but is missing the corresponding string-to-object parsing in `prepareHydratedValue`. This breaks round-trip conversion and causes test failures.

## Issue Context
- PostgreSQL returns point as string format: `(x,y)` e.g., `(10.5,20.3)`
- PostgreSQL returns circle as string format: `&lt;(x,y),radius&gt;` e.g., `&lt;(4,5),12&gt;`
- Tests expect these to be parsed into objects: `{ x: number, y: number }` for point and `{ x: number, y: number, radius: number }` for circle
- Other geometric types like vector, hstore, and cube have similar parsing logic in prepareHydratedValue

## Fix Focus Areas
- src/driver/postgres/PostgresDriver.ts[838-968] - Add point and circle parsing logic in prepareHydratedValue method, similar to how vector (lines 863-874) and cube (lines 897-923) are handled

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation Recommended

2. Stack traces logged in test error handlers 📘 Rule Violation
Description
• The test file logs full error stack traces using console.warn(err.stack) in error handlers
• This violates secure error handling practices as stack traces can expose internal implementation
  details, file paths, and system architecture
• Stack traces should only be written to secure internal logs, not to console output which may be
  visible in CI/CD pipelines or test reports

security

Code

test/functional/spatial/postgres/geometric-spatial.test.ts[26]

+            console.warn(err.stack)
Evidence
The compliance checklist requires that detailed error information including stack traces should only
be written to secure, internal logs (PR Compliance ID 4). The test code at lines 26 and 34 logs
stack traces to console.warn, which could expose internal system details in test output logs.

Rule 4: Generic: Secure Error Handling
test/functional/spatial/postgres/geometric-spatial.test.ts[26-26]
test/functional/spatial/postgres/geometric-spatial.test.ts[34-34]

Agent Prompt
## Issue description
The test error handlers are logging full stack traces to console output, which can expose internal implementation details and violate secure error handling practices.

## Issue Context
This is a test file where error handlers catch exceptions during database setup/teardown. While debugging information is useful, stack traces should not be exposed in console output as they may be visible in CI/CD logs or test reports.

## Fix Focus Areas
- test/functional/spatial/postgres/geometric-spatial.test.ts[26-26]
- test/functional/spatial/postgres/geometric-spatial.test.ts[34-34]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Missing input validation for geometric coordinates 📘 Rule Violation
Description
• The preparePersistentValue method for point and circle types lacks validation of numeric values
  before string interpolation
• Values like value.x, value.y, and value.radius are directly interpolated into SQL strings
  without checking if they are valid numbers
• This could lead to malformed SQL or unexpected behavior if non-numeric values are passed

reliability

Code

src/driver/postgres/PostgresDriver.ts[R751-769]

+        } else if (columnMetadata.type === "point") {
+            if (
+                typeof value === "object" &&
+                value.x !== undefined &&
+                value.y !== undefined
+            ) {
+                return `(${value.x},${value.y})`
+            }
+            return value
+        } else if (columnMetadata.type === "circle") {
+            if (
+                typeof value === "object" &&
+                value.x !== undefined &&
+                value.y !== undefined &&
+                value.radius !== undefined
+            ) {
+                return `<(${value.x},${value.y}),${value.radius}>`
+            }
+            return value
Evidence
The compliance checklist requires robust error handling with edge case management including
validation of external inputs and proper handling of boundary values (PR Compliance ID 3). The new
code checks for property existence but does not validate that x, y, and radius are actually numeric
values before interpolating them into strings.

Rule 3: Generic: Robust Error Handling and Edge Case Management
src/driver/postgres/PostgresDriver.ts[757-757]
src/driver/postgres/PostgresDriver.ts[767-767]

Agent Prompt
## Issue description
The point and circle type handlers directly interpolate coordinate values into SQL strings without validating that they are valid numbers. This could lead to malformed SQL if invalid values are provided.

## Issue Context
The preparePersistentValue method is responsible for converting JavaScript objects to PostgreSQL-compatible string formats. While it checks for property existence, it doesn&#x27;t validate the numeric nature of the values.

## Fix Focus Areas
- src/driver/postgres/PostgresDriver.ts[751-759]
- src/driver/postgres/PostgresDriver.ts[760-769]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. No null safety check for object properties 📘 Rule Violation
Description
• The code checks value.x !== undefined but doesn't verify that value itself is not null before
  accessing properties
• While typeof value === "object" is checked, in JavaScript typeof null === "object" returns
  true, which could cause runtime errors
• This creates a potential edge case where null values could cause property access errors

reliability

Code

src/driver/postgres/PostgresDriver.ts[R752-756]

+            if (
+                typeof value === "object" &&
+                value.x !== undefined &&
+                value.y !== undefined
+            ) {
Evidence
The compliance checklist requires explicit handling of edge cases including null values (PR
Compliance ID 3). The code uses typeof value === "object" which returns true for null in
JavaScript, potentially causing property access errors when checking value.x !== undefined.

Rule 3: Generic: Robust Error Handling and Edge Case Management
src/driver/postgres/PostgresDriver.ts[752-756]

Agent Prompt
## Issue description
The type check `typeof value === &quot;object&quot;` doesn&#x27;t exclude null values, which could cause runtime errors when accessing properties like `value.x`.

## Issue Context
In JavaScript, `typeof null === &quot;object&quot;` returns true due to a historical quirk. The code should explicitly check that value is not null before attempting to access its properties.

## Fix Focus Areas
- src/driver/postgres/PostgresDriver.ts[752-756]
- src/driver/postgres/PostgresDriver.ts[761-766]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

@gioboa
gioboa merged commit 65dea3c into typeorm:master Jan 15, 2026
38 checks passed
@Cprakhar
Cprakhar deleted the fix/postgres-geometric-types branch January 24, 2026 20:10
kranners pushed a commit to kranners/typeorm that referenced this pull request Mar 1, 2026
@pkuczynski pkuczynski added this to the 1.0 milestone Mar 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

Cannot read then save the same entity with point

5 participants