Django migration sql for conditional triggers - mysql

I want to create a trigger that only inserts into table when the condition is met.
I've tried using various combinations of IF/BEGIN/END and WHERE, but Django returns me an SQL syntax error each time.
Here, type_user_id refers to the person who triggers the like, and user_id refers to the person who receives the notification. It should only trigger when they are not the same person.
operations = [
migrations.RunSQL(
"DROP TRIGGER like_notification",
"""
CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article
FOR EACH ROW
IF (select user_id from channel WHERE channel_id IN
(SELECT channel_id FROM article WHERE article_id = NEW.article_id)) <> NEW.user_id
BEGIN
INSERT INTO notification (type, type_id, article_id, is_read, type_user_id, user_id)
VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id,
(SELECT user_id from channel WHERE channel_id IN
(SELECT channel_id FROM article WHERE article_id = NEW.article_id)
)
)
END;
"""
)
]
>>>django.db.utils.ProgrammingError: (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 'BEGIN\n INSERT INTO notification (type, type_id, article_id, is_re' at line 5")
and
CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article
FOR EACH ROW
BEGIN
DECLARE #user_same Boolean;
SELECT 1 into #user_same
FROM channel
WHERE channel_id IN (select channel_id FROM article where article_id = NEW.article_id)
AND user_id = NEW.user_id;
IF #user_same <> 1
THEN
INSERT INTO notification (type, type_id, article_id, is_read, type_user_id, user_id,)
VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id, (
SELECT user_id from channel WHERE channel_id IN (
SELECT channel_id FROM article WHERE article_id = NEW.article_id)
)
END IF;
END;
>>>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 '#user_same Boolean;\n SELECT 1 into #user_same\n FRO' at line 4"
and
CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article
FOR EACH ROW
INSERT INTO notification (type, type_id, article_id, is_read, type_user_iduser_id)
VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id,
(
SELECT user_id from channel WHERE channel_id IN
(SELECT channel_id FROM article WHERE article_id = NEW.article_id)
)
WHERE NOT user_id = NEW.user_id;
>>>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 'WHERE NOT user
I don't really understand why none of them work. Any help would be much appreciated!

#variables are not DECLARED.
Either:
DECLARE user_same BOOLEAN;
SELECT 1 INTO user_same WHERE ...
or
SELECT #user_same := 1 WHERE ...
Better yet, this avoids the need for the variable.
IF (EXISTS SELECT * FROM ...)
Also, don't use the construct IN ( SELECT ... ); it is usually better to use WHERE EXISTS ( SELECT * FROM ... ) or JOIN ... ON ....
(There may be more problems after fixing those.)

Another easy way to do this.
You should add any symbols between ; delimiters for the appropriate converting MySQL syntax to the raw SQL.
CREATE TRIGGER trigger_name BEFORE INSERT ON table
FOR EACH ROW
BEGIN
IF NEW.number <> 'anynumber' AND NEW.number <> 'anynumber'
THEN
SET NEW.number = 'anynumber'; --
END IF; --
END
This example works due to the dash symbols.

Related

ERROR 1064: Cannot execute while loop in mysql using variables

I'd like to run the below query to insert into a table in a loop:
SET #maxid = ( select max( length( id ) ) from article ) ;
SET #x=1;
WHILE #x<= #maxid DO
INSERT INTO `article_responder`
(article_id, username, reply_id)
SELECT #x, p.username, p.id
FROM article AS a, post AS p
WHERE a.id=#x AND p.article_id=#x ;
SET #x = #x + 1;
END WHILE;
But I get this error:
ERROR 1064 (42000): 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 'END WHILE' at line
Notice that article_id can not be auto incremented, because the bussiness loginc requires that after inserting the data, the next row in article_responder can be about any article. So I had no idea how to fill article_responder with usual joins.
How can I fix it?
I would suggest just making article_id a primary key auto increment column, and then doing the following INSERT INTO ... SELECT:
INSERT INTO article_responder (username, reply_id)
SELECT p.username, p.id
FROM post p
INNER JOIN article a
ON a.id = p.article_id;
Note that the logic WHERE a.id=#x AND p.article_id=#x is equivalent to saying that a.id = p.article_id.

How do I use IF THEN ELSE to SELECT and INSERT or UPDATE Queries?

I've been trying to use the following query
IF EXISTS (SELECT id FROM users WHERE id = 1)
THEN
(INSERT INTO users (id, username) VALUES (2, user2))
ELSE
(UPDATE users SET username = 'userUpdated')
But I keep getting
/* SQL Error (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 'INSERT INTO users (id) VALUES (2)) ELSE (UPDATE users SET id = 11)' at line 1 */
Also tried using the following query
IF EXISTS (SELECT id FROM users WHERE id = 1)
THEN
(SELECT username FROM users WHERE id = 1)
ELSE
(INSERT INTO users (id, username) VALUES (1, 'user'))
But this time I got
/* SQL Error (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 'ELSE
(INSERT INTO users (id, username) VALUES (1, 'user'))' at line 4 */
Am I doing or understood something wrong?
The if statement can only be used in programming blocks, such as stored procedures, functions, and triggers.
In any case, MySQL offers simpler syntax for this functionality: insert . . . on duplicate key update.
To use it, id must have a unique index, unique constraint, or be defined as the primary key. Let me assume that a column so-named is already so-defined.
Then:
INSERT INTO users (id, username)
VALUES (2, user2)
ON DUPLICATE KEY UPDATE username = 'userUpdated';
Are you missing the END IF (and semi colons)?
IF EXISTS (SELECT id FROM users WHERE id = 1)
THEN
(SELECT username FROM users WHERE id = 1);
ELSE
(INSERT INTO users (id, username) VALUES (1, 'user'));
END IF;
Try This.
IF EXISTS (SELECT id FROM users WHERE id = 1)
begin
INSERT INTO users (id, username) VALUES (2, 'user2')
end
ELSE
UPDATE users SET username = 'userUpdated'
In MariaDB 10.1 and newer, you can use compound statements outside of stored procedures. This blog post gives a good description of what you can do with it.
Here's an example the blog:
BEGIN NOT ATOMIC
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
stmt1;
....
stmtN;
COMMIT;
END

MySQL: Insert with conditional

I must perform the following situation down, but when you run got the error:
SQL Error (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 'INTO produto_seriais(serial_id) VALUES( SELECT id
FROM seriais WHERE serial =' at line 5
SELECT CASE WHEN (
SELECT COUNT(id) FROM seriais WHERE serial = '2020'
) > 1
THEN
(INSERT INTO produto_seriais(serial_id) VALUES(
SELECT id FROM seriais WHERE serial = '2020'
))
ELSE (
INSERT INTO seriais (serial) VALUE('2020');
SET #last_id_in_table1 = LAST_INSERT_ID();
INSERT INTO produto_seriais (serial_id) VALUES (#last_id_in_table1);
)
END;
The case is as follows:
I'll get in "serial" table by serial "X". If it already exists, unless your ID in the "produto_seriais" table. If there is (serial), I will save the same, recover your ID and save to "produto_seriais". Any suggestions for how to do this?
Important Note: This routine will run will be thousands of times each execution (10,000 or more, depending on the quantity of serial).
P.s.: Sorry for my bad english.
Try a stored procedure
DELIMITER //
CREATE PROCEDURE sp_produto_seriais(IN `p_serial_id`)
IF EXISTS (SELECT * FROM seriais WHERE serial = p_serial_id )
BEGIN
INSERT INTO produto_seriais (serial_id)
SELECT id
FROM seriais
WHERE serial = p_serial_id
END
ELSE
BEGIN
INSERT INTO seriais (serial) VALUE(p_serial_id);
INSERT INTO produto_seriais (serial_id) VALUES (LAST_INSERT_ID());
END //
DELIMITER ;
usage:
CALL sp_produto_seriais('2020')
You could use the if exists..else statement.
If exists (select * from ....)
Begin
Insert into ... Select id from table
End
Else
Begin
Insert..
End
Please fill .... with your statements. You could use the link here to convert it for MySQL.
Convert if exists for MySQL

select if and update issue

Am using this sql to do an update on duplicate key
IF (SELECT COUNT(*) FROM `mlm_settings` WHERE `key` = 'notify_type' AND `user_id`=7 >0 )
UPDATE mlm_settings SET value='2' WHERE user_id = 7
ELSE
BEGIN
INSERT INTO `mlm_settings` (`key`, `value`,`user_id`) VALUES ('notify_type', '2',7)
END
by i get an sql error in mysql saying
#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 'IF (SELECT COUNT(*) FROM
`mlm_settings` WHERE `key` = 'notify_type' AND `user_id' at line 1
i can't figure what is the cause of the error, as the names of the tables are valid and the values are of the same data type
what could be the error?
You can only use IF statements in stored procedures, not normal queries.
If there's a unique index on (key, user_id) in the table, you can use:
INSERT INTO mlm_settings (`key`, value, user_id) VALUES ('notify_type', '2', 7)
ON DUPLICATE KEY UPDATE value = '2';
IF control block cannot be used OUTSIDE of functions. Try this:-
SELECT IF( EXISTS(
SELECT COUNT(*) FROM `mlm_settings` WHERE `key` = 'notify_type' AND `user_id`=7 >0), 1, 0)

Mysql sql error #1064

check the manual that corresponds to your MySQL server version for the right syntax to use near: 'SELECT count(*) FROM capacity
WHERE
server=NEW.server
AND
feed' at line 2
my code:
DROP TRIGGER IF EXISTS newsmonitoringrawdata.TNTInsertionTrigger;
CREATE TRIGGER TgtInsertionTrigger BEFORE INSERT ON tnews
FOR EACH ROW BEGIN
SET #isRecordCreated =
SELECT count(*) FROM capacity
WHERE
server=NEW.server
AND
feed=NEW.Feed
AND
date_Format(streamdt,'%Y-%m-%d %H:%i')=date_Format(NEW.StreamDT,'%Y-%m-%d %H:%i');
IF #isRecordCreated>0 THEN
UPDATE capacity
SET MsgNumber=MsgNumber+1,
size=size+NEW.MSize
WHERE
server=NEW.server
AND
feed=NEW.feed
and
date_Format(streamdt,'%Y-%m-%d %H:%i')=date_Format(NEW.StreamDT,'%Y-%m-%d %H:%i');
ELSE
INSERT INTO capacity(server, feed, streamdt, msgNumber, size)
VALUES
(
NEW.server,
NEW.feed,
date_Format(NEW.StreamDT,'%Y-%m-%d %H:%i:00'),
1,
NEW.size
);
END IF;
END
SET #isRecordCreated = (
SELECT count(*) FROM capacity
WHERE
server=NEW.server
AND
feed=NEW.Feed
AND
date_Format(streamdt,'%Y-%m-%d %H:%i')=date_Format(NEW.StreamDT,'%Y-%m-%d %H:%i')
);
You have to add parantheses () around the query.