Skip to content

Instantly share code, notes, and snippets.

@Andrew-Dickinson
Created April 14, 2020 02:40
Show Gist options
  • Save Andrew-Dickinson/4f994352e12e406cca91af4aa31bc7c1 to your computer and use it in GitHub Desktop.
Save Andrew-Dickinson/4f994352e12e406cca91af4aa31bc7c1 to your computer and use it in GitHub Desktop.
import sqlalchemy
from sqlalchemy_continuum import make_versioned, version_class
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
make_versioned(
user_cls=None,
)
class Person(db.Model):
__versioned__ = {}
id = db.Column(db.Integer, primary_key=True)
# We need to manually define a join table for m2m relations
billowers = db.Table(
"billowers",
db.Column("bill_id", db.Integer, db.ForeignKey("bill.id"), primary_key=True),
db.Column("person_id", db.Integer, db.ForeignKey("person.id"), primary_key=True),
)
class Bill(db.Model):
__versioned__ = {}
id = db.Column(db.Integer, primary_key=True)
people = db.relationship(Person, secondary=billowers)
amount = db.Column(db.Float)
sqlalchemy.orm.configure_mappers()
PersonVersion = version_class(Person)
BillVersion = version_class(Bill)
db.drop_all()
db.create_all()
u1 = Person()
u2 = Person()
db.session.add(u1)
db.session.add(u2)
db.session.commit()
b1 = Bill(people=[u2], amount=10,)
b2 = Bill(people=[u2], amount=11,)
db.session.add(b1)
# Doing commit() here instead of after the next line causes the bug
db.session.commit()
db.session.add(b2)
db.session.commit()
# Change just the amount
b1.amount = 5
db.session.commit()
# The bug occurs in the last element of versions, where people is [],
# even though it's unchanged
versions = BillVersion.query.all()
for version in versions:
assert version.people != []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment