many foreign keys in one table sqlite - sqlite

I want to use many foreign keys in one table on sqlite.
But it makes just one. how can I do it?
CREATE TABLE STORES(
SId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
SName TEXT NOT NULL
)
CREATE TABLE CITY(
CId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
CName TEXT NOT NULL
)
CREATE TABLE PRODUCTS(
PId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
PName TEXT NOT NULL,
Price REAL NOT NULL
)
CREATE TABLE STORE_CITY(
CId INTEGER REFERENCES CITY(CId) NOT NULL,
SId INTEGER REFERENCES STORES(SId) NOT NULL,
PId INTEGER REFERENCES PRODUCTS(PId)
)

Define the columns first, THEN make them foreign keys.
CREATE TABLE STORE_CITY(
CId INTEGER,
SId INTEGER,
PId INTEGER,
FOREIGN KEY (CId) REFERENCES CITY(CId) NOT NULL,
FOREIGN KEY (SId) REFERENCES STORES(SId) NOT NULL,
FOREIGN KEY (PId) REFERENCES PRODUCTS(PId)
)

Related

SQLite is not assigning primary keys

I have a simple SQLite database created using sqlite3.exe (code is below). When I run it through SchemaSpy, it looks like there are no primary keys in my first three tables. I don't understand what is wrong with the CREATE TABLE statements in the first three tables.
Code In:
.open test1.db
PRAGMA foreign_keys = ON;
CREATE TABLE META_E (E_ID INTEGER PRIMARY KEY NOT NULL, E_Name TEXT, Region TEXT, Date DATE);
CREATE TABLE META_D (D_ID INTEGER PRIMARY KEY NOT NULL, Citation TEXT, is_used BOOLEAN);
CREATE TABLE META_G (Completion TEXT, D_ID INTEGER NOT NULL, Location TEXT, PRIMARY KEY (D_ID), FOREIGN KEY (D_ID) REFERENCES META_D (D_ID));
CREATE TABLE P_ID_Main (Source_File TEXT, P_ID INTEGER NOT NULL, E_ID INTEGER NOT NULL, D_ID INTEGER NOT NULL, PRIMARY KEY (P_ID, E_ID, D_ID), FOREIGN KEY (E_ID) REFERENCES META_E (E_ID), FOREIGN KEY (D_ID) REFERENCES META_D (D_ID));
.dump
Dump:
sqlite> .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE META_E (E_ID INTEGER PRIMARY KEY NOT NULL, E_Name TEXT, Region TEXT, Date DATE);
CREATE TABLE META_D (D_ID INTEGER PRIMARY KEY NOT NULL, Citation TEXT, is_used BOOLEAN);
CREATE TABLE META_G (Completion TEXT, D_ID INTEGER NOT NULL, Location TEXT, PRIMARY KEY (D_ID), FOREIGN KEY (D_ID) REFERENCES META_D (D_ID));
CREATE TABLE P_ID_Main (Source_File TEXT, P_ID INTEGER NOT NULL, E_ID INTEGER NOT NULL, D_ID INTEGER NOT NULL, PRIMARY KEY (P_ID, E_ID, D_ID), FOREIGN KEY (E_ID) REFERENCES META_E (E_ID), FOREIGN KEY (D_ID) REFERENCES META_D (D_ID));
COMMIT;
sqlite>
SchemaSpy:
I don't understand what is wrong with the CREATE TABLE statements in
the first three tables.
I regard to the indexes there is nothing wrong with the CREATE TABLE statements. Rather it appears to be a shortfall of SchemaSpy.
SQLite isn't creating indexes as there is no need as the columns E_ID, D_ID (for both the META_D and META_G tables) are aliases of the rowid column, which could be considered as the MASTER index (see link below).
In short the column's are in fact indexed but there is no need for SQLite to create an index as the index is built in (an exception is a special type of table a WITHOUT ROWID table).
As such the indexes won't appear in sqlite_master, as there is no need and it appears that SchemaSpy at least the way you have it configured, doesn't fully cater for SQLite.
You may wish to refere to ROWIDs and the INTEGER PRIMARY KEY

SQL Error Regarding Foreign Key Restraint

I am currently getting the following error when trying to add to one of my tables:
Error adding record: FOREIGN KEY constraint failed: (INSERT INTO Stock(StockID,ItemName,MinAmountRequired,AmountInStock,Order? (Yes/No),DataLastUpdated,OrderNumber,SupplierRefrence,PurchaseID`) VALUES (1,",0,0,",",0,0,0);)
Currently, This is how I have my tables set up:
Stock
CREATE TABLE Stock (
StockID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
ItemName TEXT NOT NULL,
MinAmountRequired INTEGER NOT NULL,
AmountInStock INTEGER NOT NULL,
Order? (Yes/No) TEXT NOT NULL,
DataLastUpdated TEXT NOT NULL,
OrderNumber INTEGER NOT NULL UNIQUE,
SupplierReference INTEGER NOT NULL,
PurchaseID INTEGER NOT NULL UNIQUE,
FOREIGN KEY(PurchaseID) REFERENCES Purchase(PurchaseID),
FOREIGN KEY(OrderNumber) REFERENCES Orders(OrderNumber),
FOREIGN KEY(SupplierReference) REFERENCES Supplier(SupplierReference));
Orders
CREATE TABLE Orders (
OrderNumber INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
CustomerReferenceNumber INTEGER NOT NULL UNIQUE,
OrderDate TEXT NOT NULL,
ItemName TEXT NOT NULL UNIQUE);
Suppliers
CREATE TABLE Supplier (
SupplierReference INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
Name TEXT NOT NULL UNIQUE,
Address TEXT NOT NULL UNIQUE,
ContactNumber INTEGER NOT NULL UNIQUE);
Purchases
CREATE TABLE Purchase (
PurchaseID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
Date TEXT NOT NULL,
AmountSpent REAL NOT NULL);
You have defined these foreign keys in table Stock:
FOREIGN KEY(PurchaseID) REFERENCES Purchase(PurchaseID),
FOREIGN KEY(OrderNumber) REFERENCES Orders(OrderNumber),
FOREIGN KEY(SupplierReference) REFERENCES Supplier(SupplierReference)
meaning that the values in columns PurchaseID, OrderNumber, SupplierReference need to reference values in columns of the tables Purchase, Orders and Supplier.
But you want to store 0 to all of these columns which I'm sure that is not the value of any of the referenced columns, since these referenced columns are defined as
PRIMARY KEY AUTOINCREMENT
and so their values are > 0.
Pass valid values that do exist in these 3 tables and the statement will execute succesfully.

Recursive foreign key 'on delete cascade'

CREATE TABLE IF NOT EXISTS type (
tid INTEGER NOT NULL,
uuid VARCHAR NOT NULL,
name VARCHAR NOT NULL,
CONSTRAINT PK PRIMARY KEY (tid),
CONSTRAINT UNQ_0 UNIQUE (uuid),
CONSTRAINT UNQ_1 UNIQUE (name)
);
CREATE INDEX IDX_type_0 ON type (tid,uuid,name);
CREATE TABLE IF NOT EXISTS object (
oid VARCHAR NOT NULL,
timestamp VARCHAR NOT NULL,
tid INTEGER NOT NULL,
CONSTRAINT FK_tid FOREIGN KEY (tid) REFERENCES type(tid) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT UNQ_0 UNIQUE (oid)
);
CREATE INDEX IDX_object_0 ON object (oid,timestamp,tid);
CREATE TABLE IF NOT EXISTS object_user_owner (
uid INTEGER NOT NULL,
oid VARCHAR NOT NULL,
CONSTRAINT FK_uid FOREIGN KEY (uid) REFERENCES user(uid) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT FK_oid FOREIGN KEY (oid) REFERENCES object(oid) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT UNQ_0 UNIQUE (oid,uid)
);
CREATE INDEX IDX_object_user_owner_0 ON object_user_owner (uid,oid);
CREATE TABLE IF NOT EXISTS user (
uid INTEGER NOT NULL,
uuid VARCHAR NOT NULL,
name VARCHAR NOT NULL,
password VARCHAR NOT NULL,
salt VARCHAR NOT NULL,
timestamp VARCHAR NOT NULL,
lastaccess VARCHAR NOT NULL,
CONSTRAINT PK PRIMARY KEY (uid),
CONSTRAINT UNQ_0 UNIQUE (uuid),
CONSTRAINT UNQ_1 UNIQUE (name)
);
CREATE INDEX IDX_user_0 ON user (uid,uuid,name);
The above three sqlite3 tables contain foreign keys. The problem is the deletion of a key in the upper table type. When I try do delete I get 'FOREIGN KEY constraint failed' Error. Deleting a from the lowest table object_user_owner before deleting a type works. I think sqlite does not check any recursive cascade constraints. Does anyone have experienced this too or is anything wrong with my design?

SQLite3 syntax error trying to create foreign key

I am trying to create a bunch of tables in sqlite3 and I am getting an error that I can't fix. Something to do with my syntax for sqlite3 for foreign keys but can't figure it out.
CREATE TABLE students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name VARCHAR(64),
last_name VARCHAR(64)
);
CREATE TABLE classes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
class_name VARCHAR(64)
);
CREATE TABLE students_classes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
students_id INTEGER,
classes_id INTEGER,
FOREIGN KEY (students_id) REFERENCES students(id),
FOREIGN KEY (classes_id) REFERENCES classes(id)
);
CREATE TABLE teachers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
classes_id INTEGER,
first_name VARCHAR(64),
last_name VARCHAR(64),
FOREIGN KEY classes_id REFERENCES classes(id)
);
CREATE TABLE grades (
id INTEGER PRIMARY KEY AUTOINCREMENT,
students_id INTEGER,
grade_num INTEGER,
FOREIGN KEY students_id REFERENCES students(id)
);
Error: near "students_id": syntax error
SQLite Docs seem to indicate that column name(s) in FOREIGN Key constraint must be inside parenthesis:
I'm not sure how strictly it's actually enforced. My SQL Fiddle shows that using parenthesis should solve your problem.
Please note that SQL Fiddle for SQLite is emulated, so your result might still vary.

SQLite foreign key mismatch error

Why am I getting a SQLite "foreign key mismatch" error when executing script below?
DELETE
FROM rlsconfig
WHERE importer_config_id=2 and
program_mode_config_id=1
Here is main table definition:
CREATE TABLE [RLSConfig] (
"rlsconfig_id" integer PRIMARY KEY AUTOINCREMENT NOT NULL,
"importer_config_id" integer NOT NULL,
"program_mode_config_id" integer NOT NULL,
"l2_channel_config_id" integer NOT NULL,
"rls_fixed_width" integer NOT NULL
,
FOREIGN KEY ([importer_config_id])
REFERENCES [ImporterConfig]([importer_config_id]),
FOREIGN KEY ([program_mode_config_id])
REFERENCES [ImporterConfig]([importer_config_id]),
FOREIGN KEY ([importer_config_id])
REFERENCES [ImporterConfig]([program_mode_config_id]),
FOREIGN KEY ([program_mode_config_id])
REFERENCES [ImporterConfig]([program_mode_config_id])
)
and referenced table:
CREATE TABLE [ImporterConfig] (
"importer_config_id" integer NOT NULL,
"program_mode_config_id" integer NOT NULL,
"selected" integer NOT NULL DEFAULT 0,
"combined_config_id" integer NOT NULL,
"description" varchar(50) NOT NULL COLLATE NOCASE,
"date_created" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP),
PRIMARY KEY ([program_mode_config_id], [importer_config_id])
,
FOREIGN KEY ([program_mode_config_id])
REFERENCES [ProgramModeConfig]([program_mode_config_id])
)
When you use a foreign key over a table that has a composite primary key you must use a composite foreign key with all the fields that are in the primary key of the referenced table.
Example:
CREATE TABLE IF NOT EXISTS parents
(
key1 INTEGER NOT NULL,
key2 INTEGER NOT NULL,
not_key INTEGER DEFAULT 0,
PRIMARY KEY ( key1, key2 )
);
CREATE TABLE IF NOT EXISTS childs
(
child_key INTEGER NOT NULL,
parentKey1 INTEGER NOT NULL,
parentKey2 INTEGER NOT NULL,
some_data INTEGER,
PRIMARY KEY ( child_key ),
FOREIGN KEY ( parentKey1, parentKey2 ) REFERENCES parents( key1, key2 )
);
I am not sure about SQLite. But I found this link on google. http://www.sqlite.org/foreignkeys.html.
Some of the reasons can be
The parent table does not exist, or
The parent key columns named in the foreign key constraint do not exist, or
The parent key columns named in the foreign key constraint are not the primary key of the parent table and are not subject to a unique constraint using collating sequence specified in the CREATE TABLE, or
The child table references the primary key of the parent without specifying the primary key columns and the number of primary key columns in the parent do not match the number of child key columns.
Unfortunately, SQLite gives this error all the time without mentioning WHICH foreign key constraint failed. You are left to try to check them one by one, which often doesn't work, and then rebuild the table without the constraints and add them back one by one until you find the problem. SQLite is great in a lot of ways, but this isn't one of them.

Resources