Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlite Foreign Keys

I try to enable foreign keys using HDBC-sqlite3 haskell library. This library uses a little helper c - function

int sqlite3_open2(const char *filename, finalizeonce **ppo)

which calls in turn sqlite3_open one. In the sqlite documentation I've found nice sqlite3_db_config function which is supposed to enable foreign keys. To test it I've added quickly 2 lines into sqlite3_open2 (the two last ones of the listing):

int sqlite3_open2(const char *filename, finalizeonce **ppo) {
  sqlite3 *ppDb;
  finalizeonce *newobj;
  int res, *resFK, resFK1;

  fprintf(stderr, "DB pointer: %d\n", ppDb);

  res = sqlite3_open(filename, &ppDb);

  resFK1 = sqlite3_db_config(ppDb, 1002, 1, resFK);                    
  fprintf(stderr, "\nForeign Keys: ON/OFF:%d  ERR:%d\n", resFK, resFK1);  

  ...

My surprise was the result: Foreign Keys: ON/OFF:0 ERR:1.

Could somebody give me a hint what am I doing wrong or what would be the proper way of enabling foreign keys?

like image 216
bartoszw Avatar asked Dec 06 '11 22:12

bartoszw


People also ask

Does SQLite support foreign keys?

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. To check whether your current version of SQLite supports foreign key constraints or not, you use the following command.

Can foreign key be null SQLite?

What is a Foreign Key with "Set Null on Delete" in SQLite? A foreign key with "set null on delete" means that if a record in the parent table is deleted, then the corresponding records in the child table will have the foreign key fields set to null.

Does SQLite have primary keys?

In SQLite, a primary key is a single field or combination of fields that uniquely defines a record. A table can have only one primary key. TIP: While the SQL-89 and SQL-92 standards do not allow a NULL value in a primary key, SQLite does allow a NULL under certain circumstances.


1 Answers

According to the docs:

Assuming the library is compiled with foreign key constraints enabled, it must still be enabled by the application at runtime, using the PRAGMA foreign_keys command. For example:

sqlite> PRAGMA foreign_keys = ON;

Foreign key constraints are disabled by default (for backwards compatibility), so must be enabled separately for each database connection separately.

So, after your sqlite3_open(), you probably want to add the following:

sqlite3_exec(ppDb, "PRAGMA foreign_keys = ON;", 0, 0, 0);
like image 121
Drew Hall Avatar answered Oct 03 '22 03:10

Drew Hall