Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreign key constraints in Android using SQLite? on Delete cascade

I have two tables: tracks and waypoints, a track can have many waypoints, but a waypoint is assigned to only 1 track.

In the way points table I have a column called "trackidfk" which inserts the track_ID once a track is made, however I have not setup Foreign Key constraints on this column.

When I delete a track I want to delete the assigned waypoints, is this possible?. I read about using Triggers but I don't think they are supported in Android.

To create the waypoints table:

public void onCreate(SQLiteDatabase db) {     db.execSQL( "CREATE TABLE " + TABLE_NAME                  + " ("                  + _ID         + " INTEGER PRIMARY KEY AUTOINCREMENT, "                  + LONGITUDE   + " INTEGER,"                  + LATITUDE    + " INTEGER,"                  + TIME        + " INTEGER,"                 + TRACK_ID_FK + " INTEGER"                 + " );"               );      ... } 
like image 202
jcrowson Avatar asked Mar 30 '10 13:03

jcrowson


People also ask

How does foreign key on delete cascade work?

A foreign key with cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted.

How do I delete a foreign key in SQLite?

How to Drop a Foreign Key on a Table. You can not use the ALTER TABLE statement to drop a foreign key in SQLite. Instead you will need to rename the table, create a new table without the foreign key, and then copy the data into the new table.

Is on delete cascade a constraint?

ON DELETE CASCADE constraint is used in MySQL to delete the rows from the child table automatically, when the rows from the parent table are deleted. For example when a student registers in an online learning platform, then all the details of the student are recorded with their unique number/id.


1 Answers

Foreign key constraints with on delete cascade are supported, but you need to enable them.
I just added the following to my SQLOpenHelper, which seems to do the trick.

@Override public void onOpen(SQLiteDatabase db) {     super.onOpen(db);     if (!db.isReadOnly()) {         // Enable foreign key constraints         db.execSQL("PRAGMA foreign_keys=ON;");     } } 

I declared my referencing column as follows.

mailbox_id INTEGER REFERENCES mailboxes ON DELETE CASCADE 
like image 165
Phil Avatar answered Sep 17 '22 17:09

Phil