首页 > 其他分享 >一个轻量级golang ORM框架gdbcTemplate

一个轻量级golang ORM框架gdbcTemplate

时间:2023-10-28 21:13:28浏览次数:37  
标签:gdbcTemplate err golang user go com 轻量级 USER

今天介绍一个自己写的轻量级golang ORM框架gdbcTemplate, 目前支持mysql, postgresql等数据库

项目地址位于 https://github.com/guoapeng/gdbctemplate

以下摘自readme文件, 里面有示例供参考.

1. readme file

a lightweight golang ORM framework similar to jdbc in java tech stack

currently the module support connecting db in mysql driver and PostgreSQL driver.

1.1. introduction

this is a go package to connect kinds of database using template approach.

1.2. usage

install dependencies

go get github.com/guoapeng/props v1.1.2
go get github.com/guoapeng/gdbcTemplate

prepare config.properties unser OS user home directory

for mysql


DRIVER_NAME=mysql
USERNAME=username
PASSWORD=your_pass
NETWORK=tcp
SERVER=localhost
PORT=3306
DATABASE=database_name
CHARSET=utf8mb4

in case you are using postgresql, prepare config.properties as below


DRIVER_NAME=pgx
USERNAME=postgres
PASSWORD=your_pass
NETWORK=tcp
SERVER=localhost
PORT=5432
DATABASE=database_name
CHARSET=utf8

import (
    "github.com/guoapeng/gdbcTemplate/template"
    "github.com/guoapeng/props"
    "log"
)

// sql for postgresql
const SqlUser001 = `select USER_ID,
    USER_NAME,
    NICKNAME,
    PASSWORD,
    USER_TYPE,
    DESCRIPTION
    from USER
    where USER_NAME=$1`

const SqlUser002 = `select USER_ID,
    USER_NAME,
    NICKNAME,
    PASSWORD,
    USER_TYPE,
    DESCRIPTION
    from USER
    where USER_TYPE=$1`

const SqlUser003 = "insert into USER(USER_NAME, NICKNAME, CREATE_DATE, UPDATE_DATE, USER_TYPE)" +
        "values($1, $2, $3, current_date, current_date, 'admin' );"


func main() {

    var err error

    if AppConfig, err = propsReader.NewFactory("application", "config.properties").New(); err != nil {
        log.Fatal("failed to load mandatory properties")
        panic(err)
    }

    gdbcTemplate = template.New(AppConfig)

    // insert without transaction
    result, err = gdbcTemplate.Update(SqlUser003, username, nickname)

    // or insert with transaction
    tx, err := gdbcTemplate.BeginTx()
    result, err = tx.Update(sqlfile.SqlUser003, username, nickname)

    if err != nil {
        tx.Rollback()
        log.Println("ERROR: failed to create user", err)
        return "", fmt.Errorf("failed to create user")
    }

    // query single row
    user := gdbcTemplate.QueryRow(SqlUser001, userName)
    .Map(UserMapper)
    .ToObject()

    // in somce cases, we need to query data thata not commited through transaction,
    // we can do that like the following
    user := tx.QueryRow(SqlUser001, userName)
        .Map(UserMapper)
        .ToObject()

   // query multiple rows
   users := gdbcTemplate.QueryForArray(SqlUser002)
    .Map(mapper.UserRowsMapper, userType).ToArray()

   // query multiple rows within transaction
   users := tx.QueryForArray(SqlUser002)
    .Map(mapper.UserRowsMapper, userType).ToArray()

    tx.Commit()


}

func UserMapper(row *sql.Row) interface{} {
    user := new(domain.User)
    _ = rows.Scan(&user.UserId,
        &user.UserName,
        &user.Nickname,
        &user.Password,
        &user.UserType,
        &user.Description))
    _ = row.Scan(&domainobj.UserId, &domainobj.MemoTarget)

    return user
}

func UserRowsMapper(rows *sql.Rows) interface{} {
    user := new(domain.User)
    _ = rows.Scan(&user.UserId,
        &user.UserName,
        &user.Nickname,
        &user.Password,
        &user.UserType,
        &user.Description)
    return user
}

1.3. development guide

1.3.1. build the go files

# user project root
go build datasource/datasource.go
go build mapper/rowsmapper.go
go build template/gdbcTemplate.go

1.3.2. run test


go test template/gdbcTemplate_test.go
go test transaction/transaction_test.go
go test datasource/dbManager_test.go

# or

go test ./...

1.3.3. generate mock class

generate mock classes with testify


# install mockery

cd <project_home>
go install github.com/vektra/mockery/[email protected]

cd <project_home>
go get github.com/stretchr/testify/mock
go get github.com/vektra/mockery/.../

cd <project_home>
# generate mock structs
mockery --recursive --name "GdbcTemplate|RowMapper|RowsMapper|Transaction|DataSource|ConnManager"

mockery -r -all

1.4. publish

1.4.1. create tag

    git tag v1.x.x

1.4.2. upload tag to the repository

    git push origin --tags

1.5. todo list

  1. remove dependency on github.com/guoapeng/props to only rely on sql.datasource
  2. support sqlite
  3. adopt a log lib which supports debug, infor, warning and error levels

1.6. trouble shooting

  1. cannot find module
    in case you encountered the issue:
    $ go build
    build .: cannot find module for path .
  • solution:

    replace the go build command like

     $ go build mapper/rowsmapper.go
    

标签:gdbcTemplate,err,golang,user,go,com,轻量级,USER
From: https://www.cnblogs.com/guoapeng/p/17794629.html

相关文章

  • golang 中使用 writev (sendmsg) 系统调用来一次发送多块数据
    作者:张富春(ahfuzhang),转载时请注明作者和引用链接,谢谢!cnblogs博客zhihuGithub公众号:一本正经的瞎扯writev,或者说sendmsg等系统调用,能够发送多个数据块。从节约系统调用次数的角度说,这个api非常好。下面演示如何在golang中使用sendmsg系统调用:funcsendmsg......
  • 云端golang开发,无需本地配置,能上网就能开发和运行
    欢迎访问我的GitHub这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos需求学习golang的时候,需要一个IDE,还需要一个能运行程序的环境,以及一个MySQL数据库对于有经验的程序员来说,自己动手安装部署即可,但是小白和懒人也是存在的...背景背......
  • golang 获取 mongo 数据库状态
    命令行模式navicatgolangpackagemainimport( "context" "encoding/json" "fmt" "log" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-drive......
  • Nacos相关技术文档&Golang操作Nacos实现配置监听的代码
    Nacos相关技术文档Nacos中文文档~~~(三)Nacos开发教程之服务数据持久化(四)Nacos开发教程之SpringCloud集成服务注册(参考,后续用go实现)(五)Nacos开发教程之SpringCloud集成配置管理(参考,后续用go实现)(六)Nacos开发教程之后台系统使用~~~Mac-M1电脑本地使用docker搭建Nacos-Server参考:http......
  • golang的Leaf框架安装步骤
    最近在学习golang的Leaf游戏服务器框架(官方github),官方的安装步骤,非常简单,如下图:我在安装的时候也遇到一些疑问,因此记录下来我的实操步骤!1、我的现有GOPATH=E:\Go,src目录下有一些做过的项目2、获取LeafServer,我在src目录下clone的,遵循以前的原则,项目文件都放到GOPATH的src目录......
  • Golang Gin 实战(一)| 快速安装入门
    Gin 是一个非常优秀的GolangWebFramework,它不光API友好,性能也非常高,并且设计简洁,便于入门。所以它(Gin)非常受欢迎,在Github上已经三万三千多个星星,也是我最喜欢的Web框架。  入门要求要想使用GolangGin这个框架,你必须要得会Golang这门语言,如果你还没有开始学,我强烈推荐给你,......
  • golang validator 检验工具的使用指北
    golangvalidator包的使用指北原创阿兵云原生阿兵云原生2023-09-1009:27发表于广东看到validator咱们第一反应会想起啥?见名知意我就可以知道他是一个验证器,如果用过ginweb框架的同学,自然是用过gin里面的validator,只不过gin中使用的关键字是binding去做标识 ......
  • Golang logrus用法
    packagexlogimport( "bufio" "fmt" "github.com/sirupsen/logrus"rotatelogs"github.com/lestrrat-go/file-rotatelogs""github.com/rifflock/lfshook" "os" "time")typeConf......
  • Golang sync包中errgroup的使用详解
    WaitGroup主要用于控制任务组下的并发子任务。它的具体做法就是,子任务goroutine执行前通过Add方法添加任务数目,子任务goroutine结束时调用Done标记已完成任务数,主任务goroutine通过Wait方法等待所有的任务完成后才能执行后续逻辑packagemainimport("ne......
  • golang之xorm简单使用
    gogetgithub.com/go-xorm/xormpackagemainimport("fmt"_"github.com/go-sql-driver/mysql""github.com/go-xorm/xorm")typePointInfostruct{Idint64`xorm:"pkautoincr"`Product......