I’m having a bit of trouble with SQLite in Android. As my application supports Android 1.6, I am unable to use foreign keys, so have written triggers to enforce these constraints.
My two tables are vehicle and fuel_use. vehicle and fuel_use both have a registration_number column. My trigger ensures that I cannot update registration_number in vehicle when there are entries in fuel_use referencing registration_number in vehicle:
//on update vehicle
db.execSQL("CREATE TRIGGER fk_update_vehicle_trigger_fuel_references_vehicles_reg_no " +
"BEFORE UPDATE ON " + VEHICLE_TABLE_NAME +
" FOR EACH ROW BEGIN " +
"SELECT RAISE(ROLLBACK, 'update on table " + VEHICLE_TABLE_NAME + " violates foreign key constraint fk_update_vehicle_trigger_fuel_references_vehicles_reg_no') " +
"WHERE (SELECT " + REGISTRATION_NO_COLUMN + " FROM " + FUEL_USE_TABLE_NAME +
" WHERE " + REGISTRATION_NO_COLUMN + " = OLD." + REGISTRATION_NO_COLUMN + ") IS NOT NULL; " +
"END;");
This works fine in that it stops updates which would leave fuel_use rows referencing non-existent vehicle rows. However, I have just discovered a problem – when I try to update a differnt column in vehicle – initial_mileage – this trigger disallows it and forces a rollback. I understand why this is happening but don’t know how to rewrite the trigger so only updates on the registration_number column force a rollback. I have tried:
BEFORE UPDATE ON " + VEHICLE_TABLE_NAME + "." + REGISTRATION_NO_COLUMN
but this did not work. In fact an exception was thrown.
Any help would be gratefully received.
Try:
See if that works.