我有一个事务表,它有tenant_id和transaction_id列(它们组成一个唯一的复合索引)。对于插入操作,transaction_id必须递增1,但对于给定的tenant_id。因此,使用sqlalchemy框架,我手动查找tenant_id的max transaction_id:
res = db.session.query(func.max(my_tran.transaction_id).label('last_id')) \
.filter_by(tenant_id=tenant_id).one()
if res.last_id:
my_tran.transaction_id = res.last_id
else:
my_tran.transaction_id = 1
我想要做的是将我的模型类的逻辑定义为服务器默认值:
class MyTran(db.Model):
__tablename__ = 'my_tran'
id = db.Column(db.Integer, primary_key=True)
tenant_id = db.Column(db.Integer, db.ForeignKey('tenant.id'), nullable=False)
transaction_id = db.Column(db.Integer, nullable=False, \
server_default='compute last id for tenant_id + 1')
我想我需要创建一个触发器(如何?),但不知道如何链接到我的模型类。
答案 0 :(得分:3)
我找到了答案here。详情如下(使用sqlalchemy):
create_fn_my_tran_set_num = DDL(
'''
CREATE OR REPLACE FUNCTION fn_my_tran_set_num()
RETURNS TRIGGER AS $$
DECLARE last_transaction_id INTEGER;
BEGIN
last_transaction_id := MAX(transaction_id) FROM my_tran WHERE tenant_id = NEW.tenant_id;
IF last_transaction_id IS NULL THEN
NEW.transaction_id := 1;
ELSE
NEW.transaction_id := last_transaction_id + 1;
END IF;
RETURN NEW;
END$$
LANGUAGE plpgsql
''')
event.listen(MyTran.__table__, 'after_create', create_fn_my_tran_set_trx_id)
create_tg_my_tran_set_num = DDL(
'''
CREATE TRIGGER tg_my_tran_set_num
BEFORE INSERT ON my_tran
FOR EACH ROW
EXECUTE PROCEDURE fn_my_tran_set_num();
''')
event.listen(MyTran.__table__, 'after_create', create_tg_my_tran_set_trx_id)