Mysql dropping inserts with triggers - mysql

Using mysql 5.6. I have two tables. One has a whitelist of hashes. When I insert a new row into the other table, I want to first compare the hash in the insert statement to the whitelist. If it's in the whitelist, I don't want to do the insert (less data to plow through later). The inserts are generated from another program and are text files with sql statements.
I've been playing with triggers, and almost have it working:
CREATE TRIGGER `Filelist` BEFORE INSERT ON `filelist`
FOR EACH ROW BEGIN IF(
SELECT count( md5hash ) FROM whitelist WHERE md5hash = new.hash ) >0
THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Can not have duplicates';
END IF ;
END
But there's a problem. The Signal throwing up the error stops the import. I want to skip that line, not stop the whole import.
Some searching didn't find any way to silently skip the import.
My next idea was to create a duplicate table definition, and redirect the insert to that dup table. But the old and new don't seem to apply to table names.
Other then adding an ignore column to my table then doing a mass drop based on that column after the import, is there any way to achieve my goal? I'm having problems with this too [Ignore is a tinyint(1)]:
DELIMITER $$
CREATE TRIGGER whitelisted
BEFORE INSERT ON filelist
FOR EACH ROW BEGIN
IF (select count(md5hash) from whitelist where md5hash=new.hash) > 0 THEN
SET Ignore = true;
END IF;
END$$
/* This is now "END$$" not "END;" */
/* Reset the delimiter back to ";" */
DELIMITER ;
#1064 - You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near ') THEN SET Ignore = true;
END IF; END' at line 4
Any suggestions? I've also tried
SET Ignore = 1;
SET Ignore = '1';
SET new.Ignore = {all of the above};

I'm not sure if I follow this specification:
I have two tables. One has a whitelist of hashes. When I insert a new row into the other table, I want to first compare the hash in the insert statement to the whitelist. If it's in the whitelist, I don't want to do the insert
My first attempt would be like this:
INSERT INTO filelist (filename, hash)
SELECT "myfile", "ABCD" FROM DUAL
WHERE NOT EXISTS(
SELECT md5hash FROM whitelist where md5hash = "ABCD"
);
I don't think you need triggers for this at all unless there are missing details in your requirements.

I take it you're doing some kind of ON INSERT-trigger.
You need to add the following statement to your trigger to make it work as wanted:
FOR EACH ROW
This will make the trigger execute once on every row.

Related

MySQL trigger creating error when migrating from DB2

I am trying to convert some DB2 queries to MySQL . I have tried to find some tools to convert the conversion . Unfortunately i din't find any conversions tools and some of the online tools are not converting properly. So i have tried to convert DB2 queries myself to MySQL .
I have started to create 3 trigger queries in MySQL . Unfortunately i am getting some syntax errors . These are the following queries were i migrated from DB2 to MySQL .
Trigger 1 :
CREATE TRIGGER SAMPLE_TABLE3 AFTER INSERT ON SAMPLE_TABLE4
FOR EACH ROW
BEGIN
INSERT INTO LICENSE_REVISION(LICENSE, LICENSE_REV) VALUES (NEW.ID, (NEXT VALUE FOR REVISION));
END;
Here i am getting syntax error
right syntax to use near 'VALUE FOR REVISION));
END' at line 9
I think the problem due to NEXT VALUE FOR .
Question 1 :
Is it any NEXT VALUE FOR alternative for MySQL ?
In trigger 2 , i am doing
CREATE TRIGGER SAMPLE_TRIGGER AFTER UPDATE OF SUPPORT__SERVER_UPS ON SETTINGS
FOR EACH ROW
BEGIN ATOMIC
FOR d AS SELECT ID AS D_ID FROM DOMAIN
DO UPDATE DOMAIN_REVISION DR SET DR.SERVER_DOMAIN_REV = (NEXT VALUE FOR REVISION) WHERE DR.DOMAIN = D_ID;
END FOR;
END;
and getting error :
right syntax to use near 'OF SUPPORT__SERVER_UPS ON SETTINGS
REFERENCING NEW AS NEW OLD AS OLD
FOR EAC' at line 6
i think the problem is AFTER UPDATE OF with column and i am suspecting FOR d AS line 4 and BEGIN ATOMIC too .
Question 2 :
Can i use AFTER UPDATE OF with column in MySQL ? and any mistakes
in FOR d AS line no 4 and BEGIN ATOMIC line 3 .
if i have use multiple column values like
trigger :
CREATE TRIGGER SAMPLE_4 AFTER UPDATE OF IPV4_FIRST, IPV4, IPV4_MASK, IPV6_FIRST, IPV6, IPV6_MASK ON VIRTUAL_NETWORK
FOR EACH ROW
BEGIN
FOR d AS SELECT DOMAIN AS D_ID FROM DOMAIN_VIRTUAL_NETWORK WHERE VIRTUAL_NETWORK=NEW.ID
DO UPDATE DOMAIN_REVISION DR SET DR.CLIENT_NETWORK_REV = (NEXT VALUE FOR REVISION) WHERE DR.DOMAIN = D_ID;
END FOR;
END;
How can i approach this problem ? Should i use like this
IF NEW.a <> OLD.a or NEW.b <> OLD.b ?
I am beginner in this and i want to help to migrate . I know these are syntax problem and not valid questions . Please help or suggestion .
Update :
I have tried with last_insert_id and CURSOR . This is the working code now :
CREATE TRIGGER SAMPLE_TRIGGER AFTER UPDATE ON SETTINGS
FOR EACH ROW
BEGIN
DECLARE my_cursor CURSOR FOR SELECT ID AS D_ID FROM DOMAIN;
IF NEW.SUPPORT__SERVER_UPS <=> OLD.SUPPORT__SERVER_UPS THEN
open my_cursor;
my_loop: loop
FETCH my_cursor INTO D_ID;
UPDATE DOMAIN_REVISION DR SET DR.SERVER_DOMAIN_REV = (last_insert_id()) WHERE DR.DOMAIN = D_ID;
end loop my_loop;
close my_cursor;
END IF;
END;
Sequences
MySQL doesn't have sequence objects. NEXT VALUE FOR <sequence> is not supported in MySQL.
There's an awkward workaround to simulate a sequence by creating a single table that you increment every time you want a new value.
mysql> create table sequence (id int not null primary key );
mysql> insert into sequence values (0);
mysql> update sequence set id = last_insert_id(id+1);
mysql> select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
| 1 |
+------------------+
But every time you would use NEXT VALUE FOR <sequence> you would repeat the last two steps above. The last_insert_id() function in MySQL is more or less like DB2's IDENTITY_VAL_LOCAL(). Read full docs on last_insert_id() function here: https://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_last-insert-id
Column triggers
MySQL trigger declaration syntax is like
CREATE TRIGGER SAMPLE_TRIGGER AFTER UPDATE ON SETTINGS
FOR EACH ROW ...
MySQL supports no "OF" clause. That's used in DB2 for triggering on the update of specific columns, but MySQL doesn't support triggers on specific columns.
Loops
The FOR d AS SELECT ... loop construct is not supported by MySQL. If you need to do a loop, you need to learn about CURSOR syntax. See examples at https://dev.mysql.com/doc/refman/5.7/en/cursors.html

MySQL BEFORE INSERT trigger to turn duplicate primary keys inserts into updates

I'm trying to execute this query in a database through phpmyadmin
create trigger avoid_duplicated_sharing
before insert on sharingevents
for each row
begin
if ( select count(*) from sharingevents where shared_note_id = NEW.shared_note_id AND shared_to = NEW.shared_to > 0 ) then
delete from sharingevents where shared_note_id = NEW.shared_note AND shared_to = NEW.shared_to
END IF;
END
But phpmyadmin gives me the following error:
MySQL said: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'END IF' at line 7
Two questions:
What's wrong with my script?
After a BEFORE INSERT trigger, Will INSERT operation be performed? In case it doesn't I will have to remove INSERT INTO SharingEvents (SELECT * FROM NEW);
I solve it with the following code:
delimiter $$
create trigger avoid_duplicated_sharing
before insert on sharingevents
for each row
begin
if ( select count(*) from sharingevents where shared_note_id = NEW.shared_note_id AND shared_to = NEW.shared_to > 0 ) then
delete from sharingevents where shared_note_id = NEW.shared_note_id AND shared_to = NEW.shared_to;
end if;
END$$
The problem was the delimiter.
Even so, my trigger doesn't work. When the application inserts duplicated primary keys MySQL throws the following error:
#1442 - Can't update table 'sharingevents' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
Use exists:
if (exists (select 1 from sharingevents where shared_note_id = new.shared_note_id AND shared_to = new.shared_to) > 0) then
insert into sharingevents (shared_note_id,shared_to,permission_level)
values (NEW.shared_note_id,NEW.shared_to,NEW.permission_level);
end if;
Or, better yet, add a unique index on sharingevents(shared_note-id, shared_to) and then use:
insert into sharingevents (shared_note_id, shared_to, permission_level)
values (NEW.shared_note_id, NEW.shared_to, NEW.permission_level)
on duplicate key update shared_note_id = values(shared_note_id);
This will ignore any updates where the pairs already exist in the table. No if required.
count(shared_note_id, shared_to) is invalid syntax. You can only put multiple column names inside COUNT() when you use count(DISTINCT ...). In your case, you don't need to put column names at all, just use COUNT(*) to count the number of rows matching the condition.
See count(*) and count(column_name), what's the diff? for more information about when you should put column names in COUNT()
Unfortunately, fixing the syntax errors won't really solve your problem, because you can't use a trigger to make a change to the same table. From the FAQ:
Can triggers access tables?
A trigger can access both old and new data in its own table. A trigger can also affect other tables, but it is not permitted to modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger.
You'll need to recode the callers to use INSERT ... ON DUPLICATE KEY UPDATE, or something equivalent, to accomplish this.

How to create a Trigger within sql

I have been trying to create a Trigger, however my attempts have been unsuccessful. I seem to be getting an error (#1064), which I have no solution for. Can somebody explain or demonstrate any faults in the syntax.
Let me specify:
I have delivery_id as primary key in delivery table,
I also have delivery_id as a foreign key in entry_log table.
By comparing both id's(if true), will return a text referring to the output of the bit (either 0 or 1)
DELIMITER //
DROP TRIGGER IF EXISTS entry_trigger//
CREATE TRIGGER entry_trigger BEFORE INSERT ON entry_log
FOR EACH ROW
BEGIN
DECLARE #xentry VARCHAR(45)
DECLARE #inta bit
SET #inta = SELECT allowed
FROM delivery
WHERE delivery.delivery_id = entry_log.delivery_id;
CASE
when #inta = 0 then #xentry = 'Acces Denied'
when #inta = 1 then #xentry = 'Acces Allowed'
END CASE
INSERT INTO entry_log(entry_time,access_allowed) VALUES(now(),#xentry);
END
//
This is assuming that you use MySQL. In the body of the trigger you use
WHERE delivery.delivery_id = entry_log.delivery_id;
I think you want to compare to the entry_log entry that the trigger is running on, right? In that case you must use this syntax:
WHERE delivery.delivery_id = NEW.delivery_id;
see here for more examples.
UPDATE
I see that also you try to do an INSERT INTO entry_log within the TRIGGER. This will of course not work, because you would create an infinite recursive loop. Within the
body of the trigger you can do unrelated table access, but not into the table you are inserting. You can change the values to be inserted by the trigger by setting NEW.xyz = whatever
UPDATE 2
I doubt, that your CASE statement is correct. At least it must end with END CASE. You can use IF here, since you don't have many cases to address. If you must use CASE this post might help you: MYSQL Trigger set datetime value using case statement
UPDATE 3
I am not sure, but I think you need brackets around the variable setting statement. try this trigger definition:
DELIMITER //
DROP TRIGGER IF EXISTS entry_trigger//
CREATE TRIGGER entry_trigger BEFORE INSERT ON entry_log
FOR EACH ROW
BEGIN
SET #inta = (SELECT allowed
FROM delivery
WHERE delivery.delivery_id = NEW.delivery_id);
SET NEW.access_allowed = #inta;
SET NEW.entry_time = NOW();
END
//
Note, that this is written out of my head, so beware of syntax errors in my script.

Trigger to silently ignore/delete duplicate entries on INSERT

I have the following table:
T(ID primary key, A, B)
I want to have pair (A, B) unique but I don't want to have constraint unique(A,B) on them because it will give error on insert.
Instead I want MySQL to silently ignore such inserts.
I can't use "insert on duplicate keys ignore" because I can't control client's queries.
So, can I build such trigger? Or maybe there is some constraint that allows silent ignore?
Edit: I dug around and I think I want something like SQLite's "Raise Ignore" statement.
Before mysql 5.5. it wasn't possible to stop an insert inside a trigger. There where some ugly work arounds but nothing I would recommend. Since 5.5 you can use SIGNAL to do it.
delimiter //
drop trigger if exists aborting_trigger //
create trigger aborting_trigger before insert on t
for each row
begin
set #found := false;
select true into #found from t where a=new.a and b=new.b;
if #found then
signal sqlstate '45000' set message_text = 'duplicate insert';
end if;
end //
delimiter ;
Add a unique key (A,B) and use INSERT statement with an IGNORE keyword.
From the reference - If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead.
INSERT Syntax.

mysql and trigger usage question

I have a situation in which I don't want inserts to take place (the transaction should rollback) if a certain condition is met. I could write this logic in the application code, but say for some reason, it has to be written in MySQL itself (say clients written in different languages will be inserting into this MySQL InnoDB table) [that's a separate discussion].
Table definition:
CREATE TABLE table1(x int NOT NULL);
The trigger looks something like this:
CREATE TRIGGER t1 BEFORE INSERT ON table1
FOR EACH ROW
IF (condition) THEN
NEW.x = NULL;
END IF;
END;
I am guessing it could also be written as(untested):
CREATE TRIGGER t1 BEFORE INSERT ON table1
FOR EACH ROW
IF (condition) THEN
ROLLBACK;
END IF;
END;
But, this doesn't work:
CREATE TRIGGER t1 BEFORE INSERT ON table1 ROLLBACK;
You are guaranteed that:
Your DB will always be MySQL
Table type will always be InnoDB
That NOT NULL column will always stay the way it is
Question: Do you see anything objectionable in the 1st method?
From the trigger documentation:
The trigger cannot use statements that explicitly or implicitly begin or end a transaction such as START TRANSACTION, COMMIT, or ROLLBACK.
Your second option couldn't be created. However:
Failure of a trigger causes the statement to fail, so trigger failure also causes rollback.
So Eric's suggestion to use a query that is guaranteed to result in an error is the next option. However, MySQL doesn't have the ability to raise custom errors -- you'll have false positives to deal with. Encapsulating inside a stored procedure won't be any better, due to the lack of custom error handling...
If we knew more detail about what your condition is, it's possible it could be dealt with via a constraint.
Update
I've confirmed that though MySQL has CHECK constraint syntax, it's not enforced by any engine. If you lock down access to a table, you could handle limitation logic in a stored procedure. The following trigger won't work, because it is referencing the table being inserted to:
CREATE TRIGGER t1 BEFORE INSERT ON table1
FOR EACH ROW
DECLARE num INT;
SET num = (SELECT COUNT(t.col)
FROM your_table t
WHERE t.col = NEW.col);
IF (num > 100) THEN
SET NEW.col = 1/0;
END IF;
END;
..results in MySQL error 1235.
Have you tried raising an error to force a rollback? For example:
CREATE TRIGGER t1 BEFORE INSERT ON table1
FOR EACH ROW
IF (condition) THEN
SELECT 1/0 FROM table1 LIMIT 1
END IF;
END;