Trying to apply TPT inheritance in EF Core 5, using an existing schema. How can I specify the foreign key column name of the child table, if the column name does not exactly match the parent table? In the documentation example, we would not have Pets.Id, but Pets.PetId:
CREATE TABLE [Animals] (
[Id] int NOT NULL IDENTITY,
[Species] nvarchar(max) NULL,
CONSTRAINT [PK_Animals] PRIMARY KEY ([Id])
);
CREATE TABLE [Pets] (
*[PetId] int NOT NULL*,
[Name] nvarchar(max) NULL,
CONSTRAINT [PK_Pets] PRIMARY KEY ([PetId]),
CONSTRAINT [FK_Pets_Animals_Id] FOREIGN KEY ([PetId]) REFERENCES [Animals] ([Id]) ON DELETE NO ACTION
);
Related
cannot add foreign key constraint to table
create table users
(
user_id int auto_increment primary key not null,
username varchar(50) unique null ,
email varchar(50) unique ,
passwords varchar(50) not null,
login_status boolean not null
);
create table category (
category_id int primary key not null,
category_name varchar(50) not null
);
create table answers (
id_answer int auto_increment primary key not null,
answer boolean not null
);
create table questions (
question_id int primary key not null,
category_name varchar(50) not null,
content varchar(50) not null ,
foreign key (category_name) references category (category_name)
);
You get this error because there's no index on category_name in the category table. Change that CREATE statement as follows:
create table category (
category_id int primary key not null,
category_name varchar(50) not null,
KEY category_name_index (category_name)
);
From the docs (8.0 version, but the statement is true for older versions):
MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.
Also, you're using a varchar(50) as your foreign key, which is not usually a great idea for a variety of reasons. You probably want to use a numeric value, such as category_id, instead.
See: SQLFiddle
I am having a many-to-many relationship as such:
CREATE TABLE IF NOT EXISTS store (
id BIGSERIAL PRIMARY KEY
);
CREATE TABLE IF NOT EXISTS collection (
id BIGSERIAL PRIMARY KEY,
store_id bigint NOT NULL,
FOREIGN KEY (store_id) REFERENCES store (id)
ON UPDATE CASCADE
);
CREATE TABLE IF NOT EXISTS item (
id BIGSERIAL PRIMARY KEY,
store_id bigint NOT NULL,
FOREIGN KEY (store_id) REFERENCES store (id)
ON UPDATE CASCADE
);
CREATE TABLE IF NOT EXISTS collection_item (
id BIGSERIAL PRIMARY KEY,
collection_id bigint NOT NULL,
item_id bigint,
UNIQUE (collection_id, item_id),
FOREIGN KEY (collection_id) REFERENCES collection (id)
ON DELETE CASCADE,
FOREIGN KEY (item_id) REFERENCES item (id)
ON DELETE SET NULL
);
INSERT INTO store (id) VALUES (1);
INSERT INTO item (id, store_id) VALUES (1, 1);
INSERT INTO collection (id, store_id) VALUES (1, 1);
INSERT INTO collection_item (id, collection_id, item_id) VALUES (DEFAULT, 1, 1);
My problem is that deleting a store
DELETE FROM store WHERE store.id = 1;
will give the following error:
ERROR: update or delete on table "store" violates foreign key constraint
"collection_store_id_fkey" on table "collection"
Detail: Key (id)=(1) is still referenced from table "collection".
I understand the problem but I don't know how I can resolve this issue.
If an item gets deleted, the relation in collection_item should not be removed but the item_id should be set to NULL. On the other hand, if a collection gets deleted, all related collection_item records should be removed as well.
How can DELETE CASCADE work in such a setup or do I have to model my tables differently if I need this kind of behavior?
You can just add ON DELETE CASCADE where you have ON UPDATE CASCADE
CREATE TABLE IF NOT EXISTS collection (
id BIGSERIAL PRIMARY KEY,
store_id bigint NOT NULL,
FOREIGN KEY (store_id) REFERENCES store (id)
ON UPDATE CASCADE
ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS item (
id BIGSERIAL PRIMARY KEY,
store_id bigint NOT NULL,
FOREIGN KEY (store_id) REFERENCES store (id)
ON UPDATE CASCADE
ON DELETE CASCADE
);
SQLFiddle
To resolve this issue you can add ON DELETE behavior to the store_id column of the collection table (and that of the item table). Basically you can just change the ON UPDATE to ON DELETE in both of these table definitions, since I doubt you'll be updating the id column for existing rows in the store table. You also mention the ON DELETE behavior for the item_id column of collection_item, if you want the column value to become NULL when an item is deleted, you can use ON DELETE SET NULL.
CREATE TABLE IF NOT EXISTS store (
id BIGSERIAL PRIMARY KEY
);
CREATE TABLE IF NOT EXISTS collection (
id BIGSERIAL PRIMARY KEY,
store_id bigint NOT NULL,
FOREIGN KEY (store_id) REFERENCES store (id)
ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS item (
id BIGSERIAL PRIMARY KEY,
store_id bigint NOT NULL,
FOREIGN KEY (store_id) REFERENCES store (id)
ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS collection_item (
id BIGSERIAL PRIMARY KEY,
collection_id bigint NOT NULL,
item_id bigint NOT NULL,
UNIQUE (collection_id, item_id),
FOREIGN KEY (collection_id) REFERENCES collection (id)
ON DELETE CASCADE,
FOREIGN KEY (item_id) REFERENCES item (id)
ON DELETE SET NULL
);
On this case, you have to delete table refrences before to delete stores id.
Or to do the modifications above.
DELETE FROM item where store_id= 1;
DELETE FROM collection where store_id = 1;
DELETE FROM store where id = 1;
I need to add a foreign keys for two tables each other. Can this be done ?
As an example:
CREATE SCHEMA IF NOT EXISTS schema1;
CREATE TABLE schema1.tableA
(
id serial NOT NULL,
tableB_id integer,
PRIMARY KEY (id),
FOREIGN KEY (tableB_id) REFERENCES schema1.tableB (id)
);
CREATE TABLE schema1.tableB
(
id serial NOT NULL,
tableA_id integer,
PRIMARY KEY (id),
FOREIGN KEY (tableA_id) REFERENCES schema1.tableA(id)
);
Above query causes an error !
ERROR: relation "schema1.tableb" does not exist SQL state: 42P01
Can this be done or is there any better solution?
I'am using PostgreSQL version 10.5 and pgAdmin 3.6
Add the foreign keys after creating both tables:
CREATE SCHEMA IF NOT EXISTS schema1;
CREATE TABLE schema1.tableA
(
id serial NOT NULL,
tableB_id integer,
PRIMARY KEY (id)
);
CREATE TABLE schema1.tableB
(
id serial NOT NULL,
tableA_id integer,
PRIMARY KEY (id)
);
ALTER TABLE schema1.tablea
add FOREIGN KEY (tableB_id) REFERENCES schema1.tableB (id);
ALTER TABLE schema1.tableb
add foreign key (tableA_id) REFERENCES schema1.tableA(id);
Is it possible to assign a foreign key to a json property in PostgreSQL? Here is an example what I would like to achieve, but it doesn't work:
CREATE TABLE Users (Id int NOT NULL PRIMARY KEY);
CREATE TABLE Data (
Id int NOT NULL PRIMARY KEY,
JsonData json NOT NULL, -- [{Id: 1, somedata: null},{Id: 2, somedata: null}, ...]
CONSTRAINT FK_Users_Data FOREIGN KEY (JsonData->Id) REFERENCES Users(Id) -- this constraint will fail
);
It is not possible, and may not ever be possible, to assign a foreign key to a json property. It'd be a major and quite complicated change to PostgreSQL's foreign key enforcement. I don't think it's impossible to do, but would face similar issues to those experienced by the foreign-keys-to-arrays patch.
With 9.4 it'll be possible to make a whole json object a foreign key as jsonb supports equality tests. In 9.3 you can't even do that.
Here's a little SPI function have_ids which I use for an integrity constraint on a one-to-many relationship with a jsonb column
CREATE TABLE foo (
id INTEGER NOT NULL
)
CREATE TABLE bar (
foo_ids pg_catalog.jsonb DEFAULT '[]'::jsonb NOT NULL,
CONSTRAINT bar_fooids_chk CHECK (have_ids ('foo', foo_ids))
)
With a couple of triggers on foo it's almost as good as a foreign key.
The foreign key parameter must be a column name:
http://www.postgresql.org/docs/current/static/sql-createtable.html
You will have to normalize
create table user_data (
id int not null primary key,
user_id int not null,
somedata text,
constraint fk_users_data foreign key (user_id) references Users(Id)
);
Yes it is possible but you will have to store another value. If you change your schema to:
CREATE TABLE Users (Id int NOT NULL PRIMARY KEY);
CREATE TABLE Data (
Id int NOT NULL PRIMARY KEY,
JsonData json NOT NULL,
UserId int generated always as ((JsonData->>'Id')::int) stored references Users(Id)
);
INSERT INTO Users VALUES (1);
Foreign key that doesn't exist:
INSERT INTO Data VALUES (1, '{"Id": 3}');
Returns the error:
ERROR: insert or update on table "data" violates foreign key constraint "data_userid_fkey" DETAIL: Key (userid)=(3) is not present in table "users".
Foreign key that does work:
INSERT INTO Data VALUES (1, '{"Id": 1}');
i´ve got a problem with foreign keys, it´s an strange problem.
First table:
CREATE TABLE adjunto
(
id serial NOT NULL,
codigo text,
descripcion text,
usuario integer,
file integer,
nombre text,
propiedades hstore,
CONSTRAINT adjunto_pkey PRIMARY KEY (id ),
CONSTRAINT adjunto_file_fkey FOREIGN KEY (file)
REFERENCES file (file_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE CASCADE
) WITH (
OIDS=FALSE
);
Second table:
CREATE TABLE adjunto_coleccion_privada
(
id serial NOT NULL,
adjunto integer,
coleccion integer,
CONSTRAINT adjunto_coleccion_privada_pkey PRIMARY KEY (id ),
CONSTRAINT adjunto_coleccion_privada_adjunto_fkey FOREIGN KEY (adjunto)
REFERENCES adjunto (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE CASCADE,
CONSTRAINT adjunto_coleccion_privada_coleccion_fkey FOREIGN KEY (coleccion)
REFERENCES coleccion (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE CASCADE
)
WITH (
OIDS=FALSE
);
Command:
INSERT INTO adjunto_coleccion_privada (adjunto, coleccion)
VALUES (600, 2) RETURNING id
Values 600 and 2 exist in both tables, adjunto and colecion.
Detailed error:
Mensaje: ERROR: insert or update on table "adjunto_coleccion_privada"
violates foreign key
constraint "adjunto_coleccion_privada_adjunto_fkey"
Detail: Key (adjunto)=(600) is not present in table "adjunto".
I tested your code (I dropped the adjunto_coleccion_privada_coleccion_fkey constraint since referred table does not exist in your pasted code).
I see no problem at all.
Are you really sure that there is a record with id = 600 in the adjunto table?