1
0
mirror of https://github.com/ManyakRus/crud_generator.git synced 2025-01-01 13:21:20 +02:00

сделал TemplateFilenameCrudGo

This commit is contained in:
Nikitin Aleksandr 2023-11-16 15:08:10 +03:00
parent 553b9fe517
commit 98e4cf9dfe
17 changed files with 492 additions and 496 deletions

View File

@ -1,317 +0,0 @@
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
}

View File

@ -1,124 +0,0 @@
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")
}
}

View File

@ -1,5 +0,0 @@
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{}
}

View File

@ -1 +0,0 @@
m.ModifiedAt = time.Now()

View File

@ -1,13 +1,11 @@
package lawsuit_status_types
import (
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/object_model/entities"
"gitlab.aescorp.ru/dsp_dev/claim/sync_service/pkg/db/tables/lawsuit_status_types"
)
// LawsuitStatusType
type LawsuitStatusType struct {
entities.CommonStruct
entities.NameStruct
Code string `json:"code" gorm:"column:code;default:0"`
Table_LawsuitStatusType
}

View File

@ -15,7 +15,8 @@ type SettingsINI struct {
EXCLUDE_TABLES string
TEMPLATE_FOLDERNAME string
TEMPLATE_FOLDERNAME_MODEL string
TEMPLATE_FOLDERNAME_DB string
TEMPLATE_FOLDERNAME_CRUD string
TEMPLATE_FOLDERNAME_TABLES string
TEMPLATE_FOLDERNAME_GRPC string
TEMPLATE_FOLDERNAME_GRPC_PROTO string
TEMPLATE_FOLDERNAME_GRPC_SERVER string
@ -46,10 +47,13 @@ type SettingsINI struct {
TEXT_DB_IS_DELETED string
USE_DEFAULT_TEMPLATE bool
PREFIX_SERVER_GRPC string
PREFIX_CRUD string
PREFIX_MODEL string
COMMENT_MODEL_STRUCT string
TEXT_MODULE_GENERATED string
TEMPLATE_FOLDERNAME_MAIN string
TEMPLATE_REPOSITORY_URL string
PREFIX_TABLE string
}
// FillSettings загружает переменные окружения в структуру из переменных окружения
@ -61,7 +65,7 @@ func FillSettings() {
Settings.EXCLUDE_TABLES = os.Getenv("EXCLUDE_TABLES")
Settings.TEMPLATE_FOLDERNAME = os.Getenv("TEMPLATE_FOLDERNAME")
Settings.TEMPLATE_FOLDERNAME_MODEL = os.Getenv("TEMPLATE_FOLDERNAME_MODEL")
Settings.TEMPLATE_FOLDERNAME_DB = os.Getenv("TEMPLATE_FOLDERNAME_DB")
Settings.TEMPLATE_FOLDERNAME_CRUD = os.Getenv("TEMPLATE_FOLDERNAME_CRUD")
Settings.TEMPLATE_FOLDERNAME_GRPC_PROTO = os.Getenv("TEMPLATE_FOLDERNAME_GRPC_PROTO")
Settings.TEMPLATE_FOLDERNAME_GRPC_SERVER = os.Getenv("TEMPLATE_FOLDERNAME_GRPC_SERVER")
Settings.TEMPLATE_FOLDERNAME_GRPC_CLIENT = os.Getenv("TEMPLATE_FOLDERNAME_GRPC_CLIENT")
@ -140,6 +144,10 @@ func FillSettings() {
Settings.TEMPLATE_FOLDERNAME_MAIN = os.Getenv("TEMPLATE_FOLDERNAME_MAIN")
Settings.TEMPLATE_REPOSITORY_URL = os.Getenv("TEMPLATE_REPOSITORY_URL")
Settings.TEMPLATE_FOLDERNAME_GRPC = os.Getenv("TEMPLATE_FOLDERNAME_GRPC")
Settings.PREFIX_CRUD = os.Getenv("PREFIX_CRUD")
Settings.PREFIX_TABLE = os.Getenv("PREFIX_TABLE")
Settings.TEMPLATE_FOLDERNAME_TABLES = os.Getenv("TEMPLATE_FOLDERNAME_TABLES")
Settings.PREFIX_MODEL = os.Getenv("PREFIX_MODEL")
}

View File

@ -11,3 +11,5 @@ Need fill settings in settings.txt file
const FILE_PERMISSIONS = 0666
const CONFIG_FOLDER_NAME = "configs_"
const TemplateFilenameCrudGo = "crud.go_"

View File

@ -230,7 +230,7 @@ func Find_Template_DB_Foldername() string {
DirBin := micro.ProgramDir_bin()
DirTemplates := DirBin + config.Settings.TEMPLATE_FOLDERNAME + micro.SeparatorFile()
DirTemplatesDB := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_DB + micro.SeparatorFile()
DirTemplatesDB := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_CRUD + micro.SeparatorFile()
Otvet = DirTemplatesDB
return Otvet
@ -306,6 +306,15 @@ func FindProtoURL() string {
return Otvet
}
// FindTablesURL - возвращает URL репозитория с пакетом "tables"
func FindTablesURL() string {
Otvet := ""
Otvet = config.Settings.SERVICE_REPOSITORY_URL + "/" + config.Settings.TEMPLATE_FOLDERNAME_TABLES
return Otvet
}
// FindGRPCProtoURL - возвращает URL репозитория с пакетом "grpc_proto"
func FindGRPCProtoURL() string {
Otvet := ""
@ -324,17 +333,23 @@ func FindModelTableURL(TableName string) string {
return Otvet
}
func FindTextDefaultValue(Type_go string) string {
func FindTextDefaultValue(Column1 *types.Column) string {
var Otvet string
sValue := ""
switch Type_go {
case "string":
sValue = "\\\"\\\""
case "int", "int32", "int64", "float32", "float64", "uint", "uint32", "uint64":
sValue = "0"
case "time.Time":
Type_go := Column1.TypeGo
if Column1.TableKey != "" {
sValue = "null"
} else {
switch Type_go {
case "string":
sValue = "\\\"\\\""
case "int", "int32", "int64", "float32", "float64", "uint", "uint32", "uint64":
sValue = "0"
case "time.Time":
sValue = "null"
}
}
if sValue != "" {

View File

@ -132,7 +132,7 @@ func FindTextImportModel1(Table1 *types.Table) string {
// FindTextImportDB1 - возвращает текст импорта DB для 1 таблицы
func FindTextImportDB1(Table1 *types.Table) string {
TableName := strings.ToLower(Table1.Name)
DB_URL := config.Settings.SERVICE_REPOSITORY_URL + "/" + config.Settings.TEMPLATE_FOLDERNAME_DB
DB_URL := config.Settings.SERVICE_REPOSITORY_URL + "/" + config.Settings.TEMPLATE_FOLDERNAME_CRUD
Otvet := "\n\t\"" + DB_URL + "/db_" + TableName + `"`
return Otvet

View File

@ -1 +0,0 @@
package db

View File

@ -1,4 +1,4 @@
package db
package db_crud
import (
"github.com/ManyakRus/crud_generator/internal/config"
@ -53,13 +53,13 @@ func CreateFiles(Table1 *types.Table) error {
DirBin := micro.ProgramDir_bin()
DirTemplates := DirBin + config.Settings.TEMPLATE_FOLDERNAME + micro.SeparatorFile()
DirReady := DirBin + config.Settings.READY_FOLDERNAME + micro.SeparatorFile()
DirTemplatesDB := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_DB + micro.SeparatorFile()
DirReadyDB := DirReady + config.Settings.TEMPLATE_FOLDERNAME_DB + micro.SeparatorFile()
DirTemplatesDB := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_CRUD + micro.SeparatorFile()
DirReadyDB := DirReady + config.Settings.TEMPLATE_FOLDERNAME_CRUD + micro.SeparatorFile()
FilenameTemplateDB := DirTemplatesDB + "db.go_"
FilenameTemplateDB := DirTemplatesDB + constants.TemplateFilenameCrudGo
TableName := strings.ToLower(Table1.Name)
DirTable := DirReadyDB + "db_" + TableName
FilenameReadyDB := DirTable + micro.SeparatorFile() + "db_" + TableName + ".go"
DirTable := DirReadyDB + config.Settings.PREFIX_CRUD + TableName
FilenameReadyDB := DirTable + micro.SeparatorFile() + config.Settings.PREFIX_CRUD + TableName + ".go"
//создадим каталог
ok, err := micro.FileExists(DirTable)
@ -114,12 +114,12 @@ func CreateTestFiles(Table1 *types.Table) error {
DirBin := micro.ProgramDir_bin()
DirTemplates := DirBin + config.Settings.TEMPLATE_FOLDERNAME + micro.SeparatorFile()
DirReady := DirBin + config.Settings.READY_FOLDERNAME + micro.SeparatorFile()
DirTemplatesDB := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_DB + micro.SeparatorFile()
DirReadyDB := DirReady + config.Settings.TEMPLATE_FOLDERNAME_DB + micro.SeparatorFile()
DirTemplatesDB := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_CRUD + micro.SeparatorFile()
DirReadyDB := DirReady + config.Settings.TEMPLATE_FOLDERNAME_CRUD + micro.SeparatorFile()
FilenameTemplateDB := DirTemplatesDB + "db_test.go_"
DirTable := DirReadyDB + "db_" + TableName
FilenameReadyDB := DirTable + micro.SeparatorFile() + "db_" + TableName + "_test.go"
FilenameTemplateDB := DirTemplatesDB + config.Settings.PREFIX_CRUD + "test.go_"
DirTable := DirReadyDB + config.Settings.PREFIX_CRUD + TableName
FilenameReadyDB := DirTable + micro.SeparatorFile() + config.Settings.PREFIX_CRUD + TableName + "_test.go"
//создадим каталог
ok, err := micro.FileExists(DirTable)

View File

@ -0,0 +1 @@
package db_crud

View File

@ -0,0 +1,404 @@
package db_tables
import (
"errors"
"github.com/ManyakRus/crud_generator/internal/config"
"github.com/ManyakRus/crud_generator/internal/constants"
"github.com/ManyakRus/crud_generator/internal/create_files"
"github.com/ManyakRus/crud_generator/internal/types"
"github.com/ManyakRus/starter/log"
"github.com/ManyakRus/starter/micro"
"os"
"sort"
"strings"
)
// CreateAllFiles - создаёт все файлы в папке model
func CreateAllFiles(MapAll map[string]*types.Table) error {
var err error
for _, table1 := range MapAll {
err = CreateFiles(table1)
if err != nil {
log.Error("CreateFiles() table: ", table1.Name, " error: ", err)
return err
}
}
return err
}
// CreateFiles - создаёт 1 файл в папке model
func CreateFiles(Table1 *types.Table) error {
var err error
TableName := strings.ToLower(Table1.Name)
//чтение файлов
DirBin := micro.ProgramDir_bin()
DirTemplates := DirBin + config.Settings.TEMPLATE_FOLDERNAME + micro.SeparatorFile()
DirReady := DirBin + config.Settings.READY_FOLDERNAME + micro.SeparatorFile()
DirTemplatesTable := DirTemplates + config.Settings.TEMPLATE_FOLDERNAME_TABLES + micro.SeparatorFile()
DirReadyTable := DirReady + config.Settings.TEMPLATE_FOLDERNAME_TABLES + micro.SeparatorFile() + TableName + micro.SeparatorFile()
//создадим каталог
ok, err := micro.FileExists(DirReadyTable)
if ok == false {
err = os.MkdirAll(DirReadyTable, 0777)
if err != nil {
log.Panic("Mkdir() ", DirReadyTable, " error: ", err)
}
}
// создание файла struct
if config.Settings.NEED_CREATE_MODEL_STRUCT == true {
err = CreateFilesTable_struct(Table1, DirTemplatesTable, DirReadyTable)
if err != nil {
log.Error("CreateFilesTable_struct() table: ", Table1.Name, " error: ", err)
return err
}
}
return err
}
// CreateFilesTable_struct - создаёт 1 файл со структурой в папке model
func CreateFilesTable_struct(Table1 *types.Table, DirTemplatesTable, DirReadyTable string) error {
var err error
var ModelName string
TableName := strings.ToLower(Table1.Name)
FilenameTemplateModel := DirTemplatesTable + "table.go_"
FilenameReadyModel := DirReadyTable + config.Settings.PREFIX_TABLE + TableName + ".go"
//чтение файла шаблона
bytes, err := os.ReadFile(FilenameTemplateModel)
if err != nil {
log.Panic("ReadFile() ", FilenameTemplateModel, " error: ", err)
}
TextModel := string(bytes)
//создание текста
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)
//запись файла
err = os.WriteFile(FilenameReadyModel, []byte(TextModel), constants.FILE_PERMISSIONS)
return err
}
// FindTextModelStruct - возвращает текст структуры и тегов gorm
func FindTextModelStruct(TextModel string, Table1 *types.Table) (string, string, string, error) {
var Otvet string
var ModelName string
var err error
TableName := Table1.Name
ModelName = create_files.FindSingularName(TableName)
ModelName = create_files.FormatName(ModelName)
Table1.NameGo = ModelName
COMMENT_MODEL_STRUCT := config.Settings.COMMENT_MODEL_STRUCT
Otvet = `// ` + ModelName + ` - ` + COMMENT_MODEL_STRUCT + TableName + `: ` + Table1.Comment + `
type ` + ModelName + ` struct {
`
//сортировка
keys := make([]string, 0, len(Table1.MapColumns))
for k := range Table1.MapColumns {
keys = append(keys, k)
}
sort.Strings(keys)
has_Columns_CommonStruct := create_files.Has_Columns_CommonStruct(Table1)
has_Columns_NameStruct := create_files.Has_Columns_NameStruct(Table1)
has_Columns_Groups := create_files.Has_Columns_Groups(Table1)
has_Columns_ExtLinks := create_files.Has_Columns_ExtLink(Table1)
ImportModelsName := micro.LastWord(config.Settings.TEMPLATE_FOLDERNAME_TABLES)
if has_Columns_CommonStruct == true {
Otvet = Otvet + "\t" + ImportModelsName + ".CommonStruct\n"
}
if has_Columns_NameStruct == true {
Otvet = Otvet + "\t" + ImportModelsName + ".NameStruct\n"
}
if has_Columns_Groups == true {
Otvet = Otvet + "\t" + ImportModelsName + ".GroupStruct\n"
}
if has_Columns_ExtLinks == true {
Otvet = Otvet + "\t" + ImportModelsName + ".ExtLinkStruct\n"
}
//цикл по всем колонкам
for _, key1 := range keys {
Column1, _ := Table1.MapColumns[key1]
//пропускаем колонки если они уже есть в CommonStruct
if has_Columns_CommonStruct == true && create_files.Is_Column_CommonStruct(Column1) == true {
continue
} else if has_Columns_NameStruct == true && create_files.Is_Column_NameStruct(Column1) == true {
continue
} else if has_Columns_Groups == true && create_files.Is_Column_GroupsStruct(Column1) == true {
continue
} else if has_Columns_ExtLinks == true && create_files.Is_Column_ExtLinksStruct(Column1) == true {
continue
}
var TextColumn string
TextModel, TextColumn = FindTextColumn(TextModel, Table1, Column1)
Otvet = Otvet + TextColumn + "\n"
Table1.MapColumns[key1] = Column1
}
Otvet = Otvet + "\n}"
return TextModel, Otvet, ModelName, err
}
// FindTextColumn - возвращает текст gorm
func FindTextColumn(TextModel string, Table1 *types.Table, Column1 *types.Column) (string, string) {
Otvet := ""
// Code string `json:"code" gorm:"column:code;default:0"`
ColumnName := Column1.Name
ColumnNameLowerCase := strings.ToLower(ColumnName)
ColumnModelName := create_files.FormatName(Column1.Name)
//Column1.NameGo = ColumnModelName
//SQLMapping1, ok := dbmeta.GetMappings()[Column1.Type]
//if ok == false {
// log.Panic("GetMappings() ", Column1.Type, " error: not found")
//}
//Type_go := SQLMapping1.GoType
Type_go := Column1.TypeGo
TextModel, Type_go = FindColumnTypeGoImport(TextModel, Table1, Column1)
//Column1.TypeGo = Type_go
TextDefaultValue := ""
if Column1.IsIdentity == false {
TextDefaultValue = create_files.FindTextDefaultValue(Column1)
}
TextPrimaryKey := FindTextPrimaryKey(Column1.IsIdentity)
Description := Column1.Description
Description = create_files.PrintableString(Description) //экранирование символов
TextAutoCreateTime := ""
TextAutoUpdateTime := ""
if config.Settings.USE_DEFAULT_TEMPLATE == true {
if ColumnNameLowerCase == "created_at" {
TextAutoCreateTime = ";autoCreateTime"
}
if ColumnNameLowerCase == "modified_at" {
TextAutoUpdateTime = ";autoUpdateTime"
}
}
Otvet = Otvet + "\t" + ColumnModelName + " " + Type_go + "\t"
Otvet = Otvet + "`json:\"" + ColumnName + "\""
Otvet = Otvet + " gorm:\"column:" + ColumnName + TextPrimaryKey + TextDefaultValue + TextAutoCreateTime + TextAutoUpdateTime + "\""
//Otvet = Otvet + " db:\"" + ColumnName + "\""
Otvet = Otvet + "`"
Otvet = Otvet + "\t//" + Description
return TextModel, Otvet
}
// FindTextPrimaryKey - возвращает строку gorm для primaryKey
func FindTextPrimaryKey(Is_identity bool) string {
Otvet := ""
if Is_identity == true {
Otvet = ";primaryKey;autoIncrement:true"
}
return Otvet
}
// ReplaceModelStruct - заменяет структуру модели на новую
func ReplaceModelStruct(TextTemplateModel, TextModelStruct string) string {
Otvet := ""
ModelName := config.Settings.TEXT_TEMPLATE_MODEL
//найдём начало и конец
TextFind1 := "// " + ModelName
pos1 := strings.Index(TextTemplateModel, TextFind1)
if pos1 < 0 {
TextFind1 := "type " + ModelName + " struct {"
pos1 = strings.Index(TextTemplateModel, TextFind1)
}
if pos1 < 0 {
log.Panic("ReplaceModelStruct() error: in model.go_ not found text: ", TextFind1)
}
s2 := TextTemplateModel[pos1:]
TextFind1 = "}\n"
posEnd := strings.Index(s2, TextFind1)
if posEnd < 0 {
log.Panic("ReplaceModelStruct() error: in model.go_ not found text: ", TextFind1)
}
//
Otvet = TextTemplateModel[:pos1] + TextModelStruct + TextTemplateModel[pos1+posEnd+1:]
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
//тип колонки из БД или из convert_id.json
TableName := Table1.Name
ColumnName := Column1.Name
TextConvert, ok := types.MapConvertID[TableName+"."+ColumnName]
if ok == false {
return TextModel, Otvet
}
Otvet = TextConvert
//добавим импорт
URL := create_files.FindURL_Alias()
if URL == "" {
return TextModel, Otvet
}
TextModel = create_files.AddImport(TextModel, URL)
return TextModel, Otvet
}
// FillColumnsNameGo - заполняет NameGo во все колонки
func FillColumnsNameGo(MapAll *map[string]*types.Table) error {
var err error
for _, Table1 := range *MapAll {
for _, Column1 := range Table1.MapColumns {
ColumnName := Column1.Name
ColumnModelName := create_files.FormatName(ColumnName)
Column1.NameGo = ColumnModelName
if ColumnModelName == "" {
err = errors.New("Table: " + Table1.Name + " Column: " + ColumnName + " = \"\"")
}
}
}
return err
}

View File

@ -0,0 +1 @@
package db_tables

View File

@ -73,11 +73,11 @@ func CreateFiles(Table1 *types.Table) error {
// CreateFilesModel_struct - создаёт 1 файл со структурой в папке model
func CreateFilesModel_struct(Table1 *types.Table, DirTemplatesModel, DirReadyModel string) error {
var err error
var ModelName string
//var ModelName string
TableName := strings.ToLower(Table1.Name)
FilenameTemplateModel := DirTemplatesModel + "model.go_"
FilenameReadyModel := DirReadyModel + TableName + ".go"
FilenameReadyModel := DirReadyModel + config.Settings.PREFIX_MODEL + TableName + ".go"
//чтение файла шаблона
bytes, err := os.ReadFile(FilenameTemplateModel)
@ -87,25 +87,33 @@ func CreateFilesModel_struct(Table1 *types.Table, DirTemplatesModel, DirReadyMod
TextModel := string(bytes)
//создание текста
TextModel, TextModelStruct, ModelName, err := FindTextModelStruct(TextModel, Table1)
TextModel = ReplaceModelStruct(TextModel, TextModelStruct)
//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 = 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)
//TextModel = create_files.DeleteImportModel(TextModel)
//замена импортов на новые URL
TextModel = create_files.ReplaceServiceURLImports(TextModel)
//TextModel = create_files.ReplaceServiceURLImports(TextModel)
//замена импортов на новые URL
if config.Settings.USE_DEFAULT_TEMPLATE == true {
TextModel = create_files.DeleteTemplateRepositoryImports(TextModel)
TablesURL := create_files.FindTablesURL()
TextModel = create_files.AddImport(TextModel, TablesURL)
}
//запись файла
err = os.WriteFile(FilenameReadyModel, []byte(TextModel), constants.FILE_PERMISSIONS)
@ -245,7 +253,7 @@ func FindTextColumn(TextModel string, Table1 *types.Table, Column1 *types.Column
//Column1.TypeGo = Type_go
TextDefaultValue := ""
if Column1.IsIdentity == false {
TextDefaultValue = create_files.FindTextDefaultValue(Type_go)
TextDefaultValue = create_files.FindTextDefaultValue(Column1)
}
TextPrimaryKey := FindTextPrimaryKey(Column1.IsIdentity)
Description := Column1.Description
@ -415,8 +423,8 @@ func FindColumnTypeGoImport(TextModel string, Table1 *types.Table, Column1 *type
//тип колонки из БД или из convert_id.json
TableName := Table1.Name
//IDName := Column1.NameGo
TextConvert, ok := types.MapConvertID[TableName+"."+TableName]
ColumnName := Column1.Name
TextConvert, ok := types.MapConvertID[TableName+"."+ColumnName]
if ok == false {
return TextModel, Otvet
}

View File

@ -112,7 +112,7 @@ func CreateAllFolders() {
if config.Settings.NEED_CREATE_DB == true {
//db
Filename = dir + config.Settings.SERVICE_NAME + micro.SeparatorFile() + config.Settings.TEMPLATE_FOLDERNAME_DB
Filename = dir + config.Settings.SERVICE_NAME + micro.SeparatorFile() + config.Settings.TEMPLATE_FOLDERNAME_CRUD
ok, err = micro.FileExists(Filename)
if ok == false || err != nil {
err = CreateFolder_err(Filename, 0777)

View File

@ -3,7 +3,8 @@ package logic
import (
"github.com/ManyakRus/crud_generator/internal/config"
"github.com/ManyakRus/crud_generator/internal/create_files/crud_starter"
"github.com/ManyakRus/crud_generator/internal/create_files/db"
"github.com/ManyakRus/crud_generator/internal/create_files/db_crud"
"github.com/ManyakRus/crud_generator/internal/create_files/db_tables"
"github.com/ManyakRus/crud_generator/internal/create_files/generation_code_sh"
"github.com/ManyakRus/crud_generator/internal/create_files/grpc_client_tables"
"github.com/ManyakRus/crud_generator/internal/create_files/grpc_proto"
@ -50,7 +51,7 @@ func StartFillAll() error {
}
//db crud
err = db.CreateAllFiles(MapAll)
err = db_crud.CreateAllFiles(MapAll)
if err != nil {
return err
}
@ -115,5 +116,11 @@ func StartFillAll() error {
return err
}
//tables
err = db_tables.CreateAllFiles(MapAll)
if err != nil {
return err
}
return err
}