findonebyfield.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package gen
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/tal-tech/go-zero/tools/goctl/model/sql/template"
  6. "github.com/tal-tech/go-zero/tools/goctl/util"
  7. "github.com/tal-tech/go-zero/tools/goctl/util/stringx"
  8. )
  9. func genFindOneByField(table Table, withCache bool) (string, string, error) {
  10. t := util.With("findOneByField").Parse(template.FindOneByField)
  11. var list []string
  12. camelTableName := table.Name.ToCamel()
  13. for _, field := range table.Fields {
  14. if field.IsPrimaryKey || !field.IsUniqueKey {
  15. continue
  16. }
  17. camelFieldName := field.Name.ToCamel()
  18. output, err := t.Execute(map[string]interface{}{
  19. "upperStartCamelObject": camelTableName,
  20. "upperField": camelFieldName,
  21. "in": fmt.Sprintf("%s %s", stringx.From(camelFieldName).UnTitle(), field.DataType),
  22. "withCache": withCache,
  23. "cacheKey": table.CacheKey[field.Name.Source()].KeyExpression,
  24. "cacheKeyVariable": table.CacheKey[field.Name.Source()].Variable,
  25. "primaryKeyLeft": table.CacheKey[table.PrimaryKey.Name.Source()].Left,
  26. "lowerStartCamelObject": stringx.From(camelTableName).UnTitle(),
  27. "lowerStartCamelField": stringx.From(camelFieldName).UnTitle(),
  28. "upperStartCamelPrimaryKey": table.PrimaryKey.Name.ToCamel(),
  29. "originalField": field.Name.Source(),
  30. })
  31. if err != nil {
  32. return "", "", err
  33. }
  34. list = append(list, output.String())
  35. }
  36. if withCache {
  37. out, err := util.With("findOneByFieldExtraMethod").Parse(template.FindOneByFieldExtraMethod).Execute(map[string]interface{}{
  38. "upperStartCamelObject": camelTableName,
  39. "lowerStartCamelObject": stringx.From(camelTableName).UnTitle(),
  40. "originalPrimaryField": table.PrimaryKey.Name.Source(),
  41. })
  42. if err != nil {
  43. return "", "", err
  44. }
  45. return strings.Join(list, "\n"), out.String(), nil
  46. }
  47. return strings.Join(list, "\n"), "", nil
  48. }