I set up an API where on client side user can calculate a route between to points. However, I have trouble with the psql query, which works in postgres but when I use the same query in node JS I got an error.
I am using nodeJS, Express and Postgres. If I run the query below in pgAdmin4, I get the expected output.
SELECT b.gid, b.the_geom, b.cost_s, b.length_m FROM pgr_dijkstra('SELECT gid::bigint as id, source::bigint,
target::bigint, cost_s::double precision as cost,
reverse_cost_s::double precision as reverse_cost FROM ways
WHERE the_geom && ST_Expand((SELECT ST_Collect(the_geom)
FROM ways_vertices_pgr WHERE id IN(589143, 581050)), 0.01)',
589143, 581050) a LEFT JOIN ways b ON (a.edge = b.gid);
But when I use the same query in Node Js (see below), I get an error message saying error: syntax error at or near "&&"
. What am I doing wrong?
const start = parseInt(request.params.start)
const end = parseInt(request.params.end)
const sql2 =
"SELECT b.gid, b.the_geom, b.cost_s, b.length_m FROM pgr_dijkstra('SELECT gid::bigint as id, source::bigint,"+
"target::bigint, cost_s::double precision as cost," +
"reverse_cost_s::double precision as reverse_cost FROM ways" +
"WHERE the_geom && ST_Expand((SELECT ST_Collect(the_geom)" +
"FROM ways_vertices_pgr WHERE id IN(" + start + "," + end + ")), 0.01)'," +
start + "," + end + ") a LEFT JOIN ways b ON (a.edge = b.gid);"
Got the answer. Instead of start
and end
I used arguments using the syntax $1
...and added the data type of the arguments. In my case ineteger
SELECT b.gid, b.the_geom, b.cost_s, b.length_m FROM pgr_dijkstra('SELECT gid::bigint as id, source::bigint,
target::bigint, cost_s::double precision as cost,
reverse_cost_s::double precision as reverse_cost FROM ways
WHERE the_geom && ST_Expand((SELECT ST_Collect(the_geom)
FROM ways_vertices_pgr WHERE id IN(' || $1::integer || ',' || $2::integer ||')), 0.01)',
$1::integer, $2::integer) a LEFT JOIN ways b ON (a.edge = b.gid);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.