THX1138
THX1138

Reputation: 1776

Spatial Data SQL Reprojection Function issues

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!

Upvotes: 0

Views: 351

Answers (1)

Erwin Brandstetter
Erwin Brandstetter

Reputation: 657052

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.

Upvotes: 4

Related Questions