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

сделал CreateFiles_FindModelBy()

This commit is contained in:
Nikitin Aleksandr 2024-10-15 17:43:44 +03:00
parent 9e5826a6b2
commit a471d5ab2e
10 changed files with 393 additions and 24 deletions

View File

@ -3,7 +3,7 @@ func (s *ServerGRPC) LawsuitStatusType_FindBy_FieldNamesWithUnderline(ctx contex
var Otvet grpc_proto.Response
var err error
// проверим совпадения версии модели
//проверим совпадения версии модели
VersionServer := lawsuit_status_types.LawsuitStatusType{}.GetStructVersion()
VersionClient := Request.VersionModel
if VersionServer != VersionClient {
@ -11,7 +11,7 @@ func (s *ServerGRPC) LawsuitStatusType_FindBy_FieldNamesWithUnderline(ctx contex
return &Otvet, err
}
// запрос в БД
//запрос в БД
db := postgres_gorm.GetConnection()
Model := &lawsuit_status_types.LawsuitStatusType{}
Model.FieldName = Request.RequestFieldName
@ -20,7 +20,7 @@ func (s *ServerGRPC) LawsuitStatusType_FindBy_FieldNamesWithUnderline(ctx contex
return &Otvet, err
}
// заполяем ответ
//заполяем ответ
ModelString, err := Model.GetJSON()
if err != nil {
return &Otvet, err

View File

@ -3,7 +3,7 @@ func (s *ServerGRPC) LawsuitStatusType_FindMassBy_FieldNamesWithUnderline(ctx co
var Otvet grpc_proto.ResponseMass
var err error
// проверим совпадения версии модели
//проверим совпадения версии модели
VersionServer := lawsuit_status_types.LawsuitStatusType{}.GetStructVersion()
VersionClient := Request.VersionModel
if VersionServer != VersionClient {
@ -11,7 +11,7 @@ func (s *ServerGRPC) LawsuitStatusType_FindMassBy_FieldNamesWithUnderline(ctx co
return &Otvet, err
}
// запрос в БД
//запрос в БД
db := postgres_gorm.GetConnection()
Model := &lawsuit_status_types.LawsuitStatusType{}
Model.FieldName = Request.RequestFieldName
@ -20,7 +20,7 @@ func (s *ServerGRPC) LawsuitStatusType_FindMassBy_FieldNamesWithUnderline(ctx co
return &Otvet, err
}
// заполяем ответ
//заполяем ответ
for _, v := range Mass {
ModelString, err := v.GetJSON()
if err != nil {

View File

@ -2,6 +2,8 @@ package server_grpc
import (
"context"
"encoding/json"
"fmt"
"github.com/ManyakRus/starter/postgres_gorm"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/api/grpc_proto"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/crud/crud_lawsuit_status_types"

View File

@ -1,9 +1,9 @@
// LawsuitStatusType_FindByFieldNamesWithUnderline - находит lawsuit_status_types в БД по FieldNamesWithPlus
func (s *ServerGRPC) LawsuitStatusType_FindBy_FieldNamesWithUnderline(ctx context.Context, Request *grpc_proto.RequestName) (*grpc_proto.Response, error) {
// LawsuitStatusType_FindModelByFieldNamesWithUnderline - находит ForeignModel в БД по FieldNamesWithPlus
func (s *ServerGRPC) LawsuitStatusType_FindModelBy_FieldNamesWithUnderline(ctx context.Context, Request *grpc_proto.RequestName) (*grpc_proto.Response, error) {
var Otvet grpc_proto.Response
var err error
// проверим совпадения версии модели
//проверим совпадения версии модели
VersionServer := lawsuit_status_types.LawsuitStatusType{}.GetStructVersion()
VersionClient := Request.VersionModel
if VersionServer != VersionClient {
@ -11,18 +11,29 @@ func (s *ServerGRPC) LawsuitStatusType_FindBy_FieldNamesWithUnderline(ctx contex
return &Otvet, err
}
// запрос в БД
//клиент БД
db := postgres_gorm.GetConnection()
//модель из строки
sModel := Request.ModelString
Model := &lawsuit_status_types.LawsuitStatusType{}
Model.FieldName = Request.RequestFieldName
err = crud_lawsuit_status_types.FindBy_FieldNamesWithUnderline_ctx(ctx, db, Model)
err = json.Unmarshal([]byte(sModel), Model)
if err != nil {
err = fmt.Errorf("json.Unmarshal() error: %w", err)
return &Otvet, err
}
// заполяем ответ
ModelString, err := Model.GetJSON()
//запрос crud
ModelOtvet, err := crud_lawsuit_status_types.FindModelBy_FieldNamesWithUnderline_ctx(ctx, db, Model)
if err != nil {
err = fmt.Errorf("FindModelBy_FieldNamesWithUnderline_ctx() error: %w", err)
return &Otvet, err
}
//заполяем ответ
ModelString, err := ModelOtvet.GetJSON()
if err != nil {
err = fmt.Errorf("GetJSON() error: %w", err)
return &Otvet, err
}
Otvet.ModelString = ModelString

View File

@ -1,4 +1,4 @@
func Test_server_LawsuitStatusType_FindBy_FieldNamesWithUnderline(t *testing.T) {
func Test_server_LawsuitStatusType_FindModelBy_FieldNamesWithUnderline(t *testing.T) {
config_main.LoadEnv()
crud_starter.InitCrudTransport_DB()
@ -8,13 +8,13 @@ func Test_server_LawsuitStatusType_FindBy_FieldNamesWithUnderline(t *testing.T)
Request.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion()
server1 := &ServerGRPC{}
Otvet, err := server1.LawsuitStatusType_FindBy_FieldNamesWithUnderline(ctx, &Request)
Otvet, err := server1.LawsuitStatusType_FindModelBy_FieldNamesWithUnderline(ctx, &Request)
if err != nil && crud_func.IsRecordNotFound(err) == false {
t.Error("Test_server_LawsuitStatusType_FindBy_FieldNamesWithUnderline() error: ", err)
t.Error("Test_server_LawsuitStatusType_FindModelBy_FieldNamesWithUnderline() error: ", err)
}
if Otvet.ModelString == "" {
t.Log("Test_server_LawsuitStatusType_FindBy_FieldNamesWithUnderline() error: ModelString=''")
t.Log("Test_server_LawsuitStatusType_FindModelBy_FieldNamesWithUnderline() error: ModelString=''")
}
}

View File

@ -3,7 +3,7 @@ func (s *ServerGRPC) LawsuitStatusType_ReadAll(ctx context.Context, Request *grp
var Otvet grpc_proto.ResponseMass
var err error
// проверим совпадения версии модели
//проверим совпадения версии модели
VersionServer := lawsuit_status_types.LawsuitStatusType{}.GetStructVersion()
VersionClient := Request.VersionModel
if VersionServer != VersionClient {
@ -11,14 +11,14 @@ func (s *ServerGRPC) LawsuitStatusType_ReadAll(ctx context.Context, Request *grp
return &Otvet, err
}
// запрос в БД
//запрос в БД
db := postgres_gorm.GetConnection()
Mass, err := crud_lawsuit_status_types.ReadAll_ctx(ctx, db)
if err != nil {
return &Otvet, err
}
// заполяем ответ
//заполяем ответ
for _, v := range Mass {
ModelString, err := v.GetJSON()
if err != nil {

View File

@ -32,7 +32,7 @@ func TestServerGRPC_LawsuitStatusType_UpdateManyFields(t *testing.T) {
return
}
// запишем в БД с пустым списком полей (не запишется)
//запишем в БД с пустым списком полей (не запишется)
var ModelString string
ModelString = Response1.ModelString
RequestModel := grpc_proto.Request_Model_MassString{}

View File

@ -193,7 +193,7 @@ func Test_server_LawsuitStatusType_Save(t *testing.T) {
var ModelString string
ModelString = Response1.ModelString
// sModel, _ := GetJSON(Otvet)
//sModel, _ := GetJSON(Otvet)
RequestModel := grpc_proto.RequestModel{}
RequestModel.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion()
RequestModel.ModelString = ModelString

View File

@ -77,7 +77,7 @@ func CreateAllFiles(MapAll map[string]*types.Table) error {
}
}
//
//FindBy
err = CreateFiles_FindBy(Table1)
if err != nil {
log.Error("CreateFiles_FindBy() table: ", Table1.Name, " error: ", err)
@ -118,6 +118,21 @@ func CreateAllFiles(MapAll map[string]*types.Table) error {
log.Error("CreateFiles_ReadAll_Test() table: ", Table1.Name, " error: ", err)
return err
}
//FindModelBy
err = CreateFiles_FindModelBy(MapAll, Table1)
if err != nil {
log.Error("CreateFiles_FindBy() table: ", Table1.Name, " error: ", err)
return err
}
//
err = CreateFiles_FindModelBy_Test(MapAll, Table1)
if err != nil {
log.Error("CreateFiles_FindBy_Test() table: ", Table1.Name, " error: ", err)
return err
}
}
return err
}

View File

@ -0,0 +1,341 @@
package server_grpc_tables
import (
"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/starter/log"
"github.com/ManyakRus/starter/micro"
"os"
"strings"
)
// CreateFiles_FindModelBy - создаёт 1 файл в папке server_grpc
func CreateFiles_FindModelBy(MapAll map[string]*types.Table, Table1 *types.Table) error {
var err error
if len(types.MassFindModelBy) == 0 {
return err
}
//чтение файлов
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()
FilenameTemplateGRPCServer := DirTemplatesGRPCServer + config.Settings.TEMPLATES_GRPC_SERVER_FINDMODELBY_FILENAME
TableName := strings.ToLower(Table1.Name)
DirReadyTable := DirReadyGRPCServer
FilenameReady := DirReadyTable + micro.SeparatorFile() + config.Settings.PREFIX_SERVER_GRPC + TableName + "_findmodelby.go"
//создадим каталог
ok, err := micro.FileExists(DirReadyTable)
if ok == false {
err = os.MkdirAll(DirReadyTable, 0777)
if err != nil {
log.Panic("Mkdir() ", DirReadyTable, " error: ", err)
}
}
//загрузим шаблон файла
bytes, err := os.ReadFile(FilenameTemplateGRPCServer)
if err != nil {
log.Panic("ReadFile() ", FilenameTemplateGRPCServer, " error: ", err)
}
TextGRPCServer := string(bytes)
//загрузим шаблон файла функции
FilenameTemplateGRPCServerFunction := DirTemplatesGRPCServer + config.Settings.TEMPLATES_GRPC_SERVER_FINDMODELBY_FUNCTION_FILENAME
bytes, err = os.ReadFile(FilenameTemplateGRPCServerFunction)
if err != nil {
log.Panic("ReadFile() ", FilenameTemplateGRPCServerFunction, " error: ", err)
}
TextTemplatedFunction := string(bytes)
//заменим имя пакета на новое
TextGRPCServer = create_files.Replace_PackageName(TextGRPCServer, DirReadyTable)
//ModelName := Table1.NameGo
//заменим импорты
if config.Settings.USE_DEFAULT_TEMPLATE == true {
TextGRPCServer = create_files.Delete_TemplateRepositoryImports(TextGRPCServer)
ModelTableURL := create_files.Find_ModelTableURL(TableName)
TextGRPCServer = create_files.AddImport(TextGRPCServer, ModelTableURL)
CrudTableURL := create_files.Find_CrudTableURL(TableName)
TextGRPCServer = create_files.AddImport(TextGRPCServer, CrudTableURL)
ProtoURL := create_files.Find_ProtoURL()
TextGRPCServer = create_files.AddImport(TextGRPCServer, ProtoURL)
}
//создание функций
TextServerGRPCFunc := CreateFiles_FindModelBy_Table(MapAll, Table1, TextTemplatedFunction)
if TextServerGRPCFunc == "" {
return err
}
TextGRPCServer = TextGRPCServer + TextServerGRPCFunc
//создание текста
TextGRPCServer = create_files.Replace_TemplateModel_to_Model(TextGRPCServer, Table1.NameGo)
TextGRPCServer = create_files.Replace_TemplateTableName_to_TableName(TextGRPCServer, Table1.Name)
TextGRPCServer = create_files.AddText_ModuleGenerated(TextGRPCServer)
//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
//замена импортов на новые URL
TextGRPCServer = create_files.Replace_RepositoryImportsURL(TextGRPCServer)
//uuid
TextGRPCServer = create_files.CheckAndAdd_ImportUUID_FromText(TextGRPCServer)
//alias
TextGRPCServer = create_files.CheckAndAdd_ImportAlias(TextGRPCServer)
//удаление пустого импорта
TextGRPCServer = create_files.Delete_EmptyImport(TextGRPCServer)
//удаление пустых строк
TextGRPCServer = create_files.Delete_EmptyLines(TextGRPCServer)
//запись файла
err = os.WriteFile(FilenameReady, []byte(TextGRPCServer), config.Settings.FILE_PERMISSIONS)
return err
}
// CreateFiles_FindModelBy_Table - создаёт текст всех функций
func CreateFiles_FindModelBy_Table(MapAll map[string]*types.Table, Table1 *types.Table, TextTemplateFunction string) string {
Otvet := ""
for _, TableColumns1 := range types.MassFindModelBy {
if TableColumns1.Table != Table1 {
continue
}
Otvet1 := CreateFiles_FindModelBy_Table1(MapAll, Table1, TextTemplateFunction, TableColumns1.Column)
Otvet = Otvet + Otvet1
}
return Otvet
}
// CreateFiles_FindModelBy_Table1 - создаёт текст всех функций
func CreateFiles_FindModelBy_Table1(MapAll map[string]*types.Table, Table1 *types.Table, TextTemplateFunction string, Column1 *types.Column) string {
Otvet := TextTemplateFunction
//
FieldNamesWithUnderline := ""
FieldNamesWithComma := ""
TextAssign := ""
//MassColumns := create_files.FindMass_Columns_from_MassColumnsString(Table1, MassColumnsString)
//
TextFind := "\t" + `Model.FieldName = Request.RequestFieldName` + "\n"
Underline := ""
Plus := ""
RequestName := "Request_Model_"
//RequestFieldName := create_files.Find_RequestFieldName_FromMass(Column1, MassColumns)
TextRequest, TextRequestCode := create_files.Convert_ProtobufVariableToGolangVariable(Table1, Column1, "Request.")
if TextRequestCode != "" {
TextAssign = TextAssign + TextRequestCode + "\n"
} else {
TextAssign = TextAssign + "\t" + "Model." + Column1.NameGo + " = " + TextRequest + "\n"
}
FieldNamesWithUnderline = FieldNamesWithUnderline + Underline + Column1.NameGo_translit
FieldNamesWithComma = FieldNamesWithComma + Plus + Column1.NameGo
ProtoTypeName := create_files.Convert_GolangTypeNameToProtobufFieldName(Column1.TypeGo)
RequestName = RequestName + Underline + ProtoTypeName
Underline = "_"
Plus = "+"
//}
Otvet = strings.ReplaceAll(Otvet, "RequestName", RequestName)
Otvet = strings.ReplaceAll(Otvet, TextFind, TextAssign)
Otvet = strings.ReplaceAll(Otvet, "FieldNamesWithUnderline", FieldNamesWithUnderline)
Otvet = strings.ReplaceAll(Otvet, "FieldNamesWithPlus", FieldNamesWithComma)
//
ForeignTableName := Column1.TableKey
ForeignTable, ok := MapAll[ForeignTableName]
if ok == false {
log.Panic("Table not found: ", ForeignTableName)
}
//
TextFindModelBy := "Find" + ForeignTable.NameGo_translit + "By"
Otvet = strings.ReplaceAll(Otvet, "FindModelBy", TextFindModelBy)
//
TextForeignModel := ForeignTable.NameGo
Otvet = strings.ReplaceAll(Otvet, "ForeignModel", TextForeignModel)
return Otvet
}
// CreateFiles_FindModelBy_Test - создаёт 1 файл в папке server_grpc
func CreateFiles_FindModelBy_Test(MapAll map[string]*types.Table, Table1 *types.Table) error {
var err error
if len(types.MassFindModelBy) == 0 {
return err
}
//чтение файлов
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()
FilenameTemplateGRPCServer := DirTemplatesGRPCServer + config.Settings.TEMPLATES_GRPC_SERVER_FINDMODELBY_TEST_FILENAME
TableName := strings.ToLower(Table1.Name)
DirReadyTable := DirReadyGRPCServer
FilenameReady := DirReadyTable + micro.SeparatorFile() + config.Settings.PREFIX_SERVER_GRPC + TableName + "_findmodelby_test.go"
//создадим каталог
ok, err := micro.FileExists(DirReadyTable)
if ok == false {
err = os.MkdirAll(DirReadyTable, 0777)
if err != nil {
log.Panic("Mkdir() ", DirReadyTable, " error: ", err)
}
}
//загрузим шаблон файла
bytes, err := os.ReadFile(FilenameTemplateGRPCServer)
if err != nil {
log.Panic("ReadFile() ", FilenameTemplateGRPCServer, " error: ", err)
}
TextGRPCServer := string(bytes)
//загрузим шаблон файла функции
FilenameTemplateGRPCServerFunction := DirTemplatesGRPCServer + config.Settings.TEMPLATES_GRPC_SERVER_FINDMODELBY_FUNCTION_TEST_FILENAME
bytes, err = os.ReadFile(FilenameTemplateGRPCServerFunction)
if err != nil {
log.Panic("ReadFile() ", FilenameTemplateGRPCServerFunction, " error: ", err)
}
TextTemplatedFunction := string(bytes)
//заменим имя пакета на новое
TextGRPCServer = create_files.Replace_PackageName(TextGRPCServer, DirReadyTable)
//ModelName := Table1.NameGo
//заменим импорты
if config.Settings.USE_DEFAULT_TEMPLATE == true {
TextGRPCServer = create_files.Delete_TemplateRepositoryImports(TextGRPCServer)
ModelTableURL := create_files.Find_ModelTableURL(TableName)
TextGRPCServer = create_files.AddImport(TextGRPCServer, ModelTableURL)
CrudStarterURL := create_files.Find_CrudStarterURL()
TextGRPCServer = create_files.AddImport(TextGRPCServer, CrudStarterURL)
ProtoURL := create_files.Find_ProtoURL()
TextGRPCServer = create_files.AddImport(TextGRPCServer, ProtoURL)
CrudFuncURL := create_files.Find_CrudFuncURL(TableName)
TextGRPCServer = create_files.AddImport(TextGRPCServer, CrudFuncURL)
}
//создание функций
TextGRPCServerFunc := CreateFiles_FindModelBy_Test_Table(Table1, TextTemplatedFunction)
if TextGRPCServerFunc == "" {
return err
}
TextGRPCServer = TextGRPCServer + TextGRPCServerFunc
//создание текста
TextGRPCServer = create_files.Replace_TemplateModel_to_Model(TextGRPCServer, Table1.NameGo)
TextGRPCServer = create_files.Replace_TemplateTableName_to_TableName(TextGRPCServer, Table1.Name)
TextGRPCServer = create_files.AddText_ModuleGenerated(TextGRPCServer)
//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
//замена импортов на новые URL
TextGRPCServer = create_files.Replace_RepositoryImportsURL(TextGRPCServer)
//uuid
TextGRPCServer = create_files.CheckAndAdd_ImportUUID_FromText(TextGRPCServer)
//alias
TextGRPCServer = create_files.CheckAndAdd_ImportAlias(TextGRPCServer)
//удаление пустого импорта
TextGRPCServer = create_files.Delete_EmptyImport(TextGRPCServer)
//удаление пустых строк
TextGRPCServer = create_files.Delete_EmptyLines(TextGRPCServer)
//запись файла
err = os.WriteFile(FilenameReady, []byte(TextGRPCServer), config.Settings.FILE_PERMISSIONS)
return err
}
// CreateFiles_FindModelBy_Test_Table - создаёт текст всех функций
func CreateFiles_FindModelBy_Test_Table(Table1 *types.Table, TextTemplateFunction string) string {
Otvet := ""
for _, TableColumns1 := range types.MassFindModelBy {
if TableColumns1.Table != Table1 {
continue
}
Otvet1 := CreateFiles_FindModelBy_Test_Table1(Table1, TextTemplateFunction, TableColumns1.Column)
Otvet = Otvet + Otvet1
}
return Otvet
}
// CreateFiles_FindModelBy_Test_Table1 - создаёт текст всех функций
func CreateFiles_FindModelBy_Test_Table1(Table1 *types.Table, TextTemplateFunction string, Column1 *types.Column) string {
Otvet := TextTemplateFunction
//
FieldNamesWithUnderline := ""
FieldNamesWithComma := ""
//
TextAssignFind := "\t" + `Request.RequestFieldName = 0` + "\n"
TextAssign := ""
TextFieldName_TEST := ""
//MassColumns := create_files.FindMass_Columns_from_MassColumnsString(Table1, MassColumnsString)
Underline := ""
Comma := ""
RequestName := "Request_Model_"
//for _, ColumnName1 := range MassColumnsString {
DefaultValue := create_files.FindText_DefaultValue(Column1.TypeGo)
RequestFieldName := create_files.Convert_GolangTypeNameToProtobufFieldName(Column1.TypeGo)
TextAssign = TextAssign + "\t" + `Request.` + RequestFieldName + ` = ` + DefaultValue + "\n"
FieldNamesWithUnderline = FieldNamesWithUnderline + Underline + Column1.NameGo_translit
FieldNamesWithComma = FieldNamesWithComma + Comma + Column1.NameGo
TextFieldName_TEST = TextFieldName_TEST + Comma + DefaultValue
ProtoTypeName := create_files.Convert_GolangTypeNameToProtobufFieldName(Column1.TypeGo)
RequestName = RequestName + Underline + ProtoTypeName
Underline = "_"
Comma = ", "
//}
Otvet = strings.ReplaceAll(Otvet, "RequestName", RequestName)
Otvet = strings.ReplaceAll(Otvet, TextAssignFind, TextAssign)
Otvet = strings.ReplaceAll(Otvet, "FieldNamesWithUnderline", FieldNamesWithUnderline)
Otvet = strings.ReplaceAll(Otvet, "FieldNamesWithComma", FieldNamesWithComma)
Otvet = strings.ReplaceAll(Otvet, "FieldNamesDefault", TextFieldName_TEST)
return Otvet
}