diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 50e241674..578c9beb9 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -2169,7 +2169,7 @@ struct BookInfo: FetchableRecord { var country: Country? var coverImage: CoverImage? - init(row: Row) throws { + init(row: some RowProtocol) throws { book = try Book(row: row) author = row["author"] country = row["country"] @@ -2204,7 +2204,7 @@ struct AuthorInfo: FetchableRecord { var author: Author var books: [Book] - init(row: Row) throws { + init(row: some RowProtocol) throws { author = try Author(row: row) books = row["books"] } diff --git a/Documentation/Playgrounds/Tour.playground/Contents.swift b/Documentation/Playgrounds/Tour.playground/Contents.swift index baa8f20c2..c3e3c00c6 100644 --- a/Documentation/Playgrounds/Tour.playground/Contents.swift +++ b/Documentation/Playgrounds/Tour.playground/Contents.swift @@ -75,7 +75,7 @@ struct Place { // Adopt FetchableRecord extension Place : FetchableRecord { - init(row: Row) { + init(row: some RowProtocol) { id = row["id"] title = row["title"] favorite = row["favorite"] diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index a2d087108..d00154231 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -256,6 +256,8 @@ 569BBA3622905FFA00478429 /* InflectionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA3522905FFA00478429 /* InflectionsTests.swift */; }; 569BBA4622906A8200478429 /* InflectionsTests.json in Resources */ = {isa = PBXBuildFile; fileRef = 569BBA4522906A8200478429 /* InflectionsTests.json */; }; 569BBA4E229170F800478429 /* Inflections+English.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA482291707D00478429 /* Inflections+English.swift */; }; + 569D55322BBAFE9E00B57CA5 /* DetachedRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569D55312BBAFE9E00B57CA5 /* DetachedRow.swift */; }; + 569D55342BBAFEC700B57CA5 /* StatementRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569D55332BBAFEC700B57CA5 /* StatementRow.swift */; }; 569D6DDE220EF9E100A058A9 /* SQLInterpolation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */; }; 569EF0E2200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */; }; 56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238701B9C75030082EB20 /* Configuration.swift */; }; @@ -411,6 +413,7 @@ 56F89E152A585C0B002FE2AA /* SQLTableAlterationGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */; }; 56FA0C3028B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */; }; 56FA0C3928B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */; }; + 56FA602F2BB96AA50085DEB7 /* RowProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA602E2BB96AA50085DEB7 /* RowProtocol.swift */; }; 56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; }; 56FEB8F8248403000081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */; }; 56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; @@ -721,6 +724,8 @@ 569BBA4522906A8200478429 /* InflectionsTests.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = InflectionsTests.json; sourceTree = ""; }; 569BBA482291707D00478429 /* Inflections+English.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Inflections+English.swift"; sourceTree = ""; }; 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdogTests.swift; sourceTree = ""; }; + 569D55312BBAFE9E00B57CA5 /* DetachedRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DetachedRow.swift; sourceTree = ""; }; + 569D55332BBAFEC700B57CA5 /* StatementRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementRow.swift; sourceTree = ""; }; 569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLInterpolation.swift; sourceTree = ""; }; 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegion.swift; sourceTree = ""; }; 56A238131B9C74A90082EB20 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = ""; }; @@ -846,6 +851,7 @@ 56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLTableAlterationGenerator.swift; sourceTree = ""; }; 56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Upsert.swift"; sourceTree = ""; }; 56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Upsert.swift"; sourceTree = ""; }; + 56FA602E2BB96AA50085DEB7 /* RowProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowProtocol.swift; sourceTree = ""; }; 56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.swift; sourceTree = ""; }; @@ -1585,13 +1591,15 @@ 56A238751B9C75030082EB20 /* DatabaseValue.swift */, 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */, 563363C31C942C37000BE133 /* DatabaseWriter.swift */, + 569D55312BBAFE9E00B57CA5 /* DetachedRow.swift */, + 569D55332BBAFEC700B57CA5 /* StatementRow.swift */, 5636E9BB1D22574100B9B05F /* FetchRequest.swift */, 56A238761B9C75030082EB20 /* Row.swift */, 567404871CEF84C8003ED5CC /* RowAdapter.swift */, 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */, + 56FA602E2BB96AA50085DEB7 /* RowProtocol.swift */, 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */, 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */, - 56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */, 56E9FAD7221053DC00C703A8 /* SQL.swift */, 569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */, 56FBFED82210731A00945324 /* SQLRequest.swift */, @@ -1601,6 +1609,7 @@ 56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, 56B7EE822863781300C0525F /* WALSnapshot.swift */, + 56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */, 5605F1471C672E4000235C62 /* Support */, ); path = Core; @@ -2229,6 +2238,7 @@ 563B8FAC24A1CE43007A48C9 /* DatabasePublishers.swift in Sources */, 56F89E0C2A57EC16002FE2AA /* SQLTableGenerator.swift in Sources */, 56F89DFC2A57EAEA002FE2AA /* ForeignKeyDefinition.swift in Sources */, + 569D55322BBAFE9E00B57CA5 /* DetachedRow.swift in Sources */, 56FA0C3028B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */, 5605F1691C672E4000235C62 /* NSString.swift in Sources */, 560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */, @@ -2263,6 +2273,7 @@ 5656A8AD2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */, 56D110C428AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */, 5690C3401D23E82A00E59934 /* Data.swift in Sources */, + 56FA602F2BB96AA50085DEB7 /* RowProtocol.swift in Sources */, 5659F4881EA8D94E004A4992 /* Utils.swift in Sources */, 567B5BE82AD3284100629622 /* DumpFormat.swift in Sources */, 566BE71E2342542F00A8254B /* Mutex.swift in Sources */, @@ -2319,6 +2330,7 @@ 567B5BEC2AD3284100629622 /* Database+Dump.swift in Sources */, 56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */, 567B5BEB2AD3284100629622 /* DebugDumpFormat.swift in Sources */, + 569D55342BBAFEC700B57CA5 /* StatementRow.swift in Sources */, 56B9649D1DA51B4C0002DA19 /* FTS5.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index f3d9257d1..33fb6bb1c 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -1072,7 +1072,7 @@ public struct ColumnInfo: FetchableRecord, Sendable { /// For columns that are not part of the primary key, it is zero. public let primaryKeyIndex: Int - public init(row: Row) { + public init(row: some RowProtocol) { cid = row["cid"] name = row["name"] type = row["type"] @@ -1238,7 +1238,7 @@ public struct ForeignKeyViolation: Sendable { } extension ForeignKeyViolation: FetchableRecord { - public init(row: Row) { + public init(row: some RowProtocol) { originTable = row[0] originRowID = row[1] destinationTable = row[2] @@ -1481,7 +1481,7 @@ struct TableInfo: FetchableRecord { var hasRowID: Bool var strict: Bool - init(row: Row) throws { + init(row: some RowProtocol) throws { switch row[0] as String { case "main": schemaID = .main @@ -1515,7 +1515,7 @@ struct SchemaObject: Hashable, FetchableRecord { var tbl_name: String? var sql: String? - init(row: Row) throws { + init(row: some RowProtocol) throws { // "rootpage" column is not always there: avoid using numerical indexes type = row["type"] name = row["name"] diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index df9b1b693..ed9d5a94c 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -129,45 +129,20 @@ extension DatabaseValueConvertible { // MARK: - Conversions extension DatabaseValueConvertible { - static func decode( - fromDatabaseValue dbValue: DatabaseValue, - context: @autoclosure () -> RowDecodingContext) - throws -> Self - { - if let value = fromDatabaseValue(dbValue) { + @inlinable + public static func _decode( + databaseValue: DatabaseValue, + context: @autoclosure () -> _RowDecodingContext + ) throws -> Self { + if let value = fromDatabaseValue(databaseValue) { return value } else { - throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue) + throw RowDecodingError.valueMismatch( + Self.self, + context: context(), + databaseValue: databaseValue) } } - - static func decode( - fromStatement sqliteStatement: SQLiteStatement, - atUncheckedIndex index: CInt, - context: @autoclosure () -> RowDecodingContext) - throws -> Self - { - let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index) - return try decode(fromDatabaseValue: dbValue, context: context()) - } - - @usableFromInline - static func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self { - if let sqliteStatement = row.sqliteStatement { - return try decode( - fromStatement: sqliteStatement, - atUncheckedIndex: CInt(index), - context: RowDecodingContext(row: row, key: .columnIndex(index))) - } - return try decode( - fromDatabaseValue: row.impl.databaseValue(atUncheckedIndex: index), - context: RowDecodingContext(row: row, key: .columnIndex(index))) - } - - @usableFromInline - static func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self? { - try Optional.decode(fromRow: row, atUncheckedIndex: index) - } } // MARK: - Cursors @@ -215,10 +190,9 @@ public final class DatabaseValueCursor: Databas } public func _element(sqliteStatement: SQLiteStatement) throws -> Value { - try Value.decode( - fromStatement: sqliteStatement, - atUncheckedIndex: columnIndex, - context: RowDecodingContext(statement: _statement, index: Int(columnIndex))) + try Value._decode( + databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: columnIndex), + context: _RowDecodingContext(statement: _statement, index: Int(columnIndex))) } } diff --git a/GRDB/Core/DetachedRow.swift b/GRDB/Core/DetachedRow.swift new file mode 100644 index 000000000..816be062e --- /dev/null +++ b/GRDB/Core/DetachedRow.swift @@ -0,0 +1,8 @@ +//#warning("TODO: document") +//struct DetachedRow { +// +//} +// +//extension DetachedRow: Row { +// +//} diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 9ab134163..bbe100dbc 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -204,10 +204,10 @@ public final class Row { impl.copiedRow(self) } - // MARK: - Not Public - /// Returns true if and only if the row was fetched from a database. - var isFetched: Bool { impl.isFetched } + public var _isFetched: Bool { impl.isFetched } + + // MARK: - Not Public /// Creates a row that maps an SQLite statement. Further calls to /// sqlite3_step() modify the row. @@ -260,584 +260,118 @@ public final class Row { @available(*, unavailable) extension Row: Sendable { } -extension Row { +#warning("TODO: remove what's not needed") +extension Row: RowProtocol { + public typealias Index = RowIndex - // MARK: - Columns - - /// The names of columns in the row, from left to right. - /// - /// Columns appear in the same order as they occur as the `.0` member - /// of column-value pairs in `self`. - public var columnNames: LazyMapCollection { - lazy.map { $0.0 } + public func _scopes(prefetchedRows: PrefetchedRowsView) -> ScopesView { + impl.scopes(prefetchedRows: prefetchedRows) } - /// Returns whether the row has one column with the given name - /// (case-insensitive). - public func hasColumn(_ columnName: String) -> Bool { - index(forColumn: columnName) != nil + public func _columnName(atUncheckedIndex index: Int) -> String { + impl.columnName(atUncheckedIndex: index) } - @usableFromInline - func index(forColumn name: String) -> Int? { + public func _hasNull(atUncheckedIndex index: Int) -> Bool { + impl.hasNull(atUncheckedIndex: index) + } + + public func _databaseValue(atUncheckedIndex index: Int) -> DatabaseValue { + impl.databaseValue(atUncheckedIndex: index) + } + + public func _decode( + with strategy: Strategy, + atUncheckedIndex index: Int + ) throws -> Strategy._RowDecodingOutput + { + if let sqliteStatement { + let statementIndex = CInt(index) + + if sqlite3_column_type(sqliteStatement, statementIndex) == SQLITE_NULL { + throw RowDecodingError.valueMismatch( + Strategy._RowDecodingOutput.self, + sqliteStatement: sqliteStatement, + index: statementIndex, + context: _makeRowDecodingContext(forKey: .columnIndex(index))) + } + + return try strategy._decode( + sqliteStatement: sqliteStatement, + atUncheckedIndex: CInt(index), + context: _makeRowDecodingContext(forKey: .columnIndex(index))) + } else { + return try strategy._decode( + databaseValue: impl.databaseValue(atUncheckedIndex: index), + context: _makeRowDecodingContext(forKey: .columnIndex(index))) + } + } + + public func _decode( + _ type: Value.Type, + atUncheckedIndex index: Int + ) throws -> Value + { + if let sqliteStatement { + let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: CInt(index)) + return try Value._decode( + databaseValue: dbValue, + context: _makeRowDecodingContext(forKey: .columnIndex(index))) + } else { + return try Value._decode( + databaseValue: impl.databaseValue(atUncheckedIndex: index), + context: _makeRowDecodingContext(forKey: .columnIndex(index))) + } + } + + public func _fastDecode( + _ type: Value.Type, + atUncheckedIndex index: Int + ) throws -> Value + { + try impl.fastDecode(Value.self, atUncheckedIndex: index) + } + + public func _withUnsafeData(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T { + try impl.withUnsafeData(atUncheckedIndex: index, body) + } + + public func index(forColumn name: String) -> Int? { impl.index(forColumn: name) } -} - -extension Row { - // MARK: - Extracting Values - - /// Fatal errors if index is out of bounds - @inline(__always) - @usableFromInline - /* private */ func _checkIndex(_ index: Int, file: StaticString = #file, line: UInt = #line) { - GRDBPrecondition(index >= 0 && index < count, "row index out of range", file: file, line: line) + public var _unscopedRow: Row { + impl.unscopedRow(self) } - /// Returns a boolean value indicating if the row contains one value this - /// is not `NULL`. - /// - /// For example: - /// - /// ```swift - /// let row = try Row.fetchOne(db, sql: "SELECT 'foo', NULL")! - /// row.containsNonNullValue // true - /// - /// let row = try Row.fetchOne(db, sql: "SELECT NULL, NULL")! - /// row.containsNonNullValue // false - /// ``` - public var containsNonNullValue: Bool { - for i in (0.. _RowDecodingContext { + if let statement { + return _RowDecodingContext( + row: copy(), + key: key, + sql: statement.sql, + statementArguments: statement.arguments) + } else if let sqliteStatement { + return _RowDecodingContext( + row: copy(), + key: key, + sql: String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement, + statementArguments: nil) // Can't rebuild arguments + } else { + return _RowDecodingContext( + row: copy(), + key: key, + sql: nil, + statementArguments: nil) } - - for (_, scopedRow) in scopes where scopedRow.containsNonNullValue { - return true - } - - return false - } - - /// Returns whether the row has a `NULL` value at given index. - /// - /// Indexes span from `0` for the leftmost column to `row.count - 1` for the - /// rightmost column. - /// - /// This method is equivalent to `row[index] == nil`, but may be preferred - /// in performance-critical code because it avoids decoding - /// database values. - public func hasNull(atIndex index: Int) -> Bool { - _checkIndex(index) - return impl.hasNull(atUncheckedIndex: index) - } - - /// Returns `Int64`, `Double`, `String`, `Data` or nil, depending on the - /// value stored at the given index. - /// - /// Indexes span from `0` for the leftmost column to `row.count - 1` for the - /// rightmost column. - public subscript(_ index: Int) -> (any DatabaseValueConvertible)? { - _checkIndex(index) - return impl.databaseValue(atUncheckedIndex: index).storage.value - } - - /// Returns the value at given index, converted to the requested type. - /// - /// Indexes span from `0` for the leftmost column to `row.count - 1` for the - /// rightmost column. - /// - /// For example: - /// - /// ```swift - /// let row = try Row.fetchOne(db, sql: "SELECT 42")! - /// let score: Int = row[0] // 42 - /// - /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")! - /// let name: String = row[0] // "Alice" - /// ``` - /// - /// When the database value may be nil, ask for an optional: - /// - /// ```swift - /// let row = try Row.fetchOne(db, sql: "SELECT NULL")! - /// let name: String? = row[0] // nil - /// ``` - @inlinable - public subscript(_ index: Int) -> Value { - try! decode(Value.self, atIndex: index) - } - - /// Returns the value at given index, converted to the requested type. - /// - /// This method exists as an optimization opportunity for types that adopt - /// ``StatementColumnConvertible``. It can trigger [SQLite built-in - /// conversions](https://www.sqlite.org/datatype3.html). - /// - /// Indexes span from `0` for the leftmost column to `row.count - 1` for the - /// rightmost column. - /// - /// For example: - /// - /// ```swift - /// let row = try Row.fetchOne(db, sql: "SELECT 42")! - /// let score: Int = row[0] // 42 - /// - /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")! - /// let name: String = row[0] // "Alice" - /// ``` - /// - /// When the database value may be nil, ask for an optional: - /// - /// ```swift - /// let row = try Row.fetchOne(db, sql: "SELECT NULL")! - /// let name: String? = row[0] // nil - /// ``` - @inline(__always) - @inlinable - public subscript(_ index: Int) -> Value { - try! decode(Value.self, atIndex: index) - } - - /// Returns `Int64`, `Double`, `String`, `Data` or nil, depending on the - /// value stored at the given column. - /// - /// Column name lookup is case-insensitive. When several columns exist with - /// the same name, the leftmost column is considered. - /// - /// The result is nil if the row does not contain any column with that name. - public subscript(_ columnName: String) -> (any DatabaseValueConvertible)? { - // IMPLEMENTATION NOTE - // This method has a single known use case: checking if the value is nil, - // as in: - // - // if row["foo"] != nil { ... } - // - // Without this method, the code above would not compile. - guard let index = index(forColumn: columnName) else { - return nil - } - return impl.databaseValue(atUncheckedIndex: index).storage.value - } - - /// Returns the value at given column, converted to the requested type. - /// - /// Column name lookup is case-insensitive. When several columns exist with - /// the same name, the leftmost column is considered. - /// - /// For example: - /// - /// ```swift - /// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")! - /// let score: Int = row["score"] // 42 - /// - /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! - /// let name: String = row["name"] // "Alice" - /// ``` - /// - /// When the database value may be nil, ask for an optional: - /// - /// ```swift - /// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")! - /// let name: String? = row["name"] // nil - /// ``` - /// - /// When the column does not exist, nil is returned: - /// - /// ```swift - /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! - /// let name: String? = row["missing"] // nil - /// ``` - @inlinable - public subscript(_ columnName: String) -> Value { - try! decode(Value.self, forKey: columnName) - } - - /// Returns the value at given column, converted to the requested type. - /// - /// This method exists as an optimization opportunity for types that adopt - /// ``StatementColumnConvertible``. It can trigger [SQLite built-in - /// conversions](https://www.sqlite.org/datatype3.html). - /// - /// Column name lookup is case-insensitive. When several columns exist with - /// the same name, the leftmost column is considered. - /// - /// For example: - /// - /// ```swift - /// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")! - /// let score: Int = row["score"] // 42 - /// - /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! - /// let name: String = row["name"] // "Alice" - /// ``` - /// - /// When the database value may be nil, ask for an optional: - /// - /// ```swift - /// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")! - /// let name: String? = row["name"] // nil - /// ``` - /// - /// When the column does not exist, nil is returned: - /// - /// ```swift - /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! - /// let name: String? = row["missing"] // nil - /// ``` - @inlinable - public subscript(_ columnName: String) -> Value { - try! decode(Value.self, forKey: columnName) - } - - /// Returns `Int64`, `Double`, `String`, `Data` or nil, depending on the - /// value stored at the given column. - /// - /// Column name lookup is case-insensitive. When several columns exist with - /// the same name, the leftmost column is considered. - /// - /// The result is nil if the row does not contain any column with that name. - public subscript(_ column: some ColumnExpression) -> (any DatabaseValueConvertible)? { - self[column.name] - } - - /// Returns the value at given column, converted to the requested type. - /// - /// Column name lookup is case-insensitive. When several columns exist with - /// the same name, the leftmost column is considered. - /// - /// For example: - /// - /// ```swift - /// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")! - /// let score: Int = row[Column("score")] // 42 - /// - /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! - /// let name: String = row[Column("name")] // "Alice" - /// ``` - /// - /// When the database value may be nil, ask for an optional: - /// - /// ```swift - /// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")! - /// let name: String? = row[Column("name")] // nil - /// ``` - /// - /// When the column does not exist, nil is returned: - /// - /// ```swift - /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! - /// let name: String? = row[Column("missing")] // nil - /// ``` - @inlinable - public subscript(_ column: some ColumnExpression) -> Value { - try! decode(Value.self, forKey: column.name) - } - - /// Returns the value at given column, converted to the requested type. - /// - /// This method exists as an optimization opportunity for types that adopt - /// ``StatementColumnConvertible``. It can trigger [SQLite built-in - /// conversions](https://www.sqlite.org/datatype3.html). - /// - /// Column name lookup is case-insensitive. When several columns exist with - /// the same name, the leftmost column is considered. - /// - /// For example: - /// - /// ```swift - /// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")! - /// let score: Int = row[Column("score")] // 42 - /// - /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! - /// let name: String = row[Column("name")] // "Alice" - /// ``` - /// - /// When the database value may be nil, ask for an optional: - /// - /// ```swift - /// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")! - /// let name: String? = row[Column("name")] // nil - /// ``` - /// - /// When the column does not exist, nil is returned: - /// - /// ```swift - /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! - /// let name: String? = row[Column("missing")] // nil - /// ``` - @inlinable - public subscript(_ column: some ColumnExpression) - -> Value - where Value: DatabaseValueConvertible & StatementColumnConvertible - { - try! decode(Value.self, forKey: column.name) - } - - /// Calls the given closure with the `Data` at given index. - /// - /// Indexes span from `0` for the leftmost column to `row.count - 1` for the - /// rightmost column. - /// - /// If the SQLite value is `NULL`, the data is nil. If the SQLite value can - /// not be converted to `Data`, an error is thrown. - /// - /// - warning: The `Data` argument to the body must not be stored or used - /// outside of the lifetime of the call to the closure. - public func withUnsafeData(atIndex index: Int, _ body: (Data?) throws -> T) throws -> T { - _checkIndex(index) - return try impl.withUnsafeData(atUncheckedIndex: index, body) - } - - /// Calls the given closure with the `Data` at the given column. - /// - /// Column name lookup is case-insensitive. When several columns exist with - /// the same name, the leftmost column is considered. - /// - /// If the row does not contain any column with that name, or if the SQLite - /// value is `NULL`, the data is nil. If the SQLite value can not be - /// converted to `Data`, an error is thrown. - /// - /// - warning: The `Data` argument to the body must not be stored or used - /// outside of the lifetime of the call to the closure. - public func withUnsafeData(named columnName: String, _ body: (Data?) throws -> T) throws -> T { - guard let index = index(forColumn: columnName) else { - return try body(nil) - } - return try impl.withUnsafeData(atUncheckedIndex: index, body) - } - - /// Calls the given closure with the `Data` at the given column. - /// - /// Column name lookup is case-insensitive. When several columns exist with - /// the same name, the leftmost column is considered. - /// - /// If the row does not contain any column with that name, or if the SQLite - /// value is `NULL`, the data is nil. If the SQLite value can not be - /// converted to `Data`, an error is thrown. - /// - /// - warning: The `Data` argument to the body must not be stored or used - /// outside of the lifetime of the call to the closure. - public func withUnsafeData(at column: some ColumnExpression, _ body: (Data?) throws -> T) throws -> T { - try withUnsafeData(named: column.name, body) - } - - /// Returns the optional `Data` at given index. - /// - /// Indexes span from `0` for the leftmost column to `row.count - 1` for the - /// rightmost column. - /// - /// If the SQLite value is NULL, the result is nil. If the SQLite value can - /// not be converted to Data, a fatal error is raised. - /// - /// The returned data does not owns its bytes: it must not be used longer - /// than the row's lifetime. - @available(*, deprecated, message: "Use withUnsafeData(atIndex:_:) instead.") - public func dataNoCopy(atIndex index: Int) -> Data? { - try! withUnsafeData(atIndex: index, { $0 }) - } - - /// Returns the optional `Data` at given column. - /// - /// Column name lookup is case-insensitive. When several columns exist with - /// the same name, the leftmost column is considered. - /// - /// If the column is missing or if the SQLite value is NULL, the result is - /// nil. If the SQLite value can not be converted to Data, a fatal error - /// is raised. - /// - /// The returned data does not owns its bytes: it must not be used longer - /// than the row's lifetime. - @available(*, deprecated, message: "Use withUnsafeData(named:_:) instead.") - public func dataNoCopy(named columnName: String) -> Data? { - guard let index = index(forColumn: columnName) else { - return nil - } - return try! withUnsafeData(atUncheckedIndex: index, { $0 }) - } - - /// Returns the optional `Data` at given column. - /// - /// Column name lookup is case-insensitive. When several columns exist with - /// the same name, the leftmost column is considered. - /// - /// If the column is missing or if the SQLite value is NULL, the result is - /// nil. If the SQLite value can not be converted to Data, a fatal error - /// is raised. - /// - /// The returned data does not owns its bytes: it must not be used longer - /// than the row's lifetime. - @available(*, deprecated, message: "Use withUnsafeData(at:_:) instead.") - public func dataNoCopy(_ column: some ColumnExpression) -> Data? { - dataNoCopy(named: column.name) - } -} - -extension Row { - - // MARK: - Extracting DatabaseValue - - /// The database values in the row, from left to right. - /// - /// Values appear in the same order as they occur as the `.1` member - /// of column-value pairs in `self`. - public var databaseValues: LazyMapCollection { - lazy.map { $0.1 } - } -} - -extension Row { - - // MARK: - Extracting Records - - /// The record associated to the given scope. - /// - /// Row scopes can be defined manually, with ``ScopeAdapter``. - /// The ``JoinableRequest/including(required:)`` and - /// ``JoinableRequest/including(optional:)`` request methods define scopes - /// named after the key of included associations between record types. - /// - /// A breadth-first search is performed in all available scopes in the row, - /// recursively. - /// - /// A fatal error is raised if the scope is not available, or contains only - /// `NULL` values. - /// - /// For example: - /// - /// ```swift - /// struct Book: TableRecord, FetchableRecord { - /// static let author = belongsTo(Author.self) - /// } - /// - /// struct Author: TableRecord, FetchableRecord { - /// static let country = belongsTo(Country.self) - /// } - /// - /// struct Country: TableRecord, FetchableRecord { } - /// - /// // Fetch a book, with its author, and the country of its author. - /// let request = Book - /// .including(required: Book.author - /// .including(required: Author.country)) - /// let bookRow = try Row.fetchOne(db, request)! - /// - /// let book = try Book(row: bookRow) - /// let author: Author = bookRow["author"] - /// let country: Country = bookRow["country"] - /// ``` - /// - /// See also: ``scopesTree`` - /// - /// - parameter scope: A scope identifier. - public subscript(_ scope: String) -> Record { - try! decode(Record.self, forKey: scope) - } - - /// The eventual record associated to the given scope. - /// - /// Row scopes can be defined manually, with ``ScopeAdapter``. - /// The ``JoinableRequest/including(required:)`` and - /// ``JoinableRequest/including(optional:)`` request methods define scopes - /// named after the key of included associations between record types. - /// - /// A breadth-first search is performed in all available scopes in the row, - /// recursively. - /// - /// The result is nil if the scope is not available, or contains only - /// `NULL` values. - /// - /// For example: - /// - /// ```swift - /// struct Book: TableRecord, FetchableRecord { - /// static let author = belongsTo(Author.self) - /// } - /// - /// struct Author: TableRecord, FetchableRecord { - /// static let country = belongsTo(Country.self) - /// } - /// - /// struct Country: TableRecord, FetchableRecord { } - /// - /// // Fetch a book, with its author, and the country of its author. - /// let request = Book - /// .including(optional: Book.author - /// .including(optional: Author.country)) - /// let bookRow = try Row.fetchOne(db, request)! - /// - /// let book = try Book(row: bookRow) - /// let author: Author? = bookRow["author"] - /// let country: Country? = bookRow["country"] - /// ``` - /// - /// See also: ``scopesTree`` - /// - /// - parameter scope: A scope identifier. - public subscript(_ scope: String) -> Record? { - try! decodeIfPresent(Record.self, forKey: scope) - } - - /// A collection of prefetched records associated to the given - /// association key. - /// - /// Prefetched rows are defined by the ``JoinableRequest/including(all:)`` - /// request method. - /// - /// For example: - /// - /// ```swift - /// struct Author: TableRecord, FetchableRecord { - /// static let books = hasMany(Book.self) - /// } - /// - /// struct Book: TableRecord, FetchableRecord { } - /// - /// let request = Author.including(all: Author.books) - /// let authorRow = try Row.fetchOne(db, request)! - /// - /// let author = try Author(row: authorRow) - /// let books: [Book] = author["books"] - /// ``` - /// - /// See also: ``prefetchedRows`` - /// - /// - parameter key: An association key. - public subscript(_ key: String) - -> Records - where - Records: RangeReplaceableCollection, - Records.Element: FetchableRecord - { - try! decode(Records.self, forKey: key) - } - - /// A set prefetched records associated to the given association key. - /// - /// Prefetched rows are defined by the ``JoinableRequest/including(all:)`` - /// request method. - /// - /// For example: - /// - /// ```swift - /// struct Author: TableRecord, FetchableRecord { - /// static let books = hasMany(Book.self) - /// } - /// - /// struct Book: TableRecord, FetchableRecord, Hashable { } - /// - /// let request = Author.including(all: Author.books) - /// let authorRow = try Row.fetchOne(db, request)! - /// - /// let author = try Author(row: authorRow) - /// let books: Set = author["books"] - /// ``` - /// - /// See also: ``prefetchedRows`` - /// - /// - parameter key: An association key. - public subscript(_ key: String) -> Set { - try! decode(Set.self, forKey: key) } } @@ -1008,347 +542,6 @@ extension Row { } } -// MARK: - Throwing DatabaseValueConvertible Decoding Methods - -extension Row { - /// Returns the value at given index, converted to the requested type. - /// - /// Indexes span from `0` for the leftmost column to `row.count - 1` for the - /// rightmost column. - /// - /// If the SQLite value is NULL, or if the conversion fails, a - /// `RowDecodingError` is thrown. - @inlinable - func decode( - _ type: Value.Type = Value.self, - atIndex index: Int) - throws -> Value - { - _checkIndex(index) - return try Value.decode(fromRow: self, atUncheckedIndex: index) - } - - /// Returns the value at given column, converted to the requested type. - /// - /// Column name lookup is case-insensitive. When several columns exist with - /// the same name, the leftmost column is considered. - /// - /// If the row does not contain the column, or if the SQLite value is NULL, - /// or if the SQLite value can not be converted to `Value`, a - /// `RowDecodingError` is thrown. - @inlinable - func decode( - _ type: Value.Type = Value.self, - forKey columnName: String) - throws -> Value - { - guard let index = index(forColumn: columnName) else { - if let value = Value.fromMissingColumn() { - return value - } else { - throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self)) - } - } - return try Value.decode(fromRow: self, atUncheckedIndex: index) - } -} - -// MARK: - Throwing DatabaseValueConvertible & StatementColumnConvertible Decoding Methods - -extension Row { - /// Returns the value at given index, converted to the requested type. - /// - /// This method exists as an optimization opportunity for types that adopt - /// ``StatementColumnConvertible``. It can trigger [SQLite built-in - /// conversions](https://www.sqlite.org/datatype3.html). - /// - /// Indexes span from `0` for the leftmost column to `row.count - 1` for the - /// rightmost column. - /// - /// If the SQLite value is NULL, or if the conversion fails, a - /// `RowDecodingError` is thrown. - @inline(__always) - @inlinable - func decode( - _ type: Value.Type = Value.self, - atIndex index: Int) - throws -> Value - { - _checkIndex(index) - return try Value.fastDecode(fromRow: self, atUncheckedIndex: index) - } - - /// Returns the value at given column, converted to the requested type. - /// - /// This method exists as an optimization opportunity for types that adopt - /// ``StatementColumnConvertible``. It can trigger [SQLite built-in - /// conversions](https://www.sqlite.org/datatype3.html). - /// - /// Column name lookup is case-insensitive. When several columns exist with - /// the same name, the leftmost column is considered. - /// - /// If the row does not contain the column, or if the SQLite value is NULL, - /// or if the SQLite value can not be converted to `Value`, a - /// `RowDecodingError` is thrown. - @inlinable - func decode( - _ type: Value.Type = Value.self, - forKey columnName: String) - throws -> Value - { - guard let index = index(forColumn: columnName) else { - if let value = Value.fromMissingColumn() { - return value - } else { - throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self)) - } - } - return try Value.fastDecode(fromRow: self, atUncheckedIndex: index) - } - - // Support for fast decoding in scoped rows - @usableFromInline - func fastDecode( - _ type: Value.Type, - atUncheckedIndex index: Int) - throws -> Value - { - try impl.fastDecode(type, atUncheckedIndex: index) - } -} - -// MARK: - Throwing Data Decoding Methods - -extension Row { - /// Calls the given closure with the `Data` at given index. - /// - /// Indexes span from `0` for the leftmost column to `row.count - 1` for the - /// rightmost column. - /// - /// If the SQLite value is `NULL`, the data is nil. If the SQLite value can - /// not be converted to `Data`, an error is thrown. - /// - /// - warning: The `Data` argument to the body must not be stored or used - /// outside of the lifetime of the call to the closure. - func withUnsafeData(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T { - try impl.withUnsafeData(atUncheckedIndex: index, body) - } -} - -// MARK: - Throwing Record Decoding Methods - -extension Row { - /// Returns the eventual record associated with the given scope. - /// - /// For example: - /// - /// let request = Book.including(optional: Book.author) - /// let row = try Row.fetchOne(db, request)! - /// - /// try print(Book(row: row).title) - /// // Prints "Moby-Dick" - /// - /// let author: Author? = row["author"] - /// print(author.name) - /// // Prints "Herman Melville" - /// - /// Associated records stored in nested associations are available, too: - /// - /// let request = Book.including(optional: Book.author.including(optional: Author.country)) - /// let row = try Row.fetchOne(db, request)! - /// - /// try print(Book(row: row).title) - /// // Prints "Moby-Dick" - /// - /// let country: Country? = row["country"] - /// print(country.name) - /// // Prints "United States" - /// - /// Nil is returned if the scope is not available, or contains only - /// null values. - /// - /// See ``splittingRowAdapters(columnCounts:)`` for a sample code. - func decodeIfPresent( - _ type: Record.Type = Record.self, - forKey scope: String) - throws -> Record? - { - guard let scopedRow = scopesTree[scope], scopedRow.containsNonNullValue else { - return nil - } - return try Record(row: scopedRow) - } - - /// Returns the record associated with the given scope. - /// - /// For example: - /// - /// let request = Book.including(required: Book.author) - /// let row = try Row.fetchOne(db, request)! - /// - /// try print(Book(row: row).title) - /// // Prints "Moby-Dick" - /// - /// let author: Author = row["author"] - /// print(author.name) - /// // Prints "Herman Melville" - /// - /// Associated records stored in nested associations are available, too: - /// - /// let request = Book.including(required: Book.author.including(required: Author.country)) - /// let row = try Row.fetchOne(db, request)! - /// - /// try print(Book(row: row).title) - /// // Prints "Moby-Dick" - /// - /// let country: Country = row["country"] - /// print(country.name) - /// // Prints "United States" - /// - /// A fatal error is raised if the scope is not available, or contains only - /// null values. - /// - /// See ``splittingRowAdapters(columnCounts:)`` for a sample code. - func decode( - _ type: Record.Type = Record.self, - forKey scope: String) - throws -> Record - { - guard let scopedRow = scopesTree[scope] else { - let availableScopes = scopesTree.names - if availableScopes.isEmpty { - throw RowDecodingError.keyNotFound( - .scope(scope), - RowDecodingError.Context( - decodingContext: RowDecodingContext(row: self), - debugDescription: """ - scope not found: \(String(reflecting: scope)) - """)) - } else { - throw RowDecodingError.keyNotFound( - .scope(scope), - RowDecodingError.Context( - decodingContext: RowDecodingContext(row: self), - debugDescription: """ - scope not found: \(String(reflecting: scope)) - \ - available scopes: \(availableScopes.sorted()) - """)) - } - } - guard scopedRow.containsNonNullValue else { - throw RowDecodingError.valueMismatch( - Record.self, - RowDecodingError.Context( - decodingContext: RowDecodingContext(row: self, key: .scope(scope)), - debugDescription: """ - scope \(String(reflecting: scope)) only contains null values - """)) - } - return try Record(row: scopedRow) - } -} - -// MARK: - Throwing Record RangeReplaceableCollection and Set Methods - -extension Row { - /// Returns the records encoded in the given prefetched rows. - /// - /// For example: - /// - /// let request = Author.including(all: Author.books) - /// let row = try Row.fetchOne(db, request)! - /// - /// try print(Author(row: row).name) - /// // Prints "Herman Melville" - /// - /// let books: [Book] = row["books"] - /// print(books[0].title) - /// // Prints "Moby-Dick" - func decode( - _ type: Collection.Type = Collection.self, - forKey key: String) - throws -> Collection - where - Collection: RangeReplaceableCollection, - Collection.Element: FetchableRecord - { - guard let rows = prefetchedRows[key] else { - let availableKeys = prefetchedRows.keys - if availableKeys.isEmpty { - throw RowDecodingError.keyNotFound( - .prefetchKey(key), - RowDecodingError.Context( - decodingContext: RowDecodingContext(row: self), - debugDescription: """ - key for prefetched rows not found: \(String(reflecting: key)) - """)) - } else { - throw RowDecodingError.keyNotFound( - .prefetchKey(key), - RowDecodingError.Context( - decodingContext: RowDecodingContext(row: self), - debugDescription: """ - key for prefetched rows not found: \(String(reflecting: key)) \ - - available keys: \(availableKeys.sorted()) - """)) - } - } - - var collection = Collection() - collection.reserveCapacity(rows.count) - for row in rows { - try collection.append(Collection.Element(row: row)) - } - return collection - } - - /// Returns the set of records encoded in the given prefetched rows. - /// - /// For example: - /// - /// let request = Author.including(all: Author.books) - /// let row = try Row.fetchOne(db, request)! - /// - /// try print(Author(row: row).name) - /// // Prints "Herman Melville" - /// - /// let books: Set = row["books"] - /// print(books.first!.title) - /// // Prints "Moby-Dick" - func decode( - _ type: Set.Type = Set.self, - forKey key: String) - throws -> Set - { - guard let rows = prefetchedRows[key] else { - let availableKeys = prefetchedRows.keys - if availableKeys.isEmpty { - throw RowDecodingError.keyNotFound( - .prefetchKey(key), - RowDecodingError.Context( - decodingContext: RowDecodingContext(row: self), - debugDescription: """ - key for prefetched rows not found: \(String(reflecting: key)) - """)) - } else { - throw RowDecodingError.keyNotFound( - .prefetchKey(key), - RowDecodingError.Context( - decodingContext: RowDecodingContext(row: self), - debugDescription: """ - key for prefetched rows not found: \(String(reflecting: key)) \ - - available keys: \(availableKeys.sorted()) - """)) - } - } - var set = Set(minimumCapacity: rows.count) - for row in rows { - try set.insert(Record(row: row)) - } - return set - } -} - // MARK: - RowCursor /// A cursor of raw database rows. @@ -1941,21 +1134,6 @@ extension FetchRequest { } } -extension Row: RandomAccessCollection { - public var startIndex: Index { Index(0) } - - public var endIndex: Index { Index(count) } - - /// Returns the (column, value) pair at given index. - public subscript(position: Index) -> (String, DatabaseValue) { - let index = position.index - _checkIndex(index) - return ( - impl.columnName(atUncheckedIndex: index), - impl.databaseValue(atUncheckedIndex: index)) - } -} - extension Row: Equatable { /// Returns true if and only if both rows have the same columns and values, /// in the same order. Columns are compared in a case-sensitive way. @@ -2009,14 +1187,9 @@ extension Row: Hashable { } } -extension Row: CustomStringConvertible { - public var description: String { - "[" - + map { (column, dbValue) in "\(column):\(dbValue)" }.joined(separator: " ") - + "]" - } -} +extension Row: CustomStringConvertible { } +#warning("TODO: move to RowProtocol?") extension Row: CustomDebugStringConvertible { public var debugDescription: String { debugDescription(level: 0) @@ -2072,38 +1245,10 @@ extension Row: ExpressibleByDictionaryLiteral { } } -// MARK: - Index - -@available(*, deprecated, renamed: "Row.Index") -typealias RowIndex = Row.Index - extension Row { - /// An index to a (column, value) pair in a ``Row``. - public struct Index: Sendable { - let index: Int - init(_ index: Int) { self.index = index } - } -} - -extension Row.Index: Equatable { - public static func == (lhs: Self, rhs: Self) -> Bool { - lhs.index == rhs.index - } -} - -extension Row.Index: Comparable { - public static func < (lhs: Self, rhs: Self) -> Bool { - lhs.index < rhs.index - } -} - -extension Row.Index: Strideable { - public func distance(to other: Self) -> Int { - other.index - index - } - - public func advanced(by n: Int) -> Self { - Row.Index(index + n) +#warning("TODO: document") + public convenience init(columnsWithValues: KeyValuePairs) { + self.init(impl: ArrayRowImpl(columns: columnsWithValues.map { ($0, $1?.databaseValue ?? .null) })) } } @@ -2377,16 +1522,16 @@ extension RowImpl { throws -> Value { // unless customized, use slow decoding (see StatementRowImpl and AdaptedRowImpl for customization) - try Value.decode( - fromDatabaseValue: databaseValue(atUncheckedIndex: index), - context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index))) + try Value._decode( + databaseValue: databaseValue(atUncheckedIndex: index), + context: Row(impl: self)._makeRowDecodingContext(forKey: .columnIndex(index))) } func withUnsafeData(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T { // unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization) - let data = try Optional.decode( - fromDatabaseValue: databaseValue(atUncheckedIndex: index), - context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index))) + let data = try Optional._decode( + databaseValue: databaseValue(atUncheckedIndex: index), + context: Row(impl: self)._makeRowDecodingContext(forKey: .columnIndex(index))) return try body(data) } } @@ -2502,10 +1647,10 @@ private struct StatementRowImpl: RowImpl { atUncheckedIndex index: Int) throws -> Value { - try Value.fastDecode( - fromStatement: sqliteStatement, + try Value._fastDecode( + sqliteStatement: sqliteStatement, atUncheckedIndex: CInt(index), - context: RowDecodingContext(statement: statement, index: index)) + context: _RowDecodingContext(statement: statement, index: index)) } func withUnsafeData(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T { diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index 86c42a38d..a226548c9 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -83,7 +83,7 @@ import Foundation /// } /// /// extension PlayerInfo: FetchableRecord { -/// init(row: Row) { +/// init(row: some RowProtocol) { /// player = row["player"] /// team = row["team"] /// } @@ -698,7 +698,7 @@ struct AdaptedRowImpl: RowImpl { var count: Int { mapping._layoutColumns.count } - var isFetched: Bool { base.isFetched } + var isFetched: Bool { base._isFetched } func scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView { Row.ScopesView(row: base, scopes: adapter._scopes, prefetchedRows: prefetchedRows) @@ -720,7 +720,7 @@ struct AdaptedRowImpl: RowImpl { throws -> Value { let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index) - return try Value.fastDecode(fromRow: base, atUncheckedIndex: mappedIndex) + return try base._fastDecode(Value.self, atUncheckedIndex: mappedIndex) } func withUnsafeData(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T { diff --git a/GRDB/Core/RowDecodingError.swift b/GRDB/Core/RowDecodingError.swift index c550c28c0..18bf65954 100644 --- a/GRDB/Core/RowDecodingError.swift +++ b/GRDB/Core/RowDecodingError.swift @@ -8,8 +8,7 @@ import SQLite3 #endif /// A key that is used to decode a value in a row -@usableFromInline -enum RowKey: Hashable, Sendable { +public enum _RowKey: Hashable, Sendable { /// A column name case columnName(String) @@ -38,7 +37,7 @@ enum RowDecodingError: Error { var row: Row { Row(impl: rowImpl) } /// Nil for RowDecodingError.keyNotFound, in order to avoid redundancy - let key: RowKey? + let key: _RowKey? /// The SQL query let sql: String? @@ -46,7 +45,7 @@ enum RowDecodingError: Error { /// The SQL query arguments let statementArguments: StatementArguments? - init(decodingContext: RowDecodingContext, debugDescription: String) { + init(decodingContext: _RowDecodingContext, debugDescription: String) { self.debugDescription = debugDescription self.rowImpl = ArrayRowImpl(columns: decodingContext.row) self.key = decodingContext.key @@ -55,7 +54,7 @@ enum RowDecodingError: Error { } } - case keyNotFound(RowKey, Context) + case keyNotFound(_RowKey, Context) case valueMismatch(Any.Type, Context) var context: Context { @@ -68,9 +67,10 @@ enum RowDecodingError: Error { /// Convenience method that builds the /// `could not decode from database value ` error message. + @usableFromInline static func valueMismatch( _ type: Any.Type, - context: RowDecodingContext, + context: _RowDecodingContext, databaseValue: DatabaseValue) -> Self { @@ -88,7 +88,7 @@ enum RowDecodingError: Error { _ type: Any.Type, sqliteStatement: SQLiteStatement, index: CInt, - context: RowDecodingContext) + context: _RowDecodingContext) -> Self { valueMismatch( @@ -107,14 +107,14 @@ enum RowDecodingError: Error { { valueMismatch( type, - context: RowDecodingContext(statement: statement, index: index), + context: _RowDecodingContext(statement: statement, index: index), databaseValue: DatabaseValue(sqliteStatement: statement.sqliteStatement, index: CInt(index))) } /// Convenience method that builds the `column not found: ` /// error message. @usableFromInline - static func columnNotFound(_ columnName: String, context: RowDecodingContext) -> Self { + static func columnNotFound(_ columnName: String, context: _RowDecodingContext) -> Self { keyNotFound( .columnName(columnName), RowDecodingError.Context(decodingContext: context, debugDescription: """ @@ -123,39 +123,20 @@ enum RowDecodingError: Error { } } -@usableFromInline -struct RowDecodingContext { +public struct _RowDecodingContext { /// The row that is decoded let row: Row - let key: RowKey? + let key: _RowKey? /// The SQL query let sql: String? /// The SQL query arguments let statementArguments: StatementArguments? - - @usableFromInline - init(row: Row, key: RowKey? = nil) { - if let statement = row.statement { - self.key = key - self.row = row.copy() - self.sql = statement.sql - self.statementArguments = statement.arguments - } else if let sqliteStatement = row.sqliteStatement { - self.key = key - self.row = row.copy() - self.sql = String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement - self.statementArguments = nil // Can't rebuild them - } else { - self.key = key - self.row = row.copy() - self.sql = nil - self.statementArguments = nil - } - } - +} + +extension _RowDecodingContext { /// Convenience initializer @usableFromInline init(statement: Statement, index: Int) { diff --git a/GRDB/Core/RowProtocol.swift b/GRDB/Core/RowProtocol.swift new file mode 100644 index 000000000..41298706a --- /dev/null +++ b/GRDB/Core/RowProtocol.swift @@ -0,0 +1,1205 @@ +import Foundation + +/// Support for ``DatabaseDateDecodingStrategy`` and similar types. +public protocol _RowDecodingStrategy { + associatedtype _RowDecodingOutput + + /// - precondition: value is not NULL + func _decode( + sqliteStatement: SQLiteStatement, + atUncheckedIndex index: CInt, + context: @autoclosure () -> _RowDecodingContext + ) throws -> _RowDecodingOutput + + func _decode( + databaseValue: DatabaseValue, + context: @autoclosure () -> _RowDecodingContext + ) throws -> _RowDecodingOutput +} + +public protocol _Row { + func _decode( + with strategy: Strategy, + atUncheckedIndex index: Int + ) throws -> Strategy._RowDecodingOutput + + func _decode( + _ type: Value.Type, + atUncheckedIndex index: Int + ) throws -> Value + + func _fastDecode( + _ type: Value.Type, + atUncheckedIndex index: Int + ) throws -> Value + + /// Returns true if and only if the row was fetched from a database. + var _isFetched: Bool { get } + + func _scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView + func _columnName(atUncheckedIndex index: Int) -> String + func _hasNull(atUncheckedIndex index: Int) -> Bool + func _databaseValue(atUncheckedIndex index: Int) -> DatabaseValue + + /// Calls the given closure with the `Data` at given index. + /// + /// Indexes span from `0` for the leftmost column to `row.count - 1` for the + /// rightmost column. + /// + /// If the SQLite value is `NULL`, the data is nil. If the SQLite value can + /// not be converted to `Data`, an error is thrown. + /// + /// - warning: The `Data` argument to the body must not be stored or used + /// outside of the lifetime of the call to the closure. + func _withUnsafeData(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T + + var _unscopedRow: Row { get } + var _unadaptedRow: Row { get } + #warning("TODO: remove") + var _copiedRow: Row { get } + + func _makeRowDecodingContext(forKey key: _RowKey?) -> _RowDecodingContext +} + +public protocol RowProtocol: _Row, RandomAccessCollection where Index == RowIndex, Element == (String, DatabaseValue) { + /// Returns the index of the leftmost column that matches *name* (case-insensitive) + func index(forColumn name: String) -> Int? + + #warning("TODO: only on copied database rows") + var prefetchedRows: Row.PrefetchedRowsView { get } + + #warning("TODO: check relevance") + func copy() -> Row +} + +// MARK: - Extracting Values + +extension RowProtocol { + + /// Fatal errors if index is out of bounds + @inline(__always) + @usableFromInline + func _checkIndex(_ index: Int, file: StaticString = #file, line: UInt = #line) { + GRDBPrecondition(index >= 0 && index < count, "row index out of range", file: file, line: line) + } + + /// Returns a boolean value indicating if the row contains one value this + /// is not `NULL`. + /// + /// For example: + /// + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 'foo', NULL")! + /// row.containsNonNullValue // true + /// + /// let row = try Row.fetchOne(db, sql: "SELECT NULL, NULL")! + /// row.containsNonNullValue // false + /// ``` + public var containsNonNullValue: Bool { + for i in (0.. Bool { + _checkIndex(index) + return _hasNull(atUncheckedIndex: index) + } + + /// Returns `Int64`, `Double`, `String`, `Data` or nil, depending on the + /// value stored at the given index. + /// + /// Indexes span from `0` for the leftmost column to `row.count - 1` for the + /// rightmost column. + public subscript(_ index: Int) -> (any DatabaseValueConvertible)? { + _checkIndex(index) + return _databaseValue(atUncheckedIndex: index).storage.value + } + + /// Returns the value at given index, converted to the requested type. + /// + /// Indexes span from `0` for the leftmost column to `row.count - 1` for the + /// rightmost column. + /// + /// For example: + /// + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 42")! + /// let score: Int = row[0] // 42 + /// + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")! + /// let name: String = row[0] // "Alice" + /// ``` + /// + /// When the database value may be nil, ask for an optional: + /// + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT NULL")! + /// let name: String? = row[0] // nil + /// ``` + @inlinable + public subscript(_ index: Int) -> Value { + try! decode(Value.self, atIndex: index) + } + + /// Returns the value at given index, converted to the requested type. + /// + /// This method exists as an optimization opportunity for types that adopt + /// ``StatementColumnConvertible``. It can trigger [SQLite built-in + /// conversions](https://www.sqlite.org/datatype3.html). + /// + /// Indexes span from `0` for the leftmost column to `row.count - 1` for the + /// rightmost column. + /// + /// For example: + /// + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 42")! + /// let score: Int = row[0] // 42 + /// + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")! + /// let name: String = row[0] // "Alice" + /// ``` + /// + /// When the database value may be nil, ask for an optional: + /// + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT NULL")! + /// let name: String? = row[0] // nil + /// ``` + @inline(__always) + @inlinable + public subscript(_ index: Int) -> Value { + try! fastDecode(Value.self, atIndex: index) + } + + /// Returns `Int64`, `Double`, `String`, `Data` or nil, depending on the + /// value stored at the given column. + /// + /// Column name lookup is case-insensitive. When several columns exist with + /// the same name, the leftmost column is considered. + /// + /// The result is nil if the row does not contain any column with that name. + public subscript(_ columnName: String) -> (any DatabaseValueConvertible)? { + // IMPLEMENTATION NOTE + // This method has a single known use case: checking if the value is nil, + // as in: + // + // if row["foo"] != nil { ... } + // + // Without this method, the code above would not compile. + guard let index = index(forColumn: columnName) else { + return nil + } + return _databaseValue(atUncheckedIndex: index).storage.value + } + + /// Returns the value at given column, converted to the requested type. + /// + /// Column name lookup is case-insensitive. When several columns exist with + /// the same name, the leftmost column is considered. + /// + /// For example: + /// + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")! + /// let score: Int = row["score"] // 42 + /// + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! + /// let name: String = row["name"] // "Alice" + /// ``` + /// + /// When the database value may be nil, ask for an optional: + /// + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")! + /// let name: String? = row["name"] // nil + /// ``` + /// + /// When the column does not exist, nil is returned: + /// + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! + /// let name: String? = row["missing"] // nil + /// ``` + @inlinable + public subscript(_ columnName: String) -> Value { + try! decode(Value.self, forKey: columnName) + } + + /// Returns the value at given column, converted to the requested type. + /// + /// This method exists as an optimization opportunity for types that adopt + /// ``StatementColumnConvertible``. It can trigger [SQLite built-in + /// conversions](https://www.sqlite.org/datatype3.html). + /// + /// Column name lookup is case-insensitive. When several columns exist with + /// the same name, the leftmost column is considered. + /// + /// For example: + /// + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")! + /// let score: Int = row["score"] // 42 + /// + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! + /// let name: String = row["name"] // "Alice" + /// ``` + /// + /// When the database value may be nil, ask for an optional: + /// + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")! + /// let name: String? = row["name"] // nil + /// ``` + /// + /// When the column does not exist, nil is returned: + /// + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! + /// let name: String? = row["missing"] // nil + /// ``` + @inlinable + public subscript(_ columnName: String) -> Value { + try! fastDecode(Value.self, forKey: columnName) + } + + /// Returns `Int64`, `Double`, `String`, `Data` or nil, depending on the + /// value stored at the given column. + /// + /// Column name lookup is case-insensitive. When several columns exist with + /// the same name, the leftmost column is considered. + /// + /// The result is nil if the row does not contain any column with that name. + public subscript(_ column: some ColumnExpression) -> (any DatabaseValueConvertible)? { + self[column.name] + } + + /// Returns the value at given column, converted to the requested type. + /// + /// Column name lookup is case-insensitive. When several columns exist with + /// the same name, the leftmost column is considered. + /// + /// For example: + /// + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")! + /// let score: Int = row[Column("score")] // 42 + /// + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! + /// let name: String = row[Column("name")] // "Alice" + /// ``` + /// + /// When the database value may be nil, ask for an optional: + /// + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")! + /// let name: String? = row[Column("name")] // nil + /// ``` + /// + /// When the column does not exist, nil is returned: + /// + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! + /// let name: String? = row[Column("missing")] // nil + /// ``` + @inlinable + public subscript(_ column: some ColumnExpression) -> Value { + try! decode(Value.self, forKey: column.name) + } + + /// Returns the value at given column, converted to the requested type. + /// + /// This method exists as an optimization opportunity for types that adopt + /// ``StatementColumnConvertible``. It can trigger [SQLite built-in + /// conversions](https://www.sqlite.org/datatype3.html). + /// + /// Column name lookup is case-insensitive. When several columns exist with + /// the same name, the leftmost column is considered. + /// + /// For example: + /// + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")! + /// let score: Int = row[Column("score")] // 42 + /// + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! + /// let name: String = row[Column("name")] // "Alice" + /// ``` + /// + /// When the database value may be nil, ask for an optional: + /// + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")! + /// let name: String? = row[Column("name")] // nil + /// ``` + /// + /// When the column does not exist, nil is returned: + /// + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! + /// let name: String? = row[Column("missing")] // nil + /// ``` + @inlinable + public subscript(_ column: some ColumnExpression) + -> Value + where Value: DatabaseValueConvertible & StatementColumnConvertible + { + try! fastDecode(Value.self, forKey: column.name) + } + + /// Calls the given closure with the `Data` at given index. + /// + /// Indexes span from `0` for the leftmost column to `row.count - 1` for the + /// rightmost column. + /// + /// If the SQLite value is `NULL`, the data is nil. If the SQLite value can + /// not be converted to `Data`, an error is thrown. + /// + /// - warning: The `Data` argument to the body must not be stored or used + /// outside of the lifetime of the call to the closure. + public func withUnsafeData(atIndex index: Int, _ body: (Data?) throws -> T) throws -> T { + _checkIndex(index) + return try _withUnsafeData(atUncheckedIndex: index, body) + } + + /// Calls the given closure with the `Data` at the given column. + /// + /// Column name lookup is case-insensitive. When several columns exist with + /// the same name, the leftmost column is considered. + /// + /// If the row does not contain any column with that name, or if the SQLite + /// value is `NULL`, the data is nil. If the SQLite value can not be + /// converted to `Data`, an error is thrown. + /// + /// - warning: The `Data` argument to the body must not be stored or used + /// outside of the lifetime of the call to the closure. + public func withUnsafeData(named columnName: String, _ body: (Data?) throws -> T) throws -> T { + guard let index = index(forColumn: columnName) else { + return try body(nil) + } + return try _withUnsafeData(atUncheckedIndex: index, body) + } + + /// Calls the given closure with the `Data` at the given column. + /// + /// Column name lookup is case-insensitive. When several columns exist with + /// the same name, the leftmost column is considered. + /// + /// If the row does not contain any column with that name, or if the SQLite + /// value is `NULL`, the data is nil. If the SQLite value can not be + /// converted to `Data`, an error is thrown. + /// + /// - warning: The `Data` argument to the body must not be stored or used + /// outside of the lifetime of the call to the closure. + public func withUnsafeData(at column: some ColumnExpression, _ body: (Data?) throws -> T) throws -> T { + try withUnsafeData(named: column.name, body) + } + + /// Returns the optional `Data` at given index. + /// + /// Indexes span from `0` for the leftmost column to `row.count - 1` for the + /// rightmost column. + /// + /// If the SQLite value is NULL, the result is nil. If the SQLite value can + /// not be converted to Data, a fatal error is raised. + /// + /// The returned data does not owns its bytes: it must not be used longer + /// than the row's lifetime. + @available(*, deprecated, message: "Use withUnsafeData(atIndex:_:) instead.") + public func dataNoCopy(atIndex index: Int) -> Data? { + try! withUnsafeData(atIndex: index, { $0 }) + } + + /// Returns the optional `Data` at given column. + /// + /// Column name lookup is case-insensitive. When several columns exist with + /// the same name, the leftmost column is considered. + /// + /// If the column is missing or if the SQLite value is NULL, the result is + /// nil. If the SQLite value can not be converted to Data, a fatal error + /// is raised. + /// + /// The returned data does not owns its bytes: it must not be used longer + /// than the row's lifetime. + @available(*, deprecated, message: "Use withUnsafeData(named:_:) instead.") + public func dataNoCopy(named columnName: String) -> Data? { + guard let index = index(forColumn: columnName) else { + return nil + } + return try! _withUnsafeData(atUncheckedIndex: index, { $0 }) + } + + /// Returns the optional `Data` at given column. + /// + /// Column name lookup is case-insensitive. When several columns exist with + /// the same name, the leftmost column is considered. + /// + /// If the column is missing or if the SQLite value is NULL, the result is + /// nil. If the SQLite value can not be converted to Data, a fatal error + /// is raised. + /// + /// The returned data does not owns its bytes: it must not be used longer + /// than the row's lifetime. + @available(*, deprecated, message: "Use withUnsafeData(at:_:) instead.") + public func dataNoCopy(_ column: some ColumnExpression) -> Data? { + dataNoCopy(named: column.name) + } +} + +// MARK: - Extracting DatabaseValue + +extension RowProtocol { + /// The database values in the row, from left to right. + /// + /// Values appear in the same order as they occur as the `.1` member + /// of column-value pairs in `self`. + public var databaseValues: LazyMapCollection { + lazy.map { $0.1 } + } +} + +// MARK: - Extracting Records + +extension RowProtocol { + /// The record associated to the given scope. + /// + /// Row scopes can be defined manually, with ``ScopeAdapter``. + /// The ``JoinableRequest/including(required:)`` and + /// ``JoinableRequest/including(optional:)`` request methods define scopes + /// named after the key of included associations between record types. + /// + /// A breadth-first search is performed in all available scopes in the row, + /// recursively. + /// + /// A fatal error is raised if the scope is not available, or contains only + /// `NULL` values. + /// + /// For example: + /// + /// ```swift + /// struct Book: TableRecord, FetchableRecord { + /// static let author = belongsTo(Author.self) + /// } + /// + /// struct Author: TableRecord, FetchableRecord { + /// static let country = belongsTo(Country.self) + /// } + /// + /// struct Country: TableRecord, FetchableRecord { } + /// + /// // Fetch a book, with its author, and the country of its author. + /// let request = Book + /// .including(required: Book.author + /// .including(required: Author.country)) + /// let bookRow = try Row.fetchOne(db, request)! + /// + /// let book = try Book(row: bookRow) + /// let author: Author = bookRow["author"] + /// let country: Country = bookRow["country"] + /// ``` + /// + /// See also: ``scopesTree`` + /// + /// - parameter scope: A scope identifier. + public subscript(_ scope: String) -> Record { + try! decode(Record.self, forKey: scope) + } + + /// The eventual record associated to the given scope. + /// + /// Row scopes can be defined manually, with ``ScopeAdapter``. + /// The ``JoinableRequest/including(required:)`` and + /// ``JoinableRequest/including(optional:)`` request methods define scopes + /// named after the key of included associations between record types. + /// + /// A breadth-first search is performed in all available scopes in the row, + /// recursively. + /// + /// The result is nil if the scope is not available, or contains only + /// `NULL` values. + /// + /// For example: + /// + /// ```swift + /// struct Book: TableRecord, FetchableRecord { + /// static let author = belongsTo(Author.self) + /// } + /// + /// struct Author: TableRecord, FetchableRecord { + /// static let country = belongsTo(Country.self) + /// } + /// + /// struct Country: TableRecord, FetchableRecord { } + /// + /// // Fetch a book, with its author, and the country of its author. + /// let request = Book + /// .including(optional: Book.author + /// .including(optional: Author.country)) + /// let bookRow = try Row.fetchOne(db, request)! + /// + /// let book = try Book(row: bookRow) + /// let author: Author? = bookRow["author"] + /// let country: Country? = bookRow["country"] + /// ``` + /// + /// See also: ``scopesTree`` + /// + /// - parameter scope: A scope identifier. + public subscript(_ scope: String) -> Record? { + try! decodeIfPresent(Record.self, forKey: scope) + } + + /// A collection of prefetched records associated to the given + /// association key. + /// + /// Prefetched rows are defined by the ``JoinableRequest/including(all:)`` + /// request method. + /// + /// For example: + /// + /// ```swift + /// struct Author: TableRecord, FetchableRecord { + /// static let books = hasMany(Book.self) + /// } + /// + /// struct Book: TableRecord, FetchableRecord { } + /// + /// let request = Author.including(all: Author.books) + /// let authorRow = try Row.fetchOne(db, request)! + /// + /// let author = try Author(row: authorRow) + /// let books: [Book] = author["books"] + /// ``` + /// + /// See also: ``prefetchedRows`` + /// + /// - parameter key: An association key. + public subscript(_ key: String) + -> Records + where + Records: RangeReplaceableCollection, + Records.Element: FetchableRecord + { + try! decode(Records.self, forKey: key) + } + + /// A set prefetched records associated to the given association key. + /// + /// Prefetched rows are defined by the ``JoinableRequest/including(all:)`` + /// request method. + /// + /// For example: + /// + /// ```swift + /// struct Author: TableRecord, FetchableRecord { + /// static let books = hasMany(Book.self) + /// } + /// + /// struct Book: TableRecord, FetchableRecord, Hashable { } + /// + /// let request = Author.including(all: Author.books) + /// let authorRow = try Row.fetchOne(db, request)! + /// + /// let author = try Author(row: authorRow) + /// let books: Set = author["books"] + /// ``` + /// + /// See also: ``prefetchedRows`` + /// + /// - parameter key: An association key. + public subscript(_ key: String) -> Set { + try! decode(Set.self, forKey: key) + } +} + +extension RowProtocol { + @inlinable + func _decodeIfPresent( + with strategy: Strategy, + atUncheckedIndex index: Int) + throws -> Strategy._RowDecodingOutput? + { + if _hasNull(atUncheckedIndex: index) { + return nil + } + return try _decode(with: strategy, atUncheckedIndex: index) + } + + @inlinable + func _decodeIfPresent( + _ type: Value.Type, + atUncheckedIndex index: Int) + throws -> Value? + { + try _decode(Optional.self, atUncheckedIndex: index) + } + + @inlinable + func _fastDecodeIfPresent( + _ type: Value.Type, + atUncheckedIndex index: Int) + throws -> Value? + { + try _fastDecode(Optional.self, atUncheckedIndex: index) + } + + /// Returns the eventual record associated with the given scope. + /// + /// For example: + /// + /// let request = Book.including(optional: Book.author) + /// let row = try Row.fetchOne(db, request)! + /// + /// try print(Book(row: row).title) + /// // Prints "Moby-Dick" + /// + /// let author: Author? = row["author"] + /// print(author.name) + /// // Prints "Herman Melville" + /// + /// Associated records stored in nested associations are available, too: + /// + /// let request = Book.including(optional: Book.author.including(optional: Author.country)) + /// let row = try Row.fetchOne(db, request)! + /// + /// try print(Book(row: row).title) + /// // Prints "Moby-Dick" + /// + /// let country: Country? = row["country"] + /// print(country.name) + /// // Prints "United States" + /// + /// Nil is returned if the scope is not available, or contains only + /// null values. + /// + /// See ``splittingRowAdapters(columnCounts:)`` for a sample code. + func decodeIfPresent( + _ type: Record.Type = Record.self, + forKey scope: String) + throws -> Record? + { + guard let scopedRow = scopesTree[scope], scopedRow.containsNonNullValue else { + return nil + } + return try Record(row: scopedRow) + } + + /// Returns the record associated with the given scope. + /// + /// For example: + /// + /// let request = Book.including(required: Book.author) + /// let row = try Row.fetchOne(db, request)! + /// + /// try print(Book(row: row).title) + /// // Prints "Moby-Dick" + /// + /// let author: Author = row["author"] + /// print(author.name) + /// // Prints "Herman Melville" + /// + /// Associated records stored in nested associations are available, too: + /// + /// let request = Book.including(required: Book.author.including(required: Author.country)) + /// let row = try Row.fetchOne(db, request)! + /// + /// try print(Book(row: row).title) + /// // Prints "Moby-Dick" + /// + /// let country: Country = row["country"] + /// print(country.name) + /// // Prints "United States" + /// + /// A fatal error is raised if the scope is not available, or contains only + /// null values. + /// + /// See ``splittingRowAdapters(columnCounts:)`` for a sample code. + func decode( + _ type: Record.Type = Record.self, + forKey scope: String) + throws -> Record + { + guard let scopedRow = scopesTree[scope] else { + let availableScopes = scopesTree.names + if availableScopes.isEmpty { + throw RowDecodingError.keyNotFound( + .scope(scope), + RowDecodingError.Context( + decodingContext: _makeRowDecodingContext(forKey: nil), + debugDescription: """ + scope not found: \(String(reflecting: scope)) + """)) + } else { + throw RowDecodingError.keyNotFound( + .scope(scope), + RowDecodingError.Context( + decodingContext: _makeRowDecodingContext(forKey: nil), + debugDescription: """ + scope not found: \(String(reflecting: scope)) - \ + available scopes: \(availableScopes.sorted()) + """)) + } + } + guard scopedRow.containsNonNullValue else { + throw RowDecodingError.valueMismatch( + Record.self, + RowDecodingError.Context( + decodingContext: _makeRowDecodingContext(forKey: .scope(scope)), + debugDescription: """ + scope \(String(reflecting: scope)) only contains null values + """)) + } + return try Record(row: scopedRow) + } +} + +extension RowProtocol { + /// Returns the records encoded in the given prefetched rows. + /// + /// For example: + /// + /// let request = Author.including(all: Author.books) + /// let row = try Row.fetchOne(db, request)! + /// + /// try print(Author(row: row).name) + /// // Prints "Herman Melville" + /// + /// let books: [Book] = row["books"] + /// print(books[0].title) + /// // Prints "Moby-Dick" + func decode( + _ type: Collection.Type = Collection.self, + forKey key: String) + throws -> Collection + where + Collection: RangeReplaceableCollection, + Collection.Element: FetchableRecord + { + guard let rows = prefetchedRows[key] else { + let availableKeys = prefetchedRows.keys + if availableKeys.isEmpty { + throw RowDecodingError.keyNotFound( + .prefetchKey(key), + RowDecodingError.Context( + decodingContext: _makeRowDecodingContext(forKey: nil), + debugDescription: """ + key for prefetched rows not found: \(String(reflecting: key)) + """)) + } else { + throw RowDecodingError.keyNotFound( + .prefetchKey(key), + RowDecodingError.Context( + decodingContext: _makeRowDecodingContext(forKey: nil), + debugDescription: """ + key for prefetched rows not found: \(String(reflecting: key)) \ + - available keys: \(availableKeys.sorted()) + """)) + } + } + + var collection = Collection() + collection.reserveCapacity(rows.count) + for row in rows { + try collection.append(Collection.Element(row: row)) + } + return collection + } + + /// Returns the set of records encoded in the given prefetched rows. + /// + /// For example: + /// + /// let request = Author.including(all: Author.books) + /// let row = try Row.fetchOne(db, request)! + /// + /// try print(Author(row: row).name) + /// // Prints "Herman Melville" + /// + /// let books: Set = row["books"] + /// print(books.first!.title) + /// // Prints "Moby-Dick" + func decode( + _ type: Set.Type = Set.self, + forKey key: String) + throws -> Set + { + guard let rows = prefetchedRows[key] else { + let availableKeys = prefetchedRows.keys + if availableKeys.isEmpty { + throw RowDecodingError.keyNotFound( + .prefetchKey(key), + RowDecodingError.Context( + decodingContext: _makeRowDecodingContext(forKey: nil), + debugDescription: """ + key for prefetched rows not found: \(String(reflecting: key)) + """)) + } else { + throw RowDecodingError.keyNotFound( + .prefetchKey(key), + RowDecodingError.Context( + decodingContext: _makeRowDecodingContext(forKey: nil), + debugDescription: """ + key for prefetched rows not found: \(String(reflecting: key)) \ + - available keys: \(availableKeys.sorted()) + """)) + } + } + var set = Set(minimumCapacity: rows.count) + for row in rows { + try set.insert(Record(row: row)) + } + return set + } +} + +// MARK: - Scopes + +extension RowProtocol { + /// A view on the scopes defined by row adapters. + /// + /// The returned object provides an access to all available scopes in + /// the row. + /// + /// Row scopes can be defined manually, with ``ScopeAdapter``. + /// The ``JoinableRequest/including(required:)`` and + /// ``JoinableRequest/including(optional:)`` request methods define scopes + /// named after the key of included associations between record types. + /// + /// For example: + /// + /// ```swift + /// struct Book: TableRecord { + /// static let author = belongsTo(Author.self) + /// } + /// + /// struct Author: TableRecord { + /// static let country = belongsTo(Country.self) + /// } + /// + /// struct Country: TableRecord { } + /// + /// // Fetch a book, with its author, and the country of its author. + /// let request = Book + /// .including(required: Book.author + /// .including(required: Author.country)) + /// let bookRow = try Row.fetchOne(db, request)! + /// + /// print(bookRow) + /// // Prints [id:42, title:"Moby-Dick", authorId:1] + /// + /// let authorRow = bookRow.scopes["author"]! + /// print(authorRow) + /// // Prints [id:1, name:"Herman Melville", countryCode: "US"] + /// + /// let countryRow = authorRow.scopes["country"]! + /// print(countryRow) + /// // Prints [code:"US" name:"United States of America"] + /// ``` + /// + /// See also ``scopesTree``. + public var scopes: Row.ScopesView { + _scopes(prefetchedRows: prefetchedRows) + } + + /// A view on the scopes tree defined by row adapters. + /// + /// The returned object provides an access to all available scopes in + /// the row, recursively. For any given scope identifier, a breadth-first + /// search is performed. + /// + /// Row scopes can be defined manually, with ``ScopeAdapter``. + /// The ``JoinableRequest/including(required:)`` and + /// ``JoinableRequest/including(optional:)`` request methods define scopes + /// named after the key of included associations between record types. + /// + /// For example: + /// + /// ```swift + /// struct Book: TableRecord { + /// static let author = belongsTo(Author.self) + /// } + /// + /// struct Author: TableRecord { + /// static let country = belongsTo(Country.self) + /// } + /// + /// struct Country: TableRecord { } + /// + /// // Fetch a book, with its author, and the country of its author. + /// let request = Book + /// .including(required: Book.author + /// .including(required: Author.country)) + /// let bookRow = try Row.fetchOne(db, request)! + /// + /// print(bookRow) + /// // Prints [id:42, title:"Moby-Dick", authorId:1] + /// + /// print(bookRow.scopesTree["author"]) + /// // Prints [id:1, name:"Herman Melville", countryCode: "US"] + /// + /// print(bookRow.scopesTree["country"]) + /// // Prints [code:"US" name:"United States of America"] + /// ``` + /// + /// See also ``scopes``. + public var scopesTree: Row.ScopesTreeView { + Row.ScopesTreeView(scopes: scopes) + } + + /// The row, without any scope of prefetched rows. + /// + /// This property is useful when testing the content of rows fetched from + /// joined requests. + /// + /// For example: + /// + /// ```swift + /// struct Book: TableRecord { + /// static let author = belongsTo(Author.self) + /// static let awards = hasMany(Award.self) + /// } + /// + /// struct Author: TableRecord { } + /// struct Award: TableRecord { } + /// + /// // Fetch a book, with its author, and its awards. + /// let request = Book + /// .including(required: Book.author) + /// .including(all: Book.awards) + /// let bookRow = try Row.fetchOne(db, request)! + /// + /// // Failure + /// XCTAssertEqual(bookRow, ["id":42, "title":"Moby-Dick", "authorId":1]) + /// + /// // Success + /// XCTAssertEqual(bookRow.unscoped, ["id":42, "title":"Moby-Dick", "authorId":1]) + /// ``` + public var unscoped: Row { + var row = _unscopedRow + + // Remove prefetchedRows + if row.prefetchedRows.isEmpty == false { + // Make sure we build another Row instance + row = Row(impl: row.copy().impl) + assert(row.prefetchedRows.isEmpty) + } + return row + } + + /// The raw row fetched from the database. + /// + /// This property is useful when debugging the content of rows fetched from + /// joined requests. + /// + /// For example: + /// + /// ```swift + /// struct Book: TableRecord { + /// static let author = belongsTo(Author.self) + /// } + /// + /// struct Author: TableRecord { } + /// + /// // SELECT book.*, author.* + /// // FROM book + /// // JOIN author ON author.id = book.authorId + /// let request = Book.including(required: Book.author) + /// let bookRow = try Row.fetchOne(db, request)! + /// + /// print(bookRow) + /// // Prints [id:42, title:"Moby-Dick", authorId:1] + /// + /// print(bookRow.unadapted) + /// // Prints [id:42, title:"Moby-Dick", authorId:1, id:1, name:"Herman Melville"] + /// ``` + public var unadapted: Row { + _unadaptedRow + } +} + +// MARK: - Columns + +extension RowProtocol { + + // MARK: - Columns + + /// The names of columns in the row, from left to right. + /// + /// Columns appear in the same order as they occur as the `.0` member + /// of column-value pairs in `self`. + public var columnNames: LazyMapCollection { + lazy.map { $0.0 } + } + + /// Returns whether the row has one column with the given name + /// (case-insensitive). + public func hasColumn(_ columnName: String) -> Bool { + index(forColumn: columnName) != nil + } +} + +// MARK: - Throwing DatabaseValueConvertible Decoding Methods + +extension RowProtocol { + /// Returns the value at given index, converted to the requested type. + /// + /// Indexes span from `0` for the leftmost column to `row.count - 1` for the + /// rightmost column. + /// + /// If the SQLite value is NULL, or if the conversion fails, a + /// `RowDecodingError` is thrown. + @inlinable + func decode( + _ type: Value.Type = Value.self, + atIndex index: Int) + throws -> Value + { + _checkIndex(index) + return try _decode(Value.self, atUncheckedIndex: index) + } + + /// Returns the value at given column, converted to the requested type. + /// + /// Column name lookup is case-insensitive. When several columns exist with + /// the same name, the leftmost column is considered. + /// + /// If the row does not contain the column, or if the SQLite value is NULL, + /// or if the SQLite value can not be converted to `Value`, a + /// `RowDecodingError` is thrown. + @inlinable + func decode( + _ type: Value.Type = Value.self, + forKey columnName: String) + throws -> Value + { + guard let index = index(forColumn: columnName) else { + if let value = Value.fromMissingColumn() { + return value + } else { + throw RowDecodingError.columnNotFound(columnName, context: _makeRowDecodingContext(forKey: nil)) + } + } + return try _decode(Value.self, atUncheckedIndex: index) + } +} + +// MARK: - Throwing DatabaseValueConvertible & StatementColumnConvertible Decoding Methods + +extension RowProtocol { + /// Returns the value at given index, converted to the requested type. + /// + /// This method exists as an optimization opportunity for types that adopt + /// ``StatementColumnConvertible``. It can trigger [SQLite built-in + /// conversions](https://www.sqlite.org/datatype3.html). + /// + /// Indexes span from `0` for the leftmost column to `row.count - 1` for the + /// rightmost column. + /// + /// If the SQLite value is NULL, or if the conversion fails, a + /// `RowDecodingError` is thrown. + @inline(__always) + @inlinable + func fastDecode( + _ type: Value.Type = Value.self, + atIndex index: Int) + throws -> Value + { + _checkIndex(index) + return try _fastDecode(Value.self, atUncheckedIndex: index) + } + + /// Returns the value at given column, converted to the requested type. + /// + /// This method exists as an optimization opportunity for types that adopt + /// ``StatementColumnConvertible``. It can trigger [SQLite built-in + /// conversions](https://www.sqlite.org/datatype3.html). + /// + /// Column name lookup is case-insensitive. When several columns exist with + /// the same name, the leftmost column is considered. + /// + /// If the row does not contain the column, or if the SQLite value is NULL, + /// or if the SQLite value can not be converted to `Value`, a + /// `RowDecodingError` is thrown. + @inlinable + func fastDecode( + _ type: Value.Type = Value.self, + forKey columnName: String) + throws -> Value + { + guard let index = index(forColumn: columnName) else { + if let value = Value.fromMissingColumn() { + return value + } else { + throw RowDecodingError.columnNotFound(columnName, context: _makeRowDecodingContext(forKey: nil)) + } + } + return try _fastDecode(Value.self, atUncheckedIndex: index) + } +} + +extension RowProtocol where Self: CustomStringConvertible { + public var description: String { + "[" + + map { (column, dbValue) in "\(column):\(dbValue)" }.joined(separator: " ") + + "]" + } +} + +// MARK: - RandomAccessCollection + +extension RowProtocol { + public var startIndex: RowIndex { RowIndex(0) } + + public var endIndex: RowIndex { RowIndex(count) } + + /// Returns the (column, value) pair at given index. + public subscript(position: RowIndex) -> (String, DatabaseValue) { + let index = position.index + _checkIndex(index) + return ( + _columnName(atUncheckedIndex: index), + _databaseValue(atUncheckedIndex: index)) + } +} + +/// An index to a (column, value) pair in a ``Row``. +public struct RowIndex: Sendable { + @usableFromInline + var index: Int + + @usableFromInline + init(_ index: Int) { self.index = index } +} + +extension RowIndex: Hashable { } + +extension RowIndex: Comparable { + public static func < (lhs: Self, rhs: Self) -> Bool { + lhs.index < rhs.index + } +} + +extension RowIndex: Strideable { + public func distance(to other: Self) -> Int { + other.index - index + } + + public func advanced(by n: Int) -> Self { + RowIndex(index + n) + } +} diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 9a26a927e..88605018d 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -32,7 +32,7 @@ import SQLite3 /// var name: String /// var score: Int /// -/// init(row: Row) { +/// init(row: some RowProtocol) { /// // Optimized /// name = row["name"] /// score = row["score"] @@ -136,62 +136,21 @@ extension StatementColumnConvertible { // MARK: - Conversions -extension DatabaseValueConvertible where Self: StatementColumnConvertible { - @usableFromInline - /* private */ static func _valueMismatch( - fromStatement sqliteStatement: SQLiteStatement, +extension StatementColumnConvertible { + @inlinable + public static func _fastDecode( + sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt, - context: @autoclosure () -> RowDecodingContext) - throws -> Never - { - throw RowDecodingError.valueMismatch( - Self.self, - sqliteStatement: sqliteStatement, - index: index, - context: context()) - } - - @inline(__always) - @inlinable - static func fastDecode( - fromRow row: Row, - atUncheckedIndex index: Int) - throws -> Self - { - if let sqliteStatement = row.sqliteStatement { - return try fastDecode( - fromStatement: sqliteStatement, - atUncheckedIndex: CInt(index), - context: RowDecodingContext(row: row, key: .columnIndex(index))) + context: @autoclosure () -> _RowDecodingContext + ) throws -> Self { + guard let value = fromStatement(sqliteStatement, atUncheckedIndex: index) else { + throw RowDecodingError.valueMismatch( + Self.self, + sqliteStatement: sqliteStatement, + index: index, + context: context()) } - // Support for fast decoding from adapted rows - return try row.fastDecode(Self.self, atUncheckedIndex: index) - } - - @inline(__always) - @inlinable - static func fastDecode( - fromStatement sqliteStatement: SQLiteStatement, - atUncheckedIndex index: CInt, - context: @autoclosure () -> RowDecodingContext) - throws -> Self - { - if let value = fromStatement(sqliteStatement, atUncheckedIndex: index) { - return value - } else { - try _valueMismatch(fromStatement: sqliteStatement, atUncheckedIndex: index, context: context()) - } - } - - // Support for Decodable - @inline(__always) - @inlinable - static func fastDecodeIfPresent( - fromRow row: Row, - atUncheckedIndex index: Int) - throws -> Self? - { - try Optional.fastDecode(fromRow: row, atUncheckedIndex: index) + return value } } @@ -243,10 +202,10 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible @inlinable public func _element(sqliteStatement: SQLiteStatement) throws -> Value { - try Value.fastDecode( - fromStatement: sqliteStatement, + try Value._fastDecode( + sqliteStatement: sqliteStatement, atUncheckedIndex: columnIndex, - context: RowDecodingContext(statement: _statement, index: Int(columnIndex))) + context: _RowDecodingContext(statement: _statement, index: Int(columnIndex))) } } diff --git a/GRDB/Core/StatementRow.swift b/GRDB/Core/StatementRow.swift new file mode 100644 index 000000000..47ad9fb7b --- /dev/null +++ b/GRDB/Core/StatementRow.swift @@ -0,0 +1,152 @@ +#if SWIFT_PACKAGE +import CSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + +import Foundation + +#warning("TODO: document") +final class StatementRow { + private let statement: Statement + private let sqliteStatement: SQLiteStatement + private let lowercaseColumnIndexes: [String: Int] + + init(statement: Statement) { + let sqliteStatement = statement.sqliteStatement + + self.statement = statement + self.sqliteStatement = sqliteStatement + + // Optimize index(forColumn:) + let lowercaseColumnNames = (0.. Row { + Row(copiedFromSQLiteStatement: sqliteStatement, statement: statement) + } + + func _decode( + with strategy: Strategy, + atUncheckedIndex index: Int + ) throws -> Strategy._RowDecodingOutput + { + let statementIndex = CInt(index) + + if sqlite3_column_type(sqliteStatement, statementIndex) == SQLITE_NULL { + throw RowDecodingError.valueMismatch( + Strategy._RowDecodingOutput.self, + sqliteStatement: sqliteStatement, + index: statementIndex, + context: _makeRowDecodingContext(forKey: .columnIndex(index))) + } + + return try strategy._decode( + sqliteStatement: sqliteStatement, + atUncheckedIndex: CInt(index), + context: _makeRowDecodingContext(forKey: .columnIndex(index))) + } + + func _decode( + _ type: Value.Type, + atUncheckedIndex index: Int + ) throws -> Value + { + try Value._decode( + databaseValue: _databaseValue(atUncheckedIndex: index), + context: _makeRowDecodingContext(forKey: .columnIndex(index))) + } + + func _fastDecode( + _ type: Value.Type, + atUncheckedIndex index: Int + ) throws -> Value + { + try Value._fastDecode( + sqliteStatement: sqliteStatement, + atUncheckedIndex: CInt(index), + context: _RowDecodingContext(statement: statement, index: index)) + } + + var _isFetched: Bool { + true + } + + func _scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView { + Row.ScopesView() + } + + func _columnName(atUncheckedIndex index: Int) -> String { + statement.columnNames[index] + } + + func _hasNull(atUncheckedIndex index: Int) -> Bool { + // Avoid extracting values, because this modifies the SQLite statement. + sqlite3_column_type(sqliteStatement, CInt(index)) == SQLITE_NULL + } + + func _databaseValue(atUncheckedIndex index: Int) -> DatabaseValue { + DatabaseValue(sqliteStatement: sqliteStatement, index: CInt(index)) + } + + func _withUnsafeData(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T { + guard sqlite3_column_type(sqliteStatement, CInt(index)) != SQLITE_NULL else { + return try body(nil) + } + guard let bytes = sqlite3_column_blob(sqliteStatement, CInt(index)) else { + return try body(Data()) + } + + let count = Int(sqlite3_column_bytes(sqliteStatement, CInt(index))) + let data = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none) + return try body(data) + } + + #warning("TODO: wrong return type") + var _unscopedRow: Row { + copy() + } + + #warning("TODO: wrong return type") + var _unadaptedRow: Row { + copy() + } + + #warning("TODO: wrong return type") + var _copiedRow: Row { + copy() + } + + func _makeRowDecodingContext(forKey key: _RowKey?) -> _RowDecodingContext { + _RowDecodingContext( + row: copy(), + key: key, + sql: statement.sql, + statementArguments: statement.arguments) + } + + func index(forColumn name: String) -> Int? { + if let index = lowercaseColumnIndexes[name] { + return index + } + return lowercaseColumnIndexes[name.lowercased()] + } +} diff --git a/GRDB/Core/Support/Foundation/Data.swift b/GRDB/Core/Support/Foundation/Data.swift index 67367c5fa..a1bd15001 100644 --- a/GRDB/Core/Support/Foundation/Data.swift +++ b/GRDB/Core/Support/Foundation/Data.swift @@ -69,27 +69,3 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible { } } } - -// MARK: - Conversions - -extension Data { - static func fastDecodeNoCopy( - fromStatement sqliteStatement: SQLiteStatement, - atUncheckedIndex index: CInt, - context: @autoclosure () -> RowDecodingContext) - throws -> Data - { - guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else { - throw RowDecodingError.valueMismatch( - Data.self, - sqliteStatement: sqliteStatement, - index: index, - context: context()) - } - guard let bytes = sqlite3_column_blob(sqliteStatement, index) else { - return Data() - } - let count = Int(sqlite3_column_bytes(sqliteStatement, index)) - return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none) - } -} diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 119e8a4af..a94e4b3df 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -11,7 +11,7 @@ import Foundation extension FetchableRecord where Self: Decodable { /// Creates a record from `row`, using the `Decodable` conformance. - public init(row: Row) throws { + public init(row: some RowProtocol) throws { self = try FetchableRecordDecoder().decode(Self.self, from: row) } } @@ -78,17 +78,26 @@ public class FetchableRecordDecoder { /// - row: The database row to decode. /// - Returns: An instance of the specified record type, if the decoder /// can parse the database row. - public func decode(_ type: T.Type, from row: Row) throws -> T { - let decoder = _RowDecoder(row: row, codingPath: [], columnDecodingStrategy: T.databaseColumnDecodingStrategy) + public func decode(_ type: T.Type, from row: RowType) throws -> T { + let decoder = _RowDecoder(row: row, codingPath: [], columnDecodingStrategy: T.databaseColumnDecodingStrategy) return try T(from: decoder) } } +#warning("TODO: fetch if correct") +private struct NestedDecodingContext: FetchableRecord { + init(row: some RowProtocol) throws { preconditionFailure() } + static var databaseColumnDecodingStrategy: DatabaseColumnDecodingStrategy { R.databaseColumnDecodingStrategy } + static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo } + static var databaseDataDecodingStrategy: DatabaseDataDecodingStrategy { R.databaseDataDecodingStrategy } + static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { R.databaseDateDecodingStrategy } +} + // MARK: - _RowDecoder /// The decoder that decodes a record from a database row -private struct _RowDecoder: Decoder { - var row: Row +private struct _RowDecoder: Decoder { + var row: RowType var codingPath: [CodingKey] var columnDecodingStrategy: DatabaseColumnDecodingStrategy var userInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo } @@ -118,17 +127,17 @@ private struct _RowDecoder: Decoder { func singleValueContainer() throws -> SingleValueDecodingContainer { guard let key = codingPath.last else { // Decoding an array of scalars from rows: pick the first column - return ColumnDecoder(row: row, columnIndex: 0, codingPath: codingPath) + return ColumnDecoder(row: row, columnIndex: 0, codingPath: codingPath) } guard let index = row.index(forColumn: key.stringValue) else { // Don't use DecodingError.keyNotFound: // We need to specifically recognize missing columns in order to // provide correct feedback. - throw RowDecodingError.columnNotFound(key.stringValue, context: RowDecodingContext(row: row)) + throw RowDecodingError.columnNotFound(key.stringValue, context: row._makeRowDecodingContext(forKey: nil)) } // TODO: test // See DatabaseValueConversionErrorTests.testDecodableFetchableRecord2 - return ColumnDecoder(row: row, columnIndex: index, codingPath: codingPath) + return ColumnDecoder(row: row, columnIndex: index, codingPath: codingPath) } class KeyedContainer: KeyedDecodingContainerProtocol { @@ -248,12 +257,12 @@ private struct _RowDecoder: Decoder { } // TODO: this is not quite correct: key IS NOT a column name. - // So we shouldn't use RowKey.columnName. Yet this only impacts + // So we shouldn't use _RowKey.columnName. Yet this only impacts // internal types, so the damage is limited. throw RowDecodingError.keyNotFound( .columnName(key.stringValue), // <- See above TODO RowDecodingError.Context( - decodingContext: RowDecodingContext(row: decoder.row), + decodingContext: decoder.row._makeRowDecodingContext(forKey: nil), debugDescription: "key not found: \(errorDescription)")) } @@ -270,18 +279,18 @@ private struct _RowDecoder: Decoder { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. if type == Data.self { - return try R.databaseDataDecodingStrategy.decodeIfPresent( - fromRow: row, + return try row._decodeIfPresent( + with: R.databaseDataDecodingStrategy, atUncheckedIndex: index) as! T? } else if type == Date.self { - return try R.databaseDateDecodingStrategy.decodeIfPresent( - fromRow: row, + return try row._decodeIfPresent( + with: R.databaseDateDecodingStrategy, atUncheckedIndex: index) as! T? } else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type { - return try type.fastDecodeIfPresent(fromRow: row, atUncheckedIndex: index) as! T? + return try row._fastDecodeIfPresent(type, atUncheckedIndex: index) as! T? } else if let type = T.self as? any DatabaseValueConvertible.Type { - return try type.decodeIfPresent(fromRow: row, atUncheckedIndex: index) as! T? - } else if row.impl.hasNull(atUncheckedIndex: index) { + return try row._decodeIfPresent(type, atUncheckedIndex: index) as! T? + } else if row._hasNull(atUncheckedIndex: index) { return nil } else { return try decode(type, fromRow: row, columnAtIndex: index, key: key) @@ -319,13 +328,13 @@ private struct _RowDecoder: Decoder { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. if type == Data.self { - return try R.databaseDataDecodingStrategy.decode(fromRow: row, atUncheckedIndex: index) as! T + return try row._decode(with: R.databaseDataDecodingStrategy, atUncheckedIndex: index) as! T } else if type == Date.self { - return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: index) as! T + return try row._decode(with: R.databaseDateDecodingStrategy, atUncheckedIndex: index) as! T } else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type { - return try type.fastDecode(fromRow: row, atUncheckedIndex: index) as! T + return try row._fastDecode(type, atUncheckedIndex: index) as! T } else if let type = T.self as? any DatabaseValueConvertible.Type { - return try type.decode(fromRow: row, atUncheckedIndex: index) as! T + return try row._decode(type, atUncheckedIndex: index) as! T } else { return try decode(type, fromRow: row, columnAtIndex: index, key: key) } @@ -404,9 +413,10 @@ private struct _RowDecoder: Decoder { // Helper methods - private func decode( + #warning("TODO: make NestedRowType concrete once it is settled") + private func decode( _ type: T.Type, - fromRow row: Row, + fromRow row: NestedRowType, codingPath: [CodingKey]) throws -> T where T: Decodable @@ -415,14 +425,14 @@ private struct _RowDecoder: Decoder { // Prefer FetchableRecord decoding over Decodable. return try type.init(row: row) as! T } else { - let decoder = _RowDecoder(row: row, codingPath: codingPath, columnDecodingStrategy: .useDefaultKeys) + let decoder = _RowDecoder>(row: row, codingPath: codingPath, columnDecodingStrategy: .useDefaultKeys) return try T(from: decoder) } } private func decode( _ type: T.Type, - fromRow row: Row, + fromRow row: RowType, columnAtIndex index: Int, key: Key) throws -> T @@ -433,7 +443,7 @@ private struct _RowDecoder: Decoder { // or unkeyed containers, because we're decoding a single // value here (string, int, double, data, null). If such an // error happens, we'll switch to JSON decoding. - let columnDecoder = ColumnDecoder( + let columnDecoder = ColumnDecoder( row: row, columnIndex: index, codingPath: codingPath + [key]) @@ -497,7 +507,7 @@ extension PrefetchedRowsDecoder: UnkeyedDecodingContainer { columnDecodingStrategy = .useDefaultKeys } - let decoder = _RowDecoder( + let decoder = _RowDecoder( row: rows[currentIndex], codingPath: codingPath, columnDecodingStrategy: columnDecodingStrategy) @@ -523,8 +533,8 @@ extension PrefetchedRowsDecoder: UnkeyedDecodingContainer { // MARK: - ColumnDecoder /// The decoder that decodes from a database column -private struct ColumnDecoder: Decoder { - var row: Row +private struct ColumnDecoder: Decoder { + var row: RowType var columnIndex: Int var codingPath: [CodingKey] var userInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo } @@ -565,13 +575,13 @@ extension ColumnDecoder: SingleValueDecodingContainer { func decode(_ type: T.Type) throws -> T where T: Decodable { // TODO: not tested if type == Data.self { - return try R.databaseDataDecodingStrategy.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T + return try row._decode(with: R.databaseDataDecodingStrategy, atUncheckedIndex: columnIndex) as! T } else if type == Date.self { - return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T + return try row._decode(with: R.databaseDateDecodingStrategy, atUncheckedIndex: columnIndex) as! T } else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type { - return try type.fastDecode(fromRow: row, atUncheckedIndex: columnIndex) as! T + return try row._fastDecode(type, atUncheckedIndex: columnIndex) as! T } else if let type = T.self as? any DatabaseValueConvertible.Type { - return try type.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T + return try row._decode(type, atUncheckedIndex: columnIndex) as! T } else { return try T(from: self) } @@ -584,50 +594,12 @@ private let iso8601Formatter: ISO8601DateFormatter = { return formatter }() -extension DatabaseDataDecodingStrategy { - fileprivate func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Data? { - if let sqliteStatement = row.sqliteStatement { - return try decodeIfPresent( - fromStatement: sqliteStatement, - atUncheckedIndex: CInt(index), - context: RowDecodingContext(row: row, key: .columnIndex(index))) - } else { - return try decodeIfPresent( - fromDatabaseValue: row[index], - context: RowDecodingContext(row: row, key: .columnIndex(index))) - } - } - - fileprivate func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Data { - if let sqliteStatement = row.sqliteStatement { - let statementIndex = CInt(index) - - if sqlite3_column_type(sqliteStatement, statementIndex) == SQLITE_NULL { - throw RowDecodingError.valueMismatch( - Data.self, - sqliteStatement: sqliteStatement, - index: statementIndex, - context: RowDecodingContext(row: row, key: .columnIndex(index))) - } - - return try decode( - fromStatement: sqliteStatement, - atUncheckedIndex: statementIndex, - context: RowDecodingContext(row: row, key: .columnIndex(index))) - } else { - return try decode( - fromDatabaseValue: row[index], - context: RowDecodingContext(row: row, key: .columnIndex(index))) - } - } - - /// - precondition: value is not NULL - fileprivate func decode( - fromStatement sqliteStatement: SQLiteStatement, +extension DatabaseDataDecodingStrategy: _RowDecodingStrategy { + public func _decode( + sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt, - context: @autoclosure () -> RowDecodingContext) - throws -> Data - { + context: @autoclosure () -> _RowDecodingContext + ) throws -> Data { assert(sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL, "unexpected NULL value") switch self { case .deferredToData: @@ -644,46 +616,22 @@ extension DatabaseDataDecodingStrategy { } } - fileprivate func decodeIfPresent( - fromStatement sqliteStatement: SQLiteStatement, - atUncheckedIndex index: CInt, - context: @autoclosure () -> RowDecodingContext) - throws -> Data? - { - if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { - return nil - } - return try decode(fromStatement: sqliteStatement, atUncheckedIndex: index, context: context()) - } - - fileprivate func decode( - fromDatabaseValue dbValue: DatabaseValue, - context: @autoclosure () -> RowDecodingContext) - throws -> Data - { - if let data = dataFromDatabaseValue(dbValue) { + public func _decode( + databaseValue: DatabaseValue, + context: @autoclosure () -> _RowDecodingContext + ) throws -> Data { + if let data = decode(databaseValue) { return data } else { - throw RowDecodingError.valueMismatch(Data.self, context: context(), databaseValue: dbValue) + throw RowDecodingError.valueMismatch( + Data.self, + context: context(), + databaseValue: databaseValue) } } - fileprivate func decodeIfPresent( - fromDatabaseValue dbValue: DatabaseValue, - context: @autoclosure () -> RowDecodingContext) - throws -> Data? - { - if dbValue.isNull { - return nil - } else if let data = dataFromDatabaseValue(dbValue) { - return data - } else { - throw RowDecodingError.valueMismatch(Data.self, context: context(), databaseValue: dbValue) - } - } - - // Returns nil if decoding fails - private func dataFromDatabaseValue(_ dbValue: DatabaseValue) -> Data? { + /// Returns nil if decoding fails + private func decode(_ dbValue: DatabaseValue) -> Data? { switch self { case .deferredToData: return Data.fromDatabaseValue(dbValue) @@ -693,50 +641,12 @@ extension DatabaseDataDecodingStrategy { } } -extension DatabaseDateDecodingStrategy { - fileprivate func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Date? { - if let sqliteStatement = row.sqliteStatement { - return try decodeIfPresent( - fromStatement: sqliteStatement, - atUncheckedIndex: CInt(index), - context: RowDecodingContext(row: row, key: .columnIndex(index))) - } else { - return try decodeIfPresent( - fromDatabaseValue: row[index], - context: RowDecodingContext(row: row, key: .columnIndex(index))) - } - } - - fileprivate func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Date { - if let sqliteStatement = row.sqliteStatement { - let statementIndex = CInt(index) - - if sqlite3_column_type(sqliteStatement, statementIndex) == SQLITE_NULL { - throw RowDecodingError.valueMismatch( - Date.self, - sqliteStatement: sqliteStatement, - index: statementIndex, - context: RowDecodingContext(row: row, key: .columnIndex(index))) - } - - return try decode( - fromStatement: sqliteStatement, - atUncheckedIndex: CInt(index), - context: RowDecodingContext(row: row, key: .columnIndex(index))) - } else { - return try decode( - fromDatabaseValue: row[index], - context: RowDecodingContext(row: row, key: .columnIndex(index))) - } - } - - /// - precondition: value is not NULL - fileprivate func decode( - fromStatement sqliteStatement: SQLiteStatement, +extension DatabaseDateDecodingStrategy: _RowDecodingStrategy { + public func _decode( + sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt, - context: @autoclosure () -> RowDecodingContext) - throws -> Date - { + context: @autoclosure () -> _RowDecodingContext + ) throws -> Date { assert(sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL, "unexpected NULL value") switch self { case .deferredToDate: @@ -786,46 +696,22 @@ extension DatabaseDateDecodingStrategy { } } - fileprivate func decodeIfPresent( - fromStatement sqliteStatement: SQLiteStatement, - atUncheckedIndex index: CInt, - context: @autoclosure () -> RowDecodingContext) - throws -> Date? - { - if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { - return nil - } - return try decode(fromStatement: sqliteStatement, atUncheckedIndex: index, context: context()) - } - - fileprivate func decode( - fromDatabaseValue dbValue: DatabaseValue, - context: @autoclosure () -> RowDecodingContext) - throws -> Date - { - if let date = dateFromDatabaseValue(dbValue) { + public func _decode( + databaseValue: DatabaseValue, + context: @autoclosure () -> _RowDecodingContext + ) throws -> Date { + if let date = decode(databaseValue) { return date } else { - throw RowDecodingError.valueMismatch(Date.self, context: context(), databaseValue: dbValue) + throw RowDecodingError.valueMismatch( + Date.self, + context: context(), + databaseValue: databaseValue) } } - fileprivate func decodeIfPresent( - fromDatabaseValue dbValue: DatabaseValue, - context: @autoclosure () -> RowDecodingContext) - throws -> Date? - { - if dbValue.isNull { - return nil - } else if let date = dateFromDatabaseValue(dbValue) { - return date - } else { - throw RowDecodingError.valueMismatch(Date.self, context: context(), databaseValue: dbValue) - } - } - - // Returns nil if decoding fails - private func dateFromDatabaseValue(_ dbValue: DatabaseValue) -> Date? { + /// Returns nil if decoding fails + private func decode(_ dbValue: DatabaseValue) -> Date? { switch self { case .deferredToDate: return Date.fromDatabaseValue(dbValue) diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index cdf3d085b..35011d45f 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -113,7 +113,7 @@ public protocol FetchableRecord { /// /// - throws: An error is thrown if the record can't be decoded from the /// database row. - init(row: Row) throws + init(row: some RowProtocol) throws // MARK: - Customizing the Format of Database Columns @@ -260,6 +260,13 @@ extension FetchableRecord { } } +extension FetchableRecord { + #warning("TODO: document") + public init(row columnsWithValues: KeyValuePairs) throws { + try self.init(row: Row(columnsWithValues: columnsWithValues)) + } +} + extension FetchableRecord { // MARK: Fetching From Prepared Statement diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 47f37d742..2426f3393 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -41,8 +41,8 @@ open class Record { public init() { } /// Creates a Record from a row. - public required init(row: Row) throws { - if row.isFetched { + public required init(row: some RowProtocol) throws { + if row._isFetched { // Take care of the hasDatabaseChanges flag. // // Row may be a reused row which will turn invalid as soon as the diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index c5adfae20..3fec43d9f 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -326,6 +326,7 @@ 56F89E1C2A585E0D002FE2AA /* SQLTableGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E192A585E0D002FE2AA /* SQLTableGenerator.swift */; }; 56FA0C3728B1F2EB00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C3428B1F2EB00B2DFF7 /* MutablePersistableRecord+Upsert.swift */; }; 56FA0C4128B20ADB00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C4028B20ADB00B2DFF7 /* PersistableRecord+Upsert.swift */; }; + 56FA60322BB96ABF0085DEB7 /* RowProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA60302BB96ABF0085DEB7 /* RowProtocol.swift */; }; 56FBFED62210731100945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED52210731000945324 /* SQLRequest.swift */; }; 56FEB8FE248403270081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */; }; 56FEE7FE1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; @@ -853,6 +854,7 @@ 56F89E192A585E0D002FE2AA /* SQLTableGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLTableGenerator.swift; sourceTree = ""; }; 56FA0C3428B1F2EB00B2DFF7 /* MutablePersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Upsert.swift"; sourceTree = ""; }; 56FA0C4028B20ADB00B2DFF7 /* PersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Upsert.swift"; sourceTree = ""; }; + 56FA60302BB96ABF0085DEB7 /* RowProtocol.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowProtocol.swift; sourceTree = ""; }; 56FBFED52210731000945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; 56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.swift; sourceTree = ""; }; @@ -1595,6 +1597,7 @@ 56A238761B9C75030082EB20 /* Row.swift */, 567404871CEF84C8003ED5CC /* RowAdapter.swift */, 56231E6025CEBF06001DFD2F /* RowDecodingError.swift */, + 56FA60302BB96ABF0085DEB7 /* RowProtocol.swift */, 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */, 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */, 56D3332129C38D7A00430680 /* WALSnapshotTransaction.swift */, @@ -2088,6 +2091,7 @@ 5659F48A1EA8D94E004A4992 /* Utils.swift in Sources */, F3BA807F1CFB2E61003DC1BA /* NSString.swift in Sources */, 56F89DFA2A57EAB9002FE2AA /* ColumnDefinition.swift in Sources */, + 56FA60322BB96ABF0085DEB7 /* RowProtocol.swift in Sources */, 56F89E1C2A585E0D002FE2AA /* SQLTableGenerator.swift in Sources */, 5603CEC52AC862F800CF097D /* SQLJSONExpressible.swift in Sources */, 560233D127243A9200529DF3 /* SharedValueObservation.swift in Sources */, diff --git a/README.md b/README.md index 92a73a374..25547bdda 100644 --- a/README.md +++ b/README.md @@ -1121,7 +1121,7 @@ struct Link: FetchableRecord { var url: URL var isVerified: Bool - init(row: Row) { + init(row: some RowProtocol) { url = row["url"] isVerified = row["verified"] } @@ -1876,7 +1876,7 @@ Details follow: ```swift protocol FetchableRecord { /// Row initializer - init(row: Row) throws + init(row: some RowProtocol) throws } ``` @@ -1890,7 +1890,7 @@ struct Place { } extension Place : FetchableRecord { - init(row: Row) { + init(row: some RowProtocol) { id = row["id"] title = row["title"] coordinate = CLLocationCoordinate2D( @@ -1908,7 +1908,7 @@ extension Place : FetchableRecord { case id, title, latitude, longitude } - init(row: Row) { + init(row: some RowProtocol) { id = row[Columns.id] title = row[Columns.title] coordinate = CLLocationCoordinate2D( @@ -2839,7 +2839,7 @@ class Place: Record { } /// Creates a record from a database row - required init(row: Row) throws { + required init(row: some RowProtocol) throws { id = row[Columns.id] title = row[Columns.title] isFavorite = row[Columns.favorite] @@ -3210,7 +3210,7 @@ extension Place: TableRecord { // Fetching methods extension Place: FetchableRecord { /// Creates a record from a database row - init(row: Row) { + init(row: some RowProtocol) { id = row[Columns.id] title = row[Columns.title] isFavorite = row[Columns.isFavorite] @@ -3291,7 +3291,7 @@ extension Place: TableRecord { // Fetching methods extension Place: FetchableRecord { /// Creates a record from a database row - init(row: Row) { + init(row: some RowProtocol) { // For high performance, use numeric indexes that match the // order of Place.databaseSelection id = row[0] @@ -3343,7 +3343,7 @@ class Place: Record { } /// Creates a record from a database row - required init(row: Row) throws { + required init(row: some RowProtocol) throws { id = row[Columns.id] title = row[Columns.title] isFavorite = row[Columns.isFavorite] diff --git a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift index e288e6c0c..dfb8a3075 100644 --- a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift @@ -20,7 +20,7 @@ private struct PlayerWithRequiredTeam: FetchableRecord { var player: Player var team: Team - init(row: Row) throws { + init(row: some RowProtocol) throws { player = try Player(row: row) team = row[Player.teamScope] } @@ -30,7 +30,7 @@ private struct PlayerWithOptionalTeam: FetchableRecord { var player: Player var team: Team? - init(row: Row) throws { + init(row: some RowProtocol) throws { player = try Player(row: row) team = row[Player.teamScope] } @@ -40,7 +40,7 @@ private struct PlayerWithTeamName: FetchableRecord { var player: Player var teamName: String? - init(row: Row) throws { + init(row: some RowProtocol) throws { player = try Player(row: row) teamName = row["teamName"] } diff --git a/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift b/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift index d0a49bfff..e6c72a8be 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift @@ -25,7 +25,7 @@ private struct AWithRequiredC: FetchableRecord { var a: A var c: C - init(row: Row) throws { + init(row: some RowProtocol) throws { a = try A(row: row) c = row["c"] } @@ -35,7 +35,7 @@ private struct AWithOptionalC: FetchableRecord { var a: A var c: C? - init(row: Row) throws { + init(row: some RowProtocol) throws { a = try A(row: row) c = row["c"] } @@ -46,7 +46,7 @@ private struct AWithRequiredBAndOptionalC: FetchableRecord { var b: B var c: C? - init(row: Row) throws { + init(row: some RowProtocol) throws { a = try A(row: row) b = row["b"] c = row["c"] @@ -57,7 +57,7 @@ private struct AWithCName: FetchableRecord { var a: A var cName: String? - init(row: Row) throws { + init(row: some RowProtocol) throws { a = try A(row: row) cName = row["cName"] } @@ -68,7 +68,7 @@ private struct AWithRequiredBNameAndOptionalCName: FetchableRecord { var bName: String var cName: String? - init(row: Row) throws { + init(row: some RowProtocol) throws { a = try A(row: row) bName = row["bName"] cName = row["cName"] diff --git a/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift b/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift index 6b597fe7b..e015e21e0 100644 --- a/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift @@ -5,7 +5,7 @@ private struct A: TableRecord, FetchableRecord, Equatable { var cola1: Int64 var cola2: String - init(row: Row) { + init(row: some RowProtocol) { cola1 = row["cola1"] cola2 = row["cola2"] } @@ -15,7 +15,7 @@ private struct B: TableRecord, FetchableRecord, Hashable { var colb2: Int64? var colb3: String - init(row: Row) { + init(row: some RowProtocol) { colb1 = row["colb1"] colb2 = row["colb2"] colb3 = row["colb3"] @@ -25,7 +25,7 @@ private struct C: TableRecord, FetchableRecord, Equatable { var colc1: Int64 var colc2: Int64 - init(row: Row) { + init(row: some RowProtocol) { colc1 = row["colc1"] colc2 = row["colc2"] } @@ -35,7 +35,7 @@ private struct D: TableRecord, FetchableRecord, Equatable { var cold2: Int64? var cold3: String - init(row: Row) { + init(row: some RowProtocol) { cold1 = row["cold1"] cold2 = row["cold2"] cold3 = row["cold3"] @@ -123,7 +123,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.bs = bs } - init(row: Row) { + init(row: some RowProtocol) { self.init(a: A(row: row), bs: row["bs"]) } } @@ -131,7 +131,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: [ @@ -152,7 +152,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: [ B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), @@ -172,7 +172,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.bs = bs } - init(row: Row) { + init(row: some RowProtocol) { self.init(a: A(row: row), bs: row["bs"]) } } @@ -180,7 +180,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: [ @@ -201,7 +201,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: [ B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), @@ -238,7 +238,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.bs2 = bs2 } - init(row: Row) { + init(row: some RowProtocol) { self.init(a: A(row: row), bs1: row["bs1"], bs2: row["bs2"]) } } @@ -246,7 +246,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs1: [ @@ -267,7 +267,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs1: [ B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), @@ -304,7 +304,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.ds = ds } - init(row: Row) { + init(row: some RowProtocol) { self.init(c: C(row: row), ds: row["ds"]) } } @@ -316,7 +316,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.cs = cs } - init(row: Row) { + init(row: some RowProtocol) { self.init(a: A(row: row), cs: row["cs"]) } } @@ -324,7 +324,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [ @@ -358,7 +358,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [ Record.CInfo( @@ -392,7 +392,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.ds = ds } - init(row: Row) { + init(row: some RowProtocol) { self.init(c: C(row: row), ds: row["ds"]) } } @@ -404,7 +404,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.cs = cs } - init(row: Row) { + init(row: some RowProtocol) { self.init(a: A(row: row), cs: row["cs"]) } } @@ -412,7 +412,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: []), @@ -428,7 +428,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [])) } @@ -482,7 +482,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.ds2 = ds2 } - init(row: Row) { + init(row: some RowProtocol) { self.init(c: C(row: row), ds1: row["ds1"], ds2: row["ds2"]) } } @@ -496,7 +496,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.cs2 = cs2 } - init(row: Row) { + init(row: some RowProtocol) { self.init(a: A(row: row), cs1: row["cs1"], cs2: row["cs2"]) } } @@ -504,7 +504,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs1: [], @@ -550,7 +550,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs1: [], cs2: [ @@ -590,7 +590,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.d = d } - init(row: Row) { + init(row: some RowProtocol) { self.init(c: C(row: row), d: row["d"]) } } @@ -602,7 +602,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.cs = cs } - init(row: Row) { + init(row: some RowProtocol) { self.init(a: A(row: row), cs: row["cs"]) } } @@ -610,7 +610,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [ @@ -640,7 +640,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [ Record.CInfo( @@ -672,7 +672,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.d = d } - init(row: Row) { + init(row: some RowProtocol) { self.init(c: C(row: row), d: row["d"]) } } @@ -684,7 +684,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.cs = cs } - init(row: Row) { + init(row: some RowProtocol) { self.init(a: A(row: row), cs: row["cs"]) } } @@ -692,7 +692,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: []), @@ -708,7 +708,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [])) } @@ -762,7 +762,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.d2 = d2 } - init(row: Row) { + init(row: some RowProtocol) { self.init(c: C(row: row), d1: row["d1"], d2: row["d2"]) } } @@ -776,7 +776,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.cs2 = cs2 } - init(row: Row) { + init(row: some RowProtocol) { self.init(a: A(row: row), cs1: row["cs1"], cs2: row["cs2"]) } } @@ -784,7 +784,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs1: [], @@ -818,7 +818,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs1: [], cs2: [ @@ -852,7 +852,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.ds = ds } - init(row: Row) { + init(row: some RowProtocol) { self.init(a: A(row: row), ds: row["ds"]) } } @@ -860,7 +860,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), ds: [ @@ -882,7 +882,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), ds: [ D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), @@ -923,7 +923,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.ds3 = ds3 } - init(row: Row) { + init(row: some RowProtocol) { self.init(a: A(row: row), ds1: row["ds1"], ds2: row["ds2"], ds3: row["ds3"]) } } @@ -931,7 +931,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), ds1: [], @@ -958,7 +958,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), ds1: [], ds2: [ @@ -996,7 +996,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.cs = cs } - init(row: Row) { + init(row: some RowProtocol) { self.init(a: A(row: row), cs: row["cs"]) } } @@ -1008,7 +1008,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.a = a } - init(row: Row) { + init(row: some RowProtocol) { self.init(b: B(row: row), a: row["a"]) } } @@ -1016,7 +1016,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), a: Record.AInfo( @@ -1048,7 +1048,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), a: Record.AInfo( a: A(row: ["cola1": 1, "cola2": "a1"]), @@ -1071,7 +1071,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.cs = cs } - init(row: Row) { + init(row: some RowProtocol) { self.init(b: B(row: row), a: row["a"], cs: row["cs"]) } } @@ -1079,7 +1079,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), a: A(row: ["cola1": 1, "cola2": "a1"]), @@ -1109,7 +1109,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [ @@ -1164,7 +1164,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.cs2 = cs2 } - init(row: Row) { + init(row: some RowProtocol) { self.init(a: A(row: row), cs1: row["cs1"], cs2: row["cs2"]) } } @@ -1178,7 +1178,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.a2 = a2 } - init(row: Row) { + init(row: some RowProtocol) { self.init(b: B(row: row), a1: row["a1"], a2: row["a2"]) } } @@ -1186,7 +1186,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), a1: Record.AInfo( @@ -1226,7 +1226,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), a1: Record.AInfo( a: A(row: ["cola1": 1, "cola2": "a1"]), @@ -1264,7 +1264,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { self.bs = bs } - init(row: Row) { + init(row: some RowProtocol) { self.init(d: D(row: row), bs: row["bs"]) } } @@ -1272,7 +1272,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchAll do { let records = try Record.fetchAll(db, request) - XCTAssertEqual(records, [ + try XCTAssertEqual(records, [ Record( d: D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), bs: [ @@ -1303,7 +1303,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { // Record.fetchOne do { let record = try Record.fetchOne(db, request)! - XCTAssertEqual(record, Record( + try XCTAssertEqual(record, Record( d: D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), bs: [ B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), diff --git a/Tests/GRDBTests/AssociationRowScopeSearchTests.swift b/Tests/GRDBTests/AssociationRowScopeSearchTests.swift index b8e79922b..13e7d9697 100644 --- a/Tests/GRDBTests/AssociationRowScopeSearchTests.swift +++ b/Tests/GRDBTests/AssociationRowScopeSearchTests.swift @@ -97,7 +97,7 @@ class AssociationRowScopeSearchTests: GRDBTestCase { var b: B var c: C var d: D - init(row: Row) throws { + init(row: some RowProtocol) throws { a = try A(row: row) b = row["b"] c = row["c"] @@ -174,7 +174,7 @@ class AssociationRowScopeSearchTests: GRDBTestCase { struct CustomA: FetchableRecord, Decodable { var id: Int64 var custom: Bool? - init(row: Row) { + init(row: some RowProtocol) { id = row["id"] custom = true } @@ -183,7 +183,7 @@ class AssociationRowScopeSearchTests: GRDBTestCase { var id: Int64 var aid: Int64 var custom: Bool? - init(row: Row) { + init(row: some RowProtocol) { id = row["id"] aid = row["aid"] custom = true @@ -194,7 +194,7 @@ class AssociationRowScopeSearchTests: GRDBTestCase { var aid: Int64? var bid: Int64? var custom: Bool? - init(row: Row) { + init(row: some RowProtocol) { id = row["id"] aid = row["aid"] bid = row["bid"] @@ -205,7 +205,7 @@ class AssociationRowScopeSearchTests: GRDBTestCase { var id: Int64 var bid: Int64 var custom: Bool? - init(row: Row) { + init(row: some RowProtocol) { id = row["id"] bid = row["bid"] custom = true diff --git a/Tests/GRDBTests/ColumnExpressionTests.swift b/Tests/GRDBTests/ColumnExpressionTests.swift index b716a0700..3b49d033b 100644 --- a/Tests/GRDBTests/ColumnExpressionTests.swift +++ b/Tests/GRDBTests/ColumnExpressionTests.swift @@ -22,7 +22,7 @@ class ColumnExpressionTests: GRDBTestCase { // Test databaseSelection static let databaseSelection: [any SQLSelectable] = [Columns.id, Columns.name, Columns.score] - init(row: Row) { + init(row: some RowProtocol) { // Test row subscript id = row[Columns.id] name = row[Columns.name] @@ -58,7 +58,7 @@ class ColumnExpressionTests: GRDBTestCase { try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.Columns.id)).databaseRegion(db).description, "player(id,name,score)[1,2,3]") // Test specific column updates - let player = Player(row: ["id": 1, "name": "Arthur", "score": 1000]) + let player = try Player(row: ["id": 1, "name": "Arthur", "score": 1000]) try? player.update(db, columns: [Player.Columns.name, Player.Columns.score]) XCTAssertEqual(lastSQLQuery, "UPDATE \"player\" SET \"name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1") @@ -82,7 +82,7 @@ class ColumnExpressionTests: GRDBTestCase { // Test databaseSelection static let databaseSelection: [any SQLSelectable] = [Columns.id, Columns.name, Columns.score] - init(row: Row) { + init(row: some RowProtocol) { // Test row subscript id = row[Columns.id] name = row[Columns.name] @@ -118,7 +118,7 @@ class ColumnExpressionTests: GRDBTestCase { try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.Columns.id)).databaseRegion(db).description, "player(id,name,score)[1,2,3]") // Test specific column updates - let player = Player(row: ["id": 1, "name": "Arthur", "score": 1000]) + let player = try Player(row: ["id": 1, "name": "Arthur", "score": 1000]) try? player.update(db, columns: [Player.Columns.name, Player.Columns.score]) XCTAssertEqual(lastSQLQuery, "UPDATE \"player\" SET \"name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1") diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index 183fd89ed..351cc3374 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -104,15 +104,15 @@ private class UserPersistableRecord2 : PersistableRecord { // MARK: - FetchableRecord private struct UserFetchableRecord1 : FetchableRecord { - init(row: Row) { } + init(row: some RowProtocol) { } } private class UserFetchableRecord2 : FetchableRecord { - required init(row: Row) { } + required init(row: some RowProtocol) { } } private struct UserFetchableRecord3 : FetchableRecord { - init(row: Row) throws { } + init(row: some RowProtocol) throws { } } // MARK: - StatementColumnConvertible diff --git a/Tests/GRDBTests/CompilationSubClassTests.swift b/Tests/GRDBTests/CompilationSubClassTests.swift index 4dfe564dc..9abd7d15b 100644 --- a/Tests/GRDBTests/CompilationSubClassTests.swift +++ b/Tests/GRDBTests/CompilationSubClassTests.swift @@ -7,7 +7,7 @@ import GRDB private class UserRecord : Record { override init() { super.init() } - required init(row: Row) throws { try super.init(row: row) } + required init(row: some RowProtocol) throws { try super.init(row: row) } override class var databaseTableName: String { super.databaseTableName } override class var persistenceConflictPolicy: PersistenceConflictPolicy { super.persistenceConflictPolicy } override class var databaseSelection: [any SQLSelectable] { super.databaseSelection } diff --git a/Tests/GRDBTests/DatabaseCursorTests.swift b/Tests/GRDBTests/DatabaseCursorTests.swift index d18191488..f1f07ec11 100644 --- a/Tests/GRDBTests/DatabaseCursorTests.swift +++ b/Tests/GRDBTests/DatabaseCursorTests.swift @@ -312,7 +312,7 @@ class DatabaseCursorTests: GRDBTestCase { // Profiling test func testRecordCursorStep() throws { - struct S: FetchableRecord { init(row: Row) { } } + struct S: FetchableRecord { init(row: some RowProtocol) { } } let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let cursor: RecordCursor = try S.fetchCursor(db, sql: profilingSQL) @@ -322,7 +322,7 @@ class DatabaseCursorTests: GRDBTestCase { // Profiling test func testRecordCursorForEach() throws { - struct S: FetchableRecord { init(row: Row) { } } + struct S: FetchableRecord { init(row: some RowProtocol) { } } let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let cursor: RecordCursor = try S.fetchCursor(db, sql: profilingSQL) diff --git a/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift b/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift index a639d83dc..dea090d2a 100644 --- a/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift +++ b/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift @@ -6,7 +6,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { struct Record: FetchableRecord { var name: String - init(row: Row) throws { + init(row: some RowProtocol) throws { name = try row.decode(forKey: "name") } } @@ -122,7 +122,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { struct Record: FetchableRecord { var value: Value - init(row: Row) throws { + init(row: some RowProtocol) throws { value = try row.decode(forKey: "value") } } diff --git a/Tests/GRDBTests/FTS3RecordTests.swift b/Tests/GRDBTests/FTS3RecordTests.swift index b37c08bb5..7a627a7b4 100644 --- a/Tests/GRDBTests/FTS3RecordTests.swift +++ b/Tests/GRDBTests/FTS3RecordTests.swift @@ -9,7 +9,7 @@ private struct Book { } extension Book : FetchableRecord { - init(row: Row) { + init(row: some RowProtocol) { id = row[.rowID] title = row["title"] author = row["author"] diff --git a/Tests/GRDBTests/FTS4RecordTests.swift b/Tests/GRDBTests/FTS4RecordTests.swift index 646c3852e..ef33c10f0 100644 --- a/Tests/GRDBTests/FTS4RecordTests.swift +++ b/Tests/GRDBTests/FTS4RecordTests.swift @@ -9,7 +9,7 @@ private struct Book { } extension Book : FetchableRecord { - init(row: Row) { + init(row: some RowProtocol) { id = row[.rowID] title = row["title"] author = row["author"] diff --git a/Tests/GRDBTests/FTS5RecordTests.swift b/Tests/GRDBTests/FTS5RecordTests.swift index b25b0a013..2e35bb30b 100644 --- a/Tests/GRDBTests/FTS5RecordTests.swift +++ b/Tests/GRDBTests/FTS5RecordTests.swift @@ -10,7 +10,7 @@ private struct Book { } extension Book : FetchableRecord { - init(row: Row) { + init(row: some RowProtocol) { id = row[.rowID] title = row["title"] author = row["author"] diff --git a/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift index 8fd39c92b..a724b8285 100644 --- a/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift @@ -8,7 +8,7 @@ private struct Reader: Hashable { } extension Reader : FetchableRecord { - init(row: Row) { + init(row: some RowProtocol) { id = row["id"] name = row["name"] age = row["age"] @@ -36,7 +36,7 @@ private struct AltReader { } extension AltReader : FetchableRecord { - init(row: Row) { + init(row: some RowProtocol) { id = row["id"] name = row["name"] age = row["age"] diff --git a/Tests/GRDBTests/FetchableRecordDecodableTests.swift b/Tests/GRDBTests/FetchableRecordDecodableTests.swift index d0cf06b46..cd548c823 100644 --- a/Tests/GRDBTests/FetchableRecordDecodableTests.swift +++ b/Tests/GRDBTests/FetchableRecordDecodableTests.swift @@ -39,17 +39,17 @@ extension FetchableRecordDecodableTests { } } - func testCustomFetchableRecord() { + func testCustomFetchableRecord() throws { struct Struct : FetchableRecord, Decodable { let value: String - init(row: Row) { + init(row: some RowProtocol) { value = (row["value"] as String) + " (FetchableRecord)" } } do { - let s = Struct(row: ["value": "foo"]) + let s = try Struct(row: ["value": "foo"]) XCTAssertEqual(s.value, "foo (FetchableRecord)") } } @@ -900,7 +900,7 @@ extension FetchableRecordDecodableTests { "requiredDates": "[128000]", "optionalDates": "[null, 128000]", "optionalDates2": "[128000]", - ]) + ] as Row) XCTAssertEqual(record, Record( requiredId: 1, optionalName: "test1", @@ -916,7 +916,7 @@ extension FetchableRecordDecodableTests { "REQUIREDDATES": "[128000]", "OPTIONALDATES": "[null, 128000]", "OPTIONALDATES2": "[128000]", - ]) + ] as Row) XCTAssertEqual(record, Record( requiredId: 1, optionalName: "test1", @@ -932,7 +932,7 @@ extension FetchableRecordDecodableTests { "requiredDates": "[128000]", "optionalDates": "[null, 128000]", "optionalDates2": nil, - ]) + ] as Row) XCTAssertEqual(record, Record( requiredId: 1, optionalName: nil, @@ -946,7 +946,7 @@ extension FetchableRecordDecodableTests { "requiredId": 1, "requiredDates": "[128000]", "optionalDates": "[null, 128000]", - ]) + ] as Row) XCTAssertEqual(record, Record( requiredId: 1, optionalName: nil, @@ -962,7 +962,7 @@ extension FetchableRecordDecodableTests { "requiredDates": "[128000]", "optionalDates": "[null, 128000]", "optionalDates2": "[128000]", - ]) + ] as Row) XCTFail("Expected error") } catch let RowDecodingError.keyNotFound(.columnName(column), context) { XCTAssertEqual(column, "requiredId") @@ -996,7 +996,7 @@ extension FetchableRecordDecodableTests { "required_dates": "[128000]", "optional_dates": "[null, 128000]", "optional_dates2": "[128000]", - ]) + ] as Row) XCTAssertEqual(record, Record( requiredId: 1, optionalName: "test1", @@ -1012,7 +1012,7 @@ extension FetchableRecordDecodableTests { "REQUIRED_DATES": "[128000]", "OPTIONAL_DATES": "[null, 128000]", "OPTIONAL_DATES2": "[128000]", - ]) + ] as Row) XCTAssertEqual(record, Record( requiredId: 1, optionalName: "test1", @@ -1028,7 +1028,7 @@ extension FetchableRecordDecodableTests { "required_dates": "[128000]", "optional_dates": "[null, 128000]", "optional_dates2": nil, - ]) + ] as Row) XCTAssertEqual(record, Record( requiredId: 1, optionalName: nil, @@ -1042,7 +1042,7 @@ extension FetchableRecordDecodableTests { "required_id": 1, "required_dates": "[128000]", "optional_dates": "[null, 128000]", - ]) + ] as Row) XCTAssertEqual(record, Record( requiredId: 1, optionalName: nil, @@ -1059,7 +1059,7 @@ extension FetchableRecordDecodableTests { "requiredDates": "[128000]", "optionalDates": "[null, 128000]", "optionalDates2": "[128000]", - ]) + ] as Row) XCTAssertEqual(record, Record( requiredId: 1, optionalName: "test1", @@ -1075,7 +1075,7 @@ extension FetchableRecordDecodableTests { "required_dates": "[128000]", "optional_dates": "[null, 128000]", "optional_dates2": "[128000]", - ]) + ] as Row) XCTFail("Expected error") } catch let RowDecodingError.keyNotFound(.columnName(column), context) { XCTAssertEqual(column, "requiredId") @@ -1092,7 +1092,7 @@ extension FetchableRecordDecodableTests { "required_dates": "[128000]", "optional_dates": "[null, 128000]", "optional_dates2": "[128000]", - ]) + ] as Row) XCTFail("Expected error") } catch let RowDecodingError.keyNotFound(.columnName(column), context) { XCTAssertEqual(column, "requiredID") @@ -1130,7 +1130,7 @@ extension FetchableRecordDecodableTests { "_requiredDates": "[128000]", "_optionalDates": "[null, 128000]", "_optionalDates2": "[128000]", - ]) + ] as Row) XCTAssertEqual(record, Record( requiredId: 1, optionalName: "test1", @@ -1146,7 +1146,7 @@ extension FetchableRecordDecodableTests { "_requiredDates": "[128000]", "_optionalDates": "[null, 128000]", "_optionalDates2": nil, - ]) + ] as Row) XCTAssertEqual(record, Record( requiredId: 1, optionalName: nil, @@ -1160,7 +1160,7 @@ extension FetchableRecordDecodableTests { "_requiredId": 1, "_requiredDates": "[128000]", "_optionalDates": "[null, 128000]", - ]) + ] as Row) XCTAssertEqual(record, Record( requiredId: 1, optionalName: nil, @@ -1176,7 +1176,7 @@ extension FetchableRecordDecodableTests { "_requiredDates": "[128000]", "_optionalDates": "[null, 128000]", "_optionalDates2": "[128000]", - ]) + ] as Row) XCTFail("Expected error") } catch let RowDecodingError.keyNotFound(.columnName(column), context) { XCTAssertEqual(column, "requiredId") @@ -1493,7 +1493,7 @@ extension FetchableRecordDecodableTests { // all optionals decode missing keys are nil. This is because GRDB // records accept rows with missing columns, and b and c may want to // decode columns. - _ = try FetchableRecordDecoder().decode(Composed.self, from: [:]) + _ = try FetchableRecordDecoder().decode(Composed.self, from: Row()) } // This is a regression test for https://github.com/groue/GRDB.swift/issues/664 @@ -1505,7 +1505,7 @@ extension FetchableRecordDecodableTests { var b: B } do { - _ = try FetchableRecordDecoder().decode(Composed.self, from: [:]) + _ = try FetchableRecordDecoder().decode(Composed.self, from: Row()) XCTFail("Expected error") } catch DecodingError.keyNotFound { // a or b can not be decoded because only one key is allowed to be missing @@ -1631,7 +1631,7 @@ extension FetchableRecordDecodableTests { self.isFetched = false } - init(row: Row) throws { + init(row: some RowProtocol) throws { self = try FetchableRecordDecoder().decode(Player.self, from: row) self.isFetched = true } diff --git a/Tests/GRDBTests/FetchableRecordTests.swift b/Tests/GRDBTests/FetchableRecordTests.swift index 4da399849..31fdd0f52 100644 --- a/Tests/GRDBTests/FetchableRecordTests.swift +++ b/Tests/GRDBTests/FetchableRecordTests.swift @@ -7,7 +7,7 @@ private struct Fetched: Hashable{ } extension Fetched : FetchableRecord { - init(row: Row) { + init(row: some RowProtocol) { firstName = row["firstName"] lastName = row["lastName"] } diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 2df63301a..85dd7cb5b 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -181,7 +181,7 @@ class GRDBTestCase: XCTestCase { line: UInt = #line) throws { - let request: SQLRequest = "SELECT \(expression)" + let request = SQLRequest(literal: "SELECT \(expression)") try assertEqualSQL(db, request, "SELECT \(sql)", file: file, line: line) } diff --git a/Tests/GRDBTests/JoinSupportTests.swift b/Tests/GRDBTests/JoinSupportTests.swift index 4b703bd71..acd2f47d4 100644 --- a/Tests/GRDBTests/JoinSupportTests.swift +++ b/Tests/GRDBTests/JoinSupportTests.swift @@ -84,7 +84,7 @@ private struct FlatModel: FetchableRecord { var t3: T3? var t5count: Int - init(row: Row) { + init(row: some RowProtocol) { self.t1 = row[Scopes.t1] self.t2Left = row[Scopes.t2Left] self.t2Right = row[Scopes.t2Right] diff --git a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift index f530149f8..f11f8e1b6 100644 --- a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift @@ -288,7 +288,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { case id, firstName, lastName } - required init(row: Row) throws { + required init(row: some RowProtocol) throws { id = row[Columns.id] firstName = row[Columns.firstName] lastName = row[Columns.lastName] diff --git a/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift index 86a610e17..27be426d1 100644 --- a/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift @@ -13,7 +13,7 @@ private class Reader : Record { super.init() } - required init(row: Row) throws { + required init(row: some RowProtocol) throws { self.id = row["id"] self.name = row["name"] self.age = row["age"] diff --git a/Tests/GRDBTests/RecordEditedTests.swift b/Tests/GRDBTests/RecordEditedTests.swift index 4e7416cd4..3115e4c59 100644 --- a/Tests/GRDBTests/RecordEditedTests.swift +++ b/Tests/GRDBTests/RecordEditedTests.swift @@ -31,7 +31,7 @@ private class Person : Record { "persons" } - required init(row: Row) throws { + required init(row: some RowProtocol) throws { id = row["id"] age = row["age"] name = row["name"] @@ -69,7 +69,7 @@ private class IntegerPropertyOnRealAffinityColumn : Record { // Record - required init(row: Row) throws { + required init(row: some RowProtocol) throws { value = row["value"] try super.init(row: row) } @@ -99,7 +99,7 @@ private class PersonWithModifiedCaseColumns: Record { "persons" } - required init(row: Row) throws { + required init(row: some RowProtocol) throws { id = row["ID"] age = row["AGE"] name = row["NAME"] diff --git a/Tests/GRDBTests/RecordInitializersTests.swift b/Tests/GRDBTests/RecordInitializersTests.swift index 73128fa88..f8267b007 100644 --- a/Tests/GRDBTests/RecordInitializersTests.swift +++ b/Tests/GRDBTests/RecordInitializersTests.swift @@ -15,11 +15,11 @@ class EmptyRecordWithoutInitializer : Record { // let name: String? // } -// What happens with a mutable property, and init(row: Row)? +// What happens with a mutable property, and init(row: some RowProtocol)? class RecordWithMutablePropertyAndRowInitializer : Record { var name: String? - required init(row: Row) throws { + required init(row: some RowProtocol) throws { try super.init(row: row) // super.init(row: row) is required self.name = "toto" // property can be set before or after super.init } @@ -34,7 +34,7 @@ class RecordWithMutablePropertyAndEmptyInitializer : Record { self.name = "toto" // property can be set before or after super.init } - required init(row: Row) throws { // init(row) is required + required init(row: some RowProtocol) throws { // init(row) is required try super.init(row: row) // super.init(row: row) is required } } @@ -48,7 +48,7 @@ class RecordWithMutablePropertyAndCustomInitializer : Record { super.init() // super.init() is required } - required init(row: Row) throws { // init(row) is required + required init(row: some RowProtocol) throws { // init(row) is required try super.init(row: row) // super.init(row: row) is required } } @@ -57,7 +57,7 @@ class RecordWithMutablePropertyAndCustomInitializer : Record { class RecordWithImmutableProperty : Record { let initializedFromRow: Bool - required init(row: Row) throws { // An initializer is required, and the minimum is init(row) + required init(row: some RowProtocol) throws { // An initializer is required, and the minimum is init(row) initializedFromRow = true // property must be set before super.init(row: row) try super.init(row: row) // super.init(row: row) is required } @@ -72,7 +72,7 @@ class RecordWithPedigree : Record { super.init() // super.init() is required } - required init(row: Row) throws { // An initializer is required, and the minimum is init(row) + required init(row: some RowProtocol) throws { // An initializer is required, and the minimum is init(row) initializedFromRow = true // property must be set before super.init(row: row) try super.init(row: row) // super.init(row: row) is required } @@ -87,7 +87,7 @@ class RecordWithImmutablePropertyAndCustomInitializer : Record { super.init() // super.init() is required } - required init(row: Row) throws { // An initializer is required, and the minimum is init(row) + required init(row: some RowProtocol) throws { // An initializer is required, and the minimum is init(row) initializedFromRow = true // property must be set before super.init(row: row) try super.init(row: row) // super.init(row: row) is required } @@ -97,7 +97,7 @@ class RecordInitializersTests : GRDBTestCase { func testFetchedRecordAreInitializedFromRow() throws { - // Here we test that Record.init(row: Row) can be overridden independently from Record.init(). + // Here we test that Record.init(row: row) can be overridden independently from Record.init(). // People must be able to perform some initialization work when fetching records from the database. XCTAssertFalse(RecordWithPedigree().initializedFromRow) diff --git a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift index 0c48e4788..59d9ce28f 100644 --- a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift @@ -23,7 +23,7 @@ private class MinimalNonOptionalPrimaryKeySingle: Record, Hashable { "minimalSingles" } - required init(row: Row) throws { + required init(row: some RowProtocol) throws { id = row["id"] try super.init(row: row) } diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index b6b2c9d22..6d95d42c6 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -22,7 +22,7 @@ class MinimalRowID : Record, Hashable { "minimalRowIDs" } - required init(row: Row) throws { + required init(row: some RowProtocol) throws { id = row["id"] try super.init(row: row) } diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift index d5c150b19..8024ed80a 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift @@ -21,7 +21,7 @@ class MinimalSingle: Record, Hashable { "minimalSingles" } - required init(row: Row) throws { + required init(row: some RowProtocol) throws { UUID = row["UUID"] try super.init(row: row) } diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index 30fd372ac..1d8aae2d7 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -35,7 +35,7 @@ private class Person : Record, Hashable { "persons" } - required init(row: Row) throws { + required init(row: some RowProtocol) throws { id = row[.rowID] age = row["age"] name = row["name"] diff --git a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift index 885cee2a1..4c44a92e7 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift @@ -30,7 +30,7 @@ private class Citizenship : Record, Hashable { "citizenships" } - required init(row: Row) throws { + required init(row: some RowProtocol) throws { personName = row["personName"] countryName = row["countryName"] native = row["native"] diff --git a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift index 9330925eb..b6b201de6 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift @@ -28,7 +28,7 @@ private class Item : Record, Hashable { "items" } - required init(row: Row) throws { + required init(row: some RowProtocol) throws { name = row["name"] email = row["email"] try super.init(row: row) diff --git a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift index a1e4c9b76..51342c236 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift @@ -32,7 +32,7 @@ private class Person : Record, Hashable { "persons" } - required init(row: Row) throws { + required init(row: some RowProtocol) throws { id = row["id"] age = row["age"] name = row["name"] diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift index dd5c772f9..1e2a4ba7b 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift @@ -26,7 +26,7 @@ class Pet : Record, Hashable { "pets" } - required init(row: Row) throws { + required init(row: some RowProtocol) throws { UUID = row["UUID"] name = row["name"] try super.init(row: row) diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift index af701890e..f97b9e1b4 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift @@ -25,7 +25,7 @@ class Email : Record, Hashable { "emails" } - required init(row: Row) throws { + required init(row: some RowProtocol) throws { email = row["email"] label = row["label"] try super.init(row: row) diff --git a/Tests/GRDBTests/RecordSubClassTests.swift b/Tests/GRDBTests/RecordSubClassTests.swift index 4942773ec..91c4c0d43 100644 --- a/Tests/GRDBTests/RecordSubClassTests.swift +++ b/Tests/GRDBTests/RecordSubClassTests.swift @@ -31,7 +31,7 @@ private class Person : Record { "persons" } - required init(row: Row) throws { + required init(row: some RowProtocol) throws { id = row["id"] age = row["age"] name = row["name"] @@ -64,7 +64,7 @@ private class MinimalPersonWithOverrides : Person { // Record - required init(row: Row) throws { + required init(row: some RowProtocol) throws { extra = row["extra"] try super.init(row: row) } @@ -85,7 +85,7 @@ private class PersonWithOverrides : Person { // Record - required init(row: Row) throws { + required init(row: some RowProtocol) throws { extra = row["extra"] try super.init(row: row) } diff --git a/Tests/GRDBTests/RecordUniqueIndexTests.swift b/Tests/GRDBTests/RecordUniqueIndexTests.swift index 8d42ecec9..2a65b4233 100644 --- a/Tests/GRDBTests/RecordUniqueIndexTests.swift +++ b/Tests/GRDBTests/RecordUniqueIndexTests.swift @@ -3,7 +3,7 @@ import XCTest private struct Person : FetchableRecord, TableRecord { static let databaseTableName = "persons" - init(row: Row) { + init(row: some RowProtocol) { } } diff --git a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift index 74a5b092c..43424acd8 100644 --- a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift +++ b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift @@ -23,7 +23,7 @@ class BadlyMangledStuff : Record { "stuffs" } - required init(row: Row) throws { + required init(row: some RowProtocol) throws { // Here user may peek fancy column names that match his SQL queries. // However this is not the way to do it (see testBadlyMangledStuff()). id = row["mangled_id"] diff --git a/Tests/GRDBTests/TableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift index 8c5d11e6e..a52550613 100644 --- a/Tests/GRDBTests/TableRecordDeleteTests.swift +++ b/Tests/GRDBTests/TableRecordDeleteTests.swift @@ -439,7 +439,7 @@ class TableRecordDeleteTests: GRDBTestCase { struct Player: MutablePersistableRecord, FetchableRecord { static let team = belongsTo(Team.self) func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } - init(row: Row) { preconditionFailure("should not be called") } + init(row: some RowProtocol) { preconditionFailure("should not be called") } } struct Team: MutablePersistableRecord, FetchableRecord { @@ -447,7 +447,7 @@ class TableRecordDeleteTests: GRDBTestCase { static let databaseSelection: [any SQLSelectable] = [Column("id"), Column("name")] static let players = hasMany(Player.self) func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } - init(row: Row) { preconditionFailure("should not be called") } + init(row: some RowProtocol) { preconditionFailure("should not be called") } } try db.create(table: "team") { t in @@ -605,11 +605,11 @@ class TableRecordDeleteTests: GRDBTestCase { try makeDatabaseQueue().inDatabase { db in struct Player: MutablePersistableRecord, FetchableRecord { func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } - init(row: Row) { preconditionFailure("should not be called") } + init(row: some RowProtocol) { preconditionFailure("should not be called") } } struct Passport: MutablePersistableRecord, FetchableRecord { func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } - init(row: Row) { preconditionFailure("should not be called") } + init(row: some RowProtocol) { preconditionFailure("should not be called") } } try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") diff --git a/Tests/GRDBTests/ValueObservationRecordTests.swift b/Tests/GRDBTests/ValueObservationRecordTests.swift index 9f52d61d6..41ff91395 100644 --- a/Tests/GRDBTests/ValueObservationRecordTests.swift +++ b/Tests/GRDBTests/ValueObservationRecordTests.swift @@ -8,7 +8,7 @@ private struct Player: Equatable { extension Player: TableRecord, FetchableRecord { static let databaseTableName = "t" - init(row: Row) { + init(row: some RowProtocol) { self.init(id: row["id"], name: row["name"]) } } diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index d5dbf62f8..b03a9888f 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -83,7 +83,7 @@ class ValueObservationTests: GRDBTestCase { } // Test that view v is included in the request region - let request = SQLRequest(sql: "SELECT name FROM v ORDER BY id") + let request = SQLRequest(sql: "SELECT name FROM v ORDER BY id") try dbQueue.inDatabase { db in let region = try request.databaseRegion(db) XCTAssertEqual(region.description, "t(id,name),v(id,name)") diff --git a/Tests/Performance/GRDBPerformance/FetchRecordOptimizedTests.swift b/Tests/Performance/GRDBPerformance/FetchRecordOptimizedTests.swift index 3195e3003..dc1ec7ad2 100644 --- a/Tests/Performance/GRDBPerformance/FetchRecordOptimizedTests.swift +++ b/Tests/Performance/GRDBPerformance/FetchRecordOptimizedTests.swift @@ -16,7 +16,7 @@ private struct Item: Codable, FetchableRecord, PersistableRecord { var i8: Int var i9: Int - init(row: Row) { + init(row: some RowProtocol) { i0 = row[0] i1 = row[1] i2 = row[2] diff --git a/Tests/Performance/GRDBPerformance/InsertRecordClassTests.swift b/Tests/Performance/GRDBPerformance/InsertRecordClassTests.swift index f58755727..cb9b34edb 100644 --- a/Tests/Performance/GRDBPerformance/InsertRecordClassTests.swift +++ b/Tests/Performance/GRDBPerformance/InsertRecordClassTests.swift @@ -41,7 +41,7 @@ class InsertRecordClassTests: XCTestCase { super.init() } - required init(row: Row) { + required init(row: some RowProtocol) { fatalError("init(row:) has not been implemented") }