I have a problem with my database configuration in that a ForeignKey
constraint is configured to be not null but parent deletion events take place leaving the ForeignKey pointing to a non-existant id. Here is a minimal example, which generates no IntegrityError
. Of course I need it to generate an error on the final commit..
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
app = Flask(__name__)
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////INSERT_PATH_HERE/data-test-scratch.sqlite'
db.init_app(app)
app.app_context().push()
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
class Attachment(db.Model):
__tablename__ = 'attachment'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship('User', uselist=False)
db.drop_all()
db.create_all()
user = User()
db.session.add(user)
db.session.flush()
attachment = Attachment(user_id=user.id)
db.session.add(attachment)
db.session.commit()
db.session.delete(user)
db.session.commit()
print(attachment.user, attachment.user_id) # (None, 1)
Note I am developing-testing in SQLlite but the production will be Postgres, I wonder if there are differences in default behaviour for this across the two configurations?