darold / pgFormatter

A PostgreSQL SQL syntax beautifier that can work as a console program or as a CGI. On-line demo site at http://sqlformat.darold.net/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Improper formatting for `TRIGGER`s when `OR REPLACE` is used

hexcowboy opened this issue · comments

When formatting a trigger, using OR REPLACE will cause bad indentation.

Here's a fully reproducible file with the two behaviors marked with comments:

create table if not exists my_table (
  id serial primary key,
  updated_at timestamp not null default now()
);

create or replace function trigger_set_timestamp ()
  returns trigger
  language plpgsql
  as $$
begin
  new.updated_at := current_timestamp;
  return new;
end;
$$;

-- Improper indentation with `OR REPLACE`
create or replace trigger set_timestamp before update on my_table for each row execute function trigger_set_timestamp ();

-- Proper indentation without `OR REPLACE`
create trigger set_timestamp
  before update on my_table for each row
  execute function trigger_set_timestamp ();

What are the pg_format option you are using and the version? With current development code I'm not able to reproduce, here is the formatted output:

CREATE TABLE IF NOT EXISTS my_table (
    id serial PRIMARY KEY,
    updated_at timestamp NOT NULL DEFAULT now()
);

CREATE OR REPLACE FUNCTION trigger_set_timestamp ()
    RETURNS TRIGGER
    LANGUAGE plpgsql
    AS $$
BEGIN
    NEW.updated_at := CURRENT_TIMESTAMP;
    RETURN new;
END;
$$;

@darold tried with both the binary i had instealled from brew (5.3) and the main branch (also 5.3)

the issue is the create or replace trigger bit:

$ pg_format example.sql

CREATE TABLE IF NOT EXISTS my_table (
    id serial PRIMARY KEY,
    updated_at timestamp NOT NULL DEFAULT now()
);

CREATE OR REPLACE FUNCTION trigger_set_timestamp ()
    RETURNS TRIGGER
    LANGUAGE plpgsql
    AS $$
BEGIN
    NEW.updated_at := CURRENT_TIMESTAMP;
    RETURN new;
END;
$$;

-- Improper indentation with `OR REPLACE`
CREATE OR REPLACE TRIGGER set_timestamp BEFORE UPDATE ON my_table FOR EACH ROW EXECUTE FUNCTION trigger_set_timestamp ();
-- ^ issue here, no indentation provided

Can you attach the example.sql file please.

Can you attach the example.sql file please.

It's the same as the code block I attached :)

Issue is commented on the bottom for visibility

Ah ok, I was missing the trigger part in my copy/paste. I can reproduce.

Commit 2212788 fixes this issue. Thanks.