From 780e1797a612e25bccdbc810bfa77862ea16cd9c Mon Sep 17 00:00:00 2001 From: demoManito <1430482733@qq.com> Date: Mon, 30 Sep 2024 18:28:30 +0800 Subject: [PATCH] feature: add exists method --- finisher_api.go | 6 ++++++ tests/query_test.go | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/finisher_api.go b/finisher_api.go index 6802945cc..7d3bb24fc 100644 --- a/finisher_api.go +++ b/finisher_api.go @@ -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) diff --git a/tests/query_test.go b/tests/query_test.go index 566763c51..ead5fe87a 100644 --- a/tests/query_test.go +++ b/tests/query_test.go @@ -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") + } +}