我在postgres中有一个表,其UUID字段类型必须唯一,但可以为空

带着一张桌子&像这样的模型

CREATE TABLE IF NOT EXISTS asdf(
    id bigserial primary key,
    name varchar(255) NOT NULL,
    key uuid unique,
    created_at timestamptz,
    updated_at timestamptz
);

go模型定义为

type Asdf struct {
    ID          uint64    `json:"id" gorm:"type:uuid;column:id"`
    Name        string    `json:"name" gorm:"column:name"`
    Key         uuid.UUID `json:"key" gorm:"column:key"`
    CreatedAt   time.Time `json:"created_at" gorm:"column:created_at"`
    UpdatedAt   time.Time `json:"updated_at" gorm:"column:updated_at"`
}

result := db.Connect().Create(asdf.Asdf{ID:123,Name:"This is the name"})

并将以下sql查询打印到终端

INSERT INTO "asdf" ("id","name","key","created_at","updated_at")
VALUES('123','This is the name','00000000-0000-0000-0000-000000000000','2022-04-27 03:41:49.338','2022-04-27 03:41:49.338')

它将模型插入到数据库中,将00000000-0000-0000-0000-000000000000作为key值,而不是空值

我还注意到这种情况发生在字符串类型中,它插入了一个空字符串'',而不是NULL

如何使gorm insert NULL而不是零/空字符串作为值?

推荐答案

try 将字段类型更改为指针类型:

type Asdf struct {
    ID          uint64     `json:"id" gorm:"type:uuid;column:id"`
    Name        string     `json:"name" gorm:"column:name"`
    Key         *uuid.UUID `json:"key" gorm:"column:key"`
    CreatedAt   time.Time  `json:"created_at" gorm:"column:created_at"`
    UpdatedAt   time.Time  `json:"updated_at" gorm:"column:updated_at"`
}

显然,你也必须调整你的go代码(例如:判断是否为record.Key != nil,访问*record.Key而不是record.Key,等等)


我认为gorm也尊重常规sql接口,因此您也可以try 定义一个自定义类型,该类型实现:

  • sql.Scanner将sql上的null变为""->;go 转化,
  • driver.Valuer(来自sql/driver套餐)转为""null;sql转换.

我还没有测试过,所以你得自己试试.

Postgresql相关问答推荐

使函数内部动态插入更具可读性

列不明确

使用postgres在go测试容器中使用tern迁移

如何将 SELECT 查询的结果插入表中?

在Power BI和Excel中将日期格式化为正确格式

MERGE 语句的锁定级别

当我写 SELECT ~1;在 Postgresql 上它给了我 -2 结果.这是什么原因?它一直持续〜4和-5等

获取 OperationalError: FATAL: sorry, too many clients already using psycopg2

从 Postgres 数据库中删除所有函数

如果 Column1 不为空,则按 Column1 排序,否则按 Column2 排序

为什么 sqlalchemy 的默认列值不起作用

从 PostgreSQL 中的时间戳获取日期

Postgis 中 2 点之间的距离,单位为 4326 米

返回 array_agg() 中的第一个元素

在 PostgreSQL 数组中查找值的位置

SQL 基本类型:integer vs int?

按任意时间间隔计算行数的最佳方法

Oracle 相当于 Postgres 的 DISTINCT ON?

如何查询前 10 行,下一次从表中查询其他 10 行

GRANT SELECT 特权使用一个语句对所有序列