// Copyright (c) 2021. Huawei Technologies Co., Ltd. All rights reserved.

// Package common this file for db handler
package common

import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql" // mysql driver
"huawei.com/npu-exporter/hwlog"
"sync"
)

const (
// DBType db type
DBType = "mysql"
// DBSecretName the secret name which contains db connection path
DBSecretName = "mysql-secret"
// DBSecretNameSpace the namespace for secret which contains db connection path
DBSecretNameSpace = "mindx-dl"
// GetDBSecretRetryCount retry count for getting secret
GetDBSecretRetryCount = 10
// GetDBSecretTimeInterval interval for getting secret, unit: second
GetDBSecretTimeInterval = 5
// DBSecretConnectionPathKey db connection path key in secret
DBSecretConnectionPathKey = "connection-path"
// DBTableOption db table option
DBTableOption = "gorm:table_options"
// InnoDBEngine innodb engine
InnoDBEngine = "ENGINE=InnoDB"
)

var dbOnce sync.Once

// DbCommonHandler db handler
type DbCommonHandler struct {
db *gorm.DB
dbType string
dbPath string
}

// NewDBInstance create db instance
func NewDBInstance(dbType, dbPath string) *DbCommonHandler {
handler := &DbCommonHandler{
dbType: dbType,
dbPath: dbPath,
}

return handler
}

func (handler *DbCommonHandler) initDBInstance() {
dbase, err := gorm.Open(handler.dbType, handler.dbPath)
if err != nil {
hwlog.RunLog.Fatal(err)
}
hwlog.RunLog.Info("connect to db success")
handler.db = dbase
}

// GetDB return db instance
func (handler *DbCommonHandler) GetDB() *gorm.DB {
dbOnce.Do(handler.initDBInstance)
return handler.db
}

// CloseDB close db connection
func (handler *DbCommonHandler) CloseDB() {
if handler.db == nil {
return
}

if err := handler.db.Close(); err != nil {
hwlog.RunLog.Error(err)
}
}

// SetScopes set scopes
func (handler *DbCommonHandler) SetScopes(scopes ...func(db *gorm.DB) *gorm.DB) *gorm.DB {
return handler.GetDB().Scopes(scopes...)
}

// SetPager return pager
func (handler *DbCommonHandler) SetPager(page, pageSize uint64) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
offset := (page - 1) * pageSize
return db.Offset(offset).Limit(pageSize)
}
}

// SetQueryFields set query field
func (handler *DbCommonHandler) SetQueryFields(fieldsNameList interface{}) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
return db.Select(fieldsNameList)
}
}

// SetModel set query table
func (handler *DbCommonHandler) SetModel(model interface{}) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
return db.Model(model)
}
}

// SetJoins set joins
func (handler *DbCommonHandler) SetJoins(query string, values ...interface{}) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
return db.Joins(query, values...)
}
}

// QueryAll query all data
func (handler *DbCommonHandler) QueryAll(db *gorm.DB, outPut, condition interface{}, param ...interface{}) *gorm.DB {
return db.Where(condition, param...).Find(outPut)
}

// First return the fist match data
func (handler *DbCommonHandler) First(db *gorm.DB, outPut, condition interface{}, param ...interface{}) *gorm.DB {
return db.Where(condition, param...).First(outPut)
}

mindxdl---common---db_handler.go的更多相关文章

  1. Socket聊天程序——Common

    写在前面: 上一篇记录了Socket聊天程序的客户端设计,为了记录的完整性,这里还是将Socket聊天的最后一个模块--Common模块记录一下.Common的设计如下: 功能说明: Common模块 ...

  2. angularjs 1 开发简单案例(包含common.js,service.js,controller.js,page)

    common.js var app = angular.module('app', ['ngFileUpload']) .factory('SV_Common', function ($http) { ...

  3. Common Bugs in C Programming

    There are some Common Bugs in C Programming. Most of the contents are directly from or modified from ...

  4. ANSI Common Lisp Practice - My Answers - Chatper - 3

    Ok, Go ahead. 1 (a) (b) (c) (d) 2 注:union 在 Common Lisp 中的作用就是求两个集合的并集.但是这有一个前提,即给的两个列表已经满足集合的属性了.具体 ...

  5. [LeetCode] Lowest Common Ancestor of a Binary Tree 二叉树的最小共同父节点

    Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According ...

  6. [LeetCode] Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最小共同父节点

    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...

  7. [LeetCode] Longest Common Prefix 最长共同前缀

    Write a function to find the longest common prefix string amongst an array of strings. 这道题让我们求一系列字符串 ...

  8. 48. 二叉树两结点的最低共同父结点(3种变种情况)[Get lowest common ancestor of binary tree]

    [题目] 输入二叉树中的两个结点,输出这两个结点在数中最低的共同父结点. 二叉树的结点定义如下:  C++ Code  123456   struct BinaryTreeNode {     int ...

  9. 动态规划求最长公共子序列(Longest Common Subsequence, LCS)

    1. 问题描述 子串应该比较好理解,至于什么是子序列,这里给出一个例子:有两个母串 cnblogs belong 比如序列bo, bg, lg在母串cnblogs与belong中都出现过并且出现顺序与 ...

  10. 【leetcode】Longest Common Prefix

    题目简述: Write a function to find the longest common prefix string amongst an array of strings. 解题思路: c ...

随机推荐

  1. FastJson远程命令执行漏洞学习笔记

    FastJson远程命令执行漏洞学习笔记 Fastjson简介 fastjson用于将Java Bean序列化为JSON字符串,也可以从JSON字符串反序列化到JavaBean.fastjson.ja ...

  2. KingbaseES V8R6备份恢复案例之---手工清理冗余历史备份

    案例说明: 对于KingbaseES V8R6的通过sys_rman执行的物理历史备份,可以在执行备份时,备份的保留(retention)策略自动清理.不能通过手工删除备份,可以通过expire参数手 ...

  3. KingbaseES如何更改现有表的主键

    更改主键 假设您必须更改现有表的主键.您可以通过执行以下语句来实现此目的: ALTER TABLE tablename DROP CONSTRAINT tablename_pkey , ADD PRI ...

  4. KingbaseES 的 Lateral 连接

    一.什么是 Lateral 连接 根据文档,它的作用是: LATERAL 关键字可以位于子 SELECT FROM 项之前.这允许子 SELECT 引用 FROM 列表中出现在它之前的 FROM 项的 ...

  5. K8S name_namespace

    Name 由于K8S内部,使用"资源"来定义每一种逻辑概念(功能),故没种"资源",都应该有自己的"名称" "资源"有 ...

  6. 高可用代理服务器实现keepalive+squid

    〇.前言 之前单机部署了squid代理服务器,现在实现一下高可用. 还有自定义squid的error页面 准备:两台centos7(1C2GB) ​ 三个可用IP,一主一备一虚拟IP(VIP) 一.安 ...

  7. Python数据科学手册-机器学习: 支持向量机

    support vector machine SVM 是非常强大. 灵活的有监督学习算法, 可以用于分类和回归. 贝叶斯分类器,对每个类进行了随机分布的假设,用生成的模型估计 新数据点 的标签.是属于 ...

  8. 复现禅道V16.5的SQL注入(CNVD-2022-42853)

    漏洞详情 禅道V16.5未对输入的account参数内容作过滤校验,导致攻击者拼接恶意SQL语句执行. 环境搭建 环境下载:禅道V16.5 下载后双击运行,进入目录运行start.exe 直接访问即可 ...

  9. java基础之常用类1

    java基础 以下内容为本人的学习笔记,如需要转载,请声明原文链接   java常用类: 1.内部类 2.Object类 3.Object类常用方法 4.包装类 5.String类 6.BigDeci ...

  10. Codeforces Round #442 (Div. 2) B. Nikita and string

    题意:求最长可以分a b a为三部分子串,a b a可以为空 思路在代码里 1 #include<cstdio> 2 #include<iostream> 3 #include ...