camelCase methods and properties

This commit is contained in:
Timothy Warren 2016-10-13 21:55:23 -04:00
parent 111dce92d2
commit b8d4768b1b
43 changed files with 851 additions and 1297 deletions

View File

@ -1,4 +1,4 @@
<?php <?php declare(strict_types=1);
if ( ! function_exists('glob_recursive')) if ( ! function_exists('glob_recursive'))
{ {
// Does not support flag GLOB_BRACE // Does not support flag GLOB_BRACE

View File

@ -31,9 +31,5 @@
<file>tests/databases/firebird/FirebirdTest.php</file> <file>tests/databases/firebird/FirebirdTest.php</file>
<file>tests/databases/firebird/FirebirdQBTest.php</file> <file>tests/databases/firebird/FirebirdQBTest.php</file>
</testsuite> </testsuite>
<!-- <testsuite name="OCITests">
<file>tests/databases/oci/OCITest.php</file>
<file>tests/databases/oci/OCIQBTest.php</file>
</testsuite> -->
</testsuites> </testsuites>
</phpunit> </phpunit>

View File

@ -15,6 +15,8 @@
namespace Query; namespace Query;
use PDOStatement;
/** /**
* Abstract Class for internal implementation methods of the Query Builder * Abstract Class for internal implementation methods of the Query Builder
* @package Query * @package Query
@ -37,31 +39,31 @@ abstract class AbstractQueryBuilder {
* Compiled 'select' clause * Compiled 'select' clause
* @var string * @var string
*/ */
protected $select_string = ''; protected $selectString = '';
/** /**
* Compiled 'from' clause * Compiled 'from' clause
* @var string * @var string
*/ */
protected $from_string = ''; protected $fromString = '';
/** /**
* Compiled arguments for insert / update * Compiled arguments for insert / update
* @var string * @var string
*/ */
protected $set_string; protected $setString;
/** /**
* Order by clause * Order by clause
* @var string * @var string
*/ */
protected $order_string; protected $orderString;
/** /**
* Group by clause * Group by clause
* @var string * @var string
*/ */
protected $group_string; protected $groupString;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// ! SQL Clause Arrays // ! SQL Clause Arrays
@ -71,19 +73,19 @@ abstract class AbstractQueryBuilder {
* Keys for insert/update statement * Keys for insert/update statement
* @var array * @var array
*/ */
protected $set_array_keys = []; protected $setArrayKeys = [];
/** /**
* Key/val pairs for order by clause * Key/val pairs for order by clause
* @var array * @var array
*/ */
protected $order_array = []; protected $orderArray = [];
/** /**
* Key/val pairs for group by clause * Key/val pairs for group by clause
* @var array * @var array
*/ */
protected $group_array = []; protected $groupArray = [];
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// ! Other Class vars // ! Other Class vars
@ -99,7 +101,7 @@ abstract class AbstractQueryBuilder {
* Values to apply to where clauses in prepared statements * Values to apply to where clauses in prepared statements
* @var array * @var array
*/ */
protected $where_values = []; protected $whereValues = [];
/** /**
* Value for limit string * Value for limit string
@ -126,19 +128,19 @@ abstract class AbstractQueryBuilder {
* *
* @var array * @var array
*/ */
protected $query_map = []; protected $queryMap = [];
/** /**
* Map for having clause * Map for having clause
* @var array * @var array
*/ */
protected $having_map; protected $havingMap;
/** /**
* Convenience property for connection management * Convenience property for connection management
* @var string * @var string
*/ */
public $conn_name = ""; public $connName = "";
/** /**
* List of queries executed * List of queries executed
@ -186,10 +188,10 @@ abstract class AbstractQueryBuilder {
* @param array $var * @param array $var
* @param mixed $key * @param mixed $key
* @param mixed $val * @param mixed $val
* @param int $val_type * @param int $valType
* @return array * @return array
*/ */
protected function _mixed_set(&$var, $key, $val=NULL, $val_type=self::BOTH) protected function _mixedSet(array &$var, $key, $val=NULL, int $valType=self::BOTH): array
{ {
$arg = (is_scalar($key) && is_scalar($val)) $arg = (is_scalar($key) && is_scalar($val))
? [$key => $val] ? [$key => $val]
@ -197,9 +199,9 @@ abstract class AbstractQueryBuilder {
foreach($arg as $k => $v) foreach($arg as $k => $v)
{ {
if (in_array($val_type, [self::KEY, self::VALUE])) if (in_array($valType, [self::KEY, self::VALUE]))
{ {
$var[] = ($val_type === self::KEY) $var[] = ($valType === self::KEY)
? $k ? $k
: $v; : $v;
} }
@ -219,18 +221,17 @@ abstract class AbstractQueryBuilder {
* @param string|bool $as * @param string|bool $as
* @return string * @return string
*/ */
protected function _select($field, $as = FALSE) protected function _select(string $field, $as = FALSE): string
{ {
// Escape the identifiers // Escape the identifiers
$field = $this->db->quote_ident($field); $field = $this->db->quoteIdent($field);
if ( ! is_string($as)) if ( ! is_string($as))
{ {
return $field; return $field;
} }
$as = $this->db->quoteIdent($as);
$as = $this->db->quote_ident($as);
return "({$field}) AS {$as} "; return "({$field}) AS {$as} ";
} }
@ -242,14 +243,14 @@ abstract class AbstractQueryBuilder {
* @param bool $reset * @param bool $reset
* @return string * @return string
*/ */
protected function _get_compile($type, $table, $reset) protected function _getCompile(string $type, string $table, bool $reset): string
{ {
$sql = $this->_compile($type, $table); $sql = $this->_compile($type, $table);
// Reset the query builder for the next query // Reset the query builder for the next query
if ($reset) if ($reset)
{ {
$this->reset_query(); $this->resetQuery();
} }
return $sql; return $sql;
@ -265,9 +266,9 @@ abstract class AbstractQueryBuilder {
* @param string $conj * @param string $conj
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
protected function _like($field, $val, $pos, $like='LIKE', $conj='AND') protected function _like(string $field, $val, string $pos, string $like='LIKE', string $conj='AND'): QueryBuilderInterface
{ {
$field = $this->db->quote_ident($field); $field = $this->db->quoteIdent($field);
// Add the like string into the order map // Add the like string into the order map
$like = $field. " {$like} ?"; $like = $field. " {$like} ?";
@ -285,11 +286,11 @@ abstract class AbstractQueryBuilder {
$val = "%{$val}%"; $val = "%{$val}%";
} }
$conj = (empty($this->query_map)) ? ' WHERE ' : " {$conj} "; $conj = (empty($this->queryMap)) ? ' WHERE ' : " {$conj} ";
$this->_append_map($conj, $like, 'like'); $this->_appendMap($conj, $like, 'like');
// Add to the values array // Add to the values array
$this->where_values[] = $val; $this->whereValues[] = $val;
return $this; return $this;
} }
@ -302,7 +303,7 @@ abstract class AbstractQueryBuilder {
* @param string $conj * @param string $conj
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
protected function _having($key, $val=[], $conj='AND') protected function _having($key, $val=[], string $conj='AND'): QueryBuilderInterface
{ {
$where = $this->_where($key, $val); $where = $this->_where($key, $val);
@ -311,16 +312,16 @@ abstract class AbstractQueryBuilder {
{ {
// Split each key by spaces, in case there // Split each key by spaces, in case there
// is an operator such as >, <, !=, etc. // is an operator such as >, <, !=, etc.
$f_array = explode(' ', trim($f)); $fArray = explode(' ', trim($f));
$item = $this->db->quote_ident($f_array[0]); $item = $this->db->quoteIdent($fArray[0]);
// Simple key value, or an operator // Simple key value, or an operator
$item .= (count($f_array) === 1) ? '=?' : " {$f_array[1]} ?"; $item .= (count($fArray) === 1) ? '=?' : " {$fArray[1]} ?";
// Put in the having map // Put in the having map
$this->having_map[] = [ $this->havingMap[] = [
'conjunction' => ( ! empty($this->having_map)) ? " {$conj} " : ' HAVING ', 'conjunction' => ( ! empty($this->havingMap)) ? " {$conj} " : ' HAVING ',
'string' => $item 'string' => $item
]; ];
} }
@ -335,11 +336,11 @@ abstract class AbstractQueryBuilder {
* @param mixed $val * @param mixed $val
* @return array * @return array
*/ */
protected function _where($key, $val=[]) protected function _where($key, $val=[]): array
{ {
$where = []; $where = [];
$this->_mixed_set($where, $key, $val, self::BOTH); $this->_mixedSet($where, $key, $val, self::BOTH);
$this->_mixed_set($this->where_values, $key, $val, self::VALUE); $this->_mixedSet($this->whereValues, $key, $val, self::VALUE);
return $where; return $where;
} }
@ -351,28 +352,28 @@ abstract class AbstractQueryBuilder {
* @param string $defaultConj * @param string $defaultConj
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
protected function _where_string($key, $val=[], $defaultConj='AND') protected function _whereString($key, $val=[], string $defaultConj='AND'): QueryBuilderInterface
{ {
// Create key/value placeholders // Create key/value placeholders
foreach($this->_where($key, $val) as $f => $val) foreach($this->_where($key, $val) as $f => $val)
{ {
// Split each key by spaces, in case there // Split each key by spaces, in case there
// is an operator such as >, <, !=, etc. // is an operator such as >, <, !=, etc.
$f_array = explode(' ', trim($f)); $fArray = explode(' ', trim($f));
$item = $this->db->quote_ident($f_array[0]); $item = $this->db->quoteIdent($fArray[0]);
// Simple key value, or an operator // Simple key value, or an operator
$item .= (count($f_array) === 1) ? '=?' : " {$f_array[1]} ?"; $item .= (count($fArray) === 1) ? '=?' : " {$fArray[1]} ?";
$last_item = end($this->query_map); $lastItem = end($this->queryMap);
// Determine the correct conjunction // Determine the correct conjunction
$conjunctionList = array_column($this->query_map, 'conjunction'); $conjunctionList = array_column($this->queryMap, 'conjunction');
if (empty($this->query_map) || ( ! regex_in_array($conjunctionList, "/^ ?\n?WHERE/i"))) if (empty($this->queryMap) || ( ! regex_in_array($conjunctionList, "/^ ?\n?WHERE/i")))
{ {
$conj = "\nWHERE "; $conj = "\nWHERE ";
} }
elseif ($last_item['type'] === 'group_start') elseif ($lastItem['type'] === 'group_start')
{ {
$conj = ''; $conj = '';
} }
@ -381,7 +382,7 @@ abstract class AbstractQueryBuilder {
$conj = " {$defaultConj} "; $conj = " {$defaultConj} ";
} }
$this->_append_map($conj, $item, 'where'); $this->_appendMap($conj, $item, 'where');
} }
return $this; return $this;
@ -396,20 +397,20 @@ abstract class AbstractQueryBuilder {
* @param string $conj - The where in conjunction * @param string $conj - The where in conjunction
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
protected function _where_in($key, $val=[], $in='IN', $conj='AND') protected function _whereIn($key, $val=[], string $in='IN', string $conj='AND'): QueryBuilderInterface
{ {
$key = $this->db->quote_ident($key); $key = $this->db->quoteIdent($key);
$params = array_fill(0, count($val), '?'); $params = array_fill(0, count($val), '?');
foreach($val as $v) foreach($val as $v)
{ {
$this->where_values[] = $v; $this->whereValues[] = $v;
} }
$conjunction = ( ! empty($this->query_map)) ? " {$conj} " : ' WHERE '; $conjunction = ( ! empty($this->queryMap)) ? " {$conj} " : ' WHERE ';
$str = $key . " {$in} (".implode(',', $params).') '; $str = $key . " {$in} (".implode(',', $params).') ';
$this->_append_map($conjunction, $str, 'where_in'); $this->_appendMap($conjunction, $str, 'where_in');
return $this; return $this;
} }
@ -422,9 +423,9 @@ abstract class AbstractQueryBuilder {
* @param string $sql * @param string $sql
* @param array|null $vals * @param array|null $vals
* @param boolean $reset * @param boolean $reset
* @return \PDOStatement * @return PDOStatement
*/ */
protected function _run($type, $table, $sql=NULL, $vals=NULL, $reset=TRUE) protected function _run(string $type, string $table, $sql=NULL, $vals=NULL, bool $reset=TRUE): PDOStatement
{ {
if (is_null($sql)) if (is_null($sql))
{ {
@ -433,25 +434,25 @@ abstract class AbstractQueryBuilder {
if (is_null($vals)) if (is_null($vals))
{ {
$vals = array_merge($this->values, (array) $this->where_values); $vals = array_merge($this->values, (array) $this->whereValues);
} }
$start_time = microtime(TRUE); $startTime = microtime(TRUE);
$res = (empty($vals)) $res = (empty($vals))
? $this->db->query($sql) ? $this->db->query($sql)
: $this->db->prepare_execute($sql, $vals); : $this->db->prepareExecute($sql, $vals);
$end_time = microtime(TRUE); $endTime = microtime(TRUE);
$total_time = number_format($end_time - $start_time, 5); $totalTime = number_format($endTime - $startTime, 5);
// Add this query to the list of executed queries // Add this query to the list of executed queries
$this->_append_query($vals, $sql, $total_time); $this->_appendQuery($vals, $sql, (int) $totalTime);
// Reset class state for next query // Reset class state for next query
if ($reset) if ($reset)
{ {
$this->reset_query(); $this->resetQuery();
} }
return $res; return $res;
@ -465,9 +466,9 @@ abstract class AbstractQueryBuilder {
* @param string $type * @param string $type
* @return void * @return void
*/ */
protected function _append_map($conjunction = '', $string = '', $type = '') protected function _appendMap(string $conjunction = '', string $string = '', string $type = '')
{ {
array_push($this->query_map, [ array_push($this->queryMap, [
'type' => $type, 'type' => $type,
'conjunction' => $conjunction, 'conjunction' => $conjunction,
'string' => $string 'string' => $string
@ -479,10 +480,10 @@ abstract class AbstractQueryBuilder {
* *
* @param array $vals * @param array $vals
* @param string $sql * @param string $sql
* @param int $total_time * @param int $totalTime
* @return void * @return void
*/ */
protected function _append_query($vals, $sql, $total_time) protected function _appendQuery($vals, string $sql, int $totalTime)
{ {
$evals = (is_array($vals)) ? $vals : []; $evals = (is_array($vals)) ? $vals : [];
$esql = str_replace('?', "%s", $sql); $esql = str_replace('?', "%s", $sql);
@ -499,14 +500,14 @@ abstract class AbstractQueryBuilder {
// Add the interpreted query to the list of executed queries // Add the interpreted query to the list of executed queries
$this->queries[] = [ $this->queries[] = [
'time' => $total_time, 'time' => $totalTime,
'sql' => call_user_func_array('sprintf', $evals), 'sql' => call_user_func_array('sprintf', $evals),
]; ];
$this->queries['total_time'] += (int) $total_time; $this->queries['total_time'] += $totalTime;
// Set the last query to get rowcounts properly // Set the last query to get rowcounts properly
$this->db->set_last_query($sql); $this->db->setLastQuery($sql);
} }
/** /**
@ -516,20 +517,20 @@ abstract class AbstractQueryBuilder {
* @param string $table * @param string $table
* @return string * @return string
*/ */
protected function _compile_type($type='', $table='') protected function _compileType(string $type='', string $table=''): string
{ {
switch($type) switch($type)
{ {
case "insert": case "insert":
$param_count = count($this->set_array_keys); $paramCount = count($this->setArrayKeys);
$params = array_fill(0, $param_count, '?'); $params = array_fill(0, $paramCount, '?');
$sql = "INSERT INTO {$table} (" $sql = "INSERT INTO {$table} ("
. implode(',', $this->set_array_keys) . implode(',', $this->setArrayKeys)
. ")\nVALUES (".implode(',', $params).')'; . ")\nVALUES (".implode(',', $params).')';
break; break;
case "update": case "update":
$sql = "UPDATE {$table}\nSET {$this->set_string}"; $sql = "UPDATE {$table}\nSET {$this->setString}";
break; break;
case "replace": case "replace":
@ -543,13 +544,13 @@ abstract class AbstractQueryBuilder {
// Get queries // Get queries
default: default:
$sql = "SELECT * \nFROM {$this->from_string}"; $sql = "SELECT * \nFROM {$this->fromString}";
// Set the select string // Set the select string
if ( ! empty($this->select_string)) if ( ! empty($this->selectString))
{ {
// Replace the star with the selected fields // Replace the star with the selected fields
$sql = str_replace('*', $this->select_string, $sql); $sql = str_replace('*', $this->selectString, $sql);
} }
break; break;
} }
@ -564,16 +565,16 @@ abstract class AbstractQueryBuilder {
* @param string $table * @param string $table
* @return string * @return string
*/ */
protected function _compile($type='', $table='') protected function _compile(string $type='', string $table=''): string
{ {
// Get the base clause for the query // Get the base clause for the query
$sql = $this->_compile_type($type, $this->db->quote_table($table)); $sql = $this->_compileType($type, $this->db->quoteTable($table));
$clauses = [ $clauses = [
'query_map', 'queryMap',
'group_string', 'groupString',
'order_string', 'orderString',
'having_map', 'havingMap',
]; ];
// Set each type of subclause // Set each type of subclause

View File

@ -12,9 +12,6 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query; namespace Query;
use InvalidArgumentException; use InvalidArgumentException;
@ -27,5 +24,3 @@ use InvalidArgumentException;
*/ */
class BadDBDriverException extends InvalidArgumentException { class BadDBDriverException extends InvalidArgumentException {
} }
// End of BadDBDriverException.php

View File

@ -12,9 +12,6 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query; namespace Query;
use DomainException; use DomainException;
@ -23,9 +20,6 @@ use InvalidArgumentException;
/** /**
* Connection manager class to manage connections for the * Connection manager class to manage connections for the
* Query method * Query method
*
* @package Query
* @subpackage Core
*/ */
final class ConnectionManager { final class ConnectionManager {
@ -41,8 +35,6 @@ final class ConnectionManager {
*/ */
private static $instance = NULL; private static $instance = NULL;
// --------------------------------------------------------------------------
/** /**
* Private constructor to prevent multiple instances * Private constructor to prevent multiple instances
* @codeCoverageIgnore * @codeCoverageIgnore
@ -51,8 +43,6 @@ final class ConnectionManager {
{ {
} }
// --------------------------------------------------------------------------
/** /**
* Private clone method to prevent cloning * Private clone method to prevent cloning
* *
@ -64,8 +54,6 @@ final class ConnectionManager {
throw new DomainException("Can't clone singleton"); throw new DomainException("Can't clone singleton");
} }
// --------------------------------------------------------------------------
/** /**
* Prevent serialization of this object * Prevent serialization of this object
* *
@ -77,8 +65,6 @@ final class ConnectionManager {
throw new DomainException("No serializing of singleton"); throw new DomainException("No serializing of singleton");
} }
// --------------------------------------------------------------------------
/** /**
* Make sure serialize/deserialize doesn't work * Make sure serialize/deserialize doesn't work
* *
@ -90,15 +76,13 @@ final class ConnectionManager {
throw new DomainException("Can't unserialize singleton"); throw new DomainException("Can't unserialize singleton");
} }
// --------------------------------------------------------------------------
/** /**
* Return a connection manager instance * Return a connection manager instance
* *
* @staticvar null $instance * @staticvar null $instance
* @return ConnectionManager * @return ConnectionManager
*/ */
public static function get_instance() public static function getInstance(): ConnectionManager
{ {
if (self::$instance === NULL) if (self::$instance === NULL)
{ {
@ -108,16 +92,14 @@ final class ConnectionManager {
return self::$instance; return self::$instance;
} }
// --------------------------------------------------------------------------
/** /**
* Returns the connection specified by the name given * Returns the connection specified by the name given
* *
* @param string|array|object $name * @param string|array|object $name
* @return QueryBuilder * @return QueryBuilderInterface
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public function get_connection($name = '') public function getConnection($name = ''): QueryBuilderInterface
{ {
// If the parameter is a string, use it as an array index // If the parameter is a string, use it as an array index
if (is_scalar($name) && isset($this->connections[$name])) if (is_scalar($name) && isset($this->connections[$name]))
@ -133,17 +115,15 @@ final class ConnectionManager {
throw new InvalidArgumentException("The specified connection does not exist"); throw new InvalidArgumentException("The specified connection does not exist");
} }
// --------------------------------------------------------------------------
/** /**
* Parse the passed parameters and return a connection * Parse the passed parameters and return a connection
* *
* @param \stdClass $params * @param \stdClass $params
* @return QueryBuilder * @return QueryBuilderInterface
*/ */
public function connect(\stdClass $params) public function connect(\stdClass $params): QueryBuilderInterface
{ {
list($dsn, $dbtype, $params, $options) = $this->parse_params($params); list($dsn, $dbtype, $params, $options) = $this->parseParams($params);
$dbtype = ucfirst($dbtype); $dbtype = ucfirst($dbtype);
$driver = "\\Query\\Drivers\\{$dbtype}\\Driver"; $driver = "\\Query\\Drivers\\{$dbtype}\\Driver";
@ -156,7 +136,7 @@ final class ConnectionManager {
// Set the table prefix, if it exists // Set the table prefix, if it exists
if (isset($params->prefix)) if (isset($params->prefix))
{ {
$db->set_table_prefix($params->prefix); $db->setTablePrefix($params->prefix);
} }
// Create Query Builder object // Create Query Builder object
@ -176,8 +156,6 @@ final class ConnectionManager {
return $conn; return $conn;
} }
// --------------------------------------------------------------------------
/** /**
* Parses params into a dsn and option array * Parses params into a dsn and option array
* *
@ -185,7 +163,7 @@ final class ConnectionManager {
* @return array * @return array
* @throws BadDBDriverException * @throws BadDBDriverException
*/ */
public function parse_params(\stdClass $params) public function parseParams(\stdClass $params): array
{ {
$params->type = strtolower($params->type); $params->type = strtolower($params->type);
$dbtype = ($params->type !== 'postgresql') ? $params->type : 'pgsql'; $dbtype = ($params->type !== 'postgresql') ? $params->type : 'pgsql';
@ -220,15 +198,13 @@ final class ConnectionManager {
} }
else else
{ {
$dsn = $this->create_dsn($dbtype, $params); $dsn = $this->createDsn($dbtype, $params);
} }
return [$dsn, $dbtype, $params, $options]; return [$dsn, $dbtype, $params, $options];
} }
// --------------------------------------------------------------------------
/** /**
* Create the dsn from the db type and params * Create the dsn from the db type and params
* *
@ -236,7 +212,7 @@ final class ConnectionManager {
* @param \stdClass $params * @param \stdClass $params
* @return string * @return string
*/ */
private function create_dsn($dbtype, \stdClass $params) private function createDsn(string $dbtype, \stdClass $params): string
{ {
if (strtolower($dbtype) === 'pdo_firebird') if (strtolower($dbtype) === 'pdo_firebird')
{ {
@ -272,4 +248,3 @@ final class ConnectionManager {
return strtolower($dbtype) . ':' . implode(';', $pairs); return strtolower($dbtype) . ':' . implode(';', $pairs);
} }
} }
// End of connection_manager.php

View File

@ -13,7 +13,6 @@
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query\Drivers; namespace Query\Drivers;
use InvalidArgumentException; use InvalidArgumentException;
@ -40,13 +39,13 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
* Start character to escape identifiers * Start character to escape identifiers
* @var string * @var string
*/ */
protected $escape_char_open = '"'; protected $escapeCharOpen = '"';
/** /**
* End character to escape identifiers * End character to escape identifiers
* @var string * @var string
*/ */
protected $escape_char_close = '"'; protected $escapeCharClose = '"';
/** /**
* Reference to sql class * Reference to sql class
@ -64,19 +63,19 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
* Last query executed * Last query executed
* @var string * @var string
*/ */
protected $last_query = ''; protected $lastQuery = '';
/** /**
* Prefix to apply to table names * Prefix to apply to table names
* @var string * @var string
*/ */
protected $table_prefix = ''; protected $tablePrefix = '';
/** /**
* Whether the driver supports 'TRUNCATE' * Whether the driver supports 'TRUNCATE'
* @var boolean * @var boolean
*/ */
protected $has_truncate = TRUE; protected $hasTruncate = TRUE;
/** /**
* PDO constructor wrapper * PDO constructor wrapper
@ -84,40 +83,36 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
* @param string $dsn * @param string $dsn
* @param string $username * @param string $username
* @param string $password * @param string $password
* @param array $driver_options * @param array $driverOptions
*/ */
public function __construct($dsn, $username=NULL, $password=NULL, array $driver_options=[]) public function __construct($dsn, $username=NULL, $password=NULL, array $driverOptions=[])
{ {
// Set PDO to display errors as exceptions, and apply driver options // Set PDO to display errors as exceptions, and apply driver options
$driver_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION; $driverOptions[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
parent::__construct($dsn, $username, $password, $driver_options); parent::__construct($dsn, $username, $password, $driverOptions);
$this->_load_sub_classes(); $this->_loadSubClasses();
} }
// --------------------------------------------------------------------------
/** /**
* Loads the subclasses for the driver * Loads the subclasses for the driver
* *
* @return void * @return void
*/ */
protected function _load_sub_classes() protected function _loadSubClasses()
{ {
// Load the sql and util class for the driver // Load the sql and util class for the driver
$this_class = get_class($this); $thisClass = get_class($this);
$ns_array = explode("\\", $this_class); $nsArray = explode("\\", $thisClass);
array_pop($ns_array); array_pop($nsArray);
$driver = array_pop($ns_array); $driver = array_pop($nsArray);
$sql_class = __NAMESPACE__ . "\\{$driver}\\SQL"; $sqlClass = __NAMESPACE__ . "\\{$driver}\\SQL";
$util_class = __NAMESPACE__ . "\\{$driver}\\Util"; $utilClass = __NAMESPACE__ . "\\{$driver}\\Util";
$this->sql = new $sql_class(); $this->sql = new $sqlClass();
$this->util = new $util_class($this); $this->util = new $utilClass($this);
} }
// --------------------------------------------------------------------------
/** /**
* Allow invoke to work on table object * Allow invoke to work on table object
* *
@ -147,59 +142,51 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
* *
* @return string * @return string
*/ */
public function get_last_query(): string public function getLastQuery(): string
{ {
return $this->last_query; return $this->lastQuery;
} }
// --------------------------------------------------------------------------
/** /**
* Set the last query sql * Set the last query sql
* *
* @param string $query_string * @param string $queryString
* @return void * @return void
*/ */
public function set_last_query(string $query_string) public function setLastQuery(string $queryString)
{ {
$this->last_query = $query_string; $this->lastQuery = $queryString;
} }
// --------------------------------------------------------------------------
/** /**
* Get the SQL class for the current driver * Get the SQL class for the current driver
* *
* @return SQLInterface * @return SQLInterface
*/ */
public function get_sql() public function getSql(): SQLInterface
{ {
return $this->sql; return $this->sql;
} }
// --------------------------------------------------------------------------
/** /**
* Get the Util class for the current driver * Get the Util class for the current driver
* *
* @return AbstractUtil * @return AbstractUtil
*/ */
public function get_util() public function getUtil(): AbstractUtil
{ {
return $this->util; return $this->util;
} }
// --------------------------------------------------------------------------
/** /**
* Set the common table name prefix * Set the common table name prefix
* *
* @param string $prefix * @param string $prefix
* @return void * @return void
*/ */
public function set_table_prefix($prefix) public function setTablePrefix($prefix)
{ {
$this->table_prefix = $prefix; $this->tablePrefix = $prefix;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -214,7 +201,7 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
* @return PDOStatement | FALSE * @return PDOStatement | FALSE
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public function prepare_query($sql, $data) public function prepareQuery($sql, $data)
{ {
// Prepare the sql, save the statement for easy access later // Prepare the sql, save the statement for easy access later
$this->statement = $this->prepare($sql); $this->statement = $this->prepare($sql);
@ -239,8 +226,6 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
return $this->statement; return $this->statement;
} }
// -------------------------------------------------------------------------
/** /**
* Create and execute a prepared statement with the provided parameters * Create and execute a prepared statement with the provided parameters
* *
@ -248,83 +233,75 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
* @param array $params * @param array $params
* @return PDOStatement * @return PDOStatement
*/ */
public function prepare_execute($sql, $params) public function prepareExecute($sql, $params)
{ {
$this->statement = $this->prepare_query($sql, $params); $this->statement = $this->prepareQuery($sql, $params);
$this->statement->execute(); $this->statement->execute();
return $this->statement; return $this->statement;
} }
// -------------------------------------------------------------------------
/** /**
* Returns number of rows affected by an INSERT, UPDATE, DELETE type query * Returns number of rows affected by an INSERT, UPDATE, DELETE type query
* *
* @return int * @return int
*/ */
public function affected_rows() public function affectedRows()
{ {
// Return number of rows affected // Return number of rows affected
return $this->statement->rowCount(); return $this->statement->rowCount();
} }
// --------------------------------------------------------------------------
/** /**
* Prefixes a table if it is not already prefixed * Prefixes a table if it is not already prefixed
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function prefix_table($table) public function prefixTable($table)
{ {
// Add the prefix to the table name // Add the prefix to the table name
// before quoting it // before quoting it
if ( ! empty($this->table_prefix)) if ( ! empty($this->tablePrefix))
{ {
// Split identifier by period, will split into: // Split identifier by period, will split into:
// database.schema.table OR // database.schema.table OR
// schema.table OR // schema.table OR
// database.table OR // database.table OR
// table // table
$identifierifiers = explode('.', $table); $identifiers = explode('.', $table);
$segments = count($identifierifiers); $segments = count($identifiers);
// Quote the last item, and add the database prefix // Quote the last item, and add the database prefix
$identifierifiers[$segments - 1] = $this->_prefix(end($identifierifiers)); $identifiers[$segments - 1] = $this->_prefix(end($identifiers));
// Rejoin // Rejoin
$table = implode('.', $identifierifiers); $table = implode('.', $identifiers);
} }
return $table; return $table;
} }
// --------------------------------------------------------------------------
/** /**
* Quote database table name, and set prefix * Quote database table name, and set prefix
* *
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function quote_table($table) public function quoteTable($table)
{ {
$table = $this->prefix_table($table); $table = $this->prefixTable($table);
// Finally, quote the table // Finally, quote the table
return $this->quote_ident($table); return $this->quoteIdent($table);
} }
// --------------------------------------------------------------------------
/** /**
* Surrounds the string with the databases identifier escape characters * Surrounds the string with the databases identifier escape characters
* *
* @param mixed $identifier * @param mixed $identifier
* @return string * @return string
*/ */
public function quote_ident($identifier) public function quoteIdent($identifier)
{ {
if (is_array($identifier)) if (is_array($identifier))
{ {
@ -348,199 +325,171 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
// Fix functions // Fix functions
$funcs = []; $funcs = [];
preg_match_all("#{$this->escape_char_open}([a-zA-Z0-9_]+(\((.*?)\))){$this->escape_char_close}#iu", $raw, $funcs, PREG_SET_ORDER); preg_match_all("#{$this->escapeCharOpen}([a-zA-Z0-9_]+(\((.*?)\))){$this->escapeCharClose}#iu", $raw, $funcs, PREG_SET_ORDER);
foreach($funcs as $f) foreach($funcs as $f)
{ {
// Unquote the function // Unquote the function
$raw = str_replace($f[0], $f[1], $raw); $raw = str_replace($f[0], $f[1], $raw);
// Quote the inside identifiers // Quote the inside identifiers
$raw = str_replace($f[3], $this->quote_ident($f[3]), $raw); $raw = str_replace($f[3], $this->quoteIdent($f[3]), $raw);
} }
return $raw; return $raw;
} }
// -------------------------------------------------------------------------
/** /**
* Return schemas for databases that list them * Return schemas for databases that list them
* *
* @return array * @return array
*/ */
public function get_schemas() public function getSchemas()
{ {
return NULL; return NULL;
} }
// -------------------------------------------------------------------------
/** /**
* Return list of tables for the current database * Return list of tables for the current database
* *
* @return array * @return array
*/ */
public function get_tables() public function getTables()
{ {
$tables = $this->driver_query('table_list'); $tables = $this->driverQuery('tableList');
natsort($tables); natsort($tables);
return $tables; return $tables;
} }
// -------------------------------------------------------------------------
/** /**
* Return list of dbs for the current connection, if possible * Return list of dbs for the current connection, if possible
* *
* @return array * @return array
*/ */
public function get_dbs() public function getDbs()
{ {
return $this->driver_query('db_list'); return $this->driverQuery('dbList');
} }
// -------------------------------------------------------------------------
/** /**
* Return list of views for the current database * Return list of views for the current database
* *
* @return array * @return array
*/ */
public function get_views() public function getViews()
{ {
$views = $this->driver_query('view_list'); $views = $this->driverQuery('viewList');
sort($views); sort($views);
return $views; return $views;
} }
// -------------------------------------------------------------------------
/** /**
* Return list of sequences for the current database, if they exist * Return list of sequences for the current database, if they exist
* *
* @return array * @return array
*/ */
public function get_sequences() public function getSequences()
{ {
return $this->driver_query('sequence_list'); return $this->driverQuery('sequenceList');
} }
// -------------------------------------------------------------------------
/** /**
* Return list of functions for the current database * Return list of functions for the current database
* *
* @return array * @return array
*/ */
public function get_functions() public function getFunctions()
{ {
return $this->driver_query('function_list', FALSE); return $this->driverQuery('functionList', FALSE);
} }
// -------------------------------------------------------------------------
/** /**
* Return list of stored procedures for the current database * Return list of stored procedures for the current database
* *
* @return array * @return array
*/ */
public function get_procedures() public function getProcedures()
{ {
return $this->driver_query('procedure_list', FALSE); return $this->driverQuery('procedureList', FALSE);
} }
// -------------------------------------------------------------------------
/** /**
* Return list of triggers for the current database * Return list of triggers for the current database
* *
* @return array * @return array
*/ */
public function get_triggers() public function getTriggers()
{ {
return $this->driver_query('trigger_list', FALSE); return $this->driverQuery('triggerList', FALSE);
} }
// -------------------------------------------------------------------------
/** /**
* Retrieves an array of non-user-created tables for * Retrieves an array of non-user-created tables for
* the connection/database * the connection/database
* *
* @return array * @return array
*/ */
public function get_system_tables() public function getSystemTables()
{ {
return $this->driver_query('system_table_list'); return $this->driverQuery('systemTableList');
} }
// --------------------------------------------------------------------------
/** /**
* Retrieve column information for the current database table * Retrieve column information for the current database table
* *
* @param string $table * @param string $table
* @return array * @return array
*/ */
public function get_columns($table) public function getColumns($table)
{ {
return $this->driver_query($this->get_sql()->column_list($this->prefix_table($table)), FALSE); return $this->driverQuery($this->getSql()->columnList($this->prefixTable($table)), FALSE);
} }
// --------------------------------------------------------------------------
/** /**
* Retrieve foreign keys for the table * Retrieve foreign keys for the table
* *
* @param string $table * @param string $table
* @return array * @return array
*/ */
public function get_fks($table) public function getFks($table)
{ {
return $this->driver_query($this->get_sql()->fk_list($table), FALSE); return $this->driverQuery($this->getSql()->fkList($table), FALSE);
} }
// --------------------------------------------------------------------------
/** /**
* Retrieve indexes for the table * Retrieve indexes for the table
* *
* @param string $table * @param string $table
* @return array * @return array
*/ */
public function get_indexes($table) public function getIndexes($table)
{ {
return $this->driver_query($this->get_sql()->index_list($this->prefix_table($table)), FALSE); return $this->driverQuery($this->getSql()->indexList($this->prefixTable($table)), FALSE);
} }
// --------------------------------------------------------------------------
/** /**
* Retrieve list of data types for the database * Retrieve list of data types for the database
* *
* @return array * @return array
*/ */
public function get_types() public function getTypes()
{ {
return $this->driver_query('type_list', FALSE); return $this->driverQuery('typeList', FALSE);
} }
// -------------------------------------------------------------------------
/** /**
* Method to simplify retrieving db results for meta-data queries * Method to simplify retrieving db results for meta-data queries
* *
* @param string|array|null $query * @param string|array|null $query
* @param bool $filtered_index * @param bool $filteredIndex
* @return array * @return array
*/ */
public function driver_query($query, $filtered_index=TRUE) public function driverQuery($query, $filteredIndex=TRUE)
{ {
// Call the appropriate method, if it exists // Call the appropriate method, if it exists
if (is_string($query) && method_exists($this->sql, $query)) if (is_string($query) && method_exists($this->sql, $query))
{ {
$query = $this->get_sql()->$query(); $query = $this->getSql()->$query();
} }
// Return if the values are returned instead of a query, // Return if the values are returned instead of a query,
@ -553,26 +502,24 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
// Run the query! // Run the query!
$res = $this->query($query); $res = $this->query($query);
$flag = ($filtered_index) ? PDO::FETCH_NUM : PDO::FETCH_ASSOC; $flag = ($filteredIndex) ? PDO::FETCH_NUM : PDO::FETCH_ASSOC;
$all = $res->fetchAll($flag); $all = $res->fetchAll($flag);
return ($filtered_index) ? \db_filter($all, 0) : $all; return ($filteredIndex) ? \db_filter($all, 0) : $all;
} }
// --------------------------------------------------------------------------
/** /**
* Return the number of rows returned for a SELECT query * Return the number of rows returned for a SELECT query
* *
* @see http://us3.php.net/manual/en/pdostatement.rowcount.php#87110 * @see http://us3.php.net/manual/en/pdostatement.rowcount.php#87110
* @return int|null * @return int|null
*/ */
public function num_rows() public function numRows()
{ {
$regex = '/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/i'; $regex = '/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/i';
$output = []; $output = [];
if (preg_match($regex, $this->last_query, $output) > 0) if (preg_match($regex, $this->lastQuery, $output) > 0)
{ {
$stmt = $this->query("SELECT COUNT(*) FROM {$output[1]}"); $stmt = $this->query("SELECT COUNT(*) FROM {$output[1]}");
return (int) $stmt->fetchColumn(); return (int) $stmt->fetchColumn();
@ -581,8 +528,6 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
return NULL; return NULL;
} }
// --------------------------------------------------------------------------
/** /**
* Create sql for batch insert * Create sql for batch insert
* *
@ -590,11 +535,11 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
* @param array|object $data * @param array|object $data
* @return null|array<string|array|null> * @return null|array<string|array|null>
*/ */
public function insert_batch($table, $data=[]) public function insertBatch($table, $data=[])
{ {
$data = (array) $data; $data = (array) $data;
$first_row = (array) current($data); $firstRow = (array) current($data);
if (is_scalar($first_row)) if (is_scalar($firstRow))
{ {
return NULL; return NULL;
} }
@ -605,26 +550,24 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
{ {
$vals = array_merge($vals, array_values($group)); $vals = array_merge($vals, array_values($group));
} }
$table = $this->quote_table($table); $table = $this->quoteTable($table);
$fields = array_keys($first_row); $fields = array_keys($firstRow);
$sql = "INSERT INTO {$table} (" $sql = "INSERT INTO {$table} ("
. implode(',', $this->quote_ident($fields)) . implode(',', $this->quoteIdent($fields))
. ") VALUES "; . ") VALUES ";
// Create the placeholder groups // Create the placeholder groups
$params = array_fill(0, count($fields), '?'); $params = array_fill(0, count($fields), '?');
$param_string = "(" . implode(',', $params) . ")"; $paramString = "(" . implode(',', $params) . ")";
$param_list = array_fill(0, count($data), $param_string); $paramList = array_fill(0, count($data), $paramString);
// Append the placeholder groups to the query // Append the placeholder groups to the query
$sql .= implode(',', $param_list); $sql .= implode(',', $paramList);
return [$sql, $vals]; return [$sql, $vals];
} }
// --------------------------------------------------------------------------
/** /**
* Creates a batch update, and executes it. * Creates a batch update, and executes it.
* Returns the number of affected rows * Returns the number of affected rows
@ -634,14 +577,12 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
* @param string $where * @param string $where
* @return int|null * @return int|null
*/ */
public function update_batch($table, $data, $where) public function updateBatch($table, $data, $where)
{ {
// @TODO implement // @TODO implement
return NULL; return NULL;
} }
// --------------------------------------------------------------------------
/** /**
* Helper method for quote_ident * Helper method for quote_ident
* *
@ -655,16 +596,14 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
// that value, otherwise, return the original value // that value, otherwise, return the original value
return ( return (
is_string($str) is_string($str)
&& strpos($str, $this->escape_char_open) !== 0 && strpos($str, $this->escapeCharOpen) !== 0
&& strrpos($str, $this->escape_char_close) !== 0 && strrpos($str, $this->escapeCharClose) !== 0
) )
? "{$this->escape_char_open}{$str}{$this->escape_char_close}" ? "{$this->escapeCharOpen}{$str}{$this->escapeCharClose}"
: $str; : $str;
} }
// --------------------------------------------------------------------------
/** /**
* Sets the table prefix on the passed string * Sets the table prefix on the passed string
* *
@ -674,16 +613,14 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
protected function _prefix($str) protected function _prefix($str)
{ {
// Don't prefix an already prefixed table // Don't prefix an already prefixed table
if (strpos($str, $this->table_prefix) !== FALSE) if (strpos($str, $this->tablePrefix) !== FALSE)
{ {
return $str; return $str;
} }
return $this->table_prefix.$str; return $this->tablePrefix . $str;
} }
// -------------------------------------------------------------------------
/** /**
* Empty the passed table * Empty the passed table
* *
@ -692,15 +629,14 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
*/ */
public function truncate($table) public function truncate($table)
{ {
$sql = ($this->has_truncate) $sql = ($this->hasTruncate)
? 'TRUNCATE TABLE ' ? 'TRUNCATE TABLE '
: 'DELETE FROM '; : 'DELETE FROM ';
$sql .= $this->quote_table($table); $sql .= $this->quoteTable($table);
$this->statement = $this->query($sql); $this->statement = $this->query($sql);
return $this->statement; return $this->statement;
} }
} }
// End of db_pdo.php

View File

@ -13,11 +13,6 @@
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
// --------------------------------------------------------------------------
namespace Query\Drivers; namespace Query\Drivers;
/** /**
@ -48,4 +43,3 @@ abstract class AbstractSQL implements SQLInterface {
return $sql; return $sql;
} }
} }
// End of abstract_sql.php

View File

@ -13,16 +13,13 @@
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query\Drivers; namespace Query\Drivers;
/** /**
* Abstract class defining database / table creation methods * Abstract class defining database / table creation methods
* *
* @package Query * @method string quoteIdent(string $sql)
* @subpackage Drivers * @method string quoteTable(string $sql)
* @method string quote_ident(string $sql)
* @method string quote_table(string $sql)
*/ */
abstract class AbstractUtil { abstract class AbstractUtil {
@ -42,49 +39,45 @@ abstract class AbstractUtil {
$this->conn = $conn; $this->conn = $conn;
} }
// --------------------------------------------------------------------------
/** /**
* Get the driver object for the current connection * Get the driver object for the current connection
* *
* @return DriverInterface * @return DriverInterface
*/ */
public function get_driver() public function getDriver()
{ {
return $this->conn; return $this->conn;
} }
// --------------------------------------------------------------------------
/** /**
* Convenience public function to generate sql for creating a db table * Convenience public function to generate sql for creating a db table
* *
* @param string $name * @param string $name
* @param array $fields * @param array $fields
* @param array $constraints * @param array $constraints
* @param bool $if_not_exists * @param bool $ifNotExists
* @return string * @return string
*/ */
public function create_table($name, $fields, array $constraints=[], $if_not_exists=TRUE) public function createTable($name, $fields, array $constraints=[], $ifNotExists=TRUE)
{ {
$exists_str = ($if_not_exists) ? ' IF NOT EXISTS ' : ' '; $existsStr = ($ifNotExists) ? ' IF NOT EXISTS ' : ' ';
// Reorganize into an array indexed with column information // Reorganize into an array indexed with column information
// Eg $column_array[$colname] = array( // Eg $columnArray[$colname] = array(
// 'type' => ..., // 'type' => ...,
// 'constraint' => ..., // 'constraint' => ...,
// 'index' => ..., // 'index' => ...,
// ) // )
$column_array = \array_zipper([ $columnArray = \array_zipper([
'type' => $fields, 'type' => $fields,
'constraint' => $constraints 'constraint' => $constraints
]); ]);
// Join column definitions together // Join column definitions together
$columns = []; $columns = [];
foreach($column_array as $n => $props) foreach($columnArray as $n => $props)
{ {
$str = $this->get_driver()->quote_ident($n); $str = $this->getDriver()->quoteIdent($n);
$str .= (isset($props['type'])) ? " {$props['type']}" : ""; $str .= (isset($props['type'])) ? " {$props['type']}" : "";
$str .= (isset($props['constraint'])) ? " {$props['constraint']}" : ""; $str .= (isset($props['constraint'])) ? " {$props['constraint']}" : "";
@ -92,27 +85,24 @@ abstract class AbstractUtil {
} }
// Generate the sql for the creation of the table // Generate the sql for the creation of the table
$sql = 'CREATE TABLE'.$exists_str.$this->get_driver()->quote_table($name).' ('; $sql = 'CREATE TABLE'.$existsStr.$this->getDriver()->quoteTable($name).' (';
$sql .= implode(', ', $columns); $sql .= implode(', ', $columns);
$sql .= ')'; $sql .= ')';
return $sql; return $sql;
} }
// --------------------------------------------------------------------------
/** /**
* Drop the selected table * Drop the selected table
* *
* @param string $name * @param string $name
* @return string * @return string
*/ */
public function delete_table($name) public function deleteTable($name)
{ {
return 'DROP TABLE IF EXISTS '.$this->get_driver()->quote_table($name); return 'DROP TABLE IF EXISTS '.$this->getDriver()->quoteTable($name);
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// ! Abstract Methods // ! Abstract Methods
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -123,9 +113,7 @@ abstract class AbstractUtil {
* @abstract * @abstract
* @return string * @return string
*/ */
abstract public function backup_structure(); abstract public function backupStructure();
// --------------------------------------------------------------------------
/** /**
* Return an SQL file with the database data as insert statements * Return an SQL file with the database data as insert statements
@ -133,7 +121,6 @@ abstract class AbstractUtil {
* @abstract * @abstract
* @return string * @return string
*/ */
abstract public function backup_data(); abstract public function backupData();
} }
// End of abstract_util.php

View File

@ -12,15 +12,10 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query\Drivers; namespace Query\Drivers;
/** /**
* PDO Interface to implement for database drivers * PDO Interface to implement for database drivers
*
* @package Query
* @subpackage Drivers
*/ */
interface DriverInterface extends PDOInterface { interface DriverInterface extends PDOInterface {
@ -30,9 +25,9 @@ interface DriverInterface extends PDOInterface {
* @param string $dsn * @param string $dsn
* @param string $username * @param string $username
* @param string $password * @param string $password
* @param array $driver_options * @param array $driverOptions
*/ */
public function __construct($dsn, $username=NULL, $password=NULL, array $driver_options = []); public function __construct($dsn, $username=NULL, $password=NULL, array $driverOptions = []);
/** /**
* Simplifies prepared statements for database queries * Simplifies prepared statements for database queries
@ -42,7 +37,7 @@ interface DriverInterface extends PDOInterface {
* @return \PDOStatement | FALSE * @return \PDOStatement | FALSE
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
*/ */
public function prepare_query($sql, $data); public function prepareQuery($sql, $data);
/** /**
* Retrieve column information for the current database table * Retrieve column information for the current database table
@ -50,14 +45,14 @@ interface DriverInterface extends PDOInterface {
* @param string $table * @param string $table
* @return array * @return array
*/ */
public function get_columns($table); public function getColumns($table);
/** /**
* Retrieve list of data types for the database * Retrieve list of data types for the database
* *
* @return array * @return array
*/ */
public function get_types(); public function getTypes();
/** /**
* Retrieve indexes for the table * Retrieve indexes for the table
@ -65,7 +60,7 @@ interface DriverInterface extends PDOInterface {
* @param string $table * @param string $table
* @return array * @return array
*/ */
public function get_indexes($table); public function getIndexes($table);
/** /**
* Retrieve foreign keys for the table * Retrieve foreign keys for the table
@ -73,14 +68,14 @@ interface DriverInterface extends PDOInterface {
* @param string $table * @param string $table
* @return array * @return array
*/ */
public function get_fks($table); public function getFks($table);
/** /**
* Return list of tables for the current database * Return list of tables for the current database
* *
* @return array * @return array
*/ */
public function get_tables(); public function getTables();
/** /**
* Retrieves an array of non-user-created tables for * Retrieves an array of non-user-created tables for
@ -88,49 +83,49 @@ interface DriverInterface extends PDOInterface {
* *
* @return array * @return array
*/ */
public function get_system_tables(); public function getSystemTables();
/** /**
* Return list of dbs for the current connection, if possible * Return list of dbs for the current connection, if possible
* *
* @return array * @return array
*/ */
public function get_dbs(); public function getDbs();
/** /**
* Return list of views for the current database * Return list of views for the current database
* *
* @return array * @return array
*/ */
public function get_views(); public function getViews();
/** /**
* Return list of sequences for the current database, if they exist * Return list of sequences for the current database, if they exist
* *
* @return array * @return array
*/ */
public function get_sequences(); public function getSequences();
/** /**
* Return list of functions for the current database * Return list of functions for the current database
* *
* @return array * @return array
*/ */
public function get_functions(); public function getFunctions();
/** /**
* Return list of stored procedures for the current database * Return list of stored procedures for the current database
* *
* @return array * @return array
*/ */
public function get_procedures(); public function getProcedures();
/** /**
* Return list of triggers for the current database * Return list of triggers for the current database
* *
* @return array * @return array
*/ */
public function get_triggers(); public function getTriggers();
/** /**
* Surrounds the string with the databases identifier escape characters * Surrounds the string with the databases identifier escape characters
@ -138,7 +133,7 @@ interface DriverInterface extends PDOInterface {
* @param string|array $ident * @param string|array $ident
* @return string|array * @return string|array
*/ */
public function quote_ident($ident); public function quoteIdent($ident);
/** /**
* Quote database table name, and set prefix * Quote database table name, and set prefix
@ -146,7 +141,7 @@ interface DriverInterface extends PDOInterface {
* @param string|array $table * @param string|array $table
* @return string|array * @return string|array
*/ */
public function quote_table($table); public function quoteTable($table);
/** /**
* Create and execute a prepared statement with the provided parameters * Create and execute a prepared statement with the provided parameters
@ -155,7 +150,7 @@ interface DriverInterface extends PDOInterface {
* @param array $params * @param array $params
* @return \PDOStatement * @return \PDOStatement
*/ */
public function prepare_execute($sql, $params); public function prepareExecute($sql, $params);
@ -163,17 +158,17 @@ interface DriverInterface extends PDOInterface {
* Method to simplify retrieving db results for meta-data queries * Method to simplify retrieving db results for meta-data queries
* *
* @param string|array|null $query * @param string|array|null $query
* @param bool $filtered_index * @param bool $filteredIndex
* @return array * @return array
*/ */
public function driver_query($query, $filtered_index=TRUE); public function driverQuery($query, $filteredIndex=TRUE);
/** /**
* Returns number of rows affected by an INSERT, UPDATE, DELETE type query * Returns number of rows affected by an INSERT, UPDATE, DELETE type query
* *
* @return int * @return int
*/ */
public function affected_rows(); public function affectedRows();
/** /**
* Return the number of rows returned for a SELECT query * Return the number of rows returned for a SELECT query
@ -181,7 +176,7 @@ interface DriverInterface extends PDOInterface {
* *
* @return int * @return int
*/ */
public function num_rows(); public function numRows();
/** /**
* Prefixes a table if it is not already prefixed * Prefixes a table if it is not already prefixed
@ -189,7 +184,7 @@ interface DriverInterface extends PDOInterface {
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function prefix_table($table); public function prefixTable($table);
/** /**
* Create sql for batch insert * Create sql for batch insert
@ -198,7 +193,7 @@ interface DriverInterface extends PDOInterface {
* @param array $data * @param array $data
* @return array * @return array
*/ */
public function insert_batch($table, $data=[]); public function insertBatch($table, $data=[]);
/** /**
* Creates a batch update, and executes it. * Creates a batch update, and executes it.
@ -209,28 +204,27 @@ interface DriverInterface extends PDOInterface {
* @param string $where * @param string $where
* @return int|null * @return int|null
*/ */
public function update_batch($table, $data, $where); public function updateBatch($table, $data, $where);
/** /**
* Get the SQL class for the current driver * Get the SQL class for the current driver
* *
* @return \Query\Drivers\SQLInterface * @return SQLInterface
*/ */
public function get_sql(); public function getSql(): SQLInterface;
/** /**
* Get the Util class for the current driver * Get the Util class for the current driver
* *
* @return AbstractUtil * @return AbstractUtil
*/ */
public function get_util(); public function getUtil(): AbstractUtil;
/** /**
* Set the last query sql * Set the last query sql
* *
* @param string $query_string * @param string $queryString
* @return void * @return void
*/ */
public function set_last_query(string $query_string); public function setLastQuery(string $queryString);
} }
// End of driver_interface.php

View File

@ -12,21 +12,18 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query\Drivers\Firebird; namespace Query\Drivers\Firebird;
use PDO; use PDO;
use PDOException; use PDOException;
use Query\Drivers\{AbstractDriver, DriverInterface}; use Query\Drivers\AbstractDriver;
use Query\Drivers\DriverInterface;
/** /**
* Firebird Database class * Firebird Database class
* *
* PDO-firebird isn't stable, so this is a wrapper of the fbird_ public functions. * PDO-firebird isn't stable, so this is a wrapper of the fbird_ public functions.
* *
* @package Query
* @subpackage Drivers
*/ */
class Driver extends AbstractDriver implements DriverInterface { class Driver extends AbstractDriver implements DriverInterface {
@ -36,7 +33,7 @@ class Driver extends AbstractDriver implements DriverInterface {
* *
* @var resource * @var resource
*/ */
protected $statement_link = NULL; protected $statementLink = NULL;
/** /**
* Reference to the current transaction * Reference to the current transaction
@ -64,7 +61,7 @@ class Driver extends AbstractDriver implements DriverInterface {
* *
* @var boolean * @var boolean
*/ */
protected $has_truncate = FALSE; protected $hasTruncate = FALSE;
/** /**
* Open the link to the database * Open the link to the database
@ -77,11 +74,11 @@ class Driver extends AbstractDriver implements DriverInterface {
*/ */
public function __construct($dbpath, $user='SYSDBA', $pass='masterkey', array $options = []) public function __construct($dbpath, $user='SYSDBA', $pass='masterkey', array $options = [])
{ {
$connect_function = (isset($options[PDO::ATTR_PERSISTENT]) && $options[PDO::ATTR_PERSISTENT]) $connectFunction = (isset($options[PDO::ATTR_PERSISTENT]) && $options[PDO::ATTR_PERSISTENT])
? '\\fbird_pconnect' ? '\\fbird_pconnect'
: '\\fbird_connect'; : '\\fbird_connect';
$this->conn = $connect_function($dbpath, $user, $pass, 'utf-8', 0); $this->conn = $connectFunction($dbpath, $user, $pass, 'utf-8', 0);
$this->service = \fbird_service_attach('localhost', $user, $pass); $this->service = \fbird_service_attach('localhost', $user, $pass);
// Throw an exception to make this match other pdo classes // Throw an exception to make this match other pdo classes
@ -94,11 +91,9 @@ class Driver extends AbstractDriver implements DriverInterface {
// driver does not call the constructor // driver does not call the constructor
// of AbstractDriver, which defines these // of AbstractDriver, which defines these
// class variables for the other drivers // class variables for the other drivers
$this->_load_sub_classes(); $this->_loadSubClasses();
} }
// --------------------------------------------------------------------------
/** /**
* Cleanup some loose ends * Cleanup some loose ends
* @codeCoverageIgnore * @codeCoverageIgnore
@ -108,21 +103,16 @@ class Driver extends AbstractDriver implements DriverInterface {
\fbird_service_detach($this->service); \fbird_service_detach($this->service);
} }
// --------------------------------------------------------------------------
/** /**
* Return service handle * Return service handle
* *
* @return resource * @return resource
*/ */
public function get_service() public function getService()
{ {
return $this->service; return $this->service;
} }
// --------------------------------------------------------------------------
/** /**
* Execute an sql statement and return number of affected rows * Execute an sql statement and return number of affected rows
* *
@ -134,8 +124,6 @@ class Driver extends AbstractDriver implements DriverInterface {
return NULL; return NULL;
} }
// --------------------------------------------------------------------------
/** /**
* Implement for compatibility with PDO * Implement for compatibility with PDO
* *
@ -147,8 +135,6 @@ class Driver extends AbstractDriver implements DriverInterface {
return NULL; return NULL;
} }
// --------------------------------------------------------------------------
/** /**
* Return whether the current statement is in a transaction * Return whether the current statement is in a transaction
* *
@ -159,8 +145,6 @@ class Driver extends AbstractDriver implements DriverInterface {
return ! is_null($this->trans); return ! is_null($this->trans);
} }
// --------------------------------------------------------------------------
/** /**
* Returns the last value of the specified generator * Returns the last value of the specified generator
* *
@ -172,8 +156,6 @@ class Driver extends AbstractDriver implements DriverInterface {
return \fbird_gen_id($name, 0, $this->conn); return \fbird_gen_id($name, 0, $this->conn);
} }
// --------------------------------------------------------------------------
/** /**
* Wrapper public function to better match PDO * Wrapper public function to better match PDO
* *
@ -188,24 +170,22 @@ class Driver extends AbstractDriver implements DriverInterface {
throw new PDOException("Query method requires an sql query!", 0, NULL); throw new PDOException("Query method requires an sql query!", 0, NULL);
} }
$this->statement_link = (isset($this->trans)) $this->statementLink = (isset($this->trans))
? \fbird_query($this->trans, $sql) ? \fbird_query($this->trans, $sql)
: \fbird_query($this->conn, $sql); : \fbird_query($this->conn, $sql);
// Throw the error as a exception // Throw the error as a exception
$err_string = \fbird_errmsg() . "Last query:" . $this->get_last_query(); $errString = \fbird_errmsg() . "Last query:" . $this->getLastQuery();
if ($this->statement_link === FALSE) if ($this->statementLink === FALSE)
{ {
throw new PDOException($err_string, \fbird_errcode(), NULL); throw new PDOException($errString, \fbird_errcode(), NULL);
} }
$this->statement = new Result($this->statement_link, $this); $this->statement = new Result($this->statementLink, $this);
return $this->statement; return $this->statement;
} }
// --------------------------------------------------------------------------
/** /**
* Emulate PDO prepare * Emulate PDO prepare
* *
@ -216,21 +196,19 @@ class Driver extends AbstractDriver implements DriverInterface {
*/ */
public function prepare($query, $options=[]) public function prepare($query, $options=[])
{ {
$this->statement_link = \fbird_prepare($this->conn, $query); $this->statementLink = \fbird_prepare($this->conn, $query);
// Throw the error as an exception // Throw the error as an exception
if ($this->statement_link === FALSE) if ($this->statementLink === FALSE)
{ {
throw new PDOException(\fbird_errmsg(), \fbird_errcode(), NULL); throw new PDOException(\fbird_errmsg(), \fbird_errcode(), NULL);
} }
$this->statement = new Result($this->statement_link, $this); $this->statement = new Result($this->statementLink, $this);
return $this->statement; return $this->statement;
} }
// --------------------------------------------------------------------------
/** /**
* Start a database transaction * Start a database transaction
* *
@ -241,8 +219,6 @@ class Driver extends AbstractDriver implements DriverInterface {
return (($this->trans = \fbird_trans($this->conn)) !== NULL) ? TRUE : NULL; return (($this->trans = \fbird_trans($this->conn)) !== NULL) ? TRUE : NULL;
} }
// --------------------------------------------------------------------------
/** /**
* Commit a database transaction * Commit a database transaction
* *
@ -255,8 +231,6 @@ class Driver extends AbstractDriver implements DriverInterface {
return $res; return $res;
} }
// --------------------------------------------------------------------------
/** /**
* Rollback a transaction * Rollback a transaction
* *
@ -269,8 +243,6 @@ class Driver extends AbstractDriver implements DriverInterface {
return $res; return $res;
} }
// --------------------------------------------------------------------------
/** /**
* Set a connection attribute * Set a connection attribute
* @param int $attribute * @param int $attribute
@ -282,8 +254,6 @@ class Driver extends AbstractDriver implements DriverInterface {
return FALSE; return FALSE;
} }
// --------------------------------------------------------------------------
/** /**
* Prepare and execute a query * Prepare and execute a query
* *
@ -291,26 +261,24 @@ class Driver extends AbstractDriver implements DriverInterface {
* @param array $args * @param array $args
* @return Result * @return Result
*/ */
public function prepare_execute($sql, $args) public function prepareExecute($sql, $args)
{ {
$query = $this->prepare($sql); $query = $this->prepare($sql);
// Set the statement in the class variable for easy later access // Set the statement in the class variable for easy later access
$this->statement_link =& $query; $this->statementLink =& $query;
return $query->execute($args); return $query->execute($args);
} }
// --------------------------------------------------------------------------
/** /**
* Method to emulate PDO->quote * Method to emulate PDO->quote
* *
* @param string $str * @param string $str
* @param int $param_type * @param int $paramType
* @return string * @return string
*/ */
public function quote($str, $param_type = PDO::PARAM_STR) public function quote($str, $paramType = PDO::PARAM_STR)
{ {
if(is_numeric($str)) if(is_numeric($str))
{ {
@ -320,8 +288,6 @@ class Driver extends AbstractDriver implements DriverInterface {
return "'".str_replace("'", "''", $str)."'"; return "'".str_replace("'", "''", $str)."'";
} }
// --------------------------------------------------------------------------
/** /**
* Method to emulate PDO->errorInfo / PDOStatement->errorInfo * Method to emulate PDO->errorInfo / PDOStatement->errorInfo
* *
@ -335,8 +301,6 @@ class Driver extends AbstractDriver implements DriverInterface {
return [0, $code, $msg]; return [0, $code, $msg];
} }
// --------------------------------------------------------------------------
/** /**
* Method to emulate PDO->errorCode * Method to emulate PDO->errorCode
* *
@ -347,8 +311,6 @@ class Driver extends AbstractDriver implements DriverInterface {
return \fbird_errcode(); return \fbird_errcode();
} }
// --------------------------------------------------------------------------
/** /**
* Bind a prepared query with arguments for executing * Bind a prepared query with arguments for executing
* *
@ -356,15 +318,13 @@ class Driver extends AbstractDriver implements DriverInterface {
* @param array $params * @param array $params
* @return NULL * @return NULL
*/ */
public function prepare_query($sql, $params) public function prepareQuery($sql, $params)
{ {
// You can't bind query statements before execution with // You can't bind query statements before execution with
// the firebird database // the firebird database
return NULL; return NULL;
} }
// --------------------------------------------------------------------------
/** /**
* Create sql for batch insert * Create sql for batch insert
* *
@ -372,7 +332,7 @@ class Driver extends AbstractDriver implements DriverInterface {
* @param array $data * @param array $data
* @return array * @return array
*/ */
public function insert_batch($table, $data=[]) public function insertBatch($table, $data=[])
{ {
// Each member of the data array needs to be an array // Each member of the data array needs to be an array
if ( ! is_array(current($data))) if ( ! is_array(current($data)))
@ -383,11 +343,11 @@ class Driver extends AbstractDriver implements DriverInterface {
// Start the block of sql statements // Start the block of sql statements
$sql = "EXECUTE BLOCK AS BEGIN\n"; $sql = "EXECUTE BLOCK AS BEGIN\n";
$table = $this->quote_table($table); $table = $this->quoteTable($table);
$fields = \array_keys(\current($data)); $fields = \array_keys(\current($data));
$insert_template = "INSERT INTO {$table} (" $insertTemplate = "INSERT INTO {$table} ("
. implode(',', $this->quote_ident($fields)) . implode(',', $this->quoteIdent($fields))
. ") VALUES ("; . ") VALUES (";
foreach($data as $item) foreach($data as $item)
@ -396,7 +356,7 @@ class Driver extends AbstractDriver implements DriverInterface {
$vals = array_map([$this, 'quote'], $item); $vals = array_map([$this, 'quote'], $item);
// Add the values in the sql // Add the values in the sql
$sql .= $insert_template . implode(', ', $vals) . ");\n"; $sql .= $insertTemplate . implode(', ', $vals) . ");\n";
} }
// End the block of SQL statements // End the block of SQL statements
@ -408,4 +368,3 @@ class Driver extends AbstractDriver implements DriverInterface {
return [$sql, NULL]; return [$sql, NULL];
} }
} }
// End of firebird_driver.php

View File

@ -12,9 +12,6 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query\Drivers\Firebird; namespace Query\Drivers\Firebird;
use PDOStatement; use PDOStatement;
@ -90,8 +87,6 @@ class Result extends PDOStatement implements PDOStatementInterface {
} }
} }
// --------------------------------------------------------------------------
/** /**
* Invalidate method for data consistency * Invalidate method for data consistency
* *
@ -107,70 +102,62 @@ class Result extends PDOStatement implements PDOStatementInterface {
return NULL; return NULL;
} }
// --------------------------------------------------------------------------
/** /**
* Invalidate method for data consistency * Invalidate method for data consistency
* *
* @param mixed $parameter * @param mixed $parameter
* @param mixed $variable * @param mixed $variable
* @param int $data_type * @param int $dataType
* @param mixed $maxlen * @param mixed $maxlen
* @param array $driverdata * @param array $driverdata
* @return NULL * @return NULL
*/ */
public function bindParam($parameter, &$variable, $data_type=NULL, $maxlen=NULL, $driverdata=NULL) public function bindParam($parameter, &$variable, $dataType=NULL, $maxlen=NULL, $driverdata=NULL)
{ {
return NULL; return NULL;
} }
// --------------------------------------------------------------------------
/** /**
* Invalidate method for data consistency * Invalidate method for data consistency
* *
* @param mixed $parameter * @param mixed $parameter
* @param mixed $variable * @param mixed $variable
* @param int $data_type * @param int $dataType
* @return NULL * @return NULL
*/ */
public function bindValue($parameter, $variable, $data_type=NULL) public function bindValue($parameter, $variable, $dataType=NULL)
{ {
return NULL; return NULL;
} }
// --------------------------------------------------------------------------
/** /**
* Run a prepared statement query * Run a prepared statement query
* *
* @param array $bound_input_params * @param array $boundInputParams
* @return Result * @return Result
*/ */
public function execute($bound_input_params = NULL) public function execute($boundInputParams = NULL)
{ {
//Add the prepared statement as the first parameter //Add the prepared statement as the first parameter
\array_unshift($bound_input_params, $this->statement); \array_unshift($boundInputParams, $this->statement);
// Let php do all the hard stuff in converting // Let php do all the hard stuff in converting
// the array of arguments into a list of arguments // the array of arguments into a list of arguments
// Then pass the resource to the constructor // Then pass the resource to the constructor
$this->__construct(\call_user_func_array('fbird_execute', $bound_input_params)); $this->__construct(\call_user_func_array('fbird_execute', $boundInputParams));
return $this; return $this;
} }
// --------------------------------------------------------------------------
/** /**
* Emulate PDO fetch public function * Emulate PDO fetch public function
* *
* @param int $fetch_style * @param int $fetchStyle
* @param mixed $cursor_orientation * @param mixed $cursorOrientation
* @param mixed $cursor_offset * @param mixed $cursorOffset
* @return mixed * @return mixed
*/ */
public function fetch($fetch_style=\PDO::FETCH_ASSOC, $cursor_orientation = \PDO::FETCH_ORI_NEXT, $cursor_offset=NULL) public function fetch($fetchStyle=\PDO::FETCH_ASSOC, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset=NULL)
{ {
// If there is no result, continue // If there is no result, continue
if (empty($this->result)) if (empty($this->result))
@ -187,7 +174,7 @@ class Result extends PDOStatement implements PDOStatementInterface {
return NULL; return NULL;
} }
switch($fetch_style) switch($fetchStyle)
{ {
case \PDO::FETCH_OBJ: case \PDO::FETCH_OBJ:
$row = (object) $this->result[$this->row]; $row = (object) $this->result[$this->row];
@ -205,21 +192,19 @@ class Result extends PDOStatement implements PDOStatementInterface {
return $row; return $row;
} }
// --------------------------------------------------------------------------
/** /**
* Emulate PDO fetchAll public function * Emulate PDO fetchAll public function
* *
* @param int $fetch_style * @param int $fetchStyle
* @param mixed $statement * @param mixed $statement
* @param mixed $ctor_args * @param mixed $ctorArgs
* @return mixed * @return mixed
*/ */
public function fetchAll($fetch_style=\PDO::FETCH_ASSOC, $statement=NULL, $ctor_args=NULL) public function fetchAll($fetchStyle=\PDO::FETCH_ASSOC, $statement=NULL, $ctorArgs=NULL)
{ {
$all = []; $all = [];
while($row = $this->fetch($fetch_style, $statement)) while($row = $this->fetch($fetchStyle, $statement))
{ {
$all[] = $row; $all[] = $row;
} }
@ -229,36 +214,30 @@ class Result extends PDOStatement implements PDOStatementInterface {
return $all; return $all;
} }
// --------------------------------------------------------------------------
/** /**
* Emulate PDOStatement::fetchColumn * Emulate PDOStatement::fetchColumn
* *
* @param int $column_num * @param int $columnNum
* @return mixed * @return mixed
*/ */
public function fetchColumn($column_num=0) public function fetchColumn($columnNum=0)
{ {
$row = $this->fetch(\PDO::FETCH_NUM); $row = $this->fetch(\PDO::FETCH_NUM);
return $row[$column_num]; return $row[$columnNum];
} }
// --------------------------------------------------------------------------
/** /**
* Emulate PDOStatement::fetchObject, but only for the default use * Emulate PDOStatement::fetchObject, but only for the default use
* *
* @param string $class_name * @param string $className
* @param array|null $ctor_args * @param array|null $ctorArgs
* @return object * @return object
*/ */
public function fetchObject($class_name='stdClass', $ctor_args=NULL) public function fetchObject($className='stdClass', $ctorArgs=NULL)
{ {
return $this->fetch(\PDO::FETCH_OBJ); return $this->fetch(\PDO::FETCH_OBJ);
} }
// --------------------------------------------------------------------------
/** /**
* Return the number of rows affected by the previous query * Return the number of rows affected by the previous query
* *
@ -269,8 +248,6 @@ class Result extends PDOStatement implements PDOStatementInterface {
return \fbird_affected_rows(); return \fbird_affected_rows();
} }
// --------------------------------------------------------------------------
/** /**
* Method to emulate PDOStatement->errorCode * Method to emulate PDOStatement->errorCode
* *
@ -281,8 +258,6 @@ class Result extends PDOStatement implements PDOStatementInterface {
return $this->db->errorCode(); return $this->db->errorCode();
} }
// --------------------------------------------------------------------------
/** /**
* Method to emulate PDO->errorInfo / PDOStatement->errorInfo * Method to emulate PDO->errorInfo / PDOStatement->errorInfo
* *
@ -293,4 +268,3 @@ class Result extends PDOStatement implements PDOStatementInterface {
return $this->db->errorInfo(); return $this->db->errorInfo();
} }
} }
// End of firebird_result.php

View File

@ -12,18 +12,12 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query\Drivers\Firebird; namespace Query\Drivers\Firebird;
use Query\Drivers\AbstractSQL; use Query\Drivers\AbstractSQL;
/** /**
* Firebird Specific SQL * Firebird Specific SQL
*
* @package Query
* @subpackage Drivers
*/ */
class SQL extends AbstractSQL { class SQL extends AbstractSQL {
@ -38,7 +32,7 @@ class SQL extends AbstractSQL {
public function limit($sql, $limit, $offset=FALSE) public function limit($sql, $limit, $offset=FALSE)
{ {
// Keep the current sql string safe for a moment // Keep the current sql string safe for a moment
$orig_sql = $sql; $origSql = $sql;
$sql = 'FIRST '. (int) $limit; $sql = 'FIRST '. (int) $limit;
@ -47,13 +41,11 @@ class SQL extends AbstractSQL {
$sql .= ' SKIP '. (int) $offset; $sql .= ' SKIP '. (int) $offset;
} }
$sql = preg_replace("`SELECT`i", "SELECT {$sql}", $orig_sql); $sql = preg_replace("`SELECT`i", "SELECT {$sql}", $origSql);
return $sql; return $sql;
} }
// --------------------------------------------------------------------------
/** /**
* Get the query plan for the sql query * Get the query plan for the sql query
* *
@ -65,8 +57,6 @@ class SQL extends AbstractSQL {
return $sql; return $sql;
} }
// --------------------------------------------------------------------------
/** /**
* Random ordering keyword * Random ordering keyword
* *
@ -77,27 +67,22 @@ class SQL extends AbstractSQL {
return NULL; return NULL;
} }
// --------------------------------------------------------------------------
/** /**
* Returns sql to list other databases * Returns sql to list other databases
* *
* @return NULL * @return NULL
*/ */
public function db_list() public function dbList()
{ {
return NULL; return NULL;
} }
// --------------------------------------------------------------------------
/** /**
* Returns sql to list tables * Returns sql to list tables
* *
* @return string * @return string
*/ */
public function table_list() public function tableList()
{ {
return <<<SQL return <<<SQL
SELECT TRIM("RDB\$RELATION_NAME") SELECT TRIM("RDB\$RELATION_NAME")
@ -108,14 +93,12 @@ class SQL extends AbstractSQL {
SQL; SQL;
} }
// --------------------------------------------------------------------------
/** /**
* Returns sql to list system tables * Returns sql to list system tables
* *
* @return string * @return string
*/ */
public function system_table_list() public function systemTableList()
{ {
return <<<SQL return <<<SQL
SELECT TRIM("RDB\$RELATION_NAME") SELECT TRIM("RDB\$RELATION_NAME")
@ -125,14 +108,12 @@ SQL;
SQL; SQL;
} }
// --------------------------------------------------------------------------
/** /**
* Returns sql to list views * Returns sql to list views
* *
* @return string * @return string
*/ */
public function view_list() public function viewList()
{ {
return <<<SQL return <<<SQL
SELECT DISTINCT TRIM("RDB\$VIEW_NAME") SELECT DISTINCT TRIM("RDB\$VIEW_NAME")
@ -140,14 +121,12 @@ SQL;
SQL; SQL;
} }
// --------------------------------------------------------------------------
/** /**
* Returns sql to list triggers * Returns sql to list triggers
* *
* @return string * @return string
*/ */
public function trigger_list() public function triggerList()
{ {
return <<<SQL return <<<SQL
SELECT * FROM "RDB\$FUNCTIONS" SELECT * FROM "RDB\$FUNCTIONS"
@ -155,26 +134,22 @@ SQL;
SQL; SQL;
} }
// --------------------------------------------------------------------------
/** /**
* Return sql to list functions * Return sql to list functions
* *
* @return string * @return string
*/ */
public function function_list() public function functionList()
{ {
return 'SELECT * FROM "RDB$FUNCTIONS"'; return 'SELECT * FROM "RDB$FUNCTIONS"';
} }
// --------------------------------------------------------------------------
/** /**
* Return sql to list stored procedures * Return sql to list stored procedures
* *
* @return string * @return string
*/ */
public function procedure_list() public function procedureList()
{ {
return <<<SQL return <<<SQL
SELECT "RDB\$PROCEDURE_NAME", SELECT "RDB\$PROCEDURE_NAME",
@ -195,14 +170,12 @@ SQL;
} }
// --------------------------------------------------------------------------
/** /**
* Return sql to list sequences * Return sql to list sequences
* *
* @return string * @return string
*/ */
public function sequence_list() public function sequenceList()
{ {
return <<<SQL return <<<SQL
SELECT TRIM("RDB\$GENERATOR_NAME") SELECT TRIM("RDB\$GENERATOR_NAME")
@ -211,15 +184,13 @@ SQL;
SQL; SQL;
} }
// --------------------------------------------------------------------------
/** /**
* Return sql to list columns of the specified table * Return sql to list columns of the specified table
* *
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function column_list($table) public function columnList($table)
{ {
return <<<SQL return <<<SQL
SELECT r.RDB\$FIELD_NAME AS field_name, SELECT r.RDB\$FIELD_NAME AS field_name,
@ -258,14 +229,12 @@ SQL;
SQL; SQL;
} }
// --------------------------------------------------------------------------
/** /**
* SQL to show list of field types * SQL to show list of field types
* *
* @return string * @return string
*/ */
public function type_list() public function typeList()
{ {
return <<<SQL return <<<SQL
SELECT "RDB\$TYPE_NAME", "RDB\$FIELD_NAME" FROM "RDB\$TYPES" SELECT "RDB\$TYPE_NAME", "RDB\$FIELD_NAME" FROM "RDB\$TYPES"
@ -274,8 +243,6 @@ SQL;
SQL; SQL;
} }
// --------------------------------------------------------------------------
/** /**
* Get the list of foreign keys for the current * Get the list of foreign keys for the current
* table * table
@ -283,7 +250,7 @@ SQL;
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function fk_list($table) public function fkList($table)
{ {
return <<<SQL return <<<SQL
SELECT DISTINCT SELECT DISTINCT
@ -303,15 +270,13 @@ SQL;
SQL; SQL;
} }
// --------------------------------------------------------------------------
/** /**
* Get the list of indexes for the current table * Get the list of indexes for the current table
* *
* @param string $table * @param string $table
* @return array * @return array
*/ */
public function index_list($table) public function indexList($table)
{ {
return <<<SQL return <<<SQL
SELECT "RDB\$INDEX_NAME", "RDB\$UNIQUE_FLAG", "RDB\$FOREIGN_KEY" SELECT "RDB\$INDEX_NAME", "RDB\$UNIQUE_FLAG", "RDB\$FOREIGN_KEY"
@ -320,4 +285,3 @@ SQL;
SQL; SQL;
} }
} }
//End of firebird_sql.php

View File

@ -12,17 +12,13 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query\Drivers\Firebird; namespace Query\Drivers\Firebird;
use PDO;
use Query\Drivers\AbstractUtil; use Query\Drivers\AbstractUtil;
/** /**
* Firebird-specific backup, import and creation methods * Firebird-specific backup, import and creation methods
*
* @package Query
* @subpackage Drivers
*/ */
class Util extends AbstractUtil { class Util extends AbstractUtil {
@ -32,12 +28,12 @@ class Util extends AbstractUtil {
* @param string $name * @param string $name
* @param array $fields * @param array $fields
* @param array $constraints * @param array $constraints
* @param bool $if_not_exists * @param bool $ifNotExists
* @return string * @return string
*/ */
public function create_table($name, $fields, array $constraints=[], $if_not_exists=FALSE) public function createTable($name, $fields, array $constraints=[], $ifNotExists=FALSE)
{ {
return parent::create_table($name, $fields, $constraints, FALSE); return parent::createTable($name, $fields, $constraints, FALSE);
} }
/** /**
@ -46,40 +42,36 @@ class Util extends AbstractUtil {
* @param string $name * @param string $name
* @return string * @return string
*/ */
public function delete_table($name) public function deleteTable($name)
{ {
return 'DROP TABLE '.$this->get_driver()->quote_table($name); return 'DROP TABLE '.$this->getDriver()->quoteTable($name);
} }
// --------------------------------------------------------------------------
/** /**
* Create an SQL backup file for the current database's structure * Create an SQL backup file for the current database's structure
* *
* @return string * @return string
*/ */
public function backup_structure(/* @param string $db_path, @param string $new_file */) public function backupStructure(/* @param string $dbPath, @param string $newFile */)
{ {
list($db_path, $new_file) = func_get_args(); list($dbPath, $newFile) = func_get_args();
return ibase_backup($this->get_driver()->get_service(), $db_path, $new_file, \IBASE_BKP_METADATA_ONLY); return ibase_backup($this->getDriver()->getService(), $dbPath, $newFile, \IBASE_BKP_METADATA_ONLY);
} }
// --------------------------------------------------------------------------
/** /**
* Create an SQL backup file for the current database's data * Create an SQL backup file for the current database's data
* *
* @param array $exclude * @param array $exclude
* @param bool $system_tables * @param bool $systemTables
* @return string * @return string
*/ */
public function backup_data($exclude=[], $system_tables=FALSE) public function backupData($exclude=[], $systemTables=FALSE)
{ {
// Determine which tables to use // Determine which tables to use
$tables = $this->get_driver()->get_tables(); $tables = $this->getDriver()->getTables();
if($system_tables == TRUE) if($systemTables == TRUE)
{ {
$tables = array_merge($tables, $this->get_driver()->get_system_tables()); $tables = array_merge($tables, $this->getDriver()->getSystemTables());
} }
// Filter out the tables you don't want // Filter out the tables you don't want
@ -88,49 +80,48 @@ class Util extends AbstractUtil {
$tables = array_diff($tables, $exclude); $tables = array_diff($tables, $exclude);
} }
$output_sql = ''; $outputSql = '';
// Get the data for each object // Get the data for each object
foreach($tables as $t) foreach($tables as $t)
{ {
$sql = 'SELECT * FROM "'.trim($t).'"'; $sql = 'SELECT * FROM "'.trim($t).'"';
$res = $this->get_driver()->query($sql); $res = $this->getDriver()->query($sql);
$obj_res = $res->fetchAll(\PDO::FETCH_ASSOC); $objRes = $res->fetchAll(PDO::FETCH_ASSOC);
// Don't add to the file if the table is empty // Don't add to the file if the table is empty
if (count($obj_res) < 1) if (count($objRes) < 1)
{ {
continue; continue;
} }
// Nab the column names by getting the keys of the first row // Nab the column names by getting the keys of the first row
$columns = @array_keys($obj_res[0]); $columns = @array_keys($objRes[0]);
$insert_rows = []; $insertRows = [];
// Create the insert statements // Create the insert statements
foreach($obj_res as $row) foreach($objRes as $row)
{ {
$row = array_values($row); $row = array_values($row);
// Quote values as needed by type // Quote values as needed by type
if(stripos($t, 'RDB$') === FALSE) if(stripos($t, 'RDB$') === FALSE)
{ {
$row = array_map([$this->get_driver(), 'quote'], $row); $row = array_map([$this->getDriver(), 'quote'], $row);
$row = array_map('trim', $row); $row = array_map('trim', $row);
} }
$row_string = 'INSERT INTO "'.trim($t).'" ("'.implode('","', $columns).'") VALUES ('.implode(',', $row).');'; $rowString = 'INSERT INTO "'.trim($t).'" ("'.implode('","', $columns).'") VALUES ('.implode(',', $row).');';
$row = NULL; $row = NULL;
$insert_rows[] = $row_string; $insertRows[] = $rowString;
} }
$output_sql .= "\n\nSET TRANSACTION;\n".implode("\n", $insert_rows)."\nCOMMIT;"; $outputSql .= "\n\nSET TRANSACTION;\n".implode("\n", $insertRows)."\nCOMMIT;";
} }
return $output_sql; return $outputSql;
} }
} }
// End of firebird_util.php

View File

@ -12,18 +12,14 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query\Drivers\Mysql; namespace Query\Drivers\Mysql;
use Query\Drivers\{AbstractDriver, DriverInterface}; use PDO;
use Query\Drivers\AbstractDriver;
use Query\Drivers\DriverInterface;
/** /**
* MySQL specific class * MySQL specific class
*
* @package Query
* @subpackage Drivers
*/ */
class Driver extends AbstractDriver implements DriverInterface { class Driver extends AbstractDriver implements DriverInterface {
@ -32,14 +28,14 @@ class Driver extends AbstractDriver implements DriverInterface {
* *
* @var string * @var string
*/ */
protected $escape_char_open = '`'; protected $escapeCharOpen = '`';
/** /**
* Set the backtick as the MySQL escape character * Set the backtick as the MySQL escape character
* *
* @var string * @var string
*/ */
protected $escape_char_close = '`'; protected $escapeCharClose = '`';
/** /**
* Connect to MySQL Database * Connect to MySQL Database
@ -56,7 +52,7 @@ class Driver extends AbstractDriver implements DriverInterface {
if (defined('\\PDO::MYSQL_ATTR_INIT_COMMAND')) if (defined('\\PDO::MYSQL_ATTR_INIT_COMMAND'))
{ {
$options = array_merge($options, [ $options = array_merge($options, [
\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES UTF-8 COLLATE 'UTF-8'", PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES UTF-8 COLLATE 'UTF-8'",
]); ]);
} }
@ -68,4 +64,3 @@ class Driver extends AbstractDriver implements DriverInterface {
parent::__construct($dsn, $username, $password, $options); parent::__construct($dsn, $username, $password, $options);
} }
} }
//End of mysql_driver.php

View File

@ -12,18 +12,12 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query\Drivers\Mysql; namespace Query\Drivers\Mysql;
use Query\Drivers\AbstractSQL; use Query\Drivers\AbstractSQL;
/** /**
* MySQL specific SQL * MySQL specific SQL
*
* @package Query
* @subpackage Drivers
*/ */
class SQL extends AbstractSQL { class SQL extends AbstractSQL {
@ -45,8 +39,6 @@ class SQL extends AbstractSQL {
return $sql." LIMIT {$offset}, {$limit}"; return $sql." LIMIT {$offset}, {$limit}";
} }
// --------------------------------------------------------------------------
/** /**
* Get the query plan for the sql query * Get the query plan for the sql query
* *
@ -58,8 +50,6 @@ class SQL extends AbstractSQL {
return "EXPLAIN EXTENDED {$sql}"; return "EXPLAIN EXTENDED {$sql}";
} }
// --------------------------------------------------------------------------
/** /**
* Random ordering keyword * Random ordering keyword
* *
@ -70,27 +60,23 @@ class SQL extends AbstractSQL {
return ' RAND() DESC'; return ' RAND() DESC';
} }
// --------------------------------------------------------------------------
/** /**
* Returns sql to list other databases * Returns sql to list other databases
* *
* @return string * @return string
*/ */
public function db_list() public function dbList()
{ {
return "SHOW DATABASES WHERE `Database` NOT IN ('information_schema','mysql')"; return "SHOW DATABASES WHERE `Database` NOT IN ('information_schema','mysql')";
} }
// --------------------------------------------------------------------------
/** /**
* Returns sql to list tables * Returns sql to list tables
* *
* @param string $database * @param string $database
* @return string * @return string
*/ */
public function table_list($database='') public function tableList($database='')
{ {
if ( ! empty($database)) if ( ! empty($database))
{ {
@ -100,106 +86,88 @@ class SQL extends AbstractSQL {
return 'SHOW TABLES'; return 'SHOW TABLES';
} }
// --------------------------------------------------------------------------
/** /**
* Overridden in MySQL class * Overridden in MySQL class
* *
* @return string * @return string
*/ */
public function system_table_list() public function systemTableList()
{ {
return 'SELECT `TABLE_NAME` FROM `information_schema`.`TABLES` return 'SELECT `TABLE_NAME` FROM `information_schema`.`TABLES`
WHERE `TABLE_SCHEMA`=\'information_schema\''; WHERE `TABLE_SCHEMA`=\'information_schema\'';
} }
// --------------------------------------------------------------------------
/** /**
* Returns sql to list views * Returns sql to list views
* *
* @return string * @return string
*/ */
public function view_list() public function viewList()
{ {
return 'SELECT `table_name` FROM `information_schema`.`views`'; return 'SELECT `table_name` FROM `information_schema`.`views`';
} }
// --------------------------------------------------------------------------
/** /**
* Returns sql to list triggers * Returns sql to list triggers
* *
* @return string * @return string
*/ */
public function trigger_list() public function triggerList()
{ {
return 'SHOW TRIGGERS'; return 'SHOW TRIGGERS';
} }
// --------------------------------------------------------------------------
/** /**
* Return sql to list functions * Return sql to list functions
* *
* @return string * @return string
*/ */
public function function_list() public function functionList()
{ {
return 'SHOW FUNCTION STATUS'; return 'SHOW FUNCTION STATUS';
} }
// --------------------------------------------------------------------------
/** /**
* Return sql to list stored procedures * Return sql to list stored procedures
* *
* @return string * @return string
*/ */
public function procedure_list() public function procedureList()
{ {
return 'SHOW PROCEDURE STATUS'; return 'SHOW PROCEDURE STATUS';
} }
// --------------------------------------------------------------------------
/** /**
* Return sql to list sequences * Return sql to list sequences
* *
* @return NULL * @return NULL
*/ */
public function sequence_list() public function sequenceList()
{ {
return NULL; return NULL;
} }
// --------------------------------------------------------------------------
/** /**
* SQL to show list of field types * SQL to show list of field types
* *
* @return string * @return string
*/ */
public function type_list() public function typeList()
{ {
return "SELECT DISTINCT `DATA_TYPE` FROM `information_schema`.`COLUMNS`"; return "SELECT DISTINCT `DATA_TYPE` FROM `information_schema`.`COLUMNS`";
} }
// --------------------------------------------------------------------------
/** /**
* SQL to show infromation about columns in a table * SQL to show infromation about columns in a table
* *
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function column_list($table) public function columnList($table)
{ {
return "SHOW FULL COLUMNS FROM {$table}"; return "SHOW FULL COLUMNS FROM {$table}";
} }
// --------------------------------------------------------------------------
/** /**
* Get the list of foreign keys for the current * Get the list of foreign keys for the current
* table * table
@ -207,7 +175,7 @@ class SQL extends AbstractSQL {
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function fk_list($table) public function fkList($table)
{ {
return <<<SQL return <<<SQL
SELECT DISTINCT `kcu`.`COLUMN_NAME` as `child_column`, SELECT DISTINCT `kcu`.`COLUMN_NAME` as `child_column`,
@ -225,17 +193,14 @@ class SQL extends AbstractSQL {
SQL; SQL;
} }
// --------------------------------------------------------------------------
/** /**
* Get the list of indexes for the current table * Get the list of indexes for the current table
* *
* @param string $table * @param string $table
* @return array * @return array
*/ */
public function index_list($table) public function indexList($table)
{ {
return "SHOW INDEX IN {$table}"; return "SHOW INDEX IN {$table}";
} }
} }
//End of mysql_sql.php

View File

@ -12,18 +12,13 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query\Drivers\Mysql; namespace Query\Drivers\Mysql;
use PDO;
use Query\Drivers\AbstractUtil; use Query\Drivers\AbstractUtil;
/** /**
* MySQL-specific backup, import and creation methods * MySQL-specific backup, import and creation methods
*
* @package Query
* @subpackage Drivers
*/ */
class Util extends AbstractUtil { class Util extends AbstractUtil {
@ -32,12 +27,12 @@ class Util extends AbstractUtil {
* *
* @return string * @return string
*/ */
public function backup_structure() public function backupStructure()
{ {
$string = []; $string = [];
// Get databases // Get databases
$dbs = $this->get_driver()->get_dbs(); $dbs = $this->getDriver()->getDbs();
foreach($dbs as &$d) foreach($dbs as &$d)
{ {
@ -48,11 +43,11 @@ class Util extends AbstractUtil {
} }
// Get the list of tables // Get the list of tables
$tables = $this->get_driver()->driver_query("SHOW TABLES FROM `{$d}`", TRUE); $tables = $this->getDriver()->driverQuery("SHOW TABLES FROM `{$d}`", TRUE);
foreach($tables as $table) foreach($tables as $table)
{ {
$array = $this->get_driver()->driver_query("SHOW CREATE TABLE `{$d}`.`{$table}`", FALSE); $array = $this->getDriver()->driverQuery("SHOW CREATE TABLE `{$d}`.`{$table}`", FALSE);
$row = current($array); $row = current($array);
if ( ! isset($row['Create Table'])) if ( ! isset($row['Create Table']))
@ -68,17 +63,15 @@ class Util extends AbstractUtil {
return implode("\n\n", $string); return implode("\n\n", $string);
} }
// --------------------------------------------------------------------------
/** /**
* Create an SQL backup file for the current database's data * Create an SQL backup file for the current database's data
* *
* @param array $exclude * @param array $exclude
* @return string * @return string
*/ */
public function backup_data($exclude=[]) public function backupData($exclude=[])
{ {
$tables = $this->get_driver()->get_tables(); $tables = $this->getDriver()->getTables();
// Filter out the tables you don't want // Filter out the tables you don't want
if( ! empty($exclude)) if( ! empty($exclude))
@ -86,14 +79,14 @@ class Util extends AbstractUtil {
$tables = array_diff($tables, $exclude); $tables = array_diff($tables, $exclude);
} }
$output_sql = ''; $outputSql = '';
// Select the rows from each Table // Select the rows from each Table
foreach($tables as $t) foreach($tables as $t)
{ {
$sql = "SELECT * FROM `{$t}`"; $sql = "SELECT * FROM `{$t}`";
$res = $this->get_driver()->query($sql); $res = $this->getDriver()->query($sql);
$rows = $res->fetchAll(\PDO::FETCH_ASSOC); $rows = $res->fetchAll(PDO::FETCH_ASSOC);
// Skip empty tables // Skip empty tables
if (count($rows) < 1) if (count($rows) < 1)
@ -104,7 +97,7 @@ class Util extends AbstractUtil {
// Nab the column names by getting the keys of the first row // Nab the column names by getting the keys of the first row
$columns = @array_keys($rows[0]); $columns = @array_keys($rows[0]);
$insert_rows = []; $insertRows = [];
// Create the insert statements // Create the insert statements
foreach($rows as $row) foreach($rows as $row)
@ -114,21 +107,20 @@ class Util extends AbstractUtil {
// Workaround for Quercus // Workaround for Quercus
foreach($row as &$r) foreach($row as &$r)
{ {
$r = $this->get_driver()->quote($r); $r = $this->getDriver()->quote($r);
} }
$row = array_map('trim', $row); $row = array_map('trim', $row);
$row_string = 'INSERT INTO `'.trim($t).'` (`'.implode('`,`', $columns).'`) VALUES ('.implode(',', $row).');'; $rowString = 'INSERT INTO `'.trim($t).'` (`'.implode('`,`', $columns).'`) VALUES ('.implode(',', $row).');';
$row = NULL; $row = NULL;
$insert_rows[] = $row_string; $insertRows[] = $rowString;
} }
$output_sql .= "\n\n".implode("\n", $insert_rows)."\n"; $outputSql .= "\n\n".implode("\n", $insertRows)."\n";
} }
return $output_sql; return $outputSql;
} }
} }
// End of mysql_util.php

View File

@ -12,8 +12,6 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query\Drivers; namespace Query\Drivers;
use PDO; use PDO;
@ -22,9 +20,6 @@ use PDOStatement;
/** /**
* Interface describing the PDO class in PHP * Interface describing the PDO class in PHP
*
* @package Query
* @subpackage Drivers
*/ */
interface PDOInterface { interface PDOInterface {
@ -127,10 +122,10 @@ interface PDOInterface {
* Quotes a string for use in a query * Quotes a string for use in a query
* *
* @param string $string * @param string $string
* @param int $parameter_type * @param int $parameterType
* @return string|false * @return string|false
*/ */
public function quote($string, $parameter_type = PDO::PARAM_STR); public function quote($string, $parameterType = PDO::PARAM_STR);
/** /**
* Rolls back a transaction * Rolls back a transaction

View File

@ -13,8 +13,6 @@
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query\Drivers; namespace Query\Drivers;
use PDO; use PDO;
@ -43,15 +41,15 @@ interface PDOStatementInterface {
* parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the * parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the
* 1-indexed position of the parameter. * 1-indexed position of the parameter.
* @param mixed $variable Name of the PHP variable to bind to the SQL statement parameter. * @param mixed $variable Name of the PHP variable to bind to the SQL statement parameter.
* @param int $data_type Explicit data type for the parameter using the PDO::PARAM_* constants. To return an INOUT * @param int $dataType Explicit data type for the parameter using the PDO::PARAM_* constants. To return an INOUT
* parameter from a stored procedure, use the bitwise OR operator to set the PDO::PARAM_INPUT_OUTPUT bits * parameter from a stored procedure, use the bitwise OR operator to set the PDO::PARAM_INPUT_OUTPUT bits
* for the data_type parameter. * for the data_type parameter.
* @param int $length Length of the data type. To indicate that a parameter is an OUT parameter from a stored procedure, * @param int $length Length of the data type. To indicate that a parameter is an OUT parameter from a stored procedure,
* you must explicitly set the length. * you must explicitly set the length.
* @param mixed $driver_options * @param mixed $driverOptions
* @return boolean * @return boolean
*/ */
public function bindParam($parameter, &$variable, $data_type = PDO::PARAM_STR, $length, $driver_options); public function bindParam($parameter, &$variable, $dataType = PDO::PARAM_STR, $length, $driverOptions);
/** /**
* Binds a value to a corresponding named or question mark placeholder in the SQL statement that was used to * Binds a value to a corresponding named or question mark placeholder in the SQL statement that was used to
@ -61,10 +59,10 @@ interface PDOStatementInterface {
* parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the * parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the
* 1-indexed position of the parameter. * 1-indexed position of the parameter.
* @param mixed $value The value to bind to the parameter * @param mixed $value The value to bind to the parameter
* @param int $data_type Explicit data type for the parameter using the PDO::PARAM_* constants. * @param int $dataType Explicit data type for the parameter using the PDO::PARAM_* constants.
* @return boolean * @return boolean
*/ */
public function bindValue($parameter, $value, $data_type = PDO::PARAM_STR); public function bindValue($parameter, $value, $dataType = PDO::PARAM_STR);
/** /**
* Frees up the connection to the server so that other SQL statements may be issued, but leaves the statement in a * Frees up the connection to the server so that other SQL statements may be issued, but leaves the statement in a
@ -105,10 +103,10 @@ interface PDOStatementInterface {
/** /**
* Run a prepared statement query * Run a prepared statement query
* *
* @param array $bound_input_params * @param array $boundInputParams
* @return boolean * @return boolean
*/ */
public function execute($bound_input_params = NULL); public function execute($boundInputParams = NULL);
/** /**
* Fetches the next row from a result set * Fetches the next row from a result set
@ -123,19 +121,19 @@ interface PDOStatementInterface {
/** /**
* Returns a single column from the next row of a result set * Returns a single column from the next row of a result set
* *
* @param int $column_number * @param int $columnNumber
* @return mixed * @return mixed
*/ */
public function fetchColumn($column_number = 0); public function fetchColumn($columnNumber = 0);
/** /**
* Fetches the next row and returns it as an object * Fetches the next row and returns it as an object
* *
* @param string $class_name * @param string $className
* @param array $ctor_args * @param array $ctorArgs
* @return mixed * @return mixed
*/ */
public function fetchObject($class_name = "stdClass", $ctor_args = NULL); public function fetchObject($className = "stdClass", $ctorArgs = NULL);
/** /**
* Retrieve a statement attribute * Retrieve a statement attribute

View File

@ -12,17 +12,13 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query\Drivers\Pgsql; namespace Query\Drivers\Pgsql;
use Query\Drivers\{AbstractDriver, DriverInterface}; use Query\Drivers\AbstractDriver;
use Query\Drivers\DriverInterface;
/** /**
* PostgreSQL specific class * PostgreSQL specific class
*
* @package Query
* @subpackage Drivers
*/ */
class Driver extends AbstractDriver implements DriverInterface { class Driver extends AbstractDriver implements DriverInterface {
@ -52,7 +48,7 @@ class Driver extends AbstractDriver implements DriverInterface {
* *
* @return array * @return array
*/ */
public function get_schemas() public function getSchemas()
{ {
$sql = <<<SQL $sql = <<<SQL
SELECT DISTINCT "schemaname" FROM "pg_tables" SELECT DISTINCT "schemaname" FROM "pg_tables"
@ -60,7 +56,7 @@ class Driver extends AbstractDriver implements DriverInterface {
AND "schemaname" != 'information_schema' AND "schemaname" != 'information_schema'
SQL; SQL;
return $this->driver_query($sql); return $this->driverQuery($sql);
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -71,29 +67,28 @@ SQL;
* @param string $table * @param string $table
* @return array * @return array
*/ */
public function get_fks($table) public function getFks($table)
{ {
$value_map = [ $valueMap = [
'c' => 'CASCADE', 'c' => 'CASCADE',
'r' => 'RESTRICT', 'r' => 'RESTRICT',
]; ];
$keys = parent::get_fks($table); $keys = parent::getFks($table);
foreach($keys as &$key) foreach($keys as &$key)
{ {
foreach(['update', 'delete'] AS $type) foreach(['update', 'delete'] AS $type)
{ {
if ( ! isset($value_map[$key[$type]])) if ( ! isset($valueMap[$key[$type]]))
{ {
continue; continue;
} }
$key[$type] = $value_map[$key[$type]]; $key[$type] = $valueMap[$key[$type]];
} }
} }
return $keys; return $keys;
} }
} }
//End of pgsql_driver.php

View File

@ -12,18 +12,12 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query\Drivers\Pgsql; namespace Query\Drivers\Pgsql;
use Query\Drivers\AbstractSQL; use Query\Drivers\AbstractSQL;
/** /**
* PostgreSQL specific SQL * PostgreSQL specific SQL
*
* @package Query
* @subpackage Drivers
*/ */
class SQL extends AbstractSQL { class SQL extends AbstractSQL {
@ -38,8 +32,6 @@ class SQL extends AbstractSQL {
return "EXPLAIN VERBOSE {$sql}"; return "EXPLAIN VERBOSE {$sql}";
} }
// --------------------------------------------------------------------------
/** /**
* Random ordering keyword * Random ordering keyword
* *
@ -50,14 +42,12 @@ class SQL extends AbstractSQL {
return ' RANDOM()'; return ' RANDOM()';
} }
// --------------------------------------------------------------------------
/** /**
* Returns sql to list other databases * Returns sql to list other databases
* *
* @return string * @return string
*/ */
public function db_list() public function dbList()
{ {
return <<<SQL return <<<SQL
SELECT "datname" FROM "pg_database" SELECT "datname" FROM "pg_database"
@ -66,14 +56,12 @@ class SQL extends AbstractSQL {
SQL; SQL;
} }
// --------------------------------------------------------------------------
/** /**
* Returns sql to list tables * Returns sql to list tables
* *
* @return string * @return string
*/ */
public function table_list() public function tableList()
{ {
return <<<SQL return <<<SQL
SELECT "table_name" SELECT "table_name"
@ -84,14 +72,12 @@ SQL;
SQL; SQL;
} }
// --------------------------------------------------------------------------
/** /**
* Returns sql to list system tables * Returns sql to list system tables
* *
* @return string * @return string
*/ */
public function system_table_list() public function systemTableList()
{ {
return <<<SQL return <<<SQL
SELECT "table_name" SELECT "table_name"
@ -102,14 +88,12 @@ SQL;
SQL; SQL;
} }
// --------------------------------------------------------------------------
/** /**
* Returns sql to list views * Returns sql to list views
* *
* @return string * @return string
*/ */
public function view_list() public function viewList()
{ {
return <<<SQL return <<<SQL
SELECT "viewname" FROM "pg_views" SELECT "viewname" FROM "pg_views"
@ -120,14 +104,12 @@ SQL;
SQL; SQL;
} }
// --------------------------------------------------------------------------
/** /**
* Returns sql to list triggers * Returns sql to list triggers
* *
* @return string * @return string
*/ */
public function trigger_list() public function triggerList()
{ {
return <<<SQL return <<<SQL
SELECT * SELECT *
@ -137,26 +119,22 @@ SQL;
SQL; SQL;
} }
// --------------------------------------------------------------------------
/** /**
* Return sql to list functions * Return sql to list functions
* *
* @return NULL * @return NULL
*/ */
public function function_list() public function functionList()
{ {
return NULL; return NULL;
} }
// --------------------------------------------------------------------------
/** /**
* Return sql to list stored procedures * Return sql to list stored procedures
* *
* @return string * @return string
*/ */
public function procedure_list() public function procedureList()
{ {
return <<<SQL return <<<SQL
SELECT "routine_name" SELECT "routine_name"
@ -167,14 +145,12 @@ SQL;
SQL; SQL;
} }
// --------------------------------------------------------------------------
/** /**
* Return sql to list sequences * Return sql to list sequences
* *
* @return string * @return string
*/ */
public function sequence_list() public function sequenceList()
{ {
return <<<SQL return <<<SQL
SELECT "c"."relname" SELECT "c"."relname"
@ -184,15 +160,13 @@ SQL;
SQL; SQL;
} }
// --------------------------------------------------------------------------
/** /**
* Return sql to list columns of the specified table * Return sql to list columns of the specified table
* *
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function column_list($table) public function columnList($table)
{ {
return <<<SQL return <<<SQL
SELECT ordinal_position, SELECT ordinal_position,
@ -208,14 +182,12 @@ SQL;
SQL; SQL;
} }
// --------------------------------------------------------------------------
/** /**
* SQL to show list of field types * SQL to show list of field types
* *
* @return string * @return string
*/ */
public function type_list() public function typeList()
{ {
return <<<SQL return <<<SQL
SELECT "typname" FROM "pg_catalog"."pg_type" SELECT "typname" FROM "pg_catalog"."pg_type"
@ -225,8 +197,6 @@ SQL;
SQL; SQL;
} }
// --------------------------------------------------------------------------
/** /**
* Get the list of foreign keys for the current * Get the list of foreign keys for the current
* table * table
@ -234,7 +204,7 @@ SQL;
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function fk_list($table) public function fkList($table)
{ {
return <<<SQL return <<<SQL
SELECT SELECT
@ -270,15 +240,13 @@ SQL;
SQL; SQL;
} }
// --------------------------------------------------------------------------
/** /**
* Get the list of indexes for the current table * Get the list of indexes for the current table
* *
* @param string $table * @param string $table
* @return array * @return array
*/ */
public function index_list($table) public function indexList($table)
{ {
return <<<SQL return <<<SQL
SELECT SELECT
@ -306,4 +274,3 @@ SQL;
SQL; SQL;
} }
} }
//End of pgsql_sql.php

View File

@ -12,18 +12,12 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query\Drivers\Pgsql; namespace Query\Drivers\Pgsql;
use Query\Drivers\AbstractUtil; use Query\Drivers\AbstractUtil;
/** /**
* Posgres-specific backup, import and creation methods * Posgres-specific backup, import and creation methods
*
* @package Query
* @subpackage Drivers
*/ */
class Util extends AbstractUtil { class Util extends AbstractUtil {
@ -32,23 +26,21 @@ class Util extends AbstractUtil {
* *
* @return string * @return string
*/ */
public function backup_structure() public function backupStructure()
{ {
// @TODO Implement Backup function // @TODO Implement Backup function
return ''; return '';
} }
// --------------------------------------------------------------------------
/** /**
* Create an SQL backup file for the current database's data * Create an SQL backup file for the current database's data
* *
* @param array $exclude * @param array $exclude
* @return string * @return string
*/ */
public function backup_data($exclude=[]) public function backupData($exclude=[])
{ {
$tables = $this->get_driver()->get_tables(); $tables = $this->getDriver()->getTables();
// Filter out the tables you don't want // Filter out the tables you don't want
if( ! empty($exclude)) if( ! empty($exclude))
@ -56,17 +48,17 @@ class Util extends AbstractUtil {
$tables = array_diff($tables, $exclude); $tables = array_diff($tables, $exclude);
} }
$output_sql = ''; $outputSql = '';
// Get the data for each object // Get the data for each object
foreach($tables as $t) foreach($tables as $t)
{ {
$sql = 'SELECT * FROM "'.trim($t).'"'; $sql = 'SELECT * FROM "'.trim($t).'"';
$res = $this->get_driver()->query($sql); $res = $this->getDriver()->query($sql);
$obj_res = $res->fetchAll(\PDO::FETCH_ASSOC); $objRes = $res->fetchAll(\PDO::FETCH_ASSOC);
// Don't add to the file if the table is empty // Don't add to the file if the table is empty
if (count($obj_res) < 1) if (count($objRes) < 1)
{ {
continue; continue;
} }
@ -74,33 +66,32 @@ class Util extends AbstractUtil {
$res = NULL; $res = NULL;
// Nab the column names by getting the keys of the first row // Nab the column names by getting the keys of the first row
$columns = @array_keys($obj_res[0]); $columns = @array_keys($objRes[0]);
$insert_rows = []; $insertRows = [];
// Create the insert statements // Create the insert statements
foreach($obj_res as $row) foreach($objRes as $row)
{ {
$row = array_values($row); $row = array_values($row);
// Quote values as needed by type // Quote values as needed by type
$row = array_map([$this->get_driver(), 'quote'], $row); $row = array_map([$this->getDriver(), 'quote'], $row);
$row = array_map('trim', $row); $row = array_map('trim', $row);
$row_string = 'INSERT INTO "'.trim($t).'" ("'.implode('","', $columns).'") VALUES ('.implode(',', $row).');'; $rowString = 'INSERT INTO "'.trim($t).'" ("'.implode('","', $columns).'") VALUES ('.implode(',', $row).');';
$row = NULL; $row = NULL;
$insert_rows[] = $row_string; $insertRows[] = $rowString;
} }
$obj_res = NULL; $objRes = NULL;
$output_sql .= "\n\n".implode("\n", $insert_rows)."\n"; $outputSql .= "\n\n".implode("\n", $insertRows)."\n";
} }
return $output_sql; return $outputSql;
} }
} }
// End of pgsql_util.php

View File

@ -13,11 +13,6 @@
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
// --------------------------------------------------------------------------
namespace Query\Drivers; namespace Query\Drivers;
/** /**
@ -58,63 +53,63 @@ interface SQLInterface {
* *
* @return string * @return string
*/ */
public function db_list(); public function dbList();
/** /**
* Returns sql to list tables * Returns sql to list tables
* *
* @return string * @return string
*/ */
public function table_list(); public function tableList();
/** /**
* Returns sql to list system tables * Returns sql to list system tables
* *
* @return string * @return string
*/ */
public function system_table_list(); public function systemTableList();
/** /**
* Returns sql to list views * Returns sql to list views
* *
* @return string * @return string
*/ */
public function view_list(); public function viewList();
/** /**
* Returns sql to list triggers * Returns sql to list triggers
* *
* @return string * @return string
*/ */
public function trigger_list(); public function triggerList();
/** /**
* Return sql to list functions * Return sql to list functions
* *
* @return NULL * @return NULL
*/ */
public function function_list(); public function functionList();
/** /**
* Return sql to list stored procedures * Return sql to list stored procedures
* *
* @return string * @return string
*/ */
public function procedure_list(); public function procedureList();
/** /**
* Return sql to list sequences * Return sql to list sequences
* *
* @return string * @return string
*/ */
public function sequence_list(); public function sequenceList();
/** /**
* Return sql to list database field types * Return sql to list database field types
* *
* @return string|array * @return string|array
*/ */
public function type_list(); public function typeList();
/** /**
* Get information about the columns in the * Get information about the columns in the
@ -123,7 +118,7 @@ interface SQLInterface {
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function column_list($table); public function columnList($table);
/** /**
* Get the list of foreign keys for the current * Get the list of foreign keys for the current
@ -132,7 +127,7 @@ interface SQLInterface {
* @param string $table * @param string $table
* @return array * @return array
*/ */
public function fk_list($table); public function fkList($table);
/** /**
* Get the list of indexes for the current table * Get the list of indexes for the current table
@ -140,7 +135,5 @@ interface SQLInterface {
* @param string $table * @param string $table
* @return array * @return array
*/ */
public function index_list($table); public function indexList($table);
} }
// End of sql_interface.php

View File

@ -12,19 +12,15 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query\Drivers\Sqlite; namespace Query\Drivers\Sqlite;
use PDO; use PDO;
use PDOStatement; use PDOStatement;
use Query\Drivers\{AbstractDriver, DriverInterface}; use Query\Drivers\AbstractDriver;
use Query\Drivers\DriverInterface;
/** /**
* SQLite specific class * SQLite specific class
*
* @package Query
* @subpackage Drivers
*/ */
class Driver extends AbstractDriver implements DriverInterface { class Driver extends AbstractDriver implements DriverInterface {
@ -40,7 +36,7 @@ class Driver extends AbstractDriver implements DriverInterface {
* but no support for the actual keyword * but no support for the actual keyword
* @var boolean * @var boolean
*/ */
protected $has_truncate = FALSE; protected $hasTruncate = FALSE;
/** /**
* Open SQLite Database * Open SQLite Database
@ -48,9 +44,9 @@ class Driver extends AbstractDriver implements DriverInterface {
* @param string $dsn * @param string $dsn
* @param string $user * @param string $user
* @param string $pass * @param string $pass
* @param array $driver_options * @param array $driverOptions
*/ */
public function __construct($dsn, $user=NULL, $pass=NULL, array $driver_options=[]) public function __construct($dsn, $user=NULL, $pass=NULL, array $driverOptions=[])
{ {
if (strpos($dsn, 'sqlite:') === FALSE) if (strpos($dsn, 'sqlite:') === FALSE)
{ {
@ -65,9 +61,9 @@ class Driver extends AbstractDriver implements DriverInterface {
* *
* @return mixed * @return mixed
*/ */
public function get_tables() public function getTables()
{ {
$sql = $this->sql->table_list(); $sql = $this->sql->tableList();
$res = $this->query($sql); $res = $this->query($sql);
return db_filter($res->fetchAll(PDO::FETCH_ASSOC), 'name'); return db_filter($res->fetchAll(PDO::FETCH_ASSOC), 'name');
} }
@ -78,13 +74,13 @@ class Driver extends AbstractDriver implements DriverInterface {
* @param string $table * @param string $table
* @return array * @return array
*/ */
public function get_fks($table) public function getFks($table)
{ {
$return_rows = []; $returnRows = [];
foreach(parent::get_fks($table) as $row) foreach(parent::getFks($table) as $row)
{ {
$return_rows[] = [ $returnRows[] = [
'child_column' => $row['from'], 'child_column' => $row['from'],
'parent_table' => $row['table'], 'parent_table' => $row['table'],
'parent_column' => $row['to'], 'parent_column' => $row['to'],
@ -93,7 +89,7 @@ class Driver extends AbstractDriver implements DriverInterface {
]; ];
} }
return $return_rows; return $returnRows;
} }
/** /**
@ -104,13 +100,13 @@ class Driver extends AbstractDriver implements DriverInterface {
* @param array $data * @param array $data
* @return string * @return string
*/ */
public function insert_batch($table, $data=[]) public function insertBatch($table, $data=[])
{ {
// If greater than version 3.7.11, supports the same syntax as // If greater than version 3.7.11, supports the same syntax as
// MySQL and Postgres // MySQL and Postgres
if (version_compare($this->getAttribute(PDO::ATTR_SERVER_VERSION), '3.7.11', '>=')) if (version_compare($this->getAttribute(PDO::ATTR_SERVER_VERSION), '3.7.11', '>='))
{ {
return parent::insert_batch($table, $data); return parent::insertBatch($table, $data);
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -124,7 +120,7 @@ class Driver extends AbstractDriver implements DriverInterface {
} }
// Start the block of sql statements // Start the block of sql statements
$table = $this->quote_table($table); $table = $this->quoteTable($table);
$sql = "INSERT INTO {$table} \n"; $sql = "INSERT INTO {$table} \n";
// Create a key-value mapping for each field // Create a key-value mapping for each field
@ -132,7 +128,7 @@ class Driver extends AbstractDriver implements DriverInterface {
$cols = []; $cols = [];
foreach($first as $colname => $datum) foreach($first as $colname => $datum)
{ {
$cols[] = $this->_quote($datum) . ' AS ' . $this->quote_ident($colname); $cols[] = $this->_quote($datum) . ' AS ' . $this->quoteIdent($colname);
} }
$sql .= "SELECT " . implode(', ', $cols) . "\n"; $sql .= "SELECT " . implode(', ', $cols) . "\n";
@ -145,4 +141,3 @@ class Driver extends AbstractDriver implements DriverInterface {
return [$sql, NULL]; return [$sql, NULL];
} }
} }
//End of sqlite_driver.php

View File

@ -12,18 +12,12 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query\Drivers\Sqlite; namespace Query\Drivers\Sqlite;
use Query\Drivers\AbstractSQL; use Query\Drivers\AbstractSQL;
/** /**
* SQLite Specific SQL * SQLite Specific SQL
*
* @package Query
* @subpackage Drivers
*/ */
class SQL extends AbstractSQL { class SQL extends AbstractSQL {
@ -38,8 +32,6 @@ class SQL extends AbstractSQL {
return "EXPLAIN QUERY PLAN {$sql}"; return "EXPLAIN QUERY PLAN {$sql}";
} }
// --------------------------------------------------------------------------
/** /**
* Random ordering keyword * Random ordering keyword
* *
@ -50,26 +42,22 @@ class SQL extends AbstractSQL {
return ' RANDOM()'; return ' RANDOM()';
} }
// --------------------------------------------------------------------------
/** /**
* Returns sql to list other databases * Returns sql to list other databases
* *
* @return string * @return string
*/ */
public function db_list() public function dbList()
{ {
return 'PRAGMA database_list'; return 'PRAGMA database_list';
} }
// --------------------------------------------------------------------------
/** /**
* Returns sql to list tables * Returns sql to list tables
* *
* @return string * @return string
*/ */
public function table_list() public function tableList()
{ {
return <<<SQL return <<<SQL
SELECT DISTINCT "name" SELECT DISTINCT "name"
@ -80,107 +68,89 @@ class SQL extends AbstractSQL {
SQL; SQL;
} }
// --------------------------------------------------------------------------
/** /**
* List the system tables * List the system tables
* *
* @return string[] * @return string[]
*/ */
public function system_table_list() public function systemTableList()
{ {
return ['sqlite_master', 'sqlite_temp_master', 'sqlite_sequence']; return ['sqlite_master', 'sqlite_temp_master', 'sqlite_sequence'];
} }
// --------------------------------------------------------------------------
/** /**
* Returns sql to list views * Returns sql to list views
* *
* @return string * @return string
*/ */
public function view_list() public function viewList()
{ {
return <<<SQL return <<<SQL
SELECT "name" FROM "sqlite_master" WHERE "type" = 'view' SELECT "name" FROM "sqlite_master" WHERE "type" = 'view'
SQL; SQL;
} }
// --------------------------------------------------------------------------
/** /**
* Returns sql to list triggers * Returns sql to list triggers
* *
* @return string * @return string
*/ */
public function trigger_list() public function triggerList()
{ {
return 'SELECT "name" FROM "sqlite_master" WHERE "type"=\'trigger\''; return 'SELECT "name" FROM "sqlite_master" WHERE "type"=\'trigger\'';
} }
// --------------------------------------------------------------------------
/** /**
* Return sql to list functions * Return sql to list functions
* *
* @return NULL * @return NULL
*/ */
public function function_list() public function functionList()
{ {
return NULL; return NULL;
} }
// --------------------------------------------------------------------------
/** /**
* Return sql to list stored procedures * Return sql to list stored procedures
* *
* @return NULL * @return NULL
*/ */
public function procedure_list() public function procedureList()
{ {
return NULL; return NULL;
} }
// --------------------------------------------------------------------------
/** /**
* Return sql to list sequences * Return sql to list sequences
* *
* @return NULL * @return NULL
*/ */
public function sequence_list() public function sequenceList()
{ {
return NULL; return NULL;
} }
// --------------------------------------------------------------------------
/** /**
* SQL to show list of field types * SQL to show list of field types
* *
* @return string[] * @return string[]
*/ */
public function type_list() public function typeList()
{ {
return ['INTEGER', 'REAL', 'TEXT', 'BLOB']; return ['INTEGER', 'REAL', 'TEXT', 'BLOB'];
} }
// --------------------------------------------------------------------------
/** /**
* SQL to show infromation about columns in a table * SQL to show infromation about columns in a table
* *
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function column_list($table) public function columnList($table)
{ {
return 'PRAGMA table_info("'.$table.'")'; return 'PRAGMA table_info("' . $table . '")';
} }
// --------------------------------------------------------------------------
/** /**
* Get the list of foreign keys for the current * Get the list of foreign keys for the current
* table * table
@ -188,12 +158,11 @@ SQL;
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function fk_list($table) public function fkList($table)
{ {
return 'PRAGMA foreign_key_list("' . $table . '")'; return 'PRAGMA foreign_key_list("' . $table . '")';
} }
// --------------------------------------------------------------------------
/** /**
* Get the list of indexes for the current table * Get the list of indexes for the current table
@ -201,10 +170,8 @@ SQL;
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function index_list($table) public function indexList($table)
{ {
return 'PRAGMA index_list("' . $table . '")'; return 'PRAGMA index_list("' . $table . '")';
} }
} }
//End of sqlite_sql.php

View File

@ -12,11 +12,9 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query\Drivers\Sqlite; namespace Query\Drivers\Sqlite;
use PDO;
use Query\Drivers\AbstractUtil; use Query\Drivers\AbstractUtil;
/** /**
@ -35,7 +33,7 @@ class Util extends AbstractUtil {
* @param array $excluded * @param array $excluded
* @return string * @return string
*/ */
public function backup_data($excluded=[]) public function backupData($excluded=[])
{ {
// Get a list of all the objects // Get a list of all the objects
$sql = 'SELECT DISTINCT "name" $sql = 'SELECT DISTINCT "name"
@ -47,81 +45,78 @@ class Util extends AbstractUtil {
$sql .= " AND \"name\" NOT IN('".implode("','", $excluded)."')"; $sql .= " AND \"name\" NOT IN('".implode("','", $excluded)."')";
} }
$res = $this->get_driver()->query($sql); $res = $this->getDriver()->query($sql);
$result = $res->fetchAll(\PDO::FETCH_ASSOC); $result = $res->fetchAll(PDO::FETCH_ASSOC);
unset($res); unset($res);
$output_sql = ''; $outputSql = '';
// Get the data for each object // Get the data for each object
foreach($result as $r) foreach($result as $r)
{ {
$sql = 'SELECT * FROM "'.$r['name'].'"'; $sql = 'SELECT * FROM "'.$r['name'].'"';
$res = $this->get_driver()->query($sql); $res = $this->getDriver()->query($sql);
$obj_res = $res->fetchAll(\PDO::FETCH_ASSOC); $objRes = $res->fetchAll(PDO::FETCH_ASSOC);
unset($res); unset($res);
// If the row is empty, continue; // If the row is empty, continue;
if (empty($obj_res)) if (empty($objRes))
{ {
continue; continue;
} }
// Nab the column names by getting the keys of the first row // Nab the column names by getting the keys of the first row
$columns = array_keys(current($obj_res)); $columns = array_keys(current($objRes));
$insert_rows = []; $insertRows = [];
// Create the insert statements // Create the insert statements
foreach($obj_res as $row) foreach($objRes as $row)
{ {
$row = array_values($row); $row = array_values($row);
// Quote values as needed by type // Quote values as needed by type
for($i=0, $icount=count($row); $i<$icount; $i++) for($i=0, $icount=count($row); $i<$icount; $i++)
{ {
$row[$i] = (is_numeric($row[$i])) ? $row[$i] : $this->get_driver()->quote($row[$i]); $row[$i] = (is_numeric($row[$i])) ? $row[$i] : $this->getDriver()->quote($row[$i]);
} }
$row_string = 'INSERT INTO "'.$r['name'].'" ("'.implode('","', $columns).'") VALUES ('.implode(',', $row).');'; $rowString = 'INSERT INTO "'.$r['name'].'" ("'.implode('","', $columns).'") VALUES ('.implode(',', $row).');';
unset($row); unset($row);
$insert_rows[] = $row_string; $insertRows[] = $rowString;
} }
unset($obj_res); unset($objRes);
$output_sql .= "\n\n".implode("\n", $insert_rows); $outputSql .= "\n\n".implode("\n", $insertRows);
} }
return $output_sql; return $outputSql;
} }
// --------------------------------------------------------------------------
/** /**
* Create an SQL backup file for the current database's structure * Create an SQL backup file for the current database's structure
* *
* @return string * @return string
*/ */
public function backup_structure() public function backupStructure()
{ {
// Fairly easy for SQLite...just query the master table // Fairly easy for SQLite...just query the master table
$sql = 'SELECT "sql" FROM "sqlite_master"'; $sql = 'SELECT "sql" FROM "sqlite_master"';
$res = $this->get_driver()->query($sql); $res = $this->getDriver()->query($sql);
$result = $res->fetchAll(\PDO::FETCH_ASSOC); $result = $res->fetchAll(PDO::FETCH_ASSOC);
$sql_array = []; $sqlArray = [];
foreach($result as $r) foreach($result as $r)
{ {
$sql_array[] = $r['sql']; $sqlArray[] = $r['sql'];
} }
return implode(";\n", $sql_array) . ";"; return implode(";\n", $sqlArray) . ";";
} }
} }
// End of sqlite_util.php

View File

@ -12,7 +12,6 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query; namespace Query;
use BadMethodCallException; use BadMethodCallException;
@ -20,11 +19,7 @@ use PDOStatement;
use Query\Drivers\DriverInterface; use Query\Drivers\DriverInterface;
/** /**
* Convenience class for creating sql queries - also the class that * Convenience class for creating sql queries
* instantiates the specific db driver
*
* @package Query
* @subpackage Query_Builder
*/ */
class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface { class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface {
@ -33,12 +28,12 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* *
* @var array * @var array
*/ */
private $string_vars = [ private $stringVars = [
'select_string', 'selectString',
'from_string', 'fromString',
'set_string', 'setString',
'order_string', 'orderString',
'group_string', 'groupString',
'limit', 'limit',
'offset', 'offset',
'explain', 'explain',
@ -49,14 +44,14 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* *
* @var array * @var array
*/ */
private $array_vars = [ private $arrayVars = [
'set_array_keys', 'setArrayKeys',
'order_array', 'orderArray',
'group_array', 'groupArray',
'values', 'values',
'where_values', 'whereValues',
'query_map', 'queryMap',
'having_map' 'havingMap'
]; ];
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -78,8 +73,8 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
$this->queries['total_time'] = 0; $this->queries['total_time'] = 0;
// Alias driver sql and util classes // Alias driver sql and util classes
$this->sql = $this->db->get_sql(); $this->sql = $this->db->getSql();
$this->util = $this->db->get_util(); $this->util = $this->db->getUtil();
} }
/** /**
@ -101,16 +96,16 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
*/ */
public function __call(string $name, array $params) public function __call(string $name, array $params)
{ {
// Allow camel-case method calls // Alias snake_case method calls
$snake_name = \from_camel_case($name); $camelName = \to_camel_case($name);
foreach([$this, $this->db] as $object) foreach([$this, $this->db] as $object)
{ {
foreach([$name, $snake_name] as $method_name) foreach([$name, $camelName] as $methodName)
{ {
if (method_exists($object, $method_name)) if (method_exists($object, $methodName))
{ {
return call_user_func_array([$object, $method_name], $params); return call_user_func_array([$object, $methodName], $params);
} }
} }
@ -132,36 +127,36 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
public function select(string $fields): QueryBuilderInterface public function select(string $fields): QueryBuilderInterface
{ {
// Split fields by comma // Split fields by comma
$fields_array = explode(',', $fields); $fieldsArray = explode(',', $fields);
$fields_array = array_map('mb_trim', $fields_array); $fieldsArray = array_map('mb_trim', $fieldsArray);
// Split on 'As' // Split on 'As'
foreach ($fields_array as $key => $field) foreach ($fieldsArray as $key => $field)
{ {
if (stripos($field, 'as') !== FALSE) if (stripos($field, 'as') !== FALSE)
{ {
$fields_array[$key] = preg_split('` as `i', $field); $fieldsArray[$key] = preg_split('` as `i', $field);
$fields_array[$key] = array_map('mb_trim', $fields_array[$key]); $fieldsArray[$key] = array_map('mb_trim', $fieldsArray[$key]);
} }
} }
// Quote the identifiers // Quote the identifiers
$safe_array = $this->db->quote_ident($fields_array); $safeArray = $this->db->quoteIdent($fieldsArray);
unset($fields_array); unset($fieldsArray);
// Join the strings back together // Join the strings back together
for($i = 0, $c = count($safe_array); $i < $c; $i++) for($i = 0, $c = count($safeArray); $i < $c; $i++)
{ {
if (is_array($safe_array[$i])) if (is_array($safeArray[$i]))
{ {
$safe_array[$i] = implode(' AS ', $safe_array[$i]); $safeArray[$i] = implode(' AS ', $safeArray[$i]);
} }
} }
$this->select_string .= implode(', ', $safe_array); $this->selectString .= implode(', ', $safeArray);
unset($safe_array); unset($safeArray);
return $this; return $this;
} }
@ -173,10 +168,10 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param string|bool $as * @param string|bool $as
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function select_max($field, $as=FALSE): QueryBuilderInterface public function selectMax(string $field, $as=FALSE): QueryBuilderInterface
{ {
// Create the select string // Create the select string
$this->select_string .= ' MAX'.$this->_select($field, $as); $this->selectString .= ' MAX'.$this->_select($field, $as);
return $this; return $this;
} }
@ -187,10 +182,10 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param string|bool $as * @param string|bool $as
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function select_min($field, $as=FALSE): QueryBuilderInterface public function selectMin(string $field, $as=FALSE): QueryBuilderInterface
{ {
// Create the select string // Create the select string
$this->select_string .= ' MIN'.$this->_select($field, $as); $this->selectString .= ' MIN'.$this->_select($field, $as);
return $this; return $this;
} }
@ -201,10 +196,10 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param string|bool $as * @param string|bool $as
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function select_avg($field, $as=FALSE): QueryBuilderInterface public function selectAvg(string $field, $as=FALSE): QueryBuilderInterface
{ {
// Create the select string // Create the select string
$this->select_string .= ' AVG'.$this->_select($field, $as); $this->selectString .= ' AVG'.$this->_select($field, $as);
return $this; return $this;
} }
@ -215,10 +210,10 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param string|bool $as * @param string|bool $as
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function select_sum($field, $as=FALSE): QueryBuilderInterface public function selectSum(string $field, $as=FALSE): QueryBuilderInterface
{ {
// Create the select string // Create the select string
$this->select_string .= ' SUM'.$this->_select($field, $as); $this->selectString .= ' SUM'.$this->_select($field, $as);
return $this; return $this;
} }
@ -230,7 +225,7 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
public function distinct(): QueryBuilderInterface public function distinct(): QueryBuilderInterface
{ {
// Prepend the keyword to the select string // Prepend the keyword to the select string
$this->select_string = ' DISTINCT '.$this->select_string; $this->selectString = ' DISTINCT '.$this->selectString;
return $this; return $this;
} }
@ -254,15 +249,15 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
public function from($tblname): QueryBuilderInterface public function from($tblname): QueryBuilderInterface
{ {
// Split identifiers on spaces // Split identifiers on spaces
$ident_array = explode(' ', \mb_trim($tblname)); $identArray = explode(' ', \mb_trim($tblname));
$ident_array = array_map('\\mb_trim', $ident_array); $identArray = array_map('\\mb_trim', $identArray);
// Quote the identifiers // Quote the identifiers
$ident_array[0] = $this->db->quote_table($ident_array[0]); $identArray[0] = $this->db->quoteTable($identArray[0]);
$ident_array = $this->db->quote_ident($ident_array); $identArray = $this->db->quoteIdent($identArray);
// Paste it back together // Paste it back together
$this->from_string = implode(' ', $ident_array); $this->fromString = implode(' ', $identArray);
return $this; return $this;
} }
@ -292,7 +287,7 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param string $pos * @param string $pos
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function or_like($field, $val, $pos='both'): QueryBuilderInterface public function orLike($field, $val, $pos='both'): QueryBuilderInterface
{ {
return $this->_like($field, $val, $pos, 'LIKE', 'OR'); return $this->_like($field, $val, $pos, 'LIKE', 'OR');
} }
@ -305,7 +300,7 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param string $pos * @param string $pos
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function not_like($field, $val, $pos='both'): QueryBuilderInterface public function notLike($field, $val, $pos='both'): QueryBuilderInterface
{ {
return $this->_like($field, $val, $pos, 'NOT LIKE', 'AND'); return $this->_like($field, $val, $pos, 'NOT LIKE', 'AND');
} }
@ -318,7 +313,7 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param string $pos * @param string $pos
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function or_not_like($field, $val, $pos='both'): QueryBuilderInterface public function orNotLike($field, $val, $pos='both'): QueryBuilderInterface
{ {
return $this->_like($field, $val, $pos, 'NOT LIKE', 'OR'); return $this->_like($field, $val, $pos, 'NOT LIKE', 'OR');
} }
@ -346,7 +341,7 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param mixed $val * @param mixed $val
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function or_having($key, $val=[]): QueryBuilderInterface public function orHaving($key, $val=[]): QueryBuilderInterface
{ {
return $this->_having($key, $val, 'OR'); return $this->_having($key, $val, 'OR');
} }
@ -367,7 +362,7 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
*/ */
public function where($key, $val=[], $escape=NULL): QueryBuilderInterface public function where($key, $val=[], $escape=NULL): QueryBuilderInterface
{ {
return $this->_where_string($key, $val, 'AND'); return $this->_whereString($key, $val, 'AND');
} }
/** /**
@ -377,9 +372,9 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param mixed $val * @param mixed $val
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function or_where($key, $val=[]): QueryBuilderInterface public function orWhere($key, $val=[]): QueryBuilderInterface
{ {
return $this->_where_string($key, $val, 'OR'); return $this->_whereString($key, $val, 'OR');
} }
/** /**
@ -389,9 +384,9 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param mixed $val * @param mixed $val
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function where_in($field, $val=[]): QueryBuilderInterface public function whereIn($field, $val=[]): QueryBuilderInterface
{ {
return $this->_where_in($field, $val); return $this->_whereIn($field, $val);
} }
/** /**
@ -401,9 +396,9 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param mixed $val * @param mixed $val
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function or_where_in($field, $val=[]): QueryBuilderInterface public function orWhereIn($field, $val=[]): QueryBuilderInterface
{ {
return $this->_where_in($field, $val, 'IN', 'OR'); return $this->_whereIn($field, $val, 'IN', 'OR');
} }
/** /**
@ -413,9 +408,9 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param mixed $val * @param mixed $val
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function where_not_in($field, $val=[]): QueryBuilderInterface public function whereNotIn($field, $val=[]): QueryBuilderInterface
{ {
return $this->_where_in($field, $val, 'NOT IN', 'AND'); return $this->_whereIn($field, $val, 'NOT IN', 'AND');
} }
/** /**
@ -425,9 +420,9 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param mixed $val * @param mixed $val
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function or_where_not_in($field, $val=[]): QueryBuilderInterface public function orWhereNotIn($field, $val=[]): QueryBuilderInterface
{ {
return $this->_where_in($field, $val, 'NOT IN', 'OR'); return $this->_whereIn($field, $val, 'NOT IN', 'OR');
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -443,16 +438,16 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
*/ */
public function set($key, $val = NULL): QueryBuilderInterface public function set($key, $val = NULL): QueryBuilderInterface
{ {
$this->_mixed_set($this->set_array_keys, $key, $val, self::KEY); $this->_mixedSet($this->setArrayKeys, $key, $val, self::KEY);
$this->_mixed_set($this->values, $key, $val, self::VALUE); $this->_mixedSet($this->values, $key, $val, self::VALUE);
// Use the keys of the array to make the insert/update string // Use the keys of the array to make the insert/update string
// Escape the field names // Escape the field names
$this->set_array_keys = array_map([$this->db, '_quote'], $this->set_array_keys); $this->setArrayKeys = array_map([$this->db, '_quote'], $this->setArrayKeys);
// Generate the "set" string // Generate the "set" string
$this->set_string = implode('=?,', $this->set_array_keys); $this->setString = implode('=?,', $this->setArrayKeys);
$this->set_string .= '=?'; $this->setString .= '=?';
return $this; return $this;
} }
@ -469,15 +464,15 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
{ {
// Prefix and quote table name // Prefix and quote table name
$table = explode(' ', mb_trim($table)); $table = explode(' ', mb_trim($table));
$table[0] = $this->db->quote_table($table[0]); $table[0] = $this->db->quoteTable($table[0]);
$table = $this->db->quote_ident($table); $table = $this->db->quoteIdent($table);
$table = implode(' ', $table); $table = implode(' ', $table);
// Parse out the join condition // Parse out the join condition
$parsed_condition = $this->parser->compile_join($condition); $parsedCondition = $this->parser->compileJoin($condition);
$condition = $table . ' ON ' . $parsed_condition; $condition = $table . ' ON ' . $parsedCondition;
$this->_append_map("\n" . strtoupper($type) . ' JOIN ', $condition, 'join'); $this->_appendMap("\n" . strtoupper($type) . ' JOIN ', $condition, 'join');
return $this; return $this;
} }
@ -488,19 +483,19 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param mixed $field * @param mixed $field
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function group_by($field): QueryBuilderInterface public function groupBy($field): QueryBuilderInterface
{ {
if ( ! is_scalar($field)) if ( ! is_scalar($field))
{ {
$new_group_array = array_map([$this->db, 'quote_ident'], $field); $newGroupArray = array_map([$this->db, 'quoteIdent'], $field);
$this->group_array = array_merge($this->group_array, $new_group_array); $this->groupArray = array_merge($this->groupArray, $newGroupArray);
} }
else else
{ {
$this->group_array[] = $this->db->quote_ident($field); $this->groupArray[] = $this->db->quoteIdent($field);
} }
$this->group_string = ' GROUP BY ' . implode(',', $this->group_array); $this->groupString = ' GROUP BY ' . implode(',', $this->groupArray);
return $this; return $this;
} }
@ -512,7 +507,7 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param string $type * @param string $type
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function order_by($field, $type=""): QueryBuilderInterface public function orderBy($field, $type=""): QueryBuilderInterface
{ {
// When ordering by random, do an ascending order if the driver // When ordering by random, do an ascending order if the driver
// doesn't support random ordering // doesn't support random ordering
@ -523,20 +518,20 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
} }
// Set fields for later manipulation // Set fields for later manipulation
$field = $this->db->quote_ident($field); $field = $this->db->quoteIdent($field);
$this->order_array[$field] = $type; $this->orderArray[$field] = $type;
$order_clauses = []; $orderClauses = [];
// Flatten key/val pairs into an array of space-separated pairs // Flatten key/val pairs into an array of space-separated pairs
foreach($this->order_array as $k => $v) foreach($this->orderArray as $k => $v)
{ {
$order_clauses[] = $k . ' ' . strtoupper($v); $orderClauses[] = $k . ' ' . strtoupper($v);
} }
// Set the final string // Set the final string
$this->order_string = ( ! isset($rand)) $this->orderString = ( ! isset($rand))
? "\nORDER BY ".implode(', ', $order_clauses) ? "\nORDER BY ".implode(', ', $orderClauses)
: "\nORDER BY".$rand; : "\nORDER BY".$rand;
return $this; return $this;
@ -566,11 +561,11 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* *
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function group_start(): QueryBuilderInterface public function groupStart(): QueryBuilderInterface
{ {
$conj = (empty($this->query_map)) ? ' WHERE ' : ' '; $conj = (empty($this->queryMap)) ? ' WHERE ' : ' ';
$this->_append_map($conj, '(', 'group_start'); $this->_appendMap($conj, '(', 'group_start');
return $this; return $this;
} }
@ -581,11 +576,11 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* *
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function not_group_start(): QueryBuilderInterface public function notGroupStart(): QueryBuilderInterface
{ {
$conj = (empty($this->query_map)) ? ' WHERE ' : ' AND '; $conj = (empty($this->queryMap)) ? ' WHERE ' : ' AND ';
$this->_append_map($conj, ' NOT (', 'group_start'); $this->_appendMap($conj, ' NOT (', 'group_start');
return $this; return $this;
} }
@ -596,9 +591,9 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* *
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function or_group_start(): QueryBuilderInterface public function orGroupStart(): QueryBuilderInterface
{ {
$this->_append_map('', ' OR (', 'group_start'); $this->_appendMap('', ' OR (', 'group_start');
return $this; return $this;
} }
@ -609,9 +604,9 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* *
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function or_not_group_start(): QueryBuilderInterface public function orNotGroupStart(): QueryBuilderInterface
{ {
$this->_append_map('', ' OR NOT (', 'group_start'); $this->_appendMap('', ' OR NOT (', 'group_start');
return $this; return $this;
} }
@ -621,9 +616,9 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* *
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function group_end(): QueryBuilderInterface public function groupEnd(): QueryBuilderInterface
{ {
$this->_append_map('', ')', 'group_end'); $this->_appendMap('', ')', 'group_end');
return $this; return $this;
} }
@ -667,7 +662,7 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param int|bool $offset * @param int|bool $offset
* @return PDOStatement * @return PDOStatement
*/ */
public function get_where($table, $where=[], $limit=FALSE, $offset=FALSE): PDOStatement public function getWhere($table, $where=[], $limit=FALSE, $offset=FALSE): PDOStatement
{ {
// Create the where clause // Create the where clause
$this->where($where); $this->where($where);
@ -682,9 +677,9 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param string $table * @param string $table
* @return int * @return int
*/ */
public function count_all($table): int public function countAll($table): int
{ {
$sql = 'SELECT * FROM '.$this->db->quote_table($table); $sql = 'SELECT * FROM '.$this->db->quoteTable($table);
$res = $this->db->query($sql); $res = $this->db->query($sql);
return (int) count($res->fetchAll()); return (int) count($res->fetchAll());
} }
@ -697,7 +692,7 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param boolean $reset * @param boolean $reset
* @return int * @return int
*/ */
public function count_all_results(string $table='', bool $reset = TRUE): int public function countAllResults(string $table='', bool $reset = TRUE): int
{ {
// Set the table // Set the table
if ( ! empty($table)) if ( ! empty($table))
@ -735,10 +730,10 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param array $data * @param array $data
* @return PDOStatement * @return PDOStatement
*/ */
public function insert_batch($table, $data=[]): PDOStatement public function insertBatch($table, $data=[]): PDOStatement
{ {
// Get the generated values and sql string // Get the generated values and sql string
list($sql, $data) = $this->db->insert_batch($table, $data); list($sql, $data) = $this->db->insertBatch($table, $data);
return ( ! is_null($sql)) return ( ! is_null($sql))
? $this->_run('', $table, $sql, $data) ? $this->_run('', $table, $sql, $data)
@ -771,10 +766,10 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param string $where * @param string $where
* @return int|null * @return int|null
*/ */
public function update_batch($table, $data, $where) public function updateBatch($table, $data, $where)
{ {
// Get the generated values and sql string // Get the generated values and sql string
list($sql, $data) = $this->db->update_batch($table, $data, $where); list($sql, $data) = $this->db->updateBatch($table, $data, $where);
return ( ! is_null($sql)) return ( ! is_null($sql))
? $this->_run('', $table, $sql, $data) ? $this->_run('', $table, $sql, $data)
@ -827,7 +822,7 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param bool $reset * @param bool $reset
* @return string * @return string
*/ */
public function get_compiled_select(string $table='', bool $reset=TRUE): string public function getCompiledSelect(string $table='', bool $reset=TRUE): string
{ {
// Set the table // Set the table
if ( ! empty($table)) if ( ! empty($table))
@ -835,7 +830,7 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
$this->from($table); $this->from($table);
} }
return $this->_get_compile('select', $table, $reset); return $this->_getCompile('select', $table, $reset);
} }
/** /**
@ -845,9 +840,9 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param bool $reset * @param bool $reset
* @return string * @return string
*/ */
public function get_compiled_insert(string $table, bool $reset=TRUE): string public function getCompiledInsert(string $table, bool $reset=TRUE): string
{ {
return $this->_get_compile('insert', $table, $reset); return $this->_getCompile('insert', $table, $reset);
} }
/** /**
@ -857,9 +852,9 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param bool $reset * @param bool $reset
* @return string * @return string
*/ */
public function get_compiled_update(string $table='', bool $reset=TRUE): string public function getCompiledUpdate(string $table='', bool $reset=TRUE): string
{ {
return $this->_get_compile('update', $table, $reset); return $this->_getCompile('update', $table, $reset);
} }
/** /**
@ -869,9 +864,9 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param bool $reset * @param bool $reset
* @return string * @return string
*/ */
public function get_compiled_delete(string $table='', bool $reset=TRUE): string public function getCompiledDelete(string $table='', bool $reset=TRUE): string
{ {
return $this->_get_compile('delete', $table, $reset); return $this->_getCompile('delete', $table, $reset);
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -883,16 +878,16 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* *
* @return void * @return void
*/ */
public function reset_query() public function resetQuery()
{ {
// Reset strings and booleans // Reset strings and booleans
foreach($this->string_vars as $var) foreach($this->stringVars as $var)
{ {
$this->$var = NULL; $this->$var = NULL;
} }
// Reset arrays // Reset arrays
foreach($this->array_vars as $var) foreach($this->arrayVars as $var)
{ {
$this->$var = []; $this->$var = [];
} }

View File

@ -46,7 +46,7 @@ interface QueryBuilderInterface {
* @param string|bool $as * @param string|bool $as
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function select_max($field, $as=FALSE): QueryBuilderInterface; public function selectMax(string $field, $as=FALSE): QueryBuilderInterface;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -57,7 +57,7 @@ interface QueryBuilderInterface {
* @param string|bool $as * @param string|bool $as
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function select_min($field, $as=FALSE): QueryBuilderInterface; public function selectMin(string $field, $as=FALSE): QueryBuilderInterface;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -68,7 +68,7 @@ interface QueryBuilderInterface {
* @param string|bool $as * @param string|bool $as
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function select_avg($field, $as=FALSE): QueryBuilderInterface; public function selectAvg(string $field, $as=FALSE): QueryBuilderInterface;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -79,9 +79,9 @@ interface QueryBuilderInterface {
* @param string|bool $as * @param string|bool $as
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function select_sum($field, $as=FALSE): QueryBuilderInterface; public function selectSum(string $field, $as=FALSE): QueryBuilderInterface;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------q
/** /**
* Adds the 'distinct' keyword to a query * Adds the 'distinct' keyword to a query
@ -133,7 +133,7 @@ interface QueryBuilderInterface {
* @param string $pos * @param string $pos
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function or_like($field, $val, $pos='both'): QueryBuilderInterface; public function orLike($field, $val, $pos='both'): QueryBuilderInterface;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -145,7 +145,7 @@ interface QueryBuilderInterface {
* @param string $pos * @param string $pos
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function not_like($field, $val, $pos='both'): QueryBuilderInterface; public function notLike($field, $val, $pos='both'): QueryBuilderInterface;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -157,7 +157,7 @@ interface QueryBuilderInterface {
* @param string $pos * @param string $pos
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function or_not_like($field, $val, $pos='both'): QueryBuilderInterface; public function orNotLike($field, $val, $pos='both'): QueryBuilderInterface;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// ! Having methods // ! Having methods
@ -181,7 +181,7 @@ interface QueryBuilderInterface {
* @param mixed $val * @param mixed $val
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function or_having($key, $val=[]): QueryBuilderInterface; public function orHaving($key, $val=[]): QueryBuilderInterface;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// ! 'Where' methods // ! 'Where' methods
@ -208,7 +208,7 @@ interface QueryBuilderInterface {
* @param mixed $val * @param mixed $val
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function or_where($key, $val=[]): QueryBuilderInterface; public function orWhere($key, $val=[]): QueryBuilderInterface;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -219,7 +219,7 @@ interface QueryBuilderInterface {
* @param mixed $val * @param mixed $val
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function where_in($field, $val=[]): QueryBuilderInterface; public function whereIn($field, $val=[]): QueryBuilderInterface;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -230,7 +230,7 @@ interface QueryBuilderInterface {
* @param mixed $val * @param mixed $val
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function or_where_in($field, $val=[]): QueryBuilderInterface; public function orWhereIn($field, $val=[]): QueryBuilderInterface;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -241,7 +241,7 @@ interface QueryBuilderInterface {
* @param mixed $val * @param mixed $val
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function where_not_in($field, $val=[]): QueryBuilderInterface; public function whereNotIn($field, $val=[]): QueryBuilderInterface;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -252,7 +252,7 @@ interface QueryBuilderInterface {
* @param mixed $val * @param mixed $val
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function or_where_not_in($field, $val=[]): QueryBuilderInterface; public function orWhereNotIn($field, $val=[]): QueryBuilderInterface;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// ! Other Query Modifier methods // ! Other Query Modifier methods
@ -287,7 +287,7 @@ interface QueryBuilderInterface {
* @param mixed $field * @param mixed $field
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function group_by($field): QueryBuilderInterface; public function groupBy($field): QueryBuilderInterface;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -298,7 +298,7 @@ interface QueryBuilderInterface {
* @param string $type * @param string $type
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function order_by($field, $type=""): QueryBuilderInterface; public function orderBy($field, $type=""): QueryBuilderInterface;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -320,7 +320,7 @@ interface QueryBuilderInterface {
* *
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function group_start(): QueryBuilderInterface; public function groupStart(): QueryBuilderInterface;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -330,7 +330,7 @@ interface QueryBuilderInterface {
* *
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function not_group_start(): QueryBuilderInterface; public function notGroupStart(): QueryBuilderInterface;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -340,7 +340,7 @@ interface QueryBuilderInterface {
* *
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function or_group_start(): QueryBuilderInterface; public function orGroupStart(): QueryBuilderInterface;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -350,7 +350,7 @@ interface QueryBuilderInterface {
* *
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function or_not_group_start(): QueryBuilderInterface; public function orNotGroupStart(): QueryBuilderInterface;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -359,7 +359,7 @@ interface QueryBuilderInterface {
* *
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function group_end(): QueryBuilderInterface; public function groupEnd(): QueryBuilderInterface;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// ! Query execution methods // ! Query execution methods
@ -387,7 +387,7 @@ interface QueryBuilderInterface {
* @param int|bool $offset * @param int|bool $offset
* @return PDOStatement * @return PDOStatement
*/ */
public function get_where($table, $where=[], $limit=FALSE, $offset=FALSE): PDOStatement; public function getWhere($table, $where=[], $limit=FALSE, $offset=FALSE): PDOStatement;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -397,7 +397,7 @@ interface QueryBuilderInterface {
* @param string $table * @param string $table
* @return int * @return int
*/ */
public function count_all($table): int; public function countAll($table): int;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -409,7 +409,7 @@ interface QueryBuilderInterface {
* @param bool $reset - Whether to keep the query after counting the results * @param bool $reset - Whether to keep the query after counting the results
* @return int * @return int
*/ */
public function count_all_results(string $table='', bool $reset=TRUE): int; public function countAllResults(string $table='', bool $reset=TRUE): int;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -431,7 +431,7 @@ interface QueryBuilderInterface {
* @param array $data * @param array $data
* @return \PDOStatement|null * @return \PDOStatement|null
*/ */
public function insert_batch($table, $data=[]); public function insertBatch($table, $data=[]);
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -466,7 +466,7 @@ interface QueryBuilderInterface {
* @param string $where * @param string $where
* @return int|null * @return int|null
*/ */
public function update_batch($table, $data, $where); public function updateBatch($table, $data, $where);
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -490,7 +490,7 @@ interface QueryBuilderInterface {
* @param bool $reset * @param bool $reset
* @return string * @return string
*/ */
public function get_compiled_select(string $table='', bool $reset=TRUE): string; public function getCompiledSelect(string $table='', bool $reset=TRUE): string;
/** /**
* Returns the generated 'insert' sql query * Returns the generated 'insert' sql query
@ -499,7 +499,7 @@ interface QueryBuilderInterface {
* @param bool $reset * @param bool $reset
* @return string * @return string
*/ */
public function get_compiled_insert(string $table, bool $reset=TRUE): string; public function getCompiledInsert(string $table, bool $reset=TRUE): string;
/** /**
* Returns the generated 'update' sql query * Returns the generated 'update' sql query
@ -508,7 +508,7 @@ interface QueryBuilderInterface {
* @param bool $reset * @param bool $reset
* @return string * @return string
*/ */
public function get_compiled_update(string $table='', bool $reset=TRUE): string; public function getCompiledUpdate(string $table='', bool $reset=TRUE): string;
/** /**
* Returns the generated 'delete' sql query * Returns the generated 'delete' sql query
@ -517,7 +517,7 @@ interface QueryBuilderInterface {
* @param bool $reset * @param bool $reset
* @return string * @return string
*/ */
public function get_compiled_delete(string $table='', bool $reset=TRUE): string; public function getCompiledDelete(string $table='', bool $reset=TRUE): string;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// ! Miscellaneous Methods // ! Miscellaneous Methods
@ -528,7 +528,7 @@ interface QueryBuilderInterface {
* *
* @return void * @return void
*/ */
public function reset_query(); public function resetQuery();
} }
// End of QueryBuilderInterface.php // End of QueryBuilderInterface.php

View File

@ -12,18 +12,12 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
namespace Query; namespace Query;
use Query\Drivers\DriverInterface; use Query\Drivers\DriverInterface;
/** /**
* Utility Class to parse sql clauses for properly escaping identifiers * Utility Class to parse sql clauses for properly escaping identifiers
*
* @package Query
* @subpackage Query_Builder
*/ */
class QueryParser { class QueryParser {
@ -39,7 +33,7 @@ class QueryParser {
* *
* @var array * @var array
*/ */
private $match_patterns = [ private $matchPatterns = [
'function' => '([a-zA-Z0-9_]+\((.*?)\))', 'function' => '([a-zA-Z0-9_]+\((.*?)\))',
'identifier' => '([a-zA-Z0-9_-]+\.?)+', 'identifier' => '([a-zA-Z0-9_-]+\.?)+',
'operator' => '=|AND|&&?|~|\|\|?|\^|/|>=?|<=?|-|%|OR|\+|NOT|\!=?|<>|XOR' 'operator' => '=|AND|&&?|~|\|\|?|\^|/|>=?|<=?|-|%|OR|\+|NOT|\!=?|<>|XOR'
@ -67,42 +61,38 @@ class QueryParser {
$this->db = $db; $this->db = $db;
} }
// --------------------------------------------------------------------------
/** /**
* Parser method for setting the parse string * Parser method for setting the parse string
* *
* @param string $sql * @param string $sql
* @return array * @return array
*/ */
public function parse_join($sql) public function parseJoin(string $sql): array
{ {
// Get sql clause components // Get sql clause components
preg_match_all('`'.$this->match_patterns['function'].'`', $sql, $this->matches['functions'], PREG_SET_ORDER); preg_match_all('`'.$this->matchPatterns['function'].'`', $sql, $this->matches['functions'], PREG_SET_ORDER);
preg_match_all('`'.$this->match_patterns['identifier'].'`', $sql, $this->matches['identifiers'], PREG_SET_ORDER); preg_match_all('`'.$this->matchPatterns['identifier'].'`', $sql, $this->matches['identifiers'], PREG_SET_ORDER);
preg_match_all('`'.$this->match_patterns['operator'].'`', $sql, $this->matches['operators'], PREG_SET_ORDER); preg_match_all('`'.$this->matchPatterns['operator'].'`', $sql, $this->matches['operators'], PREG_SET_ORDER);
// Get everything at once for ordering // Get everything at once for ordering
$full_pattern = '`'.$this->match_patterns['function'].'+|'.$this->match_patterns['identifier'].'|('.$this->match_patterns['operator'].')+`i'; $fullPattern = '`'.$this->matchPatterns['function'].'+|'.$this->matchPatterns['identifier'].'|('.$this->matchPatterns['operator'].')+`i';
preg_match_all($full_pattern, $sql, $this->matches['combined'], PREG_SET_ORDER); preg_match_all($fullPattern, $sql, $this->matches['combined'], PREG_SET_ORDER);
// Go through the matches, and get the most relevant matches // Go through the matches, and get the most relevant matches
$this->matches = array_map([$this, 'filter_array'], $this->matches); $this->matches = array_map([$this, 'filterArray'], $this->matches);
return $this->matches; return $this->matches;
} }
// --------------------------------------------------------------------------
/** /**
* Compiles a join condition after parsing * Compiles a join condition after parsing
* *
* @param string $condition * @param string $condition
* @return string * @return string
*/ */
public function compile_join($condition) public function compileJoin(string $condition): string
{ {
$parts = $this->parse_join($condition); $parts = $this->parseJoin($condition);
$count = count($parts['identifiers']); $count = count($parts['identifiers']);
// Go through and quote the identifiers // Go through and quote the identifiers
@ -110,33 +100,28 @@ class QueryParser {
{ {
if (in_array($parts['combined'][$i], $parts['identifiers']) && ! is_numeric($parts['combined'][$i])) if (in_array($parts['combined'][$i], $parts['identifiers']) && ! is_numeric($parts['combined'][$i]))
{ {
$parts['combined'][$i] = $this->db->quote_ident($parts['combined'][$i]); $parts['combined'][$i] = $this->db->quoteIdent($parts['combined'][$i]);
} }
} }
return implode('', $parts['combined']); return implode('', $parts['combined']);
} }
// --------------------------------------------------------------------------
/** /**
* Returns a more useful match array * Returns a more useful match array
* *
* @param array $array * @param array $array
* @return array * @return array
*/ */
protected function filter_array($array) protected function filterArray(array $array): array
{ {
$new_array = []; $newArray = [];
foreach($array as $row) foreach($array as $row)
{ {
$new_array[] = (is_array($row)) ? $row[0] : $row; $newArray[] = (is_array($row)) ? $row[0] : $row;
} }
return $new_array; return $newArray;
} }
} }
// End of QueryParser.php

View File

@ -51,37 +51,14 @@ if ( ! function_exists('db_filter'))
*/ */
function db_filter(array $array, $index): array function db_filter(array $array, $index): array
{ {
$new_array = []; $newArray = [];
foreach($array as $a) foreach($array as $a)
{ {
$new_array[] = $a[$index]; $newArray[] = $a[$index];
} }
return $new_array; return $newArray;
}
}
// --------------------------------------------------------------------------
if ( ! function_exists('from_camel_case'))
{
/**
* Create a snake_case string from camelCase
*
* @see http://stackoverflow.com/questions/1993721/how-to-convert-camelcase-to-camel-case
*
* @param string $input
* @return string
*/
function from_camel_case(string $input): string
{
preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
$ret = $matches[0];
foreach ($ret as &$match) {
$match = strtolower($match);
}
return implode('_', $ret);
} }
} }
@ -90,12 +67,12 @@ if ( ! function_exists('to_camel_case'))
/** /**
* Create a camelCase string from snake_case * Create a camelCase string from snake_case
* *
* @param string $snake_case * @param string $snakeCase
* @return string * @return string
*/ */
function to_camel_case(string $snake_case): string function to_camel_case(string $snakeCase): string
{ {
$pieces = explode('_', $snake_case); $pieces = explode('_', $snakeCase);
$pieces[0] = mb_strtolower($pieces[0]); $pieces[0] = mb_strtolower($pieces[0]);
for($i = 1; $i < count($pieces); $i++) for($i = 1; $i < count($pieces); $i++)
@ -114,17 +91,17 @@ if ( ! function_exists('array_zipper'))
/** /**
* Zip a set of arrays together on common keys * Zip a set of arrays together on common keys
* *
* The $zipper_input array is an array of arrays indexed by their place in the output * The $zipperInput array is an array of arrays indexed by their place in the output
* array. * array.
* *
* @param array $zipper_input * @param array $zipperInput
* @return array * @return array
*/ */
function array_zipper(array $zipper_input): array function array_zipper(array $zipperInput): array
{ {
$output = []; $output = [];
foreach($zipper_input as $append_key => $values) foreach($zipperInput as $appendKey => $values)
{ {
foreach($values as $index => $value) foreach($values as $index => $value)
{ {
@ -132,7 +109,7 @@ if ( ! function_exists('array_zipper'))
{ {
$output[$index] = []; $output[$index] = [];
} }
$output[$index][$append_key] = $value; $output[$index][$appendKey] = $value;
} }
} }
@ -188,19 +165,19 @@ if ( ! function_exists('Query'))
*/ */
function Query($params = '') function Query($params = '')
{ {
$manager = ConnectionManager::get_instance(); $manager = ConnectionManager::getInstance();
// If you are getting a previously created connection // If you are getting a previously created connection
if (is_scalar($params)) if (is_scalar($params))
{ {
return $manager->get_connection($params); return $manager->getConnection($params);
} }
elseif ( ! is_scalar($params) && ! is_null($params)) elseif ( ! is_scalar($params) && ! is_null($params))
{ {
$params_object = (object) $params; $paramsObject = (object) $params;
// Otherwise, return a new connection // Otherwise, return a new connection
return $manager->connect($params_object); return $manager->connect($paramsObject);
} }
return NULL; return NULL;

View File

@ -30,13 +30,13 @@ require_once(QBASE_DIR . 'vendor/autoload.php');
*/ */
if ( ! defined('IS_QUERCUS')) if ( ! defined('IS_QUERCUS'))
{ {
if ( ! isset($_SERVER_SOFTWARE)) if ( ! isset($_sERVERSOFTWARE))
{ {
define('IS_QUERCUS', FALSE); define('IS_QUERCUS', FALSE);
} }
else else
{ {
$test = strpos($_SERVER["SERVER_SOFTWARE"],'Quercus') !== FALSE; $test = strpos($_sERVER["SERVER_SOFTWARE"],'Quercus') !== FALSE;
define('IS_QUERCUS', $test); define('IS_QUERCUS', $test);
unset($test); unset($test);
} }
@ -106,9 +106,9 @@ class Query_TestCase extends TestCase {
{ {
$temp = $first; $temp = $first;
$first = uniqid("test"); $first = uniqid("test");
$is_ref = ($first === $second); $isRef = ($first === $second);
$first = $temp; $first = $temp;
$res = $is_ref; $res = $isRef;
} }
$this->assertTrue($res, $message); $this->assertTrue($res, $message);
} }

View File

@ -36,7 +36,7 @@ abstract class DBTest extends Query_TestCase {
public function testGetTables() public function testGetTables()
{ {
$tables = self::$db->get_tables(); $tables = self::$db->getTables();
$this->assertTrue(is_array($tables)); $this->assertTrue(is_array($tables));
$this->assertTrue( ! empty($tables)); $this->assertTrue( ! empty($tables));
} }
@ -45,7 +45,7 @@ abstract class DBTest extends Query_TestCase {
public function testGetSystemTables() public function testGetSystemTables()
{ {
$tables = self::$db->get_system_tables(); $tables = self::$db->getSystemTables();
$this->assertTrue(is_array($tables)); $this->assertTrue(is_array($tables));
$this->assertTrue( ! empty($tables)); $this->assertTrue( ! empty($tables));
} }
@ -54,15 +54,15 @@ abstract class DBTest extends Query_TestCase {
public function testBackupData() public function testBackupData()
{ {
$this->assertTrue(is_string(self::$db->get_util()->backup_data(array('create_delete', FALSE)))); $this->assertTrue(is_string(self::$db->getUtil()->backupData(array('create_delete', FALSE))));
$this->assertTrue(is_string(self::$db->get_util()->backup_data(array('create_delete', TRUE)))); $this->assertTrue(is_string(self::$db->getUtil()->backupData(array('create_delete', TRUE))));
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
public function testGetColumns() public function testGetColumns()
{ {
$cols = self::$db->get_columns('test'); $cols = self::$db->getColumns('test');
$this->assertTrue(is_array($cols)); $this->assertTrue(is_array($cols));
$this->assertTrue( ! empty($cols)); $this->assertTrue( ! empty($cols));
} }
@ -71,7 +71,7 @@ abstract class DBTest extends Query_TestCase {
public function testGetTypes() public function testGetTypes()
{ {
$types = self::$db->get_types(); $types = self::$db->getTypes();
$this->assertTrue(is_array($types)); $this->assertTrue(is_array($types));
$this->assertTrue( ! empty($types)); $this->assertTrue( ! empty($types));
} }
@ -88,7 +88,7 @@ abstract class DBTest extends Query_TestCase {
'delete' => 'CASCADE' 'delete' => 'CASCADE'
)); ));
$keys = self::$db->get_fks('testconstraints2'); $keys = self::$db->getFks('testconstraints2');
$this->assertEqual($expected, $keys); $this->assertEqual($expected, $keys);
} }
@ -96,7 +96,7 @@ abstract class DBTest extends Query_TestCase {
public function testGetIndexes() public function testGetIndexes()
{ {
$keys = self::$db->get_indexes('test'); $keys = self::$db->getIndexes('test');
$this->assertTrue(is_array($keys)); $this->assertTrue(is_array($keys));
} }
@ -104,7 +104,7 @@ abstract class DBTest extends Query_TestCase {
public function testGetViews() public function testGetViews()
{ {
$views = self::$db->get_views(); $views = self::$db->getViews();
$expected = array('numbersview', 'testview'); $expected = array('numbersview', 'testview');
$this->assertEqual($expected, array_values($views)); $this->assertEqual($expected, array_values($views));
$this->assertTrue(is_array($views)); $this->assertTrue(is_array($views));
@ -116,7 +116,7 @@ abstract class DBTest extends Query_TestCase {
{ {
// @TODO standardize trigger output for different databases // @TODO standardize trigger output for different databases
$triggers = self::$db->get_triggers(); $triggers = self::$db->getTriggers();
$this->assertTrue(is_array($triggers)); $this->assertTrue(is_array($triggers));
} }
@ -124,7 +124,7 @@ abstract class DBTest extends Query_TestCase {
public function testGetSequences() public function testGetSequences()
{ {
$seqs = self::$db->get_sequences(); $seqs = self::$db->getSequences();
// Normalize sequence names // Normalize sequence names
$seqs = array_map('strtolower', $seqs); $seqs = array_map('strtolower', $seqs);
@ -139,7 +139,7 @@ abstract class DBTest extends Query_TestCase {
public function testGetProcedures() public function testGetProcedures()
{ {
$procedures = self::$db->get_procedures(); $procedures = self::$db->getProcedures();
$this->assertTrue(is_array($procedures)); $this->assertTrue(is_array($procedures));
} }
@ -147,7 +147,7 @@ abstract class DBTest extends Query_TestCase {
public function testGetFunctions() public function testGetFunctions()
{ {
$funcs = self::$db->get_functions(); $funcs = self::$db->getFunctions();
$this->assertTrue(is_array($funcs)); $this->assertTrue(is_array($funcs));
} }
} }

View File

@ -13,8 +13,6 @@
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
// --------------------------------------------------------------------------
/** /**
* Query builder parent test class * Query builder parent test class
*/ */
@ -34,26 +32,23 @@ abstract class QBTest extends Query_TestCase {
{ {
self::$db = NULL; self::$db = NULL;
} }
// ! Driver-specific results // ! Driver-specific results
abstract public function testQueryExplain(); abstract public function testQueryExplain();
// ! Get tests // ! Get tests
public function testInvalidConnectionName() public function testInvalidConnectionName()
{ {
try $this->expectException('InvalidArgumentException');
{
$db = Query('foo'); $db = Query('foo');
}
catch (InvalidArgumentException $e)
{
$this->assertIsA($e, 'InvalidArgumentException');
}
} }
public function testFunctionGet() public function testFunctionGet()
{ {
$query = self::$db->select('id, COUNT(id) as count') $query = self::$db->select('id, COUNT(id) as count')
->from('test') ->from('test')
->group_by('id') ->groupBy('id')
->get(); ->get();
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
@ -78,7 +73,7 @@ abstract class QBTest extends Query_TestCase {
$query = self::$db->get('test'); $query = self::$db->get('test');
$numrows = count($query->fetchAll(PDO::FETCH_NUM)); $numrows = count($query->fetchAll(PDO::FETCH_NUM));
$this->assertEqual(self::$db->num_rows(), $numrows); $this->assertEqual(self::$db->numRows(), $numrows);
} }
public function testGetLimit() public function testGetLimit()
@ -97,7 +92,7 @@ abstract class QBTest extends Query_TestCase {
public function testGetWhere() public function testGetWhere()
{ {
$query = self::$db->get_where('test', array('id !=' => 1), 2, 1); $query = self::$db->getWhere('test', array('id !=' => 1), 2, 1);
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
} }
@ -106,7 +101,7 @@ abstract class QBTest extends Query_TestCase {
{ {
$query = self::$db->select('id') $query = self::$db->select('id')
->from('test') ->from('test')
->group_by('id') ->groupBy('id')
->having(array('id >' => 1)) ->having(array('id >' => 1))
->having('id !=', 3) ->having('id !=', 3)
->get(); ->get();
@ -118,9 +113,9 @@ abstract class QBTest extends Query_TestCase {
{ {
$query = self::$db->select('id') $query = self::$db->select('id')
->from('test') ->from('test')
->group_by('id') ->groupBy('id')
->having(array('id >' => 1)) ->having(array('id >' => 1))
->or_having('id !=', 3) ->orHaving('id !=', 3)
->get(); ->get();
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
@ -138,7 +133,7 @@ abstract class QBTest extends Query_TestCase {
public function testSelectAvg() public function testSelectAvg()
{ {
$query = self::$db->select_avg('id', 'di') $query = self::$db->selectAvg('id', 'di')
->get('test'); ->get('test');
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
@ -146,7 +141,7 @@ abstract class QBTest extends Query_TestCase {
public function testSelectSum() public function testSelectSum()
{ {
$query = self::$db->select_sum('id', 'di') $query = self::$db->selectSum('id', 'di')
->get('test'); ->get('test');
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
@ -154,7 +149,7 @@ abstract class QBTest extends Query_TestCase {
public function testSelectDistinct() public function testSelectDistinct()
{ {
$query = self::$db->select_sum('id', 'di') $query = self::$db->selectSum('id', 'di')
->distinct() ->distinct()
->get('test'); ->get('test');
@ -190,7 +185,6 @@ abstract class QBTest extends Query_TestCase {
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
} }
public function testSelectWhereGet2() public function testSelectWhereGet2()
{ {
$query = self::$db->select('id, key as k, val') $query = self::$db->select('id, key as k, val')
@ -202,7 +196,7 @@ abstract class QBTest extends Query_TestCase {
public function testSelectMax() public function testSelectMax()
{ {
$query = self::$db->select_max('id', 'di') $query = self::$db->selectMax('id', 'di')
->get('test'); ->get('test');
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
@ -210,7 +204,7 @@ abstract class QBTest extends Query_TestCase {
public function testSelectMin() public function testSelectMin()
{ {
$query = self::$db->select_min('id', 'di') $query = self::$db->selectMin('id', 'di')
->get('test'); ->get('test');
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
@ -219,7 +213,7 @@ abstract class QBTest extends Query_TestCase {
public function testMultiOrderBy() public function testMultiOrderBy()
{ {
$query = self::$db->from('test') $query = self::$db->from('test')
->order_by('id, key') ->orderBy('id, key')
->get(); ->get();
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
@ -229,10 +223,10 @@ abstract class QBTest extends Query_TestCase {
{ {
$query = self::$db->select('id, key as k, val') $query = self::$db->select('id, key as k, val')
->from('test') ->from('test')
->group_start() ->groupStart()
->where('id >', 1) ->where('id >', 1)
->where('id <', 900) ->where('id <', 900)
->group_end() ->groupEnd()
->limit(2, 1) ->limit(2, 1)
->get(); ->get();
@ -243,13 +237,13 @@ abstract class QBTest extends Query_TestCase {
{ {
$query = self::$db->select('id, key as k, val') $query = self::$db->select('id, key as k, val')
->from('test') ->from('test')
->group_start() ->groupStart()
->where('id >', 1) ->where('id >', 1)
->where('id <', 900) ->where('id <', 900)
->group_end() ->groupEnd()
->or_group_start() ->orGroupStart()
->where('id =', 0) ->where('id =', 0)
->group_end() ->groupEnd()
->limit(2, 1) ->limit(2, 1)
->get(); ->get();
@ -260,13 +254,13 @@ abstract class QBTest extends Query_TestCase {
{ {
$query = self::$db->select('id, key as k, val') $query = self::$db->select('id, key as k, val')
->from('test') ->from('test')
->group_start() ->groupStart()
->where('id >', 1) ->where('id >', 1)
->where('id <', 900) ->where('id <', 900)
->group_end() ->groupEnd()
->or_not_group_start() ->orNotGroupStart()
->where('id =', 0) ->where('id =', 0)
->group_end() ->groupEnd()
->limit(2, 1) ->limit(2, 1)
->get(); ->get();
@ -277,13 +271,13 @@ abstract class QBTest extends Query_TestCase {
{ {
$query = self::$db->select('id, key as k, val') $query = self::$db->select('id, key as k, val')
->from('test') ->from('test')
->group_start() ->groupStart()
->where('id >', 1) ->where('id >', 1)
->where('id <', 900) ->where('id <', 900)
->group_end() ->groupEnd()
->not_group_start() ->notGroupStart()
->where('id =', 0) ->where('id =', 0)
->group_end() ->groupEnd()
->limit(2, 1) ->limit(2, 1)
->get(); ->get();
@ -294,9 +288,9 @@ abstract class QBTest extends Query_TestCase {
{ {
$query = self::$db->select('id, key as k, val') $query = self::$db->select('id, key as k, val')
->from('test') ->from('test')
->not_group_start() ->notGroupStart()
->where('id =', 0) ->where('id =', 0)
->group_end() ->groupEnd()
->limit(2, 1) ->limit(2, 1)
->get(); ->get();
@ -323,7 +317,7 @@ abstract class QBTest extends Query_TestCase {
public function testWhereIn() public function testWhereIn()
{ {
$query = self::$db->from('test') $query = self::$db->from('test')
->where_in('id', array(0, 6, 56, 563, 341)) ->whereIn('id', array(0, 6, 56, 563, 341))
->get(); ->get();
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
@ -333,7 +327,7 @@ abstract class QBTest extends Query_TestCase {
{ {
$query = self::$db->from('test') $query = self::$db->from('test')
->where('key', 'false') ->where('key', 'false')
->or_where_in('id', array(0, 6, 56, 563, 341)) ->orWhereIn('id', array(0, 6, 56, 563, 341))
->get(); ->get();
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
@ -343,7 +337,7 @@ abstract class QBTest extends Query_TestCase {
{ {
$query = self::$db->from('test') $query = self::$db->from('test')
->where('key', 'false') ->where('key', 'false')
->where_not_in('id', array(0, 6, 56, 563, 341)) ->whereNotIn('id', array(0, 6, 56, 563, 341))
->get(); ->get();
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
@ -353,7 +347,7 @@ abstract class QBTest extends Query_TestCase {
{ {
$query = self::$db->from('test') $query = self::$db->from('test')
->where('key', 'false') ->where('key', 'false')
->or_where_not_in('id', array(0, 6, 56, 563, 341)) ->orWhereNotIn('id', array(0, 6, 56, 563, 341))
->get(); ->get();
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
@ -365,8 +359,8 @@ abstract class QBTest extends Query_TestCase {
->from('test') ->from('test')
->where('id >', 0) ->where('id >', 0)
->where('id <', 9000) ->where('id <', 9000)
->order_by('id', 'DESC') ->orderBy('id', 'DESC')
->order_by('k', 'ASC') ->orderBy('k', 'ASC')
->limit(5,2) ->limit(5,2)
->get(); ->get();
@ -379,7 +373,7 @@ abstract class QBTest extends Query_TestCase {
->from('test') ->from('test')
->where('id >', 0) ->where('id >', 0)
->where('id <', 9000) ->where('id <', 9000)
->order_by('id', 'rand') ->orderBy('id', 'rand')
->limit(5,2) ->limit(5,2)
->get(); ->get();
@ -392,10 +386,10 @@ abstract class QBTest extends Query_TestCase {
->from('test') ->from('test')
->where('id >', 0) ->where('id >', 0)
->where('id <', 9000) ->where('id <', 9000)
->group_by('k') ->groupBy('k')
->group_by(array('id','val')) ->groupBy(array('id','val'))
->order_by('id', 'DESC') ->orderBy('id', 'DESC')
->order_by('k', 'ASC') ->orderBy('k', 'ASC')
->limit(5,2) ->limit(5,2)
->get(); ->get();
@ -409,7 +403,7 @@ abstract class QBTest extends Query_TestCase {
$query = self::$db->select('id, key as k, val') $query = self::$db->select('id, key as k, val')
->from('test') ->from('test')
->where(' id ', 1) ->where(' id ', 1)
->or_where('key >', 0) ->orWhere('key >', 0)
->limit(2, 1) ->limit(2, 1)
->get(); ->get();
@ -429,7 +423,7 @@ abstract class QBTest extends Query_TestCase {
{ {
$query = self::$db->from('test') $query = self::$db->from('test')
->like('key', 'og') ->like('key', 'og')
->or_like('key', 'val') ->orLike('key', 'val')
->get(); ->get();
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
@ -439,7 +433,7 @@ abstract class QBTest extends Query_TestCase {
{ {
$query = self::$db->from('test') $query = self::$db->from('test')
->like('key', 'og', 'before') ->like('key', 'og', 'before')
->or_not_like('key', 'val') ->orNotLike('key', 'val')
->get(); ->get();
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
@ -449,7 +443,7 @@ abstract class QBTest extends Query_TestCase {
{ {
$query = self::$db->from('test') $query = self::$db->from('test')
->like('key', 'og', 'before') ->like('key', 'og', 'before')
->not_like('key', 'val') ->notLike('key', 'val')
->get(); ->get();
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
@ -512,6 +506,7 @@ abstract class QBTest extends Query_TestCase {
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
} }
// ! DB update tests // ! DB update tests
public function testInsert() public function testInsert()
{ {
@ -554,7 +549,7 @@ abstract class QBTest extends Query_TestCase {
), ),
); );
$query = self::$db->insert_batch('test', $data); $query = self::$db->insertBatch('test', $data);
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
} }
@ -613,17 +608,18 @@ abstract class QBTest extends Query_TestCase {
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
} }
// ! Non-data read queries // ! Non-data read queries
public function testCountAll() public function testCountAll()
{ {
$query = self::$db->count_all('test'); $query = self::$db->countAll('test');
$this->assertTrue(is_numeric($query)); $this->assertTrue(is_numeric($query));
} }
public function testCountAllResults() public function testCountAllResults()
{ {
$query = self::$db->count_all_results('test'); $query = self::$db->countAllResults('test');
$this->assertTrue(is_numeric($query)); $this->assertTrue(is_numeric($query));
} }
@ -633,29 +629,29 @@ abstract class QBTest extends Query_TestCase {
$query = self::$db->select('id, key as k, val') $query = self::$db->select('id, key as k, val')
->from('test') ->from('test')
->where(' id ', 1) ->where(' id ', 1)
->or_where('key >', 0) ->orWhere('key >', 0)
->limit(2, 1) ->limit(2, 1)
->count_all_results(); ->countAllResults();
$this->assertTrue(is_numeric($query)); $this->assertTrue(is_numeric($query));
} }
public function testNumRows() public function testNumRows()
{ {
$query = self::$db->get('test'); self::$db->get('test');
$this->assertTrue(is_numeric(self::$db->numRows()));
$this->assertTrue(is_numeric(self::$db->num_rows()));
} }
// ! Compiled Query tests // ! Compiled Query tests
public function testGetCompiledSelect() public function testGetCompiledSelect()
{ {
$sql = self::$db->get_compiled_select('test'); $sql = self::$db->getCompiledSelect('test');
$qb_res = self::$db->get('test'); $qbRes = self::$db->get('test');
$sql_res = self::$db->query($sql); $sqlRes = self::$db->query($sql);
$this->assertIsA($qb_res,'PDOStatement', "Query Builder Result is a PDO Statement"); $this->assertIsA($qbRes,'PDOStatement', "Query Builder Result is a PDO Statement");
$this->assertIsA($sql_res, 'PDOStatement', "SQL Result is a PDO Statement"); $this->assertIsA($sqlRes, 'PDOStatement', "SQL Result is a PDO Statement");
//$this->assertEquals($qb_res, $sql_res); //$this->assertEquals($qbRes, $sqlRes);
} }
public function testGetCompiledUpdate() public function testGetCompiledUpdate()
@ -664,7 +660,7 @@ abstract class QBTest extends Query_TestCase {
'id' => 4, 'id' => 4,
'key' => 'foo', 'key' => 'foo',
'val' => 'baz' 'val' => 'baz'
))->get_compiled_update('test'); ))->getCompiledUpdate('test');
$this->assertTrue(is_string($sql)); $this->assertTrue(is_string($sql));
} }
@ -675,7 +671,7 @@ abstract class QBTest extends Query_TestCase {
'id' => 4, 'id' => 4,
'key' => 'foo', 'key' => 'foo',
'val' => 'baz' 'val' => 'baz'
))->get_compiled_insert('test'); ))->getCompiledInsert('test');
$this->assertTrue(is_string($sql)); $this->assertTrue(is_string($sql));
} }
@ -683,7 +679,7 @@ abstract class QBTest extends Query_TestCase {
public function testGetCompiledDelete() public function testGetCompiledDelete()
{ {
$sql = self::$db->where('id', 4) $sql = self::$db->where('id', 4)
->get_compiled_delete('test'); ->getCompiledDelete('test');
$this->assertTrue(is_string($sql)); $this->assertTrue(is_string($sql));
} }
@ -702,26 +698,16 @@ abstract class QBTest extends Query_TestCase {
'type' => 'QGYFHGEG' 'type' => 'QGYFHGEG'
); );
try $this->expectException('Query\BadDBDriverException');
{
self::$db = Query($params); self::$db = Query($params);
}
catch(\Query\BadDBDriverException $e)
{
$this->assertInstanceOf('\\Query\\BadDBDriverException', $e);
}
} }
public function testBadMethod() public function testBadMethod()
{ {
try $this->expectException('BadMethodCallException');
{
self::$db->foo(); self::$db->foo();
}
catch(BadMethodCallException $e)
{
$this->assertInstanceOf('BadMethodCallException', $e);
}
} }
public function testBadNumRows() public function testBadNumRows()
@ -732,9 +718,7 @@ abstract class QBTest extends Query_TestCase {
'val' => 'sale' 'val' => 'sale'
))->insert('test'); ))->insert('test');
$res = self::$db->num_rows(); $res = self::$db->numRows();
$this->assertEqual(NULL, $res); $this->assertEqual(NULL, $res);
} }
} }
// End of db_qb_test.php

View File

@ -20,7 +20,7 @@ class Connection_Manager_Test extends Query_TestCase {
public static function setUpBeforeClass() public static function setUpBeforeClass()
{ {
self::$instance = Query\ConnectionManager::get_instance(); self::$instance = Query\ConnectionManager::getInstance();
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -70,7 +70,7 @@ class Connection_Manager_Test extends Query_TestCase {
array('foo' => 'bar') array('foo' => 'bar')
); );
$this->assertEqual($expected, self::$instance->parse_params($params)); $this->assertEqual($expected, self::$instance->parseParams($params));
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -91,7 +91,7 @@ class Connection_Manager_Test extends Query_TestCase {
// Check that the connection just made is returned from the get_connection method // Check that the connection just made is returned from the get_connection method
$this->assertEqual($conn, self::$instance->get_connection()); $this->assertEqual($conn, self::$instance->getConnection());
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -111,7 +111,7 @@ class Connection_Manager_Test extends Query_TestCase {
$conn = self::$instance->connect($params); $conn = self::$instance->connect($params);
$this->assertInstanceOf('Query\\QueryBuilder', $conn); $this->assertInstanceOf('Query\\QueryBuilder', $conn);
$this->assertEqual($conn, self::$instance->get_connection('conn_manager')); $this->assertEqual($conn, self::$instance->getConnection('conn_manager'));
} }
} }
// End of connection_manager_test.php // End of connection_manager_test.php

View File

@ -59,8 +59,8 @@ class CoreTest extends Query_TestCase {
$drivers = PDO::getAvailableDrivers(); $drivers = PDO::getAvailableDrivers();
$num_supported = count(array_intersect($drivers, $supported)); $numSupported = count(array_intersect($drivers, $supported));
$this->assertTrue($num_supported > 0); $this->assertTrue($numSupported > 0);
} }
} }

View File

@ -27,9 +27,9 @@ class Query_Parser_Test extends Query_TestCase {
$this->parser = new Query\QueryParser($db); $this->parser = new Query\QueryParser($db);
} }
public function TestGeneric() public function testGeneric()
{ {
$matches = $this->parser->parse_join('table1.field1=table2.field2'); $matches = $this->parser->parseJoin('table1.field1=table2.field2');
$this->assertEqual($matches['combined'], array( $this->assertEqual($matches['combined'], array(
'table1.field1', '=', 'table2.field2' 'table1.field1', '=', 'table2.field2'
)); ));
@ -37,7 +37,7 @@ class Query_Parser_Test extends Query_TestCase {
public function testGeneric2() public function testGeneric2()
{ {
$matches = $this->parser->parse_join('db1.table1.field1!=db2.table2.field2'); $matches = $this->parser->parseJoin('db1.table1.field1!=db2.table2.field2');
$this->assertEqual($matches['combined'], array( $this->assertEqual($matches['combined'], array(
'db1.table1.field1','!=','db2.table2.field2' 'db1.table1.field1','!=','db2.table2.field2'
)); ));
@ -45,7 +45,7 @@ class Query_Parser_Test extends Query_TestCase {
public function testWUnderscore() public function testWUnderscore()
{ {
$matches = $this->parser->parse_join('table_1.field1 = tab_le2.field_2'); $matches = $this->parser->parseJoin('table_1.field1 = tab_le2.field_2');
$this->assertEqual($matches['combined'], array( $this->assertEqual($matches['combined'], array(
'table_1.field1', '=', 'tab_le2.field_2' 'table_1.field1', '=', 'tab_le2.field_2'
)); ));
@ -53,7 +53,7 @@ class Query_Parser_Test extends Query_TestCase {
public function testFunction() public function testFunction()
{ {
$matches = $this->parser->parse_join('table1.field1 > SUM(3+5)'); $matches = $this->parser->parseJoin('table1.field1 > SUM(3+5)');
$this->assertEqual($matches['combined'], array( $this->assertEqual($matches['combined'], array(
'table1.field1', '>', 'SUM(3+5)' 'table1.field1', '>', 'SUM(3+5)'
)); ));

View File

@ -84,17 +84,17 @@ class FirebirdQBTest extends QBTest {
$params->user = 'sysdba'; $params->user = 'sysdba';
$params->pass = 'masterkey'; $params->pass = 'masterkey';
$params->prefix = ''; $params->prefix = '';
$f_conn = Query($params); $fConn = Query($params);
$q_conn = Query('wood'); $qConn = Query('wood');
$this->assertReference($f_conn, $q_conn); $this->assertReference($fConn, $qConn);
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
public function testTypeList() public function testTypeList()
{ {
$sql = self::$db->sql->type_list(); $sql = self::$db->sql->typeList();
$query = self::$db->query($sql); $query = self::$db->query($sql);
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
@ -113,13 +113,13 @@ class FirebirdQBTest extends QBTest {
->where('id >', 1) ->where('id >', 1)
->where('id <', 900) ->where('id <', 900)
->limit(2, 1) ->limit(2, 1)
->get_compiled_select(); ->getCompiledSelect();
$res2 = self::$db->select('id, key as k, val') $res2 = self::$db->select('id, key as k, val')
->where('id >', 1) ->where('id >', 1)
->where('id <', 900) ->where('id <', 900)
->limit(2, 1) ->limit(2, 1)
->get_compiled_select(); ->getCompiledSelect();
// Queries are equal because explain is not a keyword in Firebird // Queries are equal because explain is not a keyword in Firebird
$this->assertEqual($res, $res2); $this->assertEqual($res, $res2);
@ -155,6 +155,6 @@ class FirebirdQBTest extends QBTest {
$existing = QTEST_DIR.QDS.'db_files'.QDS.'FB_TEST_DB.FDB'; $existing = QTEST_DIR.QDS.'db_files'.QDS.'FB_TEST_DB.FDB';
$backup = QTEST_DIR.QDS.'db_files'.QDS.'FB_TEST_BKP.FDB'; $backup = QTEST_DIR.QDS.'db_files'.QDS.'FB_TEST_BKP.FDB';
$this->assertTrue(self::$db->get_util()->backup_structure($existing, $backup)); $this->assertTrue(self::$db->getUtil()->backupStructure($existing, $backup));
} }
} }

View File

@ -32,7 +32,7 @@ class FirebirdTest extends DBtest {
// test the db driver directly // test the db driver directly
self::$db = new \Query\Drivers\Firebird\Driver('localhost:'.$dbpath); self::$db = new \Query\Drivers\Firebird\Driver('localhost:'.$dbpath);
self::$db->set_table_prefix('create_'); self::$db->setTablePrefix('create_');
} }
public function setUp() public function setUp()
@ -42,7 +42,7 @@ class FirebirdTest extends DBtest {
$this->markTestSkipped('Firebird extension does not exist'); $this->markTestSkipped('Firebird extension does not exist');
} }
$this->tables = self::$db->get_tables(); $this->tables = self::$db->getTables();
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -88,20 +88,20 @@ class FirebirdTest extends DBtest {
public function testGetSystemTables() public function testGetSystemTables()
{ {
$only_system = TRUE; $onlySystem = TRUE;
$tables = self::$db->get_system_tables(); $tables = self::$db->getSystemTables();
foreach($tables as $t) foreach($tables as $t)
{ {
if(stripos($t, 'rdb$') !== 0 && stripos($t, 'mon$') !== 0) if(stripos($t, 'rdb$') !== 0 && stripos($t, 'mon$') !== 0)
{ {
$only_system = FALSE; $onlySystem = FALSE;
break; break;
} }
} }
$this->assertTrue($only_system); $this->assertTrue($onlySystem);
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -111,7 +111,7 @@ class FirebirdTest extends DBtest {
public function testCreateTable() public function testCreateTable()
{ {
//Attempt to create the table //Attempt to create the table
$sql = self::$db->get_util()->create_table('create_delete', array( $sql = self::$db->getUtil()->createTable('create_delete', array(
'id' => 'SMALLINT', 'id' => 'SMALLINT',
'key' => 'VARCHAR(64)', 'key' => 'VARCHAR(64)',
'val' => 'BLOB SUB_TYPE TEXT' 'val' => 'BLOB SUB_TYPE TEXT'
@ -119,7 +119,7 @@ class FirebirdTest extends DBtest {
self::$db->query($sql); self::$db->query($sql);
//Check //Check
$this->assertTrue(in_array('create_delete', self::$db->get_tables())); $this->assertTrue(in_array('create_delete', self::$db->getTables()));
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -127,12 +127,12 @@ class FirebirdTest extends DBtest {
public function testDeleteTable() public function testDeleteTable()
{ {
//Attempt to delete the table //Attempt to delete the table
$sql = self::$db->get_util()->delete_table('create_delete'); $sql = self::$db->getUtil()->deleteTable('create_delete');
self::$db->query($sql); self::$db->query($sql);
//Check //Check
$table_exists = in_array('create_delete', self::$db->get_tables()); $tableExists = in_array('create_delete', self::$db->getTables());
$this->assertFalse($table_exists); $this->assertFalse($tableExists);
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -141,7 +141,7 @@ class FirebirdTest extends DBtest {
{ {
self::$db->truncate('create_test'); self::$db->truncate('create_test');
$this->assertTrue(self::$db->affected_rows() > 0); $this->assertTrue(self::$db->affectedRows() > 0);
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -191,7 +191,7 @@ SQL;
INSERT INTO "create_test" ("id", "key", "val") INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?) VALUES (?,?,?)
SQL; SQL;
self::$db->prepare_execute($sql, array( self::$db->prepareExecute($sql, array(
2, "works", 'also?' 2, "works", 'also?'
)); ));
@ -221,7 +221,7 @@ SQL;
public function testPrepareQuery() public function testPrepareQuery()
{ {
$this->assertNull(self::$db->prepare_query('', array())); $this->assertNull(self::$db->prepareQuery('', array()));
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -251,7 +251,7 @@ SQL;
public function testDBList() public function testDBList()
{ {
$res = self::$db->get_sql()->db_list(); $res = self::$db->getSql()->dbList();
$this->assertNULL($res); $this->assertNULL($res);
} }

View File

@ -13,8 +13,7 @@
* @link https://git.timshomepage.net/aviat4ion/Query * @link https://git.timshomepage.net/aviat4ion/Query
*/ */
use Query\Drivers\Mysql\Driver;
// --------------------------------------------------------------------------
/** /**
* MySQLTest class. * MySQLTest class.
@ -29,19 +28,19 @@ class MySQLTest extends DBTest {
$params = get_json_config(); $params = get_json_config();
if (($var = getenv('TRAVIS'))) if (($var = getenv('TRAVIS')))
{ {
self::$db = new \Query\Drivers\Mysql\Driver('host=127.0.0.1;port=3306;dbname=test', 'root'); self::$db = new Driver('host=127.0.0.1;port=3306;dbname=test', 'root');
} }
// Attempt to connect, if there is a test config file // Attempt to connect, if there is a test config file
else if ($params !== FALSE) else if ($params !== FALSE)
{ {
$params = $params->mysql; $params = $params->mysql;
self::$db = new \Query\Drivers\Mysql\Driver("mysql:host={$params->host};dbname={$params->database}", $params->user, $params->pass, array( self::$db = new Driver("mysql:host={$params->host};dbname={$params->database}", $params->user, $params->pass, array(
PDO::ATTR_PERSISTENT => TRUE PDO::ATTR_PERSISTENT => TRUE
)); ));
} }
self::$db->set_table_prefix('create_'); self::$db->setTablePrefix('create_');
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -65,7 +64,7 @@ class MySQLTest extends DBTest {
self::$db->exec(file_get_contents(QTEST_DIR.'/db_files/mysql.sql')); self::$db->exec(file_get_contents(QTEST_DIR.'/db_files/mysql.sql'));
//Attempt to create the table //Attempt to create the table
$sql = self::$db->get_util()->create_table('test', $sql = self::$db->getUtil()->createTable('test',
array( array(
'id' => 'int(10)', 'id' => 'int(10)',
'key' => 'TEXT', 'key' => 'TEXT',
@ -79,7 +78,7 @@ class MySQLTest extends DBTest {
self::$db->query($sql); self::$db->query($sql);
//Attempt to create the table //Attempt to create the table
$sql = self::$db->get_util()->create_table('join', $sql = self::$db->getUtil()->createTable('join',
array( array(
'id' => 'int(10)', 'id' => 'int(10)',
'key' => 'TEXT', 'key' => 'TEXT',
@ -92,7 +91,7 @@ class MySQLTest extends DBTest {
self::$db->query($sql); self::$db->query($sql);
//Check //Check
$dbs = self::$db->get_tables(); $dbs = self::$db->getTables();
$this->assertTrue(in_array('create_test', $dbs)); $this->assertTrue(in_array('create_test', $dbs));
@ -114,7 +113,7 @@ class MySQLTest extends DBTest {
INSERT INTO `create_test` (`id`, `key`, `val`) INSERT INTO `create_test` (`id`, `key`, `val`)
VALUES (?,?,?) VALUES (?,?,?)
SQL; SQL;
$statement = self::$db->prepare_query($sql, array(1,"boogers", "Gross")); $statement = self::$db->prepareQuery($sql, array(1,"boogers", "Gross"));
$res = $statement->execute(); $res = $statement->execute();
@ -132,7 +131,7 @@ SQL;
SQL; SQL;
try try
{ {
$statement = self::$db->prepare_query($sql, 'foo'); $statement = self::$db->prepareQuery($sql, 'foo');
} }
catch(InvalidArgumentException $e) catch(InvalidArgumentException $e)
{ {
@ -149,7 +148,7 @@ SQL;
INSERT INTO `create_test` (`id`, `key`, `val`) INSERT INTO `create_test` (`id`, `key`, `val`)
VALUES (?,?,?) VALUES (?,?,?)
SQL; SQL;
$res = self::$db->prepare_execute($sql, array( $res = self::$db->prepareExecute($sql, array(
2, "works", 'also?' 2, "works", 'also?'
)); ));
@ -187,21 +186,21 @@ SQL;
public function testGetSchemas() public function testGetSchemas()
{ {
$this->assertNull(self::$db->get_schemas()); $this->assertNull(self::$db->getSchemas());
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
public function testGetSequences() public function testGetSequences()
{ {
$this->assertNull(self::$db->get_sequences()); $this->assertNull(self::$db->getSequences());
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
public function testBackup() public function testBackup()
{ {
$this->assertTrue(is_string(self::$db->get_util()->backup_structure())); $this->assertTrue(is_string(self::$db->getUtil()->backupStructure()));
} }

View File

@ -114,6 +114,6 @@ class PgSQLQBTest extends QBTest {
public function testBackupStructure() public function testBackupStructure()
{ {
$this->assertEquals('', self::$db->util->backup_structure()); $this->assertEquals('', self::$db->util->backupStructure());
} }
} }

View File

@ -51,7 +51,7 @@ class PgTest extends DBTest {
self::$db = new $class("pgsql:host={$params->host};dbname={$params->database};port=5432", $params->user, $params->pass); self::$db = new $class("pgsql:host={$params->host};dbname={$params->database};port=5432", $params->user, $params->pass);
} }
self::$db->set_table_prefix('create_'); self::$db->setTablePrefix('create_');
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -85,7 +85,7 @@ class PgTest extends DBTest {
//Attempt to create the table //Attempt to create the table
$sql = self::$db->get_util()->create_table('create_test', $sql = self::$db->getUtil()->createTable('create_test',
array( array(
'id' => 'integer', 'id' => 'integer',
'key' => 'TEXT', 'key' => 'TEXT',
@ -99,7 +99,7 @@ class PgTest extends DBTest {
self::$db->query($sql); self::$db->query($sql);
//Attempt to create the table //Attempt to create the table
$sql = self::$db->get_util()->create_table('create_join', $sql = self::$db->getUtil()->createTable('create_join',
array( array(
'id' => 'integer', 'id' => 'integer',
'key' => 'TEXT', 'key' => 'TEXT',
@ -118,7 +118,7 @@ class PgTest extends DBTest {
//$this->setUp(); //$this->setUp();
//Check //Check
$dbs = self::$db->get_tables(); $dbs = self::$db->getTables();
$this->assertTrue(in_array('create_test', $dbs)); $this->assertTrue(in_array('create_test', $dbs));
} }
@ -130,8 +130,8 @@ class PgTest extends DBTest {
self::$db->truncate('create_test'); self::$db->truncate('create_test');
self::$db->truncate('create_join'); self::$db->truncate('create_join');
$ct_query = self::$db->query('SELECT * FROM create_test'); $ctQuery = self::$db->query('SELECT * FROM create_test');
$cj_query = self::$db->query('SELECT * FROM create_join'); $cjQuery = self::$db->query('SELECT * FROM create_join');
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -142,7 +142,7 @@ class PgTest extends DBTest {
INSERT INTO "create_test" ("id", "key", "val") INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?) VALUES (?,?,?)
SQL; SQL;
$statement = self::$db->prepare_query($sql, array(1,"boogers", "Gross")); $statement = self::$db->prepareQuery($sql, array(1,"boogers", "Gross"));
$statement->execute(); $statement->execute();
@ -158,7 +158,7 @@ SQL;
SQL; SQL;
try try
{ {
$statement = self::$db->prepare_query($sql, 'foo'); $statement = self::$db->prepareQuery($sql, 'foo');
} }
catch(InvalidArgumentException $e) catch(InvalidArgumentException $e)
{ {
@ -177,7 +177,7 @@ SQL;
INSERT INTO "create_test" ("id", "key", "val") INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?) VALUES (?,?,?)
SQL; SQL;
self::$db->prepare_execute($sql, array( self::$db->prepareExecute($sql, array(
2, "works", 'also?' 2, "works", 'also?'
)); ));
@ -217,20 +217,20 @@ SQL;
public function testGetSchemas() public function testGetSchemas()
{ {
$this->assertTrue(is_array(self::$db->get_schemas())); $this->assertTrue(is_array(self::$db->getSchemas()));
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
public function testGetDBs() public function testGetDBs()
{ {
$this->assertTrue(is_array(self::$db->get_dbs())); $this->assertTrue(is_array(self::$db->getDbs()));
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
public function testGetFunctions() public function testGetFunctions()
{ {
$this->assertNull(self::$db->get_functions()); $this->assertNull(self::$db->getFunctions());
} }
} }

View File

@ -50,9 +50,9 @@
$res = $query->fetchAll(PDO::FETCH_ASSOC); $res = $query->fetchAll(PDO::FETCH_ASSOC);
$expected_possibilities = array(); $expectedPossibilities = array();
$expected_possibilities[] = array( $expectedPossibilities[] = array(
array( array(
'order' => '0', 'order' => '0',
'from' => '0', 'from' => '0',
@ -60,7 +60,7 @@
) )
); );
$expected_possibilities[] = array ( $expectedPossibilities[] = array (
array ( array (
'selectid' => '0', 'selectid' => '0',
'order' => '0', 'order' => '0',
@ -69,7 +69,7 @@
), ),
); );
$expected_possibilities[] = array ( $expectedPossibilities[] = array (
array ( array (
'selectid' => '0', 'selectid' => '0',
'order' => '0', 'order' => '0',
@ -78,7 +78,7 @@
), ),
); );
$expected_possibilities[] = array ( $expectedPossibilities[] = array (
array ( array (
'selectid' => '0', 'selectid' => '0',
'order' => '0', 'order' => '0',
@ -90,7 +90,7 @@
$passed = FALSE; $passed = FALSE;
// Check for a matching possibility // Check for a matching possibility
foreach($expected_possibilities as $ep) foreach($expectedPossibilities as $ep)
{ {
if ($res == $ep) if ($res == $ep)
{ {

View File

@ -38,7 +38,7 @@ class SQLiteTest extends DBTest {
); );
self::$db = Query($params); self::$db = Query($params);
self::$db->set_table_prefix('create_'); self::$db->setTablePrefix('create_');
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -50,7 +50,7 @@ class SQLiteTest extends DBTest {
self::$db->exec(file_get_contents(QTEST_DIR.'/db_files/sqlite.sql')); self::$db->exec(file_get_contents(QTEST_DIR.'/db_files/sqlite.sql'));
//Check //Check
$dbs = self::$db->get_tables(); $dbs = self::$db->getTables();
$this->assertTrue(in_array('TEST1', $dbs)); $this->assertTrue(in_array('TEST1', $dbs));
$this->assertTrue(in_array('TEST2', $dbs)); $this->assertTrue(in_array('TEST2', $dbs));
@ -65,9 +65,9 @@ class SQLiteTest extends DBTest {
/*public function testBackupData() /*public function testBackupData()
{ {
$sql = mb_trim(self::$db->get_util()->backup_data(array('create_join', 'create_test'))); $sql = mb_trim(self::$db->getUtil()->backupData(array('create_join', 'create_test')));
$sql_array = explode("\n", $sql); $sqlArray = explode("\n", $sql);
$expected = <<<SQL $expected = <<<SQL
INSERT INTO "create_test" ("id","key","val") VALUES (1,'boogers','Gross'); INSERT INTO "create_test" ("id","key","val") VALUES (1,'boogers','Gross');
@ -76,15 +76,15 @@ INSERT INTO "create_test" ("id","key","val") VALUES (10,12,14);
INSERT INTO "create_test" ("id","key","val") VALUES (587,1,2); INSERT INTO "create_test" ("id","key","val") VALUES (587,1,2);
INSERT INTO "create_test" ("id","key","val") VALUES (999,'''ring''','''sale'''); INSERT INTO "create_test" ("id","key","val") VALUES (999,'''ring''','''sale''');
SQL; SQL;
$expected_array = explode("\n", $expected); $expectedArray = explode("\n", $expected);
$this->assertEqual($expected_array, $sql_array); $this->assertEqual($expectedArray, $sqlArray);
}*/ }*/
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
public function testBackupStructure() public function testBackupStructure()
{ {
$sql = mb_trim(self::$db->get_util()->backup_structure()); $sql = mb_trim(self::$db->getUtil()->backupStructure());
$expected = <<<SQL $expected = <<<SQL
CREATE TABLE "create_test" ("id" INTEGER PRIMARY KEY, "key" TEXT, "val" TEXT); CREATE TABLE "create_test" ("id" INTEGER PRIMARY KEY, "key" TEXT, "val" TEXT);
CREATE TABLE "create_join" ("id" INTEGER PRIMARY KEY, "key" TEXT, "val" TEXT); CREATE TABLE "create_join" ("id" INTEGER PRIMARY KEY, "key" TEXT, "val" TEXT);
@ -150,22 +150,22 @@ CREATE TABLE "testconstraints2" (
; ;
SQL; SQL;
$expected_array = explode("\n", $expected); $expectedArray = explode("\n", $expected);
$result_array = explode("\n", $sql); $resultArray = explode("\n", $sql);
$this->assertEqual($expected_array, $result_array); $this->assertEqual($expectedArray, $resultArray);
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
public function testDeleteTable() public function testDeleteTable()
{ {
$sql = self::$db->get_util()->delete_table('create_delete'); $sql = self::$db->getUtil()->deleteTable('create_delete');
self::$db->query($sql); self::$db->query($sql);
//Check //Check
$dbs = self::$db->get_tables(); $dbs = self::$db->getTables();
$this->assertFalse(in_array('create_delete', $dbs)); $this->assertFalse(in_array('create_delete', $dbs));
} }
@ -200,7 +200,7 @@ SQL;
INSERT INTO "create_test" ("id", "key", "val") INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?) VALUES (?,?,?)
SQL; SQL;
$statement = self::$db->prepare_query($sql, array(1,"boogers", "Gross")); $statement = self::$db->prepareQuery($sql, array(1,"boogers", "Gross"));
$statement->execute(); $statement->execute();
@ -214,7 +214,7 @@ SQL;
INSERT INTO "create_test" ("id", "key", "val") INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?) VALUES (?,?,?)
SQL; SQL;
self::$db->prepare_execute($sql, array( self::$db->prepareExecute($sql, array(
2, "works", 'also?' 2, "works", 'also?'
)); ));
@ -260,14 +260,14 @@ SQL;
public function testGetDBs() public function testGetDBs()
{ {
$this->assertTrue(is_array(self::$db->get_dbs())); $this->assertTrue(is_array(self::$db->getDbs()));
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
public function testGetSchemas() public function testGetSchemas()
{ {
$this->assertNull(self::$db->get_schemas()); $this->assertNull(self::$db->getSchemas());
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -276,13 +276,13 @@ SQL;
public function testNullMethods() public function testNullMethods()
{ {
$sql = self::$db->sql->function_list(); $sql = self::$db->sql->functionList();
$this->assertEqual(NULL, $sql); $this->assertEqual(NULL, $sql);
$sql = self::$db->sql->procedure_list(); $sql = self::$db->sql->procedureList();
$this->assertEqual(NULL, $sql); $this->assertEqual(NULL, $sql);
$sql = self::$db->sql->sequence_list(); $sql = self::$db->sql->sequenceList();
$this->assertEqual(NULL, $sql); $this->assertEqual(NULL, $sql);
} }
@ -290,7 +290,7 @@ SQL;
public function testGetSystemTables() public function testGetSystemTables()
{ {
$sql = self::$db->get_system_tables(); $sql = self::$db->getSystemTables();
$this->assertTrue(is_array($sql)); $this->assertTrue(is_array($sql));
} }
@ -298,20 +298,20 @@ SQL;
public function testGetSequences() public function testGetSequences()
{ {
$this->assertNull(self::$db->get_sequences()); $this->assertNull(self::$db->getSequences());
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
public function testGetFunctions() public function testGetFunctions()
{ {
$this->assertNull(self::$db->get_functions()); $this->assertNull(self::$db->getFunctions());
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
public function testGetProcedures() public function testGetProcedures()
{ {
$this->assertNull(self::$db->get_procedures()); $this->assertNull(self::$db->getProcedures());
} }
} }

View File

@ -16,7 +16,7 @@
*/ */
if ( ! defined('IS_QUERCUS')) if ( ! defined('IS_QUERCUS'))
{ {
if ( ! isset($_SERVER_SOFTWARE)) if ( ! array_key_exists('SERVER_SOFTWARE', $_SERVER))
{ {
define('IS_QUERCUS', FALSE); define('IS_QUERCUS', FALSE);
} }
@ -147,7 +147,7 @@ define('QDS', DIRECTORY_SEPARATOR);
// Include db tests // Include db tests
// Load db classes based on capability // Load db classes based on capability
$test_path = QTEST_DIR.'/databases/'; $testPath = QTEST_DIR.'/databases/';
// Require base testing classes // Require base testing classes
require_once(QTEST_DIR . '/core/core_test.php'); require_once(QTEST_DIR . '/core/core_test.php');
@ -163,7 +163,7 @@ if (function_exists('fbird_connect'))
$drivers[] = 'interbase'; $drivers[] = 'interbase';
} }
$driver_test_map = array( $driverTestMap = array(
'MySQL' => in_array('mysql', $drivers), 'MySQL' => in_array('mysql', $drivers),
'SQLite' => in_array('sqlite', $drivers), 'SQLite' => in_array('sqlite', $drivers),
'PgSQL' => in_array('pgsql', $drivers), 'PgSQL' => in_array('pgsql', $drivers),
@ -172,11 +172,11 @@ $driver_test_map = array(
); );
// Determine which testcases to load // Determine which testcases to load
foreach($driver_test_map as $name => $do_load) foreach($driverTestMap as $name => $doLoad)
{ {
$path = $test_path . strtolower($name) . '/'; $path = $testPath . strtolower($name) . '/';
if ($do_load && (! IS_QUERCUS)) if ($doLoad && (! IS_QUERCUS))
{ {
require_once("{$path}{$name}Test.php"); require_once("{$path}{$name}Test.php");
require_once("{$path}{$name}QBTest.php"); require_once("{$path}{$name}QBTest.php");