使用 Liquibase、postgreSQL 和序列插入新数据

问题描述 投票:0回答:4

如果我的 id 是连续的,如何使用 Liquibase 为 PostgreSQL 进行插入。我尝试以下方法:

<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>

我尝试用

<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>

错误是:

错误:“id”列中的空值违反了非空约束

postgresql liquibase
4个回答
10
投票

我找到了使用序列(无默认)id 在 Postgres 中插入数据的解决方案

<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>

1
投票

查看

ColumnConfig
文档。您应该能够设置
valueComputed
属性并在其中调用 Postgres 函数:

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

1
投票

对于我来说,我必须先创建一个序列,然后使用它。

<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>

这将通过 Liquibase 创建 SQL(我正在使用 v3.8.1)

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

0
投票

使用 liquibase 现在的方法是

defaultValueSequenceNext

<createSequence
  schemaName="YOUR_SCHEMA"
  sequenceName="YOUR_SEQUENCE"
  dataType="bigint"
  startValue="1"
  incrementBy="1"
  cycle="false"/>
<createTable schemaName="YOUR_SCHEMA" tableName="YOUR_TABLE">
<column name="ID" type="bigint" defaultValueSequenceNext="YOUR_SEQUENCE">
  <constraints nullable="false" primaryKey="true" primaryKeyName="PK_YOUR_TABLE"/>
</column>
</createTable>

对于插入,就像上面所说的<column name="id" valueSequenceNext="YOUR_SEQUENCE"/>

那样
https://stackoverflow.com/users/3499894/renzo-parente

© www.soinside.com 2019 - 2024. All rights reserved.