Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(query_builder): add orderByRandom #1011

Open
wants to merge 4 commits into
base: 21.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/database/query_builder/chainable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { isObject } from '../../utils/index.js'
import { RawQueryBuilder } from './raw.js'
import { RawBuilder } from '../static_builder/raw.js'
import { ReferenceBuilder } from '../static_builder/reference.js'
import type { DialectContract } from '../../types/database.js'

/**
* The chainable query builder to construct SQL queries for selecting, updating and
Expand Down Expand Up @@ -105,6 +106,7 @@ export abstract class Chainable extends Macroable implements ChainableContract {
constructor(
public knexQuery: Knex.QueryBuilder,
private queryCallback: DBQueryCallback,
private dialect: DialectContract,
public keysResolver?: (columnName: string) => string
) {
super()
Expand Down Expand Up @@ -1701,6 +1703,27 @@ export abstract class Chainable extends Macroable implements ChainableContract {
return this
}

/**
* Order results by random value.
*/
orderByRandom(seed = '') {
switch (this.dialect.name) {
case 'sqlite3':
case 'better-sqlite3':
case 'postgres':
case 'redshift':
return this.orderByRaw('RANDOM()')
case 'mysql':
return this.orderByRaw(`RAND(${seed})`)
case 'mssql':
return this.orderByRaw('NEWID()')
case 'oracledb':
return this.orderByRaw('dbms_random.value')
default:
throw new Error(`Cannot order by random for the given dialect ${this.dialect.name}`)
}
}

/**
* Define select offset
*/
Expand Down
2 changes: 1 addition & 1 deletion src/database/query_builder/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil
public client: QueryClientContract,
public keysResolver?: (columnName: string) => string
) {
super(builder, queryCallback, keysResolver)
super(builder, queryCallback, client.dialect, keysResolver)
this.debugQueries = this.client.debug
}

Expand Down
1 change: 1 addition & 0 deletions src/orm/query_builder/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ export class ModelQueryBuilder
super(
builder,
customFn,
client.dialect,
model.$keys.attributesToColumns.resolve.bind(model.$keys.attributesToColumns)
)

Expand Down
1 change: 1 addition & 0 deletions src/types/querybuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -651,6 +651,7 @@ export interface ChainableContract {

orderBy: OrderBy<this>
orderByRaw: RawQueryFn<this>
orderByRandom: (seed?: string) => this
RomainLanz marked this conversation as resolved.
Show resolved Hide resolved

union: Union<this>
unionAll: UnionAll<this>
Expand Down
49 changes: 49 additions & 0 deletions test/database/query_builder.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5439,6 +5439,55 @@ test.group('Query Builder | orderByRaw', (group) => {
})
})

test.group('Query Builder | orderByRandom', (group) => {
group.setup(async () => {
await setup()
})

group.teardown(async () => {
await cleanup()
})

group.each.teardown(async () => {
await resetTables()
})

test('define order by random value', async ({ assert }) => {
const connection = new Connection('primary', getConfig(), logger)
connection.connect()

const db = getQueryBuilder(getQueryClient(connection))
await getInsertBuilder(getQueryClient(connection))
.table('users')
.multiInsert([
{
username: 'virk',
email: '[email protected]',
},
{
username: 'romain',
email: '[email protected]',
},
{
username: 'nikk',
email: '[email protected]',
},
])

const userResults: number[][] = []

for (let i = 0; i < 10; i++) {
const result = await db.from('users').orderByRandom()

userResults.push(result.map((user) => user.id))
}

assert.isTrue(userResults.some((users) => userResults[0] !== users))

await connection.disconnect()
})
})

test.group('Query Builder | offset', (group) => {
group.setup(async () => {
await setup()
Expand Down
Loading