github.com/e154/smart-home@v0.17.2-0.20240311175135-e530a6e5cd45/cmd/cli/commands/generate/db/generator.go (about) 1 // This file is part of the Smart Home 2 // Program complex distribution https://github.com/e154/smart-home 3 // Copyright (C) 2016-2023, Filippov Alex 4 // 5 // This library is free software: you can redistribute it and/or 6 // modify it under the terms of the GNU Lesser General Public 7 // License as published by the Free Software Foundation; either 8 // version 3 of the License, or (at your option) any later version. 9 // 10 // This library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 // Library General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public 16 // License along with this library. If not, see 17 // <https://www.gnu.org/licenses/>. 18 19 package adaptor 20 21 import ( 22 "os" 23 "path" 24 "strings" 25 "text/template" 26 27 "github.com/e154/smart-home/common/logger" 28 29 "github.com/e154/smart-home/cmd/cli/commands/generate" 30 "github.com/e154/smart-home/common" 31 "github.com/spf13/cobra" 32 ) 33 34 var ( 35 log = logger.MustGetLogger("db") 36 ) 37 38 var dbModelTpl = `//CODE GENERATED AUTOMATICALLY 39 40 package {{.Package}} 41 42 import ( 43 "fmt" 44 "gorm.io/gorm" 45 "time" 46 ) 47 48 // {{.Name}}s ... 49 type {{.Name}}s struct { 50 Db *gorm.DB 51 } 52 53 // {{.Name}} ... 54 type {{.Name}} struct { 55 Id int64` + "`gorm:\"primary_key\"`" + ` 56 Name string 57 CreatedAt time.Time 58 UpdatedAt time.Time 59 } 60 61 // TableName ... 62 func (d *{{.Name}}) TableName() string { 63 return "{{.Name}}" 64 } 65 66 // AddEntity ... 67 func (n {{.Name}}s) AddEntity(ver *{{.Name}}) (id int64, err error) { 68 if err = n.Db.Create(&ver).Error; err != nil { 69 return 70 } 71 id = ver.Id 72 return 73 } 74 75 // GetById ... 76 func (n {{.Name}}s) GetById(id int64) (ver *{{.Name}}, err error) { 77 ver = &{{.Name}}{Id: id} 78 err = n.Db.First(&ver).Error 79 return 80 } 81 82 // UpdateEntity ... 83 func (n {{.Name}}s) UpdateEntity(m *{{.Name}}) (err error) { 84 q := map[string]interface{}{ 85 "name": m.Name, 86 } 87 err = n.Db.Model(&{{.Name}}{Id: m.Id}).Updates(q).Error 88 return 89 } 90 91 // Delete ... 92 func (n {{.Name}}s) Delete(id int64) (err error) { 93 err = n.Db.Delete(&{{.Name}}{Id: id}).Error 94 return 95 } 96 97 // List ... 98 func (n *{{.Name}}s) List(limit, offset int64, orderBy, sort string) (list []*{{.Name}}, total int64, err error) { 99 100 if err = n.Db.Model({{.Name}}{}).Count(&total).Error; err != nil { 101 return 102 } 103 104 list = make([]*{{.Name}}, 0) 105 q := n.Db.Model(&{{.Name}}{}). 106 Limit(limit). 107 Offset(offset) 108 109 if sort != "" && orderBy != "" { 110 q = q. 111 Order(fmt.Sprintf("%s %s", sort, orderBy)) 112 } 113 114 err = q. 115 Find(&list). 116 Error 117 118 return 119 } 120 121 // Search ... 122 func (n *{{.Name}}s) Search(query string, limit, offset int) (list []*{{.Name}}, total int64, err error) { 123 124 q := n.Db.Model(&{{.Name}}{}). 125 Where("name LIKE ?", "%"+query+"%") 126 127 if err = q.Count(&total).Error; err != nil { 128 return 129 } 130 131 q = q. 132 Limit(limit). 133 Offset(offset). 134 Order("name ASC") 135 136 list = make([]*{{.Name}}, 0) 137 err = q.Find(&list).Error 138 139 return 140 } 141 142 ` 143 144 var ( 145 dbModelCmd = &cobra.Command{ 146 Use: "dbm", 147 Short: "db model generator", 148 Long: "$ cli g dbm [Name]", 149 } 150 packageName = "db" 151 ) 152 153 func init() { 154 generate.Generate.AddCommand(dbModelCmd) 155 dbModelCmd.Run = func(cmd *cobra.Command, args []string) { 156 157 if len(args) == 0 { 158 log.Error("Wrong number of arguments. Run: cli help generate") 159 return 160 } 161 162 currpath, _ := os.Getwd() 163 164 g := Generator{} 165 g.Generate(args[0], currpath) 166 } 167 } 168 169 // Generator ... 170 type Generator struct{} 171 172 // Generate ... 173 func (e Generator) Generate(modelName, currpath string) { 174 175 log.Infof("Using '%s' as model name", modelName) 176 log.Infof("Using '%s' as package name", packageName) 177 178 fp := path.Join(currpath, "db") 179 180 e.addModel(fp, modelName) 181 } 182 183 func (e Generator) addModel(fp, modelName string) { 184 185 if _, err := os.Stat(fp); os.IsNotExist(err) { 186 // Create the model's directory 187 if err := os.MkdirAll(fp, 0777); err != nil { 188 log.Errorf("Could not create db directory: %s", err.Error()) 189 return 190 } 191 } 192 193 fpath := path.Join(fp, strings.ToLower(modelName)+".go") 194 f, err := os.OpenFile(fpath, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666) 195 if err != nil { 196 log.Errorf("Could not create model file: %s", err.Error()) 197 return 198 } 199 defer f.Close() 200 201 templateData := struct { 202 Package string 203 Name string 204 List string 205 ModelName string 206 AdaptorName string 207 }{ 208 Package: packageName, 209 Name: modelName, 210 } 211 t := template.Must(template.New("dbModel").Parse(dbModelTpl)) 212 213 if t.Execute(f, templateData) != nil { 214 log.Error(err.Error()) 215 } 216 217 common.FormatSourceCode(fpath) 218 }