Insert new data using Liquibase, postgreSQL and sequence

Viewed 8011

How do I make an insert for PostgreSQL using Liquibase if my ids are sequential. I try with the following:

<changeSet author="rparente" id="service-1.1-2019-01-09-01">
        <insert tableName="tenant">
            <column name="id"defaultValueSequenceNext="hibernate_sequence"/>
            <column name="description" value="Prueba"/>
            <column name="name" value="antel"/>
            <column name="service_id" value="antel"/>
        </insert>
    </changeSet>

and I try with

<changeSet author="rparente" id="service-1.1-2019-01-09-01">
        <insert tableName="tenant">
            <column name="id"  value="nextval('hibernate_sequence')"/>
            <column name="description" value="Prueba"/>
            <column name="name" value="antel"/>
            <column name="service_id" value="antel"/>
        </insert>
    </changeSet>

The error is:

ERROR: null value in column "id" violates not-null constraint

3 Answers

I found the solution to insert data in Postgres with sequence (no default) ids

<changeSet author="author_name" id="service-1.1-2019-01-09-01"> 
    <insert tableName="tenant"> 
        <column name="id" valueSequenceNext="name_sequence"/> 
        <column name="description" value="TEST"/> 
        <column name="name" value="test"/> 
        <column name="service_id" value="testl"/> 
        <column name="status" value="ACTIVE"/> 
    </insert> 
</changeSet>

As for me, I have to create a sequence first and then use it.

<changeSet>
    <createSequence sequenceName="runtime_name_seq" dataType="bigint" incrementBy="1" maxValue="10000" minValue="1" startValue="1"/>
</changeSet>

<changeSet>
     <createTable tableName="runtime_name">
        <column name="id" type="INTEGER" defaultValueComputed="nextval('runtime_name_seq')">
            <constraints nullable="false" primaryKey="true" primaryKeyName="pk_runtime_name"/>
        </column>
    </createTable>
</changeSet>

This will create a SQL by Liquibase (v3.8.1 I am using)

CREATE TABLE public.runtime_name 
(
    index INTEGER DEFAULT nextval('runtime_name_seq') NOT NULL
)

Check out the ColumnConfig doc. You should be able to set a valueComputed property and in it call the Postgres function:

<column name="id"  valueComputed="nextval('hibernate_sequence')"/>
Related