Repository navigation
Filter datapoint exports with literals so TimescaleDB can exclude chunks - #3674
Open
costajohnt wants to merge 1 commit into
Open
costajohnt wants to merge 1 commit into
costajohnt wants to merge 1 commit into
Conversation
The export COPY query read its time bounds and attribute pairs from temp tables, so TimescaleDB could neither exclude chunks nor filter compressed batches and every export scanned the whole asset_datapoint hypertable. Build the filter from literals instead: timestamps formatted from the typed bounds, asset IDs validated, and strings as E'' constants with quotes and backslashes doubled, which evaluate to the input whatever standard_conforming_strings is and nest safely in the crosstab query text. tmp_export_bounds is gone; tmp_export_attributes is only created for the crosstab formats, for column order and keys. Closes openremote#3661
|
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.



Description
Closes #3661
The datapoint export streams a
COPY (...) TO STDOUTquery. Since #2882 that query took its time bounds fromtmp_export_bounds(cross join) and its(entity_id, attribute_name)pairs fromtmp_export_attributes(join). Neither is known at plan time, so TimescaleDB could not exclude chunks or filter compressed batches: every export, even 1 hour of one attribute, scanned and decompressed the wholeasset_datapointhypertable.What changed
AssetDatapointService:buildExportFilterbuilds theasset_datapointfilter with literals:ad.timestamp >= TIMESTAMP '...' and ad.timestamp <= TIMESTAMP '...' and (ad.entity_id, ad.attribute_name) in ((E'...', E'...'), ...). All three formats (CSV, CSV_CROSSTAB, CSV_CROSSTAB_MINUTE) use it.tmp_export_boundsis removed.tmp_export_attributesis only created for the crosstab formats, where it still provides the category query (column order) and maps each attribute to its generatedcol_Nkey. It no longer acts as the filter; the literal filter above restrictsasset_datapointbefore the join.crosstab(...)through the same literal function, instead of hand-doubled quotes (''1 minute'').canQueryDatapoints(the count query run before every export) is unchanged: it already uses bind parameters, and EXPLAIN shows it gets chunk exclusion with both custom and generic plans (see below).The UI timeout, the retry pileup and cancelling the COPY on client disconnect from the issue are not part of this PR.
How injection safety is ensured
COPYcannot take bind parameters, so values go into the SQL text. Every value goes through one of two functions:toSqlTimestampLiteral(long): the bound is alongconverted with the same JVM-local conversion as before (toDatapointLocalDateTime) and formatted with a fixedDateTimeFormatter(yyyy-MM-dd HH:mm:ss.SSS, plusBCfor years before 1). The output only contains digits,-,:,., space andBC; there is no user-controlled text in it.toSqlStringLiteral(String): returns an escape string constantE'...'with every\doubled and every'doubled.E'...'constant a backslash is always an escape character, so the result evaluates to exactly the input whateverstandard_conforming_stringsis set to. A plain'...'literal would not have that property whenstandard_conforming_strings = off.E'...'literals) is itself passed through it, so the double escaping needed there is handled by applying the same function twice, not by hand.IllegalArgumentException), as PostgreSQL text cannot hold it.client_encoding=UTF8at startup and closes the connection if it changes, unlessallowEncodingChangesis set (not set anywhere in this repo). In UTF-8 no multibyte character contains the byte of'or\, so multibyte tricks against the escaping do not apply.QueryExecutorImpl.startCopy).validateAssetId(^[0-9A-Za-z]{22}$) before they are quoted.Tests
New features in
AssetDatapointExportTest:TIMESTAMP '...'bounds and the(entity_id, attribute_name) in ((E'...', E'...'))filter, contain notmp_export, thatEXPLAINonly references one chunk, and that the filter returns only the datapoint in that hour.standard_conforming_stringsbothoffandon, every test string (an attribute name with',\',\\,''and a trailing\, plus five names that try to close the literal with',\'and\'') round-trips exactly throughselect <literal>and through a nested literal. An attribute with that name exports correctly in all three formats, and the breakout names export only a header in all three formats.Commands (local, fresh test stack from
profile/dev-testing.ymlbrought up before and down after, JDK 21,-Dorg.gradle.jvmargs=-Xmx4g --max-workers=4; the last two lines are the run on the final commit):EXPLAIN before and after
Local test DB, 3 attributes with one datapoint per minute over 40 days (7 chunks, all but the newest compressed), exporting 1 hour of one attribute 3 days ago (60 rows),
EXPLAIN (ANALYZE, BUFFERS):After, the compressed chunk is filtered on
entity_id,attribute_nameand the batch min/max timestamps before decompression. The issue has the production-sized numbers (126 chunks, about 104 s before vs 0.17 ms after).Count query from
canQueryDatapoints(bind parameters, unchanged) on the same data: custom plan scans 1 chunk; withplan_cache_mode = force_generic_planthe plan showsChunks excluded during startup: 6and scans 1 chunk.Downstream
doExportDatapointskeeps its signature.buildCopyToStdoutQuerywas private and is now protected with a new signature, andExportColumnis now protected; nothing outside this class could use either before. No Extensions, Custom Project or documentation change is needed. I did not build Extensions against this change.Checklist