Skip to content

Commit

Permalink
Remove new types from IM cache on generate error
Browse files Browse the repository at this point in the history
Previously they would hang around until database restart - corrupting the schema and preventing schema correction
  • Loading branch information
AndrewSisley committed Jan 18, 2022
1 parent 2c03d29 commit 978d6a4
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
29 changes: 28 additions & 1 deletion query/graphql/schema/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,36 @@ func (g *Generator) FromSDL(schema string) ([]*gql.Object, *ast.Document, error)
return types, doc, err
}

func (g *Generator) FromAST(document *ast.Document) ([]*gql.Object, error) {
typeMapBeforeMutation := g.manager.schema.TypeMap()
typesBeforeMutation := make(map[string]interface{}, len(typeMapBeforeMutation))

for typeName := range typeMapBeforeMutation {
typesBeforeMutation[typeName] = struct{}{}
}

result, err := g.fromAST(document)

if err != nil {
// If there is an error we should drop any new objects as they may be partial, poluting the in memory cache
// This is quite a simple check at the moment (on type name) - this should be expanded when we allow schema mutation/deletion
// There is no guarantee that `typeMapBeforeMutation` will still be the object returned by `schema.TypeMap()`, so we should re-fetch it
typeMapAfterMutation := g.manager.schema.TypeMap()
for typeName := range typeMapAfterMutation {
if _, typeExistedBeforeMutation := typesBeforeMutation[typeName]; !typeExistedBeforeMutation {
delete(typeMapAfterMutation, typeName)
}
}

return nil, err
}

return result, nil
}

// FromAST generates the query type definitions from a
// parsed GraphQL Schema Definition Language AST document
func (g *Generator) FromAST(document *ast.Document) ([]*gql.Object, error) {
func (g *Generator) fromAST(document *ast.Document) ([]*gql.Object, error) {
// build base types
defs, err := g.buildTypesFromAST(document)
if err != nil {
Expand Down
17 changes: 17 additions & 0 deletions query/graphql/schema/generate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,23 @@ func Test_Generator_buildTypesFromAST_SingleScalarField(t *testing.T) {
}, "")
}

func Test_Generator_CleansUpInvalidTypes_GivenInvalidFieldType(t *testing.T) {
g := newTestGenerator()

runTestConfigForbuildTypesFromASTSuite(t, g,
`
type MyObject {
myField: string,
myOtherField: String
}
`,
[]*gql.Object{},
"No type found for given name: string")

_, exists := g.manager.schema.TypeMap()["MyObject"]
assert.False(t, exists, "Invalid object was not cleaned from type map")
}

func Test_Generator_buildTypesFromAST_SingleNonNullScalarField(t *testing.T) {
g := newTestGenerator()

Expand Down

0 comments on commit 978d6a4

Please sign in to comment.