Skip to content

Commit

Permalink
Adding coalesce() and dateDiff() functions
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Mar 9, 2013
1 parent 1f39853 commit c84b110
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 6 deletions.
16 changes: 13 additions & 3 deletions lib/Cake/Model/Datasource/Database/Dialect/SqliteDialectTrait.php
Expand Up @@ -30,9 +30,19 @@ protected function _expressionTranslators() {
}

protected function _transformFunctionExpression(FunctionExpression $expression) {
if ($expression->name() === 'CONCAT') {
// CONCAT function is expressed as exp1 || exp2
$expression->name('')->type(' ||');
switch ($expression->name()) {
case 'CONCAT':
// CONCAT function is expressed as exp1 || exp2
$expression->name('')->type(' ||');
break;
case 'DATEDIFF':
$expression
->name('ROUND')
->type('-')
->iterateParts(function($p) {
return new FunctionExpression('JULIANDAY', [$p => 'literal']);
});
break;
}
}

Expand Down
8 changes: 8 additions & 0 deletions lib/Cake/Model/Datasource/Database/FunctionsTrait.php
Expand Up @@ -66,4 +66,12 @@ public function concat($args, $types = []) {
return $this->func('CONCAT', $args, $types);
}

public function coalesce($args, $types = []) {
return $this->func('COALESCE', $args, $types);
}

public function dateDiff($dates, $types = []) {
return $this->func('DATEDIFF', $dates, $types);
}

}
Expand Up @@ -69,11 +69,18 @@ public function testCount() {
$this->assertEquals('COUNT(*)', (string)$function);
}

public function concat() {
public function testConcat() {
$function = $this->functions->concat(['title' => 'literal', ' is a string']);
$this->assertInstanceOf('\Cake\Model\Datasource\Database\Expression\FunctionExpression', $function);
$param = $function->bindings()[0]['placeholder'];
$this->assertEquals("CONCAT(title, $param)", (string)$function);
$param = $function->bindings()[1]['placeholder'];
$this->assertEquals("CONCAT(title, :$param)", (string)$function);
}

public function testCoalesce() {
$function = $this->functions->coalesce(['NULL' => 'literal', '1', '2']);
$this->assertInstanceOf('\Cake\Model\Datasource\Database\Expression\FunctionExpression', $function);
$param = $function->bindings()[1]['placeholder'];
$param2 = $function->bindings()[2]['placeholder'];
$this->assertEquals("COALESCE(NULL, :$param, :$param2)", (string)$function);
}
}
Expand Up @@ -1965,6 +1965,12 @@ public function testSQLFunctions() {
->execute();
$expected = [['c' => 'a title is appended'], ['c' => 'another title is appended']];
$this->assertEquals($expected, $result->fetchAll('assoc'));

$query = new Query($this->connection);
$result = $query
->select(['d' => $query->dateDiff(['2012-01-05', '2012-01-02'])])
->execute();
$this->assertEquals([['d' => '3.0']], $result->fetchAll('assoc'));
}


Expand Down

0 comments on commit c84b110

Please sign in to comment.