Permalink
Browse files

feat: sequelize.random() (#8847)

  • Loading branch information...
mccabemj authored and sushantdhiman committed Jan 10, 2018
1 parent 40f7d21 commit 6f32643ee7a9d5eadcbd161fb00f6a7a5e8c7d48
Showing with 30 additions and 0 deletions.
  1. +3 −0 docs/querying.md
  2. +14 −0 lib/sequelize.js
  3. +13 −0 test/unit/sql/order.test.js
View
@@ -429,6 +429,9 @@ Subtask.findAll({
// Will order by age ascending assuming ascending is the default order when direction is omitted
order: sequelize.col('age')
// Will order by age randomly based on the dialect (instead of fn('RAND') or fn('RANDOM'))
order: sequelize.random()
})
```
View
@@ -772,6 +772,20 @@ class Sequelize {
databaseVersion(options) {
return this.getQueryInterface().databaseVersion(options);
}
/**
* Get the fn for random based on the dialect
*
* @return {Sequelize.fn}
*/
random() {
const dialect = this.getDialect();
if (_.includes(['postgres', 'sqlite'], dialect)) {
return this.fn('RANDOM');
} else {
return this.fn('RAND');
}
}
/**
* Creates an object representing a database function. This can be used in search queries, both in where and order parts, and as default values in column definitions.
@@ -344,6 +344,19 @@ describe(Support.getTestDialectTeaser('SQL'), () => {
postgres: 'SELECT "Subtask"."id", "Subtask"."name", "Subtask"."createdAt", "Task"."id" AS "Task.id", "Task"."name" AS "Task.name", "Task"."created_at" AS "Task.createdAt", "Task->Project"."id" AS "Task.Project.id", "Task->Project"."name" AS "Task.Project.name", "Task->Project"."created_at" AS "Task.Project.createdAt" FROM "subtask" AS "Subtask" INNER JOIN "task" AS "Task" ON "Subtask"."task_id" = "Task"."id" INNER JOIN "project" AS "Task->Project" ON "Task"."project_id" = "Task->Project"."id" ORDER BY "Task->Project"."created_at" ASC, "Task->Project"."created_at", "Task"."created_at" ASC, "Task"."created_at", "Task->Project"."created_at" ASC, "Task->Project"."created_at", "Task"."created_at" ASC, "Task"."created_at", "Task->Project"."created_at" ASC, "Task->Project"."created_at", "Task"."created_at" ASC, "Task"."created_at", "Task->Project"."created_at" ASC, "Task->Project"."created_at", "Task"."created_at" ASC, "Task"."created_at", "Subtask"."created_at" ASC, "Subtask"."created_at", "Subtask"."created_at";'
});
testsql({
model: Subtask,
attributes: ['id', 'name'],
order: [
Support.sequelize.random()
]
}, {
mssql: 'SELECT [id], [name] FROM [subtask] AS [Subtask] ORDER BY RAND();',
mysql: 'SELECT `id`, `name` FROM `subtask` AS `Subtask` ORDER BY RAND();',
postgres: 'SELECT "id", "name" FROM "subtask" AS "Subtask" ORDER BY RANDOM();',
sqlite: 'SELECT `id`, `name` FROM `subtask` AS `Subtask` ORDER BY RANDOM();'
});
describe('Invalid', () => {
it('Error on invalid association', () => {
return expect(Subtask.findAll({

0 comments on commit 6f32643

Please sign in to comment.