insert 时,字段为 nil 该不该拼入字段名的问题 #2101
Labels
No Label
backport/done
backport/v1
blocked
db
oracle
db
sqlserver
duplicate
feature
cache
frontport/done
frontport/main
invalid
kind
breaking
kind
bug
kind
build
kind
dependencies
kind
docs
kind
driver
kind
enhancement
kind
feature
kind
performance
kind
proposal
kind
question
kind
refactor
kind
testing
need
feedback
need
test
proposal:accepted
RaspBerry Pi
regression
skip-changelog
upstream
wip
wontfix
No Milestone
No Assignees
1 Participants
Notifications
Due Date
No due date set.
Dependencies
No dependencies set.
Reference: xorm/xorm#2101
Loading…
Reference in New Issue
Block a user
No description provided.
Delete Branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
还有一个问题,insert 的时候,能不能通过类型的 Value() 看一下是否为 nil,如果为 nil 就不要拼 insert 的 sql 文了
现在的现象是,使用了类似 sql.NullSting 的类型,然后在定义 model 时直接使用了 sql.NullSting,而没用 *sql.NullSting
然后 new(Model),这个字段就必然不是 nil,但是它的 Value() 是 nil 啊,但是 insert sql 会把这个字段拼上,导致数据库如果不允许为 null,但是有默认值,也仍然无法 insert 成功
Originally posted by @fanybook in #2099 (comment)
@Lunny Xiao 现在 insert 分为两种
1)单条 insert
如果字段为 nil 仍然拼入字段名,例如: 数据库中不允许为空,但默认值是0
insert into (name, parent_id) values ('测试1', null) 就会报错
insert into (name) values ('测试1'),不会报错 parent_id 是 0
如果模型
parent_id 为 sql.NullInt64,那么即使数据库里有默认值,也必须在 insert 时,手动给字段赋值,否则就报错,这是因为 sql.NullInt64 的初始值 Value() 是 nil
方案1:用 “类型.Value() 看一下是否为 nil”,如果是 nil 则不拼入 insert 的 sql 文中
方案2:用 “类型.Value() 看一下是否为 nil”,如果是 nil 则看字段有没有默认值,有就把 nil 改为默认值,比如模型里 parent_id default(0) 那么 insert into (name, parent_id) values ('测试1', null) -> insert into (name, parent_id) values ('测试1', 0)
2)多条 insert 不好处理
方案1:不可行
方案2:可行
方案2 session_insert.go genInsertColumns 和 insertMultipleStruct
改成