2000-01-09 04:48:39 +01:00
--
-- RULES
-- From Jan's original setup_ruletest.sql and run_ruletest.sql
-- - thomas 1998-09-13
--
--
-- Tables and rules for the view test
--
create table rtest_t1 (a int4, b int4);
create table rtest_t2 (a int4, b int4);
create table rtest_t3 (a int4, b int4);
create view rtest_v1 as select * from rtest_t1;
create rule rtest_v1_ins as on insert to rtest_v1 do instead
1998-09-16 16:35:37 +02:00
insert into rtest_t1 values (new.a, new.b);
2000-01-09 04:48:39 +01:00
create rule rtest_v1_upd as on update to rtest_v1 do instead
1998-09-16 16:35:37 +02:00
update rtest_t1 set a = new.a, b = new.b
1999-02-08 15:14:32 +01:00
where a = old.a;
2000-01-09 04:48:39 +01:00
create rule rtest_v1_del as on delete to rtest_v1 do instead
1999-02-08 15:14:32 +01:00
delete from rtest_t1 where a = old.a;
2003-11-21 23:32:49 +01:00
-- Test comments
COMMENT ON RULE rtest_v1_bad ON rtest_v1 IS 'bad rule';
ERROR: rule "rtest_v1_bad" for relation "rtest_v1" does not exist
COMMENT ON RULE rtest_v1_del ON rtest_v1 IS 'delete rule';
COMMENT ON RULE rtest_v1_del ON rtest_v1 IS NULL;
2000-01-09 04:48:39 +01:00
--
-- Tables and rules for the constraint update/delete test
--
-- Note:
-- Now that we have multiple action rule support, we check
-- both possible syntaxes to define them (The last action
-- can but must not have a semicolon at the end).
--
create table rtest_system (sysname text, sysdesc text);
create table rtest_interface (sysname text, ifname text);
create table rtest_person (pname text, pdesc text);
create table rtest_admin (pname text, sysname text);
2004-03-09 06:05:41 +01:00
create rule rtest_sys_upd as on update to rtest_system do also (
2010-11-23 21:27:50 +01:00
update rtest_interface set sysname = new.sysname
1999-02-08 15:14:32 +01:00
where sysname = old.sysname;
2010-11-23 21:27:50 +01:00
update rtest_admin set sysname = new.sysname
1999-02-08 15:14:32 +01:00
where sysname = old.sysname
1999-02-07 20:02:20 +01:00
);
2004-03-09 06:05:41 +01:00
create rule rtest_sys_del as on delete to rtest_system do also (
1999-02-08 15:14:32 +01:00
delete from rtest_interface where sysname = old.sysname;
delete from rtest_admin where sysname = old.sysname;
1999-02-07 20:02:20 +01:00
);
2004-03-09 06:05:41 +01:00
create rule rtest_pers_upd as on update to rtest_person do also
1999-02-08 15:14:32 +01:00
update rtest_admin set pname = new.pname where pname = old.pname;
2004-03-09 06:05:41 +01:00
create rule rtest_pers_del as on delete to rtest_person do also
1999-02-08 15:14:32 +01:00
delete from rtest_admin where pname = old.pname;
2000-01-09 04:48:39 +01:00
--
-- Tables and rules for the logging test
--
create table rtest_emp (ename char(20), salary money);
create table rtest_emplog (ename char(20), who name, action char(10), newsal money, oldsal money);
create table rtest_empmass (ename char(20), salary money);
create rule rtest_emp_ins as on insert to rtest_emp do
1998-09-16 16:35:37 +02:00
insert into rtest_emplog values (new.ename, current_user,
'hired', new.salary, '0.00');
2000-01-09 04:48:39 +01:00
create rule rtest_emp_upd as on update to rtest_emp where new.salary != old.salary do
1998-09-16 16:35:37 +02:00
insert into rtest_emplog values (new.ename, current_user,
1999-02-08 15:14:32 +01:00
'honored', new.salary, old.salary);
2000-01-09 04:48:39 +01:00
create rule rtest_emp_del as on delete to rtest_emp do
1999-02-08 15:14:32 +01:00
insert into rtest_emplog values (old.ename, current_user,
'fired', '0.00', old.salary);
2000-01-09 04:48:39 +01:00
--
-- Tables and rules for the multiple cascaded qualified instead
2010-11-23 21:27:50 +01:00
-- rule test
2000-01-09 04:48:39 +01:00
--
create table rtest_t4 (a int4, b text);
create table rtest_t5 (a int4, b text);
create table rtest_t6 (a int4, b text);
create table rtest_t7 (a int4, b text);
create table rtest_t8 (a int4, b text);
create table rtest_t9 (a int4, b text);
create rule rtest_t4_ins1 as on insert to rtest_t4
1998-09-16 16:35:37 +02:00
where new.a >= 10 and new.a < 20 do instead
insert into rtest_t5 values (new.a, new.b);
2000-01-09 04:48:39 +01:00
create rule rtest_t4_ins2 as on insert to rtest_t4
1998-09-16 16:35:37 +02:00
where new.a >= 20 and new.a < 30 do
insert into rtest_t6 values (new.a, new.b);
2000-01-09 04:48:39 +01:00
create rule rtest_t5_ins as on insert to rtest_t5
1998-09-16 16:35:37 +02:00
where new.a > 15 do
insert into rtest_t7 values (new.a, new.b);
2000-01-09 04:48:39 +01:00
create rule rtest_t6_ins as on insert to rtest_t6
1998-09-16 16:35:37 +02:00
where new.a > 25 do instead
insert into rtest_t8 values (new.a, new.b);
2000-01-09 04:48:39 +01:00
--
-- Tables and rules for the rule fire order test
--
2002-10-19 21:00:47 +02:00
-- As of PG 7.3, the rules should fire in order by name, regardless
-- of INSTEAD attributes or creation order.
--
2000-01-09 04:48:39 +01:00
create table rtest_order1 (a int4);
create table rtest_order2 (a int4, b int4, c text);
create sequence rtest_seq;
create rule rtest_order_r3 as on insert to rtest_order1 do instead
1998-09-16 16:35:37 +02:00
insert into rtest_order2 values (new.a, nextval('rtest_seq'),
2002-10-19 21:00:47 +02:00
'rule 3 - this should run 3rd');
2000-01-09 04:48:39 +01:00
create rule rtest_order_r4 as on insert to rtest_order1
1998-09-16 16:35:37 +02:00
where a < 100 do instead
insert into rtest_order2 values (new.a, nextval('rtest_seq'),
2002-10-19 21:00:47 +02:00
'rule 4 - this should run 4th');
2000-01-09 04:48:39 +01:00
create rule rtest_order_r2 as on insert to rtest_order1 do
1998-09-16 16:35:37 +02:00
insert into rtest_order2 values (new.a, nextval('rtest_seq'),
2002-10-19 21:00:47 +02:00
'rule 2 - this should run 2nd');
2000-01-09 04:48:39 +01:00
create rule rtest_order_r1 as on insert to rtest_order1 do instead
1998-09-16 16:35:37 +02:00
insert into rtest_order2 values (new.a, nextval('rtest_seq'),
2002-10-19 21:00:47 +02:00
'rule 1 - this should run 1st');
2000-01-09 04:48:39 +01:00
--
-- Tables and rules for the instead nothing test
--
create table rtest_nothn1 (a int4, b text);
create table rtest_nothn2 (a int4, b text);
create table rtest_nothn3 (a int4, b text);
create table rtest_nothn4 (a int4, b text);
create rule rtest_nothn_r1 as on insert to rtest_nothn1
2001-07-10 01:50:32 +02:00
where new.a >= 10 and new.a < 20 do instead nothing;
2000-01-09 04:48:39 +01:00
create rule rtest_nothn_r2 as on insert to rtest_nothn1
1998-09-16 16:35:37 +02:00
where new.a >= 30 and new.a < 40 do instead nothing;
2000-01-09 04:48:39 +01:00
create rule rtest_nothn_r3 as on insert to rtest_nothn2
1998-09-16 16:35:37 +02:00
where new.a >= 100 do instead
insert into rtest_nothn3 values (new.a, new.b);
2000-01-09 04:48:39 +01:00
create rule rtest_nothn_r4 as on insert to rtest_nothn2
1998-09-16 16:35:37 +02:00
do instead nothing;
2000-01-09 04:48:39 +01:00
--
-- Tests on a view that is select * of a table
-- and has insert/update/delete instead rules to
-- behave close like the real table.
--
--
-- We need test date later
--
insert into rtest_t2 values (1, 21);
insert into rtest_t2 values (2, 22);
insert into rtest_t2 values (3, 23);
insert into rtest_t3 values (1, 31);
insert into rtest_t3 values (2, 32);
insert into rtest_t3 values (3, 33);
insert into rtest_t3 values (4, 34);
insert into rtest_t3 values (5, 35);
-- insert values
insert into rtest_v1 values (1, 11);
insert into rtest_v1 values (2, 12);
select * from rtest_v1;
a | b
---+----
1 | 11
2 | 12
1998-08-18 02:49:04 +02:00
(2 rows)
2000-01-09 04:48:39 +01:00
-- delete with constant expression
delete from rtest_v1 where a = 1;
select * from rtest_v1;
a | b
---+----
2 | 12
1998-08-18 02:49:04 +02:00
(1 row)
2000-01-09 04:48:39 +01:00
insert into rtest_v1 values (1, 11);
delete from rtest_v1 where b = 12;
select * from rtest_v1;
a | b
---+----
1 | 11
1998-08-18 02:49:04 +02:00
(1 row)
2000-01-09 04:48:39 +01:00
insert into rtest_v1 values (2, 12);
insert into rtest_v1 values (2, 13);
select * from rtest_v1;
a | b
---+----
1 | 11
2 | 12
2 | 13
1998-08-18 02:49:04 +02:00
(3 rows)
** Remember the delete rule on rtest_v1: It says
1999-02-08 15:14:32 +01:00
** DO INSTEAD DELETE FROM rtest_t1 WHERE a = old.a
1998-08-18 02:49:04 +02:00
** So this time both rows with a = 2 must get deleted
2000-01-09 04:48:39 +01:00
\p
** Remember the delete rule on rtest_v1: It says
** DO INSTEAD DELETE FROM rtest_t1 WHERE a = old.a
** So this time both rows with a = 2 must get deleted
\r
delete from rtest_v1 where b = 12;
select * from rtest_v1;
a | b
---+----
1 | 11
1998-08-18 02:49:04 +02:00
(1 row)
2000-01-09 04:48:39 +01:00
delete from rtest_v1;
-- insert select
insert into rtest_v1 select * from rtest_t2;
select * from rtest_v1;
a | b
---+----
1 | 21
2 | 22
3 | 23
1998-08-18 02:49:04 +02:00
(3 rows)
2000-01-09 04:48:39 +01:00
delete from rtest_v1;
-- same with swapped targetlist
insert into rtest_v1 (b, a) select b, a from rtest_t2;
select * from rtest_v1;
a | b
---+----
1 | 21
2 | 22
3 | 23
1998-08-18 02:49:04 +02:00
(3 rows)
2000-01-09 04:48:39 +01:00
-- now with only one target attribute
insert into rtest_v1 (a) select a from rtest_t3;
select * from rtest_v1;
a | b
---+----
1 | 21
2 | 22
3 | 23
1 |
2 |
3 |
4 |
5 |
1998-08-18 02:49:04 +02:00
(8 rows)
2000-01-09 04:48:39 +01:00
select * from rtest_v1 where b isnull;
a | b
---+---
1 |
2 |
3 |
4 |
5 |
1998-08-18 02:49:04 +02:00
(5 rows)
2000-01-09 04:48:39 +01:00
-- let attribute a differ (must be done on rtest_t1 - see above)
update rtest_t1 set a = a + 10 where b isnull;
delete from rtest_v1 where b isnull;
select * from rtest_v1;
a | b
---+----
1 | 21
2 | 22
3 | 23
1998-08-18 02:49:04 +02:00
(3 rows)
2000-01-09 04:48:39 +01:00
-- now updates with constant expression
update rtest_v1 set b = 42 where a = 2;
select * from rtest_v1;
a | b
---+----
1 | 21
3 | 23
2 | 42
1998-08-18 02:49:04 +02:00
(3 rows)
2000-01-09 04:48:39 +01:00
update rtest_v1 set b = 99 where b = 42;
select * from rtest_v1;
a | b
---+----
1 | 21
3 | 23
2 | 99
1998-08-18 02:49:04 +02:00
(3 rows)
2000-01-09 04:48:39 +01:00
update rtest_v1 set b = 88 where b < 50;
select * from rtest_v1;
a | b
---+----
2 | 99
1 | 88
3 | 88
1998-08-18 02:49:04 +02:00
(3 rows)
2000-01-09 04:48:39 +01:00
delete from rtest_v1;
2005-04-07 03:51:41 +02:00
insert into rtest_v1 select rtest_t2.a, rtest_t3.b
from rtest_t2, rtest_t3
where rtest_t2.a = rtest_t3.a;
2000-01-09 04:48:39 +01:00
select * from rtest_v1;
a | b
---+----
1 | 31
2 | 32
3 | 33
1998-08-18 02:49:04 +02:00
(3 rows)
2000-01-09 04:48:39 +01:00
-- updates in a mergejoin
2005-04-07 03:51:41 +02:00
update rtest_v1 set b = rtest_t2.b from rtest_t2 where rtest_v1.a = rtest_t2.a;
2000-01-09 04:48:39 +01:00
select * from rtest_v1;
a | b
---+----
1 | 21
2 | 22
3 | 23
1998-08-18 02:49:04 +02:00
(3 rows)
2000-01-09 04:48:39 +01:00
insert into rtest_v1 select * from rtest_t3;
select * from rtest_v1;
a | b
---+----
1 | 21
2 | 22
3 | 23
1 | 31
2 | 32
3 | 33
4 | 34
5 | 35
1998-08-18 02:49:04 +02:00
(8 rows)
2000-01-09 04:48:39 +01:00
update rtest_t1 set a = a + 10 where b > 30;
select * from rtest_v1;
a | b
----+----
1 | 21
2 | 22
3 | 23
11 | 31
12 | 32
13 | 33
14 | 34
15 | 35
1998-08-18 02:49:04 +02:00
(8 rows)
2005-04-07 03:51:41 +02:00
update rtest_v1 set a = rtest_t3.a + 20 from rtest_t3 where rtest_v1.b = rtest_t3.b;
2000-01-09 04:48:39 +01:00
select * from rtest_v1;
a | b
----+----
1 | 21
2 | 22
3 | 23
21 | 31
22 | 32
23 | 33
24 | 34
25 | 35
1998-08-18 02:49:04 +02:00
(8 rows)
2000-01-09 04:48:39 +01:00
--
-- Test for constraint updates/deletes
--
insert into rtest_system values ('orion', 'Linux Jan Wieck');
insert into rtest_system values ('notjw', 'WinNT Jan Wieck (notebook)');
insert into rtest_system values ('neptun', 'Fileserver');
insert into rtest_interface values ('orion', 'eth0');
insert into rtest_interface values ('orion', 'eth1');
insert into rtest_interface values ('notjw', 'eth0');
insert into rtest_interface values ('neptun', 'eth0');
insert into rtest_person values ('jw', 'Jan Wieck');
insert into rtest_person values ('bm', 'Bruce Momjian');
insert into rtest_admin values ('jw', 'orion');
insert into rtest_admin values ('jw', 'notjw');
insert into rtest_admin values ('bm', 'neptun');
update rtest_system set sysname = 'pluto' where sysname = 'neptun';
select * from rtest_interface;
sysname | ifname
---------+--------
orion | eth0
orion | eth1
notjw | eth0
pluto | eth0
1998-08-18 02:49:04 +02:00
(4 rows)
2000-01-09 04:48:39 +01:00
select * from rtest_admin;
pname | sysname
-------+---------
jw | orion
jw | notjw
bm | pluto
1998-08-18 02:49:04 +02:00
(3 rows)
2000-01-09 04:48:39 +01:00
update rtest_person set pname = 'jwieck' where pdesc = 'Jan Wieck';
-- Note: use ORDER BY here to ensure consistent output across all systems.
-- The above UPDATE affects two rows with equal keys, so they could be
-- updated in either order depending on the whim of the local qsort().
select * from rtest_admin order by pname, sysname;
pname | sysname
--------+---------
bm | pluto
jwieck | notjw
jwieck | orion
1998-08-18 02:49:04 +02:00
(3 rows)
2000-01-09 04:48:39 +01:00
delete from rtest_system where sysname = 'orion';
select * from rtest_interface;
sysname | ifname
---------+--------
notjw | eth0
pluto | eth0
1998-08-18 02:49:04 +02:00
(2 rows)
2000-01-09 04:48:39 +01:00
select * from rtest_admin;
pname | sysname
--------+---------
bm | pluto
jwieck | notjw
1998-08-18 02:49:04 +02:00
(2 rows)
2000-01-09 04:48:39 +01:00
--
-- Rule qualification test
--
2009-01-19 13:02:29 +01:00
insert into rtest_emp values ('wiecc', '5000.00');
2000-01-09 04:48:39 +01:00
insert into rtest_emp values ('gates', '80000.00');
2009-01-19 13:02:29 +01:00
update rtest_emp set ename = 'wiecx' where ename = 'wiecc';
2000-01-09 04:48:39 +01:00
update rtest_emp set ename = 'wieck', salary = '6000.00' where ename = 'wiecx';
update rtest_emp set salary = '7000.00' where ename = 'wieck';
delete from rtest_emp where ename = 'gates';
select ename, who = current_user as "matches user", action, newsal, oldsal from rtest_emplog order by ename, action, newsal;
ename | matches user | action | newsal | oldsal
----------------------+--------------+------------+------------+------------
gates | t | fired | $0.00 | $80,000.00
gates | t | hired | $80,000.00 | $0.00
2009-01-19 13:02:29 +01:00
wiecc | t | hired | $5,000.00 | $0.00
2000-01-09 04:48:39 +01:00
wieck | t | honored | $6,000.00 | $5,000.00
wieck | t | honored | $7,000.00 | $6,000.00
1998-08-18 02:49:04 +02:00
(5 rows)
2000-01-09 04:48:39 +01:00
insert into rtest_empmass values ('meyer', '4000.00');
insert into rtest_empmass values ('maier', '5000.00');
insert into rtest_empmass values ('mayr', '6000.00');
insert into rtest_emp select * from rtest_empmass;
select ename, who = current_user as "matches user", action, newsal, oldsal from rtest_emplog order by ename, action, newsal;
ename | matches user | action | newsal | oldsal
----------------------+--------------+------------+------------+------------
gates | t | fired | $0.00 | $80,000.00
gates | t | hired | $80,000.00 | $0.00
maier | t | hired | $5,000.00 | $0.00
mayr | t | hired | $6,000.00 | $0.00
meyer | t | hired | $4,000.00 | $0.00
2009-01-19 13:02:29 +01:00
wiecc | t | hired | $5,000.00 | $0.00
2000-01-09 04:48:39 +01:00
wieck | t | honored | $6,000.00 | $5,000.00
wieck | t | honored | $7,000.00 | $6,000.00
1998-08-18 02:49:04 +02:00
(8 rows)
2000-01-09 04:48:39 +01:00
update rtest_empmass set salary = salary + '1000.00';
2005-04-07 03:51:41 +02:00
update rtest_emp set salary = rtest_empmass.salary from rtest_empmass where rtest_emp.ename = rtest_empmass.ename;
2000-01-09 04:48:39 +01:00
select ename, who = current_user as "matches user", action, newsal, oldsal from rtest_emplog order by ename, action, newsal;
ename | matches user | action | newsal | oldsal
----------------------+--------------+------------+------------+------------
gates | t | fired | $0.00 | $80,000.00
gates | t | hired | $80,000.00 | $0.00
maier | t | hired | $5,000.00 | $0.00
maier | t | honored | $6,000.00 | $5,000.00
mayr | t | hired | $6,000.00 | $0.00
mayr | t | honored | $7,000.00 | $6,000.00
meyer | t | hired | $4,000.00 | $0.00
meyer | t | honored | $5,000.00 | $4,000.00
2009-01-19 13:02:29 +01:00
wiecc | t | hired | $5,000.00 | $0.00
2000-01-09 04:48:39 +01:00
wieck | t | honored | $6,000.00 | $5,000.00
wieck | t | honored | $7,000.00 | $6,000.00
1998-08-18 02:49:04 +02:00
(11 rows)
2005-04-07 03:51:41 +02:00
delete from rtest_emp using rtest_empmass where rtest_emp.ename = rtest_empmass.ename;
2000-01-09 04:48:39 +01:00
select ename, who = current_user as "matches user", action, newsal, oldsal from rtest_emplog order by ename, action, newsal;
ename | matches user | action | newsal | oldsal
----------------------+--------------+------------+------------+------------
gates | t | fired | $0.00 | $80,000.00
gates | t | hired | $80,000.00 | $0.00
maier | t | fired | $0.00 | $6,000.00
maier | t | hired | $5,000.00 | $0.00
maier | t | honored | $6,000.00 | $5,000.00
mayr | t | fired | $0.00 | $7,000.00
mayr | t | hired | $6,000.00 | $0.00
mayr | t | honored | $7,000.00 | $6,000.00
meyer | t | fired | $0.00 | $5,000.00
meyer | t | hired | $4,000.00 | $0.00
meyer | t | honored | $5,000.00 | $4,000.00
2009-01-19 13:02:29 +01:00
wiecc | t | hired | $5,000.00 | $0.00
2000-01-09 04:48:39 +01:00
wieck | t | honored | $6,000.00 | $5,000.00
wieck | t | honored | $7,000.00 | $6,000.00
1998-08-18 02:49:04 +02:00
(14 rows)
2000-01-09 04:48:39 +01:00
--
-- Multiple cascaded qualified instead rule test
--
insert into rtest_t4 values (1, 'Record should go to rtest_t4');
insert into rtest_t4 values (2, 'Record should go to rtest_t4');
insert into rtest_t4 values (10, 'Record should go to rtest_t5');
insert into rtest_t4 values (15, 'Record should go to rtest_t5');
insert into rtest_t4 values (19, 'Record should go to rtest_t5 and t7');
insert into rtest_t4 values (20, 'Record should go to rtest_t4 and t6');
insert into rtest_t4 values (26, 'Record should go to rtest_t4 and t8');
insert into rtest_t4 values (28, 'Record should go to rtest_t4 and t8');
insert into rtest_t4 values (30, 'Record should go to rtest_t4');
insert into rtest_t4 values (40, 'Record should go to rtest_t4');
select * from rtest_t4;
a | b
----+-------------------------------------
1 | Record should go to rtest_t4
2 | Record should go to rtest_t4
20 | Record should go to rtest_t4 and t6
26 | Record should go to rtest_t4 and t8
28 | Record should go to rtest_t4 and t8
30 | Record should go to rtest_t4
40 | Record should go to rtest_t4
1998-08-18 02:49:04 +02:00
(7 rows)
2000-01-09 04:48:39 +01:00
select * from rtest_t5;
a | b
----+-------------------------------------
10 | Record should go to rtest_t5
15 | Record should go to rtest_t5
19 | Record should go to rtest_t5 and t7
1998-08-18 02:49:04 +02:00
(3 rows)
2000-01-09 04:48:39 +01:00
select * from rtest_t6;
a | b
----+-------------------------------------
20 | Record should go to rtest_t4 and t6
1998-08-18 02:49:04 +02:00
(1 row)
2000-01-09 04:48:39 +01:00
select * from rtest_t7;
a | b
----+-------------------------------------
19 | Record should go to rtest_t5 and t7
1998-08-18 02:49:04 +02:00
(1 row)
2000-01-09 04:48:39 +01:00
select * from rtest_t8;
a | b
----+-------------------------------------
26 | Record should go to rtest_t4 and t8
28 | Record should go to rtest_t4 and t8
1998-08-18 02:49:04 +02:00
(2 rows)
2000-01-09 04:48:39 +01:00
delete from rtest_t4;
delete from rtest_t5;
delete from rtest_t6;
delete from rtest_t7;
delete from rtest_t8;
insert into rtest_t9 values (1, 'Record should go to rtest_t4');
insert into rtest_t9 values (2, 'Record should go to rtest_t4');
insert into rtest_t9 values (10, 'Record should go to rtest_t5');
insert into rtest_t9 values (15, 'Record should go to rtest_t5');
insert into rtest_t9 values (19, 'Record should go to rtest_t5 and t7');
insert into rtest_t9 values (20, 'Record should go to rtest_t4 and t6');
insert into rtest_t9 values (26, 'Record should go to rtest_t4 and t8');
insert into rtest_t9 values (28, 'Record should go to rtest_t4 and t8');
insert into rtest_t9 values (30, 'Record should go to rtest_t4');
insert into rtest_t9 values (40, 'Record should go to rtest_t4');
insert into rtest_t4 select * from rtest_t9 where a < 20;
select * from rtest_t4;
a | b
---+------------------------------
1 | Record should go to rtest_t4
2 | Record should go to rtest_t4
1998-08-18 02:49:04 +02:00
(2 rows)
2000-01-09 04:48:39 +01:00
select * from rtest_t5;
a | b
----+-------------------------------------
10 | Record should go to rtest_t5
15 | Record should go to rtest_t5
19 | Record should go to rtest_t5 and t7
1998-08-18 02:49:04 +02:00
(3 rows)
2000-01-09 04:48:39 +01:00
select * from rtest_t6;
a | b
---+---
1998-08-18 02:49:04 +02:00
(0 rows)
2000-01-09 04:48:39 +01:00
select * from rtest_t7;
a | b
----+-------------------------------------
19 | Record should go to rtest_t5 and t7
1998-08-18 02:49:04 +02:00
(1 row)
2000-01-09 04:48:39 +01:00
select * from rtest_t8;
a | b
---+---
1998-08-18 02:49:04 +02:00
(0 rows)
2000-01-09 04:48:39 +01:00
insert into rtest_t4 select * from rtest_t9 where b ~ 'and t8';
select * from rtest_t4;
a | b
----+-------------------------------------
1 | Record should go to rtest_t4
2 | Record should go to rtest_t4
26 | Record should go to rtest_t4 and t8
28 | Record should go to rtest_t4 and t8
1998-08-18 02:49:04 +02:00
(4 rows)
2000-01-09 04:48:39 +01:00
select * from rtest_t5;
a | b
----+-------------------------------------
10 | Record should go to rtest_t5
15 | Record should go to rtest_t5
19 | Record should go to rtest_t5 and t7
1998-08-18 02:49:04 +02:00
(3 rows)
2000-01-09 04:48:39 +01:00
select * from rtest_t6;
a | b
---+---
1998-08-18 02:49:04 +02:00
(0 rows)
2000-01-09 04:48:39 +01:00
select * from rtest_t7;
a | b
----+-------------------------------------
19 | Record should go to rtest_t5 and t7
1998-08-18 02:49:04 +02:00
(1 row)
2000-01-09 04:48:39 +01:00
select * from rtest_t8;
a | b
----+-------------------------------------
26 | Record should go to rtest_t4 and t8
28 | Record should go to rtest_t4 and t8
1998-08-18 02:49:04 +02:00
(2 rows)
2000-01-09 04:48:39 +01:00
insert into rtest_t4 select a + 1, b from rtest_t9 where a in (20, 30, 40);
select * from rtest_t4;
a | b
----+-------------------------------------
1 | Record should go to rtest_t4
2 | Record should go to rtest_t4
26 | Record should go to rtest_t4 and t8
28 | Record should go to rtest_t4 and t8
21 | Record should go to rtest_t4 and t6
31 | Record should go to rtest_t4
41 | Record should go to rtest_t4
1998-08-18 02:49:04 +02:00
(7 rows)
2000-01-09 04:48:39 +01:00
select * from rtest_t5;
a | b
----+-------------------------------------
10 | Record should go to rtest_t5
15 | Record should go to rtest_t5
19 | Record should go to rtest_t5 and t7
1998-08-18 02:49:04 +02:00
(3 rows)
2000-01-09 04:48:39 +01:00
select * from rtest_t6;
a | b
----+-------------------------------------
21 | Record should go to rtest_t4 and t6
1998-08-18 02:49:04 +02:00
(1 row)
2000-01-09 04:48:39 +01:00
select * from rtest_t7;
a | b
----+-------------------------------------
19 | Record should go to rtest_t5 and t7
1998-08-18 02:49:04 +02:00
(1 row)
2000-01-09 04:48:39 +01:00
select * from rtest_t8;
a | b
----+-------------------------------------
26 | Record should go to rtest_t4 and t8
28 | Record should go to rtest_t4 and t8
1998-08-18 02:49:04 +02:00
(2 rows)
2000-01-09 04:48:39 +01:00
--
-- Check that the ordering of rules fired is correct
--
insert into rtest_order1 values (1);
select * from rtest_order2;
2002-10-19 21:00:47 +02:00
a | b | c
---+---+------------------------------
1 | 1 | rule 1 - this should run 1st
1 | 2 | rule 2 - this should run 2nd
1 | 3 | rule 3 - this should run 3rd
1 | 4 | rule 4 - this should run 4th
1998-08-18 02:49:04 +02:00
(4 rows)
2000-01-09 04:48:39 +01:00
--
-- Check if instead nothing w/without qualification works
--
insert into rtest_nothn1 values (1, 'want this');
insert into rtest_nothn1 values (2, 'want this');
insert into rtest_nothn1 values (10, 'don''t want this');
insert into rtest_nothn1 values (19, 'don''t want this');
insert into rtest_nothn1 values (20, 'want this');
insert into rtest_nothn1 values (29, 'want this');
insert into rtest_nothn1 values (30, 'don''t want this');
insert into rtest_nothn1 values (39, 'don''t want this');
insert into rtest_nothn1 values (40, 'want this');
insert into rtest_nothn1 values (50, 'want this');
insert into rtest_nothn1 values (60, 'want this');
select * from rtest_nothn1;
a | b
----+-----------
1 | want this
2 | want this
20 | want this
29 | want this
40 | want this
50 | want this
60 | want this
1998-08-18 02:49:04 +02:00
(7 rows)
2000-01-09 04:48:39 +01:00
insert into rtest_nothn2 values (10, 'too small');
insert into rtest_nothn2 values (50, 'too small');
insert into rtest_nothn2 values (100, 'OK');
insert into rtest_nothn2 values (200, 'OK');
select * from rtest_nothn2;
a | b
---+---
1998-08-18 02:49:04 +02:00
(0 rows)
2000-01-09 04:48:39 +01:00
select * from rtest_nothn3;
a | b
-----+----
100 | OK
200 | OK
1998-08-18 02:49:04 +02:00
(2 rows)
2000-01-09 04:48:39 +01:00
delete from rtest_nothn1;
delete from rtest_nothn2;
delete from rtest_nothn3;
insert into rtest_nothn4 values (1, 'want this');
insert into rtest_nothn4 values (2, 'want this');
insert into rtest_nothn4 values (10, 'don''t want this');
insert into rtest_nothn4 values (19, 'don''t want this');
insert into rtest_nothn4 values (20, 'want this');
insert into rtest_nothn4 values (29, 'want this');
insert into rtest_nothn4 values (30, 'don''t want this');
insert into rtest_nothn4 values (39, 'don''t want this');
insert into rtest_nothn4 values (40, 'want this');
insert into rtest_nothn4 values (50, 'want this');
insert into rtest_nothn4 values (60, 'want this');
insert into rtest_nothn1 select * from rtest_nothn4;
select * from rtest_nothn1;
a | b
----+-----------
1 | want this
2 | want this
20 | want this
29 | want this
40 | want this
50 | want this
60 | want this
1998-08-18 02:49:04 +02:00
(7 rows)
2000-01-09 04:48:39 +01:00
delete from rtest_nothn4;
insert into rtest_nothn4 values (10, 'too small');
insert into rtest_nothn4 values (50, 'too small');
insert into rtest_nothn4 values (100, 'OK');
insert into rtest_nothn4 values (200, 'OK');
insert into rtest_nothn2 select * from rtest_nothn4;
select * from rtest_nothn2;
a | b
---+---
1998-08-18 02:49:04 +02:00
(0 rows)
2000-01-09 04:48:39 +01:00
select * from rtest_nothn3;
a | b
-----+----
100 | OK
200 | OK
1998-08-18 02:49:04 +02:00
(2 rows)
2000-01-09 04:48:39 +01:00
create table rtest_view1 (a int4, b text, v bool);
create table rtest_view2 (a int4);
create table rtest_view3 (a int4, b text);
create table rtest_view4 (a int4, b text, c int4);
2010-11-23 21:27:50 +01:00
create view rtest_vview1 as select a, b from rtest_view1 X
1998-10-02 18:28:04 +02:00
where 0 < (select count(*) from rtest_view2 Y where Y.a = X.a);
2000-01-09 04:48:39 +01:00
create view rtest_vview2 as select a, b from rtest_view1 where v;
create view rtest_vview3 as select a, b from rtest_vview2 X
1998-10-02 18:28:04 +02:00
where 0 < (select count(*) from rtest_view2 Y where Y.a = X.a);
2000-01-09 04:48:39 +01:00
create view rtest_vview4 as select X.a, X.b, count(Y.a) as refcount
1998-10-02 18:28:04 +02:00
from rtest_view1 X, rtest_view2 Y
where X.a = Y.a
group by X.a, X.b;
2000-01-09 04:48:39 +01:00
create function rtest_viewfunc1(int4) returns int4 as
2001-08-15 00:21:59 +02:00
'select count(*)::int4 from rtest_view2 where a = $1'
2006-02-27 17:09:50 +01:00
language sql;
2000-01-09 04:48:39 +01:00
create view rtest_vview5 as select a, b, rtest_viewfunc1(a) as refcount
1998-10-02 18:28:04 +02:00
from rtest_view1;
2000-01-09 04:48:39 +01:00
insert into rtest_view1 values (1, 'item 1', 't');
insert into rtest_view1 values (2, 'item 2', 't');
insert into rtest_view1 values (3, 'item 3', 't');
insert into rtest_view1 values (4, 'item 4', 'f');
insert into rtest_view1 values (5, 'item 5', 't');
insert into rtest_view1 values (6, 'item 6', 'f');
insert into rtest_view1 values (7, 'item 7', 't');
insert into rtest_view1 values (8, 'item 8', 't');
insert into rtest_view2 values (2);
insert into rtest_view2 values (2);
insert into rtest_view2 values (4);
insert into rtest_view2 values (5);
insert into rtest_view2 values (7);
insert into rtest_view2 values (7);
insert into rtest_view2 values (7);
insert into rtest_view2 values (7);
select * from rtest_vview1;
a | b
---+--------
2 | item 2
4 | item 4
5 | item 5
7 | item 7
1998-10-02 18:28:04 +02:00
(4 rows)
2000-01-09 04:48:39 +01:00
select * from rtest_vview2;
a | b
---+--------
1 | item 1
2 | item 2
3 | item 3
5 | item 5
7 | item 7
8 | item 8
1998-10-02 18:28:04 +02:00
(6 rows)
2000-01-09 04:48:39 +01:00
select * from rtest_vview3;
a | b
---+--------
2 | item 2
5 | item 5
7 | item 7
1998-10-02 18:28:04 +02:00
(3 rows)
2002-11-21 01:42:20 +01:00
select * from rtest_vview4 order by a, b;
2000-01-09 04:48:39 +01:00
a | b | refcount
---+--------+----------
2 | item 2 | 2
4 | item 4 | 1
5 | item 5 | 1
7 | item 7 | 4
1998-10-02 18:28:04 +02:00
(4 rows)
2000-01-09 04:48:39 +01:00
select * from rtest_vview5;
a | b | refcount
---+--------+----------
1 | item 1 | 0
2 | item 2 | 2
3 | item 3 | 0
4 | item 4 | 1
5 | item 5 | 1
6 | item 6 | 0
7 | item 7 | 4
8 | item 8 | 0
1998-10-02 18:28:04 +02:00
(8 rows)
2000-01-09 04:48:39 +01:00
insert into rtest_view3 select * from rtest_vview1 where a < 7;
select * from rtest_view3;
a | b
---+--------
2 | item 2
4 | item 4
5 | item 5
1998-10-02 18:28:04 +02:00
(3 rows)
2000-01-09 04:48:39 +01:00
delete from rtest_view3;
insert into rtest_view3 select * from rtest_vview2 where a != 5 and b !~ '2';
select * from rtest_view3;
a | b
---+--------
1 | item 1
3 | item 3
7 | item 7
8 | item 8
1998-10-02 18:28:04 +02:00
(4 rows)
2000-01-09 04:48:39 +01:00
delete from rtest_view3;
insert into rtest_view3 select * from rtest_vview3;
select * from rtest_view3;
a | b
---+--------
2 | item 2
5 | item 5
7 | item 7
1998-10-02 18:28:04 +02:00
(3 rows)
2000-01-09 04:48:39 +01:00
delete from rtest_view3;
insert into rtest_view4 select * from rtest_vview4 where 3 > refcount;
2002-11-21 23:26:02 +01:00
select * from rtest_view4 order by a, b;
2000-01-09 04:48:39 +01:00
a | b | c
---+--------+---
2 | item 2 | 2
4 | item 4 | 1
5 | item 5 | 1
1998-10-02 18:28:04 +02:00
(3 rows)
2000-01-09 04:48:39 +01:00
delete from rtest_view4;
insert into rtest_view4 select * from rtest_vview5 where a > 2 and refcount = 0;
2002-11-21 23:26:02 +01:00
select * from rtest_view4;
2000-01-09 04:48:39 +01:00
a | b | c
---+--------+---
3 | item 3 | 0
6 | item 6 | 0
8 | item 8 | 0
1998-10-02 18:28:04 +02:00
(3 rows)
2000-01-09 04:48:39 +01:00
delete from rtest_view4;
--
-- Test for computations in views
--
create table rtest_comp (
1998-10-02 18:28:04 +02:00
part text,
unit char(4),
size float
);
2000-01-09 04:48:39 +01:00
create table rtest_unitfact (
1998-10-02 18:28:04 +02:00
unit char(4),
factor float
);
2010-11-23 21:27:50 +01:00
create view rtest_vcomp as
1998-10-02 18:28:04 +02:00
select X.part, (X.size * Y.factor) as size_in_cm
from rtest_comp X, rtest_unitfact Y
where X.unit = Y.unit;
2000-01-09 04:48:39 +01:00
insert into rtest_unitfact values ('m', 100.0);
insert into rtest_unitfact values ('cm', 1.0);
insert into rtest_unitfact values ('inch', 2.54);
insert into rtest_comp values ('p1', 'm', 5.0);
insert into rtest_comp values ('p2', 'm', 3.0);
insert into rtest_comp values ('p3', 'cm', 5.0);
insert into rtest_comp values ('p4', 'cm', 15.0);
insert into rtest_comp values ('p5', 'inch', 7.0);
insert into rtest_comp values ('p6', 'inch', 4.4);
select * from rtest_vcomp order by part;
part | size_in_cm
------+------------
p1 | 500
p2 | 300
p3 | 5
p4 | 15
p5 | 17.78
p6 | 11.176
1998-10-02 18:28:04 +02:00
(6 rows)
2000-01-09 04:48:39 +01:00
select * from rtest_vcomp where size_in_cm > 10.0 order by size_in_cm using >;
part | size_in_cm
------+------------
p1 | 500
p2 | 300
p5 | 17.78
p4 | 15
p6 | 11.176
1998-10-02 18:28:04 +02:00
(5 rows)
2000-01-09 04:48:39 +01:00
--
-- In addition run the (slightly modified) queries from the
-- programmers manual section on the rule system.
--
CREATE TABLE shoe_data (
shoename char(10), -- primary key
sh_avail integer, -- available # of pairs
slcolor char(10), -- preferred shoelace color
slminlen float, -- miminum shoelace length
slmaxlen float, -- maximum shoelace length
slunit char(8) -- length unit
1999-02-08 02:39:46 +01:00
);
2000-01-09 04:48:39 +01:00
CREATE TABLE shoelace_data (
sl_name char(10), -- primary key
sl_avail integer, -- available # of pairs
sl_color char(10), -- shoelace color
sl_len float, -- shoelace length
sl_unit char(8) -- length unit
1999-02-08 02:39:46 +01:00
);
2000-01-09 04:48:39 +01:00
CREATE TABLE unit (
un_name char(8), -- the primary key
un_fact float -- factor to transform to cm
1999-02-08 02:39:46 +01:00
);
2000-01-09 04:48:39 +01:00
CREATE VIEW shoe AS
1999-02-08 02:39:46 +01:00
SELECT sh.shoename,
sh.sh_avail,
sh.slcolor,
sh.slminlen,
sh.slminlen * un.un_fact AS slminlen_cm,
sh.slmaxlen,
sh.slmaxlen * un.un_fact AS slmaxlen_cm,
sh.slunit
FROM shoe_data sh, unit un
WHERE sh.slunit = un.un_name;
2000-01-09 04:48:39 +01:00
CREATE VIEW shoelace AS
1999-02-08 02:39:46 +01:00
SELECT s.sl_name,
s.sl_avail,
s.sl_color,
s.sl_len,
s.sl_unit,
s.sl_len * u.un_fact AS sl_len_cm
FROM shoelace_data s, unit u
WHERE s.sl_unit = u.un_name;
2000-01-09 04:48:39 +01:00
CREATE VIEW shoe_ready AS
1999-02-08 02:39:46 +01:00
SELECT rsh.shoename,
rsh.sh_avail,
rsl.sl_name,
rsl.sl_avail,
int4smaller(rsh.sh_avail, rsl.sl_avail) AS total_avail
FROM shoe rsh, shoelace rsl
WHERE rsl.sl_color = rsh.slcolor
AND rsl.sl_len_cm >= rsh.slminlen_cm
AND rsl.sl_len_cm <= rsh.slmaxlen_cm;
2000-01-09 04:48:39 +01:00
INSERT INTO unit VALUES ('cm', 1.0);
INSERT INTO unit VALUES ('m', 100.0);
INSERT INTO unit VALUES ('inch', 2.54);
INSERT INTO shoe_data VALUES ('sh1', 2, 'black', 70.0, 90.0, 'cm');
INSERT INTO shoe_data VALUES ('sh2', 0, 'black', 30.0, 40.0, 'inch');
INSERT INTO shoe_data VALUES ('sh3', 4, 'brown', 50.0, 65.0, 'cm');
INSERT INTO shoe_data VALUES ('sh4', 3, 'brown', 40.0, 50.0, 'inch');
INSERT INTO shoelace_data VALUES ('sl1', 5, 'black', 80.0, 'cm');
INSERT INTO shoelace_data VALUES ('sl2', 6, 'black', 100.0, 'cm');
INSERT INTO shoelace_data VALUES ('sl3', 0, 'black', 35.0 , 'inch');
INSERT INTO shoelace_data VALUES ('sl4', 8, 'black', 40.0 , 'inch');
INSERT INTO shoelace_data VALUES ('sl5', 4, 'brown', 1.0 , 'm');
INSERT INTO shoelace_data VALUES ('sl6', 0, 'brown', 0.9 , 'm');
INSERT INTO shoelace_data VALUES ('sl7', 7, 'brown', 60 , 'cm');
INSERT INTO shoelace_data VALUES ('sl8', 1, 'brown', 40 , 'inch');
-- SELECTs in doc
SELECT * FROM shoelace ORDER BY sl_name;
sl_name | sl_avail | sl_color | sl_len | sl_unit | sl_len_cm
------------+----------+------------+--------+----------+-----------
sl1 | 5 | black | 80 | cm | 80
sl2 | 6 | black | 100 | cm | 100
sl3 | 0 | black | 35 | inch | 88.9
sl4 | 8 | black | 40 | inch | 101.6
sl5 | 4 | brown | 1 | m | 100
sl6 | 0 | brown | 0.9 | m | 90
sl7 | 7 | brown | 60 | cm | 60
sl8 | 1 | brown | 40 | inch | 101.6
1999-02-08 02:39:46 +01:00
(8 rows)
2002-09-02 07:20:56 +02:00
SELECT * FROM shoe_ready WHERE total_avail >= 2 ORDER BY 1;
2000-01-09 04:48:39 +01:00
shoename | sh_avail | sl_name | sl_avail | total_avail
------------+----------+------------+----------+-------------
sh1 | 2 | sl1 | 5 | 2
sh3 | 4 | sl7 | 7 | 4
1999-02-08 02:39:46 +01:00
(2 rows)
2000-01-09 04:48:39 +01:00
CREATE TABLE shoelace_log (
sl_name char(10), -- shoelace changed
sl_avail integer, -- new available value
log_who name, -- who did it
2002-05-03 02:32:19 +02:00
log_when timestamp -- when
1999-02-08 02:39:46 +01:00
);
2000-01-09 04:48:39 +01:00
-- Want "log_who" to be CURRENT_USER,
-- but that is non-portable for the regression test
-- - thomas 1999-02-21
CREATE RULE log_shoelace AS ON UPDATE TO shoelace_data
1999-02-08 02:39:46 +01:00
WHERE NEW.sl_avail != OLD.sl_avail
DO INSERT INTO shoelace_log VALUES (
NEW.sl_name,
NEW.sl_avail,
1999-02-23 08:29:19 +01:00
'Al Bundy',
2002-04-11 22:00:18 +02:00
'epoch'
1999-02-08 02:39:46 +01:00
);
2000-01-09 04:48:39 +01:00
UPDATE shoelace_data SET sl_avail = 6 WHERE sl_name = 'sl7';
SELECT * FROM shoelace_log;
2001-09-28 10:00:11 +02:00
sl_name | sl_avail | log_who | log_when
------------+----------+----------+--------------------------
sl7 | 6 | Al Bundy | Thu Jan 01 00:00:00 1970
1999-02-08 02:39:46 +01:00
(1 row)
2000-01-09 04:48:39 +01:00
CREATE RULE shoelace_ins AS ON INSERT TO shoelace
1999-02-08 02:39:46 +01:00
DO INSTEAD
INSERT INTO shoelace_data VALUES (
NEW.sl_name,
NEW.sl_avail,
NEW.sl_color,
NEW.sl_len,
NEW.sl_unit);
2000-01-09 04:48:39 +01:00
CREATE RULE shoelace_upd AS ON UPDATE TO shoelace
1999-02-08 02:39:46 +01:00
DO INSTEAD
UPDATE shoelace_data SET
sl_name = NEW.sl_name,
sl_avail = NEW.sl_avail,
sl_color = NEW.sl_color,
sl_len = NEW.sl_len,
sl_unit = NEW.sl_unit
WHERE sl_name = OLD.sl_name;
2000-01-09 04:48:39 +01:00
CREATE RULE shoelace_del AS ON DELETE TO shoelace
1999-02-08 02:39:46 +01:00
DO INSTEAD
DELETE FROM shoelace_data
WHERE sl_name = OLD.sl_name;
2000-01-09 04:48:39 +01:00
CREATE TABLE shoelace_arrive (
1999-02-08 02:39:46 +01:00
arr_name char(10),
arr_quant integer
);
2000-01-09 04:48:39 +01:00
CREATE TABLE shoelace_ok (
1999-02-08 02:39:46 +01:00
ok_name char(10),
ok_quant integer
);
2000-01-09 04:48:39 +01:00
CREATE RULE shoelace_ok_ins AS ON INSERT TO shoelace_ok
1999-02-08 02:39:46 +01:00
DO INSTEAD
UPDATE shoelace SET
sl_avail = sl_avail + NEW.ok_quant
WHERE sl_name = NEW.ok_name;
2000-01-09 04:48:39 +01:00
INSERT INTO shoelace_arrive VALUES ('sl3', 10);
INSERT INTO shoelace_arrive VALUES ('sl6', 20);
INSERT INTO shoelace_arrive VALUES ('sl8', 20);
SELECT * FROM shoelace ORDER BY sl_name;
sl_name | sl_avail | sl_color | sl_len | sl_unit | sl_len_cm
------------+----------+------------+--------+----------+-----------
sl1 | 5 | black | 80 | cm | 80
sl2 | 6 | black | 100 | cm | 100
sl3 | 0 | black | 35 | inch | 88.9
sl4 | 8 | black | 40 | inch | 101.6
sl5 | 4 | brown | 1 | m | 100
sl6 | 0 | brown | 0.9 | m | 90
sl7 | 6 | brown | 60 | cm | 60
sl8 | 1 | brown | 40 | inch | 101.6
1999-02-08 02:39:46 +01:00
(8 rows)
2000-01-09 04:48:39 +01:00
insert into shoelace_ok select * from shoelace_arrive;
2000-10-08 04:51:50 +02:00
SELECT * FROM shoelace ORDER BY sl_name;
sl_name | sl_avail | sl_color | sl_len | sl_unit | sl_len_cm
------------+----------+------------+--------+----------+-----------
sl1 | 5 | black | 80 | cm | 80
sl2 | 6 | black | 100 | cm | 100
sl3 | 10 | black | 35 | inch | 88.9
sl4 | 8 | black | 40 | inch | 101.6
sl5 | 4 | brown | 1 | m | 100
sl6 | 20 | brown | 0.9 | m | 90
sl7 | 6 | brown | 60 | cm | 60
sl8 | 21 | brown | 40 | inch | 101.6
(8 rows)
SELECT * FROM shoelace_log ORDER BY sl_name;
2001-09-28 10:00:11 +02:00
sl_name | sl_avail | log_who | log_when
------------+----------+----------+--------------------------
sl3 | 10 | Al Bundy | Thu Jan 01 00:00:00 1970
sl6 | 20 | Al Bundy | Thu Jan 01 00:00:00 1970
sl7 | 6 | Al Bundy | Thu Jan 01 00:00:00 1970
sl8 | 21 | Al Bundy | Thu Jan 01 00:00:00 1970
2000-10-08 04:51:50 +02:00
(4 rows)
CREATE VIEW shoelace_obsolete AS
SELECT * FROM shoelace WHERE NOT EXISTS
(SELECT shoename FROM shoe WHERE slcolor = sl_color);
CREATE VIEW shoelace_candelete AS
SELECT * FROM shoelace_obsolete WHERE sl_avail = 0;
insert into shoelace values ('sl9', 0, 'pink', 35.0, 'inch', 0.0);
insert into shoelace values ('sl10', 1000, 'magenta', 40.0, 'inch', 0.0);
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
-- Unsupported (even though a similar updatable view construct is)
insert into shoelace values ('sl10', 1000, 'magenta', 40.0, 'inch', 0.0)
on conflict do nothing;
ERROR: INSERT with ON CONFLICT clause cannot be used with table that has INSERT or UPDATE rules
2005-03-26 03:14:43 +01:00
SELECT * FROM shoelace_obsolete ORDER BY sl_len_cm;
2000-10-08 04:51:50 +02:00
sl_name | sl_avail | sl_color | sl_len | sl_unit | sl_len_cm
------------+----------+------------+--------+----------+-----------
2004-04-01 23:59:45 +02:00
sl9 | 0 | pink | 35 | inch | 88.9
2005-03-24 20:14:49 +01:00
sl10 | 1000 | magenta | 40 | inch | 101.6
2000-10-08 04:51:50 +02:00
(2 rows)
SELECT * FROM shoelace_candelete;
sl_name | sl_avail | sl_color | sl_len | sl_unit | sl_len_cm
------------+----------+------------+--------+----------+-----------
sl9 | 0 | pink | 35 | inch | 88.9
(1 row)
DELETE FROM shoelace WHERE EXISTS
(SELECT * FROM shoelace_candelete
WHERE sl_name = shoelace.sl_name);
SELECT * FROM shoelace ORDER BY sl_name;
sl_name | sl_avail | sl_color | sl_len | sl_unit | sl_len_cm
------------+----------+------------+--------+----------+-----------
sl1 | 5 | black | 80 | cm | 80
sl10 | 1000 | magenta | 40 | inch | 101.6
sl2 | 6 | black | 100 | cm | 100
sl3 | 10 | black | 35 | inch | 88.9
sl4 | 8 | black | 40 | inch | 101.6
sl5 | 4 | brown | 1 | m | 100
sl6 | 20 | brown | 0.9 | m | 90
sl7 | 6 | brown | 60 | cm | 60
sl8 | 21 | brown | 40 | inch | 101.6
(9 rows)
SELECT * FROM shoe ORDER BY shoename;
shoename | sh_avail | slcolor | slminlen | slminlen_cm | slmaxlen | slmaxlen_cm | slunit
------------+----------+------------+----------+-------------+----------+-------------+----------
sh1 | 2 | black | 70 | 70 | 90 | 90 | cm
sh2 | 0 | black | 30 | 76.2 | 40 | 101.6 | inch
sh3 | 4 | brown | 50 | 50 | 65 | 65 | cm
sh4 | 3 | brown | 40 | 101.6 | 50 | 127 | inch
(4 rows)
SELECT count(*) FROM shoe;
count
-------
4
(1 row)
--
-- Simple test of qualified ON INSERT ... this did not work in 7.0 ...
--
create table foo (f1 int);
create table foo2 (f1 int);
create rule foorule as on insert to foo where f1 < 100
do instead nothing;
insert into foo values(1);
insert into foo values(1001);
select * from foo;
f1
------
1001
(1 row)
2002-04-18 22:01:11 +02:00
drop rule foorule on foo;
2000-10-08 04:51:50 +02:00
-- this should fail because f1 is not exposed for unqualified reference:
create rule foorule as on insert to foo where f1 < 100
do instead insert into foo2 values (f1);
2003-09-25 08:58:07 +02:00
ERROR: column "f1" does not exist
2007-03-13 01:33:44 +01:00
LINE 2: do instead insert into foo2 values (f1);
^
2012-08-08 01:02:54 +02:00
HINT: There is a column named "f1" in table "old", but it cannot be referenced from this part of the query.
2000-10-08 04:51:50 +02:00
-- this is the correct way:
create rule foorule as on insert to foo where f1 < 100
do instead insert into foo2 values (new.f1);
insert into foo values(2);
insert into foo values(100);
select * from foo;
f1
------
1001
100
(2 rows)
select * from foo2;
f1
----
2
(1 row)
2002-04-18 22:01:11 +02:00
drop rule foorule on foo;
2000-10-08 04:51:50 +02:00
drop table foo;
drop table foo2;
--
2000-12-05 20:15:49 +01:00
-- Test rules containing INSERT ... SELECT, which is a very ugly special
-- case as of 7.1. Example is based on bug report from Joel Burton.
--
create table pparent (pid int, txt text);
insert into pparent values (1,'parent1');
insert into pparent values (2,'parent2');
create table cchild (pid int, descrip text);
insert into cchild values (1,'descrip1');
create view vview as
select pparent.pid, txt, descrip from
pparent left join cchild using (pid);
create rule rrule as
on update to vview do instead
(
insert into cchild (pid, descrip)
2010-11-23 21:27:50 +01:00
select old.pid, new.descrip where old.descrip isnull;
2000-12-05 20:15:49 +01:00
update cchild set descrip = new.descrip where cchild.pid = old.pid;
);
select * from vview;
pid | txt | descrip
-----+---------+----------
1 | parent1 | descrip1
2 | parent2 |
(2 rows)
update vview set descrip='test1' where pid=1;
select * from vview;
pid | txt | descrip
-----+---------+---------
1 | parent1 | test1
2 | parent2 |
(2 rows)
update vview set descrip='test2' where pid=2;
select * from vview;
pid | txt | descrip
-----+---------+---------
1 | parent1 | test1
2 | parent2 | test2
(2 rows)
update vview set descrip='test3' where pid=3;
select * from vview;
pid | txt | descrip
-----+---------+---------
1 | parent1 | test1
2 | parent2 | test2
(2 rows)
select * from cchild;
pid | descrip
-----+---------
1 | test1
2 | test2
(2 rows)
2002-04-18 22:01:11 +02:00
drop rule rrule on vview;
2000-12-05 20:15:49 +01:00
drop view vview;
drop table pparent;
drop table cchild;
--
2000-10-08 04:51:50 +02:00
-- Check that ruleutils are working
--
2013-10-26 17:24:04 +02:00
-- temporarily disable fancy output, so view changes create less diff noise
\a\t
2002-12-14 01:24:35 +01:00
SELECT viewname, definition FROM pg_views WHERE schemaname <> 'information_schema' ORDER BY viewname;
2013-11-11 19:36:38 +01:00
iexit| SELECT ih.name,
ih.thepath,
2013-10-26 17:24:04 +02:00
interpt_pp(ih.thepath, r.thepath) AS exit
2013-11-11 19:36:38 +01:00
FROM ihighway ih,
2013-10-26 17:24:04 +02:00
ramp r
WHERE (ih.thepath ## r.thepath);
2016-04-15 19:04:17 +02:00
mvtest_tv| SELECT mvtest_t.type,
sum(mvtest_t.amt) AS totamt
FROM mvtest_t
GROUP BY mvtest_t.type;
mvtest_tvv| SELECT sum(mvtest_tv.totamt) AS grandtot
FROM mvtest_tv;
mvtest_tvvmv| SELECT mvtest_tvvm.grandtot
FROM mvtest_tvvm;
2013-11-11 19:36:38 +01:00
pg_available_extension_versions| SELECT e.name,
e.version,
(x.extname IS NOT NULL) AS installed,
e.superuser,
e.relocatable,
e.schema,
e.requires,
2013-10-26 17:24:04 +02:00
e.comment
FROM (pg_available_extension_versions() e(name, version, superuser, relocatable, schema, requires, comment)
2014-04-30 18:01:19 +02:00
LEFT JOIN pg_extension x ON (((e.name = x.extname) AND (e.version = x.extversion))));
2013-11-11 19:36:38 +01:00
pg_available_extensions| SELECT e.name,
e.default_version,
x.extversion AS installed_version,
2013-10-26 17:24:04 +02:00
e.comment
FROM (pg_available_extensions() e(name, default_version, comment)
2014-04-30 18:01:19 +02:00
LEFT JOIN pg_extension x ON ((e.name = x.extname)));
2016-02-17 18:12:06 +01:00
pg_config| SELECT pg_config.name,
pg_config.setting
FROM pg_config() pg_config(name, setting);
2013-11-11 19:36:38 +01:00
pg_cursors| SELECT c.name,
c.statement,
c.is_holdable,
c.is_binary,
c.is_scrollable,
2013-10-26 17:24:04 +02:00
c.creation_time
FROM pg_cursor() c(name, statement, is_holdable, is_binary, is_scrollable, creation_time);
2015-05-09 01:09:26 +02:00
pg_file_settings| SELECT a.sourcefile,
a.sourceline,
a.seqno,
a.name,
Improve design and implementation of pg_file_settings view.
As first committed, this view reported on the file contents as they were
at the last SIGHUP event. That's not as useful as reporting on the current
contents, and what's more, it didn't work right on Windows unless the
current session had serviced at least one SIGHUP. Therefore, arrange to
re-read the files when pg_show_all_settings() is called. This requires
only minor refactoring so that we can pass changeVal = false to
set_config_option() so that it won't actually apply any changes locally.
In addition, add error reporting so that errors that would prevent the
configuration files from being loaded, or would prevent individual settings
from being applied, are visible directly in the view. This makes the view
usable for pre-testing whether edits made in the config files will have the
desired effect, before one actually issues a SIGHUP.
I also added an "applied" column so that it's easy to identify entries that
are superseded by later entries; this was the main use-case for the original
design, but it seemed unnecessarily hard to use for that.
Also fix a 9.4.1 regression that allowed multiple entries for a
PGC_POSTMASTER variable to cause bogus complaints in the postmaster log.
(The issue here was that commit bf007a27acd7b2fb unintentionally reverted
3e3f65973a3c94a6, which suppressed any duplicate entries within
ParseConfigFp. However, since the original coding of the pg_file_settings
view depended on such suppression *not* happening, we couldn't have fixed
this issue now without first doing something with pg_file_settings.
Now we suppress duplicates by marking them "ignored" within
ProcessConfigFileInternal, which doesn't hide them in the view.)
Lesser changes include:
Drive the view directly off the ConfigVariable list, instead of making a
basically-equivalent second copy of the data. There's no longer any need
to hang onto the data permanently, anyway.
Convert show_all_file_settings() to do its work in one call and return a
tuplestore; this avoids risks associated with assuming that the GUC state
will hold still over the course of query execution. (I think there were
probably latent bugs here, though you might need something like a cursor
on the view to expose them.)
Arrange to run SIGHUP processing in a short-lived memory context, to
forestall process-lifespan memory leaks. (There is one known leak in this
code, in ProcessConfigDirectory; it seems minor enough to not be worth
back-patching a specific fix for.)
Remove mistaken assignment to ConfigFileLineno that caused line counting
after an include_dir directive to be completely wrong.
Add missed failure check in AlterSystemSetConfigFile(). We don't really
expect ParseConfigFp() to fail, but that's not an excuse for not checking.
2015-06-29 00:06:14 +02:00
a.setting,
a.applied,
a.error
FROM pg_show_all_file_settings() a(sourcefile, sourceline, seqno, name, setting, applied, error);
2013-11-11 19:36:38 +01:00
pg_group| SELECT pg_authid.rolname AS groname,
pg_authid.oid AS grosysid,
2013-10-26 17:24:04 +02:00
ARRAY( SELECT pg_auth_members.member
FROM pg_auth_members
WHERE (pg_auth_members.roleid = pg_authid.oid)) AS grolist
FROM pg_authid
2014-12-23 19:35:49 +01:00
WHERE (NOT pg_authid.rolcanlogin);
2013-11-11 19:36:38 +01:00
pg_indexes| SELECT n.nspname AS schemaname,
c.relname AS tablename,
i.relname AS indexname,
t.spcname AS tablespace,
2013-10-26 17:24:04 +02:00
pg_get_indexdef(i.oid) AS indexdef
FROM ((((pg_index x
2014-04-30 18:01:19 +02:00
JOIN pg_class c ON ((c.oid = x.indrelid)))
JOIN pg_class i ON ((i.oid = x.indexrelid)))
LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace)))
LEFT JOIN pg_tablespace t ON ((t.oid = i.reltablespace)))
2013-10-26 17:24:04 +02:00
WHERE ((c.relkind = ANY (ARRAY['r'::"char", 'm'::"char"])) AND (i.relkind = 'i'::"char"));
2013-11-11 19:36:38 +01:00
pg_locks| SELECT l.locktype,
l.database,
l.relation,
l.page,
l.tuple,
l.virtualxid,
l.transactionid,
l.classid,
l.objid,
l.objsubid,
l.virtualtransaction,
l.pid,
l.mode,
l.granted,
2013-10-26 17:24:04 +02:00
l.fastpath
FROM pg_lock_status() l(locktype, database, relation, page, tuple, virtualxid, transactionid, classid, objid, objsubid, virtualtransaction, pid, mode, granted, fastpath);
2013-11-11 19:36:38 +01:00
pg_matviews| SELECT n.nspname AS schemaname,
c.relname AS matviewname,
pg_get_userbyid(c.relowner) AS matviewowner,
t.spcname AS tablespace,
c.relhasindex AS hasindexes,
c.relispopulated AS ispopulated,
2013-10-26 17:24:04 +02:00
pg_get_viewdef(c.oid) AS definition
FROM ((pg_class c
2014-04-30 18:01:19 +02:00
LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace)))
LEFT JOIN pg_tablespace t ON ((t.oid = c.reltablespace)))
2013-10-26 17:24:04 +02:00
WHERE (c.relkind = 'm'::"char");
2014-10-03 22:31:53 +02:00
pg_policies| SELECT n.nspname AS schemaname,
c.relname AS tablename,
Rename pg_rowsecurity -> pg_policy and other fixes
As pointed out by Robert, we should really have named pg_rowsecurity
pg_policy, as the objects stored in that catalog are policies. This
patch fixes that and updates the column names to start with 'pol' to
match the new catalog name.
The security consideration for COPY with row level security, also
pointed out by Robert, has also been addressed by remembering and
re-checking the OID of the relation initially referenced during COPY
processing, to make sure it hasn't changed under us by the time we
finish planning out the query which has been built.
Robert and Alvaro also commented on missing OCLASS and OBJECT entries
for POLICY (formerly ROWSECURITY or POLICY, depending) in various
places. This patch fixes that too, which also happens to add the
ability to COMMENT on policies.
In passing, attempt to improve the consistency of messages, comments,
and documentation as well. This removes various incarnations of
'row-security', 'row-level security', 'Row-security', etc, in favor
of 'policy', 'row level security' or 'row_security' as appropriate.
Happy Thanksgiving!
2014-11-27 07:06:36 +01:00
pol.polname AS policyname,
Row-Level Security Policies (RLS)
Building on the updatable security-barrier views work, add the
ability to define policies on tables to limit the set of rows
which are returned from a query and which are allowed to be added
to a table. Expressions defined by the policy for filtering are
added to the security barrier quals of the query, while expressions
defined to check records being added to a table are added to the
with-check options of the query.
New top-level commands are CREATE/ALTER/DROP POLICY and are
controlled by the table owner. Row Security is able to be enabled
and disabled by the owner on a per-table basis using
ALTER TABLE .. ENABLE/DISABLE ROW SECURITY.
Per discussion, ROW SECURITY is disabled on tables by default and
must be enabled for policies on the table to be used. If no
policies exist on a table with ROW SECURITY enabled, a default-deny
policy is used and no records will be visible.
By default, row security is applied at all times except for the
table owner and the superuser. A new GUC, row_security, is added
which can be set to ON, OFF, or FORCE. When set to FORCE, row
security will be applied even for the table owner and superusers.
When set to OFF, row security will be disabled when allowed and an
error will be thrown if the user does not have rights to bypass row
security.
Per discussion, pg_dump sets row_security = OFF by default to ensure
that exports and backups will have all data in the table or will
error if there are insufficient privileges to bypass row security.
A new option has been added to pg_dump, --enable-row-security, to
ask pg_dump to export with row security enabled.
A new role capability, BYPASSRLS, which can only be set by the
superuser, is added to allow other users to be able to bypass row
security using row_security = OFF.
Many thanks to the various individuals who have helped with the
design, particularly Robert Haas for his feedback.
Authors include Craig Ringer, KaiGai Kohei, Adam Brightwell, Dean
Rasheed, with additional changes and rework by me.
Reviewers have included all of the above, Greg Smith,
Jeff McCormick, and Robert Haas.
2014-09-19 17:18:35 +02:00
CASE
Rename pg_rowsecurity -> pg_policy and other fixes
As pointed out by Robert, we should really have named pg_rowsecurity
pg_policy, as the objects stored in that catalog are policies. This
patch fixes that and updates the column names to start with 'pol' to
match the new catalog name.
The security consideration for COPY with row level security, also
pointed out by Robert, has also been addressed by remembering and
re-checking the OID of the relation initially referenced during COPY
processing, to make sure it hasn't changed under us by the time we
finish planning out the query which has been built.
Robert and Alvaro also commented on missing OCLASS and OBJECT entries
for POLICY (formerly ROWSECURITY or POLICY, depending) in various
places. This patch fixes that too, which also happens to add the
ability to COMMENT on policies.
In passing, attempt to improve the consistency of messages, comments,
and documentation as well. This removes various incarnations of
'row-security', 'row-level security', 'Row-security', etc, in favor
of 'policy', 'row level security' or 'row_security' as appropriate.
Happy Thanksgiving!
2014-11-27 07:06:36 +01:00
WHEN (pol.polroles = '{0}'::oid[]) THEN (string_to_array('public'::text, ''::text))::name[]
Row-Level Security Policies (RLS)
Building on the updatable security-barrier views work, add the
ability to define policies on tables to limit the set of rows
which are returned from a query and which are allowed to be added
to a table. Expressions defined by the policy for filtering are
added to the security barrier quals of the query, while expressions
defined to check records being added to a table are added to the
with-check options of the query.
New top-level commands are CREATE/ALTER/DROP POLICY and are
controlled by the table owner. Row Security is able to be enabled
and disabled by the owner on a per-table basis using
ALTER TABLE .. ENABLE/DISABLE ROW SECURITY.
Per discussion, ROW SECURITY is disabled on tables by default and
must be enabled for policies on the table to be used. If no
policies exist on a table with ROW SECURITY enabled, a default-deny
policy is used and no records will be visible.
By default, row security is applied at all times except for the
table owner and the superuser. A new GUC, row_security, is added
which can be set to ON, OFF, or FORCE. When set to FORCE, row
security will be applied even for the table owner and superusers.
When set to OFF, row security will be disabled when allowed and an
error will be thrown if the user does not have rights to bypass row
security.
Per discussion, pg_dump sets row_security = OFF by default to ensure
that exports and backups will have all data in the table or will
error if there are insufficient privileges to bypass row security.
A new option has been added to pg_dump, --enable-row-security, to
ask pg_dump to export with row security enabled.
A new role capability, BYPASSRLS, which can only be set by the
superuser, is added to allow other users to be able to bypass row
security using row_security = OFF.
Many thanks to the various individuals who have helped with the
design, particularly Robert Haas for his feedback.
Authors include Craig Ringer, KaiGai Kohei, Adam Brightwell, Dean
Rasheed, with additional changes and rework by me.
Reviewers have included all of the above, Greg Smith,
Jeff McCormick, and Robert Haas.
2014-09-19 17:18:35 +02:00
ELSE ARRAY( SELECT pg_authid.rolname
FROM pg_authid
Rename pg_rowsecurity -> pg_policy and other fixes
As pointed out by Robert, we should really have named pg_rowsecurity
pg_policy, as the objects stored in that catalog are policies. This
patch fixes that and updates the column names to start with 'pol' to
match the new catalog name.
The security consideration for COPY with row level security, also
pointed out by Robert, has also been addressed by remembering and
re-checking the OID of the relation initially referenced during COPY
processing, to make sure it hasn't changed under us by the time we
finish planning out the query which has been built.
Robert and Alvaro also commented on missing OCLASS and OBJECT entries
for POLICY (formerly ROWSECURITY or POLICY, depending) in various
places. This patch fixes that too, which also happens to add the
ability to COMMENT on policies.
In passing, attempt to improve the consistency of messages, comments,
and documentation as well. This removes various incarnations of
'row-security', 'row-level security', 'Row-security', etc, in favor
of 'policy', 'row level security' or 'row_security' as appropriate.
Happy Thanksgiving!
2014-11-27 07:06:36 +01:00
WHERE (pg_authid.oid = ANY (pol.polroles))
Row-Level Security Policies (RLS)
Building on the updatable security-barrier views work, add the
ability to define policies on tables to limit the set of rows
which are returned from a query and which are allowed to be added
to a table. Expressions defined by the policy for filtering are
added to the security barrier quals of the query, while expressions
defined to check records being added to a table are added to the
with-check options of the query.
New top-level commands are CREATE/ALTER/DROP POLICY and are
controlled by the table owner. Row Security is able to be enabled
and disabled by the owner on a per-table basis using
ALTER TABLE .. ENABLE/DISABLE ROW SECURITY.
Per discussion, ROW SECURITY is disabled on tables by default and
must be enabled for policies on the table to be used. If no
policies exist on a table with ROW SECURITY enabled, a default-deny
policy is used and no records will be visible.
By default, row security is applied at all times except for the
table owner and the superuser. A new GUC, row_security, is added
which can be set to ON, OFF, or FORCE. When set to FORCE, row
security will be applied even for the table owner and superusers.
When set to OFF, row security will be disabled when allowed and an
error will be thrown if the user does not have rights to bypass row
security.
Per discussion, pg_dump sets row_security = OFF by default to ensure
that exports and backups will have all data in the table or will
error if there are insufficient privileges to bypass row security.
A new option has been added to pg_dump, --enable-row-security, to
ask pg_dump to export with row security enabled.
A new role capability, BYPASSRLS, which can only be set by the
superuser, is added to allow other users to be able to bypass row
security using row_security = OFF.
Many thanks to the various individuals who have helped with the
design, particularly Robert Haas for his feedback.
Authors include Craig Ringer, KaiGai Kohei, Adam Brightwell, Dean
Rasheed, with additional changes and rework by me.
Reviewers have included all of the above, Greg Smith,
Jeff McCormick, and Robert Haas.
2014-09-19 17:18:35 +02:00
ORDER BY pg_authid.rolname)
END AS roles,
2015-01-24 22:16:22 +01:00
CASE pol.polcmd
WHEN 'r'::"char" THEN 'SELECT'::text
WHEN 'a'::"char" THEN 'INSERT'::text
WHEN 'w'::"char" THEN 'UPDATE'::text
WHEN 'd'::"char" THEN 'DELETE'::text
WHEN '*'::"char" THEN 'ALL'::text
ELSE NULL::text
Row-Level Security Policies (RLS)
Building on the updatable security-barrier views work, add the
ability to define policies on tables to limit the set of rows
which are returned from a query and which are allowed to be added
to a table. Expressions defined by the policy for filtering are
added to the security barrier quals of the query, while expressions
defined to check records being added to a table are added to the
with-check options of the query.
New top-level commands are CREATE/ALTER/DROP POLICY and are
controlled by the table owner. Row Security is able to be enabled
and disabled by the owner on a per-table basis using
ALTER TABLE .. ENABLE/DISABLE ROW SECURITY.
Per discussion, ROW SECURITY is disabled on tables by default and
must be enabled for policies on the table to be used. If no
policies exist on a table with ROW SECURITY enabled, a default-deny
policy is used and no records will be visible.
By default, row security is applied at all times except for the
table owner and the superuser. A new GUC, row_security, is added
which can be set to ON, OFF, or FORCE. When set to FORCE, row
security will be applied even for the table owner and superusers.
When set to OFF, row security will be disabled when allowed and an
error will be thrown if the user does not have rights to bypass row
security.
Per discussion, pg_dump sets row_security = OFF by default to ensure
that exports and backups will have all data in the table or will
error if there are insufficient privileges to bypass row security.
A new option has been added to pg_dump, --enable-row-security, to
ask pg_dump to export with row security enabled.
A new role capability, BYPASSRLS, which can only be set by the
superuser, is added to allow other users to be able to bypass row
security using row_security = OFF.
Many thanks to the various individuals who have helped with the
design, particularly Robert Haas for his feedback.
Authors include Craig Ringer, KaiGai Kohei, Adam Brightwell, Dean
Rasheed, with additional changes and rework by me.
Reviewers have included all of the above, Greg Smith,
Jeff McCormick, and Robert Haas.
2014-09-19 17:18:35 +02:00
END AS cmd,
Rename pg_rowsecurity -> pg_policy and other fixes
As pointed out by Robert, we should really have named pg_rowsecurity
pg_policy, as the objects stored in that catalog are policies. This
patch fixes that and updates the column names to start with 'pol' to
match the new catalog name.
The security consideration for COPY with row level security, also
pointed out by Robert, has also been addressed by remembering and
re-checking the OID of the relation initially referenced during COPY
processing, to make sure it hasn't changed under us by the time we
finish planning out the query which has been built.
Robert and Alvaro also commented on missing OCLASS and OBJECT entries
for POLICY (formerly ROWSECURITY or POLICY, depending) in various
places. This patch fixes that too, which also happens to add the
ability to COMMENT on policies.
In passing, attempt to improve the consistency of messages, comments,
and documentation as well. This removes various incarnations of
'row-security', 'row-level security', 'Row-security', etc, in favor
of 'policy', 'row level security' or 'row_security' as appropriate.
Happy Thanksgiving!
2014-11-27 07:06:36 +01:00
pg_get_expr(pol.polqual, pol.polrelid) AS qual,
pg_get_expr(pol.polwithcheck, pol.polrelid) AS with_check
FROM ((pg_policy pol
JOIN pg_class c ON ((c.oid = pol.polrelid)))
2014-10-03 22:31:53 +02:00
LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace)));
2013-11-11 19:36:38 +01:00
pg_prepared_statements| SELECT p.name,
p.statement,
p.prepare_time,
p.parameter_types,
2013-10-26 17:24:04 +02:00
p.from_sql
FROM pg_prepared_statement() p(name, statement, prepare_time, parameter_types, from_sql);
2013-11-11 19:36:38 +01:00
pg_prepared_xacts| SELECT p.transaction,
p.gid,
p.prepared,
u.rolname AS owner,
2013-10-26 17:24:04 +02:00
d.datname AS database
FROM ((pg_prepared_xact() p(transaction, gid, prepared, ownerid, dbid)
2014-04-30 18:01:19 +02:00
LEFT JOIN pg_authid u ON ((p.ownerid = u.oid)))
LEFT JOIN pg_database d ON ((p.dbid = d.oid)));
Introduce replication progress tracking infrastructure.
When implementing a replication solution ontop of logical decoding, two
related problems exist:
* How to safely keep track of replication progress
* How to change replication behavior, based on the origin of a row;
e.g. to avoid loops in bi-directional replication setups
The solution to these problems, as implemented here, consist out of
three parts:
1) 'replication origins', which identify nodes in a replication setup.
2) 'replication progress tracking', which remembers, for each
replication origin, how far replay has progressed in a efficient and
crash safe manner.
3) The ability to filter out changes performed on the behest of a
replication origin during logical decoding; this allows complex
replication topologies. E.g. by filtering all replayed changes out.
Most of this could also be implemented in "userspace", e.g. by inserting
additional rows contain origin information, but that ends up being much
less efficient and more complicated. We don't want to require various
replication solutions to reimplement logic for this independently. The
infrastructure is intended to be generic enough to be reusable.
This infrastructure also replaces the 'nodeid' infrastructure of commit
timestamps. It is intended to provide all the former capabilities,
except that there's only 2^16 different origins; but now they integrate
with logical decoding. Additionally more functionality is accessible via
SQL. Since the commit timestamp infrastructure has also been introduced
in 9.5 (commit 73c986add) changing the API is not a problem.
For now the number of origins for which the replication progress can be
tracked simultaneously is determined by the max_replication_slots
GUC. That GUC is not a perfect match to configure this, but there
doesn't seem to be sufficient reason to introduce a separate new one.
Bumps both catversion and wal page magic.
Author: Andres Freund, with contributions from Petr Jelinek and Craig Ringer
Reviewed-By: Heikki Linnakangas, Petr Jelinek, Robert Haas, Steve Singer
Discussion: 20150216002155.GI15326@awork2.anarazel.de,
20140923182422.GA15776@alap3.anarazel.de,
20131114172632.GE7522@alap2.anarazel.de
2015-04-29 19:30:53 +02:00
pg_replication_origin_status| SELECT pg_show_replication_origin_status.local_id,
pg_show_replication_origin_status.external_id,
pg_show_replication_origin_status.remote_lsn,
pg_show_replication_origin_status.local_lsn
FROM pg_show_replication_origin_status() pg_show_replication_origin_status(local_id, external_id, remote_lsn, local_lsn);
2014-02-01 04:45:17 +01:00
pg_replication_slots| SELECT l.slot_name,
Introduce logical decoding.
This feature, building on previous commits, allows the write-ahead log
stream to be decoded into a series of logical changes; that is,
inserts, updates, and deletes and the transactions which contain them.
It is capable of handling decoding even across changes to the schema
of the effected tables. The output format is controlled by a
so-called "output plugin"; an example is included. To make use of
this in a real replication system, the output plugin will need to be
modified to produce output in the format appropriate to that system,
and to perform filtering.
Currently, information can be extracted from the logical decoding
system only via SQL; future commits will add the ability to stream
changes via walsender.
Andres Freund, with review and other contributions from many other
people, including Álvaro Herrera, Abhijit Menon-Sen, Peter Gheogegan,
Kevin Grittner, Robert Haas, Heikki Linnakangas, Fujii Masao, Abhijit
Menon-Sen, Michael Paquier, Simon Riggs, Craig Ringer, and Steve
Singer.
2014-03-03 22:32:18 +01:00
l.plugin,
2014-02-01 04:45:17 +01:00
l.slot_type,
l.datoid,
d.datname AS database,
l.active,
2015-04-22 09:42:36 +02:00
l.active_pid,
2014-02-01 04:45:17 +01:00
l.xmin,
Introduce logical decoding.
This feature, building on previous commits, allows the write-ahead log
stream to be decoded into a series of logical changes; that is,
inserts, updates, and deletes and the transactions which contain them.
It is capable of handling decoding even across changes to the schema
of the effected tables. The output format is controlled by a
so-called "output plugin"; an example is included. To make use of
this in a real replication system, the output plugin will need to be
modified to produce output in the format appropriate to that system,
and to perform filtering.
Currently, information can be extracted from the logical decoding
system only via SQL; future commits will add the ability to stream
changes via walsender.
Andres Freund, with review and other contributions from many other
people, including Álvaro Herrera, Abhijit Menon-Sen, Peter Gheogegan,
Kevin Grittner, Robert Haas, Heikki Linnakangas, Fujii Masao, Abhijit
Menon-Sen, Michael Paquier, Simon Riggs, Craig Ringer, and Steve
Singer.
2014-03-03 22:32:18 +01:00
l.catalog_xmin,
2015-08-10 13:28:18 +02:00
l.restart_lsn,
l.confirmed_flush_lsn
FROM (pg_get_replication_slots() l(slot_name, plugin, slot_type, datoid, active, active_pid, xmin, catalog_xmin, restart_lsn, confirmed_flush_lsn)
2014-04-30 18:01:19 +02:00
LEFT JOIN pg_database d ON ((l.datoid = d.oid)));
2013-11-11 19:36:38 +01:00
pg_roles| SELECT pg_authid.rolname,
2014-12-23 19:35:49 +01:00
pg_authid.rolsuper,
pg_authid.rolinherit,
pg_authid.rolcreaterole,
pg_authid.rolcreatedb,
pg_authid.rolcanlogin,
pg_authid.rolreplication,
2013-11-11 19:36:38 +01:00
pg_authid.rolconnlimit,
'********'::text AS rolpassword,
pg_authid.rolvaliduntil,
2014-12-23 19:35:49 +01:00
pg_authid.rolbypassrls,
2013-11-11 19:36:38 +01:00
s.setconfig AS rolconfig,
2013-10-26 17:24:04 +02:00
pg_authid.oid
FROM (pg_authid
2014-04-30 18:01:19 +02:00
LEFT JOIN pg_db_role_setting s ON (((pg_authid.oid = s.setrole) AND (s.setdatabase = (0)::oid))));
2013-11-11 19:36:38 +01:00
pg_rules| SELECT n.nspname AS schemaname,
c.relname AS tablename,
r.rulename,
2013-10-26 17:24:04 +02:00
pg_get_ruledef(r.oid) AS definition
FROM ((pg_rewrite r
2014-04-30 18:01:19 +02:00
JOIN pg_class c ON ((c.oid = r.ev_class)))
LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace)))
2013-10-26 17:24:04 +02:00
WHERE (r.rulename <> '_RETURN'::name);
2014-04-30 19:26:26 +02:00
pg_seclabels| SELECT l.objoid,
l.classoid,
l.objsubid,
2014-04-30 18:48:12 +02:00
CASE
2014-04-30 19:26:26 +02:00
WHEN (rel.relkind = 'r'::"char") THEN 'table'::text
WHEN (rel.relkind = 'v'::"char") THEN 'view'::text
WHEN (rel.relkind = 'm'::"char") THEN 'materialized view'::text
WHEN (rel.relkind = 'S'::"char") THEN 'sequence'::text
WHEN (rel.relkind = 'f'::"char") THEN 'foreign table'::text
ELSE NULL::text
2014-04-30 18:48:12 +02:00
END AS objtype,
2014-04-30 19:26:26 +02:00
rel.relnamespace AS objnamespace,
2014-04-30 18:48:12 +02:00
CASE
2014-04-30 19:26:26 +02:00
WHEN pg_table_is_visible(rel.oid) THEN quote_ident((rel.relname)::text)
ELSE ((quote_ident((nsp.nspname)::text) || '.'::text) || quote_ident((rel.relname)::text))
2014-04-30 18:48:12 +02:00
END AS objname,
2014-04-30 19:26:26 +02:00
l.provider,
l.label
FROM ((pg_seclabel l
JOIN pg_class rel ON (((l.classoid = rel.tableoid) AND (l.objoid = rel.oid))))
JOIN pg_namespace nsp ON ((rel.relnamespace = nsp.oid)))
WHERE (l.objsubid = 0)
UNION ALL
SELECT l.objoid,
l.classoid,
l.objsubid,
'column'::text AS objtype,
rel.relnamespace AS objnamespace,
((
CASE
WHEN pg_table_is_visible(rel.oid) THEN quote_ident((rel.relname)::text)
ELSE ((quote_ident((nsp.nspname)::text) || '.'::text) || quote_ident((rel.relname)::text))
END || '.'::text) || (att.attname)::text) AS objname,
l.provider,
l.label
FROM (((pg_seclabel l
JOIN pg_class rel ON (((l.classoid = rel.tableoid) AND (l.objoid = rel.oid))))
JOIN pg_attribute att ON (((rel.oid = att.attrelid) AND (l.objsubid = att.attnum))))
JOIN pg_namespace nsp ON ((rel.relnamespace = nsp.oid)))
WHERE (l.objsubid <> 0)
UNION ALL
SELECT l.objoid,
l.classoid,
l.objsubid,
CASE
WHEN (pro.proisagg = true) THEN 'aggregate'::text
WHEN (pro.proisagg = false) THEN 'function'::text
ELSE NULL::text
END AS objtype,
pro.pronamespace AS objnamespace,
(((
CASE
WHEN pg_function_is_visible(pro.oid) THEN quote_ident((pro.proname)::text)
ELSE ((quote_ident((nsp.nspname)::text) || '.'::text) || quote_ident((pro.proname)::text))
END || '('::text) || pg_get_function_arguments(pro.oid)) || ')'::text) AS objname,
l.provider,
l.label
FROM ((pg_seclabel l
JOIN pg_proc pro ON (((l.classoid = pro.tableoid) AND (l.objoid = pro.oid))))
JOIN pg_namespace nsp ON ((pro.pronamespace = nsp.oid)))
WHERE (l.objsubid = 0)
UNION ALL
SELECT l.objoid,
l.classoid,
l.objsubid,
CASE
WHEN (typ.typtype = 'd'::"char") THEN 'domain'::text
ELSE 'type'::text
END AS objtype,
typ.typnamespace AS objnamespace,
CASE
WHEN pg_type_is_visible(typ.oid) THEN quote_ident((typ.typname)::text)
ELSE ((quote_ident((nsp.nspname)::text) || '.'::text) || quote_ident((typ.typname)::text))
END AS objname,
l.provider,
l.label
FROM ((pg_seclabel l
JOIN pg_type typ ON (((l.classoid = typ.tableoid) AND (l.objoid = typ.oid))))
JOIN pg_namespace nsp ON ((typ.typnamespace = nsp.oid)))
WHERE (l.objsubid = 0)
UNION ALL
SELECT l.objoid,
l.classoid,
l.objsubid,
'large object'::text AS objtype,
NULL::oid AS objnamespace,
(l.objoid)::text AS objname,
l.provider,
l.label
FROM (pg_seclabel l
JOIN pg_largeobject_metadata lom ON ((l.objoid = lom.oid)))
WHERE ((l.classoid = ('pg_largeobject'::regclass)::oid) AND (l.objsubid = 0))
UNION ALL
SELECT l.objoid,
l.classoid,
l.objsubid,
'language'::text AS objtype,
NULL::oid AS objnamespace,
quote_ident((lan.lanname)::text) AS objname,
l.provider,
l.label
FROM (pg_seclabel l
JOIN pg_language lan ON (((l.classoid = lan.tableoid) AND (l.objoid = lan.oid))))
WHERE (l.objsubid = 0)
2014-04-30 18:48:12 +02:00
UNION ALL
SELECT l.objoid,
l.classoid,
l.objsubid,
'schema'::text AS objtype,
nsp.oid AS objnamespace,
quote_ident((nsp.nspname)::text) AS objname,
l.provider,
l.label
FROM (pg_seclabel l
JOIN pg_namespace nsp ON (((l.classoid = nsp.tableoid) AND (l.objoid = nsp.oid))))
2014-04-30 19:26:26 +02:00
WHERE (l.objsubid = 0)
UNION ALL
SELECT l.objoid,
l.classoid,
l.objsubid,
'event trigger'::text AS objtype,
NULL::oid AS objnamespace,
quote_ident((evt.evtname)::text) AS objname,
l.provider,
l.label
FROM (pg_seclabel l
JOIN pg_event_trigger evt ON (((l.classoid = evt.tableoid) AND (l.objoid = evt.oid))))
WHERE (l.objsubid = 0)
UNION ALL
SELECT l.objoid,
l.classoid,
0 AS objsubid,
'database'::text AS objtype,
NULL::oid AS objnamespace,
quote_ident((dat.datname)::text) AS objname,
l.provider,
l.label
FROM (pg_shseclabel l
JOIN pg_database dat ON (((l.classoid = dat.tableoid) AND (l.objoid = dat.oid))))
UNION ALL
SELECT l.objoid,
l.classoid,
0 AS objsubid,
'tablespace'::text AS objtype,
NULL::oid AS objnamespace,
quote_ident((spc.spcname)::text) AS objname,
l.provider,
l.label
FROM (pg_shseclabel l
JOIN pg_tablespace spc ON (((l.classoid = spc.tableoid) AND (l.objoid = spc.oid))))
2013-11-11 19:36:38 +01:00
UNION ALL
2014-04-30 19:26:26 +02:00
SELECT l.objoid,
l.classoid,
0 AS objsubid,
'role'::text AS objtype,
NULL::oid AS objnamespace,
quote_ident((rol.rolname)::text) AS objname,
l.provider,
l.label
FROM (pg_shseclabel l
JOIN pg_authid rol ON (((l.classoid = rol.tableoid) AND (l.objoid = rol.oid))));
2013-11-11 19:36:38 +01:00
pg_settings| SELECT a.name,
a.setting,
a.unit,
a.category,
a.short_desc,
a.extra_desc,
a.context,
a.vartype,
a.source,
a.min_val,
a.max_val,
a.enumvals,
a.boot_val,
a.reset_val,
a.sourcefile,
2015-05-15 02:08:51 +02:00
a.sourceline,
a.pending_restart
FROM pg_show_all_settings() a(name, setting, unit, category, short_desc, extra_desc, context, vartype, source, min_val, max_val, enumvals, boot_val, reset_val, sourcefile, sourceline, pending_restart);
2013-11-11 19:36:38 +01:00
pg_shadow| SELECT pg_authid.rolname AS usename,
pg_authid.oid AS usesysid,
2014-12-23 19:35:49 +01:00
pg_authid.rolcreatedb AS usecreatedb,
pg_authid.rolsuper AS usesuper,
pg_authid.rolreplication AS userepl,
2015-01-29 03:47:15 +01:00
pg_authid.rolbypassrls AS usebypassrls,
2013-11-11 19:36:38 +01:00
pg_authid.rolpassword AS passwd,
(pg_authid.rolvaliduntil)::abstime AS valuntil,
2013-10-26 17:24:04 +02:00
s.setconfig AS useconfig
FROM (pg_authid
2014-04-30 18:01:19 +02:00
LEFT JOIN pg_db_role_setting s ON (((pg_authid.oid = s.setrole) AND (s.setdatabase = (0)::oid))))
2014-12-23 19:35:49 +01:00
WHERE pg_authid.rolcanlogin;
2013-11-11 19:36:38 +01:00
pg_stat_activity| SELECT s.datid,
d.datname,
s.pid,
s.usesysid,
u.rolname AS usename,
s.application_name,
s.client_addr,
s.client_hostname,
s.client_port,
s.backend_start,
s.xact_start,
s.query_start,
s.state_change,
2016-03-10 18:44:09 +01:00
s.wait_event_type,
s.wait_event,
2013-11-11 19:36:38 +01:00
s.state,
2014-02-25 18:34:04 +01:00
s.backend_xid,
s.backend_xmin,
2013-10-26 17:24:04 +02:00
s.query
2013-11-11 19:36:38 +01:00
FROM pg_database d,
2016-03-10 18:44:09 +01:00
pg_stat_get_activity(NULL::integer) s(datid, pid, usesysid, application_name, state, query, wait_event_type, wait_event, xact_start, query_start, backend_start, state_change, client_addr, client_hostname, client_port, backend_xid, backend_xmin, ssl, sslversion, sslcipher, sslbits, sslcompression, sslclientdn),
2013-10-26 17:24:04 +02:00
pg_authid u
WHERE ((s.datid = d.oid) AND (s.usesysid = u.oid));
2013-11-11 19:36:38 +01:00
pg_stat_all_indexes| SELECT c.oid AS relid,
i.oid AS indexrelid,
n.nspname AS schemaname,
c.relname,
i.relname AS indexrelname,
pg_stat_get_numscans(i.oid) AS idx_scan,
pg_stat_get_tuples_returned(i.oid) AS idx_tup_read,
2013-10-26 17:24:04 +02:00
pg_stat_get_tuples_fetched(i.oid) AS idx_tup_fetch
FROM (((pg_class c
2014-04-30 18:01:19 +02:00
JOIN pg_index x ON ((c.oid = x.indrelid)))
JOIN pg_class i ON ((i.oid = x.indexrelid)))
LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace)))
2013-10-26 17:24:04 +02:00
WHERE (c.relkind = ANY (ARRAY['r'::"char", 't'::"char", 'm'::"char"]));
2013-11-11 19:36:38 +01:00
pg_stat_all_tables| SELECT c.oid AS relid,
n.nspname AS schemaname,
c.relname,
pg_stat_get_numscans(c.oid) AS seq_scan,
pg_stat_get_tuples_returned(c.oid) AS seq_tup_read,
(sum(pg_stat_get_numscans(i.indexrelid)))::bigint AS idx_scan,
((sum(pg_stat_get_tuples_fetched(i.indexrelid)))::bigint + pg_stat_get_tuples_fetched(c.oid)) AS idx_tup_fetch,
pg_stat_get_tuples_inserted(c.oid) AS n_tup_ins,
pg_stat_get_tuples_updated(c.oid) AS n_tup_upd,
pg_stat_get_tuples_deleted(c.oid) AS n_tup_del,
pg_stat_get_tuples_hot_updated(c.oid) AS n_tup_hot_upd,
pg_stat_get_live_tuples(c.oid) AS n_live_tup,
pg_stat_get_dead_tuples(c.oid) AS n_dead_tup,
pg_stat_get_mod_since_analyze(c.oid) AS n_mod_since_analyze,
pg_stat_get_last_vacuum_time(c.oid) AS last_vacuum,
pg_stat_get_last_autovacuum_time(c.oid) AS last_autovacuum,
pg_stat_get_last_analyze_time(c.oid) AS last_analyze,
pg_stat_get_last_autoanalyze_time(c.oid) AS last_autoanalyze,
pg_stat_get_vacuum_count(c.oid) AS vacuum_count,
pg_stat_get_autovacuum_count(c.oid) AS autovacuum_count,
pg_stat_get_analyze_count(c.oid) AS analyze_count,
2013-10-26 17:24:04 +02:00
pg_stat_get_autoanalyze_count(c.oid) AS autoanalyze_count
FROM ((pg_class c
2014-04-30 18:01:19 +02:00
LEFT JOIN pg_index i ON ((c.oid = i.indrelid)))
LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace)))
2013-10-26 17:24:04 +02:00
WHERE (c.relkind = ANY (ARRAY['r'::"char", 't'::"char", 'm'::"char"]))
GROUP BY c.oid, n.nspname, c.relname;
2014-01-28 18:58:22 +01:00
pg_stat_archiver| SELECT s.archived_count,
s.last_archived_wal,
s.last_archived_time,
s.failed_count,
s.last_failed_wal,
s.last_failed_time,
s.stats_reset
FROM pg_stat_get_archiver() s(archived_count, last_archived_wal, last_archived_time, failed_count, last_failed_wal, last_failed_time, stats_reset);
2013-11-11 19:36:38 +01:00
pg_stat_bgwriter| SELECT pg_stat_get_bgwriter_timed_checkpoints() AS checkpoints_timed,
pg_stat_get_bgwriter_requested_checkpoints() AS checkpoints_req,
pg_stat_get_checkpoint_write_time() AS checkpoint_write_time,
pg_stat_get_checkpoint_sync_time() AS checkpoint_sync_time,
pg_stat_get_bgwriter_buf_written_checkpoints() AS buffers_checkpoint,
pg_stat_get_bgwriter_buf_written_clean() AS buffers_clean,
pg_stat_get_bgwriter_maxwritten_clean() AS maxwritten_clean,
pg_stat_get_buf_written_backend() AS buffers_backend,
pg_stat_get_buf_fsync_backend() AS buffers_backend_fsync,
pg_stat_get_buf_alloc() AS buffers_alloc,
2013-10-26 17:24:04 +02:00
pg_stat_get_bgwriter_stat_reset_time() AS stats_reset;
2013-11-11 19:36:38 +01:00
pg_stat_database| SELECT d.oid AS datid,
d.datname,
pg_stat_get_db_numbackends(d.oid) AS numbackends,
pg_stat_get_db_xact_commit(d.oid) AS xact_commit,
pg_stat_get_db_xact_rollback(d.oid) AS xact_rollback,
(pg_stat_get_db_blocks_fetched(d.oid) - pg_stat_get_db_blocks_hit(d.oid)) AS blks_read,
pg_stat_get_db_blocks_hit(d.oid) AS blks_hit,
pg_stat_get_db_tuples_returned(d.oid) AS tup_returned,
pg_stat_get_db_tuples_fetched(d.oid) AS tup_fetched,
pg_stat_get_db_tuples_inserted(d.oid) AS tup_inserted,
pg_stat_get_db_tuples_updated(d.oid) AS tup_updated,
pg_stat_get_db_tuples_deleted(d.oid) AS tup_deleted,
pg_stat_get_db_conflict_all(d.oid) AS conflicts,
pg_stat_get_db_temp_files(d.oid) AS temp_files,
pg_stat_get_db_temp_bytes(d.oid) AS temp_bytes,
pg_stat_get_db_deadlocks(d.oid) AS deadlocks,
pg_stat_get_db_blk_read_time(d.oid) AS blk_read_time,
pg_stat_get_db_blk_write_time(d.oid) AS blk_write_time,
2013-10-26 17:24:04 +02:00
pg_stat_get_db_stat_reset_time(d.oid) AS stats_reset
FROM pg_database d;
2013-11-11 19:36:38 +01:00
pg_stat_database_conflicts| SELECT d.oid AS datid,
d.datname,
pg_stat_get_db_conflict_tablespace(d.oid) AS confl_tablespace,
pg_stat_get_db_conflict_lock(d.oid) AS confl_lock,
pg_stat_get_db_conflict_snapshot(d.oid) AS confl_snapshot,
pg_stat_get_db_conflict_bufferpin(d.oid) AS confl_bufferpin,
2013-10-26 17:24:04 +02:00
pg_stat_get_db_conflict_startup_deadlock(d.oid) AS confl_deadlock
FROM pg_database d;
2016-03-15 18:31:18 +01:00
pg_stat_progress_vacuum| SELECT s.pid,
s.datid,
d.datname,
s.relid,
CASE s.param1
WHEN 0 THEN 'initializing'::text
WHEN 1 THEN 'scanning heap'::text
WHEN 2 THEN 'vacuuming indexes'::text
WHEN 3 THEN 'vacuuming heap'::text
WHEN 4 THEN 'cleaning up indexes'::text
WHEN 5 THEN 'truncating heap'::text
WHEN 6 THEN 'performing final cleanup'::text
ELSE NULL::text
END AS phase,
s.param2 AS heap_blks_total,
s.param3 AS heap_blks_scanned,
s.param4 AS heap_blks_vacuumed,
s.param5 AS index_vacuum_count,
s.param6 AS max_dead_tuples,
s.param7 AS num_dead_tuples
FROM (pg_stat_get_progress_info('VACUUM'::text) s(pid, datid, relid, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10)
JOIN pg_database d ON ((s.datid = d.oid)));
2013-11-11 19:36:38 +01:00
pg_stat_replication| SELECT s.pid,
s.usesysid,
u.rolname AS usename,
s.application_name,
s.client_addr,
s.client_hostname,
s.client_port,
s.backend_start,
2014-02-25 18:34:04 +01:00
s.backend_xmin,
2013-11-11 19:36:38 +01:00
w.state,
w.sent_location,
w.write_location,
w.flush_location,
w.replay_location,
w.sync_priority,
2013-10-26 17:24:04 +02:00
w.sync_state
2016-03-10 18:44:09 +01:00
FROM pg_stat_get_activity(NULL::integer) s(datid, pid, usesysid, application_name, state, query, wait_event_type, wait_event, xact_start, query_start, backend_start, state_change, client_addr, client_hostname, client_port, backend_xid, backend_xmin, ssl, sslversion, sslcipher, sslbits, sslcompression, sslclientdn),
2013-11-11 19:36:38 +01:00
pg_authid u,
2013-10-26 17:24:04 +02:00
pg_stat_get_wal_senders() w(pid, state, sent_location, write_location, flush_location, replay_location, sync_priority, sync_state)
WHERE ((s.usesysid = u.oid) AND (s.pid = w.pid));
2015-04-12 19:07:46 +02:00
pg_stat_ssl| SELECT s.pid,
s.ssl,
s.sslversion AS version,
s.sslcipher AS cipher,
s.sslbits AS bits,
s.sslcompression AS compression,
s.sslclientdn AS clientdn
2016-03-10 18:44:09 +01:00
FROM pg_stat_get_activity(NULL::integer) s(datid, pid, usesysid, application_name, state, query, wait_event_type, wait_event, xact_start, query_start, backend_start, state_change, client_addr, client_hostname, client_port, backend_xid, backend_xmin, ssl, sslversion, sslcipher, sslbits, sslcompression, sslclientdn);
2013-11-11 19:36:38 +01:00
pg_stat_sys_indexes| SELECT pg_stat_all_indexes.relid,
pg_stat_all_indexes.indexrelid,
pg_stat_all_indexes.schemaname,
pg_stat_all_indexes.relname,
pg_stat_all_indexes.indexrelname,
pg_stat_all_indexes.idx_scan,
pg_stat_all_indexes.idx_tup_read,
2013-10-26 17:24:04 +02:00
pg_stat_all_indexes.idx_tup_fetch
FROM pg_stat_all_indexes
WHERE ((pg_stat_all_indexes.schemaname = ANY (ARRAY['pg_catalog'::name, 'information_schema'::name])) OR (pg_stat_all_indexes.schemaname ~ '^pg_toast'::text));
2013-11-11 19:36:38 +01:00
pg_stat_sys_tables| SELECT pg_stat_all_tables.relid,
pg_stat_all_tables.schemaname,
pg_stat_all_tables.relname,
pg_stat_all_tables.seq_scan,
pg_stat_all_tables.seq_tup_read,
pg_stat_all_tables.idx_scan,
pg_stat_all_tables.idx_tup_fetch,
pg_stat_all_tables.n_tup_ins,
pg_stat_all_tables.n_tup_upd,
pg_stat_all_tables.n_tup_del,
pg_stat_all_tables.n_tup_hot_upd,
pg_stat_all_tables.n_live_tup,
pg_stat_all_tables.n_dead_tup,
pg_stat_all_tables.n_mod_since_analyze,
pg_stat_all_tables.last_vacuum,
pg_stat_all_tables.last_autovacuum,
pg_stat_all_tables.last_analyze,
pg_stat_all_tables.last_autoanalyze,
pg_stat_all_tables.vacuum_count,
pg_stat_all_tables.autovacuum_count,
pg_stat_all_tables.analyze_count,
2013-10-26 17:24:04 +02:00
pg_stat_all_tables.autoanalyze_count
FROM pg_stat_all_tables
WHERE ((pg_stat_all_tables.schemaname = ANY (ARRAY['pg_catalog'::name, 'information_schema'::name])) OR (pg_stat_all_tables.schemaname ~ '^pg_toast'::text));
2013-11-11 19:36:38 +01:00
pg_stat_user_functions| SELECT p.oid AS funcid,
n.nspname AS schemaname,
p.proname AS funcname,
pg_stat_get_function_calls(p.oid) AS calls,
pg_stat_get_function_total_time(p.oid) AS total_time,
2013-10-26 17:24:04 +02:00
pg_stat_get_function_self_time(p.oid) AS self_time
FROM (pg_proc p
2014-04-30 18:01:19 +02:00
LEFT JOIN pg_namespace n ON ((n.oid = p.pronamespace)))
2013-10-26 17:24:04 +02:00
WHERE ((p.prolang <> (12)::oid) AND (pg_stat_get_function_calls(p.oid) IS NOT NULL));
2013-11-11 19:36:38 +01:00
pg_stat_user_indexes| SELECT pg_stat_all_indexes.relid,
pg_stat_all_indexes.indexrelid,
pg_stat_all_indexes.schemaname,
pg_stat_all_indexes.relname,
pg_stat_all_indexes.indexrelname,
pg_stat_all_indexes.idx_scan,
pg_stat_all_indexes.idx_tup_read,
2013-10-26 17:24:04 +02:00
pg_stat_all_indexes.idx_tup_fetch
FROM pg_stat_all_indexes
WHERE ((pg_stat_all_indexes.schemaname <> ALL (ARRAY['pg_catalog'::name, 'information_schema'::name])) AND (pg_stat_all_indexes.schemaname !~ '^pg_toast'::text));
2013-11-11 19:36:38 +01:00
pg_stat_user_tables| SELECT pg_stat_all_tables.relid,
pg_stat_all_tables.schemaname,
pg_stat_all_tables.relname,
pg_stat_all_tables.seq_scan,
pg_stat_all_tables.seq_tup_read,
pg_stat_all_tables.idx_scan,
pg_stat_all_tables.idx_tup_fetch,
pg_stat_all_tables.n_tup_ins,
pg_stat_all_tables.n_tup_upd,
pg_stat_all_tables.n_tup_del,
pg_stat_all_tables.n_tup_hot_upd,
pg_stat_all_tables.n_live_tup,
pg_stat_all_tables.n_dead_tup,
pg_stat_all_tables.n_mod_since_analyze,
pg_stat_all_tables.last_vacuum,
pg_stat_all_tables.last_autovacuum,
pg_stat_all_tables.last_analyze,
pg_stat_all_tables.last_autoanalyze,
pg_stat_all_tables.vacuum_count,
pg_stat_all_tables.autovacuum_count,
pg_stat_all_tables.analyze_count,
2013-10-26 17:24:04 +02:00
pg_stat_all_tables.autoanalyze_count
FROM pg_stat_all_tables
WHERE ((pg_stat_all_tables.schemaname <> ALL (ARRAY['pg_catalog'::name, 'information_schema'::name])) AND (pg_stat_all_tables.schemaname !~ '^pg_toast'::text));
2016-01-07 20:21:19 +01:00
pg_stat_wal_receiver| SELECT s.pid,
s.status,
s.receive_start_lsn,
s.receive_start_tli,
s.received_lsn,
s.received_tli,
s.last_msg_send_time,
s.last_msg_receipt_time,
s.latest_end_lsn,
s.latest_end_time,
2016-06-29 23:13:29 +02:00
s.slot_name,
2016-07-07 05:59:39 +02:00
s.conninfo
FROM pg_stat_get_wal_receiver() s(pid, status, receive_start_lsn, receive_start_tli, received_lsn, received_tli, last_msg_send_time, last_msg_receipt_time, latest_end_lsn, latest_end_time, slot_name, conninfo)
2016-01-07 20:21:19 +01:00
WHERE (s.pid IS NOT NULL);
2013-11-11 19:36:38 +01:00
pg_stat_xact_all_tables| SELECT c.oid AS relid,
n.nspname AS schemaname,
c.relname,
pg_stat_get_xact_numscans(c.oid) AS seq_scan,
pg_stat_get_xact_tuples_returned(c.oid) AS seq_tup_read,
(sum(pg_stat_get_xact_numscans(i.indexrelid)))::bigint AS idx_scan,
((sum(pg_stat_get_xact_tuples_fetched(i.indexrelid)))::bigint + pg_stat_get_xact_tuples_fetched(c.oid)) AS idx_tup_fetch,
pg_stat_get_xact_tuples_inserted(c.oid) AS n_tup_ins,
pg_stat_get_xact_tuples_updated(c.oid) AS n_tup_upd,
pg_stat_get_xact_tuples_deleted(c.oid) AS n_tup_del,
2013-10-26 17:24:04 +02:00
pg_stat_get_xact_tuples_hot_updated(c.oid) AS n_tup_hot_upd
FROM ((pg_class c
2014-04-30 18:01:19 +02:00
LEFT JOIN pg_index i ON ((c.oid = i.indrelid)))
LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace)))
2013-10-26 17:24:04 +02:00
WHERE (c.relkind = ANY (ARRAY['r'::"char", 't'::"char", 'm'::"char"]))
GROUP BY c.oid, n.nspname, c.relname;
2013-11-11 19:36:38 +01:00
pg_stat_xact_sys_tables| SELECT pg_stat_xact_all_tables.relid,
pg_stat_xact_all_tables.schemaname,
pg_stat_xact_all_tables.relname,
pg_stat_xact_all_tables.seq_scan,
pg_stat_xact_all_tables.seq_tup_read,
pg_stat_xact_all_tables.idx_scan,
pg_stat_xact_all_tables.idx_tup_fetch,
pg_stat_xact_all_tables.n_tup_ins,
pg_stat_xact_all_tables.n_tup_upd,
pg_stat_xact_all_tables.n_tup_del,
2013-10-26 17:24:04 +02:00
pg_stat_xact_all_tables.n_tup_hot_upd
FROM pg_stat_xact_all_tables
WHERE ((pg_stat_xact_all_tables.schemaname = ANY (ARRAY['pg_catalog'::name, 'information_schema'::name])) OR (pg_stat_xact_all_tables.schemaname ~ '^pg_toast'::text));
2013-11-11 19:36:38 +01:00
pg_stat_xact_user_functions| SELECT p.oid AS funcid,
n.nspname AS schemaname,
p.proname AS funcname,
pg_stat_get_xact_function_calls(p.oid) AS calls,
pg_stat_get_xact_function_total_time(p.oid) AS total_time,
2013-10-26 17:24:04 +02:00
pg_stat_get_xact_function_self_time(p.oid) AS self_time
FROM (pg_proc p
2014-04-30 18:01:19 +02:00
LEFT JOIN pg_namespace n ON ((n.oid = p.pronamespace)))
2013-10-26 17:24:04 +02:00
WHERE ((p.prolang <> (12)::oid) AND (pg_stat_get_xact_function_calls(p.oid) IS NOT NULL));
2013-11-11 19:36:38 +01:00
pg_stat_xact_user_tables| SELECT pg_stat_xact_all_tables.relid,
pg_stat_xact_all_tables.schemaname,
pg_stat_xact_all_tables.relname,
pg_stat_xact_all_tables.seq_scan,
pg_stat_xact_all_tables.seq_tup_read,
pg_stat_xact_all_tables.idx_scan,
pg_stat_xact_all_tables.idx_tup_fetch,
pg_stat_xact_all_tables.n_tup_ins,
pg_stat_xact_all_tables.n_tup_upd,
pg_stat_xact_all_tables.n_tup_del,
2013-10-26 17:24:04 +02:00
pg_stat_xact_all_tables.n_tup_hot_upd
FROM pg_stat_xact_all_tables
WHERE ((pg_stat_xact_all_tables.schemaname <> ALL (ARRAY['pg_catalog'::name, 'information_schema'::name])) AND (pg_stat_xact_all_tables.schemaname !~ '^pg_toast'::text));
2013-11-11 19:36:38 +01:00
pg_statio_all_indexes| SELECT c.oid AS relid,
i.oid AS indexrelid,
n.nspname AS schemaname,
c.relname,
i.relname AS indexrelname,
(pg_stat_get_blocks_fetched(i.oid) - pg_stat_get_blocks_hit(i.oid)) AS idx_blks_read,
2013-10-26 17:24:04 +02:00
pg_stat_get_blocks_hit(i.oid) AS idx_blks_hit
FROM (((pg_class c
2014-04-30 18:01:19 +02:00
JOIN pg_index x ON ((c.oid = x.indrelid)))
JOIN pg_class i ON ((i.oid = x.indexrelid)))
LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace)))
2013-10-26 17:24:04 +02:00
WHERE (c.relkind = ANY (ARRAY['r'::"char", 't'::"char", 'm'::"char"]));
2013-11-11 19:36:38 +01:00
pg_statio_all_sequences| SELECT c.oid AS relid,
n.nspname AS schemaname,
c.relname,
(pg_stat_get_blocks_fetched(c.oid) - pg_stat_get_blocks_hit(c.oid)) AS blks_read,
2013-10-26 17:24:04 +02:00
pg_stat_get_blocks_hit(c.oid) AS blks_hit
FROM (pg_class c
2014-04-30 18:01:19 +02:00
LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace)))
2013-10-26 17:24:04 +02:00
WHERE (c.relkind = 'S'::"char");
2013-11-11 19:36:38 +01:00
pg_statio_all_tables| SELECT c.oid AS relid,
n.nspname AS schemaname,
c.relname,
(pg_stat_get_blocks_fetched(c.oid) - pg_stat_get_blocks_hit(c.oid)) AS heap_blks_read,
pg_stat_get_blocks_hit(c.oid) AS heap_blks_hit,
(sum((pg_stat_get_blocks_fetched(i.indexrelid) - pg_stat_get_blocks_hit(i.indexrelid))))::bigint AS idx_blks_read,
(sum(pg_stat_get_blocks_hit(i.indexrelid)))::bigint AS idx_blks_hit,
(pg_stat_get_blocks_fetched(t.oid) - pg_stat_get_blocks_hit(t.oid)) AS toast_blks_read,
pg_stat_get_blocks_hit(t.oid) AS toast_blks_hit,
(sum((pg_stat_get_blocks_fetched(x.indexrelid) - pg_stat_get_blocks_hit(x.indexrelid))))::bigint AS tidx_blks_read,
2013-10-26 17:24:04 +02:00
(sum(pg_stat_get_blocks_hit(x.indexrelid)))::bigint AS tidx_blks_hit
FROM ((((pg_class c
2014-04-30 18:01:19 +02:00
LEFT JOIN pg_index i ON ((c.oid = i.indrelid)))
LEFT JOIN pg_class t ON ((c.reltoastrelid = t.oid)))
LEFT JOIN pg_index x ON ((t.oid = x.indrelid)))
LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace)))
2013-10-26 17:24:04 +02:00
WHERE (c.relkind = ANY (ARRAY['r'::"char", 't'::"char", 'm'::"char"]))
GROUP BY c.oid, n.nspname, c.relname, t.oid, x.indrelid;
2013-11-11 19:36:38 +01:00
pg_statio_sys_indexes| SELECT pg_statio_all_indexes.relid,
pg_statio_all_indexes.indexrelid,
pg_statio_all_indexes.schemaname,
pg_statio_all_indexes.relname,
pg_statio_all_indexes.indexrelname,
pg_statio_all_indexes.idx_blks_read,
2013-10-26 17:24:04 +02:00
pg_statio_all_indexes.idx_blks_hit
FROM pg_statio_all_indexes
WHERE ((pg_statio_all_indexes.schemaname = ANY (ARRAY['pg_catalog'::name, 'information_schema'::name])) OR (pg_statio_all_indexes.schemaname ~ '^pg_toast'::text));
2013-11-11 19:36:38 +01:00
pg_statio_sys_sequences| SELECT pg_statio_all_sequences.relid,
pg_statio_all_sequences.schemaname,
pg_statio_all_sequences.relname,
pg_statio_all_sequences.blks_read,
2013-10-26 17:24:04 +02:00
pg_statio_all_sequences.blks_hit
FROM pg_statio_all_sequences
WHERE ((pg_statio_all_sequences.schemaname = ANY (ARRAY['pg_catalog'::name, 'information_schema'::name])) OR (pg_statio_all_sequences.schemaname ~ '^pg_toast'::text));
2013-11-11 19:36:38 +01:00
pg_statio_sys_tables| SELECT pg_statio_all_tables.relid,
pg_statio_all_tables.schemaname,
pg_statio_all_tables.relname,
pg_statio_all_tables.heap_blks_read,
pg_statio_all_tables.heap_blks_hit,
pg_statio_all_tables.idx_blks_read,
pg_statio_all_tables.idx_blks_hit,
pg_statio_all_tables.toast_blks_read,
pg_statio_all_tables.toast_blks_hit,
pg_statio_all_tables.tidx_blks_read,
2013-10-26 17:24:04 +02:00
pg_statio_all_tables.tidx_blks_hit
FROM pg_statio_all_tables
WHERE ((pg_statio_all_tables.schemaname = ANY (ARRAY['pg_catalog'::name, 'information_schema'::name])) OR (pg_statio_all_tables.schemaname ~ '^pg_toast'::text));
2013-11-11 19:36:38 +01:00
pg_statio_user_indexes| SELECT pg_statio_all_indexes.relid,
pg_statio_all_indexes.indexrelid,
pg_statio_all_indexes.schemaname,
pg_statio_all_indexes.relname,
pg_statio_all_indexes.indexrelname,
pg_statio_all_indexes.idx_blks_read,
2013-10-26 17:24:04 +02:00
pg_statio_all_indexes.idx_blks_hit
FROM pg_statio_all_indexes
WHERE ((pg_statio_all_indexes.schemaname <> ALL (ARRAY['pg_catalog'::name, 'information_schema'::name])) AND (pg_statio_all_indexes.schemaname !~ '^pg_toast'::text));
2013-11-11 19:36:38 +01:00
pg_statio_user_sequences| SELECT pg_statio_all_sequences.relid,
pg_statio_all_sequences.schemaname,
pg_statio_all_sequences.relname,
pg_statio_all_sequences.blks_read,
2013-10-26 17:24:04 +02:00
pg_statio_all_sequences.blks_hit
FROM pg_statio_all_sequences
WHERE ((pg_statio_all_sequences.schemaname <> ALL (ARRAY['pg_catalog'::name, 'information_schema'::name])) AND (pg_statio_all_sequences.schemaname !~ '^pg_toast'::text));
2013-11-11 19:36:38 +01:00
pg_statio_user_tables| SELECT pg_statio_all_tables.relid,
pg_statio_all_tables.schemaname,
pg_statio_all_tables.relname,
pg_statio_all_tables.heap_blks_read,
pg_statio_all_tables.heap_blks_hit,
pg_statio_all_tables.idx_blks_read,
pg_statio_all_tables.idx_blks_hit,
pg_statio_all_tables.toast_blks_read,
pg_statio_all_tables.toast_blks_hit,
pg_statio_all_tables.tidx_blks_read,
2013-10-26 17:24:04 +02:00
pg_statio_all_tables.tidx_blks_hit
FROM pg_statio_all_tables
WHERE ((pg_statio_all_tables.schemaname <> ALL (ARRAY['pg_catalog'::name, 'information_schema'::name])) AND (pg_statio_all_tables.schemaname !~ '^pg_toast'::text));
2013-11-11 19:36:38 +01:00
pg_stats| SELECT n.nspname AS schemaname,
c.relname AS tablename,
a.attname,
s.stainherit AS inherited,
s.stanullfrac AS null_frac,
s.stawidth AS avg_width,
s.stadistinct AS n_distinct,
2013-10-26 17:24:04 +02:00
CASE
WHEN (s.stakind1 = 1) THEN s.stavalues1
WHEN (s.stakind2 = 1) THEN s.stavalues2
WHEN (s.stakind3 = 1) THEN s.stavalues3
WHEN (s.stakind4 = 1) THEN s.stavalues4
WHEN (s.stakind5 = 1) THEN s.stavalues5
ELSE NULL::anyarray
2013-11-11 19:36:38 +01:00
END AS most_common_vals,
2013-10-26 17:24:04 +02:00
CASE
WHEN (s.stakind1 = 1) THEN s.stanumbers1
WHEN (s.stakind2 = 1) THEN s.stanumbers2
WHEN (s.stakind3 = 1) THEN s.stanumbers3
WHEN (s.stakind4 = 1) THEN s.stanumbers4
WHEN (s.stakind5 = 1) THEN s.stanumbers5
ELSE NULL::real[]
2013-11-11 19:36:38 +01:00
END AS most_common_freqs,
2013-10-26 17:24:04 +02:00
CASE
WHEN (s.stakind1 = 2) THEN s.stavalues1
WHEN (s.stakind2 = 2) THEN s.stavalues2
WHEN (s.stakind3 = 2) THEN s.stavalues3
WHEN (s.stakind4 = 2) THEN s.stavalues4
WHEN (s.stakind5 = 2) THEN s.stavalues5
ELSE NULL::anyarray
2013-11-11 19:36:38 +01:00
END AS histogram_bounds,
2013-10-26 17:24:04 +02:00
CASE
WHEN (s.stakind1 = 3) THEN s.stanumbers1[1]
WHEN (s.stakind2 = 3) THEN s.stanumbers2[1]
WHEN (s.stakind3 = 3) THEN s.stanumbers3[1]
WHEN (s.stakind4 = 3) THEN s.stanumbers4[1]
WHEN (s.stakind5 = 3) THEN s.stanumbers5[1]
ELSE NULL::real
2013-11-11 19:36:38 +01:00
END AS correlation,
2013-10-26 17:24:04 +02:00
CASE
WHEN (s.stakind1 = 4) THEN s.stavalues1
WHEN (s.stakind2 = 4) THEN s.stavalues2
WHEN (s.stakind3 = 4) THEN s.stavalues3
WHEN (s.stakind4 = 4) THEN s.stavalues4
WHEN (s.stakind5 = 4) THEN s.stavalues5
ELSE NULL::anyarray
2013-11-11 19:36:38 +01:00
END AS most_common_elems,
2013-10-26 17:24:04 +02:00
CASE
WHEN (s.stakind1 = 4) THEN s.stanumbers1
WHEN (s.stakind2 = 4) THEN s.stanumbers2
WHEN (s.stakind3 = 4) THEN s.stanumbers3
WHEN (s.stakind4 = 4) THEN s.stanumbers4
WHEN (s.stakind5 = 4) THEN s.stanumbers5
ELSE NULL::real[]
2013-11-11 19:36:38 +01:00
END AS most_common_elem_freqs,
2013-10-26 17:24:04 +02:00
CASE
WHEN (s.stakind1 = 5) THEN s.stanumbers1
WHEN (s.stakind2 = 5) THEN s.stanumbers2
WHEN (s.stakind3 = 5) THEN s.stanumbers3
WHEN (s.stakind4 = 5) THEN s.stanumbers4
WHEN (s.stakind5 = 5) THEN s.stanumbers5
ELSE NULL::real[]
END AS elem_count_histogram
FROM (((pg_statistic s
2014-04-30 18:01:19 +02:00
JOIN pg_class c ON ((c.oid = s.starelid)))
JOIN pg_attribute a ON (((c.oid = a.attrelid) AND (a.attnum = s.staattnum))))
LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace)))
2015-07-28 22:21:22 +02:00
WHERE ((NOT a.attisdropped) AND has_column_privilege(c.oid, a.attnum, 'select'::text) AND ((c.relrowsecurity = false) OR (NOT row_security_active(c.oid))));
2013-11-11 19:36:38 +01:00
pg_tables| SELECT n.nspname AS schemaname,
c.relname AS tablename,
pg_get_userbyid(c.relowner) AS tableowner,
t.spcname AS tablespace,
c.relhasindex AS hasindexes,
c.relhasrules AS hasrules,
Row-Level Security Policies (RLS)
Building on the updatable security-barrier views work, add the
ability to define policies on tables to limit the set of rows
which are returned from a query and which are allowed to be added
to a table. Expressions defined by the policy for filtering are
added to the security barrier quals of the query, while expressions
defined to check records being added to a table are added to the
with-check options of the query.
New top-level commands are CREATE/ALTER/DROP POLICY and are
controlled by the table owner. Row Security is able to be enabled
and disabled by the owner on a per-table basis using
ALTER TABLE .. ENABLE/DISABLE ROW SECURITY.
Per discussion, ROW SECURITY is disabled on tables by default and
must be enabled for policies on the table to be used. If no
policies exist on a table with ROW SECURITY enabled, a default-deny
policy is used and no records will be visible.
By default, row security is applied at all times except for the
table owner and the superuser. A new GUC, row_security, is added
which can be set to ON, OFF, or FORCE. When set to FORCE, row
security will be applied even for the table owner and superusers.
When set to OFF, row security will be disabled when allowed and an
error will be thrown if the user does not have rights to bypass row
security.
Per discussion, pg_dump sets row_security = OFF by default to ensure
that exports and backups will have all data in the table or will
error if there are insufficient privileges to bypass row security.
A new option has been added to pg_dump, --enable-row-security, to
ask pg_dump to export with row security enabled.
A new role capability, BYPASSRLS, which can only be set by the
superuser, is added to allow other users to be able to bypass row
security using row_security = OFF.
Many thanks to the various individuals who have helped with the
design, particularly Robert Haas for his feedback.
Authors include Craig Ringer, KaiGai Kohei, Adam Brightwell, Dean
Rasheed, with additional changes and rework by me.
Reviewers have included all of the above, Greg Smith,
Jeff McCormick, and Robert Haas.
2014-09-19 17:18:35 +02:00
c.relhastriggers AS hastriggers,
Code review for row security.
Buildfarm member tick identified an issue where the policies in the
relcache for a relation were were being replaced underneath a running
query, leading to segfaults while processing the policies to be added
to a query. Similar to how TupleDesc RuleLocks are handled, add in a
equalRSDesc() function to check if the policies have actually changed
and, if not, swap back the rsdesc field (using the original instead of
the temporairly built one; the whole structure is swapped and then
specific fields swapped back). This now passes a CLOBBER_CACHE_ALWAYS
for me and should resolve the buildfarm error.
In addition to addressing this, add a new chapter in Data Definition
under Privileges which explains row security and provides examples of
its usage, change \d to always list policies (even if row security is
disabled- but note that it is disabled, or enabled with no policies),
rework check_role_for_policy (it really didn't need the entire policy,
but it did need to be using has_privs_of_role()), and change the field
in pg_class to relrowsecurity from relhasrowsecurity, based on
Heikki's suggestion. Also from Heikki, only issue SET ROW_SECURITY in
pg_restore when talking to a 9.5+ server, list Bypass RLS in \du, and
document --enable-row-security options for pg_dump and pg_restore.
Lastly, fix a number of minor whitespace and typo issues from Heikki,
Dimitri, add a missing #include, per Peter E, fix a few minor
variable-assigned-but-not-used and resource leak issues from Coverity
and add tab completion for role attribute bypassrls as well.
2014-09-24 22:32:22 +02:00
c.relrowsecurity AS rowsecurity
2013-10-26 17:24:04 +02:00
FROM ((pg_class c
2014-04-30 18:01:19 +02:00
LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace)))
LEFT JOIN pg_tablespace t ON ((t.oid = c.reltablespace)))
2013-10-26 17:24:04 +02:00
WHERE (c.relkind = 'r'::"char");
2013-11-11 19:36:38 +01:00
pg_timezone_abbrevs| SELECT pg_timezone_abbrevs.abbrev,
pg_timezone_abbrevs.utc_offset,
2013-10-26 17:24:04 +02:00
pg_timezone_abbrevs.is_dst
FROM pg_timezone_abbrevs() pg_timezone_abbrevs(abbrev, utc_offset, is_dst);
2013-11-11 19:36:38 +01:00
pg_timezone_names| SELECT pg_timezone_names.name,
pg_timezone_names.abbrev,
pg_timezone_names.utc_offset,
2013-10-26 17:24:04 +02:00
pg_timezone_names.is_dst
FROM pg_timezone_names() pg_timezone_names(name, abbrev, utc_offset, is_dst);
2013-11-11 19:36:38 +01:00
pg_user| SELECT pg_shadow.usename,
pg_shadow.usesysid,
pg_shadow.usecreatedb,
pg_shadow.usesuper,
pg_shadow.userepl,
2015-01-29 03:47:15 +01:00
pg_shadow.usebypassrls,
2013-11-11 19:36:38 +01:00
'********'::text AS passwd,
pg_shadow.valuntil,
2013-10-26 17:24:04 +02:00
pg_shadow.useconfig
FROM pg_shadow;
2013-11-11 19:36:38 +01:00
pg_user_mappings| SELECT u.oid AS umid,
s.oid AS srvid,
s.srvname,
u.umuser,
2013-10-26 17:24:04 +02:00
CASE
WHEN (u.umuser = (0)::oid) THEN 'public'::name
ELSE a.rolname
2013-11-11 19:36:38 +01:00
END AS usename,
2013-10-26 17:24:04 +02:00
CASE
WHEN (pg_has_role(s.srvowner, 'USAGE'::text) OR has_server_privilege(s.oid, 'USAGE'::text)) THEN u.umoptions
ELSE NULL::text[]
END AS umoptions
FROM ((pg_user_mapping u
2014-04-30 18:01:19 +02:00
LEFT JOIN pg_authid a ON ((a.oid = u.umuser)))
JOIN pg_foreign_server s ON ((u.umserver = s.oid)));
2013-11-11 19:36:38 +01:00
pg_views| SELECT n.nspname AS schemaname,
c.relname AS viewname,
pg_get_userbyid(c.relowner) AS viewowner,
2013-10-26 17:24:04 +02:00
pg_get_viewdef(c.oid) AS definition
FROM (pg_class c
2014-04-30 18:01:19 +02:00
LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace)))
2013-10-26 17:24:04 +02:00
WHERE (c.relkind = 'v'::"char");
2013-11-11 19:36:38 +01:00
rtest_v1| SELECT rtest_t1.a,
2013-10-26 17:24:04 +02:00
rtest_t1.b
FROM rtest_t1;
2013-11-11 19:36:38 +01:00
rtest_vcomp| SELECT x.part,
2013-10-26 17:24:04 +02:00
(x.size * y.factor) AS size_in_cm
2013-11-11 19:36:38 +01:00
FROM rtest_comp x,
2013-10-26 17:24:04 +02:00
rtest_unitfact y
WHERE (x.unit = y.unit);
2013-11-11 19:36:38 +01:00
rtest_vview1| SELECT x.a,
2013-10-26 17:24:04 +02:00
x.b
FROM rtest_view1 x
WHERE (0 < ( SELECT count(*) AS count
FROM rtest_view2 y
WHERE (y.a = x.a)));
2013-11-11 19:36:38 +01:00
rtest_vview2| SELECT rtest_view1.a,
2013-10-26 17:24:04 +02:00
rtest_view1.b
FROM rtest_view1
WHERE rtest_view1.v;
2013-11-11 19:36:38 +01:00
rtest_vview3| SELECT x.a,
2013-10-26 17:24:04 +02:00
x.b
FROM rtest_vview2 x
WHERE (0 < ( SELECT count(*) AS count
FROM rtest_view2 y
WHERE (y.a = x.a)));
2013-11-11 19:36:38 +01:00
rtest_vview4| SELECT x.a,
x.b,
2013-10-26 17:24:04 +02:00
count(y.a) AS refcount
2013-11-11 19:36:38 +01:00
FROM rtest_view1 x,
2013-10-26 17:24:04 +02:00
rtest_view2 y
WHERE (x.a = y.a)
GROUP BY x.a, x.b;
2013-11-11 19:36:38 +01:00
rtest_vview5| SELECT rtest_view1.a,
rtest_view1.b,
2013-10-26 17:24:04 +02:00
rtest_viewfunc1(rtest_view1.a) AS refcount
FROM rtest_view1;
2013-11-11 19:36:38 +01:00
shoe| SELECT sh.shoename,
sh.sh_avail,
sh.slcolor,
sh.slminlen,
(sh.slminlen * un.un_fact) AS slminlen_cm,
sh.slmaxlen,
(sh.slmaxlen * un.un_fact) AS slmaxlen_cm,
2013-10-26 17:24:04 +02:00
sh.slunit
2013-11-11 19:36:38 +01:00
FROM shoe_data sh,
2013-10-26 17:24:04 +02:00
unit un
WHERE (sh.slunit = un.un_name);
2013-11-11 19:36:38 +01:00
shoe_ready| SELECT rsh.shoename,
rsh.sh_avail,
rsl.sl_name,
rsl.sl_avail,
2013-10-26 17:24:04 +02:00
int4smaller(rsh.sh_avail, rsl.sl_avail) AS total_avail
2013-11-11 19:36:38 +01:00
FROM shoe rsh,
2013-10-26 17:24:04 +02:00
shoelace rsl
2014-06-16 21:55:05 +02:00
WHERE ((rsl.sl_color = rsh.slcolor) AND (rsl.sl_len_cm >= rsh.slminlen_cm) AND (rsl.sl_len_cm <= rsh.slmaxlen_cm));
2013-11-11 19:36:38 +01:00
shoelace| SELECT s.sl_name,
s.sl_avail,
s.sl_color,
s.sl_len,
s.sl_unit,
2013-10-26 17:24:04 +02:00
(s.sl_len * u.un_fact) AS sl_len_cm
2013-11-11 19:36:38 +01:00
FROM shoelace_data s,
2013-10-26 17:24:04 +02:00
unit u
WHERE (s.sl_unit = u.un_name);
2013-11-11 19:36:38 +01:00
shoelace_candelete| SELECT shoelace_obsolete.sl_name,
shoelace_obsolete.sl_avail,
shoelace_obsolete.sl_color,
shoelace_obsolete.sl_len,
shoelace_obsolete.sl_unit,
2013-10-26 17:24:04 +02:00
shoelace_obsolete.sl_len_cm
FROM shoelace_obsolete
WHERE (shoelace_obsolete.sl_avail = 0);
2013-11-11 19:36:38 +01:00
shoelace_obsolete| SELECT shoelace.sl_name,
shoelace.sl_avail,
shoelace.sl_color,
shoelace.sl_len,
shoelace.sl_unit,
2013-10-26 17:24:04 +02:00
shoelace.sl_len_cm
FROM shoelace
WHERE (NOT (EXISTS ( SELECT shoe.shoename
FROM shoe
WHERE (shoe.slcolor = shoelace.sl_color))));
2013-11-11 19:36:38 +01:00
street| SELECT r.name,
r.thepath,
2013-10-26 17:24:04 +02:00
c.cname
2013-11-11 19:36:38 +01:00
FROM ONLY road r,
2013-10-26 17:24:04 +02:00
real_city c
WHERE (c.outline ## r.thepath);
Redesign tablesample method API, and do extensive code review.
The original implementation of TABLESAMPLE modeled the tablesample method
API on index access methods, which wasn't a good choice because, without
specialized DDL commands, there's no way to build an extension that can
implement a TSM. (Raw inserts into system catalogs are not an acceptable
thing to do, because we can't undo them during DROP EXTENSION, nor will
pg_upgrade behave sanely.) Instead adopt an API more like procedural
language handlers or foreign data wrappers, wherein the only SQL-level
support object needed is a single handler function identified by having
a special return type. This lets us get rid of the supporting catalog
altogether, so that no custom DDL support is needed for the feature.
Adjust the API so that it can support non-constant tablesample arguments
(the original coding assumed we could evaluate the argument expressions at
ExecInitSampleScan time, which is undesirable even if it weren't outright
unsafe), and discourage sampling methods from looking at invisible tuples.
Make sure that the BERNOULLI and SYSTEM methods are genuinely repeatable
within and across queries, as required by the SQL standard, and deal more
honestly with methods that can't support that requirement.
Make a full code-review pass over the tablesample additions, and fix
assorted bugs, omissions, infelicities, and cosmetic issues (such as
failure to put the added code stanzas in a consistent ordering).
Improve EXPLAIN's output of tablesample plans, too.
Back-patch to 9.5 so that we don't have to support the original API
in production.
2015-07-25 20:39:00 +02:00
test_tablesample_v1| SELECT test_tablesample.id
FROM test_tablesample TABLESAMPLE system ((10 * 2)) REPEATABLE (2);
test_tablesample_v2| SELECT test_tablesample.id
FROM test_tablesample TABLESAMPLE system (99);
2013-11-11 19:36:38 +01:00
toyemp| SELECT emp.name,
emp.age,
emp.location,
2013-10-26 17:24:04 +02:00
(12 * emp.salary) AS annualsal
FROM emp;
2010-11-23 21:27:50 +01:00
SELECT tablename, rulename, definition FROM pg_rules
2000-10-08 04:51:50 +02:00
ORDER BY tablename, rulename;
2013-10-26 17:24:04 +02:00
pg_settings|pg_settings_n|CREATE RULE pg_settings_n AS
ON UPDATE TO pg_settings DO INSTEAD NOTHING;
pg_settings|pg_settings_u|CREATE RULE pg_settings_u AS
ON UPDATE TO pg_settings
WHERE (new.name = old.name) DO SELECT set_config(old.name, new.setting, false) AS set_config;
rtest_emp|rtest_emp_del|CREATE RULE rtest_emp_del AS
2013-11-11 19:36:38 +01:00
ON DELETE TO rtest_emp DO INSERT INTO rtest_emplog (ename, who, action, newsal, oldsal)
2016-08-17 02:33:01 +02:00
VALUES (old.ename, CURRENT_USER, 'fired'::bpchar, '$0.00'::money, old.salary);
2013-10-26 17:24:04 +02:00
rtest_emp|rtest_emp_ins|CREATE RULE rtest_emp_ins AS
2013-11-11 19:36:38 +01:00
ON INSERT TO rtest_emp DO INSERT INTO rtest_emplog (ename, who, action, newsal, oldsal)
2016-08-17 02:33:01 +02:00
VALUES (new.ename, CURRENT_USER, 'hired'::bpchar, new.salary, '$0.00'::money);
2013-10-26 17:24:04 +02:00
rtest_emp|rtest_emp_upd|CREATE RULE rtest_emp_upd AS
ON UPDATE TO rtest_emp
2013-11-11 19:36:38 +01:00
WHERE (new.salary <> old.salary) DO INSERT INTO rtest_emplog (ename, who, action, newsal, oldsal)
2016-08-17 02:33:01 +02:00
VALUES (new.ename, CURRENT_USER, 'honored'::bpchar, new.salary, old.salary);
2013-10-26 17:24:04 +02:00
rtest_nothn1|rtest_nothn_r1|CREATE RULE rtest_nothn_r1 AS
ON INSERT TO rtest_nothn1
WHERE ((new.a >= 10) AND (new.a < 20)) DO INSTEAD NOTHING;
rtest_nothn1|rtest_nothn_r2|CREATE RULE rtest_nothn_r2 AS
ON INSERT TO rtest_nothn1
WHERE ((new.a >= 30) AND (new.a < 40)) DO INSTEAD NOTHING;
rtest_nothn2|rtest_nothn_r3|CREATE RULE rtest_nothn_r3 AS
ON INSERT TO rtest_nothn2
2013-11-11 19:36:38 +01:00
WHERE (new.a >= 100) DO INSTEAD INSERT INTO rtest_nothn3 (a, b)
2013-10-26 17:24:04 +02:00
VALUES (new.a, new.b);
rtest_nothn2|rtest_nothn_r4|CREATE RULE rtest_nothn_r4 AS
ON INSERT TO rtest_nothn2 DO INSTEAD NOTHING;
rtest_order1|rtest_order_r1|CREATE RULE rtest_order_r1 AS
2013-11-11 19:36:38 +01:00
ON INSERT TO rtest_order1 DO INSTEAD INSERT INTO rtest_order2 (a, b, c)
2013-10-26 17:24:04 +02:00
VALUES (new.a, nextval('rtest_seq'::regclass), 'rule 1 - this should run 1st'::text);
rtest_order1|rtest_order_r2|CREATE RULE rtest_order_r2 AS
2013-11-11 19:36:38 +01:00
ON INSERT TO rtest_order1 DO INSERT INTO rtest_order2 (a, b, c)
2013-10-26 17:24:04 +02:00
VALUES (new.a, nextval('rtest_seq'::regclass), 'rule 2 - this should run 2nd'::text);
rtest_order1|rtest_order_r3|CREATE RULE rtest_order_r3 AS
2013-11-11 19:36:38 +01:00
ON INSERT TO rtest_order1 DO INSTEAD INSERT INTO rtest_order2 (a, b, c)
2013-10-26 17:24:04 +02:00
VALUES (new.a, nextval('rtest_seq'::regclass), 'rule 3 - this should run 3rd'::text);
rtest_order1|rtest_order_r4|CREATE RULE rtest_order_r4 AS
ON INSERT TO rtest_order1
2013-11-11 19:36:38 +01:00
WHERE (new.a < 100) DO INSTEAD INSERT INTO rtest_order2 (a, b, c)
2013-10-26 17:24:04 +02:00
VALUES (new.a, nextval('rtest_seq'::regclass), 'rule 4 - this should run 4th'::text);
rtest_person|rtest_pers_del|CREATE RULE rtest_pers_del AS
ON DELETE TO rtest_person DO DELETE FROM rtest_admin
WHERE (rtest_admin.pname = old.pname);
rtest_person|rtest_pers_upd|CREATE RULE rtest_pers_upd AS
ON UPDATE TO rtest_person DO UPDATE rtest_admin SET pname = new.pname
WHERE (rtest_admin.pname = old.pname);
rtest_system|rtest_sys_del|CREATE RULE rtest_sys_del AS
ON DELETE TO rtest_system DO ( DELETE FROM rtest_interface
WHERE (rtest_interface.sysname = old.sysname);
DELETE FROM rtest_admin
WHERE (rtest_admin.sysname = old.sysname);
);
rtest_system|rtest_sys_upd|CREATE RULE rtest_sys_upd AS
ON UPDATE TO rtest_system DO ( UPDATE rtest_interface SET sysname = new.sysname
WHERE (rtest_interface.sysname = old.sysname);
UPDATE rtest_admin SET sysname = new.sysname
WHERE (rtest_admin.sysname = old.sysname);
);
rtest_t4|rtest_t4_ins1|CREATE RULE rtest_t4_ins1 AS
ON INSERT TO rtest_t4
2013-11-11 19:36:38 +01:00
WHERE ((new.a >= 10) AND (new.a < 20)) DO INSTEAD INSERT INTO rtest_t5 (a, b)
2013-10-26 17:24:04 +02:00
VALUES (new.a, new.b);
rtest_t4|rtest_t4_ins2|CREATE RULE rtest_t4_ins2 AS
ON INSERT TO rtest_t4
2013-11-11 19:36:38 +01:00
WHERE ((new.a >= 20) AND (new.a < 30)) DO INSERT INTO rtest_t6 (a, b)
2013-10-26 17:24:04 +02:00
VALUES (new.a, new.b);
rtest_t5|rtest_t5_ins|CREATE RULE rtest_t5_ins AS
ON INSERT TO rtest_t5
2013-11-11 19:36:38 +01:00
WHERE (new.a > 15) DO INSERT INTO rtest_t7 (a, b)
2013-10-26 17:24:04 +02:00
VALUES (new.a, new.b);
rtest_t6|rtest_t6_ins|CREATE RULE rtest_t6_ins AS
ON INSERT TO rtest_t6
2013-11-11 19:36:38 +01:00
WHERE (new.a > 25) DO INSTEAD INSERT INTO rtest_t8 (a, b)
2013-10-26 17:24:04 +02:00
VALUES (new.a, new.b);
rtest_v1|rtest_v1_del|CREATE RULE rtest_v1_del AS
ON DELETE TO rtest_v1 DO INSTEAD DELETE FROM rtest_t1
WHERE (rtest_t1.a = old.a);
rtest_v1|rtest_v1_ins|CREATE RULE rtest_v1_ins AS
2013-11-11 19:36:38 +01:00
ON INSERT TO rtest_v1 DO INSTEAD INSERT INTO rtest_t1 (a, b)
2013-10-26 17:24:04 +02:00
VALUES (new.a, new.b);
rtest_v1|rtest_v1_upd|CREATE RULE rtest_v1_upd AS
ON UPDATE TO rtest_v1 DO INSTEAD UPDATE rtest_t1 SET a = new.a, b = new.b
WHERE (rtest_t1.a = old.a);
shoelace|shoelace_del|CREATE RULE shoelace_del AS
ON DELETE TO shoelace DO INSTEAD DELETE FROM shoelace_data
WHERE (shoelace_data.sl_name = old.sl_name);
shoelace|shoelace_ins|CREATE RULE shoelace_ins AS
2013-11-11 19:36:38 +01:00
ON INSERT TO shoelace DO INSTEAD INSERT INTO shoelace_data (sl_name, sl_avail, sl_color, sl_len, sl_unit)
2013-10-26 17:24:04 +02:00
VALUES (new.sl_name, new.sl_avail, new.sl_color, new.sl_len, new.sl_unit);
shoelace|shoelace_upd|CREATE RULE shoelace_upd AS
ON UPDATE TO shoelace DO INSTEAD UPDATE shoelace_data SET sl_name = new.sl_name, sl_avail = new.sl_avail, sl_color = new.sl_color, sl_len = new.sl_len, sl_unit = new.sl_unit
WHERE (shoelace_data.sl_name = old.sl_name);
shoelace_data|log_shoelace|CREATE RULE log_shoelace AS
ON UPDATE TO shoelace_data
2013-11-11 19:36:38 +01:00
WHERE (new.sl_avail <> old.sl_avail) DO INSERT INTO shoelace_log (sl_name, sl_avail, log_who, log_when)
2013-10-26 17:24:04 +02:00
VALUES (new.sl_name, new.sl_avail, 'Al Bundy'::name, 'Thu Jan 01 00:00:00 1970'::timestamp without time zone);
shoelace_ok|shoelace_ok_ins|CREATE RULE shoelace_ok_ins AS
ON INSERT TO shoelace_ok DO INSTEAD UPDATE shoelace SET sl_avail = (shoelace.sl_avail + new.ok_quant)
WHERE (shoelace.sl_name = new.ok_name);
-- restore normal output mode
\a\t
2002-09-02 04:13:02 +02:00
--
-- CREATE OR REPLACE RULE
--
CREATE TABLE ruletest_tbl (a int, b int);
CREATE TABLE ruletest_tbl2 (a int, b int);
CREATE OR REPLACE RULE myrule AS ON INSERT TO ruletest_tbl
DO INSTEAD INSERT INTO ruletest_tbl2 VALUES (10, 10);
INSERT INTO ruletest_tbl VALUES (99, 99);
CREATE OR REPLACE RULE myrule AS ON INSERT TO ruletest_tbl
DO INSTEAD INSERT INTO ruletest_tbl2 VALUES (1000, 1000);
INSERT INTO ruletest_tbl VALUES (99, 99);
SELECT * FROM ruletest_tbl2;
a | b
------+------
10 | 10
1000 | 1000
(2 rows)
2003-10-31 15:27:57 +01:00
-- Check that rewrite rules splitting one INSERT into multiple
-- conditional statements does not disable FK checking.
create table rule_and_refint_t1 (
id1a integer,
id1b integer,
primary key (id1a, id1b)
);
create table rule_and_refint_t2 (
id2a integer,
id2c integer,
primary key (id2a, id2c)
);
create table rule_and_refint_t3 (
id3a integer,
id3b integer,
id3c integer,
data text,
primary key (id3a, id3b, id3c),
foreign key (id3a, id3b) references rule_and_refint_t1 (id1a, id1b),
foreign key (id3a, id3c) references rule_and_refint_t2 (id2a, id2c)
);
insert into rule_and_refint_t1 values (1, 11);
insert into rule_and_refint_t1 values (1, 12);
insert into rule_and_refint_t1 values (2, 21);
insert into rule_and_refint_t1 values (2, 22);
insert into rule_and_refint_t2 values (1, 11);
insert into rule_and_refint_t2 values (1, 12);
insert into rule_and_refint_t2 values (2, 21);
insert into rule_and_refint_t2 values (2, 22);
insert into rule_and_refint_t3 values (1, 11, 11, 'row1');
insert into rule_and_refint_t3 values (1, 11, 12, 'row2');
insert into rule_and_refint_t3 values (1, 12, 11, 'row3');
insert into rule_and_refint_t3 values (1, 12, 12, 'row4');
insert into rule_and_refint_t3 values (1, 11, 13, 'row5');
2004-06-10 19:56:03 +02:00
ERROR: insert or update on table "rule_and_refint_t3" violates foreign key constraint "rule_and_refint_t3_id3a_fkey1"
2009-09-22 17:46:35 +02:00
DETAIL: Key (id3a, id3c)=(1, 13) is not present in table "rule_and_refint_t2".
2003-10-31 15:27:57 +01:00
insert into rule_and_refint_t3 values (1, 13, 11, 'row6');
2004-06-10 19:56:03 +02:00
ERROR: insert or update on table "rule_and_refint_t3" violates foreign key constraint "rule_and_refint_t3_id3a_fkey"
2009-09-22 17:46:35 +02:00
DETAIL: Key (id3a, id3b)=(1, 13) is not present in table "rule_and_refint_t1".
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
-- Ordinary table
insert into rule_and_refint_t3 values (1, 13, 11, 'row6')
on conflict do nothing;
ERROR: insert or update on table "rule_and_refint_t3" violates foreign key constraint "rule_and_refint_t3_id3a_fkey"
DETAIL: Key (id3a, id3b)=(1, 13) is not present in table "rule_and_refint_t1".
-- rule not fired, so fk violation
insert into rule_and_refint_t3 values (1, 13, 11, 'row6')
on conflict (id3a, id3b, id3c) do update
set id3b = excluded.id3b;
ERROR: insert or update on table "rule_and_refint_t3" violates foreign key constraint "rule_and_refint_t3_id3a_fkey"
DETAIL: Key (id3a, id3b)=(1, 13) is not present in table "rule_and_refint_t1".
-- rule fired, so unsupported
insert into shoelace values ('sl9', 0, 'pink', 35.0, 'inch', 0.0)
on conflict (sl_name) do update
set sl_avail = excluded.sl_avail;
ERROR: INSERT with ON CONFLICT clause cannot be used with table that has INSERT or UPDATE rules
2003-10-31 15:27:57 +01:00
create rule rule_and_refint_t3_ins as on insert to rule_and_refint_t3
where (exists (select 1 from rule_and_refint_t3
where (((rule_and_refint_t3.id3a = new.id3a)
and (rule_and_refint_t3.id3b = new.id3b))
and (rule_and_refint_t3.id3c = new.id3c))))
do instead update rule_and_refint_t3 set data = new.data
where (((rule_and_refint_t3.id3a = new.id3a)
and (rule_and_refint_t3.id3b = new.id3b))
and (rule_and_refint_t3.id3c = new.id3c));
insert into rule_and_refint_t3 values (1, 11, 13, 'row7');
2004-06-10 19:56:03 +02:00
ERROR: insert or update on table "rule_and_refint_t3" violates foreign key constraint "rule_and_refint_t3_id3a_fkey1"
2009-09-22 17:46:35 +02:00
DETAIL: Key (id3a, id3c)=(1, 13) is not present in table "rule_and_refint_t2".
2003-10-31 15:27:57 +01:00
insert into rule_and_refint_t3 values (1, 13, 11, 'row8');
2004-06-10 19:56:03 +02:00
ERROR: insert or update on table "rule_and_refint_t3" violates foreign key constraint "rule_and_refint_t3_id3a_fkey"
2009-09-22 17:46:35 +02:00
DETAIL: Key (id3a, id3b)=(1, 13) is not present in table "rule_and_refint_t1".
--
-- disallow dropping a view's rule (bug #5072)
--
create view fooview as select 'foo'::text;
drop rule "_RETURN" on fooview;
ERROR: cannot drop rule _RETURN on view fooview because view fooview requires it
HINT: You can drop view fooview instead.
drop view fooview;
2004-10-03 02:13:29 +02:00
--
2012-10-24 19:39:37 +02:00
-- test conversion of table to view (needed to load some pg_dump files)
--
create table fooview (x int, y text);
select xmin, * from fooview;
xmin | x | y
------+---+---
(0 rows)
create rule "_RETURN" as on select to fooview do instead
select 1 as x, 'aaa'::text as y;
select * from fooview;
x | y
---+-----
1 | aaa
(1 row)
select xmin, * from fooview; -- fail, views don't have such a column
ERROR: column "xmin" does not exist
LINE 1: select xmin, * from fooview;
^
2013-07-03 20:24:09 +02:00
select reltoastrelid, relkind, relfrozenxid
2013-03-04 01:05:47 +01:00
from pg_class where oid = 'fooview'::regclass;
2013-07-03 20:24:09 +02:00
reltoastrelid | relkind | relfrozenxid
---------------+---------+--------------
0 | v | 0
2013-03-04 01:05:47 +01:00
(1 row)
2012-10-24 19:39:37 +02:00
drop view fooview;
--
2004-10-03 02:13:29 +02:00
-- check for planner problems with complex inherited UPDATES
--
create table id (id serial primary key, name text);
-- currently, must respecify PKEY for each inherited subtable
create table test_1 (id integer primary key) inherits (id);
NOTICE: merging column "id" with inherited definition
create table test_2 (id integer primary key) inherits (id);
NOTICE: merging column "id" with inherited definition
create table test_3 (id integer primary key) inherits (id);
NOTICE: merging column "id" with inherited definition
insert into test_1 (name) values ('Test 1');
insert into test_1 (name) values ('Test 2');
insert into test_2 (name) values ('Test 3');
insert into test_2 (name) values ('Test 4');
insert into test_3 (name) values ('Test 5');
insert into test_3 (name) values ('Test 6');
create view id_ordered as select * from id order by id;
create rule update_id_ordered as on update to id_ordered
do instead update id set name = new.name where id = old.id;
select * from id_ordered;
id | name
----+--------
1 | Test 1
2 | Test 2
3 | Test 3
4 | Test 4
5 | Test 5
6 | Test 6
(6 rows)
update id_ordered set name = 'update 2' where id = 2;
update id_ordered set name = 'update 4' where id = 4;
update id_ordered set name = 'update 5' where id = 5;
select * from id_ordered;
id | name
----+----------
1 | Test 1
2 | update 2
3 | Test 3
4 | update 4
5 | update 5
6 | Test 6
(6 rows)
set client_min_messages to warning; -- suppress cascade notices
drop table id cascade;
2007-05-26 20:23:02 +02:00
reset client_min_messages;
--
-- check corner case where an entirely-dummy subplan is created by
-- constraint exclusion
--
create temp table t1 (a integer primary key);
create temp table t1_1 (check (a >= 0 and a < 10)) inherits (t1);
create temp table t1_2 (check (a >= 10 and a < 20)) inherits (t1);
2010-11-23 21:27:50 +01:00
create rule t1_ins_1 as on insert to t1
2007-05-26 20:23:02 +02:00
where new.a >= 0 and new.a < 10
do instead
insert into t1_1 values (new.a);
2010-11-23 21:27:50 +01:00
create rule t1_ins_2 as on insert to t1
2007-05-26 20:23:02 +02:00
where new.a >= 10 and new.a < 20
do instead
insert into t1_2 values (new.a);
create rule t1_upd_1 as on update to t1
where old.a >= 0 and old.a < 10
do instead
update t1_1 set a = new.a where a = old.a;
create rule t1_upd_2 as on update to t1
where old.a >= 10 and old.a < 20
do instead
update t1_2 set a = new.a where a = old.a;
set constraint_exclusion = on;
insert into t1 select * from generate_series(5,19,1) g;
update t1 set a = 4 where a = 5;
select * from only t1;
a
---
(0 rows)
select * from only t1_1;
a
---
6
7
8
9
4
(5 rows)
select * from only t1_2;
a
----
10
11
12
13
14
15
16
17
18
19
(10 rows)
2015-02-25 18:01:12 +01:00
reset constraint_exclusion;
2012-02-19 17:43:46 +01:00
-- test various flavors of pg_get_viewdef()
select pg_get_viewdef('shoe'::regclass) as unpretty;
2013-11-11 19:36:38 +01:00
unpretty
------------------------------------------------
SELECT sh.shoename, +
sh.sh_avail, +
sh.slcolor, +
sh.slminlen, +
(sh.slminlen * un.un_fact) AS slminlen_cm,+
sh.slmaxlen, +
(sh.slmaxlen * un.un_fact) AS slmaxlen_cm,+
sh.slunit +
FROM shoe_data sh, +
unit un +
2013-02-03 21:56:45 +01:00
WHERE (sh.slunit = un.un_name);
2012-02-19 17:43:46 +01:00
(1 row)
select pg_get_viewdef('shoe'::regclass,true) as pretty;
2013-11-11 19:36:38 +01:00
pretty
----------------------------------------------
SELECT sh.shoename, +
sh.sh_avail, +
sh.slcolor, +
sh.slminlen, +
sh.slminlen * un.un_fact AS slminlen_cm,+
sh.slmaxlen, +
sh.slmaxlen * un.un_fact AS slmaxlen_cm,+
sh.slunit +
FROM shoe_data sh, +
unit un +
2012-02-19 17:43:46 +01:00
WHERE sh.slunit = un.un_name;
(1 row)
select pg_get_viewdef('shoe'::regclass,0) as prettier;
2013-11-11 19:36:38 +01:00
prettier
----------------------------------------------
SELECT sh.shoename, +
sh.sh_avail, +
sh.slcolor, +
sh.slminlen, +
sh.slminlen * un.un_fact AS slminlen_cm,+
sh.slmaxlen, +
sh.slmaxlen * un.un_fact AS slmaxlen_cm,+
sh.slunit +
FROM shoe_data sh, +
unit un +
2012-02-19 17:43:46 +01:00
WHERE sh.slunit = un.un_name;
(1 row)
2012-08-19 20:12:16 +02:00
--
2012-08-20 04:56:17 +02:00
-- check multi-row VALUES in rules
2012-08-19 20:12:16 +02:00
--
create table rules_src(f1 int, f2 int);
create table rules_log(f1 int, f2 int, tag text);
insert into rules_src values(1,2), (11,12);
create rule r1 as on update to rules_src do also
insert into rules_log values(old.*, 'old'), (new.*, 'new');
update rules_src set f2 = f2 + 1;
update rules_src set f2 = f2 * 10;
select * from rules_src;
f1 | f2
----+-----
1 | 30
11 | 130
(2 rows)
select * from rules_log;
f1 | f2 | tag
----+-----+-----
1 | 2 | old
1 | 3 | new
11 | 12 | old
11 | 13 | new
1 | 3 | old
1 | 30 | new
11 | 13 | old
11 | 130 | new
(8 rows)
create rule r2 as on update to rules_src do also
values(old.*, 'old'), (new.*, 'new');
update rules_src set f2 = f2 / 10;
column1 | column2 | column3
---------+---------+---------
1 | 30 | old
1 | 3 | new
11 | 130 | old
11 | 13 | new
(4 rows)
select * from rules_src;
f1 | f2
----+----
1 | 3
11 | 13
(2 rows)
select * from rules_log;
f1 | f2 | tag
----+-----+-----
1 | 2 | old
1 | 3 | new
11 | 12 | old
11 | 13 | new
1 | 3 | old
1 | 30 | new
11 | 13 | old
11 | 130 | new
1 | 30 | old
1 | 3 | new
11 | 130 | old
11 | 13 | new
(12 rows)
2013-05-16 22:47:26 +02:00
create rule r3 as on delete to rules_src do notify rules_src_deletion;
2012-08-19 20:12:16 +02:00
\d+ rules_src
Table "public.rules_src"
Column | Type | Modifiers | Storage | Stats target | Description
--------+---------+-----------+---------+--------------+-------------
f1 | integer | | plain | |
f2 | integer | | plain | |
Rules:
r1 AS
ON UPDATE TO rules_src DO INSERT INTO rules_log (f1, f2, tag) VALUES (old.f1,old.f2,'old'::text), (new.f1,new.f2,'new'::text)
r2 AS
ON UPDATE TO rules_src DO VALUES (old.f1,old.f2,'old'::text), (new.f1,new.f2,'new'::text)
2013-05-16 22:47:26 +02:00
r3 AS
2013-11-11 19:36:38 +01:00
ON DELETE TO rules_src DO
2013-05-16 22:47:26 +02:00
NOTIFY rules_src_deletion
2012-08-19 20:12:16 +02:00
2015-05-19 21:07:28 +02:00
--
-- Ensure a aliased target relation for insert is correctly deparsed.
--
create rule r4 as on insert to rules_src do instead insert into rules_log AS trgt SELECT NEW.* RETURNING trgt.f1, trgt.f2;
create rule r5 as on update to rules_src do instead UPDATE rules_log AS trgt SET tag = 'updated' WHERE trgt.f1 = new.f1;
\d+ rules_src
Table "public.rules_src"
Column | Type | Modifiers | Storage | Stats target | Description
--------+---------+-----------+---------+--------------+-------------
f1 | integer | | plain | |
f2 | integer | | plain | |
Rules:
r1 AS
ON UPDATE TO rules_src DO INSERT INTO rules_log (f1, f2, tag) VALUES (old.f1,old.f2,'old'::text), (new.f1,new.f2,'new'::text)
r2 AS
ON UPDATE TO rules_src DO VALUES (old.f1,old.f2,'old'::text), (new.f1,new.f2,'new'::text)
r3 AS
ON DELETE TO rules_src DO
NOTIFY rules_src_deletion
r4 AS
ON INSERT TO rules_src DO INSTEAD INSERT INTO rules_log AS trgt (f1, f2) SELECT new.f1,
new.f2
RETURNING trgt.f1,
trgt.f2
r5 AS
ON UPDATE TO rules_src DO INSTEAD UPDATE rules_log trgt SET tag = 'updated'::text
WHERE trgt.f1 = new.f1
2013-02-09 05:58:40 +01:00
--
-- check alter rename rule
--
CREATE TABLE rule_t1 (a INT);
CREATE VIEW rule_v1 AS SELECT * FROM rule_t1;
CREATE RULE InsertRule AS
ON INSERT TO rule_v1
DO INSTEAD
INSERT INTO rule_t1 VALUES(new.a);
ALTER RULE InsertRule ON rule_v1 RENAME to NewInsertRule;
INSERT INTO rule_v1 VALUES(1);
SELECT * FROM rule_v1;
a
---
1
(1 row)
\d+ rule_v1
View "public.rule_v1"
Column | Type | Modifiers | Storage | Description
--------+---------+-----------+---------+-------------
a | integer | | plain |
View definition:
SELECT rule_t1.a
FROM rule_t1;
Rules:
newinsertrule AS
2013-11-11 19:36:38 +01:00
ON INSERT TO rule_v1 DO INSTEAD INSERT INTO rule_t1 (a)
2013-02-09 05:58:40 +01:00
VALUES (new.a)
--
-- error conditions for alter rename rule
--
ALTER RULE InsertRule ON rule_v1 RENAME TO NewInsertRule; -- doesn't exist
ERROR: rule "insertrule" for relation "rule_v1" does not exist
ALTER RULE NewInsertRule ON rule_v1 RENAME TO "_RETURN"; -- already exists
ERROR: rule "_RETURN" for relation "rule_v1" already exists
ALTER RULE "_RETURN" ON rule_v1 RENAME TO abc; -- ON SELECT rule cannot be renamed
ERROR: renaming an ON SELECT rule is not allowed
DROP VIEW rule_v1;
DROP TABLE rule_t1;
2015-02-25 18:01:12 +01:00
--
-- check display of VALUES in view definitions
--
create view rule_v1 as values(1,2);
\d+ rule_v1
View "public.rule_v1"
Column | Type | Modifiers | Storage | Description
---------+---------+-----------+---------+-------------
column1 | integer | | plain |
column2 | integer | | plain |
View definition:
VALUES (1,2);
drop view rule_v1;
create view rule_v1(x) as values(1,2);
\d+ rule_v1
View "public.rule_v1"
Column | Type | Modifiers | Storage | Description
---------+---------+-----------+---------+-------------
x | integer | | plain |
column2 | integer | | plain |
View definition:
SELECT "*VALUES*".column1 AS x,
"*VALUES*".column2
FROM (VALUES (1,2)) "*VALUES*";
drop view rule_v1;
create view rule_v1(x) as select * from (values(1,2)) v;
\d+ rule_v1
View "public.rule_v1"
Column | Type | Modifiers | Storage | Description
---------+---------+-----------+---------+-------------
x | integer | | plain |
column2 | integer | | plain |
View definition:
SELECT v.column1 AS x,
v.column2
FROM ( VALUES (1,2)) v;
drop view rule_v1;
create view rule_v1(x) as select * from (values(1,2)) v(q,w);
\d+ rule_v1
View "public.rule_v1"
Column | Type | Modifiers | Storage | Description
--------+---------+-----------+---------+-------------
x | integer | | plain |
w | integer | | plain |
View definition:
SELECT v.q AS x,
v.w
FROM ( VALUES (1,2)) v(q, w);
drop view rule_v1;
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
--
-- Check DO INSTEAD rules with ON CONFLICT
--
CREATE TABLE hats (
hat_name char(10) primary key,
hat_color char(10) -- hat color
);
CREATE TABLE hat_data (
2015-05-19 21:07:28 +02:00
hat_name char(10),
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
hat_color char(10) -- hat color
);
2015-05-19 21:07:28 +02:00
create unique index hat_data_unique_idx
on hat_data (hat_name COLLATE "C" bpchar_pattern_ops);
2015-05-23 02:16:24 +02:00
-- DO NOTHING with ON CONFLICT
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
CREATE RULE hat_nosert AS ON INSERT TO hats
DO INSTEAD
INSERT INTO hat_data VALUES (
NEW.hat_name,
NEW.hat_color)
2015-05-19 21:07:28 +02:00
ON CONFLICT (hat_name COLLATE "C" bpchar_pattern_ops) WHERE hat_color = 'green'
2015-05-23 02:16:24 +02:00
DO NOTHING
RETURNING *;
SELECT definition FROM pg_rules WHERE tablename = 'hats' ORDER BY rulename;
definition
---------------------------------------------------------------------------------------------
CREATE RULE hat_nosert AS +
ON INSERT TO hats DO INSTEAD INSERT INTO hat_data (hat_name, hat_color) +
VALUES (new.hat_name, new.hat_color) ON CONFLICT(hat_name COLLATE "C" bpchar_pattern_ops)+
2016-02-07 20:57:24 +01:00
WHERE (hat_color = 'green'::bpchar) DO NOTHING +
2015-05-23 02:16:24 +02:00
RETURNING hat_data.hat_name, +
hat_data.hat_color;
(1 row)
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
-- Works (projects row)
INSERT INTO hats VALUES ('h7', 'black') RETURNING *;
hat_name | hat_color
------------+------------
h7 | black
(1 row)
-- Works (does nothing)
INSERT INTO hats VALUES ('h7', 'black') RETURNING *;
hat_name | hat_color
----------+-----------
(0 rows)
SELECT tablename, rulename, definition FROM pg_rules
WHERE tablename = 'hats';
2015-05-19 21:07:28 +02:00
tablename | rulename | definition
-----------+------------+---------------------------------------------------------------------------------------------
hats | hat_nosert | CREATE RULE hat_nosert AS +
| | ON INSERT TO hats DO INSTEAD INSERT INTO hat_data (hat_name, hat_color) +
| | VALUES (new.hat_name, new.hat_color) ON CONFLICT(hat_name COLLATE "C" bpchar_pattern_ops)+
2016-02-07 20:57:24 +01:00
| | WHERE (hat_color = 'green'::bpchar) DO NOTHING +
2015-05-19 21:07:28 +02:00
| | RETURNING hat_data.hat_name, +
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
| | hat_data.hat_color;
(1 row)
DROP RULE hat_nosert ON hats;
2015-05-23 02:16:24 +02:00
-- DO NOTHING without ON CONFLICT
CREATE RULE hat_nosert_all AS ON INSERT TO hats
DO INSTEAD
INSERT INTO hat_data VALUES (
NEW.hat_name,
NEW.hat_color)
ON CONFLICT
DO NOTHING
RETURNING *;
SELECT definition FROM pg_rules WHERE tablename = 'hats' ORDER BY rulename;
definition
------------------------------------------------------------------------------
CREATE RULE hat_nosert_all AS +
ON INSERT TO hats DO INSTEAD INSERT INTO hat_data (hat_name, hat_color)+
VALUES (new.hat_name, new.hat_color) ON CONFLICT DO NOTHING +
RETURNING hat_data.hat_name, +
hat_data.hat_color;
(1 row)
DROP RULE hat_nosert_all ON hats;
-- Works (does nothing)
INSERT INTO hats VALUES ('h7', 'black') RETURNING *;
hat_name | hat_color
------------+------------
h7 | black
(1 row)
-- DO UPDATE with a WHERE clause
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
CREATE RULE hat_upsert AS ON INSERT TO hats
DO INSTEAD
INSERT INTO hat_data VALUES (
NEW.hat_name,
NEW.hat_color)
2015-05-13 00:13:22 +02:00
ON CONFLICT (hat_name)
DO UPDATE
SET hat_name = hat_data.hat_name, hat_color = excluded.hat_color
Fix several bugs related to ON CONFLICT's EXCLUDED pseudo relation.
Four related issues:
1) attnos/varnos/resnos for EXCLUDED were out of sync when a column
after one dropped in the underlying relation was referenced.
2) References to whole-row variables (i.e. EXCLUDED.*) lead to errors.
3) It was possible to reference system columns in the EXCLUDED pseudo
relations, even though they would not have valid contents.
4) References to EXCLUDED were rewritten by the RLS machinery, as
EXCLUDED was treated as if it were the underlying relation.
To fix the first two issues, generate the excluded targetlist with
dropped columns in mind and add an entry for whole row
variables. Instead of unconditionally adding a wholerow entry we could
pull up the expression if needed, but doing it unconditionally seems
simpler. The wholerow entry is only really needed for ruleutils/EXPLAIN
support anyway.
The remaining two issues are addressed by changing the EXCLUDED RTE to
have relkind = composite. That fits with EXCLUDED not actually being a
real relation, and allows to treat it differently in the relevant
places. scanRTEForColumn now skips looking up system columns when the
RTE has a composite relkind; fireRIRrules() already had a corresponding
check, thereby preventing RLS expansion on EXCLUDED.
Also add tests for these issues, and improve a few comments around
excluded handling in setrefs.c.
Reported-By: Peter Geoghegan, Geoff Winkless
Author: Andres Freund, Amit Langote, Peter Geoghegan
Discussion: CAEzk6fdzJ3xYQZGbcuYM2rBd2BuDkUksmK=mY9UYYDugg_GgZg@mail.gmail.com,
CAM3SWZS+CauzbiCEcg-GdE6K6ycHE_Bz6Ksszy8AoixcMHOmsA@mail.gmail.com
Backpatch: 9.5, where ON CONFLICT was introduced
2015-10-03 15:12:10 +02:00
WHERE excluded.hat_color <> 'forbidden' AND hat_data.* != excluded.*
2015-05-13 00:13:22 +02:00
RETURNING *;
2015-05-23 02:16:24 +02:00
SELECT definition FROM pg_rules WHERE tablename = 'hats' ORDER BY rulename;
definition
-----------------------------------------------------------------------------------------------------------------------------------------
CREATE RULE hat_upsert AS +
ON INSERT TO hats DO INSTEAD INSERT INTO hat_data (hat_name, hat_color) +
VALUES (new.hat_name, new.hat_color) ON CONFLICT(hat_name) DO UPDATE SET hat_name = hat_data.hat_name, hat_color = excluded.hat_color+
Fix several bugs related to ON CONFLICT's EXCLUDED pseudo relation.
Four related issues:
1) attnos/varnos/resnos for EXCLUDED were out of sync when a column
after one dropped in the underlying relation was referenced.
2) References to whole-row variables (i.e. EXCLUDED.*) lead to errors.
3) It was possible to reference system columns in the EXCLUDED pseudo
relations, even though they would not have valid contents.
4) References to EXCLUDED were rewritten by the RLS machinery, as
EXCLUDED was treated as if it were the underlying relation.
To fix the first two issues, generate the excluded targetlist with
dropped columns in mind and add an entry for whole row
variables. Instead of unconditionally adding a wholerow entry we could
pull up the expression if needed, but doing it unconditionally seems
simpler. The wholerow entry is only really needed for ruleutils/EXPLAIN
support anyway.
The remaining two issues are addressed by changing the EXCLUDED RTE to
have relkind = composite. That fits with EXCLUDED not actually being a
real relation, and allows to treat it differently in the relevant
places. scanRTEForColumn now skips looking up system columns when the
RTE has a composite relkind; fireRIRrules() already had a corresponding
check, thereby preventing RLS expansion on EXCLUDED.
Also add tests for these issues, and improve a few comments around
excluded handling in setrefs.c.
Reported-By: Peter Geoghegan, Geoff Winkless
Author: Andres Freund, Amit Langote, Peter Geoghegan
Discussion: CAEzk6fdzJ3xYQZGbcuYM2rBd2BuDkUksmK=mY9UYYDugg_GgZg@mail.gmail.com,
CAM3SWZS+CauzbiCEcg-GdE6K6ycHE_Bz6Ksszy8AoixcMHOmsA@mail.gmail.com
Backpatch: 9.5, where ON CONFLICT was introduced
2015-10-03 15:12:10 +02:00
WHERE ((excluded.hat_color <> 'forbidden'::bpchar) AND (hat_data.* <> excluded.*)) +
2015-05-23 02:16:24 +02:00
RETURNING hat_data.hat_name, +
hat_data.hat_color;
(1 row)
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
-- Works (does upsert)
2015-05-13 00:13:22 +02:00
INSERT INTO hats VALUES ('h8', 'black') RETURNING *;
hat_name | hat_color
------------+------------
h8 | black
(1 row)
SELECT * FROM hat_data WHERE hat_name = 'h8';
hat_name | hat_color
------------+------------
h8 | black
(1 row)
INSERT INTO hats VALUES ('h8', 'white') RETURNING *;
hat_name | hat_color
------------+------------
h8 | white
(1 row)
SELECT * FROM hat_data WHERE hat_name = 'h8';
hat_name | hat_color
------------+------------
h8 | white
(1 row)
INSERT INTO hats VALUES ('h8', 'forbidden') RETURNING *;
hat_name | hat_color
----------+-----------
(0 rows)
SELECT * FROM hat_data WHERE hat_name = 'h8';
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
hat_name | hat_color
------------+------------
2015-05-13 00:13:22 +02:00
h8 | white
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
(1 row)
SELECT tablename, rulename, definition FROM pg_rules
WHERE tablename = 'hats';
2015-05-19 21:07:28 +02:00
tablename | rulename | definition
-----------+------------+-----------------------------------------------------------------------------------------------------------------------------------------
hats | hat_upsert | CREATE RULE hat_upsert AS +
| | ON INSERT TO hats DO INSTEAD INSERT INTO hat_data (hat_name, hat_color) +
| | VALUES (new.hat_name, new.hat_color) ON CONFLICT(hat_name) DO UPDATE SET hat_name = hat_data.hat_name, hat_color = excluded.hat_color+
Fix several bugs related to ON CONFLICT's EXCLUDED pseudo relation.
Four related issues:
1) attnos/varnos/resnos for EXCLUDED were out of sync when a column
after one dropped in the underlying relation was referenced.
2) References to whole-row variables (i.e. EXCLUDED.*) lead to errors.
3) It was possible to reference system columns in the EXCLUDED pseudo
relations, even though they would not have valid contents.
4) References to EXCLUDED were rewritten by the RLS machinery, as
EXCLUDED was treated as if it were the underlying relation.
To fix the first two issues, generate the excluded targetlist with
dropped columns in mind and add an entry for whole row
variables. Instead of unconditionally adding a wholerow entry we could
pull up the expression if needed, but doing it unconditionally seems
simpler. The wholerow entry is only really needed for ruleutils/EXPLAIN
support anyway.
The remaining two issues are addressed by changing the EXCLUDED RTE to
have relkind = composite. That fits with EXCLUDED not actually being a
real relation, and allows to treat it differently in the relevant
places. scanRTEForColumn now skips looking up system columns when the
RTE has a composite relkind; fireRIRrules() already had a corresponding
check, thereby preventing RLS expansion on EXCLUDED.
Also add tests for these issues, and improve a few comments around
excluded handling in setrefs.c.
Reported-By: Peter Geoghegan, Geoff Winkless
Author: Andres Freund, Amit Langote, Peter Geoghegan
Discussion: CAEzk6fdzJ3xYQZGbcuYM2rBd2BuDkUksmK=mY9UYYDugg_GgZg@mail.gmail.com,
CAM3SWZS+CauzbiCEcg-GdE6K6ycHE_Bz6Ksszy8AoixcMHOmsA@mail.gmail.com
Backpatch: 9.5, where ON CONFLICT was introduced
2015-10-03 15:12:10 +02:00
| | WHERE ((excluded.hat_color <> 'forbidden'::bpchar) AND (hat_data.* <> excluded.*)) +
2015-05-19 21:07:28 +02:00
| | RETURNING hat_data.hat_name, +
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
| | hat_data.hat_color;
(1 row)
2015-05-13 00:13:22 +02:00
-- ensure explain works for on insert conflict rules
explain (costs off) INSERT INTO hats VALUES ('h8', 'forbidden') RETURNING *;
Fix several bugs related to ON CONFLICT's EXCLUDED pseudo relation.
Four related issues:
1) attnos/varnos/resnos for EXCLUDED were out of sync when a column
after one dropped in the underlying relation was referenced.
2) References to whole-row variables (i.e. EXCLUDED.*) lead to errors.
3) It was possible to reference system columns in the EXCLUDED pseudo
relations, even though they would not have valid contents.
4) References to EXCLUDED were rewritten by the RLS machinery, as
EXCLUDED was treated as if it were the underlying relation.
To fix the first two issues, generate the excluded targetlist with
dropped columns in mind and add an entry for whole row
variables. Instead of unconditionally adding a wholerow entry we could
pull up the expression if needed, but doing it unconditionally seems
simpler. The wholerow entry is only really needed for ruleutils/EXPLAIN
support anyway.
The remaining two issues are addressed by changing the EXCLUDED RTE to
have relkind = composite. That fits with EXCLUDED not actually being a
real relation, and allows to treat it differently in the relevant
places. scanRTEForColumn now skips looking up system columns when the
RTE has a composite relkind; fireRIRrules() already had a corresponding
check, thereby preventing RLS expansion on EXCLUDED.
Also add tests for these issues, and improve a few comments around
excluded handling in setrefs.c.
Reported-By: Peter Geoghegan, Geoff Winkless
Author: Andres Freund, Amit Langote, Peter Geoghegan
Discussion: CAEzk6fdzJ3xYQZGbcuYM2rBd2BuDkUksmK=mY9UYYDugg_GgZg@mail.gmail.com,
CAM3SWZS+CauzbiCEcg-GdE6K6ycHE_Bz6Ksszy8AoixcMHOmsA@mail.gmail.com
Backpatch: 9.5, where ON CONFLICT was introduced
2015-10-03 15:12:10 +02:00
QUERY PLAN
-------------------------------------------------------------------------------------------------
2015-05-13 00:13:22 +02:00
Insert on hat_data
Conflict Resolution: UPDATE
2015-05-19 21:07:28 +02:00
Conflict Arbiter Indexes: hat_data_unique_idx
Fix several bugs related to ON CONFLICT's EXCLUDED pseudo relation.
Four related issues:
1) attnos/varnos/resnos for EXCLUDED were out of sync when a column
after one dropped in the underlying relation was referenced.
2) References to whole-row variables (i.e. EXCLUDED.*) lead to errors.
3) It was possible to reference system columns in the EXCLUDED pseudo
relations, even though they would not have valid contents.
4) References to EXCLUDED were rewritten by the RLS machinery, as
EXCLUDED was treated as if it were the underlying relation.
To fix the first two issues, generate the excluded targetlist with
dropped columns in mind and add an entry for whole row
variables. Instead of unconditionally adding a wholerow entry we could
pull up the expression if needed, but doing it unconditionally seems
simpler. The wholerow entry is only really needed for ruleutils/EXPLAIN
support anyway.
The remaining two issues are addressed by changing the EXCLUDED RTE to
have relkind = composite. That fits with EXCLUDED not actually being a
real relation, and allows to treat it differently in the relevant
places. scanRTEForColumn now skips looking up system columns when the
RTE has a composite relkind; fireRIRrules() already had a corresponding
check, thereby preventing RLS expansion on EXCLUDED.
Also add tests for these issues, and improve a few comments around
excluded handling in setrefs.c.
Reported-By: Peter Geoghegan, Geoff Winkless
Author: Andres Freund, Amit Langote, Peter Geoghegan
Discussion: CAEzk6fdzJ3xYQZGbcuYM2rBd2BuDkUksmK=mY9UYYDugg_GgZg@mail.gmail.com,
CAM3SWZS+CauzbiCEcg-GdE6K6ycHE_Bz6Ksszy8AoixcMHOmsA@mail.gmail.com
Backpatch: 9.5, where ON CONFLICT was introduced
2015-10-03 15:12:10 +02:00
Conflict Filter: ((excluded.hat_color <> 'forbidden'::bpchar) AND (hat_data.* <> excluded.*))
2015-05-13 00:13:22 +02:00
-> Result
(5 rows)
-- ensure upserting into a rule, with a CTE (different offsets!) works
WITH data(hat_name, hat_color) AS (
VALUES ('h8', 'green'),
('h9', 'blue'),
('h7', 'forbidden')
)
INSERT INTO hats
SELECT * FROM data
RETURNING *;
hat_name | hat_color
------------+------------
h8 | green
h9 | blue
(2 rows)
EXPLAIN (costs off) WITH data(hat_name, hat_color) AS (
VALUES ('h8', 'green'),
('h9', 'blue'),
('h7', 'forbidden')
)
INSERT INTO hats
SELECT * FROM data
RETURNING *;
Fix several bugs related to ON CONFLICT's EXCLUDED pseudo relation.
Four related issues:
1) attnos/varnos/resnos for EXCLUDED were out of sync when a column
after one dropped in the underlying relation was referenced.
2) References to whole-row variables (i.e. EXCLUDED.*) lead to errors.
3) It was possible to reference system columns in the EXCLUDED pseudo
relations, even though they would not have valid contents.
4) References to EXCLUDED were rewritten by the RLS machinery, as
EXCLUDED was treated as if it were the underlying relation.
To fix the first two issues, generate the excluded targetlist with
dropped columns in mind and add an entry for whole row
variables. Instead of unconditionally adding a wholerow entry we could
pull up the expression if needed, but doing it unconditionally seems
simpler. The wholerow entry is only really needed for ruleutils/EXPLAIN
support anyway.
The remaining two issues are addressed by changing the EXCLUDED RTE to
have relkind = composite. That fits with EXCLUDED not actually being a
real relation, and allows to treat it differently in the relevant
places. scanRTEForColumn now skips looking up system columns when the
RTE has a composite relkind; fireRIRrules() already had a corresponding
check, thereby preventing RLS expansion on EXCLUDED.
Also add tests for these issues, and improve a few comments around
excluded handling in setrefs.c.
Reported-By: Peter Geoghegan, Geoff Winkless
Author: Andres Freund, Amit Langote, Peter Geoghegan
Discussion: CAEzk6fdzJ3xYQZGbcuYM2rBd2BuDkUksmK=mY9UYYDugg_GgZg@mail.gmail.com,
CAM3SWZS+CauzbiCEcg-GdE6K6ycHE_Bz6Ksszy8AoixcMHOmsA@mail.gmail.com
Backpatch: 9.5, where ON CONFLICT was introduced
2015-10-03 15:12:10 +02:00
QUERY PLAN
-------------------------------------------------------------------------------------------------
2015-05-13 00:13:22 +02:00
Insert on hat_data
Conflict Resolution: UPDATE
2015-05-19 21:07:28 +02:00
Conflict Arbiter Indexes: hat_data_unique_idx
Fix several bugs related to ON CONFLICT's EXCLUDED pseudo relation.
Four related issues:
1) attnos/varnos/resnos for EXCLUDED were out of sync when a column
after one dropped in the underlying relation was referenced.
2) References to whole-row variables (i.e. EXCLUDED.*) lead to errors.
3) It was possible to reference system columns in the EXCLUDED pseudo
relations, even though they would not have valid contents.
4) References to EXCLUDED were rewritten by the RLS machinery, as
EXCLUDED was treated as if it were the underlying relation.
To fix the first two issues, generate the excluded targetlist with
dropped columns in mind and add an entry for whole row
variables. Instead of unconditionally adding a wholerow entry we could
pull up the expression if needed, but doing it unconditionally seems
simpler. The wholerow entry is only really needed for ruleutils/EXPLAIN
support anyway.
The remaining two issues are addressed by changing the EXCLUDED RTE to
have relkind = composite. That fits with EXCLUDED not actually being a
real relation, and allows to treat it differently in the relevant
places. scanRTEForColumn now skips looking up system columns when the
RTE has a composite relkind; fireRIRrules() already had a corresponding
check, thereby preventing RLS expansion on EXCLUDED.
Also add tests for these issues, and improve a few comments around
excluded handling in setrefs.c.
Reported-By: Peter Geoghegan, Geoff Winkless
Author: Andres Freund, Amit Langote, Peter Geoghegan
Discussion: CAEzk6fdzJ3xYQZGbcuYM2rBd2BuDkUksmK=mY9UYYDugg_GgZg@mail.gmail.com,
CAM3SWZS+CauzbiCEcg-GdE6K6ycHE_Bz6Ksszy8AoixcMHOmsA@mail.gmail.com
Backpatch: 9.5, where ON CONFLICT was introduced
2015-10-03 15:12:10 +02:00
Conflict Filter: ((excluded.hat_color <> 'forbidden'::bpchar) AND (hat_data.* <> excluded.*))
2015-05-13 00:13:22 +02:00
CTE data
-> Values Scan on "*VALUES*"
-> CTE Scan on data
(7 rows)
SELECT * FROM hat_data WHERE hat_name IN ('h8', 'h9', 'h7') ORDER BY hat_name;
hat_name | hat_color
------------+------------
h7 | black
h8 | green
h9 | blue
(3 rows)
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
DROP RULE hat_upsert ON hats;
drop table hats;
drop table hat_data;
2016-07-26 22:07:02 +02:00
-- tests for pg_get_*def with invalid objects
SELECT pg_get_constraintdef(0);
pg_get_constraintdef
----------------------
(1 row)
SELECT pg_get_functiondef(0);
pg_get_functiondef
--------------------
(1 row)
SELECT pg_get_indexdef(0);
pg_get_indexdef
-----------------
(1 row)
SELECT pg_get_ruledef(0);
pg_get_ruledef
----------------
(1 row)
SELECT pg_get_triggerdef(0);
pg_get_triggerdef
-------------------
(1 row)
SELECT pg_get_viewdef(0);
pg_get_viewdef
----------------
(1 row)
2016-07-29 18:06:18 +02:00
SELECT pg_get_function_arguments(0);
pg_get_function_arguments
---------------------------
(1 row)
SELECT pg_get_function_identity_arguments(0);
pg_get_function_identity_arguments
------------------------------------
(1 row)
SELECT pg_get_function_result(0);
pg_get_function_result
------------------------
(1 row)
SELECT pg_get_function_arg_default(0, 0);
pg_get_function_arg_default
-----------------------------
(1 row)
SELECT pg_get_function_arg_default('pg_class'::regclass, 0);
pg_get_function_arg_default
-----------------------------
(1 row)