登录
首页 >  Golang >  Go问答

使用 Jack/PGX 更新复合类型的 PSQL 行

来源:stackoverflow

时间:2024-02-08 21:54:21 461浏览 收藏

golang学习网今天将给大家带来《使用 Jack/PGX 更新复合类型的 PSQL 行》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

我正在尝试使用 jackc/pgx 将 postgresql 中的数据插入/更新到具有复合类型列的表中。这是写为 golan 结构体的表类型:

// added this struct as a types in psql
type daypricemodel struct {
    date                time.time `json:"date"`
    high                float32   `json:"high"`
    low                 float32   `json:"low"`
    open                float32   `json:"open"`
    close               float32   `json:"close"`
}

// 我的表格中的 2 列

type securitiespricehistorymodel struct {
    symbol  string          `json:"symbol"`
    history []daypricemodel `json:"history"`
}

history 是一个复合类型数组,我在 psql 中将其定义为 daypricemodel。我想使用 jack/pgx 在 golang 中向 history 添加一个新元素

到目前为止我已经编写了给定的代码:

// The code for newType was generated by ChatGPT so it might or might not be correct. Feel free to overwrite this part.
newType, _ := pgtype.NewCompositeType("day_price_model", []pgtype.CompositeTypeField{
            {Name: "date", OID: pgtype.DateOID},
            {Name: "high", OID: pgtype.Float4OID},
            {Name: "low", OID: pgtype.Float4OID},
            {Name: "open", OID: pgtype.Float4OID},
            {Name: "close", OID: pgtype.Float4OID},
        }, (*pgtype.ConnInfo)(pool.Config().ConnConfig.TLSConfig.ClientCAs))

_, err = pool.Exec(context.Background(), `UPDATE equity.securities_price_history
SET history = $1::equity.day_price[] || history WHERE symbol = $2`,
composite_value_here, "something") // unable to form the composite_value_here variable

使用 jack/pgx,如何从复合类型创建新的复合值以写入 psql 查询。


正确答案


要求

  • 复合类型使用 psql 定义
  • 更新/插入复合类型数组的列
  • 使用 github.com/jackc/pgx/v5

最简单的方法是使用 pgx.loadtype()/pgx.registertype() 并使用数据库中已定义的复合类型。

由于我们有一个复合类型数组,因此我们需要同时对复合类型本身和数组类型执行此操作(您可以分别使用 select 'day_price_model'::regtype::oid; 进行检查 select 'day_price_model[] '::regtype::oid; oid 不同)。

对于注册,我们可以从 v5/pgtype 文档中获取 registerdatatypes.

假设类型是使用 psql 创建的,如下所示:

create type day_price_model as (
    date date,
    high float,
    low  float,               
    open float,
    close float
);

registerdatatypes 可能看起来像:

func registerdatatypes(ctx context.context, conn *pgx.conn) error {
    datatypenames := []string{
        "day_price_model",
        "day_price_model[]",
    }

    for _, typename := range datatypenames {
        datatype, err := conn.loadtype(ctx, typename)
        if err != nil {
            return err
        }
        conn.typemap().registertype(datatype)
    }

    return nil
}

请注意上述两种类型的数据类型名称。

给出一些模拟数据:

history := []daypricemodel{
        {time.now().adddate(0, 0, -2), 4, 1, 2, 3},
        {time.now().adddate(0, 0, -1), 10, 5, 6, 7},
    }

insert 很简单:

insertstmt := `insert into securities_price_history values ($1, $2)`
_, err = conn.exec(context.background(), insertstmt, "something", history)

update 类似这样:

updatestmt := `update securities_price_history set history = $1 where symbol = $2`
_, err = conn.exec(context.background(), updatestmt, newhistory, "something")

测试

为了拥有一个完整的、独立的测试示例,考虑到上述几点,我们需要一个数据库和一个小型测试程序。

数据库

使用 psql 的测试数据库可以像这样创建:

create database equity;

\c equity

create type day_price_model as (
    date date,
    high float,
    low  float,               
    open float,
    close float
);

create table securities_price_history (
    symbol varchar,
    history day_price_model[]
);

go 程序

65bdbe8bd0爸爸

测试程序的输出为:

after insert: &{something [{2023-03-10 00:00:00 +0000 UTC 4 1 2 3} {2023-03-11 00:00:00 +0000 UTC 10 5 6 7}]}
after update: &{something [{2023-03-10 00:00:00 +0000 UTC 4 1 2 3} {2023-03-11 00:00:00 +0000 UTC 10 5 6 7} {2023-03-12 00:00:00 +0000 UTC 6 3 4 5}]}

可以看到,已经插入了一条记录,更新已经成功执行,因为数组中已经有了三个元素,可以从数据库中读取数据了。

如果您想重复尝试,显然应该再次从表中删除数据,例如与 psql。但是,这应该只是一个尽可能小的示例,以便使用本地数据库运行示例。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>