1
0
mirror of https://github.com/ManyakRus/crud_generator.git synced 2024-11-21 05:05:52 +02:00

сделал CreateFiles_FindModelBy()

This commit is contained in:
Nikitin Aleksandr 2024-10-15 15:24:54 +03:00
parent 3b8b214915
commit 5427c82e7d
25 changed files with 858 additions and 50 deletions

View File

@ -0,0 +1 @@
[]

View File

@ -0,0 +1,3 @@
[
{"TableName":"briefcases","ColumnName":"lawer_id"}
]

View File

@ -85,6 +85,15 @@ readall_function.json
Need for automatic create functions ReadAll() returning all rows in table (exclude is_deleted rows)
example:
{
"lawsuits": ""
"table_name1": ""
}
findmodelby_functions.json
Need for automatic create FindModelBy() functions searching 1 value in table_name1 filtered by column_name1,
this value will be searched in foreign table as identifier, and return this 1 row model
example:
[
{"TableName":"table_name1","ColumnName":"column_name1"}
]

View File

@ -489,3 +489,54 @@ TEXT_READALL = "ReadAll"
#TEMPLATES_NAME_PRIMARYKEYS_FILENAME - filename of "primary_keys.json" file
TEMPLATES_NAME_PRIMARYKEYS_FILENAME = "primary_keys.json"
#---FINDMODELBY---
#TEMPLATES_FINDMODELBY_FILENAME - short filename of "findmodelby_functions.json" file
TEMPLATES_FINDMODELBY_FILENAME="findmodelby_functions.json"
#TEMPLATES_CRUD_TABLE_FINDMODELBY_FILENAME - short filename of "crud_tables_findmodelby.go_" file
TEMPLATES_CRUD_TABLE_FINDMODELBY_FILENAME="crud_tables_findmodelby.go_"
#TEMPLATES_CRUD_TABLE_FINDMODELBY_TEST_FILENAME - short filename of "crud_tables_findmodelby_test.go_" file
TEMPLATES_CRUD_TABLE_FINDMODELBY_TEST_FILENAME="crud_tables_findmodelby_test.go_"
#TEMPLATES_CRUD_TABLE_FINDMODELBY_FUNCTION_FILENAME - short filename of "crud_tables_findmodelby_function.go_" file
TEMPLATES_CRUD_TABLE_FINDMODELBY_FUNCTION_FILENAME="crud_tables_findmodelby_function.go_"
#TEMPLATES_CRUD_TABLE_FINDMODELBY_FUNCTION_TEST_FILENAME - short filename of "crud_tables_findmodelby_function_test.go_" file
TEMPLATES_CRUD_TABLE_FINDMODELBY_FUNCTION_TEST_FILENAME="crud_tables_findmodelby_function_test.go_"
#TEMPLATES_GRPC_SERVER_FINDMODELBY_FILENAME - short filename of "server_grpc_table_findmodelby.go_" file
TEMPLATES_GRPC_SERVER_FINDMODELBY_FILENAME="server_grpc_table_findmodelby.go_"
#TEMPLATES_GRPC_SERVER_FINDMODELBY_FUNCTION_FILENAME - short filename of "server_grpc_table_findmodelby_test.go_" file
TEMPLATES_GRPC_SERVER_FINDMODELBY_FUNCTION_FILENAME="server_grpc_table_findmodelby_function.go_"
#TEMPLATES_GRPC_SERVER_FINDMODELBY_TEST_FILENAME - short filename of "server_grpc_table_findmodelby_test.go_" file
TEMPLATES_GRPC_SERVER_FINDMODELBY_TEST_FILENAME="server_grpc_table_findmodelby_test.go_"
#TEMPLATES_GRPC_SERVER_FINDMODELBY_FUNCTION_TEST_FILENAME - short filename of "server_grpc_table_findmodelby_test.go_" file
TEMPLATES_GRPC_SERVER_FINDMODELBY_FUNCTION_TEST_FILENAME="server_grpc_table_findmodelby_function_test.go_"
#TEMPLATES_MODEL_FINDMODELBY_FILENAME - short filename of "model_table_findmodelby.go_" file
TEMPLATES_MODEL_FINDMODELBY_FILENAME="model_table_findmodelby.go_"
#TEMPLATES_MODEL_FINDMODELBY_FUNCTION_FILENAME - short filename of "model_table_findmodelby_function.go_" file
TEMPLATES_MODEL_FINDMODELBY_FUNCTION_FILENAME="model_table_findmodelby_function.go_"
#TEMPLATES_GRPC_CLIENT_TABLES_FINDMODELBY_FILENAME - short filename of "grpc_client_table_findmodelby.go_" file
TEMPLATES_GRPC_CLIENT_TABLES_FINDMODELBY_FILENAME="grpc_client_table_findmodelby.go_"
#TEMPLATES_GRPC_CLIENT_TABLES_FINDMODELBY_TEST_FILENAME - short filename of "grpc_client_table_findmodelby_test.go_" file
TEMPLATES_GRPC_CLIENT_TABLES_FINDMODELBY_TEST_FILENAME="grpc_client_table_findmodelby_test.go_"
#TEMPLATES_GRPC_CLIENT_TABLES_FINDMODELBY_FUNCTION_FILENAME - short filename of "grpc_client_table_findmodelby_function.go_" file
TEMPLATES_GRPC_CLIENT_TABLES_FINDMODELBY_FUNCTION_FILENAME="grpc_client_table_findmodelby_function.go_"
#TEMPLATES_GRPC_CLIENT_TABLES_FINDMODELBY_FUNCTION_TEST_FILENAME - short filename of "grpc_client_table_findmodelby_function_test.go_" file
TEMPLATES_GRPC_CLIENT_TABLES_FINDMODELBY_FUNCTION_TEST_FILENAME="grpc_client_table_findmodelby_function_test.go_"
#

View File

@ -0,0 +1,10 @@
package server_grpc
import (
"context"
"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"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types"
)

View File

@ -0,0 +1,32 @@
// LawsuitStatusType_FindByFieldNamesWithUnderline - находит lawsuit_status_types в БД по FieldNamesWithPlus
func (s *ServerGRPC) LawsuitStatusType_FindBy_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 {
err = ErrorModelVersion(lawsuit_status_types.LawsuitStatusType{})
return &Otvet, err
}
// запрос в БД
db := postgres_gorm.GetConnection()
Model := &lawsuit_status_types.LawsuitStatusType{}
Model.FieldName = Request.RequestFieldName
err = crud_lawsuit_status_types.FindBy_FieldNamesWithUnderline_ctx(ctx, db, Model)
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,20 @@
func Test_server_LawsuitStatusType_FindBy_FieldNamesWithUnderline(t *testing.T) {
config_main.LoadEnv()
crud_starter.InitCrudTransport_DB()
ctx := context.Background()
Request := grpc_proto.RequestName{}
Request.RequestFieldName = 0
Request.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion()
server1 := &ServerGRPC{}
Otvet, err := server1.LawsuitStatusType_FindBy_FieldNamesWithUnderline(ctx, &Request)
if err != nil && crud_func.IsRecordNotFound(err) == false {
t.Error("Test_server_LawsuitStatusType_FindBy_FieldNamesWithUnderline() error: ", err)
}
if Otvet.ModelString == "" {
t.Log("Test_server_LawsuitStatusType_FindBy_FieldNamesWithUnderline() error: ModelString=''")
}
}

View File

@ -0,0 +1,12 @@
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/files"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/crud_func"
"testing"
)

View File

@ -0,0 +1,11 @@
package crud_lawsuit_status_types
import (
"context"
"github.com/ManyakRus/starter/postgres_gorm"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/db_constants"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types"
"gorm.io/gorm"
"time"
)

View File

@ -0,0 +1,46 @@
// FindModelBy_FieldNamesWithUnderline - находит запись в БД из связанной таблицы по FieldNamesWithPlus
func (crud Crud_DB) FindModelBy_FieldNamesWithUnderline(m *lawsuit_status_types.LawsuitStatusType) (foreign_package.ForeignModel, error) {
var err error
ctxMain := context.Background()
ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(db_constants.TIMEOUT_DB_SECONDS))
defer ctxCancelFunc()
db := postgres_gorm.GetConnection()
Otvet, err := FindModelBy_FieldNamesWithUnderline_ctx(ctx, db, m)
return Otvet, err
}
// FindModelBy_FieldNamesWithUnderline_ctx - находит запись в БД из связанной таблицы по FieldNamesWithPlus
func FindModelBy_FieldNamesWithUnderline_ctx(ctx context.Context, db *gorm.DB, m *lawsuit_status_types.LawsuitStatusType) (foreign_package.ForeignModel, error) {
Otvet := foreign_package.ForeignModel{}
var err error
tx := db.WithContext(ctx)
//находим запись в этой таблице
//tx = tx.Where("ColumnName = ?", m.PrimaryKeyName)
tx = tx.First(m)
err = tx.Error
if err != nil {
err = fmt.Errorf("tx.First() error: %w", err)
return Otvet, err
}
//находим запись в другой таблице
tx = db.WithContext(ctx)
ID := m.FieldName
Otvet.ForeignPrimaryKeyName = ID
tx = tx.First(&Otvet)
err = tx.Error
if err != nil {
err = fmt.Errorf("tx.First() error: %w", err)
return Otvet, err
}
return Otvet, err
}

View File

@ -0,0 +1,15 @@
func TestFindModelBy_FieldNamesWithUnderline(t *testing.T) {
config_main.LoadEnv()
postgres_gorm.Connect()
defer postgres_gorm.CloseConnection()
crud := Crud_DB{}
Otvet := lawsuit_status_types.LawsuitStatusType{}
Otvet.FieldName = 0
_, err := crud.FindModelBy_FieldNamesWithUnderline(&Otvet)
if err != nil && crud_func.IsRecordNotFound(err) == false {
t.Error("crud_"+TableName+"_test.TestFindModelBy_FieldNamesWithUnderline() FieldNamesWithComma:", FieldNamesDefault, " error: ", err)
}
}

View File

@ -0,0 +1,10 @@
package crud_lawsuit_status_types
import (
"github.com/ManyakRus/starter/config_main"
"github.com/ManyakRus/starter/postgres_gorm"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/crud_func"
"testing"
)

View File

@ -0,0 +1,12 @@
package grpc_lawsuit_status_types
import (
"context"
"encoding/json"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/api/grpc_proto"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_client_func"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_constants"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types"
"github.com/ManyakRus/starter/log"
)

View File

@ -0,0 +1,42 @@
// FieldNamesWithUnderline - находит модель в БД по FieldNamesWithPlus
func (crud Crud_GRPC) FindBy_FieldNamesWithUnderline(m *lawsuit_status_types.LawsuitStatusType) error {
var err error
// подключение
grpc_client_func.Func_Connect_GRPC_NRPC.Connect_GRPC_NRPC()
// подготовка запроса
var VersionModel = crud.GetVersionModel()
Request := &grpc_proto.RequestName{}
Request.VersionModel = VersionModel
Request.RequestFieldName = m.FieldName
ctxMain := context.Background()
ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(grpc_constants.GetTimeoutSeconds()))
defer ctxCancelFunc()
// запрос
var Response *grpc_proto.Response
if grpc_nrpc.NeedNRPC == true {
Response, err = nrpc_client.Client.LawsuitStatusType_FindBy_FieldNamesWithUnderline(Request)
} else {
Response, err = grpc_client_func.Client.LawsuitStatusType_FindBy_FieldNamesWithUnderline(ctx, Request)
}
if err != nil {
if grpc_client_func.IsErrorModelVersion(err) == true {
log.Panic("table: ", TableName, " error: ", err)
}
return err
}
// ответ
sModel := Response.ModelString
err = json.Unmarshal([]byte(sModel), m)
if err != nil {
return err
}
return err
}

View File

@ -0,0 +1,17 @@
func TestFindBy_FieldNamesWithUnderline(t *testing.T) {
config_main.LoadEnv()
grpc_client.Connect()
defer grpc_client.CloseConnection()
crud := grpc_lawsuit_status_types.Crud_GRPC{}
Otvet := lawsuit_status_types.LawsuitStatusType{}
Otvet.FieldName = 0
err := crud.FindBy_FieldNamesWithUnderline(&Otvet)
if err != nil && crud_func.IsRecordNotFound(err) == false {
t.Error("TestFindBy_FieldNamesWithUnderline() error: ", err)
}
}

View File

@ -0,0 +1,11 @@
package grpc_lawsuit_status_types
import (
"github.com/ManyakRus/starter/config_main"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_client"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_client/grpc_lawsuit_status_types"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/crud_func"
"testing"
)

View File

@ -152,6 +152,23 @@ type SettingsINI struct {
TEMPLATES_MODEL_READALL_FILENAME string
TEMPLATES_MODEL_READALL_FUNCTION_FILENAME string
//---FINDMODELBY---
TEMPLATES_FINDMODELBY_FILENAME string
TEMPLATES_CRUD_TABLE_FINDMODELBY_FILENAME string
TEMPLATES_CRUD_TABLE_FINDMODELBY_TEST_FILENAME string
TEMPLATES_CRUD_TABLE_FINDMODELBY_FUNCTION_FILENAME string
TEMPLATES_CRUD_TABLE_FINDMODELBY_FUNCTION_TEST_FILENAME string
TEMPLATES_GRPC_SERVER_FINDMODELBY_FILENAME string
TEMPLATES_GRPC_SERVER_FINDMODELBY_FUNCTION_FILENAME string
TEMPLATES_GRPC_SERVER_FINDMODELBY_TEST_FILENAME string
TEMPLATES_GRPC_SERVER_FINDMODELBY_FUNCTION_TEST_FILENAME string
TEMPLATES_GRPC_CLIENT_TABLES_FINDMODELBY_FILENAME string
TEMPLATES_GRPC_CLIENT_TABLES_FINDMODELBY_TEST_FILENAME string
TEMPLATES_GRPC_CLIENT_TABLES_FINDMODELBY_FUNCTION_FILENAME string
TEMPLATES_GRPC_CLIENT_TABLES_FINDMODELBY_FUNCTION_TEST_FILENAME string
TEMPLATES_MODEL_FINDMODELBY_FILENAME string
TEMPLATES_MODEL_FINDMODELBY_FUNCTION_FILENAME string
TEMPLATES_CRUD_FUNC_FOLDERNAME string
TEMPLATES_CRUD_FUNC_FILENAME string
TEMPLATES_CRUD_FUNC_TEST_FILENAME string
@ -869,6 +886,82 @@ func FillSettings() {
s = Getenv(Name, true)
Settings.TEMPLATES_GRPC_CLIENT_TABLES_READALL_FUNCTION_TEST_FILENAME = s
//-----------------FINDMODELBY---------------------------
//
Name = "TEMPLATES_FINDMODELBY_FILENAME"
s = Getenv(Name, true)
Settings.TEMPLATES_FINDMODELBY_FILENAME = s
//
Name = "TEMPLATES_CRUD_TABLE_FINDMODELBY_FILENAME"
s = Getenv(Name, true)
Settings.TEMPLATES_CRUD_TABLE_FINDMODELBY_FILENAME = s
//
Name = "TEMPLATES_CRUD_TABLE_FINDMODELBY_TEST_FILENAME"
s = Getenv(Name, true)
Settings.TEMPLATES_CRUD_TABLE_FINDMODELBY_TEST_FILENAME = s
//
Name = "TEMPLATES_CRUD_TABLE_FINDMODELBY_FUNCTION_FILENAME"
s = Getenv(Name, true)
Settings.TEMPLATES_CRUD_TABLE_FINDMODELBY_FUNCTION_FILENAME = s
//
Name = "TEMPLATES_CRUD_TABLE_FINDMODELBY_FUNCTION_TEST_FILENAME"
s = Getenv(Name, true)
Settings.TEMPLATES_CRUD_TABLE_FINDMODELBY_FUNCTION_TEST_FILENAME = s
//
Name = "TEMPLATES_GRPC_SERVER_FINDMODELBY_FILENAME"
s = Getenv(Name, true)
Settings.TEMPLATES_GRPC_SERVER_FINDMODELBY_FILENAME = s
//
Name = "TEMPLATES_GRPC_SERVER_FINDMODELBY_FUNCTION_FILENAME"
s = Getenv(Name, true)
Settings.TEMPLATES_GRPC_SERVER_FINDMODELBY_FUNCTION_FILENAME = s
//
Name = "TEMPLATES_GRPC_SERVER_FINDMODELBY_TEST_FILENAME"
s = Getenv(Name, true)
Settings.TEMPLATES_GRPC_SERVER_FINDMODELBY_TEST_FILENAME = s
//
Name = "TEMPLATES_GRPC_SERVER_FINDMODELBY_FUNCTION_TEST_FILENAME"
s = Getenv(Name, true)
Settings.TEMPLATES_GRPC_SERVER_FINDMODELBY_FUNCTION_TEST_FILENAME = s
//
Name = "TEMPLATES_MODEL_FINDMODELBY_FILENAME"
s = Getenv(Name, true)
Settings.TEMPLATES_MODEL_FINDMODELBY_FILENAME = s
//
Name = "TEMPLATES_MODEL_FINDMODELBY_FUNCTION_FILENAME"
s = Getenv(Name, true)
Settings.TEMPLATES_MODEL_FINDMODELBY_FUNCTION_FILENAME = s
//
Name = "TEMPLATES_GRPC_CLIENT_TABLES_FINDMODELBY_FILENAME"
s = Getenv(Name, true)
Settings.TEMPLATES_GRPC_CLIENT_TABLES_FINDMODELBY_FILENAME = s
//
Name = "TEMPLATES_GRPC_CLIENT_TABLES_FINDMODELBY_TEST_FILENAME"
s = Getenv(Name, true)
Settings.TEMPLATES_GRPC_CLIENT_TABLES_FINDMODELBY_TEST_FILENAME = s
//
Name = "TEMPLATES_GRPC_CLIENT_TABLES_FINDMODELBY_FUNCTION_FILENAME"
s = Getenv(Name, true)
Settings.TEMPLATES_GRPC_CLIENT_TABLES_FINDMODELBY_FUNCTION_FILENAME = s
//
Name = "TEMPLATES_GRPC_CLIENT_TABLES_FINDMODELBY_FUNCTION_TEST_FILENAME"
s = Getenv(Name, true)
Settings.TEMPLATES_GRPC_CLIENT_TABLES_FINDMODELBY_FUNCTION_TEST_FILENAME = s
//----------------CRUD_FUNC----------------------------
//
Name = "TEMPLATES_CRUD_FUNC_FOLDERNAME"

View File

@ -21,8 +21,8 @@ func CreateCrud() error {
DirReady := DirBin + config.Settings.READY_FOLDERNAME + micro.SeparatorFile()
DirTemplatesCrud := DirTemplates + config.Settings.TEMPLATES_CRUD_FUNC_FOLDERNAME + micro.SeparatorFile()
DirReadyCrud := DirReady + config.Settings.TEMPLATES_CRUD_FUNC_FOLDERNAME + micro.SeparatorFile()
FilenameReadyCrud := DirReadyCrud + create_files.Delete_LastUnderline(config.Settings.TEMPLATES_CRUD_FUNC_TEST_FILENAME)
FilenameTemplateCrud := DirTemplatesCrud + config.Settings.TEMPLATES_CRUD_FUNC_TEST_FILENAME
FilenameReadyCrud := DirReadyCrud + create_files.Delete_LastUnderline(config.Settings.TEMPLATES_CRUD_FUNC_FILENAME)
FilenameTemplateCrud := DirTemplatesCrud + config.Settings.TEMPLATES_CRUD_FUNC_FILENAME
//создадим папку готовых файлов
folders.CreateFolder(DirReadyCrud)

View File

@ -74,48 +74,61 @@ func CreateAllFiles(MapAll map[string]*types.Table) error {
return err
}
}
}
//FindBy
err = CreateFiles_FindBy(Table1)
if err != nil {
log.Error("CreateFiles_FindBy() table: ", Table1.Name, " error: ", err)
return err
}
//FindBy
err = CreateFiles_FindBy(Table1)
if err != nil {
log.Error("CreateFiles_FindBy() table: ", Table1.Name, " error: ", err)
return err
}
//
err = CreateFiles_FindBy_Test(Table1)
if err != nil {
log.Error("CreateFiles_FindBy_Test() table: ", Table1.Name, " error: ", err)
return err
}
//
err = CreateFiles_FindBy_Test(Table1)
if err != nil {
log.Error("CreateFiles_FindBy_Test() table: ", Table1.Name, " error: ", err)
return err
}
//FindMassBy
err = CreateFiles_FindMassBy(Table1)
if err != nil {
log.Error("CreateFiles_FindMassBy() table: ", Table1.Name, " error: ", err)
return err
}
//FindMassBy
err = CreateFiles_FindMassBy(Table1)
if err != nil {
log.Error("CreateFiles_FindMassBy() table: ", Table1.Name, " error: ", err)
return err
}
//
err = CreateFiles_FindMassBy_Test(Table1)
if err != nil {
log.Error("CreateFiles_FindMassBy_Test() table: ", Table1.Name, " error: ", err)
return err
}
//
err = CreateFiles_FindMassBy_Test(Table1)
if err != nil {
log.Error("CreateFiles_FindMassBy_Test() table: ", Table1.Name, " error: ", err)
return err
}
//ReadAll
err = CreateFiles_ReadAll(Table1)
if err != nil {
log.Error("CreateFiles_FindMassBy() table: ", Table1.Name, " error: ", err)
return err
}
//ReadAll
err = CreateFiles_ReadAll(Table1)
if err != nil {
log.Error("CreateFiles_FindMassBy() table: ", Table1.Name, " error: ", err)
return err
}
//
err = CreateFiles_ReadAll_Test(Table1)
if err != nil {
log.Error("CreateFiles_FindMassBy_Test() table: ", Table1.Name, " error: ", err)
return err
}
//
err = CreateFiles_ReadAll_Test(Table1)
if err != nil {
log.Error("CreateFiles_FindMassBy_Test() table: ", Table1.Name, " error: ", err)
return err
}
//FindModelBy
err = CreateFiles_FindModelBy(MapAll, Table1)
if err != nil {
log.Error("CreateFiles_FindMassBy() table: ", Table1.Name, " error: ", err)
return err
}
//
err = CreateFiles_FindModelBy_Test(MapAll, Table1)
if err != nil {
log.Error("CreateFiles_FindMassBy_Test() table: ", Table1.Name, " error: ", err)
return err
}
}

View File

@ -0,0 +1,345 @@
package crud_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 файл в папке crud
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()
DirTemplatesCrud := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_CRUD + micro.SeparatorFile()
DirReadyCrud := DirReady + config.Settings.TEMPLATE_FOLDERNAME_CRUD + micro.SeparatorFile()
FilenameTemplateCrud := DirTemplatesCrud + config.Settings.TEMPLATES_CRUD_TABLE_FINDMODELBY_FILENAME
TableName := strings.ToLower(Table1.Name)
DirReadyTable := DirReadyCrud + config.Settings.PREFIX_CRUD + TableName
FilenameReady := DirReadyTable + micro.SeparatorFile() + config.Settings.PREFIX_CRUD + 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(FilenameTemplateCrud)
if err != nil {
log.Panic("ReadFile() ", FilenameTemplateCrud, " error: ", err)
}
TextCrud := string(bytes)
//загрузим шаблон файла функции
FilenameTemplateCrudFunction := DirTemplatesCrud + config.Settings.TEMPLATES_CRUD_TABLE_FINDMODELBY_FUNCTION_FILENAME
bytes, err = os.ReadFile(FilenameTemplateCrudFunction)
if err != nil {
log.Panic("ReadFile() ", FilenameTemplateCrudFunction, " error: ", err)
}
TextTemplatedFunction := string(bytes)
//заменим имя пакета на новое
TextCrud = create_files.Replace_PackageName(TextCrud, DirReadyTable)
//ModelName := Table1.NameGo
//заменим импорты
if config.Settings.USE_DEFAULT_TEMPLATE == true {
TextCrud = create_files.Delete_TemplateRepositoryImports(TextCrud)
ModelTableURL := create_files.Find_ModelTableURL(TableName)
TextCrud = create_files.AddImport(TextCrud, ModelTableURL)
ConstantsURL := create_files.Find_DBConstantsURL()
TextCrud = create_files.AddImport(TextCrud, ConstantsURL)
}
//создание функций
TextCrudFunc := CreateFiles_FindModelBy_Table(MapAll, Table1, &TextCrud, TextTemplatedFunction)
if TextCrudFunc == "" {
return err
}
TextCrud = TextCrud + TextCrudFunc
//создание текста
TextCrud = create_files.Replace_TemplateModel_to_Model(TextCrud, Table1.NameGo)
TextCrud = create_files.Replace_TemplateTableName_to_TableName(TextCrud, Table1.Name)
TextCrud = create_files.AddText_ModuleGenerated(TextCrud)
//TextCrud = strings.ReplaceAll(TextCrud, config.Settings.TEXT_TEMPLATE_MODEL, ModelName)
//TextCrud = strings.ReplaceAll(TextCrud, config.Settings.TEXT_TEMPLATE_TABLENAME, Table1.Name)
//TextCrud = config.Settings.TEXT_MODULE_GENERATED + TextCrud
//замена импортов на новые URL
TextCrud = create_files.Replace_RepositoryImportsURL(TextCrud)
//uuid
TextCrud = create_files.CheckAndAdd_ImportUUID_FromText(TextCrud)
//alias
TextCrud = create_files.CheckAndAdd_ImportAlias(TextCrud)
//fmt
TextCrud = create_files.CheckAndAdd_ImportFmt(TextCrud)
//удаление пустого импорта
TextCrud = create_files.Delete_EmptyImport(TextCrud)
//удаление пустых строк
TextCrud = create_files.Delete_EmptyLines(TextCrud)
//запись файла
err = os.WriteFile(FilenameReady, []byte(TextCrud), config.Settings.FILE_PERMISSIONS)
return err
}
// CreateFiles_FindModelBy_Table - создаёт текст всех функций
func CreateFiles_FindModelBy_Table(MapAll map[string]*types.Table, Table1 *types.Table, TextCrud *string, TextTemplateFunction string) string {
Otvet := ""
for _, TableColumns1 := range types.MassFindModelBy {
if TableColumns1.Table != Table1 {
continue
}
Otvet1 := CreateFiles_FindModelBy_Table1(MapAll, Table1, TextCrud, TextTemplateFunction, TableColumns1.Column)
Otvet = Otvet + Otvet1
}
return Otvet
}
// CreateFiles_FindModelBy_Table1 - создаёт текст всех функций
func CreateFiles_FindModelBy_Table1(MapAll map[string]*types.Table, Table1 *types.Table, TextCrud *string, TextTemplateFunction string, Column1 *types.Column) string {
Otvet := TextTemplateFunction
//
FieldNamesWithUnderline := ""
FieldNamesWithComma := ""
TextWhere := ""
//ColumnPK := create_files.Find_PrimaryKeyColumn(Table1)
//
TextFind := "\t" + `//tx = tx.Where("ColumnName = ?", m.PrimaryKeyName)` + "\n"
Underline := ""
Plus := ""
//TextWhere = TextWhere + "\t" + `tx = tx.Where("` + ColumnPK.Name + ` = ?", m.` + ColumnPK.NameGo + `)` + "\n"
FieldNamesWithUnderline = FieldNamesWithUnderline + Underline + Column1.NameGo
FieldNamesWithComma = FieldNamesWithComma + Plus + Column1.NameGo
Underline = "_"
Plus = "+"
//кроме помеченных на удаление
if create_files.Has_Column_IsDeleted_Bool(Table1) == true {
TextWhere = TextWhere + "\t" + `tx = tx.Where("is_deleted = ?", false)` + "\n"
}
//
Otvet = strings.ReplaceAll(Otvet, TextFind, TextWhere)
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)
//
TextForeignPackage := ForeignTable.Name
Otvet = strings.ReplaceAll(Otvet, "foreign_package", TextForeignPackage)
//
TextForeignModel := ForeignTable.NameGo
Otvet = strings.ReplaceAll(Otvet, "ForeignModel", TextForeignModel)
//
Foreign_ColumnPK := create_files.Find_PrimaryKeyColumn(ForeignTable)
TextForeignPrimaryKeyName := Foreign_ColumnPK.NameGo
Otvet = strings.ReplaceAll(Otvet, "ForeignPrimaryKeyName", TextForeignPrimaryKeyName)
//
TextFieldName := Column1.NameGo
Otvet = strings.ReplaceAll(Otvet, "FieldName", TextFieldName)
//
ModelTableURL := create_files.Find_ModelTableURL(ForeignTableName)
*TextCrud = create_files.AddImport(*TextCrud, ModelTableURL)
return Otvet
}
// CreateFiles_FindModelBy_Test - создаёт 1 файл в папке crud
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()
DirTemplatesCrud := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_CRUD + micro.SeparatorFile()
DirReadyCrud := DirReady + config.Settings.TEMPLATE_FOLDERNAME_CRUD + micro.SeparatorFile()
FilenameTemplateCrud := DirTemplatesCrud + config.Settings.TEMPLATES_CRUD_TABLE_FINDMODELBY_TEST_FILENAME
TableName := strings.ToLower(Table1.Name)
DirReadyTable := DirReadyCrud + config.Settings.PREFIX_CRUD + TableName
FilenameReady := DirReadyTable + micro.SeparatorFile() + config.Settings.PREFIX_CRUD + 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(FilenameTemplateCrud)
if err != nil {
log.Panic("ReadFile() ", FilenameTemplateCrud, " error: ", err)
}
TextCrud := string(bytes)
//загрузим шаблон файла функции
FilenameTemplateCrudFunction := DirTemplatesCrud + config.Settings.TEMPLATES_CRUD_TABLE_FINDMODELBY_FUNCTION_TEST_FILENAME
bytes, err = os.ReadFile(FilenameTemplateCrudFunction)
if err != nil {
log.Panic("ReadFile() ", FilenameTemplateCrudFunction, " error: ", err)
}
TextTemplatedFunction := string(bytes)
//заменим имя пакета на новое
TextCrud = create_files.Replace_PackageName(TextCrud, DirReadyTable)
//ModelName := Table1.NameGo
//заменим импорты
if config.Settings.USE_DEFAULT_TEMPLATE == true {
TextCrud = create_files.Delete_TemplateRepositoryImports(TextCrud)
ModelTableURL := create_files.Find_ModelTableURL(TableName)
TextCrud = create_files.AddImport(TextCrud, ModelTableURL)
CrudFuncURL := create_files.Find_CrudFuncURL(TableName)
TextCrud = create_files.AddImport(TextCrud, CrudFuncURL)
}
//создание функций
TextCrudFunc := CreateFiles_FindModelBy_Test_Table(MapAll, Table1, TextTemplatedFunction)
if TextCrudFunc == "" {
return err
}
TextCrud = TextCrud + TextCrudFunc
//создание текста
TextCrud = create_files.Replace_TemplateModel_to_Model(TextCrud, Table1.NameGo)
TextCrud = create_files.Replace_TemplateTableName_to_TableName(TextCrud, Table1.Name)
TextCrud = create_files.AddText_ModuleGenerated(TextCrud)
//TextCrud = strings.ReplaceAll(TextCrud, config.Settings.TEXT_TEMPLATE_MODEL, ModelName)
//TextCrud = strings.ReplaceAll(TextCrud, config.Settings.TEXT_TEMPLATE_TABLENAME, Table1.Name)
//TextCrud = config.Settings.TEXT_MODULE_GENERATED + TextCrud
//замена импортов на новые URL
TextCrud = create_files.Replace_RepositoryImportsURL(TextCrud)
//uuid
TextCrud = create_files.CheckAndAdd_ImportUUID_FromText(TextCrud)
//alias
TextCrud = create_files.CheckAndAdd_ImportAlias(TextCrud)
//удаление пустого импорта
TextCrud = create_files.Delete_EmptyImport(TextCrud)
//удаление пустых строк
TextCrud = create_files.Delete_EmptyLines(TextCrud)
//запись файла
err = os.WriteFile(FilenameReady, []byte(TextCrud), config.Settings.FILE_PERMISSIONS)
return err
}
// CreateFiles_FindModelBy_Test_Table - создаёт текст всех функций
func CreateFiles_FindModelBy_Test_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_Test_Table1(MapAll, Table1, TextTemplateFunction, TableColumns1.Column)
Otvet = Otvet + Otvet1
}
return Otvet
}
// CreateFiles_FindModelBy_Test_Table1 - создаёт текст всех функций
func CreateFiles_FindModelBy_Test_Table1(MapAll map[string]*types.Table, Table1 *types.Table, TextTemplateFunction string, Column1 *types.Column) string {
Otvet := TextTemplateFunction
//
FieldNamesWithUnderline := ""
FieldNamesWithComma := ""
//
TextAssignFind := "\t" + `Otvet.FieldName = 0` + "\n"
TextAssign := ""
TextFieldName_TEST := ""
Underline := ""
Comma := ""
DefaultValue := create_files.FindText_DefaultValue(Column1.TypeGo)
TextAssign = TextAssign + "\t" + `Otvet.` + Column1.NameGo + ` = ` + DefaultValue + "\n"
FieldNamesWithUnderline = FieldNamesWithUnderline + Underline + Column1.NameGo
FieldNamesWithComma = FieldNamesWithComma + Comma + Column1.NameGo
TextFieldName_TEST = TextFieldName_TEST + Comma + DefaultValue
Underline = "_"
Comma = ", "
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)
//
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)
return Otvet
}

View File

@ -339,7 +339,7 @@ order by
}
MapColumns[v.ColumnName] = &Column1
//Table1.Columns = append(Table1.Columns, Column1)
//Table1.Column = append(Table1.Column, Column1)
OrderNumberColumn++
TableName0 = v.TableName

View File

@ -220,13 +220,6 @@ func LoadFindBy() {
TextError := fmt.Sprint("ReadFile() error: ", err)
log.Panic(TextError)
}
//MassFindBy1 := types.TableColumns_String{}
//MassFindBy1.TableName = "TableName"
//MassFindBy1.MassColumnNames = []string{"ColumnName"}
//types.MassFindBy_String = append(types.MassFindBy_String, MassFindBy1)
//bytes, _ = json.Marshal(types.MassFindBy_String) //удалить
//json в map
err = json.Unmarshal(bytes, &types.MassFindBy_String)
if err != nil {
@ -315,3 +308,47 @@ func Load_MapPrimaryKeys() {
}
}
// LoadFindModelBy - загружает из файла .json список функций FindModelBy которые надо создать
func LoadFindModelBy(MapTables map[string]*types.Table) {
dir := micro.ProgramDir_bin()
FileName := dir + config.Settings.TEMPLATE_FOLDERNAME + micro.SeparatorFile() + constants.CONFIG_FOLDER_NAME + micro.SeparatorFile() + config.Settings.TEMPLATES_FINDMODELBY_FILENAME
var err error
//чтение файла
bytes, err := os.ReadFile(FileName)
if err != nil {
TextError := fmt.Sprint("ReadFile() error: ", err)
log.Panic(TextError)
}
//json в map, строки
MassTableColumn_string := make([]types.TableColumn_string, 0)
err = json.Unmarshal(bytes, &MassTableColumn_string)
if err != nil {
log.Panic("Unmarshal() error: ", err)
}
//map strings в map tables
for _, TableColumn_string1 := range MassTableColumn_string {
Table1, ok := MapTables[TableColumn_string1.TableName]
if ok == false {
log.Panic("Table not found: ", TableColumn_string1.TableName)
}
Column1, ok := Table1.MapColumns[TableColumn_string1.ColumnName]
if ok == false {
log.Panic("Column not found: ", TableColumn_string1.ColumnName)
}
if Column1.TableKey == "" || Column1.ColumnKey == "" {
log.Panic("error: foreign key is empty fot table: ", Table1.Name, " column: ", Column1.Name)
}
TableColumn1 := types.TableColumn{}
TableColumn1.Table = Table1
TableColumn1.Column = Column1
types.MassFindModelBy = append(types.MassFindModelBy, TableColumn1)
}
}

View File

@ -56,6 +56,9 @@ func StartFillAll() error {
return err
}
//загрузим FindModelBy .json
load_configs.LoadFindModelBy(MapAll)
//
FillGlobalVariables(MapAll)

View File

@ -22,7 +22,7 @@ type Table struct {
Name string `json:"name" gorm:"column:name;default:''"`
//Element *etree.Element
MapColumns map[string]*Column
//Columns []Column
//Column []Column
OrderNumber int
NameGo string
NameGo_translit string `gorm:-` //имя для golang, русские буквы заменены на английские
@ -59,7 +59,7 @@ var MapRenameFunctions = make(map[string][]ReplaceStruct, 0)
// TableColumns_String - структура строк для загрузки из JSON
type TableColumns_String struct {
TableName string `json:"Table"`
MassColumnNames []string `json:"Columns"`
MassColumnNames []string `json:"Column"`
}
// MassFindBy_String - карта функций которые будут созданы для поиска 1 строки в таблице
@ -74,6 +74,18 @@ type TableColumns struct {
Columns []*Column
}
// TableColumn - структура таблица + колонка
type TableColumn struct {
Table *Table
Column *Column
}
// TableColumn_string - структура таблица + колонка, только строки
type TableColumn_string struct {
TableName string
ColumnName string
}
// MassFindBy - карта функций которые будут созданы для поиска 1 строки в таблице
var MassFindBy = make([]TableColumns, 0)
@ -94,3 +106,6 @@ type SettingsFillFromDatabase struct {
// MapPrimaryKeys - карта первичных ключей, добавленных вручную в файл primary_keys.json
var MapPrimaryKeys = make(map[string][]string, 0)
// MassFindModelBy - массив функций которые будут созданы для поиска 1 строки в связанной таблицы из foreign key, фильтр по колонке
var MassFindModelBy = make([]TableColumn, 0)

View File

@ -67,7 +67,7 @@ func GenerateDeleteSQL(dbTable DbTableMeta) (string, error) {
// GenerateUpdateSQL generate sql for a update
func GenerateUpdateSQL(dbTable DbTableMeta) (string, error) {
primaryCnt := PrimaryKeyCount(dbTable)
// nonPrimaryCnt := len(dbTable.Columns()) - primaryCnt
// nonPrimaryCnt := len(dbTable.Column()) - primaryCnt
if primaryCnt == 0 {
return "", fmt.Errorf("table %s does not have a primary key, cannot generate sql", dbTable.TableName())