table_business.go 15.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
package service

import (
	"bytes"
	"fmt"
	"github.com/linmadan/egglib-go/core/application"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/application/factory"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/application/table/command"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/application/table/query"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/constant"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/api/bytelib"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/domainService"
	"gorm.io/driver/mysql"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"log"
	"os"
	"strings"
)

func (tableService *TableService) ShowBusinessDatabases(ctx *domain.Context, cmd *query.ShowBusinessDatabasesRequest) (interface{}, error) {
	byteCoreService := domainService.ByteCoreService{}
	response, err := byteCoreService.ShowBusinessDatabases(bytelib.ReqShowBusinessDatabases{})
	if err != nil {
		return nil, factory.FastError(err)
	}
	return response, err
}

var GlobalDB []command.DBTablesRequest = []command.DBTablesRequest{
	{
		ByteBankDBName:   "allied_creation_reporting_system_test.public",
		ByteBankDBZhName: "销导报表系统",
		GenerateBusinessTableViewRequest: command.GenerateBusinessTableViewRequest{
			Host:       "114.55.200.59",
			Port:       "31543",
			User:       "postgres",
			Password:   "eagle1010",
			DBName:     "allied-creation-reporting-system_test",
			SchemaName: "public",
			DBType:     "postgresql",
		},
	},
}

func getDB(databaseEnName string) (*command.DBTablesRequest, bool) {
	for i := range GlobalDB {
		if GlobalDB[i].ByteBankDBName == databaseEnName {
			return &GlobalDB[i], true
		}
	}
	return nil, false
}
func (tableService *TableService) ShowBusinessTables(ctx *domain.Context, cmd *query.ShowTablesRequest) (interface{}, error) {
	req, ok := getDB(cmd.DatabaseEnName)
	if !ok {
		return nil, factory.FastError(fmt.Errorf("db " + cmd.DatabaseEnName + "未配置"))
	}
	return DBTables(req)
}

func (tableService *TableService) ShowBusinessTables1(ctx *domain.Context, cmd *query.ShowTablesRequest) (interface{}, error) {
	byteCoreService := domainService.ByteCoreService{}
	response, err := byteCoreService.ShowBusinessTables(bytelib.ReqShowBusinessTables{
		DatabaseEnName: cmd.DatabaseEnName,
		DatabaseType:   cmd.DatabaseType,
	})
	if err != nil {
		return nil, factory.FastError(err)
	}
	result := make([]map[string]interface{}, 0)
	for _, t := range response.TableFullNames {
		simpleName := strings.Split(t, ".")
		result = append(result, map[string]interface{}{
			"name":       t,
			"simpleName": simpleName[len(simpleName)-1],
		})
	}
	return map[string]interface{}{
		"list": result,
	}, err
}

func (tableService *TableService) QueryBusinessTable(ctx *domain.Context, cmd *query.ShowTableDataRequest) (interface{}, error) {
	byteCoreService := domainService.ByteCoreService{}
	response, err := byteCoreService.QueryBusinessTable(bytelib.ReqQueryBusinessTable{
		TableFullName: cmd.TableFullName,
		PageNumber:    cmd.PageNumber - 1, // 分页从0开始
		PageSize:      cmd.PageSize,
	})
	if err != nil {
		return nil, factory.FastError(err)
	}
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	tableRepository, _, _ := factory.FastPgTable(transactionContext, 0)
	table, _ := tableRepository.FindBusinessTable(constant.COMPANY_SU_TIAN_XIA, response.TableFullName)
	if table != nil {
		response.TableRemarkName = table.Name
		response.ShowTableNameBy = table.TableInfo.BusinessTableShowTableNameBy
		response.ShowTableFieldNameBy = table.TableInfo.BusinessTableShowTableFieldNameBy
		for i, f := range response.FieldSchemas {
			for j, jf := range table.DataFields {
				if jf.SQLName == f.FieldEnName {
					response.FieldSchemas[i].FieldZhName = table.DataFields[j].Name
				}
			}
		}

	}
	return response, err
}

func (tableService *TableService) UpdateBusinessTable(ctx *domain.Context, cmd *command.UpdateBusinessTableRequest) (interface{}, error) {
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	var tableRepository domain.TableRepository
	if value, err := factory.CreateTableRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	} else {
		tableRepository = value
	}

	ctx.CompanyId = int(constant.COMPANY_SU_TIAN_XIA)

	var (
		fields    = make([]*domain.Field, 0)
		mainTable *domain.Table
	)
	for i, f := range cmd.Fields {
		fields = append(fields, &domain.Field{
			Index:   i + 1,
			Name:    f.FieldZhName,
			SQLName: f.FieldEnName,
			SQLType: f.FieldType, //TODO:类型转换
			Flag:    domain.MainTableField,
		})
	}
	table, _ := tableRepository.FindBusinessTable(constant.COMPANY_SU_TIAN_XIA, cmd.TableFullName)
	if table == nil {
		mainTable = domainService.NewTable(domain.BusinessTable, cmd.TableName, fields, 0).
			WithContext(ctx).
			WithPrefix(domain.BusinessTable.ToString())
		mainTable.SQLName = cmd.TableFullName
		mainTable.DataFields = fields
		mainTable.TableInfo.BusinessTableShowTableNameBy = cmd.ShowTableNameBy
		mainTable.TableInfo.BusinessTableShowTableFieldNameBy = cmd.ShowTableFieldNameBy
		mainTable.TableInfo.TableFrom = 1

		if mainTable, err = tableRepository.Save(mainTable); err != nil {
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
		}
	} else {
		table.Name = cmd.TableName
		table.DataFields = fields
		table.TableInfo.BusinessTableShowTableNameBy = cmd.ShowTableNameBy
		table.TableInfo.BusinessTableShowTableFieldNameBy = cmd.ShowTableFieldNameBy
		if table, err = tableRepository.Save(table); err != nil {
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
		}
	}

	if err = transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	return mainTable, nil
}

func (tableService *TableService) GenerateBusinessTable(ctx *domain.Context, cmd *command.GenerateBusinessTableRequest) (interface{}, error) {
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	var tableRepository domain.TableRepository
	if value, err := factory.CreateTableRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	} else {
		tableRepository = value
	}
	ctx.CompanyId = int(constant.COMPANY_SU_TIAN_XIA)

	duplicateTable, err := tableRepository.FindOne(map[string]interface{}{"context": ctx, "tableName": cmd.TableName,
		"tableTypes": []string{string(domain.MainTable), string(domain.SubTable), string(domain.SideTable)}})
	if err == nil && duplicateTable != nil {
		return nil, factory.FastError(fmt.Errorf("表名称重复"))
	}

	var (
		fields     = make([]*domain.Field, 0)
		mainTable  *domain.Table
		hasPkField bool
	)
	for i, f := range cmd.Fields {
		if strings.ToLower(f.FieldEnName) == "id" {
			hasPkField = true
			continue
		}
		var filedName = f.FieldZhName
		// 使用备注名
		if cmd.ShowTableFieldNameBy == 0 {
			filedName = f.FieldEnName
		}
		// 字段为空时显示原字段名
		if cmd.ShowTableFieldNameBy == 1 && filedName == "" {
			filedName = f.FieldEnName
		}
		fields = append(fields, &domain.Field{
			Index:   i + 1,
			Name:    filedName,
			SQLName: f.FieldEnName,
			SQLType: f.FieldType, //TODO:类型转换
			Flag:    domain.MainTableField,
		})
	}
	if !hasPkField {
		return nil, factory.FastError(fmt.Errorf("业务表未包含字段 `id`"))
	}
	var tableName = cmd.TableName
	if cmd.ShowTableNameBy == 0 {
		tableName = cmd.TableFullName
	}
	mainTable = domainService.NewTable(domain.MainTable, tableName, fields, 0).
		WithContext(ctx).
		WithPrefix(domain.MainTable.ToString()).ApplyDefaultModule()
	mainTable.SQLName = cmd.TableFullName
	mainTable.TableInfo.TableFrom = 1
	mainTable.DataFields = fields
	if mainTable, err = tableRepository.Save(mainTable); err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}

	if err = transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	return nil, nil
}

type Field struct {
	Field string `json:"field"`
	Type  string `json:"type"`
}

func (tableService *TableService) GenerateBusinessTablesView(ctx *domain.Context, cmd *command.GenerateBusinessTableViewRequest) (interface{}, error) {
	var (
		db  *gorm.DB
		err error
	)
	if cmd.DBType == "" {
		cmd.SchemaName = "postgresql"
	}
	if cmd.SchemaName == "" {
		cmd.SchemaName = "public"
	}

	buf := bytes.NewBuffer(nil)
	if cmd.DBType == "postgresql" {
		db, err = gorm.Open(postgres.Open(fmt.Sprintf("user=%v password=%v host=%v  port=%v dbname=%v sslmode=disable TimeZone=Asia/Shanghai",
			cmd.User, cmd.Password, cmd.Host, cmd.Port, cmd.DBName)), &gorm.Config{PrepareStmt: false})
		if err != nil {
			return nil, factory.FastError(err)
		}
		var tables []string
		if tx := db.Raw(fmt.Sprintf(`select tablename from pg_tables where schemaname='%v';`, cmd.SchemaName)).Scan(&tables); tx.Error != nil {
			return nil, factory.FastError(tx.Error)
		}
		var fields = make([]Field, 0)
		for _, t := range tables {
			if tx := db.Raw(fmt.Sprintf(`SELECT a.attnum,a.attname AS field,t.typname AS type,a.attlen AS length,a.atttypmod AS lengthvar,a.attnotnull AS notnull
FROM pg_class c,pg_attribute a,pg_type t
WHERE c.relname = '%v' and a.attnum > 0 and a.attrelid = c.oid and a.atttypid = t.oid
ORDER BY a.attnum;`, t)).Scan(&fields); tx.Error != nil {
				return nil, factory.FastError(tx.Error)
			}
			var commonFields []string
			var jsonbFields []string
			var pkFields []string
			var containPkId = false
			for _, f := range fields {
				if f.Field == "id" {
					containPkId = true
				}
			}
			for index, f := range fields {
				if index == 0 && strings.HasSuffix(f.Field, "id") && !containPkId {
					commonFields = append(commonFields, fmt.Sprintf("%v as id", f.Field))
					pkFields = append(pkFields, f.Field)
				}
				if f.Type == "jsonb" || f.Type == "json" {
					jsonbFields = append(jsonbFields, f.Field)
				} else {
					commonFields = append(commonFields, f.Field)
				}
			}
			buf.WriteString(fmt.Sprintf("-- == 表【%v】建视图语句 ==\n", t))
			buf.WriteString(fmt.Sprintf("-- drop view view_%v;\n", t))
			buf.WriteString(fmt.Sprintf(`DO $$ 
BEGIN
  IF EXISTS (SELECT 1 FROM information_schema.views WHERE table_name = 'view_%s') THEN
    -- 如果存在就删除视图
    DROP VIEW view_%s;
    RAISE NOTICE '视图已删除';
  ELSE
    RAISE NOTICE '视图不存在';
  END IF;
END $$;`, t, t))
			buf.WriteString("\n")
			buf.WriteString(fmt.Sprintf("create view view_%v as select %v from %v;\n", t, strings.Join(commonFields, ","), t))
			buf.WriteString(fmt.Sprintf("-- pk %v\n", strings.Join(pkFields, ",")))
			buf.WriteString(fmt.Sprintf("-- jsonb %v\n", strings.Join(jsonbFields, ",")))
			buf.WriteString("\n\n")
		}
		generalWrite(cmd.DBName+"_tables_view.sql", buf)
	} else if cmd.DBType == "mysql" {
		db, err = gorm.Open(mysql.Open(fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8&parseTime=True&loc=Local",
			cmd.User, cmd.Password, cmd.Host, cmd.Port, cmd.DBName)), &gorm.Config{PrepareStmt: false})
		if err != nil {
			return nil, factory.FastError(err)
		}
		var tables []string
		if tx := db.Raw(fmt.Sprintf(`show tables;`)).Scan(&tables); tx.Error != nil {
			return nil, factory.FastError(tx.Error)
		}
		var fields = make([]Field, 0)
		for _, t := range tables {
			if tx := db.Raw(fmt.Sprintf(`SHOW COLUMNS FROM %s;`, t)).Scan(&fields); tx.Error != nil {
				return nil, factory.FastError(tx.Error)
			}
			writeToBuf(buf, t, fields)
		}
		generalWrite(cmd.DBName+"_tables_view.sql", buf)
	}

	return nil, nil
}

func DBTables(cmd *command.DBTablesRequest) (interface{}, error) {
	var (
		result = make([]map[string]interface{}, 0)
		tables []string
		db     *gorm.DB
		err    error
	)
	if cmd.DBType == "postgresql" {
		db, err = gorm.Open(postgres.Open(fmt.Sprintf("user=%v password=%v host=%v  port=%v dbname=%v sslmode=disable TimeZone=Asia/Shanghai",
			cmd.User, cmd.Password, cmd.Host, cmd.Port, cmd.DBName)), &gorm.Config{PrepareStmt: false})
		if err != nil {
			return nil, factory.FastError(err)
		}
		if tx := db.Raw(fmt.Sprintf(`select tablename from pg_tables where schemaname='%v';`, cmd.SchemaName)).Scan(&tables); tx.Error != nil {
			return nil, factory.FastError(tx.Error)
		}
	} else if cmd.DBType == "mysql" {
		db, err = gorm.Open(mysql.Open(fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8&parseTime=True&loc=Local",
			cmd.User, cmd.Password, cmd.Host, cmd.Port, cmd.DBName)), &gorm.Config{PrepareStmt: false})
		if err != nil {
			return nil, factory.FastError(err)
		}
		if tx := db.Raw(fmt.Sprintf(`show tables;`)).Scan(&tables); tx.Error != nil {
			return nil, factory.FastError(tx.Error)
		}
	}
	for _, t := range tables {
		viewT := "view_" + t
		result = append(result, map[string]interface{}{
			"name":       fmt.Sprintf("%s.%s", cmd.ByteBankDBName, viewT), //返回所有视图 view开头
			"simpleName": viewT,
		})
	}
	return map[string]interface{}{
		"list": result,
	}, nil
}

func writeToBuf(buf *bytes.Buffer, t string, fields []Field) {
	var commonFields []string
	var jsonbFields []string
	var pkFields []string
	var containPkId = false
	for _, f := range fields {
		if f.Field == "id" {
			containPkId = true
		}
	}
	for index, f := range fields {
		if index == 0 && strings.HasSuffix(f.Field, "id") && !containPkId {
			commonFields = append(commonFields, fmt.Sprintf("%v as id", f.Field))
			pkFields = append(pkFields, f.Field)
		}
		if f.Type == "jsonb" || f.Type == "json" {
			jsonbFields = append(jsonbFields, f.Field)
		} else {
			commonFields = append(commonFields, f.Field)
		}
	}
	buf.WriteString(fmt.Sprintf("-- == 表【%v】建视图语句 ==\n", t))
	buf.WriteString(fmt.Sprintf("-- drop view view_%v;\n", t))
	buf.WriteString(fmt.Sprintf("DROP VIEW IF EXISTS %s;", t))
	buf.WriteString("\n")
	buf.WriteString(fmt.Sprintf("create view view_%v as select %v from %v;\n", t, strings.Join(commonFields, ","), t))
	buf.WriteString(fmt.Sprintf("-- pk %v\n", strings.Join(pkFields, ",")))
	buf.WriteString(fmt.Sprintf("-- jsonb %v\n", strings.Join(jsonbFields, ",")))
	buf.WriteString("\n\n")
}

func generalWrite(filename string, buf *bytes.Buffer) {
	f, err := os.OpenFile(filename, os.O_RDONLY|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		log.Println("open file error :", err)
		return
	}
	// 关闭文件
	defer f.Close()
	// 字符串写入
	_, err = f.WriteString(buf.String())
	if err != nil {
		log.Println(err)
		return
	}
}