mirror of
https://github.com/ent/ent.git
synced 2026-03-05 19:35:23 +03:00
dialect/sql: add OrderByRand option (#3518)
This commit is contained in:
@@ -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) {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user