CREATE EXTENSION dblink;
CREATE EXTENSION pgrowlocks;

DO $$
BEGIN
	IF EXISTS (SELECT 1 FROM pg_proc WHERE oid = 'pgrowlocks'::regproc AND 'modes' = ANY (proargnames)) THEN
		CREATE OR REPLACE VIEW remote_rowlocks AS
		SELECT * FROM dblink('dbname=' || current_database(),
			$q$SELECT * FROM pgrowlocks('test_rowlock')$q$)
			AS t(locked_row tid, lock_type text, locker xid, multi boolean,
			     xids xid[], modes text[], pids integer[]);
	ELSE
		CREATE OR REPLACE VIEW remote_rowlocks AS
		SELECT * FROM dblink('dbname=' || current_database(),
			$q$SELECT * FROM pgrowlocks('test_rowlock')$q$)
			AS t(locked_row tid, lock_type text, locker xid, multi boolean,
			     xids xid[], pids integer[]);
	END IF;
END
$$;

DROP TABLE IF EXISTS test_rowlock;
CREATE TABLE test_rowlock (key_col int PRIMARY KEY, non_key_col int);
INSERT INTO test_rowlock VALUES (1,10);

BEGIN;
SELECT * FROM test_rowlock FOR KEY SHARE;
SELECT * FROM remote_rowlocks;
ROLLBACK;

BEGIN;
SELECT * FROM test_rowlock FOR SHARE;
SELECT * FROM remote_rowlocks;
ROLLBACK;

BEGIN;
SELECT * FROM test_rowlock FOR UPDATE;
SELECT * FROM remote_rowlocks;
ROLLBACK;

BEGIN;
UPDATE test_rowlock SET non_key_col = 11;
SELECT * FROM remote_rowlocks;
ROLLBACK;

BEGIN;
UPDATE test_rowlock SET key_col = 2;
SELECT * FROM remote_rowlocks;
ROLLBACK;
