Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Foster auto-incremented primary keys #337

Merged
merged 4 commits into from
Apr 22, 2018
Merged

Conversation

groue
Copy link
Owner

@groue groue commented Apr 21, 2018

This PR introduces the TableDefinition.autoIncrementedPrimaryKey method, that defines an auto-incremented integer primary key. The documentation has been updated in order to foster this method:

try db.create(table: "players") { t in
    // Recommended
    t.autoIncrementedPrimaryKey("id")
    
    // Still valid, but no longer recommended:
    t.column("id", .integer).primaryKey()
    
    ...
}

An auto-incremented primary key comes with the guarantee that ids are never reused. It is safer than an integer primary key that is not auto-incremented, and can reuse ids:

Imagine an application screen that displays and tracks the player with id 1. In the background, the application synchronizes the players with some server content. The player 1 is destroyed. A new and different player is inserted. If the primary key is not auto-incremented, SQLite can reuse the id 1 for the newly inserted player: the application screen may not notice that its player was destroyed, and may display the new player instead: this is a bug.

This kind of dangerous scenario is unfortunately likely to happen with the database observation tools that come with GRDB: FetchedRecordsController and RxGRDB. Even though both track changes in order to fetch fresh request results, they don't care about individual changes, and do not notice id reuses.

This is why we now foster the safest option: auto-incremented primary keys. Expert users can still use naked integer primary keys when they need.

@groue groue added this to the GRDB 3.0 milestone Apr 21, 2018
@groue groue mentioned this pull request Apr 21, 2018
29 tasks
@groue groue merged commit ddc5516 into GRDB3 Apr 22, 2018
@groue groue deleted the GRDB3-autoIncrementedPrimaryKey branch April 22, 2018 04:39
groue added a commit that referenced this pull request Apr 25, 2018
groue added a commit that referenced this pull request Apr 26, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant