Skip to content

Commit d46c92e

Browse files
committed
feature: add exists method
1 parent 62bd0b9 commit d46c92e

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

finisher_api.go

+8
Original file line numberDiff line numberDiff line change
@@ -502,6 +502,14 @@ func (db *DB) Count(count *int64) (tx *DB) {
502502
return
503503
}
504504

505+
// Exists checks if there is any record matching the given conditions
506+
func (db *DB) Exists() (bool, error) {
507+
var exist bool
508+
return exist, db.Session(&Session{NewDB: true}).
509+
Raw("SELECT ? AS exist", Expr("EXISTS(?)", db.Select("1").Limit(1))).
510+
Pluck("exist", &exist).Error
511+
}
512+
505513
func (db *DB) Row() *sql.Row {
506514
tx := db.getInstance().Set("rows", false)
507515
tx = tx.callbacks.Row().Execute(tx)

tests/query_test.go

+18
Original file line numberDiff line numberDiff line change
@@ -1453,3 +1453,21 @@ func TestQueryScanToArray(t *testing.T) {
14531453
t.Error("users[1] should be empty")
14541454
}
14551455
}
1456+
1457+
func TestExists(t *testing.T) {
1458+
ok, err := DB.Table("users").Where("name = ?", "jinzhu").Exists()
1459+
if err != nil {
1460+
t.Fatalf("Failed to scan, got %v", err)
1461+
}
1462+
if !ok {
1463+
t.Errorf("Should found record")
1464+
}
1465+
1466+
ok, err = DB.Table("users").Where("name = ?", "jinzhu-jinzhu").Exists()
1467+
if err != nil {
1468+
t.Fatalf("Failed to scan, got %v", err)
1469+
}
1470+
if ok {
1471+
t.Errorf("Should not found record")
1472+
}
1473+
}

0 commit comments

Comments
 (0)