Search code examples
postgresqlh2liquibaseuuid

liquibase auto generate UUID for multi database


I am trying to use liquibase to auto generate the UUID as the primary key. This post has provided some ideas for postgresql, which I am trying to use. Liquibase - insert rows with uuid

<property name="uuid_type" value="uuid" dbms="postgresql"/>
<property name="uuid_function" value="uid.uuid_generate_v4()" dbms="postgresql"/>

<column name="id" type="${uuid_type}" defaultValueComputed="${uuid_function}">
    <constraints nullable="false" unique="true" />
</column>

However, I need a solution to get this work alone with H2. I have seen someone suggest using the following, when using h2 on its own, but it can't share defaultValueComputed in the column definition (I am not sure there is a supported function for h2 that can be assigned to defaultValueComputed)

<property name="uuid_type" value="varchar(36)" dbms="h2"/>

Is there a way to support both Postgres and H2 in liquibase


Solution

  • Part of your question is asking if you can generate uuid in H2 right? I'm no expert, but it looks like you can: http://www.h2database.com/html/functions.html#random_uuid

    Second, you are asking if you can do this in liquibase similar to the way it is done targeting Postgres:

    <property name="uuid_type" value="uuid" dbms="postgresql"/>
    <property name="uuid_function" value="uid.uuid_generate_v4()" dbms="postgresql"/>
    
    <column name="id" type="${uuid_type}" defaultValueComputed="${uuid_function}">
        <constraints nullable="false" unique="true" />
    </column>
    

    Have you tried:

    <property name="uuid_type" value="uuid" dbms="h2"/>
    <property name="uuid_function" value="RANDOM_UUID()" dbms="h2"/>
    
    <column name="id" type="${uuid_type}" defaultValueComputed="${uuid_function}">
        <constraints nullable="false" unique="true" />
    </column>