pg_table_repository.go 5.6 KB
package repository

import (
	"fmt"
	"github.com/go-pg/pg/v10"

	"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
	pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg/models"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg/transform"
)

type TableRepository struct {
	transactionContext *pgTransaction.TransactionContext
}

func (repository *TableRepository) Save(table *domain.Table) (*domain.Table, error) {
	sqlBuildFields := []string{
		"table_id",
		"table_type",
		"name",
		"sql_name",
		"parent_id",
		"data_field_index",
		"pk",
		"data_fields",
		"manual_fields",
		"created_at",
		"updated_at",
		"deleted_at",
		"version",
		"row_count",
		"context",
	}
	insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "table_id", "deleted_at"))
	insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "table_id", "deleted_at"))
	returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
	updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "table_id", "deleted_at")
	updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
	tx := repository.transactionContext.PgTx
	if table.Identify() == nil {
		if _, err := tx.QueryOne(
			pg.Scan(
				&table.TableId,
				&table.TableType,
				&table.Name,
				&table.SQLName,
				&table.ParentId,
				&table.DataFieldIndex,
				&table.PK,
				&table.DataFields,
				&table.ManualFields,
				&table.CreatedAt,
				&table.UpdatedAt,
				&table.DeletedAt,
				&table.Version,
				&table.RowCount,
				&table.Context,
			),
			fmt.Sprintf("INSERT INTO metadata.tables (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
			table.TableType,
			table.Name,
			table.SQLName,
			table.ParentId,
			table.DataFieldIndex,
			table.PK,
			table.DataFields,
			table.ManualFields,
			table.CreatedAt,
			table.UpdatedAt,
			table.Version,
			table.RowCount,
			table.Context,
		); err != nil {
			return table, err
		}
	} else {
		oldVersion := table.Version
		table.Version += 1
		if _, err := tx.QueryOne(
			pg.Scan(
				&table.TableId,
				&table.TableType,
				&table.Name,
				&table.SQLName,
				&table.ParentId,
				&table.DataFieldIndex,
				&table.PK,
				&table.DataFields,
				&table.ManualFields,
				&table.CreatedAt,
				&table.UpdatedAt,
				&table.DeletedAt,
				&table.Version,
				&table.RowCount,
				&table.Context,
			),
			fmt.Sprintf("UPDATE metadata.tables SET %s WHERE table_id=? and version=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
			table.TableType,
			table.Name,
			table.SQLName,
			table.ParentId,
			table.DataFieldIndex,
			table.PK,
			table.DataFields,
			table.ManualFields,
			table.CreatedAt,
			table.UpdatedAt,
			table.Version,
			table.RowCount,
			table.Context,
			table.Identify(),
			oldVersion,
		); err != nil {
			return table, err
		}
	}
	return table, nil
}
func (repository *TableRepository) Remove(table *domain.Table) (*domain.Table, error) {
	tx := repository.transactionContext.PgTx
	tableModel := new(models.Table)
	tableModel.TableId = table.Identify().(int)
	if _, err := tx.Model(tableModel).WherePK().Delete(); err != nil {
		return table, err
	}
	return table, nil
}
func (repository *TableRepository) FindOne(queryOptions map[string]interface{}) (*domain.Table, error) {
	tx := repository.transactionContext.PgTx
	tableModel := new(models.Table)
	query := sqlbuilder.BuildQuery(tx.Model(tableModel), queryOptions)
	WhereContext(query, queryOptions)
	query.SetWhereByQueryOption("table_id = ?", "tableId")
	query.SetWhereByQueryOption(`table_type = ?`, "tableType")
	query.SetWhereByQueryOption("name = ?", "tableName")
	query.SetWhereByQueryOption("parent_id = ?", "parentId")
	if v, ok := queryOptions["tableTypes"]; ok && len(v.([]string)) > 0 {
		query.Where(`table_type in (?)`, pg.In(v.([]string)))
	}
	if err := query.First(); err != nil {
		if err.Error() == "pg: no rows in result set" {
			return nil, domain.ErrorNotFound
		} else {
			return nil, err
		}
	}
	if tableModel.TableId == 0 {
		return nil, nil
	} else {
		return transform.TransformToTableDomainModelFromPgModels(tableModel)
	}
}
func (repository *TableRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Table, error) {
	tx := repository.transactionContext.PgTx
	var tableModels []*models.Table
	tables := make([]*domain.Table, 0)
	query := sqlbuilder.BuildQuery(tx.Model(&tableModels), queryOptions)
	WhereContext(query, queryOptions)
	query.SetWhereByQueryOption(fmt.Sprintf("name like '%%%v%%'", queryOptions["name"]), "name")

	query.SetWhereByQueryOption("parent_id = ?", "parentId")
	if v, ok := queryOptions["tableTypes"]; ok && len(v.([]string)) > 0 {
		query.Where(`table_type in (?)`, pg.In(v.([]string)))
	}

	//query.SetOffsetAndLimit(20)
	query.SetOrderDirect("table_id", "DESC")
	if count, err := query.SelectAndCount(); err != nil {
		return 0, tables, err
	} else {
		for _, tableModel := range tableModels {
			if table, err := transform.TransformToTableDomainModelFromPgModels(tableModel); err != nil {
				return 0, tables, err
			} else {
				tables = append(tables, table)
			}
		}
		return int64(count), tables, nil
	}
}
func NewTableRepository(transactionContext *pgTransaction.TransactionContext) (*TableRepository, error) {
	if transactionContext == nil {
		return nil, fmt.Errorf("transactionContext参数不能为nil")
	} else {
		return &TableRepository{
			transactionContext: transactionContext,
		}, nil
	}
}