0

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

4

1 回答 1

1

Can't give a direct answer on your pgx question, but yes, you need to create a table first before trying to create a hypertable. So I'd try to do the former as a separate transaction and see if that succeeeds.

于 2020-11-22T15:56:41.650 回答