Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ALTER TABLE CREATE CONSTRAINT IF NOT EXIST possible?

I have an application which starts (AppStarter) a web server with a web application. The Web Application has migration scripts (flyway).

I want to write some data from AppStarter through JDBC in a table. But I want to create the table if it does not exist. The table also has some constraints.

Within the AppStarter I execute following command:

CREATE CACHED TABLE PUBLIC.CORE_USERROLE_TO_PARAMETER (
    ID VARCHAR(32) PRIMARY KEY NOT NULL,
    VERSION INTEGER,
    USER_ID VARCHAR(32)NOT NULL,
    ROLE_ID VARCHAR(32) NOT NULL,
    PARAMETER VARCHAR(255) NOT NULL
);

ALTER TABLE PUBLIC.CORE_USERROLE_TO_PARAMETER ADD CONSTRAINT PUBLIC.CURTBP_USER_ID FOREIGN KEY(USER_ID) REFERENCES PUBLIC.CORE_USER(ID) NOCHECK;
ALTER TABLE PUBLIC.CORE_USERROLE_TO_PARAMETER ADD CONSTRAINT PUBLIC.CURTBP_ROLE_ID FOREIGN KEY(ROLE_ID) REFERENCES PUBLIC.CORE_USER_ROLE(ID) NOCHECK;

The web app also reads some information from this table and creates the tables. Now I have a sql migration script

CREATE CACHED TABLE IF NOT EXISTS PUBLIC.CORE_USERROLE_TO_PARAMETER (
    ID VARCHAR(32) PRIMARY KEY NOT NULL,
    VERSION INTEGER,
    USER_ID VARCHAR(32)NOT NULL,
    ROLE_ID VARCHAR(32) NOT NULL,
    PARAMETER VARCHAR(255) NOT NULL
);

But how do I create the constraint only if they does not already exist?

Thanks in advance

Currently I can get if the constraints exists with

select * from INFORMATION_SCHEMA.CONSTRAINTS WHERE CONSTRAINT_NAME='CURTRP_USER_ID'

but how do I build this into a if query with H2

Edit: I could move the constraint part in total to the migration script, but this seems somehow wrong.

I am working with H2 Database.

like image 374
kism3t Avatar asked Nov 07 '22 22:11

kism3t


1 Answers

Following my comment, this should be possible:

ALTER TABLE PUBLIC.CORE_USERROLE_TO_PARAMETER
  ADD CONSTRAINT IF NOT EXISTS PUBLIC.CURTBP_USER_ID
    FOREIGN KEY(USER_ID) REFERENCES PUBLIC.CORE_USER(ID) NOCHECK;

ALTER TABLE PUBLIC.CORE_USERROLE_TO_PARAMETER
  ADD CONSTRAINT IF NOT EXISTS PUBLIC.CURTBP_ROLE_ID
    FOREIGN KEY(ROLE_ID) REFERENCES PUBLIC.CORE_USER_ROLE(ID) NOCHECK;
like image 177
Sonata Avatar answered Nov 14 '22 22:11

Sonata