Browse Source

Add sql cast function cakephp#13694

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

+ 15 - 0
src/Database/FunctionsBuilder.php

@@ -159,6 +159,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 = $this->_literalArgumentFunction('CAST', $field);
+        $expression->setConjunction(' AS')->add([$type => 'literal']);
+
+        return $expression;
+    }
+
+    /**
      * Returns a FunctionExpression representing the difference in days between
      * two dates.
      *

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

@@ -147,6 +147,22 @@ class FunctionsBuilderTest extends TestCase
     }
 
     /**
+     * Tests generating a CAST() function
+     *
+     * @return void
+     */
+    public function testCast()
+    {
+        $function = $this->functions->cast('field', 'varchar');
+        $this->assertSame('CAST(field AS varchar)', $function->sql(new ValueBinder()));
+        $this->assertSame('string', $function->getReturnType());
+
+        $function = $this->functions->cast($this->functions->now(), 'varchar');
+        $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