flexmeasures.data.services.timescaledb
Optional TimescaleDB support for the timed_belief table.
FlexMeasures runs on plain PostgreSQL, and nothing here is needed for it to work. Hosts whose PostgreSQL server ships TimescaleDB can convert timed_belief into a hypertable, partitioned into time chunks on event_start, of which the ones older than a given age are compressed. Queries do not change: a hypertable is still a table to SQLAlchemy and to timely-beliefs.
This is deliberately an explicit operation (see flexmeasures db-ops enable-timescaledb),
not a migration.
TimescaleDB’s own Docker images install the extension into every new database,
so the extension being present says nothing about whether a host chose this.
And converting a populated table moves every row into chunks under a lock that blocks writes,
which no host should get as a side effect of a routine flexmeasures db upgrade.
The way back (flexmeasures db-ops disable-timescaledb) copies the beliefs into a new plain table.
Queries and TimescaleDB’s functions are expressed with SQLAlchemy. The statements SQLAlchemy has no construct for (installing the extension, ANALYZE and the compression settings), are DDL elements bound to the timed_belief table, so that its name is quoted by SQLAlchemy rather than by hand.
Module Attributes
- flexmeasures.data.services.timescaledb.MINIMUM_VERSION = (2, 18)
The sensor_data_source trigger on timed_belief reads the inserted rows from a transition table (REFERENCING NEW TABLE), which hypertables only accept from TimescaleDB 2.18 on.
- flexmeasures.data.services.timescaledb.DEFAULT_CHUNK_TIME_INTERVAL = '30 days'
Chunks this long keep the number of chunks low (a query without a time range is planned against all of them), while the most recent chunk, with its indexes, still fits in memory on most hosts.
- flexmeasures.data.services.timescaledb.DEFAULT_COMPRESS_AFTER = '30 days'
Beliefs about events older than this are rarely rewritten on a live host, so they can be compressed.
- flexmeasures.data.services.timescaledb.COMPRESS_SEGMENT_BY = (Column('sensor_id', Integer(), ForeignKey('sensor.id'), table=<timed_belief>, primary_key=True, nullable=False), Column('source_id', Integer(), ForeignKey('data_source.id'), table=<timed_belief>, primary_key=True, nullable=False))
Compressed chunks are stored per segment, and nearly every query asks for one sensor (and often one source), so segmenting by those lets a query decompress only the segments it needs.
- flexmeasures.data.services.timescaledb.COMPRESS_ORDER_BY = (Column('event_start', DateTime(timezone=True), table=<timed_belief>, primary_key=True, nullable=False), Column('belief_horizon', Interval(), table=<timed_belief>, primary_key=True, nullable=False), Column('cumulative_probability', Float(), table=<timed_belief>, primary_key=True, nullable=False, default=ScalarElementColumnDefault(0.5)))
The rest of the primary key orders the rows within a segment, so that time-range filters can skip compressed batches, and so that upserts find their conflicts cheaply.
- flexmeasures.data.services.timescaledb.OLD_HYPERTABLE_SCHEMA = 'flexmeasures_timescaledb_old'
Where disable-timescaledb parks the hypertable while it copies the beliefs out of it. Moving it there frees the names of timed_belief’s indexes for the new plain table.
Functions
- flexmeasures.data.services.timescaledb.available_version(session: Session) str | None
Return the TimescaleDB version the server could install, or None if it has none.
- flexmeasures.data.services.timescaledb.compress_eligible_chunks(session: Session, compress_after: str) int
Compress the chunks the policy would compress, right away rather than when its job next runs.
Chunks that were compressed already are left out, including ones that took new beliefs since, which the policy recompresses on its own schedule.
- Returns:
the number of chunks compressed.
- flexmeasures.data.services.timescaledb.compression_policy_age(session: Session) str | None
Return the age after which the compression policy compresses chunks, e.g. ‘30 days’, or None if there is no policy.
- flexmeasures.data.services.timescaledb.convert_to_hypertable(session: Session, chunk_time_interval: str) None
Convert timed_belief into a hypertable, moving any existing rows into chunks.
The primary key already contains event_start, which TimescaleDB requires of every unique index. TimescaleDB’s default index on the partition column is not created: the existing indexes cover it, and an index that the data model does not declare would make
flexmeasures db migratepropose dropping it.- Parameters:
chunk_time_interval – how much event time each chunk spans, as a PostgreSQL interval (e.g. ‘30 days’).
- flexmeasures.data.services.timescaledb.convert_to_plain_table(session: Session) int
Replace the timed_belief hypertable with a plain table holding the same beliefs.
The hypertable is moved into a schema of its own, a plain timed_belief is created from the data model in its place (with the same primary key, indexes, foreign keys and trigger), the beliefs are copied over (decompressing on the way), and the hypertable is dropped, with its chunks and compression policy. The indexes and foreign keys are added after the copy, as building them in one go is faster than maintaining them row by row. The trigger is installed last, as sensor_data_source already lists every sensor and source that has beliefs. It all happens in the session’s transaction, which holds an exclusive lock on timed_belief from the start, so reads and writes wait until it is committed or rolled back.
The new table is owned by the role that runs this, so privileges granted on the hypertable to other roles must be granted again.
- Returns:
the number of beliefs copied.
- flexmeasures.data.services.timescaledb.count_chunks(session: Session) int
Return how many chunks the timed_belief hypertable has.
- flexmeasures.data.services.timescaledb.decompressed_size(session: Session) int
Estimate how many bytes the hypertable’s beliefs, with their indexes, would take once decompressed.
That is about what a plain copy of timed_belief needs. Compressed chunks count with the size they had before compression.
- flexmeasures.data.services.timescaledb.enable_compression(session: Session, compress_after: str) None
Compress chunks whose events are all older than
compress_after, from now on.TimescaleDB runs the policy as a background job. A policy set earlier is replaced, so that running this again changes the age. Compressed chunks still accept inserts, updates, upserts and deletes, but these are slower than on uncompressed chunks, so pick an age beyond which data is rarely rewritten.
- Parameters:
compress_after – a PostgreSQL interval (e.g. ‘30 days’).
- flexmeasures.data.services.timescaledb.ensure_extension(session: Session) str
Install the TimescaleDB extension in this database if needed, and return its version.
Installing needs the server to preload the library (
shared_preload_libraries = 'timescaledb'), and a role that may create extensions. Errors from the server about either are left to propagate, as they say what is wrong better than we could.
- flexmeasures.data.services.timescaledb.installed_version(session: Session) str | None
Return the TimescaleDB version installed in this database, or None if it is not installed.
- flexmeasures.data.services.timescaledb.is_hypertable(session: Session) bool
Whether timed_belief (as resolved via the search path) is already a hypertable.
- flexmeasures.data.services.timescaledb.set_chunk_time_interval(session: Session, chunk_time_interval: str) None
Make chunks created from now on span this much event time; existing chunks keep theirs.
- flexmeasures.data.services.timescaledb.setting(session: Session, name: str) str | None
Return a server setting, such as ‘timescaledb.license’, or None if the server does not know it.
- flexmeasures.data.services.timescaledb.supports_compression(session: Session) bool
Whether this server runs a TimescaleDB edition that can compress.
The Apache-licensed edition, offered by some managed services, cannot.
- flexmeasures.data.services.timescaledb.table_size(session: Session) dict[str, int]
Return the on-disk size of timed_belief in bytes, split into heap (including TOAST) and indexes.
For a hypertable this sums over its chunks, including compressed ones.
Exceptions
The database server cannot run TimescaleDB, or runs a version or edition that cannot do what was asked.