登录
首页 >  Golang >  Go问答

使用golang批量查询创建TimescaleDB的超级表

来源:stackoverflow

时间:2024-02-13 20:45:24 126浏览 收藏

Golang不知道大家是否熟悉?今天我将给大家介绍《使用golang批量查询创建TimescaleDB的超级表》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!

问题内容

我的golang服务需要在timescale db中动态创建一个超表。我使用 pgx 驱动程序。我的代码如下(我删除了错误处理):

func (s *storage) createhypertablebatch(ctx context.context, tablename string) error {

    indexname := "idx_" + tablename

    conn, _ := s.pool.acquire(ctx)
    defer conn.release()

    b := pgx.batch{}

    b.queue(fmt.sprintf(`create table if not exists public.%s (
    ts timestamptz primary key not null,
    data jsonb not null
);
    `, tablename))

    b.queue(fmt.sprintf(`create index if not exists public.%s on public.%s using gin (data);`, indexname, tablename))

    b.queue(fmt.sprintf(`select create_hypertable('%s', 'ts', if_not_exists => true);`, tablename))

    batchresult := conn.sendbatch(ctx, &b)
    defer func() { _ = batchresult.close() }()

    _, _ = batchresult.exec()

    return nil
}

exec() 返回错误

failed to create tabletwo: failed to run query: error: relation "tabletwo" does not exist (sqlstate 42p01)

我将架构名称添加到查询中(如您所见),但这没有帮助。如果我将其分成三个查询,一切都会正常

func (s *Storage) CreateHyperTable(ctx context.Context, tableName string) error {

    indexName := "idx_" + tableName

    conn, _ := s.pool.Acquire(ctx)
    defer conn.Release()

    _, _ := conn.Exec(ctx, fmt.Sprintf(`create table if not exists %s (
    ts timestamptz primary key not null,
    data jsonb not null
);
`, tableName))

     _, _ := conn.Exec(ctx, fmt.Sprintf(`create index if not exists %s on %s using gin (data);`, indexName, tableName))

    _, _ := conn.Exec(ctx, fmt.Sprintf(`select create_hypertable('%s', 'ts', if_not_exists => true);`, tableName))

    return nil
}

我认为问题是 timescale 数据库需要创建一个普通表并提交来创建一个超级表。这是正确的还是有什么问题?有人遇到过这个问题吗?您是如何解决的?


解决方案


无法直接回答您的 pgx 问题,但是,是的,您需要先创建一个表,然后再尝试创建超表。因此,我尝试将前者作为单独的事务进行,看看是否成功。

终于介绍完啦!小伙伴们,这篇关于《使用golang批量查询创建TimescaleDB的超级表》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

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