sockeqwe / sqlbrite-dao

DAO for SQLBrite
http://hannesdorfmann.com/android/sqlbrite-dao
Apache License 2.0
182 stars 22 forks source link

Foreign key support #18

Closed mtiidla closed 8 years ago

mtiidla commented 8 years ago

Please add foreign key support. For example in OpenHelper:

@Override
public void onOpen(SQLiteDatabase db) {
    super.onOpen(db);
    db.execSQL("PRAGMA foreign_keys=ON;");
}

(Or provide way to subclass OpenHelper and add constructor for DaoManager.)

This could be turned on via DaoManager the same way logging is used.

Thank you! (Sorry I'm not good with github, so I can't create pull request myself)

sockeqwe commented 8 years ago

Is it not enough to execute that in dao.onCreateTable() or is does foreign key have to be enabled everytime the database gets opened?

mtiidla commented 8 years ago

This is where I have it right now, but it feels a bit bad to execute this command 20+ times for each table. (Yes, everyone could implement their own flag, that will protect from this.)

However, to do it correctly, there should be API >=16 version of this call as explained in this discussion

And for this overriding is the only way.

@Override
public void onConfigure(SQLiteDatabase db){
    db.setForeignKeyConstraintsEnabled(true);
}

Instead of the onOpen call, I think calling from onCreate would also be enough, but you cannot do this with app in production where you cannot reset the database.

sockeqwe commented 8 years ago

I see, I will consider that ...

T0bbes commented 8 years ago

@mtiidla , where do you have the code right now? My code has no effect.. it is a new app. I have no users with existing databases.

@Override
public void createTable(SQLiteDatabase database) {
    database.execSQL("PRAGMA foreign_keys=ON;");
    CREATE_TABLE(xyz).execute(database);
}
mtiidla commented 8 years ago

@T0bbes It's funny that you mention this as I never got it working either.

See I never built the App on a device when I tested this lib, so I assumed that the issue was with the SQLite bundled into Robolectric (now I know that this was not the case).

If the snippet by @T0bbes does not work, then if I'm correct there is no way you can turn foreign keys on with this lib.

sockeqwe commented 8 years ago

@T0bbes @mtiidla I have added support for foreign keys #38 and have deployed a 0.6.1-SNAPSHOT

Now you can enable / disable foreign key support in DaoManager.Builder.foreignKeyConstraints(true).

Please have a look at the source code #38 and let me know if 0.6.1-SNAPSHOT works for you

sockeqwe commented 8 years ago

Released in 0.6.1