首页 > 其他分享 >go语言DB通用查询实现解析

go语言DB通用查询实现解析

时间:2024-08-30 11:55:23浏览次数:13  
标签:case return checkType DB field go 解析 goType ptr

用例

func Test018_QueryShop(t *testing.T) {

    var dbRequest = Default()
    dbRequest.TableName = "contact_shop"
    dbRequest.SetPageSize(2).OrderByAsc("id")
    dbRequest.FieldsName = "id_10,id,name"
    var result = dbRequest.GeneralQuery()

    goutils.Info(result)
    assert.Equal(t, 200, result.Code)

}



结果



INFO[2024-08-830 11:49:10]D:/go-ichub/git.ichub.com/webcli120/goconfig/base/goutils/go_log.go:65 git.ichub.com/general/webcli120/goconfig/base/goutils.Info() [{
     "code": 200,
     "msg": "成功",
     "data": [
          {
               "name": "万1商户",
               "id_10": 0,
               "id": 722612810457022465
          },
          {
               "id_10": 0,
               "id": 722622552951128065,
               "name": "杨1商户"
          }
     ],
     "total": 621,
     "page_size": 2,
     "current": 1
}] 

代码

func (this *PageDbRequest) GeneralQuery() *page.PageResult {

    if pageResult := this.InitFields(); pageResult != nil {
       return pageResult
    }

    count, err := this.CountTable(this.TableName)
    if err != nil {
       return page.NewPageResultError(err.Error())
    }
    var pageResult = page.PageResultOf(this.PageRequest)
    pageResult.Total = count
    if count == 0 {
       return pageResult
    }

    var ret = this.FindRecords(pageResult)
    if ret.Code != 200 {
       return ret

    }
    if this.IfSubTable() {
       this.QuerySubTable(pageResult.Data.([]map[string]interface{}))
    }
    pageResult.PageSize = this.PageSize
    pageResult.PageCurrent = this.PageCurrent
    return pageResult

}

count

func (this *PageRequest) CountTable(table string) (int, error) {
    dbc := this.GetDB().Table(table)
    dbc = this.BuildWhere(dbc).Offset(0).Limit(1)
    var count int
    if err := dbc.Count(&count).Error; err != nil {
       goutils.Error(err)
       return 0, err
    }

    return count, nil

}

buildWhere

func (this *PageRequest) BuildWhere(dbc *gorm.DB) *gorm.DB {

    this.InitPage()
    if this.Fields == nil {
       return dbc
    }
    for _, field := range this.Fields {
       this.TransOpType(field)
       //if notbetween noin notlike
       if field.OpType == base.OpSign[base.Between] {
          dbc = dbc.Where(fmt.Sprintf("%s BETWEEN ? and ?", field.Field),
             field.Values[0], field.Values[1])
       }
       if field.OpType == base.OpSign[base.NotBetween] {
          dbc = dbc.Where(fmt.Sprintf("%s Not BETWEEN ? and ?", field.Field),
             field.Values[0], field.Values[1])
       }

       if field.OpType == base.OpSign[base.Ge] {
          dbc = dbc.Where(fmt.Sprintf("%s >= ?", field.Field), field.Values[0])
       }
       if field.OpType == base.OpSign[base.Gt] {
          dbc = dbc.Where(fmt.Sprintf("%s > ?", field.Field), field.Values[0])
       }
       if field.OpType == base.OpSign[base.Le] {
          dbc = dbc.Where(fmt.Sprintf("%s <= ?", field.Field), field.Values[0])
       }
       if field.OpType == base.OpSign[base.Lt] {
          dbc = dbc.Where(fmt.Sprintf("%s < ?", field.Field), field.Values[0])
       }
       if field.OpType == base.OpSign[base.Eq] {
          dbc = dbc.Where(fmt.Sprintf("%s = ?", field.Field), field.Values[0])
       }
       if field.OpType == base.OpSign[base.Ne] {
          dbc = dbc.Where(fmt.Sprintf("%s != ?", field.Field), field.Values[0])
       }
       if field.OpType == base.OpSign[base.In] {

          dbc = dbc.Where(fmt.Sprintf("%s in (%s)", field.Field, field.Values2InStr()))
       }
       if field.OpType == base.OpSign[base.NotIn] {
          dbc = dbc.Where(fmt.Sprintf("%s not in (%s)", field.Field, field.Values2InStr()))
       }
       if field.OpType == base.OpSign[base.Like] {

          dbc = dbc.Where(fmt.Sprintf("%s like ?", field.Field), this.Value2Like(field.Values[0]))
       }
       if field.OpType == base.OpSign[base.NotLike] {
          dbc = dbc.Where(fmt.Sprintf("%s not like ?", field.Field), this.Value2Like(field.Values[0]))
       }
       if field.OpType == base.OpSign[base.IsNull] {
          dbc = dbc.Where(fmt.Sprintf("%s is null", field.Field))
       }
       if field.OpType == base.OpSign[base.IsNotNull] {
          dbc = dbc.Where(fmt.Sprintf("%s is not null", field.Field))
       }
    }
    return dbc
}

FindRecords

func (this *PageDbRequest) FindRecords(result *page.PageResult) *page.PageResult {

    var db = this.FindTable()
    rows, errs := db.Rows()
    if errs != nil {
       goutils.Error(errs)
       return page.NewPageResultError(errs.Error())
    }
    defer func() {
       if err := rows.Close(); err != nil {
          logrus.Error(err)
       }
    }()

    var records = dto.NewIchubRecords(this.DbClientDto)

    var err = records.TableFields(this.TableName, this.FieldsName).ScanRows(this.TimeToInt, rows)
    if err != nil {
       goutils.Error(err)
       return page.NewPageResultError(err.Error())
    }
    result.Data = records.Records
    return result
}

ScanRows

func (ir *IchubRecords) ScanRows(timeToInt bool, sqlRows *sql.Rows) error {
    ir.TimeToInt = timeToInt

    for sqlRows.Next() {
       var result, row = ir.NewIchubFields2Result()
       if err := sqlRows.Scan(result...); err != nil {
          logrus.Error(err)
          return err
       }
       ir.AppendRow(row)
    }
    ir.PtrRow2Result()
    ir.Count = len(ir.Records)
    return nil
}
func (ir *IchubRecords) NewIchubFields2Result() ([]interface{}, []*IchubField) {
    var ichubFields = ir.MakeIchubFields()
    var result = []interface{}{}
    for _, v := range ichubFields {
       result = append(result, &v.Value)
    }
    return result, ichubFields
}

func (ir *IchubRecords) MakeIchubFields() []*IchubField {
    var IchubFields = []*IchubField{}

    for _, field := range ir.Fields {
       var ichubField = MakeIchubField(ir.DbClientDto, ir.TableName, field)

       IchubFields = append(IchubFields, ichubField)
    }
    return IchubFields
}
func MakeIchubField(dbcli *baseconfig.DbClientDto, table, field string) *IchubField {
    field = strings.TrimSpace(field)

    var goField = FindGoField(dbcli, table, field)
    var goType = goField.GoType
    field = strings.TrimSpace(field)

    if goType == "bool" {
       return NewIchubField(field, goType, *new(sql.NullBool)).SetFieldType(goField.ColumnType)
    }
    if goType == "string" {
       return NewIchubField(field, goType, *new(sql.NullString)).SetFieldType(goField.ColumnType)
    }
    if goType == "uint8" {
       return NewIchubField(field, goType, *new(sql.NullByte)).SetFieldType(goField.ColumnType)
    }
    if goType == "[]uint8" {
       return NewIchubField(field, goType, *new([]int8)).SetFieldType(goField.ColumnType)
    }
    if goType == "uint16" {
       return NewIchubField(field, goType, *new(uint16)).SetFieldType(goField.ColumnType)
    }
    if goType == "uint32" {
       return NewIchubField(field, goType, *new(uint32)).SetFieldType(goField.ColumnType)
    }
    if goType == "uint64" {
       return NewIchubField(field, goType, *new(uint64)).SetFieldType(goField.ColumnType)
    }
    if goType == "int" {
       return NewIchubField(field, goType, *new(sql.NullInt64)).SetFieldType(goField.ColumnType)
    }
    if goType == "int8" {
       return NewIchubField(field, goType, *new(int8)).SetFieldType(goField.ColumnType)
    }
    if goType == "int16" {
       return NewIchubField(field, goType, *new(sql.NullInt16)).SetFieldType(goField.ColumnType)
    }
    if goType == "int32" {
       return NewIchubField(field, goType, *new(sql.NullInt32)).SetFieldType(goField.ColumnType)
    }
    if goType == "int64" {
       return NewIchubField(field, goType, *new(sql.NullInt64)).SetFieldType(goField.ColumnType)
    }
    if goType == "float32" {
       return NewIchubField(field, goType, *new(float32)).SetFieldType(goField.ColumnType)
    }
    if goType == "float64" {
       return NewIchubField(field, goType, *new(sql.NullFloat64)).SetFieldType(goField.ColumnType)
    }

    if goType == "time.Time" {
       return NewIchubField(field, goType, *new(sql.NullTime)).SetFieldType(goField.ColumnType)
    }

    return NewIchubField(field, goType, *new(string)).SetFieldType("string")
}
func FindGoField(dbcli *baseconfig.DbClientDto, tableName, fieldName string) *MetaGoField {
    fieldName = strings.TrimSpace(fieldName)

    var metatable, ok = InstMetadataCache.CacheGet(dbcli.CacheKey() + tableName) //var metatable = FindMapTableGoDict(tableName)
    if !ok {
       logrus.Error("not found metatable ", tableName)
       return nil
    }

    var goField = metatable.FindGoField(fieldName)
    if goField == nil {
       goutils.Error("not found goField ", fieldName)
       return nil
    }
    return goField
}

PtrField2Value

func (ir *IchubRecords) PtrRow2Result() {

    for _, row := range ir.Rows {
       var record = make(map[string]interface{})
       for _, v := range row {
          record[v.Field] = ir.PtrField2Value(v)
       }
       ir.Records = append(ir.Records, record)

    }

}
func (ir *IchubRecords) PtrField2Value(field *IchubField) interface{} {

    var ptr = field.Value
    var checkType = ir.CheckType(field)
    if ptr == nil {
       return ir.PtrNilField2Value(field)
    }

    if checkType == "*int" {
       return ptr.(*int)
    }
    if checkType == "*bool" {
       return ptr.(*bool)
    }
    if checkType == "*uint8" {
       return ptr.(*uint8)
    }
    if checkType == "*[]uint8" {
       var s = baseutils.Any2Str(ptr)
       return &s
    }
    if checkType == "*int8" {
       return ptr.(*int8)
    }
    if checkType == "*int16" {
       return ptr.(*int16)
    }
    if checkType == "*int32" {
       return ptr.(*int32)
    }
    if checkType == "*uint32" {
       return ptr.(*uint32)
    }
    if checkType == "*uint64" {
       return ptr.(*uint64)
    }
    if checkType == "*int64" {
       return ptr.(*int64)
    }
    if checkType == "*float32" {
       return ptr.(*float32)
    }
    if checkType == "*float64" {
       return ptr.(*float64)
    }
    if checkType == "*string" {
       return ptr.(*string)
    }

    if checkType == "*time.Time" {
       return ir.PtrTimeField2Value(field)
    }

    if checkType == "int" {
       return ptr.(int)
    }
    if checkType == "bool" {
       return ptr.(bool)
    }
    if checkType == "uint8" {
       return ptr.(uint8)
    }
    if checkType == "[]uint8" {
       return baseutils.Any2Str(ptr)
    }
    if checkType == "int8" {
       return ptr.(int8)
    }
    if checkType == "int16" {
       return ptr.(int16)
    }
    if checkType == "int32" {

       return ptr.(*sql.NullInt32)
    }
    if checkType == "uint32" {
       return ptr.(uint32)
    }
    if checkType == "uint64" {
       return ptr.(uint64)
    }
    if checkType == "int64" {
       return ptr.(int64)
    }
    if checkType == "float32" {
       return ptr.(float32)
    }
    if checkType == "float64" {
       return ptr.(float64)
    }
    if checkType == "string" {
       return ptr.(string)
    }

    if checkType == "time.Time" {
       return ir.TimeField2Value(field)

    }

    return gconv.String(ptr)
}
func (ir *IchubRecords) PtrNilField2Value(field *IchubField) interface{} {

    var ptr = field.Value
    var checkType = ir.CheckType(field)

    if checkType == "*int" {
       return new(int)

    }
    if checkType == "*bool" {
       return new(bool)

    }
    if checkType == "*uint8" {

       return new(uint8)
    }
    if checkType == "*[]uint8" {

       return new([]uint8)

    }
    if checkType == "*int8" {
       return new(int8)
    }
    if checkType == "*int16" {
       return new(int16)
    }
    if checkType == "*int32" {
       return new(int32)
    }
    if checkType == "*uint32" {
       return new(uint32)
    }
    if checkType == "*uint64" {
       return uint64(0)
    }
    if checkType == "*int64" {
       return new(int64)
    }
    if checkType == "*float32" {
       return new(float32)
    }
    if checkType == "*float64" {
       return new(float64)
    }
    if checkType == "*string" {
       return new(string)
    }

    if checkType == "*time.Time" {
       return ir.PtrTimeField2Value(field)
    }

    if checkType == "int" {
       return 0

    }
    if checkType == "bool" {
       return false

    }
    if checkType == "uint8" {
       return uint8(0)
    }
    if checkType == "[]uint8" {
       return ""
    }
    if checkType == "int8" {
       return int8(0)
    }
    if checkType == "int16" {
       return int16(0)
    }
    if checkType == "int32" {
       return int32(0)
    }
    if checkType == "uint32" {
       return uint32(0)
    }
    if checkType == "uint64" {
       return uint64(0)
    }
    if checkType == "int64" {
       return int64(0)
    }
    if checkType == "float32" {
       return float32(0)
    }
    if checkType == "float64" {
       return float64(0)
    }
    if checkType == "string" {
       if field.IfFieldNumber64() {
          return "0"
       }
       if field.IfFieldNumber() {
          return 0
       }
       return ""

    }
    if checkType == "time.Time" {
       return ir.TimeField2Value(field)
    }
    return gconv.String(ptr)
}

CheckType

func (ir *IchubRecords) CheckType(field *IchubField) string {
    var i = field.Value
    switch i.(type) {
    case *string:
       return "*string"
    case *bool:
       return "*bool"
    case *int:
       return "*int"
    case *int8:
       return "*int8"
    case *int16:
       return "*int16"
    case *int32:
       return "*int32"
    case *int64:
       return "*int64"
    case *byte:
       return "*byte"
    case *time.Time:
       return "*time.Time"

    case *[]uint8:
       return "*[]uint8"

    case *uint16:
       return "*uint16"
    case *uint32:
       return "*uint32"
    case *uint64:
       return "*uint64"
    case *float32:
       return "*float32"
    case *float64:
       return "*float64"

    case time.Time:
       return "time.Time"
    case string:
       return "string"
    case bool:
       return "bool"
    case int:
       return "int"
    case []uint8:
       return "[]uint8"
    case int8:
       return "int8"
    case int16:
       return "int16"
    case int32:
       return "int32"
    case int64:
       return "int64"
    case uint8:
       return "uint8"
    case uint16:
       return "uint16"
    case uint32:
       return "uint32"
    case uint64:
       return "uint64"
    case float32:
       return "float32"
    case float64:
       return "float64"
    }

    return field.GoType
}

标签:case,return,checkType,DB,field,go,解析,goType,ptr
From: https://blog.csdn.net/leijmdas/article/details/141714288

相关文章

  • IndigoSCADA协助ARMxy实现智能工厂可视化解决方案
    一、IndigoSCADA简介IndigoSCADA基于先进的软件架构设计,确保了系统的稳定性和可扩展性。它支持多种通信协议,包括但不限于Modbus、OPCUA、MQTT等,使得与各种工业设备和系统的无缝对接成为可能。此外,IndigoSCADA还提供了丰富的图形库和脚本工具,允许用户根据实际需求快速构建个性化的......
  • 亚信安慧AntDB数据库分布式集群在线升级
     一、概述数据库作为现代信息系统的核心组成部分,其持续优化和升级对于保证系统性能、安全性和稳定性至关重要。在线升级是一种不需要停机就可以进行的升级方式,它的出现极大地提高了数据库升级的效率和可靠性。本文将重点探讨在线升级的优势以及其在实际应用中的相关技术和场景。......
  • JDBC连接数据库
    什么是JDBCJDBC(JavaDatabaseConnectivity)是Java语言中用于连接和操作数据库的一组API。它允许Java程序通过标准的数据库连接方式,与不同种类的关系型数据库进行通信和交互。JDBC提供了一种统一的编程接口,使得开发人员可以使用相同的代码来访问不同的数据库。它提供了一组类......
  • c++解析xml文件实际应用(增删改查进阶)看完必会
    《c++解析xml文件(增删改查)看完必会》遍历xml所有节点下的数据已经在上一篇文章末尾写道,写法大同小异,资源下载也在上一篇提到,这里就不再提及,这篇博客主要是对上一篇基础知识的运用,如有疑问,可以call我XML解析类#include<iostream>#include<string>#include<string.h>#include......
  • 最新干货|互联网算法备案办理要点解析
    一、 算法备案的主体不同于欧盟的算法治理路径,算法主体责任机制是我国算法问责制的基础。原因在于,我国认为算法是开发者价值观的技术体现,因此可以穿透算法面纱将开发者的责任承担至于前线,对应承担算法安全主体责任,也即预设了算法设计的工具属性。《算法推荐规定》《深度合成......
  • Go,你也可以的!-【7.2 panic】
    7.2panicpanic就是Go语言中的崩溃,崩溃也就是程序不可用,这在实际的业务中基本是最严重的BUG。在大部分语言中,产生崩溃的原因基本是差不多的,大多都是访问了空指针、数组越界、内存溢出等。基本可以总结为,发生崩溃都是与系统进行了非法的内存或资源操作。本节代码存放目录......
  • DBA_oracle日期函数-【来自多个项目】
    selectTO_DATE(trunc(F_GXSJ),'YYYY-MONTH-DD')fromfsxx_dx_log_newwheretrunc(F_GXSJ)=TO_DATE()selecttrunc(F_GXSJ)fromfsxx_dx_log_new--2012-10-26selectSUBSTR(TO_CHAR(trunc(F_GXSJ),'YYYY-MM-DD'),6,2)fromfsxx_dx_......
  • 【GaussDB】应用报错 socket is not closed; Urgent packet sent to backend successf
    数据库原理差异在Oracle中连接会话默认永不超时,Mysql中连接会话默认8小时超时,而在GaussDB中,默认30min超时问题排查确认探活是否生效方式一:查询审计日志,可以看到会话退出方式为超时退出:selecttime,type,result,client_conninfo,detail_infofrompg_query_audit('2023-06-06......
  • CSP-J 2021 初赛试题解析(第三部分:完善程序(2))
    完善程序二完整程序代码#include<iostream>usingnamespacestd;structpoint{intx,y,id;};boolequals(pointa,pointb){returna.x==b.x&&a.y==b.y;}boolcmp(pointa,pointb){returna.x!=b.x?a.x<b.x:a.y<b.y;}......
  • Hive源码解析
    1.概述ApacheHive是一款建立在Hadoop之上的数据仓库工具,它提供了类似于SQL的查询语言,使得用户能够通过简单的SQL语句来处理和分析大规模的数据。本文将深入分析ApacheHive的源代码,探讨其关键组件和工作原理,以便更好地理解其在大数据处理中的角色。2.内容在开始源代码分析之前......