1
0
mirror of https://github.com/ManyakRus/crud_generator.git synced 2025-01-03 01:22:21 +02:00

сделал model

This commit is contained in:
Nikitin Aleksandr 2023-10-25 14:52:49 +03:00
parent 55bdf2adee
commit 57e240ba3e
6 changed files with 156 additions and 16 deletions

1
.gitignore vendored
View File

@ -13,3 +13,4 @@
/bin/settings/connections_add.txt /bin/settings/connections_add.txt
/database.graphml /database.graphml
/database.graphml0 /database.graphml0
/bin/ready/pkg/model/

View File

@ -20,12 +20,12 @@ type LawsuitStatusType struct {
} }
type ICrud_LawsuitStatusType interface { type ICrud_LawsuitStatusType interface {
Read(l *LawsuitStatusType) error Read(*LawsuitStatusType) error
Save(l *LawsuitStatusType) error Save(*LawsuitStatusType) error
Update(l *LawsuitStatusType) error Update(*LawsuitStatusType) error
Create(l *LawsuitStatusType) error Create(*LawsuitStatusType) error
Delete(l *LawsuitStatusType) error Delete(*LawsuitStatusType) error
Restore(l *LawsuitStatusType) error Restore(*LawsuitStatusType) error
} }
// TableName - возвращает имя таблицы в БД, нужен для gorm // TableName - возвращает имя таблицы в БД, нужен для gorm
@ -136,7 +136,7 @@ func (l *LawsuitStatusType) Restore() error {
} }
// SetCrudInterface - заполняет интерфейс crud: DB, GRPC, NRPC // SetCrudInterface - заполняет интерфейс crud: DB, GRPC, NRPC
func (c LawsuitStatusType) SetCrudInterface(crud ICrud_LawsuitStatusType) { func (l LawsuitStatusType) SetCrudInterface(crud ICrud_LawsuitStatusType) {
crud_LawsuitStatusType = crud crud_LawsuitStatusType = crud
return return

View File

@ -24,6 +24,7 @@ type SettingsINI struct {
SERVICE_NAME string SERVICE_NAME string
TEXT_TEMPLATE_MODEL string TEXT_TEMPLATE_MODEL string
TEXT_TEMPLATE_TABLENAME string TEXT_TEMPLATE_TABLENAME string
HAS_IS_DELETED bool
} }
// FillSettings загружает переменные окружения в структуру из переменных окружения // FillSettings загружает переменные окружения в структуру из переменных окружения
@ -38,6 +39,7 @@ func FillSettings() {
Settings.TEMPLATE_FOLDERNAME_NRPC = os.Getenv("TEMPLATE_FOLDERNAME_NRPC") Settings.TEMPLATE_FOLDERNAME_NRPC = os.Getenv("TEMPLATE_FOLDERNAME_NRPC")
Settings.TEXT_TEMPLATE_MODEL = os.Getenv("TEXT_TEMPLATE_MODEL") Settings.TEXT_TEMPLATE_MODEL = os.Getenv("TEXT_TEMPLATE_MODEL")
Settings.TEXT_TEMPLATE_TABLENAME = os.Getenv("TEXT_TEMPLATE_TABLENAME") Settings.TEXT_TEMPLATE_TABLENAME = os.Getenv("TEXT_TEMPLATE_TABLENAME")
sHAS_IS_DELETED := os.Getenv("HAS_IS_DELETED")
sNEED_CRUD := os.Getenv("NEED_CRUD") sNEED_CRUD := os.Getenv("NEED_CRUD")
Settings.NEED_CRUD = BoolFromString(sNEED_CRUD) Settings.NEED_CRUD = BoolFromString(sNEED_CRUD)
@ -61,6 +63,9 @@ func FillSettings() {
if Settings.TEXT_TEMPLATE_TABLENAME == "" { if Settings.TEXT_TEMPLATE_TABLENAME == "" {
Settings.TEXT_TEMPLATE_TABLENAME = "lawsuit_status_types" Settings.TEXT_TEMPLATE_TABLENAME = "lawsuit_status_types"
} }
HAS_IS_DELETED := BoolFromString(sHAS_IS_DELETED)
Settings.HAS_IS_DELETED = HAS_IS_DELETED
} }
// CurrentDirectory - возвращает текущую директорию ОС // CurrentDirectory - возвращает текущую директорию ОС

View File

@ -7,3 +7,10 @@ Need create .env file with settings
const FolderTemplates string = "templates" const FolderTemplates string = "templates"
const FolderReady string = "ready" const FolderReady string = "ready"
const FILE_PERMISSIONS = 0600
const TEXT_GENERATED = `//File generated automatic with crud_generator app
//Do not change anything here.
`

View File

@ -6,9 +6,10 @@ import (
"github.com/ManyakRus/crud_generator/internal/create_files" "github.com/ManyakRus/crud_generator/internal/create_files"
"github.com/ManyakRus/crud_generator/internal/types" "github.com/ManyakRus/crud_generator/internal/types"
"github.com/ManyakRus/crud_generator/pkg/dbmeta" "github.com/ManyakRus/crud_generator/pkg/dbmeta"
"github.com/ManyakRus/starter/log"
"github.com/ManyakRus/starter/micro" "github.com/ManyakRus/starter/micro"
"log"
"os" "os"
"strconv"
"strings" "strings"
) )
@ -18,6 +19,7 @@ func CreateModelFiles(MapAll map[string]*types.Table) error {
for _, table1 := range MapAll { for _, table1 := range MapAll {
err = CreateModelFiles1(table1) err = CreateModelFiles1(table1)
if err != nil { if err != nil {
log.Error("CreateModelFiles1() table: ", table1.Name, " error: ", err)
return err return err
} }
} }
@ -28,6 +30,7 @@ func CreateModelFiles(MapAll map[string]*types.Table) error {
func CreateModelFiles1(Table1 *types.Table) error { func CreateModelFiles1(Table1 *types.Table) error {
var err error var err error
//чтение файлов
DirBin := micro.ProgramDir_bin() DirBin := micro.ProgramDir_bin()
DirTemplates := DirBin + constants.FolderTemplates + micro.SeparatorFile() DirTemplates := DirBin + constants.FolderTemplates + micro.SeparatorFile()
DirReady := DirBin + constants.FolderReady + micro.SeparatorFile() DirReady := DirBin + constants.FolderReady + micro.SeparatorFile()
@ -41,10 +44,36 @@ func CreateModelFiles1(Table1 *types.Table) error {
if err != nil { if err != nil {
log.Panic("ReadFile() ", FilenameTemplateModel, " error: ", err) log.Panic("ReadFile() ", FilenameTemplateModel, " error: ", err)
} }
TextTemplateModel := string(bytes) TextModel := string(bytes)
//создание текста
TextModelStruct, ModelName, err := FindTextModelStruct(Table1) TextModelStruct, ModelName, err := FindTextModelStruct(Table1)
TextTemplateModel = ReplaceModelStruct(TextTemplateModel, TextModelStruct) TextModel = ReplaceModelStruct(TextModel, TextModelStruct)
////(l LawsuitStatusType) = (b Branch)
//TextTemplateVarModel := "(" + strings.ToLower(config.Settings.TEXT_TEMPLATE_MODEL[:1]) + " " + config.Settings.TEXT_TEMPLATE_MODEL
//TextVarModel := "(" + strings.ToLower(ModelName[:1]) + " " + ModelName
//TextModel = strings.ReplaceAll(TextModel, TextTemplateVarModel, TextVarModel)
//
////(l *LawsuitStatusType) = (b *Branch)
//TextTemplateVarModel = "(" + strings.ToLower(config.Settings.TEXT_TEMPLATE_MODEL[:1]) + " *" + config.Settings.TEXT_TEMPLATE_MODEL
//TextVarModel = "(" + strings.ToLower(ModelName[:1]) + " *" + ModelName
//TextModel = strings.ReplaceAll(TextModel, TextTemplateVarModel, TextVarModel)
//
TextModel = strings.ReplaceAll(TextModel, config.Settings.TEXT_TEMPLATE_MODEL, ModelName)
TextModel = strings.ReplaceAll(TextModel, config.Settings.TEXT_TEMPLATE_TABLENAME, Table1.Name)
TextModel = constants.TEXT_GENERATED + TextModel
if config.Settings.HAS_IS_DELETED == true {
TextModel = DeleteFuncDelete(TextModel, ModelName, Table1)
TextModel = DeleteFuncRestore(TextModel, ModelName, Table1)
}
TextModel = AddImportTime(TextModel, Table1)
//запись файла
err = os.WriteFile(FilenameReadyModel, []byte(TextModel), constants.FILE_PERMISSIONS)
return err return err
} }
@ -83,9 +112,15 @@ func FindTextColumn(Column1 types.Column) string {
Type_go := SQLMapping1.GoType Type_go := SQLMapping1.GoType
TextDefaultValue := FindTextDefaultValue(Type_go) TextDefaultValue := FindTextDefaultValue(Type_go)
TextPrimaryKey := FindTextPrimaryKey(Column1.Is_identity) TextPrimaryKey := FindTextPrimaryKey(Column1.Is_identity)
Description := Column1.Description
Description = strconv.Quote(Description) //экранирование символов
Otvet = Otvet + "\t" + ColumnModelName + " " + Type_go + " `json:\"" + ColumnName + "\"" + "gorm:\"column:" + ColumnName + TextPrimaryKey + TextDefaultValue Otvet = Otvet + "\t" + ColumnModelName + " " + Type_go + "\t"
Otvet = Otvet + "`json:\"" + ColumnName + "\""
Otvet = Otvet + "\tgorm:\"column:" + ColumnName + TextPrimaryKey + TextDefaultValue + "\""
Otvet = Otvet + "\tdb:\"" + ColumnName + "\""
Otvet = Otvet + "`" Otvet = Otvet + "`"
Otvet = Otvet + "\t//" + Description
return Otvet return Otvet
} }
@ -96,7 +131,7 @@ func FindTextDefaultValue(Type_go string) string {
sValue := "" sValue := ""
switch Type_go { switch Type_go {
case "string": case "string":
sValue = "\"\"" sValue = "\\\"\\\""
case "int", "int32", "int64", "float32", "float64", "uint", "uint32", "uint64": case "int", "int32", "int64", "float32", "float64", "uint", "uint32", "uint64":
sValue = "0" sValue = "0"
case "time.Time": case "time.Time":
@ -125,16 +160,108 @@ func ReplaceModelStruct(TextTemplateModel, TextModelStruct string) string {
ModelName := config.Settings.TEXT_TEMPLATE_MODEL ModelName := config.Settings.TEXT_TEMPLATE_MODEL
//найдём начало и конец
TextFind1 := "// " + ModelName TextFind1 := "// " + ModelName
pos1 := strings.Index(TextTemplateModel, TextFind1) pos1 := strings.Index(TextTemplateModel, TextFind1)
if pos1 == 0 { if pos1 < 0 {
TextFind1 := "type " + ModelName + " struct {" TextFind1 := "type " + ModelName + " struct {"
pos1 = strings.Index(TextTemplateModel, TextFind1) pos1 = strings.Index(TextTemplateModel, TextFind1)
} }
if pos1 == 0 { if pos1 < 0 {
log.Panic("ReplaceModelStruct() error: in model.go_ not found text: ", TextFind1) log.Panic("ReplaceModelStruct() error: in model.go_ not found text: ", TextFind1)
} }
s2 := TextTemplateModel[pos1:]
TextFind1 = "}\n"
posEnd := strings.Index(s2, TextFind1)
if posEnd < 0 {
log.Panic("ReplaceModelStruct() error: in model.go_ not found text: ", TextFind1)
}
//
Otvet = TextTemplateModel[:pos1] + TextModelStruct + TextTemplateModel[pos1+posEnd+1:]
return Otvet
}
// DeleteFuncDelete - удаляет функцию Delete()
func DeleteFuncDelete(TextModel, ModelName string, Table1 *types.Table) string {
Otvet := TextModel
_, ok := Table1.MapColumns["is_deleted"]
if ok == true {
return Otvet
}
//FirstSymbol := strings.ToLower(ModelName)[:1]
TextFind := "Delete(*" + ModelName + ") error"
Otvet = strings.ReplaceAll(Otvet, TextFind, "")
TextFind = "\n// Delete "
pos1 := strings.Index(Otvet, TextFind)
if pos1 < 0 {
return Otvet
}
s2 := Otvet[pos1+1:]
posEnd := strings.Index(s2, "\n}")
if posEnd < 0 {
return Otvet
}
Otvet = Otvet[:pos1-1] + Otvet[pos1+posEnd+3:]
return Otvet
}
// DeleteFuncRestore - удаляет функцию Restore()
func DeleteFuncRestore(TextModel, Modelname string, Table1 *types.Table) string {
Otvet := TextModel
_, ok := Table1.MapColumns["is_deleted"]
if ok == true {
return Otvet
}
//FirstSymbol := strings.ToLower(Modelname)[:1]
TextFind := "Restore(*" + Modelname + ") error"
Otvet = strings.ReplaceAll(Otvet, TextFind, "")
TextFind = "\n// Restore "
pos1 := strings.Index(Otvet, TextFind)
if pos1 < 0 {
return Otvet
}
s2 := Otvet[pos1+1:]
posEnd := strings.Index(s2, "\n}")
if posEnd < 0 {
return Otvet
}
Otvet = Otvet[:pos1-1] + Otvet[pos1+posEnd+3:]
return Otvet
}
func AddImportTime(TextModel string, Table1 *types.Table) string {
Otvet := TextModel
//если уже есть импорт
pos1 := strings.Index(Otvet, `"time"`)
if pos1 >= 0 {
return Otvet
}
//
pos1 = strings.Index(Otvet, "import (")
if pos1 < 0 {
log.Error("not found word: import (")
return TextModel
}
Otvet = Otvet[:pos1+8] + "\n\t" + `"time"` + Otvet[pos1+8:]
return Otvet return Otvet
} }

View File

@ -25,8 +25,8 @@ func StartApp() {
postgres_gorm.GetConnection().Logger.LogMode(1) postgres_gorm.GetConnection().Logger.LogMode(1)
log.Info("postgres host: ", postgres_gorm.Settings.DB_HOST) log.Info("postgres host: ", postgres_gorm.Settings.DB_HOST)
ok := logic.StartFillAll() err := logic.StartFillAll()
if ok == false { if err != nil {
println(constants.TEXT_HELP) println(constants.TEXT_HELP)
} }