0

I have a database made in sqlite3 and have set foreign keys on the loan table to the student table and book table to stop duplicate loans:

using create table:

CREATE TABLE loan(
  SudentID INTEGER,
  ISBN INTEGER,
  out INTEGER,
  FOREIGN KEY(SudentID)
      REFERENCES student(SudentID)
      ON DELETE CASCADE
  FOREIGN KEY(ISBN)
      REFERENCES book(ISBN)
      ON DELETE CASCADE
)

CREATE TABLE student(
  SudentID INTEGER PRIMARY KEY,
  First TEXT,
  Last,
  Contact Text,
  Year INTEGER)

CREATE TABLE book(
  ISBN INTEGER PRIMARY KEY,
  Title TEXT,
  Price INTEGER,
  Qty INTEGER,
  Subject TEXT)

If i try to insert a duplicate records into the loan table the foreign key does not prevent it.

Pragma is switched on both in the code and in Firefox database settings.

The version is 2.6.0

My work around is to use Distinct to filter out duplicates but is there any way I can activate them as I use this database as a teaching tool. However the cascade delete does not work! Why?

JosefAssad
  • 4,018
  • 28
  • 37
Timothy Lawman
  • 2,194
  • 6
  • 24
  • 33

2 Answers2

1

You want a composite primary key on the loan table.

CREATE TABLE loan(
  StudentID INTEGER,
  ISBN INTEGER,
  out INTEGER,
  FOREIGN KEY(SudentID)
      REFERENCES student(SudentID)
      ON DELETE CASCADE
  FOREIGN KEY(ISBN)
      REFERENCES book(ISBN)
      ON DELETE CASCADE
  PRIMARY KEY(StudentID, ISBN)
)
JosefAssad
  • 4,018
  • 28
  • 37
0

Foreign key support is only available in Sqlite version 3.6.19 and upwards. So the problem may be one of the following:

  1. Sqlite version < 3.6.19. To whether your version supports foreign key or not try the following:

sqlite> PRAGMA foreign_keys;

If no data is return as opposed to 0 or 1, then your version does not support foreign keys.

  1. Your version of sqlite3 was compiled with either of these defined

SQLITE_OMIT_FOREIGN_KEY

SQLITE_OMIT_TRIGGER

One thing though, foreign keys are not enforced in sqlite3. Find all this information from here

Behzad
  • 3,502
  • 4
  • 36
  • 63
Charitoo
  • 1,814
  • 17
  • 21