Skip to content

Commit

Permalink
feat: add Exists method (#421)
Browse files Browse the repository at this point in the history
* feat: add Exists method

* update Exists method and test

---------

Co-authored-by: Wenbo Han <[email protected]>
  • Loading branch information
Kamandlou and hwbrzzl authored Feb 15, 2024
1 parent 300c1c3 commit 1a9f352
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 0 deletions.
2 changes: 2 additions & 0 deletions contracts/database/orm/orm.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ type Query interface {
Distinct(args ...any) Query
// Exec executes raw sql
Exec(sql string, values ...any) (*Result, error)
// Exists returns true if matching records exist; otherwise, it returns false.
Exists(exists *bool) error
// Find finds records that match given conditions.
Find(dest any, conds ...any) error
// FindOrFail finds records that match given conditions or throws an error.
Expand Down
4 changes: 4 additions & 0 deletions database/gorm/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,10 @@ func (r *QueryImpl) Exec(sql string, values ...any) (*ormcontract.Result, error)
}, result.Error
}

func (r *QueryImpl) Exists(exists *bool) error {
return r.instance.Select("1").Limit(1).Find(exists).Error
}

func (r *QueryImpl) Find(dest any, conds ...any) error {
if err := r.refreshConnection(dest); err != nil {
return err
Expand Down
22 changes: 22 additions & 0 deletions database/gorm/query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1552,6 +1552,28 @@ func (s *QueryTestSuite) TestExec() {
}
}

func (s *QueryTestSuite) TestExists() {
for driver, query := range s.queries {
s.Run(driver.String(), func() {
user := User{Name: "exists_user", Avatar: "exists_avatar"}
s.Nil(query.Create(&user))
s.True(user.ID > 0)

user1 := User{Name: "exists_user", Avatar: "exists_avatar_1"}
s.Nil(query.Create(&user1))
s.True(user1.ID > 0)

var t bool
s.Nil(query.Model(&User{}).Where("name = ?", "exists_user").Exists(&t))
s.True(t)

var f bool
s.Nil(query.Model(&User{}).Where("name = ?", "no_exists_user").Exists(&f))
s.False(f)
})
}
}

func (s *QueryTestSuite) TestFind() {
for _, query := range s.queries {
tests := []struct {
Expand Down
14 changes: 14 additions & 0 deletions mocks/database/orm/Query.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions mocks/database/orm/Transaction.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 1a9f352

Please sign in to comment.