From fc8d095da8ba025c9b3ccce099d912a3483a179a Mon Sep 17 00:00:00 2001 From: Ariel Mashraki <7413593+a8m@users.noreply.github.com> Date: Thu, 4 May 2023 12:13:24 +0300 Subject: [PATCH] dialect/sql: add OrderByRand option (#3518) --- dialect/sql/sql.go | 16 ++++++++++++++++ entc/integration/integration_test.go | 4 ++++ 2 files changed, 20 insertions(+) diff --git a/dialect/sql/sql.go b/dialect/sql/sql.go index 117f1a672..a0a3e35f0 100644 --- a/dialect/sql/sql.go +++ b/dialect/sql/sql.go @@ -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) { diff --git a/entc/integration/integration_test.go b/entc/integration/integration_test.go index 75d564dbb..6e5c8f3fb 100644 --- a/entc/integration/integration_test.go +++ b/entc/integration/integration_test.go @@ -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) {