Search code examples
androidsqlitekotlinandroid-sqlite

Android sqlite foreign key error check not working?


I have 2 tables Users and Computers

Users = (id, name, age)

id -> primary key

Computers = (comp_id, comp_model_name, user_id)

comp_id -> primary key

user_id -> foreign key to users table user_id field. As I want one computer to be used by a single person.

if (db != null) {
        if (!db.isReadOnly) {
            db.execSQL("PRAGMA foreign_keys=ON;");
        }
    }

db?.execSQL(
    "create table Users " +
            "(id integer primary key, name text, age integer)"
)


db?.execSQL(
    "create table Computers " +
            "(id integer primary key, model_name text, user_id integer," +
            " FOREIGN KEY (user_id) references Users (id))")

What problem I am seeing is that, if for 3rd field of computer object I specify a value which is not in Users table id field it doesn't throw an error. It is accepting values.


Solution

  • To enable foreign key constraint support you must override onConfigure() in your SQLiteOpenHelper class and call setForeignKeyConstraintsEnabled(true):

    override fun onConfigure(db: SQLiteDatabase) {
        db.setForeignKeyConstraintsEnabled(true)
    }