Search code examples
go-gorm

Gorm Go - Query with an empty slice of primary keys


The Gorm documentation for Struct & Map Conditions provides the following snippet for querying a table with a slice of primary keys

// Slice of primary keys
db.Where([]int64{20, 21, 22}).Find(&users)
// SELECT * FROM users WHERE id IN (20, 21, 22);

However, if the slice is empty then all records are returned. Looking at the source code for the Find function I can see conditions are only added if len(conds) > 0

// Find find records that match given conditions
func (db *DB) Find(dest interface{}, conds ...interface{}) (tx *DB) {
    tx = db.getInstance()
    if len(conds) > 0 {
        if exprs := tx.Statement.BuildCondition(conds[0], conds[1:]...); len(exprs) > 0 {
            tx.Statement.AddClause(clause.Where{Exprs: exprs})
        }
    }
    tx.Statement.Dest = dest
    return tx.callbacks.Query().Execute(tx)
}

This is the opposite of what my SQLite command line returns. If the condition is empty then no records are returned (because they all have a primary key)

-- no records returned
SELECT * FROM my_table WHERE id IN ();

Question

  • Is there a way to query a slice of primary keys using Gorm such that if the slice is empty, no records are returned?

Solution

  • Since primary keys increases from 1, 0 id could be used in a empty query.

    ids := []int64{20, 21, 22}
    db.Where(append([]int64{0}, ids...)).Find(&users)