Insert POINT into postgres database
I recently came across a similar problem using node-postgres
when inserting into a postgis
database with a geography (point) column. My solution was to use:
pool.query("INSERT INTO table (name, geography) VALUES ($1, ST_SetSRID(ST_POINT($2, $3), 4326))",
[req.body.name, req.body.lat, req.body.lng ]);
Current versions (Postgres 12, pg 8) should work simply use Postgres's POINT function to set a point column value.
Example:
export async function setPoint(client, x, y, id) {
const sql = `UPDATE table_name SET my_point = POINT($1,$2) WHERE id = $3 RETURNING my_point`;
const result = await client.query(sql, [x, y, id]);
return result.rows[0];
}
await setPoint(client, 10, 20, 5);
Result:
{x: 10.0, y: 20.0}
After couple of combinations, found out this works.!!
( '(' + req.body.places.point.x + ',' + req.body.places.point.y +')' )
Posting as answer if someone is trying to do this just using node-postgres
.
So you can use single-quoted points: insert into x values ( '(1,2)' );
But using insert into x values (point(1,2));
in the query does not work.
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, 4));
SELECT * FROM x ;
Results
(1,2)
(3,4)