dialect/sql: add OrderByRand option (#3518)

This commit is contained in:
Ariel Mashraki
2023-05-04 12:13:24 +03:00
committed by GitHub
parent f251400818
commit fc8d095da8
2 changed files with 20 additions and 0 deletions

View File

@@ -7,6 +7,8 @@ package sql
import (
"fmt"
"strings"
"entgo.io/ent/dialect"
)
// The following helpers exist to simplify the way raw predicates
@@ -312,6 +314,20 @@ func orderByAgg(fn, field string, opts ...OrderTermOption) *OrderExprTerm {
}
}
// OrderByRand returns a term to natively order by a random value.
func OrderByRand() func(*Selector) {
return func(s *Selector) {
s.OrderExprFunc(func(b *Builder) {
switch s.Dialect() {
case dialect.MySQL:
b.WriteString("RAND()")
default:
b.WriteString("RANDOM()")
}
})
}
}
// ToFunc returns a function that sets the ordering on the given selector.
// This is used by the generated code.
func (f *OrderFieldTerm) ToFunc() func(*Selector) {

View File

@@ -792,6 +792,10 @@ func Select(t *testing.T, client *ent.Client) {
require.NoError(err)
require.EqualValues(len(p.Name), n)
}
// Order by random value should compile a valid query.
_, err = client.User.Query().Order(sql.OrderByRand()).All(ctx)
require.NoError(err)
}
func Aggregate(t *testing.T, client *ent.Client) {