【问题标题】:Create TimescaleDB hypertable using golang batch query使用 golang 批量查询创建 TimescaleDB 超表
【发布时间】:2021-03-05 08:11:54
【问题描述】:

我的 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 db 需要创建一个普通表并提交以创建一个超表。是对的还是有什么问题?有没有人遇到过这个问题,你是怎么解决的?

【问题讨论】:

    标签: go timescaledb pgx


    【解决方案1】:

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

    【讨论】:

    • 是的,它有效,正如您在我的第二个实现中看到的那样。我只是想知道更多。
    猜你喜欢
    • 2021-02-03
    • 2017-05-15
    • 2019-11-01
    • 1970-01-01
    • 2020-08-14
    • 2014-06-27
    • 1970-01-01
    • 2015-10-14
    相关资源
    最近更新 更多