mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-29 04:24:21 +00:00
Merge pull request #676 from groue/dev/moreDeleteAndUpdate
More batch delete and update
This commit is contained in:
8 files changed
+494
-88
No files matched your search
+4
-4
@@ -6,9 +6,7 @@ All notable changes to this project will be documented in this file.
|
||||
GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library.
|
||||
|
||||
|
||||
<!--
|
||||
[Next Release](#next-release)
|
||||
-->
|
||||
|
||||
|
||||
#### 4.x Releases
|
||||
@@ -60,9 +58,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
- [0.110.0](#01100), ...
|
||||
|
||||
|
||||
<!--
|
||||
## Next Release
|
||||
-->
|
||||
|
||||
**New**
|
||||
|
||||
- [#676](https://github.com/groue/GRDB.swift/pull/676): More batch delete and update
|
||||
|
||||
|
||||
## 4.7.0
|
||||
|
||||
@@ -360,8 +360,14 @@ extension Database {
|
||||
where T.Iterator.Element == String
|
||||
{
|
||||
// Check primaryKey first, so that we fail early if the table does not exist
|
||||
let primaryKey = try self.primaryKey(tableName)
|
||||
let lowercasedColumns = Set(columns.map { $0.lowercased() })
|
||||
|
||||
// Assume "rowid" is a primary key
|
||||
if lowercasedColumns == ["rowid"] {
|
||||
return ["rowid"]
|
||||
}
|
||||
|
||||
let primaryKey = try self.primaryKey(tableName)
|
||||
if Set(primaryKey.columns.map { $0.lowercased() }) == lowercasedColumns {
|
||||
return primaryKey.columns
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ public struct Column: ColumnExpression {
|
||||
/// A qualified column in the database, as in `SELECT t.a FROM t`
|
||||
struct QualifiedColumn: ColumnExpression {
|
||||
var name: String
|
||||
private let alias: TableAlias
|
||||
let alias: TableAlias
|
||||
|
||||
/// Creates a column given its name.
|
||||
init(_ name: String, alias: TableAlias) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/// SQLQueryGenerator is able to generate an SQL SELECT query.
|
||||
struct SQLQueryGenerator {
|
||||
fileprivate let relation: SQLQualifiedRelation
|
||||
fileprivate private(set) var relation: SQLQualifiedRelation
|
||||
private let isDistinct: Bool
|
||||
private let groupPromise: DatabasePromise<[SQLExpression]>?
|
||||
private let havingExpressions: [SQLExpression]
|
||||
@@ -127,42 +127,63 @@ struct SQLQueryGenerator {
|
||||
}
|
||||
|
||||
func makeDeleteStatement(_ db: Database) throws -> UpdateStatement {
|
||||
if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty {
|
||||
switch try grouping(db) {
|
||||
case .none:
|
||||
guard case .table = relation.source else {
|
||||
// Programmer error
|
||||
fatalError("Can't delete without any database table")
|
||||
}
|
||||
|
||||
guard relation.joins.isEmpty else {
|
||||
return try makeTrivialDeleteStatement(db)
|
||||
}
|
||||
|
||||
var context = SQLGenerationContext.queryGenerationContext(aliases: relation.allAliases)
|
||||
|
||||
var sql = try "DELETE FROM " + relation.source.sql(db, &context)
|
||||
|
||||
let filters = try relation.filtersPromise.resolve(db)
|
||||
if filters.isEmpty == false {
|
||||
sql += " WHERE " + SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false)
|
||||
}
|
||||
|
||||
if let limit = limit {
|
||||
let orderings = try relation.ordering.resolve(db)
|
||||
if !orderings.isEmpty {
|
||||
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ")
|
||||
}
|
||||
sql += " LIMIT " + limit.sql
|
||||
}
|
||||
|
||||
let statement = try db.makeUpdateStatement(sql: sql)
|
||||
statement.arguments = context.arguments!
|
||||
return statement
|
||||
|
||||
case .unique:
|
||||
return try makeTrivialDeleteStatement(db)
|
||||
|
||||
case .nonUnique:
|
||||
// Programmer error
|
||||
fatalError("Can't delete query with GROUP BY clause")
|
||||
}
|
||||
|
||||
guard havingExpressions.isEmpty else {
|
||||
// Programmer error
|
||||
fatalError("Can't delete query with HAVING clause")
|
||||
}
|
||||
|
||||
guard relation.joins.isEmpty else {
|
||||
// Programmer error
|
||||
fatalError("Can't delete query with JOIN clause")
|
||||
}
|
||||
|
||||
guard case .table = relation.source else {
|
||||
}
|
||||
|
||||
/// DELETE FROM table WHERE rowid IN (SELECT rowid FROM table ...)
|
||||
private func makeTrivialDeleteStatement(_ db: Database) throws -> UpdateStatement {
|
||||
guard case let .table(tableName: tableName, alias: _) = relation.source else {
|
||||
// Programmer error
|
||||
fatalError("Can't delete without any database table")
|
||||
}
|
||||
|
||||
var context = SQLGenerationContext.queryGenerationContext(aliases: relation.allAliases)
|
||||
|
||||
var sql = try "DELETE FROM " + relation.source.sql(db, &context)
|
||||
// SELECT rowid FROM table ...
|
||||
var generator = self
|
||||
generator.relation = generator.relation.selectOnly([Column.rowID])
|
||||
let selectSQL = try generator.sql(db, &context)
|
||||
|
||||
let filters = try relation.filtersPromise.resolve(db)
|
||||
if filters.isEmpty == false {
|
||||
sql += " WHERE " + SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false)
|
||||
}
|
||||
|
||||
if let limit = limit {
|
||||
let orderings = try relation.ordering.resolve(db)
|
||||
if !orderings.isEmpty {
|
||||
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ")
|
||||
}
|
||||
sql += " LIMIT " + limit.sql
|
||||
}
|
||||
// DELETE FROM table WHERE rowid IN (SELECT rowid FROM table ...)
|
||||
let sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE rowid IN (\(selectSQL))"
|
||||
|
||||
let statement = try db.makeUpdateStatement(sql: sql)
|
||||
statement.arguments = context.arguments!
|
||||
@@ -176,39 +197,104 @@ struct SQLQueryGenerator {
|
||||
assignments: [ColumnAssignment])
|
||||
throws -> UpdateStatement?
|
||||
{
|
||||
if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty {
|
||||
switch try grouping(db) {
|
||||
case .none:
|
||||
guard case .table = relation.source else {
|
||||
// Programmer error
|
||||
fatalError("Can't update without any database table")
|
||||
}
|
||||
|
||||
guard relation.joins.isEmpty else {
|
||||
return try makeTrivialUpdateStatement(
|
||||
db,
|
||||
conflictResolution: conflictResolution,
|
||||
assignments: assignments)
|
||||
}
|
||||
|
||||
// Check for empty assignments after all programmer errors have
|
||||
// been checked.
|
||||
if assignments.isEmpty {
|
||||
return nil
|
||||
}
|
||||
|
||||
var context = SQLGenerationContext.queryGenerationContext(aliases: relation.allAliases)
|
||||
|
||||
var sql = "UPDATE "
|
||||
|
||||
if conflictResolution != .abort {
|
||||
sql += "OR \(conflictResolution.rawValue) "
|
||||
}
|
||||
|
||||
sql += try relation.source.sql(db, &context)
|
||||
|
||||
let assignmentsSQL = assignments
|
||||
.map({ assignment in
|
||||
assignment.column.expressionSQL(&context, wrappedInParenthesis: false) +
|
||||
" = " +
|
||||
assignment.value.sqlExpression.expressionSQL(&context, wrappedInParenthesis: false)
|
||||
})
|
||||
.joined(separator: ", ")
|
||||
sql += " SET " + assignmentsSQL
|
||||
|
||||
let filters = try relation.filtersPromise.resolve(db)
|
||||
if filters.isEmpty == false {
|
||||
sql += " WHERE " + SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false)
|
||||
}
|
||||
|
||||
if let limit = limit {
|
||||
let orderings = try relation.ordering.resolve(db)
|
||||
if !orderings.isEmpty {
|
||||
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ")
|
||||
}
|
||||
sql += " LIMIT " + limit.sql
|
||||
}
|
||||
|
||||
let statement = try db.makeUpdateStatement(sql: sql)
|
||||
statement.arguments = context.arguments!
|
||||
return statement
|
||||
|
||||
case .unique:
|
||||
return try makeTrivialUpdateStatement(db, conflictResolution: conflictResolution, assignments: assignments)
|
||||
|
||||
case .nonUnique:
|
||||
// Programmer error
|
||||
fatalError("Can't update query with GROUP BY clause")
|
||||
}
|
||||
|
||||
guard havingExpressions.isEmpty else {
|
||||
}
|
||||
|
||||
/// UPDATE table SET ... WHERE rowid IN (SELECT rowid FROM table ...)
|
||||
/// Returns nil if assignments is empty
|
||||
private func makeTrivialUpdateStatement(
|
||||
_ db: Database,
|
||||
conflictResolution: Database.ConflictResolution,
|
||||
assignments: [ColumnAssignment])
|
||||
throws -> UpdateStatement?
|
||||
{
|
||||
guard case let .table(tableName: tableName, alias: _) = relation.source else {
|
||||
// Programmer error
|
||||
fatalError("Can't update query with HAVING clause")
|
||||
}
|
||||
|
||||
guard relation.joins.isEmpty else {
|
||||
// Programmer error
|
||||
fatalError("Can't update query with JOIN clause")
|
||||
}
|
||||
|
||||
guard case .table = relation.source else {
|
||||
// Programmer error
|
||||
fatalError("Can't update without any database table")
|
||||
fatalError("Can't delete without any database table")
|
||||
}
|
||||
|
||||
// Check for empty assignments after all programmer errors have
|
||||
// been checked.
|
||||
if assignments.isEmpty {
|
||||
return nil
|
||||
}
|
||||
|
||||
var context = SQLGenerationContext.queryGenerationContext(aliases: relation.allAliases)
|
||||
|
||||
// SELECT rowid FROM table ...
|
||||
var generator = self
|
||||
generator.relation = generator.relation.selectOnly([Column.rowID])
|
||||
let selectSQL = try generator.sql(db, &context)
|
||||
|
||||
var sql = "UPDATE "
|
||||
|
||||
if conflictResolution != .abort {
|
||||
sql += "OR \(conflictResolution.rawValue) "
|
||||
}
|
||||
|
||||
sql += try relation.source.sql(db, &context)
|
||||
sql += tableName.quotedDatabaseIdentifier
|
||||
|
||||
let assignmentsSQL = assignments
|
||||
.map({ assignment in
|
||||
@@ -218,25 +304,13 @@ struct SQLQueryGenerator {
|
||||
})
|
||||
.joined(separator: ", ")
|
||||
sql += " SET " + assignmentsSQL
|
||||
|
||||
let filters = try relation.filtersPromise.resolve(db)
|
||||
if filters.isEmpty == false {
|
||||
sql += " WHERE " + SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false)
|
||||
}
|
||||
|
||||
if let limit = limit {
|
||||
let orderings = try relation.ordering.resolve(db)
|
||||
if !orderings.isEmpty {
|
||||
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ")
|
||||
}
|
||||
sql += " LIMIT " + limit.sql
|
||||
}
|
||||
sql += " WHERE rowid IN (\(selectSQL))"
|
||||
|
||||
let statement = try db.makeUpdateStatement(sql: sql)
|
||||
statement.arguments = context.arguments!
|
||||
return statement
|
||||
}
|
||||
|
||||
|
||||
/// Returns a select statement
|
||||
func makeSelectStatement(_ db: Database) throws -> SelectStatement {
|
||||
// Build an SQK generation context with all aliases found in the query,
|
||||
@@ -256,6 +330,56 @@ struct SQLQueryGenerator {
|
||||
return statement
|
||||
}
|
||||
|
||||
/// Informs about the query grouping
|
||||
private enum GroupingInfo {
|
||||
/// No grouping at all: SELECT ... FROM player
|
||||
case none
|
||||
/// Grouped by unique key: SELECT ... FROM player GROUP BY id
|
||||
case unique
|
||||
/// Grouped by some non-unique columnns: SELECT ... FROM player GROUP BY teamId
|
||||
case nonUnique
|
||||
}
|
||||
|
||||
/// Informs about the query grouping
|
||||
private func grouping(_ db: Database) throws -> GroupingInfo {
|
||||
// Empty group clause: no grouping
|
||||
// SELECT * FROM player
|
||||
guard let groupExpressions = try groupPromise?.resolve(db), groupExpressions.isEmpty == false else {
|
||||
return .none
|
||||
}
|
||||
|
||||
// Grouping by something which is not a column: assume non
|
||||
// unique grouping.
|
||||
// SELECT * FROM player GROUP BY (score + bonus)
|
||||
let qualifiedColumns = groupExpressions.compactMap { $0 as? QualifiedColumn }
|
||||
if qualifiedColumns.count != groupExpressions.count {
|
||||
return .nonUnique
|
||||
}
|
||||
|
||||
// Grouping something which is not a table: assume non unique grouping.
|
||||
guard case let .table(tableName: tableName, alias: alias) = relation.source else {
|
||||
return .nonUnique
|
||||
}
|
||||
|
||||
// Grouping by some column(s) which do not come from the main table:
|
||||
// assume non unique grouping.
|
||||
// SELECT * FROM player JOIN team ... GROUP BY team.id
|
||||
guard qualifiedColumns.allSatisfy({ $0.alias == alias }) else {
|
||||
return .nonUnique
|
||||
}
|
||||
|
||||
// Grouping by some column(s) which are unique
|
||||
// SELECT * FROM player GROUP BY id
|
||||
let columnNames = qualifiedColumns.map { $0.name }
|
||||
if try db.table(tableName, hasUniqueKey: columnNames) {
|
||||
return .unique
|
||||
}
|
||||
|
||||
// Grouping by some column(s) which are not unique
|
||||
// SELECT * FROM player GROUP BY score
|
||||
return .nonUnique
|
||||
}
|
||||
|
||||
/// Returns the row adapter which presents the fetched rows according to the
|
||||
/// tree of joined relations.
|
||||
///
|
||||
@@ -322,7 +446,7 @@ private struct SQLQualifiedRelation {
|
||||
let source: SQLQualifiedSource
|
||||
|
||||
/// The selection, not including selection of joined relations
|
||||
private let ownSelection: [SQLSelectable]
|
||||
private var ownSelection: [SQLSelectable]
|
||||
|
||||
/// The full selection, including selection of joined relations
|
||||
///
|
||||
@@ -361,7 +485,7 @@ private struct SQLQualifiedRelation {
|
||||
/// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ...
|
||||
/// |
|
||||
/// • joins
|
||||
let joins: OrderedDictionary<String, SQLQualifiedJoin>
|
||||
private(set) var joins: OrderedDictionary<String, SQLQualifiedJoin>
|
||||
|
||||
init(_ relation: SQLRelation) {
|
||||
// Qualify the source, so that it be disambiguated with an SQL alias
|
||||
@@ -456,6 +580,14 @@ private struct SQLQualifiedRelation {
|
||||
|
||||
return (adapter: adapter, endIndex: endIndex)
|
||||
}
|
||||
|
||||
/// Removes all selections from joins
|
||||
func selectOnly(_ selection: [SQLSelectable]) -> SQLQualifiedRelation {
|
||||
var relation = self
|
||||
relation.ownSelection = selection.map { $0.qualifiedSelectable(with: alias) }
|
||||
relation.joins = relation.joins.mapValues { $0.selectOnly([]) }
|
||||
return relation
|
||||
}
|
||||
}
|
||||
|
||||
/// A "qualified" source, where all tables are identified with a table alias.
|
||||
@@ -520,6 +652,14 @@ private struct SQLQualifiedJoin {
|
||||
return try sql(db, &context, leftAlias: leftAlias, allowingInnerJoin: true)
|
||||
}
|
||||
|
||||
/// Removes all selections from joins
|
||||
func selectOnly(_ selection: [SQLSelectable]) -> SQLQualifiedJoin {
|
||||
return SQLQualifiedJoin(
|
||||
kind: kind,
|
||||
condition: condition,
|
||||
relation: relation.selectOnly(selection))
|
||||
}
|
||||
|
||||
private func sql(
|
||||
_ db: Database,
|
||||
_ context: inout SQLGenerationContext,
|
||||
|
||||
@@ -2630,6 +2630,7 @@ try place.delete(db) // DELETE
|
||||
try place.exists(db)
|
||||
|
||||
// Type methods
|
||||
try Place.updateAll(db, ...) // UPDATE
|
||||
try Place.deleteAll(db) // DELETE
|
||||
try Place.deleteAll(db, keys:...) // DELETE
|
||||
try Place.deleteOne(db, key:...) // DELETE
|
||||
@@ -2641,6 +2642,8 @@ try Place.deleteOne(db, key:...) // DELETE
|
||||
|
||||
When saving an object that may or may not already exist in the database, prefer the `save` method:
|
||||
|
||||
- `updateAll` performs a batch update. See [Update Requests](#update-requests).
|
||||
|
||||
- `save` makes sure your values are stored in the database.
|
||||
|
||||
It performs an UPDATE if the record has a non-null primary key, and then, if no row was modified, an INSERT. It directly perfoms an INSERT if the record has no primary key, or a null primary key.
|
||||
|
||||
@@ -56,14 +56,16 @@ class IndexInfoTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)")
|
||||
try XCTAssertTrue(db.table("persons", hasUniqueKey: ["rowid"]))
|
||||
try XCTAssertTrue(db.table("persons", hasUniqueKey: ["id"]))
|
||||
try XCTAssertTrue(db.table("persons", hasUniqueKey: ["email"]))
|
||||
try XCTAssertFalse(db.table("persons", hasUniqueKey: []))
|
||||
try XCTAssertFalse(db.table("persons", hasUniqueKey: ["name"]))
|
||||
try XCTAssertFalse(db.table("persons", hasUniqueKey: ["id", "email"]))
|
||||
try XCTAssertFalse(db.table("persons", hasUniqueKey: ["id", "email"])) // TODO: is it expected?
|
||||
|
||||
try db.execute(sql: "CREATE TABLE citizenships (year INTEGER, personId INTEGER NOT NULL, countryIsoCode TEXT NOT NULL, PRIMARY KEY (personId, countryIsoCode))")
|
||||
try db.execute(sql: "CREATE INDEX citizenshipsOnYear ON citizenships(year)")
|
||||
try XCTAssertTrue(db.table("citizenships", hasUniqueKey: ["rowid"]))
|
||||
try XCTAssertTrue(db.table("citizenships", hasUniqueKey: ["personId", "countryIsoCode"]))
|
||||
try XCTAssertTrue(db.table("citizenships", hasUniqueKey: ["countryIsoCode", "personId"]))
|
||||
try XCTAssertFalse(db.table("citizenships", hasUniqueKey: []))
|
||||
|
||||
@@ -184,4 +184,120 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testJoinedRequestDelete() throws {
|
||||
try makeDatabaseQueue().inDatabase { db in
|
||||
struct Player: MutablePersistableRecord {
|
||||
static let team = belongsTo(Team.self)
|
||||
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
|
||||
}
|
||||
|
||||
struct Team: MutablePersistableRecord {
|
||||
static let players = hasMany(Player.self)
|
||||
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
|
||||
}
|
||||
|
||||
try db.create(table: "team") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
}
|
||||
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("teamId", .integer).references("team")
|
||||
}
|
||||
|
||||
do {
|
||||
try Player.including(required: Player.team).deleteAll(db)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
DELETE FROM "player" WHERE rowid IN (\
|
||||
SELECT "player"."rowid" \
|
||||
FROM "player" \
|
||||
JOIN "team" ON "team"."id" = "player"."teamId")
|
||||
""")
|
||||
}
|
||||
do {
|
||||
let alias = TableAlias(name: "p")
|
||||
try Player.aliased(alias).including(required: Player.team).deleteAll(db)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
DELETE FROM "player" WHERE rowid IN (\
|
||||
SELECT "p"."rowid" \
|
||||
FROM "player" "p" \
|
||||
JOIN "team" ON "team"."id" = "p"."teamId")
|
||||
""")
|
||||
}
|
||||
do {
|
||||
try Team.having(Team.players.isEmpty).deleteAll(db)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
DELETE FROM "team" WHERE rowid IN (\
|
||||
SELECT "team"."rowid" \
|
||||
FROM "team" \
|
||||
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
|
||||
GROUP BY "team"."id" \
|
||||
HAVING COUNT(DISTINCT "player"."rowid") = 0)
|
||||
""")
|
||||
}
|
||||
do {
|
||||
try Team.including(all: Team.players).deleteAll(db)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
DELETE FROM "team"
|
||||
""")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testGroupedRequestDelete() throws {
|
||||
try makeDatabaseQueue().inDatabase { db in
|
||||
struct Player: MutablePersistableRecord {
|
||||
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
|
||||
}
|
||||
struct Passport: MutablePersistableRecord {
|
||||
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
|
||||
}
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("score", .integer)
|
||||
}
|
||||
try db.create(table: "passport") { t in
|
||||
t.column("countryCode", .text).notNull()
|
||||
t.column("citizenId", .integer).notNull()
|
||||
t.primaryKey(["countryCode", "citizenId"])
|
||||
}
|
||||
do {
|
||||
try Player.all().groupByPrimaryKey().deleteAll(db)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
DELETE FROM "player" WHERE rowid IN (\
|
||||
SELECT "rowid" \
|
||||
FROM "player" \
|
||||
GROUP BY "id")
|
||||
""")
|
||||
}
|
||||
do {
|
||||
try Player.all().group(Column.rowID).deleteAll(db)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
DELETE FROM "player" WHERE rowid IN (\
|
||||
SELECT "rowid" \
|
||||
FROM "player" \
|
||||
GROUP BY "rowid")
|
||||
""")
|
||||
}
|
||||
do {
|
||||
try Passport.all().groupByPrimaryKey().deleteAll(db)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
DELETE FROM "passport" WHERE rowid IN (\
|
||||
SELECT "rowid" \
|
||||
FROM "passport" \
|
||||
GROUP BY "countryCode", "citizenId")
|
||||
""")
|
||||
}
|
||||
do {
|
||||
try Passport.all().group(Column.rowID).deleteAll(db)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
DELETE FROM "passport" WHERE rowid IN (\
|
||||
SELECT "rowid" \
|
||||
FROM "passport" \
|
||||
GROUP BY "rowid")
|
||||
""")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import XCTest
|
||||
#if GRDBCUSTOMSQLITE
|
||||
import GRDBCustomSQLite
|
||||
import GRDBCustomSQLite
|
||||
#else
|
||||
import GRDB
|
||||
import GRDB
|
||||
#endif
|
||||
|
||||
private struct Player: Codable, PersistableRecord, FetchableRecord {
|
||||
@@ -10,6 +10,15 @@ private struct Player: Codable, PersistableRecord, FetchableRecord {
|
||||
var name: String
|
||||
var score: Int
|
||||
var bonus: Int
|
||||
|
||||
static func createTable(_ db: Database) throws {
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text)
|
||||
t.column("score", .integer)
|
||||
t.column("bonus", .integer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private enum Columns: String, ColumnExpression {
|
||||
@@ -23,19 +32,9 @@ private extension QueryInterfaceRequest where RowDecoder == Player {
|
||||
}
|
||||
|
||||
class MutablePersistableRecordUpdateTests: GRDBTestCase {
|
||||
override func setup(_ dbWriter: DatabaseWriter) throws {
|
||||
try dbWriter.write { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text)
|
||||
t.column("score", .integer)
|
||||
t.column("bonus", .integer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testRequestUpdateAll() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try Player.createTable(db)
|
||||
let assignment = Columns.score <- 0
|
||||
|
||||
try Player.updateAll(db, assignment)
|
||||
@@ -57,7 +56,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = 0 WHERE "id" IN (1, 2)
|
||||
""")
|
||||
|
||||
|
||||
try Player.filter(sql: "id = 1").updateAll(db, assignment)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = 0 WHERE id = 1
|
||||
@@ -67,7 +66,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = 0 WHERE (id = 1) AND (\"name\" = 'Arthur')
|
||||
""")
|
||||
|
||||
|
||||
try Player.select(Columns.name).updateAll(db, assignment)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = 0
|
||||
@@ -88,7 +87,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = 0
|
||||
""")
|
||||
|
||||
|
||||
try Player.order(Columns.name).limit(1).updateAll(db, assignment)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = 0 ORDER BY \"name\" LIMIT 1
|
||||
@@ -109,6 +108,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
|
||||
|
||||
func testComplexAssignment() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try Player.createTable(db)
|
||||
|
||||
try Player.updateAll(db, Columns.score <- Columns.score * (Columns.bonus + 1))
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" * ("bonus" + 1)
|
||||
@@ -118,6 +119,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
|
||||
|
||||
func testAssignmentSubtractAndAssign() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try Player.createTable(db)
|
||||
|
||||
try Player.updateAll(db, Columns.score -= 1)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" - 1
|
||||
@@ -132,7 +135,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" - (-"bonus")
|
||||
""")
|
||||
|
||||
|
||||
try Player.updateAll(db, Columns.score -= Columns.bonus * 2)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" - ("bonus" * 2)
|
||||
@@ -142,6 +145,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
|
||||
|
||||
func testAssignmentAddAndAssign() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try Player.createTable(db)
|
||||
|
||||
try Player.updateAll(db, Columns.score += 1)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" + 1
|
||||
@@ -156,7 +161,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" + (-"bonus")
|
||||
""")
|
||||
|
||||
|
||||
try Player.updateAll(db, Columns.score += Columns.bonus * 2)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" + ("bonus" * 2)
|
||||
@@ -166,6 +171,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
|
||||
|
||||
func testAssignmentMultiplyAndAssign() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try Player.createTable(db)
|
||||
|
||||
try Player.updateAll(db, Columns.score *= 1)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" * 1
|
||||
@@ -180,7 +187,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" * (-"bonus")
|
||||
""")
|
||||
|
||||
|
||||
try Player.updateAll(db, Columns.score *= Columns.bonus * 2)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" * ("bonus" * 2)
|
||||
@@ -190,6 +197,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
|
||||
|
||||
func testAssignmentDivideAndAssign() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try Player.createTable(db)
|
||||
|
||||
try Player.updateAll(db, Columns.score /= 1)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" / 1
|
||||
@@ -204,16 +213,18 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" / (-"bonus")
|
||||
""")
|
||||
|
||||
|
||||
try Player.updateAll(db, Columns.score /= Columns.bonus * 2)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" / ("bonus" * 2)
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func testMultipleAssignments() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try Player.createTable(db)
|
||||
|
||||
try Player.updateAll(db, Columns.score <- 0, Columns.bonus <- 1)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = 0, "bonus" = 1
|
||||
@@ -238,15 +249,17 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
|
||||
|
||||
func testUpdateAllWithoutAssignmentDoesNotAccessTheDatabase() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try Player.createTable(db)
|
||||
sqlQueries.removeAll()
|
||||
try XCTAssertEqual(Player.updateAll(db, []), 0)
|
||||
try XCTAssertEqual(Player.all().updateAll(db, []), 0)
|
||||
XCTAssert(sqlQueries.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func testUpdateAllReturnsNumberOfUpdatedRows() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try Player.createTable(db)
|
||||
try Player(id: 1, name: "Arthur", score: 0, bonus: 2).insert(db)
|
||||
try Player(id: 2, name: "Barbara", score: 0, bonus: 1).insert(db)
|
||||
try Player(id: 3, name: "Craig", score: 0, bonus: 0).insert(db)
|
||||
@@ -269,6 +282,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
|
||||
|
||||
func testQueryInterfaceExtension() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try Player.createTable(db)
|
||||
try Player(id: 1, name: "Arthur", score: 0, bonus: 0).insert(db)
|
||||
try Player(id: 2, name: "Barbara", score: 0, bonus: 0).insert(db)
|
||||
try Player(id: 3, name: "Craig", score: 0, bonus: 0).insert(db)
|
||||
@@ -289,6 +303,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
|
||||
func encode(to container: inout PersistenceContainer) { }
|
||||
}
|
||||
try makeDatabaseQueue().write { db in
|
||||
try Player.createTable(db)
|
||||
|
||||
try AbortPlayer.updateAll(db, Column("score") <- 0)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = 0
|
||||
@@ -303,7 +319,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = 0
|
||||
""")
|
||||
|
||||
|
||||
try AbortPlayer.all().updateAll(db, [Column("score") <- 0])
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = 0
|
||||
@@ -318,6 +334,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
|
||||
func encode(to container: inout PersistenceContainer) { }
|
||||
}
|
||||
try makeDatabaseQueue().write { db in
|
||||
try Player.createTable(db)
|
||||
|
||||
try IgnorePlayer.updateAll(db, Column("score") <- 0)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE OR IGNORE "player" SET "score" = 0
|
||||
@@ -342,6 +360,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
|
||||
|
||||
func testConflictPolicyCustom() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try Player.createTable(db)
|
||||
|
||||
try Player.updateAll(db, Column("score") <- 0)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = 0
|
||||
@@ -368,4 +388,123 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
func testJoinedRequestUpdate() throws {
|
||||
try makeDatabaseQueue().inDatabase { db in
|
||||
struct Player: MutablePersistableRecord {
|
||||
static let team = belongsTo(Team.self)
|
||||
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
|
||||
}
|
||||
|
||||
struct Team: MutablePersistableRecord {
|
||||
static let players = hasMany(Player.self)
|
||||
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
|
||||
}
|
||||
|
||||
try db.create(table: "team") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("active", .boolean)
|
||||
}
|
||||
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("teamId", .integer).references("team")
|
||||
t.column("score", .integer)
|
||||
}
|
||||
|
||||
do {
|
||||
try Player.including(required: Player.team).updateAll(db, Column("score") <- 0)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = 0 WHERE rowid IN (\
|
||||
SELECT "player"."rowid" \
|
||||
FROM "player" \
|
||||
JOIN "team" ON "team"."id" = "player"."teamId")
|
||||
""")
|
||||
}
|
||||
do {
|
||||
let alias = TableAlias(name: "p")
|
||||
try Player.aliased(alias).including(required: Player.team).updateAll(db, Column("score") <- 0)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = 0 WHERE rowid IN (\
|
||||
SELECT "p"."rowid" \
|
||||
FROM "player" "p" \
|
||||
JOIN "team" ON "team"."id" = "p"."teamId")
|
||||
""")
|
||||
}
|
||||
do {
|
||||
try Team.having(Team.players.isEmpty).updateAll(db, Column("active") <- false)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "team" SET "active" = 0 WHERE rowid IN (\
|
||||
SELECT "team"."rowid" \
|
||||
FROM "team" \
|
||||
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
|
||||
GROUP BY "team"."id" \
|
||||
HAVING COUNT(DISTINCT "player"."rowid") = 0)
|
||||
""")
|
||||
}
|
||||
do {
|
||||
try Team.including(all: Team.players).updateAll(db, Column("active") <- false)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "team" SET "active" = 0
|
||||
""")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testGroupedRequestUpdate() throws {
|
||||
try makeDatabaseQueue().inDatabase { db in
|
||||
struct Player: MutablePersistableRecord {
|
||||
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
|
||||
}
|
||||
struct Passport: MutablePersistableRecord {
|
||||
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
|
||||
}
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("score", .integer)
|
||||
}
|
||||
try db.create(table: "passport") { t in
|
||||
t.column("countryCode", .text).notNull()
|
||||
t.column("citizenId", .integer).notNull()
|
||||
t.column("active", .boolean)
|
||||
t.primaryKey(["countryCode", "citizenId"])
|
||||
}
|
||||
do {
|
||||
try Player.all().groupByPrimaryKey().updateAll(db, Column("score") <- 0)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = 0 WHERE rowid IN (\
|
||||
SELECT "rowid" \
|
||||
FROM "player" \
|
||||
GROUP BY "id")
|
||||
""")
|
||||
}
|
||||
do {
|
||||
try Player.all().group(Column.rowID).updateAll(db, Column("score") <- 0)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = 0 WHERE rowid IN (\
|
||||
SELECT "rowid" \
|
||||
FROM "player" \
|
||||
GROUP BY "rowid")
|
||||
""")
|
||||
}
|
||||
do {
|
||||
try Passport.all().groupByPrimaryKey().updateAll(db, Column("active") <- true)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "passport" SET "active" = 1 WHERE rowid IN (\
|
||||
SELECT "rowid" \
|
||||
FROM "passport" \
|
||||
GROUP BY "countryCode", "citizenId")
|
||||
""")
|
||||
}
|
||||
do {
|
||||
try Passport.all().group(Column.rowID).updateAll(db, Column("active") <- true)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "passport" SET "active" = 1 WHERE rowid IN (\
|
||||
SELECT "rowid" \
|
||||
FROM "passport" \
|
||||
GROUP BY "rowid")
|
||||
""")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user