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

сделал объединил templates_main и templates

This commit is contained in:
Nikitin Aleksandr 2024-02-09 15:17:57 +03:00
parent 75e717b43c
commit 7f75a67305
46 changed files with 1257 additions and 266 deletions

2
.gitignore vendored
View File

@ -19,3 +19,5 @@
/bin/sync_service_test/
/bin/crud_service/
/bin/templates_main/
/bin/templates/configs_/.env_rapira
/bin/templates/configs_/.env_test

View File

@ -5,7 +5,8 @@ FILEMAIN=./cmd/$(SERVICENAME)/main.go
FILEAPP=./bin/$(SERVICENAME)
NEW_REPO=$(SERVICENAME)
GENERATION_PROTO=cd ./api && ./generation_code.sh
CD_GENERATION_PROTO=cd ./api
GENERATION_PROTO=generation_code.sh
run:
@ -52,8 +53,9 @@ conn:
image_connections ./internal docs/connections.graphml $(SERVICENAME)
init:
clear
rm ./go.mod
rm -f ./go.mod
go mod init gitlab.aescorp.ru/dsp_dev/claim/sync_service
$(CD_GENERATION_PROTO)
$(GENERATION_PROTO)
go mod tidy
go mod vendor

View File

@ -1,3 +1,14 @@
{
"lawsuit_payments.id": "alias.PaymentId",
"lawsuit_payments.invoice_id": "alias.InvoiceId",
"lawsuit_payments.lawsuit_id": "alias.LawsuitId",
"lawsuit_payments.id": "alias.PaymentId",
"invoice_debt_type_stats.invoice_id": "alias.InvoiceId",
"invoice_debt_type_stats.lawsuit_id": "alias.LawsuitId",
"contract_black_items.contract_number": "alias.ContractNumber",
"contract_white_items.contract_number": "alias.ContractNumber",
"lawsuits.number_claim": "alias.ClaimNumber",
"lawsuits.number": "alias.LawsuitNumber",
"contracts.number": "alias.ContractNumber"
}

View File

@ -1,2 +1,8 @@
{
"lawsuits": [
{
"old": "create_update_ctx",
"new": "create_update_ctx_original"
}
]
}

View File

@ -1,2 +1,3 @@
{
"lawsuits": "NewLawsuit,AsLawsuit,create_update_ctx"
}

View File

@ -1,2 +1,19 @@
{
"inn": "INN",
"kpp": "KPP",
"okpo": "OKPO",
"ogrn": "OGRN",
"okato": "OKATO",
"nsi_flat": "NSIFlat",
"nsi_flat_id": "NSIFlatID",
"nsi_id": "NSIID",
"www": "WWW",
"bik": "BIK",
"city_name": "City",
"edms_link": "EDMSLink",
"code_nsi": "CodeNSI",
"json_updated_at": "JSONUpdatedAt",
"pdf_updated_at": "PDFUpdatedAt",
"pdf_file_id": "PDFFileID",
"json_file_id": "JSONFileID"
}

View File

@ -1,2 +1,4 @@
{
"ext_id": true,
"created_at": false
}

View File

@ -21,15 +21,15 @@ DB_PASSWORD=
INCLUDE_TABLES=""
#INCLUDE_TABLES - table name ignore filter. Regular expression
EXCLUDE_TABLES=
EXCLUDE_TABLES="ext_"
#---------------------Template settings---------------------
#SERVICE_REPOSITORY_URL - URL of your new service repository (Github, gitlab, etc.)
SERVICE_REPOSITORY_URL="gitlab.aescorp.ru/dsp_dev/claim/crud_service"
SERVICE_REPOSITORY_URL="gitlab.aescorp.ru/dsp_dev/claim/sync_service"
#SERVICE_NAME - service name for your new service
SERVICE_NAME=crud_service
SERVICE_NAME=sync_service
#TEMPLATE_SERVICE_NAME - service name in your template files
TEMPLATE_SERVICE_NAME=sync_service
@ -99,7 +99,7 @@ TEXT_TEMPLATE_TABLENAME="lawsuit_status_types"
USE_DEFAULT_TEMPLATE=true
#HAS_IS_DELETED - fill "true" if you have "is_deleted" column, and want Delete() Restore() functions.
HAS_IS_DELETED=false
HAS_IS_DELETED=true
#---------------------Create files settings---------------------
@ -157,3 +157,14 @@ COMMENT_MODEL_STRUCT="модель для таблицы "
#TEXT_MODULE_GENERATED - comment text for every module file
TEXT_MODULE_GENERATED="//Файл создан автоматически кодогенератором crud_generator\n//Не изменяйте ничего здесь.\n\n"
#TEMPLATES_ALIAS_FILENAME - short filename of "alias.go_" file
TEMPLATES_ALIAS_FILENAME="alias.go_"
#READY_ALIAS_FILENAME - short filename of "alias.go" file
READY_ALIAS_FILENAME="alias.go"
#TEMPLATES_CRUD_FILENAME - short filename of "crud_tables.go_" file
TEMPLATES_CRUD_FILENAME="crud_tables_rapira.go_"
#TEMPLATES_CRUD_TEST_FILENAME - short filename of "crud_tables_test.go_" file
TEMPLATES_CRUD_TEST_FILENAME="crud_tables_rapira_test.go_"

View File

@ -7,7 +7,6 @@ import (
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_proto"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types"
"testing"
"math"
)
// LawsuitStatusType_ID_Test - ID таблицы для тестирования
@ -38,7 +37,7 @@ func Test_server_LawsuitStatusType_Delete(t *testing.T) {
ctx := context.Background()
Request := grpc_proto.RequestId{}
Request.ID = math.MinInt64
Request.ID = LawsuitStatusType_ID_Test
Request.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion()
server1 := &ServerGRPC{}

View File

@ -0,0 +1,320 @@
package crud_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"
"time"
"github.com/ManyakRus/starter/contextmain"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/crud_functions"
)
// 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
if err != nil {
err = fmt.Errorf("Read() id: %v, error: %v", id, err)
}
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")
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)
return err
}
//
db := postgres_gorm.GetConnection()
db.WithContext(ctx)
// заполним даты
//Text_modified_at
//Text_is_deleted_deleted_at
//Text_created_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 в пустые колонки
MapOmit := crud_functions.MapOmit_from_MassOmit(MassOmit)
tx = db.Model(&m).Updates(MapOmit)
err = tx.Error
if err != nil {
TextError := fmt.Sprint("Updates() ", TableName, " id: ", m.ID, " error: ", err)
err = errors.New(TextError)
return err
}
if err != nil {
err = fmt.Errorf("Create_Update() id: %v, error: %v", m.ID, err)
}
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)
if err != nil {
err = fmt.Errorf("Restore() id: %v, error: %v", m.ID, err)
}
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
if err != nil {
err = fmt.Errorf("Find_ByExtID() id: %v, error: %v", m.ID, err)
}
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 - удаляет запись в БД
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
}
db := postgres_gorm.GetConnection()
db.WithContext(ctx)
tx := db.Delete(m)
err = tx.Error
return err
}

View File

@ -49,7 +49,7 @@ func (crud Crud_DB) Read_ctx(ctx context.Context, m *lawsuit_status_types.Lawsui
tx := db.First(m, id)
err = tx.Error
if err != nil {
err = fmt.Errorf("Read() id: %v, error: %v", m.ID, err)
err = fmt.Errorf("Read() id: %v, error: %v", id, err)
}
return err
@ -196,7 +196,7 @@ func (crud Crud_DB) create_update_ctx(ctx context.Context, m *lawsuit_status_typ
return err
}
if err != nil {
err = fmt.Errorf("Create_update() id: %v, error: %v", m.ID, err)
err = fmt.Errorf("Create_Update() id: %v, error: %v", m.ID, err)
}
return err

View File

@ -95,7 +95,6 @@ func TestDelete(t *testing.T) {
}
func TestFind_ByExtID(t *testing.T) {
config_main.LoadEnv()
postgres_gorm.Connect()

View File

@ -0,0 +1,101 @@
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"
"testing"
)
const Postgres_ID_Test = 1
func TestRead(t *testing.T) {
config_main.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_main.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 = math.MinInt64
err := crud.Delete(&Otvet)
if err != nil {
t.Error("TestDelete() error: ", err)
}
}
func TestFind_ByExtID(t *testing.T) {
config_main.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")
}
}

View File

@ -4,7 +4,6 @@ import (
"github.com/ManyakRus/starter/config_main"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_client"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types"
"math"
"testing"
)
@ -111,12 +110,45 @@ func TestDelete(t *testing.T) {
crud := Crud_GRPC{}
Otvet := lawsuit_status_types.LawsuitStatusType{}
Otvet.ID = math.MinInt64
Otvet.ID = Postgres_ID_Test
err := crud.Read(&Otvet)
if err != nil {
t.Error("TestRead() error: ", err)
}
err := crud.Delete(&Otvet)
if Otvet.IsDeleted == false {
err = crud.Delete(&Otvet)
if err != nil {
t.Error("TestDelete() error: ", err)
}
if Otvet.ID == 0 {
t.Error("TestDelete() error: ID =0")
}
err = crud.Restore(&Otvet)
if err != nil {
t.Error("TestDelete() error: ", err)
}
if Otvet.ID == 0 {
t.Error("TestDelete() error: ID =0")
}
} else {
err = crud.Restore(&Otvet)
if err != nil {
t.Error("TestDelete() error: ", err)
}
if Otvet.ID == 0 {
t.Error("TestDelete() error: ID =0")
}
err = crud.Delete(&Otvet)
if err != nil {
t.Error("TestDelete() error: ", err)
}
if Otvet.ID == 0 {
t.Error("TestDelete() error: ID =0")
}
}
}
func TestFindByExtID(t *testing.T) {

View File

@ -11,8 +11,8 @@ import (
// versionLawsuitStatusType - версия структуры модели, с учётом имен и типов полей
var versionLawsuitStatusType uint32
// crud_LawsuitStatusType - объект контроллер crud операций
var crud_LawsuitStatusType ICrud_LawsuitStatusType
// Crud_LawsuitStatusType - объект контроллер crud операций
var Crud_LawsuitStatusType ICrud_LawsuitStatusType
// интерфейс стандартных CRUD операций, для использования в DB или GRPC или NRPC
type ICrud_LawsuitStatusType interface {
@ -92,84 +92,84 @@ func (m LawsuitStatusType) GetJSON() (string, error) {
// Read - находит запись в БД по ID, и заполняет в объект
func (m *LawsuitStatusType) Read() error {
if crud_LawsuitStatusType == nil {
if Crud_LawsuitStatusType == nil {
return constants.ErrorCrudIsNotInit
}
err := crud_LawsuitStatusType.Read(m)
err := Crud_LawsuitStatusType.Read(m)
return err
}
// Save - записывает объект в БД по ID
func (m *LawsuitStatusType) Save() error {
if crud_LawsuitStatusType == nil {
if Crud_LawsuitStatusType == nil {
return constants.ErrorCrudIsNotInit
}
err := crud_LawsuitStatusType.Save(m)
err := Crud_LawsuitStatusType.Save(m)
return err
}
// Update - обновляет объект в БД по ID
func (m *LawsuitStatusType) Update() error {
if crud_LawsuitStatusType == nil {
if Crud_LawsuitStatusType == nil {
return constants.ErrorCrudIsNotInit
}
err := crud_LawsuitStatusType.Update(m)
err := Crud_LawsuitStatusType.Update(m)
return err
}
// Create - создаёт объект в БД с новым ID
func (m *LawsuitStatusType) Create() error {
if crud_LawsuitStatusType == nil {
if Crud_LawsuitStatusType == nil {
return constants.ErrorCrudIsNotInit
}
err := crud_LawsuitStatusType.Create(m)
err := Crud_LawsuitStatusType.Create(m)
return err
}
// Delete - устанавливает признак пометки удаления в БД
func (m *LawsuitStatusType) Delete() error {
if crud_LawsuitStatusType == nil {
if Crud_LawsuitStatusType == nil {
return constants.ErrorCrudIsNotInit
}
err := crud_LawsuitStatusType.Delete(m)
err := Crud_LawsuitStatusType.Delete(m)
return err
}
// Restore - снимает признак пометки удаления в БД
func (m *LawsuitStatusType) Restore() error {
if crud_LawsuitStatusType == nil {
if Crud_LawsuitStatusType == nil {
return constants.ErrorCrudIsNotInit
}
err := crud_LawsuitStatusType.Restore(m)
err := Crud_LawsuitStatusType.Restore(m)
return err
}
// Find_ByExtID - находит объект по ExtID
func (m *LawsuitStatusType) Find_ByExtID() error {
if crud_LawsuitStatusType == nil {
if Crud_LawsuitStatusType == nil {
return constants.ErrorCrudIsNotInit
}
err := crud_LawsuitStatusType.Find_ByExtID(m)
err := Crud_LawsuitStatusType.Find_ByExtID(m)
return err
}
// SetCrudInterface - заполняет интерфейс crud: DB, GRPC, NRPC
func (m LawsuitStatusType) SetCrudInterface(crud ICrud_LawsuitStatusType) {
crud_LawsuitStatusType = crud
Crud_LawsuitStatusType = crud
return
}

View File

@ -0,0 +1,15 @@
package lawsuit_status_types
// Crud_manual_LawsuitStatusType - объект контроллер crud операций
var Crud_manual_LawsuitStatusType ICrud_manual_LawsuitStatusType
// интерфейс CRUD операций сделанных вручную, для использования в DB или GRPC или NRPC
type ICrud_manual_LawsuitStatusType interface {
}
// SetCrudManualInterface - заполняет интерфейс crud: DB, GRPC, NRPC
func (m LawsuitStatusType) SetCrudManualInterface(crud ICrud_manual_LawsuitStatusType) {
Crud_manual_LawsuitStatusType = crud
return
}

View File

@ -0,0 +1,3 @@
// Package alias -- special types
package alias

View File

@ -52,6 +52,7 @@ conn:
image_connections ./internal docs/connections.graphml $(SERVICENAME)
init:
clear
rm ./go.mod
go mod init gitlab.aescorp.ru/dsp_dev/claim/sync_service
$(GENERATION_PROTO)
go mod tidy

View File

@ -11,120 +11,12 @@ option go_package = "./grpc_proto";
// sync_service - сервис обмена с Базой данных
service Sync_service {
//
rpc Organization_Read(RequestId) returns (Response) {}
rpc Organization_Create(RequestModel) returns (Response) {}
rpc Organization_Update(RequestModel) returns (Response) {}
rpc Organization_Save(RequestModel) returns (Response) {}
rpc Organization_Delete(RequestId) returns (Response) {}
rpc Organization_Restore(RequestId) returns (Response) {}
rpc Organization_FindByInnKpp(RequestInnKpp) returns (Response) {}
rpc Organization_FindByExtId(RequestExtId) returns (Response) {}
//
rpc File_Read(RequestId) returns (Response) {}
rpc File_Create(RequestModel) returns (Response) {}
rpc File_Update(RequestModel) returns (Response) {}
rpc File_Save(RequestModel) returns (Response) {}
rpc File_Delete(RequestId) returns (Response) {}
rpc File_Restore(RequestId) returns (Response) {}
rpc File_FindByFileID(RequestString) returns (Response) {}
rpc File_FindByFullName(RequestString) returns (Response) {}
//
rpc OrganizationCasebook_Read(RequestId) returns (Response) {}
rpc OrganizationCasebook_Create(RequestModel) returns (Response) {}
rpc OrganizationCasebook_Update(RequestModel) returns (Response) {}
rpc OrganizationCasebook_Save(RequestModel) returns (Response) {}
rpc OrganizationCasebook_Delete(RequestId) returns (Response) {}
rpc OrganizationCasebook_Restore(RequestId) returns (Response) {}
rpc OrganizationCasebook_FindByInnKpp(RequestInnKpp) returns (Response) {}
rpc OrganizationCasebook_FindByInn(RequestString) returns (Response) {}
rpc OrganizationCasebook_FindByOrganizationId(RequestId) returns (Response) {}
//
rpc Connection_Read(RequestId) returns (Response) {}
rpc Connection_Create(RequestModel) returns (Response) {}
rpc Connection_Update(RequestModel) returns (Response) {}
rpc Connection_Save(RequestModel) returns (Response) {}
//
rpc Employee_Read(RequestId) returns (Response) {}
rpc Employee_Create(RequestModel) returns (Response) {}
rpc Employee_Update(RequestModel) returns (Response) {}
rpc Employee_Save(RequestModel) returns (Response) {}
rpc Employee_Delete(RequestId) returns (Response) {}
rpc Employee_Restore(RequestId) returns (Response) {}
rpc Employee_FindByExtId(RequestExtId) returns (Response) {}
rpc Employee_FindByLogin(RequestString) returns (Response) {}
rpc Employee_FindByEMail(RequestString) returns (Response) {}
rpc Employee_FindByFIO(RequestString3) returns (Response) {}
//
rpc LawsuitStatusState_Read(RequestId) returns (Response) {}
rpc LawsuitStatusState_Create(RequestModel) returns (Response) {}
rpc LawsuitStatusState_Update(RequestModel) returns (Response) {}
rpc LawsuitStatusState_Save(RequestModel) returns (Response) {}
rpc LawsuitStatusState_Delete(RequestId) returns (Response) {}
rpc LawsuitStatusState_Restore(RequestId) returns (Response) {}
rpc LawsuitStatusState_FillFromLawsuit(RequestIdId) returns (ResponseEmpty) {}
rpc LawsuitStatusState_FindDebtSum(RequestIdId) returns (ResponseFloat64) {}
//
rpc LawsuitStatusType_Read(RequestId) returns (Response) {}
rpc LawsuitStatusType_Create(RequestModel) returns (Response) {}
rpc LawsuitStatusType_Update(RequestModel) returns (Response) {}
rpc LawsuitStatusType_Save(RequestModel) returns (Response) {}
rpc LawsuitStatusType_Delete(RequestId) returns (Response) {}
rpc LawsuitStatusType_Restore(RequestId) returns (Response) {}
//
rpc Lawsuit_Read(RequestId) returns (Response) {}
rpc Lawsuit_Create(RequestModel) returns (Response) {}
rpc Lawsuit_Update(RequestModel) returns (Response) {}
rpc Lawsuit_Save(RequestModel) returns (Response) {}
rpc Lawsuit_Delete(RequestId) returns (Response) {}
rpc Lawsuit_Restore(RequestId) returns (Response) {}
//
rpc MessageAttachement_Read(RequestId) returns (Response) {}
rpc MessageAttachement_Create(RequestModel) returns (Response) {}
rpc MessageAttachement_Update(RequestModel) returns (Response) {}
rpc MessageAttachement_Save(RequestModel) returns (Response) {}
rpc MessageAttachement_Delete(RequestId) returns (Response) {}
rpc MessageAttachement_Restore(RequestId) returns (Response) {}
//
rpc MessageSendStatuse_Read(RequestId) returns (Response) {}
rpc MessageSendStatuse_Create(RequestModel) returns (Response) {}
rpc MessageSendStatuse_Update(RequestModel) returns (Response) {}
rpc MessageSendStatuse_Save(RequestModel) returns (Response) {}
rpc MessageSendStatuse_Delete(RequestId) returns (Response) {}
rpc MessageSendStatuse_Restore(RequestId) returns (Response) {}
//
rpc MessageType_Read(RequestId) returns (Response) {}
rpc MessageType_Create(RequestModel) returns (Response) {}
rpc MessageType_Update(RequestModel) returns (Response) {}
rpc MessageType_Save(RequestModel) returns (Response) {}
rpc MessageType_Delete(RequestId) returns (Response) {}
rpc MessageType_Restore(RequestId) returns (Response) {}
//
rpc Message_Read(RequestId) returns (Response) {}
rpc Message_Create(RequestModel) returns (Response) {}
rpc Message_Update(RequestModel) returns (Response) {}
rpc Message_Save(RequestModel) returns (Response) {}
rpc Message_Delete(RequestId) returns (Response) {}
rpc Message_Restore(RequestId) returns (Response) {}
rpc Message_FindBy_LawsuitID_MessageTypeID(RequestIdId) returns (Response) {}
}
// RequestId - параметры запроса на сервер
message RequestId {
uint32 VersionModel= 1; //версия структуры модели
int64 id = 2; // id записи в БД
int64 ID = 2; // id записи в БД
}
// RequestString - параметры запроса на сервер
@ -142,9 +34,9 @@ message RequestString3 {
}
// RequestId - параметры запроса на сервер
message RequestExtId {
message RequestExtID {
uint32 VersionModel= 1; //версия структуры модели
int64 Ext_id = 2; // ext_id записи в БД
int64 ExtID = 2; // ext_id записи в БД
int64 Connection_id =3; // Connection_id записи в БД
}
@ -164,8 +56,8 @@ message RequestInnKpp {
// RequestId - параметры запроса на сервер
message RequestIdId {
uint32 VersionModel= 1; //версия структуры модели
int64 id1 = 2; // id записи в БД
int64 id2 = 3; // id записи в БД
int64 ID1 = 2; // id записи в БД
int64 ID2 = 3; // id записи в БД
}

View File

@ -77,6 +77,9 @@ TEMPLATE_FOLDERNAME_NRPC="pkg/network/nrpc"
#TEMPLATE_FOLDERNAME_NRPC_CLIENT - foldr name for create nrpc client files
TEMPLATE_FOLDERNAME_NRPC_CLIENT="pkg/network/nrpc/nrpc_client"
#TEMPLATE_FOLDERNAME_GRPC_NRPC - folder name for create grpc_nrpc.go file
TEMPLATE_FOLDERNAME_GRPC_NRPC="pkg/network/grpc_nrpc"
#TEMPLATE_FOLDERNAME_CRUD_STARTER - folder name for create crud_starter.go file
TEMPLATE_FOLDERNAME_CRUD_STARTER="pkg/crud_starter"
@ -133,6 +136,9 @@ NEED_CREATE_NRPC_SERVER_TEST=true
#NEED_CREATE_NRPC_CLIENT_TEST - fill "true" if you want create NRPC client _test.go files
NEED_CREATE_NRPC_CLIENT_TEST=true
#NEED_CREATE_MANUAL_FILES - fill "true" if you want create "_manual.go" files, intended for user manual changes
NEED_CREATE_MANUAL_FILES=true
#PREFIX_SERVER_GRPC - filename prefix for grpc server files
PREFIX_SERVER_GRPC="server_grpc_"

View File

@ -245,7 +245,7 @@ func (s *ServerGRPC) LawsuitStatusType_Save(ctx context.Context, Request *grpc_p
}
// LawsuitStatusType_FindByExtID - возвращает запись из БД по ext_id и connection_id
func (s *ServerGRPC) LawsuitStatusType_FindByExtID(ctx context.Context, Request *grpc_proto.RequestExtId) (*grpc_proto.Response, error) {
func (s *ServerGRPC) LawsuitStatusType_FindByExtID(ctx context.Context, Request *grpc_proto.RequestExtID) (*grpc_proto.Response, error) {
var Otvet grpc_proto.Response
var err error
@ -265,7 +265,7 @@ func (s *ServerGRPC) LawsuitStatusType_FindByExtID(ctx context.Context, Request
//запрос в БД
Model := &lawsuit_status_types.LawsuitStatusType{}
Model.ExtID = Request.ExtId
Model.ExtID = Request.ExtID
Model.ConnectionID = Request.ConnectionId
err = Model.Find_ByExtID()
if err != nil {

View File

@ -178,16 +178,16 @@ func Test_server_LawsuitStatusType_FindByExtID(t *testing.T) {
ctx = context.Background()
RequestExtId:= grpc_proto.RequestExtId{}
RequestExtId.ExtId = Model.ExtID
RequestExtId.ConnectionId = Model.ConnectionID
RequestExtId.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion()
RequestExtID:= grpc_proto.RequestExtID{}
RequestExtID.ExtID = Model.ExtID
RequestExtID.ConnectionId = Model.ConnectionID
RequestExtID.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion()
Otvet, err := server1.LawsuitStatusType_FindByExtID(ctx, &RequestExtId)
Otvet, err := server1.LawsuitStatusType_FindByExtID(ctx, &RequestExtID)
if err != nil {
t.Error("Test_server_LawsuitStatusType_FindByExtId() error: ", err)
t.Error("Test_server_LawsuitStatusType_FindByExtID() error: ", err)
}
if Otvet.ModelString == "" {
t.Error("Test_server_LawsuitStatusType_FindByExtId() error: ModelString=''")
t.Error("Test_server_LawsuitStatusType_FindByExtID() error: ModelString=''")
}
}

View File

@ -0,0 +1,12 @@
package crud_starter_lawsuit_status_types
import (
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types"
)
// SetCrudInterface - заполняет интерфейс crud: DB, GRPC, NRPC
func SetCrudInterface(crud lawsuit_status_types.ICrud_LawsuitStatusType) {
lawsuit_status_types.Crud_LawsuitStatusType = crud
return
}

View File

@ -0,0 +1,12 @@
package crud_starter_lawsuit_status_types
import (
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types"
)
// SetCrudManualInterface - заполняет интерфейс crud: DB, GRPC, NRPC
func SetCrudManualInterface(crud lawsuit_status_types.ICrud_manual_LawsuitStatusType) {
lawsuit_status_types.Crud_manual_LawsuitStatusType = crud
return
}

View File

@ -0,0 +1,19 @@
package crud_starter_lawsuit_status_types
import (
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/crud/crud_starter_lawsuit_status_types"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types"
"testing"
)
func TestSetCrudManualInterface(t *testing.T) {
crud := crud_lawsuit_status_types.Crud_DB{}
SetCrudManualInterface(crud)
// Test that the crud variable is set correctly
if employees.Crud_manual_LawsuitStatusType != crud {
t.Errorf("Expected lawsuit_status_types.Crud_manual_LawsuitStatusType to be set to crud, but got %+v", lawsuit_status_types.Crud_manual_LawsuitStatusType)
}
}

View File

@ -0,0 +1,12 @@
package starter_crud_starter_lawsuit_status_types
import (
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/crud/crud_lawsuit_status_types"
"testing"
)
func TestSetCrudInterface(t *testing.T) {
crud := crud_lawsuit_status_types.Crud_DB{}
SetCrudInterface(crud)
}

View File

@ -48,6 +48,9 @@ func (crud Crud_DB) Read_ctx(ctx context.Context, m *lawsuit_status_types.Lawsui
tx := db.First(m, id)
err = tx.Error
if err != nil {
err = fmt.Errorf("Read() id: %v, error: %v", m.ID, err)
}
return err
}
@ -192,6 +195,9 @@ func (crud Crud_DB) create_update_ctx(ctx context.Context, m *lawsuit_status_typ
err = errors.New(TextError)
return err
}
if err != nil {
err = fmt.Errorf("Create_update() id: %v, error: %v", m.ID, err)
}
return err
}
@ -228,6 +234,9 @@ func (crud Crud_DB) Delete_ctx(ctx context.Context, m *lawsuit_status_types.Laws
m.IsDeleted = true
err = crud.Save_ctx(ctx, &m2)
if err != nil {
err = fmt.Errorf("Delete() id: %v, error: %v", m.ID, err)
}
return err
}
@ -264,6 +273,9 @@ func (crud Crud_DB) Restore_ctx(ctx context.Context, m *lawsuit_status_types.Law
m.IsDeleted = false
err = crud.Save_ctx(ctx, &m2)
if err != nil {
err = fmt.Errorf("Restore() id: %v, error: %v", m.ID, err)
}
return err
}
@ -306,6 +318,9 @@ func (crud Crud_DB) Find_ByExtID_ctx(ctx context.Context, m *lawsuit_status_type
tx := db.Where("ext_id = ?", m.ExtID).Where("connection_id = ?", m.ConnectionID).First(m)
err = tx.Error
if err != nil {
err = fmt.Errorf("Find_ByExtID() id: %v, error: %v", m.ID, err)
}
return err
}

View File

@ -1,5 +0,0 @@
package constants
var TIMEOUT_SECONDS = 30
const TEXT_ERROR_MODEL_VERSION = "Error: wrong version object model"

View File

@ -1,57 +1,110 @@
package grpc_client
import (
"context"
"errors"
"github.com/ManyakRus/starter/contextmain"
"github.com/ManyakRus/starter/log"
"github.com/ManyakRus/starter/port_checker"
"github.com/ManyakRus/starter/stopapp"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/api/grpc_proto"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/constants"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_proto"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_constants"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/nrpc/nrpc_client"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"os"
"strings"
"sync"
"time"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc_nrpc"
)
// SettingsINI - тип структуры для хранения настроек подключени
type SettingsINI struct {
SYNC_SERVICE_HOST string
SYNC_SERVICE_PORT string
}
// SettingsINI - структура для хранения настроек подключени
var Settings SettingsINI
// Conn - подключение к серверу GRPC
var Conn *grpc.ClientConn
// Client - подключение к клиенту GRPC
var Client grpc_proto.SyncServiceClient
// mutex_Connect - защита от многопоточности Reconnect()
var mutex_Connect = &sync.Mutex{}
// NeedReconnect - флаг необходимости переподключения
var NeedReconnect bool
// Connect - подключается к серверу GRPC, при ошибке вызывает панику
func Connect() {
var err error
err = Connect_err()
if err != nil {
log.Panicf("GRPC Connect() error: %v", err)
} else {
addr := Settings.SYNC_SERVICE_HOST + ":" + Settings.SYNC_SERVICE_PORT
log.Info("GRPC client connected. Address: ", addr)
}
}
// Connect_err - подключается к серверу GRPC, возвращает ошибку
func Connect_err() error {
var err error
//
mutex_Connect.Lock()
defer mutex_Connect.Unlock()
//
if Settings.SYNC_SERVICE_HOST == "" {
FillSettings()
err = FillSettings()
if err != nil {
return err
}
}
addr := Settings.SYNC_SERVICE_HOST + ":" + Settings.SYNC_SERVICE_PORT
Conn, err = grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf("did not connect: %v", err)
return err
}
log.Info("GRPC client connected. Address: ", addr)
Client = grpc_proto.NewSyncServiceClient(Conn)
grpc_nrpc.NeedNRPC = false
return err
}
func FillSettings() {
func FillSettings() error {
var err error
Settings = SettingsINI{}
Settings.SYNC_SERVICE_HOST = os.Getenv("SYNC_SERVICE_HOST")
Settings.SYNC_SERVICE_PORT = os.Getenv("SYNC_SERVICE_PORT")
if Settings.SYNC_SERVICE_HOST == "" {
log.Panic("Need fill SYNC_SERVICE_HOST ! in OS Environment ")
TextError := "Need fill SYNC_SERVICE_HOST ! in OS Environment "
err = errors.New(TextError)
return err
}
if Settings.SYNC_SERVICE_PORT == "" {
log.Panic("Need fill SYNC_SERVICE_PORT ! in OS Environment ")
TextError := "Need fill SYNC_SERVICE_PORT ! in OS Environment "
err = errors.New(TextError)
return err
}
return err
}
// WaitStop - ожидает отмену глобального контекста
@ -71,23 +124,58 @@ func WaitStop() {
}
// Start - необходимые процедуры для запуска сервера GRPC
// если контекст хранится в contextmain.GetContext()
// и есть stopapp.GetWaitGroup_Main()
// при ошибке вызывает панику
func Start() {
Connect()
stopapp.GetWaitGroup_Main().Add(1)
go WaitStop()
stopapp.GetWaitGroup_Main().Add(1)
go ping_go()
}
func CloseConnection() {
err := Conn.Close()
// Start_ctx - необходимые процедуры для запуска сервера GRPC
// ctx - глобальный контекст приложения
// wg - глобальный WaitGroup приложения
func Start_ctx(ctx *context.Context, wg *sync.WaitGroup) error {
var err error
contextmain.Ctx = ctx
stopapp.SetWaitGroup_Main(wg)
err = Connect_err()
if err != nil {
log.Panic("GRPC client CloseConnection() error: ", err)
return err
}
stopapp.GetWaitGroup_Main().Add(1)
go WaitStop()
stopapp.GetWaitGroup_Main().Add(1)
go ping_go()
return err
}
// CloseConnection - закрывает подключение к GRPC, и пишет лог
func CloseConnection() {
err := CloseConnection_err()
if err != nil {
log.Error("GRPC client CloseConnection() error: ", err)
} else {
log.Info("GRPC client connection closed")
}
}
// CloseConnection - закрывает подключение к GRPC, и возвращает ошибку
func CloseConnection_err() error {
err := Conn.Close()
return err
}
// IsRecordNotFound - возвращает true если ошибка = "record not found"
func IsRecordNotFound(err error) bool {
Otvet := false
@ -104,3 +192,64 @@ func IsRecordNotFound(err error) bool {
return Otvet
}
// ping_go - делает пинг каждые 60 секунд, и реконнект
func ping_go() {
ticker := time.NewTicker(60 * time.Second)
defer ticker.Stop()
addr := Settings.SYNC_SERVICE_HOST + ":" + Settings.SYNC_SERVICE_PORT
//бесконечный цикл
loop:
for {
select {
case <-contextmain.GetContext().Done():
log.Warn("Context app is canceled. grpc_client.ping")
break loop
case <-ticker.C:
err := port_checker.CheckPort_err(Settings.SYNC_SERVICE_HOST, Settings.SYNC_SERVICE_PORT)
//log.Debug("ticker, ping err: ", err) //удалить
if err != nil {
NeedReconnect = true
log.Warn("grpc_client CheckPort(", addr, ") error: ", err)
} else if NeedReconnect == true {
log.Warn("grpc_client CheckPort(", addr, ") OK. Start Reconnect()")
NeedReconnect = false
err = Connect_err()
if err != nil {
NeedReconnect = true
log.Error("grpc_client Connect() error: ", err)
}
}
}
}
stopapp.GetWaitGroup_Main().Done()
}
// GetTimeoutSeconds - возвращает время ожидания ответа
func GetTimeoutSeconds() int {
Otvet := grpc_constants.GetTimeoutSeconds()
return Otvet
}
// SetTimeoutSeconds - устанавливает время ожидания ответа
func SetTimeoutSeconds(seconds int) {
grpc_constants.SetTimeoutSeconds(seconds)
}
// Connect_GRPC_NRPC - подключается к серверу GRPC или NRPC, при ошибке вызывает панику
func Connect_GRPC_NRPC() {
if grpc_nrpc.NeedNRPC == true {
if nrpc_client.Client == nil {
nrpc_client.Connect()
}
} else {
if Client == nil {
Connect()
}
}
}

View File

@ -1,13 +1,20 @@
//Файл создан автоматически кодогенератором crud_generator
//Не изменяйте ничего здесь.
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_constants"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/constants"
"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/constants"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_proto"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/nrpc/nrpc_client"
"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_nrpc"
"log"
"sync"
"time"
)
@ -17,12 +24,18 @@ var VersionModel uint32
// TableName - имя таблицы в БД Postgres
const TableName string = "lawsuit_status_types"
// mutex_GetVersionModel - защита от многопоточности GetVersionModel()
var mutex_GetVersionModel = sync.Mutex{}
// объект для CRUD операций через GRPC
type Crud_GRPC struct {
}
// GetVersionModel - возвращает хэш версии структуры модели
func (crud Crud_GRPC) GetVersionModel() uint32 {
mutex_GetVersionModel.Lock()
defer mutex_GetVersionModel.Unlock()
if VersionModel == 0 {
VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion()
}
@ -31,29 +44,32 @@ func (crud Crud_GRPC) GetVersionModel() uint32 {
// Read - возвращает модель из БД
func (crud Crud_GRPC) Read(m *lawsuit_status_types.LawsuitStatusType) error {
// var Otvet lawsuit_status_types.LawsuitStatusType
var err error
// подключение
if grpc_client.Client == nil {
grpc_client.Connect()
}
grpc_client.Connect_GRPC_NRPC()
// подготовка запроса
var VersionModel = crud.GetVersionModel()
var versionModel = crud.GetVersionModel()
Request := &grpc_proto.RequestId{}
Request.ID = int64(m.ID)
Request.VersionModel = VersionModel
Request.VersionModel = versionModel
ctxMain := context.Background()
ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_SECONDS))
ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(grpc_constants.GetTimeoutSeconds()))
defer ctxCancelFunc()
// запрос
Response, err := grpc_client.Client.LawsuitStatusType_Read(ctx, Request)
var Response *grpc_proto.Response
if grpc_nrpc.NeedNRPC == true {
Response, err = nrpc_client.Client.LawsuitStatusType_Read(Request)
} else {
Response, err = grpc_client.Client.LawsuitStatusType_Read(ctx, Request)
}
if err != nil {
sError := err.Error()
if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION {
if len(sError) >= len(grpc_constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(grpc_constants.TEXT_ERROR_MODEL_VERSION)] == grpc_constants.TEXT_ERROR_MODEL_VERSION {
log.Panic("table: ", TableName, " error: ", err)
}
return err
@ -71,12 +87,10 @@ func (crud Crud_GRPC) Read(m *lawsuit_status_types.LawsuitStatusType) error {
// Create - записывает новую модель в БД
func (crud Crud_GRPC) Create(m *lawsuit_status_types.LawsuitStatusType) error {
// var Otvet lawsuit_status_types.LawsuitStatusType
var err error
// подключение
if grpc_client.Client == nil {
grpc_client.Connect()
}
grpc_client.Connect_GRPC_NRPC()
// подготовка запроса
var VersionModel = crud.GetVersionModel()
@ -90,14 +104,19 @@ func (crud Crud_GRPC) Create(m *lawsuit_status_types.LawsuitStatusType) error {
Request.VersionModel = VersionModel
ctxMain := context.Background()
ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_SECONDS))
ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(grpc_constants.GetTimeoutSeconds()))
defer ctxCancelFunc()
// запрос
Response, err := grpc_client.Client.LawsuitStatusType_Create(ctx, Request)
var Response *grpc_proto.Response
if grpc_nrpc.NeedNRPC == true {
Response, err = nrpc_client.Client.LawsuitStatusType_Create(Request)
} else {
Response, err = grpc_client.Client.LawsuitStatusType_Create(ctx, Request)
}
if err != nil {
sError := err.Error()
if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION {
if len(sError) >= len(grpc_constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(grpc_constants.TEXT_ERROR_MODEL_VERSION)] == grpc_constants.TEXT_ERROR_MODEL_VERSION {
log.Panic("table: ", TableName, " error: ", err)
}
return err
@ -115,12 +134,10 @@ func (crud Crud_GRPC) Create(m *lawsuit_status_types.LawsuitStatusType) error {
// Update - обновляет модель в БД
func (crud Crud_GRPC) Update(m *lawsuit_status_types.LawsuitStatusType) error {
// var Otvet lawsuit_status_types.LawsuitStatusType
var err error
// подключение
if grpc_client.Client == nil {
grpc_client.Connect()
}
grpc_client.Connect_GRPC_NRPC()
// подготовка запроса
var VersionModel = crud.GetVersionModel()
@ -134,14 +151,19 @@ func (crud Crud_GRPC) Update(m *lawsuit_status_types.LawsuitStatusType) error {
Request.VersionModel = VersionModel
ctxMain := context.Background()
ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_SECONDS))
ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(grpc_constants.GetTimeoutSeconds()))
defer ctxCancelFunc()
// запрос
Response, err := grpc_client.Client.LawsuitStatusType_Update(ctx, Request)
var Response *grpc_proto.Response
if grpc_nrpc.NeedNRPC == true {
Response, err = nrpc_client.Client.LawsuitStatusType_Update(Request)
} else {
Response, err = grpc_client.Client.LawsuitStatusType_Update(ctx, Request)
}
if err != nil {
sError := err.Error()
if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION {
if len(sError) >= len(grpc_constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(grpc_constants.TEXT_ERROR_MODEL_VERSION)] == grpc_constants.TEXT_ERROR_MODEL_VERSION {
log.Panic("table: ", TableName, " error: ", err)
}
return err
@ -159,12 +181,10 @@ func (crud Crud_GRPC) Update(m *lawsuit_status_types.LawsuitStatusType) error {
// Save - обновляет (или создаёт) модель в БД
func (crud Crud_GRPC) Save(m *lawsuit_status_types.LawsuitStatusType) error {
// var Otvet lawsuit_status_types.LawsuitStatusType
var err error
// подключение
if grpc_client.Client == nil {
grpc_client.Connect()
}
grpc_client.Connect_GRPC_NRPC()
// подготовка запроса
var VersionModel = crud.GetVersionModel()
@ -178,14 +198,19 @@ func (crud Crud_GRPC) Save(m *lawsuit_status_types.LawsuitStatusType) error {
Request.VersionModel = VersionModel
ctxMain := context.Background()
ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_SECONDS))
ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(grpc_constants.GetTimeoutSeconds()))
defer ctxCancelFunc()
// запрос
Response, err := grpc_client.Client.LawsuitStatusType_Save(ctx, Request)
var Response *grpc_proto.Response
if grpc_nrpc.NeedNRPC == true {
Response, err = nrpc_client.Client.LawsuitStatusType_Save(Request)
} else {
Response, err = grpc_client.Client.LawsuitStatusType_Save(ctx, Request)
}
if err != nil {
sError := err.Error()
if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION {
if len(sError) >= len(grpc_constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(grpc_constants.TEXT_ERROR_MODEL_VERSION)] == grpc_constants.TEXT_ERROR_MODEL_VERSION {
log.Panic("table: ", TableName, " error: ", err)
}
return err
@ -203,12 +228,10 @@ func (crud Crud_GRPC) Save(m *lawsuit_status_types.LawsuitStatusType) error {
// Delete - устанавливает is_deleted = true в БД
func (crud Crud_GRPC) Delete(m *lawsuit_status_types.LawsuitStatusType) error {
// var Otvet lawsuit_status_types.LawsuitStatusType
var err error
// подключение
if grpc_client.Client == nil {
grpc_client.Connect()
}
grpc_client.Connect_GRPC_NRPC()
// подготовка запроса
var VersionModel = crud.GetVersionModel()
@ -218,14 +241,19 @@ func (crud Crud_GRPC) Delete(m *lawsuit_status_types.LawsuitStatusType) error {
Request.VersionModel = VersionModel
ctxMain := context.Background()
ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_SECONDS))
ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(grpc_constants.GetTimeoutSeconds()))
defer ctxCancelFunc()
// запрос
Response, err := grpc_client.Client.LawsuitStatusType_Delete(ctx, Request)
var Response *grpc_proto.Response
if grpc_nrpc.NeedNRPC == true {
Response, err = nrpc_client.Client.LawsuitStatusType_Delete(Request)
} else {
Response, err = grpc_client.Client.LawsuitStatusType_Delete(ctx, Request)
}
if err != nil {
sError := err.Error()
if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION {
if len(sError) >= len(grpc_constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(grpc_constants.TEXT_ERROR_MODEL_VERSION)] == grpc_constants.TEXT_ERROR_MODEL_VERSION {
log.Panic("table: ", TableName, " error: ", err)
}
return err
@ -243,12 +271,10 @@ func (crud Crud_GRPC) Delete(m *lawsuit_status_types.LawsuitStatusType) error {
// Restore - устанавливает is_deleted = false в БД
func (crud Crud_GRPC) Restore(m *lawsuit_status_types.LawsuitStatusType) error {
// var Otvet lawsuit_status_types.LawsuitStatusType
var err error
// подключение
if grpc_client.Client == nil {
grpc_client.Connect()
}
grpc_client.Connect_GRPC_NRPC()
// подготовка запроса
var VersionModel = crud.GetVersionModel()
@ -258,14 +284,19 @@ func (crud Crud_GRPC) Restore(m *lawsuit_status_types.LawsuitStatusType) error {
Request.VersionModel = VersionModel
ctxMain := context.Background()
ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_SECONDS))
ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(grpc_constants.GetTimeoutSeconds()))
defer ctxCancelFunc()
// запрос
Response, err := grpc_client.Client.LawsuitStatusType_Restore(ctx, Request)
var Response *grpc_proto.Response
if grpc_nrpc.NeedNRPC == true {
Response, err = nrpc_client.Client.LawsuitStatusType_Restore(Request)
} else {
Response, err = grpc_client.Client.LawsuitStatusType_Restore(ctx, Request)
}
if err != nil {
sError := err.Error()
if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION {
if len(sError) >= len(grpc_constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(grpc_constants.TEXT_ERROR_MODEL_VERSION)] == grpc_constants.TEXT_ERROR_MODEL_VERSION {
log.Panic("table: ", TableName, " error: ", err)
}
return err
@ -283,28 +314,33 @@ func (crud Crud_GRPC) Restore(m *lawsuit_status_types.LawsuitStatusType) error {
// Find_ByExtID - находит модель в БД по ext_id и connection_id
func (crud Crud_GRPC) Find_ByExtID(m *lawsuit_status_types.LawsuitStatusType) error {
var err error
// подключение
if grpc_client.Client == nil {
grpc_client.Connect()
}
grpc_client.Connect_GRPC_NRPC()
//подготовка запроса
var VersionModel = crud.GetVersionModel()
Request := &grpc_proto.RequestExtId{}
Request.ExtId = m.ExtID
Request := &grpc_proto.RequestExtID{}
Request.ExtID = m.ExtID
Request.ConnectionId = m.ConnectionID
Request.VersionModel = VersionModel
ctxMain := context.Background()
ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_SECONDS))
ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(grpc_constants.GetTimeoutSeconds()))
defer ctxCancelFunc()
//запрос
Response, err := grpc_client.Client.LawsuitStatusType_FindByExtID(ctx, Request)
var Response *grpc_proto.Response
if grpc_nrpc.NeedNRPC == true {
Response, err = nrpc_client.Client.LawsuitStatusType_FindByExtID(Request)
} else {
Response, err = grpc_client.Client.LawsuitStatusType_FindByExtID(ctx, Request)
}
if err != nil {
sError := err.Error()
if sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION {
if sError[0:len(grpc_constants.TEXT_ERROR_MODEL_VERSION)] == grpc_constants.TEXT_ERROR_MODEL_VERSION {
log.Panic("table: ", TableName, " error: ", err)
}
return err

View File

@ -1,7 +1,7 @@
package grpc_lawsuit_status_types
import (
config "github.com/ManyakRus/starter/config_main"
"github.com/ManyakRus/starter/config_main"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_client"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types"
"math"

View File

@ -0,0 +1,28 @@
package grpc_constants
import "sync"
// timeout_seconds - время ожидания ответа
var timeout_seconds int = 30
// TEXT_ERROR_MODEL_VERSION - текст ошибки версии модели
const TEXT_ERROR_MODEL_VERSION = "Error: wrong version object model"
// mutex_TIMEOUT_SECONDS - защита от многопоточности GetTimeoutSeconds()
var mutex_TIMEOUT_SECONDS sync.RWMutex
// GetTimeoutSeconds - возвращает время ожидания ответа
func GetTimeoutSeconds() int {
mutex_TIMEOUT_SECONDS.RLock()
defer mutex_TIMEOUT_SECONDS.RUnlock()
return timeout_seconds
}
// SetTimeoutSeconds - устанавливает время ожидания ответа
func SetTimeoutSeconds(seconds int) {
mutex_TIMEOUT_SECONDS.Lock()
defer mutex_TIMEOUT_SECONDS.Unlock()
timeout_seconds = seconds
}

View File

@ -0,0 +1,4 @@
package grpc_nrpc
// NeedNRPC - нужно ли использовать NRPC или GRPC
var NeedNRPC bool

View File

@ -1,23 +1,36 @@
//Файл создан автоматически кодогенератором crud_generator
//Не изменяйте ничего здесь.
//Файл создан автоматически кодогенератором crud_generator
//Не изменяйте ничего здесь.
package nrpc_client
import (
"context"
"errors"
"github.com/ManyakRus/starter/contextmain"
"github.com/ManyakRus/starter/log"
"github.com/ManyakRus/starter/port_checker"
"github.com/ManyakRus/starter/stopapp"
"github.com/nats-io/nats.go"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/api/grpc_proto"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/constants"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_proto"
nrpc_constants "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/nrpc/constants"
"sync"
"os"
"strings"
"time"
)
// SettingsINI - тип структуры для хранения настроек подключени
type SettingsINI struct {
NATS_HOST string
NATS_PORT string
}
// SettingsINI - структура для хранения настроек подключени
var Settings SettingsINI
// Conn - подключение к NATS
@ -26,30 +39,57 @@ var Conn *nats.Conn
// Client - подключение к клиенту NRPC
var Client *grpc_proto.Sync_serviceClient
// Connect - подключается к NATS
// mutex_Connect - защита от многопоточности Reconnect()
var mutex_Connect = &sync.Mutex{}
// NeedReconnect - флаг необходимости переподключения
var NeedReconnect bool
// Connect - подключается к серверу NRPC, при ошибке вызывает панику
func Connect() {
var err error
err = Connect_err()
if err != nil {
log.Panicf("NRPC Connect() error: %v", err)
} else {
NatsURL := "nats://" + Settings.NATS_HOST + ":" + Settings.NATS_PORT
log.Info("GRPC client connected. Address: ", NatsURL)
}
}
// Connect_err - подключается к серверу NRPC, возвращает ошибку
func Connect_err() error {
var err error
//
mutex_Connect.Lock()
defer mutex_Connect.Unlock()
if Settings.NATS_HOST == "" {
FillSettings()
}
NatsURL := "nats://" + Settings.NATS_HOST + ":" + Settings.NATS_PORT
// Connect to the NATS server.
Conn, err = nats.Connect(NatsURL, nats.Timeout(5*time.Second))
if err != nil {
log.Panic(err)
return err
}
// defer Conn.Close()
// This is our generated client.
Client = grpc_proto.NewSync_serviceClient(Conn)
log.Info("Client NRPC connected: ", NatsURL)
return err
}
// FillSettings - заполняет настройки из переменных окружения
func FillSettings() {
func FillSettings() error {
var err error
Settings = SettingsINI{}
Settings.NATS_HOST = os.Getenv("NATS_HOST")
Settings.NATS_PORT = os.Getenv("NATS_PORT")
@ -63,14 +103,19 @@ func FillSettings() {
Settings.NATS_PORT = os.Getenv("BUS_LOCAL_PORT")
}
if Settings.NATS_HOST == "" {
log.Panic("Need fill BUS_LOCAL_HOST ! in OS Environment ")
TextError := "Need fill BUS_LOCAL_HOST ! in OS Environment "
err = errors.New(TextError)
return err
}
if Settings.NATS_PORT == "" {
log.Panic("Need fill BUS_LOCAL_PORT ! in OS Environment ")
TextError := "Need fill BUS_LOCAL_PORT ! in OS Environment "
err = errors.New(TextError)
return err
}
return err
}
// WaitStop - ожидает отмену глобального контекста
@ -90,12 +135,40 @@ func WaitStop() {
}
// Start - необходимые процедуры для запуска сервера NRPC
// если контекст хранится в contextmain.GetContext()
// и есть stopapp.GetWaitGroup_Main()
// при ошибке вызывает панику
func Start() {
Connect()
stopapp.GetWaitGroup_Main().Add(1)
go WaitStop()
stopapp.GetWaitGroup_Main().Add(1)
go ping_go()
}
// Start_ctx - необходимые процедуры для запуска сервера NRPC
// ctx - глобальный контекст приложения
// wg - глобальный WaitGroup приложения
func Start_ctx(ctx *context.Context, wg *sync.WaitGroup) error {
var err error
contextmain.Ctx = ctx
stopapp.SetWaitGroup_Main(wg)
err = Connect_err()
if err != nil {
return err
}
stopapp.GetWaitGroup_Main().Add(1)
go WaitStop()
stopapp.GetWaitGroup_Main().Add(1)
go ping_go()
return err
}
// CloseConnection - закрывает подключение к NATS
@ -122,3 +195,51 @@ func IsRecordNotFound(err error) bool {
return Otvet
}
// ping_go - делает пинг каждые 60 секунд, и реконнект
func ping_go() {
ticker := time.NewTicker(60 * time.Second)
defer ticker.Stop()
addr := Settings.NATS_HOST + ":" + Settings.NATS_PORT
//бесконечный цикл
loop:
for {
select {
case <-contextmain.GetContext().Done():
log.Warn("Context app is canceled. nrpc_client.ping")
break loop
case <-ticker.C:
err := port_checker.CheckPort_err(Settings.NATS_HOST, Settings.NATS_PORT)
//log.Debug("ticker, ping err: ", err) //удалить
if err != nil {
NeedReconnect = true
log.Warn("nrpc_client CheckPort(", addr, ") error: ", err)
} else if NeedReconnect == true {
log.Warn("nrpc_client CheckPort(", addr, ") OK. Start Reconnect()")
NeedReconnect = false
err = Connect_err()
if err != nil {
NeedReconnect = true
log.Error("nrpc_client Connect() error: ", err)
}
}
}
}
stopapp.GetWaitGroup_Main().Done()
}
// GetTimeoutSeconds - возвращает время ожидания ответа
func GetTimeoutSeconds() int {
Otvet := nrpc_constants.GetTimeoutSeconds()
return Otvet
}
// SetTimeoutSeconds - устанавливает время ожидания ответа
func SetTimeoutSeconds(seconds int) {
nrpc_constants.SetTimeoutSeconds(seconds)
}

View File

@ -4,9 +4,11 @@ import (
"encoding/json"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_proto"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/nrpc/nrpc_client"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/nrpc/grpc_client/constants"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/nrpc/nrpc_client/nrpc_constants"
"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"
"log"
"sync"
)
// VersionModel - хранит версию структуры модели
@ -19,8 +21,14 @@ const TableName string = "lawsuit_status_types"
type Crud_NRPC struct {
}
// mutex_GetVersionModel - защита от многопоточности GetVersionModel()
var mutex_GetVersionModel = sync.Mutex{}
// GetVersionModel - возвращает хэш версии структуры модели
func (crud Crud_NRPC) GetVersionModel() uint32 {
mutex_GetVersionModel.Lock()
defer mutex_GetVersionModel.Unlock()
if VersionModel == 0 {
VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion()
}
@ -32,19 +40,19 @@ func (crud Crud_NRPC) Read(m *lawsuit_status_types.LawsuitStatusType) error {
// var Otvet lawsuit_status_types.LawsuitStatusType
// подключение
if nrpc_client.Client == nil {
if nrpc_client.LawsuitStatusTypeClient == nil {
nrpc_client.Connect()
}
// подготовка запроса
var VersionModel = crud.GetVersionModel()
var versionModel = crud.GetVersionModel()
Request := &grpc_proto.RequestId{}
Request.ID = int64(m.ID)
Request.VersionModel = VersionModel
Request.VersionModel = versionModel
// запрос
Response, err := nrpc_client.Client.LawsuitStatusType_Read(Request)
Response, err := nrpc_client.LawsuitStatusTypeClient.Read(Request)
if err != nil {
sError := err.Error()
if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION {
@ -68,7 +76,7 @@ func (crud Crud_NRPC) Create(m *lawsuit_status_types.LawsuitStatusType) error {
// var Otvet lawsuit_status_types.LawsuitStatusType
// подключение
if nrpc_client.Client == nil {
if nrpc_client.LawsuitStatusTypeClient == nil {
nrpc_client.Connect()
}
@ -84,7 +92,7 @@ func (crud Crud_NRPC) Create(m *lawsuit_status_types.LawsuitStatusType) error {
Request.VersionModel = VersionModel
// запрос
Response, err := nrpc_client.Client.LawsuitStatusType_Create(Request)
Response, err := nrpc_client.LawsuitStatusTypeClient.Create(Request)
if err != nil {
sError := err.Error()
if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION {
@ -108,7 +116,7 @@ func (crud Crud_NRPC) Update(m *lawsuit_status_types.LawsuitStatusType) error {
// var Otvet lawsuit_status_types.LawsuitStatusType
// подключение
if nrpc_client.Client == nil {
if nrpc_client.LawsuitStatusTypeClient == nil {
nrpc_client.Connect()
}
@ -124,7 +132,7 @@ func (crud Crud_NRPC) Update(m *lawsuit_status_types.LawsuitStatusType) error {
Request.VersionModel = VersionModel
// запрос
Response, err := nrpc_client.Client.LawsuitStatusType_Update(Request)
Response, err := nrpc_client.LawsuitStatusTypeClient.Update(Request)
if err != nil {
sError := err.Error()
if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION {
@ -148,7 +156,7 @@ func (crud Crud_NRPC) Save(m *lawsuit_status_types.LawsuitStatusType) error {
// var Otvet lawsuit_status_types.LawsuitStatusType
// подключение
if nrpc_client.Client == nil {
if nrpc_client.LawsuitStatusTypeClient == nil {
nrpc_client.Connect()
}
@ -164,7 +172,7 @@ func (crud Crud_NRPC) Save(m *lawsuit_status_types.LawsuitStatusType) error {
Request.VersionModel = VersionModel
// запрос
Response, err := nrpc_client.Client.LawsuitStatusType_Save(Request)
Response, err := nrpc_client.LawsuitStatusTypeClient.Save(Request)
if err != nil {
sError := err.Error()
if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION {
@ -188,7 +196,7 @@ func (crud Crud_NRPC) Delete(m *lawsuit_status_types.LawsuitStatusType) error {
// var Otvet lawsuit_status_types.LawsuitStatusType
// подключение
if nrpc_client.Client == nil {
if nrpc_client.LawsuitStatusTypeClient == nil {
nrpc_client.Connect()
}
@ -200,7 +208,7 @@ func (crud Crud_NRPC) Delete(m *lawsuit_status_types.LawsuitStatusType) error {
Request.VersionModel = VersionModel
// запрос
Response, err := nrpc_client.Client.LawsuitStatusType_Delete(Request)
Response, err := nrpc_client.LawsuitStatusTypeClient.Delete(Request)
if err != nil {
sError := err.Error()
if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION {
@ -224,7 +232,7 @@ func (crud Crud_NRPC) Restore(m *lawsuit_status_types.LawsuitStatusType) error {
// var Otvet lawsuit_status_types.LawsuitStatusType
// подключение
if nrpc_client.Client == nil {
if nrpc_client.LawsuitStatusTypeClient == nil {
nrpc_client.Connect()
}
@ -236,7 +244,7 @@ func (crud Crud_NRPC) Restore(m *lawsuit_status_types.LawsuitStatusType) error {
Request.VersionModel = VersionModel
// запрос
Response, err := nrpc_client.Client.LawsuitStatusType_Restore(Request)
Response, err := nrpc_client.LawsuitStatusTypeClient.Restore(Request)
if err != nil {
sError := err.Error()
if len(sError) >= len(constants.TEXT_ERROR_MODEL_VERSION) && sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION {
@ -258,20 +266,20 @@ func (crud Crud_NRPC) Restore(m *lawsuit_status_types.LawsuitStatusType) error {
// Find_ByExtID - находит модель в БД по ext_id и connection_id
func (crud Crud_NRPC) Find_ByExtID(m *lawsuit_status_types.LawsuitStatusType) error {
//подключение
if nrpc_client.Client == nil {
if nrpc_client.LawsuitStatusTypeClient == nil {
nrpc_client.Connect()
}
//подготовка запроса
var VersionModel = crud.GetVersionModel()
Request := &grpc_proto.RequestExtId{}
Request.ExtId = m.ExtID
Request := &grpc_proto.RequestExtID{}
Request.ExtID = m.ExtID
Request.ConnectionId = m.ConnectionID
Request.VersionModel = VersionModel
//запрос
Response, err := nrpc_client.Client.LawsuitStatusType_FindByExtID(Request)
Response, err := nrpc_client.LawsuitStatusTypeClient.FindByExtID(Request)
if err != nil {
sError := err.Error()
if sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION {

View File

@ -1,11 +1,10 @@
package nrpc_lawsuit_status_types
import (
config "github.com/ManyakRus/starter/config_main"
"github.com/ManyakRus/starter/config_main"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/nrpc/nrpc_client"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities/lawsuit_status_types"
"testing"
"math"
)
// Postgres_ID_Test - ID таблицы для тестирования
@ -111,11 +110,45 @@ func TestDelete(t *testing.T) {
crud := Crud_NRPC{}
Otvet := lawsuit_status_types.LawsuitStatusType{}
Otvet.ID = math.MinInt64
err := crud.Delete(&Otvet)
Otvet.ID = Postgres_ID_Test
err := crud.Read(&Otvet)
if err != nil {
t.Error("TestRead() error: ", err)
}
if Otvet.IsDeleted == false {
err = crud.Delete(&Otvet)
if err != nil {
t.Error("TestDelete() error: ", err)
}
if Otvet.ID == 0 {
t.Error("TestDelete() error: ID =0")
}
err = crud.Restore(&Otvet)
if err != nil {
t.Error("TestDelete() error: ", err)
}
if Otvet.ID == 0 {
t.Error("TestDelete() error: ID =0")
}
} else {
err = crud.Restore(&Otvet)
if err != nil {
t.Error("TestDelete() error: ", err)
}
if Otvet.ID == 0 {
t.Error("TestDelete() error: ID =0")
}
err = crud.Delete(&Otvet)
if err != nil {
t.Error("TestDelete() error: ", err)
}
if Otvet.ID == 0 {
t.Error("TestDelete() error: ID =0")
}
}
}
func TestFindByExtID(t *testing.T) {
@ -142,10 +175,10 @@ func TestFindByExtID(t *testing.T) {
err = crud.Find_ByExtID(&Otvet)
if err != nil {
t.Error("TestFindByExtId() error: ", err)
t.Error("TestFindByExtID() error: ", err)
}
if Otvet.ID == 0 {
t.Error("TestFindByExtId() error: ID =0")
t.Error("TestFindByExtID() error: ID =0")
}
}

View File

@ -0,0 +1,28 @@
package nrpc_constants
import "sync"
// timeout_seconds - время ожидания ответа
var timeout_seconds int = 30
// TEXT_ERROR_MODEL_VERSION - текст ошибки версии модели
const TEXT_ERROR_MODEL_VERSION = "Error: wrong version object model"
// mutex_TIMEOUT_SECONDS - защита от многопоточности GetTimeoutSeconds()
var mutex_TIMEOUT_SECONDS sync.RWMutex
// GetTimeoutSeconds - возвращает время ожидания ответа
func GetTimeoutSeconds() int {
mutex_TIMEOUT_SECONDS.RLock()
defer mutex_TIMEOUT_SECONDS.RUnlock()
return timeout_seconds
}
// SetTimeoutSeconds - устанавливает время ожидания ответа
func SetTimeoutSeconds(seconds int) {
mutex_TIMEOUT_SECONDS.Lock()
defer mutex_TIMEOUT_SECONDS.Unlock()
timeout_seconds = seconds
}

View File

@ -25,7 +25,7 @@ type ICrud_LawsuitStatusType interface {
Find_ByExtID(*LawsuitStatusType) error
}
// TableName - возвращает имя таблицы в БД, нужен для gorm
// TableName - возвращает имя таблицы в БД
func (m LawsuitStatusType) TableNameDB() string {
return "lawsuit_status_types"
}

View File

@ -0,0 +1,15 @@
package lawsuit_status_types
// Crud_manual_LawsuitStatusType - объект контроллер crud операций
var Crud_manual_LawsuitStatusType ICrud_manual_LawsuitStatusType
// интерфейс CRUD операций сделанных вручную, для использования в DB или GRPC или NRPC
type ICrud_manual_LawsuitStatusType interface {
}
// SetCrudManualInterface - заполняет интерфейс crud: DB, GRPC, NRPC
func (m LawsuitStatusType) SetCrudManualInterface(crud ICrud_manual_LawsuitStatusType) {
Crud_manual_LawsuitStatusType = crud
return
}

View File

@ -36,6 +36,9 @@ type SettingsINI struct {
TEMPLATE_FOLDERNAME_MAIN string
TEMPLATE_REPOSITORY_URL string
TEMPLATE_EXTERNAL_PROTO_FILENAME string
TEMPLATES_CRUD_FILENAME string
TEMPLATES_CRUD_TEST_FILENAME string
TEMPLATES_ALIAS_FILENAME string
NEED_CREATE_MODEL_STRUCT bool
NEED_CREATE_MODEL_CRUD bool
NEED_CREATE_DB bool
@ -64,6 +67,7 @@ type SettingsINI struct {
COMMENT_MODEL_STRUCT string
TEXT_MODULE_GENERATED string
PREFIX_TABLE string
READY_ALIAS_FILENAME string
}
// FillSettings загружает переменные окружения в структуру из переменных окружения
@ -169,6 +173,10 @@ func FillSettings() {
Settings.TEMPLATE_EXTERNAL_PROTO_FILENAME = os.Getenv("TEMPLATE_EXTERNAL_PROTO_FILENAME")
Settings.TEMPLATE_FOLDERNAME_GRPC_NRPC = os.Getenv("TEMPLATE_FOLDERNAME_GRPC_NRPC")
Settings.NEED_CREATE_MANUAL_FILES = BoolFromString(os.Getenv("NEED_CREATE_MANUAL_FILES"))
Settings.TEMPLATES_CRUD_FILENAME = os.Getenv("TEMPLATES_CRUD_FILENAME")
Settings.TEMPLATES_CRUD_TEST_FILENAME = os.Getenv("TEMPLATES_CRUD_TEST_FILENAME")
Settings.TEMPLATES_ALIAS_FILENAME = os.Getenv("TEMPLATES_ALIAS_FILENAME")
Settings.READY_ALIAS_FILENAME = os.Getenv("READY_ALIAS_FILENAME")
}

View File

@ -0,0 +1,55 @@
package alias
import (
"github.com/ManyakRus/crud_generator/internal/config"
"github.com/ManyakRus/crud_generator/internal/constants"
"github.com/ManyakRus/crud_generator/internal/folders"
"github.com/ManyakRus/starter/log"
"github.com/ManyakRus/starter/micro"
"os"
)
// CreateAllFiles - создаёт файл makefile в корне проекта
func CreateAllFiles() error {
var err error
err = CreateAlias()
if err != nil {
log.Error("CreateAlias() error: ", err)
return err
}
return err
}
// CreateAlias - создаёт 1 файл в папке grpc
func CreateAlias() error {
var err error
if config.Settings.USE_DEFAULT_TEMPLATE == false {
return err
}
//чтение файлов
DirBin := micro.ProgramDir_bin()
DirTemplates := DirBin + config.Settings.TEMPLATE_FOLDERNAME + micro.SeparatorFile()
DirReady := DirBin + config.Settings.READY_FOLDERNAME + micro.SeparatorFile()
DirTemplatesAlias := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_ALIAS + micro.SeparatorFile()
DirReadyAlias := DirReady + config.Settings.TEMPLATE_FOLDERNAME_ALIAS + micro.SeparatorFile()
FilenameTemplateAlias := DirTemplatesAlias + config.Settings.TEMPLATES_ALIAS_FILENAME
FilenameReadyAlias := DirReadyAlias + config.Settings.READY_ALIAS_FILENAME
//создадим папку готовых файлов
folders.CreateFolder(DirReadyAlias)
bytes, err := os.ReadFile(FilenameTemplateAlias)
if err != nil {
log.Panic("ReadFile() ", FilenameTemplateAlias, " error: ", err)
}
TextAlias := string(bytes)
//запись файла в bin
err = os.WriteFile(FilenameReadyAlias, []byte(TextAlias), constants.FILE_PERMISSIONS)
return err
}

View File

@ -0,0 +1 @@
package alias

View File

@ -389,7 +389,7 @@ func FindCrudStarterURL() string {
func Find_GRPC_NRPC_URL() string {
Otvet := ""
Otvet = config.Settings.SERVICE_REPOSITORY_URL + config.Settings.TEMPLATE_FOLDERNAME_GRPC_NRPC
Otvet = config.Settings.SERVICE_REPOSITORY_URL + "/" + config.Settings.TEMPLATE_FOLDERNAME_GRPC_NRPC
return Otvet
}
@ -830,3 +830,15 @@ func DeleteEmptyLines(Text string) string {
}
return Otvet
}
// DeleteLastUnderline - удаляет последний символ подчёркивания
func DeleteLastUnderline(s string) string {
Otvet := s
if s == "" {
return Otvet
}
Otvet = strings.TrimSuffix(Otvet, "_")
return Otvet
}

View File

@ -57,7 +57,7 @@ func CreateFiles(Table1 *types.Table) error {
DirTemplatesDB := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_CRUD + micro.SeparatorFile()
DirReadyDB := DirReady + config.Settings.TEMPLATE_FOLDERNAME_CRUD + micro.SeparatorFile()
FilenameTemplateDB := DirTemplatesDB + constants.TemplateFilenameCrudGo
FilenameTemplateDB := DirTemplatesDB + config.Settings.TEMPLATES_CRUD_FILENAME
TableName := strings.ToLower(Table1.Name)
DirReadyTable := DirReadyDB + config.Settings.PREFIX_CRUD + TableName
FilenameReadyDB := DirReadyTable + micro.SeparatorFile() + config.Settings.PREFIX_CRUD + TableName + ".go"
@ -146,7 +146,7 @@ func CreateTestFiles(Table1 *types.Table) error {
DirTemplatesDB := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_CRUD + micro.SeparatorFile()
DirReadyDB := DirReady + config.Settings.TEMPLATE_FOLDERNAME_CRUD + micro.SeparatorFile()
FilenameTemplateDB := DirTemplatesDB + constants.TemplateFilenameCrudGoTest
FilenameTemplateDB := DirTemplatesDB + config.Settings.TEMPLATES_CRUD_TEST_FILENAME
DirReadyTable := DirReadyDB + config.Settings.PREFIX_CRUD + TableName
FilenameReadyDB := DirReadyTable + micro.SeparatorFile() + config.Settings.PREFIX_CRUD + TableName + "_test.go"

View File

@ -2,6 +2,7 @@ package logic
import (
"github.com/ManyakRus/crud_generator/internal/config"
"github.com/ManyakRus/crud_generator/internal/create_files/alias"
"github.com/ManyakRus/crud_generator/internal/create_files/crud_starter"
"github.com/ManyakRus/crud_generator/internal/create_files/crud_starter_tables"
"github.com/ManyakRus/crud_generator/internal/create_files/db_crud_tables"
@ -176,5 +177,12 @@ func StartFillAll() error {
return err
}
//alias
err = alias.CreateAllFiles()
if err != nil {
//log.Error("env_file.CreateAllFiles() error: ", err)
return err
}
return err
}