From 376d29585302f7cdf3336842b5360e54156db1be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 18 Aug 2017 16:27:24 +0200 Subject: [PATCH] Replace TableMapping.selectsRowID with TableMapping.databaseSelection --- CHANGELOG.md | 34 ++++++++ GRDB.xcodeproj/project.pbxproj | 18 ++++ .../FTS3+QueryInterfaceRequest.swift | 10 +-- GRDB/QueryInterface/FTS5+QueryInterface.swift | 10 +-- .../QueryInterfaceRequest.swift | 84 +++++++------------ .../QueryInterfaceSelectQueryDefinition.swift | 8 +- GRDB/QueryInterface/SQLExpression.swift | 2 +- .../SQLSelectable+QueryInterface.swift | 34 ++++++-- GRDB/QueryInterface/SQLSelectable.swift | 2 +- GRDB/Record/FetchedRecordsController.swift | 13 +-- GRDB/Record/Record.swift | 31 +++++-- GRDB/Record/RowConvertible+TableMapping.swift | 15 ++++ GRDB/Record/TableMapping.swift | 42 ++++++++-- README.md | 58 +++++++++++-- .../GRDBTests/CompilationSubClassTests.swift | 2 +- Tests/GRDBTests/FTS3RecordTests.swift | 2 +- Tests/GRDBTests/FTS4RecordTests.swift | 4 +- Tests/GRDBTests/FTS5RecordTests.swift | 4 +- .../RecordPrimaryKeyHiddenRowIDTests.swift | 4 +- Tests/GRDBTests/TableMappingTests.swift | 49 +++++++++++ 20 files changed, 314 insertions(+), 112 deletions(-) create mode 100644 Tests/GRDBTests/TableMappingTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e0f4c68f..8bd5dd8c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,9 +18,24 @@ Release Notes - The deprecated `TableMapping.primaryKeyRowComparator` method has been removed. +- The `TableMapping.selectsRowID` property has been replaced with `TableMapping.databaseSelection`. + + To upgrade, replace: + + ```swift + struct Player: TableMapping { + - static let selectsRowID = true + + static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] + } + ``` + **API diff** ```diff ++struct AllColumns { ++ init() ++} + class Row { - func value(atIndex index: Int) -> DatabaseValueConvertible? - func value(atIndex index: Int) -> Value? @@ -41,6 +56,16 @@ Release Notes + subscript(_ column: Column) -> Value? + subscript(_ column: Column) -> Value } + + class Record { +- open class var selectsRowID: Bool ++ open class var databaseSelection: [SQLSelectable] + } + + protocol TableMapping { +- static var selectsRowID: Bool { get } ++ static var databaseSelection: [SQLSelectable] { get } + } extension TableMapping { - @available(*, deprecated) @@ -48,6 +73,15 @@ Release Notes } ``` +**Experimental API diff** + +```diff + enum SQLCount { +- case star ++ case all + } +``` + ## 1.3.0 diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 1d046e820..1ba87cc3b 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -1492,6 +1492,14 @@ 56FC987D1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; 56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; 56FDECE31BB32DFD009AD709 /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; + 56FEE7FB1F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; + 56FEE7FC1F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; + 56FEE7FD1F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; + 56FEE7FE1F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; + 56FEE7FF1F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; + 56FEE8001F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; + 56FEE8011F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; + 56FEE8021F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; 56FF45411D2C23BA00F21EF9 /* TableMappingDeleteByKeyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* TableMappingDeleteByKeyTests.swift */; }; 56FF45421D2C23BA00F21EF9 /* TableMappingDeleteByKeyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* TableMappingDeleteByKeyTests.swift */; }; 56FF45431D2C23BA00F21EF9 /* TableMappingDeleteByKeyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* TableMappingDeleteByKeyTests.swift */; }; @@ -2220,6 +2228,7 @@ 56F3E7621E67F8C100BF0F01 /* Fixits-0.101.1.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.101.1.swift"; sourceTree = ""; }; 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; + 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableMappingTests.swift; sourceTree = ""; }; 56FF453F1D2C23BA00F21EF9 /* TableMappingDeleteByKeyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableMappingDeleteByKeyTests.swift; sourceTree = ""; }; 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = ""; }; 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = ""; }; @@ -2527,6 +2536,7 @@ isa = PBXGroup; children = ( 56FF453F1D2C23BA00F21EF9 /* TableMappingDeleteByKeyTests.swift */, + 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */, ); name = TableMapping; sourceTree = ""; @@ -4107,6 +4117,7 @@ 560FC5891CB00B880014AA8E /* TransactionObserverTests.swift in Sources */, 5674A72C1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */, 56C3F7541CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, + 56FEE7FC1F47253700D930EA /* TableMappingTests.swift in Sources */, 56F3E74A1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 567A80541D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 560FC58B1CB00B880014AA8E /* DatabaseValueTests.swift in Sources */, @@ -4354,6 +4365,7 @@ 567156481CB16729007DC145 /* DatabaseValueTests.swift in Sources */, 5674A72E1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */, 5671564A1CB16729007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */, + 56FEE7FD1F47253700D930EA /* TableMappingTests.swift in Sources */, 56F3E74B1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 5671564B1CB16729007DC145 /* Row+FoundationTests.swift in Sources */, 56A8C2431D1918EE0096E9D4 /* FoundationNSUUIDTests.swift in Sources */, @@ -4581,6 +4593,7 @@ 5698AC451DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 5674A72B1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */, 56AF74701D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, + 56FEE8001F47253700D930EA /* TableMappingTests.swift in Sources */, 56F3E74E1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 5690C33C1D23E7D200E59934 /* FoundationDateTests.swift in Sources */, 56AFCA581CB1AA9900F48B96 /* Row+FoundationTests.swift in Sources */, @@ -4717,6 +4730,7 @@ 56AF74711D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, 5674A7281F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */, 56AFCAAE1CB1ABC800F48B96 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, + 56FEE8011F47253700D930EA /* TableMappingTests.swift in Sources */, 56F3E74F1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 56AFCAAF1CB1ABC800F48B96 /* DatabasePoolConcurrencyTests.swift in Sources */, 56AFCAB01CB1ABC800F48B96 /* TransactionObserverTests.swift in Sources */, @@ -4943,6 +4957,7 @@ 5623935B1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 5674A72D1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */, 56176C701EACCCC9000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, + 56FEE7FF1F47253700D930EA /* TableMappingTests.swift in Sources */, 56A2386A1B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */, 56A2383E1B9C74A90082EB20 /* DatabaseValueTests.swift in Sources */, 567156181CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */, @@ -5079,6 +5094,7 @@ 5698AC9E1DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, 5674A72A1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */, 56176C5E1EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, + 56FEE7FB1F47253700D930EA /* TableMappingTests.swift in Sources */, 56D496641D81304E008276D7 /* FoundationUUIDTests.swift in Sources */, 56D496921D81316E008276D7 /* RowFromDictionaryLiteralTests.swift in Sources */, 562206081E420EA4005860AC /* DatabasePoolReadOnlyTests.swift in Sources */, @@ -5397,6 +5413,7 @@ 5690C33E1D23E7D200E59934 /* FoundationDateTests.swift in Sources */, 567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 5674A7291F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */, + 56FEE8021F47253700D930EA /* TableMappingTests.swift in Sources */, F3BA81211CFB3063003DC1BA /* RecordPrimaryKeyNoneTests.swift in Sources */, F3BA80F71CFB3021003DC1BA /* SelectStatementTests.swift in Sources */, 56F3E7501E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, @@ -5624,6 +5641,7 @@ 5698AC061D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, F3BA80FA1CFB3021003DC1BA /* SelectStatementTests.swift in Sources */, 5674A7271F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */, + 56FEE7FE1F47253700D930EA /* TableMappingTests.swift in Sources */, F3BA81191CFB305F003DC1BA /* QueryInterfaceRequestTests.swift in Sources */, F3BA812F1CFB3064003DC1BA /* RecordPrimaryKeyNoneTests.swift in Sources */, 5690C33A1D23E7D200E59934 /* FoundationDateTests.swift in Sources */, diff --git a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift index e6c6130cb..aa1229783 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift @@ -31,14 +31,12 @@ extension TableMapping { /// // SELECT * FROM books WHERE books MATCH '...' /// var request = Book.matching(pattern) /// - /// If the `selectsRowID` type property is true, then the selection includes - /// the hidden "rowid" column: - /// - /// // SELECT *, rowid FROM books WHERE books MATCH '...' - /// var request = Book.matching(pattern) - /// /// If the search pattern is nil, the request does not match any /// database row. + /// + /// The selection defaults to all columns. This default can be changed for + /// all requests by the `TableMapping.databaseSelection` property, or + /// for individual requests with the `TableMapping.select` method. public static func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest { return all().matching(pattern) } diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index df1857d91..bb0191eae 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -12,6 +12,10 @@ /// /// If the search pattern is nil, the request does not match any /// database row. + /// + /// The selection defaults to all columns. This default can be changed for + /// all requests by the `TableMapping.databaseSelection` property, or + /// for individual requests with the `TableMapping.select` method. public func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest { switch query.source { case .table(let name, let alias)?: @@ -36,12 +40,6 @@ /// // SELECT * FROM books WHERE books MATCH '...' /// var request = Book.matching(pattern) /// - /// If the `selectsRowID` type property is true, then the selection - /// includes the hidden "rowid" column: - /// - /// // SELECT *, rowid FROM books WHERE books MATCH '...' - /// var request = Book.matching(pattern) - /// /// If the search pattern is nil, the request does not match any /// database row. public static func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest { diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 06a33ab36..858517d33 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -258,21 +258,13 @@ extension TableMapping { /// Creates a QueryInterfaceRequest which fetches all records. /// /// // SELECT * FROM persons - /// var request = Person.all() + /// let request = Person.all() /// - /// If the `selectsRowID` type property is true, then the selection includes - /// the hidden "rowid" column: - /// - /// // SELECT *, rowid FROM persons - /// var request = Person.all() + /// The selection defaults to all columns. This default can be changed for + /// all requests by the `TableMapping.databaseSelection` property, or + /// for individual requests with the `TableMapping.select` method. public static func all() -> QueryInterfaceRequest { - let selection: [SQLSelectable] - if selectsRowID { - selection = [SQLStar(), Column.rowID] - } else { - selection = [SQLStar()] - } - return QueryInterfaceRequest(query: QueryInterfaceSelectQueryDefinition(select: selection, from: .table(name: databaseTableName, alias: nil))) + return QueryInterfaceRequest(query: QueryInterfaceSelectQueryDefinition(select: databaseSelection, from: .table(name: databaseTableName, alias: nil))) } /// Creates a QueryInterfaceRequest which fetches no record. @@ -283,7 +275,7 @@ extension TableMapping { /// Creates a QueryInterfaceRequest which selects *selection*. /// /// // SELECT id, email FROM persons - /// var request = Person.select(Column("id"), Column("email")) + /// let request = Person.select(Column("id"), Column("email")) public static func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest { return all().select(selection) } @@ -291,7 +283,7 @@ extension TableMapping { /// Creates a QueryInterfaceRequest which selects *selection*. /// /// // SELECT id, email FROM persons - /// var request = Person.select([Column("id"), Column("email")]) + /// let request = Person.select([Column("id"), Column("email")]) public static func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest { return all().select(selection) } @@ -299,7 +291,7 @@ extension TableMapping { /// Creates a QueryInterfaceRequest which selects *sql*. /// /// // SELECT id, email FROM persons - /// var request = Person.select(sql: "id, email") + /// let request = Person.select(sql: "id, email") public static func select(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { return all().select(sql: sql, arguments: arguments) } @@ -307,13 +299,11 @@ extension TableMapping { /// Creates a QueryInterfaceRequest with the provided *predicate*. /// /// // SELECT * FROM persons WHERE email = 'arthur@example.com' - /// var request = Person.filter(Column("email") == "arthur@example.com") + /// let request = Person.filter(Column("email") == "arthur@example.com") /// - /// If the `selectsRowID` type property is true, then the selection includes - /// the hidden "rowid" column: - /// - /// // SELECT *, rowid FROM persons WHERE email = 'arthur@example.com' - /// var request = Person.filter(Column("email") == "arthur@example.com") + /// The selection defaults to all columns. This default can be changed for + /// all requests by the `TableMapping.databaseSelection` property, or + /// for individual requests with the `TableMapping.select` method. public static func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest { return all().filter(predicate) } @@ -321,13 +311,11 @@ extension TableMapping { /// Creates a QueryInterfaceRequest with the provided *predicate*. /// /// // SELECT * FROM persons WHERE email = 'arthur@example.com' - /// var request = Person.filter(sql: "email = ?", arguments: ["arthur@example.com"]) + /// let request = Person.filter(sql: "email = ?", arguments: ["arthur@example.com"]) /// - /// If the `selectsRowID` type property is true, then the selection includes - /// the hidden "rowid" column: - /// - /// // SELECT *, rowid FROM persons WHERE email = 'arthur@example.com' - /// var request = Person.filter(sql: "email = ?", arguments: ["arthur@example.com"]) + /// The selection defaults to all columns. This default can be changed for + /// all requests by the `TableMapping.databaseSelection` property, or + /// for individual requests with the `TableMapping.select` method. public static func filter(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { return all().filter(sql: sql, arguments: arguments) } @@ -336,13 +324,11 @@ extension TableMapping { /// provided *orderings*. /// /// // SELECT * FROM persons ORDER BY name - /// var request = Person.order(Column("name")) + /// let request = Person.order(Column("name")) /// - /// If the `selectsRowID` type property is true, then the selection includes - /// the hidden "rowid" column: - /// - /// // SELECT *, rowid FROM persons ORDER BY name - /// var request = Person.order(Column("name")) + /// The selection defaults to all columns. This default can be changed for + /// all requests by the `TableMapping.databaseSelection` property, or + /// for individual requests with the `TableMapping.select` method. public static func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest { return all().order(orderings) } @@ -351,13 +337,11 @@ extension TableMapping { /// provided *orderings*. /// /// // SELECT * FROM persons ORDER BY name - /// var request = Person.order([Column("name")]) + /// let request = Person.order([Column("name")]) /// - /// If the `selectsRowID` type property is true, then the selection includes - /// the hidden "rowid" column: - /// - /// // SELECT *, rowid FROM persons ORDER BY name - /// var request = Person.order([Column("name")]) + /// The selection defaults to all columns. This default can be changed for + /// all requests by the `TableMapping.databaseSelection` property, or + /// for individual requests with the `TableMapping.select` method. public static func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest { return all().order(orderings) } @@ -365,13 +349,11 @@ extension TableMapping { /// Creates a QueryInterfaceRequest sorted according to *sql*. /// /// // SELECT * FROM persons ORDER BY name - /// var request = Person.order(sql: "name") + /// let request = Person.order(sql: "name") /// - /// If the `selectsRowID` type property is true, then the selection includes - /// the hidden "rowid" column: - /// - /// // SELECT *, rowid FROM persons ORDER BY name - /// var request = Person.order(sql: "name") + /// The selection defaults to all columns. This default can be changed for + /// all requests by the `TableMapping.databaseSelection` property, or + /// for individual requests with the `TableMapping.select` method. public static func order(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { return all().order(sql: sql, arguments: arguments) } @@ -380,13 +362,11 @@ extension TableMapping { /// *offset*. /// /// // SELECT * FROM persons LIMIT 1 - /// var request = Person.limit(1) + /// let request = Person.limit(1) /// - /// If the `selectsRowID` type property is true, then the selection includes - /// the hidden "rowid" column: - /// - /// // SELECT *, rowid FROM persons LIMIT 1 - /// var request = Person.limit(1) + /// The selection defaults to all columns. This default can be changed for + /// all requests by the `TableMapping.databaseSelection` property, or + /// for individual requests with the `TableMapping.select` method. public static func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { return all().limit(limit, offset: offset) } diff --git a/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift b/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift index 2bba12190..3deb6880a 100644 --- a/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift +++ b/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift @@ -176,7 +176,7 @@ extension QueryInterfaceSelectQueryDefinition : Request { // -> // SELECT COUNT(*) FROM tableName ... var countQuery = unorderedQuery - countQuery.selection = [SQLExpressionCount(SQLStar())] + countQuery.selection = [SQLExpressionCount(AllColumns())] return countQuery } } @@ -184,7 +184,7 @@ extension QueryInterfaceSelectQueryDefinition : Request { // SELECT COUNT(*) FROM (self) private var trivialCountQuery: QueryInterfaceSelectQueryDefinition { return QueryInterfaceSelectQueryDefinition( - select: [SQLExpressionCount(SQLStar())], + select: [SQLExpressionCount(AllColumns())], from: .query(query: unorderedQuery, alias: nil)) } } @@ -227,8 +227,8 @@ struct SQLLimit { extension SQLCount { var sqlSelectable: SQLSelectable { switch self { - case .star: - return SQLExpressionCount(SQLStar()) + case .all: + return SQLExpressionCount(AllColumns()) case .distinct(let expression): return SQLExpressionCountDistinct(expression) } diff --git a/GRDB/QueryInterface/SQLExpression.swift b/GRDB/QueryInterface/SQLExpression.swift index 88839e008..a9d1328bf 100644 --- a/GRDB/QueryInterface/SQLExpression.swift +++ b/GRDB/QueryInterface/SQLExpression.swift @@ -94,7 +94,7 @@ extension SQLExpression { // SELECT expr FROM tableName ... // -> // SELECT COUNT(*) FROM tableName ... - return .star + return .all } } } diff --git a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift index 537bebf53..5d16e2392 100644 --- a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift @@ -1,15 +1,37 @@ -// MARK: - SQLStar +// MARK: - AllColumns -struct SQLStar : SQLSelectable { - func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { +/// AllColumns is the `*` in `SELECT *`. +/// +/// You use AllColumns in your custom implementation of +/// TableMapping.databaseSelection. +/// +/// For example: +/// +/// struct Person : TableMapping { +/// static var databaseTableName = "persons" +/// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] +/// } +/// +/// // SELECT *, rowid FROM persons +/// let request = Person.all() +public struct AllColumns { + /// + public init() { } +} + +extension AllColumns : SQLSelectable { + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { return "*" } - func countedSQL(_ arguments: inout StatementArguments?) -> String { + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + public func countedSQL(_ arguments: inout StatementArguments?) -> String { return "*" } - func count(distinct: Bool) -> SQLCount? { + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + public func count(distinct: Bool) -> SQLCount? { // SELECT DISTINCT * FROM tableName ... guard !distinct else { return nil @@ -18,7 +40,7 @@ struct SQLStar : SQLSelectable { // SELECT * FROM tableName ... // -> // SELECT COUNT(*) FROM tableName ... - return .star + return .all } } diff --git a/GRDB/QueryInterface/SQLSelectable.swift b/GRDB/QueryInterface/SQLSelectable.swift index 7bf30db6e..c3492980c 100644 --- a/GRDB/QueryInterface/SQLSelectable.swift +++ b/GRDB/QueryInterface/SQLSelectable.swift @@ -22,7 +22,7 @@ public enum SQLCount { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Represents COUNT(*) - case star + case all /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 1bb93edc4..87f1f401e 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -486,16 +486,14 @@ extension FetchedRecordsController where Record: TableMapping { let columns: [String] if let primaryKey = try db.primaryKey(Record.databaseTableName) { columns = primaryKey.columns - } else if Record.selectsRowID { - columns = [Column.rowID.name] } else { - // No primary key => can't compare rows - return { _,_ in false } + columns = [Column.rowID.name] } // Compare primary keys assert(!columns.isEmpty) return { (lItem, rItem) in + var notNullValue = false for column in columns { let lValue: DatabaseValue = lItem.row[column] let rValue: DatabaseValue = rItem.row[column] @@ -503,9 +501,12 @@ extension FetchedRecordsController where Record: TableMapping { // different primary keys return false } + if !lValue.isNull || !rValue.isNull { + notNullValue = true + } } - // identical primary keys - return true + // identical primary keys iff at least one value is not null + return notNullValue } } try self.init( diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index a54d037ae..ad9afe08e 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -60,20 +60,37 @@ open class Record : RowConvertible, TableMapping, Persistable { return PersistenceConflictPolicy(insert: .abort, update: .abort) } - /// This flag tells whether the hidden "rowid" column should be fetched - /// with other columns. + /// The default request selection. /// - /// Its default value is false: + /// Unless this method is overriden, requests select all columns: /// /// // SELECT * FROM persons /// try Person.fetchAll(db) /// - /// When true, the rowid column is fetched: + /// You can override this property and provide an explicit list + /// of columns: + /// + /// class RestrictedPerson : Record { + /// override static var databaseSelection: [SQLSelectable] { + /// return [Column("id"), Column("name")] + /// } + /// } + /// + /// // SELECT id, name FROM persons + /// try RestrictedPerson.fetchAll(db) + /// + /// You can also add extra columns such as the `rowid` column: + /// + /// class ExtendedPerson : Person { + /// override static var databaseSelection: [SQLSelectable] { + /// return [AllColumns(), Column.rowID] + /// } + /// } /// /// // SELECT *, rowid FROM persons - /// try Person.fetchAll(db) - open class var selectsRowID: Bool { - return false + /// try ExtendedPerson.fetchAll(db) + open class var databaseSelection: [SQLSelectable] { + return [AllColumns()] } diff --git a/GRDB/Record/RowConvertible+TableMapping.swift b/GRDB/Record/RowConvertible+TableMapping.swift index b6a77e5a4..160aed3c6 100644 --- a/GRDB/Record/RowConvertible+TableMapping.swift +++ b/GRDB/Record/RowConvertible+TableMapping.swift @@ -4,6 +4,7 @@ extension RowConvertible where Self: TableMapping { /// A cursor over all records fetched from the database. /// + /// // SELECT * FROM persons /// let persons = try Person.fetchCursor(db) // DatabaseCursor /// while let person = try persons.next() { // Person /// ... @@ -16,6 +17,10 @@ extension RowConvertible where Self: TableMapping { /// /// The cursor must be iterated in a protected dispath queue. /// + /// The selection defaults to all columns. This default can be changed for + /// all requests by the `TableMapping.databaseSelection` property, or + /// for individual requests with the `TableMapping.select` method. + /// /// - parameter db: A database connection. /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. @@ -25,8 +30,13 @@ extension RowConvertible where Self: TableMapping { /// An array of all records fetched from the database. /// + /// // SELECT * FROM persons /// let persons = try Person.fetchAll(db) // [Person] /// + /// The selection defaults to all columns. This default can be changed for + /// all requests by the `TableMapping.databaseSelection` property, or + /// for individual requests with the `TableMapping.select` method. + /// /// - parameter db: A database connection. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database) throws -> [Self] { @@ -35,8 +45,13 @@ extension RowConvertible where Self: TableMapping { /// The first found record. /// + /// // SELECT * FROM persons /// let person = try Person.fetchOne(db) // Person? /// + /// The selection defaults to all columns. This default can be changed for + /// all requests by the `TableMapping.databaseSelection` property, or + /// for individual requests with the `TableMapping.select` method. + /// /// - parameter db: A database connection. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database) throws -> Self? { diff --git a/GRDB/Record/TableMapping.swift b/GRDB/Record/TableMapping.swift index 5ff9dc3be..506b18373 100644 --- a/GRDB/Record/TableMapping.swift +++ b/GRDB/Record/TableMapping.swift @@ -9,27 +9,51 @@ /// /// TableMapping is adopted by Record. public protocol TableMapping { - /// The name of the database table + /// The name of the database table used to build requests. + /// + /// struct Person : TableMapping { + /// static var databaseTableName = "persons" + /// } + /// + /// // SELECT * FROM persons + /// try RestrictedPerson.fetchAll(db) static var databaseTableName: String { get } - /// This flag tells whether the hidden "rowid" column should be fetched - /// with other columns. + /// The default request selection. /// - /// Its default value is false: + /// Unless said otherwise, requests select all columns: /// /// // SELECT * FROM persons /// try Person.fetchAll(db) /// - /// When true, the rowid column is fetched: + /// You can provide a custom implementation and provide an explicit list + /// of columns: + /// + /// struct RestrictedPerson : TableMapping { + /// static var databaseTableName = "persons" + /// static var databaseSelection = [Column("id"), Column("name")] + /// } + /// + /// // SELECT id, name FROM persons + /// try RestrictedPerson.fetchAll(db) + /// + /// You can also add extra columns such as the `rowid` column: + /// + /// struct ExtendedPerson : TableMapping { + /// static var databaseTableName = "persons" + /// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] + /// } /// /// // SELECT *, rowid FROM persons - /// try Person.fetchAll(db) - static var selectsRowID: Bool { get } + /// try ExtendedPerson.fetchAll(db) + static var databaseSelection: [SQLSelectable] { get } } extension TableMapping { - /// Default value: false. - public static var selectsRowID: Bool { return false } + /// Default value: `[AllColumns()]`. + public static var databaseSelection: [SQLSelectable] { + return [AllColumns()] + } } extension TableMapping { diff --git a/README.md b/README.md index 177ba95c5..94e90ca49 100644 --- a/README.md +++ b/README.md @@ -2017,11 +2017,11 @@ Occasionnally, you'll want to write a complex SQL query that uses different colu ```swift protocol TableMapping { static var databaseTableName: String { get } - static var selectsRowID: Bool { get } + static var databaseSelection: [SQLSelectable] { get } } ``` -The `databaseTableName` type property is the name of a database table. `selectsRowID` is optional, and documented in the [The Implicit RowID Primary Key](#the-implicit-rowid-primary-key) chapter. +The `databaseTableName` type property is the name of a database table. `databaseSelection` is optional, and documented in the [Columns Selected by a Request](#columns-selected-by-a-request) chapter. **To use TableMapping**, subclass the [Record](#record-class) class, or adopt it explicitely. For example: @@ -2034,6 +2034,7 @@ extension PointOfInterest : TableMapping { Adopting types can be fetched without SQL, using the [query interface](#the-query-interface): ```swift +// SELECT * FROM pointOfInterests WHERE name = 'Paris' let paris = try PointOfInterest.filter(nameColumn == "Paris").fetchOne(db) ``` @@ -2437,17 +2438,17 @@ Without primary key, records don't have any identity, and the [persistence metho When SQLite won't let you provide an explicit primary key (as in [full-text](#full-text-search) tables, for example), you may want to make your record type fully aware of the hidden rowid column: -1. Have the `selectsRowID` static property from the [TableMapping](#tablemapping-protocol) protocol be true. +1. Have the `databaseSelection` static property (from the [TableMapping](#tablemapping-protocol) protocol) return the hidden rowid column: ```swift struct Event : TableMapping { - static let selectsRowID = true + static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] } // When you subclass Record, you need an override: class Book : Record { - override class var selectsRowID: Bool { - return true + override class var databaseSelection: [SQLSelectable] { + return [AllColums(), Column.rowID] } } ``` @@ -2670,6 +2671,7 @@ So don't miss the [SQL API](#sqlite-api). - [Database Schema](#database-schema) - [Requests](#requests) + - [Columns Selected by a Request](#columns-selected-by-a-request) - [Expressions](#expressions) - [SQL Operators](#sql-operators) - [SQL Functions](#sql-functions) @@ -3006,6 +3008,50 @@ Person ``` +### Columns Selected by a Request + +By default, query interface requests select all columns: + +```swift +// SELECT * FROM persons +let request = Person.all() +``` + +**The selection can be changed for each individual requests, or for all requests built from a given type.** + +To specify the selection of a specific request, use the `select` method: + +```swift +// SELECT id, name FROM persons +let request = Person.select(Column("id"), Column("name")) + +// SELECT *, rowid FROM persons +let request = Person.select(AllColumns(), Column.rowID) +``` + +To specify the default selection for all requests built from a type, define the `databaseSelection` property: + +```swift +struct RestrictedPerson : TableMapping { + static let databaseTableName = "persons" + static let databaseSelection: [SQLSelectable] = [Column("id"), Column("name")] +} + +struct ExtendedPerson : TableMapping { + static let databaseTableName = "persons" + static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] +} + +// SELECT id, name FROM persons +let request = RestrictedPerson.all() + +// SELECT *, rowid FROM persons +let request = ExtendedPerson.all() +``` + +> :point_up: **Note**: make sure the `databaseSelection` property is explicitely declared as `[SQLSelectable]`. If it is not, the Swift compiler may infer a type which may silently miss the protocol requirement, resulting in sticky `SELECT *` requests. + + ## Expressions Feed [requests](#requests) with SQL expressions built from your Swift code: diff --git a/Tests/GRDBTests/CompilationSubClassTests.swift b/Tests/GRDBTests/CompilationSubClassTests.swift index 049de8207..826b57088 100644 --- a/Tests/GRDBTests/CompilationSubClassTests.swift +++ b/Tests/GRDBTests/CompilationSubClassTests.swift @@ -16,7 +16,7 @@ private class UserRecord : Record { required init(row: Row) { super.init(row: row) } override class var databaseTableName: String { return super.databaseTableName } override class var persistenceConflictPolicy: PersistenceConflictPolicy { return super.persistenceConflictPolicy } - override class var selectsRowID: Bool { return super.selectsRowID } + override class var databaseSelection: [SQLSelectable] { return super.databaseSelection } override func encode(to container: inout PersistenceContainer) { super.encode(to: &container) } override func didInsert(with rowID: Int64, for column: String?) { super.didInsert(with: rowID, for: column) } override func copy() -> Self { preconditionFailure() } diff --git a/Tests/GRDBTests/FTS3RecordTests.swift b/Tests/GRDBTests/FTS3RecordTests.swift index 47bc242f2..1d0404233 100644 --- a/Tests/GRDBTests/FTS3RecordTests.swift +++ b/Tests/GRDBTests/FTS3RecordTests.swift @@ -25,7 +25,7 @@ extension Book : RowConvertible { extension Book : MutablePersistable { static let databaseTableName = "books" - static let selectsRowID = true + static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] func encode(to container: inout PersistenceContainer) { container[.rowID] = id diff --git a/Tests/GRDBTests/FTS4RecordTests.swift b/Tests/GRDBTests/FTS4RecordTests.swift index 8c0ea3be5..107176e91 100644 --- a/Tests/GRDBTests/FTS4RecordTests.swift +++ b/Tests/GRDBTests/FTS4RecordTests.swift @@ -25,8 +25,8 @@ extension Book : RowConvertible { extension Book : MutablePersistable { static let databaseTableName = "books" - static let selectsRowID = true - + static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] + func encode(to container: inout PersistenceContainer) { container[.rowID] = id container["title"] = title diff --git a/Tests/GRDBTests/FTS5RecordTests.swift b/Tests/GRDBTests/FTS5RecordTests.swift index 1f859cd76..8906440d2 100644 --- a/Tests/GRDBTests/FTS5RecordTests.swift +++ b/Tests/GRDBTests/FTS5RecordTests.swift @@ -26,8 +26,8 @@ extension Book : RowConvertible { extension Book : MutablePersistable { static let databaseTableName = "books" - static let selectsRowID = true - + static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] + func encode(to container: inout PersistenceContainer) { container[.rowID] = id container["title"] = title diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index 57d350a10..3f32eb639 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -33,8 +33,8 @@ private class Person : Record { // Record - override class var selectsRowID: Bool { - return true + override static var databaseSelection: [SQLSelectable] { + return [AllColumns(), Column.rowID] } override class var databaseTableName: String { diff --git a/Tests/GRDBTests/TableMappingTests.swift b/Tests/GRDBTests/TableMappingTests.swift new file mode 100644 index 000000000..c310cf690 --- /dev/null +++ b/Tests/GRDBTests/TableMappingTests.swift @@ -0,0 +1,49 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +class TableMappingTests: GRDBTestCase { + + func testDefaultDatabaseSelection() throws { + struct Record: TableMapping { + static let databaseTableName = "t1" + } + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE t1(a,b,c)") + _ = try Record.all().asRequest(of: Row.self).fetchAll(db) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"t1\"") + } + } + + func testExtendedDatabaseSelection() throws { + struct Record: TableMapping { + static let databaseTableName = "t1" + static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] + } + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE t1(a,b,c)") + _ = try Record.all().asRequest(of: Row.self).fetchAll(db) + XCTAssertEqual(lastSQLQuery, "SELECT *, \"rowid\" FROM \"t1\"") + } + } + + func testRestrictedDatabaseSelection() throws { + struct Record: TableMapping { + static let databaseTableName = "t1" + static let databaseSelection: [SQLSelectable] = [Column("a"), Column("b")] + } + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE t1(a,b,c)") + _ = try Record.all().asRequest(of: Row.self).fetchAll(db) + XCTAssertEqual(lastSQLQuery, "SELECT \"a\", \"b\" FROM \"t1\"") + } + } +}