Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating foreign key constraints in ORMLite under SQLite

As it is not possible to add foreign keys using an "ALTER TABLE" statement in SQLite, I am stuck on how to configure my database to enforce valid foreign keys, or perform cascaded deletes without explicit code overhead.

Anybody got an idea how to accomplish this with ORMLite under SQLite?

like image 870
Timo Avatar asked May 22 '11 19:05

Timo


People also ask

What is foreign key constraints in SQLite?

SQLite Foreign Key is used to specify that values in one table also appear in another table. It enforces referential integrity within SQLite database. The referenced table is known as parent table while the table with the foreign key is known as child table.

How do I add a foreign key to an existing table in SQLite?

How to Add a Foreign Key to an Existing Table. You can not use the ALTER TABLE statement to add a foreign key in SQLite. Instead you will need to rename the table, create a new table with the foreign key, and then copy the data into the new table.

Does SQLite enforce foreign key constraint?

SQLite has supported foreign key constraint since version 3.6. 19. The SQLite library must also be compiled with neither SQLITE_OMIT_FOREIGN_KEY nor SQLITE_OMIT_TRIGGER.


1 Answers

To elaborate on Gray's awesome answer (for anyone else who stumbles upon this question), you can use the columnDefinition annotation to define a foreign key constraint and cascading delete.

First, foreign key constraints were added to SQLite in 3.6.19, which means you can use them in Android 2.2 or higher (since 2.2 ships with SQLite 3.6.22). However, foreign key constraints are not enabled by default. To enable them, use the technique from this answer.

Here's an example using the columnDefinition annotation. This assumes your table/object you are referencing is called parent which has a primary key of id.

@DatabaseField(foreign = true,
      columnDefinition = "integer references parent(id) on delete cascade")
private Parent parent;

Note that the format for the String value does not include the column name (that's what the columnName annotation is for).

like image 186
wsanville Avatar answered Sep 27 '22 21:09

wsanville