Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(datastore): fix has-one associations #1676

Draft
wants to merge 9 commits into
base: v1
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,17 @@ public enum ModelAssociation {
return .belongsTo(associatedFieldName: associatedWith?.stringValue, targetName: targetName)
}

/// Convenience method to access the `targetName` for those associations that have one (currently `.belongsTo` and `.hasOne`).
/// Returns `nil` for associations that don't have an explicit target name.
public func targetName() -> String? {
switch self {
case .belongsTo(_, let targetName),
.hasOne(_, let targetName):
return targetName
case .hasMany:
return nil
}
}
}

extension ModelField {
Expand Down Expand Up @@ -207,10 +218,19 @@ extension ModelField {
/// application making any change to these `public` types should be backward compatible, otherwise it will be a
/// breaking change.
public var isAssociationOwner: Bool {
guard case .belongsTo = association else {
switch association {
case .belongsTo:
return true
case .hasOne:
// in case of a bi-directional association
// we pick the model with a belongs-to
if case .belongsTo = associatedField?.association {
return false
}
return true
default:
return false
}
return true
}

/// - Warning: Although this has `public` access, it is intended for internal & codegen use and should not be used
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ public struct ModelSchema {

public let sortedFields: [ModelField]

/// Lazy view of associations target names
public var associationsTargets: Set<ModelFieldName>

public var primaryKey: ModelField {
guard let primaryKey = fields.first(where: { $1.isPrimaryKey }) else {
preconditionFailure("Primary Key not defined for `\(name)`")
Expand All @@ -110,6 +113,8 @@ public struct ModelSchema {
self.fields = fields

self.sortedFields = fields.sortedFields()

self.associationsTargets = Set(sortedFields.compactMap { $0.association?.targetName() })
}

public func field(withName name: String) -> ModelField? {
Expand Down
2 changes: 1 addition & 1 deletion AmplifyPlugins/API/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,4 @@ SPEC CHECKSUMS:

PODFILE CHECKSUM: 54e87158e45936fe60756d4a417b89eb64ea1c51

COCOAPODS: 1.10.1
COCOAPODS: 1.11.2
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ extension Model {
/// used as the `input` of GraphQL related operations.
func graphQLInputForMutation(_ modelSchema: ModelSchema) -> GraphQLInput {
var input: GraphQLInput = [:]
modelSchema.fields.forEach {
let modelField = $0.value
modelSchema.sortedFields.forEach { modelField in

// When the field is read-only don't add it to the GraphQL input object
if modelField.isReadOnly {
Expand Down Expand Up @@ -93,8 +92,7 @@ extension Model {
private func fixHasOneAssociationsWithExplicitFieldOnModel(_ input: GraphQLInput,
modelSchema: ModelSchema) -> GraphQLInput {
var input = input
modelSchema.fields.forEach {
let modelField = $0.value
modelSchema.sortedFields.forEach { modelField in
if case .model = modelField.type,
case .hasOne = modelField.association,
input.keys.contains(modelField.name) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ class AWSAuthServiceBehaviorTests: XCTestCase {
}
}

fileprivate class _MockAWSAuthService: AWSAuthServiceBehavior {
private class _MockAWSAuthService: AWSAuthServiceBehavior {
let identityID: () -> Result<String, AuthError>
let userPoolAccessToken: () -> Result<String, AuthError>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ class GraphQLCreateMutationTests: XCTestCase {
override func setUp() {
ModelRegistry.register(modelType: Comment.self)
ModelRegistry.register(modelType: Post.self)
ModelRegistry.register(modelType: Project2V2.self)
ModelRegistry.register(modelType: Team2V2.self)
ModelRegistry.register(modelType: Record.self)
ModelRegistry.register(modelType: RecordCover.self)
Comment on lines +19 to +22
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

those models were missing, so the selection set in queries wasn't properly generated (see GraphQL queries below)

}

override func tearDown() {
Expand Down Expand Up @@ -236,6 +240,66 @@ class GraphQLCreateMutationTests: XCTestCase {
XCTAssertEqual(input["commentPostId"] as? String, post.id)
}

/// - Given: a `Model` instance
/// - When:
/// - the model is of type `Project2V2`
/// - the model has an `hasOne` associations
/// - the mutation is of type `.create`
/// - Then:
/// - check if the generated GraphQL document is a valid mutation:
/// - it is named `CreateProject2`
/// - it contains an `input` of type `CreateProject2V2Input`
/// - it has a list of fields with a `teamId`
func testCreateGraphQLMutationFromModelWithHasOneAssociationWithSyncEnabled() {
let team = Team1V2(name: "team1v2")
let project = Project1V2(name: "project1v2", team: team)

var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: Project2V2.schema,
operationType: .mutation)
documentBuilder.add(decorator: DirectiveNameDecorator(type: .create))
documentBuilder.add(decorator: ModelDecorator(model: project))
documentBuilder.add(decorator: ConflictResolutionDecorator())
let document = documentBuilder.build()
let expectedQueryDocument = """
mutation CreateProject2V2($input: CreateProject2V2Input!) {
createProject2V2(input: $input) {
id
createdAt
name
teamID
updatedAt
team {
id
createdAt
name
updatedAt
__typename
_version
_deleted
_lastChangedAt
}
__typename
_version
_deleted
_lastChangedAt
}
}
"""
XCTAssertEqual(document.name, "createProject2V2")
XCTAssertEqual(document.stringValue, expectedQueryDocument)
guard let variables = document.variables else {
XCTFail("The document doesn't contain variables")
return
}
guard let input = variables["input"] as? GraphQLInput else {
XCTFail("Variables should contain a valid input")
return
}
XCTAssertEqual(input["id"] as? String, project.id)
XCTAssertEqual(input["name"] as? String, project.name)
XCTAssertEqual(input["teamID"] as? String, team.id)
}

func testCreateGraphQLMutationFromModelWithReadonlyFields() {
let recordCover = RecordCover(artist: "artist")
let record = Record(name: "name", description: "description", cover: recordCover)
Expand All @@ -254,6 +318,16 @@ class GraphQLCreateMutationTests: XCTestCase {
description
name
updatedAt
cover {
id
artist
createdAt
updatedAt
__typename
_version
_deleted
_lastChangedAt
}
__typename
_version
_deleted
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ class GraphQLDeleteMutationTests: XCTestCase {
override func setUp() {
ModelRegistry.register(modelType: Comment.self)
ModelRegistry.register(modelType: Post.self)
ModelRegistry.register(modelType: Record.self)
ModelRegistry.register(modelType: RecordCover.self)
}

override func tearDown() {
Expand Down Expand Up @@ -137,6 +139,16 @@ class GraphQLDeleteMutationTests: XCTestCase {
description
name
updatedAt
cover {
id
artist
createdAt
updatedAt
__typename
_version
_deleted
_lastChangedAt
}
__typename
_version
_deleted
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ class GraphQLGetQueryTests: XCTestCase {
override func setUp() {
ModelRegistry.register(modelType: Comment.self)
ModelRegistry.register(modelType: Post.self)
ModelRegistry.register(modelType: Record.self)
ModelRegistry.register(modelType: RecordCover.self)
}

/// - Given: a `Model` type
Expand Down Expand Up @@ -198,6 +200,13 @@ class GraphQLGetQueryTests: XCTestCase {
description
name
updatedAt
cover {
id
artist
createdAt
updatedAt
__typename
}
__typename
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ class GraphQLUpdateMutationTests: XCTestCase {
override func setUp() {
ModelRegistry.register(modelType: Comment.self)
ModelRegistry.register(modelType: Post.self)
ModelRegistry.register(modelType: Record.self)
ModelRegistry.register(modelType: RecordCover.self)
}

override func tearDown() {
Expand Down Expand Up @@ -141,6 +143,16 @@ class GraphQLUpdateMutationTests: XCTestCase {
description
name
updatedAt
cover {
id
artist
createdAt
updatedAt
__typename
_version
_deleted
_lastChangedAt
}
__typename
_version
_deleted
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,20 @@ extension ModelSchema {
/// the owner of a foreign key to another `Model`. Fields that reference the inverse side of
/// the relationship (i.e. the "one" side of a "one-to-many" relationship) are excluded.
var columns: [ModelField] {
sortedFields.filter { !$0.hasAssociation || $0.isForeignKey }
return sortedFields.filter {
!$0.hasAssociation || $0.isForeignKey
}
}

/// This is a temporary workaround to circumvent a Codegen issue where
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we add a link to more information to track the removal of this temp workaround? perhaps an issue in our repo to describe the situation

/// both the field representing an association and its target are explicitly emitted.
/// Warning: don't use it unless necessary, it will be removed in future releases.
/// Returns fields that represent actual columns on the SQL table.
/// It also exclude explicit fields that are referenced as an association target
/// (i.e. team: Team => teamId: ID).
var columnsUnique: [ModelField] {
return columns
.filter { !associationsTargets.contains($0.name) }
}

/// Filter the fields that represent foreign keys.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ struct CreateTableStatement: SQLStatement {
var stringValue: String {
let name = modelSchema.name
var statement = #"create table if not exists "\#(name)" (\#n"#

let columns = modelSchema.columns
let columns = modelSchema.columnsUnique
let foreignKeys = modelSchema.foreignKeys

for (index, column) in columns.enumerated() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,12 @@ struct InsertStatement: SQLStatement {

init(model: Model, modelSchema: ModelSchema) {
self.modelSchema = modelSchema
self.variables = model.sqlValues(for: modelSchema.columns, modelSchema: modelSchema)
self.variables = model.sqlValues(for: modelSchema.columnsUnique,
modelSchema: modelSchema)
}

var stringValue: String {
let fields = modelSchema.columns
let fields = modelSchema.columnsUnique
let columns = fields.map { $0.columnName() }
var statement = "insert into \"\(modelSchema.name)\" "
statement += "(\(columns.joined(separator: ", ")))\n"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class DataStoreConnectionScenario2FlutterTests: SyncEngineFlutterIntegrationTest
return
}
let saveTeamCompleted = expectation(description: "save team completed")
plugin.save(team.model, modelSchema: Team1.schema) { result in
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed as in this scenario we are testing models Team2 and Project2

plugin.save(team.model, modelSchema: Team2.schema) { result in
switch result {
case .success:
saveTeamCompleted.fulfill()
Expand Down
Loading