Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I enable foreign key constraint in onOpen or onConfigure

Tags:

android

sqlite

I came across different code snippet, regarding enable foreign key constraint in SQLiteHelper. I was wondering, should I enable foreign key constraint in onOpen or onConfigure, if I want to support API < 16 as well.

This discussion suggest onOpen is the right place, before API 16 : Foreign key constraints in Android using SQLite? on Delete cascade

However, since API 16, official document does mention onConfigure is the right place.

public void setForeignKeyConstraintsEnabled (boolean enable)
...
A good time to call this method is right after calling openOrCreateDatabase(File, SQLiteDatabase.CursorFactory) or in the onConfigure(SQLiteDatabase) callback.

May I know what is the single entry point, for both API 16 and <16 ?

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

or

// https://stackoverflow.com/questions/13641250/sqlite-delete-cascade-not-working
@SuppressLint("NewApi")
@Override
public void onConfigure(SQLiteDatabase database) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        database.setForeignKeyConstraintsEnabled(true);
    } else {
        database.execSQL("PRAGMA foreign_keys=ON");
    }
}
like image 520
Cheok Yan Cheng Avatar asked Apr 01 '14 16:04

Cheok Yan Cheng


1 Answers

onConfigure() would be ideal but it is only called on API 16 and up. If your minSdkVersion is 16 or above, use it.

onOpen() has the problem that it is only called after possible onCreate()/onUpgrade() etc. If you have SQL in onCreate()/onUpgrade() that requires foreign keys to be enforced, it's too late to set the foreign keys pragma in onOpen(). For minSdkVersion < 16, consider the following:

  • Always enable foreign keys in onOpen().

  • If your onCreate()/onUpgrade() requires foreign keys to be enforced, enable them there, too. There's no harm really enabling them possibly twice.

like image 140
laalto Avatar answered Oct 20 '22 18:10

laalto