Skip to content

Commit

Permalink
Added SQL RAND() function.
Browse files Browse the repository at this point in the history
  • Loading branch information
dmromanov committed May 16, 2018
1 parent fe6d068 commit 102ed1a
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/Database/Dialect/PostgresDialectTrait.php
Expand Up @@ -132,6 +132,9 @@ protected function _transformFunctionExpression(FunctionExpression $expression)
case 'NOW':
$expression->setName('LOCALTIMESTAMP')->add([' 0 ' => 'literal']);
break;
case 'RAND':
$expression->setName('RANDOM');
break;
case 'DATE_ADD':
$expression
->setName('')
Expand Down
5 changes: 5 additions & 0 deletions src/Database/Dialect/SqliteDialectTrait.php
Expand Up @@ -108,6 +108,11 @@ protected function _transformFunctionExpression(FunctionExpression $expression)
case 'NOW':
$expression->setName('DATETIME')->add(["'now'" => 'literal']);
break;
case 'RAND':
$expression
->setName('ABS')
->add(["RANDOM() % 1" => 'literal'], [], true);
break;
case 'CURRENT_DATE':
$expression->setName('DATE')->add(["'now'" => 'literal']);
break;
Expand Down
10 changes: 10 additions & 0 deletions src/Database/FunctionsBuilder.php
Expand Up @@ -60,6 +60,16 @@ protected function _literalArgumentFunction($name, $expression, $types = [], $re
return $this->_build($name, $expression, $types, $return);
}

/**
* Returns a FunctionExpression representing a call to SQL RAND function.
*
* @return \Cake\Database\Expression\FunctionExpression
*/
public function rand()
{
return $this->_build('RAND', [], [], 'float');
}

/**
* Returns a FunctionExpression representing a call to SQL SUM function.
*
Expand Down
13 changes: 13 additions & 0 deletions tests/TestCase/Database/FunctionsBuilderTest.php
Expand Up @@ -217,4 +217,17 @@ public function testDayOfWeek()
$this->assertEquals('DAYOFWEEK(created)', $function->sql(new ValueBinder));
$this->assertEquals('integer', $function->getReturnType());
}

/**
* Tests generating a RAND() function
*
* @return void
*/
public function testRand()
{
$function = $this->functions->rand();
$this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function);
$this->assertEquals('RAND()', $function->sql(new ValueBinder));
$this->assertEquals('float', $function->getReturnType());
}
}
20 changes: 20 additions & 0 deletions tests/TestCase/ORM/QueryTest.php
Expand Up @@ -1699,6 +1699,26 @@ public function testCountWithCustomCounter()
$this->assertEquals(1, $result);
}

/**
* Test that RAND() returns correct results.
*
* @return void
*/
public function testSelectRandom()
{
$table = $this->getTableLocator()->get('articles');
$query = $table
->query();

$query->select(['s' => $query->func()->rand()]);
$result = $query
->extract('s')
->first();

$this->assertGreaterThanOrEqual(0, $result);
$this->assertLessThan(1, $result);
}

/**
* Test update method.
*
Expand Down

0 comments on commit 102ed1a

Please sign in to comment.