Skip to content

Instantly share code, notes, and snippets.

@groue
Last active June 15, 2020 15:14
Show Gist options
  • Select an option

  • Save groue/ccb07cdcda772fb3d62f318a4c10cf6e to your computer and use it in GitHub Desktop.

Select an option

Save groue/ccb07cdcda772fb3d62f318a4c10cf6e to your computer and use it in GitHub Desktop.
GRDB request.deleteAllOther(db)
import GRDB
extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
/// Deletes all records in the database, but the ones selected by the request.
///
/// For example:
///
/// // Delete all players whose score is below 1000
/// let bestPlayers = Player.filter(Column("score") > 1000)
/// try dbQueue.write(bestPlayers.deleteAllOther)
///
/// - parameter db: A database connection.
/// - returns: The number of deleted rows.
@discardableResult
func deleteAllOther(_ db: Database) throws -> Int {
try db.execute(literal: """
DELETE FROM \(RowDecoder.self) WHERE \(RowDecoder.primaryKey) NOT IN (\(select(RowDecoder.primaryKey)))
""")
return db.changesCount
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment