jfgodoy / knex-postgis

postgis extension for knex
MIT License
183 stars 25 forks source link

geomFromGeoJSON #33

Closed carolspirit closed 5 years ago

carolspirit commented 5 years ago

I use 'geom' : st.setSRID(st.geomFromGeoJSON({"type":"Point","coordinates":[39.915272,116.4792]}),4326) and the result is image but the geojson is SELECT ST_AsText(ST_GeomFromGeoJSON('{"type":"Point","coordinates":[-48.23456,20.12345]}')) As wkt;

lost the single quotes。。。。 so can't insert the table...

jfgodoy commented 5 years ago

hi @carolspirit, I can't understand your issue. Can you explain it more clearly? or even better, provide an example to reproduce it.

carolspirit commented 5 years ago

@jfgodoy , I want to insert data like this, const knex = require('knex'); const knexPostgis = require('knex-postgis'); const db = knex({ client: 'postgres' }); const st = knexPostgis(db); const fields = { 'geom' : st.setSRID(st.geomFromGeoJSON({"type":"Point","coordinates":[104.19499969482,35.861698150635]}),4326) }; const sql = db.insert(fields).into('nodes').toString(); console.log(sql);

the console result is

insert into "nodes" ("geom") values (ST_SetSRID(ST_geomFromGeoJSON({"type":"Point","coordinates":[104.19499969482,35.861698150635]}), 4326))

but this sql can't insert the table nodes;

ERROR: syntax error at or near "{" LINE 1: ...s" ("geom") values (ST_SetSRID(ST_geomFromGeoJSON({"type":"P...

from the https://postgis.net/docs/ST_GeomFromGeoJSON.html I kown that the right way is

ST_AsText(ST_GeomFromGeoJSON('{"type":"Point","coordinates":[-48.23456,20.12345]}'))

lost the single quotes. I don't know if I express it clearly.Thank u very much.

jfgodoy commented 5 years ago

hi @carolspirit, Now I understood your issue. The problem happens when you use .toString to generate the sql because it generates an invalid sql.

Even if the sql generated is invalid, the current implementation inserts the point correctly because knex sends pg a parametrized query:

sql:  'insert into "nodes" ("geom") values (ST_SetSRID(ST_geomFromGeoJSON(?), ?))',
bindings:  [ { type: 'Point', coordinates: [104.19499969482,35.861698150635] }, 4326 ]

I created a PR that fixes the sql generated. Could you test it please?

carolspirit commented 5 years ago

Thanks. Tested the code and could insert to the database as expected.

jfgodoy commented 5 years ago

thank you @carolspirit. I just published knex-postgis@0.8.1 with the fix