diff --git a/bin/templates/configs/nullable.json b/bin/templates/configs/nullable.json new file mode 100644 index 0000000..4cbce43 --- /dev/null +++ b/bin/templates/configs/nullable.json @@ -0,0 +1,3 @@ +{ + "ExtID": "0" +} diff --git a/bin/templates/pkg/db/db.go_ b/bin/templates/pkg/db/db.go_ index 63e71a9..8afe0c9 100644 --- a/bin/templates/pkg/db/db.go_ +++ b/bin/templates/pkg/db/db.go_ @@ -38,7 +38,7 @@ func (crud Crud_DB) Read_ctx(ctx context.Context, m *lawsuit_status_types.Lawsui // var Otvet lawsuit_status_types.LawsuitStatusType var err error - id := m.ID + id := int64(m.ID) db := postgres_gorm.GetConnection() db.WithContext(ctx) @@ -61,7 +61,7 @@ func (crud Crud_DB) Save(m *lawsuit_status_types.LawsuitStatusType) error { // Save_ctx - записывает новый или существующий объект в базу данных func (crud Crud_DB) Save_ctx(ctx context.Context, m *lawsuit_status_types.LawsuitStatusType) error { - is_create := !micro.BoolFromInt64(m.ID) + is_create := !micro.BoolFromInt64(int64(m.ID)) err := crud.create_update_ctx(ctx, m, is_create) return err } @@ -102,7 +102,7 @@ func (crud Crud_DB) Create_ctx(ctx context.Context, m *lawsuit_status_types.Laws func (crud Crud_DB) create_update(m *lawsuit_status_types.LawsuitStatusType, is_create bool) error { var err error - // log.Trace("start Save() ", TableName, " id: ", m.ID) + // log.Trace("start Save() ", TableName, " id: ", int64(m.ID)) ctxMain := context.Background() ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_DB_SECONDS)) @@ -116,17 +116,17 @@ func (crud Crud_DB) create_update(m *lawsuit_status_types.LawsuitStatusType, is_ func (crud Crud_DB) create_update_ctx(ctx context.Context, m *lawsuit_status_types.LawsuitStatusType, is_create bool) error { var err error - // log.Trace("start Save() ", TableName, " id: ", m.ID) + // log.Trace("start Save() ", TableName, " id: ", int64(m.ID)) // проверка ID if is_create == true { - if m.ID != 0 { + if int64(m.ID) != 0 { TextError := fmt.Sprint("db.Save() ", TableName, " error: id !=0") // log.Panic(sError) err = errors.New(TextError) return err } - } else if m.ID == 0 { + } else if int64(m.ID) == 0 { TextError := fmt.Sprint("db.Save() ", TableName, " error: id =0") err = errors.New(TextError) // log.Panic(sError) @@ -138,33 +138,14 @@ func (crud Crud_DB) create_update_ctx(ctx context.Context, m *lawsuit_status_typ db.WithContext(ctx) // заполним даты - Now := time.Now() - m.ModifiedAt = Now - if m.IsDeleted == true && m.DeletedAt.IsZero() == true { - m.DeletedAt = Now - } else if m.IsDeleted == false && m.DeletedAt.IsZero() == false { - m.DeletedAt = time.Time{} - } + //Text_modified_at + //Text_is_deleted_deleted_at //колонки с null tx := db MassOmit := make([]string, 0) var ColumnName string - ColumnName = "DeletedAt" - if m.DeletedAt.IsZero() == true { - MassOmit = append(MassOmit, ColumnName) - } - - ColumnName = "CreatedAt" - if m.CreatedAt.IsZero() == true { - MassOmit = append(MassOmit, ColumnName) - } - - ColumnName = "ExtID" - if m.ExtID == 0 { - MassOmit = append(MassOmit, ColumnName) - } //игнор пустых колонок tx = tx.Omit(MassOmit...) @@ -268,8 +249,8 @@ func Find_ByExtID(ext_id int64, connection_id int64) (lawsuit_status_types.Lawsu var Otvet lawsuit_status_types.LawsuitStatusType var err error - if ext_id <= 0 { - err = errors.New("Error: ext_id <=0") + if ext_id == 0 { + err = errors.New("Error: ext_id =0") return Otvet, err } @@ -289,8 +270,8 @@ func Find_ByExtID_ctx(ctx context.Context, ext_id int64, connection_id int64) (l var err error //log.Trace("start Find_ByExtID() ", TableName, " ext_id: ", ext_id) - if ext_id <= 0 { - err = errors.New("Error: ext_id <=0") + if ext_id == 0 { + err = errors.New("Error: ext_id =0") return Otvet, err } diff --git a/bin/templates/pkg/db/is_deleted.go_ b/bin/templates/pkg/db/is_deleted.go_ new file mode 100644 index 0000000..adc19f4 --- /dev/null +++ b/bin/templates/pkg/db/is_deleted.go_ @@ -0,0 +1,5 @@ +if m.IsDeleted == true && m.DeletedAt.IsZero() == true { + m.DeletedAt = time.Now() + } else if m.IsDeleted == false && m.DeletedAt.IsZero() == false { + m.DeletedAt = time.Time{} + } diff --git a/bin/templates/pkg/db/modified_at.go_ b/bin/templates/pkg/db/modified_at.go_ new file mode 100644 index 0000000..f648e98 --- /dev/null +++ b/bin/templates/pkg/db/modified_at.go_ @@ -0,0 +1 @@ +m.ModifiedAt = time.Now() \ No newline at end of file diff --git a/internal/config/config.go b/internal/config/config.go index 834348e..c5df29e 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -33,6 +33,8 @@ type SettingsINI struct { TEXT_TEMPLATE_TABLENAME string HAS_IS_DELETED bool READY_FOLDERNAME string + TEXT_DB_MODIFIED_AT string + TEXT_DB_IS_DELETED string } // FillSettings загружает переменные окружения в структуру из переменных окружения diff --git a/internal/create_files/create_files.go b/internal/create_files/create_files.go index 5250b00..12b5387 100644 --- a/internal/create_files/create_files.go +++ b/internal/create_files/create_files.go @@ -3,8 +3,10 @@ package create_files import ( "errors" "fmt" + "github.com/ManyakRus/crud_generator/internal/config" "github.com/ManyakRus/crud_generator/internal/mini_func" "github.com/ManyakRus/crud_generator/internal/types" + "github.com/ManyakRus/starter/micro" "github.com/iancoleman/strcase" "github.com/jinzhu/inflection" "strconv" @@ -240,3 +242,38 @@ func PrintableString(s string) string { return Otvet } + +// Find_Template_DB_Foldername - возвращает путь к папке +func Find_Template_DB_Foldername() string { + Otvet := "" + + DirBin := micro.ProgramDir_bin() + DirTemplates := DirBin + config.Settings.TEMPLATE_FOLDERNAME + micro.SeparatorFile() + DirTemplatesDB := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_DB + micro.SeparatorFile() + + Otvet = DirTemplatesDB + return Otvet +} + +// DeleteImportModel - удаляет лишний импорт модели +func DeleteImportModel(s string) string { + Otvet := s + + ModelURL := FindModelURL() + ImportName := micro.LastWord(ModelURL) + + pos1 := strings.Index(Otvet, ImportName+".") + if pos1 < 0 { + Otvet = strings.ReplaceAll(Otvet, `"`+ModelURL+`"`, "") + } + + return Otvet +} + +func FindModelURL() string { + Otvet := "" + + Otvet = config.Settings.SERVICE_REPOSITORY_URL + "/" + config.Settings.TEMPLATE_FOLDERNAME_MODEL + + return Otvet +} diff --git a/internal/create_files/db/db.go b/internal/create_files/db/db.go index b53e853..7915280 100644 --- a/internal/create_files/db/db.go +++ b/internal/create_files/db/db.go @@ -88,6 +88,9 @@ func CreateFiles(Table1 *types.Table) error { TextDB = DeleteFuncFind_byExtID(TextDB, Table1) TextDB = DeleteFuncFind_byExtIDCtx(TextDB, Table1) TextDB = AddTextOmit(TextDB, Table1) + TextDB = ReplaceText_modified_at(TextDB, Table1) + TextDB = ReplaceText_is_deleted_deleted_at(TextDB, Table1) + TextDB = create_files.DeleteImportModel(TextDB) //запись файла err = os.WriteFile(FilenameReadyDB, []byte(TextDB), constants.FILE_PERMISSIONS) @@ -305,13 +308,15 @@ func AddTextOmit(TextDB string, Table1 *types.Table) string { TextOmit := "" for _, Column1 := range Table1.MapColumns { + ColumnNameGo := Column1.NameGo TypeGo := Column1.TypeGo + + _, is_nullable_config := types.MapNullableFileds[ColumnNameGo] + if Column1.IsNullable == false { continue } - ColumnNameGo := Column1.NameGo - if TypeGo == "time.Time" { TextFind := `if m.` + ColumnNameGo + `.IsZero() == true {` pos1 := strings.Index(TextDB, TextFind) @@ -325,7 +330,7 @@ func AddTextOmit(TextDB string, Table1 *types.Table) string { } ` - } else if mini_func.IsNumberType(TypeGo) == true && Column1.TableKey != "" { + } else if mini_func.IsNumberType(TypeGo) == true && (Column1.TableKey != "" || is_nullable_config == true) { TextFind := `if m.` + ColumnNameGo + ` == 0 {` pos1 := strings.Index(TextDB, TextFind) if pos1 >= 0 { @@ -346,3 +351,40 @@ func AddTextOmit(TextDB string, Table1 *types.Table) string { return Otvet } + +// ReplaceText_modified_at - заменяет текст "Text_modified_at" на текст из файла +func ReplaceText_modified_at(s string, Table1 *types.Table) string { + Otvet := s + + TextNew := config.Settings.TEXT_DB_MODIFIED_AT + _, ok := Table1.MapColumns["modified_at"] + if ok == false { + TextNew = "" + } + + TextFind := "//Text_modified_at" + Otvet = strings.ReplaceAll(Otvet, TextFind, TextNew) + + return Otvet +} + +// ReplaceText_is_deleted_deleted_at - заменяет текст "Text_is_deleted_deleted_at" на текст из файла +func ReplaceText_is_deleted_deleted_at(s string, Table1 *types.Table) string { + Otvet := s + + TextNew := config.Settings.TEXT_DB_IS_DELETED + _, ok := Table1.MapColumns["is_deleted"] + if ok == false { + TextNew = "" + } + + _, ok = Table1.MapColumns["deleted_at"] + if ok == false { + TextNew = "" + } + + TextFind := "//Text_is_deleted_deleted_at" + Otvet = strings.ReplaceAll(Otvet, TextFind, TextNew) + + return Otvet +} diff --git a/internal/create_files/model/model.go b/internal/create_files/model/model.go index 0a4eab5..5f765ea 100644 --- a/internal/create_files/model/model.go +++ b/internal/create_files/model/model.go @@ -83,6 +83,7 @@ func CreateFiles(Table1 *types.Table) error { TextModel = DeleteFuncFind_byExtID(TextModel, ModelName, Table1) TextModel = AddImportTime(TextModel, Table1) + TextModel = create_files.DeleteImportModel(TextModel) //запись файла err = os.WriteFile(FilenameReadyModel, []byte(TextModel), constants.FILE_PERMISSIONS) diff --git a/internal/load_configs/load_configs.go b/internal/load_configs/load_configs.go index 3466dd3..4426bb0 100644 --- a/internal/load_configs/load_configs.go +++ b/internal/load_configs/load_configs.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "github.com/ManyakRus/crud_generator/internal/config" + "github.com/ManyakRus/crud_generator/internal/create_files" "github.com/ManyakRus/crud_generator/internal/types" "github.com/ManyakRus/crud_generator/pkg/dbmeta" "github.com/ManyakRus/starter/log" @@ -14,6 +15,9 @@ import ( func LoadConfigsAll() { LoadMappings() LoadNameReplace() + LoadNullable() + Load_TEXT_DB_MODIFIED_AT() + Load_TEXT_DB_IS_DELETED() } // LoadMappings - загружает маппинг ТипБД = ТипGolang, из файла .json @@ -48,3 +52,62 @@ func LoadNameReplace() { } } + +// LoadNullable - загружает список полей которые могут быть null +func LoadNullable() { + dir := micro.ProgramDir_bin() + FileName := dir + config.Settings.TEMPLATE_FOLDERNAME + micro.SeparatorFile() + "configs" + micro.SeparatorFile() + "nullable.json" + + var err error + + //чтение файла + bytes, err := os.ReadFile(FileName) + if err != nil { + TextError := fmt.Sprint("ReadFile() error: ", err) + log.Panic(TextError) + } + + //json в map + //var MapServiceURL2 = make(map[string]string) + err = json.Unmarshal(bytes, &types.MapNullableFileds) + if err != nil { + log.Panic("Unmarshal() error: ", err) + } + +} + +// Load_TEXT_DB_MODIFIED_AT - загружает текст DB_MODIFIED_AT +func Load_TEXT_DB_MODIFIED_AT() { + DirTemplatesDB := create_files.Find_Template_DB_Foldername() + FileName := DirTemplatesDB + "modified_at.go_" + + var err error + + //чтение файла + bytes, err := os.ReadFile(FileName) + if err != nil { + TextError := fmt.Sprint("ReadFile() error: ", err) + log.Error(TextError) + } + + config.Settings.TEXT_DB_MODIFIED_AT = string(bytes) + +} + +// Load_TEXT_DB_IS_DELETED - загружает текст DB_IS_DELETED +func Load_TEXT_DB_IS_DELETED() { + DirTemplatesDB := create_files.Find_Template_DB_Foldername() + FileName := DirTemplatesDB + "is_deleted.go_" + + var err error + + //чтение файла + bytes, err := os.ReadFile(FileName) + if err != nil { + TextError := fmt.Sprint("ReadFile() error: ", err) + log.Error(TextError) + } + + config.Settings.TEXT_DB_IS_DELETED = string(bytes) + +} diff --git a/internal/types/types.go b/internal/types/types.go index e08d38a..3baf90c 100644 --- a/internal/types/types.go +++ b/internal/types/types.go @@ -24,3 +24,5 @@ type Table struct { } var MapReplaceName = make(map[string]string, 0) + +var MapNullableFileds = make(map[string]string, 0)