From 98e4cf9dfe158fa4a2ba9f7a07207e2e35ccaa3d Mon Sep 17 00:00:00 2001 From: Nikitin Aleksandr Date: Thu, 16 Nov 2023 15:08:10 +0300 Subject: [PATCH] =?UTF-8?q?=D1=81=D0=B4=D0=B5=D0=BB=D0=B0=D0=BB=20Template?= =?UTF-8?q?FilenameCrudGo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/templates/pkg/db/db.go_ | 317 -------------- bin/templates/pkg/db/db_test.go_ | 124 ------ bin/templates/pkg/db/is_deleted.go_ | 5 - bin/templates/pkg/db/modified_at.go_ | 1 - .../pkg/object_model/entities/model.go_ | 6 +- internal/config/config.go | 12 +- internal/constants/constants.go | 2 + internal/create_files/create_files.go | 31 +- .../create_files/crud_starter/crud_starter.go | 2 +- internal/create_files/db/db_test.go | 1 - .../{db/db.go => db_crud/db_crud.go} | 22 +- internal/create_files/db_crud/db_crud_test.go | 1 + internal/create_files/db_tables/db_tables.go | 404 ++++++++++++++++++ .../create_files/db_tables/db_tables_test.go | 1 + internal/create_files/model/model.go | 46 +- internal/folders/folders.go | 2 +- internal/logic/logic.go | 11 +- 17 files changed, 492 insertions(+), 496 deletions(-) delete mode 100644 bin/templates/pkg/db/db.go_ delete mode 100644 bin/templates/pkg/db/db_test.go_ delete mode 100644 bin/templates/pkg/db/is_deleted.go_ delete mode 100644 bin/templates/pkg/db/modified_at.go_ delete mode 100644 internal/create_files/db/db_test.go rename internal/create_files/{db/db.go => db_crud/db_crud.go} (93%) create mode 100644 internal/create_files/db_crud/db_crud_test.go create mode 100644 internal/create_files/db_tables/db_tables.go create mode 100644 internal/create_files/db_tables/db_tables_test.go diff --git a/bin/templates/pkg/db/db.go_ b/bin/templates/pkg/db/db.go_ deleted file mode 100644 index 52e2c1b..0000000 --- a/bin/templates/pkg/db/db.go_ +++ /dev/null @@ -1,317 +0,0 @@ -package db_lawsuit_status_types - -import ( - "context" - "errors" - "fmt" - "github.com/ManyakRus/starter/micro" - "github.com/ManyakRus/starter/postgres_gorm" - "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/constants" - "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types" - "gorm.io/gorm" - "time" - "github.com/ManyakRus/starter/contextmain" -) - -// TableName - имя таблицы в БД Postgres -const TableName string = "lawsuit_status_types" - -// Crud_DB - объект для CRUD операций через БД -type Crud_DB struct { -} - -// Read - находит запись в БД по ID -func (crud Crud_DB) Read(m *lawsuit_status_types.LawsuitStatusType) error { - var err error - - ctxMain := contextmain.GetContext() - ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_DB_SECONDS)) - defer ctxCancelFunc() - - err = crud.Read_ctx(ctx, m) - return err -} - -// Read_ctx - находит запись в БД по ID -func (crud Crud_DB) Read_ctx(ctx context.Context, m *lawsuit_status_types.LawsuitStatusType) error { - var err error - - if micro.ContextDone(ctx) == true { - err = context.Canceled - return err - } - - id := int64(m.ID) - - db := postgres_gorm.GetConnection() - db.WithContext(ctx) - - tx := db.First(m, id) - err = tx.Error - - return err -} - -// Save - записывает новый или существующий объект в базу данных -func (crud Crud_DB) Save(m *lawsuit_status_types.LawsuitStatusType) error { - ctxMain := contextmain.GetContext() - ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_DB_SECONDS)) - defer ctxCancelFunc() - - err := crud.Save_ctx(ctx, m) - return err -} - -// Save_ctx - записывает новый или существующий объект в базу данных -func (crud Crud_DB) Save_ctx(ctx context.Context, m *lawsuit_status_types.LawsuitStatusType) error { - var err error - if micro.ContextDone(ctx) == true { - err = context.Canceled - return err - } - - is_create := !micro.BoolFromInt64(int64(m.ID)) - err = crud.create_update_ctx(ctx, m, is_create) - return err -} - -// Update - записывает существующий объект в базу данных -func (crud Crud_DB) Update(m *lawsuit_status_types.LawsuitStatusType) error { - ctxMain := contextmain.GetContext() - ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_DB_SECONDS)) - defer ctxCancelFunc() - - err := crud.Update_ctx(ctx, m) - return err -} - -// Update_ctx - записывает существующий объект в базу данных -func (crud Crud_DB) Update_ctx(ctx context.Context, m *lawsuit_status_types.LawsuitStatusType) error { - var err error - if micro.ContextDone(ctx) == true { - err = context.Canceled - return err - } - - err = crud.create_update_ctx(ctx, m, false) - return err -} - -// Create - записывает новый объект в базу данных -func (crud Crud_DB) Create(m *lawsuit_status_types.LawsuitStatusType) error { - ctxMain := contextmain.GetContext() - ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_DB_SECONDS)) - defer ctxCancelFunc() - - err := crud.Create_ctx(ctx, m) - return err -} - -// Create_ctx - записывает новый объект в базу данных -func (crud Crud_DB) Create_ctx(ctx context.Context, m *lawsuit_status_types.LawsuitStatusType) error { - var err error - if micro.ContextDone(ctx) == true { - err = context.Canceled - return err - } - - err = crud.create_update_ctx(ctx, m, true) - return err -} - -// create_update - записывает объект в базу данных -func (crud Crud_DB) create_update(m *lawsuit_status_types.LawsuitStatusType, is_create bool) error { - var err error - - ctxMain := contextmain.GetContext() - ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_DB_SECONDS)) - defer ctxCancelFunc() - - err = crud.create_update_ctx(ctx, m, is_create) - return err -} - -// create_update_ctx - записывает объект в базу данных -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: ", int64(m.ID)) - - if micro.ContextDone(ctx) == true { - err = context.Canceled - return err - } - - // проверка ID - if is_create == true { - 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 int64(m.ID) == 0 { - TextError := fmt.Sprint("db.Save() ", TableName, " error: id =0") - err = errors.New(TextError) - // log.Panic(sError) - return err - } - - // - db := postgres_gorm.GetConnection() - db.WithContext(ctx) - - // заполним даты - //Text_modified_at - //Text_is_deleted_deleted_at - - //колонки с null - tx := db - MassOmit := make([]string, 0) - var ColumnName string - - - //игнор пустых колонок - tx = tx.Omit(MassOmit...) - - // запись - if is_create == true { - tx = tx.Create(&m) - } else { - tx = tx.Save(&m) - } - err = tx.Error - if err != nil { - return err - } - - // запишем NULL в пустые колонки - for f := 0; f < len(MassOmit); f++ { - ColumnName := MassOmit[f] - tx = db.Model(&m).Update(ColumnName, gorm.Expr("NULL")) - - err = tx.Error - if err != nil { - TextError := fmt.Sprint("db.Update() ", TableName, " id: ", m.ID, " error: ", err) - err = errors.New(TextError) - return err - // log.Panic(sError) - } - } - - return err -} - -// Delete - записывает is_deleted = true -func (crud Crud_DB) Delete(m *lawsuit_status_types.LawsuitStatusType) error { - var err error - - ctxMain := contextmain.GetContext() - ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_DB_SECONDS)) - defer ctxCancelFunc() - - err = crud.Delete_ctx(ctx, m) - return err -} - -// Delete_ctx - записывает is_deleted = true -func (crud Crud_DB) Delete_ctx(ctx context.Context, m *lawsuit_status_types.LawsuitStatusType) error { - var err error - - if micro.ContextDone(ctx) == true { - err = context.Canceled - return err - } - - m2 := lawsuit_status_types.LawsuitStatusType{} - m2.ID = m.ID - err = crud.Read_ctx(ctx, &m2) - if err != nil { - return err - } - - m2.IsDeleted = true - m.IsDeleted = true - - err = crud.Save_ctx(ctx, &m2) - - return err -} - -// Restore - записывает is_deleted = true -func (crud Crud_DB) Restore(m *lawsuit_status_types.LawsuitStatusType) error { - var err error - - ctxMain := contextmain.GetContext() - ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_DB_SECONDS)) - defer ctxCancelFunc() - - err = crud.Restore_ctx(ctx, m) - return err -} - -// Restore_ctx - записывает is_deleted = true -func (crud Crud_DB) Restore_ctx(ctx context.Context, m *lawsuit_status_types.LawsuitStatusType) error { - var err error - - if micro.ContextDone(ctx) == true { - err = context.Canceled - return err - } - - m2 := lawsuit_status_types.LawsuitStatusType{} - m2.ID = m.ID - err = crud.Read_ctx(ctx, &m2) - if err != nil { - return err - } - - m2.IsDeleted = false - m.IsDeleted = false - - err = crud.Save_ctx(ctx, &m2) - - return err -} - -// Find_ByExtID - находит запись в БД по ext_id и connection_id -func (crud Crud_DB) Find_ByExtID(m *lawsuit_status_types.LawsuitStatusType) error { - var err error - - if m.ExtID == 0 { - err = errors.New("Error: ext_id =0") - return err - } - - // - ctxMain := contextmain.GetContext() - ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_DB_SECONDS)) - defer ctxCancelFunc() - - err = crud.Find_ByExtID_ctx(ctx, m) - - return err -} - -// Find_ByExtID_ctx - находит запись в БД по ext_id и connection_id -func (crud Crud_DB) Find_ByExtID_ctx(ctx context.Context, m *lawsuit_status_types.LawsuitStatusType) error { - var err error - - if micro.ContextDone(ctx) == true { - err = context.Canceled - return err - } - - if m.ExtID == 0 { - err = errors.New("Error: ExtID=0") - return err - } - - db := postgres_gorm.GetConnection() - db.WithContext(ctx) - - tx := db.Where("ext_id = ?", m.ExtID).Where("connection_id = ?", m.ConnectionID).First(m) - err = tx.Error - - return err -} diff --git a/bin/templates/pkg/db/db_test.go_ b/bin/templates/pkg/db/db_test.go_ deleted file mode 100644 index e943429..0000000 --- a/bin/templates/pkg/db/db_test.go_ +++ /dev/null @@ -1,124 +0,0 @@ -package db_lawsuit_status_types - -import ( - "github.com/ManyakRus/starter/config" - "github.com/ManyakRus/starter/postgres_gorm" - "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types" - "testing" -) - -const Postgres_ID_Test = 1 - -func TestRead(t *testing.T) { - config.LoadEnv() - - postgres_gorm.Connect() - defer postgres_gorm.CloseConnection() - - crud := Crud_DB{} - Otvet := lawsuit_status_types.LawsuitStatusType{} - Otvet.ID = Postgres_ID_Test - err := crud.Read(&Otvet) - if err != nil { - t.Error("TestRead() error: ", err) - } - - if Otvet.ID == 0 { - t.Error(TableName + "_test.TestRead() error ID=0 ") - } else { - t.Log(TableName+"_test.TestRead() Otvet: ", Otvet.ID) - } -} - -func TestSave(t *testing.T) { - config.LoadEnv() - - postgres_gorm.Connect() - defer postgres_gorm.CloseConnection() - - crud := Crud_DB{} - Otvet := lawsuit_status_types.LawsuitStatusType{} - Otvet.ID = Postgres_ID_Test - err := crud.Read(&Otvet) - if err != nil { - t.Error("TestSave() error: ", err) - } - - if Otvet.ID == 0 { - t.Error(TableName + "_test.TestSave() error ID=0 ") - } - - err = crud.Save(&Otvet) - if err != nil { - t.Error("TestSave() error: ", err) - } - t.Log(TableName+"_test.TestSave() Otvet: ", Otvet.ID) - -} - -func TestDelete(t *testing.T) { - config.LoadEnv() - - postgres_gorm.Connect() - defer postgres_gorm.CloseConnection() - - crud := Crud_DB{} - Otvet := lawsuit_status_types.LawsuitStatusType{} - Otvet.ID = Postgres_ID_Test - err := crud.Read(&Otvet) - if err != nil { - t.Error("TestDelete() error: ", err) - } - - if Otvet.IsDeleted == false { - err = crud.Delete(&Otvet) - if err != nil { - t.Error("TestDelete() error: ", err) - } - - err = crud.Restore(&Otvet) - if err != nil { - t.Error("TestDelete() error: ", err) - } - } else { - err = crud.Restore(&Otvet) - if err != nil { - t.Error("TestDelete() error: ", err) - } - - err = crud.Delete(&Otvet) - if err != nil { - t.Error("TestDelete() error: ", err) - } - - } - -} - - -func TestFind_ByExtID(t *testing.T) { - config.LoadEnv() - postgres_gorm.Connect() - defer postgres_gorm.CloseConnection() - - crud := Crud_DB{} - Otvet := lawsuit_status_types.LawsuitStatusType{} - Otvet.ID = Postgres_ID_Test - err := crud.Read(&Otvet) - if err != nil { - t.Error("TestFind_ByExtID() error: ", err) - } - - if Otvet.ExtID ==0 { - return - } - - err = crud.Find_ByExtID(&Otvet) - if err != nil { - t.Error("TestFind_ByExtID() error: ", err) - } - - if Otvet.ID == 0 { - t.Error("TestFind_ByExtID() error: ID =0") - } -} diff --git a/bin/templates/pkg/db/is_deleted.go_ b/bin/templates/pkg/db/is_deleted.go_ deleted file mode 100644 index adc19f4..0000000 --- a/bin/templates/pkg/db/is_deleted.go_ +++ /dev/null @@ -1,5 +0,0 @@ -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_ deleted file mode 100644 index f648e98..0000000 --- a/bin/templates/pkg/db/modified_at.go_ +++ /dev/null @@ -1 +0,0 @@ -m.ModifiedAt = time.Now() \ No newline at end of file diff --git a/bin/templates/pkg/object_model/entities/model.go_ b/bin/templates/pkg/object_model/entities/model.go_ index 7170e8b..ce9cb92 100644 --- a/bin/templates/pkg/object_model/entities/model.go_ +++ b/bin/templates/pkg/object_model/entities/model.go_ @@ -1,13 +1,11 @@ package lawsuit_status_types import ( - "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/tables/lawsuit_status_types" ) // LawsuitStatusType type LawsuitStatusType struct { - entities.CommonStruct - entities.NameStruct - Code string `json:"code" gorm:"column:code;default:0"` + Table_LawsuitStatusType } diff --git a/internal/config/config.go b/internal/config/config.go index 9f9f5df..8812f14 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -15,7 +15,8 @@ type SettingsINI struct { EXCLUDE_TABLES string TEMPLATE_FOLDERNAME string TEMPLATE_FOLDERNAME_MODEL string - TEMPLATE_FOLDERNAME_DB string + TEMPLATE_FOLDERNAME_CRUD string + TEMPLATE_FOLDERNAME_TABLES string TEMPLATE_FOLDERNAME_GRPC string TEMPLATE_FOLDERNAME_GRPC_PROTO string TEMPLATE_FOLDERNAME_GRPC_SERVER string @@ -46,10 +47,13 @@ type SettingsINI struct { TEXT_DB_IS_DELETED string USE_DEFAULT_TEMPLATE bool PREFIX_SERVER_GRPC string + PREFIX_CRUD string + PREFIX_MODEL string COMMENT_MODEL_STRUCT string TEXT_MODULE_GENERATED string TEMPLATE_FOLDERNAME_MAIN string TEMPLATE_REPOSITORY_URL string + PREFIX_TABLE string } // FillSettings загружает переменные окружения в структуру из переменных окружения @@ -61,7 +65,7 @@ func FillSettings() { Settings.EXCLUDE_TABLES = os.Getenv("EXCLUDE_TABLES") Settings.TEMPLATE_FOLDERNAME = os.Getenv("TEMPLATE_FOLDERNAME") Settings.TEMPLATE_FOLDERNAME_MODEL = os.Getenv("TEMPLATE_FOLDERNAME_MODEL") - Settings.TEMPLATE_FOLDERNAME_DB = os.Getenv("TEMPLATE_FOLDERNAME_DB") + Settings.TEMPLATE_FOLDERNAME_CRUD = os.Getenv("TEMPLATE_FOLDERNAME_CRUD") Settings.TEMPLATE_FOLDERNAME_GRPC_PROTO = os.Getenv("TEMPLATE_FOLDERNAME_GRPC_PROTO") Settings.TEMPLATE_FOLDERNAME_GRPC_SERVER = os.Getenv("TEMPLATE_FOLDERNAME_GRPC_SERVER") Settings.TEMPLATE_FOLDERNAME_GRPC_CLIENT = os.Getenv("TEMPLATE_FOLDERNAME_GRPC_CLIENT") @@ -140,6 +144,10 @@ func FillSettings() { Settings.TEMPLATE_FOLDERNAME_MAIN = os.Getenv("TEMPLATE_FOLDERNAME_MAIN") Settings.TEMPLATE_REPOSITORY_URL = os.Getenv("TEMPLATE_REPOSITORY_URL") Settings.TEMPLATE_FOLDERNAME_GRPC = os.Getenv("TEMPLATE_FOLDERNAME_GRPC") + Settings.PREFIX_CRUD = os.Getenv("PREFIX_CRUD") + Settings.PREFIX_TABLE = os.Getenv("PREFIX_TABLE") + Settings.TEMPLATE_FOLDERNAME_TABLES = os.Getenv("TEMPLATE_FOLDERNAME_TABLES") + Settings.PREFIX_MODEL = os.Getenv("PREFIX_MODEL") } diff --git a/internal/constants/constants.go b/internal/constants/constants.go index 1262c22..61b2837 100644 --- a/internal/constants/constants.go +++ b/internal/constants/constants.go @@ -11,3 +11,5 @@ Need fill settings in settings.txt file const FILE_PERMISSIONS = 0666 const CONFIG_FOLDER_NAME = "configs_" + +const TemplateFilenameCrudGo = "crud.go_" diff --git a/internal/create_files/create_files.go b/internal/create_files/create_files.go index c63cfef..3cb3dec 100644 --- a/internal/create_files/create_files.go +++ b/internal/create_files/create_files.go @@ -230,7 +230,7 @@ func Find_Template_DB_Foldername() string { DirBin := micro.ProgramDir_bin() DirTemplates := DirBin + config.Settings.TEMPLATE_FOLDERNAME + micro.SeparatorFile() - DirTemplatesDB := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_DB + micro.SeparatorFile() + DirTemplatesDB := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_CRUD + micro.SeparatorFile() Otvet = DirTemplatesDB return Otvet @@ -306,6 +306,15 @@ func FindProtoURL() string { return Otvet } +// FindTablesURL - возвращает URL репозитория с пакетом "tables" +func FindTablesURL() string { + Otvet := "" + + Otvet = config.Settings.SERVICE_REPOSITORY_URL + "/" + config.Settings.TEMPLATE_FOLDERNAME_TABLES + + return Otvet +} + // FindGRPCProtoURL - возвращает URL репозитория с пакетом "grpc_proto" func FindGRPCProtoURL() string { Otvet := "" @@ -324,17 +333,23 @@ func FindModelTableURL(TableName string) string { return Otvet } -func FindTextDefaultValue(Type_go string) string { +func FindTextDefaultValue(Column1 *types.Column) string { var Otvet string sValue := "" - switch Type_go { - case "string": - sValue = "\\\"\\\"" - case "int", "int32", "int64", "float32", "float64", "uint", "uint32", "uint64": - sValue = "0" - case "time.Time": + Type_go := Column1.TypeGo + if Column1.TableKey != "" { sValue = "null" + } else { + + switch Type_go { + case "string": + sValue = "\\\"\\\"" + case "int", "int32", "int64", "float32", "float64", "uint", "uint32", "uint64": + sValue = "0" + case "time.Time": + sValue = "null" + } } if sValue != "" { diff --git a/internal/create_files/crud_starter/crud_starter.go b/internal/create_files/crud_starter/crud_starter.go index a874c15..7af5c04 100644 --- a/internal/create_files/crud_starter/crud_starter.go +++ b/internal/create_files/crud_starter/crud_starter.go @@ -132,7 +132,7 @@ func FindTextImportModel1(Table1 *types.Table) string { // FindTextImportDB1 - возвращает текст импорта DB для 1 таблицы func FindTextImportDB1(Table1 *types.Table) string { TableName := strings.ToLower(Table1.Name) - DB_URL := config.Settings.SERVICE_REPOSITORY_URL + "/" + config.Settings.TEMPLATE_FOLDERNAME_DB + DB_URL := config.Settings.SERVICE_REPOSITORY_URL + "/" + config.Settings.TEMPLATE_FOLDERNAME_CRUD Otvet := "\n\t\"" + DB_URL + "/db_" + TableName + `"` return Otvet diff --git a/internal/create_files/db/db_test.go b/internal/create_files/db/db_test.go deleted file mode 100644 index 3a49c63..0000000 --- a/internal/create_files/db/db_test.go +++ /dev/null @@ -1 +0,0 @@ -package db diff --git a/internal/create_files/db/db.go b/internal/create_files/db_crud/db_crud.go similarity index 93% rename from internal/create_files/db/db.go rename to internal/create_files/db_crud/db_crud.go index 3acef3c..ea819b4 100644 --- a/internal/create_files/db/db.go +++ b/internal/create_files/db_crud/db_crud.go @@ -1,4 +1,4 @@ -package db +package db_crud import ( "github.com/ManyakRus/crud_generator/internal/config" @@ -53,13 +53,13 @@ func CreateFiles(Table1 *types.Table) error { DirBin := micro.ProgramDir_bin() DirTemplates := DirBin + config.Settings.TEMPLATE_FOLDERNAME + micro.SeparatorFile() DirReady := DirBin + config.Settings.READY_FOLDERNAME + micro.SeparatorFile() - DirTemplatesDB := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_DB + micro.SeparatorFile() - DirReadyDB := DirReady + config.Settings.TEMPLATE_FOLDERNAME_DB + micro.SeparatorFile() + DirTemplatesDB := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_CRUD + micro.SeparatorFile() + DirReadyDB := DirReady + config.Settings.TEMPLATE_FOLDERNAME_CRUD + micro.SeparatorFile() - FilenameTemplateDB := DirTemplatesDB + "db.go_" + FilenameTemplateDB := DirTemplatesDB + constants.TemplateFilenameCrudGo TableName := strings.ToLower(Table1.Name) - DirTable := DirReadyDB + "db_" + TableName - FilenameReadyDB := DirTable + micro.SeparatorFile() + "db_" + TableName + ".go" + DirTable := DirReadyDB + config.Settings.PREFIX_CRUD + TableName + FilenameReadyDB := DirTable + micro.SeparatorFile() + config.Settings.PREFIX_CRUD + TableName + ".go" //создадим каталог ok, err := micro.FileExists(DirTable) @@ -114,12 +114,12 @@ func CreateTestFiles(Table1 *types.Table) error { DirBin := micro.ProgramDir_bin() DirTemplates := DirBin + config.Settings.TEMPLATE_FOLDERNAME + micro.SeparatorFile() DirReady := DirBin + config.Settings.READY_FOLDERNAME + micro.SeparatorFile() - DirTemplatesDB := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_DB + micro.SeparatorFile() - DirReadyDB := DirReady + config.Settings.TEMPLATE_FOLDERNAME_DB + micro.SeparatorFile() + DirTemplatesDB := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_CRUD + micro.SeparatorFile() + DirReadyDB := DirReady + config.Settings.TEMPLATE_FOLDERNAME_CRUD + micro.SeparatorFile() - FilenameTemplateDB := DirTemplatesDB + "db_test.go_" - DirTable := DirReadyDB + "db_" + TableName - FilenameReadyDB := DirTable + micro.SeparatorFile() + "db_" + TableName + "_test.go" + FilenameTemplateDB := DirTemplatesDB + config.Settings.PREFIX_CRUD + "test.go_" + DirTable := DirReadyDB + config.Settings.PREFIX_CRUD + TableName + FilenameReadyDB := DirTable + micro.SeparatorFile() + config.Settings.PREFIX_CRUD + TableName + "_test.go" //создадим каталог ok, err := micro.FileExists(DirTable) diff --git a/internal/create_files/db_crud/db_crud_test.go b/internal/create_files/db_crud/db_crud_test.go new file mode 100644 index 0000000..42e8858 --- /dev/null +++ b/internal/create_files/db_crud/db_crud_test.go @@ -0,0 +1 @@ +package db_crud diff --git a/internal/create_files/db_tables/db_tables.go b/internal/create_files/db_tables/db_tables.go new file mode 100644 index 0000000..2fa9729 --- /dev/null +++ b/internal/create_files/db_tables/db_tables.go @@ -0,0 +1,404 @@ +package db_tables + +import ( + "errors" + "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/types" + "github.com/ManyakRus/starter/log" + "github.com/ManyakRus/starter/micro" + "os" + "sort" + "strings" +) + +// CreateAllFiles - создаёт все файлы в папке model +func CreateAllFiles(MapAll map[string]*types.Table) error { + var err error + + for _, table1 := range MapAll { + err = CreateFiles(table1) + if err != nil { + log.Error("CreateFiles() table: ", table1.Name, " error: ", err) + return err + } + } + + return err +} + +// CreateFiles - создаёт 1 файл в папке model +func CreateFiles(Table1 *types.Table) error { + var err error + + TableName := strings.ToLower(Table1.Name) + + //чтение файлов + DirBin := micro.ProgramDir_bin() + DirTemplates := DirBin + config.Settings.TEMPLATE_FOLDERNAME + micro.SeparatorFile() + DirReady := DirBin + config.Settings.READY_FOLDERNAME + micro.SeparatorFile() + DirTemplatesTable := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_TABLES + micro.SeparatorFile() + DirReadyTable := DirReady + config.Settings.TEMPLATE_FOLDERNAME_TABLES + micro.SeparatorFile() + TableName + micro.SeparatorFile() + + //создадим каталог + ok, err := micro.FileExists(DirReadyTable) + if ok == false { + err = os.MkdirAll(DirReadyTable, 0777) + if err != nil { + log.Panic("Mkdir() ", DirReadyTable, " error: ", err) + } + } + + // создание файла struct + if config.Settings.NEED_CREATE_MODEL_STRUCT == true { + err = CreateFilesTable_struct(Table1, DirTemplatesTable, DirReadyTable) + if err != nil { + log.Error("CreateFilesTable_struct() table: ", Table1.Name, " error: ", err) + return err + } + } + + return err +} + +// CreateFilesTable_struct - создаёт 1 файл со структурой в папке model +func CreateFilesTable_struct(Table1 *types.Table, DirTemplatesTable, DirReadyTable string) error { + var err error + var ModelName string + + TableName := strings.ToLower(Table1.Name) + FilenameTemplateModel := DirTemplatesTable + "table.go_" + FilenameReadyModel := DirReadyTable + config.Settings.PREFIX_TABLE + TableName + ".go" + + //чтение файла шаблона + bytes, err := os.ReadFile(FilenameTemplateModel) + if err != nil { + log.Panic("ReadFile() ", FilenameTemplateModel, " error: ", err) + } + TextModel := string(bytes) + + //создание текста + TextModel, TextModelStruct, ModelName, err := FindTextModelStruct(TextModel, Table1) + TextModel = ReplaceModelStruct(TextModel, TextModelStruct) + + // + TextModel = strings.ReplaceAll(TextModel, config.Settings.TEXT_TEMPLATE_MODEL, ModelName) + TextModel = strings.ReplaceAll(TextModel, config.Settings.TEXT_TEMPLATE_TABLENAME, Table1.Name) + //TextModel = config.Settings.TEXT_MODULE_GENERATED + TextModel + + if config.Settings.HAS_IS_DELETED == true { + TextModel = DeleteFuncDelete(TextModel, ModelName, Table1) + TextModel = DeleteFuncRestore(TextModel, ModelName, Table1) + } + TextModel = DeleteFuncFind_byExtID(TextModel, ModelName, Table1) + + TextModel = create_files.CheckAndAddImportTime_FromText(TextModel) + TextModel = create_files.DeleteImportModel(TextModel) + + //замена импортов на новые URL + TextModel = create_files.ReplaceServiceURLImports(TextModel) + + //запись файла + err = os.WriteFile(FilenameReadyModel, []byte(TextModel), constants.FILE_PERMISSIONS) + + return err +} + +// FindTextModelStruct - возвращает текст структуры и тегов gorm +func FindTextModelStruct(TextModel string, Table1 *types.Table) (string, string, string, error) { + var Otvet string + var ModelName string + var err error + + TableName := Table1.Name + ModelName = create_files.FindSingularName(TableName) + ModelName = create_files.FormatName(ModelName) + Table1.NameGo = ModelName + COMMENT_MODEL_STRUCT := config.Settings.COMMENT_MODEL_STRUCT + + Otvet = `// ` + ModelName + ` - ` + COMMENT_MODEL_STRUCT + TableName + `: ` + Table1.Comment + ` +type ` + ModelName + ` struct { +` + + //сортировка + keys := make([]string, 0, len(Table1.MapColumns)) + for k := range Table1.MapColumns { + keys = append(keys, k) + } + sort.Strings(keys) + + 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_TABLES) + + 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" + } + + //цикл по всем колонкам + for _, key1 := range keys { + Column1, _ := Table1.MapColumns[key1] + + //пропускаем колонки если они уже есть в 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 + } + + var TextColumn string + TextModel, TextColumn = FindTextColumn(TextModel, Table1, Column1) + Otvet = Otvet + TextColumn + "\n" + Table1.MapColumns[key1] = Column1 + } + + Otvet = Otvet + "\n}" + return TextModel, Otvet, ModelName, err +} + +// FindTextColumn - возвращает текст gorm +func FindTextColumn(TextModel string, Table1 *types.Table, Column1 *types.Column) (string, string) { + Otvet := "" + // Code string `json:"code" gorm:"column:code;default:0"` + + ColumnName := Column1.Name + ColumnNameLowerCase := strings.ToLower(ColumnName) + ColumnModelName := create_files.FormatName(Column1.Name) + //Column1.NameGo = ColumnModelName + //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 + TextModel, Type_go = FindColumnTypeGoImport(TextModel, Table1, Column1) + //Column1.TypeGo = Type_go + TextDefaultValue := "" + if Column1.IsIdentity == false { + TextDefaultValue = create_files.FindTextDefaultValue(Column1) + } + TextPrimaryKey := FindTextPrimaryKey(Column1.IsIdentity) + Description := Column1.Description + Description = create_files.PrintableString(Description) //экранирование символов + + TextAutoCreateTime := "" + TextAutoUpdateTime := "" + if config.Settings.USE_DEFAULT_TEMPLATE == true { + if ColumnNameLowerCase == "created_at" { + TextAutoCreateTime = ";autoCreateTime" + } + + if ColumnNameLowerCase == "modified_at" { + TextAutoUpdateTime = ";autoUpdateTime" + } + } + + Otvet = Otvet + "\t" + ColumnModelName + " " + Type_go + "\t" + Otvet = Otvet + "`json:\"" + ColumnName + "\"" + Otvet = Otvet + " gorm:\"column:" + ColumnName + TextPrimaryKey + TextDefaultValue + TextAutoCreateTime + TextAutoUpdateTime + "\"" + //Otvet = Otvet + " db:\"" + ColumnName + "\"" + Otvet = Otvet + "`" + Otvet = Otvet + "\t//" + Description + + return TextModel, Otvet +} + +// FindTextPrimaryKey - возвращает строку gorm для primaryKey +func FindTextPrimaryKey(Is_identity bool) string { + Otvet := "" + + if Is_identity == true { + Otvet = ";primaryKey;autoIncrement:true" + } + + return Otvet +} + +// ReplaceModelStruct - заменяет структуру модели на новую +func ReplaceModelStruct(TextTemplateModel, TextModelStruct string) string { + Otvet := "" + + ModelName := config.Settings.TEXT_TEMPLATE_MODEL + + //найдём начало и конец + TextFind1 := "// " + ModelName + pos1 := strings.Index(TextTemplateModel, TextFind1) + if pos1 < 0 { + TextFind1 := "type " + ModelName + " struct {" + pos1 = strings.Index(TextTemplateModel, TextFind1) + } + + if pos1 < 0 { + 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 +} + +// DeleteFuncFind_byExtID - удаляет функцию Find_ByExtID() +func DeleteFuncFind_byExtID(TextModel, Modelname string, Table1 *types.Table) string { + Otvet := TextModel + + // + _, ok1 := Table1.MapColumns["ext_id"] + + // + _, ok2 := Table1.MapColumns["connection_id"] + if ok1 == true && ok2 == true { + return Otvet + } + + //FirstSymbol := strings.ToLower(Modelname)[:1] + TextFind := "Find_ByExtID(*" + Modelname + ") error" + Otvet = strings.ReplaceAll(Otvet, TextFind, "") + + TextFind = "\n// Find_ByExtID " + 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 +} + +// FindColumnTypeGoImport - заменяет ID на Alias +func FindColumnTypeGoImport(TextModel string, Table1 *types.Table, Column1 *types.Column) (string, string) { + Otvet := Column1.TypeGo + + //тип колонки из БД или из convert_id.json + TableName := Table1.Name + ColumnName := Column1.Name + TextConvert, ok := types.MapConvertID[TableName+"."+ColumnName] + 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 +} + +// 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 +} diff --git a/internal/create_files/db_tables/db_tables_test.go b/internal/create_files/db_tables/db_tables_test.go new file mode 100644 index 0000000..1660e29 --- /dev/null +++ b/internal/create_files/db_tables/db_tables_test.go @@ -0,0 +1 @@ +package db_tables diff --git a/internal/create_files/model/model.go b/internal/create_files/model/model.go index 5cbd3f3..3e7b2c1 100644 --- a/internal/create_files/model/model.go +++ b/internal/create_files/model/model.go @@ -73,11 +73,11 @@ func CreateFiles(Table1 *types.Table) error { // CreateFilesModel_struct - создаёт 1 файл со структурой в папке model func CreateFilesModel_struct(Table1 *types.Table, DirTemplatesModel, DirReadyModel string) error { var err error - var ModelName string + //var ModelName string TableName := strings.ToLower(Table1.Name) FilenameTemplateModel := DirTemplatesModel + "model.go_" - FilenameReadyModel := DirReadyModel + TableName + ".go" + FilenameReadyModel := DirReadyModel + config.Settings.PREFIX_MODEL + TableName + ".go" //чтение файла шаблона bytes, err := os.ReadFile(FilenameTemplateModel) @@ -87,25 +87,33 @@ func CreateFilesModel_struct(Table1 *types.Table, DirTemplatesModel, DirReadyMod TextModel := string(bytes) //создание текста - TextModel, TextModelStruct, ModelName, err := FindTextModelStruct(TextModel, Table1) - TextModel = ReplaceModelStruct(TextModel, TextModelStruct) - + //TextModel, TextModelStruct, ModelName, err := FindTextModelStruct(TextModel, Table1) + //TextModel = ReplaceModelStruct(TextModel, TextModelStruct) // - TextModel = strings.ReplaceAll(TextModel, config.Settings.TEXT_TEMPLATE_MODEL, ModelName) - TextModel = strings.ReplaceAll(TextModel, config.Settings.TEXT_TEMPLATE_TABLENAME, Table1.Name) - //TextModel = config.Settings.TEXT_MODULE_GENERATED + TextModel - - if config.Settings.HAS_IS_DELETED == true { - TextModel = DeleteFuncDelete(TextModel, ModelName, Table1) - TextModel = DeleteFuncRestore(TextModel, ModelName, Table1) - } - TextModel = DeleteFuncFind_byExtID(TextModel, ModelName, Table1) + //// + //TextModel = strings.ReplaceAll(TextModel, config.Settings.TEXT_TEMPLATE_MODEL, ModelName) + //TextModel = strings.ReplaceAll(TextModel, config.Settings.TEXT_TEMPLATE_TABLENAME, Table1.Name) + ////TextModel = config.Settings.TEXT_MODULE_GENERATED + TextModel + // + //if config.Settings.HAS_IS_DELETED == true { + // TextModel = DeleteFuncDelete(TextModel, ModelName, Table1) + // TextModel = DeleteFuncRestore(TextModel, ModelName, Table1) + //} + //TextModel = DeleteFuncFind_byExtID(TextModel, ModelName, Table1) TextModel = create_files.CheckAndAddImportTime_FromText(TextModel) - TextModel = create_files.DeleteImportModel(TextModel) + //TextModel = create_files.DeleteImportModel(TextModel) //замена импортов на новые URL - TextModel = create_files.ReplaceServiceURLImports(TextModel) + //TextModel = create_files.ReplaceServiceURLImports(TextModel) + + //замена импортов на новые URL + if config.Settings.USE_DEFAULT_TEMPLATE == true { + TextModel = create_files.DeleteTemplateRepositoryImports(TextModel) + + TablesURL := create_files.FindTablesURL() + TextModel = create_files.AddImport(TextModel, TablesURL) + } //запись файла err = os.WriteFile(FilenameReadyModel, []byte(TextModel), constants.FILE_PERMISSIONS) @@ -245,7 +253,7 @@ func FindTextColumn(TextModel string, Table1 *types.Table, Column1 *types.Column //Column1.TypeGo = Type_go TextDefaultValue := "" if Column1.IsIdentity == false { - TextDefaultValue = create_files.FindTextDefaultValue(Type_go) + TextDefaultValue = create_files.FindTextDefaultValue(Column1) } TextPrimaryKey := FindTextPrimaryKey(Column1.IsIdentity) Description := Column1.Description @@ -415,8 +423,8 @@ func FindColumnTypeGoImport(TextModel string, Table1 *types.Table, Column1 *type //тип колонки из БД или из convert_id.json TableName := Table1.Name - //IDName := Column1.NameGo - TextConvert, ok := types.MapConvertID[TableName+"."+TableName] + ColumnName := Column1.Name + TextConvert, ok := types.MapConvertID[TableName+"."+ColumnName] if ok == false { return TextModel, Otvet } diff --git a/internal/folders/folders.go b/internal/folders/folders.go index 914a318..34d20d7 100644 --- a/internal/folders/folders.go +++ b/internal/folders/folders.go @@ -112,7 +112,7 @@ func CreateAllFolders() { if config.Settings.NEED_CREATE_DB == true { //db - Filename = dir + config.Settings.SERVICE_NAME + micro.SeparatorFile() + config.Settings.TEMPLATE_FOLDERNAME_DB + Filename = dir + config.Settings.SERVICE_NAME + micro.SeparatorFile() + config.Settings.TEMPLATE_FOLDERNAME_CRUD ok, err = micro.FileExists(Filename) if ok == false || err != nil { err = CreateFolder_err(Filename, 0777) diff --git a/internal/logic/logic.go b/internal/logic/logic.go index d45137a..27e5a46 100644 --- a/internal/logic/logic.go +++ b/internal/logic/logic.go @@ -3,7 +3,8 @@ package logic import ( "github.com/ManyakRus/crud_generator/internal/config" "github.com/ManyakRus/crud_generator/internal/create_files/crud_starter" - "github.com/ManyakRus/crud_generator/internal/create_files/db" + "github.com/ManyakRus/crud_generator/internal/create_files/db_crud" + "github.com/ManyakRus/crud_generator/internal/create_files/db_tables" "github.com/ManyakRus/crud_generator/internal/create_files/generation_code_sh" "github.com/ManyakRus/crud_generator/internal/create_files/grpc_client_tables" "github.com/ManyakRus/crud_generator/internal/create_files/grpc_proto" @@ -50,7 +51,7 @@ func StartFillAll() error { } //db crud - err = db.CreateAllFiles(MapAll) + err = db_crud.CreateAllFiles(MapAll) if err != nil { return err } @@ -115,5 +116,11 @@ func StartFillAll() error { return err } + //tables + err = db_tables.CreateAllFiles(MapAll) + if err != nil { + return err + } + return err }