Skip to content

Commit

Permalink
feat: add sql command
Browse files Browse the repository at this point in the history
  • Loading branch information
thinkgos committed May 10, 2024
1 parent 1cebc62 commit abe2588
Show file tree
Hide file tree
Showing 14 changed files with 466 additions and 393 deletions.
24 changes: 16 additions & 8 deletions cmd/ormat/command/helper_gen_file.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,16 @@ func (self *genFileOpt) build(mixin ens.Schemaer) *ens.Schema {
}

func (self *genFileOpt) GenModel(mixin ens.Schemaer) error {
codegenOption := []codegen.Option{
codegen.WithByName("ormat"),
codegen.WithVersion(version),
codegen.WithPackageName(utils.GetPkgName(self.OutputDir)),
codegen.WithDisableDocComment(self.View.DisableDocComment),
}
sc := self.build(mixin)
if self.Merge {
data, err := codegen.New(sc.Entities, codegenOption...).GenModel().FormatSource()
g := codegen.CodeGen{
Entities: sc.Entities,
ByName: "ormat",
Version: version,
PackageName: utils.GetPkgName(self.OutputDir),
DisableDocComment: self.View.DisableDocComment,
}
data, err := g.Gen().FormatSource()
if err != nil {
return err
}
Expand All @@ -42,7 +43,14 @@ func (self *genFileOpt) GenModel(mixin ens.Schemaer) error {
slog.Info("👉 " + filename)
} else {
for _, entity := range sc.Entities {
data, err := codegen.New([]*ens.EntityDescriptor{entity}, codegenOption...).GenModel().FormatSource()
g := codegen.CodeGen{
Entities: []*ens.EntityDescriptor{entity},
ByName: "ormat",
Version: version,
PackageName: utils.GetPkgName(self.OutputDir),
DisableDocComment: self.View.DisableDocComment,
}
data, err := g.Gen().FormatSource()
if err != nil {
return fmt.Errorf("%v: %v", entity.Name, err)
}
Expand Down
49 changes: 25 additions & 24 deletions cmd/ormat/command/sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,27 @@ import (

"ariga.io/atlas/sql/schema"
"github.com/spf13/cobra"
"github.com/things-go/ens"
"github.com/things-go/ens/codegen"
"github.com/things-go/ens/driver"
"github.com/things-go/ens/utils"
"github.com/things-go/ens/sqlx"
)

type sqlOpt struct {
OutputDir string
Merge bool
Filename string
URL string
Tables []string
Exclude []string
DisableDocComment bool

OutputDir string
Merge bool
Filename string
}

type sqlCmd struct {
cmd *cobra.Command
sqlOpt
}

// atlas schema inspect -u "mysql://localhost" --format "{{ sql . }}"
// must be same as atlas schema inspect -u "mysql://localhost" --format "{{ sql . }}"
func newSqlCmd() *sqlCmd {
root := &sqlCmd{}
cmd := &cobra.Command{
Expand All @@ -39,7 +38,7 @@ func newSqlCmd() *sqlCmd {
if err != nil {
return err
}
mixin, err := d.InspectSchema(context.Background(), &driver.InspectOption{
schemaes, err := d.InspectSql(context.Background(), &driver.InspectOption{
URL: root.URL,
Data: "",
InspectOptions: schema.InspectOptions{
Expand All @@ -51,28 +50,30 @@ func newSqlCmd() *sqlCmd {
if err != nil {
return err
}
sc := mixin.Build(nil)
codegenOption := []codegen.Option{
codegen.WithByName("ormat"),
codegen.WithVersion(version),
codegen.WithPackageName(utils.GetPkgName(root.OutputDir)),
codegen.WithDisableDocComment(root.DisableDocComment),
}

if root.Merge {
data := codegen.New(sc.Entities, codegenOption...).
GenDDL().
Bytes()
codegen := &sqlx.CodeGen{
Entities: schemaes.Entities,
ByName: "ormat",
Version: version,
DisableDocComment: root.DisableDocComment,
}
data := codegen.Gen().Bytes()
filename := joinFilename(root.OutputDir, root.Filename, ".sql")
err = WriteFile(filename, data)
if err != nil {
return err
}
slog.Info("👉 " + filename)
} else {
for _, entity := range sc.Entities {
data := codegen.New([]*ens.EntityDescriptor{entity}, codegenOption...).
GenDDL().
Bytes()
for _, entity := range schemaes.Entities {
codegen := &sqlx.CodeGen{
Entities: schemaes.Entities,
ByName: "ormat",
Version: version,
DisableDocComment: root.DisableDocComment,
}
data := codegen.Gen().Bytes()
filename := joinFilename(root.OutputDir, entity.Name, ".sql")
err = WriteFile(filename, data)
if err != nil {
Expand All @@ -87,8 +88,8 @@ func newSqlCmd() *sqlCmd {
cmd.Flags().StringVar(&root.URL, "url", "", "mysql://root:[email protected]:3306/test)")
cmd.PersistentFlags().StringSliceVarP(&root.Tables, "table", "t", nil, "only out custom table")
cmd.PersistentFlags().StringSliceVar(&root.Exclude, "exclude", nil, "exclude table pattern")
cmd.Flags().StringVarP(&root.OutputDir, "out", "o", "./model/migration", "out directory")
cmd.Flags().StringVar(&root.Filename, "filename", "migration", "filename when merge enabled")
cmd.Flags().StringVarP(&root.OutputDir, "out", "o", "./migration", "out directory")
cmd.Flags().StringVar(&root.Filename, "filename", "create_table", "filename when merge enabled")
cmd.Flags().BoolVar(&root.Merge, "merge", false, "merge in a file")
cmd.Flags().BoolVarP(&root.DisableDocComment, "disableDocComment", "d", false, "禁用文档注释")

Expand Down
50 changes: 5 additions & 45 deletions codegen/codegen.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,51 +10,11 @@ import (

type CodeGen struct {
buf bytes.Buffer
entities []*ens.EntityDescriptor
byName string
version string
packageName string
disableDocComment bool
}

type Option func(*CodeGen)

// WithByName the code generator by which executables name.
func WithByName(s string) Option {
return func(g *CodeGen) {
g.byName = s
}
}

func WithVersion(version string) Option {
return func(g *CodeGen) {
g.version = version
}
}

func WithPackageName(s string) Option {
return func(g *CodeGen) {
g.packageName = s
}
}

func WithDisableDocComment(b bool) Option {
return func(g *CodeGen) {
g.disableDocComment = b
}
}

func New(md []*ens.EntityDescriptor, opts ...Option) *CodeGen {
g := &CodeGen{
entities: md,
byName: "codegen",
version: "unknown",
packageName: "codegen",
}
for _, opt := range opts {
opt(g)
}
return g
Entities []*ens.EntityDescriptor
ByName string
Version string
PackageName string
DisableDocComment bool
}

// Bytes returns the CodeBuf's buffer.
Expand Down
37 changes: 8 additions & 29 deletions codegen/model.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,24 @@
package codegen

import (
"fmt"
"strings"

"github.com/things-go/ens"
"github.com/things-go/ens/utils"
)

func (g *CodeGen) GenModel() *CodeGen {
if !g.disableDocComment {
g.Printf("// Code generated by %s. DO NOT EDIT.\n", g.byName)
g.Printf("// version: %s\n", g.version)
func (g *CodeGen) Gen() *CodeGen {
if !g.DisableDocComment {
g.Printf("// Code generated by %s. DO NOT EDIT.\n", g.ByName)
g.Printf("// version: %s\n", g.Version)
g.Println()
}
g.Printf("package %s\n", g.packageName)
g.Printf("package %s\n", g.PackageName)
g.Println()

//* import
imports := make(map[string]struct{})
for _, st := range g.entities {
for _, st := range g.Entities {
for _, field := range st.Fields {
if field.Type.PkgPath != "" {
imports[field.Type.PkgPath] = struct{}{}
Expand All @@ -35,11 +34,11 @@ func (g *CodeGen) GenModel() *CodeGen {
}

//* struct
for _, et := range g.entities {
for _, et := range g.Entities {
structName := utils.CamelCase(et.Name)
tableName := et.Name

g.Printf("// %s %s\n", structName, trimStructComment(et.Comment, "\n", "\n// "))
g.Printf("// %s %s\n", structName, strings.ReplaceAll(strings.TrimSpace(et.Comment), "\n", "\n// "))
g.Printf("type %s struct {\n", structName)
for _, field := range et.Fields {
g.Println(genModelStructField(field))
Expand Down Expand Up @@ -77,23 +76,3 @@ func genModelStructField(field *ens.FieldDescriptor) string {
}
return b.String()
}

func genModelStructVarField(tableName string, field *ens.FieldDescriptor, skip bool) string {
b := strings.Builder{}
b.Grow(64)
if skip {
b.WriteString("// ")
}
b.WriteString(`"`)
if field.Type.IsTime() {
if field.Nullable {
b.WriteString(fmt.Sprintf("IFNULL(UNIX_TIMESTAMP(`%[1]s`.`%[2]s`), 0) AS `%[2]s`", tableName, field.Name))
} else {
b.WriteString(fmt.Sprintf("UNIX_TIMESTAMP(`%[1]s`.`%[2]s`) AS `%[2]s`", tableName, field.Name))
}
} else {
b.WriteString(fmt.Sprintf("`%s`.`%s`", tableName, field.Name))
}
b.WriteString(`",`)
return b.String()
}
25 changes: 0 additions & 25 deletions codegen/sql_ddl.go

This file was deleted.

2 changes: 2 additions & 0 deletions driver/driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/things-go/ens"
"github.com/things-go/ens/proto"
"github.com/things-go/ens/rapier"
"github.com/things-go/ens/sqlx"
)

const (
Expand All @@ -24,6 +25,7 @@ type Driver interface {
InspectSchema(context.Context, *InspectOption) (*ens.MixinSchema, error)
InspectProto(context.Context, *InspectOption) (*proto.Schema, error)
InspectRapier(ctx context.Context, arg *InspectOption) (*rapier.Schema, error)
InspectSql(ctx context.Context, arg *InspectOption) (*sqlx.Schema, error)
}

func RegisterDriver(name string, d Driver) {
Expand Down
Loading

0 comments on commit abe2588

Please sign in to comment.