Skip to content

Commit

Permalink
feat(query_builder): add orderByRandom
Browse files Browse the repository at this point in the history
  • Loading branch information
RomainLanz committed Mar 9, 2024
1 parent 8c333e0 commit 008ec0e
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
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
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

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

0 comments on commit 008ec0e

Please sign in to comment.