Skip to content

Commit

Permalink
feat: 增加新的helper方法
Browse files Browse the repository at this point in the history
  • Loading branch information
yeaha committed Jun 28, 2023
1 parent b0e6a2e commit 3253d64
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,37 @@ func Transaction(db *sqlx.DB, fn func(tx *sqlx.Tx) error) (err error) {
return fn(tx)
}

// TryTransaction 尝试执行事务,如果DB不是*sqlx.DB,则直接执行fn
func TryTransaction(db DB, fn func(DB) error) error {
if v, ok := db.(*sqlx.DB); ok {
return Transaction(v, func(tx *sqlx.Tx) error {
return fn(tx)
})
}
return fn(db)
}

// QueryBy 查询并使用回调函数处理游标
func QueryBy(ctx context.Context, db DB, stmt *goqu.SelectDataset, fn func(ctx context.Context, rows *sqlx.Rows) error) error {
query, args, err := stmt.ToSQL()
if err != nil {
return fmt.Errorf("build sql, %w", err)
}

rows, err := db.QueryxContext(ctx, query, args...)
if err != nil {
return fmt.Errorf("execute query, %w", err)
}
defer rows.Close()

for rows.Next() {
if err := fn(ctx, rows); err != nil {
return fmt.Errorf("handle row, %w", err)
}
}
return nil
}

// Pagination 数据库分页计算
type Pagination struct {
First int `json:"first"`
Expand Down

0 comments on commit 3253d64

Please sign in to comment.