Passing array of custom type to postgres function from node-pg and SQL injection

好久不见. 提交于 2020-01-03 03:06:06

问题


CREATE TYPE phototable AS (
    photoid integer,
    parentid integer,
    fileextension character varying(20),
    description text,
    tag character varying(100)
);

CREATE FUNCTION addphotos(
          p_placeid integer
        , p_permissiontypeid integer
        , p_description text DEFAULT NULL::text
        , p_photos phototable[] DEFAULT NULL::phototable[]) 

BEGIN
........
END

I am calling this function from node.js (using node-postres) by generating an SQL query. I want to avoid it and want to use parameterized queries because I think it is not secure against SQL injection attacks. I was not able to find a way to pass custom type array to the query method of node-postgres. Is there a way to pass custom type array to the query function of node-postgres?

Query:

select * from addphotos(p_placeid:=2210, p_permissiontypeid:=2, p_description:='Party', 
p_photos:=array[row(null, null,'.JPG','smart','6e8f74b2-4c14-4f40-ae19-8abae026a539'),
row(null, null,'.JPG',null,'c4e9f75f-25fa-4893-82f1-44c4791d58e5')]::phototable[]);

回答1:


I am not familiar with node.js, but you could provide a string literal for your column p_photos instead of the ARRAY and ROW constructors (which are functions that need to be executed at the Postgres side!). Your query would look like this:

SELECT * FROM addphotos(
    p_placeid := 2210
  , p_permissiontypeid := 2
  , p_description := 'Party'
  , p_photos:='{"(,,.JPG,smart,6e8f74b2-4c14-4f40-ae19-8abae026a539)"
               ,"(,,.JPG,,c4e9f75f-25fa-4893-82f1-44c4791d58e5)"}'::phototable[]
    );

Should even work without explicit cast:

SELECT * FROM addphotos(
    p_placeid := 2210
  , p_permissiontypeid := 2
  , p_description := 'Party'
  , p_photos:='{"(,,.JPG,smart,6e8f74b2-4c14-4f40-ae19-8abae026a539)"
               ,"(,,.JPG,,c4e9f75f-25fa-4893-82f1-44c4791d58e5)"}'
    );

The fast and simple way to "rewrite" your syntax to a string literal: let Postgres do it:

SELECT array[row(null, null,'.JPG','smart','6e8f74b2-4c14-4f40-ae19-8abae026a539'),
             row(null, null,'.JPG',null,'c4e9f75f-25fa-4893-82f1-44c4791d58e5')]::phototable[]

Returns the string representation I used above:



来源:https://stackoverflow.com/questions/20384035/passing-array-of-custom-type-to-postgres-function-from-node-pg-and-sql-injection

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