Browse Source

Add sql cast function cakephp#13694

mcsknp 6 years ago
parent
commit
6b27418ffe
2 changed files with 33 additions and 0 deletions
  1. 15 0
      src/Database/FunctionsBuilder.php
  2. 18 0
      tests/TestCase/Database/FunctionsBuilderTest.php

+ 15 - 0
src/Database/FunctionsBuilder.php

@@ -127,6 +127,21 @@ class FunctionsBuilder
     }
 
     /**
+     * Returns a FunctionExpression representing a call to SQL CAST function.
+     *
+     * @param string|\Cake\Database\ExpressionInterface $field Field or expression to cast.
+     * @param string $type The target data type
+     * @return \Cake\Database\Expression\FunctionExpression
+     */
+    public function cast($field, string $type): FunctionExpression
+    {
+        $expression = new FunctionExpression('CAST', $this->toLiteralParam($field));
+        $expression->setConjunction(' AS')->add([$type => 'literal']);
+
+        return $expression;
+    }
+
+    /**
      * Returns a FunctionExpression representing the difference in days between
      * two dates.
      *

+ 18 - 0
tests/TestCase/Database/FunctionsBuilderTest.php

@@ -172,6 +172,24 @@ class FunctionsBuilderTest extends TestCase
     }
 
     /**
+     * Tests generating a CAST() function
+     *
+     * @return void
+     */
+    public function testCast()
+    {
+        $function = $this->functions->cast('field', 'varchar');
+        $this->assertInstanceOf(FunctionExpression::class, $function);
+        $this->assertSame('CAST(field AS varchar)', $function->sql(new ValueBinder()));
+        $this->assertSame('string', $function->getReturnType());
+
+        $function = $this->functions->cast($this->functions->now(), 'varchar');
+        $this->assertInstanceOf(FunctionExpression::class, $function);
+        $this->assertSame('CAST(NOW() AS varchar)', $function->sql(new ValueBinder()));
+        $this->assertSame('string', $function->getReturnType());
+    }
+
+    /**
      * Tests generating a NOW(), CURRENT_TIME() and CURRENT_DATE() function
      *
      * @return void