github.com/kunlun-qilian/sqlx/v2@v2.24.0/generator/sql_func_generator.go (about)

     1  package generator
     2  
     3  import (
     4  	"go/types"
     5  	"path"
     6  	"path/filepath"
     7  
     8  	"github.com/go-courier/codegen"
     9  	"github.com/go-courier/packagesx"
    10  )
    11  
    12  func NewSqlFuncGenerator(pkg *packagesx.Package) *SqlFuncGenerator {
    13  	return &SqlFuncGenerator{
    14  		pkg: pkg,
    15  	}
    16  }
    17  
    18  type SqlFuncGenerator struct {
    19  	Config
    20  	pkg   *packagesx.Package
    21  	model *Model
    22  }
    23  
    24  type Config struct {
    25  	StructName string
    26  	TableName  string
    27  	Database   string
    28  
    29  	WithComments        bool
    30  	WithTableName       bool
    31  	WithTableInterfaces bool
    32  	WithMethods         bool
    33  
    34  	FieldPrimaryKey   string
    35  	FieldKeyDeletedAt string
    36  	FieldKeyCreatedAt string
    37  	FieldKeyUpdatedAt string
    38  }
    39  
    40  func (g *Config) SetDefaults() {
    41  	if g.FieldKeyDeletedAt == "" {
    42  		g.FieldKeyDeletedAt = "DeletedAt"
    43  	}
    44  
    45  	if g.FieldKeyCreatedAt == "" {
    46  		g.FieldKeyCreatedAt = "CreatedAt"
    47  	}
    48  
    49  	if g.FieldKeyUpdatedAt == "" {
    50  		g.FieldKeyUpdatedAt = "UpdatedAt"
    51  	}
    52  
    53  	if g.TableName == "" {
    54  		g.TableName = toDefaultTableName(g.StructName)
    55  	}
    56  }
    57  
    58  func (g *SqlFuncGenerator) Scan() {
    59  	for ident, obj := range g.pkg.TypesInfo.Defs {
    60  		if typeName, ok := obj.(*types.TypeName); ok {
    61  			if typeName.Name() == g.StructName {
    62  				if _, ok := typeName.Type().Underlying().(*types.Struct); ok {
    63  					g.model = NewModel(g.pkg, typeName, g.pkg.CommentsOf(ident), &g.Config)
    64  				}
    65  			}
    66  		}
    67  	}
    68  }
    69  
    70  func (g *SqlFuncGenerator) Output(cwd string) {
    71  	if g.model == nil {
    72  		return
    73  	}
    74  
    75  	dir, _ := filepath.Rel(cwd, filepath.Dir(g.pkg.GoFiles[0]))
    76  	filename := codegen.GeneratedFileSuffix(path.Join(dir, codegen.LowerSnakeCase(g.StructName)+".go"))
    77  
    78  	file := codegen.NewFile(g.pkg.Name, filename)
    79  	g.model.WriteTo(file)
    80  	_, _ = file.WriteFile()
    81  }