一、简介
1.1 go-pg是什么
官网描述为Golang ORM with focus on PostgreSQL features and performance
一个专注于 PostgreSQL 特性和性能的 Golang ORM。
如果你已经厌倦了手动写查询语句,那么可以尝试下go-pg框架来编写业务代码。
1.2 特性
基础类型: integers, floats, string, bool, time.Time, net.IP, net.IPNet.
sql.NullBool, sql.NullString, sql.NullInt64, sql.NullFloat64 and pg.NullTime.
sql.Scanner and sql/driver.Valuer interfaces.
Structs, maps and arrays 默认序列化为json格式.
PostgreSQL 多维数组使用 array tag and Array wrapper.(重点)
hstore使用 hstore tag and Hstore wrapper.(重点)
组合类型Composite types.
默认情况下,所有结构字段都默认为空,并且零值(空字符串、0、零时间、空map映射或切片、nil 指针)被编组为 SQL“NULL”。
pg:",notnull"
标签用户添加SQL 非空约束。pg:",use_zero"
标签允许Go零值.Transactions.
Prepared statements.
Notifications using
LISTEN
andNOTIFY
.拷贝数据 使用
COPY FROM
andCOPY TO
.Timeouts and canceling queries using context.Context.
Automatic connection pooling with circuit breaker support.
Queries retry on network errors.
Working with models using ORM and SQL.
Scanning variables using ORM and SQL.
SelectOrInsert using on-conflict.
INSERT ... ON CONFLICT DO UPDATE using ORM.
Bulk/batch inserts, updates, and deletes.
Common table expressions using WITH and WrapWith.
CountEstimate using
EXPLAIN
to get estimated number of matching rows.ORM 框架支持 has one, belongs to, has many, and many to many with composite/multi-column primary keys.
Soft deletes.
Creating tables from structs.从接口体来创建数据库表
ForEach that calls a function for each row returned by the query without loading all rows into the memory.
1.3 优缺点
1.优点
1.没有rows.Close去手动管理连接
在go-pg中,无需为每个打开的连接进行rows.Close操作。
2.go-pg比其他GORM性能更好
go-pg本身就很专注于性能这块。
3.go-pg自动将行数据映射为go的结构体和slice切片
4.go-pg 生成更高效的连接查询
与其他 ORM 甚至数据库包相比,您可以对连接进行高效查询。
5.简化你的代码
go-