英文:
Golang lib/pq postgresql create a dynamic update statement
问题
当成功提交用户详细信息后,我从客户端得到一个JSON。
由于某些元素未更新,可以跳过JSON中的某些元素。
在Golang服务器端,我定义了一个等效的结构体。
服务器成功地将JSON字节解组为结构体。
type user struct {
Id *int64 `json:",omitempty"`
Name *string `json:",omitempty"`
Age *int64 `json:",omitempty"`
}
根据可用的JSON元素,如何创建动态的更新语句?
例如,我可能只会得到Id和Age。我如何动态地创建更新语句,例如 update user set age = $1 where id = $2
?
另一次可能是Id和Name。
英文:
I get a JSON from a client on the successful submit of user details.
Some element in the JSON can be skipped since they were not updated.
On the Golang server side, I have an equivalent struct defined.
The server successfully marshals the JSON bytes into the struct.
type user struct {
Id *int64 `json:",omitempty"`
Name *string `json:",omitempty"`
Age *int64 `json:",omitempty"`
}
How do I create a dynamic update statement depending on the available JSON elements?
For example, I might get the Id and Age alone.
How can I create a update statement dynamically, like update user set age = $1 where id = $2
Another time it might be Id and Name.
答案1
得分: 2
如果你不想使用ORM,可以尝试使用类似Squirrel的SQL生成器,并在修改SQL语句之前检查每个参数:
import (
sq "github.com/lann/squirrel"
"fmt"
)
statement := sq.Update("user").Where(sq.Eq{"Id": &u.Id})
if &u.Name != nil {
statement = statement.Set("Name", "Jack")
}
sql, args, err := statement.ToSql()
fmt.Println(sql)
在某些情况下,你可能需要先查询数据库,以确保输入数据不会将列Name
显式设置为null(例如update user set Name = null
...)。
另一种方法是使用类似gorp或gorm的“ORM-ish”包,这两个包都可以正确处理SQL更新。
英文:
In case you don't want to use an ORM, try a SQL generator like Squirrel, and check every argument before modifying the sql statement:
import (
sq "github.com/lann/squirrel"
"fmt"
)
statement := sq.Update("user").Where(sq.Eq{"Id": &u.Id})
if &u.Name != nil {
statement = statement.Set("Name", "Jack")
}
sql, args, err := statement.ToSql()
fmt.Println(sql)
In some scenarios you may need to query the DB first to make sure the input data is not trying to explicitly set column ´Name´ to null (like update user set Name = null
...).
A different approach will be to use an 'ORM-ish' package like gorp or gorm, both should handle sql updates properly.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论