try (Timer.Context context = _insertTimer.time()) {
final long docId = nextId("hts_master_seq");
final long docOid = (document.getUniqueId() != null ? extractOid(document.getUniqueId()) : docId);
// the arguments for inserting into the table
final ManageableHistoricalTimeSeriesInfo info = document.getInfo();
final DbMapSqlParameterSource docArgs = new DbMapSqlParameterSource()
.addValue("doc_id", docId)
.addValue("doc_oid", docOid)
.addTimestamp("ver_from_instant", document.getVersionFromInstant())
.addTimestampNullFuture("ver_to_instant", document.getVersionToInstant())
.addTimestamp("corr_from_instant", document.getCorrectionFromInstant())
.addTimestampNullFuture("corr_to_instant", document.getCorrectionToInstant())
.addValue("name_id", getNameTable().ensure(info.getName()))
.addValue("data_field_id", getDataFieldTable().ensure(info.getDataField()))
.addValue("data_source_id", getDataSourceTable().ensure(info.getDataSource()))
.addValue("data_provider_id", getDataProviderTable().ensure(info.getDataProvider()))
.addValue("observation_time_id", getObservationTimeTable().ensure(info.getObservationTime()));
// the arguments for inserting into the idkey tables
final List<DbMapSqlParameterSource> assocList = new ArrayList<DbMapSqlParameterSource>();
final List<DbMapSqlParameterSource> idKeyList = new ArrayList<DbMapSqlParameterSource>();
final String sqlSelectIdKey = getElSqlBundle().getSql("SelectIdKey");
for (ExternalIdWithDates id : info.getExternalIdBundle()) {
final DbMapSqlParameterSource assocArgs = new DbMapSqlParameterSource()
.addValue("doc_id", docId)
.addValue("key_scheme", id.getExternalId().getScheme().getName())
.addValue("key_value", id.getExternalId().getValue())
.addValue("valid_from", DbDateUtils.toSqlDateNullFarPast(id.getValidFrom()))
.addValue("valid_to", DbDateUtils.toSqlDateNullFarFuture(id.getValidTo()));
assocList.add(assocArgs);
if (getJdbcTemplate().queryForList(sqlSelectIdKey, assocArgs).isEmpty()) {
// select avoids creating unecessary id, but id may still not be used
final long idKeyId = nextId("hts_idkey_seq");
final DbMapSqlParameterSource idkeyArgs = new DbMapSqlParameterSource()
.addValue("idkey_id", idKeyId)
.addValue("key_scheme", id.getExternalId().getScheme().getName())
.addValue("key_value", id.getExternalId().getValue());
idKeyList.add(idkeyArgs);
}