Skip to content

Commit

Permalink
feature: add exists method
Browse files Browse the repository at this point in the history
  • Loading branch information
demoManito committed Sep 30, 2024
1 parent 62bd0b9 commit d46c92e
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
8 changes: 8 additions & 0 deletions finisher_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,14 @@ func (db *DB) Count(count *int64) (tx *DB) {
return
}

// Exists checks if there is any record matching the given conditions
func (db *DB) Exists() (bool, error) {
var exist bool
return exist, db.Session(&Session{NewDB: true}).
Raw("SELECT ? AS exist", Expr("EXISTS(?)", db.Select("1").Limit(1))).
Pluck("exist", &exist).Error
}

func (db *DB) Row() *sql.Row {
tx := db.getInstance().Set("rows", false)
tx = tx.callbacks.Row().Execute(tx)
Expand Down
18 changes: 18 additions & 0 deletions tests/query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1453,3 +1453,21 @@ func TestQueryScanToArray(t *testing.T) {
t.Error("users[1] should be empty")
}
}

func TestExists(t *testing.T) {
ok, err := DB.Table("users").Where("name = ?", "jinzhu").Exists()
if err != nil {
t.Fatalf("Failed to scan, got %v", err)
}
if !ok {
t.Errorf("Should found record")
}

ok, err = DB.Table("users").Where("name = ?", "jinzhu-jinzhu").Exists()
if err != nil {
t.Fatalf("Failed to scan, got %v", err)
}
if ok {
t.Errorf("Should not found record")
}
}

0 comments on commit d46c92e

Please sign in to comment.