1
0
mirror of https://github.com/ManyakRus/crud_generator.git synced 2025-01-03 01:22:21 +02:00

сделал NEED_CREATE_CACHE_API

This commit is contained in:
Nikitin Aleksandr 2024-03-06 17:45:55 +03:00
parent c9fa7505f3
commit a7e17d06bb
10 changed files with 311 additions and 22 deletions

View File

@ -14,7 +14,7 @@ run:
./bin/$(SERVICENAME) ./bin/$(SERVICENAME)
mod: mod:
clear clear
go get -u ./cmd/crud_generator/... ./internal/... ./pkg/... go get -u ./internal/...
go mod tidy -compat=1.18 go mod tidy -compat=1.18
go mod vendor go mod vendor
go fmt ./... go fmt ./...

View File

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

View File

@ -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=''")
}
}

View File

@ -23,6 +23,7 @@ type ICrud_LawsuitStatusType interface {
Delete(*LawsuitStatusType) error Delete(*LawsuitStatusType) error
Restore(*LawsuitStatusType) error Restore(*LawsuitStatusType) error
Find_ByExtID(*LawsuitStatusType) error Find_ByExtID(*LawsuitStatusType) error
ReadFromCache(*LawsuitStatusType) error
} }
// TableName - возвращает имя таблицы в БД // TableName - возвращает имя таблицы в БД
@ -167,6 +168,17 @@ func (m *LawsuitStatusType) Find_ByExtID() error {
return err 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 // SetCrudInterface - заполняет интерфейс crud: DB, GRPC, NRPC
func (m LawsuitStatusType) SetCrudInterface(crud ICrud_LawsuitStatusType) { func (m LawsuitStatusType) SetCrudInterface(crud ICrud_LawsuitStatusType) {
Crud_LawsuitStatusType = crud Crud_LawsuitStatusType = crud

View File

@ -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_FILENAME = "crud_table_cache.go_"
const CRUD_TABLES_CACHE_TEST_FILENAME = "crud_table_cache_test.go_" const CRUD_TABLES_CACHE_TEST_FILENAME = "crud_table_cache_test.go_"
const TEXT_CACHE_REMOVE = "cache.Remove(m.ID)" 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_"

View File

@ -932,6 +932,21 @@ func DeleteFuncTestDelete(Text string, Table1 *types.Table) string {
return Otvet 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() // DeleteFuncTestRestore - удаляет функцию Restore()
func DeleteFuncTestRestore(Text string, Table1 *types.Table) string { func DeleteFuncTestRestore(Text string, Table1 *types.Table) string {
Otvet := Text Otvet := Text

View File

@ -111,6 +111,7 @@ func CreateFiles(Table1 *types.Table) error {
} }
} }
//загрузим шаблон файла
bytes, err := os.ReadFile(FilenameTemplateDB) bytes, err := os.ReadFile(FilenameTemplateDB)
if err != nil { if err != nil {
log.Panic("ReadFile() ", FilenameTemplateDB, " error: ", err) log.Panic("ReadFile() ", FilenameTemplateDB, " error: ", err)
@ -120,6 +121,7 @@ func CreateFiles(Table1 *types.Table) error {
//заменим имя пакета на новое //заменим имя пакета на новое
TextDB = create_files.ReplacePackageName(TextDB, DirReadyTable) TextDB = create_files.ReplacePackageName(TextDB, DirReadyTable)
ModelName := Table1.NameGo
//заменим импорты //заменим импорты
if config.Settings.USE_DEFAULT_TEMPLATE == true { if config.Settings.USE_DEFAULT_TEMPLATE == true {
TextDB = create_files.DeleteTemplateRepositoryImports(TextDB) TextDB = create_files.DeleteTemplateRepositoryImports(TextDB)
@ -142,19 +144,19 @@ func CreateFiles(Table1 *types.Table) error {
TextDB = create_files.DeleteFuncDeleteCtx(TextDB, Table1) TextDB = create_files.DeleteFuncDeleteCtx(TextDB, Table1)
TextDB = create_files.DeleteFuncRestoreCtx(TextDB, Table1) TextDB = create_files.DeleteFuncRestoreCtx(TextDB, Table1)
TextDB = create_files.DeleteFuncFind_byExtIDCtx(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_MODEL, ModelName)
TextDB = strings.ReplaceAll(TextDB, config.Settings.TEXT_TEMPLATE_TABLENAME, Table1.Name) TextDB = strings.ReplaceAll(TextDB, config.Settings.TEXT_TEMPLATE_TABLENAME, Table1.Name)
TextDB = config.Settings.TEXT_MODULE_GENERATED + TextDB 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_byExtID(TextDB, Table1)
//TextDB = create_files.DeleteFuncFind_byExtIDCtx(TextDB, Table1) //TextDB = create_files.DeleteFuncFind_byExtIDCtx(TextDB, Table1)
TextDB = AddTextOmit(TextDB, Table1) TextDB = AddTextOmit(TextDB, Table1)
@ -789,7 +791,7 @@ func CreateFilesCache(Table1 *types.Table) error {
FilenameTemplateCache := DirTemplatesCrud + constants.CRUD_TABLES_CACHE_FILENAME FilenameTemplateCache := DirTemplatesCrud + constants.CRUD_TABLES_CACHE_FILENAME
DirReadyTable := DirReadyCrud DirReadyTable := DirReadyCrud
FilenameReadyCache := DirReadyTable + create_files.FilenameWithoutLastUnderline(constants.CRUD_TABLES_CACHE_FILENAME) FilenameReadyCache := DirReadyTable + "crud_" + TableName + "_cache.go"
//создадим папку готовых файлов //создадим папку готовых файлов
folders.CreateFolder(DirReadyTable) folders.CreateFolder(DirReadyTable)
@ -850,7 +852,7 @@ func CreateFilesCacheTest(Table1 *types.Table) error {
FilenameTemplateCache := DirTemplatesCrud + constants.CRUD_TABLES_CACHE_TEST_FILENAME FilenameTemplateCache := DirTemplatesCrud + constants.CRUD_TABLES_CACHE_TEST_FILENAME
DirReadyTable := DirReadyCrud DirReadyTable := DirReadyCrud
FilenameReadyCache := DirReadyTable + create_files.FilenameWithoutLastUnderline(constants.CRUD_TABLES_CACHE_TEST_FILENAME) FilenameReadyCache := DirReadyTable + "crud_" + TableName + "_cache_test.go"
//создадим папку готовых файлов //создадим папку готовых файлов
folders.CreateFolder(DirReadyTable) folders.CreateFolder(DirReadyTable)

View File

@ -41,7 +41,7 @@ func CreateAllFiles(MapAll map[string]*types.Table) error {
} }
} }
// //UPDATE_EVERY_COLUMN
if config.Settings.NEED_CREATE_UPDATE_EVERY_COLUMN == true { if config.Settings.NEED_CREATE_UPDATE_EVERY_COLUMN == true {
//файлы grpc_server update //файлы grpc_server update
err = CreateFilesUpdateEveryColumn(Table1) 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 return err
} }
@ -116,18 +138,6 @@ func CreateFiles(Table1 *types.Table) error {
if config.Settings.USE_DEFAULT_TEMPLATE == true { if config.Settings.USE_DEFAULT_TEMPLATE == true {
TextGRPCServer = create_files.ConvertIdToAlias(TextGRPCServer, Table1) 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 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
}

View File

@ -178,6 +178,12 @@ func CreateFilesModel_crud(Table1 *types.Table, DirTemplatesModel, DirReadyModel
TextModel = DeleteFromInterfaceDelete(TextModel, Table1) TextModel = DeleteFromInterfaceDelete(TextModel, Table1)
TextModel = DeleteFromInterfaceRestore(TextModel, Table1) TextModel = DeleteFromInterfaceRestore(TextModel, Table1)
TextModel = DeleteFromInterfaceFind_ByExtID(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 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
}

View File

@ -84,6 +84,10 @@ func CreateFileProto(MapAll map[string]*types.Table) error {
TextProtoNew = TextProtoNew + FindTextProtoTable1(TextProto, Table1) TextProtoNew = TextProtoNew + FindTextProtoTable1(TextProto, Table1)
TextProtoNew = TextProtoNew + FindTextProtoTable1_UpdateEveryColumn(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 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
}