During the development of an android application I have noticed that the ON UPDATE CASCADE
is not working when a NULL
field is updated. However, when the field is a NON NULL
value the ON UPDATE CASCADE
works just fine.
I searched online but couldn't find a specific answer.
My class extends the SQLiteOpenHelper
and I have the override onOpen
method where I activate the foreign key constraint. I don't believe this is where the issue lies as it's just not working when updating a NULL
field.
@Override
public void onOpen(@Nonnull final SQLiteDatabase db) {
super.onOpen(db);
if (!db.isReadOnly()) {
// Enable foreign key constraints
db.execSQL("PRAGMA foreign_keys=ON;");
}
}
The schema I am using is:
CREATE TABLE IF NOT EXIST users (
role_id INTEGER,
user_id NUMERIC,
username TEXT,
PRIMARY KEY(user_id)
)
CREATE TABLE IF NOT EXIST devices (
user_id NUMERIC,
device_id NUMERIC,
device_name TEXT,
PRIMARY KEY(device_id),
FOREIGN KEY(user_id) REFERENCES users(user_id)
ON UPDATE CASCADE
)
INSERT INTO users (role_id, user_id, username) VALUES (1, NULL, 'test')
INSERT INTO devices (user_id, devices, device_name) VALUES (NULL, NULL, 'test')
When we now update this user row and replace the NULL
with 1 the update is not being cascaded to the device row.