question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Postgres point type support for insert queries

See original GitHub issue

I am using kysely with the PostgresDialect configuration as

const db = new Kysely<Database>({
    dialect: new PostgresDialect({
      pool,
    }),
    plugins: [new CamelCasePlugin()],
  });

I am also using postgres point type to store coordinates, which is of the format (x,y).

The cool thing is that the point type is transformed on queries to an object as {x, y} which is way better to work with.

When inserting however like

db.insertInto("points").values({
   location: {x: 4.4, y: 5.5}
}).execute();

I get an error like

“invalid input syntax for type point: "{"x":4.4,"y":5.5}"”.

So I have to manually parse the datatype like

const location = {x: 4.4, y: 5.5};
// @ts-ignore
db.insertInto("points").values({
   location: `(${location.x},${location.y})`
}).execute();

which works correctly but introduces overhead and reduced typesafety.

Can we have the transformation also supported on insert or have a plugin at hand for this?

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
koskimascommented, Aug 9, 2022

I tried this and it works:

      interface Point {
        x: number
        y: number
      }

      class PointPlugin implements KyselyPlugin {
        readonly #transformer = new PointTransformer()

        transformQuery(args: PluginTransformQueryArgs): RootOperationNode {
          return this.#transformer.transformNode(args.node)
        }

        transformResult(
          args: PluginTransformResultArgs
        ): Promise<QueryResult<UnknownRow>> {
          return Promise.resolve(args.result)
        }
      }

      class PointTransformer extends OperationNodeTransformer {
        protected transformValue(node: ValueNode): ValueNode {
          return {
            ...node,
            value: isPoint(node.value) ? mapPoint(node.value) : node.value,
          }
        }

        protected transformPrimitiveValueList(
          node: PrimitiveValueListNode
        ): PrimitiveValueListNode {
          return {
            ...node,
            values: node.values.map((it) => (isPoint(it) ? mapPoint(it) : it)),
          }
        }
      }

      function mapPoint(point: Point): string {
        return `(${point.x}, ${point.y})`
      }

      function isPoint(point: unknown): point is Point {
        return (
          typeof point === 'object' && !!point && 'x' in point && 'y' in point
        )
      }

      const db = new Kysely<DB>({ dialect: ..., plugins: [new PointPlugin()]})

This should actually work in all situations for that I can think of.

0reactions
lovis-ffcommented, Aug 10, 2022

That works well. Thanks for the update!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Insert POINT into postgres database - Stack Overflow
This works if you write SQL "directly": CREATE TEMP TABLE x(p point) ; INSERT INTO x VALUES ('(1,2)'); INSERT INTO x VALUES (point(3,...
Read more >
Using point data type in insert statement - PostgreSQL
1. Create table with point data type. 2. Use Point data type in insert statement. 3. Using Point data type in a function ......
Read more >
Documentation: 15: INSERT - PostgreSQL
INSERT inserts new rows into a table. One can insert one or more rows specified by value expressions, or zero or more rows...
Read more >
PostgreSQL Data Types: Point
Continuing our series of PostgreSQL Data Types today we're going to introduce the PostgreSQL Point type. In order to put the Point datatype...
Read more >
Insert point into point column in postgres/postgis
INSERT INTO points(coordinates) VALUES (ST_GeomFromText('POINT(10.809003 54.097834)',4326)); ERROR: column "coordinates" is of type point but ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found