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.
>>> from sqlalchemy import *
>>>
>>> trigger_text = """
... 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
... """
>>>
>>> metadata = MetaData()
>>> authors = Table("authors", metadata,
... Column("id", Integer, primary_key=True),
... Column("rank", Integer),
... Column("pub_id", Integer))
>>>
>>> engine = create_engine("mysql://[email protected]/test", echo=True)
>>> authors.create(engine)
2012-05-04 17:11:41,093 INFO sqlalchemy.engine.base.Engine
CREATE TABLE authors (
id INTEGER NOT NULL AUTO_INCREMENT,
rank INTEGER,
pub_id INTEGER,
PRIMARY KEY (id)
)
2012-05-04 17:11:41,093 INFO sqlalchemy.engine.base.Engine ()
2012-05-04 17:10:51,376 INFO sqlalchemy.engine.base.Engine COMMIT
>>> engine.execute(trigger_text)
2012-05-04 17:11:41,159 INFO sqlalchemy.engine.base.Engine
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
2012-05-04 17:11:41,159 INFO sqlalchemy.engine.base.Engine ()
2012-05-04 17:11:41,312 INFO sqlalchemy.engine.base.Engine COMMIT
<sqlalchemy.engine.base.ResultProxy object at 0x2be1ed0>
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With