Permalink
Browse files

Ensure that query conditions are cast properly when using table alias…

…es in conditions key.
  • Loading branch information...
1 parent baa62ee commit 198523cd97b0e389985db8d9d3905b03b72e9574 @nealerickson nealerickson committed Aug 24, 2012
Showing with 32 additions and 2 deletions.
  1. +17 −1 data/source/Database.php
  2. +15 −1 tests/cases/data/source/DatabaseTest.php
View
@@ -241,6 +241,22 @@ public function name($name) {
}
/**
+ * Return the field name from a conditions key.
+ *
+ * @param string $field Field or identifier name.
+ * @return string Returns the field name without the table alias, if applicable.
+ */
+ public function fieldName($field) {
+ if (is_string($field)) {
+ if (preg_match('/^[a-z0-9_-]+\.[a-z0-9_-]+$/i', $field)) {
+ list($first, $second) = explode('.', $field, 2);
+ return $second;
+ }
+ }
+ return $field;
+ }
+
+ /**
* Converts a given value into the proper type based on a given schema definition.
*
* @see lithium\data\source\Database::schema()
@@ -707,7 +723,7 @@ protected function _conditions($conditions, $context, array $options = array())
public function _processConditions($key, $value, $context, $schema, $glue = 'AND') {
$constraintTypes =& $this->_constraintTypes;
- $fieldMeta = $schema->fields($key) ?: array();
+ $fieldMeta = $schema->fields($this->fieldName($key)) ?: array();
switch (true) {
case (is_numeric($key) && is_string($value)):
@@ -303,6 +303,20 @@ public function testNestedQueryConditions() {
$this->assertEqual($sql, $this->db->renderCommand($query));
}
+ public function testCastingQueryConditionsWithSchemaWithAlias() {
+ $query = new Query(array(
+ 'type' => 'read',
+ 'model' => $this->_model,
+ 'conditions' => array(
+ 'MockDatabasePost.title' => '007'
+ )
+ ));
+ $result = $this->db->renderCommand($query);
+
+ $sql = "SELECT * FROM {mock_database_posts} AS {MockDatabasePost} WHERE {MockDatabasePost}.{title} = '007';";
+ $this->assertEqual($sql, $result);
+ }
+
public function testJoin() {
$query = new Query(array(
'type' => 'read',
@@ -657,7 +671,7 @@ public function testConditions() {
'type' => 'read', 'model' => $this->_model,
'conditions' => array('lower(title)' => 'test')
));
-
+
$this->assertEqual($sql, $this->db->renderCommand($query));
$query = new Query(array(

0 comments on commit 198523c

Please sign in to comment.