# LogicTest: local local-opt local-parallel-stmts fakedist fakedist-opt fakedist-metadata

# Disable automatic stats to avoid flakiness.
statement ok
SET CLUSTER SETTING sql.stats.automatic_collection.enabled = false

statement ok
CREATE TABLE customers (id INT PRIMARY KEY, email STRING UNIQUE)

statement ok
INSERT INTO customers VALUES (1, 'a@co.tld'), (2, 'b@co.tld')

statement ok
CREATE TABLE products (sku STRING PRIMARY KEY, upc STRING UNIQUE, vendor STRING)

statement ok
INSERT INTO products VALUES ('VP-W9QH-W44L', '867072000006', 'Dave'), ('780', '885155001450', 'iRobot')

statement error pgcode 42P01 relation "productz" does not exist
CREATE TABLE missing (product STRING REFERENCES productz)

statement error pgcode 42P01 relation "customerz" does not exist
CREATE TABLE missing_with_col (customer INT REFERENCES customerz (id))

statement error pgcode 42703 column "idz" does not exist
CREATE TABLE missing_col (customer INT REFERENCES customers (idz))

statement ok
CREATE TABLE unindexed (customer INT REFERENCES customers)

query TTBITTBB colnames
SHOW INDEXES FROM unindexed
----
table_name  index_name                                      non_unique  seq_in_index  column_name  direction  storing  implicit
unindexed   primary                                         false       1             rowid        ASC        false    false
unindexed   unindexed_auto_index_fk_customer_ref_customers  true        1             customer     ASC        false    false
unindexed   unindexed_auto_index_fk_customer_ref_customers  true        2             rowid        ASC        false    true

statement error there is no unique constraint matching given keys for referenced table products
CREATE TABLE non_unique (product STRING REFERENCES products (vendor))

statement error type of "customer" \(INT\) does not match foreign key "customers"."email" \(STRING\)
CREATE TABLE mismatch (customer INT REFERENCES customers (email))

statement error columns cannot be used by multiple foreign key constraints
CREATE TABLE orders (
  id INT PRIMARY KEY,
  product STRING REFERENCES products,
  customer INT CONSTRAINT valid_customer REFERENCES customers (id),
  CONSTRAINT fk FOREIGN KEY (product) REFERENCES products,
  INDEX (product),
  INDEX (customer)
)

statement ok
CREATE TABLE orders (
  id INT,
  shipment INT,
  product STRING DEFAULT 'sprockets' REFERENCES products,
  customer INT CONSTRAINT valid_customer REFERENCES customers (id),
  PRIMARY KEY (id, shipment),
  INDEX (product),
  INDEX (customer)
)

statement ok
ALTER TABLE orders DROP CONSTRAINT fk_product_ref_products

statement ok
ALTER TABLE orders ADD FOREIGN KEY (product) REFERENCES products ON DELETE NO ACTION

statement error pq: columns cannot be used by multiple foreign key constraints
ALTER TABLE orders ADD FOREIGN KEY (product) REFERENCES products ON UPDATE NO ACTION

statement ok
ALTER TABLE orders DROP CONSTRAINT fk_product_ref_products

statement ok
ALTER TABLE orders ADD FOREIGN KEY (product) REFERENCES products ON UPDATE NO ACTION

statement ok
ALTER TABLE orders DROP CONSTRAINT fk_product_ref_products

statement ok
ALTER TABLE orders ADD FOREIGN KEY (product) REFERENCES products ON DELETE CASCADE

statement ok
ALTER TABLE orders DROP CONSTRAINT fk_product_ref_products

statement ok
ALTER TABLE orders ADD FOREIGN KEY (product) REFERENCES products ON UPDATE CASCADE

statement ok
ALTER TABLE orders DROP CONSTRAINT fk_product_ref_products

statement ok
ALTER TABLE orders ADD FOREIGN KEY (product) REFERENCES products ON DELETE SET NULL

statement ok
ALTER TABLE orders DROP CONSTRAINT fk_product_ref_products

statement ok
ALTER TABLE orders ADD FOREIGN KEY (product) REFERENCES products ON UPDATE SET NULL

statement ok
ALTER TABLE orders DROP CONSTRAINT fk_product_ref_products

statement ok
ALTER TABLE orders ADD FOREIGN KEY (product) REFERENCES products ON DELETE SET DEFAULT

statement ok
ALTER TABLE orders DROP CONSTRAINT fk_product_ref_products

statement ok
ALTER TABLE orders ADD FOREIGN KEY (product) REFERENCES products ON UPDATE SET DEFAULT

statement ok
ALTER TABLE orders DROP CONSTRAINT fk_product_ref_products

statement ok
ALTER TABLE orders ADD FOREIGN KEY (product) REFERENCES products ON DELETE RESTRICT ON UPDATE NO ACTION

statement ok
ALTER TABLE orders DROP CONSTRAINT fk_product_ref_products

statement ok
ALTER TABLE orders ADD FOREIGN KEY (product) REFERENCES products ON DELETE RESTRICT ON UPDATE RESTRICT

statement ok
ALTER TABLE orders VALIDATE CONSTRAINT fk_product_ref_products

statement ok
CREATE DATABASE "user content"

# "reviews" makes "products" have multiple inbound references, as well as making
# "orders" have both directions, and makes sure that we're handling escaping and
# cross-database references.
statement ok
CREATE TABLE "user content"."customer reviews" (
  id INT PRIMARY KEY,
  product STRING NOT NULL REFERENCES products,
  customer INT,
  "order" INT,
  shipment int,
  body STRING,
  CONSTRAINT customerfk FOREIGN KEY (customer) REFERENCES customers,
  CONSTRAINT orderfk FOREIGN KEY ("order", shipment) REFERENCES orders (id, shipment),
  INDEX (product),
  INDEX (customer),
  INDEX ("order")
)

statement ok
INSERT INTO orders VALUES (1, 1, '780', 2)

statement error foreign key violation: value \['fake'\] not found in products@primary
SET tracing = on,kv,results; INSERT INTO orders VALUES (2, 2, 'fake', 2)

statement ok
SET tracing = off

query T rowsort
SELECT message FROM [SHOW KV TRACE FOR SESSION]
WHERE message LIKE 'FKScan%'
----
FKScan /Table/54/1/"fake"{-/#}
FKScan /Table/53/1/2{-/#}

statement error pgcode 23503 foreign key violation: values \['780'\] in columns \[sku\] referenced in table "orders"
DELETE FROM products

statement ok
INSERT INTO "user content"."customer reviews" VALUES (1, '780', 2, 1, 1, NULL)

statement error pgcode 23503 foreign key violation: value \['790'\] not found in products@primary \[sku\]
INSERT INTO "user content"."customer reviews" (id, product, body) VALUES (2, '790', 'would not buy again')

statement ok
INSERT INTO "user content"."customer reviews" (id, product, body) VALUES (2, '780', 'would not buy again')

statement ok
CREATE TABLE "user content".review_stats (
  id INT PRIMARY KEY,
  upvotes INT,
  CONSTRAINT reviewfk FOREIGN KEY (id) REFERENCES "user content"."customer reviews"
)

query TTTTB
SHOW CONSTRAINTS FROM "user content".review_stats
----
review_stats  primary   PRIMARY KEY  PRIMARY KEY (id ASC)                                 true
review_stats  reviewfk  FOREIGN KEY  FOREIGN KEY (id) REFERENCES "customer reviews" (id)  true

statement error pgcode 23503 foreign key violation: value \[5\] not found in customer reviews@primary \[id\]
INSERT INTO "user content".review_stats (id, upvotes) VALUES (5, 1)

statement ok
INSERT INTO "user content".review_stats (id, upvotes) VALUES (2, 1)

statement error pgcode 23503 foreign key violation: values \[2\] in columns \[id\] referenced in table "review_stats"
DELETE FROM "user content"."customer reviews" WHERE id = 2

statement ok
ALTER TABLE "user content".review_stats DROP CONSTRAINT reviewfk

query TTTTB
SHOW CONSTRAINTS FROM "user content".review_stats
----
review_stats  primary  PRIMARY KEY  PRIMARY KEY (id ASC)  true

statement ok
DELETE FROM "user content"."customer reviews"

statement error pgcode 23503 foreign key violation: value \['790'\] not found in products@primary \[sku\]
INSERT INTO orders VALUES (2, 1, '790', 2)

statement error pgcode 23503 foreign key violation: value \[43\] not found in customers@primary \[id\]
INSERT INTO orders VALUES (2, 1, '780', 43)

statement ok
INSERT INTO orders VALUES (2, 1, '780', 1)

# Try to point to missing FK.
statement error pgcode 23503 foreign key violation: value \['790'\] not found in products@primary \[sku\]
UPDATE orders SET product = '790' WHERE id = 2

# Try to point to missing fk *while changing PK*.
statement error pgcode 23503 foreign key violation: value \['790'\] not found in products@primary \[sku\]
UPDATE orders SET id = 3, product = '790' WHERE id = 2

# Change PK while leaving everything else is fine though.
statement ok
UPDATE orders SET id = 3 WHERE id = 2

# Change PK and point to different product.
statement ok
UPDATE orders SET id = 2, product = 'VP-W9QH-W44L' WHERE id = 3

statement ok
UPDATE orders SET product = '780' WHERE id = 2

# "delivery" is interesting since it references a secondary index with different col names.
statement ok
CREATE TABLE delivery (
  ts TIMESTAMP DEFAULT now(),
  "order" int,
  shipment int,
  item STRING REFERENCES products (upc),
  FOREIGN KEY ("order", shipment) REFERENCES orders (id, shipment),
  INDEX (item)
)

query TT
SHOW CREATE TABLE delivery
----
delivery  CREATE TABLE delivery (
          ts TIMESTAMP NULL DEFAULT now():::TIMESTAMP,
          "order" INT8 NULL,
          shipment INT8 NULL,
          item STRING NULL,
          CONSTRAINT fk_item_ref_products FOREIGN KEY (item) REFERENCES products (upc),
          INDEX delivery_item_idx (item ASC),
          CONSTRAINT fk_order_ref_orders FOREIGN KEY ("order", shipment) REFERENCES orders (id, shipment),
          INDEX delivery_auto_index_fk_order_ref_orders ("order" ASC, shipment ASC),
          FAMILY "primary" (ts, "order", shipment, item, rowid)
)

statement ok
INSERT INTO delivery ("order", shipment, item) VALUES
  (1, 1, '867072000006'), (1, 1, '867072000006'), (1, 1, '885155001450'), (1, 1, '867072000006')

statement error pgcode 23503 foreign key violation: value \['missing'\] not found in products@products_upc_key \[upc\]
INSERT INTO delivery ("order", shipment, item) VALUES
  (1, 1, '867072000006'), (1, 1, 'missing'), (1, 1, '885155001450'), (1, 1, '867072000006')

statement error pgcode 23503 foreign key violation: value \[1 99\] not found in orders@primary \[id shipment\]
INSERT INTO delivery ("order", shipment, item) VALUES
  (1, 1, '867072000006'), (1, 99, '867072000006')

statement error pgcode 23503 foreign key violation: values \['867072000006'\] in columns \[upc\] referenced in table "delivery"
DELETE FROM products WHERE sku = 'VP-W9QH-W44L'

# Blanking a field nobody cares about is fine.
statement ok
UPDATE products SET vendor = '' WHERE sku = '780'

# No-op update should be fine.
statement ok
UPDATE products SET sku = '770' WHERE sku = '750'

# Changing referenced PK fails.
statement error pgcode 23503 foreign key violation: values \['780'\] in columns \[sku\] referenced in table "orders"
UPDATE products SET sku = '770' WHERE sku = '780'

# No-op change to existing data is fine.
statement ok
UPDATE products SET upc = '885155001450' WHERE sku = '780'

# Changing referenced non-pk index fails.
statement error pgcode 23503 foreign key violation: values \['885155001450'\] in columns \[upc\] referenced in table "delivery"
UPDATE products SET upc = 'blah' WHERE sku = '780'

statement ok
ALTER TABLE delivery DROP CONSTRAINT fk_item_ref_products

statement ok
UPDATE products SET upc = 'blah' WHERE sku = '780'

statement ok
ALTER TABLE delivery ADD FOREIGN KEY (item) REFERENCES products (upc)

query TTTTB
SHOW CONSTRAINTS FROM delivery
----
delivery  fk_item_ref_products  FOREIGN KEY  FOREIGN KEY (item) REFERENCES products (upc)                      false
delivery  fk_order_ref_orders   FOREIGN KEY  FOREIGN KEY ("order", shipment) REFERENCES orders (id, shipment)  true

statement error pgcode 23503 foreign key violation: "delivery" row item='885155001450' has no match in "products"
ALTER TABLE delivery VALIDATE CONSTRAINT fk_item_ref_products

query TTTTB
SHOW CONSTRAINTS FROM delivery
----
delivery  fk_item_ref_products  FOREIGN KEY  FOREIGN KEY (item) REFERENCES products (upc)                      false
delivery  fk_order_ref_orders   FOREIGN KEY  FOREIGN KEY ("order", shipment) REFERENCES orders (id, shipment)  true

statement ok
UPDATE products SET upc = '885155001450' WHERE sku = '780'

# Changing referenced non-pk index fails once again with constraint re-added.
statement error pgcode 23503 foreign key violation: values \['885155001450'\] in columns \[upc\] referenced in table "delivery"
UPDATE products SET upc = 'blah' WHERE sku = '780'

statement ok
ALTER TABLE delivery VALIDATE CONSTRAINT fk_item_ref_products

query TTTTB
SHOW CONSTRAINTS FROM delivery
----
delivery  fk_item_ref_products  FOREIGN KEY  FOREIGN KEY (item) REFERENCES products (upc)                      true
delivery  fk_order_ref_orders   FOREIGN KEY  FOREIGN KEY ("order", shipment) REFERENCES orders (id, shipment)  true

statement ok
ALTER TABLE "user content"."customer reviews"
  DROP CONSTRAINT orderfk

statement ok
INSERT INTO "user content"."customer reviews" (id, product, body, "order") VALUES (3, '780', 'i ordered 100 of them', 9)

statement ok
ALTER TABLE "user content"."customer reviews"
  ADD CONSTRAINT orderfk2 FOREIGN KEY ("order", shipment) REFERENCES orders (id, shipment)

# This is allowed because we match using MATCH SIMPLE.
statement ok
ALTER TABLE "user content"."customer reviews"
  VALIDATE CONSTRAINT orderfk2

# This is allowed because we match using MATCH SIMPLE.
statement ok
INSERT INTO "user content"."customer reviews" (id, product, body, "order") VALUES (4, '780', 'i ordered 101 of them', 9)

statement error pgcode 23503 foreign key violation: value \[9 1\] not found in orders@primary \[id shipment\]
INSERT INTO "user content"."customer reviews" (id, product, body, "order", shipment) VALUES (4, '780', 'i ordered 101 of them', 9, 1)

statement error pgcode 23503 foreign key violation: value \[1 9\] not found in orders@primary \[id shipment\]
INSERT INTO "user content"."customer reviews" (id, product, body, shipment, "order") VALUES (4, '780', 'i ordered 101 of them', 9, 1)

statement ok
ALTER TABLE delivery DROP CONSTRAINT fk_order_ref_orders

statement ok
TRUNCATE orders, "user content"."customer reviews"

# Changing now non-referenced and secondary field is fine.
statement ok
UPDATE products SET sku = '750', vendor = 'roomba' WHERE sku = '780'

# Changing PK and referenced secondary index is not ok.
statement error pgcode 23503 foreign key violation: values \['885155001450'\] in columns \[upc\] referenced in table "delivery"
UPDATE products SET sku = '780', upc = 'blah' WHERE sku = '750'

statement error pgcode 23503 foreign key violation: values \['885155001450'\] in columns \[upc\] referenced in table "delivery"
DELETE FROM products WHERE sku = '750'

statement error "products" is referenced by foreign key from table "orders"
TRUNCATE products

query I
SELECT count(*) FROM delivery
----
4

statement ok
TRUNCATE products CASCADE

query I
SELECT count(*) FROM delivery
----
0

statement ok
TRUNCATE delivery, products, orders, "user content"."customer reviews"

query TTTTB colnames
SHOW CONSTRAINTS FROM orders
----
table_name  constraint_name          constraint_type  details                                                                                validated
orders      fk_product_ref_products  FOREIGN KEY      FOREIGN KEY (product) REFERENCES products (sku) ON DELETE RESTRICT ON UPDATE RESTRICT  true
orders      primary                  PRIMARY KEY      PRIMARY KEY (id ASC, shipment ASC)                                                     true
orders      valid_customer           FOREIGN KEY      FOREIGN KEY (customer) REFERENCES customers (id)                                       true

statement error "products_upc_key" is referenced by foreign key from table "delivery"
DROP INDEX products@products_upc_key

statement error "products_upc_key" is referenced by foreign key from table "delivery"
DROP INDEX products@products_upc_key RESTRICT

statement error "products_upc_key" is referenced by foreign key from table "delivery"
ALTER TABLE products DROP COLUMN upc

statement ok
ALTER TABLE delivery DROP COLUMN "item"

statement ok
DROP INDEX products@products_upc_key CASCADE

statement error index "orders_product_idx" is in use as a foreign key constraint
DROP INDEX orders@orders_product_idx

statement error index "orders_product_idx" is in use as a foreign key constraint
DROP INDEX orders@orders_product_idx RESTRICT

statement error "products" is referenced by foreign key from table "orders"
DROP TABLE products

statement error referenced by foreign key from table "orders"
DROP TABLE products RESTRICT

statement error referenced by foreign key from table "customer reviews"
DROP TABLE orders

# reviews has a multi-col FK in which dropping one col is not allowed.
statement error column "order" is referenced by existing index "customer reviews_auto_index_orderfk"
ALTER TABLE "user content"."customer reviews" DROP COLUMN "order"

statement ok
ALTER TABLE "user content"."customer reviews" DROP COLUMN "order" CASCADE

statement ok
DROP TABLE "user content"."customer reviews"

statement ok
DROP TABLE orders

statement ok
DROP TABLE products

statement ok
CREATE TABLE parent (id int primary key)

statement ok
CREATE TABLE child (id INT PRIMARY KEY, parent_id INT UNIQUE REFERENCES parent)

statement ok
CREATE TABLE grandchild (id INT PRIMARY KEY, parent_id INT REFERENCES child (parent_id), INDEX (parent_id))

statement error "parent" is referenced by foreign key from table "child"
DROP TABLE parent

statement error "child" is referenced by foreign key from table "grandchild"
DROP TABLE child

statement error pgcode 23503 foreign key violation
INSERT INTO child VALUES (2, 2)

statement ok
DROP TABLE parent CASCADE

statement ok
INSERT INTO child VALUES (2, 2)

statement error pgcode 23503 foreign key violation
INSERT INTO grandchild VALUES (1, 1)

statement error in use as a foreign key constraint
DROP INDEX grandchild@grandchild_parent_id_idx

statement ok
DROP INDEX grandchild@grandchild_parent_id_idx CASCADE

statement ok
INSERT INTO grandchild VALUES (1, 1)

statement ok
DROP TABLE grandchild

statement ok
CREATE TABLE grandchild (id INT PRIMARY KEY, parent_id INT REFERENCES child (parent_id), INDEX (parent_id))

statement error pgcode 23503 foreign key violation
INSERT INTO grandchild VALUES (1, 1)

statement error "child_parent_id_key" is referenced by foreign key from table "grandchild"
DROP INDEX child@child_parent_id_key

statement ok
DROP INDEX child@child_parent_id_key CASCADE

statement ok
INSERT INTO grandchild VALUES (1, 1)

statement ok
CREATE TABLE employees (id INT PRIMARY KEY, manager INT REFERENCES employees, INDEX (manager))

statement ok
INSERT INTO employees VALUES (1, NULL)

statement ok
INSERT INTO employees VALUES (2, 1), (3, 1)

statement ok
INSERT INTO employees VALUES (4, 2), (5, 3)

statement error pgcode 23503 foreign key violation
DELETE FROM employees WHERE id = 2

statement error pgcode 23503 foreign key violation
DELETE FROM employees WHERE id > 1

statement ok
DROP TABLE employees

statement ok
CREATE TABLE pairs (id INT PRIMARY KEY, src INT, dest STRING, UNIQUE (src, dest))

statement ok
INSERT INTO pairs VALUES (1, 100, 'one'), (2, 200, 'two')

statement error type of "b" \(STRING\) does not match foreign key "pairs"."id" \(INT\)
CREATE TABLE refpairs (a INT, b STRING, CONSTRAINT fk FOREIGN KEY (b) REFERENCES pairs)

statement error 2 columns must reference exactly 2 columns in referenced table \(found 1\)
CREATE TABLE refpairs (a INT, b STRING, CONSTRAINT fk FOREIGN KEY (a, b) REFERENCES pairs)

# TODO(dt): remove ordering constraint on matching index
statement ok
CREATE TABLE refpairs_wrong_order (
  a INT,
  b STRING,
  FOREIGN KEY (a, b) REFERENCES pairs (src, dest),
  INDEX (b, a)
)

query TTBITTBB colnames
SHOW INDEXES FROM refpairs_wrong_order
----
table_name            index_name                                      non_unique  seq_in_index  column_name  direction  storing  implicit
refpairs_wrong_order  primary                                         false       1             rowid        ASC        false    false
refpairs_wrong_order  refpairs_wrong_order_b_a_idx                    true        1             b            ASC        false    false
refpairs_wrong_order  refpairs_wrong_order_b_a_idx                    true        2             a            ASC        false    false
refpairs_wrong_order  refpairs_wrong_order_b_a_idx                    true        3             rowid        ASC        false    true
refpairs_wrong_order  refpairs_wrong_order_auto_index_fk_a_ref_pairs  true        1             a            ASC        false    false
refpairs_wrong_order  refpairs_wrong_order_auto_index_fk_a_ref_pairs  true        2             b            ASC        false    false
refpairs_wrong_order  refpairs_wrong_order_auto_index_fk_a_ref_pairs  true        3             rowid        ASC        false    true

statement ok
CREATE TABLE refpairs_c_between (a INT, b STRING, c INT, FOREIGN KEY (a, b) REFERENCES pairs (src, dest), INDEX (a, c, b))

query TTBITTBB colnames
SHOW INDEXES FROM refpairs_c_between
----
table_name          index_name                                    non_unique  seq_in_index  column_name  direction  storing  implicit
refpairs_c_between  primary                                       false       1             rowid        ASC        false    false
refpairs_c_between  refpairs_c_between_a_c_b_idx                  true        1             a            ASC        false    false
refpairs_c_between  refpairs_c_between_a_c_b_idx                  true        2             c            ASC        false    false
refpairs_c_between  refpairs_c_between_a_c_b_idx                  true        3             b            ASC        false    false
refpairs_c_between  refpairs_c_between_a_c_b_idx                  true        4             rowid        ASC        false    true
refpairs_c_between  refpairs_c_between_auto_index_fk_a_ref_pairs  true        1             a            ASC        false    false
refpairs_c_between  refpairs_c_between_auto_index_fk_a_ref_pairs  true        2             b            ASC        false    false
refpairs_c_between  refpairs_c_between_auto_index_fk_a_ref_pairs  true        3             rowid        ASC        false    true

statement ok
CREATE TABLE refpairs (
  a INT,
  b STRING,
  c INT,
  FOREIGN KEY (a, b) REFERENCES pairs (src, dest) ON UPDATE RESTRICT,
  INDEX (a, b, c)
)

query TTBITTBB colnames
SHOW INDEXES FROM refpairs
----
table_name  index_name          non_unique  seq_in_index  column_name  direction  storing  implicit
refpairs    primary             false       1             rowid        ASC        false    false
refpairs    refpairs_a_b_c_idx  true        1             a            ASC        false    false
refpairs    refpairs_a_b_c_idx  true        2             b            ASC        false    false
refpairs    refpairs_a_b_c_idx  true        3             c            ASC        false    false
refpairs    refpairs_a_b_c_idx  true        4             rowid        ASC        false    true

query TT
SHOW CREATE TABLE refpairs
----
refpairs  CREATE TABLE refpairs (
  a INT8 NULL,
  b STRING NULL,
  c INT8 NULL,
  CONSTRAINT fk_a_ref_pairs FOREIGN KEY (a, b) REFERENCES pairs (src, dest) ON UPDATE RESTRICT,
  INDEX refpairs_a_b_c_idx (a ASC, b ASC, c ASC),
  FAMILY "primary" (a, b, c, rowid)
)

statement error pgcode 23503 foreign key violation: value \[100 'two'\] not found in pairs@pairs_src_dest_key \[src dest\]
INSERT INTO refpairs VALUES (100, 'two'), (200, 'two')

statement ok
INSERT INTO refpairs VALUES (100, 'one', 3), (200, 'two', null)

statement error pgcode 23503 foreign key violation: values \[200 'two'\] in columns \[src dest\] referenced in table "refpairs"
UPDATE pairs SET dest = 'too' WHERE id = 2

statement error pgcode 23503 foreign key violation: values \[200 'two'\] in columns \[src dest\] referenced in table "refpairs"
DELETE FROM pairs WHERE id = 2

statement error pgcode 23503 foreign key violation: values \[100 'one'\] in columns \[src dest\] referenced in table "refpairs"
DELETE FROM pairs WHERE id = 1

statement error foreign key violation: values \[100 'one'\] in columns \[src dest\] referenced in table "refpairs"
SET tracing = on,kv; DELETE FROM pairs WHERE id = 1

statement ok
SET tracing=off

# Test that fk scans on indexes that are longer than the foreign key use
# PrefixEnd instead of interleave end.
query T rowsort
SELECT message FROM [SHOW KV TRACE FOR SESSION]
WHERE message LIKE 'FKScan%'
----
FKScan /Table/85/3/100/"one"{-/#}
FKScan /Table/86/3/100/"one"{-/#}
FKScan /Table/87/2/100/"one"{-/PrefixEnd}

# since PKs are handled differently than other indexes, check pk<->pk ref with no other indexes in play.
statement ok
CREATE TABLE foo (id INT PRIMARY KEY)

statement ok
CREATE TABLE bar (id INT PRIMARY KEY REFERENCES foo)

statement ok
INSERT INTO foo VALUES (2)

statement ok
INSERT INTO bar VALUES (2)

statement error pgcode 23503 foreign key violation: values \[2] in columns \[id\] referenced in table "bar"
DELETE FROM foo

statement ok
CREATE DATABASE otherdb

statement ok
CREATE TABLE otherdb.othertable (id INT PRIMARY KEY)

statement ok
CREATE TABLE crossdb (id INT PRIMARY KEY, FOREIGN KEY (id) REFERENCES otherdb.othertable)

statement error pgcode 23503 foreign key violation: value \[2\] not found in othertable@primary \[id\]
INSERT INTO crossdb VALUES (2)

statement ok
INSERT INTO otherdb.othertable VALUES (1), (2)

statement ok
INSERT INTO crossdb VALUES (2)

statement error pgcode 23503 foreign key violation: values \[2] in columns \[id\] referenced in table "crossdb"
DELETE FROM otherdb.othertable WHERE id = 2

statement error "othertable" is referenced by foreign key from table "crossdb"
DROP TABLE otherdb.othertable

statement ok
DROP TABLE otherdb.othertable, crossdb

statement ok
CREATE TABLE modules (id BIGSERIAL NOT NULL PRIMARY KEY)

statement ok
CREATE TABLE domains (id BIGSERIAL NOT NULL PRIMARY KEY)

# We'll use the unique index for the domain fk (since it is a prefix), but we
# we correctly only mark the prefix as used and thus still allow module_id to be
# used in another FK.
statement ok
CREATE TABLE domain_modules (
  id         BIGSERIAL    NOT NULL PRIMARY KEY,
  domain_id  BIGINT       NOT NULL,
  module_id  BIGINT       NOT NULL,
  CONSTRAINT domain_modules_domain_id_fk FOREIGN KEY (domain_id) REFERENCES domains (id),
  CONSTRAINT domain_modules_module_id_fk FOREIGN KEY (module_id) REFERENCES modules (id),
  CONSTRAINT domain_modules_uq UNIQUE (domain_id, module_id)
)

query TTTTB
SHOW CONSTRAINTS FROM domain_modules
----
domain_modules  domain_modules_domain_id_fk  FOREIGN KEY  FOREIGN KEY (domain_id) REFERENCES domains (id)  true
domain_modules  domain_modules_module_id_fk  FOREIGN KEY  FOREIGN KEY (module_id) REFERENCES modules (id)  true
domain_modules  domain_modules_uq            UNIQUE       UNIQUE (domain_id ASC, module_id ASC)            true
domain_modules  primary                      PRIMARY KEY  PRIMARY KEY (id ASC)                             true

statement ok
INSERT INTO modules VALUES(3)

statement error foreign key violation: value \[2\] not found in domains@primary
SET tracing = on,kv; INSERT INTO domain_modules VALUES (1, 2, 3)

statement ok
SET tracing=off

query T rowsort
SELECT message FROM [SHOW KV TRACE FOR SESSION]
WHERE message LIKE 'FKScan%'
----
FKScan /Table/93/1/3{-/#}
FKScan /Table/94/1/2{-/#}

statement ok
CREATE TABLE tx (
  id INT NOT NULL PRIMARY KEY
)

statement ok
CREATE TABLE tx_leg (
  leg_id SERIAL NOT NULL PRIMARY KEY,
  tx_id INT NOT NULL REFERENCES tx
)

statement ok
BEGIN TRANSACTION

statement ok
INSERT INTO tx VALUES (2)

statement ok
INSERT INTO tx_leg VALUES (201, 2);

statement ok
INSERT INTO tx_leg VALUES (202, 2);

statement ok
COMMIT

statement ok
BEGIN TRANSACTION

statement error pgcode 23503 foreign key violation: value \[3\] not found in tx@primary \[id\]
INSERT INTO tx_leg VALUES (302, 3);

statement ok
COMMIT

statement ok
CREATE TABLE a (id SERIAL NOT NULL, self_id INT, b_id INT NOT NULL, PRIMARY KEY (id))

statement ok
CREATE TABLE b (id SERIAL NOT NULL, PRIMARY KEY (id))

# The index needed for the fk constraint is automatically added because the table is empty
statement ok
ALTER TABLE a ADD CONSTRAINT fk_self_id FOREIGN KEY (self_id) REFERENCES a;

# The index needed for the fk constraint is automatically added because the table is empty
statement ok
ALTER TABLE a ADD CONSTRAINT fk_b FOREIGN KEY (b_id) REFERENCES b;

statement ok
INSERT INTO b VALUES (1), (2), (3);

statement ok
INSERT INTO a VALUES (1, NULL, 1)

statement ok
INSERT INTO a VALUES (2, 1, 1), (3, 1, 2)

statement ok
INSERT INTO a VALUES (4, 2, 2)

statement ok
DELETE FROM b WHERE id = 3

statement error pgcode 23503 foreign key violation
DELETE FROM b WHERE id = 2

statement error pgcode 23503 foreign key violation
DELETE FROM a WHERE id = 1

statement ok
DELETE FROM a WHERE id > 2

statement ok
DELETE FROM b WHERE id = 2

statement ok
DROP TABLE a

statement ok
DROP TABLE b

# A CREATE TABLE with a FK reference within a transaction.
statement ok
CREATE TABLE referee (id INT PRIMARY KEY);

statement ok
BEGIN TRANSACTION

statement ok
CREATE TABLE refers (
  a INT REFERENCES referee,
  b INT,
  INDEX b_idx (b)
)

# Add some schema changes within the same transaction to verify that a
# table that isn't yet public can be modified.
statement ok
CREATE INDEX foo ON refers (a)

statement ok
ALTER INDEX refers@b_idx RENAME TO another_idx

query TT
SHOW CREATE TABLE refers
----
refers  CREATE TABLE refers (
        a INT8 NULL,
        b INT8 NULL,
        INDEX another_idx (b ASC),
        CONSTRAINT fk_a_ref_referee FOREIGN KEY (a) REFERENCES referee (id),
        INDEX refers_auto_index_fk_a_ref_referee (a ASC),
        INDEX foo (a ASC),
        FAMILY "primary" (a, b, rowid)
)

statement ok
DROP INDEX refers@another_idx

# refers is not visible because it is in the ADD state.
query T
SHOW TABLES FROM test
----
bar
child
customers
delivery
domain_modules
domains
foo
grandchild
modules
pairs
referee
refpairs
refpairs_c_between
refpairs_wrong_order
tx
tx_leg
unindexed

statement ok
COMMIT

# CREATE AND DROP a table with a fk in the same transaction.
statement ok
BEGIN TRANSACTION

statement ok
CREATE TABLE refers1 (a INT REFERENCES referee);

statement ok
DROP TABLE refers1

statement ok
COMMIT

# Check that removing self-ref FK correctly removed backref too, #16070.
statement ok
CREATE TABLE employee (
   id INT PRIMARY KEY,
   manager INT,
   UNIQUE (manager)
);

statement ok
ALTER TABLE employee
   ADD CONSTRAINT emp_emp
   FOREIGN KEY (manager)
   REFERENCES employee;

statement ok
ALTER TABLE employee
   DROP CONSTRAINT emp_emp;

statement ok
SHOW CREATE TABLE employee;

# Ensure that tables with an fk reference from their pk appear correctly in
# SHOW CREATE TABLE (#17596).
statement ok
CREATE TABLE pkref_a (a INT PRIMARY KEY)

statement ok
CREATE TABLE pkref_b (b INT PRIMARY KEY REFERENCES pkref_a ON UPDATE NO ACTION ON DELETE RESTRICT)

query TT
SHOW CREATE TABLE pkref_b
----
pkref_b  CREATE TABLE pkref_b (
         b INT8 NOT NULL,
         CONSTRAINT "primary" PRIMARY KEY (b ASC),
         CONSTRAINT fk_b_ref_pkref_a FOREIGN KEY (b) REFERENCES pkref_a (a) ON DELETE RESTRICT,
         FAMILY "primary" (b)
)

subtest 20042

statement ok
CREATE TABLE test20042 (
  x STRING PRIMARY KEY
 ,y STRING UNIQUE
 ,z STRING REFERENCES test20042(y)
);

statement ok
INSERT INTO test20042 (x, y, z) VALUES ('pk1', 'k1', null);

statement ok
INSERT INTO test20042 (x, y, z) VALUES ('pk2', 'k2 ', 'k1');

statement ok
DELETE FROM test20042 WHERE x = 'pk2';

statement ok
DELETE FROM test20042 WHERE x = 'pk1';

subtest 20045

statement ok
CREATE TABLE test20045 (
  x STRING PRIMARY KEY
 ,y STRING UNIQUE REFERENCES test20045(x)
 ,z STRING REFERENCES test20045(y)
);

statement ok
INSERT INTO test20045 (x, y, z) VALUES ('pk1', NULL, NULL);

statement ok
INSERT INTO test20045 (x, y, z) VALUES ('pk2', 'pk1', NULL);

statement ok
INSERT INTO test20045 (x, y, z) VALUES ('pk3', 'pk2', 'pk1');

statement ok
DELETE FROM test20045 WHERE x = 'pk3';

statement ok
DELETE FROM test20045 WHERE x = 'pk2';

statement ok
DELETE FROM test20045 WHERE x = 'pk1';

## Delete cascade without privileges

statement ok
CREATE DATABASE d;

statement ok
CREATE TABLE d.a (
  id STRING PRIMARY KEY
);

statement ok
CREATE TABLE d.b (
  id STRING PRIMARY KEY
 ,a_id STRING REFERENCES d.a ON DELETE CASCADE
);

statement ok
INSERT INTO d.a VALUES ('a1');

statement ok
INSERT INTO d.b VALUES ('b1', 'a1');

statement ok
GRANT ALL ON DATABASE d TO testuser;

statement ok
GRANT ALL ON d.a TO testuser;

user testuser

statement error user testuser does not have SELECT privilege on relation b
DELETE FROM d.a WHERE id = 'a1';

user root

statement ok
GRANT SELECT ON d.b TO testuser;

user testuser

statement error user testuser does not have DELETE privilege on relation b
DELETE FROM d.a WHERE id = 'a1';

user root

statement ok
GRANT DELETE ON d.b TO testuser;

user testuser

statement ok
DELETE FROM d.a WHERE id = 'a1';

user root

# Clean up after the test.
statement ok
DROP DATABASE d CASCADE;

subtest setNullWithNotNullConstraint
### Make sure that one cannot add a set null action on a NOT NULL column.

statement ok
CREATE TABLE a (
  id INT PRIMARY KEY
);

# Create a table with a NOT NULL column and a SET NULL action.
statement error pq: cannot add a SET NULL cascading action on column "test.public.not_null_table.delete_not_nullable" which has a NOT NULL constraint
CREATE TABLE not_null_table (
  id INT PRIMARY KEY
 ,delete_not_nullable INT NOT NULL REFERENCES a ON DELETE SET NULL
);

statement error pq: cannot add a SET NULL cascading action on column "test.public.not_null_table.update_not_nullable" which has a NOT NULL constraint
CREATE TABLE not_null_table (
  id INT PRIMARY KEY
 ,update_not_nullable INT NOT NULL REFERENCES a ON UPDATE SET NULL
);

# Create a table where the primary key has a SET NULL action.
statement error pq: cannot add a SET NULL cascading action on column "test.public.primary_key_table.id" which has a NOT NULL constraint
CREATE TABLE primary_key_table (
  id INT PRIMARY KEY REFERENCES a ON DELETE SET NULL
);

statement error pq: cannot add a SET NULL cascading action on column "test.public.primary_key_table.id" which has a NOT NULL constraint
CREATE TABLE primary_key_table (
  id INT PRIMARY KEY REFERENCES a ON UPDATE SET NULL
);

# Add a SET NULL action after the fact with a NOT NULL column.
statement ok
CREATE TABLE not_null_table (
  id INT PRIMARY KEY
 ,delete_not_nullable INT NOT NULL
 ,update_not_nullable INT NOT NULL
);

statement error pq: cannot add a SET NULL cascading action on column "test.public.not_null_table.delete_not_nullable" which has a NOT NULL constraint
ALTER TABLE not_null_table ADD CONSTRAINT not_null_delete_set_null
  FOREIGN KEY (delete_not_nullable) REFERENCES a (id)
  ON DELETE SET NULL;

statement error pq: cannot add a SET NULL cascading action on column "test.public.not_null_table.update_not_nullable" which has a NOT NULL constraint
ALTER TABLE not_null_table ADD CONSTRAINT not_null_update_set_null
  FOREIGN KEY (update_not_nullable) REFERENCES a (id)
  ON UPDATE SET NULL;

# Clean up so far,
statement ok
DROP TABLE not_null_table;

# Add a SET NULL action after the fact with a primary key column.
statement ok
CREATE TABLE primary_key_table (
  id INT PRIMARY KEY
);

statement error pq: cannot add a SET NULL cascading action on column "test.public.primary_key_table.id" which has a NOT NULL constraint
ALTER TABLE primary_key_table ADD CONSTRAINT not_null_set_null
  FOREIGN KEY (id) REFERENCES a (id)
  ON DELETE SET NULL;

statement error pq: cannot add a SET NULL cascading action on column "test.public.primary_key_table.id" which has a NOT NULL constraint
ALTER TABLE primary_key_table ADD CONSTRAINT not_null_set_null
  FOREIGN KEY (id) REFERENCES a (id)
  ON UPDATE SET NULL;

# Clean up the tables used so far.
statement ok
DROP TABLE primary_key_table, a;

# Now test composite foreign keys
statement ok
CREATE TABLE a (
  id1 INT
 ,id2 INT
 ,PRIMARY KEY (id2, id1)
);

# Create a table with a NOT NULL column and a SET NULL action.
statement error pq: cannot add a SET NULL cascading action on column "test.public.not_null_table.ref1" which has a NOT NULL constraint
CREATE TABLE not_null_table (
  id INT PRIMARY KEY
 ,ref1 INT NOT NULL
 ,ref2 INT NOT NULL
 ,INDEX (ref1, ref2)
 ,FOREIGN KEY (ref1, ref2) REFERENCES a (id2, id1) ON DELETE SET NULL
);

statement error pq: cannot add a SET NULL cascading action on column "test.public.not_null_table.ref1" which has a NOT NULL constraint
CREATE TABLE not_null_table (
  id INT PRIMARY KEY
 ,ref1 INT NOT NULL
 ,ref2 INT NOT NULL
 ,INDEX (ref1, ref2)
 ,FOREIGN KEY (ref1, ref2) REFERENCES a (id2, id1) ON UPDATE SET NULL
);

statement error pq: cannot add a SET NULL cascading action on column "test.public.not_null_table.ref1" which has a NOT NULL constraint
CREATE TABLE not_null_table (
  id INT PRIMARY KEY
 ,ref1 INT NOT NULL
 ,ref2 INT
 ,INDEX (ref1, ref2)
 ,FOREIGN KEY (ref1, ref2) REFERENCES a (id2, id1) ON DELETE SET NULL
);

statement error pq: cannot add a SET NULL cascading action on column "test.public.not_null_table.ref1" which has a NOT NULL constraint
CREATE TABLE not_null_table (
  id INT PRIMARY KEY
 ,ref1 INT NOT NULL
 ,ref2 INT
 ,INDEX (ref1, ref2)
 ,FOREIGN KEY (ref1, ref2) REFERENCES a (id2, id1) ON UPDATE SET NULL
);

statement error pq: cannot add a SET NULL cascading action on column "test.public.not_null_table.ref2" which has a NOT NULL constraint
CREATE TABLE not_null_table (
  id INT PRIMARY KEY
 ,ref1 INT
 ,ref2 INT NOT NULL
 ,INDEX (ref1, ref2)
 ,FOREIGN KEY (ref1, ref2) REFERENCES a (id2, id1) ON DELETE SET NULL
);

statement error pq: cannot add a SET NULL cascading action on column "test.public.not_null_table.ref2" which has a NOT NULL constraint
CREATE TABLE not_null_table (
  id INT PRIMARY KEY
 ,ref1 INT
 ,ref2 INT NOT NULL
 ,INDEX (ref1, ref2)
 ,FOREIGN KEY (ref1, ref2) REFERENCES a (id2, id1) ON UPDATE SET NULL
);

# Create a table where the primary key has a SET NULL action.
statement error pq: cannot add a SET NULL cascading action on column "test.public.primary_key_table.ref1" which has a NOT NULL constraint
CREATE TABLE primary_key_table (
  ref1 INT
 ,ref2 INT
 ,PRIMARY KEY (ref2, ref1)
 ,FOREIGN KEY (ref1, ref2) REFERENCES a (id2, id1) ON DELETE SET NULL
);

# Create a table where the primary key has a SET NULL action.
statement error pq: cannot add a SET NULL cascading action on column "test.public.primary_key_table.ref1" which has a NOT NULL constraint
CREATE TABLE primary_key_table (
  ref1 INT
 ,ref2 INT
 ,PRIMARY KEY (ref2, ref1)
 ,FOREIGN KEY (ref1, ref2) REFERENCES a (id2, id1) ON UPDATE SET NULL
);

statement error pq: cannot add a SET NULL cascading action on column "test.public.primary_key_table.ref2" which has a NOT NULL constraint
CREATE TABLE primary_key_table (
  ref1 INT
 ,ref2 INT
 ,PRIMARY KEY (ref2, ref1)
 ,FOREIGN KEY (ref2, ref1) REFERENCES a (id2, id1) ON DELETE SET NULL
);

statement error pq: cannot add a SET NULL cascading action on column "test.public.primary_key_table.ref2" which has a NOT NULL constraint
CREATE TABLE primary_key_table (
  ref1 INT
 ,ref2 INT
 ,PRIMARY KEY (ref2, ref1)
 ,FOREIGN KEY (ref2, ref1) REFERENCES a (id2, id1) ON UPDATE SET NULL
);

# Clean up after the test.
statement ok
DROP TABLE a;

subtest setDefaultWithoutDefault
### Make sure that one cannot add a SET DEFAULT action with no default values
### on a column.

statement ok
CREATE TABLE a (
  id INT PRIMARY KEY
);

# Create a table with no DEFAULT expressions column and a SET DEFAULT action.
statement error pq: cannot add a SET DEFAULT cascading action on column "test.public.no_default_table.delete_no_default" which has no DEFAULT expression
CREATE TABLE no_default_table (
  id INT PRIMARY KEY
 ,delete_no_default INT REFERENCES a ON DELETE SET DEFAULT
);

statement error pq: cannot add a SET DEFAULT cascading action on column "test.public.no_default_table.update_no_default" which has no DEFAULT expression
CREATE TABLE no_default_table (
  id INT PRIMARY KEY
 ,update_no_default INT NOT NULL REFERENCES a ON UPDATE SET DEFAULT
);

# Create a table where the primary key has a SET DEFAULT action.
statement error pq: cannot add a SET DEFAULT cascading action on column "test.public.primary_key_table.id" which has no DEFAULT expression
CREATE TABLE primary_key_table (
  id INT PRIMARY KEY REFERENCES a ON DELETE SET DEFAULT
);

statement error pq: cannot add a SET DEFAULT cascading action on column "test.public.primary_key_table.id" which has no DEFAULT expression
CREATE TABLE primary_key_table (
  id INT PRIMARY KEY REFERENCES a ON UPDATE SET DEFAULT
);

# Add a SET DEFAULT action after the to a column with no DEFAULT expression.
statement ok
CREATE TABLE no_default_table (
  id INT PRIMARY KEY
 ,delete_no_default INT
 ,update_no_default INT
);

statement error pq: cannot add a SET DEFAULT cascading action on column "test.public.no_default_table.delete_no_default" which has no DEFAULT expression
ALTER TABLE no_default_table ADD CONSTRAINT no_default_delete_set_default
  FOREIGN KEY (delete_no_default) REFERENCES a (id)
  ON DELETE SET DEFAULT;

statement error pq: cannot add a SET DEFAULT cascading action on column "test.public.no_default_table.update_no_default" which has no DEFAULT expression
ALTER TABLE no_default_table ADD CONSTRAINT no_default_update_set_default
  FOREIGN KEY (update_no_default) REFERENCES a (id)
  ON UPDATE SET DEFAULT;

# Clean up so far,
statement ok
DROP TABLE no_default_table;

# Add a SET DEFAULT action after the fact with a primary key column that has no
# DEFAULT expression.
statement ok
CREATE TABLE primary_key_table (
  id INT PRIMARY KEY
);

statement error pq: cannot add a SET DEFAULT cascading action on column "test.public.primary_key_table.id" which has no DEFAULT expression
ALTER TABLE primary_key_table ADD CONSTRAINT no_default_delete_set_default
  FOREIGN KEY (id) REFERENCES a (id)
  ON DELETE SET DEFAULT;

statement error pq: cannot add a SET DEFAULT cascading action on column "test.public.primary_key_table.id" which has no DEFAULT expression
ALTER TABLE primary_key_table ADD CONSTRAINT no_default_update_set_default
  FOREIGN KEY (id) REFERENCES a (id)
  ON UPDATE SET DEFAULT;

# Clean up the tables used so far.
statement ok
DROP TABLE primary_key_table, a;

# Now test composite foreign keys
statement ok
CREATE TABLE a (
  id1 INT
 ,id2 INT
 ,PRIMARY KEY (id2, id1)
);

# Create a table with a column without a DEFAULT expression and a SET DEFAULT action.
statement error pq: cannot add a SET DEFAULT cascading action on column "test.public.no_default_table.ref1" which has no DEFAULT expression
CREATE TABLE no_default_table (
  id INT PRIMARY KEY
 ,ref1 INT
 ,ref2 INT
 ,INDEX (ref1, ref2)
 ,FOREIGN KEY (ref1, ref2) REFERENCES a (id2, id1) ON DELETE SET DEFAULT
);

statement error pq: cannot add a SET DEFAULT cascading action on column "test.public.no_default_table.ref1" which has no DEFAULT expression
CREATE TABLE no_default_table (
  id INT PRIMARY KEY
 ,ref1 INT
 ,ref2 INT
 ,INDEX (ref1, ref2)
 ,FOREIGN KEY (ref1, ref2) REFERENCES a (id2, id1) ON UPDATE SET DEFAULT
);

statement error pq: cannot add a SET DEFAULT cascading action on column "test.public.no_default_table.ref1" which has no DEFAULT expression
CREATE TABLE no_default_table (
  id INT PRIMARY KEY
 ,ref1 INT
 ,ref2 INT DEFAULT 1
 ,INDEX (ref1, ref2)
 ,FOREIGN KEY (ref1, ref2) REFERENCES a (id2, id1) ON DELETE SET DEFAULT
);


statement error pq: cannot add a SET DEFAULT cascading action on column "test.public.no_default_table.ref1" which has no DEFAULT expression
CREATE TABLE no_default_table (
  id INT PRIMARY KEY
 ,ref1 INT
 ,ref2 INT DEFAULT 1
 ,INDEX (ref1, ref2)
 ,FOREIGN KEY (ref1, ref2) REFERENCES a (id2, id1) ON UPDATE SET DEFAULT
);

statement error pq: cannot add a SET DEFAULT cascading action on column "test.public.no_default_table.ref2" which has no DEFAULT expression
CREATE TABLE no_default_table (
  id INT PRIMARY KEY
 ,ref1 INT DEFAULT 1
 ,ref2 INT
 ,INDEX (ref1, ref2)
 ,FOREIGN KEY (ref1, ref2) REFERENCES a (id2, id1) ON DELETE SET DEFAULT
);

statement error pq: cannot add a SET DEFAULT cascading action on column "test.public.no_default_table.ref2" which has no DEFAULT expression
CREATE TABLE no_default_table (
  id INT PRIMARY KEY
 ,ref1 INT DEFAULT 1
 ,ref2 INT
 ,INDEX (ref1, ref2)
 ,FOREIGN KEY (ref1, ref2) REFERENCES a (id2, id1) ON UPDATE SET DEFAULT
);

# Clean up after the test.
statement ok
DROP TABLE a;

subtest 24664

statement ok
CREATE TABLE t (a INT, b INT, UNIQUE INDEX (a), UNIQUE INDEX (a, b))

statement ok
ALTER TABLE t ADD FOREIGN KEY (a) REFERENCES t (a)

statement error column "a" cannot be used by multiple foreign key constraints
ALTER TABLE t ADD FOREIGN KEY (a, b) REFERENCES t (a, b)

statement ok
DROP TABLE t

subtest Composite_Simple
# Originally from 26748.

# Test composite key with two columns.
statement ok
CREATE TABLE a (
  x STRING NULL
 ,y STRING NULL
 ,CONSTRAINT "primary" PRIMARY KEY (y, x)
);

statement ok
CREATE TABLE b (
 a_y STRING NULL
 ,a_x STRING NULL
 ,CONSTRAINT fk_ref FOREIGN KEY (a_y, a_x) REFERENCES a (y, x)
);

statement ok
INSERT INTO a (x, y) VALUES ('x1', 'y1')

# All of these are allowed because we do composite matching using MATCH SIMPLE.
statement ok
INSERT INTO b (a_x) VALUES ('x1')

statement ok
INSERT INTO b (a_y) VALUES ('y1')

statement ok
INSERT INTO b (a_y, a_x) VALUES ('y1', NULL)

statement ok
INSERT INTO b (a_y, a_x) VALUES (NULL, 'x1')

statement ok
INSERT INTO b (a_x, a_y) VALUES ('x1', 'y1')

statement ok
INSERT INTO b (a_x, a_y) VALUES (NULL, NULL)

statement ok
DROP TABLE b, a

# Test composite key with three columns.
statement ok
CREATE TABLE a (
  x STRING NULL
 ,y STRING NULL
 ,z STRING NULL
 ,CONSTRAINT "primary" PRIMARY KEY (z, y, x)
);

statement ok
CREATE TABLE b (
  a_y STRING NULL
 ,a_x STRING NULL
 ,a_z STRING NULL
 ,CONSTRAINT fk_ref FOREIGN KEY (a_z, a_y, a_x) REFERENCES a (z, y, x)
);

statement ok
INSERT INTO a (x, y, z) VALUES ('x1', 'y1', 'z1')

# All of these are allowed because we do composite matching using MATCH SIMPLE.
statement ok
INSERT INTO b (a_x) VALUES ('x1')

statement ok
INSERT INTO b (a_y) VALUES ('y1')

statement ok
INSERT INTO b (a_z) VALUES ('z1')

statement ok
INSERT INTO b (a_x, a_y) VALUES ('x1', 'y1')

statement ok
INSERT INTO b (a_x, a_y) VALUES (NULL, 'y1')

statement ok
INSERT INTO b (a_x, a_y) VALUES ('x1', NULL)

statement ok
INSERT INTO b (a_x, a_z) VALUES ('x1', 'z1')

statement ok
INSERT INTO b (a_x, a_z) VALUES (NULL, 'z1')

statement ok
INSERT INTO b (a_x, a_z) VALUES ('x1', NULL)

statement ok
INSERT INTO b (a_y, a_z) VALUES ('y1', 'z1')

statement ok
INSERT INTO b (a_y, a_z) VALUES (NULL, 'z1')

statement ok
INSERT INTO b (a_y, a_z) VALUES ('y1', NULL)

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES ('x1', NULL, NULL)

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, 'y1', NULL)

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, NULL, 'z1')

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES ('x1', 'y1', NULL)

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES ('x1', NULL, 'z1')

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, 'y1', 'z1')

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, NULL, NULL)

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES ('x2', NULL, NULL)

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, 'y2', NULL)

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, NULL, 'z2')

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES ('x2', 'y2', NULL)

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES ('x2', NULL, 'z2')

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, 'y2', 'z2')

statement ok
DROP TABLE b, a

subtest Composite_Simple_Unvalidated
# Test inserting into table with an unvalidated constraint, and running VALIDATE CONSTRAINT later

# Test composite key with two columns.
statement ok
CREATE TABLE a (
  x STRING NULL
 ,y STRING NULL
 ,CONSTRAINT "primary" PRIMARY KEY (y, x)
);

statement ok
CREATE TABLE b (
 a_y STRING NULL
 ,a_x STRING NULL
);

# Add the constraint separately so that it's unvalidated, so we can test VALIDATE CONSTRAINT.
statement ok
ALTER TABLE b ADD CONSTRAINT fk_ref FOREIGN KEY (a_y, a_x) REFERENCES a (y, x)

statement ok
INSERT INTO a (x, y) VALUES ('x1', 'y1')

# All of these are allowed because we do composite matching using MATCH SIMPLE.
statement ok
INSERT INTO b (a_x) VALUES ('x1')

statement ok
INSERT INTO b (a_y) VALUES ('y1')

statement ok
INSERT INTO b (a_y, a_x) VALUES ('y1', NULL)

statement ok
INSERT INTO b (a_y, a_x) VALUES (NULL, 'x1')

statement ok
INSERT INTO b (a_y, a_x) VALUES ('y2', NULL)

statement ok
INSERT INTO b (a_y, a_x) VALUES (NULL, 'x2')

statement ok
INSERT INTO b (a_x, a_y) VALUES ('x1', 'y1')

statement ok
INSERT INTO b (a_x, a_y) VALUES (NULL, NULL)

statement ok
ALTER TABLE b VALIDATE CONSTRAINT fk_ref

statement ok
DROP TABLE b, a

# Test composite key with three columns.
statement ok
CREATE TABLE a (
  x STRING NULL
 ,y STRING NULL
 ,z STRING NULL
 ,CONSTRAINT "primary" PRIMARY KEY (z, y, x)
);

statement ok
CREATE TABLE b (
  a_y STRING NULL
 ,a_x STRING NULL
 ,a_z STRING NULL
);

# Add the constraint separately so that it's unvalidated, so we can test VALIDATE CONSTRAINT.
statement ok
ALTER TABLE b ADD CONSTRAINT fk_ref FOREIGN KEY (a_z, a_y, a_x) REFERENCES a (z, y, x)

statement ok
INSERT INTO a (x, y, z) VALUES ('x1', 'y1', 'z1')

# All of these are allowed because we do composite matching using MATCH SIMPLE.
statement ok
INSERT INTO b (a_x) VALUES ('x1')

statement ok
INSERT INTO b (a_y) VALUES ('y1')

statement ok
INSERT INTO b (a_z) VALUES ('z1')

statement ok
INSERT INTO b (a_x, a_y) VALUES ('x1', 'y1')

statement ok
INSERT INTO b (a_x, a_y) VALUES (NULL, 'y1')

statement ok
INSERT INTO b (a_x, a_y) VALUES ('x1', NULL)

statement ok
INSERT INTO b (a_x, a_z) VALUES ('x1', 'z1')

statement ok
INSERT INTO b (a_x, a_z) VALUES (NULL, 'z1')

statement ok
INSERT INTO b (a_x, a_z) VALUES ('x1', NULL)

statement ok
INSERT INTO b (a_y, a_z) VALUES ('y1', 'z1')

statement ok
INSERT INTO b (a_y, a_z) VALUES (NULL, 'z1')

statement ok
INSERT INTO b (a_y, a_z) VALUES ('y1', NULL)

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES ('x1', NULL, NULL)

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, 'y1', NULL)

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, NULL, 'z1')

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES ('x1', 'y1', NULL)

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES ('x1', NULL, 'z1')

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, 'y1', 'z1')

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES ('x2', NULL, NULL)

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, 'y2', NULL)

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, NULL, 'z2')

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES ('x2', 'y2', NULL)

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES ('x2', NULL, 'z2')

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, 'y2', 'z2')

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, NULL, NULL)

statement ok
ALTER TABLE b VALIDATE CONSTRAINT fk_ref

statement ok
DROP TABLE b, a

subtest Composite_Simple_Validate_Constraint_Invalid
# Test VALIDATE CONSTRAINT by inserting invalid rows before the constraint is added, one at a time.

statement ok
CREATE TABLE a (
  x STRING NULL
 ,y STRING NULL
 ,z STRING NULL
 ,CONSTRAINT "primary" PRIMARY KEY (z, y, x)
);

statement ok
CREATE TABLE b (
  a_y STRING NULL
 ,a_x STRING NULL
 ,a_z STRING NULL
 ,INDEX idx (a_z, a_y, a_x)
);

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES ('x2', 'y1', 'z1')

statement ok
ALTER TABLE b ADD CONSTRAINT fk_ref FOREIGN KEY (a_z, a_y, a_x) REFERENCES a (z, y, x)

# Verify that the optimizer doesn't use an unvalidated constraint to simplify plans.
query TTT
SELECT
  s.a_z, s.a_y, s.a_x
FROM
  (SELECT * FROM b WHERE a_z IS NOT NULL AND a_y IS NOT NULL AND a_x IS NOT NULL) AS s
  LEFT JOIN a AS t ON s.a_z = t.z AND s.a_y = t.y AND s.a_x = t.x
WHERE
  t.z IS NULL
----
z1 y1 x2

statement error foreign key violation: "b" row a_z='z1', a_y='y1', a_x='x2' has no match in "a"
ALTER TABLE b VALIDATE CONSTRAINT fk_ref

statement ok
TRUNCATE b

statement ok
ALTER TABLE b DROP CONSTRAINT fk_ref

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES ('x2', 'y2', 'z1')

statement ok
ALTER TABLE b ADD CONSTRAINT fk_ref FOREIGN KEY (a_z, a_y, a_x) REFERENCES a (z, y, x)

statement error foreign key violation: "b" row a_z='z1', a_y='y2', a_x='x2' has no match in "a"
ALTER TABLE b VALIDATE CONSTRAINT fk_ref

statement ok
TRUNCATE b

statement ok
ALTER TABLE b DROP CONSTRAINT fk_ref

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES ('x2', 'y2', 'z2')

statement ok
ALTER TABLE b ADD CONSTRAINT fk_ref FOREIGN KEY (a_z, a_y, a_x) REFERENCES a (z, y, x)

statement error foreign key violation: "b" row a_z='z2', a_y='y2', a_x='x2' has no match in "a"
ALTER TABLE b VALIDATE CONSTRAINT fk_ref

statement ok
DROP TABLE b, a

subtest Composite_Full
# Originally from 26748.

# Test composite key with two columns.
statement ok
CREATE TABLE a (
  x STRING NULL
 ,y STRING NULL
 ,CONSTRAINT "primary" PRIMARY KEY (y, x)
);

statement ok
CREATE TABLE b (
 a_y STRING NULL
 ,a_x STRING NULL
 ,CONSTRAINT fk_ref FOREIGN KEY (a_y, a_x) REFERENCES a (y, x) MATCH FULL
);

statement ok
INSERT INTO a (x, y) VALUES ('x1', 'y1')

# These statements should all fail because this uses MATCH FULL.
statement error missing value for column "a_y" in multi-part foreign key
INSERT INTO b (a_x) VALUES ('x1')

statement error missing value for column "a_x" in multi-part foreign key
INSERT INTO b (a_y) VALUES ('y1')

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
INSERT INTO b (a_y, a_x) VALUES ('y1', NULL)

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
INSERT INTO b (a_y, a_x) VALUES (NULL, 'x1')

# These next two statements should still be allowed.
statement ok
INSERT INTO b (a_x, a_y) VALUES ('x1', 'y1')

statement ok
INSERT INTO b (a_x, a_y) VALUES (NULL, NULL)

statement ok
DROP TABLE b, a

# Test composite key with three columns.
statement ok
CREATE TABLE a (
  x STRING NULL
 ,y STRING NULL
 ,z STRING NULL
 ,CONSTRAINT "primary" PRIMARY KEY (z, y, x)
);

statement ok
CREATE TABLE b (
  a_y STRING NULL
 ,a_x STRING NULL
 ,a_z STRING NULL
 ,CONSTRAINT fk_ref FOREIGN KEY (a_z, a_y, a_x) REFERENCES a (z, y, x) MATCH FULL
);

statement ok
INSERT INTO a (x, y, z) VALUES ('x1', 'y1', 'z1')

# These statements should all fail because this uses MATCH FULL.
statement error missing values for columns \["a_y" "a_z"\] in multi-part foreign key
INSERT INTO b (a_x) VALUES ('x1')

statement error missing values for columns \["a_x" "a_z"\] in multi-part foreign key
INSERT INTO b (a_y) VALUES ('y1')

statement error missing values for columns \["a_x" "a_y"\] in multi-part foreign key
INSERT INTO b (a_z) VALUES ('z1')

statement error missing value for column "a_z" in multi-part foreign key
INSERT INTO b (a_x, a_y) VALUES ('x1', 'y1')

statement error missing value for column "a_z" in multi-part foreign key
INSERT INTO b (a_x, a_y) VALUES (NULL, 'y1')

statement error missing value for column "a_z" in multi-part foreign key
INSERT INTO b (a_x, a_y) VALUES ('x1', NULL)

statement error missing value for column "a_y" in multi-part foreign key
INSERT INTO b (a_x, a_z) VALUES ('x1', 'z1')

statement error missing value for column "a_y" in multi-part foreign key
INSERT INTO b (a_x, a_z) VALUES (NULL, 'z1')

statement error missing value for column "a_y" in multi-part foreign key
INSERT INTO b (a_x, a_z) VALUES ('x1', NULL)

statement error missing value for column "a_x" in multi-part foreign key
INSERT INTO b (a_y, a_z) VALUES ('y1', 'z1')

statement error missing value for column "a_x" in multi-part foreign key
INSERT INTO b (a_y, a_z) VALUES (NULL, 'z1')

statement error missing value for column "a_x" in multi-part foreign key
INSERT INTO b (a_y, a_z) VALUES ('y1', NULL)

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
INSERT INTO b (a_x, a_y, a_z) VALUES ('x1', NULL, NULL)

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, 'y1', NULL)

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, NULL, 'z1')

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
INSERT INTO b (a_x, a_y, a_z) VALUES ('x1', 'y1', NULL)

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
INSERT INTO b (a_x, a_y, a_z) VALUES ('x1', NULL, 'z1')

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, 'y1', 'z1')

# This statement should still be allowed.
statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, NULL, NULL)

statement ok
DROP TABLE b, a

subtest Composite_Full_Validate_Later
# Test inserting into table with an unvalidated constraint, and running VALIDATE CONSTRAINT later

# Test composite key with two columns.
statement ok
CREATE TABLE a (
  x STRING NULL
 ,y STRING NULL
 ,CONSTRAINT "primary" PRIMARY KEY (y, x)
);

statement ok
CREATE TABLE b (
 a_y STRING NULL
 ,a_x STRING NULL
);

# Add the constraint separately so that it's unvalidated, so we can test VALIDATE CONSTRAINT.
statement ok
ALTER TABLE b ADD CONSTRAINT fk_ref FOREIGN KEY (a_y, a_x) REFERENCES a (y, x) MATCH FULL

statement ok
INSERT INTO a (x, y) VALUES ('x1', 'y1')

# These statements should all fail because this uses MATCH FULL.
statement error missing value for column "a_y" in multi-part foreign key
INSERT INTO b (a_x) VALUES ('x1')

statement error missing value for column "a_x" in multi-part foreign key
INSERT INTO b (a_y) VALUES ('y1')

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
INSERT INTO b (a_y, a_x) VALUES ('y1', NULL)

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
INSERT INTO b (a_y, a_x) VALUES (NULL, 'x1')

# These next two statements should still be allowed.
statement ok
INSERT INTO b (a_x, a_y) VALUES ('x1', 'y1')

statement ok
INSERT INTO b (a_x, a_y) VALUES (NULL, NULL)

statement ok
ALTER TABLE b VALIDATE CONSTRAINT fk_ref

statement ok
DROP TABLE b, a

# Test composite key with three columns.
statement ok
CREATE TABLE a (
  x STRING NULL
 ,y STRING NULL
 ,z STRING NULL
 ,CONSTRAINT "primary" PRIMARY KEY (z, y, x)
);

statement ok
CREATE TABLE b (
  a_y STRING NULL
 ,a_x STRING NULL
 ,a_z STRING NULL
);

# Add the constraint separately so that it's unvalidated, so we can test VALIDATE CONSTRAINT.
statement ok
ALTER TABLE b ADD CONSTRAINT fk_ref FOREIGN KEY (a_z, a_y, a_x) REFERENCES a (z, y, x) MATCH FULL

statement ok
INSERT INTO a (x, y, z) VALUES ('x1', 'y1', 'z1')

# These statements should all fail because this uses MATCH FULL.
statement error missing values for columns \["a_y" "a_z"\] in multi-part foreign key
INSERT INTO b (a_x) VALUES ('x1')

statement error missing values for columns \["a_x" "a_z"\] in multi-part foreign key
INSERT INTO b (a_y) VALUES ('y1')

statement error missing values for columns \["a_x" "a_y"\] in multi-part foreign key
INSERT INTO b (a_z) VALUES ('z1')

statement error missing value for column "a_z" in multi-part foreign key
INSERT INTO b (a_x, a_y) VALUES ('x1', 'y1')

statement error missing value for column "a_z" in multi-part foreign key
INSERT INTO b (a_x, a_y) VALUES (NULL, 'y1')

statement error missing value for column "a_z" in multi-part foreign key
INSERT INTO b (a_x, a_y) VALUES ('x1', NULL)

statement error missing value for column "a_y" in multi-part foreign key
INSERT INTO b (a_x, a_z) VALUES ('x1', 'z1')

statement error missing value for column "a_y" in multi-part foreign key
INSERT INTO b (a_x, a_z) VALUES (NULL, 'z1')

statement error missing value for column "a_y" in multi-part foreign key
INSERT INTO b (a_x, a_z) VALUES ('x1', NULL)

statement error missing value for column "a_x" in multi-part foreign key
INSERT INTO b (a_y, a_z) VALUES ('y1', 'z1')

statement error missing value for column "a_x" in multi-part foreign key
INSERT INTO b (a_y, a_z) VALUES (NULL, 'z1')

statement error missing value for column "a_x" in multi-part foreign key
INSERT INTO b (a_y, a_z) VALUES ('y1', NULL)

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
INSERT INTO b (a_x, a_y, a_z) VALUES ('x1', NULL, NULL)

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, 'y1', NULL)

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, NULL, 'z1')

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
INSERT INTO b (a_x, a_y, a_z) VALUES ('x1', 'y1', NULL)

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
INSERT INTO b (a_x, a_y, a_z) VALUES ('x1', NULL, 'z1')

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, 'y1', 'z1')

# This statement should still be allowed.
statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, NULL, NULL)

statement ok
ALTER TABLE b VALIDATE CONSTRAINT fk_ref

statement ok
DROP TABLE b, a

subtest Composite_Full_Validate_Constraint_Invalid
# Test VALIDATE CONSTRAINT by inserting invalid rows before the constraint is added, one at a time.

statement ok
CREATE TABLE a (
  x STRING NULL
 ,y STRING NULL
 ,z STRING NULL
 ,CONSTRAINT "primary" PRIMARY KEY (z, y, x)
);

statement ok
CREATE TABLE b (
  a_y STRING NULL
 ,a_x STRING NULL
 ,a_z STRING NULL
 ,INDEX idx (a_z, a_y, a_x)
);

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES ('x1', NULL, NULL)

statement ok
ALTER TABLE b ADD CONSTRAINT fk_ref FOREIGN KEY (a_z, a_y, a_x) REFERENCES a (z, y, x) MATCH FULL

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
ALTER TABLE b VALIDATE CONSTRAINT fk_ref

statement ok
TRUNCATE b

statement ok
ALTER TABLE b DROP CONSTRAINT fk_ref

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, 'y1', NULL)

statement ok
ALTER TABLE b ADD CONSTRAINT fk_ref FOREIGN KEY (a_z, a_y, a_x) REFERENCES a (z, y, x) MATCH FULL

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
ALTER TABLE b VALIDATE CONSTRAINT fk_ref

statement ok
TRUNCATE b

statement ok
ALTER TABLE b DROP CONSTRAINT fk_ref

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, NULL, 'z1')

statement ok
ALTER TABLE b ADD CONSTRAINT fk_ref FOREIGN KEY (a_z, a_y, a_x) REFERENCES a (z, y, x) MATCH FULL

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
ALTER TABLE b VALIDATE CONSTRAINT fk_ref

statement ok
TRUNCATE b

statement ok
ALTER TABLE b DROP CONSTRAINT fk_ref

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES ('x1', 'y1', NULL)

statement ok
ALTER TABLE b ADD CONSTRAINT fk_ref FOREIGN KEY (a_z, a_y, a_x) REFERENCES a (z, y, x) MATCH FULL

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
ALTER TABLE b VALIDATE CONSTRAINT fk_ref

statement ok
TRUNCATE b

statement ok
ALTER TABLE b DROP CONSTRAINT fk_ref

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES ('x1', NULL, 'z1')

statement ok
ALTER TABLE b ADD CONSTRAINT fk_ref FOREIGN KEY (a_z, a_y, a_x) REFERENCES a (z, y, x) MATCH FULL

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
ALTER TABLE b VALIDATE CONSTRAINT fk_ref

statement ok
TRUNCATE b

statement ok
ALTER TABLE b DROP CONSTRAINT fk_ref

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES (NULL, 'y1', 'z1')

statement ok
ALTER TABLE b ADD CONSTRAINT fk_ref FOREIGN KEY (a_z, a_y, a_x) REFERENCES a (z, y, x) MATCH FULL

statement error foreign key violation: MATCH FULL does not allow mixing of null and nonnull values
ALTER TABLE b VALIDATE CONSTRAINT fk_ref

statement ok
TRUNCATE b

statement ok
ALTER TABLE b DROP CONSTRAINT fk_ref

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES ('x2', 'y1', 'z1')

statement ok
ALTER TABLE b ADD CONSTRAINT fk_ref FOREIGN KEY (a_z, a_y, a_x) REFERENCES a (z, y, x) MATCH FULL

statement error foreign key violation: "b" row a_z='z1', a_y='y1', a_x='x2' has no match in "a"
ALTER TABLE b VALIDATE CONSTRAINT fk_ref

statement ok
TRUNCATE b

statement ok
ALTER TABLE b DROP CONSTRAINT fk_ref

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES ('x2', 'y2', 'z1')

statement ok
ALTER TABLE b ADD CONSTRAINT fk_ref FOREIGN KEY (a_z, a_y, a_x) REFERENCES a (z, y, x) MATCH FULL

statement error foreign key violation: "b" row a_z='z1', a_y='y2', a_x='x2' has no match in "a"
ALTER TABLE b VALIDATE CONSTRAINT fk_ref

statement ok
TRUNCATE b

statement ok
ALTER TABLE b DROP CONSTRAINT fk_ref

statement ok
INSERT INTO b (a_x, a_y, a_z) VALUES ('x2', 'y2', 'z2')

statement ok
ALTER TABLE b ADD CONSTRAINT fk_ref FOREIGN KEY (a_z, a_y, a_x) REFERENCES a (z, y, x) MATCH FULL

statement error foreign key violation: "b" row a_z='z2', a_y='y2', a_x='x2' has no match in "a"
ALTER TABLE b VALIDATE CONSTRAINT fk_ref

statement ok
DROP TABLE b, a

subtest auto_add_fk_with_composite_index_to_empty_table

statement ok
CREATE TABLE parent_composite_index (a_id INT NOT NULL, b_id INT NOT NULL, PRIMARY KEY (a_id, b_id))

statement ok
CREATE TABLE child_composite_index (id SERIAL NOT NULL, parent_a_id INT, parent_b_id INT, PRIMARY KEY (id))

# The (composite) index needed for the fk constraint is automatically added because the table is empty
statement ok
ALTER TABLE child_composite_index ADD CONSTRAINT fk_id FOREIGN KEY (parent_a_id, parent_b_id) REFERENCES parent_composite_index;

statement ok
INSERT INTO parent_composite_index VALUES (100, 200)

statement ok
INSERT INTO child_composite_index VALUES (1, 100, 200)

statement error foreign key violation: value \[100 300\] not found in parent_composite_index@primary \[a_id b_id\]
INSERT INTO child_composite_index VALUES (2, 100, 300)

statement ok
DROP TABLE child_composite_index, parent_composite_index

subtest auto_add_fk_to_nonempty_table_error

statement ok
CREATE TABLE nonempty_a (id SERIAL NOT NULL, self_id INT, b_id INT NOT NULL, PRIMARY KEY (id))

statement ok
CREATE TABLE nonempty_b (id SERIAL NOT NULL, PRIMARY KEY (id))

statement ok
INSERT INTO nonempty_b VALUES (1), (2), (3);

statement ok
INSERT INTO nonempty_a VALUES (1, NULL, 1)

# Fails because self_id is not indexed, and an index will not be automatically created because the table is nonempty
statement error foreign key requires an existing index on columns \("self_id"\)
ALTER TABLE nonempty_a ADD CONSTRAINT fk_self_id FOREIGN KEY (self_id) REFERENCES nonempty_a;

statement ok
CREATE INDEX ON nonempty_a (self_id)

# This now succeeds with the manually added index
statement ok
ALTER TABLE nonempty_a ADD CONSTRAINT fk_self_id FOREIGN KEY (self_id) REFERENCES nonempty_a;

# Fails because b_id is not indexed, and an index will not be automatically created because the table is nonempty
statement error foreign key requires an existing index on columns \("b_id"\)
ALTER TABLE nonempty_a ADD CONSTRAINT fk_b FOREIGN KEY (b_id) REFERENCES nonempty_b;

statement ok
CREATE INDEX ON nonempty_a (b_id)

# This now succeeds with the manually added index
statement ok
ALTER TABLE nonempty_a ADD CONSTRAINT fk_b FOREIGN KEY (b_id) REFERENCES nonempty_b;

statement ok
DROP TABLE nonempty_a, nonempty_b

subtest auto_add_fk_index_name_collision

statement ok
CREATE TABLE parent_name_collision (id SERIAL NOT NULL, PRIMARY KEY (id))

statement ok
CREATE TABLE child_name_collision (id SERIAL NOT NULL, parent_id INT, other_col INT)

statement ok
CREATE INDEX child_name_collision_auto_index_fk_id ON child_name_collision (other_col)

# Testing the unusual case where an index already exists that has the same name
# as the index to be auto-generated when adding a fk constraint to an empty
# table (but the existing index is not on the referencing column), in which
# case the ALTER TABLE will fail due to the name collision.
statement error duplicate index name: "child_name_collision_auto_index_fk_id"
ALTER TABLE child_name_collision ADD CONSTRAINT fk_id FOREIGN KEY (parent_id) references parent_name_collision

subtest auto_add_fk_duplicate_cols_error

statement ok
CREATE TABLE parent (a_id INT, b_id INT, PRIMARY KEY (a_id, b_id))

statement ok
CREATE TABLE child_duplicate_cols (id INT, parent_id INT, PRIMARY KEY (id))

# The fk constraint is invalid because it has duplicate columns, so automatically adding the index fails
statement error index \"child_duplicate_cols_auto_index_fk\" contains duplicate column \"parent_id\"
ALTER TABLE child_duplicate_cols ADD CONSTRAINT fk FOREIGN KEY (parent_id, parent_id) references parent

statement ok
DROP TABLE parent, child_duplicate_cols

# Check that a FK cannot be added to a column being backfilled.
# If this behavior is changed you should create a test similar to
# TestCRUDWhileColumnBackfill to test that CRUD operations operating
# with FK relationships work correctly over NON NULL columns that
# are still being backfilled.
subtest cannot_add_fk_on_col_needing_backfill

statement ok
CREATE TABLE parentid (
    k INT NOT NULL PRIMARY KEY,
    v INT NOT NULL
);

statement ok
CREATE TABLE childid (
    id INT NOT NULL PRIMARY KEY
);

# Make tables non-empty.
statement ok
INSERT INTO parentid (k, v) VALUES (0, 1); INSERT INTO childid (id) VALUES (2);

statement error column \"id\" does not exist
BEGIN; ALTER TABLE parentid ADD id INT NOT NULL AS (k + 2) STORED; ALTER TABLE childid ADD CONSTRAINT fk_id FOREIGN KEY (id) REFERENCES parentid (id);

statement ok
ROLLBACK;

statement error adding a REFERENCES constraint while the column is being added not supported
BEGIN; ALTER TABLE childid ADD id2 INT UNIQUE NOT NULL DEFAULT 0; ALTER TABLE childid ADD CONSTRAINT fk_id FOREIGN KEY (id2) REFERENCES parentid (k);

statement ok
ROLLBACK;

subtest dont_check_nulls
# Make sure that nulls are never checked while executing FK constraints.

statement ok
CREATE TABLE t1(x INT UNIQUE)

statement ok
INSERT INTO t1(x) VALUES (1), (null)

statement ok
CREATE TABLE t2(
  x INT REFERENCES t1(x)
)

statement ok
INSERT INTO t2(x) VALUES (1), (null)

statement ok
DELETE FROM t1 WHERE x IS NULL

statement ok
DROP TABLE t2, t2 CASCADE
