Maison  >  Article  >  développement back-end  >  Impossible de générer generate_sort.go à partir de gqlgen-sqlboiler

Impossible de générer generate_sort.go à partir de gqlgen-sqlboiler

PHPz
PHPzavant
2024-02-14 12:00:12658parcourir

无法从 gqlgen-sqlboiler 生成 generated_sort.go

L'éditeur PHP Xinyi a mentionné que parfois, lors de l'utilisation du générateur gqlgen-sqlboiler, vous pouvez rencontrer le problème que le fichier généré_sort.go ne peut pas être généré. Ce problème peut être dû à des erreurs de configuration ou de dépendance. Avant de résoudre ce problème, nous devons vérifier soigneusement le fichier de configuration et les dépendances associées pour nous assurer qu'il n'y a pas d'omissions ou d'erreurs. Parallèlement, nous pouvons également essayer de mettre à jour les versions du générateur et des bibliothèques associées pour résoudre d'éventuels bugs. Si le problème persiste, nous pouvons demander de l'aide à la communauté pour voir si quelqu'un d'autre a rencontré le même problème et a trouvé une solution. Dans l’ensemble, résoudre ce problème nécessite de la patience et de l’attention, et en dépannant et en essayant différentes solutions, nous pourrons, espérons-le, trouver une solution efficace.

Contenu de la question

J'utilise version de SQLBoiler : v4.14.2 version gqlgen : v0.17.33 version de gqlgen-sqlboiler : v3.3.12 https://github.com/web-ridge/gqlgen-sqlboiler

Après avoir suivi les prérequis readme.md, j'obtiens l'erreur suivante lors de l'exécution de convert.go Ce qui suit est convert.go

package main

import (
    "github.com/99designs/gqlgen/codegen/config"
    "github.com/rs/zerolog/log"
    gbgen "github.com/web-ridge/gqlgen-sqlboiler/v3"
    "github.com/web-ridge/gqlgen-sqlboiler/v3/cache"
    "github.com/web-ridge/gqlgen-sqlboiler/v3/structs"
    "os"
    "os/exec"
    "strings"
)

func main() {
    // change working directory to parent directory where all configs are located
    newdir, _ := os.getwd()
    os.chdir(strings.trimsuffix(newdir, "/convert"))

    enablesoftdeletes := true
    boilerargs := []string{"mysql", "--no-back-referencing", "--wipe", "-d"}
    if enablesoftdeletes {
        boilerargs = append(boilerargs, "--add-soft-deletes")
    }
    cmd := exec.command("sqlboiler", boilerargs...)

    err := cmd.run()
    if err != nil {
        log.fatal().err(err).str("command", cmd.string()).msg("error generating dm models running sql-boiler")
    }

    output := structs.config{
        directory:   "helpers", // supports root or sub directories
        packagename: "helpers",
    }
    backend := structs.config{
        directory:   "models",
        packagename: "models",
    }
    frontend := structs.config{
        directory:   "models",
        packagename: "models",
    }

    boilercache := cache.initializeboilercache(backend)

    generateschema := true
    generatedschema := !generateschema
    if generateschema {
        if err := gbgen.schemawrite(
            gbgen.schemaconfig{
                boilercache:         boilercache,
                directives:          []string{"isauthenticated"},
                skipinputfields:     []string{"createdat", "updatedat", "deletedat"},
                generatemutations:   true,
                generatebatchcreate: false,
                generatebatchdelete: false,
                generatebatchupdate: false,
                hookshouldaddmodel: func(model gbgen.schemamodel) bool {
                    if model.name == "config" {
                        return false
                    }
                    return true
                },
                hookchangefields: func(model *gbgen.schemamodel, fields []*gbgen.schemafield, parentype gbgen.parenttype) []*gbgen.schemafield {
                    //profile: userpayload! @isauthenticated

                    return fields
                },
                hookchangefield: func(model *gbgen.schemamodel, field *gbgen.schemafield) {
                    //"userid", "userorganizationid",
                    if field.name == "userid" && model.name != "useruserorganization" {
                        field.skipinput = true
                    }
                    if field.name == "userorganizationid" && model.name != "useruserorganization" {
                        field.skipinput = true
                    }
                },
            },
            "../schema.graphql",
            gbgen.schemagenerateconfig{
                mergeschema: false,
            },
        ); err != nil {
            log.fatal().err(err).msg("error generating schema")
        }
        generatedschema = true
    }
    if generatedschema {

        cfg, err := config.loadconfigfromdefaultlocations()
        if err != nil {
            log.fatal().err(err).msg("error loading config")
        }

        data, err := gbgen.newmodelplugin().generatecode(cfg)
        if err != nil {
            log.fatal().err(err).msg("error generating graphql models using gqlgen")
        }

        modelcache := cache.initializemodelcache(cfg, boilercache, output, backend, frontend)

        if err := gbgen.newconvertplugin(
            modelcache,
            gbgen.convertpluginconfig{
                databasedriver: gbgen.mysql,
                //searchable: {
                //  company: {
                //      column: dm.companycolumns.name
                //  },
                //},
            },
        ).generatecode(); err != nil {
            log.fatal().err(err).msg("error while generating convert/filters")
        }

        if err := gbgen.newresolverplugin(
            config.resolverconfig{
                filename: "resolvers/all_generated_resolvers.go",
                package:  "resolvers",
                type:     "resolver",
            },
            output,
            boilercache,
            modelcache,
            gbgen.resolverpluginconfig{

                enablesoftdeletes: enablesoftdeletes,
                // authorization scopes can be used to override e.g. userid, organizationid, tenantid
                // this will be resolved used the provided scoperesolvername if the result of the addtrigger=true
                // you would need this if you don't want to require these fields in your schema but you want to add them
                // to the db model.
                // if you do have these fields in your schema but want them authorized you could use a gqlgen directive
                authorizationscopes: []*gbgen.authorizationscope{},
                //  {
                //      importpath:        "github.com/my-repo/app/backend/auth",
                //      importalias:       "auth",
                //      scoperesolvername: "useridfromcontext", // function which is called with the context of the resolver
                //      boilercolumnname:  "userid",
                //      addhook: func(model *gbgen.boilermodel, resolver *gbgen.resolver, templatekey string) bool {
                //          // fmt.println(model.name)
                //          // fmt.println(templatekey)
                //          // templatekey contains a unique where the resolver tries to add something
                //          // e.g.
                //          // most of the time you can ignore this

                //          // we want the delete call to work for every object we don't want to take in account te user-id here
                //          if resolver.isdelete {
                //              return false
                //          }

                //          var addresolver bool
                //          for _, field := range model.fields {
                //              if field.name == "userid" {
                //                  addresolver = true
                //              }
                //          }
                //          return addresolver
                //      },
                //  },
                //  {
                //      importpath:        "github.com/my-repo/app/backend/auth",
                //      importalias:       "auth",
                //      scoperesolvername: "userorganizationidfromcontext", // function which is called with the context of the resolver
                //      boilercolumnname:  "userorganizationid",

                //      addhook: func(model *gbgen.boilermodel, resolver *gbgen.resolver, templatekey string) bool {
                //          // fmt.println(model.name)
                //          // fmt.println(templatekey)
                //          // templatekey contains a unique where the resolver tries to add something
                //          // e.g.
                //          // most of the time you can ignore this
                //          var addresolver bool
                //          for _, field := range model.fields {
                //              if field.name == "userorganizationid" {
                //                  addresolver = true
                //              }
                //          }
                //          return addresolver
                //      },
                //  },
                // },
            },
        ).generatecode(data); err != nil {
            log.fatal().err(err).msg("error while generating resolvers")
        }

    }
}

Ce qui suit est le journal

go run convert/convert.go
4:10PM DBG [boiler-cache] building cache
4:10PM DBG [boiler-cache] built cache!
4:10PM DBG write GraphQL schema to disk bytes=3918
file=../schema.graphql
4:10PM DBG formatting GraphQL schema
../schema.graphql 71ms 4:10PM DBG formatted GraphQL schema
4:10PM DBG [model-cache] get structs
4:10PM DBG [model-cache] get extra's from schema
4:10PM DBG [model-cache] enhance structs with information
4:10PM DBG [model-cache] built cache!
4:10PM DBG [convert] render generated_convert.gotpl
4:10PM DBG [convert] rendered generated_convert.gotpl
4:10PM DBG [convert] render generated_convert_batch.gotpl
4:10PM DBG [convert] rendered generated_convert_batch.gotpl
4:10PM DBG [convert] render generated_convert_input.gotpl
4:10PM DBG [convert] rendered generated_convert_input.gotpl
4:10PM DBG [convert] render generated_filter.gotpl
4:10PM DBG [convert] rendered generated_filter.gotpl
4:10PM DBG [convert] render generated_preload.gotpl
4:10PM DBG [convert] rendered generated_preload.gotpl
4:10PM DBG [convert] render generated_sort.gotpl
4:10PM ERR could not parse golang file error="src.go:1:1: expected
'package', found 'EOF'"
4:10PM ERR error while rendering generated_sort.gotpl error="errors
while writing template to helpers/generated_sort.go writeError: ,
contentError: execute: template: :44:17: executing "" at
<$field.Enum.Name>: nil pointer evaluating *structs.Enum.Name,
importError: helpers/generated_sort.go:1:1: expected 'package', found
'EOF'"
4:10PM DBG [convert] rendered generated_sort.gotpl
4:10PM ERR could not parse golang file error="src.go:1:1: expected
'package', found 'EOF'"
4:10PM ERR could not close file error="invalid argument"
fileName=resolvers/all_generated_resolvers.go
4:10PM FTL error while generating resolvers error="errors while
printing template to resolvers/all_generated_resolvers.go  invalid
argument"
exit status 1

Veuillez aider à résoudre ce problème ?

Solution de contournement

Résolu le problème en mappant le bon répertoire. convert.go sur le côté Lors de la création d'une structure dans convert.go

//output représente le dossier dans lequel les fichiers seront générés à partir de gqlgen-sqlboiler

output := structs.config{
        directory:   "helpers", // supports root or sub directories
        packagename: "helpers",
    }

//backend est le dossier dans lequel tous les modèles sqlboiler sont générés

backend := structs.config{
    directory:   "models",
    packagename: "models",
}

//! ! ! Le frontal important est le dossier dans lequel gqlgen génère tous les fichiers graphql

frontend := structs.Config{
    Directory:   "graph",
    PackageName: "graph",
}

Erreur de mappage des dossiers front-end.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer