drizzle-orm icon indicating copy to clipboard operation
drizzle-orm copied to clipboard

[BUG]: Postgis `geometry` query select fails when using `with`

Open BryanAbate opened this issue 1 year ago • 9 comments

What version of drizzle-orm are you using?

0.31.2

What version of drizzle-kit are you using?

0.22.6

Describe the Bug

If we have two tables like:

const locations = pgTable('locations', {
  id: serial('id').primaryKey(),
  geoLongitudeLatitude: geometry('geo_longitude_latitude', { type: 'point', mode: 'xy', srid: 4326 }),
})

const tests = pgTable('tests', {
  id: serial('id').primaryKey(),
  locationId: integer('location_id')
    .references(() => locations.id)
    .notNull()
})

relations(tests, ({ one }) => ({
  location: one(locations, {
    fields: [tests.locationId],
    references: [locations.id],
}),

It works fine to select locations by themselves like client.query.locations.findFirst(...) but if we do a join and try a query like:

client.query.tests.findFirst(
  with: {
    location: true
  }
)

Then it fails with the following error:

RangeError: Offset is outside the bounds of the DataView
    at DataView.getUint32 (<anonymous>)
    at parseEWKB

Expected behavior

No response

Environment & setup

No response

BryanAbate avatar Jun 18 '24 09:06 BryanAbate

I have the same issue, did you find any workarounds?

bent101 avatar Jul 10 '24 20:07 bent101

I haven't had time to investigate further unfortunately. But one potential workaround would be to see if the issue is present as well when using the query builder (db.select()...) instead of Drizzle queries.

BryanAbate avatar Jul 11 '24 08:07 BryanAbate

db.select() works as a workaround. Waiting for the fix for with: {}.

madispuk avatar Aug 08 '24 12:08 madispuk

I found a fix https://github.com/drizzle-team/drizzle-orm/pull/2778

mauriciabad avatar Aug 09 '24 20:08 mauriciabad

Having the same issue here. Thanks Maurici for providing a fix, looking forward to this PR being merged and released.

oscar-corredor avatar Aug 19 '24 16:08 oscar-corredor

Bump

NicHaley avatar Sep 25 '24 02:09 NicHaley

I had this issue, resolved it with querying location like this:

    extras: {
      x: sql<number>`ST_X(${table.location})`.as("x"),
      y: sql<number>`ST_Y(${table.location})`.as("y"),
    },

It's not perfect, but it lets me use findMany and handle geometry type without issues.

FNDEVVE avatar Oct 12 '24 10:10 FNDEVVE

Encountered the same issue described in #2778, which explains the root cause well.

As a temporary workaround (to avoid manually patching the package), you can use a custom PostgreSQL type, based on the parsing code provided by @mauriciabad :

import { customType } from "drizzle-orm/pg-core";
import { parseEWKB } from "drizzle-orm/pg-core/columns/postgis_extension/utils";

interface GeometryPointObject {
  type: "Point";
  crs?: {
    type: "name";
    properties?: {
      name: string;
    };
  };
  coordinates: [number, number];
}

function parsePointObject(obj: GeometryPointObject): [number, number] {
  if (
    !obj ||
    obj.type !== "Point" ||
    !Array.isArray(obj.coordinates) ||
    obj.coordinates.length !== 2 ||
    !obj.coordinates.every((n): n is number => Number.isFinite(n))
  ) {
    throw new Error("Invalid geometry point object");
  }

  return obj.coordinates;
}

// Override Geometry type
export const point = customType<{
  data: { x: number; y: number } | null | undefined;
}>({
  dataType() {
    return "geometry(point)";
  },
  toDriver(value) {
    if (value) {
      return `point(${value.x} ${value.y})`;
    }

    return "NULL";
  },
  fromDriver(value): { x: number; y: number } | null {
    switch (typeof value) {
      case "string": {
        const [x, y] = parseEWKB(value);
        return { x, y };
      }
      case "object": {
        const [x, y] = parsePointObject(value as GeometryPointObject);
        return { x, y };
      }
      default:
        return null;
    }
  },
});

Something like the following would fix the issue. Hopefully, this problem will be fixed and we can just use provided drizzle geometry type.

shellbear avatar Nov 06 '24 23:11 shellbear

Bump

chris-allen avatar Apr 25 '25 01:04 chris-allen

Hey everyone!

I've created this message to send in a batch to all opened issues we have, just because there are a lot of them and I want to update all of you with our current work, why issues are not responded to, and the amount of work that has been done by our team over ~8 months.

I saw a lot of issues with suggestions on how to fix something while we were not responding – so thanks everyone. Also, thanks to everyone patiently waiting for a response from us and continuing to use Drizzle!

We currently have 4 major branches with a lot of work done. Each branch was handled by different devs and teams to make sure we could make all the changes in parallel.


First branch is drizzle-kit rewrite

All of the work can be found on the alternation-engine branch. Here is a PR with the work done: https://github.com/drizzle-team/drizzle-orm/pull/4439

As you can see, it has 167k added lines of code and 67k removed, which means we've completely rewritten the drizzle-kit alternation engine, the way we handle diffs for each dialect, together with expanding our test suite from 600 tests to ~9k test units for all different types of actions you can do with kit. More importantly, we changed the migration folder structure and made commutative migrations, so you won't face complex conflicts on migrations when working in a team.

What's left here:

  • We are finishing handling defaults for Postgres, the last being geometry (yes, we fixed the srid issue here as well).
  • We are finishing commutative migrations for all dialects.
  • We are finishing up the command, so the migration flow will be as simple as drizzle-kit up for you.

Where it brings us:

  • We are getting drizzle-kit into a new good shape where we can call it [email protected]!

Timeline:

  • We need ~2 weeks to finish all of the above and send this branch to beta for testing.

Second big branch is a complex one with several HUGE updates

  • Bringing Relational Queries v2 finally live. We've done a lot of work here to actually make it faster than RQBv1 and much better from a DX point of view. But in implementing it, we had to make another big rewrite, so we completely rewrote the drizzle-orm type system, which made it much simpler and improved type performance by ~21.4x:
(types instantiations for 3300 lines production drizzle schema + 990 lines relations)

TS v5.8.3: 728.8k -> 34.1k
TS v5.9.2: 553.7k -> 25.4k

You can read more about it here.

What's left here:

Where it brings us:

  • We are getting drizzle-orm into a new good shape where we can call it [email protected]!

Breaking changes:

  • We will have them, but we will have open channels for everyone building on top of drizzle types, so we can guide you through all the changes.

Third branch is adding support for CockroachDB and MSSQL dialects

Support for them is already in the alternation-engine branch and will be available together with the drizzle-kit rewrite.

Summary

All of the work we are doing is crucial and should be done sooner rather than later. We've received a lot of feedback and worked really hard to find the best strategies and decisions for API, DX, architecture, etc., so we can confidently mark it as v1 and be sure we can improve it and remain flexible for all the features you are asking for, while becoming even better for everyone building on top of the drizzle API as well.

We didn't want to stay with some legacy decisions and solutions we had, and instead wanted to shape Drizzle in a way that will be best looking ahead to 2025–2026 trends (v1 will get proper effect support, etc.).

We believe that all of the effort we've put in will boost Drizzle and benefit everyone using it.

Thanks everyone, as we said, we are here to stay for a long time to build a great tool together!

Timelines

We are hoping to get v1 for drizzle in beta this fall and same timeline for latest. Right after that we can go through all of the issues and PRs and resond everyone. v1 for drizzle should close ~70% of all the bug tickets we have, so on beta release we will start marking them as closed!

AndriiSherman avatar Aug 30 '25 18:08 AndriiSherman

@AndriiSherman @L-Mario564 any update with this fix in beta? just ran into the same issue. Is this part of the beta-branch I can test?

GwFreak01 avatar Oct 15 '25 04:10 GwFreak01