1
0
mirror of https://github.com/ManyakRus/crud_generator.git synced 2024-12-16 21:52:42 +02:00
crud_generator/internal/create_files/model/model.go

456 lines
15 KiB
Go
Raw Normal View History

2023-10-24 17:03:04 +02:00
package model
import (
2023-11-08 16:37:35 +02:00
"errors"
2023-10-24 17:03:04 +02:00
"github.com/ManyakRus/crud_generator/internal/config"
"github.com/ManyakRus/crud_generator/internal/constants"
"github.com/ManyakRus/crud_generator/internal/create_files"
"github.com/ManyakRus/crud_generator/internal/folders"
2023-10-24 17:03:04 +02:00
"github.com/ManyakRus/crud_generator/internal/types"
2023-10-25 13:52:49 +02:00
"github.com/ManyakRus/starter/log"
2023-10-24 17:03:04 +02:00
"github.com/ManyakRus/starter/micro"
"os"
2023-10-25 15:22:30 +02:00
"sort"
2023-10-24 17:03:04 +02:00
"strings"
)
2023-11-08 12:32:47 +02:00
// CreateAllFiles - создаёт все файлы в папке model
2023-10-26 10:33:12 +02:00
func CreateAllFiles(MapAll map[string]*types.Table) error {
2023-10-24 17:03:04 +02:00
var err error
for _, table1 := range MapAll {
2023-10-26 10:33:12 +02:00
err = CreateFiles(table1)
2023-10-24 17:03:04 +02:00
if err != nil {
2023-10-26 10:33:12 +02:00
log.Error("CreateFiles() table: ", table1.Name, " error: ", err)
2023-10-24 17:03:04 +02:00
return err
}
}
return err
}
2023-11-08 12:32:47 +02:00
// CreateFiles - создаёт 1 файл в папке model
2023-10-26 10:33:12 +02:00
func CreateFiles(Table1 *types.Table) error {
2023-10-24 17:03:04 +02:00
var err error
2023-11-01 16:34:57 +02:00
TableName := strings.ToLower(Table1.Name)
2023-10-25 13:52:49 +02:00
//чтение файлов
2023-10-24 17:03:04 +02:00
DirBin := micro.ProgramDir_bin()
2023-11-01 16:34:57 +02:00
DirTemplates := DirBin + config.Settings.TEMPLATE_FOLDERNAME + micro.SeparatorFile()
DirReady := DirBin + config.Settings.READY_FOLDERNAME + micro.SeparatorFile()
2023-10-24 17:03:04 +02:00
DirTemplatesModel := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_MODEL + micro.SeparatorFile()
2023-11-01 16:34:57 +02:00
DirReadyModel := DirReady + config.Settings.TEMPLATE_FOLDERNAME_MODEL + micro.SeparatorFile() + TableName + micro.SeparatorFile()
//создадим папку готовых файлов
folders.CreateFolder(DirReadyModel)
2023-10-24 17:03:04 +02:00
2023-11-08 14:15:52 +02:00
// создание файла struct
if config.Settings.NEED_CREATE_MODEL_STRUCT == true {
err = CreateFilesModel_struct(Table1, DirTemplatesModel, DirReadyModel)
if err != nil {
log.Error("CreateFilesModel_struct() table: ", Table1.Name, " error: ", err)
return err
}
}
// создание файла crud
if config.Settings.NEED_CREATE_MODEL_CRUD == true {
err = CreateFilesModel_crud(Table1, DirTemplatesModel, DirReadyModel)
if err != nil {
log.Error("CreateFilesModel_struct() table: ", Table1.Name, " error: ", err)
return err
}
}
return err
}
// CreateFilesModel_struct - создаёт 1 файл со структурой в папке model
func CreateFilesModel_struct(Table1 *types.Table, DirTemplatesModel, DirReadyModel string) error {
var err error
2023-11-16 14:08:10 +02:00
//var ModelName string
2023-11-08 14:15:52 +02:00
TableName := strings.ToLower(Table1.Name)
2023-11-16 17:07:59 +02:00
ModelName := Table1.NameGo
2023-11-08 14:15:52 +02:00
FilenameTemplateModel := DirTemplatesModel + "model.go_"
2023-11-16 14:08:10 +02:00
FilenameReadyModel := DirReadyModel + config.Settings.PREFIX_MODEL + TableName + ".go"
2023-11-08 14:15:52 +02:00
//создадим папку готовых файлов
folders.CreateFolder(DirReadyModel)
2023-11-08 14:15:52 +02:00
//чтение файла шаблона
2023-10-24 17:03:04 +02:00
bytes, err := os.ReadFile(FilenameTemplateModel)
if err != nil {
log.Panic("ReadFile() ", FilenameTemplateModel, " error: ", err)
}
2023-10-25 13:52:49 +02:00
TextModel := string(bytes)
2023-10-24 17:03:04 +02:00
2023-11-17 12:23:15 +02:00
//заменим имя пакета на новое
2023-12-01 15:00:11 +02:00
TextModel = create_files.ReplacePackageName(TextModel, DirReadyModel)
2023-11-17 12:23:15 +02:00
2023-11-17 13:24:26 +02:00
//заменим импорты
if config.Settings.USE_DEFAULT_TEMPLATE == true {
TextModel = create_files.DeleteTemplateRepositoryImports(TextModel)
TableURL := create_files.FindTableNameURL(TableName)
TextModel = create_files.AddImport(TextModel, TableURL)
}
2023-11-08 16:37:35 +02:00
TextModel = create_files.CheckAndAddImportTime_FromText(TextModel)
2023-11-16 17:07:59 +02:00
TextModel = create_files.ReplaceModelAndTableName(TextModel, Table1)
2023-11-16 14:08:10 +02:00
//замена импортов на новые URL
if config.Settings.USE_DEFAULT_TEMPLATE == true {
2023-11-16 17:07:59 +02:00
Comment := create_files.FindModelComment(Table1)
TextTemplate := "// " + ModelName
TextModel = strings.ReplaceAll(TextModel, TextTemplate, Comment)
2023-11-16 14:08:10 +02:00
TextModel = create_files.DeleteTemplateRepositoryImports(TextModel)
2023-11-16 17:07:59 +02:00
TableNameURL := create_files.FindTableNameURL(TableName)
TextModel = create_files.AddImport(TextModel, TableNameURL)
2023-11-16 14:08:10 +02:00
}
2023-11-15 16:59:21 +02:00
//удаление пустого импорта
TextModel = create_files.DeleteEmptyImport(TextModel)
2023-11-08 14:15:52 +02:00
//запись файла
err = os.WriteFile(FilenameReadyModel, []byte(TextModel), constants.FILE_PERMISSIONS)
return err
}
// CreateFilesModel_crud - создаёт 1 файл с crud операциями
func CreateFilesModel_crud(Table1 *types.Table, DirTemplatesModel, DirReadyModel string) error {
var err error
ModelName := Table1.NameGo
TableName := strings.ToLower(Table1.Name)
FilenameTemplateModel := DirTemplatesModel + "model_crud.go_"
FilenameReadyModel := DirReadyModel + TableName + "_crud.go"
//чтение файла шаблона
bytes, err := os.ReadFile(FilenameTemplateModel)
if err != nil {
log.Panic("ReadFile() ", FilenameTemplateModel, " error: ", err)
}
TextModel := string(bytes)
2023-11-17 12:23:15 +02:00
//заменим имя пакета на новое
2023-12-01 15:00:11 +02:00
TextModel = create_files.ReplacePackageName(TextModel, DirReadyModel)
2023-11-08 14:15:52 +02:00
2023-11-17 13:24:26 +02:00
//заменим импорты
if config.Settings.USE_DEFAULT_TEMPLATE == true {
TextModel = create_files.DeleteTemplateRepositoryImports(TextModel)
TableURL := create_files.FindCalcStructVersionURL()
TextModel = create_files.AddImport(TextModel, TableURL)
2023-11-28 14:08:44 +02:00
DBConstantsURL := create_files.FindDBConstantsURL()
TextModel = create_files.AddImport(TextModel, DBConstantsURL)
2023-12-01 15:00:11 +02:00
//удалим лишние функции
TextModel = create_files.DeleteFuncDelete(TextModel, Table1)
TextModel = create_files.DeleteFuncRestore(TextModel, Table1)
TextModel = create_files.DeleteFuncFind_byExtID(TextModel, Table1)
//удалим лишние функции из интерфейса
TextModel = DeleteFromInterfaceDelete(TextModel, Table1)
TextModel = DeleteFromInterfaceRestore(TextModel, Table1)
TextModel = DeleteFromInterfaceFind_ByExtID(TextModel, Table1)
2023-11-17 13:24:26 +02:00
}
2023-11-17 12:23:15 +02:00
//создание текста
2023-11-08 14:15:52 +02:00
TextModel = strings.ReplaceAll(TextModel, config.Settings.TEXT_TEMPLATE_MODEL, ModelName)
TextModel = strings.ReplaceAll(TextModel, config.Settings.TEXT_TEMPLATE_TABLENAME, Table1.Name)
2023-11-10 14:04:05 +02:00
TextModel = config.Settings.TEXT_MODULE_GENERATED + TextModel
2023-11-08 14:15:52 +02:00
TextModel = create_files.CheckAndAddImportTime_FromText(TextModel)
2023-11-02 17:19:33 +02:00
TextModel = create_files.DeleteImportModel(TextModel)
2023-10-25 13:52:49 +02:00
2023-11-15 16:59:21 +02:00
//замена импортов на новые URL
TextModel = create_files.ReplaceServiceURLImports(TextModel)
//удаление пустого импорта
TextModel = create_files.DeleteEmptyImport(TextModel)
//удаление функций
TextModel = DeleteFunctions(TextModel, TableName, types.MapModelCrudDeleteFunctions)
2023-10-25 13:52:49 +02:00
//запись файла
err = os.WriteFile(FilenameReadyModel, []byte(TextModel), constants.FILE_PERMISSIONS)
2023-10-24 17:03:04 +02:00
return err
}
// DeleteFunctions - удаляет функции из текста, по карте MapModelCrudDeleteFunctions
func DeleteFunctions(Text, TableName string, MapModelCrudDeleteFunctions map[string]string) string {
Otvet := Text
TextDelete, ok := MapModelCrudDeleteFunctions[TableName]
if ok == false {
return Otvet
}
MassDelete := strings.Split(TextDelete, ",")
for _, FunctionName1 := range MassDelete {
2023-11-29 13:09:53 +02:00
Otvet = create_files.DeleteFuncFromComment(Otvet, "\n// "+FunctionName1)
Otvet = create_files.DeleteFuncFromFuncName(Otvet, FunctionName1)
}
return Otvet
}
2023-11-08 12:32:47 +02:00
// FindTextModelStruct - возвращает текст структуры и тегов gorm
func FindTextModelStruct(TextModel string, Table1 *types.Table) (string, string, string, error) {
2023-10-24 17:03:04 +02:00
var Otvet string
2023-10-25 10:41:26 +02:00
var ModelName string
2023-10-24 17:03:04 +02:00
var err error
TableName := Table1.Name
2023-11-16 17:07:59 +02:00
//ModelName = create_files.FindSingularName(TableName)
//ModelName = create_files.FormatName(ModelName)
//Table1.NameGo = ModelName
2023-11-08 14:15:52 +02:00
COMMENT_MODEL_STRUCT := config.Settings.COMMENT_MODEL_STRUCT
2023-10-24 17:03:04 +02:00
2023-11-08 14:15:52 +02:00
Otvet = `// ` + ModelName + ` - ` + COMMENT_MODEL_STRUCT + TableName + `: ` + Table1.Comment + `
2023-10-24 17:03:04 +02:00
type ` + ModelName + ` struct {
`
2023-10-25 15:22:30 +02:00
//сортировка
keys := make([]string, 0, len(Table1.MapColumns))
for k := range Table1.MapColumns {
keys = append(keys, k)
}
sort.Strings(keys)
2023-11-08 16:37:35 +02:00
has_Columns_CommonStruct := create_files.Has_Columns_CommonStruct(Table1)
has_Columns_NameStruct := create_files.Has_Columns_NameStruct(Table1)
has_Columns_Groups := create_files.Has_Columns_Groups(Table1)
has_Columns_ExtLinks := create_files.Has_Columns_ExtLink(Table1)
ImportModelsName := micro.LastWord(config.Settings.TEMPLATE_FOLDERNAME_MODEL)
if has_Columns_CommonStruct == true {
Otvet = Otvet + "\t" + ImportModelsName + ".CommonStruct\n"
}
if has_Columns_NameStruct == true {
Otvet = Otvet + "\t" + ImportModelsName + ".NameStruct\n"
}
if has_Columns_Groups == true {
Otvet = Otvet + "\t" + ImportModelsName + ".GroupStruct\n"
}
if has_Columns_ExtLinks == true {
Otvet = Otvet + "\t" + ImportModelsName + ".ExtLinkStruct\n"
}
2023-10-25 15:22:30 +02:00
//цикл по всем колонкам
for _, key1 := range keys {
Column1, _ := Table1.MapColumns[key1]
2023-11-08 16:37:35 +02:00
//пропускаем колонки если они уже есть в CommonStruct
if has_Columns_CommonStruct == true && create_files.Is_Column_CommonStruct(Column1) == true {
continue
} else if has_Columns_NameStruct == true && create_files.Is_Column_NameStruct(Column1) == true {
continue
} else if has_Columns_Groups == true && create_files.Is_Column_GroupsStruct(Column1) == true {
continue
} else if has_Columns_ExtLinks == true && create_files.Is_Column_ExtLinksStruct(Column1) == true {
continue
}
2023-11-08 12:32:47 +02:00
var TextColumn string
2023-11-08 16:37:35 +02:00
TextModel, TextColumn = FindTextColumn(TextModel, Table1, Column1)
2023-10-25 10:41:26 +02:00
Otvet = Otvet + TextColumn + "\n"
2023-10-25 16:30:18 +02:00
Table1.MapColumns[key1] = Column1
2023-10-25 10:41:26 +02:00
}
Otvet = Otvet + "\n}"
2023-11-08 12:32:47 +02:00
return TextModel, Otvet, ModelName, err
2023-10-25 10:41:26 +02:00
}
2023-11-08 12:32:47 +02:00
// FindTextColumn - возвращает текст gorm
func FindTextColumn(TextModel string, Table1 *types.Table, Column1 *types.Column) (string, string) {
2023-10-25 10:41:26 +02:00
Otvet := ""
// Code string `json:"code" gorm:"column:code;default:0"`
ColumnName := Column1.Name
2023-11-07 16:58:02 +02:00
ColumnNameLowerCase := strings.ToLower(ColumnName)
2023-10-25 10:41:26 +02:00
ColumnModelName := create_files.FormatName(Column1.Name)
2023-11-08 16:37:35 +02:00
//Column1.NameGo = ColumnModelName
2023-10-27 10:43:15 +02:00
//SQLMapping1, ok := dbmeta.GetMappings()[Column1.Type]
//if ok == false {
// log.Panic("GetMappings() ", Column1.Type, " error: not found")
//}
//Type_go := SQLMapping1.GoType
Type_go := Column1.TypeGo
2023-11-08 16:37:35 +02:00
TextModel, Type_go = FindColumnTypeGoImport(TextModel, Table1, Column1)
//Column1.TypeGo = Type_go
2023-11-16 11:40:37 +02:00
TextDefaultValue := ""
if Column1.IsIdentity == false {
2023-11-16 14:08:10 +02:00
TextDefaultValue = create_files.FindTextDefaultValue(Column1)
2023-11-16 11:40:37 +02:00
}
2023-10-26 09:33:18 +02:00
TextPrimaryKey := FindTextPrimaryKey(Column1.IsIdentity)
2023-10-25 13:52:49 +02:00
Description := Column1.Description
2023-11-02 14:57:13 +02:00
Description = create_files.PrintableString(Description) //экранирование символов
2023-10-25 10:41:26 +02:00
2023-11-07 16:58:02 +02:00
TextAutoCreateTime := ""
TextAutoUpdateTime := ""
if config.Settings.USE_DEFAULT_TEMPLATE == true {
if ColumnNameLowerCase == "created_at" {
TextAutoCreateTime = ";autoCreateTime"
}
if ColumnNameLowerCase == "modified_at" {
TextAutoUpdateTime = ";autoUpdateTime"
}
}
2023-10-25 13:52:49 +02:00
Otvet = Otvet + "\t" + ColumnModelName + " " + Type_go + "\t"
Otvet = Otvet + "`json:\"" + ColumnName + "\""
2023-11-07 16:58:02 +02:00
Otvet = Otvet + " gorm:\"column:" + ColumnName + TextPrimaryKey + TextDefaultValue + TextAutoCreateTime + TextAutoUpdateTime + "\""
2023-11-16 11:40:37 +02:00
//Otvet = Otvet + " db:\"" + ColumnName + "\""
2023-10-25 10:41:26 +02:00
Otvet = Otvet + "`"
2023-10-25 13:52:49 +02:00
Otvet = Otvet + "\t//" + Description
2023-10-25 10:41:26 +02:00
2023-11-08 12:32:47 +02:00
return TextModel, Otvet
2023-10-25 10:41:26 +02:00
}
2023-11-08 12:32:47 +02:00
// FindTextPrimaryKey - возвращает строку gorm для primaryKey
2023-10-25 10:41:26 +02:00
func FindTextPrimaryKey(Is_identity bool) string {
Otvet := ""
if Is_identity == true {
Otvet = ";primaryKey;autoIncrement:true"
}
return Otvet
}
2023-11-08 12:32:47 +02:00
// ReplaceModelStruct - заменяет структуру модели на новую
2023-10-25 10:41:26 +02:00
func ReplaceModelStruct(TextTemplateModel, TextModelStruct string) string {
Otvet := ""
ModelName := config.Settings.TEXT_TEMPLATE_MODEL
2023-10-25 13:52:49 +02:00
//найдём начало и конец
2023-10-25 10:41:26 +02:00
TextFind1 := "// " + ModelName
pos1 := strings.Index(TextTemplateModel, TextFind1)
2023-10-25 13:52:49 +02:00
if pos1 < 0 {
2023-10-25 10:41:26 +02:00
TextFind1 := "type " + ModelName + " struct {"
pos1 = strings.Index(TextTemplateModel, TextFind1)
}
2023-10-25 13:52:49 +02:00
if pos1 < 0 {
2023-10-25 10:41:26 +02:00
log.Panic("ReplaceModelStruct() error: in model.go_ not found text: ", TextFind1)
}
2023-10-24 17:03:04 +02:00
2023-10-25 13:52:49 +02:00
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
}
2023-11-08 16:37:35 +02:00
// FindColumnTypeGoImport - заменяет ID на Alias
func FindColumnTypeGoImport(TextModel string, Table1 *types.Table, Column1 *types.Column) (string, string) {
2023-11-08 12:32:47 +02:00
Otvet := Column1.TypeGo
//тип колонки из БД или из convert_id.json
TableName := Table1.Name
2023-11-16 14:08:10 +02:00
ColumnName := Column1.Name
TextConvert, ok := types.MapConvertID[TableName+"."+ColumnName]
2023-11-08 12:32:47 +02:00
if ok == false {
return TextModel, Otvet
}
Otvet = TextConvert
//добавим импорт
URL := create_files.FindURL_Alias()
if URL == "" {
return TextModel, Otvet
}
TextModel = create_files.AddImport(TextModel, URL)
return TextModel, Otvet
}
2023-11-08 16:37:35 +02:00
// FillColumnsNameGo - заполняет NameGo во все колонки
func FillColumnsNameGo(MapAll *map[string]*types.Table) error {
var err error
for _, Table1 := range *MapAll {
for _, Column1 := range Table1.MapColumns {
ColumnName := Column1.Name
ColumnModelName := create_files.FormatName(ColumnName)
Column1.NameGo = ColumnModelName
if ColumnModelName == "" {
err = errors.New("Table: " + Table1.Name + " Column: " + ColumnName + " = \"\"")
}
}
}
return err
}
2023-12-01 15:00:11 +02:00
// DeleteFromInterfaceDelete - удаляет функцию Delete() из интерфейса
func DeleteFromInterfaceDelete(TextModel string, Table1 *types.Table) string {
Otvet := TextModel
//проверим есть ли колонка IsDeleted
if create_files.Has_Column_IsDeleted(Table1) == true {
return Otvet
}
ModelName := config.Settings.TEXT_TEMPLATE_MODEL
TextFind := "\n\tDelete(*" + ModelName + ") error"
Otvet = strings.ReplaceAll(Otvet, TextFind, "")
return Otvet
}
// DeleteFromInterfaceRestore - удаляет функцию Restore() из интерфейса
func DeleteFromInterfaceRestore(TextModel string, Table1 *types.Table) string {
Otvet := TextModel
//проверим есть ли колонка IsDeleted
if create_files.Has_Column_IsDeleted(Table1) == true && config.Settings.HAS_IS_DELETED == true {
return Otvet
}
ModelName := config.Settings.TEXT_TEMPLATE_MODEL
TextFind := "\n\tRestore(*" + ModelName + ") error"
Otvet = strings.ReplaceAll(Otvet, TextFind, "")
return Otvet
}
// DeleteFromInterfaceFind_ByExtID - удаляет функцию Find_ByExtID() из интерфейса
func DeleteFromInterfaceFind_ByExtID(TextModel string, Table1 *types.Table) string {
Otvet := TextModel
//проверим есть ли колонки ExtID и ConnectionID
if create_files.Has_Column_ExtID_ConnectionID(Table1) == true {
return Otvet
}
ModelName := config.Settings.TEXT_TEMPLATE_MODEL
TextFind := "\n\tFind_ByExtID(*" + ModelName + ") error"
Otvet = strings.ReplaceAll(Otvet, TextFind, "")
return Otvet
}