3

我有一个事务表,其中有 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')

我想我需要创建一个触发器(如何?),但不知道如何链接到我的模型类。

4

1 回答 1

3

我在这里找到了答案。详细信息如下(使用 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)
于 2013-09-14T05:13:51.563 回答