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'))
{
// Does not support flag GLOB_BRACE

View File

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

View File

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

View File

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

View File

@ -13,7 +13,6 @@
* @link https://git.timshomepage.net/aviat4ion/Query
*/
namespace Query\Drivers;
use InvalidArgumentException;
@ -40,13 +39,13 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
* Start character to escape identifiers
* @var string
*/
protected $escape_char_open = '"';
protected $escapeCharOpen = '"';
/**
* End character to escape identifiers
* @var string
*/
protected $escape_char_close = '"';
protected $escapeCharClose = '"';
/**
* Reference to sql class
@ -64,19 +63,19 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
* Last query executed
* @var string
*/
protected $last_query = '';
protected $lastQuery = '';
/**
* Prefix to apply to table names
* @var string
*/
protected $table_prefix = '';
protected $tablePrefix = '';
/**
* Whether the driver supports 'TRUNCATE'
* @var boolean
*/
protected $has_truncate = TRUE;
protected $hasTruncate = TRUE;
/**
* PDO constructor wrapper
@ -84,40 +83,36 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
* @param string $dsn
* @param string $username
* @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
$driver_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
parent::__construct($dsn, $username, $password, $driver_options);
$driverOptions[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
parent::__construct($dsn, $username, $password, $driverOptions);
$this->_load_sub_classes();
$this->_loadSubClasses();
}
// --------------------------------------------------------------------------
/**
* Loads the subclasses for the driver
*
* @return void
*/
protected function _load_sub_classes()
protected function _loadSubClasses()
{
// Load the sql and util class for the driver
$this_class = get_class($this);
$ns_array = explode("\\", $this_class);
array_pop($ns_array);
$driver = array_pop($ns_array);
$sql_class = __NAMESPACE__ . "\\{$driver}\\SQL";
$util_class = __NAMESPACE__ . "\\{$driver}\\Util";
$thisClass = get_class($this);
$nsArray = explode("\\", $thisClass);
array_pop($nsArray);
$driver = array_pop($nsArray);
$sqlClass = __NAMESPACE__ . "\\{$driver}\\SQL";
$utilClass = __NAMESPACE__ . "\\{$driver}\\Util";
$this->sql = new $sql_class();
$this->util = new $util_class($this);
$this->sql = new $sqlClass();
$this->util = new $utilClass($this);
}
// --------------------------------------------------------------------------
/**
* Allow invoke to work on table object
*
@ -147,59 +142,51 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
*
* @return string
*/
public function get_last_query(): string
public function getLastQuery(): string
{
return $this->last_query;
return $this->lastQuery;
}
// --------------------------------------------------------------------------
/**
* Set the last query sql
*
* @param string $query_string
* @param string $queryString
* @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
*
* @return SQLInterface
*/
public function get_sql()
public function getSql(): SQLInterface
{
return $this->sql;
}
// --------------------------------------------------------------------------
/**
* Get the Util class for the current driver
*
* @return AbstractUtil
*/
public function get_util()
public function getUtil(): AbstractUtil
{
return $this->util;
}
// --------------------------------------------------------------------------
/**
* Set the common table name prefix
*
* @param string $prefix
* @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
* @throws InvalidArgumentException
*/
public function prepare_query($sql, $data)
public function prepareQuery($sql, $data)
{
// Prepare the sql, save the statement for easy access later
$this->statement = $this->prepare($sql);
@ -239,8 +226,6 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
return $this->statement;
}
// -------------------------------------------------------------------------
/**
* Create and execute a prepared statement with the provided parameters
*
@ -248,83 +233,75 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
* @param array $params
* @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();
return $this->statement;
}
// -------------------------------------------------------------------------
/**
* Returns number of rows affected by an INSERT, UPDATE, DELETE type query
*
* @return int
*/
public function affected_rows()
public function affectedRows()
{
// Return number of rows affected
return $this->statement->rowCount();
}
// --------------------------------------------------------------------------
/**
* Prefixes a table if it is not already prefixed
* @param string $table
* @return string
*/
public function prefix_table($table)
public function prefixTable($table)
{
// Add the prefix to the table name
// before quoting it
if ( ! empty($this->table_prefix))
if ( ! empty($this->tablePrefix))
{
// Split identifier by period, will split into:
// database.schema.table OR
// schema.table OR
// database.table OR
// table
$identifierifiers = explode('.', $table);
$segments = count($identifierifiers);
$identifiers = explode('.', $table);
$segments = count($identifiers);
// Quote the last item, and add the database prefix
$identifierifiers[$segments - 1] = $this->_prefix(end($identifierifiers));
$identifiers[$segments - 1] = $this->_prefix(end($identifiers));
// Rejoin
$table = implode('.', $identifierifiers);
$table = implode('.', $identifiers);
}
return $table;
}
// --------------------------------------------------------------------------
/**
* Quote database table name, and set prefix
*
* @param string $table
* @return string
*/
public function quote_table($table)
public function quoteTable($table)
{
$table = $this->prefix_table($table);
$table = $this->prefixTable($table);
// Finally, quote the table
return $this->quote_ident($table);
return $this->quoteIdent($table);
}
// --------------------------------------------------------------------------
/**
* Surrounds the string with the databases identifier escape characters
*
* @param mixed $identifier
* @return string
*/
public function quote_ident($identifier)
public function quoteIdent($identifier)
{
if (is_array($identifier))
{
@ -348,199 +325,171 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
// Fix functions
$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)
{
// Unquote the function
$raw = str_replace($f[0], $f[1], $raw);
// 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 schemas for databases that list them
*
* @return array
*/
public function get_schemas()
public function getSchemas()
{
return NULL;
}
// -------------------------------------------------------------------------
/**
* Return list of tables for the current database
*
* @return array
*/
public function get_tables()
public function getTables()
{
$tables = $this->driver_query('table_list');
$tables = $this->driverQuery('tableList');
natsort($tables);
return $tables;
}
// -------------------------------------------------------------------------
/**
* Return list of dbs for the current connection, if possible
*
* @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 array
*/
public function get_views()
public function getViews()
{
$views = $this->driver_query('view_list');
$views = $this->driverQuery('viewList');
sort($views);
return $views;
}
// -------------------------------------------------------------------------
/**
* Return list of sequences for the current database, if they exist
*
* @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 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 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 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
* the connection/database
*
* @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
*
* @param string $table
* @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
*
* @param string $table
* @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
*
* @param string $table
* @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
*
* @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
*
* @param string|array|null $query
* @param bool $filtered_index
* @param bool $filteredIndex
* @return array
*/
public function driver_query($query, $filtered_index=TRUE)
public function driverQuery($query, $filteredIndex=TRUE)
{
// Call the appropriate method, if it exists
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,
@ -553,26 +502,24 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
// Run the 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);
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
*
* @see http://us3.php.net/manual/en/pdostatement.rowcount.php#87110
* @return int|null
*/
public function num_rows()
public function numRows()
{
$regex = '/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/i';
$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]}");
return (int) $stmt->fetchColumn();
@ -581,8 +528,6 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
return NULL;
}
// --------------------------------------------------------------------------
/**
* Create sql for batch insert
*
@ -590,11 +535,11 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
* @param array|object $data
* @return null|array<string|array|null>
*/
public function insert_batch($table, $data=[])
public function insertBatch($table, $data=[])
{
$data = (array) $data;
$first_row = (array) current($data);
if (is_scalar($first_row))
$firstRow = (array) current($data);
if (is_scalar($firstRow))
{
return NULL;
}
@ -605,26 +550,24 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
{
$vals = array_merge($vals, array_values($group));
}
$table = $this->quote_table($table);
$fields = array_keys($first_row);
$table = $this->quoteTable($table);
$fields = array_keys($firstRow);
$sql = "INSERT INTO {$table} ("
. implode(',', $this->quote_ident($fields))
. implode(',', $this->quoteIdent($fields))
. ") VALUES ";
// Create the placeholder groups
$params = array_fill(0, count($fields), '?');
$param_string = "(" . implode(',', $params) . ")";
$param_list = array_fill(0, count($data), $param_string);
$paramString = "(" . implode(',', $params) . ")";
$paramList = array_fill(0, count($data), $paramString);
// Append the placeholder groups to the query
$sql .= implode(',', $param_list);
$sql .= implode(',', $paramList);
return [$sql, $vals];
}
// --------------------------------------------------------------------------
/**
* Creates a batch update, and executes it.
* Returns the number of affected rows
@ -634,14 +577,12 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
* @param string $where
* @return int|null
*/
public function update_batch($table, $data, $where)
public function updateBatch($table, $data, $where)
{
// @TODO implement
return NULL;
}
// --------------------------------------------------------------------------
/**
* Helper method for quote_ident
*
@ -655,16 +596,14 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
// that value, otherwise, return the original value
return (
is_string($str)
&& strpos($str, $this->escape_char_open) !== 0
&& strrpos($str, $this->escape_char_close) !== 0
&& strpos($str, $this->escapeCharOpen) !== 0
&& strrpos($str, $this->escapeCharClose) !== 0
)
? "{$this->escape_char_open}{$str}{$this->escape_char_close}"
? "{$this->escapeCharOpen}{$str}{$this->escapeCharClose}"
: $str;
}
// --------------------------------------------------------------------------
/**
* Sets the table prefix on the passed string
*
@ -674,16 +613,14 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
protected function _prefix($str)
{
// Don't prefix an already prefixed table
if (strpos($str, $this->table_prefix) !== FALSE)
if (strpos($str, $this->tablePrefix) !== FALSE)
{
return $str;
}
return $this->table_prefix.$str;
return $this->tablePrefix . $str;
}
// -------------------------------------------------------------------------
/**
* Empty the passed table
*
@ -692,15 +629,14 @@ abstract class AbstractDriver extends PDO implements DriverInterface {
*/
public function truncate($table)
{
$sql = ($this->has_truncate)
$sql = ($this->hasTruncate)
? 'TRUNCATE TABLE '
: 'DELETE FROM ';
$sql .= $this->quote_table($table);
$sql .= $this->quoteTable($table);
$this->statement = $this->query($sql);
return $this->statement;
}
}
// End of db_pdo.php

View File

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

View File

@ -13,16 +13,13 @@
* @link https://git.timshomepage.net/aviat4ion/Query
*/
namespace Query\Drivers;
/**
* Abstract class defining database / table creation methods
*
* @package Query
* @subpackage Drivers
* @method string quote_ident(string $sql)
* @method string quote_table(string $sql)
* @method string quoteIdent(string $sql)
* @method string quoteTable(string $sql)
*/
abstract class AbstractUtil {
@ -42,49 +39,45 @@ abstract class AbstractUtil {
$this->conn = $conn;
}
// --------------------------------------------------------------------------
/**
* Get the driver object for the current connection
*
* @return DriverInterface
*/
public function get_driver()
public function getDriver()
{
return $this->conn;
}
// --------------------------------------------------------------------------
/**
* Convenience public function to generate sql for creating a db table
*
* @param string $name
* @param array $fields
* @param array $constraints
* @param bool $if_not_exists
* @param bool $ifNotExists
* @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
// Eg $column_array[$colname] = array(
// Eg $columnArray[$colname] = array(
// 'type' => ...,
// 'constraint' => ...,
// 'index' => ...,
// )
$column_array = \array_zipper([
$columnArray = \array_zipper([
'type' => $fields,
'constraint' => $constraints
]);
// Join column definitions together
$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['constraint'])) ? " {$props['constraint']}" : "";
@ -92,27 +85,24 @@ abstract class AbstractUtil {
}
// 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 .= ')';
return $sql;
}
// --------------------------------------------------------------------------
/**
* Drop the selected table
*
* @param string $name
* @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
// --------------------------------------------------------------------------
@ -123,9 +113,7 @@ abstract class AbstractUtil {
* @abstract
* @return string
*/
abstract public function backup_structure();
// --------------------------------------------------------------------------
abstract public function backupStructure();
/**
* Return an SQL file with the database data as insert statements
@ -133,7 +121,6 @@ abstract class AbstractUtil {
* @abstract
* @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
* @link https://git.timshomepage.net/aviat4ion/Query
*/
namespace Query\Drivers;
/**
* PDO Interface to implement for database drivers
*
* @package Query
* @subpackage Drivers
*/
interface DriverInterface extends PDOInterface {
@ -30,9 +25,9 @@ interface DriverInterface extends PDOInterface {
* @param string $dsn
* @param string $username
* @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
@ -42,7 +37,7 @@ interface DriverInterface extends PDOInterface {
* @return \PDOStatement | FALSE
* @throws \InvalidArgumentException
*/
public function prepare_query($sql, $data);
public function prepareQuery($sql, $data);
/**
* Retrieve column information for the current database table
@ -50,14 +45,14 @@ interface DriverInterface extends PDOInterface {
* @param string $table
* @return array
*/
public function get_columns($table);
public function getColumns($table);
/**
* Retrieve list of data types for the database
*
* @return array
*/
public function get_types();
public function getTypes();
/**
* Retrieve indexes for the table
@ -65,7 +60,7 @@ interface DriverInterface extends PDOInterface {
* @param string $table
* @return array
*/
public function get_indexes($table);
public function getIndexes($table);
/**
* Retrieve foreign keys for the table
@ -73,14 +68,14 @@ interface DriverInterface extends PDOInterface {
* @param string $table
* @return array
*/
public function get_fks($table);
public function getFks($table);
/**
* Return list of tables for the current database
*
* @return array
*/
public function get_tables();
public function getTables();
/**
* Retrieves an array of non-user-created tables for
@ -88,49 +83,49 @@ interface DriverInterface extends PDOInterface {
*
* @return array
*/
public function get_system_tables();
public function getSystemTables();
/**
* Return list of dbs for the current connection, if possible
*
* @return array
*/
public function get_dbs();
public function getDbs();
/**
* Return list of views for the current database
*
* @return array
*/
public function get_views();
public function getViews();
/**
* Return list of sequences for the current database, if they exist
*
* @return array
*/
public function get_sequences();
public function getSequences();
/**
* Return list of functions for the current database
*
* @return array
*/
public function get_functions();
public function getFunctions();
/**
* Return list of stored procedures for the current database
*
* @return array
*/
public function get_procedures();
public function getProcedures();
/**
* Return list of triggers for the current database
*
* @return array
*/
public function get_triggers();
public function getTriggers();
/**
* Surrounds the string with the databases identifier escape characters
@ -138,7 +133,7 @@ interface DriverInterface extends PDOInterface {
* @param string|array $ident
* @return string|array
*/
public function quote_ident($ident);
public function quoteIdent($ident);
/**
* Quote database table name, and set prefix
@ -146,7 +141,7 @@ interface DriverInterface extends PDOInterface {
* @param string|array $table
* @return string|array
*/
public function quote_table($table);
public function quoteTable($table);
/**
* Create and execute a prepared statement with the provided parameters
@ -155,7 +150,7 @@ interface DriverInterface extends PDOInterface {
* @param array $params
* @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
*
* @param string|array|null $query
* @param bool $filtered_index
* @param bool $filteredIndex
* @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
*
* @return int
*/
public function affected_rows();
public function affectedRows();
/**
* Return the number of rows returned for a SELECT query
@ -181,7 +176,7 @@ interface DriverInterface extends PDOInterface {
*
* @return int
*/
public function num_rows();
public function numRows();
/**
* Prefixes a table if it is not already prefixed
@ -189,7 +184,7 @@ interface DriverInterface extends PDOInterface {
* @param string $table
* @return string
*/
public function prefix_table($table);
public function prefixTable($table);
/**
* Create sql for batch insert
@ -198,7 +193,7 @@ interface DriverInterface extends PDOInterface {
* @param array $data
* @return array
*/
public function insert_batch($table, $data=[]);
public function insertBatch($table, $data=[]);
/**
* Creates a batch update, and executes it.
@ -209,28 +204,27 @@ interface DriverInterface extends PDOInterface {
* @param string $where
* @return int|null
*/
public function update_batch($table, $data, $where);
public function updateBatch($table, $data, $where);
/**
* 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
*
* @return AbstractUtil
*/
public function get_util();
public function getUtil(): AbstractUtil;
/**
* Set the last query sql
*
* @param string $query_string
* @param string $queryString
* @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
* @link https://git.timshomepage.net/aviat4ion/Query
*/
namespace Query\Drivers\Firebird;
use PDO;
use PDOException;
use Query\Drivers\{AbstractDriver, DriverInterface};
use Query\Drivers\AbstractDriver;
use Query\Drivers\DriverInterface;
/**
* Firebird Database class
*
* 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 {
@ -36,7 +33,7 @@ class Driver extends AbstractDriver implements DriverInterface {
*
* @var resource
*/
protected $statement_link = NULL;
protected $statementLink = NULL;
/**
* Reference to the current transaction
@ -64,7 +61,7 @@ class Driver extends AbstractDriver implements DriverInterface {
*
* @var boolean
*/
protected $has_truncate = FALSE;
protected $hasTruncate = FALSE;
/**
* 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 = [])
{
$connect_function = (isset($options[PDO::ATTR_PERSISTENT]) && $options[PDO::ATTR_PERSISTENT])
$connectFunction = (isset($options[PDO::ATTR_PERSISTENT]) && $options[PDO::ATTR_PERSISTENT])
? '\\fbird_pconnect'
: '\\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);
// 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
// of AbstractDriver, which defines these
// class variables for the other drivers
$this->_load_sub_classes();
$this->_loadSubClasses();
}
// --------------------------------------------------------------------------
/**
* Cleanup some loose ends
* @codeCoverageIgnore
@ -108,21 +103,16 @@ class Driver extends AbstractDriver implements DriverInterface {
\fbird_service_detach($this->service);
}
// --------------------------------------------------------------------------
/**
* Return service handle
*
* @return resource
*/
public function get_service()
public function getService()
{
return $this->service;
}
// --------------------------------------------------------------------------
/**
* Execute an sql statement and return number of affected rows
*
@ -134,8 +124,6 @@ class Driver extends AbstractDriver implements DriverInterface {
return NULL;
}
// --------------------------------------------------------------------------
/**
* Implement for compatibility with PDO
*
@ -147,8 +135,6 @@ class Driver extends AbstractDriver implements DriverInterface {
return NULL;
}
// --------------------------------------------------------------------------
/**
* Return whether the current statement is in a transaction
*
@ -159,8 +145,6 @@ class Driver extends AbstractDriver implements DriverInterface {
return ! is_null($this->trans);
}
// --------------------------------------------------------------------------
/**
* 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);
}
// --------------------------------------------------------------------------
/**
* 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);
}
$this->statement_link = (isset($this->trans))
$this->statementLink = (isset($this->trans))
? \fbird_query($this->trans, $sql)
: \fbird_query($this->conn, $sql);
// Throw the error as a exception
$err_string = \fbird_errmsg() . "Last query:" . $this->get_last_query();
if ($this->statement_link === FALSE)
$errString = \fbird_errmsg() . "Last query:" . $this->getLastQuery();
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;
}
// --------------------------------------------------------------------------
/**
* Emulate PDO prepare
*
@ -216,21 +196,19 @@ class Driver extends AbstractDriver implements DriverInterface {
*/
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
if ($this->statement_link === FALSE)
if ($this->statementLink === FALSE)
{
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;
}
// --------------------------------------------------------------------------
/**
* Start a database transaction
*
@ -241,8 +219,6 @@ class Driver extends AbstractDriver implements DriverInterface {
return (($this->trans = \fbird_trans($this->conn)) !== NULL) ? TRUE : NULL;
}
// --------------------------------------------------------------------------
/**
* Commit a database transaction
*
@ -255,8 +231,6 @@ class Driver extends AbstractDriver implements DriverInterface {
return $res;
}
// --------------------------------------------------------------------------
/**
* Rollback a transaction
*
@ -269,8 +243,6 @@ class Driver extends AbstractDriver implements DriverInterface {
return $res;
}
// --------------------------------------------------------------------------
/**
* Set a connection attribute
* @param int $attribute
@ -282,8 +254,6 @@ class Driver extends AbstractDriver implements DriverInterface {
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Prepare and execute a query
*
@ -291,26 +261,24 @@ class Driver extends AbstractDriver implements DriverInterface {
* @param array $args
* @return Result
*/
public function prepare_execute($sql, $args)
public function prepareExecute($sql, $args)
{
$query = $this->prepare($sql);
// Set the statement in the class variable for easy later access
$this->statement_link =& $query;
$this->statementLink =& $query;
return $query->execute($args);
}
// --------------------------------------------------------------------------
/**
* Method to emulate PDO->quote
*
* @param string $str
* @param int $param_type
* @param int $paramType
* @return string
*/
public function quote($str, $param_type = PDO::PARAM_STR)
public function quote($str, $paramType = PDO::PARAM_STR)
{
if(is_numeric($str))
{
@ -320,8 +288,6 @@ class Driver extends AbstractDriver implements DriverInterface {
return "'".str_replace("'", "''", $str)."'";
}
// --------------------------------------------------------------------------
/**
* Method to emulate PDO->errorInfo / PDOStatement->errorInfo
*
@ -335,8 +301,6 @@ class Driver extends AbstractDriver implements DriverInterface {
return [0, $code, $msg];
}
// --------------------------------------------------------------------------
/**
* Method to emulate PDO->errorCode
*
@ -347,8 +311,6 @@ class Driver extends AbstractDriver implements DriverInterface {
return \fbird_errcode();
}
// --------------------------------------------------------------------------
/**
* Bind a prepared query with arguments for executing
*
@ -356,15 +318,13 @@ class Driver extends AbstractDriver implements DriverInterface {
* @param array $params
* @return NULL
*/
public function prepare_query($sql, $params)
public function prepareQuery($sql, $params)
{
// You can't bind query statements before execution with
// the firebird database
return NULL;
}
// --------------------------------------------------------------------------
/**
* Create sql for batch insert
*
@ -372,7 +332,7 @@ class Driver extends AbstractDriver implements DriverInterface {
* @param array $data
* @return array
*/
public function insert_batch($table, $data=[])
public function insertBatch($table, $data=[])
{
// Each member of the data array needs to be an array
if ( ! is_array(current($data)))
@ -383,11 +343,11 @@ class Driver extends AbstractDriver implements DriverInterface {
// Start the block of sql statements
$sql = "EXECUTE BLOCK AS BEGIN\n";
$table = $this->quote_table($table);
$table = $this->quoteTable($table);
$fields = \array_keys(\current($data));
$insert_template = "INSERT INTO {$table} ("
. implode(',', $this->quote_ident($fields))
$insertTemplate = "INSERT INTO {$table} ("
. implode(',', $this->quoteIdent($fields))
. ") VALUES (";
foreach($data as $item)
@ -396,7 +356,7 @@ class Driver extends AbstractDriver implements DriverInterface {
$vals = array_map([$this, 'quote'], $item);
// Add the values in the sql
$sql .= $insert_template . implode(', ', $vals) . ");\n";
$sql .= $insertTemplate . implode(', ', $vals) . ");\n";
}
// End the block of SQL statements
@ -408,4 +368,3 @@ class Driver extends AbstractDriver implements DriverInterface {
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
* @link https://git.timshomepage.net/aviat4ion/Query
*/
namespace Query\Drivers\Firebird;
use PDOStatement;
@ -90,8 +87,6 @@ class Result extends PDOStatement implements PDOStatementInterface {
}
}
// --------------------------------------------------------------------------
/**
* Invalidate method for data consistency
*
@ -107,70 +102,62 @@ class Result extends PDOStatement implements PDOStatementInterface {
return NULL;
}
// --------------------------------------------------------------------------
/**
* Invalidate method for data consistency
*
* @param mixed $parameter
* @param mixed $variable
* @param int $data_type
* @param int $dataType
* @param mixed $maxlen
* @param array $driverdata
* @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;
}
// --------------------------------------------------------------------------
/**
* Invalidate method for data consistency
*
* @param mixed $parameter
* @param mixed $variable
* @param int $data_type
* @param int $dataType
* @return NULL
*/
public function bindValue($parameter, $variable, $data_type=NULL)
public function bindValue($parameter, $variable, $dataType=NULL)
{
return NULL;
}
// --------------------------------------------------------------------------
/**
* Run a prepared statement query
*
* @param array $bound_input_params
* @param array $boundInputParams
* @return Result
*/
public function execute($bound_input_params = NULL)
public function execute($boundInputParams = NULL)
{
//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
// the array of arguments into a list of arguments
// 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;
}
// --------------------------------------------------------------------------
/**
* Emulate PDO fetch public function
*
* @param int $fetch_style
* @param mixed $cursor_orientation
* @param mixed $cursor_offset
* @param int $fetchStyle
* @param mixed $cursorOrientation
* @param mixed $cursorOffset
* @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 (empty($this->result))
@ -187,7 +174,7 @@ class Result extends PDOStatement implements PDOStatementInterface {
return NULL;
}
switch($fetch_style)
switch($fetchStyle)
{
case \PDO::FETCH_OBJ:
$row = (object) $this->result[$this->row];
@ -205,21 +192,19 @@ class Result extends PDOStatement implements PDOStatementInterface {
return $row;
}
// --------------------------------------------------------------------------
/**
* Emulate PDO fetchAll public function
*
* @param int $fetch_style
* @param int $fetchStyle
* @param mixed $statement
* @param mixed $ctor_args
* @param mixed $ctorArgs
* @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 = [];
while($row = $this->fetch($fetch_style, $statement))
while($row = $this->fetch($fetchStyle, $statement))
{
$all[] = $row;
}
@ -229,36 +214,30 @@ class Result extends PDOStatement implements PDOStatementInterface {
return $all;
}
// --------------------------------------------------------------------------
/**
* Emulate PDOStatement::fetchColumn
*
* @param int $column_num
* @param int $columnNum
* @return mixed
*/
public function fetchColumn($column_num=0)
public function fetchColumn($columnNum=0)
{
$row = $this->fetch(\PDO::FETCH_NUM);
return $row[$column_num];
return $row[$columnNum];
}
// --------------------------------------------------------------------------
/**
* Emulate PDOStatement::fetchObject, but only for the default use
*
* @param string $class_name
* @param array|null $ctor_args
* @param string $className
* @param array|null $ctorArgs
* @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 the number of rows affected by the previous query
*
@ -269,8 +248,6 @@ class Result extends PDOStatement implements PDOStatementInterface {
return \fbird_affected_rows();
}
// --------------------------------------------------------------------------
/**
* Method to emulate PDOStatement->errorCode
*
@ -281,8 +258,6 @@ class Result extends PDOStatement implements PDOStatementInterface {
return $this->db->errorCode();
}
// --------------------------------------------------------------------------
/**
* Method to emulate PDO->errorInfo / PDOStatement->errorInfo
*
@ -293,4 +268,3 @@ class Result extends PDOStatement implements PDOStatementInterface {
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
* @link https://git.timshomepage.net/aviat4ion/Query
*/
namespace Query\Drivers\Firebird;
use Query\Drivers\AbstractSQL;
/**
* Firebird Specific SQL
*
* @package Query
* @subpackage Drivers
*/
class SQL extends AbstractSQL {
@ -38,7 +32,7 @@ class SQL extends AbstractSQL {
public function limit($sql, $limit, $offset=FALSE)
{
// Keep the current sql string safe for a moment
$orig_sql = $sql;
$origSql = $sql;
$sql = 'FIRST '. (int) $limit;
@ -47,13 +41,11 @@ class SQL extends AbstractSQL {
$sql .= ' SKIP '. (int) $offset;
}
$sql = preg_replace("`SELECT`i", "SELECT {$sql}", $orig_sql);
$sql = preg_replace("`SELECT`i", "SELECT {$sql}", $origSql);
return $sql;
}
// --------------------------------------------------------------------------
/**
* Get the query plan for the sql query
*
@ -65,8 +57,6 @@ class SQL extends AbstractSQL {
return $sql;
}
// --------------------------------------------------------------------------
/**
* Random ordering keyword
*
@ -77,27 +67,22 @@ class SQL extends AbstractSQL {
return NULL;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list other databases
*
* @return NULL
*/
public function db_list()
public function dbList()
{
return NULL;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list tables
*
* @return string
*/
public function table_list()
public function tableList()
{
return <<<SQL
SELECT TRIM("RDB\$RELATION_NAME")
@ -108,14 +93,12 @@ class SQL extends AbstractSQL {
SQL;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list system tables
*
* @return string
*/
public function system_table_list()
public function systemTableList()
{
return <<<SQL
SELECT TRIM("RDB\$RELATION_NAME")
@ -125,14 +108,12 @@ SQL;
SQL;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list views
*
* @return string
*/
public function view_list()
public function viewList()
{
return <<<SQL
SELECT DISTINCT TRIM("RDB\$VIEW_NAME")
@ -140,14 +121,12 @@ SQL;
SQL;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list triggers
*
* @return string
*/
public function trigger_list()
public function triggerList()
{
return <<<SQL
SELECT * FROM "RDB\$FUNCTIONS"
@ -155,26 +134,22 @@ SQL;
SQL;
}
// --------------------------------------------------------------------------
/**
* Return sql to list functions
*
* @return string
*/
public function function_list()
public function functionList()
{
return 'SELECT * FROM "RDB$FUNCTIONS"';
}
// --------------------------------------------------------------------------
/**
* Return sql to list stored procedures
*
* @return string
*/
public function procedure_list()
public function procedureList()
{
return <<<SQL
SELECT "RDB\$PROCEDURE_NAME",
@ -195,14 +170,12 @@ SQL;
}
// --------------------------------------------------------------------------
/**
* Return sql to list sequences
*
* @return string
*/
public function sequence_list()
public function sequenceList()
{
return <<<SQL
SELECT TRIM("RDB\$GENERATOR_NAME")
@ -211,15 +184,13 @@ SQL;
SQL;
}
// --------------------------------------------------------------------------
/**
* Return sql to list columns of the specified table
*
* @param string $table
* @return string
*/
public function column_list($table)
public function columnList($table)
{
return <<<SQL
SELECT r.RDB\$FIELD_NAME AS field_name,
@ -258,14 +229,12 @@ SQL;
SQL;
}
// --------------------------------------------------------------------------
/**
* SQL to show list of field types
*
* @return string
*/
public function type_list()
public function typeList()
{
return <<<SQL
SELECT "RDB\$TYPE_NAME", "RDB\$FIELD_NAME" FROM "RDB\$TYPES"
@ -274,8 +243,6 @@ SQL;
SQL;
}
// --------------------------------------------------------------------------
/**
* Get the list of foreign keys for the current
* table
@ -283,7 +250,7 @@ SQL;
* @param string $table
* @return string
*/
public function fk_list($table)
public function fkList($table)
{
return <<<SQL
SELECT DISTINCT
@ -303,15 +270,13 @@ SQL;
SQL;
}
// --------------------------------------------------------------------------
/**
* Get the list of indexes for the current table
*
* @param string $table
* @return array
*/
public function index_list($table)
public function indexList($table)
{
return <<<SQL
SELECT "RDB\$INDEX_NAME", "RDB\$UNIQUE_FLAG", "RDB\$FOREIGN_KEY"
@ -320,4 +285,3 @@ SQL;
SQL;
}
}
//End of firebird_sql.php

View File

@ -12,17 +12,13 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query
*/
namespace Query\Drivers\Firebird;
use PDO;
use Query\Drivers\AbstractUtil;
/**
* Firebird-specific backup, import and creation methods
*
* @package Query
* @subpackage Drivers
*/
class Util extends AbstractUtil {
@ -32,12 +28,12 @@ class Util extends AbstractUtil {
* @param string $name
* @param array $fields
* @param array $constraints
* @param bool $if_not_exists
* @param bool $ifNotExists
* @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
* @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
*
* @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();
return ibase_backup($this->get_driver()->get_service(), $db_path, $new_file, \IBASE_BKP_METADATA_ONLY);
list($dbPath, $newFile) = func_get_args();
return ibase_backup($this->getDriver()->getService(), $dbPath, $newFile, \IBASE_BKP_METADATA_ONLY);
}
// --------------------------------------------------------------------------
/**
* Create an SQL backup file for the current database's data
*
* @param array $exclude
* @param bool $system_tables
* @param bool $systemTables
* @return string
*/
public function backup_data($exclude=[], $system_tables=FALSE)
public function backupData($exclude=[], $systemTables=FALSE)
{
// Determine which tables to use
$tables = $this->get_driver()->get_tables();
if($system_tables == TRUE)
$tables = $this->getDriver()->getTables();
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
@ -88,49 +80,48 @@ class Util extends AbstractUtil {
$tables = array_diff($tables, $exclude);
}
$output_sql = '';
$outputSql = '';
// Get the data for each object
foreach($tables as $t)
{
$sql = 'SELECT * FROM "'.trim($t).'"';
$res = $this->get_driver()->query($sql);
$obj_res = $res->fetchAll(\PDO::FETCH_ASSOC);
$res = $this->getDriver()->query($sql);
$objRes = $res->fetchAll(PDO::FETCH_ASSOC);
// Don't add to the file if the table is empty
if (count($obj_res) < 1)
if (count($objRes) < 1)
{
continue;
}
// 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
foreach($obj_res as $row)
foreach($objRes as $row)
{
$row = array_values($row);
// Quote values as needed by type
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_string = 'INSERT INTO "'.trim($t).'" ("'.implode('","', $columns).'") VALUES ('.implode(',', $row).');';
$rowString = 'INSERT INTO "'.trim($t).'" ("'.implode('","', $columns).'") VALUES ('.implode(',', $row).');';
$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
* @link https://git.timshomepage.net/aviat4ion/Query
*/
namespace Query\Drivers\Mysql;
use Query\Drivers\{AbstractDriver, DriverInterface};
use PDO;
use Query\Drivers\AbstractDriver;
use Query\Drivers\DriverInterface;
/**
* MySQL specific class
*
* @package Query
* @subpackage Drivers
*/
class Driver extends AbstractDriver implements DriverInterface {
@ -32,14 +28,14 @@ class Driver extends AbstractDriver implements DriverInterface {
*
* @var string
*/
protected $escape_char_open = '`';
protected $escapeCharOpen = '`';
/**
* Set the backtick as the MySQL escape character
*
* @var string
*/
protected $escape_char_close = '`';
protected $escapeCharClose = '`';
/**
* Connect to MySQL Database
@ -56,7 +52,7 @@ class Driver extends AbstractDriver implements DriverInterface {
if (defined('\\PDO::MYSQL_ATTR_INIT_COMMAND'))
{
$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);
}
}
//End of mysql_driver.php

View File

@ -12,18 +12,12 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query
*/
namespace Query\Drivers\Mysql;
use Query\Drivers\AbstractSQL;
/**
* MySQL specific SQL
*
* @package Query
* @subpackage Drivers
*/
class SQL extends AbstractSQL {
@ -45,8 +39,6 @@ class SQL extends AbstractSQL {
return $sql." LIMIT {$offset}, {$limit}";
}
// --------------------------------------------------------------------------
/**
* Get the query plan for the sql query
*
@ -58,8 +50,6 @@ class SQL extends AbstractSQL {
return "EXPLAIN EXTENDED {$sql}";
}
// --------------------------------------------------------------------------
/**
* Random ordering keyword
*
@ -70,27 +60,23 @@ class SQL extends AbstractSQL {
return ' RAND() DESC';
}
// --------------------------------------------------------------------------
/**
* Returns sql to list other databases
*
* @return string
*/
public function db_list()
public function dbList()
{
return "SHOW DATABASES WHERE `Database` NOT IN ('information_schema','mysql')";
}
// --------------------------------------------------------------------------
/**
* Returns sql to list tables
*
* @param string $database
* @return string
*/
public function table_list($database='')
public function tableList($database='')
{
if ( ! empty($database))
{
@ -100,106 +86,88 @@ class SQL extends AbstractSQL {
return 'SHOW TABLES';
}
// --------------------------------------------------------------------------
/**
* Overridden in MySQL class
*
* @return string
*/
public function system_table_list()
public function systemTableList()
{
return 'SELECT `TABLE_NAME` FROM `information_schema`.`TABLES`
WHERE `TABLE_SCHEMA`=\'information_schema\'';
}
// --------------------------------------------------------------------------
/**
* Returns sql to list views
*
* @return string
*/
public function view_list()
public function viewList()
{
return 'SELECT `table_name` FROM `information_schema`.`views`';
}
// --------------------------------------------------------------------------
/**
* Returns sql to list triggers
*
* @return string
*/
public function trigger_list()
public function triggerList()
{
return 'SHOW TRIGGERS';
}
// --------------------------------------------------------------------------
/**
* Return sql to list functions
*
* @return string
*/
public function function_list()
public function functionList()
{
return 'SHOW FUNCTION STATUS';
}
// --------------------------------------------------------------------------
/**
* Return sql to list stored procedures
*
* @return string
*/
public function procedure_list()
public function procedureList()
{
return 'SHOW PROCEDURE STATUS';
}
// --------------------------------------------------------------------------
/**
* Return sql to list sequences
*
* @return NULL
*/
public function sequence_list()
public function sequenceList()
{
return NULL;
}
// --------------------------------------------------------------------------
/**
* SQL to show list of field types
*
* @return string
*/
public function type_list()
public function typeList()
{
return "SELECT DISTINCT `DATA_TYPE` FROM `information_schema`.`COLUMNS`";
}
// --------------------------------------------------------------------------
/**
* SQL to show infromation about columns in a table
*
* @param string $table
* @return string
*/
public function column_list($table)
public function columnList($table)
{
return "SHOW FULL COLUMNS FROM {$table}";
}
// --------------------------------------------------------------------------
/**
* Get the list of foreign keys for the current
* table
@ -207,7 +175,7 @@ class SQL extends AbstractSQL {
* @param string $table
* @return string
*/
public function fk_list($table)
public function fkList($table)
{
return <<<SQL
SELECT DISTINCT `kcu`.`COLUMN_NAME` as `child_column`,
@ -225,17 +193,14 @@ class SQL extends AbstractSQL {
SQL;
}
// --------------------------------------------------------------------------
/**
* Get the list of indexes for the current table
*
* @param string $table
* @return array
*/
public function index_list($table)
public function indexList($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
* @link https://git.timshomepage.net/aviat4ion/Query
*/
namespace Query\Drivers\Mysql;
use PDO;
use Query\Drivers\AbstractUtil;
/**
* MySQL-specific backup, import and creation methods
*
* @package Query
* @subpackage Drivers
*/
class Util extends AbstractUtil {
@ -32,12 +27,12 @@ class Util extends AbstractUtil {
*
* @return string
*/
public function backup_structure()
public function backupStructure()
{
$string = [];
// Get databases
$dbs = $this->get_driver()->get_dbs();
$dbs = $this->getDriver()->getDbs();
foreach($dbs as &$d)
{
@ -48,11 +43,11 @@ class Util extends AbstractUtil {
}
// 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)
{
$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);
if ( ! isset($row['Create Table']))
@ -68,17 +63,15 @@ class Util extends AbstractUtil {
return implode("\n\n", $string);
}
// --------------------------------------------------------------------------
/**
* Create an SQL backup file for the current database's data
*
* @param array $exclude
* @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
if( ! empty($exclude))
@ -86,14 +79,14 @@ class Util extends AbstractUtil {
$tables = array_diff($tables, $exclude);
}
$output_sql = '';
$outputSql = '';
// Select the rows from each Table
foreach($tables as $t)
{
$sql = "SELECT * FROM `{$t}`";
$res = $this->get_driver()->query($sql);
$rows = $res->fetchAll(\PDO::FETCH_ASSOC);
$res = $this->getDriver()->query($sql);
$rows = $res->fetchAll(PDO::FETCH_ASSOC);
// Skip empty tables
if (count($rows) < 1)
@ -104,7 +97,7 @@ class Util extends AbstractUtil {
// Nab the column names by getting the keys of the first row
$columns = @array_keys($rows[0]);
$insert_rows = [];
$insertRows = [];
// Create the insert statements
foreach($rows as $row)
@ -114,21 +107,20 @@ class Util extends AbstractUtil {
// Workaround for Quercus
foreach($row as &$r)
{
$r = $this->get_driver()->quote($r);
$r = $this->getDriver()->quote($r);
}
$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;
$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
* @link https://git.timshomepage.net/aviat4ion/Query
*/
namespace Query\Drivers;
use PDO;
@ -22,9 +20,6 @@ use PDOStatement;
/**
* Interface describing the PDO class in PHP
*
* @package Query
* @subpackage Drivers
*/
interface PDOInterface {
@ -127,10 +122,10 @@ interface PDOInterface {
* Quotes a string for use in a query
*
* @param string $string
* @param int $parameter_type
* @param int $parameterType
* @return string|false
*/
public function quote($string, $parameter_type = PDO::PARAM_STR);
public function quote($string, $parameterType = PDO::PARAM_STR);
/**
* Rolls back a transaction

View File

@ -13,8 +13,6 @@
* @link https://git.timshomepage.net/aviat4ion/Query
*/
namespace Query\Drivers;
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
* 1-indexed position of the 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
* 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,
* you must explicitly set the length.
* @param mixed $driver_options
* @param mixed $driverOptions
* @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
@ -61,10 +59,10 @@ interface PDOStatementInterface {
* parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the
* 1-indexed position of 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
*/
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
@ -105,10 +103,10 @@ interface PDOStatementInterface {
/**
* Run a prepared statement query
*
* @param array $bound_input_params
* @param array $boundInputParams
* @return boolean
*/
public function execute($bound_input_params = NULL);
public function execute($boundInputParams = NULL);
/**
* 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
*
* @param int $column_number
* @param int $columnNumber
* @return mixed
*/
public function fetchColumn($column_number = 0);
public function fetchColumn($columnNumber = 0);
/**
* Fetches the next row and returns it as an object
*
* @param string $class_name
* @param array $ctor_args
* @param string $className
* @param array $ctorArgs
* @return mixed
*/
public function fetchObject($class_name = "stdClass", $ctor_args = NULL);
public function fetchObject($className = "stdClass", $ctorArgs = NULL);
/**
* Retrieve a statement attribute

View File

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

View File

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

View File

@ -12,18 +12,12 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query
*/
namespace Query\Drivers\Pgsql;
use Query\Drivers\AbstractUtil;
/**
* Posgres-specific backup, import and creation methods
*
* @package Query
* @subpackage Drivers
*/
class Util extends AbstractUtil {
@ -32,23 +26,21 @@ class Util extends AbstractUtil {
*
* @return string
*/
public function backup_structure()
public function backupStructure()
{
// @TODO Implement Backup function
return '';
}
// --------------------------------------------------------------------------
/**
* Create an SQL backup file for the current database's data
*
* @param array $exclude
* @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
if( ! empty($exclude))
@ -56,17 +48,17 @@ class Util extends AbstractUtil {
$tables = array_diff($tables, $exclude);
}
$output_sql = '';
$outputSql = '';
// Get the data for each object
foreach($tables as $t)
{
$sql = 'SELECT * FROM "'.trim($t).'"';
$res = $this->get_driver()->query($sql);
$obj_res = $res->fetchAll(\PDO::FETCH_ASSOC);
$res = $this->getDriver()->query($sql);
$objRes = $res->fetchAll(\PDO::FETCH_ASSOC);
// Don't add to the file if the table is empty
if (count($obj_res) < 1)
if (count($objRes) < 1)
{
continue;
}
@ -74,33 +66,32 @@ class Util extends AbstractUtil {
$res = NULL;
// 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
foreach($obj_res as $row)
foreach($objRes as $row)
{
$row = array_values($row);
// 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_string = 'INSERT INTO "'.trim($t).'" ("'.implode('","', $columns).'") VALUES ('.implode(',', $row).');';
$rowString = 'INSERT INTO "'.trim($t).'" ("'.implode('","', $columns).'") VALUES ('.implode(',', $row).');';
$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
*/
// --------------------------------------------------------------------------
namespace Query\Drivers;
/**
@ -58,63 +53,63 @@ interface SQLInterface {
*
* @return string
*/
public function db_list();
public function dbList();
/**
* Returns sql to list tables
*
* @return string
*/
public function table_list();
public function tableList();
/**
* Returns sql to list system tables
*
* @return string
*/
public function system_table_list();
public function systemTableList();
/**
* Returns sql to list views
*
* @return string
*/
public function view_list();
public function viewList();
/**
* Returns sql to list triggers
*
* @return string
*/
public function trigger_list();
public function triggerList();
/**
* Return sql to list functions
*
* @return NULL
*/
public function function_list();
public function functionList();
/**
* Return sql to list stored procedures
*
* @return string
*/
public function procedure_list();
public function procedureList();
/**
* Return sql to list sequences
*
* @return string
*/
public function sequence_list();
public function sequenceList();
/**
* Return sql to list database field types
*
* @return string|array
*/
public function type_list();
public function typeList();
/**
* Get information about the columns in the
@ -123,7 +118,7 @@ interface SQLInterface {
* @param string $table
* @return string
*/
public function column_list($table);
public function columnList($table);
/**
* Get the list of foreign keys for the current
@ -132,7 +127,7 @@ interface SQLInterface {
* @param string $table
* @return array
*/
public function fk_list($table);
public function fkList($table);
/**
* Get the list of indexes for the current table
@ -140,7 +135,5 @@ interface SQLInterface {
* @param string $table
* @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
* @link https://git.timshomepage.net/aviat4ion/Query
*/
namespace Query\Drivers\Sqlite;
use PDO;
use PDOStatement;
use Query\Drivers\{AbstractDriver, DriverInterface};
use Query\Drivers\AbstractDriver;
use Query\Drivers\DriverInterface;
/**
* SQLite specific class
*
* @package Query
* @subpackage Drivers
*/
class Driver extends AbstractDriver implements DriverInterface {
@ -40,7 +36,7 @@ class Driver extends AbstractDriver implements DriverInterface {
* but no support for the actual keyword
* @var boolean
*/
protected $has_truncate = FALSE;
protected $hasTruncate = FALSE;
/**
* Open SQLite Database
@ -48,9 +44,9 @@ class Driver extends AbstractDriver implements DriverInterface {
* @param string $dsn
* @param string $user
* @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)
{
@ -65,9 +61,9 @@ class Driver extends AbstractDriver implements DriverInterface {
*
* @return mixed
*/
public function get_tables()
public function getTables()
{
$sql = $this->sql->table_list();
$sql = $this->sql->tableList();
$res = $this->query($sql);
return db_filter($res->fetchAll(PDO::FETCH_ASSOC), 'name');
}
@ -78,13 +74,13 @@ class Driver extends AbstractDriver implements DriverInterface {
* @param string $table
* @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'],
'parent_table' => $row['table'],
'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
* @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
// MySQL and Postgres
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
$table = $this->quote_table($table);
$table = $this->quoteTable($table);
$sql = "INSERT INTO {$table} \n";
// Create a key-value mapping for each field
@ -132,7 +128,7 @@ class Driver extends AbstractDriver implements DriverInterface {
$cols = [];
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";
@ -145,4 +141,3 @@ class Driver extends AbstractDriver implements DriverInterface {
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
* @link https://git.timshomepage.net/aviat4ion/Query
*/
namespace Query\Drivers\Sqlite;
use Query\Drivers\AbstractSQL;
/**
* SQLite Specific SQL
*
* @package Query
* @subpackage Drivers
*/
class SQL extends AbstractSQL {
@ -38,8 +32,6 @@ class SQL extends AbstractSQL {
return "EXPLAIN QUERY PLAN {$sql}";
}
// --------------------------------------------------------------------------
/**
* Random ordering keyword
*
@ -50,26 +42,22 @@ class SQL extends AbstractSQL {
return ' RANDOM()';
}
// --------------------------------------------------------------------------
/**
* Returns sql to list other databases
*
* @return string
*/
public function db_list()
public function dbList()
{
return 'PRAGMA database_list';
}
// --------------------------------------------------------------------------
/**
* Returns sql to list tables
*
* @return string
*/
public function table_list()
public function tableList()
{
return <<<SQL
SELECT DISTINCT "name"
@ -80,107 +68,89 @@ class SQL extends AbstractSQL {
SQL;
}
// --------------------------------------------------------------------------
/**
* List the system tables
*
* @return string[]
*/
public function system_table_list()
public function systemTableList()
{
return ['sqlite_master', 'sqlite_temp_master', 'sqlite_sequence'];
}
// --------------------------------------------------------------------------
/**
* Returns sql to list views
*
* @return string
*/
public function view_list()
public function viewList()
{
return <<<SQL
SELECT "name" FROM "sqlite_master" WHERE "type" = 'view'
SQL;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list triggers
*
* @return string
*/
public function trigger_list()
public function triggerList()
{
return 'SELECT "name" FROM "sqlite_master" WHERE "type"=\'trigger\'';
}
// --------------------------------------------------------------------------
/**
* Return sql to list functions
*
* @return NULL
*/
public function function_list()
public function functionList()
{
return NULL;
}
// --------------------------------------------------------------------------
/**
* Return sql to list stored procedures
*
* @return NULL
*/
public function procedure_list()
public function procedureList()
{
return NULL;
}
// --------------------------------------------------------------------------
/**
* Return sql to list sequences
*
* @return NULL
*/
public function sequence_list()
public function sequenceList()
{
return NULL;
}
// --------------------------------------------------------------------------
/**
* SQL to show list of field types
*
* @return string[]
*/
public function type_list()
public function typeList()
{
return ['INTEGER', 'REAL', 'TEXT', 'BLOB'];
}
// --------------------------------------------------------------------------
/**
* SQL to show infromation about columns in a table
*
* @param string $table
* @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
* table
@ -188,12 +158,11 @@ SQL;
* @param string $table
* @return string
*/
public function fk_list($table)
public function fkList($table)
{
return 'PRAGMA foreign_key_list("' . $table . '")';
}
// --------------------------------------------------------------------------
/**
* Get the list of indexes for the current table
@ -201,10 +170,8 @@ SQL;
* @param string $table
* @return string
*/
public function index_list($table)
public function indexList($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
* @link https://git.timshomepage.net/aviat4ion/Query
*/
namespace Query\Drivers\Sqlite;
use PDO;
use Query\Drivers\AbstractUtil;
/**
@ -35,7 +33,7 @@ class Util extends AbstractUtil {
* @param array $excluded
* @return string
*/
public function backup_data($excluded=[])
public function backupData($excluded=[])
{
// Get a list of all the objects
$sql = 'SELECT DISTINCT "name"
@ -47,81 +45,78 @@ class Util extends AbstractUtil {
$sql .= " AND \"name\" NOT IN('".implode("','", $excluded)."')";
}
$res = $this->get_driver()->query($sql);
$result = $res->fetchAll(\PDO::FETCH_ASSOC);
$res = $this->getDriver()->query($sql);
$result = $res->fetchAll(PDO::FETCH_ASSOC);
unset($res);
$output_sql = '';
$outputSql = '';
// Get the data for each object
foreach($result as $r)
{
$sql = 'SELECT * FROM "'.$r['name'].'"';
$res = $this->get_driver()->query($sql);
$obj_res = $res->fetchAll(\PDO::FETCH_ASSOC);
$res = $this->getDriver()->query($sql);
$objRes = $res->fetchAll(PDO::FETCH_ASSOC);
unset($res);
// If the row is empty, continue;
if (empty($obj_res))
if (empty($objRes))
{
continue;
}
// 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
foreach($obj_res as $row)
foreach($objRes as $row)
{
$row = array_values($row);
// Quote values as needed by type
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);
$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
*
* @return string
*/
public function backup_structure()
public function backupStructure()
{
// Fairly easy for SQLite...just query the master table
$sql = 'SELECT "sql" FROM "sqlite_master"';
$res = $this->get_driver()->query($sql);
$result = $res->fetchAll(\PDO::FETCH_ASSOC);
$res = $this->getDriver()->query($sql);
$result = $res->fetchAll(PDO::FETCH_ASSOC);
$sql_array = [];
$sqlArray = [];
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
* @link https://git.timshomepage.net/aviat4ion/Query
*/
namespace Query;
use BadMethodCallException;
@ -20,11 +19,7 @@ use PDOStatement;
use Query\Drivers\DriverInterface;
/**
* Convenience class for creating sql queries - also the class that
* instantiates the specific db driver
*
* @package Query
* @subpackage Query_Builder
* Convenience class for creating sql queries
*/
class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface {
@ -33,12 +28,12 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
*
* @var array
*/
private $string_vars = [
'select_string',
'from_string',
'set_string',
'order_string',
'group_string',
private $stringVars = [
'selectString',
'fromString',
'setString',
'orderString',
'groupString',
'limit',
'offset',
'explain',
@ -49,14 +44,14 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
*
* @var array
*/
private $array_vars = [
'set_array_keys',
'order_array',
'group_array',
private $arrayVars = [
'setArrayKeys',
'orderArray',
'groupArray',
'values',
'where_values',
'query_map',
'having_map'
'whereValues',
'queryMap',
'havingMap'
];
// --------------------------------------------------------------------------
@ -78,8 +73,8 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
$this->queries['total_time'] = 0;
// Alias driver sql and util classes
$this->sql = $this->db->get_sql();
$this->util = $this->db->get_util();
$this->sql = $this->db->getSql();
$this->util = $this->db->getUtil();
}
/**
@ -101,16 +96,16 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
*/
public function __call(string $name, array $params)
{
// Allow camel-case method calls
$snake_name = \from_camel_case($name);
// Alias snake_case method calls
$camelName = \to_camel_case($name);
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
{
// Split fields by comma
$fields_array = explode(',', $fields);
$fields_array = array_map('mb_trim', $fields_array);
$fieldsArray = explode(',', $fields);
$fieldsArray = array_map('mb_trim', $fieldsArray);
// Split on 'As'
foreach ($fields_array as $key => $field)
foreach ($fieldsArray as $key => $field)
{
if (stripos($field, 'as') !== FALSE)
{
$fields_array[$key] = preg_split('` as `i', $field);
$fields_array[$key] = array_map('mb_trim', $fields_array[$key]);
$fieldsArray[$key] = preg_split('` as `i', $field);
$fieldsArray[$key] = array_map('mb_trim', $fieldsArray[$key]);
}
}
// 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
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;
}
@ -173,10 +168,10 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param string|bool $as
* @return QueryBuilderInterface
*/
public function select_max($field, $as=FALSE): QueryBuilderInterface
public function selectMax(string $field, $as=FALSE): QueryBuilderInterface
{
// Create the select string
$this->select_string .= ' MAX'.$this->_select($field, $as);
$this->selectString .= ' MAX'.$this->_select($field, $as);
return $this;
}
@ -187,10 +182,10 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param string|bool $as
* @return QueryBuilderInterface
*/
public function select_min($field, $as=FALSE): QueryBuilderInterface
public function selectMin(string $field, $as=FALSE): QueryBuilderInterface
{
// Create the select string
$this->select_string .= ' MIN'.$this->_select($field, $as);
$this->selectString .= ' MIN'.$this->_select($field, $as);
return $this;
}
@ -201,10 +196,10 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param string|bool $as
* @return QueryBuilderInterface
*/
public function select_avg($field, $as=FALSE): QueryBuilderInterface
public function selectAvg(string $field, $as=FALSE): QueryBuilderInterface
{
// Create the select string
$this->select_string .= ' AVG'.$this->_select($field, $as);
$this->selectString .= ' AVG'.$this->_select($field, $as);
return $this;
}
@ -215,10 +210,10 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param string|bool $as
* @return QueryBuilderInterface
*/
public function select_sum($field, $as=FALSE): QueryBuilderInterface
public function selectSum(string $field, $as=FALSE): QueryBuilderInterface
{
// Create the select string
$this->select_string .= ' SUM'.$this->_select($field, $as);
$this->selectString .= ' SUM'.$this->_select($field, $as);
return $this;
}
@ -230,7 +225,7 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
public function distinct(): QueryBuilderInterface
{
// Prepend the keyword to the select string
$this->select_string = ' DISTINCT '.$this->select_string;
$this->selectString = ' DISTINCT '.$this->selectString;
return $this;
}
@ -254,15 +249,15 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
public function from($tblname): QueryBuilderInterface
{
// Split identifiers on spaces
$ident_array = explode(' ', \mb_trim($tblname));
$ident_array = array_map('\\mb_trim', $ident_array);
$identArray = explode(' ', \mb_trim($tblname));
$identArray = array_map('\\mb_trim', $identArray);
// Quote the identifiers
$ident_array[0] = $this->db->quote_table($ident_array[0]);
$ident_array = $this->db->quote_ident($ident_array);
$identArray[0] = $this->db->quoteTable($identArray[0]);
$identArray = $this->db->quoteIdent($identArray);
// Paste it back together
$this->from_string = implode(' ', $ident_array);
$this->fromString = implode(' ', $identArray);
return $this;
}
@ -292,7 +287,7 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param string $pos
* @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');
}
@ -305,7 +300,7 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param string $pos
* @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');
}
@ -318,7 +313,7 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param string $pos
* @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');
}
@ -346,7 +341,7 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param mixed $val
* @return QueryBuilderInterface
*/
public function or_having($key, $val=[]): QueryBuilderInterface
public function orHaving($key, $val=[]): QueryBuilderInterface
{
return $this->_having($key, $val, 'OR');
}
@ -367,7 +362,7 @@ class QueryBuilder extends AbstractQueryBuilder implements 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
* @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
* @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
* @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
* @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
* @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
{
$this->_mixed_set($this->set_array_keys, $key, $val, self::KEY);
$this->_mixed_set($this->values, $key, $val, self::VALUE);
$this->_mixedSet($this->setArrayKeys, $key, $val, self::KEY);
$this->_mixedSet($this->values, $key, $val, self::VALUE);
// Use the keys of the array to make the insert/update string
// 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
$this->set_string = implode('=?,', $this->set_array_keys);
$this->set_string .= '=?';
$this->setString = implode('=?,', $this->setArrayKeys);
$this->setString .= '=?';
return $this;
}
@ -469,15 +464,15 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
{
// Prefix and quote table name
$table = explode(' ', mb_trim($table));
$table[0] = $this->db->quote_table($table[0]);
$table = $this->db->quote_ident($table);
$table[0] = $this->db->quoteTable($table[0]);
$table = $this->db->quoteIdent($table);
$table = implode(' ', $table);
// Parse out the join condition
$parsed_condition = $this->parser->compile_join($condition);
$condition = $table . ' ON ' . $parsed_condition;
$parsedCondition = $this->parser->compileJoin($condition);
$condition = $table . ' ON ' . $parsedCondition;
$this->_append_map("\n" . strtoupper($type) . ' JOIN ', $condition, 'join');
$this->_appendMap("\n" . strtoupper($type) . ' JOIN ', $condition, 'join');
return $this;
}
@ -488,19 +483,19 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param mixed $field
* @return QueryBuilderInterface
*/
public function group_by($field): QueryBuilderInterface
public function groupBy($field): QueryBuilderInterface
{
if ( ! is_scalar($field))
{
$new_group_array = array_map([$this->db, 'quote_ident'], $field);
$this->group_array = array_merge($this->group_array, $new_group_array);
$newGroupArray = array_map([$this->db, 'quoteIdent'], $field);
$this->groupArray = array_merge($this->groupArray, $newGroupArray);
}
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;
}
@ -512,7 +507,7 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param string $type
* @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
// doesn't support random ordering
@ -523,20 +518,20 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
}
// Set fields for later manipulation
$field = $this->db->quote_ident($field);
$this->order_array[$field] = $type;
$field = $this->db->quoteIdent($field);
$this->orderArray[$field] = $type;
$order_clauses = [];
$orderClauses = [];
// 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
$this->order_string = ( ! isset($rand))
? "\nORDER BY ".implode(', ', $order_clauses)
$this->orderString = ( ! isset($rand))
? "\nORDER BY ".implode(', ', $orderClauses)
: "\nORDER BY".$rand;
return $this;
@ -566,11 +561,11 @@ class QueryBuilder extends AbstractQueryBuilder implements 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;
}
@ -581,11 +576,11 @@ class QueryBuilder extends AbstractQueryBuilder implements 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;
}
@ -596,9 +591,9 @@ class QueryBuilder extends AbstractQueryBuilder implements 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;
}
@ -609,9 +604,9 @@ class QueryBuilder extends AbstractQueryBuilder implements 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;
}
@ -621,9 +616,9 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
*
* @return QueryBuilderInterface
*/
public function group_end(): QueryBuilderInterface
public function groupEnd(): QueryBuilderInterface
{
$this->_append_map('', ')', 'group_end');
$this->_appendMap('', ')', 'group_end');
return $this;
}
@ -667,7 +662,7 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param int|bool $offset
* @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
$this->where($where);
@ -682,9 +677,9 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param string $table
* @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);
return (int) count($res->fetchAll());
}
@ -697,7 +692,7 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param boolean $reset
* @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
if ( ! empty($table))
@ -735,10 +730,10 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param array $data
* @return PDOStatement
*/
public function insert_batch($table, $data=[]): PDOStatement
public function insertBatch($table, $data=[]): PDOStatement
{
// 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))
? $this->_run('', $table, $sql, $data)
@ -771,10 +766,10 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param string $where
* @return int|null
*/
public function update_batch($table, $data, $where)
public function updateBatch($table, $data, $where)
{
// 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))
? $this->_run('', $table, $sql, $data)
@ -827,7 +822,7 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
* @param bool $reset
* @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
if ( ! empty($table))
@ -835,7 +830,7 @@ class QueryBuilder extends AbstractQueryBuilder implements QueryBuilderInterface
$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
* @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
* @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
* @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
*/
public function reset_query()
public function resetQuery()
{
// Reset strings and booleans
foreach($this->string_vars as $var)
foreach($this->stringVars as $var)
{
$this->$var = NULL;
}
// Reset arrays
foreach($this->array_vars as $var)
foreach($this->arrayVars as $var)
{
$this->$var = [];
}

View File

@ -46,7 +46,7 @@ interface QueryBuilderInterface {
* @param string|bool $as
* @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
* @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
* @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
* @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
@ -133,7 +133,7 @@ interface QueryBuilderInterface {
* @param string $pos
* @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
* @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
* @return QueryBuilderInterface
*/
public function or_not_like($field, $val, $pos='both'): QueryBuilderInterface;
public function orNotLike($field, $val, $pos='both'): QueryBuilderInterface;
// --------------------------------------------------------------------------
// ! Having methods
@ -181,7 +181,7 @@ interface QueryBuilderInterface {
* @param mixed $val
* @return QueryBuilderInterface
*/
public function or_having($key, $val=[]): QueryBuilderInterface;
public function orHaving($key, $val=[]): QueryBuilderInterface;
// --------------------------------------------------------------------------
// ! 'Where' methods
@ -208,7 +208,7 @@ interface QueryBuilderInterface {
* @param mixed $val
* @return QueryBuilderInterface
*/
public function or_where($key, $val=[]): QueryBuilderInterface;
public function orWhere($key, $val=[]): QueryBuilderInterface;
// --------------------------------------------------------------------------
@ -219,7 +219,7 @@ interface QueryBuilderInterface {
* @param mixed $val
* @return QueryBuilderInterface
*/
public function where_in($field, $val=[]): QueryBuilderInterface;
public function whereIn($field, $val=[]): QueryBuilderInterface;
// --------------------------------------------------------------------------
@ -230,7 +230,7 @@ interface QueryBuilderInterface {
* @param mixed $val
* @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
* @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
* @return QueryBuilderInterface
*/
public function or_where_not_in($field, $val=[]): QueryBuilderInterface;
public function orWhereNotIn($field, $val=[]): QueryBuilderInterface;
// --------------------------------------------------------------------------
// ! Other Query Modifier methods
@ -287,7 +287,7 @@ interface QueryBuilderInterface {
* @param mixed $field
* @return QueryBuilderInterface
*/
public function group_by($field): QueryBuilderInterface;
public function groupBy($field): QueryBuilderInterface;
// --------------------------------------------------------------------------
@ -298,7 +298,7 @@ interface QueryBuilderInterface {
* @param string $type
* @return QueryBuilderInterface
*/
public function order_by($field, $type=""): QueryBuilderInterface;
public function orderBy($field, $type=""): QueryBuilderInterface;
// --------------------------------------------------------------------------
@ -320,7 +320,7 @@ interface QueryBuilderInterface {
*
* @return QueryBuilderInterface
*/
public function group_start(): QueryBuilderInterface;
public function groupStart(): QueryBuilderInterface;
// --------------------------------------------------------------------------
@ -330,7 +330,7 @@ interface QueryBuilderInterface {
*
* @return QueryBuilderInterface
*/
public function not_group_start(): QueryBuilderInterface;
public function notGroupStart(): QueryBuilderInterface;
// --------------------------------------------------------------------------
@ -340,7 +340,7 @@ interface QueryBuilderInterface {
*
* @return QueryBuilderInterface
*/
public function or_group_start(): QueryBuilderInterface;
public function orGroupStart(): QueryBuilderInterface;
// --------------------------------------------------------------------------
@ -350,7 +350,7 @@ interface QueryBuilderInterface {
*
* @return QueryBuilderInterface
*/
public function or_not_group_start(): QueryBuilderInterface;
public function orNotGroupStart(): QueryBuilderInterface;
// --------------------------------------------------------------------------
@ -359,7 +359,7 @@ interface QueryBuilderInterface {
*
* @return QueryBuilderInterface
*/
public function group_end(): QueryBuilderInterface;
public function groupEnd(): QueryBuilderInterface;
// --------------------------------------------------------------------------
// ! Query execution methods
@ -387,7 +387,7 @@ interface QueryBuilderInterface {
* @param int|bool $offset
* @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
* @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
* @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
* @return \PDOStatement|null
*/
public function insert_batch($table, $data=[]);
public function insertBatch($table, $data=[]);
// --------------------------------------------------------------------------
@ -466,7 +466,7 @@ interface QueryBuilderInterface {
* @param string $where
* @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
* @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
@ -499,7 +499,7 @@ interface QueryBuilderInterface {
* @param bool $reset
* @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
@ -508,7 +508,7 @@ interface QueryBuilderInterface {
* @param bool $reset
* @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
@ -517,7 +517,7 @@ interface QueryBuilderInterface {
* @param bool $reset
* @return string
*/
public function get_compiled_delete(string $table='', bool $reset=TRUE): string;
public function getCompiledDelete(string $table='', bool $reset=TRUE): string;
// --------------------------------------------------------------------------
// ! Miscellaneous Methods
@ -528,7 +528,7 @@ interface QueryBuilderInterface {
*
* @return void
*/
public function reset_query();
public function resetQuery();
}
// End of QueryBuilderInterface.php

View File

@ -12,18 +12,12 @@
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query
*/
namespace Query;
use Query\Drivers\DriverInterface;
/**
* Utility Class to parse sql clauses for properly escaping identifiers
*
* @package Query
* @subpackage Query_Builder
*/
class QueryParser {
@ -39,7 +33,7 @@ class QueryParser {
*
* @var array
*/
private $match_patterns = [
private $matchPatterns = [
'function' => '([a-zA-Z0-9_]+\((.*?)\))',
'identifier' => '([a-zA-Z0-9_-]+\.?)+',
'operator' => '=|AND|&&?|~|\|\|?|\^|/|>=?|<=?|-|%|OR|\+|NOT|\!=?|<>|XOR'
@ -67,42 +61,38 @@ class QueryParser {
$this->db = $db;
}
// --------------------------------------------------------------------------
/**
* Parser method for setting the parse string
*
* @param string $sql
* @return array
*/
public function parse_join($sql)
public function parseJoin(string $sql): array
{
// Get sql clause components
preg_match_all('`'.$this->match_patterns['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->match_patterns['operator'].'`', $sql, $this->matches['operators'], PREG_SET_ORDER);
preg_match_all('`'.$this->matchPatterns['function'].'`', $sql, $this->matches['functions'], PREG_SET_ORDER);
preg_match_all('`'.$this->matchPatterns['identifier'].'`', $sql, $this->matches['identifiers'], PREG_SET_ORDER);
preg_match_all('`'.$this->matchPatterns['operator'].'`', $sql, $this->matches['operators'], PREG_SET_ORDER);
// Get everything at once for ordering
$full_pattern = '`'.$this->match_patterns['function'].'+|'.$this->match_patterns['identifier'].'|('.$this->match_patterns['operator'].')+`i';
preg_match_all($full_pattern, $sql, $this->matches['combined'], PREG_SET_ORDER);
$fullPattern = '`'.$this->matchPatterns['function'].'+|'.$this->matchPatterns['identifier'].'|('.$this->matchPatterns['operator'].')+`i';
preg_match_all($fullPattern, $sql, $this->matches['combined'], PREG_SET_ORDER);
// 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;
}
// --------------------------------------------------------------------------
/**
* Compiles a join condition after parsing
*
* @param string $condition
* @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']);
// 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]))
{
$parts['combined'][$i] = $this->db->quote_ident($parts['combined'][$i]);
$parts['combined'][$i] = $this->db->quoteIdent($parts['combined'][$i]);
}
}
return implode('', $parts['combined']);
}
// --------------------------------------------------------------------------
/**
* Returns a more useful match array
*
* @param array $array
* @return array
*/
protected function filter_array($array)
protected function filterArray(array $array): array
{
$new_array = [];
$newArray = [];
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
{
$new_array = [];
$newArray = [];
foreach($array as $a)
{
$new_array[] = $a[$index];
$newArray[] = $a[$index];
}
return $new_array;
}
}
// --------------------------------------------------------------------------
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);
return $newArray;
}
}
@ -90,12 +67,12 @@ if ( ! function_exists('to_camel_case'))
/**
* Create a camelCase string from snake_case
*
* @param string $snake_case
* @param string $snakeCase
* @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]);
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
*
* 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.
*
* @param array $zipper_input
* @param array $zipperInput
* @return array
*/
function array_zipper(array $zipper_input): array
function array_zipper(array $zipperInput): array
{
$output = [];
foreach($zipper_input as $append_key => $values)
foreach($zipperInput as $appendKey => $values)
{
foreach($values as $index => $value)
{
@ -132,7 +109,7 @@ if ( ! function_exists('array_zipper'))
{
$output[$index] = [];
}
$output[$index][$append_key] = $value;
$output[$index][$appendKey] = $value;
}
}
@ -188,19 +165,19 @@ if ( ! function_exists('Query'))
*/
function Query($params = '')
{
$manager = ConnectionManager::get_instance();
$manager = ConnectionManager::getInstance();
// If you are getting a previously created connection
if (is_scalar($params))
{
return $manager->get_connection($params);
return $manager->getConnection($params);
}
elseif ( ! is_scalar($params) && ! is_null($params))
{
$params_object = (object) $params;
$paramsObject = (object) $params;
// Otherwise, return a new connection
return $manager->connect($params_object);
return $manager->connect($paramsObject);
}
return NULL;

View File

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

View File

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

View File

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

View File

@ -59,8 +59,8 @@ class CoreTest extends Query_TestCase {
$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);
}
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(
'table1.field1', '=', 'table2.field2'
));
@ -37,7 +37,7 @@ class Query_Parser_Test extends Query_TestCase {
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(
'db1.table1.field1','!=','db2.table2.field2'
));
@ -45,7 +45,7 @@ class Query_Parser_Test extends Query_TestCase {
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(
'table_1.field1', '=', 'tab_le2.field_2'
));
@ -53,7 +53,7 @@ class Query_Parser_Test extends Query_TestCase {
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(
'table1.field1', '>', 'SUM(3+5)'
));

View File

@ -84,17 +84,17 @@ class FirebirdQBTest extends QBTest {
$params->user = 'sysdba';
$params->pass = 'masterkey';
$params->prefix = '';
$f_conn = Query($params);
$q_conn = Query('wood');
$fConn = Query($params);
$qConn = Query('wood');
$this->assertReference($f_conn, $q_conn);
$this->assertReference($fConn, $qConn);
}
// --------------------------------------------------------------------------
public function testTypeList()
{
$sql = self::$db->sql->type_list();
$sql = self::$db->sql->typeList();
$query = self::$db->query($sql);
$this->assertIsA($query, 'PDOStatement');
@ -113,13 +113,13 @@ class FirebirdQBTest extends QBTest {
->where('id >', 1)
->where('id <', 900)
->limit(2, 1)
->get_compiled_select();
->getCompiledSelect();
$res2 = self::$db->select('id, key as k, val')
->where('id >', 1)
->where('id <', 900)
->limit(2, 1)
->get_compiled_select();
->getCompiledSelect();
// Queries are equal because explain is not a keyword in Firebird
$this->assertEqual($res, $res2);
@ -155,6 +155,6 @@ class FirebirdQBTest extends QBTest {
$existing = QTEST_DIR.QDS.'db_files'.QDS.'FB_TEST_DB.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
self::$db = new \Query\Drivers\Firebird\Driver('localhost:'.$dbpath);
self::$db->set_table_prefix('create_');
self::$db->setTablePrefix('create_');
}
public function setUp()
@ -42,7 +42,7 @@ class FirebirdTest extends DBtest {
$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()
{
$only_system = TRUE;
$onlySystem = TRUE;
$tables = self::$db->get_system_tables();
$tables = self::$db->getSystemTables();
foreach($tables as $t)
{
if(stripos($t, 'rdb$') !== 0 && stripos($t, 'mon$') !== 0)
{
$only_system = FALSE;
$onlySystem = FALSE;
break;
}
}
$this->assertTrue($only_system);
$this->assertTrue($onlySystem);
}
// --------------------------------------------------------------------------
@ -111,7 +111,7 @@ class FirebirdTest extends DBtest {
public function testCreateTable()
{
//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',
'key' => 'VARCHAR(64)',
'val' => 'BLOB SUB_TYPE TEXT'
@ -119,7 +119,7 @@ class FirebirdTest extends DBtest {
self::$db->query($sql);
//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()
{
//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);
//Check
$table_exists = in_array('create_delete', self::$db->get_tables());
$this->assertFalse($table_exists);
$tableExists = in_array('create_delete', self::$db->getTables());
$this->assertFalse($tableExists);
}
// --------------------------------------------------------------------------
@ -141,7 +141,7 @@ class FirebirdTest extends DBtest {
{
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")
VALUES (?,?,?)
SQL;
self::$db->prepare_execute($sql, array(
self::$db->prepareExecute($sql, array(
2, "works", 'also?'
));
@ -221,7 +221,7 @@ SQL;
public function testPrepareQuery()
{
$this->assertNull(self::$db->prepare_query('', array()));
$this->assertNull(self::$db->prepareQuery('', array()));
}
// --------------------------------------------------------------------------
@ -251,7 +251,7 @@ SQL;
public function testDBList()
{
$res = self::$db->get_sql()->db_list();
$res = self::$db->getSql()->dbList();
$this->assertNULL($res);
}

View File

@ -13,8 +13,7 @@
* @link https://git.timshomepage.net/aviat4ion/Query
*/
// --------------------------------------------------------------------------
use Query\Drivers\Mysql\Driver;
/**
* MySQLTest class.
@ -29,19 +28,19 @@ class MySQLTest extends DBTest {
$params = get_json_config();
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
else if ($params !== FALSE)
{
$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
));
}
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'));
//Attempt to create the table
$sql = self::$db->get_util()->create_table('test',
$sql = self::$db->getUtil()->createTable('test',
array(
'id' => 'int(10)',
'key' => 'TEXT',
@ -79,7 +78,7 @@ class MySQLTest extends DBTest {
self::$db->query($sql);
//Attempt to create the table
$sql = self::$db->get_util()->create_table('join',
$sql = self::$db->getUtil()->createTable('join',
array(
'id' => 'int(10)',
'key' => 'TEXT',
@ -92,7 +91,7 @@ class MySQLTest extends DBTest {
self::$db->query($sql);
//Check
$dbs = self::$db->get_tables();
$dbs = self::$db->getTables();
$this->assertTrue(in_array('create_test', $dbs));
@ -114,7 +113,7 @@ class MySQLTest extends DBTest {
INSERT INTO `create_test` (`id`, `key`, `val`)
VALUES (?,?,?)
SQL;
$statement = self::$db->prepare_query($sql, array(1,"boogers", "Gross"));
$statement = self::$db->prepareQuery($sql, array(1,"boogers", "Gross"));
$res = $statement->execute();
@ -132,7 +131,7 @@ SQL;
SQL;
try
{
$statement = self::$db->prepare_query($sql, 'foo');
$statement = self::$db->prepareQuery($sql, 'foo');
}
catch(InvalidArgumentException $e)
{
@ -149,7 +148,7 @@ SQL;
INSERT INTO `create_test` (`id`, `key`, `val`)
VALUES (?,?,?)
SQL;
$res = self::$db->prepare_execute($sql, array(
$res = self::$db->prepareExecute($sql, array(
2, "works", 'also?'
));
@ -187,21 +186,21 @@ SQL;
public function testGetSchemas()
{
$this->assertNull(self::$db->get_schemas());
$this->assertNull(self::$db->getSchemas());
}
// --------------------------------------------------------------------------
public function testGetSequences()
{
$this->assertNull(self::$db->get_sequences());
$this->assertNull(self::$db->getSequences());
}
// --------------------------------------------------------------------------
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()
{
$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->set_table_prefix('create_');
self::$db->setTablePrefix('create_');
}
// --------------------------------------------------------------------------
@ -85,7 +85,7 @@ class PgTest extends DBTest {
//Attempt to create the table
$sql = self::$db->get_util()->create_table('create_test',
$sql = self::$db->getUtil()->createTable('create_test',
array(
'id' => 'integer',
'key' => 'TEXT',
@ -99,7 +99,7 @@ class PgTest extends DBTest {
self::$db->query($sql);
//Attempt to create the table
$sql = self::$db->get_util()->create_table('create_join',
$sql = self::$db->getUtil()->createTable('create_join',
array(
'id' => 'integer',
'key' => 'TEXT',
@ -118,7 +118,7 @@ class PgTest extends DBTest {
//$this->setUp();
//Check
$dbs = self::$db->get_tables();
$dbs = self::$db->getTables();
$this->assertTrue(in_array('create_test', $dbs));
}
@ -130,8 +130,8 @@ class PgTest extends DBTest {
self::$db->truncate('create_test');
self::$db->truncate('create_join');
$ct_query = self::$db->query('SELECT * FROM create_test');
$cj_query = self::$db->query('SELECT * FROM create_join');
$ctQuery = self::$db->query('SELECT * FROM create_test');
$cjQuery = self::$db->query('SELECT * FROM create_join');
}
// --------------------------------------------------------------------------
@ -142,7 +142,7 @@ class PgTest extends DBTest {
INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?)
SQL;
$statement = self::$db->prepare_query($sql, array(1,"boogers", "Gross"));
$statement = self::$db->prepareQuery($sql, array(1,"boogers", "Gross"));
$statement->execute();
@ -158,7 +158,7 @@ SQL;
SQL;
try
{
$statement = self::$db->prepare_query($sql, 'foo');
$statement = self::$db->prepareQuery($sql, 'foo');
}
catch(InvalidArgumentException $e)
{
@ -177,7 +177,7 @@ SQL;
INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?)
SQL;
self::$db->prepare_execute($sql, array(
self::$db->prepareExecute($sql, array(
2, "works", 'also?'
));
@ -217,20 +217,20 @@ SQL;
public function testGetSchemas()
{
$this->assertTrue(is_array(self::$db->get_schemas()));
$this->assertTrue(is_array(self::$db->getSchemas()));
}
// --------------------------------------------------------------------------
public function testGetDBs()
{
$this->assertTrue(is_array(self::$db->get_dbs()));
$this->assertTrue(is_array(self::$db->getDbs()));
}
// --------------------------------------------------------------------------
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);
$expected_possibilities = array();
$expectedPossibilities = array();
$expected_possibilities[] = array(
$expectedPossibilities[] = array(
array(
'order' => '0',
'from' => '0',
@ -60,7 +60,7 @@
)
);
$expected_possibilities[] = array (
$expectedPossibilities[] = array (
array (
'selectid' => '0',
'order' => '0',
@ -69,7 +69,7 @@
),
);
$expected_possibilities[] = array (
$expectedPossibilities[] = array (
array (
'selectid' => '0',
'order' => '0',
@ -78,7 +78,7 @@
),
);
$expected_possibilities[] = array (
$expectedPossibilities[] = array (
array (
'selectid' => '0',
'order' => '0',
@ -90,7 +90,7 @@
$passed = FALSE;
// Check for a matching possibility
foreach($expected_possibilities as $ep)
foreach($expectedPossibilities as $ep)
{
if ($res == $ep)
{

View File

@ -38,7 +38,7 @@ class SQLiteTest extends DBTest {
);
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'));
//Check
$dbs = self::$db->get_tables();
$dbs = self::$db->getTables();
$this->assertTrue(in_array('TEST1', $dbs));
$this->assertTrue(in_array('TEST2', $dbs));
@ -65,9 +65,9 @@ class SQLiteTest extends DBTest {
/*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
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 (999,'''ring''','''sale''');
SQL;
$expected_array = explode("\n", $expected);
$this->assertEqual($expected_array, $sql_array);
$expectedArray = explode("\n", $expected);
$this->assertEqual($expectedArray, $sqlArray);
}*/
// --------------------------------------------------------------------------
public function testBackupStructure()
{
$sql = mb_trim(self::$db->get_util()->backup_structure());
$sql = mb_trim(self::$db->getUtil()->backupStructure());
$expected = <<<SQL
CREATE TABLE "create_test" ("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;
$expected_array = explode("\n", $expected);
$result_array = explode("\n", $sql);
$expectedArray = explode("\n", $expected);
$resultArray = explode("\n", $sql);
$this->assertEqual($expected_array, $result_array);
$this->assertEqual($expectedArray, $resultArray);
}
// --------------------------------------------------------------------------
public function testDeleteTable()
{
$sql = self::$db->get_util()->delete_table('create_delete');
$sql = self::$db->getUtil()->deleteTable('create_delete');
self::$db->query($sql);
//Check
$dbs = self::$db->get_tables();
$dbs = self::$db->getTables();
$this->assertFalse(in_array('create_delete', $dbs));
}
@ -200,7 +200,7 @@ SQL;
INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?)
SQL;
$statement = self::$db->prepare_query($sql, array(1,"boogers", "Gross"));
$statement = self::$db->prepareQuery($sql, array(1,"boogers", "Gross"));
$statement->execute();
@ -214,7 +214,7 @@ SQL;
INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?)
SQL;
self::$db->prepare_execute($sql, array(
self::$db->prepareExecute($sql, array(
2, "works", 'also?'
));
@ -260,14 +260,14 @@ SQL;
public function testGetDBs()
{
$this->assertTrue(is_array(self::$db->get_dbs()));
$this->assertTrue(is_array(self::$db->getDbs()));
}
// --------------------------------------------------------------------------
public function testGetSchemas()
{
$this->assertNull(self::$db->get_schemas());
$this->assertNull(self::$db->getSchemas());
}
// --------------------------------------------------------------------------
@ -276,13 +276,13 @@ SQL;
public function testNullMethods()
{
$sql = self::$db->sql->function_list();
$sql = self::$db->sql->functionList();
$this->assertEqual(NULL, $sql);
$sql = self::$db->sql->procedure_list();
$sql = self::$db->sql->procedureList();
$this->assertEqual(NULL, $sql);
$sql = self::$db->sql->sequence_list();
$sql = self::$db->sql->sequenceList();
$this->assertEqual(NULL, $sql);
}
@ -290,7 +290,7 @@ SQL;
public function testGetSystemTables()
{
$sql = self::$db->get_system_tables();
$sql = self::$db->getSystemTables();
$this->assertTrue(is_array($sql));
}
@ -298,20 +298,20 @@ SQL;
public function testGetSequences()
{
$this->assertNull(self::$db->get_sequences());
$this->assertNull(self::$db->getSequences());
}
// --------------------------------------------------------------------------
public function testGetFunctions()
{
$this->assertNull(self::$db->get_functions());
$this->assertNull(self::$db->getFunctions());
}
// --------------------------------------------------------------------------
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 ( ! isset($_SERVER_SOFTWARE))
if ( ! array_key_exists('SERVER_SOFTWARE', $_SERVER))
{
define('IS_QUERCUS', FALSE);
}
@ -147,7 +147,7 @@ define('QDS', DIRECTORY_SEPARATOR);
// Include db tests
// Load db classes based on capability
$test_path = QTEST_DIR.'/databases/';
$testPath = QTEST_DIR.'/databases/';
// Require base testing classes
require_once(QTEST_DIR . '/core/core_test.php');
@ -163,7 +163,7 @@ if (function_exists('fbird_connect'))
$drivers[] = 'interbase';
}
$driver_test_map = array(
$driverTestMap = array(
'MySQL' => in_array('mysql', $drivers),
'SQLite' => in_array('sqlite', $drivers),
'PgSQL' => in_array('pgsql', $drivers),
@ -172,11 +172,11 @@ $driver_test_map = array(
);
// 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}QBTest.php");