Skip to content

Commit b2d78f6

Browse files
Faster getPreviousMigrationId (#1119)
* Faster getPreviousMigrationId [ci] Signed-off-by: Robert Autenrieth <[email protected]> * [ci] fix hardcoded history_id=1 Signed-off-by: Oriol Muñoz <[email protected]> --------- Signed-off-by: Robert Autenrieth <[email protected]> Signed-off-by: Oriol Muñoz <[email protected]> Co-authored-by: Oriol Muñoz <[email protected]>
1 parent a91c38d commit b2d78f6

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

apps/common/src/main/scala/org/lfdecentralizedtrust/splice/store/UpdateHistory.scala

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1726,10 +1726,20 @@ class UpdateHistory(
17261726
): Future[Option[Long]] = {
17271727
def previousId(table: String) = {
17281728
storage.query(
1729+
// The following is equivalent to:
1730+
// select max(migration_id)
1731+
// from #$table
1732+
// where history_id = $historyId and migration_id < $migrationId
1733+
// but uses a recursive CTE to avoid a backwards-index-scan which attempts to read most of the table.
17291734
sql"""
1730-
select max(migration_id)
1731-
from #$table
1732-
where history_id = $historyId and migration_id < $migrationId
1735+
WITH RECURSIVE t AS (
1736+
(SELECT migration_id FROM #$table where history_id = $historyId and migration_id < $migrationId ORDER BY migration_id LIMIT 1)
1737+
UNION ALL
1738+
SELECT (SELECT migration_id FROM #$table WHERE history_id = $historyId and migration_id < $migrationId and migration_id > t.migration_id ORDER BY migration_id LIMIT 1)
1739+
FROM t
1740+
WHERE t.migration_id IS NOT NULL
1741+
)
1742+
SELECT MAX(migration_id) FROM t WHERE migration_id IS NOT NULL;
17331743
""".as[Option[Long]].head,
17341744
s"getPreviousMigrationId.$table",
17351745
)

0 commit comments

Comments
 (0)