Firebird autoIncrement issue - sql

I've created Customers Table through following code :
CREATE TABLE CUSTOMERS (
ID INTEGER DEFAULT 1 NOT NULL,
"NAME" VARCHAR(30) CHARACTER SET UTF8 COLLATE UTF8,
"LASTNAME" VARCHAR(30) CHARACTER SET UTF8 COLLATE UTF8);
ALTER TABLE CUSTOMERS ADD PRIMARY KEY (ID);
SET TERM ^ ;
CREATE TRIGGER BI_CUSTOMERS_ID FOR CUSTOMERS
ACTIVE BEFORE INSERT
POSITION 1
AS
BEGIN
IF (NEW.ID IS NULL) THEN
NEW.ID = GEN_ID(CUSTOMERS_ID_GEN, 1);
END^
SET TERM ; ^
But when I inserting second row like :
insert into Customers(Name,LastName) values('Hamed','Kamrava');
It gets below error :
Violation of PRIMARY or UNIQUE KEY constraint "INTEG_2" on table "CUSTOMERS".

id is a primary key with default value 1.
In the first record, since you have not explicitly mentioned the value of id, it has inserted with 1. But you cannot have any other records with id = 1 since id is a Primary Key.
Use the statement:
insert into Customers(id, Name, LastName) values (2, 'Hamed', 'Kamrava');
This should insert the record. If you do not want to hardcode the value of ID for each row, suggest you to create a sequence and then during the insert, use,
insert into Customers(id, Name, LastName) values (nextval('<seq_name>'), <name>, <lastname>);

Since your trigger code is
IF (NEW.ID IS NULL) THEN
NEW.ID = GEN_ID(CUSTOMERS_ID_GEN, 1);
and, as #Orangecrush posted, you set a default value of 1, a unique id is never generated. So you should try to omit the default value in the ddl.

Related

SQL Trigger Wont Generate Primary Key

I am trying to create a table that logs all inserts in the author table. Here is the author table, and the Audit_log Table:
CREATE TABLE Author(AuthorID INT PRIMARY KEY NOT NULL,
last_name CHAR(20),
first_name CHAR(20));
CREATE TABLE Audit_Log(Action_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
table_name Char(40),
action_name Char(6),
Date_Time DATETIME DEFAULT CURRENT_TIMESTAMP);
Here is the simple trigger.
DELIMITER $$
CREATE TRIGGER Author_Trigger AFTER INSERT
ON Author
FOR EACH ROW BEGIN
INSERT INTO Audit_Log VALUES('Author', 'INSERT', CURRENT_TIMESTAMP);
END $$
DELIMITER ;
However, when I cause the trigger to occur by inserting into the author table, it says that the columns do not match row 1. How come my Primary key does not get auto generated, despite having the AUTO_INCREMENT Constraint?
How can I get this trigger to generate the primary key?
Basically MySQL thinks that 'Author' is being inserted as the PRIMARY KEY (Action_ID). What you can do to avoid this is specify wich attribute correspond to wich element of the INSERT query. This should work :)
DELIMITER $$
CREATE TRIGGER Author_Trigger AFTER INSERT
ON Author
FOR EACH ROW BEGIN
INSERT INTO Audit_Log(table_name, action_name, Date_Time)
VALUES('Author', 'INSERT', CURRENT_TIMESTAMP);
END $$
DELIMITER ;
For the value to autoincrement, since you do not have defined the data you must insert and place the autoincremental, it does not take it, so the first value is null and through this null it will autoincrement.
DELIMITER $$
CREATE TRIGGER Author_Trigger AFTER INSERT
ON Author
FOR EACH ROW BEGIN
INSERT INTO Audit_Log VALUES(null,'Author', 'INSERT', CURRENT_TIMESTAMP);
END $$
DELIMITER ;

Upsert/on conflict with serial primary key

The upsert works using on conflict but the datatype of id is serial meaning I want to have it auto-generated/incremented. If I do the insert without specifying id the insert works fine.
The problem I have is combining the two. To get the key auto incremented I do not pass the id into the insert but if I do not pass id then the update will never fire. I cannot pass null to id as it is non-null field.
In below example - I run the query first time and it does insert and second time it does update but I cannot figure out how to pass 'nothing' to insert so the identity key still works on insert. I can put DEFAULT in the insert but then I cannot pass a real id value if there is one.
CREATE TABLE public.upsert_test
(
id INTEGER NOT NULL DEFAULT nextval('upsert_test_id_seq'::regclass),
name character varying(20) COLLATE pg_catalog."default",
description character varying(20) COLLATE pg_catalog."default",
CONSTRAINT upsert_test_pkey PRIMARY KEY (id)
)
INSERT INTO upsert_test (id, name, description)
VALUES (1, 'thing1', 'test')
on conflict (id)
do update set (name , description) = ('thing_updated','test-updated')
where upsert_test.id = 1;
You can change your query to use sequence functions like:
INSERT INTO upsert_test (id, name, description)
VALUES ((select nextval('upsert_test_id_seq')), 'thing1', 'test')
on conflict (id)
do update set (name , description) = ('thing_updated','test-updated')
where upsert_test.id = (select currval('upsert_test_id_seq'));
Note this may not be threadsafe, for eg if second call to this sql is executed before select currval('upsert_test_id_seq') in first call, then the update may fail in first query.
Update after more information from op
You can change the query to like this:
INSERT INTO upsert_test (id, name, description)
VALUES (COALESCE(:YOUR_ID_PARAM, (select nextval('upsert_test_id_seq'))), 'thing1', 'test')
on conflict (id)
do update set (name , description) = ('thing_updated','test-updated')
where upsert_test.id = :YOUR_ID_PARAM;
Note I added the coalesce function so if your parameter is null then use sequence nextval. Also, the update now also uses your parameter.

How to add values in one table automatically when a condition is true

So, Here is the condition.
I have a User_tbl whose code is as follow
CREATE TABLE Users_tbl (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
username TEXT,
password TEXT,
user_type INT
);
user_type is either 0,1 or 2 .. If it is 0 then it is player , 1 is for coach and 2 is for audience.
Now, I want to create a new table which has lists of coach inside it . Whose schema will be
CREATE TABLE coach_tbl(
coach_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
username TEXT,
password TEXT
)
and what I need is that, when the entry which is placed in Users_tbl has user_type =1 then it should Trigger one other query which will create an entry in coach_tbl and fill the columns. It should happen dynamically .
The following TRIGGER would accomplish what you want :-
CREATE TRIGGER setup_coach
AFTER INSERT ON Users_tbl
WHEN new.user_type = 1
BEGIN
INSERT INTO coach_tbl (username, password) VALUES(new.username,new.password);
END
;
The following was used for testing the above :-
DROP TABLE IF EXISTS Users_tbl;
CREATE TABLE IF NOT EXISTS Users_tbl (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
username TEXT,
password TEXT,
user_type INT
);
DROP TABLE IF EXISTS coach_tbl;
CREATE TABLE IF NOT EXISTS coach_tbl(
coach_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
username TEXT,
password TEXT
);
CREATE TRIGGER setup_coach
AFTER INSERT ON Users_tbl
WHEN new.user_type = 1
BEGIN
INSERT INTO coach_tbl (username, password) VALUES(new.username,new.password);
END
;
INSERT INTO Users_tbl (username, password,user_type)
VALUES
('Fred','fred1234',0),
('Bert','bert1234',1),
('Harold','harold1234',0),
('Alan','alan1234',1);
The result being :-
Supplementary (aka Why not the above)
Storing the exact same values. i.e. duplicating them, is contrary to normalisation and could lead to issues. e.g. if (using the above) "Bert"'s name or "password" changed you'd have to change it in two places. As it stands there is no need to duplicate this data as it would be easily available
For example, if you wanted to list the coaches you could use :-
SELECT username FROM coach_tbl;
Using the following, though, returns exactly the same but without the additional table :-
SELECT username FROM Users_tbl WHERE user_type = 1;
Supposing you had coach specific information say for example the number of times coaching then you could have an additional table such as :-
CREATE TABLE IF NOT EXISTS coaching_information
(
user_id_reference INTEGER REFERENCES Users_tbl(id),
number_of_times_coaching INTEGER DEFAULT 0
)
;
Along with a TRIGGER to automatically add default coaching information :-
CREATE TRIGGER autoadd_coaching_information_entry
AFTER INSERT ON Users_tbl
WHEN new.user_type = 1
BEGIN
INSERT INTO coaching_information
(user_id_reference)
VALUES (new.id)
;
END
;
Note! no need to set the number_of_times_coaching column as it will default to 0.
Assuming that all TABLES have been emptied then using (again):-
INSERT INTO Users_tbl (username, password,user_type)
VALUES
('Fred','fred1234',0),
('Bert','bert1234',1),
('Harold','harold1234',0),
('Alan','alan1234',1);
results in :-
2 refers to Bert, 4 to Alan
You could then list all coaches who have not coached (chosen for laziness of not having to update coaching inforamtion) :-
SELECT 'Coach '||username||' is up for a coaching experience.' AS coaching_needed
FROM coaching_information
JOIN Users_tbl ON Users_tbl.id = coaching_information.user_id_reference
WHERE coaching_information.number_of_times_coaching < 1
The result would be :-
Say Bert changed name to Charles e.g. using UPDATE Users_tbl SET username = 'Charles' WHERE username = 'Bert';
Then just with the 1 change the results from the above query would be :-
The full SQL used for testing the above was :-
DROP TABLE IF EXISTS coach_tbl;
DROP TABLE IF EXISTS Users_tbl;
CREATE TABLE IF NOT EXISTS Users_tbl (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
username TEXT,
password TEXT,
user_type INT
);
DROP TRIGGER IF EXISTS setup_coach; -- get rid of defunct TRIGGER
CREATE TABLE IF NOT EXISTS coaching_information
(
user_id_reference INTEGER REFERENCES Users_tbl(id) ON DELETE CASCADE,
-- Note ON DELETE CASCADE will automatically delete a coach should
-- the coach's User_tbl entry be deleted i.e. the deletion is propoagted
-- to the children of the parent.
-- (could also use ON UPDATE CASCADE but unlikely to change the underlying id)
number_of_times_coaching INTEGER DEFAULT 0
)
;
DROP TRIGGER IF EXISTS autoadd_coaching_information_entry;
CREATE TRIGGER autoadd_coaching_information_entry
AFTER INSERT ON Users_tbl
WHEN new.user_type = 1
BEGIN
INSERT INTO coaching_information
(user_id_reference)
VALUES (new.id)
;
END
;
INSERT INTO Users_tbl (username, password,user_type)
VALUES
('Fred','fred1234',0),
('Bert','bert1234',1),
('Harold','harold1234',0),
('Alan','alan1234',1)
;
--
-- Note! oncommmenting this will change Bert's name to Charles
--UPDATE Users_tbl SET username = 'Charles' WHERE username = 'Bert';
--
SELECT 'Coach '||username||' is up for a coaching experience.' AS coaching_needed
FROM coaching_information
JOIN Users_tbl ON Users_tbl.id = coaching_information.user_id_reference
WHERE coaching_information.number_of_times_coaching < 1

PostgreSQL constraint - only one row can have flag set

I have a PostgreSQL table
CREATE TABLE my_table
(
id serial NOT NULL,
name text,
actual boolean DEFAULT false,
CONSTRAINT my_table_pkey PRIMARY KEY (id),
);
How can I set a constraint that only one row can have actual flag set to TRUE?
You can create a unique partial index on that column only for true values:
create unique index on my_table (actual)
where actual = true;
SQLFiddle: http://sqlfiddle.com/#!15/91f62/1
My approach would add another feature to an index-based only solution: automatic deactivation of the current flag when setting the flag on another row.
That would involve, of course a trigger.
I would also recommand, as suggested by Frank Heikens, storing "not actual" state as a null instead of false. In postgresql, each null value is different from another null value, so the unicity constraint is quite easy to solve: we can allow for only one true value, and as many null value as necessary.
Here is my implementation:
CREATE TABLE my_table
(
id serial NOT NULL,
name text,
actual boolean,
CONSTRAINT my_table_pkey PRIMARY KEY (id),
CONSTRAINT actual_not_false CHECK(actual != false)
);
.
CREATE UNIQUE INDEX ON my_table USING btree(actual nulls LAST);
.
CREATE OR REPLACE FUNCTION ensure_only_one_enabled_state_trigger()
RETURNS trigger
AS $function$
BEGIN
-- nothing to do if updating the row currently enabled
IF (TG_OP = 'UPDATE' AND OLD.actual = true) THEN
RETURN NEW;
END IF;
-- disable the currently enabled row
EXECUTE format('UPDATE %I.%I SET actual = null WHERE actual = true;', TG_TABLE_SCHEMA, TG_TABLE_NAME);
-- enable new row
NEW.actual := true;
RETURN NEW;
END;
$function$
LANGUAGE plpgsql;
.
CREATE TRIGGER my_table_only_one_enabled_state
BEFORE INSERT OR UPDATE OF actual ON my_table
FOR EACH ROW WHEN (NEW.actual = true)
EXECUTE PROCEDURE ensure_only_one_enabled_state_trigger();
This should be doable with an exclusion constraint. For your case:
CREATE TABLE my_table
(
id serial NOT NULL,
name text,
actual boolean DEFAULT false,
CONSTRAINT my_table_pkey PRIMARY KEY (id),
EXCLUDE (actual WITH =) WHERE (actual)
);
Tested with:
INSERT INTO my_table VALUES (1, 'something', false);
INSERT INTO my_table VALUES (2, 'something_else', true);
Then the following is a constraint violation
INSERT INTO my_table VALUES (3, 'third_thing', true);

Why is trigger not fired on every single row when using "insert select" or "merge"

I defined a BEFORE INSERT trigger for a table and it works as expected for single INSERTstatements, but not for INSERT ... SELECT nor MERGE statements.
These are my database objects (simplified):
CREATE TABLE "COMPANY" (
"ID" NUMBER NOT NULL,
"NAME" VARCHAR(100)
);
CREATE TABLE "EMPLOYEE" (
"ID" NUMBER NOT NULL,
"COMPANY_ID" NUMBER NOT NULL
);
CREATE UNIQUE INDEX "EMPLOYEE_PK" ON "EMPLOYEE" ("ID");
CREATE SEQUENCE "EMPLOYEE_SEQUENCE";
CREATE TRIGGER "BI_EMPLOYEE" BEFORE INSERT ON "EMPLOYEE"
REFERENCING NEW AS newrow FOR EACH ROW BEGIN ATOMIC
IF newrow.id IS NULL THEN
SET newrow.id = NEXT VALUE FOR employee_sequence;
END IF;
END;
If single INSERTstatements are executed, everything works as expected, the ÌD is fetched from the sequence. But if I execute something like
INSERT INTO employee (company_id) SELECT id FROM company;
the I get an error:
integrity constraint violation: unique constraint or index violation: "EMPLOYEE_PK"
which could propably mean that it tries to insert the same key from the sequence twice.
I'm using the latests version 2.3.2 of HSQLDB.
Because triggers are set based, not row based.
See details here