flexmeasures.data.migration_utils

Helpers for database migrations that change indexes on a table FlexMeasures keeps writing to, such as timed_belief.

On a plain table, such migrations build and drop indexes CONCURRENTLY, so that writes can go on meanwhile. TimescaleDB refuses that on a hypertable (see flexmeasures db-ops enable-timescaledb), as each chunk has its own copy of every index. These helpers leave out CONCURRENTLY on a hypertable, and build a new index one chunk at a time instead (timescaledb.transaction_per_chunk), so that a migration works on both, and blocks writes to a hypertable only one chunk at a time.

Call them inside op.get_context().autocommit_block(), as neither way of building an index may run inside a transaction.

Functions

flexmeasures.data.migration_utils.create_index_online(name: str, schema: str, table_name: str, columns: Sequence[str], if_not_exists: bool = False) → None

Create a (non-unique) index, letting writes to the table go on meanwhile, or on a hypertable, all but those to one chunk at a time.

TimescaleDB builds unique indexes on a hypertable neither concurrently nor per chunk, so a migration that needs one there has to build it in a transaction, blocking writes until it is done.

Parameters:
  • name – the index name, unquoted; the index is created in the schema of its table.

  • schema – the table’s schema, unquoted.

  • table_name – the table name, unquoted.

  • columns – the indexed column names, unquoted.

flexmeasures.data.migration_utils.drop_index_online(qualified_name: str, schema: str, table_name: str) → None

Drop an index if it exists, letting writes to the table go on meanwhile, except on a hypertable.

Dropping an index from a hypertable cannot be done concurrently, but takes only as long as removing the files of each chunk’s copy of it.

Parameters:
  • qualified_name – the index’s schema-qualified name, quoted as SQL needs it.

  • schema – the schema of the index’s table, unquoted.

  • table_name – the name of the index’s table, unquoted.

flexmeasures.data.migration_utils.is_hypertable(schema: str, table_name: str) → bool

Whether the given table (with its schema unquoted) is a TimescaleDB hypertable.