PostgreSQL PL/pgSQL – Syntax Error at or Near ‘IF’

plpgsqlpostgresqlstored-procedures

I try to create a sp that checks if a job that didn't started already exists and if not creates a new one. It should return the id of the job.
For now I have the following code:

CREATE OR REPLACE FUNCTION 
public.create_category_training_job(category_id integer) RETURNS integer AS
$BODY$
-- check if a job for this category is already queued and not started
DECLARE job_id Integer := (SELECT id FROM category_training_jobs WHERE startdate IS NULL);
-- if a not started job is present return the id it
IF job_id IS NOT NULL THEN
    RETURN job_id;
-- if id is not present create a new job and return its id
ELSE    
    (INSERT INTO 
        category_training_jobs (category_id, submissiondate, startdate, enddate)
     VALUES
        (category_id, NOW(), NULL, NULL)
     RETURNING id);
END IF;
$BODY$
LANGUAGE plpgsql VOLATILE NOT LEAKPROOF
COST 100;

For some rease I get "ERROR: syntax error at or near "IF"
LINE 6: IF job_id IS NOT NULL THEN"

As far as I know IS NOT NULL should be a boolean expression, so it should be a valid expression. Am I missing something?

Best Answer

You are missing a BEGIN and END around your body:

REPLACE FUNCTION create_category_training_job(category_id integer) 
  RETURNS integer 
AS
$BODY$
-- check if a job for this category is already queued and not started
DECLARE 
  job_id Integer := (SELECT id FROM category_training_jobs WHERE startdate IS NULL);
BEGIN --<<<< HERE

  -- if a not started job is present return the id it
  IF job_id IS NOT NULL THEN
      RETURN job_id;
  -- if id is not present create a new job and return its id
  ELSE    
      INSERT INTO 
          category_training_jobs (category_id, submissiondate, startdate, enddate)
       VALUES
          (category_id, NOW(), NULL, NULL)
       RETURNING id;
  END IF;

END; --<<<< AND HERE
$BODY$
LANGUAGE plpgsql;

The parentheses around your insert are useless noise as well, you should remove them.

Related Question