1

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?

Ilja Everilä
  • 50,538
  • 7
  • 126
  • 127
Attack68
  • 4,437
  • 1
  • 20
  • 40
  • SQLite does not enforce foreign key constraints by default. Enabling them is covered in https://stackoverflow.com/questions/2614984/sqlite-sqlalchemy-how-to-enforce-foreign-keys – Ilja Everilä Oct 31 '18 at 11:14
  • Does Postgres? Are there any options to force it to do so that it mirrors a postgres environment? Or are there any options that I can explicitly state in my SQLAlchemy model that will function across both database types? – Attack68 Oct 31 '18 at 11:19
  • @IljaEverilä thanks for the link. Implemented KiranJonnalagadda solution and IntegrityError is now generated for SQLite connections. – Attack68 Oct 31 '18 at 11:31
  • Postgres enforces foreign key constraints out of the box. – Ilja Everilä Oct 31 '18 at 11:58

0 Answers0