Refactored query construction

This commit is contained in:
Timothy Warren 2012-03-14 10:52:11 -04:00
parent 3f7236c706
commit b550cacdd6
4 changed files with 213 additions and 105 deletions

View File

@ -15,15 +15,12 @@
/** /**
* Convienience class for creating sql queries - also the class that * Convienience class for creating sql queries - also the class that
* instantiates the specific db driver * instantiates the specific db driver
*
* @todo Implement query queue to better match user meaning on queries
*/ */
class Query_Builder { class Query_Builder {
// Compiled query component strings // Compiled query component strings
private $select_string, private $select_string,
$from_string, $from_string,
$where_string,
$insert_string, $insert_string,
$update_string, $update_string,
$set_string, $set_string,
@ -31,13 +28,14 @@ class Query_Builder {
$group_string; $group_string;
// Key value pairs // Key value pairs
private $where_array, private $set_array,
$like_array,
$set_array,
$set_array_keys, $set_array_keys,
$order_array, $order_array,
$group_array; $group_array;
// Values to apply to prepared statements
private $values;
// Query-global components // Query-global components
private $limit, private $limit,
$offset; $offset;
@ -46,6 +44,15 @@ class Query_Builder {
private $sql; private $sql;
// Query component order mapping // Query component order mapping
// for complex select queries
//
// Format:
//
// array(
// 'type' => 'where',
// 'conjunction' => ' AND ',
// 'string' => 'k=?'
// )
private $query_map; private $query_map;
/** /**
@ -167,36 +174,35 @@ class Query_Builder {
*/ */
public function like($field, $val, $pos='both') public function like($field, $val, $pos='both')
{ {
// @todo Fix like syntax
$field = $this->db->quote_ident($field); $field = $this->db->quote_ident($field);
$this->like_array[$field] = array(
'value' => $val,
'pos' => $post
);
// Add the like string into the order map // Add the like string into the order map
$l = $field. ' LIKE '; $l = $field. ' LIKE ?';
if ($pos == 'before') if ($pos == 'before')
{ {
$l .= '%?'; $val = "%{$val}";
} }
elseif ($pos == 'after') elseif ($pos == 'after')
{ {
$l .= '?%'; $val = "{$val}%";
} }
else else
{ {
$l .= '%?%'; $val = "%{$val}%";
} }
$this->query_map[] = array( $this->query_map[] = array(
'type' => 'like', 'type' => 'like',
'conjunction' => (empty($this->query_map)) ? 'WHERE ' : ' AND ', 'conjunction' => (empty($this->query_map)) ? 'WHERE ' : ' AND ',
'string' => $l, 'string' => $l
'value' => $val
); );
// Add to the values array
$this->values[] = $val;
return $this; return $this;
} }
@ -213,28 +219,26 @@ class Query_Builder {
*/ */
public function where($key, $val=array()) public function where($key, $val=array())
{ {
$where = array();
// Key and value passed? Add them to the where array // Key and value passed? Add them to the where array
if (is_scalar($key) && is_scalar($val)) if (is_scalar($key) && is_scalar($val))
{ {
$this->where_array[$key] = $val; $where[$key] = $val;
$this->values[] = $val;
} }
// Array or object, loop through and add to the where array // Array or object, loop through and add to the where array
elseif ( ! is_scalar($key)) elseif ( ! is_scalar($key))
{ {
foreach($key as $k => $v) foreach($key as $k => $v)
{ {
$this->where_array[$k] = $v; $where[$k] = $v;
$this->values[] = $v;
} }
} }
// The values are irrelevant until the query is actually run
$fields = array_keys($this->where_array);
// Array of conditions
$kv_array = array();
// Create key/value placeholders // Create key/value placeholders
foreach($fields as $f) foreach($where as $f => $val)
{ {
// Split each key by spaces, incase there // Split each key by spaces, incase there
// is an operator such as >, <, !=, etc. // is an operator such as >, <, !=, etc.
@ -243,19 +247,20 @@ class Query_Builder {
// Simple key = val // Simple key = val
if (count($f_array) === 1) if (count($f_array) === 1)
{ {
$kv_array[] = $this->db->quote_ident($f_array[0]) . '= ?'; $item = $this->db->quote_ident($f_array[0]) . '= ?';
} }
else // Other operators else // Other operators
{ {
$kv_array[] = $this->db->quote_ident($f_array[0]) . " {$f_array[1]} ?"; $item = $this->db->quote_ident($f_array[0]) . " {$f_array[1]} ?";
}
} }
// Create the where portion of the string // Put in the query map for select statements
$this->where_string = ' WHERE '.implode(' AND ', $kv_array); $this->query_map[] = array(
'type' => 'where',
unset($kv_array); 'conjunction' => ( ! empty($this->query_map)) ? ' AND ' : ' WHERE ',
unset($fields); 'string' => $item
);
}
return $this; return $this;
} }
@ -271,7 +276,49 @@ class Query_Builder {
*/ */
public function or_where($field, $val=array()) public function or_where($field, $val=array())
{ {
// @todo Implement or_where method $where = array();
// Key and value passed? Add them to the where array
if (is_scalar($field) && is_scalar($val))
{
$where[$field] = $val;
$this->values[] = $val;
}
// Array or object, loop through and add to the where array
elseif ( ! is_scalar($field))
{
foreach($key as $k => $v)
{
$where[$k] = $v;
$this->values[] = $v;
}
}
// Create key/value placeholders
foreach($where as $f => $val)
{
// Split each key by spaces, incase there
// is an operator such as >, <, !=, etc.
$f_array = explode(' ', trim($f));
// Simple key = val
if (count($f_array) === 1)
{
$item = $this->db->quote_ident($f_array[0]) . '= ?';
}
else // Other operators
{
$item = $this->db->quote_ident($f_array[0]) . " {$f_array[1]} ?";
}
// Put in the query map for select statements
$this->query_map[] = array(
'type' => 'where',
'conjunction' => ( ! empty($this->query_map)) ? ' OR ' : ' WHERE ',
'string' => $item
);
}
return $this; return $this;
} }
@ -445,7 +492,7 @@ class Query_Builder {
// Set the table // Set the table
if ( ! empty($table)) if ( ! empty($table))
{ {
$this->from_string = $this->db->quote_ident($table); $this->from($table);
} }
// Set the limit, if it exists // Set the limit, if it exists
@ -454,12 +501,12 @@ class Query_Builder {
$this->limit($limit, $offset); $this->limit($limit, $offset);
} }
$sql = $this->_compile('select'); $sql = $this->_compile_select();
// Do prepared statements for anything involving a "where" clause // Do prepared statements for anything involving a "where" clause
if ( ! empty($this->where_string)) if ( ! empty($this->query_map))
{ {
$result = $this->db->prepare_execute($sql, array_values($this->where_array)); $result = $this->db->prepare_execute($sql, $this->values);
} }
else else
{ {
@ -490,6 +537,7 @@ class Query_Builder {
if (is_scalar($key) && is_scalar($val)) if (is_scalar($key) && is_scalar($val))
{ {
$this->set_array[$key] = $val; $this->set_array[$key] = $val;
$this->values[] = $val;
} }
// Object or array // Object or array
elseif ( ! is_scalar($key)) elseif ( ! is_scalar($key))
@ -497,6 +545,7 @@ class Query_Builder {
foreach($key as $k => $v) foreach($key as $k => $v)
{ {
$this->set_array[$k] = $v; $this->set_array[$k] = $v;
$this->values[] = $val;
} }
} }
@ -528,11 +577,13 @@ class Query_Builder {
$this->set($data); $this->set($data);
} }
$params = array_values($this->set_array);
$sql = $this->_compile("insert", $table); $sql = $this->_compile("insert", $table);
return $this->db->prepare_execute($sql, $params); $res = $this->db->prepare_execute($sql, $this->values);
$this->_reset();
return $res;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -554,24 +605,12 @@ class Query_Builder {
$sql = $this->_compile('update', $table); $sql = $this->_compile('update', $table);
$params = array_values($this->set_array); $res = $this->db->prepare_execute($sql, $this->values);
// Do a linear array merge if there is a where string. $this->_reset();
// We need all the parameters to line up, even when
// there are placeholders in the where string and
// the set string
if ( ! empty($this->where_string))
{
$where_params = array_values($this->where_array);
foreach($where_params as $w)
{
$params[] = $w;
}
}
// Run the query // Run the query
return $this->db->prepare_execute($sql, $params); return $res;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -593,10 +632,13 @@ class Query_Builder {
// Create the SQL and parameters // Create the SQL and parameters
$sql = $this->_compile("delete", $table); $sql = $this->_compile("delete", $table);
$params = array_values($this->where_array);
// Delete the table, and return the result $res = $this->db->prepare_execute($sql, $this->values);
return $this->db->prepare_execute($sql, $params);
$this->_reset();
// Delete the table rows, and return the result
return $res;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -641,14 +683,65 @@ class Query_Builder {
* @param string $table * @param string $table
* @return $string * @return $string
*/ */
private function _compile($type="select", $table="") private function _compile($type, $table="")
{ {
$sql = ''; $sql = '';
switch($type) switch($type)
{ {
default: default:
case "select": break;
case "insert":
$param_count = count($this->set_array);
$params = array_fill(0, $param_count, '?');
$sql = 'INSERT INTO '. $this->db->quote_ident($table) .
' (' . implode(', ', $this->set_array_keys) .
') VALUES ('.implode(', ', $params).')';
break;
case "update":
$sql = 'UPDATE '.$this->db->quote_ident($table). ' SET '. $this->set_string;
// Set the where string
if ( ! empty($this->query_map))
{
foreach($this->query_map as $q)
{
$sql .= $q['conjunction'] . $q['string'];
}
}
break;
case "delete":
$sql = 'DELETE FROM '.$this->db->quote_ident($table);
// Set the where string
if ( ! empty($this->query_map))
{
foreach($this->query_map as $q)
{
$sql .= $q['conjunction'] . $q['string'];
}
}
break;
}
// echo $sql.'<br />';
return $sql;
}
// --------------------------------------------------------------------------
/**
* Compiles a "select" type query
*
* @return string
*/
private function _compile_select()
{
$sql = 'SELECT * FROM '.$this->from_string; $sql = 'SELECT * FROM '.$this->from_string;
// Set the select string // Set the select string
@ -659,9 +752,12 @@ class Query_Builder {
} }
// Set the where string // Set the where string
if ( ! empty($this->where_string)) if ( ! empty($this->query_map))
{ {
$sql .= $this->where_string; foreach($this->query_map as $q)
{
$sql .= $q['conjunction'] . $q['string'];
}
} }
// Set the group_by string // Set the group_by string
@ -681,37 +777,8 @@ class Query_Builder {
{ {
$sql = $this->sql->limit($sql, $this->limit, $this->offset); $sql = $this->sql->limit($sql, $this->limit, $this->offset);
} }
break;
case "insert": echo $sql."<br />";
$param_count = count($this->set_array);
$params = array_fill(0, $param_count, '?');
$sql = 'INSERT INTO '. $this->db->quote_ident($table) .
' (' . implode(', ', $this->set_array_keys) .
') VALUES ('.implode(', ', $params).')';
break;
case "update":
$sql = 'UPDATE '.$this->db->quote_ident($table). ' SET '. $this->set_string;
if ( ! empty($this->where_string))
{
$sql .= $this->where_string;
}
break;
case "delete":
$sql = 'DELETE FROM '.$this->db->quote_ident($table);
if ( ! empty($this->where_string))
{
$sql .= $this->where_string;
}
break;
}
//echo $sql.'<br />';
return $sql; return $sql;
} }

View File

@ -37,7 +37,7 @@ class FirebirdQBTest extends UnitTestCase {
function TestGet() function TestGet()
{ {
$query = $this->qb->get('create_test'); $query = $this->qb->get('create_test ct');
$this->assertTrue(is_resource($query)); $this->assertTrue(is_resource($query));
} }
@ -76,7 +76,6 @@ class FirebirdQBTest extends UnitTestCase {
$this->assertTrue(is_resource($query)); $this->assertTrue(is_resource($query));
} }
function TestSelectGet() function TestSelectGet()
{ {
$query = $this->qb->select('id, key as k, val') $query = $this->qb->select('id, key as k, val')
@ -133,6 +132,18 @@ class FirebirdQBTest extends UnitTestCase {
$this->assertTrue(is_resource($query)); $this->assertTrue(is_resource($query));
} }
function TestOrWhere()
{
$query = $this->qb->select('id, key as k, val')
->from('create_test')
->where(' id ', 1)
->or_where('key >', 0)
->limit(2, 1)
->get();
$this->assertTrue(is_resource($query));
}
/*function TestGroupBy() /*function TestGroupBy()
{ {
$query = $this->qb->select('id, key as k, val') $query = $this->qb->select('id, key as k, val')
@ -149,6 +160,15 @@ class FirebirdQBTest extends UnitTestCase {
$this->assertTrue(is_resource($query)); $this->assertTrue(is_resource($query));
}*/ }*/
function TestLike()
{
$query = $this->qb->from('create_test')
->like('key', 'og')
->get();
$this->assertTrue(is_resource($query));
}
function TestInsert() function TestInsert()
{ {
$query = $this->qb->set('id', 4) $query = $this->qb->set('id', 4)

View File

@ -33,7 +33,7 @@
function TestGet() function TestGet()
{ {
$query = $this->qb->get('create_test'); $query = $this->qb->get('create_test ct');
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
} }
@ -143,6 +143,27 @@
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
} }
function TestOrWhere()
{
$query = $this->qb->select('id, key as k, val')
->from('create_test')
->where(' id ', 1)
->or_where('key >', 0)
->limit(2, 1)
->get();
$this->assertIsA($query, 'PDOStatement');
}
function TestLike()
{
$query = $this->qb->from('create_test')
->like('key', 'og')
->get();
$this->assertIsA($query, 'PDOStatement');
}
function TestInsert() function TestInsert()
{ {
$query = $this->qb->set('id', 4) $query = $this->qb->set('id', 4)

Binary file not shown.