Spatial Data SQL Reprojection Function issues

放肆的年华 提交于 2019-12-13 05:47:07

问题


Hello I am just learning postGIS and thus postgresql (9.1) and am trying to save some time copying the same code over and over by creating an sql function to reproject some spatial data.

Create Function reproject_shapefile(text,text,numeric) returns void as $$

    -- Reprojects shapefiles given that they follow the pattern "gid * the_geom"

    CREATE TABLE $2 AS
        SELECT *, ST_Transform(the_geom,$3) AS the_geom2
        FROM $1;
    Alter table $2 add Primary Key (gid);
    Alter table $2 drop column the_geom;
    Alter table $2 rename column the_geom2 to the_geom;
$$ Language SQL;

I read over the docs specifying how to do this, but everytime I try to create the function from the sql editor in pgAdmin, I receive the following error:

ERROR:  syntax error at or near "$2"
LINE 5:     CREATE TABLE $2 AS
                     ^

********** Error **********

ERROR: syntax error at or near "$2"
SQL state: 42601
Character: 175

Unlike the error messages in python, this tells me absolutely nothing of use, so I am hoping that someone can point me in the right direction on how to fix this error.

If there is some way to perform this same function using python feel free to post that as a solution instead/ as well, as python syntax is much easier for me to understand than ancient SQL.

Any help would be greatly appreciated!


回答1:


You can not write dynamic SQL in this form. Parameters can only pass in values, not identifiers. Something like this is impossible in an SQL function:

CREATE TABLE $2 AS

You need to write a plpgsql function for that and use EXECUTE. Could look like this:

CREATE OR REPLACE FUNCTION reproject_shapefile(text, text, numeric)
  RETURNS void as $$
BEGIN

EXECUTE '
   CREATE TABLE ' || quote_ident($2) || ' AS
   SELECT *, ST_Transform(the_geom,$1) AS the_geom2
   FROM  ' || quote_ident($1)
USING $3;

EXECUTE 'ALTER TABLE ' || quote_ident($2) || ' ADD PRIMARY KEY (gid)';
EXECUTE 'ALTER TABLE ' || quote_ident($2) || ' DROP COLUMN the_geom';
EXECUTE 'ALTER TABLE ' || quote_ident($2) || ' RENAME column the_geom2 TO the_geom';

END;
$$ Language plpgsql;

Major points

  • plpgsql function, not sql
  • EXECUTE any query with dynamic identifiers
  • use quote_ident to safeguard against SQLi
  • pass in values with the USING clause to avoid casting and quoting madness.


来源:https://stackoverflow.com/questions/8044006/spatial-data-sql-reprojection-function-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!