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

feature(finisher_api): add Exists method #7216

Closed
wants to merge 1 commit 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: 6 additions & 0 deletions finisher_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,12 @@ 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 exists bool
return exists, db.Session(&Session{NewDB: true}).Raw("SELECT ?", Expr("EXISTS(?)", db.Select("1"))).Pluck("exists", &exists).Error
}

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

func TestExists(t *testing.T) {
if DB.Dialector.Name() == "sqlserver" {
t.Skip()
}

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")
}
}
Loading