Search code examples
postgresqlplpgsql

ERROR: syntax error at or near "QUERY" QUERY EXECUTE 'set enable_parallel_append = off';


I have below plpgsql function -

CREATE OR REPLACE FUNCTION public.end_to_end_query(part_id integer)
 LANGUAGE plpgsql IMMUTABLE
AS $function$
DECLARE
  query_pw varchar := format(
    $dynsql$
    ALTER TABLE metric_events_%s SET (parallel_workers = 16)
    $dynsql$, part_id
  );

BEGIN
    RAISE NOTICE 'Value: %', query;
    QUERY EXECUTE 'set enable_parallel_append = off';
    QUERY EXECUTE "SET work_mem TO '1GB'";
    QUERY EXECUTE query_pw;
    QUERY EXECUTE "SET max_parallel_workers_per_gather = 16";
    QUERY EXECUTE "set max_worker_processes=8";
END $function$;

When I run the above function, I get the error -

ERROR: syntax error at or near "QUERY"

LINE 13: QUERY EXECUTE 'set enable_parallel_append = off'; ^

SQL state: 42601

Character: 1419

How can I fix this error?


Solution

  • query execute is not a valid SQL command, you just need to call execute:

    CREATE OR REPLACE FUNCTION public.end_to_end_query(part_id integer)
     LANGUAGE plpgsql IMMUTABLE
    AS $function$
    DECLARE
      query_pw varchar := format(
        $dynsql$
        ALTER TABLE metric_events_%s SET (parallel_workers = 16)
        $dynsql$, part_id
      );
    
    BEGIN
        RAISE NOTICE 'Value: %', query;
        EXECUTE 'set enable_parallel_append = off';
        EXECUTE 'SET work_mem TO ''1GB''';
        EXECUTE query_pw;
        EXECUTE "SET max_parallel_workers_per_gather = 16";
        EXECUTE "set max_worker_processes=8";
    END $function$;