diff --git a/persist/sqlite/init.sql b/persist/sqlite/init.sql index 7cd147ec..1f0d0a14 100644 --- a/persist/sqlite/init.sql +++ b/persist/sqlite/init.sql @@ -58,6 +58,7 @@ CREATE TABLE volume_sectors ( UNIQUE (volume_id, volume_index) ); CREATE INDEX volume_sectors_volume_id_sector_id_volume_index_compound ON volume_sectors(volume_id, sector_id, volume_index) WHERE sector_id IS NULL; +CREATE INDEX volume_sectors_volume_id_sector_id_volume_index_set_compound ON volume_sectors (volume_id, sector_id, volume_index) WHERE sector_id IS NOT NULL; CREATE INDEX volume_sectors_volume_id_sector_id ON volume_sectors(volume_id, sector_id); CREATE INDEX volume_sectors_volume_id ON volume_sectors(volume_id); CREATE INDEX volume_sectors_volume_index ON volume_sectors(volume_index ASC); diff --git a/persist/sqlite/migrations.go b/persist/sqlite/migrations.go index bea64182..d1f471ba 100644 --- a/persist/sqlite/migrations.go +++ b/persist/sqlite/migrations.go @@ -9,6 +9,12 @@ import ( "go.sia.tech/hostd/host/contracts" ) +// migrateVersion20 adds a compound index to the volume_sectors table +func migrateVersion20(tx txn) error { + _, err := tx.Exec(`CREATE INDEX volume_sectors_volume_id_sector_id_volume_index_set_compound ON volume_sectors (volume_id, sector_id, volume_index) WHERE sector_id IS NOT NULL;`) + return err +} + // migrateVersion19 adds a compound index to the volume_sectors table func migrateVersion19(tx txn) error { const query = ` @@ -505,4 +511,5 @@ var migrations = []func(tx txn) error{ migrateVersion17, migrateVersion18, migrateVersion19, + migrateVersion20, } diff --git a/persist/sqlite/volumes.go b/persist/sqlite/volumes.go index 68e93201..b4ce375d 100644 --- a/persist/sqlite/volumes.go +++ b/persist/sqlite/volumes.go @@ -521,7 +521,8 @@ func sectorForMigration(tx txn, volumeID int64, minIndex uint64) (loc storage.Se const query = `SELECT vs.id, vs.volume_id, vs.volume_index, s.sector_root FROM volume_sectors vs INNER JOIN stored_sectors s ON (s.id=vs.sector_id) - WHERE vs.sector_id IS NOT NULL AND vs.volume_id=$1 AND vs.volume_index >= $2` + WHERE vs.sector_id IS NOT NULL AND vs.volume_id=$1 AND vs.volume_index >= $2 + LIMIT 1` err = tx.QueryRow(query, volumeID, minIndex).Scan(&loc.ID, &loc.Volume, &loc.Index, (*sqlHash256)(&loc.Root)) if errors.Is(err, sql.ErrNoRows) {