diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index a92e1b12f..24d0bc600 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -131,7 +131,9 @@ extension Row { // MARK: - Extracting Values - /// Returns true if and only if one column contains a non-null value. + /// Returns true if and only if one column contains a non-null value, or if + /// the row was fetched along with a row adapter that defines a scoped row + /// that contains a non-null value. public var containsNonNullValue: Bool { // In case of trouble, see 0149a0265010ef7bb7b41815f91315c4b8dbd4fd if let sqliteStatement = sqliteStatement { // fast path @@ -143,6 +145,11 @@ extension Row { if !hasNull(atIndex: i) { return true } } } + + for name in scopeNames where scoped(on: name)!.containsNonNullValue { + return true + } + return false } @@ -509,6 +516,10 @@ extension Row { // MARK: - Scopes + var scopeNames: Set { + return impl.scopeNames + } + /// Returns a scoped row, if the row was fetched along with a row adapter /// that defines this scope. /// @@ -535,6 +546,12 @@ extension Row { public func scoped(on name: String) -> Row? { return impl.scoped(on: name) } + + /// Returns a copy of the row, without any scoped row (if the row was fetched + /// with a row adapter that defines scopes). + public var unscoped: Row { + return Row(impl: ArrayRowImpl(columns: map { ($0, $1) })) + } } /// A cursor of database rows. For example: diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index af802b226..4b329eea0 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -1,5 +1,42 @@ import Foundation +/// Returns an array of row adapters that split a row according to the input +/// number of columns. +/// +/// For example: +/// +/// let sql = "SELECT 1, 2, 3, 4, 5, 6, 7, 8" +/// // < >< >< >< > +/// let adapters = splittingRowAdapters([1, 2, 3]) +/// let adapter = ScopeAdapter([ +/// "a": adapters[0], +/// "b": adapters[1], +/// "c": adapters[2], +/// "d": adapters[3]]) +/// let row = try Row.fetchOne(db, sql, adapter: adapter) +/// row.scoped(on: "a") // [1] +/// row.scoped(on: "b") // [2, 3] +/// row.scoped(on: "c") // [4, 5, 6] +/// row.scoped(on: "d") // [7, 8] +public func splittingRowAdapters(columnCounts: [Int]) -> [RowAdapter] { + guard !columnCounts.isEmpty else { + return [SuffixRowAdapter(fromIndex: 0)] + } + + // [2, 4] -> [0, 2, 6] + let columnIndexes = columnCounts.reduce(into: [0]) { (acc, count) in + acc.append(acc.last! + count) + } + + // [0, 2, 6] -> [(0..<2), (2..<6)] + let rangeAdapters = zip(columnIndexes, columnIndexes.suffix(from: 1)) + .map { RangeRowAdapter($0..<$1) } + + let suffixAdapter = SuffixRowAdapter(fromIndex: columnIndexes.last!) + + return rangeAdapters + [suffixAdapter] +} + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// LayoutedColumnMapping is a type that supports the RowAdapter protocol. @@ -209,6 +246,13 @@ extension RowAdapter { } } +/// EmptyAdapter is a row adapter that hides all columns. +struct EmptyAdapter: RowAdapter { + func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { + return LayoutedColumnMapping(layoutColumns: []) + } +} + /// ColumnMapping is a row adapter that maps column names. /// /// let adapter = ColumnMapping(["foo": "bar"]) @@ -342,6 +386,16 @@ public struct ScopeAdapter : RowAdapter { self.scopes = scopes } + /// Creates a scoped adapter that hides all columns. Columns can only + /// be accessed through scopes. + /// + /// - parameter scopes: A dictionary that maps scope names to + /// row adapters. + public init(nestedScopes: [String: RowAdapter]) { // TODO: find a better name + self.mainAdapter = EmptyAdapter() + self.scopes = nestedScopes + } + init(mainAdapter: RowAdapter, scopes: [String: RowAdapter]) { self.mainAdapter = mainAdapter self.scopes = scopes diff --git a/GRDB/QueryInterface/SQLExpressible.swift b/GRDB/QueryInterface/SQLExpressible.swift index 1ee8ec614..1991a8a66 100644 --- a/GRDB/QueryInterface/SQLExpressible.swift +++ b/GRDB/QueryInterface/SQLExpressible.swift @@ -95,4 +95,11 @@ extension SQLExpressible where Self: SQLSelectable { public func count(distinct: Bool) -> SQLCount? { return sqlExpression.count(distinct: distinct) } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// :nodoc: + public func columnCount(_ db: Database) throws -> Int { + return 1 + } } diff --git a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift index 1a015822a..b8a8c1ded 100644 --- a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift @@ -74,6 +74,16 @@ extension AllColumns : SQLSelectable { allColumns.qualifier = qualifier return allColumns } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// :nodoc: + public func columnCount(_ db: Database) throws -> Int { + guard let qualifier = qualifier else { + fatalError("Can't compute number of columns without a qualifier") + } + return try db.columnCount(in: qualifier.tableName) + } } @@ -103,4 +113,8 @@ struct SQLAliasedExpression : SQLSelectable { func qualified(by qualifier: SQLTableQualifier) -> SQLAliasedExpression { return SQLAliasedExpression(expression.qualified(by: qualifier), alias: alias) } + + func columnCount(_ db: Database) throws -> Int { + return 1 + } } diff --git a/GRDB/QueryInterface/SQLSelectable.swift b/GRDB/QueryInterface/SQLSelectable.swift index 2e0d1c35d..257269eea 100644 --- a/GRDB/QueryInterface/SQLSelectable.swift +++ b/GRDB/QueryInterface/SQLSelectable.swift @@ -16,6 +16,9 @@ public protocol SQLSelectable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) func count(distinct: Bool) -> SQLCount? + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + func columnCount(_ db: Database) throws -> Int + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) func qualified(by qualifier: SQLTableQualifier) -> Self } @@ -24,7 +27,7 @@ public protocol SQLSelectable { /// /// :nodoc: public class SQLTableQualifier { - private var tableName: String + var tableName: String private var alias: String? init(tableName: String, alias: String?) { diff --git a/GRDB/Record/RowConvertible+Decodable.swift b/GRDB/Record/RowConvertible+Decodable.swift index b1f50659b..c63ae9942 100644 --- a/GRDB/Record/RowConvertible+Decodable.swift +++ b/GRDB/Record/RowConvertible+Decodable.swift @@ -1,19 +1,20 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainerProtocol { - let row: Row + let decoder: RowDecoder - init(row: Row) { - self.row = row + init(decoder: RowDecoder) { + self.decoder = decoder } - /// The path of coding keys taken to get to this point in decoding. - /// A `nil` value indicates an unkeyed container. - var codingPath: [CodingKey] { return [] } + var codingPath: [CodingKey] { return decoder.codingPath } /// All the keys the `Decoder` has for this container. /// /// Different keyed containers from the same `Decoder` may return different keys here; it is possible to encode with multiple key types which are not convertible to one another. This should report all keys present which are convertible to the requested type. var allKeys: [Key] { - return row.columnNames.flatMap { Key(stringValue: $0) } + let row = decoder.row + let columnNames = Set(row.columnNames) + let scopeNames = row.scopeNames + return columnNames.union(scopeNames).flatMap { Key(stringValue: $0) } } /// Returns whether the `Decoder` contains a value associated with the given key. @@ -23,7 +24,8 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer /// - parameter key: The key to search for. /// - returns: Whether the `Decoder` has an entry for the given key. func contains(_ key: Key) -> Bool { - return row.hasColumn(key.stringValue) + let row = decoder.row + return row.hasColumn(key.stringValue) || (row.scoped(on: key.stringValue) != nil) } /// Decodes a null value for the given key. @@ -32,7 +34,8 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer /// - returns: Whether the encountered value was null. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. func decodeNil(forKey key: Key) throws -> Bool { - return row[key.stringValue] == nil + let row = decoder.row + return row[key.stringValue] == nil && (row.scoped(on: key.stringValue) == nil) } /// Decodes a value of the given type for the given key. @@ -43,20 +46,50 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. - func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return row[key.stringValue] } - func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return row[key.stringValue] } - func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return row[key.stringValue] } - func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { return row[key.stringValue] } - func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { return row[key.stringValue] } - func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { return row[key.stringValue] } - func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { return row[key.stringValue] } - func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { return row[key.stringValue] } - func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { return row[key.stringValue] } - func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { return row[key.stringValue] } - func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { return row[key.stringValue] } - func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return row[key.stringValue] } - func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return row[key.stringValue] } - func decode(_ type: String.Type, forKey key: Key) throws -> String { return row[key.stringValue] } + func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return decoder.row[key.stringValue] } + func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return decoder.row[key.stringValue] } + func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return decoder.row[key.stringValue] } + func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { return decoder.row[key.stringValue] } + func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { return decoder.row[key.stringValue] } + func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { return decoder.row[key.stringValue] } + func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { return decoder.row[key.stringValue] } + func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { return decoder.row[key.stringValue] } + func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { return decoder.row[key.stringValue] } + func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { return decoder.row[key.stringValue] } + func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { return decoder.row[key.stringValue] } + func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return decoder.row[key.stringValue] } + func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return decoder.row[key.stringValue] } + func decode(_ type: String.Type, forKey key: Key) throws -> String { return decoder.row[key.stringValue] } + + /// Decodes a value of the given type for the given key, if present. + /// + /// This method returns nil if the container does not have a value + /// associated with key, or if the value is null. The difference between + /// these states can be distinguished with a contains(_:) call. + func decodeIfPresent(_ type: T.Type, forKey key: Key) throws -> T? where T : Decodable { + let row = decoder.row + + // Try column + if row.hasColumn(key.stringValue) { + let dbValue: DatabaseValue = row[key.stringValue] + if let type = T.self as? DatabaseValueConvertible.Type { + // Prefer DatabaseValueConvertible decoding over Decodable. + // This allows decoding Date from String, or DatabaseValue from NULL. + return type.fromDatabaseValue(dbValue) as! T? + } else if dbValue.isNull { + return nil + } else { + return try T(from: RowDecoder(row: row, codingPath: codingPath + [key])) + } + } + + // Fallback on scope + if let scopedRow = row.scoped(on: key.stringValue), scopedRow.containsNonNullValue { + return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key])) + } + + return nil + } /// Decodes a value of the given type for the given key. /// @@ -67,14 +100,27 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable { - let dbValue: DatabaseValue = row[key.stringValue] - if let type = T.self as? DatabaseValueConvertible.Type { - // Prefer DatabaseValueConvertible decoding over Decodable. - // This allows decoding Date from String, or DatabaseValue from NULL. - return type.fromDatabaseValue(dbValue) as! T - } else { - return try T(from: RowDecoder(row: row, codingPath: codingPath + [key])) + let row = decoder.row + + // Try column + if row.hasColumn(key.stringValue) { + let dbValue: DatabaseValue = row[key.stringValue] + if let type = T.self as? DatabaseValueConvertible.Type { + // Prefer DatabaseValueConvertible decoding over Decodable. + // This allows decoding Date from String, or DatabaseValue from NULL. + return type.fromDatabaseValue(dbValue) as! T + } else { + return try T(from: RowDecoder(row: row, codingPath: codingPath + [key])) + } } + + // Fallback on scope + if let scopedRow = row.scoped(on: key.stringValue) { + return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key])) + } + + let path = (codingPath.map { $0.stringValue } + [key.stringValue]).joined(separator: ".") + fatalError("No such column or scope: \(path)") } /// Returns the data stored for the given key as represented in a container keyed by the given key type. @@ -84,7 +130,7 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer /// - returns: A keyed decoding container view into `self`. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not a keyed container. func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer where NestedKey : CodingKey { - fatalError("Not implemented") + fatalError("not implemented") } /// Returns the data stored for the given key as represented in an unkeyed container. @@ -93,7 +139,9 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer /// - returns: An unkeyed decoding container view into `self`. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not an unkeyed container. func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { - fatalError("Not implemented") + throw DecodingError.typeMismatch( + UnkeyedDecodingContainer.self, + DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported")) } /// Returns a `Decoder` instance for decoding `super` from the container associated with the default `super` key. @@ -104,7 +152,7 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the default `super` key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the default `super` key. public func superDecoder() throws -> Decoder { - fatalError("Not implemented") + return decoder } /// Returns a `Decoder` instance for decoding `super` from the container associated with the given key. @@ -114,16 +162,15 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func superDecoder(forKey key: Key) throws -> Decoder { - fatalError("Not implemented") + return decoder } } private struct RowSingleValueDecodingContainer: SingleValueDecodingContainer { let row: Row + var codingPath: [CodingKey] let column: CodingKey - var codingPath: [CodingKey] { return [] } - /// Decodes a null value. /// /// - returns: Whether the encountered value was null. @@ -182,14 +229,7 @@ private struct RowDecoder: Decoder { var userInfo: [CodingUserInfoKey : Any] { return [:] } func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { - // Asked for a keyed type: top level required - guard codingPath.isEmpty else { - throw DecodingError.typeMismatch( - RowDecoder.self, - DecodingError.Context(codingPath: codingPath, debugDescription: "nested decoding is not supported")) - } - - return KeyedDecodingContainer(RowKeyedDecodingContainer(row: row)) + return KeyedDecodingContainer(RowKeyedDecodingContainer(decoder: self)) } func unkeyedContainer() throws -> UnkeyedDecodingContainer { @@ -205,7 +245,7 @@ private struct RowDecoder: Decoder { RowDecoder.self, DecodingError.Context(codingPath: codingPath, debugDescription: "single value decoding requires a coding key")) } - return RowSingleValueDecodingContainer(row: row, column: codingKey) + return RowSingleValueDecodingContainer(row: row, codingPath: codingPath, column: codingKey) } } diff --git a/GRDB/Record/RowConvertible.swift b/GRDB/Record/RowConvertible.swift index a6cf9cff4..d8e9df77a 100644 --- a/GRDB/Record/RowConvertible.swift +++ b/GRDB/Record/RowConvertible.swift @@ -24,7 +24,7 @@ /// RowConvertible is adopted by Record. public protocol RowConvertible { - /// Initializes a record from `row`. + /// Creates a record from `row`. /// /// For performance reasons, the row argument may be reused during the /// iteration of a fetch query. If you want to keep the row for later use, @@ -32,6 +32,20 @@ public protocol RowConvertible { init(row: Row) } +extension RowConvertible { + /// Creates a record from `row`, if and only if the row is not nil, and + /// contains at least one non-null value. + public init?(leftJoinedRow row: Row?) { + guard let row = row else { + return nil + } + guard row.containsNonNullValue else { + return nil + } + self.init(row: row) + } +} + /// A cursor of records. For example: /// /// struct Player : RowConvertible { ... } diff --git a/GRDB/Record/TableMapping.swift b/GRDB/Record/TableMapping.swift index 9c7c74265..250ba39aa 100644 --- a/GRDB/Record/TableMapping.swift +++ b/GRDB/Record/TableMapping.swift @@ -93,5 +93,30 @@ extension TableMapping { .map { $0.resultColumnSQL(&arguments) } .joined(separator: ", ") } + + /// Returns the number of selected columns. + /// + /// For example: + /// + /// struct Player: TableMapping { + /// static let databaseTableName = "players" + /// } + /// + /// try dbQueue.inDatabase { db in + /// try db.create(table: "players") { t in + /// t.column("id", .integer).primaryKey() + /// t.column("name", .text) + /// t.column("score", .integer) + /// } + /// + /// // 3 + /// try Player.numberOfSelectedColumns(db) + /// } + public static func numberOfSelectedColumns(_ db: Database) throws -> Int { + let qualifier = SQLTableQualifier(tableName: databaseTableName, alias: nil) + return try databaseSelection + .map { try $0.qualified(by: qualifier).columnCount(db) } + .reduce(0, +) + } } diff --git a/TODO.md b/TODO.md index a606638ab..0771f2a00 100644 --- a/TODO.md +++ b/TODO.md @@ -28,6 +28,8 @@ GRDB 3.0 - [ ] Not sure: Consider introducing RowDecodable and RowEncodable on top of FetchableRecord and MutablePersistableRecord. This would allow keeping fetching and persistence methods private in some files. - [ ] Drop IteratorCursor, use AnyCursor instead - [ ] Drop TypedRequest, have FetchRequest defaults to Row requests. +- [ ] Rename columnCount -> numberOfColumns +- [ ] Try to remove double Persistable/MutablePersistable protocols: Would non-mutating Record methods help? Not sure diff --git a/Tests/GRDBTests/JoinSupportTests.swift b/Tests/GRDBTests/JoinSupportTests.swift index 74363ac6b..0e311baf7 100644 --- a/Tests/GRDBTests/JoinSupportTests.swift +++ b/Tests/GRDBTests/JoinSupportTests.swift @@ -7,14 +7,114 @@ import XCTest import GRDB #endif +private struct T1: Codable, RowConvertible, TableMapping { + static let databaseTableName = "t1" + var id: Int64 + var name: String +} + +private struct T2: Codable, RowConvertible, TableMapping { + static let databaseTableName = "t2" + var id: Int64 + var t1id: Int64 + var name: String +} + +private struct T3: Codable, RowConvertible, TableMapping { + static let databaseTableName = "t3" + static let databaseSelection: [SQLSelectable] = [Column("t1id"), Column("name")] + var t1id: Int64 + var name: String +} + +private struct T4: Codable, RowConvertible, TableMapping { + static let databaseTableName = "t4" + var t1id: Int64 + var name: String +} + +private struct T5: Codable, RowConvertible, TableMapping { + static let databaseTableName = "t5" + var id: Int64 + var t3id: Int64? + var t4id: Int64? + var name: String +} + +private struct FlatModel: RowConvertible { + var t1: T1 + var t2Left: T2? + var t2Right: T2? + var t3: T3? + var t5count: Int + + init(row: Row) { + self.t1 = T1(row: row.scoped(on: "t1")!) + self.t2Left = T2(leftJoinedRow: row.scoped(on: "t2Left")) + self.t2Right = T2(leftJoinedRow: row.scoped(on: "t2Right")) + self.t3 = T3(leftJoinedRow: row.scoped(on: "t3")) + self.t5count = row.scoped(on: "suffix")!["t5count"] + } +} + +private struct CodableFlatModel: RowConvertible, Codable { + var t1: T1 + var t2Left: T2? + var t2Right: T2? + var t3: T3? + var t5count: Int +} + +private struct CodableNestedModel: RowConvertible, Codable { + struct T2Pair: Codable { + var left: T2? + var right: T2? + } + var t1: T1 + var optionalT2Pair: T2Pair? + var t2Pair: T2Pair + var t3: T3? + var t5count: Int +} + class JoinSupportTests: GRDBTestCase { - func testExample() throws { - let dbQueue = try makeDatabaseQueue() - - // Schema - - try dbQueue.inDatabase { db in + let expectedSQL = """ + SELECT + "t1".*, + "t2Left".*, + "t2Right".*, + "t3"."t1id", "t3"."name", + COUNT(DISTINCT t5.id) AS t5count + FROM t1 + LEFT JOIN t2 t2Left ON t2Left.t1id = t1.id AND t2Left.name = 'left' + LEFT JOIN t2 t2Right ON t2Right.t1id = t1.id AND t2Right.name = 'right' + LEFT JOIN t3 ON t3.t1id = t1.id + LEFT JOIN t4 ON t4.t1id = t1.id + LEFT JOIN t5 ON t5.t3id = t3.t1id OR t5.t4id = t4.t1id + GROUP BY t1.id + ORDER BY t1.id + """ + + let testedSQL = """ + SELECT + \(T1.selectionSQL()), + \(T2.selectionSQL(alias: "t2Left")), + \(T2.selectionSQL(alias: "t2Right")), + \(T3.selectionSQL()), + COUNT(DISTINCT t5.id) AS t5count + FROM t1 + LEFT JOIN t2 t2Left ON t2Left.t1id = t1.id AND t2Left.name = 'left' + LEFT JOIN t2 t2Right ON t2Right.t1id = t1.id AND t2Right.name = 'right' + LEFT JOIN t3 ON t3.t1id = t1.id + LEFT JOIN t4 ON t4.t1id = t1.id + LEFT JOIN t5 ON t5.t3id = t3.t1id OR t5.t4id = t4.t1id + GROUP BY t1.id + ORDER BY t1.id + """ + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in try db.create(table: "t1") { t in t.column("id", .integer).primaryKey() t.column("name", .text).notNull() @@ -47,6 +147,7 @@ class JoinSupportTests: GRDBTestCase { try db.execute(""" INSERT INTO t1 (id, name) VALUES (1, 'A1'); INSERT INTO t1 (id, name) VALUES (2, 'A2'); + INSERT INTO t1 (id, name) VALUES (3, 'A3'); INSERT INTO t2 (id, t1id, name) VALUES (1, 1, 'left'); INSERT INTO t2 (id, t1id, name) VALUES (2, 1, 'right'); INSERT INTO t2 (id, t1id, name) VALUES (3, 2, 'left'); @@ -61,119 +162,283 @@ class JoinSupportTests: GRDBTestCase { INSERT INTO t5 (id, t3id, t4id, name) VALUES (6, NULL, 2, 'F5'); INSERT INTO t5 (id, t3id, t4id, name) VALUES (7, NULL, 2, 'G5'); """) - - // Check sample data with SQL - - do { - let sql = """ - SELECT - t1.*, - t2Left.*, - t2Right.*, - t3.t1id, t3.name, - COUNT(DISTINCT t5.id) AS t5count - FROM t1 - LEFT JOIN t2 t2Left ON t2Left.t1id = t1.id AND t2Left.name = 'left' - LEFT JOIN t2 t2Right ON t2Right.t1id = t1.id AND t2Right.name = 'right' - LEFT JOIN t3 ON t3.t1id = t1.id - LEFT JOIN t4 ON t4.t1id = t1.id - LEFT JOIN t5 ON t5.t3id = t3.t1id OR t5.t4id = t4.t1id - GROUP BY t1.id - ORDER BY t1.id - """ - let rows = try Row.fetchAll(db, sql) - XCTAssertEqual(rows.count, 2) - XCTAssertEqual(rows[0], [ - // t1.* - "id": 1, "name": "A1", - // t2Left.* - "id": 1, "t1id": 1, "name": "left", - // t2Right.* - "id": 2, "t1id": 1, "name": "right", - // t3.* - "t1id": 1, "name": "A3", - // t5count - "t5count": 5]) - XCTAssertEqual(rows[1], [ - // t1.* - "id": 2, "name": "A2", - // t2Left.* - "id": 3, "t1id": 2, "name": "left", - // t2Right.* - "id": nil, "t1id": nil, "name": nil, - // t3.* - "t1id": nil, "name": nil, - // t5count - "t5count": 2]) + } + } + + func testSampleData() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let rows = try Row.fetchAll(db, expectedSQL) + XCTAssertEqual(rows.count, 3) + XCTAssertEqual(rows[0], [ + // t1.* + "id": 1, "name": "A1", + // t2Left.* + "id": 1, "t1id": 1, "name": "left", + // t2Right.* + "id": 2, "t1id": 1, "name": "right", + // t3.* + "t1id": 1, "name": "A3", + // t5count + "t5count": 5]) + XCTAssertEqual(rows[1], [ + // t1.* + "id": 2, "name": "A2", + // t2Left.* + "id": 3, "t1id": 2, "name": "left", + // t2Right.* + "id": nil, "t1id": nil, "name": nil, + // t3.* + "t1id": nil, "name": nil, + // t5count + "t5count": 2]) + XCTAssertEqual(rows[2], [ + // t1.* + "id": 3, "name": "A3", + // t2Left.* + "id": nil, "t1id": nil, "name": nil, + // t2Right.* + "id": nil, "t1id": nil, "name": nil, + // t3.* + "t1id": nil, "name": nil, + // t5count + "t5count": 0]) + } + } + + func testTestedSQL() throws { + XCTAssertEqual(testedSQL, expectedSQL) + } + + func testSplittingRowAdapters() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = SQLRequest(testedSQL).adapted { db in + let adapters = try splittingRowAdapters(columnCounts: [ + T1.numberOfSelectedColumns(db), + T2.numberOfSelectedColumns(db), + T2.numberOfSelectedColumns(db), + T3.numberOfSelectedColumns(db)]) + return ScopeAdapter([ + "t1": adapters[0], + "t2Left": adapters[1], + "t2Right": adapters[2], + "t3": adapters[3], + "suffix": adapters[4]]) } + let rows = try Row.fetchAll(db, request) + XCTAssertEqual(rows.count, 3) - // Records + XCTAssertEqual(rows[0].unscoped, [ + // t1.* + "id": 1, "name": "A1", + // t2Left.* + "id": 1, "t1id": 1, "name": "left", + // t2Right.* + "id": 2, "t1id": 1, "name": "right", + // t3.* + "t1id": 1, "name": "A3", + // t5count + "t5count": 5]) + XCTAssertEqual(rows[0].scoped(on: "t1")!, ["id": 1, "name": "A1"]) + XCTAssertEqual(rows[0].scoped(on: "t2Left")!, ["id": 1, "t1id": 1, "name": "left"]) + XCTAssertEqual(rows[0].scoped(on: "t2Right")!, ["id": 2, "t1id": 1, "name": "right"]) + XCTAssertEqual(rows[0].scoped(on: "t3")!, ["t1id": 1, "name": "A3"]) + XCTAssertEqual(rows[0].scoped(on: "suffix")!, ["t5count": 5]) - struct T1: Codable, RowConvertible, TableMapping { - static let databaseTableName = "t1" - var id: Int64 - var name: String - } - struct T2: Codable, RowConvertible, TableMapping { - static let databaseTableName = "t2" - var id: Int64 - var t1id: Int64 - var name: String - } - struct T3: Codable, RowConvertible, TableMapping { - static let databaseTableName = "t3" - static let databaseSelection: [SQLSelectable] = [Column("t1id"), Column("name")] - var t1id: Int64 - var name: String - } - struct T4: Codable, RowConvertible, TableMapping { - static let databaseTableName = "t4" - var t1id: Int64 - var name: String - } - struct T5: Codable, RowConvertible, TableMapping { - static let databaseTableName = "t5" - var id: Int64 - var t3id: Int64? - var t4id: Int64? - var name: String - } + XCTAssertEqual(rows[1].unscoped, [ + // t1.* + "id": 2, "name": "A2", + // t2Left.* + "id": 3, "t1id": 2, "name": "left", + // t2Right.* + "id": nil, "t1id": nil, "name": nil, + // t3.* + "t1id": nil, "name": nil, + // t5count + "t5count": 2]) + XCTAssertEqual(rows[1].scoped(on: "t1")!, ["id": 2, "name": "A2"]) + XCTAssertEqual(rows[1].scoped(on: "t2Left")!, ["id": 3, "t1id": 2, "name": "left"]) + XCTAssertEqual(rows[1].scoped(on: "t2Right")!, ["id": nil, "t1id": nil, "name": nil]) + XCTAssertEqual(rows[1].scoped(on: "t3")!, ["t1id": nil, "name": nil]) + XCTAssertEqual(rows[1].scoped(on: "suffix")!, ["t5count": 2]) - // Generated SQL + XCTAssertEqual(rows[2].unscoped, [ + // t1.* + "id": 3, "name": "A3", + // t2Left.* + "id": nil, "t1id": nil, "name": nil, + // t2Right.* + "id": nil, "t1id": nil, "name": nil, + // t3.* + "t1id": nil, "name": nil, + // t5count + "t5count": 0]) + XCTAssertEqual(rows[2].scoped(on: "t1")!, ["id": 3, "name": "A3"]) + XCTAssertEqual(rows[2].scoped(on: "t2Left")!, ["id": nil, "t1id": nil, "name": nil]) + XCTAssertEqual(rows[2].scoped(on: "t2Right")!, ["id": nil, "t1id": nil, "name": nil]) + XCTAssertEqual(rows[2].scoped(on: "t3")!, ["t1id": nil, "name": nil]) + XCTAssertEqual(rows[2].scoped(on: "suffix")!, ["t5count": 0]) + } + } + + func testFlatModel() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = SQLRequest(testedSQL).adapted { db in + let adapters = try splittingRowAdapters(columnCounts: [ + T1.numberOfSelectedColumns(db), + T2.numberOfSelectedColumns(db), + T2.numberOfSelectedColumns(db), + T3.numberOfSelectedColumns(db)]) + return ScopeAdapter([ + "t1": adapters[0], + "t2Left": adapters[1], + "t2Right": adapters[2], + "t3": adapters[3], + "suffix": adapters[4]]) + } + let models = try FlatModel.fetchAll(db, request) + XCTAssertEqual(models.count, 3) - let sql = """ - SELECT - \(T1.selectionSQL()), - \(T2.selectionSQL(alias: "t2Left")) - \(T2.selectionSQL(alias: "t2Right")) - \(T3.selectionSQL()), - COUNT(DISTINCT t5.id) AS t5count - FROM t1 - LEFT JOIN t2 t2Left ON t2Left.t1id = t1.id AND t2Left.name = 'left' - LEFT JOIN t2 t2Right ON t2Right.t1id = t1.id AND t2Right.name = 'right' - LEFT JOIN t3 ON t3.t1id = t1.id - LEFT JOIN t4 ON t4.t1id = t1.id - LEFT JOIN t5 ON t5.t3id = t3.t1id OR t5.t4id = t4.t1id - GROUP BY t1.id - ORDER BY t1.id - """ - let expectedSQL = """ - SELECT - "t1".*, - "t2Left".* - "t2Right".* - "t3"."t1id", "t3"."name", - COUNT(DISTINCT t5.id) AS t5count - FROM t1 - LEFT JOIN t2 t2Left ON t2Left.t1id = t1.id AND t2Left.name = 'left' - LEFT JOIN t2 t2Right ON t2Right.t1id = t1.id AND t2Right.name = 'right' - LEFT JOIN t3 ON t3.t1id = t1.id - LEFT JOIN t4 ON t4.t1id = t1.id - LEFT JOIN t5 ON t5.t3id = t3.t1id OR t5.t4id = t4.t1id - GROUP BY t1.id - ORDER BY t1.id - """ - XCTAssertEqual(sql, expectedSQL) + XCTAssertEqual(models[0].t1.id, 1) + XCTAssertEqual(models[0].t1.name, "A1") + XCTAssertEqual(models[0].t2Left!.id, 1) + XCTAssertEqual(models[0].t2Left!.t1id, 1) + XCTAssertEqual(models[0].t2Left!.name, "left") + XCTAssertEqual(models[0].t2Right!.id, 2) + XCTAssertEqual(models[0].t2Right!.t1id, 1) + XCTAssertEqual(models[0].t2Right!.name, "right") + XCTAssertEqual(models[0].t3!.t1id, 1) + XCTAssertEqual(models[0].t3!.name, "A3") + XCTAssertEqual(models[0].t5count, 5) + + XCTAssertEqual(models[1].t1.id, 2) + XCTAssertEqual(models[1].t1.name, "A2") + XCTAssertEqual(models[1].t2Left!.id, 3) + XCTAssertEqual(models[1].t2Left!.t1id, 2) + XCTAssertEqual(models[1].t2Left!.name, "left") + XCTAssertNil(models[1].t2Right) + XCTAssertNil(models[1].t3) + XCTAssertEqual(models[1].t5count, 2) + + XCTAssertEqual(models[2].t1.id, 3) + XCTAssertEqual(models[2].t1.name, "A3") + XCTAssertNil(models[2].t2Left) + XCTAssertNil(models[2].t2Right) + XCTAssertNil(models[2].t3) + XCTAssertEqual(models[2].t5count, 0) + } + } + + func testCodableFlatModel() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = SQLRequest(testedSQL).adapted { db in + let adapters = try splittingRowAdapters(columnCounts: [ + T1.numberOfSelectedColumns(db), + T2.numberOfSelectedColumns(db), + T2.numberOfSelectedColumns(db), + T3.numberOfSelectedColumns(db)]) + return ScopeAdapter([ + "t1": adapters[0], + "t2Left": adapters[1], + "t2Right": adapters[2], + "t3": adapters[3]]) + } + let models = try CodableFlatModel.fetchAll(db, request) + XCTAssertEqual(models.count, 3) + + XCTAssertEqual(models[0].t1.id, 1) + XCTAssertEqual(models[0].t1.name, "A1") + XCTAssertEqual(models[0].t2Left!.id, 1) + XCTAssertEqual(models[0].t2Left!.t1id, 1) + XCTAssertEqual(models[0].t2Left!.name, "left") + XCTAssertEqual(models[0].t2Right!.id, 2) + XCTAssertEqual(models[0].t2Right!.t1id, 1) + XCTAssertEqual(models[0].t2Right!.name, "right") + XCTAssertEqual(models[0].t3!.t1id, 1) + XCTAssertEqual(models[0].t3!.name, "A3") + XCTAssertEqual(models[0].t5count, 5) + + XCTAssertEqual(models[1].t1.id, 2) + XCTAssertEqual(models[1].t1.name, "A2") + XCTAssertEqual(models[1].t2Left!.id, 3) + XCTAssertEqual(models[1].t2Left!.t1id, 2) + XCTAssertEqual(models[1].t2Left!.name, "left") + XCTAssertNil(models[1].t2Right) + XCTAssertNil(models[1].t3) + XCTAssertEqual(models[1].t5count, 2) + + XCTAssertEqual(models[2].t1.id, 3) + XCTAssertEqual(models[2].t1.name, "A3") + XCTAssertNil(models[2].t2Left) + XCTAssertNil(models[2].t2Right) + XCTAssertNil(models[2].t3) + XCTAssertEqual(models[2].t5count, 0) + } + } + + func testCodableNestedModel() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = SQLRequest(testedSQL).adapted { db in + let adapters = try splittingRowAdapters(columnCounts: [ + T1.numberOfSelectedColumns(db), + T2.numberOfSelectedColumns(db), + T2.numberOfSelectedColumns(db), + T3.numberOfSelectedColumns(db)]) + return ScopeAdapter([ + "t1": adapters[0], + "optionalT2Pair": ScopeAdapter(nestedScopes: [ + "left": adapters[1], + "right": adapters[2]]), + "t2Pair": ScopeAdapter(nestedScopes: [ + "left": adapters[1], + "right": adapters[2]]), + "t3": adapters[3]]) + } + let models = try CodableNestedModel.fetchAll(db, request) + XCTAssertEqual(models.count, 3) + + XCTAssertEqual(models[0].t1.id, 1) + XCTAssertEqual(models[0].t1.name, "A1") + XCTAssertEqual(models[0].optionalT2Pair!.left!.id, 1) + XCTAssertEqual(models[0].optionalT2Pair!.left!.t1id, 1) + XCTAssertEqual(models[0].optionalT2Pair!.left!.name, "left") + XCTAssertEqual(models[0].optionalT2Pair!.right!.id, 2) + XCTAssertEqual(models[0].optionalT2Pair!.right!.t1id, 1) + XCTAssertEqual(models[0].optionalT2Pair!.right!.name, "right") + XCTAssertEqual(models[0].t2Pair.left!.id, 1) + XCTAssertEqual(models[0].t2Pair.left!.t1id, 1) + XCTAssertEqual(models[0].t2Pair.left!.name, "left") + XCTAssertEqual(models[0].t2Pair.right!.id, 2) + XCTAssertEqual(models[0].t2Pair.right!.t1id, 1) + XCTAssertEqual(models[0].t2Pair.right!.name, "right") + XCTAssertEqual(models[0].t3!.t1id, 1) + XCTAssertEqual(models[0].t3!.name, "A3") + XCTAssertEqual(models[0].t5count, 5) + + XCTAssertEqual(models[1].t1.id, 2) + XCTAssertEqual(models[1].t1.name, "A2") + XCTAssertEqual(models[1].optionalT2Pair!.left!.id, 3) + XCTAssertEqual(models[1].optionalT2Pair!.left!.t1id, 2) + XCTAssertEqual(models[1].optionalT2Pair!.left!.name, "left") + XCTAssertEqual(models[1].t2Pair.left!.id, 3) + XCTAssertEqual(models[1].t2Pair.left!.t1id, 2) + XCTAssertEqual(models[1].t2Pair.left!.name, "left") + XCTAssertNil(models[1].optionalT2Pair!.right) + XCTAssertNil(models[1].t2Pair.right) + XCTAssertNil(models[1].t3) + XCTAssertEqual(models[1].t5count, 2) + + XCTAssertEqual(models[2].t1.id, 3) + XCTAssertEqual(models[2].t1.name, "A3") + XCTAssertNil(models[2].optionalT2Pair) + XCTAssertNil(models[2].t2Pair.left) + XCTAssertNil(models[2].t2Pair.right) + XCTAssertNil(models[2].t3) + XCTAssertEqual(models[2].t5count, 0) } } }