diff --git a/examples/crud_service/templates/.env_ b/examples/crud_service/templates/.env_ new file mode 100644 index 0000000..096eab9 --- /dev/null +++ b/examples/crud_service/templates/.env_ @@ -0,0 +1,21 @@ +STAGE="local" +LOG_LEVEL="debug" + +DB_HOST="" +DB_NAME="" +DB_SCHEME="" +DB_PORT="" +DB_USER="" +DB_PASSWORD="" + +NATS_HOST="" +NATS_PORT="" +NATS_LOGIN="" +NATS_PASSWORD="" + +SYNC_SERVICE_HOST=localhost +SYNC_SERVICE_PORT=30031 + +GRPC_PORT=30031 + + diff --git a/examples/crud_service/templates/.gitignore b/examples/crud_service/templates/.gitignore new file mode 100644 index 0000000..c270948 --- /dev/null +++ b/examples/crud_service/templates/.gitignore @@ -0,0 +1,7 @@ +.env +/bin/.env + +/.idea/ +.vscode +/log.txt +cover.out diff --git a/examples/crud_service/templates/Makefile_ b/examples/crud_service/templates/Makefile_ new file mode 100644 index 0000000..b8896c4 --- /dev/null +++ b/examples/crud_service/templates/Makefile_ @@ -0,0 +1,58 @@ +SERVICENAME=sync_service +SERVICEURL=github.com/ManyakRus/$(SERVICENAME) + +FILEMAIN=./cmd/$(SERVICENAME)/main.go +FILEAPP=./bin/$(SERVICENAME) + +NEW_REPO=$(SERVICENAME) +GENERATION_PROTO=cd ./api && ./generation_code.sh + + +run: + clear + go build -race -o $(FILEAPP) $(FILEMAIN) + # cd ./bin && \ + ./bin/$(SERVICENAME) +mod: + clear + go get -u ./... + go mod tidy -compat=1.18 + go mod vendor + go fmt ./... +build: + clear + go build -race -o $(FILEAPP) $(FILEMAIN) + cd ./scripts && \ + ./VersionToFile.py + +lint: + clear + go fmt ./... + golangci-lint run ./internal/... + golangci-lint run ./pkg/... + gocyclo -over 10 ./internal + gocyclo -over 10 ./pkg + gocritic check ./internal/... + gocritic check ./pkg/... + staticcheck ./internal/... + staticcheck ./pkg/... +run.test: + clear + go fmt ./... + go test -coverprofile cover.out ./internal/v0/app/... + go tool cover -func=cover.out +newrepo: + sed -i 's+$(SERVICEURL)+$(NEW_REPO)+g' go.mod + find -name *.go -not -path "*/vendor/*"|xargs sed -i 's+$(SERVICEURL)+$(NEW_REPO)+g' +graph: + clear + image_packages ./ docs/packages.graphml +conn: + clear + image_connections ./internal docs/connections.graphml $(SERVICENAME) +init: + clear + go mod init gitlab.aescorp.ru/dsp_dev/claim/sync_service + $(GENERATION_PROTO) + go mod tidy + go mod vendor \ No newline at end of file diff --git a/examples/crud_service/templates/api/generation_code.sh_ b/examples/crud_service/templates/api/generation_code.sh_ new file mode 100755 index 0000000..7c46f85 --- /dev/null +++ b/examples/crud_service/templates/api/generation_code.sh_ @@ -0,0 +1,6 @@ +#!/bin/bash + +ADAPT_PATH=./ + +clear +protoc --go_out=${ADAPT_PATH} --nrpc_out=./ --go_opt=paths=import --go-grpc_out=${ADAPT_PATH} --go-grpc_opt=paths=import ${ADAPT_PATH}sync_service.proto diff --git a/examples/crud_service/templates/api/service.proto_ b/examples/crud_service/templates/api/service.proto_ new file mode 100644 index 0000000..99d9d88 --- /dev/null +++ b/examples/crud_service/templates/api/service.proto_ @@ -0,0 +1,186 @@ +syntax = "proto3"; + +/* + Файл содержит описание сервиса Sync_service +*/ + + +package grpc; + +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 записи в БД +} + +// RequestString - параметры запроса на сервер +message RequestString { + uint32 VersionModel= 1; //версия структуры модели + string StringFind = 2; // строка поиска +} + +// RequestString3 - параметры запроса на сервер +message RequestString3 { + uint32 VersionModel= 1; //версия структуры модели + string StringFind1 = 2; // строка поиска + string StringFind2 = 3; // строка поиска + string StringFind3 = 4; // строка поиска +} + +// RequestId - параметры запроса на сервер +message RequestExtId { + uint32 VersionModel= 1; //версия структуры модели + int64 Ext_id = 2; // ext_id записи в БД + int64 Connection_id =3; // Connection_id записи в БД +} + +// RequestModel - параметры запроса на сервер +message RequestModel { + uint32 VersionModel= 1; //версия структуры модели + string ModelString = 2; //объект-модель в формате json +} + +// RequestInnKpp - параметры запроса на сервер +message RequestInnKpp { + uint32 VersionModel= 1; //версия структуры модели + string Inn = 2; // ИНН + string Kpp =3; // КПП +} + +// RequestId - параметры запроса на сервер +message RequestIdId { + uint32 VersionModel= 1; //версия структуры модели + int64 id1 = 2; // id записи в БД + int64 id2 = 3; // id записи в БД +} + + + +// Response - параметры ответа на клиент +message Response { + string ModelString = 1; //объект-модель в формате json +} + +// ResponseFloat64 - параметры ответа на клиент +message ResponseFloat64 { + double Otvet = 1; //Ответ - число +} + +// Response - параметры ответа на клиент +message ResponseEmpty { +} + diff --git a/examples/crud_service/templates/bin/date.txt b/examples/crud_service/templates/bin/date.txt new file mode 100644 index 0000000..99a18f2 --- /dev/null +++ b/examples/crud_service/templates/bin/date.txt @@ -0,0 +1 @@ +2023-11-15 12:11:15.838 \ No newline at end of file diff --git a/examples/crud_service/templates/bin/settings.txt b/examples/crud_service/templates/bin/settings.txt new file mode 100644 index 0000000..01ca9cb --- /dev/null +++ b/examples/crud_service/templates/bin/settings.txt @@ -0,0 +1,29 @@ +STAGE="local" +LOG_LEVEL="debug" + +#---------------------Database settings--------------------- +#DB_HOST - Database server name or ip-address. Only Postgres SQL +DB_HOST="" + +#DB_NAME - Database table name +DB_NAME="" + +#DB_SCHEME - Database schema name +DB_SCHEME="public" + +#DB_PORT - Database port number +DB_PORT="5432" + +#DB_USER - Database login (user) +DB_USER="" + +#DB_PASSWORD - Database login password +DB_PASSWORD="" + + +#---------------------NATS messages broker settings--------------------- +NATS_HOST="" +NATS_PORT="" +NATS_LOGIN="" +NATS_PASSWORD="" + diff --git a/examples/crud_service/templates/bin/subversion.txt b/examples/crud_service/templates/bin/subversion.txt new file mode 100644 index 0000000..4424fb1 --- /dev/null +++ b/examples/crud_service/templates/bin/subversion.txt @@ -0,0 +1 @@ +00133 \ No newline at end of file diff --git a/examples/crud_service/templates/bin/version.txt b/examples/crud_service/templates/bin/version.txt new file mode 100644 index 0000000..a5e11e5 --- /dev/null +++ b/examples/crud_service/templates/bin/version.txt @@ -0,0 +1 @@ +v0 \ No newline at end of file diff --git a/examples/crud_service/templates/cmd/main.go_ b/examples/crud_service/templates/cmd/main.go_ new file mode 100644 index 0000000..8e9fa2d --- /dev/null +++ b/examples/crud_service/templates/cmd/main.go_ @@ -0,0 +1,27 @@ +package main + +import ( + configmain "github.com/ManyakRus/starter/config" + "github.com/ManyakRus/starter/stopapp" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/crud_starter" + "github.com/ManyakRus/starter/postgres_gorm" +) + +// main - старт приложения +func main() { + StartApp() +} + +// StartApp - выполнение всех операций для старта приложения +func StartApp() { + configmain.LoadEnv() + + stopapp.StartWaitStop() + crud_starter.InitCrudTransport_DB() + postgres_gorm.StartDB() + server_grpc.Start() + server_nrpc.Start() + + stopapp.GetWaitGroup_Main().Wait() + +} diff --git a/examples/crud_service/templates/configs_/convert_id.json b/examples/crud_service/templates/configs_/convert_id.json new file mode 100644 index 0000000..e12763f --- /dev/null +++ b/examples/crud_service/templates/configs_/convert_id.json @@ -0,0 +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" +} + diff --git a/examples/crud_service/templates/configs_/mapping.json b/examples/crud_service/templates/configs_/mapping.json new file mode 100644 index 0000000..7f5fd24 --- /dev/null +++ b/examples/crud_service/templates/configs_/mapping.json @@ -0,0 +1,571 @@ +{ + "mappings": [ + { + "sql_type": "bit", + "go_type": "bool", + "json_type": "Boolean", + "protobuf_type": "bool", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullBool", + "swagger_type": "bool" + }, + { + "sql_type": "bool", + "go_type": "bool", + "json_type": "Boolean", + "protobuf_type": "bool", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullBool", + "swagger_type": "bool" + }, + { + "sql_type": "tinyint", + "go_type": "int32", + "json_type": "Integer", + "protobuf_type": "int32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt32", + "swagger_type": "int" + }, + { + "sql_type": "int", + "go_type": "int32", + "json_type": "Integer", + "protobuf_type": "int32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt32", + "swagger_type": "int" + }, + { + "sql_type": "smallint", + "size": 2, + "go_type": "int32", + "json_type": "Integer", + "protobuf_type": "int32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt32", + "swagger_type": "int" + }, + { + "sql_type": "mediumint", + "go_type": "int32", + "json_type": "Integer", + "protobuf_type": "int32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt32", + "swagger_type": "int" + }, + { + "sql_type": "int4", + "go_type": "int32", + "json_type": "Integer", + "protobuf_type": "int32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt32", + "swagger_type": "int" + }, + { + "sql_type": "int2", + "go_type": "int32", + "json_type": "Integer", + "protobuf_type": "int32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt32", + "swagger_type": "int" + }, + { + "sql_type": "integer", + "go_type": "int32", + "json_type": "Integer", + "protobuf_type": "int32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt32", + "swagger_type": "int" + }, + { + "sql_type": "bigint", + "go_type": "int64", + "json_type": "Integer", + "protobuf_type": "int64", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt64", + "swagger_type": "int64" + }, + { + "sql_type": "int8", + "go_type": "int64", + "json_type": "Integer", + "protobuf_type": "int64", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt64", + "swagger_type": "int64" + }, + { + "sql_type": "char", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "enum", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "varchar", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "nvarchar", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "longtext", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "mediumtext", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "text", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "tinytext", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "varchar2", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "inet", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "json", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "datatypes.JSON", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "jsonb", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "datatypes.JSON", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "nchar", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "date", + "go_type": "time.Time", + "json_type": "Text", + "protobuf_type": "google.protobuf.Timestamp", + "guregu_type": "null.Time", + "go_nullable_type": "time.Time", + "swagger_type": "time.Time" + }, + { + "sql_type": "datetime2", + "go_type": "time.Time", + "json_type": "Text", + "protobuf_type": "google.protobuf.Timestamp", + "guregu_type": "null.Time", + "go_nullable_type": "time.Time", + "swagger_type": "time.Time" + }, + { + "sql_type": "datetime", + "go_type": "time.Time", + "json_type": "Text", + "protobuf_type": "google.protobuf.Timestamp", + "guregu_type": "null.Time", + "go_nullable_type": "time.Time", + "swagger_type": "time.Time" + }, + { + "sql_type": "time", + "go_type": "time.Time", + "json_type": "Text", + "protobuf_type": "google.protobuf.Timestamp", + "guregu_type": "null.Time", + "go_nullable_type": "time.Time", + "swagger_type": "time.Time" + }, + { + "sql_type": "timestamp", + "go_type": "time.Time", + "json_type": "Text", + "protobuf_type": "uint64", + "guregu_type": "null.Time", + "go_nullable_type": "time.Time", + "swagger_type": "time.Time" + }, + { + "sql_type": "timestamptz", + "go_type": "time.Time", + "json_type": "Text", + "protobuf_type": "uint64", + "guregu_type": "null.Time", + "go_nullable_type": "time.Time", + "swagger_type": "time.Time" + }, + { + "sql_type": "smalldatetime", + "go_type": "time.Time", + "json_type": "Text", + "protobuf_type": "google.protobuf.Timestamp", + "guregu_type": "null.Time", + "go_nullable_type": "time.Time", + "swagger_type": "time.Time" + }, + { + "sql_type": "decimal", + "go_type": "float64", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float64" + }, + { + "sql_type": "double", + "go_type": "float64", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float64" + }, + { + "sql_type": "money", + "go_type": "float64", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float64" + }, + { + "sql_type": "real", + "go_type": "float64", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float64" + }, + { + "sql_type": "float4", + "go_type": "float32", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float32" + }, + + { + "sql_type": "float", + "go_type": "float32", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float32" + }, + { + "sql_type": "float8", + "go_type": "float64", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float64" + }, + + { + "sql_type": "binary", + "go_type": "[]byte", + "json_type": "Text", + "protobuf_type": "bytes", + "guregu_type": "[]byte", + "go_nullable_type": "[]byte", + "swagger_type": "[]byte" + }, + { + "sql_type": "blob", + "go_type": "[]byte", + "json_type": "Text", + "protobuf_type": "bytes", + "guregu_type": "[]byte", + "go_nullable_type": "[]byte", + "swagger_type": "[]byte" + }, + { + "sql_type": "longblob", + "go_type": "[]byte", + "json_type": "Text", + "protobuf_type": "bytes", + "guregu_type": "[]byte", + "go_nullable_type": "[]byte", + "swagger_type": "[]byte" + }, + { + "sql_type": "mediumblob", + "go_type": "[]byte", + "json_type": "Text", + "protobuf_type": "bytes", + "guregu_type": "[]byte", + "go_nullable_type": "[]byte", + "swagger_type": "[]byte" + }, + { + "sql_type": "varbinary", + "go_type": "[]byte", + "json_type": "Text", + "protobuf_type": "bytes", + "guregu_type": "[]byte", + "go_nullable_type": "[]byte", + "swagger_type": "[]byte" + }, + { + "sql_type": "numeric", + "go_type": "float64", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float64" + }, + { + "sql_type": "bpchar", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "tsvector", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "_text", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "bytea", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "USER_DEFINED", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "bytes", + "guregu_type": "interface{}", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "uuid", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "string", + "guregu_type": "null.String", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "", + "go_type": "string", + "json_type": "Text", + "protobuf_type": "bytes", + "guregu_type": "interface{}", + "go_nullable_type": "sql.NullString", + "swagger_type": "string" + }, + { + "sql_type": "utinyint", + "go_type": "uint32", + "json_type": "Integer", + "protobuf_type": "uint32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt64", + "swagger_type": "int" + }, + { + "sql_type": "usmallint", + "go_type": "uint32", + "json_type": "Integer", + "protobuf_type": "uint32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt64", + "swagger_type": "int" + }, + { + "sql_type": "umediumint", + "go_type": "uint32", + "json_type": "Integer", + "protobuf_type": "uint32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt64", + "swagger_type": "int" + }, + { + "sql_type": "uint", + "go_type": "uint32", + "json_type": "Integer", + "protobuf_type": "uint32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt64", + "swagger_type": "int" + }, + { + "sql_type": "ubigint", + "go_type": "uint64", + "json_type": "Integer", + "protobuf_type": "uint64", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt64", + "swagger_type": "int64" + }, + { + "sql_type": "udecimal", + "go_type": "float64", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float64" + }, + { + "sql_type": "udouble", + "go_type": "float64", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float64" + }, + { + "sql_type": "ufloat", + "go_type": "float32", + "json_type": "Float", + "protobuf_type": "float", + "guregu_type": "null.Float", + "go_nullable_type": "sql.NullFloat64", + "swagger_type": "float32" + }, + { + "sql_type": "smallserial", + "size": 2, + "custom": "postgres", + "go_type": "int32", + "json_type": "Integer", + "protobuf_type": "int32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt64", + "swagger_type": "int" + }, + { + "sql_type": "serial", + "size": 4, + "custom": "postgres", + "go_type": "int32", + "json_type": "Integer", + "protobuf_type": "int32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt64", + "swagger_type": "int" + }, + { + "sql_type": "bigserial", + "size": 8, + "custom": "postgres", + "go_type": "int32", + "json_type": "Integer", + "protobuf_type": "int32", + "guregu_type": "null.Int", + "go_nullable_type": "sql.NullInt64", + "swagger_type": "int" + } + ] +} diff --git a/examples/crud_service/templates/configs_/model_crud_delete_functions.json b/examples/crud_service/templates/configs_/model_crud_delete_functions.json new file mode 100644 index 0000000..6a8d05d --- /dev/null +++ b/examples/crud_service/templates/configs_/model_crud_delete_functions.json @@ -0,0 +1,3 @@ +{ + "lawsuits": "NewLawsuit,AsLawsuit" +} diff --git a/examples/crud_service/templates/configs_/name_replace.json b/examples/crud_service/templates/configs_/name_replace.json new file mode 100644 index 0000000..cab0526 --- /dev/null +++ b/examples/crud_service/templates/configs_/name_replace.json @@ -0,0 +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" +} \ No newline at end of file diff --git a/examples/crud_service/templates/configs_/nullable.json b/examples/crud_service/templates/configs_/nullable.json new file mode 100644 index 0000000..3f0a502 --- /dev/null +++ b/examples/crud_service/templates/configs_/nullable.json @@ -0,0 +1,4 @@ +{ + "ext_id": true, + "created_at": false +} diff --git a/examples/crud_service/templates/configs_/readme.txt b/examples/crud_service/templates/configs_/readme.txt new file mode 100644 index 0000000..1c44590 --- /dev/null +++ b/examples/crud_service/templates/configs_/readme.txt @@ -0,0 +1,47 @@ +convert_id.json: +Mapping database table name . field name = field type in golang. +For tables file. +For non standart rare case or type aliases +example: +{ + "lawsuit_payments.id": "alias.PaymentId", + "lawsuit_payments.invoice_id": "alias.InvoiceId", +} + + + +mapping.json +Mapping Postgres types to Golang types + + + +name_replace.json +Mapping database field name = golang field name +For tables file. +Replace standart field name to filled name +For non standart rare case. +example: +{ + "inn": "INN", + "json_file_id": "JSONFileID" +} + + +nullable.json +List of golang field names, which need change 0 to null. +true = need change 0 to null +For non standart rare case. +example: +{ + "ext_id": true, + "created_at": false +} + + +model_crud_delete_functions.json +Mapping postgres tables to golang function name, +this functions will be deleted from model crud files. +example: +{ + "lawsuits": "NewLawsuit,AsLawsuit" +} diff --git a/examples/crud_service/templates/configs_/settings.txt b/examples/crud_service/templates/configs_/settings.txt new file mode 100644 index 0000000..6647da1 --- /dev/null +++ b/examples/crud_service/templates/configs_/settings.txt @@ -0,0 +1,153 @@ +#---------------------Database settings--------------------- +#DB_HOST - Database server name or ip-address. Only Postgres SQL +DB_HOST= + +#DB_NAME - Database table name +DB_NAME= + +#DB_SCHEME - Database schema name +DB_SCHEME= + +#DB_PORT - Database port number +DB_PORT= + +#DB_USER - Database login (user) +DB_USER= + +#DB_PASSWORD - Database login password +DB_PASSWORD= + +#INCLUDE_TABLES - table name filter. Regular expression +INCLUDE_TABLES="" + +#INCLUDE_TABLES - table name ignore filter. Regular expression +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/sync_service" + +#SERVICE_NAME - service name for your new service +SERVICE_NAME=sync_service + +#TEMPLATE_SERVICE_NAME - service name in your template files +TEMPLATE_SERVICE_NAME=sync_service + +#TEMPLATE_REPOSITORY_URL - repository URL in template files +TEMPLATE_REPOSITORY_URL="gitlab.aescorp.ru/dsp_dev/claim/sync_service" + +#same folder names uses for read template files and create new files +#TEMPLATE_FOLDERNAME - filder name in your computer with templates +TEMPLATE_FOLDERNAME="templates" + +#TEMPLATE_FOLDERNAME_MAIN - folder name for create models (golang struct with all table fields) +TEMPLATE_FOLDERNAME_MAIN="cmd" + +#TEMPLATE_FOLDERNAME_MODEL - folder name for create models (golang struct with all table fields) +TEMPLATE_FOLDERNAME_MODEL="pkg/object_model/entities" + +#TEMPLATE_FOLDERNAME_DB - folder name for create database crud operations +TEMPLATE_FOLDERNAME_CRUD="pkg/db/crud" + +#TEMPLATE_FOLDERNAME_TABLES - folder name for create database tables models +TEMPLATE_FOLDERNAME_TABLES="pkg/db/tables" + +#TEMPLATE_FOLDERNAME_DB - folder name for create db +TEMPLATE_FOLDERNAME_DB="pkg/db" + +#TEMPLATE_FOLDERNAME_GRPC - folder name for create .proto file +TEMPLATE_FOLDERNAME_GRPC_PROTO="api" + +#TEMPLATE_FOLDERNAME_GRPC - folder name for grpc +TEMPLATE_FOLDERNAME_GRPC="pkg/network/grpc" + +#TEMPLATE_FOLDERNAME_GRPC_SERVER - filder name for create grpc server files +TEMPLATE_FOLDERNAME_GRPC_SERVER="internal/app/grpc/server_grpc" + +#TEMPLATE_FOLDERNAME_GRPC_CLIENT - folder name for create grpc client files +TEMPLATE_FOLDERNAME_GRPC_CLIENT="pkg/network/grpc/grpc_client" + +#TEMPLATE_FOLDERNAME_NRPC_SERVER - folder name for create nrpc server files +TEMPLATE_FOLDERNAME_NRPC_SERVER="internal/app/nrpc/server_nrpc" + +#TEMPLATE_FOLDERNAME_NRPC - folder name for create common nrpc files +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_CRUD_STARTER - folder name for create crud_starter.go file +TEMPLATE_FOLDERNAME_CRUD_STARTER="pkg/crud_starter" + +#TEMPLATE_FOLDERNAME_ALIAS - folder name for create alias.go file, with go types with aliases +TEMPLATE_FOLDERNAME_ALIAS="pkg/object_model/types/alias" + +#TEMPLATE_FOLDER_CRUD_FUNCTIONS - folder name for create crud_functions.go file +TEMPLATE_FOLDER_CRUD_FUNCTIONS="pkg/db/crud_functions" + +#TEXT_TEMPLATE_MODEL - model name text in templates, for replace to new model names +TEXT_TEMPLATE_MODEL="LawsuitStatusType" + +#TEXT_TEMPLATE_TABLENAME - table name text in tamplates, for replace to new table names +TEXT_TEMPLATE_TABLENAME="lawsuit_status_types" + +#USE_DEFAULT_TEMPLATE - "true" will do default text replaces. "false" - for use own templates +USE_DEFAULT_TEMPLATE=true + +#HAS_IS_DELETED - fill "true" if you have "is_deleted" column, and want Delete() Restore() functions. +HAS_IS_DELETED=true + +#---------------------Create files settings--------------------- + +#NEED_CREATE_CRUD - fill "true" if you want create crud operations files +NEED_CREATE_CRUD=true + +#NEED_CREATE_GRPC - fill "true" if you want create grpc operations files +NEED_CREATE_GRPC=true + +#NEED_CREATE_NRPC - fill "true" if you want create nrpc operations files (need NATS message query server) +NEED_CREATE_NRPC=true + +#NEED_CREATE_MODEL_STRUCT - fill "true" if you want create model files with golang struct with all database fields +NEED_CREATE_MODEL_STRUCT=true + +#NEED_CREATE_MODEL_CRUD - fill "true" if you want create crud operations in model files +NEED_CREATE_MODEL_CRUD=true + +#NEED_CREATE_DB_TEST - fill "true" if you want create DB _test.go files +NEED_CREATE_DB_TEST=true + +#NEED_CREATE_DB - fill "true" if you want create DB .go files +NEED_CREATE_DB=true + +#NEED_CREATE_GRPC_SERVER_TEST - fill "true" if you want create GRPC server _test.go files +NEED_CREATE_GRPC_SERVER_TEST=true + +#NEED_CREATE_GRPC_CLIENT_TEST - fill "true" if you want create GRPC client _test.go files +NEED_CREATE_GRPC_CLIENT_TEST=true + +#NEED_CREATE_NRPC_SERVER_TEST - fill "true" if you want create NRPC server _test.go files +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 + +#PREFIX_SERVER_GRPC - filename prefix for grpc server files +PREFIX_SERVER_GRPC="server_grpc_" + +#PREFIC_CRUD - filename prefix for crud database files +PREFIX_CRUD="crud_" + +#PREFIX_TABLE - filename prefix for database table model files +PREFIX_TABLE="table_" + +#PREFIX_MODEL - filename prefix for view model files +PREFIX_MODEL="" + +#COMMENT_MODEL_STRUCT - fill comments to every model structure +COMMENT_MODEL_STRUCT="модель для таблицы " + +#TEXT_MODULE_GENERATED - comment text for every module file +TEXT_MODULE_GENERATED="//Файл создан автоматически кодогенератором crud_generator\n//Не изменяйте ничего здесь.\n\n" + diff --git a/examples/crud_service/templates/internal/app/grpc/server_grpc/server_grpc.go_ b/examples/crud_service/templates/internal/app/grpc/server_grpc/server_grpc.go_ new file mode 100644 index 0000000..b0de569 --- /dev/null +++ b/examples/crud_service/templates/internal/app/grpc/server_grpc/server_grpc.go_ @@ -0,0 +1,283 @@ +package server_grpc + +import ( + "context" + "github.com/ManyakRus/starter/micro" + "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" +) + +// LawsuitStatusType_Read - читает и возвращает модель из БД +func (s *ServerGRPC) LawsuitStatusType_Read(ctx context.Context, Request *grpc_proto.RequestId) (*grpc_proto.Response, error) { + var Otvet grpc_proto.Response + var err error + + //проверим контекст уже отменён + if micro.ContextDone(ctx) == true { + err = context.Canceled + return &Otvet, err + } + + //проверим совпадения версии модели + VersionServer := lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + VersionClient := Request.VersionModel + if VersionServer != VersionClient { + err = ErrorModelVersion(lawsuit_status_types.LawsuitStatusType{}) + return &Otvet, err + } + + //запрос в БД + Model := &lawsuit_status_types.LawsuitStatusType{} + Model.ID = Request.Id + err = Model.Read() + if err != nil { + return &Otvet, err + } + + //заполяем ответ + ModelString, err := Model.GetJSON() + if err != nil { + return &Otvet, err + } + Otvet.ModelString = ModelString + + return &Otvet, err +} + +// LawsuitStatusType_Delete - записывает в БД is_deleted = true и возвращает модель из БД +func (s *ServerGRPC) LawsuitStatusType_Delete(ctx context.Context, Request *grpc_proto.RequestId) (*grpc_proto.Response, error) { + var Otvet grpc_proto.Response + var err error + + //проверим контекст уже отменён + if micro.ContextDone(ctx) == true { + err = context.Canceled + return &Otvet, err + } + + //проверим совпадения версии модели + VersionServer := lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + VersionClient := Request.VersionModel + if VersionServer != VersionClient { + err = ErrorModelVersion(lawsuit_status_types.LawsuitStatusType{}) + return &Otvet, err + } + + //запрос в БД + Model := &lawsuit_status_types.LawsuitStatusType{} + Model.ID = Request.Id + err = Model.Delete() + if err != nil { + return &Otvet, err + } + + //заполяем ответ + ModelString, err := Model.GetJSON() + if err != nil { + return &Otvet, err + } + Otvet.ModelString = ModelString + + return &Otvet, err +} + +// LawsuitStatusType_Restore - записывает в БД is_deleted = false и возвращает модель из БД +func (s *ServerGRPC) LawsuitStatusType_Restore(ctx context.Context, Request *grpc_proto.RequestId) (*grpc_proto.Response, error) { + var Otvet grpc_proto.Response + var err error + + //проверим контекст уже отменён + if micro.ContextDone(ctx) == true { + err = context.Canceled + return &Otvet, err + } + + //проверим совпадения версии модели + VersionServer := lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + VersionClient := Request.VersionModel + if VersionServer != VersionClient { + err = ErrorModelVersion(lawsuit_status_types.LawsuitStatusType{}) + return &Otvet, err + } + + //запрос в БД + Model := &lawsuit_status_types.LawsuitStatusType{} + Model.ID = Request.Id + err = Model.Restore() + if err != nil { + return &Otvet, err + } + + //заполяем ответ + ModelString, err := Model.GetJSON() + if err != nil { + return &Otvet, err + } + Otvet.ModelString = ModelString + + return &Otvet, err +} + +// LawsuitStatusType_Create - создаёт новую запись в БД +func (s *ServerGRPC) LawsuitStatusType_Create(ctx context.Context, Request *grpc_proto.RequestModel) (*grpc_proto.Response, error) { + var Otvet grpc_proto.Response + var err error + + //проверим контекст уже отменён + if micro.ContextDone(ctx) == true { + err = context.Canceled + return &Otvet, err + } + + //проверим совпадения версии модели + VersionServer := lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + VersionClient := Request.VersionModel + if VersionServer != VersionClient { + err = ErrorModelVersion(lawsuit_status_types.LawsuitStatusType{}) + return &Otvet, err + } + + //получим модель из строки JSON + Model := &lawsuit_status_types.LawsuitStatusType{} + err = Model.GetModelFromJSON(Request.ModelString) + if err != nil { + return &Otvet, err + } + + //запрос в БД + err = Model.Create() + if err != nil { + return &Otvet, err + } + + //заполяем ответ + ModelString, err := Model.GetJSON() + if err != nil { + return &Otvet, err + } + Otvet.ModelString = ModelString + + return &Otvet, err +} + +// LawsuitStatusType_Update - обновляет новую запись в БД +func (s *ServerGRPC) LawsuitStatusType_Update(ctx context.Context, Request *grpc_proto.RequestModel) (*grpc_proto.Response, error) { + var Otvet grpc_proto.Response + var err error + + //проверим контекст уже отменён + if micro.ContextDone(ctx) == true { + err = context.Canceled + return &Otvet, err + } + + //проверим совпадения версии модели + VersionServer := lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + VersionClient := Request.VersionModel + if VersionServer != VersionClient { + err = ErrorModelVersion(lawsuit_status_types.LawsuitStatusType{}) + return &Otvet, err + } + + //получим модель из строки JSON + Model := &lawsuit_status_types.LawsuitStatusType{} + err = Model.GetModelFromJSON(Request.ModelString) + if err != nil { + return &Otvet, err + } + + //запрос в БД + err = Model.Update() + if err != nil { + return &Otvet, err + } + + //заполяем ответ + ModelString, err := Model.GetJSON() + if err != nil { + return &Otvet, err + } + Otvet.ModelString = ModelString + + return &Otvet, err +} + +// LawsuitStatusType_Save - записывает (создаёт или обновляет) запись в БД +func (s *ServerGRPC) LawsuitStatusType_Save(ctx context.Context, Request *grpc_proto.RequestModel) (*grpc_proto.Response, error) { + var Otvet grpc_proto.Response + var err error + + //проверим контекст уже отменён + if micro.ContextDone(ctx) == true { + err = context.Canceled + return &Otvet, err + } + + //проверим совпадения версии модели + VersionServer := lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + VersionClient := Request.VersionModel + if VersionServer != VersionClient { + err = ErrorModelVersion(lawsuit_status_types.LawsuitStatusType{}) + return &Otvet, err + } + + //получим модель из строки JSON + Model := lawsuit_status_types.LawsuitStatusType{} + err = Model.GetModelFromJSON(Request.ModelString) + if err != nil { + return &Otvet, err + } + + //запрос в БД + err = Model.Save() + if err != nil { + return &Otvet, err + } + + //заполяем ответ + ModelString, err := Model.GetJSON() + if err != nil { + return &Otvet, err + } + Otvet.ModelString = ModelString + + return &Otvet, err +} + +// LawsuitStatusType_FindByExtID - возвращает запись из БД по ext_id и connection_id +func (s *ServerGRPC) LawsuitStatusType_FindByExtID(ctx context.Context, Request *grpc_proto.RequestExtId) (*grpc_proto.Response, error) { + var Otvet grpc_proto.Response + var err error + + //проверим контекст уже отменён + if micro.ContextDone(ctx) == true { + err = context.Canceled + return &Otvet, err + } + + //проверим совпадения версии модели + VersionServer := lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + VersionClient := Request.VersionModel + if VersionServer != VersionClient { + err = ErrorModelVersion(lawsuit_status_types.LawsuitStatusType{}) + return &Otvet, err + } + + //запрос в БД + Model := &lawsuit_status_types.LawsuitStatusType{} + Model.ExtID = Request.ExtId + Model.ConnectionID = Request.ConnectionId + err = Model.Find_ByExtID() + if err != nil { + return &Otvet, err + } + + //заполяем ответ + ModelString, err := Model.GetJSON() + if err != nil { + return &Otvet, err + } + Otvet.ModelString = ModelString + + return &Otvet, err +} diff --git a/examples/crud_service/templates/internal/app/grpc/server_grpc/server_grpc_func.go_ b/examples/crud_service/templates/internal/app/grpc/server_grpc/server_grpc_func.go_ new file mode 100644 index 0000000..41f5bd7 --- /dev/null +++ b/examples/crud_service/templates/internal/app/grpc/server_grpc/server_grpc_func.go_ @@ -0,0 +1,18 @@ +package server_grpc + +import ( + "errors" + "github.com/ManyakRus/starter/micro" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/constants" +) + +// ErrorModelVersion +func ErrorModelVersion(Model interface{}) error { + var err error + + TypeName := micro.GetType(Model) + + s := constants.TEXT_ERROR_MODEL_VERSION + " " + TypeName + err = errors.New(s) + return err +} diff --git a/examples/crud_service/templates/internal/app/grpc/server_grpc/server_grpc_starter.go_ b/examples/crud_service/templates/internal/app/grpc/server_grpc/server_grpc_starter.go_ new file mode 100644 index 0000000..19b0814 --- /dev/null +++ b/examples/crud_service/templates/internal/app/grpc/server_grpc/server_grpc_starter.go_ @@ -0,0 +1,94 @@ +package server_grpc + +import ( + "github.com/ManyakRus/starter/contextmain" + "github.com/ManyakRus/starter/log" + "github.com/ManyakRus/starter/stopapp" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_proto" + "google.golang.org/grpc" + "net" + "os" +) + +// ServerGRPC is used to implement UnimplementedSyncServiceServer. +type ServerGRPC struct { + grpc_proto.UnimplementedSyncServiceServer +} + +type SettingsINI struct { + GRPC_PORT string +} + +var Settings SettingsINI + +var Conn *grpc.Server + +func Connect() { + //var err error + + if Settings.GRPC_PORT == "" { + FillSettings() + } + + Conn = grpc.NewServer() + grpc_proto.RegisterSyncServiceServer(Conn, &ServerGRPC{}) + + stopapp.GetWaitGroup_Main().Add(1) + go serve_go() + +} + +func serve_go() { + defer stopapp.GetWaitGroup_Main().Done() + + lis, err := net.Listen("tcp", ":"+Settings.GRPC_PORT) + if err != nil { + log.Fatalf("failed to listen: %v", err) + } + + log.Printf("Server GRPC listening at %v", lis.Addr()) + if err := Conn.Serve(lis); err != nil { + log.Fatalf("failed to serve: %v", err) + } + + return +} + +func FillSettings() { + Settings = SettingsINI{} + Settings.GRPC_PORT = os.Getenv("GRPC_PORT") + if Settings.GRPC_PORT == "" { + log.Panic("Need fill GRPC_PORT ! in OS Environment ") + } + +} + +// WaitStop - ожидает отмену глобального контекста +func WaitStop() { + defer stopapp.GetWaitGroup_Main().Done() + + select { + case <-contextmain.GetContext().Done(): + log.Warn("Context app is canceled. grpc_connect") + } + + //ждём пока отправляемых сейчас сообщений будет =0 + stopapp.WaitTotalMessagesSendingNow("grpc_connect") + + //закрываем соединение + CloseConnection() + +} + +// Start - необходимые процедуры для запуска сервера GRPC +func Start() { + Connect() + + stopapp.GetWaitGroup_Main().Add(1) + go WaitStop() + +} + +func CloseConnection() { + Conn.Stop() +} diff --git a/examples/crud_service/templates/internal/app/grpc/server_grpc/server_grpc_test.go_ b/examples/crud_service/templates/internal/app/grpc/server_grpc/server_grpc_test.go_ new file mode 100644 index 0000000..b44b962 --- /dev/null +++ b/examples/crud_service/templates/internal/app/grpc/server_grpc/server_grpc_test.go_ @@ -0,0 +1,192 @@ +package server_grpc + +import ( + "context" + "github.com/ManyakRus/starter/config" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/crud_starter" + "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" +) + +// LawsuitStatusType_ID_Test - ID таблицы для тестирования +const LawsuitStatusType_ID_Test = 1 + +func Test_server_LawsuitStatusType_Read(t *testing.T) { + config.LoadEnv() + crud_starter.InitCrudTransport_DB() + + ctx := context.Background() + Request := grpc_proto.RequestId{} + Request.Id = LawsuitStatusType_ID_Test + Request.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + + server1 := &ServerGRPC{} + Otvet, err := server1.LawsuitStatusType_Read(ctx, &Request) + if err != nil { + t.Error("Test_server_LawsuitStatusType_Read() error: ", err) + } + if Otvet.ModelString == "" { + t.Error("Test_server_LawsuitStatusType_Read() error: ModelString=''") + } +} + +func Test_server_LawsuitStatusType_Delete(t *testing.T) { + config.LoadEnv() + crud_starter.InitCrudTransport_DB() + + ctx := context.Background() + Request := grpc_proto.RequestId{} + Request.Id = LawsuitStatusType_ID_Test + Request.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + + server1 := &ServerGRPC{} + Otvet, err := server1.LawsuitStatusType_Delete(ctx, &Request) + if err != nil { + t.Error("Test_server_LawsuitStatusType_Delete() error: ", err) + } + if Otvet.ModelString == "" { + t.Error("Test_server_LawsuitStatusType_Delete() error: ModelString=''") + } + Otvet, err = server1.LawsuitStatusType_Restore(ctx, &Request) +} + +func Test_server_LawsuitStatusType_Create(t *testing.T) { + config.LoadEnv() + crud_starter.InitCrudTransport_DB() + + var ModelString string + Model := lawsuit_status_types.LawsuitStatusType{} + Model.ID = 1 + ModelString, err := Model.GetJSON() + if err != nil { + t.Error("Test_server_LawsuitStatusType_Create() error: ", err) + return + } + + RequestModel := grpc_proto.RequestModel{} + RequestModel.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + RequestModel.ModelString = ModelString + + ctx := context.Background() + server1 := &ServerGRPC{} + Otvet, err := server1.LawsuitStatusType_Create(ctx, &RequestModel) + if err == nil { + t.Error("Test_server_LawsuitStatusType_Create() error: ", err) + } + if Otvet.ModelString != "" { + t.Error("Test_server_LawsuitStatusType_Create() error: ModelString !=''") + } +} + +func Test_server_LawsuitStatusType_Update(t *testing.T) { + config.LoadEnv() + crud_starter.InitCrudTransport_DB() + + ctx := context.Background() + Request := grpc_proto.RequestId{} + Request.Id = LawsuitStatusType_ID_Test + Request.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + + server1 := &ServerGRPC{} + Response1, err := server1.LawsuitStatusType_Read(ctx, &Request) + if err != nil { + t.Error("Test_server_LawsuitStatusType_Update() error: ", err) + return + } + if Response1.ModelString == "" { + t.Error("Test_server_LawsuitStatusType_Update() error: ModelString=''") + } + + var ModelString string + ModelString = Response1.ModelString + + RequestModel := grpc_proto.RequestModel{} + RequestModel.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + RequestModel.ModelString = ModelString + + Otvet, err := server1.LawsuitStatusType_Update(ctx, &RequestModel) + if err != nil { + t.Error("Test_server_LawsuitStatusType_Update() error: ", err) + } + if Otvet.ModelString == "" { + t.Error("Test_server_LawsuitStatusType_Update() error: ModelString=''") + } + +} + +func Test_server_LawsuitStatusType_Save(t *testing.T) { + config.LoadEnv() + crud_starter.InitCrudTransport_DB() + + ctx := context.Background() + Request := grpc_proto.RequestId{} + Request.Id = LawsuitStatusType_ID_Test + Request.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + + server1 := &ServerGRPC{} + Response1, err := server1.LawsuitStatusType_Read(ctx, &Request) + if err != nil { + t.Error("Test_server_LawsuitStatusType_Save() error: ", err) + return + } + + var ModelString string + ModelString = Response1.ModelString + + // sModel, _ := GetJSON(Otvet) + RequestModel := grpc_proto.RequestModel{} + RequestModel.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + RequestModel.ModelString = ModelString + + Otvet, err := server1.LawsuitStatusType_Save(ctx, &RequestModel) + if err != nil { + t.Error("Test_server_LawsuitStatusType_Save() error: ", err) + } + if Otvet.ModelString == "" { + t.Error("Test_server_LawsuitStatusType_Save() error: ModelString=''") + } + +} + +func Test_server_LawsuitStatusType_FindByExtID(t *testing.T) { + config.LoadEnv() + crud_starter.InitCrudTransport_DB() + + ctx := context.Background() + Request := grpc_proto.RequestId{} + Request.Id = LawsuitStatusType_ID_Test + Request.VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + + server1 := &ServerGRPC{} + Otvet1, err := server1.LawsuitStatusType_Read(ctx, &Request) + if err != nil { + t.Error("Test_server_LawsuitStatusType_FindByExtID() error: ", err) + } + + // получим модель из строки JSON + Model := lawsuit_status_types.LawsuitStatusType{} + err = Model.GetModelFromJSON(Otvet1.ModelString) + if err != nil { + t.Error("Test_server_LawsuitStatusType_FindByExtID() GetModelFromJSON() error: ", err) + } + + if Model.ExtID == 0 { + return + } + + + ctx = context.Background() + 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) + if err != nil { + t.Error("Test_server_LawsuitStatusType_FindByExtId() error: ", err) + } + if Otvet.ModelString == "" { + t.Error("Test_server_LawsuitStatusType_FindByExtId() error: ModelString=''") + } +} diff --git a/examples/crud_service/templates/internal/app/nrpc/server_nrpc/server_nrpc_starter.go_ b/examples/crud_service/templates/internal/app/nrpc/server_nrpc/server_nrpc_starter.go_ new file mode 100644 index 0000000..f5b4fd0 --- /dev/null +++ b/examples/crud_service/templates/internal/app/nrpc/server_nrpc/server_nrpc_starter.go_ @@ -0,0 +1,141 @@ +package server_nrpc + +import ( + "github.com/ManyakRus/starter/contextmain" + "github.com/ManyakRus/starter/log" + "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/internal/app/grpc/server_grpc" + "os" + "strings" + "time" +) + +//// server is used to implement UnimplementedSyncServiceServer. +//type server struct { +//} + +type SettingsINI struct { + NATS_HOST string + NATS_PORT string +} + +var Settings SettingsINI + +// Conn - подключение к NATS +var Conn *nats.Conn + +// NRPCSubscription - подписка на топик NATS +var NRPCSubscription *nats.Subscription + +type server struct{} + +func Connect() { + var err error + + 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(60*time.Second)) + if err != nil { + log.Panic(err) + } + //defer Conn.Close() + + // Our server implementation. + s := &server_grpc.ServerGRPC{} + //s := &server{} + + // The NATS handler from the helloworld.nrpc.proto file. + h := grpc_proto.NewSync_serviceHandler(contextmain.GetContext(), Conn, s) + + // Start a NATS subscription using the handler. You can also use the + // QueueSubscribe() method for a load-balanced set of servers. + NRPCSubscription2, err := Conn.Subscribe(h.Subject(), h.Handler) + if err != nil { + log.Panic(err) + } + if NRPCSubscription2 == nil { + log.Panic(err) + } + NRPCSubscription = NRPCSubscription2 + + log.Info("Server NRPC started. NATS: ", NatsURL) +} + +// FillSettings - заполняет настройки из переменных окружения +func FillSettings() { + Settings = SettingsINI{} + Settings.NATS_HOST = os.Getenv("NATS_HOST") + Settings.NATS_PORT = os.Getenv("NATS_PORT") + + //синонимы + if Settings.NATS_HOST == "" { + Settings.NATS_HOST = os.Getenv("BUS_LOCAL_HOST") + } + + if Settings.NATS_PORT == "" { + Settings.NATS_PORT = os.Getenv("BUS_LOCAL_PORT") + } + + //удалим лишний :порт + if Settings.NATS_PORT != "" { + pos1 := strings.Index(Settings.NATS_HOST, ":") + if pos1 > 0 { + Settings.NATS_HOST = Settings.NATS_HOST[0:pos1] + } + } + + //проверка + if Settings.NATS_HOST == "" { + log.Panic("Need fill BUS_LOCAL_HOST ! in OS Environment ") + } + + if Settings.NATS_PORT == "" { + log.Panic("Need fill BUS_LOCAL_PORT ! in OS Environment ") + } +} + +// WaitStop - ожидает отмену глобального контекста +func WaitStop() { + defer stopapp.GetWaitGroup_Main().Done() + + select { + case <-contextmain.GetContext().Done(): + log.Warn("Context app is canceled. nrpc server connect") + } + + //ждём пока отправляемых сейчас сообщений будет =0 + stopapp.WaitTotalMessagesSendingNow("nrpc server connect") + + //закрываем соединение + CloseConnection() + +} + +// Start - необходимые процедуры для запуска сервера GRPC +func Start() { + Connect() + + stopapp.GetWaitGroup_Main().Add(1) + go WaitStop() + +} + +func CloseConnection() { + if NRPCSubscription != nil { + NRPCSubscription.Unsubscribe() + } + Conn.Close() + log.Info("Server NRPC connection closed") +} + +//func (s *server) Read(ctx context.Context, Reques *grpc_proto.RequestId) *grpc_proto.Response { +// var Otvet *grpc_proto.Response +// +// return Otvet +//} diff --git a/examples/crud_service/templates/internal/app/nrpc/server_nrpc/server_nrpc_starter_test.go b/examples/crud_service/templates/internal/app/nrpc/server_nrpc/server_nrpc_starter_test.go new file mode 100644 index 0000000..696be90 --- /dev/null +++ b/examples/crud_service/templates/internal/app/nrpc/server_nrpc/server_nrpc_starter_test.go @@ -0,0 +1,14 @@ +package server_nrpc + +import ( + config_main "github.com/ManyakRus/starter/config" + "testing" +) + +func TestConnect(t *testing.T) { + config_main.LoadEnv() + FillSettings() + + Connect() + CloseConnection() +} diff --git a/examples/crud_service/templates/pkg/crud_starter/crud_starter_manual.go b/examples/crud_service/templates/pkg/crud_starter/crud_starter_manual.go new file mode 100644 index 0000000..f647a6c --- /dev/null +++ b/examples/crud_service/templates/pkg/crud_starter/crud_starter_manual.go @@ -0,0 +1,15 @@ +package crud_starter + +import () + +// initCrudTransport_manual_DB - заполняет объекты crud для работы с БД напрямую +func initCrudTransport_manual_DB() { +} + +// initCrudTransport_manual_GRPC - заполняет объекты crud для работы с БД напрямую +func initCrudTransport_manual_GRPC() { +} + +// initCrudTransport_manual_NRPC - заполняет объекты crud для работы с БД напрямую +func initCrudTransport_manual_NRPC() { +} diff --git a/examples/crud_service/templates/pkg/db/calc_struct_version/calc_struct_version.go b/examples/crud_service/templates/pkg/db/calc_struct_version/calc_struct_version.go new file mode 100644 index 0000000..ea44705 --- /dev/null +++ b/examples/crud_service/templates/pkg/db/calc_struct_version/calc_struct_version.go @@ -0,0 +1,24 @@ +package calc_struct_version + +import ( + "github.com/ManyakRus/starter/micro" + "reflect" +) + +// CalcStructVersion - вычисляет версию модели +func CalcStructVersion(t reflect.Type) uint32 { + var ReturnVar uint32 + + names := make([]string, t.NumField()) + + // имя + тип поля + s := "" + for i := range names { + s = s + t.Field(i).Name + s = s + t.Field(i).Type.Name() + } + + ReturnVar = micro.Hash(s) + + return ReturnVar +} diff --git a/examples/crud_service/templates/pkg/db/calc_struct_version/calc_struct_version_test.go b/examples/crud_service/templates/pkg/db/calc_struct_version/calc_struct_version_test.go new file mode 100644 index 0000000..b94001d --- /dev/null +++ b/examples/crud_service/templates/pkg/db/calc_struct_version/calc_struct_version_test.go @@ -0,0 +1 @@ +package calc_struct_version diff --git a/examples/crud_service/templates/pkg/db/constants/constants.go b/examples/crud_service/templates/pkg/db/constants/constants.go new file mode 100644 index 0000000..d1deba6 --- /dev/null +++ b/examples/crud_service/templates/pkg/db/constants/constants.go @@ -0,0 +1,15 @@ +package constants + +import ( + "errors" +) + +const CONNECTION_ID_TEST = 3 + +const TIMEOUT_DB_SECONDS = 30 + +const TEXT_RECORD_NOT_FOUND = "record not found" + +const TextCrudIsNotInit = "Need initializate crud with InitCrudTransport_NRPC() function at first." + +var ErrorCrudIsNotInit error = errors.New(TextCrudIsNotInit) diff --git a/examples/crud_service/templates/pkg/db/crud/crud.go_ b/examples/crud_service/templates/pkg/db/crud/crud.go_ new file mode 100644 index 0000000..c4fe2cd --- /dev/null +++ b/examples/crud_service/templates/pkg/db/crud/crud.go_ @@ -0,0 +1,312 @@ +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 + + 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") + // log.Panic(sError) + 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) + // log.Panic(sError) + return err + } + + // + db := postgres_gorm.GetConnection() + db.WithContext(ctx) + + // заполним даты + //Text_modified_at + //Text_is_deleted_deleted_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 + } + + 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 - записывает is_deleted = true +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 + } + + m2 := lawsuit_status_types.LawsuitStatusType{} + m2.ID = m.ID + err = crud.Read_ctx(ctx, &m2) + if err != nil { + return err + } + + m2.IsDeleted = true + m.IsDeleted = true + + err = crud.Save_ctx(ctx, &m2) + + 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) + + 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 + + return err +} diff --git a/examples/crud_service/templates/pkg/db/crud/crud_test.go_ b/examples/crud_service/templates/pkg/db/crud/crud_test.go_ new file mode 100644 index 0000000..875143c --- /dev/null +++ b/examples/crud_service/templates/pkg/db/crud/crud_test.go_ @@ -0,0 +1,124 @@ +package crud_lawsuit_status_types + +import ( + "github.com/ManyakRus/starter/config" + "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.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.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 = Postgres_ID_Test + err := crud.Read(&Otvet) + if err != nil { + t.Error("TestDelete() error: ", err) + } + + if Otvet.IsDeleted == false { + err = crud.Delete(&Otvet) + if err != nil { + t.Error("TestDelete() error: ", err) + } + + err = crud.Restore(&Otvet) + if err != nil { + t.Error("TestDelete() error: ", err) + } + } else { + err = crud.Restore(&Otvet) + if err != nil { + t.Error("TestDelete() error: ", err) + } + + err = crud.Delete(&Otvet) + if err != nil { + t.Error("TestDelete() error: ", err) + } + + } + +} + + +func TestFind_ByExtID(t *testing.T) { + config.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") + } +} diff --git a/examples/crud_service/templates/pkg/db/crud/is_deleted.go_ b/examples/crud_service/templates/pkg/db/crud/is_deleted.go_ new file mode 100644 index 0000000..adc19f4 --- /dev/null +++ b/examples/crud_service/templates/pkg/db/crud/is_deleted.go_ @@ -0,0 +1,5 @@ +if m.IsDeleted == true && m.DeletedAt.IsZero() == true { + m.DeletedAt = time.Now() + } else if m.IsDeleted == false && m.DeletedAt.IsZero() == false { + m.DeletedAt = time.Time{} + } diff --git a/examples/crud_service/templates/pkg/db/crud/modified_at.go_ b/examples/crud_service/templates/pkg/db/crud/modified_at.go_ new file mode 100644 index 0000000..f648e98 --- /dev/null +++ b/examples/crud_service/templates/pkg/db/crud/modified_at.go_ @@ -0,0 +1 @@ +m.ModifiedAt = time.Now() \ No newline at end of file diff --git a/examples/crud_service/templates/pkg/db/crud_functions/crud_functions.go b/examples/crud_service/templates/pkg/db/crud_functions/crud_functions.go new file mode 100644 index 0000000..880d9f0 --- /dev/null +++ b/examples/crud_service/templates/pkg/db/crud_functions/crud_functions.go @@ -0,0 +1,13 @@ +package crud_functions + +import "gorm.io/gorm" + +// MapOmit_from_MassOmit - создает MapOmit из MassOmit +func MapOmit_from_MassOmit(MassOmit []string) map[string]interface{} { + MapOmit := make(map[string]interface{}, 0) + for _, v := range MassOmit { + MapOmit[v] = gorm.Expr("NULL") + } + + return MapOmit +} diff --git a/examples/crud_service/templates/pkg/db/crud_functions/crud_functions_test.go b/examples/crud_service/templates/pkg/db/crud_functions/crud_functions_test.go new file mode 100644 index 0000000..31a80a7 --- /dev/null +++ b/examples/crud_service/templates/pkg/db/crud_functions/crud_functions_test.go @@ -0,0 +1 @@ +package crud_functions diff --git a/examples/crud_service/templates/pkg/db/tables/common_struct.go b/examples/crud_service/templates/pkg/db/tables/common_struct.go new file mode 100644 index 0000000..bf80f25 --- /dev/null +++ b/examples/crud_service/templates/pkg/db/tables/common_struct.go @@ -0,0 +1,18 @@ +package tables + +import ( + "time" +) + +// =========================================================================== +// ===== Объекты ===== +// =========================================================================== + +type CommonStruct struct { + ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement:true"` + ExtID int64 `json:"ext_id" gorm:"column:ext_id;default:null"` + CreatedAt time.Time `json:"created_at" gorm:"column:created_at;autoCreateTime"` + ModifiedAt time.Time `json:"modified_at" gorm:"column:modified_at;autoUpdateTime"` + DeletedAt time.Time `json:"deleted_at" gorm:"column:deleted_at;default:null"` + IsDeleted bool `json:"is_deleted" gorm:"column:is_deleted;default:false"` +} diff --git a/examples/crud_service/templates/pkg/db/tables/ext_link_struct.go b/examples/crud_service/templates/pkg/db/tables/ext_link_struct.go new file mode 100644 index 0000000..272e5d4 --- /dev/null +++ b/examples/crud_service/templates/pkg/db/tables/ext_link_struct.go @@ -0,0 +1,6 @@ +package tables + +type ExtLinkStruct struct { + TableNameID int64 `json:"table_name_id" gorm:"column:table_name_id;default:null"` + TableRowID int64 `json:"table_row_id" gorm:"column:table_row_id;default:null"` +} diff --git a/examples/crud_service/templates/pkg/db/tables/group_struct.go b/examples/crud_service/templates/pkg/db/tables/group_struct.go new file mode 100644 index 0000000..81744c5 --- /dev/null +++ b/examples/crud_service/templates/pkg/db/tables/group_struct.go @@ -0,0 +1,6 @@ +package tables + +type GroupStruct struct { + IsGroup bool `json:"is_group" gorm:"column:is_group;default:false"` + ParentID int64 `json:"parent_id" gorm:"column:parent_id;default:null"` +} diff --git a/examples/crud_service/templates/pkg/db/tables/name_struct.go b/examples/crud_service/templates/pkg/db/tables/name_struct.go new file mode 100644 index 0000000..9310c26 --- /dev/null +++ b/examples/crud_service/templates/pkg/db/tables/name_struct.go @@ -0,0 +1,10 @@ +package tables + +// =========================================================================== +// ===== Списки ===== +// =========================================================================== + +type NameStruct struct { + Description string `json:"description" gorm:"column:description;default:\"\""` + Name string `json:"name" gorm:"column:name;default:\"\""` +} diff --git a/examples/crud_service/templates/pkg/db/tables/table.go_ b/examples/crud_service/templates/pkg/db/tables/table.go_ new file mode 100644 index 0000000..b5c4ead --- /dev/null +++ b/examples/crud_service/templates/pkg/db/tables/table.go_ @@ -0,0 +1,12 @@ +package table_lawsuit_status_types + +import ( + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/tables" +) + +// LawsuitStatusType +type LawsuitStatusType struct { + tables.CommonStruct + tables.NameStruct + Code string `json:"code" gorm:"column:code;default:0"` +} diff --git a/examples/crud_service/templates/pkg/network/grpc/constants/constants.go b/examples/crud_service/templates/pkg/network/grpc/constants/constants.go new file mode 100644 index 0000000..809887d --- /dev/null +++ b/examples/crud_service/templates/pkg/network/grpc/constants/constants.go @@ -0,0 +1,5 @@ +package constants + +var TIMEOUT_SECONDS = 30 + +const TEXT_ERROR_MODEL_VERSION = "Error: wrong version object model" diff --git a/examples/crud_service/templates/pkg/network/grpc/grpc_client/grpc_client.go_ b/examples/crud_service/templates/pkg/network/grpc/grpc_client/grpc_client.go_ new file mode 100644 index 0000000..ecb859e --- /dev/null +++ b/examples/crud_service/templates/pkg/network/grpc/grpc_client/grpc_client.go_ @@ -0,0 +1,106 @@ +package grpc_client + +import ( + "github.com/ManyakRus/starter/contextmain" + "github.com/ManyakRus/starter/log" + "github.com/ManyakRus/starter/stopapp" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/constants" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_proto" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "os" + "strings" +) + +type SettingsINI struct { + SYNC_SERVICE_HOST string + SYNC_SERVICE_PORT string +} + +var Settings SettingsINI + +var Conn *grpc.ClientConn +var Client grpc_proto.SyncServiceClient + +func Connect() { + var err error + + if Settings.SYNC_SERVICE_HOST == "" { + FillSettings() + } + + 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) + } + + log.Info("GRPC client connected. Address: ", addr) + + Client = grpc_proto.NewSyncServiceClient(Conn) +} + +func FillSettings() { + 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 ") + } + + if Settings.SYNC_SERVICE_PORT == "" { + log.Panic("Need fill SYNC_SERVICE_PORT ! in OS Environment ") + } +} + +// WaitStop - ожидает отмену глобального контекста +func WaitStop() { + + select { + case <-contextmain.GetContext().Done(): + log.Warn("Context app is canceled. grpc_connect") + } + + // ждём пока отправляемых сейчас сообщений будет =0 + stopapp.WaitTotalMessagesSendingNow("sync_service_client") + + // закрываем соединение + CloseConnection() + stopapp.GetWaitGroup_Main().Done() +} + +// Start - необходимые процедуры для запуска сервера GRPC +func Start() { + Connect() + + stopapp.GetWaitGroup_Main().Add(1) + go WaitStop() + +} + +func CloseConnection() { + err := Conn.Close() + if err != nil { + log.Panic("GRPC client CloseConnection() error: ", err) + } else { + log.Info("GRPC client connection closed") + } +} + +// IsRecordNotFound - возвращает true если ошибка = "record not found" +func IsRecordNotFound(err error) bool { + Otvet := false + + if err == nil { + return Otvet + } + + TextErr := err.Error() + pos1 := strings.Index(TextErr, constants.TEXT_RECORD_NOT_FOUND) + if pos1 >= 0 { + Otvet = true + } + + return Otvet +} diff --git a/examples/crud_service/templates/pkg/network/grpc/grpc_client/grpc_client_table.go_ b/examples/crud_service/templates/pkg/network/grpc/grpc_client/grpc_client_table.go_ new file mode 100644 index 0000000..5cfc11c --- /dev/null +++ b/examples/crud_service/templates/pkg/network/grpc/grpc_client/grpc_client_table.go_ @@ -0,0 +1,321 @@ +package grpc_lawsuit_status_types + +import ( + "context" + "encoding/json" + "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/object_model/entities/lawsuit_status_types" + "log" + "time" +) + +// VersionModel - хранит версию структуры модели +var VersionModel uint32 + +// TableName - имя таблицы в БД Postgres +const TableName string = "lawsuit_status_types" + +// объект для CRUD операций через GRPC +type Crud_GRPC struct { +} + +// GetVersionModel - возвращает хэш версии структуры модели +func (crud Crud_GRPC) GetVersionModel() uint32 { + if VersionModel == 0 { + VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + } + return VersionModel +} + +// Read - возвращает модель из БД +func (crud Crud_GRPC) Read(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if grpc_client.Client == nil { + grpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + Request := &grpc_proto.RequestId{} + Request.Id = int64(m.ID) + Request.VersionModel = VersionModel + + ctxMain := context.Background() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_SECONDS)) + defer ctxCancelFunc() + + // запрос + 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 { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Create - записывает новую модель в БД +func (crud Crud_GRPC) Create(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if grpc_client.Client == nil { + grpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + ModelString, err := m.GetJSON() + if err != nil { + return err + } + Request := &grpc_proto.RequestModel{} + Request.ModelString = ModelString + Request.VersionModel = VersionModel + + ctxMain := context.Background() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_SECONDS)) + defer ctxCancelFunc() + + // запрос + 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 { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Update - обновляет модель в БД +func (crud Crud_GRPC) Update(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if grpc_client.Client == nil { + grpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + ModelString, err := m.GetJSON() + if err != nil { + return err + } + Request := &grpc_proto.RequestModel{} + Request.ModelString = ModelString + Request.VersionModel = VersionModel + + ctxMain := context.Background() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_SECONDS)) + defer ctxCancelFunc() + + // запрос + 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 { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Save - обновляет (или создаёт) модель в БД +func (crud Crud_GRPC) Save(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if grpc_client.Client == nil { + grpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + ModelString, err := m.GetJSON() + if err != nil { + return err + } + Request := &grpc_proto.RequestModel{} + Request.ModelString = ModelString + Request.VersionModel = VersionModel + + ctxMain := context.Background() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_SECONDS)) + defer ctxCancelFunc() + + // запрос + 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 { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Delete - устанавливает is_deleted = true в БД +func (crud Crud_GRPC) Delete(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if grpc_client.Client == nil { + grpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + Request := &grpc_proto.RequestId{} + Request.Id = int64(m.ID) + Request.VersionModel = VersionModel + + ctxMain := context.Background() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_SECONDS)) + defer ctxCancelFunc() + + // запрос + 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 { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Restore - устанавливает is_deleted = false в БД +func (crud Crud_GRPC) Restore(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if grpc_client.Client == nil { + grpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + Request := &grpc_proto.RequestId{} + Request.Id = int64(m.ID) + Request.VersionModel = VersionModel + + ctxMain := context.Background() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_SECONDS)) + defer ctxCancelFunc() + + // запрос + 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 { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Find_ByExtID - находит модель в БД по ext_id и connection_id +func (crud Crud_GRPC) Find_ByExtID(m *lawsuit_status_types.LawsuitStatusType) error { + //подключение + if grpc_client.Client == nil { + grpc_client.Connect() + } + + //подготовка запроса + var VersionModel = crud.GetVersionModel() + + 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)) + defer ctxCancelFunc() + + //запрос + 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 { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + //ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} diff --git a/examples/crud_service/templates/pkg/network/grpc/grpc_client/grpc_client_table_test.go_ b/examples/crud_service/templates/pkg/network/grpc/grpc_client/grpc_client_table_test.go_ new file mode 100644 index 0000000..2bd2c6d --- /dev/null +++ b/examples/crud_service/templates/pkg/network/grpc/grpc_client/grpc_client_table_test.go_ @@ -0,0 +1,184 @@ +package grpc_lawsuit_status_types + +import ( + config "github.com/ManyakRus/starter/config" + "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" + "testing" +) + +// Postgres_ID_Test - ID таблицы для тестирования +const Postgres_ID_Test = 1 + +func TestGetVersionModel(t *testing.T) { + + crud := Crud_GRPC{} + Otvet := crud.GetVersionModel() + if Otvet == 0 { + t.Error("TestGetVersionModel() error: Otvet =0") + } +} + +func TestRead(t *testing.T) { + config.LoadEnv() + grpc_client.Connect() + defer grpc_client.CloseConnection() + + crud := Crud_GRPC{} + 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("TestRead() error: ID =0") + } +} + +func TestCreate(t *testing.T) { + config.LoadEnv() + grpc_client.Connect() + defer grpc_client.CloseConnection() + + Model := lawsuit_status_types.LawsuitStatusType{} + Model.ID = -1 + + crud := Crud_GRPC{} + err := crud.Create(&Model) + + if err == nil { + t.Error("TestCreate() error: ", err) + } + + if Model.ID > 0 { + t.Error("TestCreate() error: ID >0") + } +} + +func TestUpdate(t *testing.T) { + config.LoadEnv() + grpc_client.Connect() + defer grpc_client.CloseConnection() + + Model := lawsuit_status_types.LawsuitStatusType{} + Model.ID = 0 + + crud := Crud_GRPC{} + err := crud.Update(&Model) + + if err == nil { + t.Error("TestUpdate() error: ", err) + } + + if Model.ID != 0 { + t.Error("TestUpdate() error: ID =0") + } +} + +func TestSave(t *testing.T) { + config.LoadEnv() + grpc_client.Connect() + defer grpc_client.CloseConnection() + + crud := Crud_GRPC{} + Otvet := lawsuit_status_types.LawsuitStatusType{} + Otvet.ID = Postgres_ID_Test + err := crud.Read(&Otvet) + if err != nil { + t.Error("TestSave() error: ", err) + return + } + + err = crud.Save(&Otvet) + + if err != nil { + t.Error("TestSave() error: ", err) + } + + if Otvet.ID == 0 { + t.Error("TestSave() error: ID =0") + } +} + +func TestDelete(t *testing.T) { + config.LoadEnv() + grpc_client.Connect() + defer grpc_client.CloseConnection() + + crud := Crud_GRPC{} + Otvet := lawsuit_status_types.LawsuitStatusType{} + 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) { + config.LoadEnv() + grpc_client.Connect() + defer grpc_client.CloseConnection() + + crud := Crud_GRPC{} + Otvet1 := lawsuit_status_types.LawsuitStatusType{} + Otvet1.ID = Postgres_ID_Test + err := crud.Read(&Otvet1) + + if err != nil { + t.Error("TestFind_ByExtID() error: ", err) + } + + if Otvet1.ExtID == 0 { + return + } + + Otvet := lawsuit_status_types.LawsuitStatusType{} + Otvet.ExtID = Otvet1.ExtID + Otvet.ConnectionID = Otvet1.ConnectionID + err = crud.Find_ByExtID(&Otvet) + + if err != nil { + t.Error("TestFindByExtID() error: ", err) + } + + if Otvet.ID == 0 { + t.Error("TestFindByExtID() error: ID =0") + } +} diff --git a/examples/crud_service/templates/pkg/network/grpc/grpc_client/grpc_client_test.go_ b/examples/crud_service/templates/pkg/network/grpc/grpc_client/grpc_client_test.go_ new file mode 100644 index 0000000..cf46fa7 --- /dev/null +++ b/examples/crud_service/templates/pkg/network/grpc/grpc_client/grpc_client_test.go_ @@ -0,0 +1,23 @@ +package grpc_client + +import ( + "errors" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/constants" + "testing" +) + +func TestIsRecordNotFound(t *testing.T) { + + err := errors.New(constants.TEXT_RECORD_NOT_FOUND + " !") + Otvet := IsRecordNotFound(err) + if Otvet != true { + t.Error("TestIsRecordNotFound() error: false") + } + + err = errors.New("rpc error: code = Unknown desc = record not found") + Otvet = IsRecordNotFound(err) + if Otvet != true { + t.Error("TestIsRecordNotFound() error: false") + } + +} diff --git a/examples/crud_service/templates/pkg/network/nrpc/nrpc_client/nrpc_client.go_ b/examples/crud_service/templates/pkg/network/nrpc/nrpc_client/nrpc_client.go_ new file mode 100644 index 0000000..155205e --- /dev/null +++ b/examples/crud_service/templates/pkg/network/nrpc/nrpc_client/nrpc_client.go_ @@ -0,0 +1,124 @@ +package nrpc_client + +import ( + "github.com/ManyakRus/starter/contextmain" + "github.com/ManyakRus/starter/log" + "github.com/ManyakRus/starter/stopapp" + "github.com/nats-io/nats.go" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/constants" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/network/grpc/grpc_proto" + + "os" + "strings" + "time" +) + +type SettingsINI struct { + NATS_HOST string + NATS_PORT string +} + +var Settings SettingsINI + +// Conn - подключение к NATS +var Conn *nats.Conn + +// Client - подключение к клиенту NRPC +var Client *grpc_proto.Sync_serviceClient + +// Connect - подключается к NATS +func Connect() { + var err error + + 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) + } + // defer Conn.Close() + + // This is our generated client. + Client = grpc_proto.NewSync_serviceClient(Conn) + + log.Info("Client NRPC connected: ", NatsURL) +} + +// FillSettings - заполняет настройки из переменных окружения +func FillSettings() { + Settings = SettingsINI{} + Settings.NATS_HOST = os.Getenv("NATS_HOST") + Settings.NATS_PORT = os.Getenv("NATS_PORT") + + //синонимы + if Settings.NATS_HOST == "" { + Settings.NATS_HOST = os.Getenv("BUS_LOCAL_HOST") + } + + if Settings.NATS_PORT == "" { + Settings.NATS_PORT = os.Getenv("BUS_LOCAL_PORT") + } + + + if Settings.NATS_HOST == "" { + log.Panic("Need fill BUS_LOCAL_HOST ! in OS Environment ") + } + + if Settings.NATS_PORT == "" { + log.Panic("Need fill BUS_LOCAL_PORT ! in OS Environment ") + } +} + +// WaitStop - ожидает отмену глобального контекста +func WaitStop() { + + select { + case <-contextmain.GetContext().Done(): + log.Warn("Context app is canceled. nrpc client connect") + } + + // ждём пока отправляемых сейчас сообщений будет =0 + stopapp.WaitTotalMessagesSendingNow("sync_service_client") + + // закрываем соединение + CloseConnection() + stopapp.GetWaitGroup_Main().Done() +} + +// Start - необходимые процедуры для запуска сервера NRPC +func Start() { + Connect() + + stopapp.GetWaitGroup_Main().Add(1) + go WaitStop() + +} + +// CloseConnection - закрывает подключение к NATS +func CloseConnection() { + Conn.Close() + log.Info("NRPC client connection closed") +} + +// IsRecordNotFound - возвращает true если ошибка = "record not found" +func IsRecordNotFound(err error) bool { + Otvet := false + + if err == nil { + return Otvet + } + + // len1 := len(constants.TEXT_RECORD_NOT_FOUND) + TextErr := err.Error() + pos1 := strings.Index(TextErr, constants.TEXT_RECORD_NOT_FOUND) + // if TextErr[0:len1] == constants.TEXT_RECORD_NOT_FOUND { + if pos1 >= 0 { + Otvet = true + } + + return Otvet +} diff --git a/examples/crud_service/templates/pkg/network/nrpc/nrpc_client/nrpc_client_table.go_ b/examples/crud_service/templates/pkg/network/nrpc/nrpc_client/nrpc_client_table.go_ new file mode 100644 index 0000000..11c56af --- /dev/null +++ b/examples/crud_service/templates/pkg/network/nrpc/nrpc_client/nrpc_client_table.go_ @@ -0,0 +1,291 @@ +package nrpc_lawsuit_status_types + +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/object_model/entities/lawsuit_status_types" + "log" +) + +// VersionModel - хранит версию структуры модели +var VersionModel uint32 + +// TableName - имя таблицы в БД Postgres +const TableName string = "lawsuit_status_types" + +// объект для CRUD операций через GRPC +type Crud_NRPC struct { +} + +// GetVersionModel - возвращает хэш версии структуры модели +func (crud Crud_NRPC) GetVersionModel() uint32 { + if VersionModel == 0 { + VersionModel = lawsuit_status_types.LawsuitStatusType{}.GetStructVersion() + } + return VersionModel +} + +// Read - возвращает модель из БД +func (crud Crud_NRPC) Read(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if nrpc_client.Client == nil { + nrpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + Request := &grpc_proto.RequestId{} + Request.Id = int64(m.ID) + Request.VersionModel = VersionModel + + // запрос + Response, err := nrpc_client.Client.LawsuitStatusType_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 { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Create - записывает новую модель в БД +func (crud Crud_NRPC) Create(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if nrpc_client.Client == nil { + nrpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + ModelString, err := m.GetJSON() + if err != nil { + return err + } + Request := &grpc_proto.RequestModel{} + Request.ModelString = ModelString + Request.VersionModel = VersionModel + + // запрос + Response, err := nrpc_client.Client.LawsuitStatusType_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 { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Update - обновляет модель в БД +func (crud Crud_NRPC) Update(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if nrpc_client.Client == nil { + nrpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + ModelString, err := m.GetJSON() + if err != nil { + return err + } + Request := &grpc_proto.RequestModel{} + Request.ModelString = ModelString + Request.VersionModel = VersionModel + + // запрос + Response, err := nrpc_client.Client.LawsuitStatusType_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 { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Save - обновляет (или создаёт) модель в БД +func (crud Crud_NRPC) Save(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if nrpc_client.Client == nil { + nrpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + ModelString, err := m.GetJSON() + if err != nil { + return err + } + Request := &grpc_proto.RequestModel{} + Request.ModelString = ModelString + Request.VersionModel = VersionModel + + // запрос + Response, err := nrpc_client.Client.LawsuitStatusType_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 { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Delete - устанавливает is_deleted = true в БД +func (crud Crud_NRPC) Delete(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if nrpc_client.Client == nil { + nrpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + Request := &grpc_proto.RequestId{} + Request.Id = int64(m.ID) + Request.VersionModel = VersionModel + + // запрос + Response, err := nrpc_client.Client.LawsuitStatusType_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 { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Restore - устанавливает is_deleted = false в БД +func (crud Crud_NRPC) Restore(m *lawsuit_status_types.LawsuitStatusType) error { + // var Otvet lawsuit_status_types.LawsuitStatusType + + // подключение + if nrpc_client.Client == nil { + nrpc_client.Connect() + } + + // подготовка запроса + var VersionModel = crud.GetVersionModel() + + Request := &grpc_proto.RequestId{} + Request.Id = int64(m.ID) + Request.VersionModel = VersionModel + + // запрос + Response, err := nrpc_client.Client.LawsuitStatusType_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 { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + // ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} + +// Find_ByExtID - находит модель в БД по ext_id и connection_id +func (crud Crud_NRPC) Find_ByExtID(m *lawsuit_status_types.LawsuitStatusType) error { + //подключение + if nrpc_client.Client == nil { + nrpc_client.Connect() + } + + //подготовка запроса + var VersionModel = crud.GetVersionModel() + + Request := &grpc_proto.RequestExtId{} + Request.ExtId = m.ExtID + Request.ConnectionId = m.ConnectionID + Request.VersionModel = VersionModel + + //запрос + Response, err := nrpc_client.Client.LawsuitStatusType_FindByExtID(Request) + if err != nil { + sError := err.Error() + if sError[0:len(constants.TEXT_ERROR_MODEL_VERSION)] == constants.TEXT_ERROR_MODEL_VERSION { + log.Panic("table: ", TableName, " error: ", err) + } + return err + } + + //ответ + sModel := Response.ModelString + err = json.Unmarshal([]byte(sModel), m) + if err != nil { + return err + } + + return err +} diff --git a/examples/crud_service/templates/pkg/network/nrpc/nrpc_client/nrpc_client_table_test.go_ b/examples/crud_service/templates/pkg/network/nrpc/nrpc_client/nrpc_client_table_test.go_ new file mode 100644 index 0000000..8e58f6a --- /dev/null +++ b/examples/crud_service/templates/pkg/network/nrpc/nrpc_client/nrpc_client_table_test.go_ @@ -0,0 +1,184 @@ +package nrpc_lawsuit_status_types + +import ( + config "github.com/ManyakRus/starter/config" + "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" +) + +// Postgres_ID_Test - ID таблицы для тестирования +const Postgres_ID_Test = 1 + +func TestGetVersionModel(t *testing.T) { + + crud := Crud_NRPC{} + Otvet := crud.GetVersionModel() + if Otvet == 0 { + t.Error("TestGetVersionModel() error: Otvet =0") + } +} + +func TestRead(t *testing.T) { + config.LoadEnv() + nrpc_client.Connect() + defer nrpc_client.CloseConnection() + + crud := Crud_NRPC{} + 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("TestRead() error: ID =0") + } +} + +func TestCreate(t *testing.T) { + config.LoadEnv() + nrpc_client.Connect() + defer nrpc_client.CloseConnection() + + Model := lawsuit_status_types.LawsuitStatusType{} + Model.ID = -1 + + crud := Crud_NRPC{} + err := crud.Create(&Model) + + if err == nil { + t.Error("TestCreate() error: ", err) + } + + if Model.ID > 0 { + t.Error("TestCreate() error: ID >0") + } +} + +func TestUpdate(t *testing.T) { + config.LoadEnv() + nrpc_client.Connect() + defer nrpc_client.CloseConnection() + + Model := lawsuit_status_types.LawsuitStatusType{} + Model.ID = 0 + + crud := Crud_NRPC{} + err := crud.Update(&Model) + + if err == nil { + t.Error("TestUpdate() error: ", err) + } + + if Model.ID != 0 { + t.Error("TestUpdate() error: ID =0") + } +} + +func TestSave(t *testing.T) { + config.LoadEnv() + nrpc_client.Connect() + defer nrpc_client.CloseConnection() + + crud := Crud_NRPC{} + Otvet := lawsuit_status_types.LawsuitStatusType{} + Otvet.ID = Postgres_ID_Test + err := crud.Read(&Otvet) + if err != nil { + t.Error("TestSave() error: ", err) + return + } + + err = crud.Save(&Otvet) + + if err != nil { + t.Error("TestSave() error: ", err) + } + + if Otvet.ID == 0 { + t.Error("TestSave() error: ID =0") + } +} + +func TestDelete(t *testing.T) { + config.LoadEnv() + nrpc_client.Connect() + defer nrpc_client.CloseConnection() + + crud := Crud_NRPC{} + Otvet := lawsuit_status_types.LawsuitStatusType{} + 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) { + config.LoadEnv() + nrpc_client.Connect() + defer nrpc_client.CloseConnection() + + crud := Crud_NRPC{} + Otvet1 := lawsuit_status_types.LawsuitStatusType{} + Otvet1.ID = Postgres_ID_Test + err := crud.Read(&Otvet1) + + if err != nil { + t.Error("TestFind_ByExtID() error: ", err) + } + + if Otvet1.ExtID == 0 { + return + } + + Otvet := lawsuit_status_types.LawsuitStatusType{} + Otvet.ExtID = Otvet1.ExtID + Otvet.ConnectionID = Otvet1.ConnectionID + err = crud.Find_ByExtID(&Otvet) + + if err != nil { + t.Error("TestFindByExtId() error: ", err) + } + + if Otvet.ID == 0 { + t.Error("TestFindByExtId() error: ID =0") + } +} diff --git a/examples/crud_service/templates/pkg/network/nrpc/nrpc_client/nrpc_client_test.go_ b/examples/crud_service/templates/pkg/network/nrpc/nrpc_client/nrpc_client_test.go_ new file mode 100644 index 0000000..1e01603 --- /dev/null +++ b/examples/crud_service/templates/pkg/network/nrpc/nrpc_client/nrpc_client_test.go_ @@ -0,0 +1,13 @@ +package nrpc_client + +import ( + "github.com/ManyakRus/starter/config" + "testing" +) + +func TestConnect(t *testing.T) { + config.LoadEnv() + FillSettings() + Connect() + CloseConnection() +} diff --git a/examples/crud_service/templates/pkg/object_model/entities/model.go_ b/examples/crud_service/templates/pkg/object_model/entities/model.go_ new file mode 100644 index 0000000..75d8282 --- /dev/null +++ b/examples/crud_service/templates/pkg/object_model/entities/model.go_ @@ -0,0 +1,10 @@ +package lawsuit_status_types + +import ( + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/tables/table_lawsuit_status_types" +) + +// LawsuitStatusType +type LawsuitStatusType struct { + table_lawsuit_status_types.Table_LawsuitStatusType +} diff --git a/examples/crud_service/templates/pkg/object_model/entities/model_crud.go_ b/examples/crud_service/templates/pkg/object_model/entities/model_crud.go_ new file mode 100644 index 0000000..d00a2b5 --- /dev/null +++ b/examples/crud_service/templates/pkg/object_model/entities/model_crud.go_ @@ -0,0 +1,177 @@ +package lawsuit_status_types + +import ( + "encoding/json" + "github.com/vmihailenco/msgpack/v5" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/calc_struct_version" + "reflect" + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/constants" +) + +// versionLawsuitStatusType - версия структуры модели, с учётом имен и типов полей +var versionLawsuitStatusType uint32 + +// crud_LawsuitStatusType - объект контроллер crud операций +var crud_LawsuitStatusType ICrud_LawsuitStatusType + +// интерфейс стандартных CRUD операций, для использования в DB или GRPC или NRPC +type ICrud_LawsuitStatusType interface { + Read(*LawsuitStatusType) error + Save(*LawsuitStatusType) error + Update(*LawsuitStatusType) error + Create(*LawsuitStatusType) error + Delete(*LawsuitStatusType) error + Restore(*LawsuitStatusType) error + Find_ByExtID(*LawsuitStatusType) error +} + +// TableName - возвращает имя таблицы в БД, нужен для gorm +func (m LawsuitStatusType) TableNameDB() string { + return "lawsuit_status_types" +} + +// NewLawsuitStatusType - возвращает новый объект +func NewLawsuitStatusType() LawsuitStatusType { + return LawsuitStatusType{} +} + +// AsLawsuitStatusType - создаёт объект из упакованного объекта в массиве байтов +func AsLawsuitStatusType(b []byte) (LawsuitStatusType, error) { + c := NewLawsuitStatusType() + err := msgpack.Unmarshal(b, &c) + if err != nil { + return NewLawsuitStatusType(), err + } + return c, nil +} + +// LawsuitStatusTypeAsBytes - упаковывает объект в массив байтов +func LawsuitStatusTypeAsBytes(m *LawsuitStatusType) ([]byte, error) { + b, err := msgpack.Marshal(m) + if err != nil { + return nil, err + } + return b, nil +} + +// GetStructVersion - возвращает версию модели +func (m LawsuitStatusType) GetStructVersion() uint32 { + if versionLawsuitStatusType == 0 { + versionLawsuitStatusType = calc_struct_version.CalcStructVersion(reflect.TypeOf(m)) + } + + return versionLawsuitStatusType +} + +// GetModelFromJSON - создаёт модель из строки json +func (m *LawsuitStatusType) GetModelFromJSON(sModel string) error { + var err error + + var bytes []byte + bytes = []byte(sModel) + + err = json.Unmarshal(bytes, m) + + return err +} + +// GetJSON - возвращает строку json из модели +func (m LawsuitStatusType) GetJSON() (string, error) { + var ReturnVar string + var err error + + bytes, err := json.Marshal(m) + if err != nil { + return ReturnVar, err + } + ReturnVar = string(bytes) + return ReturnVar, err +} + +// ---------------------------- CRUD операции ------------------------------------------------------------ + +// Read - находит запись в БД по ID, и заполняет в объект +func (m *LawsuitStatusType) Read() error { + if crud_LawsuitStatusType == nil { + return constants.ErrorCrudIsNotInit + } + + err := crud_LawsuitStatusType.Read(m) + + return err +} + +// Save - записывает объект в БД по ID +func (m *LawsuitStatusType) Save() error { + if crud_LawsuitStatusType == nil { + return constants.ErrorCrudIsNotInit + } + + err := crud_LawsuitStatusType.Save(m) + + return err +} + +// Update - обновляет объект в БД по ID +func (m *LawsuitStatusType) Update() error { + if crud_LawsuitStatusType == nil { + return constants.ErrorCrudIsNotInit + } + + err := crud_LawsuitStatusType.Update(m) + + return err +} + +// Create - создаёт объект в БД с новым ID +func (m *LawsuitStatusType) Create() error { + if crud_LawsuitStatusType == nil { + return constants.ErrorCrudIsNotInit + } + + err := crud_LawsuitStatusType.Create(m) + + return err +} + +// Delete - устанавливает признак пометки удаления в БД +func (m *LawsuitStatusType) Delete() error { + if crud_LawsuitStatusType == nil { + return constants.ErrorCrudIsNotInit + } + + err := crud_LawsuitStatusType.Delete(m) + + return err +} + +// Restore - снимает признак пометки удаления в БД +func (m *LawsuitStatusType) Restore() error { + if crud_LawsuitStatusType == nil { + return constants.ErrorCrudIsNotInit + } + + err := crud_LawsuitStatusType.Restore(m) + + return err +} + +// Find_ByExtID - находит объект по ExtID +func (m *LawsuitStatusType) Find_ByExtID() error { + if crud_LawsuitStatusType == nil { + return constants.ErrorCrudIsNotInit + } + + err := crud_LawsuitStatusType.Find_ByExtID(m) + + return err +} + +// SetCrudInterface - заполняет интерфейс crud: DB, GRPC, NRPC +func (m LawsuitStatusType) SetCrudInterface(crud ICrud_LawsuitStatusType) { + crud_LawsuitStatusType = crud + + return +} + +// ---------------------------- конец CRUD операции ------------------------------------------------------------ diff --git a/examples/crud_service/templates/pkg/object_model/types/alias/alias.go b/examples/crud_service/templates/pkg/object_model/types/alias/alias.go new file mode 100644 index 0000000..4007f5d --- /dev/null +++ b/examples/crud_service/templates/pkg/object_model/types/alias/alias.go @@ -0,0 +1,35 @@ +// Package alias -- специальные типы РАПИРы +package alias + +// PaymentId -- ID платёжки +type PaymentId int64 + +// InvoiceId -- ID счёт-фактуры +type InvoiceId int64 + +// LawsuitId -- ID претензии +type LawsuitId int64 + +// LawsuitNumber -- номер претензии +type LawsuitNumber string + +// ClaimNumber -- Номер дела +type ClaimNumber string + +// TrialNumber -- Номер иска +type TrialNumber string + +// ContractNumber -- Номер договора +type ContractNumber string + +// FrontDate -- специальный тип даты для фронта +type FrontDate string + +// FrontTime -- специальный тип даты-времени для фронта +type FrontTime string + +// PaymentRegisteredAt -- тип даты времени при регистрации в системе +type PaymentRegisteredAt string + +// IsAfterNotify -- признак регистрации документа после уведомления +type IsAfterNotify bool diff --git a/examples/crud_service/templates/scripts/VersionToFile.py b/examples/crud_service/templates/scripts/VersionToFile.py new file mode 100755 index 0000000..c768562 --- /dev/null +++ b/examples/crud_service/templates/scripts/VersionToFile.py @@ -0,0 +1,52 @@ +#!/usr/bin/python3 +# Python script to create an empty file +# with current date as name. + +# importing datetime module +from datetime import datetime +import os + +# datetime.datetime.now() to get +# current date as filename. +# TimeNow = datetime.datetime.now() + +FILESUBVERSION="../bin/subversion.txt" +FILEDATE="../bin/date.txt" + +# create empty file +def create_file(): + fmt = "%Y-%m-%d %H:%M:%S.%f" + str1 = datetime.utcnow().strftime(fmt)[:-3] + + # Function creates an empty file + # %d - date, %B - month, %Y - Year + with open(FILEDATE, "w") as file: + file.write(str1) + file.close() + +def set_version(): + filename=FILESUBVERSION + build=0 + mode = 'r' if os.path.exists(filename) else 'w+' + with open(filename, encoding="utf8", mode=mode) as file_in: + _str_build = file_in.read() + file_in.close() + try: + build = int(_str_build) + except ValueError as err: + print("Build.__setVers(): при конвертировании строки в число, err=", err) + finally: + pass + build += 1 + str_build = str(build) + while len(str_build) < 5: + str_build = "0" + str_build + print("Build.set_version(): new build=", str_build) + with open(filename, "w", encoding="utf8") as file_in: + file_in.write(str_build) + file_in.close() + + +# Driver Code +create_file() +set_version() \ No newline at end of file diff --git a/internal/create_files/create_files.go b/internal/create_files/create_files.go index 277909a..60f2cde 100644 --- a/internal/create_files/create_files.go +++ b/internal/create_files/create_files.go @@ -383,7 +383,7 @@ func FindCalcStructVersionURL() string { func FindCrudFunctionsURL() string { Otvet := "" - Otvet = config.Settings.SERVICE_REPOSITORY_URL + "/" + config.Settings.TEMPLATE_FOLDERNAME_DB + "/" + "crud_functions" + Otvet = config.Settings.SERVICE_REPOSITORY_URL + "/" + config.Settings.TEMPLATE_FOLDER_CRUD_FUNCTIONS return Otvet }