DROP EXTENSION postgres_fdw CASCADE;
DROP table t1;
CREATE EXTENSION postgres_fdw;

CREATE table t1 (
  c1 varchar,
  c2 varchar
);

CREATE SERVER local_postgres FOREIGN DATA WRAPPER postgres_fdw
OPTIONS(
  dbname 'postgres'
);
CREATE USER MAPPING FOR postgres SERVER local_postgres;

CREATE FOREIGN TABLE ft1 (
  c1 varchar,
  c2 varchar
) SERVER local_postgres
OPTIONS (
  table_name 't1'
);

CREATE OR REPLACE FUNCTION test_trig_ins() RETURNS TRIGGER AS $$
  BEGIN
    RAISE NOTICE '% % %', TG_WHEN, TG_OP, TG_LEVEL;
    RAISE NOTICE 'NEW: %', NEW;
    RETURN NEW;
  END
$$ language plpgsql;

CREATE OR REPLACE FUNCTION test_trig_del() RETURNS TRIGGER AS $$
  BEGIN
    RAISE NOTICE '% % %', TG_WHEN, TG_OP, TG_LEVEL;
    RAISE NOTICE 'OLD: %', OLD;
    RETURN OLD;
  END
$$ language plpgsql;

CREATE OR REPLACE FUNCTION test_trig_upd() RETURNS TRIGGER AS $$
  BEGIN
    RAISE NOTICE '% % %', TG_WHEN, TG_OP, TG_LEVEL;
    RAISE NOTICE 'OLD: % NEW: %', OLD, NEW;
    RETURN NEW;
  END
$$ language plpgsql;

CREATE OR REPLACE FUNCTION test_trig_stmt() RETURNS TRIGGER AS $$
  BEGIN
    RAISE NOTICE '% % %', TG_WHEN, TG_OP, TG_LEVEL;
    RETURN NULL;
  END
$$ language plpgsql;

CREATE TRIGGER test_row_before_ins  BEFORE INSERT ON ft1 FOR EACH ROW       EXECUTE PROCEDURE test_trig_ins();
CREATE TRIGGER test_row_before_upd  BEFORE UPDATE ON ft1 FOR EACH ROW       EXECUTE PROCEDURE test_trig_upd();
CREATE TRIGGER test_row_before_del  BEFORE DELETE ON ft1 FOR EACH ROW       EXECUTE PROCEDURE test_trig_del();


CREATE TRIGGER test_row_after_ins  AFTER INSERT ON ft1 FOR EACH ROW       EXECUTE PROCEDURE test_trig_ins();
CREATE TRIGGER test_row_after_upd  AFTER UPDATE ON ft1 FOR EACH ROW       EXECUTE PROCEDURE test_trig_upd();
CREATE TRIGGER test_row_after_del  AFTER DELETE ON ft1 FOR EACH ROW       EXECUTE PROCEDURE test_trig_del();

CREATE TRIGGER test_stmt_before    BEFORE DELETE OR INSERT OR UPDATE ON ft1 FOR EACH STATEMENT EXECUTE PROCEDURE test_trig_stmt();
CREATE TRIGGER test_stmt_after     AFTER DELETE OR INSERT OR UPDATE ON ft1 FOR EACH STATEMENT EXECUTE PROCEDURE test_trig_stmt();


INSERT INTO ft1 (c1) VALUES ('test C1');
INSERT INTO ft1 (c2) VALUES ('test C2');

UPDATE ft1 set c1 = coalesce(c1, '') || ' update';

DELETE from ft1;
