diff --git a/bin/templates/configs_/settings.txt b/bin/templates/configs_/settings.txt index 6647da1..667ff6b 100644 --- a/bin/templates/configs_/settings.txt +++ b/bin/templates/configs_/settings.txt @@ -21,15 +21,15 @@ DB_PASSWORD= INCLUDE_TABLES="" #INCLUDE_TABLES - table name ignore filter. Regular expression -EXCLUDE_TABLES="ext_" +EXCLUDE_TABLES= #---------------------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_REPOSITORY_URL="gitlab.aescorp.ru/dsp_dev/claim/crud_service" #SERVICE_NAME - service name for your new service -SERVICE_NAME=sync_service +SERVICE_NAME=crud_service #TEMPLATE_SERVICE_NAME - service name in your template files TEMPLATE_SERVICE_NAME=sync_service @@ -96,7 +96,7 @@ TEXT_TEMPLATE_TABLENAME="lawsuit_status_types" USE_DEFAULT_TEMPLATE=true #HAS_IS_DELETED - fill "true" if you have "is_deleted" column, and want Delete() Restore() functions. -HAS_IS_DELETED=true +HAS_IS_DELETED=false #---------------------Create files settings--------------------- diff --git a/examples/default/templates/.env_ b/examples/default/templates/.env_ new file mode 100644 index 0000000..096eab9 --- /dev/null +++ b/examples/default/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/default/templates/.gitignore b/examples/default/templates/.gitignore new file mode 100644 index 0000000..c270948 --- /dev/null +++ b/examples/default/templates/.gitignore @@ -0,0 +1,7 @@ +.env +/bin/.env + +/.idea/ +.vscode +/log.txt +cover.out diff --git a/examples/default/templates/Makefile_ b/examples/default/templates/Makefile_ new file mode 100644 index 0000000..b8896c4 --- /dev/null +++ b/examples/default/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/default/templates/api/generation_code.sh_ b/examples/default/templates/api/generation_code.sh_ new file mode 100755 index 0000000..7c46f85 --- /dev/null +++ b/examples/default/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/default/templates/api/service.proto_ b/examples/default/templates/api/service.proto_ new file mode 100644 index 0000000..99d9d88 --- /dev/null +++ b/examples/default/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/default/templates/bin/date.txt b/examples/default/templates/bin/date.txt new file mode 100644 index 0000000..99a18f2 --- /dev/null +++ b/examples/default/templates/bin/date.txt @@ -0,0 +1 @@ +2023-11-15 12:11:15.838 \ No newline at end of file diff --git a/examples/default/templates/bin/settings.txt b/examples/default/templates/bin/settings.txt new file mode 100644 index 0000000..01ca9cb --- /dev/null +++ b/examples/default/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/default/templates/bin/subversion.txt b/examples/default/templates/bin/subversion.txt new file mode 100644 index 0000000..4424fb1 --- /dev/null +++ b/examples/default/templates/bin/subversion.txt @@ -0,0 +1 @@ +00133 \ No newline at end of file diff --git a/examples/default/templates/bin/version.txt b/examples/default/templates/bin/version.txt new file mode 100644 index 0000000..a5e11e5 --- /dev/null +++ b/examples/default/templates/bin/version.txt @@ -0,0 +1 @@ +v0 \ No newline at end of file diff --git a/examples/default/templates/cmd/main.go_ b/examples/default/templates/cmd/main.go_ new file mode 100644 index 0000000..8e9fa2d --- /dev/null +++ b/examples/default/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/default/templates/configs_/convert_id.json b/examples/default/templates/configs_/convert_id.json new file mode 100644 index 0000000..e12763f --- /dev/null +++ b/examples/default/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/default/templates/configs_/mapping.json b/examples/default/templates/configs_/mapping.json new file mode 100644 index 0000000..7f5fd24 --- /dev/null +++ b/examples/default/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/default/templates/configs_/model_crud_delete_functions.json b/examples/default/templates/configs_/model_crud_delete_functions.json new file mode 100644 index 0000000..6a8d05d --- /dev/null +++ b/examples/default/templates/configs_/model_crud_delete_functions.json @@ -0,0 +1,3 @@ +{ + "lawsuits": "NewLawsuit,AsLawsuit" +} diff --git a/examples/default/templates/configs_/name_replace.json b/examples/default/templates/configs_/name_replace.json new file mode 100644 index 0000000..cab0526 --- /dev/null +++ b/examples/default/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/default/templates/configs_/nullable.json b/examples/default/templates/configs_/nullable.json new file mode 100644 index 0000000..3f0a502 --- /dev/null +++ b/examples/default/templates/configs_/nullable.json @@ -0,0 +1,4 @@ +{ + "ext_id": true, + "created_at": false +} diff --git a/examples/default/templates/configs_/readme.txt b/examples/default/templates/configs_/readme.txt new file mode 100644 index 0000000..1c44590 --- /dev/null +++ b/examples/default/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/default/templates/configs_/settings.txt b/examples/default/templates/configs_/settings.txt new file mode 100644 index 0000000..667ff6b --- /dev/null +++ b/examples/default/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= + +#---------------------Template settings--------------------- + +#SERVICE_REPOSITORY_URL - URL of your new service repository (Github, gitlab, etc.) +SERVICE_REPOSITORY_URL="gitlab.aescorp.ru/dsp_dev/claim/crud_service" + +#SERVICE_NAME - service name for your new service +SERVICE_NAME=crud_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=false + +#---------------------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/default/templates/internal/app/grpc/server_grpc/server_grpc.go_ b/examples/default/templates/internal/app/grpc/server_grpc/server_grpc.go_ new file mode 100644 index 0000000..b0de569 --- /dev/null +++ b/examples/default/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/default/templates/internal/app/grpc/server_grpc/server_grpc_func.go_ b/examples/default/templates/internal/app/grpc/server_grpc/server_grpc_func.go_ new file mode 100644 index 0000000..41f5bd7 --- /dev/null +++ b/examples/default/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/default/templates/internal/app/grpc/server_grpc/server_grpc_starter.go_ b/examples/default/templates/internal/app/grpc/server_grpc/server_grpc_starter.go_ new file mode 100644 index 0000000..19b0814 --- /dev/null +++ b/examples/default/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/default/templates/internal/app/grpc/server_grpc/server_grpc_test.go_ b/examples/default/templates/internal/app/grpc/server_grpc/server_grpc_test.go_ new file mode 100644 index 0000000..b44b962 --- /dev/null +++ b/examples/default/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/default/templates/internal/app/nrpc/server_nrpc/server_nrpc_starter.go_ b/examples/default/templates/internal/app/nrpc/server_nrpc/server_nrpc_starter.go_ new file mode 100644 index 0000000..f5b4fd0 --- /dev/null +++ b/examples/default/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/default/templates/internal/app/nrpc/server_nrpc/server_nrpc_starter_test.go b/examples/default/templates/internal/app/nrpc/server_nrpc/server_nrpc_starter_test.go new file mode 100644 index 0000000..696be90 --- /dev/null +++ b/examples/default/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/default/templates/pkg/crud_starter/crud_starter_manual.go b/examples/default/templates/pkg/crud_starter/crud_starter_manual.go new file mode 100644 index 0000000..f647a6c --- /dev/null +++ b/examples/default/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/default/templates/pkg/db/calc_struct_version/calc_struct_version.go b/examples/default/templates/pkg/db/calc_struct_version/calc_struct_version.go new file mode 100644 index 0000000..ea44705 --- /dev/null +++ b/examples/default/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/default/templates/pkg/db/calc_struct_version/calc_struct_version_test.go b/examples/default/templates/pkg/db/calc_struct_version/calc_struct_version_test.go new file mode 100644 index 0000000..b94001d --- /dev/null +++ b/examples/default/templates/pkg/db/calc_struct_version/calc_struct_version_test.go @@ -0,0 +1 @@ +package calc_struct_version diff --git a/examples/default/templates/pkg/db/constants/constants.go b/examples/default/templates/pkg/db/constants/constants.go new file mode 100644 index 0000000..d1deba6 --- /dev/null +++ b/examples/default/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/default/templates/pkg/db/crud/crud.go_ b/examples/default/templates/pkg/db/crud/crud.go_ new file mode 100644 index 0000000..e6e3ada --- /dev/null +++ b/examples/default/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).Order("is_deleted").Order("id").First(m) + err = tx.Error + + return err +} diff --git a/examples/default/templates/pkg/db/crud/crud_test.go_ b/examples/default/templates/pkg/db/crud/crud_test.go_ new file mode 100644 index 0000000..875143c --- /dev/null +++ b/examples/default/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/default/templates/pkg/db/crud/is_deleted.go_ b/examples/default/templates/pkg/db/crud/is_deleted.go_ new file mode 100644 index 0000000..adc19f4 --- /dev/null +++ b/examples/default/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/default/templates/pkg/db/crud/modified_at.go_ b/examples/default/templates/pkg/db/crud/modified_at.go_ new file mode 100644 index 0000000..f648e98 --- /dev/null +++ b/examples/default/templates/pkg/db/crud/modified_at.go_ @@ -0,0 +1 @@ +m.ModifiedAt = time.Now() \ No newline at end of file diff --git a/examples/default/templates/pkg/db/crud_functions/crud_functions.go b/examples/default/templates/pkg/db/crud_functions/crud_functions.go new file mode 100644 index 0000000..880d9f0 --- /dev/null +++ b/examples/default/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/default/templates/pkg/db/crud_functions/crud_functions_test.go b/examples/default/templates/pkg/db/crud_functions/crud_functions_test.go new file mode 100644 index 0000000..31a80a7 --- /dev/null +++ b/examples/default/templates/pkg/db/crud_functions/crud_functions_test.go @@ -0,0 +1 @@ +package crud_functions diff --git a/examples/default/templates/pkg/db/tables/common_struct.go b/examples/default/templates/pkg/db/tables/common_struct.go new file mode 100644 index 0000000..bf80f25 --- /dev/null +++ b/examples/default/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/default/templates/pkg/db/tables/ext_link_struct.go b/examples/default/templates/pkg/db/tables/ext_link_struct.go new file mode 100644 index 0000000..272e5d4 --- /dev/null +++ b/examples/default/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/default/templates/pkg/db/tables/group_struct.go b/examples/default/templates/pkg/db/tables/group_struct.go new file mode 100644 index 0000000..81744c5 --- /dev/null +++ b/examples/default/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/default/templates/pkg/db/tables/name_struct.go b/examples/default/templates/pkg/db/tables/name_struct.go new file mode 100644 index 0000000..9310c26 --- /dev/null +++ b/examples/default/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/default/templates/pkg/db/tables/table.go_ b/examples/default/templates/pkg/db/tables/table.go_ new file mode 100644 index 0000000..b5c4ead --- /dev/null +++ b/examples/default/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/default/templates/pkg/network/grpc/constants/constants.go b/examples/default/templates/pkg/network/grpc/constants/constants.go new file mode 100644 index 0000000..809887d --- /dev/null +++ b/examples/default/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/default/templates/pkg/network/grpc/grpc_client/grpc_client.go_ b/examples/default/templates/pkg/network/grpc/grpc_client/grpc_client.go_ new file mode 100644 index 0000000..ecb859e --- /dev/null +++ b/examples/default/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/default/templates/pkg/network/grpc/grpc_client/grpc_client_table.go_ b/examples/default/templates/pkg/network/grpc/grpc_client/grpc_client_table.go_ new file mode 100644 index 0000000..5cfc11c --- /dev/null +++ b/examples/default/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/default/templates/pkg/network/grpc/grpc_client/grpc_client_table_test.go_ b/examples/default/templates/pkg/network/grpc/grpc_client/grpc_client_table_test.go_ new file mode 100644 index 0000000..2bd2c6d --- /dev/null +++ b/examples/default/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/default/templates/pkg/network/grpc/grpc_client/grpc_client_test.go_ b/examples/default/templates/pkg/network/grpc/grpc_client/grpc_client_test.go_ new file mode 100644 index 0000000..cf46fa7 --- /dev/null +++ b/examples/default/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/default/templates/pkg/network/nrpc/nrpc_client/nrpc_client.go_ b/examples/default/templates/pkg/network/nrpc/nrpc_client/nrpc_client.go_ new file mode 100644 index 0000000..155205e --- /dev/null +++ b/examples/default/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/default/templates/pkg/network/nrpc/nrpc_client/nrpc_client_table.go_ b/examples/default/templates/pkg/network/nrpc/nrpc_client/nrpc_client_table.go_ new file mode 100644 index 0000000..11c56af --- /dev/null +++ b/examples/default/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/default/templates/pkg/network/nrpc/nrpc_client/nrpc_client_table_test.go_ b/examples/default/templates/pkg/network/nrpc/nrpc_client/nrpc_client_table_test.go_ new file mode 100644 index 0000000..8e58f6a --- /dev/null +++ b/examples/default/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/default/templates/pkg/network/nrpc/nrpc_client/nrpc_client_test.go_ b/examples/default/templates/pkg/network/nrpc/nrpc_client/nrpc_client_test.go_ new file mode 100644 index 0000000..1e01603 --- /dev/null +++ b/examples/default/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/default/templates/pkg/object_model/entities/model.go_ b/examples/default/templates/pkg/object_model/entities/model.go_ new file mode 100644 index 0000000..75d8282 --- /dev/null +++ b/examples/default/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/default/templates/pkg/object_model/entities/model_crud.go_ b/examples/default/templates/pkg/object_model/entities/model_crud.go_ new file mode 100644 index 0000000..d00a2b5 --- /dev/null +++ b/examples/default/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/default/templates/pkg/object_model/types/alias/alias.go b/examples/default/templates/pkg/object_model/types/alias/alias.go new file mode 100644 index 0000000..4007f5d --- /dev/null +++ b/examples/default/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/default/templates/scripts/VersionToFile.py b/examples/default/templates/scripts/VersionToFile.py new file mode 100755 index 0000000..c768562 --- /dev/null +++ b/examples/default/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 60f2cde..722bad8 100644 --- a/internal/create_files/create_files.go +++ b/internal/create_files/create_files.go @@ -107,19 +107,6 @@ func DeleteCommentFromFuncName(Text, FuncName string) string { TextFind := "//" + FuncName + "()" Otvet = strings.ReplaceAll(Otvet, TextFind, "") - //pos1 := strings.Index(Otvet, TextFind) - //if pos1 < 0 { - // return Otvet - //} - //s2 := Otvet[pos1+1:] - // - //posEnd := strings.Index(s2, "\n}") - //if posEnd < 0 { - // return Otvet - //} - // - //Otvet = Otvet[:pos1-1] + Otvet[pos1+posEnd+3:] - return Otvet } @@ -639,7 +626,7 @@ func ReplacePackageName(Text, PackageName string) string { return Otvet } - Otvet = Otvet[:pos1] + "\t" + PackageName + Otvet[pos1+posEnd:] + Otvet = Otvet[:pos1+len(TextFind)] + PackageName + Otvet[pos1+posEnd:] return Otvet } @@ -655,3 +642,139 @@ func DeleteEmptyImport(Text string) string { return Otvet } + +// DeleteFuncDelete - удаляет функцию Delete() +func DeleteFuncDelete(TextModel string, Table1 *types.Table) string { + Otvet := TextModel + + //проверим есть ли колонка IsDeleted + if Has_Column_IsDeleted(Table1) == true { + return Otvet + } + + Otvet = DeleteFuncFromComment(Otvet, "\n// Delete ") + Otvet = DeleteFuncFromFuncName(Otvet, "Delete") + + return Otvet +} + +// DeleteFuncRestore - удаляет функцию Restore() +func DeleteFuncRestore(TextModel string, Table1 *types.Table) string { + Otvet := TextModel + + //проверим есть ли колонка IsDeleted + if Has_Column_IsDeleted(Table1) == true && config.Settings.HAS_IS_DELETED == true { + return Otvet + } + + Otvet = DeleteFuncFromComment(Otvet, "\n// Restore ") + Otvet = DeleteFuncFromFuncName(Otvet, "Restore") + + return Otvet +} + +// DeleteFuncFind_byExtID - удаляет функцию Find_ByExtID() +func DeleteFuncFind_byExtID(TextModel string, Table1 *types.Table) string { + Otvet := TextModel + + //проверка есть ли колонки ExtID и ConnectionID + if Has_Column_ExtID_ConnectionID(Table1) == true { + return Otvet + } + + Otvet = DeleteFuncFromComment(Otvet, "\n// Find_ByExtID ") + Otvet = DeleteFuncFromFuncName(Otvet, "Find_ByExtID") + + return Otvet +} + +// DeleteFuncDeleteCtx - удаляет функцию Delete_ctx() +func DeleteFuncDeleteCtx(TextModel string, Table1 *types.Table) string { + Otvet := TextModel + + //проверим есть ли колонка IsDeleted + if Has_Column_IsDeleted(Table1) == true { + return Otvet + } + + Otvet = DeleteFuncFromComment(Otvet, "\n// Delete_ctx ") + Otvet = DeleteFuncFromFuncName(Otvet, "Delete_ctx") + + return Otvet +} + +// DeleteFuncRestoreCtx - удаляет функцию Restore_ctx() +func DeleteFuncRestoreCtx(TextModel string, Table1 *types.Table) string { + Otvet := TextModel + + //проверим есть ли колонка IsDeleted + if Has_Column_IsDeleted(Table1) == true && config.Settings.HAS_IS_DELETED == true { + return Otvet + } + + Otvet = DeleteFuncFromComment(Otvet, "\n// Restore_ctx ") + Otvet = DeleteFuncFromFuncName(Otvet, "Restore_ctx") + + return Otvet +} + +// DeleteFuncFind_byExtIDCtx - удаляет функцию Find_ByExtID_ctx() +func DeleteFuncFind_byExtIDCtx(TextModel string, Table1 *types.Table) string { + Otvet := TextModel + + //проверка есть ли колонки ExtID и ConnectionID + if Has_Column_ExtID_ConnectionID(Table1) == true { + return Otvet + } + + Otvet = DeleteFuncFromComment(Otvet, "\n// Find_ByExtID_ctx ") + Otvet = DeleteFuncFromFuncName(Otvet, "Find_ByExtID_ctx") + + return Otvet +} + +// DeleteFuncTestDelete - удаляет функцию Delete() +func DeleteFuncTestDelete(Text string, Table1 *types.Table) string { + Otvet := Text + + //проверим есть ли колонка IsDeleted + if Has_Column_IsDeleted(Table1) == true { + return Otvet + } + + Otvet = DeleteFuncFromComment(Otvet, "\n// TestDelete ") + Otvet = DeleteFuncFromFuncName(Otvet, "TestDelete") + + return Otvet +} + +// DeleteFuncTestRestore - удаляет функцию Restore() +func DeleteFuncTestRestore(Text string, Table1 *types.Table) string { + Otvet := Text + + //проверим есть ли колонка IsDeleted + if Has_Column_IsDeleted(Table1) == true && config.Settings.HAS_IS_DELETED == true { + return Otvet + } + + Otvet = DeleteFuncFromComment(Otvet, "\n// TestRestore ") + Otvet = DeleteFuncFromFuncName(Otvet, "TestRestore") + + return Otvet +} + +// DeleteFuncFind_byExtID - удаляет функцию Find_ByExtID() +func DeleteFuncTestFind_byExtID(Text string, Table1 *types.Table) string { + Otvet := Text + + //проверка есть ли колонки ExtID и ConnectionID + if Has_Column_ExtID_ConnectionID(Table1) == true { + return Otvet + } + + // + Otvet = DeleteFuncFromComment(Otvet, "\n// TestFind_ByExtID ") + Otvet = DeleteFuncFromFuncName(Otvet, "TestFind_ByExtID") + + return Otvet +} diff --git a/internal/create_files/db_crud_tables/db_crud_tables.go b/internal/create_files/db_crud_tables/db_crud_tables.go index 67e6be0..52ecd06 100644 --- a/internal/create_files/db_crud_tables/db_crud_tables.go +++ b/internal/create_files/db_crud_tables/db_crud_tables.go @@ -78,7 +78,7 @@ func CreateFiles(Table1 *types.Table) error { TextDB := string(bytes) //заменим имя пакета на новое - create_files.ReplacePackageName(TextDB, DirReadyTable) + TextDB = create_files.ReplacePackageName(TextDB, DirReadyTable) //заменим импорты if config.Settings.USE_DEFAULT_TEMPLATE == true { @@ -92,6 +92,16 @@ func CreateFiles(Table1 *types.Table) error { CrudFunctionsURL := create_files.FindCrudFunctionsURL() TextDB = create_files.AddImport(TextDB, CrudFunctionsURL) + + //удалим лишние функции + TextDB = create_files.DeleteFuncDelete(TextDB, Table1) + TextDB = create_files.DeleteFuncRestore(TextDB, Table1) + TextDB = create_files.DeleteFuncFind_byExtID(TextDB, Table1) + + //удалим лишние функции ctx + TextDB = create_files.DeleteFuncDeleteCtx(TextDB, Table1) + TextDB = create_files.DeleteFuncRestoreCtx(TextDB, Table1) + TextDB = create_files.DeleteFuncFind_byExtIDCtx(TextDB, Table1) } //создание текста @@ -100,14 +110,8 @@ func CreateFiles(Table1 *types.Table) error { TextDB = strings.ReplaceAll(TextDB, config.Settings.TEXT_TEMPLATE_TABLENAME, Table1.Name) TextDB = config.Settings.TEXT_MODULE_GENERATED + TextDB - if config.Settings.HAS_IS_DELETED == true { - TextDB = DeleteFuncDelete(TextDB, Table1) - TextDB = DeleteFuncDeleteCtx(TextDB, Table1) - TextDB = DeleteFuncRestore(TextDB, Table1) - TextDB = DeleteFuncRestoreCtx(TextDB, Table1) - } - TextDB = DeleteFuncFind_byExtID(TextDB, Table1) - TextDB = DeleteFuncFind_byExtIDCtx(TextDB, Table1) + //TextDB = create_files.DeleteFuncFind_byExtID(TextDB, Table1) + //TextDB = create_files.DeleteFuncFind_byExtIDCtx(TextDB, Table1) TextDB = AddTextOmit(TextDB, Table1) TextDB = ReplaceText_modified_at(TextDB, Table1) TextDB = ReplaceText_is_deleted_deleted_at(TextDB, Table1) @@ -152,7 +156,7 @@ func CreateTestFiles(Table1 *types.Table) error { TextDB := string(bytes) //заменим имя пакета на новое - create_files.ReplacePackageName(TextDB, DirReadyTable) + TextDB = create_files.ReplacePackageName(TextDB, DirReadyTable) //заменим импорты if config.Settings.USE_DEFAULT_TEMPLATE == true { @@ -161,8 +165,10 @@ func CreateTestFiles(Table1 *types.Table) error { ModelTableURL := create_files.FindModelTableURL(TableName) TextDB = create_files.AddImport(TextDB, ModelTableURL) - //ConstantsURL := create_files.FindGRPCConstantsURL() - //TextDB = create_files.AddImport(TextDB, ConstantsURL) + //удалим лишние функции + TextDB = create_files.DeleteFuncTestDelete(TextDB, Table1) + TextDB = create_files.DeleteFuncTestRestore(TextDB, Table1) + TextDB = create_files.DeleteFuncTestFind_byExtID(TextDB, Table1) } //создание текста @@ -172,10 +178,10 @@ func CreateTestFiles(Table1 *types.Table) error { TextDB = config.Settings.TEXT_MODULE_GENERATED + TextDB if config.Settings.HAS_IS_DELETED == true { - TextDB = DeleteFuncTestDelete(TextDB, Table1) - TextDB = DeleteFuncTestRestore(TextDB, Table1) + TextDB = create_files.DeleteFuncTestDelete(TextDB, Table1) + TextDB = create_files.DeleteFuncTestRestore(TextDB, Table1) } - TextDB = DeleteFuncTestFind_byExtID(TextDB, Table1) + TextDB = create_files.DeleteFuncTestFind_byExtID(TextDB, Table1) //Postgres_ID_Test = ID Minimum if Table1.IDMinimum != "" { @@ -201,141 +207,93 @@ func CreateTestFiles(Table1 *types.Table) error { return err } -// DeleteFuncDelete - удаляет функцию Delete() -func DeleteFuncDelete(Text string, Table1 *types.Table) string { - Otvet := Text - - _, ok := Table1.MapColumns["is_deleted"] - if ok == true { - return Otvet - } - - Otvet = create_files.DeleteFuncFromComment(Text, "\n// Delete ") - - return Otvet -} - -// DeleteFuncRestore - удаляет функцию Restore() -func DeleteFuncRestore(Text string, Table1 *types.Table) string { - Otvet := Text - - _, ok := Table1.MapColumns["is_deleted"] - if ok == true { - return Otvet - } - - Otvet = create_files.DeleteFuncFromComment(Text, "\n// Restore ") - - return Otvet -} - -// DeleteFuncDeleteCtx - удаляет функцию Delete_ctx() -func DeleteFuncDeleteCtx(Text string, Table1 *types.Table) string { - Otvet := Text - - _, ok := Table1.MapColumns["is_deleted"] - if ok == true { - return Otvet - } - - Otvet = create_files.DeleteFuncFromComment(Text, "\n// Delete_ctx ") - - return Otvet -} - -// DeleteFuncRestoreCtx - удаляет функцию Restore_ctx() -func DeleteFuncRestoreCtx(Text string, Table1 *types.Table) string { - Otvet := Text - - _, ok := Table1.MapColumns["is_deleted"] - if ok == true { - return Otvet - } - - Otvet = create_files.DeleteFuncFromComment(Text, "\n// Restore_ctx ") - - return Otvet -} - -// DeleteFuncFind_byExtID - удаляет функцию Find_ByExtID() -func DeleteFuncFind_byExtID(Text string, Table1 *types.Table) string { - Otvet := Text - - //если есть обе колонки - ничего не делаем - ok := create_files.Has_Column_ExtID_ConnectionID(Table1) - if ok == true { - return Otvet - } - - // - Otvet = create_files.DeleteFuncFromComment(Text, "\n// Find_ByExtID ") - - return Otvet -} - -// DeleteFuncFind_byExtIDCtx - удаляет функцию Find_ByExtID_ctx() -func DeleteFuncFind_byExtIDCtx(Text string, Table1 *types.Table) string { - Otvet := Text - - //если есть обе колонки - ничего не делаем - ok := create_files.Has_Column_ExtID_ConnectionID(Table1) - if ok == true { - return Otvet - } - - // - Otvet = create_files.DeleteFuncFromComment(Text, "\n// Find_ByExtID_ctx ") - - return Otvet -} - -// DeleteFuncTestDelete - удаляет функцию Delete() -func DeleteFuncTestDelete(Text string, Table1 *types.Table) string { - Otvet := Text - - _, ok := Table1.MapColumns["is_deleted"] - if ok == true { - return Otvet - } - - Otvet = create_files.DeleteFuncFromFuncName(Otvet, "TestDelete") - - return Otvet -} - -// DeleteFuncTestRestore - удаляет функцию Restore() -func DeleteFuncTestRestore(Text string, Table1 *types.Table) string { - Otvet := Text - - _, ok := Table1.MapColumns["is_deleted"] - if ok == true { - return Otvet - } - - Otvet = create_files.DeleteFuncFromFuncName(Otvet, "TestRestore") - - return Otvet -} - -// DeleteFuncFind_byExtID - удаляет функцию Find_ByExtID() -func DeleteFuncTestFind_byExtID(Text string, Table1 *types.Table) string { - Otvet := Text - - FuncName := "TestFind_ByExtID" - - //если есть обе колонки - ничего не делаем - ok := create_files.Has_Column_ExtID_ConnectionID(Table1) - if ok == true { - Otvet = create_files.DeleteCommentFromFuncName(Otvet, FuncName) - return Otvet - } - - // - Otvet = create_files.DeleteFuncFromFuncName(Otvet, FuncName) - //Otvet = create_files.DeleteLineWithComment(Otvet, FuncName) - - return Otvet -} +//// DeleteFuncDelete - удаляет функцию Delete() +//func DeleteFuncDelete(Text string, Table1 *types.Table) string { +// Otvet := Text +// +// _, ok := Table1.MapColumns["is_deleted"] +// if ok == true { +// return Otvet +// } +// +// Otvet = create_files.DeleteFuncFromComment(Text, "\n// Delete ") +// +// return Otvet +//} +// +//// DeleteFuncRestore - удаляет функцию Restore() +//func DeleteFuncRestore(Text string, Table1 *types.Table) string { +// Otvet := Text +// +// _, ok := Table1.MapColumns["is_deleted"] +// if ok == true { +// return Otvet +// } +// +// Otvet = create_files.DeleteFuncFromComment(Text, "\n// Restore ") +// +// return Otvet +//} +// +//// DeleteFuncDeleteCtx - удаляет функцию Delete_ctx() +//func DeleteFuncDeleteCtx(Text string, Table1 *types.Table) string { +// Otvet := Text +// +// _, ok := Table1.MapColumns["is_deleted"] +// if ok == true { +// return Otvet +// } +// +// Otvet = create_files.DeleteFuncFromComment(Text, "\n// Delete_ctx ") +// +// return Otvet +//} +// +//// DeleteFuncRestoreCtx - удаляет функцию Restore_ctx() +//func DeleteFuncRestoreCtx(Text string, Table1 *types.Table) string { +// Otvet := Text +// +// _, ok := Table1.MapColumns["is_deleted"] +// if ok == true { +// return Otvet +// } +// +// Otvet = create_files.DeleteFuncFromComment(Text, "\n// Restore_ctx ") +// +// return Otvet +//} +// +//// DeleteFuncFind_byExtID - удаляет функцию Find_ByExtID() +//func DeleteFuncFind_byExtID(Text string, Table1 *types.Table) string { +// Otvet := Text +// +// //если есть обе колонки - ничего не делаем +// ok := create_files.Has_Column_ExtID_ConnectionID(Table1) +// if ok == true { +// return Otvet +// } +// +// // +// Otvet = create_files.DeleteFuncFromComment(Text, "\n// Find_ByExtID ") +// +// return Otvet +//} +// +//// DeleteFuncFind_byExtIDCtx - удаляет функцию Find_ByExtID_ctx() +//func DeleteFuncFind_byExtIDCtx(Text string, Table1 *types.Table) string { +// Otvet := Text +// +// //если есть обе колонки - ничего не делаем +// ok := create_files.Has_Column_ExtID_ConnectionID(Table1) +// if ok == true { +// return Otvet +// } +// +// // +// Otvet = create_files.DeleteFuncFromComment(Text, "\n// Find_ByExtID_ctx ") +// +// return Otvet +//} // AddTextOmit - добавляет код для записи null в колонки Nullable func AddTextOmit(TextDB string, Table1 *types.Table) string { diff --git a/internal/create_files/db_tables/db_tables.go b/internal/create_files/db_tables/db_tables.go index a2ad1d0..e73edb6 100644 --- a/internal/create_files/db_tables/db_tables.go +++ b/internal/create_files/db_tables/db_tables.go @@ -74,7 +74,7 @@ func CreateFilesTable_struct(Table1 *types.Table, DirTemplatesTable, DirReadyTab TextModel := string(bytes) //заменим имя пакета на новое - create_files.ReplacePackageName(TextModel, DirReadyTable) + TextModel = create_files.ReplacePackageName(TextModel, DirReadyTable) //создание текста TextModel, TextModelStruct, ModelName, err := FindTextModelStruct(TextModel, Table1) diff --git a/internal/create_files/grpc_client/grpc_client.go b/internal/create_files/grpc_client/grpc_client.go index 2c0d302..df514e3 100644 --- a/internal/create_files/grpc_client/grpc_client.go +++ b/internal/create_files/grpc_client/grpc_client.go @@ -57,7 +57,7 @@ func CreateGRPCClient() error { TextGRPCClient := string(bytes) //заменим имя пакета на новое - create_files.ReplacePackageName(TextGRPCClient, DirReadyClientGRPC) + TextGRPCClient = create_files.ReplacePackageName(TextGRPCClient, DirReadyClientGRPC) //добавим импорты if config.Settings.USE_DEFAULT_TEMPLATE == true { @@ -74,6 +74,7 @@ func CreateGRPCClient() error { ServiceName := config.Settings.SERVICE_NAME TextGRPCClient = strings.ReplaceAll(TextGRPCClient, ServiceNameTemplate, ServiceName) TextGRPCClient = strings.ReplaceAll(TextGRPCClient, strings.ToUpper(ServiceNameTemplate), strings.ToUpper(ServiceName)) + } //заменим имя сервиса на новое @@ -120,7 +121,7 @@ func CreateGRPCClientTest() error { TextGRPCClient := string(bytes) //заменим имя пакета на новое - create_files.ReplacePackageName(TextGRPCClient, DirReadyClientGRPC) + TextGRPCClient = create_files.ReplacePackageName(TextGRPCClient, DirReadyClientGRPC) //добавим импорты if config.Settings.USE_DEFAULT_TEMPLATE == true { diff --git a/internal/create_files/grpc_client_tables/grpc_client_tables.go b/internal/create_files/grpc_client_tables/grpc_client_tables.go index ea20b31..e45dde9 100644 --- a/internal/create_files/grpc_client_tables/grpc_client_tables.go +++ b/internal/create_files/grpc_client_tables/grpc_client_tables.go @@ -70,7 +70,7 @@ func CreateFiles(Table1 *types.Table) error { TextGRPCClient := string(bytes) //заменим имя пакета на новое - create_files.ReplacePackageName(TextGRPCClient, DirReadyTable) + TextGRPCClient = create_files.ReplacePackageName(TextGRPCClient, DirReadyTable) //заменим импорты if config.Settings.USE_DEFAULT_TEMPLATE == true { @@ -79,8 +79,10 @@ func CreateFiles(Table1 *types.Table) error { ConstantsURL := create_files.FindGRPCConstantsURL() TextGRPCClient = create_files.AddImport(TextGRPCClient, ConstantsURL) - //ProtoURL := create_files.FindProtobufURL() - //TextGRPCClient = create_files.AddImport(TextGRPCClient, ProtoURL) + //удалим лишние функции + TextGRPCClient = create_files.DeleteFuncDelete(TextGRPCClient, Table1) + TextGRPCClient = create_files.DeleteFuncRestore(TextGRPCClient, Table1) + TextGRPCClient = create_files.DeleteFuncFind_byExtID(TextGRPCClient, Table1) } //создание текста @@ -89,17 +91,6 @@ func CreateFiles(Table1 *types.Table) error { TextGRPCClient = strings.ReplaceAll(TextGRPCClient, config.Settings.TEXT_TEMPLATE_TABLENAME, Table1.Name) TextGRPCClient = config.Settings.TEXT_MODULE_GENERATED + TextGRPCClient - if config.Settings.HAS_IS_DELETED == true { - TextGRPCClient = DeleteFuncDelete(TextGRPCClient, ModelName, Table1) - //TextGRPCClient = DeleteFuncDeleteCtx(TextGRPCClient, ModelName, Table1) - TextGRPCClient = DeleteFuncRestore(TextGRPCClient, ModelName, Table1) - //TextGRPCClient = DeleteFuncRestoreCtx(TextGRPCClient, ModelName, Table1) - } - TextGRPCClient = DeleteFuncFind_byExtID(TextGRPCClient, ModelName, Table1) - - //замена импортов на новые URL - //TextGRPCClient = create_files.ReplaceServiceURLImports(TextGRPCClient) - if config.Settings.USE_DEFAULT_TEMPLATE == true { //TextGRPCServer = create_files.ReplaceServiceURLImports(TextGRPCServer) TextGRPCClient = create_files.DeleteTemplateRepositoryImports(TextGRPCClient) @@ -156,7 +147,7 @@ func CreateTestFiles(Table1 *types.Table) error { TextGRPCClient := string(bytes) //заменим имя пакета на новое - create_files.ReplacePackageName(TextGRPCClient, DirReadyTable) + TextGRPCClient = create_files.ReplacePackageName(TextGRPCClient, DirReadyTable) //заменим импорты if config.Settings.USE_DEFAULT_TEMPLATE == true { diff --git a/internal/create_files/grpc_server/grpc_server_test.go b/internal/create_files/grpc_server/grpc_server_test.go deleted file mode 100644 index b589eaf..0000000 --- a/internal/create_files/grpc_server/grpc_server_test.go +++ /dev/null @@ -1 +0,0 @@ -package grpc_server diff --git a/internal/create_files/grpc_server/grpc_server.go b/internal/create_files/grpc_server_tables/grpc_server_tables.go similarity index 77% rename from internal/create_files/grpc_server/grpc_server.go rename to internal/create_files/grpc_server_tables/grpc_server_tables.go index 38cab54..4ae64e3 100644 --- a/internal/create_files/grpc_server/grpc_server.go +++ b/internal/create_files/grpc_server_tables/grpc_server_tables.go @@ -1,4 +1,4 @@ -package grpc_server +package grpc_server_tables import ( "github.com/ManyakRus/crud_generator/internal/config" @@ -69,7 +69,7 @@ func CreateFiles(Table1 *types.Table) error { TextGRPCServer := string(bytes) //заменим имя пакета на новое - create_files.ReplacePackageName(TextGRPCServer, DirReadyTable) + TextGRPCServer = create_files.ReplacePackageName(TextGRPCServer, DirReadyTable) //заменим импорты if config.Settings.USE_DEFAULT_TEMPLATE == true { @@ -80,6 +80,11 @@ func CreateFiles(Table1 *types.Table) error { ProtoURL := create_files.FindProtoURL() TextGRPCServer = create_files.AddImport(TextGRPCServer, ProtoURL) + + //удалим лишние функции + TextGRPCServer = DeleteFuncDelete(TextGRPCServer, Table1) + TextGRPCServer = DeleteFuncRestore(TextGRPCServer, Table1) + TextGRPCServer = DeleteFuncFind_byExtID(TextGRPCServer, Table1) } //создание текста @@ -89,13 +94,6 @@ func CreateFiles(Table1 *types.Table) error { TextGRPCServer = config.Settings.TEXT_MODULE_GENERATED + TextGRPCServer if config.Settings.USE_DEFAULT_TEMPLATE == true { - if config.Settings.HAS_IS_DELETED == true { - TextGRPCServer = DeleteFuncDelete(TextGRPCServer, ModelName, Table1) - TextGRPCServer = DeleteFuncDeleteCtx(TextGRPCServer, ModelName, Table1) - TextGRPCServer = DeleteFuncRestore(TextGRPCServer, ModelName, Table1) - TextGRPCServer = DeleteFuncRestoreCtx(TextGRPCServer, ModelName, Table1) - } - TextGRPCServer = DeleteFuncFind_byExtID(TextGRPCServer, ModelName, Table1) TextGRPCServer = ConvertID(TextGRPCServer, Table1) //замена импортов на новые URL @@ -146,7 +144,7 @@ func CreateTestFiles(Table1 *types.Table) error { TextGRPCServer := string(bytes) //заменим имя пакета на новое - create_files.ReplacePackageName(TextGRPCServer, DirReadyTable) + TextGRPCServer = create_files.ReplacePackageName(TextGRPCServer, DirReadyTable) //заменим импорты if config.Settings.USE_DEFAULT_TEMPLATE == true { @@ -160,6 +158,11 @@ func CreateTestFiles(Table1 *types.Table) error { CrudStarterURL := create_files.FindCrudStarterURL() TextGRPCServer = create_files.AddImport(TextGRPCServer, CrudStarterURL) + + //удалим лишние функции + TextGRPCServer = DeleteFuncTestDelete(TextGRPCServer, Table1) + TextGRPCServer = DeleteFuncTestRestore(TextGRPCServer, Table1) + TextGRPCServer = DeleteFuncTestFind_byExtID(TextGRPCServer, Table1) } //создание текста @@ -168,12 +171,6 @@ func CreateTestFiles(Table1 *types.Table) error { TextGRPCServer = strings.ReplaceAll(TextGRPCServer, config.Settings.TEXT_TEMPLATE_TABLENAME, Table1.Name) TextGRPCServer = config.Settings.TEXT_MODULE_GENERATED + TextGRPCServer - if config.Settings.HAS_IS_DELETED == true { - TextGRPCServer = DeleteFuncTestDelete(TextGRPCServer, ModelName, Table1) - TextGRPCServer = DeleteFuncTestRestore(TextGRPCServer, ModelName, Table1) - } - TextGRPCServer = DeleteFuncTestFind_byExtID(TextGRPCServer, ModelName, Table1) - //Postgres_ID_Test = ID Minimum if Table1.IDMinimum != "" { TextFind := "const " + ModelName + "_ID_Test = " @@ -199,63 +196,65 @@ func CreateTestFiles(Table1 *types.Table) error { } // DeleteFuncDelete - удаляет функцию Delete() -func DeleteFuncDelete(Text, ModelName string, Table1 *types.Table) string { +func DeleteFuncDelete(Text string, Table1 *types.Table) string { Otvet := Text - _, ok := Table1.MapColumns["is_deleted"] - if ok == true { + //проверим есть ли колонка IsDeleted + if create_files.Has_Column_IsDeleted(Table1) == true { return Otvet } + ModelName := config.Settings.TEXT_TEMPLATE_MODEL Otvet = create_files.DeleteFuncFromComment(Otvet, "\n// "+ModelName+"_Delete ") return Otvet } // DeleteFuncRestore - удаляет функцию Restore() -func DeleteFuncRestore(Text, ModelName string, Table1 *types.Table) string { +func DeleteFuncRestore(Text string, Table1 *types.Table) string { Otvet := Text - _, ok := Table1.MapColumns["is_deleted"] - if ok == true { + //проверим есть ли колонка IsDeleted + if create_files.Has_Column_IsDeleted(Table1) == true && config.Settings.HAS_IS_DELETED == true { return Otvet } + ModelName := config.Settings.TEXT_TEMPLATE_MODEL Otvet = create_files.DeleteFuncFromComment(Text, "\n// "+ModelName+"_Restore ") return Otvet } -// DeleteFuncDeleteCtx - удаляет функцию Delete_ctx() -func DeleteFuncDeleteCtx(Text, ModelName string, Table1 *types.Table) string { - Otvet := Text - - _, ok := Table1.MapColumns["is_deleted"] - if ok == true { - return Otvet - } - - Otvet = create_files.DeleteFuncFromComment(Text, "\n// "+ModelName+"_Delete_ctx ") - - return Otvet -} - -// DeleteFuncRestoreCtx - удаляет функцию Restore_ctx() -func DeleteFuncRestoreCtx(Text, ModelName string, Table1 *types.Table) string { - Otvet := Text - - _, ok := Table1.MapColumns["is_deleted"] - if ok == true { - return Otvet - } - - Otvet = create_files.DeleteFuncFromComment(Text, "\n// "+ModelName+"_Restore_ctx ") - - return Otvet -} +//// DeleteFuncDeleteCtx - удаляет функцию Delete_ctx() +//func DeleteFuncDeleteCtx(Text, ModelName string, Table1 *types.Table) string { +// Otvet := Text +// +// _, ok := Table1.MapColumns["is_deleted"] +// if ok == true { +// return Otvet +// } +// +// Otvet = create_files.DeleteFuncFromComment(Text, "\n// "+ModelName+"_Delete_ctx ") +// +// return Otvet +//} +// +//// DeleteFuncRestoreCtx - удаляет функцию Restore_ctx() +//func DeleteFuncRestoreCtx(Text, ModelName string, Table1 *types.Table) string { +// Otvet := Text +// +// _, ok := Table1.MapColumns["is_deleted"] +// if ok == true { +// return Otvet +// } +// +// Otvet = create_files.DeleteFuncFromComment(Text, "\n// "+ModelName+"_Restore_ctx ") +// +// return Otvet +//} // DeleteFuncFind_byExtID - удаляет функцию Find_ByExtID() -func DeleteFuncFind_byExtID(Text, ModelName string, Table1 *types.Table) string { +func DeleteFuncFind_byExtID(Text string, Table1 *types.Table) string { Otvet := Text //если есть обе колонки - ничего не делаем @@ -265,41 +264,44 @@ func DeleteFuncFind_byExtID(Text, ModelName string, Table1 *types.Table) string } // + ModelName := config.Settings.TEXT_TEMPLATE_MODEL Otvet = create_files.DeleteFuncFromComment(Text, "\n// "+ModelName+"_FindByExtID ") return Otvet } // DeleteFuncTestDelete - удаляет функцию Delete() -func DeleteFuncTestDelete(Text, ModelName string, Table1 *types.Table) string { +func DeleteFuncTestDelete(Text string, Table1 *types.Table) string { Otvet := Text - _, ok := Table1.MapColumns["is_deleted"] - if ok == true { + //проверим есть ли колонка IsDeleted + if create_files.Has_Column_IsDeleted(Table1) == true { return Otvet } + ModelName := config.Settings.TEXT_TEMPLATE_MODEL Otvet = create_files.DeleteFuncFromFuncName(Otvet, "Test_server_"+ModelName+"_Delete") return Otvet } // DeleteFuncTestRestore - удаляет функцию Restore() -func DeleteFuncTestRestore(Text, ModelName string, Table1 *types.Table) string { +func DeleteFuncTestRestore(Text string, Table1 *types.Table) string { Otvet := Text - _, ok := Table1.MapColumns["is_deleted"] - if ok == true { + //проверим есть ли колонка IsDeleted + if create_files.Has_Column_IsDeleted(Table1) == true && config.Settings.HAS_IS_DELETED == true { return Otvet } + ModelName := config.Settings.TEXT_TEMPLATE_MODEL Otvet = create_files.DeleteFuncFromFuncName(Otvet, "Test_server_"+ModelName+"Restore") return Otvet } // DeleteFuncFind_byExtID - удаляет функцию Find_ByExtID() -func DeleteFuncTestFind_byExtID(Text, ModelName string, Table1 *types.Table) string { +func DeleteFuncTestFind_byExtID(Text string, Table1 *types.Table) string { Otvet := Text //если есть обе колонки - ничего не делаем @@ -309,6 +311,7 @@ func DeleteFuncTestFind_byExtID(Text, ModelName string, Table1 *types.Table) str } // + ModelName := config.Settings.TEXT_TEMPLATE_MODEL Otvet = create_files.DeleteFuncFromFuncName(Otvet, "Test_server_"+ModelName+"_FindByExtID") return Otvet diff --git a/internal/create_files/grpc_server_tables/grpc_server_tables_test.go b/internal/create_files/grpc_server_tables/grpc_server_tables_test.go new file mode 100644 index 0000000..4dd9d5d --- /dev/null +++ b/internal/create_files/grpc_server_tables/grpc_server_tables_test.go @@ -0,0 +1 @@ +package grpc_server_tables diff --git a/internal/create_files/model/model.go b/internal/create_files/model/model.go index 39d9e14..2f67120 100644 --- a/internal/create_files/model/model.go +++ b/internal/create_files/model/model.go @@ -86,7 +86,7 @@ func CreateFilesModel_struct(Table1 *types.Table, DirTemplatesModel, DirReadyMod TextModel := string(bytes) //заменим имя пакета на новое - create_files.ReplacePackageName(TextModel, DirReadyModel) + TextModel = create_files.ReplacePackageName(TextModel, DirReadyModel) //заменим импорты if config.Settings.USE_DEFAULT_TEMPLATE == true { @@ -96,27 +96,7 @@ func CreateFilesModel_struct(Table1 *types.Table, DirTemplatesModel, DirReadyMod TextModel = create_files.AddImport(TextModel, TableURL) } - //создание текста - //TextModel, TextModelStruct, ModelName, err := FindTextModelStruct(TextModel, Table1) - //TextModel = ReplaceModelStruct(TextModel, TextModelStruct) - // - //// - //TextModel = strings.ReplaceAll(TextModel, config.Settings.TEXT_TEMPLATE_MODEL, ModelName) - //TextModel = strings.ReplaceAll(TextModel, config.Settings.TEXT_TEMPLATE_TABLENAME, Table1.Name) - ////TextModel = config.Settings.TEXT_MODULE_GENERATED + TextModel - // - //if config.Settings.HAS_IS_DELETED == true { - // TextModel = DeleteFuncDelete(TextModel, ModelName, Table1) - // TextModel = DeleteFuncRestore(TextModel, ModelName, Table1) - //} - //TextModel = DeleteFuncFind_byExtID(TextModel, ModelName, Table1) - TextModel = create_files.CheckAndAddImportTime_FromText(TextModel) - //TextModel = create_files.DeleteImportModel(TextModel) - - //замена импортов на новые URL - //TextModel = create_files.ReplaceServiceURLImports(TextModel) - TextModel = create_files.ReplaceModelAndTableName(TextModel, Table1) //замена импортов на новые URL @@ -158,7 +138,7 @@ func CreateFilesModel_crud(Table1 *types.Table, DirTemplatesModel, DirReadyModel TextModel := string(bytes) //заменим имя пакета на новое - create_files.ReplacePackageName(TextModel, DirReadyModel) + TextModel = create_files.ReplacePackageName(TextModel, DirReadyModel) //заменим импорты if config.Settings.USE_DEFAULT_TEMPLATE == true { @@ -169,6 +149,16 @@ func CreateFilesModel_crud(Table1 *types.Table, DirTemplatesModel, DirReadyModel DBConstantsURL := create_files.FindDBConstantsURL() TextModel = create_files.AddImport(TextModel, DBConstantsURL) + + //удалим лишние функции + TextModel = create_files.DeleteFuncDelete(TextModel, Table1) + TextModel = create_files.DeleteFuncRestore(TextModel, Table1) + TextModel = create_files.DeleteFuncFind_byExtID(TextModel, Table1) + + //удалим лишние функции из интерфейса + TextModel = DeleteFromInterfaceDelete(TextModel, Table1) + TextModel = DeleteFromInterfaceRestore(TextModel, Table1) + TextModel = DeleteFromInterfaceFind_ByExtID(TextModel, Table1) } //создание текста @@ -176,12 +166,6 @@ func CreateFilesModel_crud(Table1 *types.Table, DirTemplatesModel, DirReadyModel TextModel = strings.ReplaceAll(TextModel, config.Settings.TEXT_TEMPLATE_TABLENAME, Table1.Name) TextModel = config.Settings.TEXT_MODULE_GENERATED + TextModel - if config.Settings.HAS_IS_DELETED == true { - TextModel = DeleteFuncDelete(TextModel, ModelName, Table1) - TextModel = DeleteFuncRestore(TextModel, ModelName, Table1) - } - TextModel = DeleteFuncFind_byExtID(TextModel, ModelName, Table1) - TextModel = create_files.CheckAndAddImportTime_FromText(TextModel) TextModel = create_files.DeleteImportModel(TextModel) @@ -378,100 +362,6 @@ func ReplaceModelStruct(TextTemplateModel, TextModelStruct string) string { return Otvet } -// DeleteFuncDelete - удаляет функцию Delete() -func DeleteFuncDelete(TextModel, ModelName string, Table1 *types.Table) string { - Otvet := TextModel - - _, ok := Table1.MapColumns["is_deleted"] - if ok == true { - return Otvet - } - - //FirstSymbol := strings.ToLower(ModelName)[:1] - TextFind := "Delete(*" + ModelName + ") error" - Otvet = strings.ReplaceAll(Otvet, TextFind, "") - - TextFind = "\n// Delete " - pos1 := strings.Index(Otvet, TextFind) - if pos1 < 0 { - return Otvet - } - s2 := Otvet[pos1+1:] - - posEnd := strings.Index(s2, "\n}") - if posEnd < 0 { - return Otvet - } - - Otvet = Otvet[:pos1-1] + Otvet[pos1+posEnd+3:] - - return Otvet -} - -// DeleteFuncRestore - удаляет функцию Restore() -func DeleteFuncRestore(TextModel, Modelname string, Table1 *types.Table) string { - Otvet := TextModel - - _, ok := Table1.MapColumns["is_deleted"] - if ok == true { - return Otvet - } - - //FirstSymbol := strings.ToLower(Modelname)[:1] - TextFind := "Restore(*" + Modelname + ") error" - Otvet = strings.ReplaceAll(Otvet, TextFind, "") - - TextFind = "\n// Restore " - pos1 := strings.Index(Otvet, TextFind) - if pos1 < 0 { - return Otvet - } - s2 := Otvet[pos1+1:] - - posEnd := strings.Index(s2, "\n}") - if posEnd < 0 { - return Otvet - } - - Otvet = Otvet[:pos1-1] + Otvet[pos1+posEnd+3:] - - return Otvet -} - -// DeleteFuncFind_byExtID - удаляет функцию Find_ByExtID() -func DeleteFuncFind_byExtID(TextModel, Modelname string, Table1 *types.Table) string { - Otvet := TextModel - - // - _, ok1 := Table1.MapColumns["ext_id"] - - // - _, ok2 := Table1.MapColumns["connection_id"] - if ok1 == true && ok2 == true { - return Otvet - } - - //FirstSymbol := strings.ToLower(Modelname)[:1] - TextFind := "Find_ByExtID(*" + Modelname + ") error" - Otvet = strings.ReplaceAll(Otvet, TextFind, "") - - TextFind = "\n// Find_ByExtID " - pos1 := strings.Index(Otvet, TextFind) - if pos1 < 0 { - return Otvet - } - s2 := Otvet[pos1+1:] - - posEnd := strings.Index(s2, "\n}") - if posEnd < 0 { - return Otvet - } - - Otvet = Otvet[:pos1-1] + Otvet[pos1+posEnd+3:] - - return Otvet -} - // FindColumnTypeGoImport - заменяет ID на Alias func FindColumnTypeGoImport(TextModel string, Table1 *types.Table, Column1 *types.Column) (string, string) { Otvet := Column1.TypeGo @@ -515,3 +405,51 @@ func FillColumnsNameGo(MapAll *map[string]*types.Table) error { return err } + +// DeleteFromInterfaceDelete - удаляет функцию Delete() из интерфейса +func DeleteFromInterfaceDelete(TextModel string, Table1 *types.Table) string { + Otvet := TextModel + + //проверим есть ли колонка IsDeleted + if create_files.Has_Column_IsDeleted(Table1) == true { + return Otvet + } + + ModelName := config.Settings.TEXT_TEMPLATE_MODEL + TextFind := "\n\tDelete(*" + ModelName + ") error" + Otvet = strings.ReplaceAll(Otvet, TextFind, "") + + return Otvet +} + +// DeleteFromInterfaceRestore - удаляет функцию Restore() из интерфейса +func DeleteFromInterfaceRestore(TextModel string, Table1 *types.Table) string { + Otvet := TextModel + + //проверим есть ли колонка IsDeleted + if create_files.Has_Column_IsDeleted(Table1) == true && config.Settings.HAS_IS_DELETED == true { + return Otvet + } + + ModelName := config.Settings.TEXT_TEMPLATE_MODEL + TextFind := "\n\tRestore(*" + ModelName + ") error" + Otvet = strings.ReplaceAll(Otvet, TextFind, "") + + return Otvet +} + +// DeleteFromInterfaceFind_ByExtID - удаляет функцию Find_ByExtID() из интерфейса +func DeleteFromInterfaceFind_ByExtID(TextModel string, Table1 *types.Table) string { + Otvet := TextModel + + //проверим есть ли колонки ExtID и ConnectionID + if create_files.Has_Column_ExtID_ConnectionID(Table1) == true { + return Otvet + } + + ModelName := config.Settings.TEXT_TEMPLATE_MODEL + TextFind := "\n\tFind_ByExtID(*" + ModelName + ") error" + Otvet = strings.ReplaceAll(Otvet, TextFind, "") + + return Otvet +} diff --git a/internal/create_files/nrpc_client/nrpc_client.go b/internal/create_files/nrpc_client/nrpc_client.go index cc48e52..bd24ce5 100644 --- a/internal/create_files/nrpc_client/nrpc_client.go +++ b/internal/create_files/nrpc_client/nrpc_client.go @@ -57,7 +57,7 @@ func CreateNRPCClient() error { TextNRPCClient := string(bytes) //заменим имя пакета на новое - create_files.ReplacePackageName(TextNRPCClient, DirReadyClientNRPC) + TextNRPCClient = create_files.ReplacePackageName(TextNRPCClient, DirReadyClientNRPC) //добавим комментарий TextNRPCClient = config.Settings.TEXT_MODULE_GENERATED + TextNRPCClient @@ -71,6 +71,7 @@ func CreateNRPCClient() error { DBConstantsURL := create_files.FindDBConstantsURL() TextNRPCClient = create_files.AddImport(TextNRPCClient, DBConstantsURL) + } //заменим имя сервиса на новое @@ -117,7 +118,7 @@ func CreateNRPCClientTest() error { TextNRPCClient := string(bytes) //заменим имя пакета на новое - create_files.ReplacePackageName(TextNRPCClient, DirReadyClientNRPC) + TextNRPCClient = create_files.ReplacePackageName(TextNRPCClient, DirReadyClientNRPC) //добавим комментарий TextNRPCClient = config.Settings.TEXT_MODULE_GENERATED + TextNRPCClient diff --git a/internal/create_files/nrpc_client_tables/nrpc_client_tables.go b/internal/create_files/nrpc_client_tables/nrpc_client_tables.go index 4901ad2..d65dbe0 100644 --- a/internal/create_files/nrpc_client_tables/nrpc_client_tables.go +++ b/internal/create_files/nrpc_client_tables/nrpc_client_tables.go @@ -69,7 +69,7 @@ func CreateFiles(Table1 *types.Table) error { TextNRPCClient := string(bytes) //заменим имя пакета на новое - create_files.ReplacePackageName(TextNRPCClient, DirReadyTable) + TextNRPCClient = create_files.ReplacePackageName(TextNRPCClient, DirReadyTable) //заменим импорты if config.Settings.USE_DEFAULT_TEMPLATE == true { @@ -86,6 +86,11 @@ func CreateFiles(Table1 *types.Table) error { TableURL := create_files.FindModelTableURL(TableName) TextNRPCClient = create_files.AddImport(TextNRPCClient, TableURL) + + //удалим лишние функции + TextNRPCClient = create_files.DeleteFuncDelete(TextNRPCClient, Table1) + TextNRPCClient = create_files.DeleteFuncRestore(TextNRPCClient, Table1) + TextNRPCClient = create_files.DeleteFuncFind_byExtID(TextNRPCClient, Table1) } //создание текста @@ -94,13 +99,11 @@ func CreateFiles(Table1 *types.Table) error { TextNRPCClient = strings.ReplaceAll(TextNRPCClient, config.Settings.TEXT_TEMPLATE_TABLENAME, Table1.Name) TextNRPCClient = config.Settings.TEXT_MODULE_GENERATED + TextNRPCClient - if config.Settings.HAS_IS_DELETED == true { - TextNRPCClient = DeleteFuncDelete(TextNRPCClient, ModelName, Table1) - //TextNRPCClient = DeleteFuncDeleteCtx(TextNRPCClient, ModelName, Table1) - TextNRPCClient = DeleteFuncRestore(TextNRPCClient, ModelName, Table1) - //TextNRPCClient = DeleteFuncRestoreCtx(TextNRPCClient, ModelName, Table1) - } - TextNRPCClient = DeleteFuncFind_byExtID(TextNRPCClient, ModelName, Table1) + //if config.Settings.HAS_IS_DELETED == true { + // TextNRPCClient = DeleteFuncDelete(TextNRPCClient, ModelName, Table1) + // TextNRPCClient = DeleteFuncRestore(TextNRPCClient, ModelName, Table1) + //} + //TextNRPCClient = DeleteFuncFind_byExtID(TextNRPCClient, ModelName, Table1) //замена импортов на новые URL TextNRPCClient = create_files.ReplaceServiceURLImports(TextNRPCClient) @@ -140,7 +143,7 @@ func CreateTestFiles(Table1 *types.Table) error { TextNRPCClient := string(bytes) //заменим имя пакета на новое - create_files.ReplacePackageName(TextNRPCClient, DirReadyTable) + TextNRPCClient = create_files.ReplacePackageName(TextNRPCClient, DirReadyTable) //заменим импорты if config.Settings.USE_DEFAULT_TEMPLATE == true { @@ -151,6 +154,11 @@ func CreateTestFiles(Table1 *types.Table) error { TableURL := create_files.FindModelTableURL(TableName) TextNRPCClient = create_files.AddImport(TextNRPCClient, TableURL) + + //удалим лишние функции + TextNRPCClient = create_files.DeleteFuncDelete(TextNRPCClient, Table1) + TextNRPCClient = create_files.DeleteFuncRestore(TextNRPCClient, Table1) + TextNRPCClient = create_files.DeleteFuncFind_byExtID(TextNRPCClient, Table1) } //создание текста @@ -159,11 +167,11 @@ func CreateTestFiles(Table1 *types.Table) error { TextNRPCClient = strings.ReplaceAll(TextNRPCClient, config.Settings.TEXT_TEMPLATE_TABLENAME, Table1.Name) TextNRPCClient = config.Settings.TEXT_MODULE_GENERATED + TextNRPCClient - if config.Settings.HAS_IS_DELETED == true { - TextNRPCClient = DeleteFuncTestDelete(TextNRPCClient, ModelName, Table1) - TextNRPCClient = DeleteFuncTestRestore(TextNRPCClient, ModelName, Table1) - } - TextNRPCClient = DeleteFuncTestFind_byExtID(TextNRPCClient, ModelName, Table1) + //if config.Settings.HAS_IS_DELETED == true { + // TextNRPCClient = DeleteFuncTestDelete(TextNRPCClient, ModelName, Table1) + // TextNRPCClient = DeleteFuncTestRestore(TextNRPCClient, ModelName, Table1) + //} + //TextNRPCClient = DeleteFuncTestFind_byExtID(TextNRPCClient, ModelName, Table1) //Postgres_ID_Test = ID Minimum if Table1.IDMinimum != "" { diff --git a/internal/create_files/protobuf/protobuf.go b/internal/create_files/protobuf/protobuf.go index 338b293..bd9e0e6 100644 --- a/internal/create_files/protobuf/protobuf.go +++ b/internal/create_files/protobuf/protobuf.go @@ -131,9 +131,12 @@ func FindTextProtoTable1(TextProto string, Table1 *types.Table) string { Otvet = Otvet + FindTextFindByExtId(TextProto, ModelName) } - if create_files.Has_Column_IsDeleted(Table1) == true && config.Settings.HAS_IS_DELETED == true { + if create_files.Has_Column_IsDeleted(Table1) == true { Otvet = Otvet + FindTextDelete(TextProto, ModelName) - Otvet = Otvet + FindTextRestore(TextProto, ModelName) + + if config.Settings.HAS_IS_DELETED == true { + Otvet = Otvet + FindTextRestore(TextProto, ModelName) + } } return Otvet diff --git a/internal/create_files/server_grpc_func/server_grpc_func.go b/internal/create_files/server_grpc_func/server_grpc_func.go index 0e64c42..13b02d1 100644 --- a/internal/create_files/server_grpc_func/server_grpc_func.go +++ b/internal/create_files/server_grpc_func/server_grpc_func.go @@ -50,7 +50,7 @@ func CreateServerGRPCFunc() error { TextGRPCFunc := string(bytes) //заменим имя пакета на новое - create_files.ReplacePackageName(TextGRPCFunc, DirReadyServerGRPC) + TextGRPCFunc = create_files.ReplacePackageName(TextGRPCFunc, DirReadyServerGRPC) ////заменим имя сервиса на новое //ServiceNameTemplate := config.Settings.TEMPLATE_SERVICE_NAME diff --git a/internal/create_files/server_grpc_starter/server_grpc_starter.go b/internal/create_files/server_grpc_starter/server_grpc_starter.go index 4f8e0f5..cf63e0a 100644 --- a/internal/create_files/server_grpc_starter/server_grpc_starter.go +++ b/internal/create_files/server_grpc_starter/server_grpc_starter.go @@ -51,7 +51,7 @@ func CreateServerGRPCStarter() error { TextGRPCStarter := string(bytes) //заменим имя пакета на новое - create_files.ReplacePackageName(TextGRPCStarter, DirReadyServerGRPC) + TextGRPCStarter = create_files.ReplacePackageName(TextGRPCStarter, DirReadyServerGRPC) //добавим импорты if config.Settings.USE_DEFAULT_TEMPLATE == true { diff --git a/internal/create_files/server_nrpc_starter/server_nrpc_starter.go b/internal/create_files/server_nrpc_starter/server_nrpc_starter.go index be02616..62534bf 100644 --- a/internal/create_files/server_nrpc_starter/server_nrpc_starter.go +++ b/internal/create_files/server_nrpc_starter/server_nrpc_starter.go @@ -51,7 +51,7 @@ func CreateServerGRPCStarter() error { TextNRPCStarter := string(bytes) //заменим имя пакета на новое - create_files.ReplacePackageName(TextNRPCStarter, DirReadyServerNRPC) + TextNRPCStarter = create_files.ReplacePackageName(TextNRPCStarter, DirReadyServerNRPC) if config.Settings.USE_DEFAULT_TEMPLATE == true { TextNRPCStarter = create_files.DeleteTemplateRepositoryImports(TextNRPCStarter) diff --git a/internal/logic/logic.go b/internal/logic/logic.go index e712f29..6f83208 100644 --- a/internal/logic/logic.go +++ b/internal/logic/logic.go @@ -9,7 +9,7 @@ import ( "github.com/ManyakRus/crud_generator/internal/create_files/generation_code_sh" "github.com/ManyakRus/crud_generator/internal/create_files/grpc_client" "github.com/ManyakRus/crud_generator/internal/create_files/grpc_client_tables" - "github.com/ManyakRus/crud_generator/internal/create_files/grpc_server" + "github.com/ManyakRus/crud_generator/internal/create_files/grpc_server_tables" "github.com/ManyakRus/crud_generator/internal/create_files/main_file" "github.com/ManyakRus/crud_generator/internal/create_files/makefile" "github.com/ManyakRus/crud_generator/internal/create_files/model" @@ -65,7 +65,7 @@ func StartFillAll() error { } //grpc_server - err = grpc_server.CreateAllFiles(MapAll) + err = grpc_server_tables.CreateAllFiles(MapAll) if err != nil { //log.Error("grpc_server.CreateAllFiles() error: ", err) return err