Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

V0.0.3 #78

Closed
wants to merge 12 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ VALUES
下载Gorm-Plus

```SQL
go get github.com/acmestack/gorm-plus
go get github.com/aixj1984/gorm-plus
```


Expand All @@ -62,7 +62,7 @@ VALUES
package main

import (
"github.com/acmestack/gorm-plus/gplus"
"github.com/aixj1984/gorm-plus/gplus"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
Expand Down Expand Up @@ -135,5 +135,5 @@ func main() {

然而,`Gorm-Plus`的强大功能远不止于此。

更多文档请查看: [https://github.com/acmestack/gorm-plus/wiki](https://github.com/acmestack/gorm-plus/wiki)
更多文档请查看: [https://github.com/aixj1984/gorm-plus/wiki](https://github.com/aixj1984/gorm-plus/wiki)

2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module github.com/acmestack/gorm-plus
module github.com/aixj1984/gorm-plus

go 1.18

Expand Down
107 changes: 95 additions & 12 deletions gplus/dao.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package gplus

import (
"database/sql"
"github.com/acmestack/gorm-plus/constants"
"reflect"
"strings"
"time"

"github.com/aixj1984/gorm-plus/constants"
"gorm.io/gorm"
"gorm.io/gorm/schema"
"gorm.io/gorm/utils"
"reflect"
"strings"
)

var globalDb *gorm.DB
Expand All @@ -34,11 +37,12 @@ func Init(db *gorm.DB) {
}

type Page[T any] struct {
Current int
Size int
Total int64
Records []*T
RecordsMap []T
Current int `json:"page"` // 页码
Size int `json:"pageSize"` // 每页大小
Total int64 `json:"total"`
Records []*T `json:"list"`
CurTime int64 `json:"curTime"` // 当前时间,毫秒
RecordsMap []T `json:"listMap"`
}

type Dao[T any] struct{}
Expand Down Expand Up @@ -148,7 +152,7 @@ func SelectById[T any](id any, opts ...OptionFunc) (*T, *gorm.DB) {
q.Eq(getPkColumnName[T](), id)
var entity T
resultDb := buildCondition(q, opts...)
return &entity, resultDb.First(&entity)
return &entity, resultDb.Take(&entity)
}

// SelectByIds 根据 ID 查询多条记录
Expand All @@ -162,7 +166,7 @@ func SelectByIds[T any](ids any, opts ...OptionFunc) ([]*T, *gorm.DB) {
func SelectOne[T any](q *QueryCond[T], opts ...OptionFunc) (*T, *gorm.DB) {
var entity T
resultDb := buildCondition(q, opts...)
return &entity, resultDb.First(&entity)
return &entity, resultDb.Take(&entity)
}

// SelectList 根据条件查询多条记录
Expand All @@ -173,6 +177,70 @@ func SelectList[T any](q *QueryCond[T], opts ...OptionFunc) ([]*T, *gorm.DB) {
return results, resultDb
}

// add start

// SelectByIdGeneric 查询时,转化为其他类型
// 第一个泛型代表数据库表实体
// 第二个泛型代表返回记录实体
func SelectByIdGeneric[T any, R any](id any, opts ...OptionFunc) (*R, *gorm.DB) {
q, _ := NewQuery[T]()
q.Eq(getPkColumnName[T](), id)
var entity R
resultDb := buildCondition(q, opts...)
return &entity, resultDb.First(&entity)
}

// Pluck 取某列值,不去重
func Pluck[T any, R any](column string, q *QueryCond[T], opts ...OptionFunc) ([]R, *gorm.DB) {
var results []R
resultDb := buildCondition(q, opts...)
resultDb.Pluck(column, &results)
return results, resultDb
}

// PluckDistinct 取某列值,去重
func PluckDistinct[T any, R any](column string, q *QueryCond[T], opts ...OptionFunc) ([]R, *gorm.DB) {
var results []R
resultDb := buildCondition(q, opts...)
resultDb.Distinct(column).Pluck(column, &results)
return results, resultDb
}

// SelectListBySql 按任意SQL执行,指定返回类型数组
func SelectListBySql[R any](querySql string, opts ...OptionFunc) ([]*R, *gorm.DB) {
resultDb := getDb(opts...)
var results []*R
resultDb = resultDb.Raw(querySql).Scan(&results)
return results, resultDb
}

// SelectOneBySql 根据原始的SQL语句,取一个
func SelectOneBySql[R any](countSql string, opts ...OptionFunc) (R, *gorm.DB) {
resultDb := getDb(opts...)
var result R
resultDb = resultDb.Raw(countSql).Scan(&result)
return result, resultDb
}

// ExcSql 按任意SQL执行,返回影响的行
func ExcSql(querySql string, opts ...OptionFunc) *gorm.DB {
resultDb := getDb(opts...)
resultDb = resultDb.Exec(querySql)
return resultDb
}

// add end

// SelectListGeneric 根据条件查询多条记录
// 第一个泛型代表数据库表实体
// 第二个泛型代表返回记录实体
func SelectListGeneric[T any, R any](q *QueryCond[T], opts ...OptionFunc) ([]*R, *gorm.DB) {
resultDb := buildCondition(q, opts...)
var results []*R
resultDb.Scan(&results)
return results, resultDb
}

// SelectPage 根据条件分页查询记录
func SelectPage[T any](page *Page[T], q *QueryCond[T], opts ...OptionFunc) (*Page[T], *gorm.DB) {
option := getOption(opts)
Expand All @@ -190,21 +258,27 @@ func SelectPage[T any](page *Page[T], q *QueryCond[T], opts ...OptionFunc) (*Pag
var results []*T
resultDb.Scopes(paginate(page)).Find(&results)
page.Records = results
page.CurTime = time.Now().UnixMilli()
return page, resultDb
}

// SelectCount 根据条件查询记录数量
func SelectCount[T any](q *QueryCond[T], opts ...OptionFunc) (int64, *gorm.DB) {
var count int64
resultDb := buildCondition(q, opts...)
//fix 查询有设置Select并且数量只有一个且有设置别名,生成sql不对问题
resultDb.Statement.Selects = nil
resultDb.Count(&count)
return count, resultDb
}

// Exists 根据条件判断记录是否存在
func Exists[T any](q *QueryCond[T], opts ...OptionFunc) (bool, *gorm.DB) {
func Exists[T any](q *QueryCond[T], opts ...OptionFunc) (bool, error) {
count, resultDb := SelectCount[T](q, opts...)
return count > 0, resultDb
if resultDb.Error == gorm.ErrRecordNotFound {
return false, nil
}
return count > 0, resultDb.Error
}

// SelectPageGeneric 根据传入的泛型封装分页记录
Expand Down Expand Up @@ -232,6 +306,7 @@ func SelectPageGeneric[T any, R any](page *Page[R], q *QueryCond[T], opts ...Opt
resultDb.Scopes(paginate(page)).Scan(&results)
page.Records = results
}
page.CurTime = time.Now().UnixMilli()
return page, resultDb
}

Expand Down Expand Up @@ -279,6 +354,10 @@ func buildCondition[T any](q *QueryCond[T], opts ...OptionFunc) *gorm.DB {
resultDb.Select(q.selectColumns)
}

if len(q.omitColumns) > 0 {
resultDb.Omit(q.omitColumns...)
}

expressions := q.queryExpressions
if len(expressions) > 0 {
var sqlBuilder strings.Builder
Expand Down Expand Up @@ -327,6 +406,10 @@ func buildSqlAndArgs[T any](expressions []any, sqlBuilder *strings.Builder, quer
queryArgs = append(queryArgs, segment.value)
}
case *QueryCond[T]:
// 当子条件不存在查询表达式时,无需进行递归处理
if len(segment.queryExpressions) == 0 {
continue
}
sqlBuilder.WriteString(constants.LeftBracket + " ")
// 递归处理条件
queryArgs = buildSqlAndArgs[T](segment.queryExpressions, sqlBuilder, queryArgs)
Expand Down
2 changes: 1 addition & 1 deletion gplus/function.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
package gplus

import (
"github.com/acmestack/gorm-plus/constants"
"github.com/aixj1984/gorm-plus/constants"
"strings"
)

Expand Down
2 changes: 1 addition & 1 deletion gplus/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func Omit(columns ...any) OptionFunc {
}
}

// IgnoreTotal 分页查询忽略总数 issue: https://github.com/acmestack/gorm-plus/issues/37
// IgnoreTotal 分页查询忽略总数 issue: https://github.com/aixj1984/gorm-plus/issues/37
func IgnoreTotal() OptionFunc {
return func(o *Option) {
o.IgnoreTotal = true
Expand Down
75 changes: 74 additions & 1 deletion gplus/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,14 @@ package gplus

import (
"fmt"
"github.com/acmestack/gorm-plus/constants"
"github.com/aixj1984/gorm-plus/constants"
"reflect"
"strings"
)

type QueryCond[T any] struct {
selectColumns []string
omitColumns []string
distinctColumns []string
queryExpressions []any
orderBuilder strings.Builder
Expand All @@ -37,6 +38,7 @@ type QueryCond[T any] struct {
limit *int
offset int
updateMap map[string]any
columnTypeMap map[string]reflect.Type
}

func (q *QueryCond[T]) getSqlSegment() string {
Expand Down Expand Up @@ -150,13 +152,27 @@ func (q *QueryCond[T]) LikeLeft(column any, val any) *QueryCond[T] {
return q
}

// NotLikeLeft 非左模糊 NOT LIKE '%值'
func (q *QueryCond[T]) NotLikeLeft(column any, val any) *QueryCond[T] {
s := fmt.Sprintf("%v", val)
q.addExpression(q.buildSqlSegment(column, constants.Not+" "+constants.Like, "%"+s)...)
return q
}

// LikeRight 右模糊 LIKE '值%'
func (q *QueryCond[T]) LikeRight(column any, val any) *QueryCond[T] {
s := fmt.Sprintf("%v", val)
q.addExpression(q.buildSqlSegment(column, constants.Like, s+"%")...)
return q
}

// NotLikeRight 非右模糊 NOT LIKE '值%'
func (q *QueryCond[T]) NotLikeRight(column any, val any) *QueryCond[T] {
s := fmt.Sprintf("%v", val)
q.addExpression(q.buildSqlSegment(column, constants.Not+" "+constants.Like, s+"%")...)
return q
}

// IsNull 是否为空 字段 IS NULL
func (q *QueryCond[T]) IsNull(column any) *QueryCond[T] {
q.addExpression(q.buildSqlSegment(column, constants.IsNull, "")...)
Expand Down Expand Up @@ -284,6 +300,15 @@ func (q *QueryCond[T]) Select(columns ...any) *QueryCond[T] {
return q
}

// Omit 忽略字段
func (q *QueryCond[T]) Omit(columns ...any) *QueryCond[T] {
for _, v := range columns {
columnName := getColumnName(v)
q.omitColumns = append(q.omitColumns, columnName)
}
return q
}

// Set 设置更新的字段
func (q *QueryCond[T]) Set(column any, val any) *QueryCond[T] {
columnName := getColumnName(column)
Expand Down Expand Up @@ -388,3 +413,51 @@ func (q *QueryCond[T]) buildOrder(orderType string, columns ...string) {
q.orderBuilder.WriteString(orderType)
}
}

// 执行增加AND条件
func (q *QueryCond[T]) AddAndStrCond(cond string) *QueryCond[T] {
if len(q.queryExpressions) > 0 {
sk := sqlKeyword{keyword: constants.And}
q.queryExpressions = append(q.queryExpressions, &sk)
}
condSk := sqlKeyword{keyword: cond}
q.queryExpressions = append(q.queryExpressions, &condSk)
q.last = &condSk
return q
}

// 执行增加OR条件
func (q *QueryCond[T]) AddOrStrCond(cond string) *QueryCond[T] {
if len(q.queryExpressions) > 0 {
sk := sqlKeyword{keyword: constants.Or}
q.queryExpressions = append(q.queryExpressions, &sk)
}
condSk := sqlKeyword{keyword: cond}
q.queryExpressions = append(q.queryExpressions, &condSk)
q.last = &condSk
return q
}

// 根据条件,执行方法
func (q *QueryCond[T]) Case(isTrue bool, handleFunc func()) *QueryCond[T] {
if isTrue {
handleFunc()
}
return q
}

// 重置查询条件
func (q *QueryCond[T]) Reset() *QueryCond[T] {
q.selectColumns = q.selectColumns[:0]
q.omitColumns = q.omitColumns[:0]
q.distinctColumns = q.distinctColumns[:0]
q.queryExpressions = q.queryExpressions[:0]
q.orderBuilder.Reset()
q.groupBuilder.Reset()
q.havingBuilder.Reset()
q.havingArgs = q.havingArgs[:0]
q.queryArgs = q.queryArgs[:0]
q.updateMap = nil

return q
}
Loading
Loading