Implement select_max, select_min, select_avg, and select_sum methods in query builder

This commit is contained in:
Timothy Warren 2012-04-13 12:49:13 -04:00
parent 15e7ef0832
commit 272dfd62d4
7 changed files with 223 additions and 32 deletions

View File

@ -45,7 +45,7 @@ Create a connection array or object similar to this:
The parameters required depend on the database. The parameters required depend on the database.
### Running Queries ### Running Queries
Query uses the same interface as CodeIgniter's [Active Record class](http://codeigniter.com/user_guide/database/active_record.html). However, it does not implement the `select_` methods, `count_all_results`, `distinct`, `having`, `or_having`, `insert_batch`, `update_batch`, or `count_all` methods. Query uses the same interface as CodeIgniter's [Active Record class](http://codeigniter.com/user_guide/database/active_record.html). However, it does not implement the `count_all_results`, `distinct`, `having`, `or_having`, `insert_batch`, `update_batch`, or `count_all` methods.
#### Retrieving Results #### Retrieving Results

View File

@ -27,6 +27,11 @@ abstract class DB_PDO extends PDO {
/** /**
* PDO constructor wrapper * PDO constructor wrapper
*
* @param string $dsn
* @param string $username
* @param string $password
* @param array $driver_options
*/ */
public function __construct($dsn, $username=NULL, $password=NULL, $driver_options=array()) public function __construct($dsn, $username=NULL, $password=NULL, $driver_options=array())
{ {
@ -35,7 +40,9 @@ abstract class DB_PDO extends PDO {
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} }
// ------------------------------------------------------------------------- // --------------------------------------------------------------------------
// ! Concrete functions that can be overridden in child classes
// --------------------------------------------------------------------------
/** /**
* Simplifies prepared statements for database queries * Simplifies prepared statements for database queries
@ -327,9 +334,8 @@ abstract class DB_PDO extends PDO {
return $this->driver_query($this->sql->system_table_list()); return $this->driver_query($this->sql->system_table_list());
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
// ! Abstract public functions to override in child classes // ! Abstract public functions to implement in child classes
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
/** /**

View File

@ -67,6 +67,18 @@ abstract class DB_SQL {
return ' AVG'; return ' AVG';
} }
// --------------------------------------------------------------------------
/**
* Get the 'sum' keyword
*
* @return string
*/
public function sum()
{
return ' SUM';
}
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// ! Abstract Methods // ! Abstract Methods
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------

View File

@ -38,7 +38,7 @@ class Query_Builder {
private $limit, private $limit,
$offset; $offset;
// Alias to $this->db->sql // Alias to $this->sql
private $sql; private $sql;
// Query component order mapping // Query component order mapping
@ -59,7 +59,7 @@ class Query_Builder {
/** /**
* Constructor * Constructor
* *
* @param object $conn_name - the name of the connection/parameters * @param object $params - the connection parametere
*/ */
public function __construct($params) public function __construct($params)
{ {
@ -111,9 +111,6 @@ class Query_Builder {
break; break;
} }
// Set the charset
//$dsn .= ";charset=utf-8";
// Create the database connection // Create the database connection
if ( ! empty($params->user)) if ( ! empty($params->user))
{ {
@ -183,6 +180,102 @@ class Query_Builder {
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/**
* Selects the maximum value of a field from a query
*
* @param string $field
* @param string $as
* @return $this
*/
public function select_max($field, $as=FALSE)
{
// Escape the identifiers
$field = $this->quote_ident($field);
$as = ($as !== FALSE)
? $this->quote_ident($as)
: $field;
// Create the select string
$this->select_string = $this->sql->max()."({$field}) AS {$as} ";
return $this;
}
// --------------------------------------------------------------------------
/**
* Selects the minimum value of a field from a query
*
* @param string $field
* @param string $as
* @return $this
*/
public function select_min($field, $as=FALSE)
{
// Escape the identifiers
$field = $this->quote_ident($field);
$as = ($as !== FALSE)
? $this->quote_ident($as)
: $field;
// Create the select string
$this->select_string = $this->sql->min()."({$field}) AS {$as} ";
return $this;
}
// --------------------------------------------------------------------------
/**
* Selects the average value of a field from a query
*
* @param string $field
* @param string $as
* @return $this
*/
public function select_avg($field, $as=FALSE)
{
// Escape the identifiers
$field = $this->quote_ident($field);
$as = ($as !== FALSE)
? $this->quote_ident($as)
: $field;
// Create the select string
$this->select_string = $this->sql->avg()."({$field}) AS {$as} ";
return $this;
}
// --------------------------------------------------------------------------
/**
* Selects the sum of a field from a query
*
* @param string $field
* @param string $as
* @return $this
*/
public function select_sum($field, $as=FALSE)
{
// Escape the identifiers
$field = $this->quote_ident($field);
$as = ($as !== FALSE)
? $this->quote_ident($as)
: $field;
// Create the select string
$this->select_string = $this->sql->sum()."({$field}) AS {$as} ";
return $this;
}
// --------------------------------------------------------------------------
/** /**
* Specify the database table to select from * Specify the database table to select from
* *
@ -218,7 +311,7 @@ class Query_Builder {
*/ */
public function like($field, $val, $pos='both') public function like($field, $val, $pos='both')
{ {
$field = $this->db->quote_ident($field); $field = $this->quote_ident($field);
// Add the like string into the order map // Add the like string into the order map
$l = $field. ' LIKE ?'; $l = $field. ' LIKE ?';
@ -260,7 +353,7 @@ class Query_Builder {
*/ */
public function or_like($field, $val, $pos='both') public function or_like($field, $val, $pos='both')
{ {
$field = $this->db->quote_ident($field); $field = $this->quote_ident($field);
// Add the like string into the order map // Add the like string into the order map
$l = $field. ' LIKE ?'; $l = $field. ' LIKE ?';
@ -302,7 +395,7 @@ class Query_Builder {
*/ */
public function not_like($field, $val, $pos='both') public function not_like($field, $val, $pos='both')
{ {
$field = $this->db->quote_ident($field); $field = $this->quote_ident($field);
// Add the like string into the order map // Add the like string into the order map
$l = $field. ' NOT LIKE ?'; $l = $field. ' NOT LIKE ?';
@ -344,7 +437,7 @@ class Query_Builder {
*/ */
public function or_not_like($field, $val, $pos='both') public function or_not_like($field, $val, $pos='both')
{ {
$field = $this->db->quote_ident($field); $field = $this->quote_ident($field);
// Add the like string into the order map // Add the like string into the order map
$l = $field. ' NOT LIKE ?'; $l = $field. ' NOT LIKE ?';
@ -430,7 +523,7 @@ class Query_Builder {
// is an operator such as >, <, !=, etc. // is an operator such as >, <, !=, etc.
$f_array = explode(' ', trim($f)); $f_array = explode(' ', trim($f));
$item = $this->db->quote_ident($f_array[0]); $item = $this->quote_ident($f_array[0]);
// Simple key value, or an operator // Simple key value, or an operator
$item .= (count($f_array === 1)) ? '= ?' : " {$f_array[1]} ?"; $item .= (count($f_array === 1)) ? '= ?' : " {$f_array[1]} ?";
@ -469,11 +562,11 @@ class Query_Builder {
// Simple key = val // Simple key = val
if (count($f_array) === 1) if (count($f_array) === 1)
{ {
$item = $this->db->quote_ident($f_array[0]) . '= ?'; $item = $this->quote_ident($f_array[0]) . '= ?';
} }
else // Other operators else // Other operators
{ {
$item = $this->db->quote_ident($f_array[0]) . " {$f_array[1]} ?"; $item = $this->quote_ident($f_array[0]) . " {$f_array[1]} ?";
} }
// Put in the query map for select statements // Put in the query map for select statements
@ -498,7 +591,7 @@ class Query_Builder {
*/ */
public function where_in($field, $val=array()) public function where_in($field, $val=array())
{ {
$field = $this->db->quote_ident($field); $field = $this->quote_ident($field);
$params = array_fill(0, count($val), '?'); $params = array_fill(0, count($val), '?');
foreach($val as $v) foreach($val as $v)
@ -528,7 +621,7 @@ class Query_Builder {
*/ */
public function or_where_in($field, $val=array()) public function or_where_in($field, $val=array())
{ {
$field = $this->db->quote_ident($field); $field = $this->quote_ident($field);
$params = array_fill(0, count($val), '?'); $params = array_fill(0, count($val), '?');
foreach($val as $v) foreach($val as $v)
@ -558,7 +651,7 @@ class Query_Builder {
*/ */
public function where_not_in($field, $val=array()) public function where_not_in($field, $val=array())
{ {
$field = $this->db->quote_ident($field); $field = $this->quote_ident($field);
$params = array_fill(0, count($val), '?'); $params = array_fill(0, count($val), '?');
foreach($val as $v) foreach($val as $v)
@ -588,7 +681,7 @@ class Query_Builder {
*/ */
public function or_where_not_in($field, $val=array()) public function or_where_not_in($field, $val=array())
{ {
$field = $this->db->quote_ident($field); $field = $this->quote_ident($field);
$params = array_fill(0, count($val), '?'); $params = array_fill(0, count($val), '?');
foreach($val as $v) foreach($val as $v)
@ -627,8 +720,8 @@ class Query_Builder {
$cond_array = explode(' ', trim($condition)); $cond_array = explode(' ', trim($condition));
$cond_array = array_map('trim', $cond_array); $cond_array = array_map('trim', $cond_array);
$condition = $table . ' ON ' . $this->db->quote_ident($cond_array[0]) . $cond_array[1] . $condition = $table . ' ON ' . $this->quote_ident($cond_array[0]) . $cond_array[1] .
' ' . $this->db->quote_ident($cond_array[2]); ' ' . $this->quote_ident($cond_array[2]);
$this->query_map[] = array( $this->query_map[] = array(
'type' => 'join', 'type' => 'join',
@ -655,7 +748,7 @@ class Query_Builder {
} }
else else
{ {
$this->group_array[] = $this->db->quote_ident($field); $this->group_array[] = $this->quote_ident($field);
} }
$this->group_string = ' GROUP BY ' . implode(', ', $this->group_array); $this->group_string = ' GROUP BY ' . implode(', ', $this->group_array);
@ -681,7 +774,7 @@ class Query_Builder {
} }
// Set fields for later manipulation // Set fields for later manipulation
$field = $this->db->quote_ident($field); $field = $this->quote_ident($field);
$this->order_array[$field] = $type; $this->order_array[$field] = $type;
$order_clauses = array(); $order_clauses = array();
@ -825,12 +918,12 @@ class Query_Builder {
// Do prepared statements for anything involving a "where" clause // Do prepared statements for anything involving a "where" clause
if ( ! empty($this->query_map)) if ( ! empty($this->query_map))
{ {
$result = $this->db->prepare_execute($sql, $this->values); $result = $this->prepare_execute($sql, $this->values);
} }
else else
{ {
// Otherwise, a simple query will do. // Otherwise, a simple query will do.
$result = $this->db->query($sql); $result = $this->query($sql);
} }
// Reset for next query // Reset for next query
@ -878,7 +971,7 @@ class Query_Builder {
$sql = $this->_compile("insert", $table); $sql = $this->_compile("insert", $table);
$res = $this->db->prepare_execute($sql, $this->values); $res = $this->prepare_execute($sql, $this->values);
$this->_reset(); $this->_reset();
@ -904,7 +997,7 @@ class Query_Builder {
$sql = $this->_compile('update', $table); $sql = $this->_compile('update', $table);
$res = $this->db->prepare_execute($sql, $this->values); $res = $this->prepare_execute($sql, $this->values);
$this->_reset(); $this->_reset();
@ -932,7 +1025,7 @@ class Query_Builder {
// Create the SQL and parameters // Create the SQL and parameters
$sql = $this->_compile("delete", $table); $sql = $this->_compile("delete", $table);
$res = $this->db->prepare_execute($sql, $this->values); $res = $this->prepare_execute($sql, $this->values);
$this->_reset(); $this->_reset();
@ -1090,13 +1183,13 @@ class Query_Builder {
case "insert": case "insert":
$param_count = count($this->set_array); $param_count = count($this->set_array);
$params = array_fill(0, $param_count, '?'); $params = array_fill(0, $param_count, '?');
$sql = 'INSERT INTO '. $this->db->quote_ident($table) . $sql = 'INSERT INTO '. $this->quote_ident($table) .
' (' . implode(', ', $this->set_array_keys) . ' (' . implode(', ', $this->set_array_keys) .
') VALUES ('.implode(', ', $params).')'; ') VALUES ('.implode(', ', $params).')';
break; break;
case "update": case "update":
$sql = 'UPDATE '.$this->db->quote_ident($table). ' SET '. $this->set_string; $sql = 'UPDATE '.$this->quote_ident($table). ' SET '. $this->set_string;
// Set the where string // Set the where string
if ( ! empty($this->query_map)) if ( ! empty($this->query_map))
@ -1109,7 +1202,7 @@ class Query_Builder {
break; break;
case "delete": case "delete":
$sql = 'DELETE FROM '.$this->db->quote_ident($table); $sql = 'DELETE FROM '.$this->quote_ident($table);
// Set the where string // Set the where string
if ( ! empty($this->query_map)) if ( ! empty($this->query_map))

View File

@ -76,6 +76,46 @@ class FirebirdQBTest extends QBTest {
$this->assertIsA($query, 'Firebird_Result'); $this->assertIsA($query, 'Firebird_Result');
} }
function TestSelectMax()
{
if (empty($this->db)) return;
$query = $this->db->select_max('id', 'di')
->get('create_test');
$this->assertIsA($query, 'Firebird_Result');
}
function TestSelectMin()
{
if (empty($this->db)) return;
$query = $this->db->select_min('id', 'di')
->get('create_test');
$this->assertIsA($query, 'Firebird_Result');
}
function TestSelectAvg()
{
if (empty($this->db)) return;
$query = $this->db->select_avg('id', 'di')
->get('create_test');
$this->assertIsA($query, 'Firebird_Result');
}
function TestSelectSum()
{
if (empty($this->db)) return;
$query = $this->db->select_sum('id', 'di')
->get('create_test');
$this->assertIsA($query, 'Firebird_Result');
}
function TestGetWhere() function TestGetWhere()
{ {
if (empty($this->db)) return; if (empty($this->db)) return;

Binary file not shown.

View File

@ -107,6 +107,46 @@ abstract class QBTest extends UnitTestCase {
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
} }
function TestSelectMax()
{
if (empty($this->db)) return;
$query = $this->db->select_max('id', 'di')
->get('create_test');
$this->assertIsA($query, 'PDOStatement');
}
function TestSelectMin()
{
if (empty($this->db)) return;
$query = $this->db->select_min('id', 'di')
->get('create_test');
$this->assertIsA($query, 'PDOStatement');
}
function TestSelectAvg()
{
if (empty($this->db)) return;
$query = $this->db->select_avg('id', 'di')
->get('create_test');
$this->assertIsA($query, 'PDOStatement');
}
function TestSelectSum()
{
if (empty($this->db)) return;
$query = $this->db->select_sum('id', 'di')
->get('create_test');
$this->assertIsA($query, 'PDOStatement');
}
function TestGetWhere() function TestGetWhere()
{ {
if (empty($this->db)) return; if (empty($this->db)) return;