Skip to content

Commit 7ea02b5

Browse files
Merge pull request #76 from samueldasilvadev/update-fork
chore(multi-tenant): creating multi tenant stubs
2 parents 2998ead + 54e0726 commit 7ea02b5

File tree

24 files changed

+236
-179
lines changed

24 files changed

+236
-179
lines changed

cmd/cli/cli/cli.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ func NewCli(cmd *cobra.Command) *Cli {
2020
func (c *Cli) Start() {
2121
generatorInstance := generator.NewGenerator()
2222
generatorInstance.DeclareCommands(c.Cmd)
23+
generatorInstance.DeclareDomainCreatorFromSchema(c.Cmd)
2324
migratorInstance := migrator.NewMigrator()
2425
migratorInstance.DeclareCommands(c.Cmd)
2526
}

cmd/cli/migrator/migrator.go

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,8 @@ func (m *Migrator) DeclareCommands(cmd *cobra.Command) {
3636
},
3737
&cobra.Command{
3838
Use: "generate-schema-from-db",
39-
Short: "generate-schema-from-db <schema name>",
40-
Long: "generate HCL schema from database connected on env",
39+
Short: "generate-schema-from-db <schema name> <database name>",
40+
Long: "generate HCL schema from connection on env \ngenerate all databases if <database name> is not provided (all databases generations does`nt work with domain generation from schema)",
4141
PreRun: m.BootMigrator,
4242
Run: m.Generate,
4343
},
@@ -60,11 +60,15 @@ func (m *Migrator) Inspect(_ *cobra.Command, _ []string) {
6060

6161
func (m *Migrator) Generate(_ *cobra.Command, args []string) {
6262
schema := ""
63+
if len(args) > 0 {
64+
schema = args[0]
65+
}
66+
databaseName := ""
6367
if len(args) > 1 {
64-
schema = args[1]
68+
databaseName = args[1]
6569
}
6670
migratorInstance := migrator.NewMigrator(m.dsn, m.dsnTest, m.database)
67-
migratorInstance.Generate(schema)
71+
migratorInstance.Generate(schema, databaseName)
6872
}
6973

7074
func (m *Migrator) BootMigrator(_ *cobra.Command, _ []string) {

internal/application/services/dummy/GET/service.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,14 +25,14 @@ func (s *Service) Execute(request Request) {
2525
s.BadRequest(err.Error())
2626
return
2727
}
28-
s.produceResponseRule(request.Data, request.Client, request.Domain)
28+
s.produceResponseRule(request.Data, request.Domain)
2929
}
3030

3131
func (s *Service) GetResponse() (*Response, *services.Error) {
3232
return s.response, s.Error
3333
}
3434

35-
func (s *Service) produceResponseRule(data *Data, client string, domain *dummy.Dummy) {
35+
func (s *Service) produceResponseRule(data *Data, domain *dummy.Dummy) {
3636
dummyData, err := s.repository.Get(*domain, "id", data.ID)
3737

3838
if err != nil {

schemas/schema.my.hcl

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
table "dummy" {
2-
schema = schema.skeleton
2+
schema = schema.zord
33
column "id" {
44
null = false
55
type = char(26)
@@ -16,15 +16,7 @@ table "dummy" {
1616
columns = [column.id]
1717
}
1818
}
19-
20-
//{{newTable}}
21-
22-
variable "database" {
23-
type = string
24-
}
25-
26-
schema "skeleton" {
27-
name = var.database
19+
schema "zord" {
2820
charset = "utf8mb4"
2921
collate = "utf8mb4_0900_ai_ci"
3022
}

tools/generator/config.toml

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,13 +39,15 @@ table "{{domain}}" {
3939
$repeat$"""
4040
"{{domainType}}" = """type {{domainPascalCase}} struct {
4141
ID string `db:"id"`
42+
client string
43+
filters *filters.Filters
4244
}"""
4345
"{{pkType}}" = "ID string `param:\"id\"`"
4446
"{{pkName}}" = "ID"
4547
"{{pkDbName}}" = "id"
4648
"{{dataType}}" = ""
47-
"{{createServiceData}}" = "ID: s.idCreator.Create(),"
48-
"{{editServiceData}}" = "ID: id,"
49+
"{{createServiceData}}" = ""
50+
"{{editServiceData}}" = ""
4951
"{{optionalImports}}" = ""
5052
"{{idVar}}" = ""
5153

@@ -101,7 +103,7 @@ deleteLinePatterns = [
101103
]
102104

103105
[stubs.crud.migrator_schema]
104-
toPath = "tools/migrator/schema/schema.my.hcl"
106+
toPath = "schemas/schema.my.hcl"
105107
isGenerated = false
106108
deleteRegex = "(?s)table \"{{domain}}\" {\\s*.*?\\s*}\n*//tableEnd\n\n"
107109

tools/generator/generateFromDb.go

Lines changed: 55 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ func (cg *CodeGenerator) ReadFromSchema(schema string, table string) {
2727
}
2828

2929
func (cg *CodeGenerator) getHclFile(schema string) (*hclwrite.File, error) {
30-
filepath := fmt.Sprintf("tools/migrator/schema/%s.my.hcl", schema)
30+
filepath := fmt.Sprintf("schemas/%s.my.hcl", schema)
3131
content, err := os.ReadFile(filepath)
3232
if err != nil {
3333
fmt.Println("Error reading file:", err)
@@ -45,7 +45,7 @@ func (cg *CodeGenerator) handleHclBlock(block *hclwrite.Block) error {
4545
return nil
4646
}
4747

48-
tableName := block.Labels()[0]
48+
tableName := CamelCase(block.Labels()[0])
4949
replacers := cg.generateDomainFromHclBlock(block, tableName)
5050
validateErr := cg.validateFiles(tableName)
5151
if validateErr != nil {
@@ -65,21 +65,21 @@ func (cg *CodeGenerator) generateDomainFromHclBlock(block *hclwrite.Block, table
6565
*cg.isIntId = false
6666
domain := cg.generateDomainStruct(block.Body().Blocks(), tableName, cg.primaryKey, cg.pkType)
6767
dataType := cg.generateStruct(block.Body().Blocks(), nil, nil, cg.generateDeclarationLine)
68-
createAttrData := cg.generateStruct(block.Body().Blocks(), nil, nil, cg.generateCreateAttributionLine)
69-
editAttrData := cg.generateStruct(block.Body().Blocks(), nil, nil, cg.generateEditAttributionLine)
68+
createAttrData := cg.generateStruct(block.Body().Blocks(), nil, nil, cg.generateAttributionLine)
69+
editAttrData := cg.generateStruct(block.Body().Blocks(), nil, nil, cg.generateAttributionLine)
7070
replacers := GetReplacersConfig(cg.config, cg.domainType, []string{tableName})
7171
replacers["{{domainType}}"] = domain
7272
replacers["{{dataType}}"] = dataType
7373
replacers["{{pkDbName}}"] = *cg.primaryKey
74-
replacers["{{pkName}}"] = PascalCase(*cg.primaryKey)
74+
replacers["{{pkName}}"] = *cg.primaryKey
7575
replacers["{{pkType}}"] = *cg.pkType
7676
replacers["{{createServiceData}}"] = createAttrData
7777
replacers["{{editServiceData}}"] = editAttrData
7878
if *cg.needImportTime {
7979
replacers["{{optionalImports}}"] = "\"time\""
8080
}
8181
if !*cg.isIntId {
82-
replacers["{{idVar}}"] = "id := s.idCreator.Create()"
82+
replacers["{{idVar}}"] = "domain." + PascalCase(*cg.primaryKey) + " = s.idCreator.Create()"
8383
}
8484
return replacers
8585
}
@@ -88,12 +88,13 @@ func (cg *CodeGenerator) generateDomainStruct(blocks []*hclwrite.Block, tableNam
8888
*pk = cg.findPkOnBlocks(blocks)
8989
structString := "type " + PascalCase(tableName) + " struct {\n"
9090
structString += cg.generateStruct(blocks, pk, pkType, cg.generateDeclarationLine)
91+
structString += "\tclient string\n\tfilters *filters.Filters\n"
9192
structString += "}"
9293
return structString
9394
}
9495

9596
func (cg *CodeGenerator) generateStruct(blocks []*hclwrite.Block, pk, pkType *string, strFormationFunc func(string, string, string, string) string) string {
96-
declarationString := "\n"
97+
declarationString := ""
9798
for _, block := range blocks {
9899
if block.Type() == "column" {
99100
token, ok := block.Body().Attributes()["type"]
@@ -102,9 +103,14 @@ func (cg *CodeGenerator) generateStruct(blocks []*hclwrite.Block, pk, pkType *st
102103
}
103104
tokenStr := string(token.Expr().BuildTokens(nil).Bytes())
104105
goType := cg.dbTypesToGoTypes(tokenStr)
106+
nullable, nullOk := block.Body().Attributes()["null"]
107+
isNullable := cg.verifyIsNullable(nullable, nullOk)
108+
if isNullable {
109+
goType = "*" + goType
110+
}
105111

106112
if pk != nil && block.Labels()[0] == *pk {
107-
*pkType = fmt.Sprintf("%s string `param:\"id\"`", PascalCase(*pk))
113+
*pkType = fmt.Sprintf("%s string `param:\"id\"`\n", PascalCase(*pk))
108114
}
109115

110116
declarationString = strFormationFunc(
@@ -137,39 +143,12 @@ func (cg *CodeGenerator) generateDeclarationLine(str, name, goType, dbTag string
137143
)
138144
}
139145

140-
func (cg *CodeGenerator) generateCreateAttributionLine(str, name, goType, _ string) string {
146+
func (cg *CodeGenerator) generateAttributionLine(str, name, _, _ string) string {
141147
if name == PascalCase(*cg.primaryKey) {
142-
if strings.Contains(goType, "int") {
143-
*cg.isIntId = true
144-
return str
145-
}
146-
return fmt.Sprintf(
147-
"%s %s: &id,\n",
148-
str,
149-
name,
150-
)
148+
return str
151149
}
152150
return fmt.Sprintf(
153-
"%s %s: data.%s,\n",
154-
str,
155-
name,
156-
name,
157-
)
158-
}
159-
160-
func (cg *CodeGenerator) generateEditAttributionLine(str, name, goType, _ string) string {
161-
if name == PascalCase(*cg.primaryKey) {
162-
if strings.Contains(goType, "int") {
163-
return str
164-
}
165-
return fmt.Sprintf(
166-
"%s %s: &id,\n",
167-
str,
168-
name,
169-
)
170-
}
171-
return fmt.Sprintf(
172-
"%s %s: data.%s,\n",
151+
"%s domain.%s = data.%s\n",
173152
str,
174153
name,
175154
name,
@@ -188,7 +167,7 @@ func (cg *CodeGenerator) findPkOnBlocks(blocks []*hclwrite.Block) string {
188167
str = cg.getColumnFromAttrString(pkAttr)
189168
}
190169
}
191-
return str
170+
return PascalCase(str)
192171
}
193172

194173
func (cg *CodeGenerator) getColumnFromAttrString(attrStr string) string {
@@ -200,52 +179,63 @@ func (cg *CodeGenerator) getColumnFromAttrString(attrStr string) string {
200179

201180
func (cg *CodeGenerator) dbTypesToGoTypes(typo string) string {
202181
dbTypesMap := map[string]string{
203-
" bigint": "*int64",
204-
" bit": "* ",
205-
" char": "*string",
206-
" decimal": "*float64",
207-
" float": "*float32",
208-
" double": "*float64",
209-
" int": "*int",
210-
" longtext": "*string",
211-
" mediumint": "*int",
212-
" mediumtext": "*string",
213-
" smallint": "*int16",
214-
" text": "*string",
215-
" time": "*string",
216-
" timestamp": "*string",
217-
" datetime": "*time.Time",
218-
" date": "*string",
219-
" tinyint": "*int8",
220-
" tinytext": "*string",
221-
" varbinary": "*string",
222-
" varchar": "*string",
223-
" json": "*string",
182+
" bigint": "int64",
183+
" bit": " ",
184+
" char": "string",
185+
" decimal": "float64",
186+
" float": "float32",
187+
" double": "float64",
188+
" int": "int",
189+
" longtext": "string",
190+
" mediumint": "int",
191+
" mediumtext": "string",
192+
" smallint": "int16",
193+
" text": "string",
194+
" time": "string",
195+
" timestamp": "string",
196+
" datetime": "time.Time",
197+
" date": "string",
198+
" tinyint": "int8",
199+
" tinytext": "string",
200+
" varbinary": "string",
201+
" varchar": "string",
202+
" json": "string",
224203
}
225204

226205
GolangType, ok := dbTypesMap[typo]
227206
if ok {
228-
if GolangType == "*time.Time" {
207+
if GolangType == "time.Time" {
229208
*cg.needImportTime = true
230209
}
231210
return GolangType
232211
}
233212

234213
if strings.Contains(typo, "char") {
235-
return "*string"
214+
return "string"
236215
}
237216

238217
if strings.Contains(typo, "double") {
239-
return "*float64"
218+
return "float64"
240219
}
241220

242221
if strings.Contains(typo, "year") {
243-
return "*string"
222+
return "string"
244223
}
245224

246225
if strings.Contains(typo, "decimal") {
247-
return "*float64"
226+
return "float64"
248227
}
249228

250229
return typo
251230
}
231+
232+
func (cg *CodeGenerator) verifyIsNullable(token *hclwrite.Attribute, ok bool) bool {
233+
if !ok {
234+
return false
235+
}
236+
value := token.Expr().BuildTokens(nil).Bytes()
237+
if string(value) == "true" {
238+
return true
239+
}
240+
return false
241+
}

tools/generator/generator.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ func (cg *CodeGenerator) GenerateFilesFromStubs(stubs map[string]Stubs, replacer
8989
if !stub.IsGenerated {
9090
data, err := GetFileData(stub.ToPath)
9191
if err != nil {
92-
cg.Logger.Error(err)
92+
cg.Logger.Info("File: " + stub.ToPath + " does not exist, generation in this file will be ignored")
9393
}
9494

9595
replData := Replacer(data, replacers)

tools/generator/stubs/crud/domain/{{domain}}.go.stub

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,27 @@ package {{domain}}
33
import (
44
"go-skeleton/internal/application/providers/pagination"
55
"go-skeleton/internal/repositories/base_repository"
6+
"go-skeleton/internal/application/providers/filters"
67
{{optionalImports}}
78
)
89

910
{{domainType}}
1011

12+
func (d *{{domainPascalCase}}) SetClient(client string) {
13+
d.client = client
14+
}
15+
16+
func (d *{{domainPascalCase}}) SetFilters(filters *filters.Filters) {
17+
d.filters = filters
18+
}
19+
20+
func (d {{domainPascalCase}}) GetFilters() filters.Filters {
21+
if d.filters != nil {
22+
return *d.filters
23+
}
24+
return filters.Filters{}
25+
}
26+
1127
func (d {{domainPascalCase}}) Schema() string {
1228
return "{{domain}}"
1329
}

0 commit comments

Comments
 (0)