Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sqlite: foreign key constraint checking #17

Merged
merged 1 commit into from
Nov 18, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions invenio_db/shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
"""Shared database object for Invenio."""

from flask_sqlalchemy import SQLAlchemy as FlaskSQLAlchemy
from sqlalchemy import event
from sqlalchemy.engine import Engine


class SQLAlchemy(FlaskSQLAlchemy):
Expand All @@ -43,6 +45,20 @@ def apply_driver_hacks(self, app, info, options):
# also stops it from emitting COMMIT before any DDL.
connect_args['isolation_level'] = None

event.listen(Engine, "connect", do_sqlite_connect)


def do_sqlite_connect(dbapi_connection, connection_record):
"""Ensure SQLite checks foreign key constraints.

For further details see "Foreign key support" sections on
http://docs.sqlalchemy.org/en/latest/dialects/sqlite.html
"""
# Enable foreign key constraint checking
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close()


db = SQLAlchemy()
"""Shared database instance using Flask-SQLAlchemy extension.
Expand Down
16 changes: 16 additions & 0 deletions tests/test_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,14 @@
import importlib
import os

import pytest
import sqlalchemy as sa
from click.testing import CliRunner
from flask import Flask
from flask_cli import FlaskCLI, ScriptInfo
from mock import patch
from pkg_resources import EntryPoint
from sqlalchemy.exc import IntegrityError
from sqlalchemy_utils.functions import create_database, drop_database

from invenio_db import InvenioDB, db
Expand Down Expand Up @@ -85,6 +87,20 @@ class Demo2(db.Model):
create_database(db.engine.url)
db.create_all()
assert len(db.metadata.tables) == 2

# Test foreign key constraint checking
d1 = Demo()
db.session.add(d1)
d2 = Demo2(fk=d1.pk)
db.session.add(d2)
db.session.commit()

# Fails fk check
d3 = Demo2(fk=10)
db.session.add(d3)
pytest.raises(IntegrityError, db.session.commit)
db.session.rollback()

db.drop_all()
drop_database(db.engine.url)

Expand Down