diff --git a/Makefile b/Makefile index 9894bdd..3867b59 100644 --- a/Makefile +++ b/Makefile @@ -14,7 +14,7 @@ run: ./bin/$(SERVICENAME) mod: clear - go get -u ./cmd/crud_generator/... ./internal/... ./pkg/... + go get -u ./internal/... go mod tidy -compat=1.18 go mod vendor go fmt ./... diff --git a/bin/templates/internal/app/grpc/server_grpc/server_grpc_table_cache.go_ b/bin/templates/internal/app/grpc/server_grpc/server_grpc_table_cache.go_ new file mode 100644 index 0000000..175476c --- /dev/null +++ b/bin/templates/internal/app/grpc/server_grpc/server_grpc_table_cache.go_ @@ -0,0 +1,45 @@ +package server_grpc + +import ( + "context" + "github.com/ManyakRus/starter/micro" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/api/grpc_proto" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types" +) + +// LawsuitStatusType_ReadFromCache - читает и возвращает модель из кеша или БД +func (s *ServerGRPC) LawsuitStatusType_ReadFromCache(ctx context.Context, Request *grpc_proto.RequestId) (*grpc_proto.Response, error) { + var Otvet grpc_proto.Response + var err error + + //проверим контекст уже отменён + if micro.ContextDone(ctx) == true { + err = context.Canceled + return &Otvet, err + } + + //проверим совпадения версии модели + VersionServer := lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + VersionClient := Request.VersionModel + if VersionServer != VersionClient { + err = ErrorModelVersion(lawsuit_status_types.LawsuitStatusType{}) + return &Otvet, err + } + + //запрос в БД + Model := &lawsuit_status_types.LawsuitStatusType{} + Model.ID = Request.ID + err = Model.ReadFromCache() + if err != nil { + return &Otvet, err + } + + //заполяем ответ + ModelString, err := Model.GetJSON() + if err != nil { + return &Otvet, err + } + Otvet.ModelString = ModelString + + return &Otvet, err +} diff --git a/bin/templates/internal/app/grpc/server_grpc/server_grpc_table_cache_test.go_ b/bin/templates/internal/app/grpc/server_grpc/server_grpc_table_cache_test.go_ new file mode 100644 index 0000000..3af8e7a --- /dev/null +++ b/bin/templates/internal/app/grpc/server_grpc/server_grpc_table_cache_test.go_ @@ -0,0 +1,29 @@ +package server_grpc + +import ( + "context" + "github.com/ManyakRus/starter/config_main" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/api/grpc_proto" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/crud_starter" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types" + "testing" +) + +func Test_server_LawsuitStatusType_ReadFromCache(t *testing.T) { + config_main.LoadEnv() + crud_starter.InitCrudTransport_DB() + + ctx := context.Background() + Request := grpc_proto.RequestId{} + Request.ID = LawsuitStatusType_ID_Test + Request.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + + server1 := &ServerGRPC{} + Otvet, err := server1.LawsuitStatusType_ReadFromCache(ctx, &Request) + if err != nil { + t.Error("Test_server_LawsuitStatusType_ReadFromCache() error: ", err) + } + if Otvet.ModelString == "" { + t.Error("Test_server_LawsuitStatusType_ReadFromCache() error: ModelString=''") + } +} diff --git a/bin/templates/pkg/object_model/entities/model_crud.go_ b/bin/templates/pkg/object_model/entities/model_crud.go_ index 2ae6e0d..9d051c3 100644 --- a/bin/templates/pkg/object_model/entities/model_crud.go_ +++ b/bin/templates/pkg/object_model/entities/model_crud.go_ @@ -23,6 +23,7 @@ type ICrud_LawsuitStatusType interface { Delete(*LawsuitStatusType) error Restore(*LawsuitStatusType) error Find_ByExtID(*LawsuitStatusType) error + ReadFromCache(*LawsuitStatusType) error } // TableName - возвращает имя таблицы в БД @@ -167,6 +168,17 @@ func (m *LawsuitStatusType) Find_ByExtID() error { return err } +// ReadFromCache - находит запись в кэше или в БД по ID, и заполняет в объект +func (m *LawsuitStatusType) ReadFromCache() error { + if Crud_LawsuitStatusType == nil { + return constants.ErrorCrudIsNotInit + } + + err := Crud_LawsuitStatusType.ReadFromCache(m) + + return err +} + // SetCrudInterface - заполняет интерфейс crud: DB, GRPC, NRPC func (m LawsuitStatusType) SetCrudInterface(crud ICrud_LawsuitStatusType) { Crud_LawsuitStatusType = crud diff --git a/internal/constants/constants.go b/internal/constants/constants.go index f02b8dd..63a6759 100644 --- a/internal/constants/constants.go +++ b/internal/constants/constants.go @@ -57,3 +57,6 @@ const GRPC_CLIENT_TABLE_UPDATE_FUNC_TEST_FILENAME = "grpc_client_table_update_fu const CRUD_TABLES_CACHE_FILENAME = "crud_table_cache.go_" const CRUD_TABLES_CACHE_TEST_FILENAME = "crud_table_cache_test.go_" const TEXT_CACHE_REMOVE = "cache.Remove(m.ID)" + +const SERVER_GRPC_TABLE_CACHE_FILENAME = "server_grpc_table_cache.go_" +const SERVER_GRPC_TABLE_CACHE_TEST_FILENAME = "server_grpc_table_cache_test.go_" diff --git a/internal/create_files/create_files.go b/internal/create_files/create_files.go index b3a0e3e..8445c36 100644 --- a/internal/create_files/create_files.go +++ b/internal/create_files/create_files.go @@ -932,6 +932,21 @@ func DeleteFuncTestDelete(Text string, Table1 *types.Table) string { return Otvet } +// DeleteFuncReadFromCache - удаляет функцию ReadFromCache() +func DeleteFuncReadFromCache(TextModel string, Table1 *types.Table) string { + Otvet := TextModel + + //проверим есть ли колонка IsDeleted + if Has_Column_IsDeleted(Table1) == true { + return Otvet + } + + Otvet = DeleteFuncFromComment(Otvet, "\n// ReadFromCache ") + Otvet = DeleteFuncFromFuncName(Otvet, "ReadFromCache") + + return Otvet +} + // DeleteFuncTestRestore - удаляет функцию Restore() func DeleteFuncTestRestore(Text string, Table1 *types.Table) string { Otvet := Text diff --git a/internal/create_files/db_crud_tables/db_crud_tables.go b/internal/create_files/db_crud_tables/db_crud_tables.go index fad1ee5..2fa3adf 100644 --- a/internal/create_files/db_crud_tables/db_crud_tables.go +++ b/internal/create_files/db_crud_tables/db_crud_tables.go @@ -111,6 +111,7 @@ func CreateFiles(Table1 *types.Table) error { } } + //загрузим шаблон файла bytes, err := os.ReadFile(FilenameTemplateDB) if err != nil { log.Panic("ReadFile() ", FilenameTemplateDB, " error: ", err) @@ -120,6 +121,7 @@ func CreateFiles(Table1 *types.Table) error { //заменим имя пакета на новое TextDB = create_files.ReplacePackageName(TextDB, DirReadyTable) + ModelName := Table1.NameGo //заменим импорты if config.Settings.USE_DEFAULT_TEMPLATE == true { TextDB = create_files.DeleteTemplateRepositoryImports(TextDB) @@ -142,19 +144,19 @@ func CreateFiles(Table1 *types.Table) error { TextDB = create_files.DeleteFuncDeleteCtx(TextDB, Table1) TextDB = create_files.DeleteFuncRestoreCtx(TextDB, Table1) TextDB = create_files.DeleteFuncFind_byExtIDCtx(TextDB, Table1) + + //кэш + if config.Settings.NEED_CREATE_CACHE_API == true { + //исправление Save() + TextDB = strings.ReplaceAll(TextDB, `//`+constants.TEXT_CACHE_REMOVE, constants.TEXT_CACHE_REMOVE) + } } //создание текста - ModelName := Table1.NameGo TextDB = strings.ReplaceAll(TextDB, config.Settings.TEXT_TEMPLATE_MODEL, ModelName) TextDB = strings.ReplaceAll(TextDB, config.Settings.TEXT_TEMPLATE_TABLENAME, Table1.Name) TextDB = config.Settings.TEXT_MODULE_GENERATED + TextDB - //кэш - if config.Settings.NEED_CREATE_CACHE_API == true { - TextDB = strings.ReplaceAll(TextDB, `//`+constants.TEXT_CACHE_REMOVE, constants.TEXT_CACHE_REMOVE) - } - //TextDB = create_files.DeleteFuncFind_byExtID(TextDB, Table1) //TextDB = create_files.DeleteFuncFind_byExtIDCtx(TextDB, Table1) TextDB = AddTextOmit(TextDB, Table1) @@ -789,7 +791,7 @@ func CreateFilesCache(Table1 *types.Table) error { FilenameTemplateCache := DirTemplatesCrud + constants.CRUD_TABLES_CACHE_FILENAME DirReadyTable := DirReadyCrud - FilenameReadyCache := DirReadyTable + create_files.FilenameWithoutLastUnderline(constants.CRUD_TABLES_CACHE_FILENAME) + FilenameReadyCache := DirReadyTable + "crud_" + TableName + "_cache.go" //создадим папку готовых файлов folders.CreateFolder(DirReadyTable) @@ -850,7 +852,7 @@ func CreateFilesCacheTest(Table1 *types.Table) error { FilenameTemplateCache := DirTemplatesCrud + constants.CRUD_TABLES_CACHE_TEST_FILENAME DirReadyTable := DirReadyCrud - FilenameReadyCache := DirReadyTable + create_files.FilenameWithoutLastUnderline(constants.CRUD_TABLES_CACHE_TEST_FILENAME) + FilenameReadyCache := DirReadyTable + "crud_" + TableName + "_cache_test.go" //создадим папку готовых файлов folders.CreateFolder(DirReadyTable) diff --git a/internal/create_files/grpc_server_tables/grpc_server_tables.go b/internal/create_files/grpc_server_tables/grpc_server_tables.go index 147784f..e998100 100644 --- a/internal/create_files/grpc_server_tables/grpc_server_tables.go +++ b/internal/create_files/grpc_server_tables/grpc_server_tables.go @@ -41,7 +41,7 @@ func CreateAllFiles(MapAll map[string]*types.Table) error { } } - // + //UPDATE_EVERY_COLUMN if config.Settings.NEED_CREATE_UPDATE_EVERY_COLUMN == true { //файлы grpc_server update err = CreateFilesUpdateEveryColumn(Table1) @@ -60,6 +60,28 @@ func CreateAllFiles(MapAll map[string]*types.Table) error { } } + + //UPDATE_EVERY_COLUMN + if config.Settings.NEED_CREATE_CACHE_API == true { + //файлы grpc_server cache + if config.Settings.NEED_CREATE_CACHE_FILES == true { + err = CreateFilesCache(Table1) + if err != nil { + log.Error("CreateFiles() table: ", Table1.Name, " error: ", err) + return err + } + } + + //тестовые файлы grpc_server cache + if config.Settings.NEED_CREATE_CACHE_TEST_FILES == true { + err = CreateFilesCacheTest(Table1) + if err != nil { + log.Error("CreateTestFiles() table: ", Table1.Name, " error: ", err) + return err + } + } + + } } return err } @@ -116,18 +138,6 @@ func CreateFiles(Table1 *types.Table) error { if config.Settings.USE_DEFAULT_TEMPLATE == true { TextGRPCServer = create_files.ConvertIdToAlias(TextGRPCServer, Table1) - - //замена импортов на новые URL - //TextGRPCServer = create_files.ReplaceServiceURLImports(TextGRPCServer) - //TextGRPCServer = create_files.DeleteTemplateRepositoryImports(TextGRPCServer) - - ////proto - //RepositoryGRPCProtoURL := create_files.FindProtoURL() - //TextGRPCServer = create_files.AddImport(TextGRPCServer, RepositoryGRPCProtoURL) - // - ////model - //RepositoryModelURL := create_files.FindModelTableURL(TableName) - //TextGRPCServer = create_files.AddImport(TextGRPCServer, RepositoryModelURL) } //удаление пустого импорта @@ -633,3 +643,122 @@ func FindTextUpdateEveryColumnTest1(TextGRPCServerUpdateFunc string, Table1 *typ return Otvet } + +// CreateFilesCache - создаёт 1 файл в папке grpc_server +func CreateFilesCache(Table1 *types.Table) error { + var err error + + //чтение файлов + DirBin := micro.ProgramDir_bin() + DirTemplates := DirBin + config.Settings.TEMPLATE_FOLDERNAME + micro.SeparatorFile() + DirReady := DirBin + config.Settings.READY_FOLDERNAME + micro.SeparatorFile() + DirTemplatesGRPCServer := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_GRPC_SERVER + micro.SeparatorFile() + DirReadyGRPCServer := DirReady + config.Settings.TEMPLATE_FOLDERNAME_GRPC_SERVER + micro.SeparatorFile() + + FilenameTemplateCache := DirTemplatesGRPCServer + constants.SERVER_GRPC_TABLE_CACHE_FILENAME + TableName := strings.ToLower(Table1.Name) + DirReadyTable := DirReadyGRPCServer + FilenameReadyCache := DirReadyTable + config.Settings.PREFIX_SERVER_GRPC + TableName + "_cache.go" + + //создадим папку готовых файлов + folders.CreateFolder(DirReadyTable) + + bytes, err := os.ReadFile(FilenameTemplateCache) + if err != nil { + log.Panic("ReadFile() ", FilenameTemplateCache, " error: ", err) + } + TextGRPCServer := string(bytes) + + //заменим имя пакета на новое + TextGRPCServer = create_files.ReplacePackageName(TextGRPCServer, DirReadyTable) + + //заменим импорты + if config.Settings.USE_DEFAULT_TEMPLATE == true { + TextGRPCServer = create_files.DeleteTemplateRepositoryImports(TextGRPCServer) + + ModelTableURL := create_files.FindModelTableURL(TableName) + TextGRPCServer = create_files.AddImport(TextGRPCServer, ModelTableURL) + + ProtoURL := create_files.FindProtoURL() + TextGRPCServer = create_files.AddImport(TextGRPCServer, ProtoURL) + } + + //создание текста + ModelName := Table1.NameGo + TextGRPCServer = strings.ReplaceAll(TextGRPCServer, config.Settings.TEXT_TEMPLATE_MODEL, ModelName) + TextGRPCServer = strings.ReplaceAll(TextGRPCServer, config.Settings.TEXT_TEMPLATE_TABLENAME, Table1.Name) + TextGRPCServer = config.Settings.TEXT_MODULE_GENERATED + TextGRPCServer + + if config.Settings.USE_DEFAULT_TEMPLATE == true { + TextGRPCServer = create_files.ConvertIdToAlias(TextGRPCServer, Table1) + } + + //удаление пустого импорта + TextGRPCServer = create_files.DeleteEmptyImport(TextGRPCServer) + + //запись файла + err = os.WriteFile(FilenameReadyCache, []byte(TextGRPCServer), constants.FILE_PERMISSIONS) + + return err +} + +// CreateFilesCacheTest - создаёт 1 файл в папке grpc_server +func CreateFilesCacheTest(Table1 *types.Table) error { + var err error + + //чтение файлов + DirBin := micro.ProgramDir_bin() + DirTemplates := DirBin + config.Settings.TEMPLATE_FOLDERNAME + micro.SeparatorFile() + DirReady := DirBin + config.Settings.READY_FOLDERNAME + micro.SeparatorFile() + DirTemplatesGRPCServer := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_GRPC_SERVER + micro.SeparatorFile() + DirReadyGRPCServer := DirReady + config.Settings.TEMPLATE_FOLDERNAME_GRPC_SERVER + micro.SeparatorFile() + + FilenameTemplateCache := DirTemplatesGRPCServer + constants.SERVER_GRPC_TABLE_CACHE_TEST_FILENAME + TableName := strings.ToLower(Table1.Name) + DirReadyTable := DirReadyGRPCServer + FilenameReadyCache := DirReadyTable + config.Settings.PREFIX_SERVER_GRPC + TableName + "_cache_test.go" + + //создадим папку готовых файлов + folders.CreateFolder(DirReadyTable) + + bytes, err := os.ReadFile(FilenameTemplateCache) + if err != nil { + log.Panic("ReadFile() ", FilenameTemplateCache, " error: ", err) + } + TextGRPCServer := string(bytes) + + //заменим имя пакета на новое + TextGRPCServer = create_files.ReplacePackageName(TextGRPCServer, DirReadyTable) + + //заменим импорты + if config.Settings.USE_DEFAULT_TEMPLATE == true { + TextGRPCServer = create_files.DeleteTemplateRepositoryImports(TextGRPCServer) + + ModelTableURL := create_files.FindModelTableURL(TableName) + TextGRPCServer = create_files.AddImport(TextGRPCServer, ModelTableURL) + + ProtoURL := create_files.FindProtoURL() + TextGRPCServer = create_files.AddImport(TextGRPCServer, ProtoURL) + + CrudStarterURL := create_files.FindCrudStarterURL() + TextGRPCServer = create_files.AddImport(TextGRPCServer, CrudStarterURL) + } + + //создание текста + ModelName := Table1.NameGo + TextGRPCServer = strings.ReplaceAll(TextGRPCServer, config.Settings.TEXT_TEMPLATE_MODEL, ModelName) + TextGRPCServer = strings.ReplaceAll(TextGRPCServer, config.Settings.TEXT_TEMPLATE_TABLENAME, Table1.Name) + TextGRPCServer = config.Settings.TEXT_MODULE_GENERATED + TextGRPCServer + + if config.Settings.USE_DEFAULT_TEMPLATE == true { + TextGRPCServer = create_files.ConvertIdToAlias(TextGRPCServer, Table1) + } + + //удаление пустого импорта + TextGRPCServer = create_files.DeleteEmptyImport(TextGRPCServer) + + //запись файла + err = os.WriteFile(FilenameReadyCache, []byte(TextGRPCServer), constants.FILE_PERMISSIONS) + + return err +} diff --git a/internal/create_files/model_tables/model_tables.go b/internal/create_files/model_tables/model_tables.go index f5648d6..5f9edf2 100644 --- a/internal/create_files/model_tables/model_tables.go +++ b/internal/create_files/model_tables/model_tables.go @@ -178,6 +178,12 @@ func CreateFilesModel_crud(Table1 *types.Table, DirTemplatesModel, DirReadyModel TextModel = DeleteFromInterfaceDelete(TextModel, Table1) TextModel = DeleteFromInterfaceRestore(TextModel, Table1) TextModel = DeleteFromInterfaceFind_ByExtID(TextModel, Table1) + //кэш + if config.Settings.NEED_CREATE_CACHE_API == false { + //исправление Save() + TextModel = DeleteFromInterfaceReadFromCache(TextModel, Table1) + TextModel = create_files.DeleteFuncReadFromCache(TextModel, Table1) + } } // @@ -666,3 +672,14 @@ func FindTextInterfaceUpdateEveryColumn(Table1 *types.Table, Column1 *types.Colu return Otvet } + +// DeleteFromInterfaceReadFromCache - удаляет функцию ReadFromCache() из интерфейса +func DeleteFromInterfaceReadFromCache(TextModel string, Table1 *types.Table) string { + Otvet := TextModel + + ModelName := config.Settings.TEXT_TEMPLATE_MODEL + TextFind := "\n\tReadFromCache(*" + ModelName + ") error" + Otvet = strings.ReplaceAll(Otvet, TextFind, "") + + return Otvet +} diff --git a/internal/create_files/protobuf/protobuf.go b/internal/create_files/protobuf/protobuf.go index 9762680..e64365f 100644 --- a/internal/create_files/protobuf/protobuf.go +++ b/internal/create_files/protobuf/protobuf.go @@ -84,6 +84,10 @@ func CreateFileProto(MapAll map[string]*types.Table) error { TextProtoNew = TextProtoNew + FindTextProtoTable1(TextProto, Table1) TextProtoNew = TextProtoNew + FindTextProtoTable1_UpdateEveryColumn(TextProto, Table1) + + if config.Settings.NEED_CREATE_CACHE_API == true { + TextProtoNew = TextProtoNew + FindTextProtoTable1_Cache(TextProto, Table1) + } } //найдём куда вставить текст @@ -379,3 +383,36 @@ func TextUpdateEveryColumn(Table1 *types.Table, Column1 *types.Column) string { return Otvet } + +// FindTextProtoTable1_Cache - возвращает текст функции ReadFromCache() .proto для таблицы +func FindTextProtoTable1_Cache(TextProto string, Table1 *types.Table) string { + Otvet := "\n" //"\n\t//\n" + + ModelName := Table1.NameGo + Otvet = Otvet + FindTextReadFromCache(TextProto, ModelName) + + return Otvet +} + +// FindTextReadFromCache - возвращает текст .proto +func FindTextReadFromCache(TextProto string, ModelName string) string { + Otvet := "" + Otvet2 := TextReadFromCache(ModelName) + + //проверка такой текст уже есть + pos1 := strings.Index(TextProto, Otvet2) + if pos1 >= 0 { + return Otvet + } + + Otvet = "\t" + Otvet2 + "\n" + + return Otvet +} + +// TextReadFromCache - возвращает текст .proto +func TextReadFromCache(ModelName string) string { + Otvet := "rpc " + ModelName + "_ReadFromCache(RequestId) returns (Response) {}" + + return Otvet +}