Golang lib/pq PostgreSQL创建一个动态更新语句。

huangapple go评论87阅读模式
英文:

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...)。

另一种方法是使用类似gorpgorm的“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.

huangapple
  • 本文由 发表于 2014年8月2日 09:29:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/25090797.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定