diff --git a/bin/templates/pkg/db/crud/crud.go_ b/bin/templates/pkg/db/crud/crud.go_ new file mode 100644 index 0000000..52e2c1b --- /dev/null +++ b/bin/templates/pkg/db/crud/crud.go_ @@ -0,0 +1,317 @@ +package db_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" + "gorm.io/gorm" + "time" + "github.com/ManyakRus/starter/contextmain" +) + +// 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 в пустые колонки + for f := 0; f < len(MassOmit); f++ { + ColumnName := MassOmit[f] + tx = db.Model(&m).Update(ColumnName, gorm.Expr("NULL")) + + err = tx.Error + if err != nil { + TextError := fmt.Sprint("db.Update() ", TableName, " id: ", m.ID, " error: ", err) + err = errors.New(TextError) + return err + // log.Panic(sError) + } + } + + return err +} + +// Delete - записывает is_deleted = true +func (crud Crud_DB) Delete(m *lawsuit_status_types.LawsuitStatusType) error { + var err error + + ctxMain := contextmain.GetContext() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_DB_SECONDS)) + defer ctxCancelFunc() + + err = crud.Delete_ctx(ctx, m) + return err +} + +// Delete_ctx - записывает is_deleted = true +func (crud Crud_DB) Delete_ctx(ctx context.Context, m *lawsuit_status_types.LawsuitStatusType) error { + var err error + + if micro.ContextDone(ctx) == true { + err = context.Canceled + return err + } + + m2 := lawsuit_status_types.LawsuitStatusType{} + m2.ID = m.ID + err = crud.Read_ctx(ctx, &m2) + if err != nil { + return err + } + + m2.IsDeleted = true + m.IsDeleted = true + + err = crud.Save_ctx(ctx, &m2) + + return err +} + +// Restore - записывает is_deleted = true +func (crud Crud_DB) Restore(m *lawsuit_status_types.LawsuitStatusType) error { + var err error + + ctxMain := contextmain.GetContext() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_DB_SECONDS)) + defer ctxCancelFunc() + + err = crud.Restore_ctx(ctx, m) + return err +} + +// Restore_ctx - записывает is_deleted = true +func (crud Crud_DB) Restore_ctx(ctx context.Context, m *lawsuit_status_types.LawsuitStatusType) error { + var err error + + if micro.ContextDone(ctx) == true { + err = context.Canceled + return err + } + + m2 := lawsuit_status_types.LawsuitStatusType{} + m2.ID = m.ID + err = crud.Read_ctx(ctx, &m2) + if err != nil { + return err + } + + m2.IsDeleted = false + m.IsDeleted = false + + err = crud.Save_ctx(ctx, &m2) + + return err +} + +// Find_ByExtID - находит запись в БД по ext_id и connection_id +func (crud Crud_DB) Find_ByExtID(m *lawsuit_status_types.LawsuitStatusType) error { + var err error + + if m.ExtID == 0 { + err = errors.New("Error: ext_id =0") + return err + } + + // + ctxMain := contextmain.GetContext() + ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(constants.TIMEOUT_DB_SECONDS)) + defer ctxCancelFunc() + + err = crud.Find_ByExtID_ctx(ctx, m) + + return err +} + +// Find_ByExtID_ctx - находит запись в БД по ext_id и connection_id +func (crud Crud_DB) Find_ByExtID_ctx(ctx context.Context, m *lawsuit_status_types.LawsuitStatusType) error { + var err error + + if micro.ContextDone(ctx) == true { + err = context.Canceled + return err + } + + if m.ExtID == 0 { + err = errors.New("Error: ExtID=0") + return err + } + + db := postgres_gorm.GetConnection() + db.WithContext(ctx) + + tx := db.Where("ext_id = ?", m.ExtID).Where("connection_id = ?", m.ConnectionID).First(m) + err = tx.Error + + return err +} diff --git a/bin/templates/pkg/db/crud/crud_test.go_ b/bin/templates/pkg/db/crud/crud_test.go_ new file mode 100644 index 0000000..e943429 --- /dev/null +++ b/bin/templates/pkg/db/crud/crud_test.go_ @@ -0,0 +1,124 @@ +package db_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/bin/templates/pkg/db/crud/is_deleted.go_ b/bin/templates/pkg/db/crud/is_deleted.go_ new file mode 100644 index 0000000..adc19f4 --- /dev/null +++ b/bin/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/bin/templates/pkg/db/crud/modified_at.go_ b/bin/templates/pkg/db/crud/modified_at.go_ new file mode 100644 index 0000000..f648e98 --- /dev/null +++ b/bin/templates/pkg/db/crud/modified_at.go_ @@ -0,0 +1 @@ +m.ModifiedAt = time.Now() \ No newline at end of file diff --git a/bin/templates/pkg/db/tables/common_struct.go b/bin/templates/pkg/db/tables/common_struct.go new file mode 100644 index 0000000..bf80f25 --- /dev/null +++ b/bin/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/bin/templates/pkg/db/tables/ext_link_struct.go b/bin/templates/pkg/db/tables/ext_link_struct.go new file mode 100644 index 0000000..272e5d4 --- /dev/null +++ b/bin/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/bin/templates/pkg/db/tables/group_struct.go b/bin/templates/pkg/db/tables/group_struct.go new file mode 100644 index 0000000..81744c5 --- /dev/null +++ b/bin/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/bin/templates/pkg/db/tables/name_struct.go b/bin/templates/pkg/db/tables/name_struct.go new file mode 100644 index 0000000..9310c26 --- /dev/null +++ b/bin/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/bin/templates/pkg/db/tables/table.go_ b/bin/templates/pkg/db/tables/table.go_ new file mode 100644 index 0000000..7170e8b --- /dev/null +++ b/bin/templates/pkg/db/tables/table.go_ @@ -0,0 +1,13 @@ +package lawsuit_status_types + +import ( + "gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities" +) + +// LawsuitStatusType +type LawsuitStatusType struct { + entities.CommonStruct + entities.NameStruct + Code string `json:"code" gorm:"column:code;default:0"` +} +