zd

package module
v2.1.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 24, 2024 License: Apache-2.0 Imports: 18 Imported by: 0

README

zorm-md

介绍

后端项目封装。将应用与数据库、前端的逻辑进行封装,在此封装的基础上进行后端项目开发,只需关注在业务逻辑。

软件架构

以 struct 为基础,实现数据库的各类操作封装(Create/Drop/Truncate/Select/Insert/Update/Delete),为 apiFox 提供数据结构所需的 json 代码(camel 格式),生成或更新为前端 vue 所用的 interface。

使用说明

安装达梦(docker)
  1. 下载镜像 https://eco.dameng.com/download/
  2. 安装
    docker load -i dm8_20230808_rev197096_x86_rh6_64_single.tar
    docker run -d -p 5236:5236 --restart=always --name dm8 --privileged=true -e PAGE_SIZE=16 -e LD_LIBRARY_PATH=/opt/dmdbms/bin -e INSTANCE_NAME=dm8_01 -v /data/dm8_01:/opt/dmdbms/data dm8_single:dm8_20230808_rev197096_x86_rh6_64
    
数据库操作使用 zorm 框架
  • 初始化 InitDao(dmDSN)

  • 数据表函数(create/drop/truncate)统一为 func[type]()

  • GetTableName 默认取 struct 类别名作为表名(无 schema), 如需改名或增加 schema 则需实现 GetTableName 自定义函数.

  • GetDataType 自定义类型

    • 以 string 的别名, 实现 GetDataType()string 返回 "varchar(nn)", 以实现特定类型的定义, 并在多处重复使用.
工具
  • ToUpperMap 类型转 map 并 key 全大写, 以适应数据库字段匹配
  • ToLittleCamelMap 类型转 map key 采用 camel 格式
  • StructToJson 转为 json 为 apiFox 使用
数据库
  • Create Table
    • GetTableName
    • GetPrimaryKey
    • GetColumns
    • struct 组合
      • 重名字段的定义以父 struct 为准
      • zorm.Select 遇到重名字段会报错
    • tag: primaryKey/not null/size/default/index/comment
    • tag: unique/check
    • 自定义类型
      • type xxx string
      • type xxx byte
      • DM 读取 char(1)转为 byte 的自定义类型
      • type xxx bool
      • DM 读取 BIT 转为 bool 自定义类型
      • type xxx float64
      • DM 读取 number 转为 float64 自定义类型
    • 基础类型: int float64 bool
  • Drop Table
  • Truncate Table
  • select/find
  • insert
  • update
  • 开启事务
自定义类型转换
/*
自定义 ENUM 类型 type XXX byte
const AAA XXX = '0'
*/
package zd

import (
	"context"
	"database/sql"
	"database/sql/driver"
	"reflect"
	"unsafe"

	"gitee.com/chunanyong/zorm"
)

// RegEnumByteType 自定义 byte 的 enum
func RegEnumByteType() {
	//RegisterCustomDriverValueConver 注册自定义的字段处理逻辑,用于驱动无法直接转换的场景,例如达梦的 TEXT 无法直接转化成 string
	//一般是放到init方法里进行注册
	zorm.RegisterCustomDriverValueConver("dm.CHAR", EnumType{})
}

type EnumType struct{}

// GetDriverValue 根据数据库列类型,返回driver.Value的实例,struct属性类型
// 非struct类型接收,无法获取到structFieldType,会传入nil
func (e EnumType) GetDriverValue(ctx context.Context, columnType *sql.ColumnType, structFieldType *reflect.Type) (driver.Value, error) {
	return new(string), nil
}

// ConverDriverValue 数据库列类型,GetDriverValue返回的driver.Value的临时接收值,struct属性类型
// 非struct类型接收,无法获取到structFieldType,会传入nil
// 返回符合接收类型值的指针,指针,指针!!!!
func (e EnumType) ConverDriverValue(ctx context.Context, columnType *sql.ColumnType, tempDriverValue driver.Value, structFieldType *reflect.Type) (interface{}, error) {
	val := tempDriverValue.(*string)
	if len(*val) == 1 {
		if structFieldType == nil { // map 方式时为 nil(因无法取到 structField)
			return val, nil // zorm.QueryMap 自定义 byte 取值为 "1"
		}
		if kind := (*structFieldType).Kind(); kind == reflect.Uint8 && (*structFieldType).Name() != "uint8" {
			// 变量类型为 structFieldType 否则提示类型不匹配
			c := byte((*val)[0])
			v := reflect.NewAt(*structFieldType, unsafe.Pointer(&c))
			return v.Interface(), nil
		}
	}
	return val, nil
}
示例

sql 增删改查 table 建删清空

Documentation

Overview

自定义 ENUM 类型 type XXX byte const AAA XXX = '0'

  • @Author: haifengat hubert28@qq.com
  • @Date: 2023-06-12 13:35:21
  • @LastEditors: haifengat hubert28@qq.com
  • @LastEditTime: 2023-06-12 15:28:10
  • @FilePath: /zorm-dm/entity.go
  • @Description: DML

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateSchema

func CreateSchema(ctx context.Context) error

CreateSchema creates a new schema

@param ctx
@return error

func CreateTable

func CreateTable[T IEntity](ctx context.Context) (err error)

CreateTable creates a new table

主键primaryKey;列名column:User_Name;长度size:12;非空not null;索引index;默认default

@param ctx
@return err

func Delete

func Delete[T IEntity](ctx context.Context, where map[string]any) (int, error)

Delete 删除

@param ctx
@param where map[string]any 删除条件
@return int 删除数量
@return error 错误

func DeleteByName

func DeleteByName(ctx context.Context, tblName string, params map[string]any) (int, error)

DeleteByName 根据表名删除

@param ctx
@param tblName string 表名
@param params map[string]any 删除条件
@return int 删除数量
@return error 错误

func DisableTransaction added in v2.0.2

func DisableTransaction(ctx context.Context) context.Context

DisableTransaction 关闭事务

@param ctx 上下文
@return context.Context 返回新的上下文

func DropTable

func DropTable[T IEntity](ctx context.Context) error

DropTable drops a table

@param ctx
@return error

func ExecuteSql

func ExecuteSql(ctx context.Context, sqlStr string, values ...any) (int, error)

ExecuteSql 执行 sql 语句

@param ctx
@param sqlStr string sql进行查询
@param values ...any sql中?对应的结果
@return int 返回影响的行数
@return error 错误

func FixMaps added in v2.1.4

func FixMaps[T IEntity](ctx context.Context, maps []map[string]any) (mm []map[string]any)

FixMaps 将 maps 的key转为正确的大小写(pg→snake, 其他→Camel)

@param ctx
@param maps
@return mm

func GetColumnName

func GetColumnName(ctx context.Context, tblName string) []string

GetColumnName 取列名(从dm库中取)

@param ctx
@param tblName 表名,格式: SchemaName.TblName
@return []string 列名表

func GetPrimaryKey

func GetPrimaryKey[T IEntity](ctx context.Context) []string

GetPrimaryKey 取表的主键

@return []string 主键

func GetPrimaryKeyByName

func GetPrimaryKeyByName(ctx context.Context, tblName string) ([]string, error)

GetPrimaryKeyByName 获取指定表名的主键

@param ctx
@param tblName string 表名
@return []string 主键名称
@return error 错误

func GetTableName

func GetTableName[T IEntity](ctx context.Context) string

GetTableName 取表名

@param ctx
@return string SchemaName.TblName(DM:Camel PG:snake)

func InitDao

func InitDao(dao zorm.DataSourceConfig, schemaName string) (context.Context, error)

InitDao InitDaoDM 初始化数据库

注册自定义类型: RegEnumByteType RegBoolType(dm.BIT) RegNumberType(dm.NUMBER,dm.NUMERIC)

@param dao 参见: Go数据库驱动列表:https://github.com/golang/go/wiki/SQLDrivers
@return context.Context 数据层上下文
@return error 错误

func InitDaoDM

func InitDaoDM(dmDSN, schemaName string) (context.Context, error)

InitDaoDM 初始化数据库

注册自定义类型: RegEnumByteType RegBoolType(dm.BIT) RegNumberType(dm.NUMBER,dm.NUMERIC)

@param dmDSN string dm://SYSDBA:SYSDBA001@localhost:5236
@return context.Context 数据层上下文
@return error 错误

func InitDaoOracle

func InitDaoOracle(oraDSN, schemaName string) (context.Context, error)

InitDaoOracle 初始化 oracle

应用需要 import _ "github.com/godror/godror"

Go数据库驱动列表:https://github.com/golang/go/wiki/SQLDrivers

@param crmsDSN string
@return context.Context 数据上下文
@return error 错误

func InitDaoPostgres added in v2.1.0

func InitDaoPostgres(pgDSN, schemaName string) (context.Context, error)

InitDaoOracle 初始化 oracle

应用需要 import _ "github.com/godror/godror"

Go数据库驱动列表:https://github.com/golang/go/wiki/SQLDrivers

@param crmsDSN string
@return context.Context 数据上下文
@return error 错误

func Insert

func Insert[T IEntity](ctx context.Context, filterZeroField bool, entities ...T) (n int, err error)

Insert 插入数据(不要用指针类型!!!不要用指针类型!!!不要用指针类型!!!)

@param ctx
@param filterZeroField bool 是否过滤空值[推荐:false](string:"",int:0,bool:false)
@param entities ...T 插入数据
@return n int 成功数量
@return err

func InsertMap

func InsertMap[T IEntity](ctx context.Context, mm ...map[string]any) (n int, err error)

InsertMap 插入数据

@param ctx
@param mm ...map[string]any 插入数据
@return n 插入数量
@return err

func InsertMapByName

func InsertMapByName(ctx context.Context, tblName string, entities ...map[string]any) error

InsertMapByName 根据表名插入数据

@param ctx
@param tblName 表名
@param entities 插入数据
@return error 错误

func QueryMap

func QueryMap(ctx context.Context, sqlStr string, values ...any) ([]map[string]any, error)

QueryMap 执行sql指令进行查询

用于多表联查,或其他复杂的情况

@param ctx
@param sqlStr string sql进行查询
@param values ...any sql中?对应的值
@return []map[string]any 结果集
@return error 错误

func RegBoolType

func RegBoolType()

RegBoolType 注册自定义 bool 类型

func RegEnumByteType

func RegEnumByteType()

RegEnumByteType 自定义 byte 的 enum

func RegNumberType

func RegNumberType()

RegNumberType dm 和 oracle Number/Numeric 类型转为 float64

func Select

func Select[T IEntity](ctx context.Context, p *PageInfo, where map[string]any, sqlStrAppend ...string) ([]T, error)

Select 查询, 返回 struct

@param ctx
@param p *PageInfo 分页
@param where map[string]any 查询条件
@param sqlStrAppend ...string sql拓展, 如 order by xxx, 不会被 fnd 替换
@return []T 返回结果集
@return error 错误

func SelectByStruct

func SelectByStruct[T IEntity](ctx context.Context, p *PageInfo, t T, sqlStrAppend ...string) ([]T, error)

SelectByStruct 查询,条件用 IEntity 实例, 返回 struct

@param ctx
@param p *PageInfo 分页
@param t T 只接受非0值, 若查查询 bool:false int:0 string:"" 的条件,可在 sqlStrAppend 拼接
@param sqlStrAppend ...string sql拓展, 如 order by xxx, 不会被 fnd 替换
@return []T 返回结果集
@return error 错误

func SelectCount

func SelectCount[T IEntity](ctx context.Context, where map[string]any) (int, error)

SelectCount 查询 count(1)

@param ctx
@param where map[string]any 查询条件
@return int count(1)
@return error 错误

func SelectCountByName

func SelectCountByName(ctx context.Context, tblName string, where map[string]any) (int, error)

SelectCountByName 根据表名查询 count(1)

@param ctx
@param tblName string 表名
@param where map[string]any 查询条件
@return int count(1)
@return error 错误

func SelectMap

func SelectMap[T IEntity](ctx context.Context, p *PageInfo, where map[string]any, sqlStrAppend ...string) ([]map[string]any, error)

SelectMap 返回 map 指定列名

@param ctx
@param p *PageInfo 分页
@param where map[string]any 查询条件
@param sqlStrAppend ...string sql拓展, 如 order by xxx, 不会被 fnd 替换
@return []map[string]any 返回结果集
@return error 错误

func SelectMapColumns

func SelectMapColumns[T IEntity](ctx context.Context, p *PageInfo, where map[string]any, columns []string, sqlStrAppend ...string) ([]map[string]any, error)

SelectMapColumns SelectMap 返回 map 指定列名

@param ctx
@param p *PageInfo 分页
@param where map[string]any 查询条件
@param columns []string 指定列名(可用字段名,或 max(XX))
@param sqlStrAppend ...string sql拓展, 如 order by xxx, 不会被 fnd 替换
@return []map[string]any 返回结果集
@return error 错误

func SelectMapColumnsByName

func SelectMapColumnsByName(ctx context.Context, tblName string, p *PageInfo, where map[string]any, columns []string, sqlStrAppend ...string) ([]map[string]any, error)

SelectMapColumnsByName 根据表名查询, 返回 map 指定列名

@param ctx
@param tblName string 表名
@param p *PageInfo 分页
@param where map[string]any 查询条件
@param columns []string 查询列
@param sqlStrAppend ...string sql拓展, 如 order by xxx, 不会被 fnd 替换
@return []map[string]any 返回结果集
@return error 错误

func SelectRow

func SelectRow[T IEntity](ctx context.Context, columnName string, where map[string]any, sqlStrAppend ...string) (any, error)

SelectRow 查询首行指定列的值

@param ctx
@param columnName []string 列名
@param where map[string]any 查询条件
@param sqlStrAppend ...string sql拓展, 如 order by xxx, 不会被 fnd 替换
@return any 无效查询返回  nil
@return error

func SelectRowByName

func SelectRowByName(ctx context.Context, tblName string, columnName string, params map[string]any, sqlStrAppend ...string) (any, error)

SelectRowByName 查询首行指定列的值

@param ctx
@param tblName string 表名
@param columnName []string 列名
@param params map[string]any 查询条件
@param sqlStrAppend ...string sql拓展, 如 order by xxx, 不会被 fnd 替换
@return any 无效查询返回 nil
@return error

func StructToMap

func StructToMap(ctx context.Context, t any, filterZeroField, filterAutoIncrementField bool) (mm map[string]any)

StructToMap 结构体转 map(key Camel大驼峰格式)

@param ctx
@param t any 不能是指针!!!
@param filterZeroField bool 过滤0值字段(bool-false, int-0, string-"", nil)
@param filterAutoIncrementField bool 过滤自增字段(用于 insert/update)
@return mm

func ToCamel added in v2.1.4

func ToCamel[T IEntity](ctx context.Context, m map[string]any) map[string]any

ToCamel map 的 key 转为 Camel 格式

@param ctx
@param m map
@return map

func ToCamels added in v2.1.4

func ToCamels[T IEntity](ctx context.Context, maps []map[string]any) (mm []map[string]any)

ToCamels maps 的 key 转为 Camel 格式

@param maps
@return []map

func ToLittleCamelKey added in v2.1.0

func ToLittleCamelKey(t map[string]any) map[string]any

ToLittleCamelKey 小写 camel

@param t
@return map [string]any 结果数据(ID转id)

func ToUpperKey added in v2.1.0

func ToUpperKey(t map[string]any) map[string]any

ToUpperKey

@param t
@return map

func Transaction

func Transaction(ctx context.Context, fun func(ctx context.Context) error) error

Transaction 使用事务

@param ctx
@param fun func() error 使用了什么代码就抛出什么错误
@return error 错误

func TrunTable

func TrunTable[T IEntity](ctx context.Context) error

TrunTable truncates a table

@param ctx
@return error

func Update

func Update[T IEntity](ctx context.Context, entities []T, filterZero bool) (n int, err error)

Update 更新 Struct

@param ctx
@param entities []T 替换数据(**不能是指针! 不能是指针! 不能是指针!**)
@param filterZero 是否过滤零值(会影响 int:0, bool:false, string: "")
@return n int 成功数量
@return err error

func UpdateMap

func UpdateMap[T IEntity](ctx context.Context, where map[string]any, set map[string]any) (n int, err error)

UpdateMap UpdateOne 更新(单个条件)

@param ctx
@param where map[string]any 查询条件
@param set map[string]any 替换数据
@return int 替换数量
@return error 错误

func UpdateMapByName

func UpdateMapByName(ctx context.Context, tblName string, where map[string]any, set map[string]any) (n int, err error)

UpdateMapByName 根据表名更新(单个条件)

@param ctx
@param tblName string 表名
@param where map[string]any 查询条件
@param set map[string]any 替换数据
@return n
@return err

Types

type BoolType

type BoolType struct{}

func (BoolType) ConverDriverValue

func (e BoolType) ConverDriverValue(ctx context.Context, columnType *sql.ColumnType, tempDriverValue driver.Value, structFieldType *reflect.Type) (interface{}, error)

ConverDriverValue 数据库列类型,GetDriverValue返回的driver.Value的临时接收值,struct属性类型 非struct类型接收,无法获取到structFieldType,会传入nil 返回符合接收类型值的指针,指针,指针!!!!

func (BoolType) GetDriverValue

func (e BoolType) GetDriverValue(ctx context.Context, columnType *sql.ColumnType, structFieldType *reflect.Type) (driver.Value, error)

GetDriverValue 根据数据库列类型,返回driver.Value的实例,struct属性类型 非struct类型接收,无法获取到structFieldType,会传入nil

type CtxKey added in v2.1.0

type CtxKey string
const PG CtxKey = "postgresql"

const DM DialectType = "DM"

const Schema CtxKey = "schemaName"

type Entity

type Entity struct{}

Entity 实现 IEntity

func (Entity) GetDefaultValue added in v2.0.3

func (Entity) GetDefaultValue() map[string]interface{}

GetDefaultValue 获取列的默认值Map,用于Insert和Update Struct对象,UpdateNotZeroValue请使用BindContextMustUpdate方法.返回map的key是Struct属性名,value是默认值,value可以是nil.

func (Entity) GetPKColumnName

func (Entity) GetPKColumnName() string

用 GetPrimaryKey[T] 替代

func (Entity) GetPkSequence

func (Entity) GetPkSequence() string

func (Entity) GetPrimaryKey

func (Entity) GetPrimaryKey() []string

GetPrimaryKey 表的主键, 返回 nil 时忽略此函数; 否则以此函数为准, 忽略 tag中的 primaryKey 配置

func (Entity) GetTableName

func (Entity) GetTableName() string

GetTableName 返回struct类型名;需要struct自行实现

type EnumType

type EnumType struct{}

func (EnumType) ConverDriverValue

func (e EnumType) ConverDriverValue(ctx context.Context, columnType *sql.ColumnType, tempDriverValue driver.Value, structFieldType *reflect.Type) (interface{}, error)

ConverDriverValue 数据库列类型,GetDriverValue返回的driver.Value的临时接收值,struct属性类型 非struct类型接收,无法获取到structFieldType,会传入nil 返回符合接收类型值的指针,指针,指针!!!!

func (EnumType) GetDriverValue

func (e EnumType) GetDriverValue(ctx context.Context, columnType *sql.ColumnType, structFieldType *reflect.Type) (driver.Value, error)

GetDriverValue 根据数据库列类型,返回driver.Value的实例,struct属性类型 非struct类型接收,无法获取到structFieldType,会传入nil

type IEntity

type IEntity interface {
	zorm.IEntityStruct
	GetPrimaryKey() []string // 主键
}

type NumericType

type NumericType struct{}

func (NumericType) ConverDriverValue

func (e NumericType) ConverDriverValue(ctx context.Context, columnType *sql.ColumnType, tempDriverValue driver.Value, structFieldType *reflect.Type) (interface{}, error)

ConverDriverValue 数据库列类型,GetDriverValue返回的driver.Value的临时接收值,struct属性类型 非struct类型接收,无法获取到structFieldType,会传入nil 返回符合接收类型值的指针,指针,指针!!!!

func (NumericType) GetDriverValue

func (e NumericType) GetDriverValue(ctx context.Context, columnType *sql.ColumnType, structFieldType *reflect.Type) (driver.Value, error)

GetDriverValue 根据数据库列类型,返回driver.Value的实例,struct属性类型 非struct类型接收,无法获取到structFieldType,会传入nil

type PageInfo

type PageInfo struct {
	PageNo     int `json:"pageNo,omitempty"`
	PageSize   int `json:"pageSize,omitempty"`
	TotalCount int `json:"totalCount,omitempty"`
}

PageInfo 分页数据

type TableColumn

type TableColumn struct {
	ColumnName      string // 数据表字段名(字段名or由columns定义)
	StructFieldName string // 结构体字段名称
	ColumnType      string // 数据表中的类型定义
	Comment         string
	PrimaryKey      bool
	NotNull         bool
	Unique          bool
	Index           bool
	AutoIncrement   bool // 自增
	Default         string
}

TableColumn 数据列定义

func GetColumns

func GetColumns[T IEntity](ctx context.Context) []TableColumn

GetColumns 取列定义

@param ctx
@return []TableColumn 数据列定义

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL