Imagine that you have to implement a table which must contain one row minimum and
may not have more than one rows. So, on insert of a row you can check if there’s
already a row in the table by joining the table to itself, like the next statement
select 1 from table t1 , table t2 where t1.id != t2.id
The obvious way to do this is to create a set
of database triggers. You cannot use only one row trigger because the query is mutating,
so you need to put the rowid on a stack on a row event trigger and loop
over the rowid’s on stack on a after statement event.
Next create 3 triggers to prevent (sort of) that more than 1 row is
in the table at all times.
Because checking the record count involves a mutating table issue
the rowid is put on a stack and handled in the after statement trigger.
You need
1) a before statement trigger to initialize the stack
2) a (after) row trigger to put the new row on the stack.
I prefer to use an after row trigger above before row because when the after row event fires all
database constraints (when not flagged defered) are finished.
Failures on these constraints are handled immediately and after row triggers do not fire,
thus will cost nothing. It more expensive for a before row to fire when the row fails
due to a constraint violation. So I prefer to let the database do it’s work before I will throw in
some business rules checking.
3) a after statement trigger to perform the singularity check
Here’s the scripting:
create table ags_parameters ( par_id number(4) not null, par_name varchar2(100 byte) ) /
alter table ags_parameters add constraint ags_par_pk primary key(par_id) / create or replace trigger ags_par_bs before delete or insert or update on ags_parameters declare begin if inserting or updating then acc_rowid_stack_light.create_stack; end if; exception when others then raise_application_error(-20010, sqlerrm ); end; /
create or replace trigger ags_par_ar after delete or insert or update on ags_parameters for each row declare flg_par1 constant binary_integer := 1; begin if inserting then acc_rowid_stack_light.push_flag(:new.rowid, flg_par1); elsif deleting then raise_application_error(-20010, 'Delete is not allowed' ); end if; exception when others then raise_application_error(-20010, sqlerrm ); end ags_par_ar; / create or replace trigger ags_par_as after delete or insert or update on ags_parameters declare flg_par1 constant binary_integer := 1; e_locked exception; pragma exception_init (e_locked, -54); t_rowid rowid; t_value binary_integer; begin while acc_rowid_stack_light.pop_flagset( t_rowid, t_value ) loop if acc_rowid_stack_light.check_flag(t_value, flg_par1) then declare cursor c_par(b_rowid in rowid) is select 1 from ags_parameters par1 , ags_parameters par2 where par1.par_id != par2.par_id and par1.rowid = b_rowid for update of par1.par_id; r_par c_par%rowtype; l_par_found boolean; e_par exception; begin open c_par(t_rowid); fetch c_par into r_par; l_par_found := c_par%found; close c_par; if l_par_found then raise e_par; end if; exception when e_par then raise_application_error(-20010, 'Only one row is allowed in this table'); end; end if; end loop; acc_rowid_stack_light.delete_stack; exception when others then raise_application_error(-20010, sqlerrm ); end ags_par_as; /
Now the testing.
First try to insert 2 records and see if it works.
insert into ags_parameters (par_name) values ('test1'); insert into ags_parameters (par_name) values ('test2');
The second row will raise an excpetion “ORA-20010 – Only one row is allowed in this table”. That’s fine.
But is it?
Let’s try another experiment. This time I’m going to use 2 concurrent sessions.
In the first session I insert a row.
prompt Rollback previous test results. rollback; insert into ags_parameters (par_name) values ('session1'); pause; commit;
It returns with “1 row created” Now do NOT commit! Open another session and also insert a row into ags_parameters and commit
prompt second session insert into ags_parameters (par_name) values ('session2'); commit;
It also returns with “1 row created”
Return to the first session and commit that session also. Than count the records.
select count(*) from ags_parameters;
Oh no, 2 records ! ! ! !
Working alternative/solution
create table fbi_parameters ( par_id number(4) not null, par_name varchar2(100 byte) ) /
alter table fbi_parameters add constraint fbi_par_pk primary key(par_id) /
Create a function based index. This index returns cq indexes value 1 for each and every record. Because it is
defined as a UNIQUE index, only one row is permitted in the table.
create unique index fbi_one_row_table_i on fbi_parameters (1) / insert into fbi_parameters (par_name) values ('session 1'); pause; commit;
Do NOT commit! Open another session and also insert a row into fbi_parameters and commit
insert into ags_parameters(par_name) values ('session2'); pause; commit;
It is immediately being locked by the other session.
Return to the first session and issue a commit;
Return to the second session and issue a commit;
The second session stops because “ORA-00001: unique constraint (fbi_one_row_table) violated”
select count(*) from fbi_parameters;
Yippie! Function based index to the rescue.
And as a side effect, less objects (1 table + 1 index + 3 triggers) vs (1 table + 2 indices + 0 triggers)
But that”s only part of the story: It is still possible to delete all record from fbi_parameters.
Here, I guess a database trigger is the only possible solution.
create or replace trigger fbi_par_br after delete or insert or update on ags_parameters for each row begin if deleting then raise_application_error(-20010, 'Deleting the last/only row in this table is not allowed'); end if; end fbi_par_br; /
Table ags_parameters already has a check against deleting rows in the after row trigger. It might
as well be implemented as a before row trigger.
Your solution is correct but there is no need to create an extra column . just pickup a non null column in the table and build a unique key by applying a single result function to it.
Eg: Number —>CREATE UNIQUE INDEX tableX_ix ON tableX ( LEAST(0,ABS(fieldN)) );
varchar2—->CREATE UNIQUE INDEX tableX_ix ON tableX ( LEAST(0,ASCII(substr(fieldC,1,1))) );
…..
Laura, your solution is elegant and perfect, thank you very much!
This was a great help to me, I ended up creating table with a primary key that has a default value of 1 and a check constraint =1 (no Triggers necessary).
Similar to Tobias, but returning to trigger type solution, how about:
A) Create the table
B) Insert one row into it.
C) Create a trigger forbidding insert and delete as in…
create or replace trigger trig_name
before delete or insert on table_name
for each row
begin
raise_application_error(-20010, ‘The table “TABLE_NAME” must always have one and only one row’);
end;
Alternativly create the table using a DBA’s account and only grant select,update to anyone else 🙂
@Tobias,
So, now you have 2 concurrent sessions inserting into that table at the same time. Hoe many rows will you end up with?
My guess: 2 rows.
That’s what this post is all about.
You can use roles:
CREATE TABLE tablename (
value1 INTEGER NOT NULL,
value2 INTEGER NOT NULL
);
INSERT INTO tablename (value1, value2) VALUES (1, 2);
CREATE RULE noDeleteRule AS ON DELETE TO tablename DO INSTEAD NOTHING;
CREATE RULE noInsertRule AS ON INSERT TO tablename DO INSTEAD NOTHING;
this work in postgresql 8.1
Besides less objects, a nice feature of the solutions given by Anton and LewisC is that it
works on RDBMS from 7.3 up to 10g, while mine “only” works on RDBMS 8i up to 10g
because of the function based index. All options work perfectly.
Hello Toon,
The row must persist in all sessions even after a restart of the database.
The row must be updateble (by privileged users).
The maximum amount of rows in the table must be 1
and the minimum amount of rows must be 1. In others words: one mandatory row.
Harm,
What *exactly* is the requirement here?
A table with one row in it… could you not just implement the
values that need be stored, as persistent package variables?
Or should the values really persist across sessions?
Toon
Lean!
The same, but in another way (1 table + 1 index + 1 trigger)
create table test( id number(1) primary key, v1 varchar2(10) )
create or replace trigger test_br
before delete or insert or update on test
for each row
begin
if inserting or updating
then
:new.id := 1;
else
raise_application_error(-20010, ‘Deleting the last/only row in this table is not allowed’);
end if;
end;
Anton
Hi,
Very interesting problem. I think I have an alternative that is a bit less code. If I
understand the requirement, I think you can do it with a unique index and 1 trigger.
How about this:
CREATE TABLE TEST_UK
(
FIELD1 NUMBER DEFAULT 1 NOT NULL,
REAL_DATA VARCHAR2(10),
MORE_DATA NUMBER
);
Field1 is a field not used by the application. It’s just along for the ride. Real_data and
more_data are application fields.
We create a Unique Key on field1.
CREATE UNIQUE INDEX TEST_UK_IDX ON TEST_UK
(FIELD1);
And a single trigger on the table:
CREATE OR REPLACE TRIGGER TEST_UK_TRG
BEFORE DELETE OR INSERT OR UPDATE
ON TEST_UK
REFERENCING NEW AS NEW OLD AS OLD
FOR EACH ROW
BEGIN
IF deleting THEN
raise_application_error( -20001, ‘Cannot delete a row from this table’);
ELSE
:new.field1 := 1;
END IF;
END ;
/
You can ignore the field1 column in all updates and inserts. The trigger will make sure
that this not null column is populated.
I think that does it. A PK could be used instead of a unique key in this instance but by
using a unique key, the PK remains available for use by the application. Although with
a one row table, I wonder how important that really is.
Thanks,
LewisC