Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a table with foreign key constraint in Liquibase?

Tags:

liquibase

I am using yaml, but I guess it is almost the same as xml or json. I found that you can use addForeignKeyConstraint, but I want to add the constraint at table creation, not altering an existing table. How should I do that? Can I do something like this?

  - changeSet:
      id: create_questions
      author: Author
      changes:
        - createTable:
            tableName: questions
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: user_id
                  type: int
                  constraints:
                    foreignKey:
                      referencedColumnNames: id
                      referencedTableName: users
                    nullable: false
              - column:
                  name: question
                  type: varchar(255)
                  constraints:
                    nullable: false
like image 684
godzsa Avatar asked Sep 30 '16 14:09

godzsa


People also ask

How do you create a table in Liquibase?

To create a table for your database, follow these steps: Step 1: Add the createTable Change Type to your changeset with the needed attributes, as shown in the examples. Step 2: Deploy your changeset by running the update command. Now, you should see a new table.

What is deferrable in Liquibase?

NOT DEFERRABLE. This controls whether the constraint can be deferred. A constraint that is not deferrable will be checked immediately after every command. Checking of constraints that are deferrable may be postponed until the end of the transaction (using the SET CONSTRAINTS command).

Can a table contain multiple foreign key's?

A table can have multiple foreign keys based on the requirement.


1 Answers

I never used the YAML format, but in an XML changelog you can do this:

<column name="user_id" type="int">
   <constraints nullable="false" 
                foreignKeyName="fk_questions_author" 
                references="users(id)"/>
</column>

The equivalent YAML should be something like this:

- column:
    name: user_id
    type: int
    constraints:
        nullable: false
        foreignKeyName: fk_questions_author
        references: users(id)
like image 139
a_horse_with_no_name Avatar answered Oct 11 '22 11:10

a_horse_with_no_name