golang基础-Postgresql-ORM框架github.com/go-pg/pg学习五(实战)

Posted 进击的小猿

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang基础-Postgresql-ORM框架github.com/go-pg/pg学习五(实战)相关的知识,希望对你有一定的参考价值。

文章目录


golang基础-Postgresql-ORM框架github.com/go-pg/pg学习一(连接数据库、创建、删除表)

golang基础-Postgresql-ORM框架github.com/go-pg/pg学习二(增删改)

golang基础-Postgresql-ORM框架github.com/go-pg/pg学习三(QueryOne、Query、Select用法)

golang基础-Postgresql-ORM框架github.com/go-pg/pg学习四(其他)

以上4篇是总结了,golang中关于对pg对学习,今天就来总结下实例代码

接口介绍

接口如下:
1、完成支付后台接口
CreateWXOrder 创建订单
UpdateOrderById 通过ID修改订单字段值
UpdateOrderByOrderNum 修改订单字段值,这里是通过订单编号
GetOrderByNum 通过编号查询订单
GetOrderById 通过ID查询订单
GetCourseByOrderNum 通过单号,查询每笔订单关联的课程列表
UpdateOrderByOrderNum1修改订单字段值,这里是通过订单编号(方法二)
GetOrdersByCertainTime 获取某个时间段内的订单
GetOrdersForUser 获取一个用户的所有订单
GetOrdersByCertainTimeForUser 获取一个用户特性时间断的订单

接口代码

我这里就不去一个个接口分析了,之前已经总结过,我就直接贴代码了
我在数据库生成的数据如下:

package main

import (
	"bytes"
	"fmt"
	"github.com/go-pg/pg"
	"github.com/go-pg/pg/orm"
	_ "github.com/lib/pq"
	"github.com/pkg/errors"
	"time"
)

const (
	host     = "localhost"
	port     = 5432
	user     = "wyfzhiliao"
	password = "wyfzhiliao"
	dbname   = "go"
)

func connet() *pg.DB
	db:=pg.Connect(&pg.Options
		User:user,
		Password:password,
		Database:dbname,
	)

	var n int
	_,err:=db.QueryOne(pg.Scan(&n),"SELECT 1")
	if err != nil
		panic(err)
	
	return db




type Order struct 
tableName		struct	`sql:"u_order",pg:",discard_unknown_columns"`
Id				string		`sql:"id,pk,type:varchar(40)"` //ID
AppId		    string		`sql:"app_id,type:varchar(40)"` //公众账号String(32)
MchId           string		`sql:"mch_id,type:varchar(40)"`//商户String(32)
NonceStr		string		`sql:"nonce_str,type:varchar(40)"`//随机字符String(32)
Sign		    string		`sql:"sign,type:varchar(40)"`//签名String(32)
SignType		string		`sql:"sign_type,type:varchar(40)"`//签名类型String(32)
Body			string		`sql:"body,type:varchar(130)"` //订单描述String(128)
//Detail  		string		`sql:"body,type:varchar(6000)"` //商品详情String(128)
OutTradeNo		string      `sql:"out_trade_no,type:varchar(40)"`//订单号String(32)
TotalFee		int         `sql:"total_fee,type:int"` //总费用单位为分
FeeType		    string      `sql:"fee_type,default:'CNY',type:varchar(10)"` //费用类型String(16) CNY
SpbillCreateIp	string		`sql:"spbill_create_ip,type:varchar(20)"`//APP和网页支付提交用户端ipString(16)
TimeStart       time.Time	`sql:"time_start,default:now(),type:timestamptz"`//String(14)交易开始时间 yyyyMMddHHmmss,如2009年12月25日9点10分10秒表示为20091225091010
TimeExpire      time.Time	`sql:"time_expire,default:now(),type:timestamptz"`//String(14)交易结束时间 yyyyMMddHHmmss,如2009年12月25日9点10分10秒表示为20091225091010
TradeType		string      `sql:"trade_type,type:varchar(20)"`//交易类型 JSAPI 公众号支付  NATIVE 扫码支付 APP APP支付 String(16)

WechatOpenId	string		`sql:"wechat_open_id,type:varchar(130)"`//微信公众号,用户标识 String(128)
WechatUnionId	string		`sql:"wechat_union_id,type:varchar(130)"`//只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。
WechatPayKey	string		`sql:"wechat_pay_key,type:varchar(40)"`//key为商户平台设置的密钥key
UserId			string		`sql:"user_id,type:varchar(40)"`//下单关联的用户
Platform		string		`sql:"platform,type:varchar(20)"`//订单来源 公众号或者pc
PayCourses		[]string	`sql:"pay_courses,type:text[]"`//订单关联的课程
PayStatus       int         `sql:"pay_status,type:int"` //交易状态 0预付 1成功 -1失败/取消







func CreateTabel(db *pg.DB)  error
	for _,model:= range []interface&Order
		err:=db.CreateTable(model,&orm.CreateTableOptions
			IfNotExists:true,
			FKConstraints:false,
		)
		if err!= nil
			fmt.Println(err)
			return err
		
	
	return nil


func main()  
	db:=connet()
	fmt.Println("db",db)

	CreateTabel(db)



	payCourse:=[]string"1","3","4"
	course_order:=&Order
		Id:"4",
		AppId:"11111",
		MchId:"22222",
		NonceStr:"werwerwl",
		Sign:"jlkwejkflwjel",//SetOrder返回
		Body:"课程很好",
		OutTradeNo:"2343200000",
		TotalFee:23232,
		SpbillCreateIp:"sdfsf",
		TradeType:"spa",

		WechatOpenId:"234234",
		WechatUnionId:"llj2ljk",
		WechatPayKey:"ljl34ll[[[",
		UserId:"342344",
		Platform:"1",//公众号
		PayCourses:payCourse,
		PayStatus:1,
	
	CreateWXOrder(db,course_order)

	//通过ID获取订单
	//order,er:=GetOrderById(db,"1")
	//fmt.Println(order,"---",er)

	//通过编号获取订单
	//order,err := GetOrderByNum(db,"24322342089")
	//fmt.Println(order,"----",err)

	//通过ID修改订单
	//updateOrder:=Order
	//	Id:"1",
	//
	//er=UpdateOrderById(db,&updateOrder, func(order_parms *Order) 
	//	order_parms.WechatPayKey = "yyyyyyyyyy66666"
	//)

	//通过订单编号修改订单
	//user:=&Order
	//	//Id:25,
	//	Body:"67776urruu",
	//	Sign:"saferrr",
	//	Platform:"sfs",
	//	WechatPayKey:"yyyyyyyyyy66666",
	//
	db.Model(user).Set("body=?body,sign=?sign").Where("platform=?platform and wechat_pay_key=?wechat_pay_key").Update()

	//通过订单编号修改订单
	//var setParms = map[string]string"body":"body", "sign":"sign",
	//var whereParms = map[string]string"wechat_pay_key":"wechat_pay_key",
	//UpdateOrderByOrderNum(db,setParms, whereParms,func(order_params *Order) 
	//	*order_params=Order
	//		Body:"我是新的bodyeee",
	//		Sign:"jjel",
	//		WechatPayKey:"yyyyyyyyyy66666",
	//	
		/*或者如下的方式也可以*/
		//order_params.Body = "我是新的body"
		//order_params.Sign = "jlkwejkflwjel"
		//order_params.WechatPayKey = "yyyyyyyyyy66666"
	//)


	//通过订单编号获取课程列表
	//order,_:= GetCourseByOrderNum(db,"24322342089")
	//fmt.Println("payCourse",order,reflect.TypeOf(order))

	//获取特定时间段的订单
	//orders,_:=GetOrdersByCertainTime(db,"2018-11-06 16:01:17","2018-11-06 18:08:43")

	//获取某个用户特定时间段的订单
	//orders,_:=GetOrdersByCertainTimeForUser(db,"342344","2018-11-06 16:01:17","2018-11-07 09:32:52")
	//fmt.Println(orders)

	//获取用户的所有订单
	//orders,_:=GetOrdersForUser(db,"3423")


	db.Model(user).Set("body=?body,sign=?sign").Where("platform=?platform and wechat_pay_key=?wechat_pay_key").Update()
	//通过订单编号更新订单
	order:=&Order
		OutTradeNo:"24322342089",
	
	UpdateOrderByOrderNum(db,order, func(order *Order) 
		order.Body = "我已经被修改"
	)




//todo 查询


func Str2TimeTemp(formatTimeStr string) time.Time
	timeLayout := "2006-01-02 15:04:05"
	loc, _ := time.LoadLocation("Local")
	theTime, _ := time.ParseInLocation(timeLayout, formatTimeStr, loc) //使用模板在对应时区转化为time.time类型

	return theTime


/*查询用户的所有订单 按订单时间降序*/
func GetOrdersForUser(db *pg.DB,userId string)(*[]Order,error)
	order:=new([]Order)
	err:=db.Model(order).Where("user_id =?",userId).Order("time_expire DESC").Select()
	if err!= nil
		fmt.Println("error",err)
		return nil,errors.Wrapf(err, "GetOrdersForUser order by userId error, id:%s ",userId)
	

	return  order,nil



/*查询某个用户某个时间段位的订单*/
func GetOrdersByCertainTimeForUser(db *pg.DB,userId string,startTimeStr string,endTimeStr string) (*[]Order,error) 
	time_start:=Str2TimeTemp(startTimeStr)
	time_end:=Str2TimeTemp(endTimeStr)

	order:=new([]Order)
	err:=db.Model(order).Where("time_start >= ?",time_start).
		Where("time_expire <= ?",time_end).Where("user_id = ?",userId).Select()

	if err!=nil
		return nil,errors.Wrap(err, "GetOrdersByCertainTime order by time error, id: ")
	
	return order,nil




/*查询某个时间段位的订单*/

func GetOrdersByCertainTime(db *pg.DB,startTimeStr string,endTimeStr string) (*[]Order,error) 
	time_start:=Str2TimeTemp(startTimeStr)
	time_end:=Str2TimeTemp(endTimeStr)

	//func new(Type) *Type
	order:=new([]Order)
	err:=db.Model(order).Where("time_start >= ?",time_start).
		Where("time_expire <= ?",time_end).Select()

	if err!=nil
		 fmt.Println("err",err)
		 return nil,errors.Wrap(err, "GetOrdersByCertainTime order by time error, id: ")
	
	return order,nil




/*通过单号,查询每笔订单关联的课程列表*/
func GetCourseByOrderNum(db *pg.DB,orderNum string)([]string,error)
	order:=new(Order)
	err:= db.Model(order).Column("pay_courses").Where("out_trade_no = ?",orderNum).Select()
	if err!=nil//查询不到
		return nil,err
	
	return order.PayCourses,nil






/*通过编号查询订单*/
func GetOrderByNum(db *pg.DB,orderNum string)(*Order,error)
	order:=new(Order)
	err:= db.Model(order).Where("out_trade_no = ?",orderNum).Select()

	if err!=nil//查询不到
		return nil,err
	

	return order,nil



/*通过ID查询订单*/
func GetOrderById(db *pg.DB,orderId string)(*Order,error)
	order:=&OrderId:orderId
	err:=db.Select(order)

	if err!= nil
		return nil, errors.Wrap(err, "query error, id: " + orderId)
	
	return order,nil


//todo 修改
/*通过某个字段查询,修改订单字段值,这里是通过订单编号*/

func UpdateOrderByOrderNum(db *pg.DB,order *Order,f func(order2 *Order)) error

	order,err:=GetOrderByNum(db,order.OutTradeNo)

	if err != nil
		return errors.Wrapf(err, "GetOrderByNum order by num error, id:%s ",order.OutTradeNo)
	
	f(order)

	_,err=db.Model(order).Set("body=?",order.Body).
		Where("out_trade_no=?",order.OutTradeNo).Update()

	if err != nil
		return errors.Wrap(err, "UpdateOrderByOrderNum order by num error, id: " + order.Id)
	
	return nil




/*通过ID修改订单字段值*/
func UpdateOrderById(db *pg.DB,updateOrder *Order,f func(order *Order)) error 
	order,err:=GetOrderById(db,updateOrder.Id)
	if err!= nil
		return errors.Wrap(err, "GetOrderById order by id error, id: " + updateOrder.Id)
	

	f(order)

	err = db.Update(order)

	if err!= nil
		return errors.Wrap(err, "query error, id: " + updateOrder.Id)
	
	return  nil



/*通过某个字段查询,修改订单字段值,这里是通过订单编号*/
func UpdateOrderByOrderNum1(db *pg.DB, setParams map[string]string,
	whereParams map[string]string,f func(order_params *Order)) error
	var order = &Order
	f(order)
	cSetParams := CreateParms(setParams,"set")
	cWhereParams := CreateParms(whereParams,"where")
	_,err:=db.Model(order).Set(cSetParams).
		Where(cWhereParams).Update()

	if err != nil
		return errors.Wrap(err, "UpdateOrderByOrderNum order by num error, id: " + order.Id)
	
	return nil

/**构造查询条件*/
func CreateParms(a map[string]string,paramType string) string
	var map_len = len(a)-1
	var buffer bytes.Buffer
	var count = 0
	for k,v:=range a
		buffer.WriteString(k)
		buffer.WriteString("=?")
		buffer.WriteString(v)
		if count < map_len
			if paramType == "set"
				buffer.WriteString(",")
			
			if paramType == "where"
				buffer.WriteString(" and ")
			
		
		count++
	
	return buffer.String()




//todo 创建
/*创建订单*/
func CreateWXOrder(db *pg.DB,orderModel *Order) (bool,error)
	exist,err:=JudgeOrderExistByNum(db,orderModel.OutTradeNo)
	if err!= nil
		return false,errors.Wrapf(err, "insert wxpay error, openid: %s", orderModel.WechatOpenId)
	
	if !exist//查询未果,创建订单
		_,err := db.Model(orderModel).Insert()
		if err!= nil
			orderModel.Id = ""
			return exist,errors.Wrapf(err, "insert wxpay error, openid: %s", orderModel.WechatOpenId)
		
		return  exist,nil
	else //订单存在
		return exist,nil
	

/*查询订单是否存在*/
func JudgeOrderExistByNum(db *pg.DB,orderNum string) (bool,error)
	exist,err:=db.Model(&Order).Where("out_trade_no = ?",orderNum).Exists()

	if err!= nil
		return false,errors.Wrapf(err, "JudgeOrderExistByNum wxpay Exists error, orderNum: %s", orderNum)
	

	if exist 
		return true ,nil
	
	return false,nil


以上是关于golang基础-Postgresql-ORM框架github.com/go-pg/pg学习五(实战)的主要内容,如果未能解决你的问题,请参考以下文章

golang基础学习及web框架

golang 都有哪些比较稳定的 web 开发框架

某互联网上市公司基于 Golang 的运维基础框架

今晚九点|某互联网上市公司基于 Golang 的运维基础框架

明晚九点|某互联网上市公司基于 Golang 的运维基础框架

[golang] 语法基础之结构体