Skip to content
Permalink
Browse files

Adding new DateType and adding tests for executing queries with params

and types
  • Loading branch information...
lorenzo committed May 30, 2012
1 parent ea74b74 commit 83a878f519603ebabb0341332cfc8ede4c28ff33
@@ -250,21 +250,17 @@ protected function _bindValues($statement, $params, $types) {
return;
}
if (!empty($types) && ctype_digit(key($types))) {
$params = array_values($params);
}
$annonymousParams = is_int(key($params)) ? true : false;
$offset = 1;
foreach ($params as $index => $value) {
$type = null;
if (isset($types[$index])) {
$type = $types[$index];
}
if ($annonymousParams) {
$index += $offset;
}
if (isset($types[$index])) {
$statement->bindValue($index, $value, $type);
} else {
$statement->bindValue($index, $value);
}
$statement->bindValue($index, $value, $type);
}
}
@@ -43,6 +43,7 @@ class Statement implements \IteratorAggregate, \Countable {
**/
public function __construct($statement = null, $driver = null) {
$this->_statement = $statement;
$this->_driver = $driver;
}
/**
@@ -0,0 +1,25 @@
<?php
namespace Cake\Model\Datasource\Database\Type;
use \DateTime;
class DateType extends \Cake\Model\Datasource\Database\Type {
public function toDatabase($value, $driver) {
if (is_string($value)) {
return $value;
}
return $value->format('Y-m-d');
}
public function toPHP($value, $driver) {
if ($value === null) {
return null;
}
$value = DateTime::createFromFormat('Y-m-d', $value);
return $value;
}
}
@@ -124,4 +124,34 @@ public function testExecuteWithArguments() {
$this->assertEquals(array('total' => 6), $result);
}
/**
* Tests executing a query with params and associated types
*
* @return void
**/
public function testExecuteWithArgumentsAndTypes() {
$sql = 'SELECT ?';
$statement = $this->connection->execute($sql, array(new \DateTime('2012-01-01')), array('date'));
$result = $statement->fetch();
$this->assertEquals('2012-01-01', $result[0]);
$sql = 'SELECT ?, ?, ?';
$params = array(new \DateTime('2012-01-01 10:10:10'), '2000-01-01 10:10:10', 1.1);
$statement = $this->connection->execute($sql, $params, array('date', 'string', 'float'));
$result = $statement->fetch();
$this->assertEquals(array('2012-01-01', '2000-01-01 10:10:10', 1.1), $result);
}
/**
* Tests that passing a unknown value to a query throws an exception
*
* @expectedException \InvalidArgumentException
* @return void
**/
public function testExecuteWithMissingType() {
$sql = 'SELECT ?';
$statement = $this->connection->execute($sql, array(new \DateTime('2012-01-01')), array('bar'));
}
}

0 comments on commit 83a878f

Please sign in to comment.
You can’t perform that action at this time.