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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(query_builder): add orderByRandom #1011

Open
wants to merge 2 commits into
base: develop
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/database/query_builder/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,27 @@ export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuil
return this
}

/**
* Order results by random value.
*/
orderByRandom(seed = '') {
switch (this.client.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.client.dialect.name}`)
}
}

/**
* Executes the query
*/
Expand Down
21 changes: 21 additions & 0 deletions src/orm/query_builder/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -643,6 +643,27 @@ export class ModelQueryBuilder
return this.addWhereHas(relationName, 'not', operator, value)
}

/**
* Order results by random value.
*/
orderByRandom(seed = '') {
switch (this.client.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.client.dialect.name}`)
}
}

/**
* Define a relationship to be preloaded
*/
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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we added the method to the ChainableContract, the modelQuery builder needs to implement this method as well, otherwise we get typing errors


union: Union<this>
unionAll: UnionAll<this>
Expand Down
43 changes: 43 additions & 0 deletions test/database/query_builder.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5439,6 +5439,49 @@ 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: 'virk@adonisjs.com',
},
{
username: 'romain',
email: 'romain@adonisjs.com',
},
{
username: 'nikk',
email: 'nikk@adonisjs.com',
},
])

const users = await db.from('users').orderByRandom()
const users2 = await db.from('users').orderByRandom()

assert.notEqual(users[0].id, users2[0].id)
await connection.disconnect()
}).retry(3)
})

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