SecretContentDAO { @VisibleForTesting void pruneOldContents(long secretId) { SecretsRecord secret = dslContext.select(SECRETS.CURRENT) .from(SECRETS) .where(SECRETS.ID.eq(secretId)) .fetchOneInto(SecretsRecord.class); if (secret == null || secret.getCurrent() == null) { return; } long cutoff = OffsetDateTime.now().minusDays(PRUNE_CUTOFF_DAYS).toEpochSecond(); List<Long> records = dslContext.select(SECRETS_CONTENT.ID) .from(SECRETS_CONTENT) .where(SECRETS_CONTENT.SECRETID.eq(secretId)) .and(SECRETS_CONTENT.CREATEDAT.lt(cutoff)) .and(SECRETS_CONTENT.ID.ne(secret.getCurrent())) .orderBy(SECRETS_CONTENT.CREATEDAT.desc()) .fetch(SECRETS_CONTENT.ID); if (records.size() > PRUNE_CUTOFF_ITEMS) { for (long id : records.subList(PRUNE_CUTOFF_ITEMS, records.size())) { dslContext.deleteFrom(SECRETS_CONTENT).where(SECRETS_CONTENT.ID.eq(id)).execute(); } } } private  SecretContentDAO(DSLContext dslContext, ObjectMapper mapper,
      SecretContentMapper secretContentMapper, RowHmacGenerator rowHmacGenerator,
      KeywhizConfig config); long createSecretContent(long secretId, String encryptedContent, String hmac,
      String creator, Map<String, String> metadata, long expiry, long now); Optional<SecretContent> getSecretContentById(long id); Optional<ImmutableList<SecretContent>> getSecretVersionsBySecretId(long id,
      int versionIdx, int numVersions); long dangerPermanentlyRemoveRecordsForGivenSecretsIDs(List<Long> ids);  }
@Test public void pruneOldContents() throws Exception { long now = OffsetDateTime.now().toEpochSecond(); long secretSeriesId = 666; jooqContext.insertInto(SECRETS, SECRETS.ID, SECRETS.NAME, SECRETS.CREATEDAT, SECRETS.UPDATEDAT) .values(secretSeriesId, "secretForPruneTest1", now, now) .execute(); int before = tableSize(); long[] ids = new long[15]; for (int i = 0; i < ids.length; i++) { long id = secretContentDAO.createSecretContent(secretSeriesId, "encrypted", "checksum", "creator", metadata, 1136214245, i); ids[i] = id; } assertThat(tableSize()).isEqualTo(before + ids.length); jooqContext.update(SECRETS) .set(SECRETS.CURRENT, ids[ids.length-1]) .where(SECRETS.ID.eq(secretSeriesId)) .execute(); secretContentDAO.pruneOldContents(secretSeriesId); assertThat(tableSize()).isEqualTo(before + PRUNE_CUTOFF_ITEMS + 1); for (int i = 0; i < (ids.length - PRUNE_CUTOFF_ITEMS - 1); i++) { assertThat(secretContentDAO.getSecretContentById(ids[i])).isEmpty(); } for (int i = (ids.length - PRUNE_CUTOFF_ITEMS - 1); i < ids.length; i++) { assertThat(secretContentDAO.getSecretContentById(ids[i])).isPresent(); } assertThat(secretContentDAO.getSecretContentById(secretContent1.id())).isPresent(); }