final long oid = extractOid(objectId);
final VersionCorrection vc = versionCorrection.withLatestFixed(now());
// Set up the basic query arguments
final DbMapSqlParameterSource args = new DbMapSqlParameterSource()
.addValue("doc_oid", oid)
.addTimestamp("version_as_of_instant", vc.getVersionAsOf())
.addTimestamp("corrected_to_instant", vc.getCorrectedTo())
.addValue("start_date", DbDateUtils.toSqlDateNullFarPast(filter.getEarliestDate()))
.addValue("end_date", DbDateUtils.toSqlDateNullFarFuture(filter.getLatestDate()));
final NamedParameterJdbcOperations namedJdbc = getDbConnector().getJdbcTemplate();
// Get version metadata from the data-points and set up a Manageable HTS accordingly
// While the HTS doc itself might have been deleted, the data-points can still be retrieved here
final String sqlVersion = getElSqlBundle().getSql("SelectDataPointsVersion", args);
ManageableHistoricalTimeSeries result = namedJdbc.query(sqlVersion, args, new ManageableHTSExtractor(oid));
if (result == null) {
// No data-points were found, check if the time-series doc exists or existed at some point
final String sqlExists = getElSqlBundle().getSql("SelectExistential", args);
result = namedJdbc.query(sqlExists, args, new ManageableHTSExtractor(oid));
if (result != null) {
// The time series doc exists or existed at some point, it's just that there are no data-points
result.setTimeSeries(ImmutableLocalDateDoubleTimeSeries.EMPTY_SERIES);
return result;
} else {
// The time series with the supplied id never existed
throw new DataNotFoundException("Unable to find time-series: " + objectId);
}
}
// Set up query arguments to limit the number of points to return
if (filter.getMaxPoints() == null) {
// return all points (limit all)
args.addValue("order", "ASC");
} else if (filter.getMaxPoints() > 0) {
// return first few points
args.addValue("paging_fetch", filter.getMaxPoints());
args.addValue("order", "ASC");
} else if (filter.getMaxPoints() < 0) {
// return last few points
args.addValue("paging_fetch", -filter.getMaxPoints());
args.addValue("order", "DESC");
} else {
// Zero datapoints requested
result.setTimeSeries(ImmutableLocalDateDoubleTimeSeries.EMPTY_SERIES);
return result;
}