From 564c4cef5cc9950b387b97f9d20f416c90c397fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 3 Dec 2021 19:24:56 +0100 Subject: [PATCH 01/13] annotated(withOptional:), annotated(withRequired:) --- .../Request/RequestProtocols.swift | 28 +++++++++++++++++++ GRDB/QueryInterface/SQL/Table.swift | 16 +++++++++++ .../TableRecord+Association.swift | 16 +++++++++++ 3 files changed, 60 insertions(+) diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 72a9ccccc..d4c1ecd48 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -703,6 +703,34 @@ extension JoinableRequest { } } +extension JoinableRequest where Self: SelectionRequest { +#warning("TODO: document") + public func annotated(withOptional association: A) -> Self where A.OriginRowDecoder == RowDecoder { + let alias = TableAlias() + let selection = association._sqlAssociation.destination.relation.selectionPromise + return self + .joining(optional: association.aliased(alias)) + .annotated(with: { db in + try selection.resolve(db).map { selection in + selection.qualified(with: alias) + } + }) + } + +#warning("TODO: document") + public func annotated(withRequired association: A) -> Self where A.OriginRowDecoder == RowDecoder { + let selection = association._sqlAssociation.destination.relation.selectionPromise + let alias = TableAlias() + return self + .joining(required: association.aliased(alias)) + .annotated(with: { db in + try selection.resolve(db).map { selection in + selection.qualified(with: alias) + } + }) + } +} + // MARK: - DerivableRequest /// The base protocol for all requests that can be refined. diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index 03f8fa45c..14e180d8c 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -1186,6 +1186,22 @@ extension Table { { all().joining(required: association) } + +#warning("TODO: document") + public func annotated(withOptional association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == RowDecoder + { + all().annotated(withOptional: association) + } + +#warning("TODO: document") + public func annotated(withRequired association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == RowDecoder + { + all().annotated(withRequired: association) + } } // MARK: - Association Aggregates diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index 7c2fdaee6..e3b367a1a 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -620,6 +620,22 @@ extension TableRecord { { all().joining(required: association) } + +#warning("TODO: document") + public static func annotated(withOptional association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self + { + all().annotated(withOptional: association) + } + +#warning("TODO: document") + public static func annotated(withRequired association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self + { + all().annotated(withRequired: association) + } } // MARK: - Aggregates From b4ca10300290a6cc64d8a5e1cb89988bdf812009 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 3 Dec 2021 19:25:03 +0100 Subject: [PATCH 02/13] Tests for annotated(withOptional:), annotated(withRequired:) --- ...ciationBelongsToDecodableRecordTests.swift | 34 ++ ...ciationBelongsToFetchableRecordTests.swift | 41 +- .../AssociationBelongsToRowScopeTests.swift | 70 ++- .../AssociationBelongsToSQLTests.swift | 384 ++++++++++++++++ ...ionHasOneThroughFetchableRecordTests.swift | 81 ++++ ...ssociationHasOneThroughRowScopeTests.swift | 96 ++++ .../AssociationHasOneThroughSQLTests.swift | 428 ++++++++++++++++++ 7 files changed, 1132 insertions(+), 2 deletions(-) diff --git a/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift index 22da30dba..d68fdb353 100644 --- a/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift @@ -27,6 +27,11 @@ private struct PlayerWithOptionalTeam: Decodable, FetchableRecord { static let team = Player.team.forKey(CodingKeys.team) } +private struct PlayerWithTeamName: Decodable, FetchableRecord { + var player: Player + var teamName: String? +} + extension QueryInterfaceRequest where RowDecoder == Player { func filter(teamName: String) -> QueryInterfaceRequest { joining(required: PlayerWithOptionalTeam.team.filter(Column("name") == teamName)) @@ -74,6 +79,19 @@ class AssociationBelongsToDecodableRecordTests: GRDBTestCase { XCTAssertEqual(records[0].team.name, "Reds") } + func testAnnotatedWithRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player + .annotated(withRequired: Player.team.select(Column("name").forKey("teamName"))) + .asRequest(of: PlayerWithTeamName.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(records.count, 1) + XCTAssertEqual(records[0].player.id, 1) + XCTAssertEqual(records[0].player.teamId, 1) + XCTAssertEqual(records[0].player.name, "Arthur") + XCTAssertEqual(records[0].teamName, "Reds") + } + func testIncludingOptional() throws { let dbQueue = try makeDatabaseQueue() let request = Player @@ -92,6 +110,22 @@ class AssociationBelongsToDecodableRecordTests: GRDBTestCase { XCTAssertNil(records[1].team) } + func testAnnotatedWithOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player + .annotated(withOptional: Player.team.select(Column("name").forKey("teamName"))) + .asRequest(of: PlayerWithTeamName.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(records.count, 2) + XCTAssertEqual(records[0].player.id, 1) + XCTAssertEqual(records[0].player.teamId, 1) + XCTAssertEqual(records[0].player.name, "Arthur") + XCTAssertEqual(records[0].teamName, "Reds") + XCTAssertEqual(records[1].player.id, 2) + XCTAssertEqual(records[1].player.name, "Barbara") + XCTAssertNil(records[1].teamName) + } + func testJoiningRequired() throws { let dbQueue = try makeDatabaseQueue() let request = Player.joining(required: Player.team) diff --git a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift index ebbabc3cc..8c4eb67f5 100644 --- a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift @@ -36,6 +36,16 @@ private struct PlayerWithOptionalTeam: FetchableRecord { } } +private struct PlayerWithTeamName: FetchableRecord { + var player: Player + var teamName: String? + + init(row: Row) { + player = Player(row: row) + teamName = row["teamName"] + } +} + /// Test support for FetchableRecord records class AssociationBelongsToFetchableRecordTests: GRDBTestCase { @@ -71,6 +81,19 @@ class AssociationBelongsToFetchableRecordTests: GRDBTestCase { XCTAssertEqual(records[0].team.name, "Reds") } + func testAnnotatedWithRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player + .annotated(withRequired: Player.team.select(Column("name").forKey("teamName"))) + .asRequest(of: PlayerWithTeamName.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(records.count, 1) + XCTAssertEqual(records[0].player.id, 1) + XCTAssertEqual(records[0].player.teamId, 1) + XCTAssertEqual(records[0].player.name, "Arthur") + XCTAssertEqual(records[0].teamName, "Reds") + } + func testIncludingOptional() throws { let dbQueue = try makeDatabaseQueue() let request = Player @@ -89,6 +112,22 @@ class AssociationBelongsToFetchableRecordTests: GRDBTestCase { XCTAssertNil(records[1].team) } + func testAnnotatedWithOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player + .annotated(withOptional: Player.team.select(Column("name").forKey("teamName"))) + .asRequest(of: PlayerWithTeamName.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(records.count, 2) + XCTAssertEqual(records[0].player.id, 1) + XCTAssertEqual(records[0].player.teamId, 1) + XCTAssertEqual(records[0].player.name, "Arthur") + XCTAssertEqual(records[0].teamName, "Reds") + XCTAssertEqual(records[1].player.id, 2) + XCTAssertEqual(records[1].player.name, "Barbara") + XCTAssertNil(records[1].teamName) + } + func testJoiningRequired() throws { let dbQueue = try makeDatabaseQueue() let request = Player.joining(required: Player.team) @@ -99,7 +138,7 @@ class AssociationBelongsToFetchableRecordTests: GRDBTestCase { XCTAssertEqual(players[0].name, "Arthur") } - func testJoiningsOptional() throws { + func testJoiningOptional() throws { let dbQueue = try makeDatabaseQueue() let request = Player.joining(optional: Player.team) let players = try dbQueue.inDatabase { try request.fetchAll($0) } diff --git a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift index 03894a677..11cbaf274 100644 --- a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift @@ -66,6 +66,22 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase { XCTAssertEqual(rows[0].scopes["team"]!, ["id":1, "name":"Reds"]) } + func testDefaultScopeAnnotatedWithRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.annotated(withRequired: Player.defaultTeam) + let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "id":1, "name":"Reds"]) + } + + func testDefaultScopeAnnotatedWithRequiredCustomSelection() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.annotated(withRequired: Player.defaultTeam.select(Column("name").forKey("teamName"))) + let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "teamName":"Reds"]) + } + func testDefaultScopeIncludingOptional() throws { let dbQueue = try makeDatabaseQueue() let request = Player.including(optional: Player.defaultTeam) @@ -79,6 +95,24 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase { XCTAssertEqual(rows[1].scopes["team"]!, ["id":nil, "name":nil]) } + func testDefaultScopeAnnotatedWithOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.annotated(withOptional: Player.defaultTeam) + let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "id":1, "name":"Reds"]) + XCTAssertEqual(rows[1], ["id":2, "teamId":nil, "name":"Barbara", "id":nil, "name":nil]) + } + + func testDefaultScopeAnnotatedWithOptionalCustomSelection() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.annotated(withOptional: Player.defaultTeam.select(Column("name").forKey("teamName"))) + let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "teamName":"Reds"]) + XCTAssertEqual(rows[1], ["id":2, "teamId":nil, "name":"Barbara", "teamName":nil]) + } + func testDefaultScopeJoiningRequired() throws { let dbQueue = try makeDatabaseQueue() let request = Player.joining(required: Player.defaultTeam) @@ -118,7 +152,23 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase { XCTAssertEqual(Set(rows[0].scopes.names), ["customTeam"]) XCTAssertEqual(rows[0].scopes["customTeam"]!, ["id":1, "name":"Reds"]) } - + + func testCustomScopeAnnotatedWithRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.annotated(withRequired: Player.customTeam) + let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "id":1, "name":"Reds"]) + } + + func testCustomScopeAnnotatedWithRequiredCustomSelection() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.annotated(withRequired: Player.customTeam.select(Column("name").forKey("teamName"))) + let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "teamName":"Reds"]) + } + func testCustomScopeIncludingOptional() throws { let dbQueue = try makeDatabaseQueue() let request = Player.including(optional: Player.customTeam) @@ -132,6 +182,24 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase { XCTAssertEqual(rows[1].scopes["customTeam"]!, ["id":nil, "name":nil]) } + func testCustomScopeAnnotatedWithOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.annotated(withOptional: Player.customTeam) + let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "id":1, "name":"Reds"]) + XCTAssertEqual(rows[1], ["id":2, "teamId":nil, "name":"Barbara", "id":nil, "name":nil]) + } + + func testCustomScopeAnnotatedWithOptionalCustomSelection() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.annotated(withOptional: Player.customTeam.select(Column("name").forKey("teamName"))) + let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "teamName":"Reds"]) + XCTAssertEqual(rows[1], ["id":2, "teamId":nil, "name":"Barbara", "teamName":nil]) + } + func testCustomPluralScopeIncludingRequired() throws { // Make sure explicit plural keys are preserved let dbQueue = try makeDatabaseQueue() diff --git a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift index 55c1f8bdb..ed21f4c95 100644 --- a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift @@ -61,6 +61,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "parents" ON ("parents"."rowid" = "children"."parentId") AND ("parents"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON "parents"."rowid" = "children"."parentId" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."rowid" = "children"."parentId" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("rowid"))), """ + SELECT "children".*, "parents"."rowid" \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."rowid" = "children"."parentId" + """) + try assertEqualSQL(db, Child(parentID: 1).request(for: association), """ SELECT * FROM "parents" WHERE "rowid" = 1 """) @@ -108,6 +124,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") AND ("parents"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON "parents"."id" = "children"."parentId" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."id" = "children"."parentId" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """ + SELECT "children".*, "parents"."id" \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."id" = "children"."parentId" + """) + try assertEqualSQL(db, Child(parentID: 1).request(for: association), """ SELECT * FROM "parents" WHERE "id" = 1 """) @@ -182,6 +214,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") AND ("parents"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON "parents"."id" = "children"."parentId" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."id" = "children"."parentId" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """ + SELECT "children".*, "parents"."id" \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."id" = "children"."parentId" + """) + try assertEqualSQL(db, Child(parentID: 1).request(for: association), """ SELECT * FROM "parents" WHERE "id" = 1 """) @@ -229,6 +277,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") AND ("parents"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON "parents"."id" = "children"."parentId" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."id" = "children"."parentId" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """ + SELECT "children".*, "parents"."id" \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."id" = "children"."parentId" + """) + try assertEqualSQL(db, Child(parentID: 1).request(for: association), """ SELECT * FROM "parents" WHERE "id" = 1 """) @@ -301,6 +365,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") AND ("parents"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON "parents"."id" = "children"."parentId" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."id" = "children"."parentId" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """ + SELECT "children".*, "parents"."id" \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."id" = "children"."parentId" + """) + try assertEqualSQL(db, Child(parentID: 1).request(for: association), """ SELECT * FROM "parents" WHERE "id" = 1 """) @@ -348,6 +428,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") AND ("parents"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON "parents"."id" = "children"."parentId" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."id" = "children"."parentId" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """ + SELECT "children".*, "parents"."id" \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."id" = "children"."parentId" + """) + try assertEqualSQL(db, Child(parentID: 1).request(for: association), """ SELECT * FROM "parents" WHERE "id" = 1 """) @@ -395,6 +491,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") AND ("parents"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON "parents"."id" = "children"."parentId" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."id" = "children"."parentId" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """ + SELECT "children".*, "parents"."id" \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."id" = "children"."parentId" + """) + try assertEqualSQL(db, Child(parentID: 1).request(for: association), """ SELECT * FROM "parents" WHERE "id" = 1 """) @@ -472,6 +584,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "parents" ON ("parents"."id" = "children"."parent1Id") AND ("parents"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON "parents"."id" = "children"."parent1Id" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """ + SELECT "children".*, "parents"."id" \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id" + """) + try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """ SELECT * FROM "parents" WHERE "id" = 1 """) @@ -519,6 +647,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "parents" ON ("parents"."id" = "children"."parent1Id") AND ("parents"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON "parents"."id" = "children"."parent1Id" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """ + SELECT "children".*, "parents"."id" \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id" + """) + try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """ SELECT * FROM "parents" WHERE "id" = 1 """) @@ -566,6 +710,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "parents" ON ("parents"."id" = "children"."parent2Id") AND ("parents"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON "parents"."id" = "children"."parent2Id" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """ + SELECT "children".*, "parents"."id" \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id" + """) + try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """ SELECT * FROM "parents" WHERE "id" = 2 """) @@ -613,6 +773,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "parents" ON ("parents"."id" = "children"."parent2Id") AND ("parents"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON "parents"."id" = "children"."parent2Id" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """ + SELECT "children".*, "parents"."id" \ + FROM "children" \ + LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id" + """) + try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """ SELECT * FROM "parents" WHERE "id" = 2 """) @@ -691,6 +867,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") AND ("parents"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("a"), Column("b"))), """ + SELECT "children".*, "parents"."a", "parents"."b" \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") + """) + try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """ SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2) """) @@ -784,6 +976,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") AND ("parents"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("a"), Column("b"))), """ + SELECT "children".*, "parents"."a", "parents"."b" \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") + """) + try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """ SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2) """) @@ -845,6 +1053,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") AND ("parents"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("a"), Column("b"))), """ + SELECT "children".*, "parents"."a", "parents"."b" \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") + """) + try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """ SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2) """) @@ -937,6 +1161,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") AND ("parents"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("a"), Column("b"))), """ + SELECT "children".*, "parents"."a", "parents"."b" \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") + """) + try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """ SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2) """) @@ -998,6 +1238,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") AND ("parents"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("a"), Column("b"))), """ + SELECT "children".*, "parents"."a", "parents"."b" \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") + """) + try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """ SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2) """) @@ -1059,6 +1315,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") AND ("parents"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("a"), Column("b"))), """ + SELECT "children".*, "parents"."a", "parents"."b" \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB") + """) + try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """ SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2) """) @@ -1160,6 +1432,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B") AND ("parents"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B") + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B") + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("a"), Column("b"))), """ + SELECT "children".*, "parents"."a", "parents"."b" \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B") + """) + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """ SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2) """) @@ -1221,6 +1509,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B") AND ("parents"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B") + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B") + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("a"), Column("b"))), """ + SELECT "children".*, "parents"."a", "parents"."b" \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B") + """) + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """ SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2) """) @@ -1282,6 +1586,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B") AND ("parents"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B") + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B") + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("a"), Column("b"))), """ + SELECT "children".*, "parents"."a", "parents"."b" \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B") + """) + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """ SELECT * FROM "parents" WHERE ("a" = 3) AND ("b" = 4) """) @@ -1343,6 +1663,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B") AND ("parents"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B") + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B") + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("a"), Column("b"))), """ + SELECT "children".*, "parents"."a", "parents"."b" \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B") + """) + try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """ SELECT * FROM "parents" WHERE ("a" = 3) AND ("b" = 4) """) @@ -1470,6 +1806,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "PARENTS" ON ("PARENTS"."id" = "CHILDREN"."parentId") AND ("PARENTS"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "CHILDREN".*, "PARENTS".* \ + FROM "CHILDREN" \ + JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "CHILDREN".*, "PARENTS".* \ + FROM "CHILDREN" \ + LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """ + SELECT "CHILDREN".*, "PARENTS"."id" \ + FROM "CHILDREN" \ + LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId" + """) + try assertEqualSQL(db, Child(parentID: 1).request(for: association), """ SELECT * FROM "PARENTS" WHERE "id" = 1 """) @@ -1517,6 +1869,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "PARENTS" ON ("PARENTS"."id" = "CHILDREN"."parentId") AND ("PARENTS"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "CHILDREN".*, "PARENTS".* \ + FROM "CHILDREN" \ + JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "CHILDREN".*, "PARENTS".* \ + FROM "CHILDREN" \ + LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """ + SELECT "CHILDREN".*, "PARENTS"."id" \ + FROM "CHILDREN" \ + LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId" + """) + try assertEqualSQL(db, Child(parentID: 1).request(for: association), """ SELECT * FROM "PARENTS" WHERE "id" = 1 """) @@ -1564,6 +1932,22 @@ class AssociationBelongsToSQLTests: GRDBTestCase { LEFT JOIN "PARENTS" ON ("PARENTS"."ID" = "CHILDREN"."PARENTID") AND ("PARENTS"."name" = 'foo') """) + try assertEqualSQL(db, Child.annotated(withRequired: association), """ + SELECT "CHILDREN".*, "PARENTS".* \ + FROM "CHILDREN" \ + JOIN "PARENTS" ON "PARENTS"."ID" = "CHILDREN"."PARENTID" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association), """ + SELECT "CHILDREN".*, "PARENTS".* \ + FROM "CHILDREN" \ + LEFT JOIN "PARENTS" ON "PARENTS"."ID" = "CHILDREN"."PARENTID" + """) + try assertEqualSQL(db, Child.annotated(withOptional: association.select(Column("id"))), """ + SELECT "CHILDREN".*, "PARENTS"."id" \ + FROM "CHILDREN" \ + LEFT JOIN "PARENTS" ON "PARENTS"."ID" = "CHILDREN"."PARENTID" + """) + try assertEqualSQL(db, Child(parentID: 1).request(for: association), """ SELECT * FROM "PARENTS" WHERE "ID" = 1 """) diff --git a/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift b/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift index 4f107780c..feb415424 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift @@ -53,6 +53,28 @@ private struct AWithRequiredBAndOptionalC: FetchableRecord { } } +private struct AWithCName: FetchableRecord { + var a: A + var cName: String? + + init(row: Row) { + a = A(row: row) + cName = row["cName"] + } +} + +private struct AWithRequiredBNameAndOptionalCName: FetchableRecord { + var a: A + var bName: String + var cName: String? + + init(row: Row) { + a = A(row: row) + bName = row["bName"] + cName = row["cName"] + } +} + /// Test support for FetchableRecord records class AssociationHasOneThroughFetchableRecordTests: GRDBTestCase { @@ -96,6 +118,19 @@ class AssociationHasOneThroughFetchableRecordTests: GRDBTestCase { XCTAssertEqual(records[0].c.name, "c1") } + func testAnnotatedWithRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.annotated(withRequired: A.c.select(Column("name").forKey("cName"))).order(sql: "a.id") + let records = try dbQueue.inDatabase { try AWithCName.fetchAll($0, request) } + + XCTAssertEqual(records.count, 1) + + XCTAssertEqual(records[0].a.id, 1) + XCTAssertEqual(records[0].a.bId, 1) + XCTAssertEqual(records[0].a.name, "a1") + XCTAssertEqual(records[0].cName, "c1") + } + func testIncludingOptional() throws { let dbQueue = try makeDatabaseQueue() let request = A.including(optional: A.c).order(sql: "a.id") @@ -120,6 +155,29 @@ class AssociationHasOneThroughFetchableRecordTests: GRDBTestCase { XCTAssertNil(records[2].c) } + func testAnnotatedWithOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.annotated(withOptional: A.c.select(Column("name").forKey("cName"))).order(sql: "a.id") + let records = try dbQueue.inDatabase { try AWithCName.fetchAll($0, request) } + + XCTAssertEqual(records.count, 3) + + XCTAssertEqual(records[0].a.id, 1) + XCTAssertEqual(records[0].a.bId, 1) + XCTAssertEqual(records[0].a.name, "a1") + XCTAssertEqual(records[0].cName, "c1") + + XCTAssertEqual(records[1].a.id, 2) + XCTAssertEqual(records[1].a.bId, 2) + XCTAssertEqual(records[1].a.name, "a2") + XCTAssertNil(records[1].cName) + + XCTAssertEqual(records[2].a.id, 3) + XCTAssertNil(records[2].a.bId) + XCTAssertEqual(records[2].a.name, "a3") + XCTAssertNil(records[2].cName) + } + func testJoiningRequired() throws { let dbQueue = try makeDatabaseQueue() let request = A.joining(required: A.c).order(sql: "a.id") @@ -177,4 +235,27 @@ class AssociationHasOneThroughFetchableRecordTests: GRDBTestCase { XCTAssertEqual(records[1].b.name, "b2") XCTAssertNil(records[1].c) } + + func testAnnotatedWithOptionalAnnotatedWithRequiredPivot() throws { + let dbQueue = try makeDatabaseQueue() + let request = A + .annotated(withOptional: A.c.select(Column("name").forKey("cName"))) + .annotated(withRequired: A.b.select(Column("name").forKey("bName"))) + .order(sql: "a.id") + let records = try dbQueue.inDatabase { try AWithRequiredBNameAndOptionalCName.fetchAll($0, request) } + + XCTAssertEqual(records.count, 2) + + XCTAssertEqual(records[0].a.id, 1) + XCTAssertEqual(records[0].a.bId, 1) + XCTAssertEqual(records[0].a.name, "a1") + XCTAssertEqual(records[0].bName, "b1") + XCTAssertEqual(records[0].cName, "c1") + + XCTAssertEqual(records[1].a.id, 2) + XCTAssertEqual(records[1].a.bId, 2) + XCTAssertEqual(records[1].a.name, "a2") + XCTAssertEqual(records[1].bName, "b2") + XCTAssertNil(records[1].cName) + } } diff --git a/Tests/GRDBTests/AssociationHasOneThroughRowScopeTests.swift b/Tests/GRDBTests/AssociationHasOneThroughRowScopeTests.swift index b0516973f..f07532c22 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughRowScopeTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughRowScopeTests.swift @@ -74,6 +74,22 @@ class AssociationHasOneThroughRowscopeTests: GRDBTestCase { XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.unscoped, ["id":1, "name":"c1"]) } + func testDefaultScopeAnnotatedWithRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.annotated(withRequired: A.defaultC).order(sql: "a.id") + let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0], ["id":1, "bId":1, "name":"a1", "id":1, "name":"c1"]) + } + + func testDefaultScopeAnnotatedWithRequiredCustomSelection() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.annotated(withRequired: A.defaultC.select(Column("name").forKey("cName"))).order(sql: "a.id") + let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0], ["id":1, "bId":1, "name":"a1", "cName":"c1"]) + } + func testDefaultScopeIncludingOptional() throws { let dbQueue = try makeDatabaseQueue() let request = A.including(optional: A.defaultC).order(sql: "a.id") @@ -100,6 +116,30 @@ class AssociationHasOneThroughRowscopeTests: GRDBTestCase { XCTAssertEqual(rows[2].scopes["b"]!.scopes["c"]!.unscoped, ["id":nil, "name":nil]) } + func testDefaultScopeAnnotatedWithOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.annotated(withOptional: A.defaultC).order(sql: "a.id") + let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0], ["id":1, "bId":1, "name":"a1", "id":1, "name":"c1"]) + XCTAssertEqual(rows[1], ["id":2, "bId":2, "name":"a2", "id":nil, "name":nil]) + XCTAssertEqual(rows[2], ["id":3, "bId":nil, "name":"a3", "id":nil, "name":nil]) + } + + func testDefaultScopeAnnotatedWithOptionalCustomSelection() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.annotated(withOptional: A.defaultC.select(Column("name").forKey("cName"))).order(sql: "a.id") + let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0], ["id":1, "bId":1, "name":"a1", "cName":"c1"]) + XCTAssertEqual(rows[1], ["id":2, "bId":2, "name":"a2", "cName":nil]) + XCTAssertEqual(rows[2], ["id":3, "bId":nil, "name":"a3", "cName":nil]) + } + func testDefaultScopeJoiningRequired() throws { let dbQueue = try makeDatabaseQueue() let request = A.joining(required: A.defaultC).order(sql: "a.id") @@ -184,4 +224,60 @@ class AssociationHasOneThroughRowscopeTests: GRDBTestCase { XCTAssertEqual(Set(rows[1].scopes["b"]!.scopes.names), ["c"]) XCTAssertEqual(rows[1].scopes["b"]!.scopes["c"]!.unscoped, ["id":nil, "name":nil]) } + + func testDefaultScopeAnnotatedWithOptionalAnnotatedWithRequiredPivot() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A + .annotated(withOptional: A.defaultC) + .annotated(withRequired: A.defaultB) + .order(sql: "a.id") + let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0], ["id":1, "bId":1, "name":"a1", "id":1, "name":"c1", "id":1, "cId":1, "name":"b1"]) + XCTAssertEqual(rows[1], ["id":2, "bId":2, "name":"a2", "id":nil, "name":nil, "id":2, "cId":nil, "name":"b2"]) + } + do { + let request = A + .annotated(withRequired: A.defaultB) + .annotated(withOptional: A.defaultC) + .order(sql: "a.id") + let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0], ["id":1, "bId":1, "name":"a1", "id":1, "cId":1, "name":"b1", "id":1, "name":"c1"]) + XCTAssertEqual(rows[1], ["id":2, "bId":2, "name":"a2", "id":2, "cId":nil, "name":"b2", "id":nil, "name":nil]) + } + } + + func testDefaultScopeAnnotatedWithOptionalAnnotatedWithRequiredPivotCustomSelection() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A + .annotated(withOptional: A.defaultC.select(Column("name").forKey("cName"))) + .annotated(withRequired: A.defaultB.select(Column("name").forKey("bName"))) + .order(sql: "a.id") + let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0], ["id":1, "bId":1, "name":"a1", "cName":"c1", "bName":"b1"]) + XCTAssertEqual(rows[1], ["id":2, "bId":2, "name":"a2", "cName":nil, "bName":"b2"]) + } + do { + let request = A + .annotated(withRequired: A.defaultB.select(Column("name").forKey("bName"))) + .annotated(withOptional: A.defaultC.select(Column("name").forKey("cName"))) + .order(sql: "a.id") + let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0], ["id":1, "bId":1, "name":"a1", "bName":"b1", "cName":"c1"]) + XCTAssertEqual(rows[1], ["id":2, "bId":2, "name":"a2", "bName":"b2", "cName":nil]) + } + } } diff --git a/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift b/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift index f5d71cc8c..368aadd96 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift @@ -206,6 +206,25 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) """) + + try assertEqualSQL(db, A.annotated(withOptional: ac), """ + SELECT "a".*, "c".* \ + FROM "a" \ + LEFT JOIN "b" ON \(bCondition) \ + LEFT JOIN "c" ON \(cCondition) + """) + try assertEqualSQL(db, A.annotated(withRequired: ac), """ + SELECT "a".*, "c".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) + """) + try assertEqualSQL(db, A.annotated(withRequired: ac.select(Column.rowID)), """ + SELECT "a".*, "c"."rowid" \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) + """) } do { try assertEqualSQL(db, A.including(optional: ac).including(optional: ab), """ @@ -232,6 +251,25 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) """) + + try assertEqualSQL(db, A.annotated(withOptional: ab).including(optional: ac), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + LEFT JOIN "b" ON \(bCondition) \ + LEFT JOIN "c" ON \(cCondition) + """) + try assertEqualSQL(db, A.including(optional: ac).annotated(withRequired: ab), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + LEFT JOIN "c" ON \(cCondition) + """) + try assertEqualSQL(db, A.including(optional: ac).annotated(withRequired: ab.select(Column.rowID)), """ + SELECT "a".*, "b"."rowid", "c".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + LEFT JOIN "c" ON \(cCondition) + """) } do { try assertEqualSQL(db, A.including(required: ac).including(optional: ab), """ @@ -258,6 +296,25 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) """) + + try assertEqualSQL(db, A.annotated(withOptional: ab).including(required: ac), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) + """) + try assertEqualSQL(db, A.including(required: ac).annotated(withRequired: ab), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) + """) + try assertEqualSQL(db, A.including(required: ac).annotated(withRequired: ab.select(Column.rowID)), """ + SELECT "a".*, "b"."rowid", "c".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) + """) } do { try assertEqualSQL(db, A.joining(optional: ac).including(optional: ab), """ @@ -284,6 +341,25 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) """) + + try assertEqualSQL(db, A.annotated(withOptional: ab).joining(optional: ac), """ + SELECT "a".*, "b".* \ + FROM "a" \ + LEFT JOIN "b" ON \(bCondition) \ + LEFT JOIN "c" ON \(cCondition) + """) + try assertEqualSQL(db, A.joining(optional: ac).annotated(withRequired: ab), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + LEFT JOIN "c" ON \(cCondition) + """) + try assertEqualSQL(db, A.joining(optional: ac).annotated(withRequired: ab.select(Column.rowID)), """ + SELECT "a".*, "b"."rowid" \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + LEFT JOIN "c" ON \(cCondition) + """) } do { try assertEqualSQL(db, A.joining(required: ac).including(optional: ab), """ @@ -310,6 +386,25 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) """) + + try assertEqualSQL(db, A.annotated(withOptional: ab).joining(required: ac), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) + """) + try assertEqualSQL(db, A.joining(required: ac).annotated(withRequired: ab), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) + """) + try assertEqualSQL(db, A.joining(required: ac).annotated(withRequired: ab.select(Column.rowID)), """ + SELECT "a".*, "b"."rowid" \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) + """) } } @@ -841,6 +936,43 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { JOIN "d" ON \(dCondition) """) } + + for request in [ + A.annotated(withOptional: dThroughC), + A.annotated(withOptional: dThroughB)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON \(bCondition) \ + LEFT JOIN "c" ON \(cCondition) \ + LEFT JOIN "d" ON \(dCondition) + """) + } + for request in [ + A.annotated(withRequired: dThroughC), + A.annotated(withRequired: dThroughB)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) \ + JOIN "d" ON \(dCondition) + """) + } + for request in [ + A.annotated(withRequired: dThroughC.select(Column.rowID)), + A.annotated(withRequired: dThroughB.select(Column.rowID))] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d"."rowid" \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) \ + JOIN "d" ON \(dCondition) + """) + } } do { @@ -893,6 +1025,43 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { JOIN "d" ON \(dCondition) """) } + + for request in [ + A.including(optional: b).annotated(withOptional: dThroughC), + A.annotated(withOptional: dThroughB).including(optional: b)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".*, "b".* \ + FROM "a" \ + LEFT JOIN "b" ON \(bCondition) \ + LEFT JOIN "c" ON \(cCondition) \ + LEFT JOIN "d" ON \(dCondition) + """) + } + for request in [ + A.including(optional: b).annotated(withRequired: dThroughC), + A.annotated(withRequired: dThroughB).including(optional: b)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".*, "b".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) \ + JOIN "d" ON \(dCondition) + """) + } + for request in [ + A.including(optional: b).annotated(withRequired: dThroughC.select(Column.rowID)), + A.annotated(withRequired: dThroughB.select(Column.rowID)).including(optional: b)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d"."rowid", "b".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) \ + JOIN "d" ON \(dCondition) + """) + } } do { @@ -944,6 +1113,43 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { JOIN "d" ON \(dCondition) """) } + + for request in [ + A.including(required: b).annotated(withOptional: dThroughC), + A.annotated(withOptional: dThroughB).including(required: b)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".*, "b".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + LEFT JOIN "c" ON \(cCondition) \ + LEFT JOIN "d" ON \(dCondition) + """) + } + for request in [ + A.including(required: b).annotated(withRequired: dThroughC), + A.annotated(withRequired: dThroughB).including(required: b)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".*, "b".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) \ + JOIN "d" ON \(dCondition) + """) + } + for request in [ + A.including(required: b).annotated(withRequired: dThroughC.select(Column.rowID)), + A.annotated(withRequired: dThroughB.select(Column.rowID)).including(required: b)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d"."rowid", "b".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) \ + JOIN "d" ON \(dCondition) + """) + } } do { @@ -995,6 +1201,43 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { JOIN "d" ON \(dCondition) """) } + + for request in [ + A.joining(optional: b).annotated(withOptional: dThroughC), + A.annotated(withOptional: dThroughB).joining(optional: b)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON \(bCondition) \ + LEFT JOIN "c" ON \(cCondition) \ + LEFT JOIN "d" ON \(dCondition) + """) + } + for request in [ + A.joining(optional: b).annotated(withRequired: dThroughC), + A.annotated(withRequired: dThroughB).joining(optional: b)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) \ + JOIN "d" ON \(dCondition) + """) + } + for request in [ + A.joining(optional: b).annotated(withRequired: dThroughC.select(Column.rowID)), + A.annotated(withRequired: dThroughB.select(Column.rowID)).joining(optional: b)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d"."rowid" \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) \ + JOIN "d" ON \(dCondition) + """) + } } do { @@ -1046,6 +1289,43 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { JOIN "d" ON \(dCondition) """) } + + for request in [ + A.joining(required: b).annotated(withOptional: dThroughC), + A.annotated(withOptional: dThroughB).joining(required: b)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + LEFT JOIN "c" ON \(cCondition) \ + LEFT JOIN "d" ON \(dCondition) + """) + } + for request in [ + A.joining(required: b).annotated(withRequired: dThroughC), + A.annotated(withRequired: dThroughB).joining(required: b)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) \ + JOIN "d" ON \(dCondition) + """) + } + for request in [ + A.joining(required: b).annotated(withRequired: dThroughC.select(Column.rowID)), + A.annotated(withRequired: dThroughB.select(Column.rowID)).joining(required: b)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d"."rowid" \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) \ + JOIN "d" ON \(dCondition) + """) + } } } @@ -1099,6 +1379,43 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { JOIN "d" ON \(dCondition) """) } + + for request in [ + A.including(optional: c).annotated(withOptional: dThroughC), + A.annotated(withOptional: dThroughB).including(optional: c)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".*, "c".* \ + FROM "a" \ + LEFT JOIN "b" ON \(bCondition) \ + LEFT JOIN "c" ON \(cCondition) \ + LEFT JOIN "d" ON \(dCondition) + """) + } + for request in [ + A.including(optional: c).annotated(withRequired: dThroughC), + A.annotated(withRequired: dThroughB).including(optional: c)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".*, "c".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) \ + JOIN "d" ON \(dCondition) + """) + } + for request in [ + A.including(optional: c).annotated(withRequired: dThroughC.select(Column.rowID)), + A.annotated(withRequired: dThroughB.select(Column.rowID)).including(optional: c)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d"."rowid", "c".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) \ + JOIN "d" ON \(dCondition) + """) + } } do { @@ -1150,6 +1467,43 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { JOIN "d" ON \(dCondition) """) } + + for request in [ + A.including(required: c).annotated(withOptional: dThroughC), + A.annotated(withOptional: dThroughB).including(required: c)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".*, "c".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) \ + LEFT JOIN "d" ON \(dCondition) + """) + } + for request in [ + A.including(required: c).annotated(withRequired: dThroughC), + A.annotated(withRequired: dThroughB).including(required: c)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".*, "c".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) \ + JOIN "d" ON \(dCondition) + """) + } + for request in [ + A.including(required: c).annotated(withRequired: dThroughC.select(Column.rowID)), + A.annotated(withRequired: dThroughB.select(Column.rowID)).including(required: c)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d"."rowid", "c".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) \ + JOIN "d" ON \(dCondition) + """) + } } do { @@ -1201,6 +1555,43 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { JOIN "d" ON \(dCondition) """) } + + for request in [ + A.joining(optional: c).annotated(withOptional: dThroughC), + A.annotated(withOptional: dThroughB).joining(optional: c)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON \(bCondition) \ + LEFT JOIN "c" ON \(cCondition) \ + LEFT JOIN "d" ON \(dCondition) + """) + } + for request in [ + A.joining(optional: c).annotated(withRequired: dThroughC), + A.annotated(withRequired: dThroughB).joining(optional: c)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) \ + JOIN "d" ON \(dCondition) + """) + } + for request in [ + A.joining(optional: c).annotated(withRequired: dThroughC.select(Column.rowID)), + A.annotated(withRequired: dThroughB.select(Column.rowID)).joining(optional: c)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d"."rowid" \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) \ + JOIN "d" ON \(dCondition) + """) + } } do { @@ -1252,6 +1643,43 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { JOIN "d" ON \(dCondition) """) } + + for request in [ + A.joining(required: c).annotated(withOptional: dThroughC), + A.annotated(withOptional: dThroughB).joining(required: c)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) \ + LEFT JOIN "d" ON \(dCondition) + """) + } + for request in [ + A.joining(required: c).annotated(withRequired: dThroughC), + A.annotated(withRequired: dThroughB).joining(required: c)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) \ + JOIN "d" ON \(dCondition) + """) + } + for request in [ + A.joining(required: c).annotated(withRequired: dThroughC.select(Column.rowID)), + A.annotated(withRequired: dThroughB.select(Column.rowID)).joining(required: c)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d"."rowid" \ + FROM "a" \ + JOIN "b" ON \(bCondition) \ + JOIN "c" ON \(cCondition) \ + JOIN "d" ON \(dCondition) + """) + } } } } From 88e60ed0c6d795b22e21c4f3c9b118a9d9850b5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 4 Dec 2021 09:50:16 +0100 Subject: [PATCH 03/13] Update FAQ: How do I select only one column of an associated record? --- README.md | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index e14672a2e..fc5d849d5 100644 --- a/README.md +++ b/README.md @@ -7824,11 +7824,9 @@ struct BookInfo: Decodable, FetchableRecord { // SELECT book.*, author.name AS authorName // FROM book // LEFT JOIN author ON author.id = book.authorID - let authorAlias = TableAlias() - let authorName = authorAlias[Author.Columns.name].forKey(CodingKeys.authorName) + let authorName = Author.Columns.name.forKey(CodingKeys.authorName) return Book - .annotated(with: authorName) - .joining(optional: Book.author.aliased(authorAlias)) + .annotated(withOptional: Book.author.select(authorName)) .asRequest(of: BookInfo.self) } } @@ -7838,13 +7836,9 @@ let bookInfos: [BookInfo] = try dbQueue.read { db in } ``` -By using a TableAlias, you can refer to an author column from a request of books. - By defining the request as a static method of BookInfo, you have access to the private `CodingKeys.authorName`, and a compiler-checked SQL column name. -By using the `annotated(with:)` method, you append the author name to the top-level selection that can be decoded by the ad-hoc record. - -By using the `joining()` method, you make sure no author column is selected, but the one declared in `annotated(with:)`. +By using the `annotated(withOptional:)` method, you append the author name to the top-level selection that can be decoded by the ad-hoc record. By using `asRequest(of:)`, you enhance the type-safety of your request. From e1dc24ac9331932f36430635f7cef542a65e84fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 4 Dec 2021 10:01:31 +0100 Subject: [PATCH 04/13] Update examples with Team/Player --- .../Request/RequestProtocols.swift | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index d4c1ecd48..2f6d9b6ff 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -7,9 +7,9 @@ import Foundation public protocol TypedRequest { /// The type that can decode database rows. /// - /// In the request below, it is Book: + /// In the request below, it is Player: /// - /// let request = Book.all() + /// let request = Player.all() associatedtype RowDecoder } @@ -825,20 +825,20 @@ extension DerivableRequest { /// Creates a request which appends *aggregates* to the current selection. /// - /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount - /// // FROM player LEFT JOIN book ... - /// var request = Player.all() - /// request = request.annotated(with: Player.books.count) + /// // SELECT team.*, COUNT(DISTINCT player.id) AS playerCount + /// // FROM team LEFT JOIN player ... + /// var request = Team.all() + /// request = request.annotated(with: Team.players.count) public func annotated(with aggregates: AssociationAggregate...) -> Self { annotated(with: aggregates) } /// Creates a request which appends *aggregates* to the current selection. /// - /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount - /// // FROM player LEFT JOIN book ... - /// var request = Player.all() - /// request = request.annotated(with: [Player.books.count]) + /// // SELECT team.*, COUNT(DISTINCT player.id) AS playerCount + /// // FROM team LEFT JOIN player ... + /// var request = team.all() + /// request = request.annotated(with: [Team.players.count]) public func annotated(with aggregates: [AssociationAggregate]) -> Self { aggregates.reduce(self) { request, aggregate in request.annotated(with: aggregate) @@ -848,11 +848,11 @@ extension DerivableRequest { /// Creates a request which appends the provided aggregate *predicate* to /// the eventual set of already applied predicates. /// - /// // SELECT player.* - /// // FROM player LEFT JOIN book ... - /// // HAVING COUNT(DISTINCT book.id) = 0 - /// var request = Player.all() - /// request = request.having(Player.books.isEmpty) + /// // SELECT team.* + /// // FROM team LEFT JOIN player ... + /// // HAVING COUNT(DISTINCT player.id) = 0 + /// var request = Team.all() + /// request = request.having(Team.players.isEmpty) public func having(_ predicate: AssociationAggregate) -> Self { var request = self let expression = predicate.prepare(&request) From 9df0f4cdbd915d1d16851f868bc8a461bdc5b2b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 4 Dec 2021 10:20:18 +0100 Subject: [PATCH 05/13] Inline documentation for annotated(withOptional:), annotated(withRequired:) --- .../Request/RequestProtocols.swift | 62 +++++++++++++++- GRDB/QueryInterface/SQL/Table.swift | 70 ++++++++++++++++++- .../TableRecord+Association.swift | 62 +++++++++++++++- 3 files changed, 188 insertions(+), 6 deletions(-) diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 2f6d9b6ff..ac3051c33 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -704,7 +704,36 @@ extension JoinableRequest { } extension JoinableRequest where Self: SelectionRequest { -#warning("TODO: document") + /// Creates a request which appends *columns of an associated record* to + /// the current selection. + /// + /// // SELECT player.*, team.color + /// // FROM player LEFT JOIN team ... + /// let teamColor = Player.team.select(Column("color")) + /// let request = Player.all().annotated(withOptional: teamColor) + /// + /// This method performs the same SQL request as `including(optional:)`. + /// The difference is in the shape of Decodable records that decode such + /// a request: the associated columns can be decoded at the same level as + /// the main record: + /// + /// struct PlayerWithTeamColor: FetchableRecord, Decodable { + /// var player: Player + /// var color: String? + /// } + /// let players = try dbQueue.read { db in + /// try request + /// .asRequest(of: PlayerWithTeamColor.self) + /// .fetchAll(db) + /// } + /// + /// Note: this is a convenience method. You can build the same request with + /// `TableAlias`, `annotated(with:)`, and `joining(optional:)`: + /// + /// let teamAlias = TableAlias() + /// let request = Player.all() + /// .annotated(with: teamAlias[Column("color")]) + /// .joining(optional: Player.team.aliased(teamAlias)) public func annotated(withOptional association: A) -> Self where A.OriginRowDecoder == RowDecoder { let alias = TableAlias() let selection = association._sqlAssociation.destination.relation.selectionPromise @@ -717,7 +746,36 @@ extension JoinableRequest where Self: SelectionRequest { }) } -#warning("TODO: document") + /// Creates a request which appends *columns of an associated record* to + /// the current selection. + /// + /// // SELECT player.*, team.color + /// // FROM player JOIN team ... + /// let teamColor = Player.team.select(Column("color")) + /// let request = Player.all().annotated(withRequired: teamColor) + /// + /// This method performs the same SQL request as `including(required:)`. + /// The difference is in the shape of Decodable records that decode such + /// a request: the associated columns can be decoded at the same level as + /// the main record: + /// + /// struct PlayerWithTeamColor: FetchableRecord, Decodable { + /// var player: Player + /// var color: String + /// } + /// let players = try dbQueue.read { db in + /// try request + /// .asRequest(of: PlayerWithTeamColor.self) + /// .fetchAll(db) + /// } + /// + /// Note: this is a convenience method. You can build the same request with + /// `TableAlias`, `annotated(with:)`, and `joining(required:)`: + /// + /// let teamAlias = TableAlias() + /// let request = Player.all() + /// .annotated(with: teamAlias[Column("color")]) + /// .joining(required: Player.team.aliased(teamAlias)) public func annotated(withRequired association: A) -> Self where A.OriginRowDecoder == RowDecoder { let selection = association._sqlAssociation.destination.relation.selectionPromise let alias = TableAlias() diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index 14e180d8c..722937b6a 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -1187,7 +1187,40 @@ extension Table { all().joining(required: association) } -#warning("TODO: document") + /// Creates a request which appends *columns of an associated record* to + /// the columns of the table. + /// + /// let playerTable = Table("player") + /// let teamTable = Table("team") + /// let playerTeam = playerTable.belongsTo(teamTable) + /// + /// // SELECT player.*, team.color + /// // FROM player LEFT JOIN team ... + /// let teamColor = playerTeam.select(Column("color") + /// let request = playerTable.annotated(withOptional: teamColor)) + /// + /// This method performs the same SQL request as `including(optional:)`. + /// The difference is in the shape of Decodable records that decode such + /// a request: the associated columns can be decoded at the same level as + /// the main record: + /// + /// struct PlayerWithTeamColor: FetchableRecord, Decodable { + /// var player: Player + /// var color: String? + /// } + /// let players = try dbQueue.read { db in + /// try request + /// .asRequest(of: PlayerWithTeamColor.self) + /// .fetchAll(db) + /// } + /// + /// Note: this is a convenience method. You can build the same request with + /// `TableAlias`, `annotated(with:)`, and `joining(optional:)`: + /// + /// let teamAlias = TableAlias() + /// let request = playerTable + /// .annotated(with: teamAlias[Column("color")]) + /// .joining(optional: playerTeam.aliased(teamAlias)) public func annotated(withOptional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder @@ -1195,7 +1228,40 @@ extension Table { all().annotated(withOptional: association) } -#warning("TODO: document") + /// Creates a request which appends *columns of an associated record* to + /// the columns of the table. + /// + /// let playerTable = Table("player") + /// let teamTable = Table("team") + /// let playerTeam = playerTable.belongsTo(teamTable) + /// + /// // SELECT player.*, team.color + /// // FROM player JOIN team ... + /// let teamColor = playerTeam.select(Column("color") + /// let request = playerTable.annotated(withRequired: teamColor)) + /// + /// This method performs the same SQL request as `including(required:)`. + /// The difference is in the shape of Decodable records that decode such + /// a request: the associated columns can be decoded at the same level as + /// the main record: + /// + /// struct PlayerWithTeamColor: FetchableRecord, Decodable { + /// var player: Player + /// var color: String + /// } + /// let players = try dbQueue.read { db in + /// try request + /// .asRequest(of: PlayerWithTeamColor.self) + /// .fetchAll(db) + /// } + /// + /// Note: this is a convenience method. You can build the same request with + /// `TableAlias`, `annotated(with:)`, and `joining(required:)`: + /// + /// let teamAlias = TableAlias() + /// let request = playerTable + /// .annotated(with: teamAlias[Column("color")]) + /// .joining(required: playerTeam.aliased(teamAlias)) public func annotated(withRequired association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index e3b367a1a..98b49fa7d 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -621,7 +621,36 @@ extension TableRecord { all().joining(required: association) } -#warning("TODO: document") + /// Creates a request which appends *columns of an associated record* to + /// the selection. + /// + /// // SELECT player.*, team.color + /// // FROM player LEFT JOIN team ... + /// let teamColor = Player.team.select(Column("color")) + /// let request = Player.annotated(withOptional: teamColor) + /// + /// This method performs the same SQL request as `including(optional:)`. + /// The difference is in the shape of Decodable records that decode such + /// a request: the associated columns can be decoded at the same level as + /// the main record: + /// + /// struct PlayerWithTeamColor: FetchableRecord, Decodable { + /// var player: Player + /// var color: String? + /// } + /// let players = try dbQueue.read { db in + /// try request + /// .asRequest(of: PlayerWithTeamColor.self) + /// .fetchAll(db) + /// } + /// + /// Note: this is a convenience method. You can build the same request with + /// `TableAlias`, `annotated(with:)`, and `joining(optional:)`: + /// + /// let teamAlias = TableAlias() + /// let request = Player + /// .annotated(with: teamAlias[Column("color")]) + /// .joining(optional: Player.team.aliased(teamAlias)) public static func annotated(withOptional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self @@ -629,7 +658,36 @@ extension TableRecord { all().annotated(withOptional: association) } -#warning("TODO: document") + /// Creates a request which appends *columns of an associated record* to + /// the selection. + /// + /// // SELECT player.*, team.color + /// // FROM player JOIN team ... + /// let teamColor = Player.team.select(Column("color")) + /// let request = Player.annotated(withRequired: teamColor) + /// + /// This method performs the same SQL request as `including(required:)`. + /// The difference is in the shape of Decodable records that decode such + /// a request: the associated columns can be decoded at the same level as + /// the main record: + /// + /// struct PlayerWithTeamColor: FetchableRecord, Decodable { + /// var player: Player + /// var color: String + /// } + /// let players = try dbQueue.read { db in + /// try request + /// .asRequest(of: PlayerWithTeamColor.self) + /// .fetchAll(db) + /// } + /// + /// Note: this is a convenience method. You can build the same request with + /// `TableAlias`, `annotated(with:)`, and `joining(required:)`: + /// + /// let teamAlias = TableAlias() + /// let request = Player + /// .annotated(with: teamAlias[Column("color")]) + /// .joining(required: Player.team.aliased(teamAlias)) public static func annotated(withRequired association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self From 4fe0b687d2ea70d0f5f0a9c0b9e24cbb56d40041 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 4 Dec 2021 10:43:07 +0100 Subject: [PATCH 06/13] Documentation for annotated(withOptional:), annotated(withRequired:) --- Documentation/AssociationsBasics.md | 55 ++++++++++++++++++++++++----- 1 file changed, 47 insertions(+), 8 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 22f17d1e8..c8fa83215 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -842,13 +842,15 @@ let novels = try author ## Joining And Prefetching Associated Records -**You build requests that involve several records with the following "joining methods":** +**You build requests that involve associations with the following "joining methods":** - `joining(optional: association)` - `joining(required: association)` - `including(optional: association)` - `including(required: association)` - `including(all: associationToMany)` +- `annotated(withOptional: association)` +- `annotated(withRequired: association)` Before we describe them in detail, let's see a few requests they can build: @@ -865,10 +867,9 @@ let request = Author let request = Book .including(required: Book.author) -/// All books with their respective author, sorted by title +/// All books with their respective author country let request = Book - .including(required: Book.author) - .order(Column("title")) + .annotated(withRequired: Book.author.select(Column("country"))) /// All books written by a French author let request = Book @@ -879,9 +880,11 @@ The pattern is always the same: you start from a base request, that you extend w **To choose the joining method you need, you ask yourself two questions:** -1. Should the associated records be fetched along with the base records? +1. Should the columns of the associated records be fetched along with the base records? - If yes, use `including(...)`. Otherwise, use `joining(...)`. + - If not, use `joining(...)`. + - If you only need a few columns of the associated record, use `annotated(...)`. + - Otherwise, use `including(...)`. For example, to load books with their respective author, you use `including(required:)`: @@ -898,7 +901,22 @@ The pattern is always the same: you start from a base request, that you extend w let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request) ``` - And to load authors with their respective books, you use `including(all:)`: + To load books with their respective author country, you use `annotated(withRequired:)`: + + ```swift + // All books with their respective author country + let request = Book + .annotated(withRequired: Book.author.select(Column("country"))) + + // This request can feed the following record: + struct BookInfo: FetchableRecord, Decodable { + var book: Book + var country: String // the country of the required associated author + } + let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request) + ``` + + To load authors with their respective books, you use `including(all:)`: ```swift // All authors with their respective books @@ -943,7 +961,22 @@ The pattern is always the same: you start from a base request, that you extend w let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request) ``` - You can remember to use `optional` when the fetched associated records should feed optional Swift values, of type `Author?`. Conversely, when the fetched results feed non-optional values of type `Author`, prefer `required`. + And to load all books with their respective author countries, even if the book has no recorded author, you'd use `annotated(withOptional:)`: + + ```swift + // All books with their respective (eventual) authors + let request = Book + .annotated(withOptional: Book.author.select(Column("country"))) + + // This request can feed the following record: + struct BookInfo: FetchableRecord, Decodable { + var book: Book + var country: String? // the country of the optional associated author + } + let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request) + ``` + + You can remember to use `including(optional:)` when the fetched associated records should feed optional Swift values, of type `Author?`. Conversely, when the fetched results feed non-optional values of type `Author`, prefer `including(required:)`. Another way to describe the difference is that `required` filters the fetched results in order to discard missing associated records, when `optional` does not filter anything, and lets missing values pass through. @@ -961,6 +994,12 @@ The pattern is always the same: you start from a base request, that you extend w // SELECT book.*, author.* FROM book JOIN author ON author.id = book.authorID Book.including(required: Book.author) + + // SELECT book.*, author.country FROM book LEFT JOIN author ON author.id = book.authorID + Book.annotated(withOptional: Book.author.select(Column("country"))) + + // SELECT book.*, author.country FROM book JOIN author ON author.id = book.authorID + Book.annotated(withRequired: Book.author.select(Column("country"))) ``` From 3298cca75f2ce2feb97b73870c4985c24b60da2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 5 Dec 2021 12:25:25 +0100 Subject: [PATCH 07/13] Rewrite the Joining And Prefetching Associated Records chapter --- Documentation/AssociationsBasics.md | 611 ++++++++++++++---- ...ciationPrefetchingCodableRecordTests.swift | 40 ++ 2 files changed, 524 insertions(+), 127 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index c8fa83215..1e0690d61 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -842,164 +842,512 @@ let novels = try author ## Joining And Prefetching Associated Records -**You build requests that involve associations with the following "joining methods":** +You build requests that involve associations with one of the following "joining methods": -- `joining(optional: association)` -- `joining(required: association)` -- `including(optional: association)` -- `including(required: association)` -- `including(all: associationToMany)` -- `annotated(withOptional: association)` -- `annotated(withRequired: association)` +- Prefetch associated records: + - [`including(required:)`] + - [`including(optional:)`] + - [`including(all:)`] +- Prefetch only a few columns of an associated record: + - [`annotated(withRequired:)`] + - [`annotated(withOptional:)`] + - [`including(all:)`] +- Join associated records without prefetching: + - [`joining(required:)`] + - [`joining(optional:)`] +- [Choosing a Joining Method Given the Shape of the Decoded Type] -Before we describe them in detail, let's see a few requests they can build: +### `including(required:)` + +For example, fetch books along with their author: ```swift -/// All authors with their respective books -let request = Author - .including(all: Author.books) - -/// All authors with their awarded books -let request = Author - .including(all: Author.books.having(Book.awards.isEmpty == false)) - -/// All books with their respective author -let request = Book - .including(required: Book.author) - -/// All books with their respective author country -let request = Book - .annotated(withRequired: Book.author.select(Column("country"))) - -/// All books written by a French author -let request = Book - .joining(required: Book.author.filter(Column("countryCode") == "FR")) +// SELECT book.*, author.* +// FROM book +// JOIN author ON author.id = book.authorId +let request = Book.including(required: Book.author) ``` -The pattern is always the same: you start from a base request, that you extend with one of the joining methods. +This method accepts any association. It has the base record fetched along with one associated record, which is "included" in the fetched results. When the associated record does not exist, records are not present in the fetched results: the associated record is "required". -**To choose the joining method you need, you ask yourself two questions:** +To fetch results from such a request, you define a dedicated record type: + +```swift +// Fetch all books along with their author +struct BookInfo: Decodable, FetchableRecord { + var book: Book // The base record + var author: Author // The required associated record +} +let bookInfos = try Book + .including(required: Book.author) + .asRequest(of: BookInfo.self) + .fetchAll(db) +``` + +The CodingKey for the `BookInfo.author` property must match the association key of the `Book.author` association. The association key is, by default, the name of the associated database table. This can be configured with the association `forKey(_:)` method: + +```swift +struct Author: TableRecord { + static let databaseTableName = "writer" +} +struct Book: TableRecord { + // Replace the defaut "writer" association key with "author" + static let author = belongsTo(Author.self).forKey("author") +} + +// Fetch all books along with their author +struct BookInfo: Decodable, FetchableRecord { + var book: Book + var author: Author // Matches the "author" association key +} +let bookInfos = try Book + .including(required: Book.author) + .asRequest(of: BookInfo.self) + .fetchAll(db) +``` + +When you only need a few columns of the associated record, define a partial type with one property per selected column of the associated record: + +```swift +// Fetch all books along with the name and country of their author +struct BookInfo: Decodable, FetchableRecord { + struct PartialAuthor: Decodable { + var name: String + var country: String + } + var book: Book + var author: PartialAuthor +} +let bookInfos = try Book + .including(required: Book.author.select(Column("name"), Column("country"))) + .asRequest(of: BookInfo.self) + .fetchAll(db) +``` + +But if you'd rather avoid this extra partial type, prefer [`annotated(withRequired:)`]: + +```swift +// Fetch all books along with the country of their author +struct BookInfo: Decodable, FetchableRecord { + var book: Book + var country: String +} +let bookInfos = try Book + .annotated(withRequired: Book.author.select(Column("country"))) + .asRequest(of: BookInfo.self) + .fetchAll(db) +``` + +### `including(optional:)` + +For example, fetch books along with their eventual author: + +```swift +// SELECT book.*, author.* +// FROM book +// LEFT JOIN author ON author.id = book.authorId +let request = Book.including(optional: Book.author) +``` + +This method accepts any association. It has the base record fetched along with one associated record, which is "included" in the fetched results. The associated record can be missing: it is "optional". + +To fetch results from such a request, you define a dedicated record type: + +```swift +// Fetch all books along with their eventual author +struct BookInfo: Decodable, FetchableRecord { + var book: Book // The base record + var author: Author? // The optional associated record +} +let bookInfos = try Book + .including(optional: Book.author) + .asRequest(of: BookInfo.self) + .fetchAll(db) +``` + +The CodingKey for the `BookInfo.author` property must match the association key of the `Book.author` association. See [`including(required:)`] for more information. + +When you only need a few columns of the associated record, define a partial type with one property per selected column of the associated record: + +```swift +// Fetch all books along with the name and country of their eventual author +struct BookInfo: Decodable, FetchableRecord { + struct PartialAuthor: Decodable { + var name: String + var country: String + } + var book: Book + var author: PartialAuthor? +} +let bookInfos = try Book + .including(optional: Book.author.select(Column("name"), Column("country"))) + .asRequest(of: BookInfo.self) + .fetchAll(db) +``` + +But if you'd rather avoid this extra partial type, prefer [`annotated(withOptional:)`]: + +```swift +// Fetch all books along with the country of their eventual author +struct BookInfo: Decodable, FetchableRecord { + var book: Book + var country: String? +} +let bookInfos = try Book + .annotated(withOptional: Book.author.select(Column("country"))) + .asRequest(of: BookInfo.self) + .fetchAll(db) +``` + +### `including(all:)` + +For example, fetch authors along their books: + +```swift +// SELECT author.* FROM author +// SELECT book.* FROM book WHERE authorId IN (...) +let request = Author.including(all: Author.books) +``` + +This method accepts any to-many association ([HasMany] or [HasManyThrough]). It has the base record fetched along with all its associated records, which are "included" in the fetched results. + +To fetch results from such a request, you define a dedicated record type: + +```swift +// Fetch all authors along with their books +struct AuthorInfo: Decodable, FetchableRecord { + var author: Author // The base record + var books: [Book] // A collection of associated records +} +let authorInfos = try Author + .including(all: Author.books) + .asRequest(of: AuthorInfo.self) + .fetchAll(db) +``` + +The associated records can be stored into an Array as in the above example, but also a Set, and generally speaking any decodable Swift collection. + +The CodingKey for the `AuthorInfo.books` property must match the association key of the `Author.books` association. The association key is, by default, the pluralized name of the associated database table. This can be configured with the association `forKey(_:)` method: + +```swift +struct Book: TableRecord { + static let databaseTableName = "publication" +} +struct Author: TableRecord { + // Replace the defaut "publications" association key with "books" + static let books = hasMany(Book.self).forKey("books") +} + +// Fetch all authors along with their books +struct AuthorInfo: Decodable, FetchableRecord { + var author: Author + var books: [Book] // Matches the "books" association key +} +let authorInfos = try Author + .including(all: Author.books) + .asRequest(of: AuthorInfo.self) + .fetchAll(db) +``` + +When you only need a few columns of the associated records, define a partial type with one property per selected column of the associated record: + +```swift +// Fetch all authors along with the titles and years of their books +struct AuthorInfo: Decodable, FetchableRecord { + struct PartialBook: Decodable { + var title: String + var year: Int + } + var author: Author + var books: [PartialBook] +} +let authorInfos = try Author + .including(all: Author.books.select(Column("title"), Column("year"))) + .asRequest(of: AuthorInfo.self) + .fetchAll(db) +``` + +And when you need a single column of the associated records, use the association `forKey(_:)` method in order to match the name of the decoded property: + +```swift +// Fetch all authors along with the titles of their books +struct AuthorInfo: Decodable, FetchableRecord { + var author: Author + var bookTitles: [String] +} +let authorInfos = try Author + .including(all: Author.books + .select(Column("title")) + .forKey("bookTitles")) + .asRequest(of: AuthorInfo.self) + .fetchAll(db) +``` + +### `annotated(withRequired:)` + +For example, fetch books along with the name and country of their author: + +```swift +// SELECT book.*, author.name, author.country +// FROM book +// JOIN author ON author.id = book.authorId +let request = Book.annotated(withRequired: Book.author.select(Column("name"), Column("country"))) +``` + +This method accepts any association. The base record is annotated with the selected columns of one associated record. When the associated record does not exist, records are not present in the fetched results: the associated record is "required". + +To fetch results from such a request, you define a dedicated record type: + +```swift +// Fetch all books along with the name and country of their author +struct BookInfo: Decodable, FetchableRecord { + var book: Book // The base record + var name: String // A column of the required associated record + var country: String // A column of the required associated record +} +let bookInfos = try Book + .annotated(withRequired: Book.author.select(Column("name"), Column("country"))) + .asRequest(of: BookInfo.self) + .fetchAll(db) +``` + +If the name of a column of the associated record is also the name of a column of the base record, rename the associated column with the column `forKey(_:)` method, and accordingly rename the property of the decoded record type: + +```swift +// Fetch all books along with the name of their author +struct BookInfo: Decodable, FetchableRecord { + var book: Book + var authorName: String +} +let bookInfos = try Book + .annotated(withRequired: Book.author.select(Column("name").forKey("authorName"))) + .asRequest(of: BookInfo.self) + .fetchAll(db) +``` + +### `annotated(withOptional:)` + +For example, fetch books along with the name and country of their eventual author: + +```swift +// SELECT book.*, author.name, author.country +// FROM book +// LEFT JOIN author ON author.id = book.authorId +let request = Book.annotated(withOptional: Book.author.select(Column("name"), Column("country"))) +``` + +This method accepts any association. The base record is annotated with the selected columns of one associated record. When the associated record does not exist, the columns of the associated record are NULL: the associated record is "optional". + +To fetch results from such a request, you define a dedicated record type: + +```swift +// Fetch all books along with the name of their eventual author +struct BookInfo: Decodable, FetchableRecord { + var book: Book // The base record + var name: String? // A column of the optional associated record + var country: String? // A column of the optional associated record +} +let bookInfos = try Book + .annotated(withOptional: Book.author.select(Column("name"), Column("country"))) + .asRequest(of: BookInfo.self) + .fetchAll(db) +``` + +If the name of a column of the associated record is also the name of a column of the base record, rename the associated column with the column `forKey(_:)` method, and accordingly rename the property of the decoded record type: + +```swift +// Fetch all books along with the name of their eventual author +struct BookInfo: Decodable, FetchableRecord { + var book: Book + var authorName: String? +} +let bookInfos = try Book + .annotated(withOptional: Book.author.select(Column("name").forKey("authorName"))) + .asRequest(of: BookInfo.self) + .fetchAll(db) +``` + +### `joining(required:)` + +For example, fetch books by French authors: + +```swift +// SELECT book.* +// FROM book +// JOIN author ON author.id = book.authorId +// AND author.country = 'France' +let request = Book.joining(required: Book.author.filter(Column("country") == "France")) +``` + +This method accepts any association. It has the base record "joined" with one associated record, which is not included in the fetched results. When the associated record does not exist, the base record is not present in the fetched results: the associated record is "required". + +To fetch results from such a request, you do not need to define a dedicated record type: + +```swift +// Fetch all books by French authors +let books = try Book + .joining(required: Book.author.filter(Column("country") == "France")) + .fetchAll(db) +``` + + +### `joining(optional:)` + +```swift +// SELECT book.* +// FROM book +// LEFT JOIN author ON author.id = book.authorId +let request = Book.joining(optional: Book.author) +``` + +This method accepts any association. It has the base record "joined" with one associated record, which is not included in the fetched results. The associated record can be missing: it is "optional". + +This method has no observable effect unless the associated record is used in a way or another. We'll see examples later in this documentation. + +### Choosing a Joining Method Given the Shape of the Decoded Type + +In the description of the [joining methods] above, we have seen that you need to define dedicated record types in order to prefetch associated records. Each joining method needs a dedicated record type to have a specific shape. + +In this chapter, we take the reversed perspective. We list various shapes of decoded record types. When you find the type you want, you'll know the joining method you need. + +> :point_up: **Note**: If you don't find the type you want, chances are that you are fighting the framework, and should reconsider your position. Your escape hatch is the low-level apis described in [Decoding a Joined Request with FetchableRecord]. + +- [`including(required:)`] -1. Should the columns of the associated records be fetched along with the base records? - - - If not, use `joining(...)`. - - If you only need a few columns of the associated record, use `annotated(...)`. - - Otherwise, use `including(...)`. - - For example, to load books with their respective author, you use `including(required:)`: - ```swift - // All books with their respective author - let request = Book + struct BookInfo: Decodable, FetchableRecord { + var book: Book // The base record + var author: Author // The associated record + } + + let bookInfos = try Book .including(required: Book.author) - - // This request can feed the following record: - struct BookInfo: FetchableRecord, Decodable { - var book: Book - var author: Author // the required associated author - } - let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request) + .asRequest(of: BookInfo.self) + .fetchAll(db) ``` - To load books with their respective author country, you use `annotated(withRequired:)`: - ```swift - // All books with their respective author country - let request = Book - .annotated(withRequired: Book.author.select(Column("country"))) - - // This request can feed the following record: - struct BookInfo: FetchableRecord, Decodable { - var book: Book - var country: String // the country of the required associated author + struct BookInfo: Decodable, FetchableRecord { + struct PartialAuthor: Decodable { + var name: String + var country: String + } + var book: Book // The base record + var author: PartialAuthor // The partial associated record } - let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request) - ``` - To load authors with their respective books, you use `including(all:)`: - - ```swift - // All authors with their respective books - let request = Author - .including(all: Author.books) - - // This request can feed the following record: - struct AuthorInfo: FetchableRecord, Decodable { - var author: Author - var books: [Book] // all associated books - } - let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request) - ``` - - On the other side, to load all books written by a French author, you sure need to filter authors, but you don't need them to be present in the fetched results. You prefer `joining`: - - ```swift - // All books written by a French author - let request = Book - .joining(required: Book.author.filter(Column("countryCode") == "FR")) - - // This request feeds the Book record: - let books: [Book] = try request.fetchAll(db) + let bookInfos = try Book + .including(required: Book.author.select(Column("name"), Column("country"))) + .asRequest(of: BookInfo.self) + .fetchAll(db) ``` -2. For to-one associations, should the request allow missing associated records? - - If yes, choose the `optional` variant. Otherwise, choose `required`. - - For example, to load all books with their respective authors, even if the book has no recorded author, you'd use `including(optional:)`: +- [`annotated(withRequired:)`] ```swift - // All books with their respective (eventual) authors - let request = Book + struct BookInfo: Decodable, FetchableRecord { + var book: Book // The base record + var authorName: String // A column of the associated record + var country: String // A column of the associated record + } + + let bookInfos = try Book + .annotated(withRequired: Book.author.select( + Column("name").forKey("authorName"), + Column("country"))) + .asRequest(of: BookInfo.self) + .fetchAll(db) + ``` + +- [`including(optional:)`] + + ```swift + struct BookInfo: Decodable, FetchableRecord { + var book: Book // The base record + var author: Author? // The eventual associated record + } + + let bookInfos = try Book .including(optional: Book.author) - - // This request can feed the following record: - struct BookInfo: FetchableRecord, Decodable { - var book: Book - var author: Author? // the optional associated author - } - let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request) + .asRequest(of: BookInfo.self) + .fetchAll(db) ``` - And to load all books with their respective author countries, even if the book has no recorded author, you'd use `annotated(withOptional:)`: + ```swift + struct BookInfo: Decodable, FetchableRecord { + struct PartialAuthor: Decodable { + var name: String + var country: String + } + var book: Book // The base record + var author: PartialAuthor? // The eventual partial associated record + } + + let bookInfos = try Book + .including(optional: Book.author.select(Column("name"), Column("country"))) + .asRequest(of: BookInfo.self) + .fetchAll(db) + ``` + +- [`annotated(withOptional:)`] ```swift - // All books with their respective (eventual) authors - let request = Book - .annotated(withOptional: Book.author.select(Column("country"))) - - // This request can feed the following record: - struct BookInfo: FetchableRecord, Decodable { - var book: Book - var country: String? // the country of the optional associated author + struct BookInfo: Decodable, FetchableRecord { + var book: Book // The base record + var authorName: String? // A column of the eventual associated record + var country: String? // A column of the eventual associated record } - let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request) + + let bookInfos = try Book + .annotated(withOptional: Book.author.select( + Column("name").forKey("authorName"), + Column("country"))) + .asRequest(of: BookInfo.self) + .fetchAll(db) + ``` + +- [`including(all:)`] + + ```swift + struct AuthorInfo: Decodable, FetchableRecord { + var author: Author // The base record + var books: [Book] // A collection of associated records + } + + let authorInfos = try Author + .including(all: Author.books) + .asRequest(of: AuthorInfo.self) + .fetchAll(db) ``` - You can remember to use `including(optional:)` when the fetched associated records should feed optional Swift values, of type `Author?`. Conversely, when the fetched results feed non-optional values of type `Author`, prefer `including(required:)`. + ```swift + struct AuthorInfo: Decodable, FetchableRecord { + struct PartialBook: Decodable { + var title: String + var year: Int + } + var author: Author // The base record + var books: [PartialBook] // A collection of partial associated records + } - Another way to describe the difference is that `required` filters the fetched results in order to discard missing associated records, when `optional` does not filter anything, and lets missing values pass through. - - Finally, readers who speak SQL may compare `optional` with left joins, and `required` with inner joins: + let authorInfos = try Author + .including(all: Author.books.select(Column("title"), Column("year"))) + .asRequest(of: AuthorInfo.self) + .fetchAll(db) + ``` ```swift - // SELECT book.* FROM book LEFT JOIN author ON author.id = book.authorID - Book.joining(optional: Book.author) + struct AuthorInfo: Decodable, FetchableRecord { + var author: Author // The base record + var bookTitles: [String] // A collection of one column of the associated records + } - // SELECT book.* FROM book JOIN author ON author.id = book.authorID - Book.joining(required: Book.author) - - // SELECT book.*, author.* FROM book LEFT JOIN author ON author.id = book.authorID - Book.including(optional: Book.author) - - // SELECT book.*, author.* FROM book JOIN author ON author.id = book.authorID - Book.including(required: Book.author) - - // SELECT book.*, author.country FROM book LEFT JOIN author ON author.id = book.authorID - Book.annotated(withOptional: Book.author.select(Column("country"))) - - // SELECT book.*, author.country FROM book JOIN author ON author.id = book.authorID - Book.annotated(withRequired: Book.author.select(Column("country"))) + let authorInfos = try Author + .including(all: Author.books + .select(Column("title")) + .forKey("bookTitles")) + .asRequest(of: AuthorInfo.self) + .fetchAll(db) ``` @@ -2607,6 +2955,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [Requesting Associated Records]: #requesting-associated-records [requests for associated records]: #requesting-associated-records [Joining And Prefetching Associated Records]: #joining-and-prefetching-associated-records +[joining methods]: #joining-and-prefetching-associated-records [Filtering Associations]: #filtering-associations [Sorting Associations]: #sorting-associations [Columns Selected by an Association]: #columns-selected-by-an-association @@ -2642,3 +2991,11 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [common table expressions]: CommonTableExpressions.md [Common Table Expressions]: CommonTableExpressions.md [Associations to Common Table Expressions]: CommonTableExpressions.md#associations-to-common-table-expressions +[`including(required:)`]: #includingrequired +[`including(optional:)`]: #includingoptional +[`including(all:)`]: #includingall +[`annotated(withRequired:)`]: #annotatedwithrequired +[`annotated(withOptional:)`]: #annotatedwithoptional +[`joining(required:)`]: #joiningrequired +[`joining(optional:)`]: #joiningoptional +[Choosing a Joining Method Given the Shape of the Decoded Type]: #choosing-a-joining-method-given-the-shape-of-the-decoded-type diff --git a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift index 04fa5c549..8749ad797 100644 --- a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift @@ -130,6 +130,46 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { } } + // ContiguousArray + do { + struct Record: FetchableRecord, Decodable, Equatable { + var a: A + var bs: ContiguousArray + } + + // Record.fetchAll + do { + let records = try Record.fetchAll(db, request) + XCTAssertEqual(records, [ + Record( + a: A(row: ["cola1": 1, "cola2": "a1"]), + bs: [ + B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), + B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), + ]), + Record( + a: A(row: ["cola1": 2, "cola2": "a2"]), + bs: [ + B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), + ]), + Record( + a: A(row: ["cola1": 3, "cola2": "a3"]), + bs: []), + ]) + } + + // Record.fetchOne + do { + let record = try Record.fetchOne(db, request)! + XCTAssertEqual(record, Record( + a: A(row: ["cola1": 1, "cola2": "a1"]), + bs: [ + B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), + B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), + ])) + } + } + // Set do { struct Record: FetchableRecord, Decodable, Equatable { From 54ca12437a84d38f04efaecae6254f01a105e726 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 5 Dec 2021 14:47:02 +0100 Subject: [PATCH 08/13] CHANGELOG --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 70accc30d..a1b5780ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -82,6 +82,13 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## Next Release + +- **New**: [#1106](https://github.com/groue/GRDB.swift/pull/1106) by [@groue](https://github.com/groue): Sugar for fetching only a few columns of associated records +- **Documentation Update**: The [Joining And Prefetching Associated Records](Documentation/AssociationsBasics.md#joining-and-prefetching-associated-records) chapter was fully rewritten. The joining methods `including(required:)` and others are much more detailed, with an exploration of frequent use cases. +- **Documentation Update**: The [Joining And Prefetching Associated Records](Documentation/AssociationsBasics.md#joining-and-prefetching-associated-records) chapter introduces the new `annotated(withRequired:)` and `annotated(withOptional:)` joining methods. +- **Documentation Update**: The new [Choosing a Joining Method Given the Shape of the Decoded Type](Documentation/AssociationsBasics.md#choosing-a-joining-method-given-the-shape-of-the-decoded-type) chapter helps choosing a joining method, given the shape of the fetched data. + ## 5.15.0 Released December 2, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.14.0...v5.15.0) From 54a991b3b9fe7b3131fca02bc6a48714ab25ceaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 5 Dec 2021 15:15:38 +0100 Subject: [PATCH 09/13] Emphasize sections --- Documentation/AssociationsBasics.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 1e0690d61..9df00a3f8 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -870,7 +870,7 @@ let request = Book.including(required: Book.author) This method accepts any association. It has the base record fetched along with one associated record, which is "included" in the fetched results. When the associated record does not exist, records are not present in the fetched results: the associated record is "required". -To fetch results from such a request, you define a dedicated record type: +**To fetch results from such a request**, you define a dedicated record type: ```swift // Fetch all books along with their author @@ -884,7 +884,7 @@ let bookInfos = try Book .fetchAll(db) ``` -The CodingKey for the `BookInfo.author` property must match the association key of the `Book.author` association. The association key is, by default, the name of the associated database table. This can be configured with the association `forKey(_:)` method: +**The CodingKey for the `BookInfo.author` property must match the association key of the `Book.author` association.** The association key is, by default, the name of the associated database table. This can be configured with the association `forKey(_:)` method: ```swift struct Author: TableRecord { @@ -906,7 +906,7 @@ let bookInfos = try Book .fetchAll(db) ``` -When you only need a few columns of the associated record, define a partial type with one property per selected column of the associated record: +**When you only need a few columns of the associated record**, you can define a partial type with one property per selected column of the associated record: ```swift // Fetch all books along with the name and country of their author @@ -951,7 +951,7 @@ let request = Book.including(optional: Book.author) This method accepts any association. It has the base record fetched along with one associated record, which is "included" in the fetched results. The associated record can be missing: it is "optional". -To fetch results from such a request, you define a dedicated record type: +**To fetch results from such a request**, you define a dedicated record type: ```swift // Fetch all books along with their eventual author @@ -965,9 +965,9 @@ let bookInfos = try Book .fetchAll(db) ``` -The CodingKey for the `BookInfo.author` property must match the association key of the `Book.author` association. See [`including(required:)`] for more information. +**The CodingKey for the `BookInfo.author` property must match the association key of the `Book.author` association.** See [`including(required:)`] for more information. -When you only need a few columns of the associated record, define a partial type with one property per selected column of the associated record: +**When you only need a few columns of the associated record**, you can define a partial type with one property per selected column of the associated record: ```swift // Fetch all books along with the name and country of their eventual author @@ -1011,7 +1011,7 @@ let request = Author.including(all: Author.books) This method accepts any to-many association ([HasMany] or [HasManyThrough]). It has the base record fetched along with all its associated records, which are "included" in the fetched results. -To fetch results from such a request, you define a dedicated record type: +**To fetch results from such a request**, you define a dedicated record type: ```swift // Fetch all authors along with their books @@ -1027,7 +1027,7 @@ let authorInfos = try Author The associated records can be stored into an Array as in the above example, but also a Set, and generally speaking any decodable Swift collection. -The CodingKey for the `AuthorInfo.books` property must match the association key of the `Author.books` association. The association key is, by default, the pluralized name of the associated database table. This can be configured with the association `forKey(_:)` method: +**The CodingKey for the `AuthorInfo.books` property must match the association key of the `Author.books` association.** The association key is, by default, the pluralized name of the associated database table. This can be configured with the association `forKey(_:)` method: ```swift struct Book: TableRecord { @@ -1049,7 +1049,7 @@ let authorInfos = try Author .fetchAll(db) ``` -When you only need a few columns of the associated records, define a partial type with one property per selected column of the associated record: +**When you only need a few columns of the associated records**, you can define a partial type with one property per selected column of the associated record: ```swift // Fetch all authors along with the titles and years of their books @@ -1067,7 +1067,7 @@ let authorInfos = try Author .fetchAll(db) ``` -And when you need a single column of the associated records, use the association `forKey(_:)` method in order to match the name of the decoded property: +When you need a single column of the associated records, avoid the extra partial type, and instead use the association `forKey(_:)` method in order to match the name of the decoded property: ```swift // Fetch all authors along with the titles of their books @@ -1096,7 +1096,7 @@ let request = Book.annotated(withRequired: Book.author.select(Column("name"), Co This method accepts any association. The base record is annotated with the selected columns of one associated record. When the associated record does not exist, records are not present in the fetched results: the associated record is "required". -To fetch results from such a request, you define a dedicated record type: +**To fetch results from such a request**, you define a dedicated record type: ```swift // Fetch all books along with the name and country of their author @@ -1138,7 +1138,7 @@ let request = Book.annotated(withOptional: Book.author.select(Column("name"), Co This method accepts any association. The base record is annotated with the selected columns of one associated record. When the associated record does not exist, the columns of the associated record are NULL: the associated record is "optional". -To fetch results from such a request, you define a dedicated record type: +**To fetch results from such a request**, you define a dedicated record type: ```swift // Fetch all books along with the name of their eventual author @@ -1190,7 +1190,6 @@ let books = try Book .fetchAll(db) ``` - ### `joining(optional:)` ```swift @@ -1204,6 +1203,7 @@ This method accepts any association. It has the base record "joined" with one as This method has no observable effect unless the associated record is used in a way or another. We'll see examples later in this documentation. + ### Choosing a Joining Method Given the Shape of the Decoded Type In the description of the [joining methods] above, we have seen that you need to define dedicated record types in order to prefetch associated records. Each joining method needs a dedicated record type to have a specific shape. From a7002e1e09f8e001e2c67e41980935b7398d7cb0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 5 Dec 2021 15:22:07 +0100 Subject: [PATCH 10/13] Enhance "Columns Selected by an Association" --- Documentation/AssociationsBasics.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 9df00a3f8..8285fb536 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -1630,7 +1630,7 @@ let teamInfos = try Team ## Columns Selected by an Association -By default, associated records include all their columns: +By default, associated records, like all records, include all their columns: ```swift // SELECT book.*, author.* @@ -1641,7 +1641,9 @@ let request = Book.including(required: Book.author) **The selection can be changed for each individual request, or for all requests including a given type.** -To specify the selection of an associated record in a specific request, use the `select` method: +To specify the default selection for a given record type, see [Columns Selected by a Request](../README.md#columns-selected-by-a-request). + +To specify the selection in a specific request, use the `select` method: ```swift // SELECT book.*, author.id, author.name @@ -1651,7 +1653,7 @@ let restrictedAuthor = Book.author.select(Column("id"), Column("name")) let request = Book.including(required: restrictedAuthor) ``` -To specify the default selection for all inclusions of a given type, see [Columns Selected by a Request](../README.md#columns-selected-by-a-request). +In order to fetch from such requests of partial records, see the documentation of the [joining methods]. ## Further Refinements to Associations From 94caf4ba97c621201bb8bc0bd617d66ac8440434 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 5 Dec 2021 15:53:59 +0100 Subject: [PATCH 11/13] todo: find a way to prefix the selection with the association key --- GRDB/QueryInterface/Request/RequestProtocols.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index ac3051c33..2e31fbc32 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -735,6 +735,7 @@ extension JoinableRequest where Self: SelectionRequest { /// .annotated(with: teamAlias[Column("color")]) /// .joining(optional: Player.team.aliased(teamAlias)) public func annotated(withOptional association: A) -> Self where A.OriginRowDecoder == RowDecoder { + // TODO: find a way to prefix the selection with the association key let alias = TableAlias() let selection = association._sqlAssociation.destination.relation.selectionPromise return self @@ -777,6 +778,7 @@ extension JoinableRequest where Self: SelectionRequest { /// .annotated(with: teamAlias[Column("color")]) /// .joining(required: Player.team.aliased(teamAlias)) public func annotated(withRequired association: A) -> Self where A.OriginRowDecoder == RowDecoder { + // TODO: find a way to prefix the selection with the association key let selection = association._sqlAssociation.destination.relation.selectionPromise let alias = TableAlias() return self From 6c7f71f6200978dde6a7b52fa50e1368faa27ba8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 5 Dec 2021 16:47:32 +0100 Subject: [PATCH 12/13] Fix typo --- Documentation/AssociationsBasics.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 8285fb536..ff3685845 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -1001,7 +1001,7 @@ let bookInfos = try Book ### `including(all:)` -For example, fetch authors along their books: +For example, fetch authors along with their books: ```swift // SELECT author.* FROM author From ca2f36781e9b558267c50c9b3705fb98fed86a69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 5 Dec 2021 16:59:37 +0100 Subject: [PATCH 13/13] v5.16.0 --- CHANGELOG.md | 5 +++- Documentation/FullTextSearch.md | 4 ++-- Documentation/Migrations.md | 2 +- GRDB.swift.podspec | 2 +- Makefile | 6 ++--- README.md | 42 ++++++++++++++++----------------- Support/Info.plist | 2 +- 7 files changed, 33 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a1b5780ac..5fd2ddfbf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 5.x Releases +- `5.16.x` Releases - [5.16.0](#5160) - `5.15.x` Releases - [5.15.0](#5150) - `5.14.x` Releases - [5.14.0](#5140) - `5.13.x` Releases - [5.13.0](#5130) @@ -82,7 +83,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- -## Next Release +## 5.16.0 + +Released December 5, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.15.0...v5.16.0) - **New**: [#1106](https://github.com/groue/GRDB.swift/pull/1106) by [@groue](https://github.com/groue): Sugar for fetching only a few columns of associated records - **Documentation Update**: The [Joining And Prefetching Associated Records](Documentation/AssociationsBasics.md#joining-and-prefetching-associated-records) chapter was fully rewritten. The joining methods `including(required:)` and others are much more detailed, with an exploration of frequent use cases. diff --git a/Documentation/FullTextSearch.md b/Documentation/FullTextSearch.md index c9cb0481e..df9efd1b9 100644 --- a/Documentation/FullTextSearch.md +++ b/Documentation/FullTextSearch.md @@ -304,7 +304,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html): +FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.16/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, @@ -587,7 +587,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html): +FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.16/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index e77e563ca..82cfea890 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -77,7 +77,7 @@ try dbQueue.read { db in } ``` -See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.15/Structs/DatabaseMigrator.html) for more migrator methods. +See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.16/Structs/DatabaseMigrator.html) for more migrator methods. ## The `eraseDatabaseOnSchemaChange` Option diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 953788528..9a24e3624 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '5.15.0' + s.version = '5.16.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/Makefile b/Makefile index 006ecaace..8eb2d7947 100644 --- a/Makefile +++ b/Makefile @@ -488,10 +488,10 @@ ifdef JAZZY --author 'Gwendal Roué' \ --author_url https://github.com/groue \ --github_url https://github.com/groue/GRDB.swift \ - --github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.15.0 \ - --module-version 5.15.0 \ + --github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.16.0 \ + --module-version 5.16.0 \ --module GRDB \ - --root-url http://groue.github.io/GRDB.swift/docs/5.15/ \ + --root-url http://groue.github.io/GRDB.swift/docs/5.16/ \ --output Documentation/Reference \ --xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS else diff --git a/README.md b/README.md index fc5d849d5..0e8e1f6c1 100644 --- a/README.md +++ b/README.md @@ -11,13 +11,13 @@ --- -**Latest release**: December 2, 2021 • [version 5.15.0](https://github.com/groue/GRDB.swift/tree/v5.15.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) +**Latest release**: December 5, 2021 • [version 5.16.0](https://github.com/groue/GRDB.swift/tree/v5.16.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) **Requirements**: iOS 11.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ • SQLite 3.8.5+ • Swift 5.3+ / Xcode 12+ | Swift version | GRDB version | | -------------- | ----------------------------------------------------------- | -| **Swift 5.3+** | **v5.15.0** | +| **Swift 5.3+** | **v5.16.0** | | Swift 5.2 | [v5.12.0](https://github.com/groue/GRDB.swift/tree/v5.12.0) | | Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | | Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | @@ -317,7 +317,7 @@ Documentation #### Reference -- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.15/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) +- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.16/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) #### Getting Started @@ -511,7 +511,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.15/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.16/Structs/Configuration.html) for more details. ## Database Pools @@ -591,7 +591,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.15/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.16/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -651,7 +651,7 @@ try dbQueue.write { db in } ``` -The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.16/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. You can also embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details. @@ -909,7 +909,7 @@ try dbQueue.read { db in let dictionary = try Dictionary(uniqueKeysWithValues: cursor) ``` -- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.15/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: +- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.16/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: ```swift // Prints all Github links @@ -988,7 +988,7 @@ let rows = try Row.fetchAll(db, arguments: ["name": "Arthur"]) ``` -See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.16/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care: @@ -1273,7 +1273,7 @@ GRDB ships with built-in support for the following value types: - Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol. -Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html): +Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.16/Structs/StatementArguments.html): ```swift let url: URL = ... @@ -1720,7 +1720,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction } ``` -Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.15/Structs/Configuration.html) configuration flag: +Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.16/Structs/Configuration.html) configuration flag: ```swift // fatal error: A transaction has been left opened at the end of a database access @@ -1832,7 +1832,7 @@ try dbQueue.write { db in } ``` -The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). +The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.16/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). ```swift insertStatement.arguments = ["name": "Arthur", "score": 1000] @@ -1915,7 +1915,7 @@ See also `Database.execute(sql:)` in the [Executing Updates](#executing-updates) > :point_up: **Note**: it is a programmer error to reuse a prepared statement that has failed: GRDB may crash if you do so. -For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.15/Classes/Statement.html). +For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.16/Classes/Statement.html). ### Prepared Statements Cache @@ -2658,7 +2658,7 @@ try Place.fetchSet(db, sql: "SELECT ...", arguments:...) // Set try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place? ``` -See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html) for more information about the query arguments. +See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.16/Structs/StatementArguments.html) for more information about the query arguments. > :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`. @@ -3098,7 +3098,7 @@ protocol EncodableRecord { } ``` -See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.15/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.15/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies. +See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.16/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.16/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies. ### Date and UUID Coding Strategies @@ -3120,7 +3120,7 @@ protocol EncodableRecord { } ``` -See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.15/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.15/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.15/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. +See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.16/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.16/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.16/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. There is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs and uuid strings, both uppercase and lowercase). @@ -4642,7 +4642,7 @@ Player // SELECT * FROM player ``` -Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html): +Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.16/Structs/StatementArguments.html): ```swift // SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) @@ -5410,7 +5410,7 @@ try Player.customRequest().fetchAll(db) // [Player] - The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method. -- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.15/Structs/AnyFetchRequest.html): a type-erased request. +- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.16/Structs/AnyFetchRequest.html): a type-erased request. ## Joined Queries Support @@ -6700,7 +6700,7 @@ DatabaseRegion helps [ValueObservation] and [DatabaseRegionObservation] track ch For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table. -For more details, see the [reference](https://groue.github.io/GRDB.swift/docs/5.15/Structs/DatabaseRegion.html). +For more details, see the [reference](https://groue.github.io/GRDB.swift/docs/5.16/Structs/DatabaseRegion.html). #### The DatabaseRegionConvertible Protocol @@ -7979,7 +7979,7 @@ When this is the case, there are two possible explanations: try db.execute(sql: "UPDATE player SET name = ?", arguments: [name]) ``` -For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.15/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp). +For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.16/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp). @@ -8120,7 +8120,7 @@ This chapter has [moved](Documentation/Concurrency.md#database-snapshots). #### DatabaseWriter and DatabaseReader Protocols -This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.15/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.15/Protocols/DatabaseWriter.html). +This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.16/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.16/Protocols/DatabaseWriter.html). #### Asynchronous APIs @@ -8168,7 +8168,7 @@ This chapter has [moved](Documentation/Concurrency.md#safe-and-unsafe-database-a [Sharing a Database]: Documentation/SharingADatabase.md [FAQ]: #faq [Database Observation]: #database-changes-observation -[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.15/Structs/SQLRequest.html +[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.16/Structs/SQLRequest.html [SQL literal]: Documentation/SQLInterpolation.md#sql-literal [Identifiable]: https://developer.apple.com/documentation/swift/identifiable [Query Interface Organization]: Documentation/QueryInterfaceOrganization.md diff --git a/Support/Info.plist b/Support/Info.plist index 00dd8a268..2a340505d 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 5.15.0 + 5.16.0 CFBundleSignature ???? CFBundleVersion