godzsa godzsa - 2 months ago 31
YAML Question

How to create a table with foreign key constraint in 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

Answer

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)