Skip to content

Instantly share code, notes, and snippets.

@neoneye
Last active October 19, 2017 19:35
Show Gist options
  • Save neoneye/fe96f484f5f23dfe3c6b0fd0885bfe23 to your computer and use it in GitHub Desktop.
Save neoneye/fe96f484f5f23dfe3c6b0fd0885bfe23 to your computer and use it in GitHub Desktop.
There can be gaps in the id column. This ensures that the id column is set to the max value
import PostgresStORM
extension PostgresStORM {
/// Set Next ID Value to MAX ID
///
/// This is a workaround for issue [ISS-546](http://jira.perfect.org:8080/browse/ISS-546)
///
/// When inserting new rows then I'm getting errors like this:
///
/// ERROR: duplicate key value violates unique constraint "president_key"
/// DETAIL: Key (id)=(45) already exists.
///
/// I'm having gaps in my `id` column, eg: 1, 2, 3, 7, 8
/// Because I have imported a dataset with gaps in the `id` column.
func pickNextId() throws {
let table = self.table()
let statement = "SELECT setval('\(table)_id_seq', (SELECT MAX(id) FROM \(table)))"
try self.sql(statement, params: [])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment