-- Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
-- and the EPL 1.0 (https://h2database.com/html/license.html).
-- Initial Developer: H2 Group
--

CREATE TABLE TEST(A INT, B INT, C INT);
> ok

CREATE UNIQUE INDEX TEST_IDX ON TEST(C) INCLUDE(B);
> ok

INSERT INTO TEST VALUES (10, 20, 1), (11, 20, 2), (12, 21, 3);
> update count: 3

INSERT INTO TEST VALUES (13, 22, 1);
> exception DUPLICATE_KEY_1

SELECT INDEX_NAME, TABLE_NAME, INDEX_TYPE_NAME FROM INFORMATION_SCHEMA.INDEXES WHERE INDEX_NAME = 'TEST_IDX';
> INDEX_NAME TABLE_NAME INDEX_TYPE_NAME
> ---------- ---------- ---------------
> TEST_IDX   TEST       UNIQUE INDEX
> rows: 1

SELECT INDEX_NAME, TABLE_NAME, COLUMN_NAME, ORDINAL_POSITION, IS_UNIQUE FROM INFORMATION_SCHEMA.INDEX_COLUMNS
    WHERE INDEX_NAME = 'TEST_IDX' ORDER BY ORDINAL_POSITION;
> INDEX_NAME TABLE_NAME COLUMN_NAME ORDINAL_POSITION IS_UNIQUE
> ---------- ---------- ----------- ---------------- ---------
> TEST_IDX   TEST       C           1                TRUE
> TEST_IDX   TEST       B           2                FALSE
> rows (ordered): 2

SELECT DB_OBJECT_SQL('INDEX', 'PUBLIC', 'TEST_IDX');
>> CREATE UNIQUE NULLS DISTINCT INDEX "PUBLIC"."TEST_IDX" ON "PUBLIC"."TEST"("C" NULLS FIRST) INCLUDE("B" NULLS FIRST)

ALTER TABLE TEST ADD CONSTRAINT TEST_UNI_C UNIQUE(C);
> ok

SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE, TABLE_NAME, INDEX_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'TEST';
> CONSTRAINT_NAME CONSTRAINT_TYPE TABLE_NAME INDEX_NAME
> --------------- --------------- ---------- ----------
> TEST_UNI_C      UNIQUE          TEST       TEST_IDX
> rows: 1

SELECT CONSTRAINT_NAME, TABLE_NAME, COLUMN_NAME, ORDINAL_POSITION FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
    WHERE CONSTRAINT_NAME = 'TEST_UNI_C';
> CONSTRAINT_NAME TABLE_NAME COLUMN_NAME ORDINAL_POSITION
> --------------- ---------- ----------- ----------------
> TEST_UNI_C      TEST       C           1
> rows: 1

EXPLAIN SELECT B, C FROM TEST ORDER BY C, B;
>> SELECT "B", "C" FROM "PUBLIC"."TEST" /* PUBLIC.TEST_IDX */ ORDER BY 2, 1 /* index sorted */

DROP TABLE TEST;
> ok

CREATE TABLE TEST(A INT, B INT, C INT);
> ok

CREATE UNIQUE INDEX TEST_IDX_A_B ON TEST(A) INCLUDE (B);
> ok

CREATE UNIQUE INDEX TEST_IDX_A ON TEST(A);
> ok

CREATE UNIQUE INDEX TEST_IDX_A_B_C ON TEST(A) INCLUDE (B, C);
> ok

ALTER TABLE TEST ADD CONSTRAINT UNI_TEST_A UNIQUE(A);
> ok

SELECT INDEX_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_NAME = 'UNI_TEST_A';
>> TEST_IDX_A

DROP TABLE TEST;
> ok
