Klaus Nji
Klaus Nji

Reputation: 18857

PL/pgSQL CREATE or REPLACE within EXECUTE

I have the following script to dynamically create views into a PostgreSQL database.

CREATE OR REPLACE FUNCTION cs_refresh_mviews() RETURNS integer AS $$
DECLARE
    mviews RECORD;
    query text;
    park_name text;
    ppstatements int;
BEGIN
    RAISE NOTICE 'Creating views...';

    FOR mviews IN SELECT name FROM "Canadian_Parks" LOOP
        park_name := mviews.name;
        RAISE NOTICE 'Creating or replace view %s...', mviews.name; 
        query := 'CREATE OR REPLACE VIEW %_view AS
          SELECT * from "Canadian_Parks" where name=''%'';
          ALTER TABLE %_view OWNER TO postgres', park_name, park_name, park_name;
      --  RAISE NOTICE query;
        EXECUTE query;
    END LOOP;

    RAISE NOTICE 'Done refreshing materialized views.';
    RETURN 1;
END;
$$ LANGUAGE plpgsql;

I have confirmed integrity of the string, such as

CREATE OR REPLACE VIEW Saguenay_St__Lawrence_view AS
SELECT * from "Canadian_Parks" where name='Saguenay_St__Lawrence';
ALTER TABLE Saguenay_St__Lawrence_view OWNER TO postgres

assigned to the query variable by manually submitting this to the database and getting a successful response.

However, if I attempt to execute the function using

SELECT cs_refresh_mviews();

the followig error is displayed:

ERROR:  query "SELECT 'CREATE OR REPLACE VIEW %_view AS SELECT * from "Canadian_Parks" where name=''%''; ALTER TABLE %_view OWNER TO postgres', park_name, park_name, park_name" returned 4 columns
CONTEXT:  PL/pgSQL function "cs_refresh_mviews" line 32 at assignment

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

ERROR: query "SELECT 'CREATE OR REPLACE VIEW %_view AS SELECT * from "Canadian_Parks" where name=''%''; ALTER TABLE %_view OWNER TO postgres', park_name, park_name, park_name" returned 4 columns
SQL state: 42601
Context: PL/pgSQL function "cs_refresh_mviews" line 32 at assignment

Why has this been converted to a SELECT statement, instead of a pure CREATE?

Upvotes: 2

Views: 4539

Answers (2)

Erwin Brandstetter
Erwin Brandstetter

Reputation: 658032

You setup is pretty twisted. Why would you save part of the name of a view in a composite type of a table instead of saving it in a plain text column?

Anyhow, it could work like this:

Setup matching question:

CREATE SCHEMA x;  -- demo in test schema
SET search_path = x;
CREATE TYPE mviews AS (id int, name text); -- composite type used in table

CREATE TABLE "Canadian_Parks" (name mviews);
INSERT INTO "Canadian_Parks"(name) VALUES
 ('(1,"canadian")')
,('(2,"islandic")');  -- composite types, seriously?

SELECT name, (name).* from "Canadian_Parks";

CREATE OR REPLACE FUNCTION cs_refresh_mviews()
  RETURNS int LANGUAGE plpgsql SET search_path = x AS  -- search_path for test
$func$
DECLARE
    _parkname text;
BEGIN

FOR _parkname IN SELECT (name).name FROM "Canadian_Parks" LOOP
   EXECUTE format('
      CREATE OR REPLACE VIEW %1$I AS
      SELECT * FROM "Canadian_Parks" WHERE (name).name = %2$L;
      ALTER TABLE %1$I OWNER TO postgres'
      , _parkname || '_view', _parkname);
END LOOP;

RETURN 1;

END
$func$;

SELECT cs_refresh_mviews();

DROP SCHEMA x CASCADE; -- clean up

Major points

  • As you are executing text with execute, you need to safeguard against SQL injection. I use the format() function for identifiers and the literal

  • I use the syntax SELECT (name).name to cope with your weird setup and extract the name we need right away.

  • Similarly, the VIEW needs to read WHERE (name).name = .. to work in this setup.

  • I removed a lot of noise that is irrelevant to the question.

  • It's also probably pointless to have the function RETURN 1. Just define the function with RETURNS void. I kept it, though, to match the question.

Untangled setup

How it probably should be:

CREATE SCHEMA x;
SET search_path = x;

CREATE TABLE canadian_parks (id serial primary key, name text);
INSERT INTO canadian_parks(name) VALUES ('canadian'), ('islandic');

SELECT * from canadian_parks;

CREATE OR REPLACE FUNCTION cs_refresh_mviews()
  RETURNS void LANGUAGE plpgsql SET search_path = x AS
$func$
DECLARE
    parkname text;
BEGIN

FOR parkname IN SELECT name FROM canadian_parks LOOP
   EXECUTE format('
      CREATE OR REPLACE VIEW %1$I AS
      SELECT * FROM canadian_parks WHERE name = %2$L;
      ALTER TABLE %1$I OWNER TO postgres'
      , parkname || '_view', parkname);
END LOOP;

END
$func$;

SELECT cs_refresh_mviews();

DROP SCHEMA x CASCADE;

Upvotes: 4

SadSamurai
SadSamurai

Reputation: 111

You've misunderstood usage of commas in assignment expression. It turns query to array (RECORD) instead of scalar. Use concatenation:

park_name := quote_ident(mviews.name||'_view');
query := 'CREATE OR REPLACE VIEW '||park_name||' AS SELECT * from "Canadian_Parks" where name='||quote_literal(mviews.name)||'; ALTER TABLE '||park_name||' OWNER TO postgres';

Upvotes: 2

Related Questions