Flask SQL Alchemy saves to DB despite a Null Primary Key and the addition of nullable=False
to the Primary Key field (even though it should not be necessary to add it).
I am assigning the id and not using the normal auto-increment or whatever comes with SQL Alchemy.
model.py
class User(db.Model):
id = db.Column(db.Integer, primary_key=True, unique=True, nullable=False)
# passing in the ID manually
@classmethod
def new(cls, sender_id):
try:
db.create_all()
d = cls()
d.id = sender_id
return d
except Exception as e:
print('Error in User new:', e)
def insert(self):
try:
db.session.add(self)
db.session.commit()
print('INSERT OKAY')
except Exception as e:
print('RollBack', e)
db.session.rollback()
test.py
#FLASK_ENV = 'dev_testing'
#----SETUP
# load env variables
def setup_testing_environment():
load_dotenv(find_dotenv(".env", raise_error_if_not_found=True)
#test setup testing DB
def create_test_app():
try:
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
if os.environ['FLASK_ENV'] == 'development' or os.environ['FLASK_ENV'] == 'dev_testing':
setup_testing_environment()
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///:memory:"
return app
except Exception as e:
print('Error in create_test_app', e)
#---- ACTUAL TEST
def test_should_fail(unittest.testcase):
#assign DB and create context for test to run
app = create_test_app()
with app.app_context():
db.init_app(app)
# make ID value None;
user = User.new(None)
# <User id=None>
user.insert()
# fails - user *is* being added to DB
assert user in not db.session
#end test
db.session.remove()
db.drop_all()
No rollback is occurring. No error are being shown by SQL Alchemy. The User is being saved to the DB but it is impossible to look up since there is no ID. The User table is completely empty.
Why is SQL Alchemy not catching this? How can I assign the ID so that it will work?