I have a transaction table, which has tenant_id and transaction_id columns (they make up a unique composite index). For insert operation, transaction_id must be incremented by 1, but for given tenant_id. So, using sqlalchemy framework, I manually find max transaction_id for tenant_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
What I'd like to do instead is define the logic for my model class as server default:
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')
I guess I need to create a trigger (how?), but don't know how to link to my model class.