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

I use yaml, but I think it is almost the same as xml or json. I found that you can use addForeignKeyConstraint, but I want to add a constraint when creating the table without modifying the existing table. How should I do it? 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
+4
source share
1 answer

I never used the YAML format, but in the XML change log you can do this:

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

Equivalent YAML should be something like this:

- column:
    name: user_id
    type: int
    constraints:
        nullable: false
        foreignKeyName: fk_questions_author
        references: users(id)
+8
source

Source: https://habr.com/ru/post/1656373/


All Articles