1
0
mirror of https://github.com/ManyakRus/crud_generator.git synced 2024-11-24 08:22:42 +02:00

сделал nullable.json

This commit is contained in:
Nikitin Aleksandr 2023-11-02 18:19:33 +03:00
parent 7ed0bdad5b
commit 1b4b7ecfe2
10 changed files with 171 additions and 34 deletions

View File

@ -0,0 +1,3 @@
{
"ExtID": "0"
}

View File

@ -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
}

View File

@ -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{}
}

View File

@ -0,0 +1 @@
m.ModifiedAt = time.Now()

View File

@ -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 загружает переменные окружения в структуру из переменных окружения

View File

@ -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
}

View File

@ -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
}

View File

@ -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)

View File

@ -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)
}

View File

@ -24,3 +24,5 @@ type Table struct {
}
var MapReplaceName = make(map[string]string, 0)
var MapNullableFileds = make(map[string]string, 0)