如何将 NULL 值插入 UUID 而非零值
时间:2024-02-08
浏览:276
作者:佚名
在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《如何将 NULL 值插入 UUID 而非零值》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!
我在 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:"这就是名字"})
并将以下 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-000000000000as key 值而不是 null
我还注意到字符串类型会发生这种情况,它插入了一个空字符串 '' 而不是 null
如何让 gorm 插入 null 而不是零/空字符串作为值?
正确答案
尝试将字段类型更改为指针类型:
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 接口,因此您也可以尝试定义一个实现以下功能的自定义类型:
sql.Scanner在 sql -> go 转换上将null转换为"",driver.Valuer(来自sql/driver软件包)在 go -> sql 转换中将""转换为null。
我还没有测试过它,所以你必须自己尝试一下。
问题中没有指定你使用的包。如果您使用的是 satori/go.uuid,则可以使用 NullUUID type:
type asdf struct {
id uint64 `json:"id" gorm:"type:uuid;column:id"`
name string `json:"name" gorm:"column:name"`
nullablekey uuid.nulluuid `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"`
}
设置一个值:
key := uuid.NullUUID{
Value: id, // of type uuid.UUID
Valid: true
}
要保存 null,只需保存零值即可。 scan 和 value 方法均已定义。
理论要掌握,实操不能落!以上关于《如何将 NULL 值插入 UUID 而非零值》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
