Search code examples
androidandroid-contentprovider

ContentProvider.delete with related tables


I'm writing a ContentProvider to work with a database. In this database, I have a "trip" table, and a "day" table. Each record in the trip table is associated with multiple records in the day table, i.e. each trip spans multiple days, but any one day record can belong to only one trip. If a trip is deleted, so must all the days associated with it.

My question is this, what is the standard or generally accepted method of dealing with this table relationship from a ContentProvider when deleting? When my delete method gets a URI to delete a particular trip, should it also delete the associated days, or should it just delete the trip and require the program using the ContentProvider to do the necessary logic of deleting the days as well?

Delete all at once, one call from the app with the trip id to delete:

@Override
public int delete( Uri uri, String selection, String[] selectionArgs )
{
    SQLiteDatabase db;
    int count;

    db = _dbHelper.getWritableDatabase();
    switch( uriMatcher.match( uri ) )
    {
        case TRIP_ID:
            count = db.delete( TRIP_TABLE, KEY_TRIP_ID + "=?", new String[]{ uri.getLastPathSegment() } );
            count += db.delete( DAY_TABLE, KEY_TRIP_ID + "=?", new String[]{ uri.getLastPathSegment() } );
            return count;
    }
}

Or delete only exactly what's requested, multiple calls from the app with the trip and as many days as needed:

@Override
public int delete( Uri uri, String selection, String[] selectionArgs )
{
    SQLiteDatabase db;
    int count;

    db = _dbHelper.getWritableDatabase();
    switch( uriMatcher.match( uri ) )
    {
        case TRIP_ID:
            count = db.delete( TRIP_TABLE, KEY_TRIP_ID + "=?", new String[]{ uri.getLastPathSegment() } );
            return count;
        case Day_ID:
            count = db.delete( DAY_TABLE, KEY_DAY_ID + "=?", new String[]{ uri.getLastPathSegment() } );
            return count;
    }
}

Solution

  • When my delete method gets a URI to delete a particular trip, should it also delete the associated days, or should it just delete the trip and require the program using the ContentProvider to do the necessary logic of deleting the days as well?

    I would vote the former, perhaps using a FOREIGN KEY relationship within SQLite rather than by manually doing it yourself. Since day records have no life outside of the trip, deleting a trip should delete those dependent records.