I have a table participant to connect tables tournaments and players. For this, I write :
@Entity(tableName = "participants", foreignKeys = [
ForeignKey(entity = TournamentEntity::class,
parentColumns = ["id"],
childColumns = ["tournamentId"],
onDelete = ForeignKey.CASCADE),
ForeignKey(entity = PlayerEntity::class,
parentColumns = ["id"],
childColumns = ["playerId"],
onDelete = ForeignKey.CASCADE),
], primaryKeys = ["tournamentId","playerId"])
data class ParticipantEntity(
var tournamentId:Long,
var playerId:Long
)
But during the build, I see the warning :
playerId column references a foreign key but it is not part of an index. This may trigger full table scans whenever parent table is modified so you are highly advised to create an index that covers this column.
Normally, when a foreign key is a part of the primary key, it isn't necessary to create an index.
Please, what is the procedure to follow to fix this issue?
The WARNING is because the
PlayerIDis not what the index (PrimaryKey) is primarily constructed from. That is the index, the primary key, will be built using first theTournamentIdthen thePlayerId.So a search of the table base upon a
PlayerIdwould either have to scan the rowid or the primarykey to find thePlayerIdin question.To remove the warning, simply use:-
Then an index on the
PlayerIdwill exist and be maintained. If so then the respective row can be obtained for a playerId via the index.Demonstration (using SQLite tool)
Consider the following:-
This:-
> Affected rows: 250000and> Time: 0.833sSELECT * FROM pe WHERE p='PLY1'does.SELECT * FROM pe WHERE p= 'PLY1'> OK> Time: 0.032sSELECT * FROM pe WHERE p='PLY1'> OK> Time: 0.012s0.012 seconds is noticeably less than the FULL SCAN that took 0.032 seconds