I need to create a BEFORE INSERT trigger in SQLAlchemy:
DELIMITER |
CREATE TRIGGER set_rank BEFORE INSERT ON authors
FOR EACH ROW BEGIN
IF NEW.rank = 0 THEN
SET NEW.rank = (SELECT IFNULL(MAX(a.rank),0) + 1
FROM authors AS a
WHERE a.id = NEW.pub_id);
END IF;
END |
DELIMITER ;
Executing the code in mysql-workbench works just fine, but renders a “You have an error in your SQL syntax” exception when executed in my actual code:
from sqlalchemy.sql.expression import text
connection = db.session.connection()
text(..., connection).execute();
Running SELECT SLEEP(1), CREATE TABLE test (id INT) or even USE some_db works just fine.
This the the mysql error message I get:
(1064, “You have an error in your SQL syntax; … near ‘DELIMITER |\nCREATE TRIGGER set_rank BE…”)
I am quite sure that I use the DELIMITER incorrectly. What is the right syntax in this very context / How to fix my problem?
You really honestly don’t need the
DELIMITER. Thats only for the command line client. You as a programmer will be dividing up statements, so the delimiters are otherwise ignored.