diff --git a/CHANGELOG.md b/CHANGELOG.md index ecc509738..0f6d69d91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -81,7 +81,6 @@ Release Notes - GRDB is now able to store and load zero-length blobs. - ### New New features have been added in order to plug a few holes and support the [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) and [GRDBObjc](http://github.com/groue/GRDBObjc) companion projects: @@ -94,8 +93,15 @@ New features have been added in order to plug a few holes and support the [RxGRD print(dict) // Prints {"id": 1, "name": "Arthur", "score": 1000} ``` + +- Query interface requests learned how to limit the number of deleted rows: - This dictionary supports generic SQLite tools, and is not intended as a general encoding purpose because it contains values of type DatabaseValue. For example, dates are encoded as SQLite-friendly strings. + ```swift + // Delete the worse ten players: + // DELETE FROM players ORDER BY score LIMIT 10 + let request = Player.order(scoreColumn).limit(10) + try request.deleteAll(db) + ``` - Prepared statements know the index of their columns: @@ -111,6 +117,12 @@ New features have been added in order to plug a few holes and support the [RxGRD let statement = rows.statement ``` +- One can build a Set from a cursor: + + ```swift + let strings = try Set(String.fetchCursor(...)) + ``` + ### Breaking Changes @@ -219,6 +231,10 @@ New features have been added in order to plug a few holes and support the [RxGRD + init() +} ++extension Set { ++ init(_ cursor: C) throws where C.Element == Element ++} + -final class DatabaseCursor { } +final class ColumnCursor : Cursor { + typealias Element = Value diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index f7b90dd57..525b9c3e1 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -11,6 +11,19 @@ extension Array { } } +extension Set { + /// Creates a set containing the elements of a cursor. + /// + /// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'foo'") + /// let strings = try Set(cursor) // ["foo"] + public init(_ cursor: C) throws where C.Element == Element { + self.init() + while let element = try cursor.next() { + insert(element) + } + } +} + /// A type that supplies the values of some external resource, one at a time. /// /// ## Overview diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 508003bc8..d0abfcde6 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -255,6 +255,9 @@ public final class Database { // MARK: - Database Information + /// The list of compile options used when building SQLite + static let sqliteCompileOptions: Set = DatabaseQueue().inDatabase { try! Set(String.fetchCursor($0, "PRAGMA COMPILE_OPTIONS")) } + /// The database configuration public let configuration: Configuration diff --git a/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift b/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift index 3deb6880a..9724f1782 100644 --- a/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift +++ b/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift @@ -59,26 +59,7 @@ struct QueryInterfaceSelectQueryDefinition { sql += " HAVING " + havingExpression.expressionSQL(&arguments) } - var orderings = self.orderings - if isReversed { - if orderings.isEmpty { - // https://www.sqlite.org/lang_createtable.html#rowid - // - // > The rowid value can be accessed using one of the special - // > case-independent names "rowid", "oid", or "_rowid_" in - // > place of a column name. If a table contains a user defined - // > column named "rowid", "oid" or "_rowid_", then that name - // > always refers the explicitly declared column and cannot be - // > used to retrieve the integer rowid value. - // - // Here we assume that rowid is not a custom column. - // TODO: support for user-defined rowid column. - // TODO: support for WITHOUT ROWID tables. - orderings = [Column.rowID.desc] - } else { - orderings = orderings.map { $0.reversed } - } - } + let orderings = self.queryOrderings if !orderings.isEmpty { sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ") } @@ -101,11 +82,6 @@ struct QueryInterfaceSelectQueryDefinition { fatalError("Can't delete query with GROUP BY expression") } - guard limit == nil else { - // Programmer error - fatalError("Can't delete query with limit") - } - var sql = "DELETE" var arguments: StatementArguments? = StatementArguments() @@ -117,11 +93,48 @@ struct QueryInterfaceSelectQueryDefinition { sql += " WHERE " + whereExpression.expressionSQL(&arguments) } + if let limit = limit { + let orderings = self.queryOrderings + if !orderings.isEmpty { + sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ") + } + + if Database.sqliteCompileOptions.contains("ENABLE_UPDATE_DELETE_LIMIT") { + sql += " LIMIT " + limit.sql + } else { + fatalError("Can't delete query with limit") + } + } + let statement = try db.makeUpdateStatement(sql) statement.arguments = arguments! return statement } + private var queryOrderings: [SQLOrderingTerm] { + if isReversed { + if orderings.isEmpty { + // https://www.sqlite.org/lang_createtable.html#rowid + // + // > The rowid value can be accessed using one of the special + // > case-independent names "rowid", "oid", or "_rowid_" in + // > place of a column name. If a table contains a user defined + // > column named "rowid", "oid" or "_rowid_", then that name + // > always refers the explicitly declared column and cannot be + // > used to retrieve the integer rowid value. + // + // Here we assume that rowid is not a custom column. + // TODO: support for user-defined rowid column. + // TODO: support for WITHOUT ROWID tables. + return [Column.rowID.desc] + } else { + return orderings.map { $0.reversed } + } + } else { + return orderings + } + } + /// Remove ordering var unorderedQuery: QueryInterfaceSelectQueryDefinition { var query = self diff --git a/Tests/GRDBTests/MutablePersistableDeleteTests.swift b/Tests/GRDBTests/MutablePersistableDeleteTests.swift index ed275bac2..d6ba182e0 100644 --- a/Tests/GRDBTests/MutablePersistableDeleteTests.swift +++ b/Tests/GRDBTests/MutablePersistableDeleteTests.swift @@ -158,6 +158,18 @@ class MutablePersistableDeleteTests: GRDBTestCase { try Person.order(Column("name")).deleteAll(db) XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\"") + + try Person.limit(1).deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" LIMIT 1") + + try Person.order(Column("name")).limit(1).deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" ORDER BY \"name\" LIMIT 1") + + try Person.order(Column("name")).limit(1, offset: 2).reversed().deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" ORDER BY \"name\" DESC LIMIT 1 OFFSET 2") + + try Person.limit(1, offset: 2).reversed().deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" ORDER BY \"rowid\" DESC LIMIT 1 OFFSET 2") } } }