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

codegen: support predicate arguments #178

Merged
merged 4 commits into from
Jan 16, 2025
Merged
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
138 changes: 86 additions & 52 deletions cmd/hasura-ndc-go/command/internal/connector.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,11 @@ func ParseAndGenerateConnector(args ConnectorGenerationArguments, moduleName str
if err != nil {
return fmt.Errorf("failed to create trace file at %s", args.Trace)
}

defer func() {
_ = w.Close()
}()

if err = trace.Start(w); err != nil {
return fmt.Errorf("failed to start trace: %w", err)
}
Expand All @@ -115,10 +117,12 @@ func ParseAndGenerateConnector(args ConnectorGenerationArguments, moduleName str
typeBuilders: make(map[string]*connectorTypeBuilder),
typeOnly: args.TypeOnly,
}

connectorPkgName, err := connectorGen.loadConnectorPackage()
if err != nil {
return err
}

return connectorGen.generateConnector(connectorPkgName)
}

Expand Down Expand Up @@ -315,8 +319,15 @@ func (cg *connectorGenerator) writeToMapProperty(sb *connectorTypeBuilder, field
switch t := ty.(type) {
case *NullableType:
sb.builder.WriteString(fmt.Sprintf(" if %s != nil {\n", selector))
propName := cg.writeToMapProperty(sb, field, fmt.Sprintf("(*%s)", selector), assigner, t.UnderlyingType)
newSelector := selector

if t.UnderlyingType.Kind() != schema.TypePredicate {
newSelector = fmt.Sprintf("(*%s)", selector)
}

propName := cg.writeToMapProperty(sb, field, newSelector, assigner, t.UnderlyingType)
sb.builder.WriteString(" }\n")

return propName
case *ArrayType:
varName := formatLocalFieldName(selector)
Expand All @@ -326,6 +337,7 @@ func (cg *connectorGenerator) writeToMapProperty(sb *connectorTypeBuilder, field
cg.writeToMapProperty(sb, field, valueName, varName+"[i]", t.ElementType)
sb.builder.WriteString(" }\n")
sb.builder.WriteString(fmt.Sprintf(" %s = %s\n", assigner, varName))

return varName
case *NamedType:
innerObject, ok := cg.rawSchema.Objects[t.Name]
Expand All @@ -339,16 +351,23 @@ func (cg *connectorGenerator) writeToMapProperty(sb *connectorTypeBuilder, field
sb.builder.WriteString(fmt.Sprintf(" %s := make(map[string]any)\n", varName))
cg.writeObjectToMap(sb, &innerObject, selector, varName)
sb.builder.WriteString(fmt.Sprintf(" %s = %s\n", assigner, varName))

return varName
}

if !field.Embedded {
sb.builder.WriteString(fmt.Sprintf(" %s = %s\n", assigner, selector))

return selector
}

sb.imports[packageSDKUtils] = ""
sb.builder.WriteString(fmt.Sprintf(" r = utils.MergeMap(r, %s.ToMap())\n", selector))

return selector
case *PredicateType:
sb.builder.WriteString(fmt.Sprintf(" %s = %s\n", assigner, selector))

return selector
default:
panic(fmt.Errorf("failed to write the ToMap method; invalid type: %s", ty))
Expand Down Expand Up @@ -549,6 +568,7 @@ func (cg *connectorGenerator) writeGetTypeValueDecoder(sb *connectorTypeBuilder,
fieldName := field.Name
typeName := ty.String()
fullTypeName := ty.FullName()

if strings.Contains(typeName, "complex64") || strings.Contains(typeName, "complex128") || strings.Contains(typeName, "time.Duration") {
panic(fmt.Errorf("unsupported type: %s", typeName))
}
Expand Down Expand Up @@ -644,68 +664,82 @@ func (cg *connectorGenerator) writeGetTypeValueDecoder(sb *connectorTypeBuilder,
cg.writeScalarDecodeValue(sb, fieldName, "GetArbitraryJSONPtrSlice", "", key, objectField, false)
case "*[]*any", "*[]*interface{}":
cg.writeScalarDecodeValue(sb, fieldName, "GetNullableArbitraryJSONPtrSlice", "", key, objectField, true)
case fmt.Sprintf("*%s.Expression", packageSDKSchema):
cg.writeScalarDecodeValue(sb, fieldName, "GetNullableUUID", "", key, objectField, true)
default:
sb.imports[packageSDKUtils] = ""
sb.builder.WriteString(" j.")
sb.builder.WriteString(fieldName)
sb.builder.WriteString(", err = utils.")
switch t := ty.(type) {
case *NullableType:
var tyName string
var packagePaths []string
if t.IsAnonymous() {
tyName, packagePaths = cg.getAnonymousObjectTypeName(sb, field.TypeAST, true)
} else {
packagePaths = getTypePackagePaths(t.UnderlyingType, sb.packagePath)
tyName = getTypeArgumentName(t.UnderlyingType, sb.packagePath, false)
}
for _, pkgPath := range packagePaths {
sb.imports[pkgPath] = ""
}
if field.Embedded {
sb.builder.WriteString("DecodeNullableObject[")
sb.builder.WriteString(tyName)
sb.builder.WriteString("](input)")
} else {
sb.builder.WriteString("DecodeNullableObjectValue[")
sb.builder.WriteString(tyName)
sb.builder.WriteString(`](input, "`)
sb.builder.WriteString(key)
sb.builder.WriteString(`")`)
}
default:
var tyName string
var packagePaths []string
if t.IsAnonymous() {
tyName, packagePaths = cg.getAnonymousObjectTypeName(sb, field.TypeAST, true)
} else {
packagePaths = getTypePackagePaths(ty, sb.packagePath)
tyName = getTypeArgumentName(ty, sb.packagePath, false)
}
for _, pkgPath := range packagePaths {
sb.imports[pkgPath] = ""

t := ty
var tyName string
var packagePaths []string

if nt, ok := ty.(*NullableType); ok {
if nt.UnderlyingType.Kind() != schema.TypePredicate {
if nt.IsAnonymous() {
tyName, packagePaths = cg.getAnonymousObjectTypeName(sb, field.TypeAST, true)
} else {
packagePaths = getTypePackagePaths(nt.UnderlyingType, sb.packagePath)
tyName = getTypeArgumentName(nt.UnderlyingType, sb.packagePath, false)
}

for _, pkgPath := range packagePaths {
sb.imports[pkgPath] = ""
}

if field.Embedded {
sb.builder.WriteString("DecodeNullableObject[")
sb.builder.WriteString(tyName)
sb.builder.WriteString("](input)")
} else {
sb.builder.WriteString("DecodeNullableObjectValue[")
sb.builder.WriteString(tyName)
sb.builder.WriteString(`](input, "`)
sb.builder.WriteString(key)
sb.builder.WriteString(`")`)
}

break
}

if field.Embedded {
sb.builder.WriteString("DecodeObject")
sb.builder.WriteRune('[')
sb.builder.WriteString(tyName)
sb.builder.WriteString("](input)")
} else {
sb.builder.WriteString("DecodeObjectValue")
if len(objectField.Type) > 0 {
if typeEnum, err := objectField.Type.Type(); err == nil && typeEnum == schema.TypeNullable {
sb.builder.WriteString("Default")
}
t = nt.UnderlyingType
}

if t.IsAnonymous() {
tyName, packagePaths = cg.getAnonymousObjectTypeName(sb, field.TypeAST, true)
} else {
packagePaths = getTypePackagePaths(t, sb.packagePath)
tyName = getTypeArgumentName(t, sb.packagePath, false)
}

for _, pkgPath := range packagePaths {
sb.imports[pkgPath] = ""
}

if field.Embedded {
sb.builder.WriteString("DecodeObject")
sb.builder.WriteRune('[')
sb.builder.WriteString(tyName)
sb.builder.WriteString("](input)")
} else {
sb.builder.WriteString("DecodeObjectValue")

if len(objectField.Type) > 0 {
if typeEnum, err := objectField.Type.Type(); err == nil && typeEnum == schema.TypeNullable {
sb.builder.WriteString("Default")
}
sb.builder.WriteRune('[')
sb.builder.WriteString(tyName)
sb.builder.WriteString(`](input, "`)
sb.builder.WriteString(key)
sb.builder.WriteString(`")`)
}

sb.builder.WriteRune('[')
sb.builder.WriteString(tyName)
sb.builder.WriteString(`](input, "`)
sb.builder.WriteString(key)
sb.builder.WriteString(`")`)
}
}

writeErrorCheck(sb.builder, 1, 2)
}

Expand Down
2 changes: 1 addition & 1 deletion cmd/hasura-ndc-go/command/internal/connector_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func (chb connectorHandlerBuilder) Render() {
bs.imports["log/slog"] = ""
bs.imports["slices"] = ""
bs.imports["github.com/hasura/ndc-sdk-go/connector"] = ""
bs.imports["github.com/hasura/ndc-sdk-go/schema"] = ""
bs.imports[packageSDKSchema] = ""
bs.imports["go.opentelemetry.io/otel/trace"] = ""
bs.imports[packageSDKUtils] = ""

Expand Down
3 changes: 2 additions & 1 deletion cmd/hasura-ndc-go/command/internal/constant.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,5 +154,6 @@ var (
)

const (
packageSDKUtils = "github.com/hasura/ndc-sdk-go/utils"
packageSDKUtils = "github.com/hasura/ndc-sdk-go/utils"
packageSDKSchema = "github.com/hasura/ndc-sdk-go/schema"
)
56 changes: 56 additions & 0 deletions cmd/hasura-ndc-go/command/internal/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package internal
import (
"fmt"
"go/types"
"slices"
"strings"

"github.com/hasura/ndc-sdk-go/schema"
)
Expand Down Expand Up @@ -150,6 +152,41 @@ func (t *NamedType) String() string {
return t.NativeType.String()
}

// PredicateType the information of a predicate type
type PredicateType struct {
ObjectName string
}

var _ Type = &PredicateType{}

func NewPredicateType(name string) *PredicateType {
return &PredicateType{name}
}

func (t *PredicateType) Kind() schema.TypeEnum {
return schema.TypePredicate
}

func (t *PredicateType) IsAnonymous() bool {
return false
}

func (t *PredicateType) Schema() schema.TypeEncoder {
return schema.NewPredicateType(t.ObjectName)
}

func (t PredicateType) SchemaName(_ bool) string {
return t.String()
}

func (t PredicateType) FullName() string {
return t.String()
}

func (t *PredicateType) String() string {
return "Predicate<" + t.ObjectName + ">"
}

// TypeInfo represents the serialization information of a type.
type TypeInfo struct {
Name string
Expand Down Expand Up @@ -328,16 +365,27 @@ func (rcs RawConnectorSchema) Schema() *schema.SchemaResponse {
for key, item := range rcs.Scalars {
result.ScalarTypes[key] = item.Schema
}

for _, obj := range rcs.Objects {
result.ObjectTypes[obj.Type.SchemaName] = *obj.Schema()
}

for _, function := range rcs.Functions {
result.Functions = append(result.Functions, function.Schema())
}

slices.SortFunc(result.Functions, func(a, b schema.FunctionInfo) int {
return strings.Compare(a.Name, b.Name)
})

for _, procedure := range rcs.Procedures {
result.Procedures = append(result.Procedures, procedure.Schema())
}

slices.SortFunc(result.Procedures, func(a, b schema.ProcedureInfo) int {
return strings.Compare(a.Name, b.Name)
})

return result
}

Expand Down Expand Up @@ -382,6 +430,12 @@ func getTypeArgumentName(input Type, packagePath string, isAbsolute bool) string
return "[]" + getTypeArgumentName(t.ElementType, packagePath, isAbsolute)
case *NamedType:
return t.NativeType.getArgumentName(packagePath, isAbsolute)
case *PredicateType:
if isAbsolute {
return fmt.Sprintf("%s.%s", packageSDKSchema, "Expression")
}

return "schema.Expression"
default:
panic(fmt.Errorf("getTypeArgumentName: invalid type %v", input))
}
Expand All @@ -395,6 +449,8 @@ func getTypePackagePaths(input Type, currentPackagePath string) []string {
return getTypePackagePaths(t.ElementType, currentPackagePath)
case *NamedType:
return t.NativeType.GetPackagePaths(currentPackagePath)
case *PredicateType:
return []string{packageSDKSchema}
default:
panic(fmt.Errorf("getTypePackagePaths: invalid type %v", input))
}
Expand Down
4 changes: 2 additions & 2 deletions cmd/hasura-ndc-go/command/internal/schema_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ func (sp *SchemaParser) parsePackageScope(pkg *types.Package, name string) error
// ignore 2 first parameters (context and state)
if params.Len() == 3 {
arg := params.At(2)
argumentParser := NewTypeParser(sp, &Field{}, arg.Type(), &opInfo.Kind)
argumentParser := NewTypeParser(sp, &Field{}, arg.Type(), NDCTagInfo{}, &opInfo.Kind)
argumentInfo, err := argumentParser.ParseArgumentTypes([]string{})
if err != nil {
return err
Expand All @@ -236,7 +236,7 @@ func (sp *SchemaParser) parsePackageScope(pkg *types.Package, name string) error
}
}

typeParser := NewTypeParser(sp, &Field{}, resultTuple.At(0).Type(), nil)
typeParser := NewTypeParser(sp, &Field{}, resultTuple.At(0).Type(), NDCTagInfo{}, nil)
resultType, err := typeParser.Parse([]string{})
if err != nil {
return err
Expand Down
2 changes: 2 additions & 0 deletions cmd/hasura-ndc-go/command/internal/schema_template.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,8 @@ func (rcs RawConnectorSchema) writeType(schemaType schema.Type, depth uint) (str
result += fmt.Sprintf("NewNullableType(%s)", nested)
case *schema.NamedType:
result += fmt.Sprintf(`NewNamedType("%s")`, t.Name)
case *schema.PredicateType:
result += fmt.Sprintf(`NewPredicateType("%s")`, t.ObjectTypeName)
default:
return "", fmt.Errorf("invalid schema type: %w", err)
}
Expand Down
Loading
Loading