Add more type hinting

This commit is contained in:
Timothy Warren 2018-01-24 13:14:03 -05:00
parent 516ddcd76d
commit 1d583bcc23
20 changed files with 258 additions and 475 deletions

View File

@ -200,6 +200,7 @@ final class ConnectionManager {
/** /**
* Create the dsn from the db type and params * Create the dsn from the db type and params
* *
* @codeCoverageIgnore
* @param string $dbtype * @param string $dbtype
* @param \stdClass $params * @param \stdClass $params
* @return string * @return string

View File

@ -83,7 +83,7 @@ abstract class AbstractDriver
* @param string $password * @param string $password
* @param array $driverOptions * @param array $driverOptions
*/ */
public function __construct($dsn, $username=NULL, $password=NULL, array $driverOptions=[]) public function __construct(string $dsn, string $username=NULL, string $password=NULL, array $driverOptions=[])
{ {
// Set PDO to display errors as exceptions, and apply driver options // Set PDO to display errors as exceptions, and apply driver options
$driverOptions[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION; $driverOptions[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
@ -182,7 +182,7 @@ abstract class AbstractDriver
* @param string $prefix * @param string $prefix
* @return void * @return void
*/ */
public function setTablePrefix($prefix) public function setTablePrefix(string $prefix): void
{ {
$this->tablePrefix = $prefix; $this->tablePrefix = $prefix;
} }
@ -199,16 +199,11 @@ abstract class AbstractDriver
* @return PDOStatement | FALSE * @return PDOStatement | FALSE
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public function prepareQuery($sql, $data) public function prepareQuery(string $sql, array $data): ?PDOStatement
{ {
// Prepare the sql, save the statement for easy access later // Prepare the sql, save the statement for easy access later
$this->statement = $this->prepare($sql); $this->statement = $this->prepare($sql);
if( ! (\is_array($data) || \is_object($data)))
{
throw new InvalidArgumentException('Data argument must be an object or associative array');
}
// Bind the parameters // Bind the parameters
foreach($data as $k => $value) foreach($data as $k => $value)
{ {
@ -229,9 +224,10 @@ abstract class AbstractDriver
* *
* @param string $sql * @param string $sql
* @param array $params * @param array $params
* @throws InvalidArgumentException
* @return PDOStatement * @return PDOStatement
*/ */
public function prepareExecute($sql, $params): PDOStatement public function prepareExecute(string $sql, array $params): ?PDOStatement
{ {
$this->statement = $this->prepareQuery($sql, $params); $this->statement = $this->prepareQuery($sql, $params);
$this->statement->execute(); $this->statement->execute();
@ -255,7 +251,7 @@ abstract class AbstractDriver
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function prefixTable($table): string public function prefixTable(string $table): string
{ {
// Add the prefix to the table name // Add the prefix to the table name
// before quoting it // before quoting it
@ -502,7 +498,7 @@ abstract class AbstractDriver
$flag = $filteredIndex ? PDO::FETCH_NUM : PDO::FETCH_ASSOC; $flag = $filteredIndex ? PDO::FETCH_NUM : PDO::FETCH_ASSOC;
$all = $res->fetchAll($flag); $all = $res->fetchAll($flag);
return $filteredIndex ? \db_filter($all, 0) : $all; return $filteredIndex ? \dbFilter($all, 0) : $all;
} }
/** /**
@ -529,10 +525,10 @@ abstract class AbstractDriver
* Create sql for batch insert * Create sql for batch insert
* *
* @param string $table * @param string $table
* @param array|object $data * @param mixed $data
* @return null|array<string|array|null> * @return null|array<string|array|null>
*/ */
public function insertBatch($table, $data=[]) public function insertBatch(string $table, array $data=[]): array
{ {
$data = (array) $data; $data = (array) $data;
$firstRow = (array) current($data); $firstRow = (array) current($data);
@ -570,12 +566,30 @@ abstract class AbstractDriver
* @param string $where * @param string $where
* @return int|null * @return int|null
*/ */
public function updateBatch($table, $data, $where) public function updateBatch(string $table, $data, $where)
{ {
// @TODO implement // @TODO implement
return NULL; return NULL;
} }
/**
* Empty the passed table
*
* @param string $table
* @return PDOStatement
*/
public function truncate(string $table): PDOStatement
{
$sql = $this->hasTruncate
? 'TRUNCATE TABLE '
: 'DELETE FROM ';
$sql .= $this->quoteTable($table);
$this->statement = $this->query($sql);
return $this->statement;
}
/** /**
* Helper method for quote_ident * Helper method for quote_ident
* *
@ -603,7 +617,7 @@ abstract class AbstractDriver
* @param string $str * @param string $str
* @return string * @return string
*/ */
protected function _prefix($str): string protected function _prefix(string $str): string
{ {
// Don't prefix an already prefixed table // Don't prefix an already prefixed table
if (strpos($str, $this->tablePrefix) !== FALSE) if (strpos($str, $this->tablePrefix) !== FALSE)
@ -613,23 +627,4 @@ abstract class AbstractDriver
return $this->tablePrefix . $str; return $this->tablePrefix . $str;
} }
/**
* Empty the passed table
*
* @param string $table
* @return PDOStatement
*/
public function truncate($table): PDOStatement
{
$sql = $this->hasTruncate
? 'TRUNCATE TABLE '
: 'DELETE FROM ';
$sql .= $this->quoteTable($table);
$this->statement = $this->query($sql);
return $this->statement;
}
} }

View File

@ -30,7 +30,7 @@ abstract class AbstractSQL implements SQLInterface {
* @param int|bool $offset * @param int|bool $offset
* @return string * @return string
*/ */
public function limit($sql, $limit, $offset=FALSE) public function limit(string $sql, int $limit, $offset=FALSE): string
{ {
$sql .= "\nLIMIT {$limit}"; $sql .= "\nLIMIT {$limit}";

View File

@ -67,7 +67,7 @@ abstract class AbstractUtil {
// 'constraint' => ..., // 'constraint' => ...,
// 'index' => ..., // 'index' => ...,
// ) // )
$columnArray = \array_zipper([ $columnArray = \arrayZipper([
'type' => $fields, 'type' => $fields,
'constraint' => $constraints 'constraint' => $constraints
]); ]);

View File

@ -14,6 +14,8 @@
*/ */
namespace Query\Drivers; namespace Query\Drivers;
use PDOStatement;
/** /**
* PDO Interface to implement for database drivers * PDO Interface to implement for database drivers
*/ */
@ -27,17 +29,17 @@ interface DriverInterface {
* @param string $password * @param string $password
* @param array $driverOptions * @param array $driverOptions
*/ */
public function __construct($dsn, $username=NULL, $password=NULL, array $driverOptions = []); public function __construct(string $dsn, string $username=NULL, string $password=NULL, array $driverOptions = []);
/** /**
* Simplifies prepared statements for database queries * Simplifies prepared statements for database queries
* *
* @param string $sql * @param string $sql
* @param array $data * @param array $data
* @return \PDOStatement | FALSE * @return \PDOStatement|null
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
*/ */
public function prepareQuery($sql, $data); public function prepareQuery(string $sql, array $data): ?PDOStatement;
/** /**
* Retrieve column information for the current database table * Retrieve column information for the current database table
@ -45,14 +47,14 @@ interface DriverInterface {
* @param string $table * @param string $table
* @return array * @return array
*/ */
public function getColumns($table); public function getColumns($table): ?array;
/** /**
* Retrieve list of data types for the database * Retrieve list of data types for the database
* *
* @return array * @return array
*/ */
public function getTypes(); public function getTypes(): ?array;
/** /**
* Retrieve indexes for the table * Retrieve indexes for the table
@ -60,7 +62,7 @@ interface DriverInterface {
* @param string $table * @param string $table
* @return array * @return array
*/ */
public function getIndexes($table); public function getIndexes($table): ?array;
/** /**
* Retrieve foreign keys for the table * Retrieve foreign keys for the table
@ -68,14 +70,14 @@ interface DriverInterface {
* @param string $table * @param string $table
* @return array * @return array
*/ */
public function getFks($table); public function getFks($table): ?array;
/** /**
* Return list of tables for the current database * Return list of tables for the current database
* *
* @return array * @return array
*/ */
public function getTables(); public function getTables(): ?array;
/** /**
* Retrieves an array of non-user-created tables for * Retrieves an array of non-user-created tables for
@ -83,49 +85,49 @@ interface DriverInterface {
* *
* @return array * @return array
*/ */
public function getSystemTables(); public function getSystemTables(): ?array;
/** /**
* Return list of dbs for the current connection, if possible * Return list of dbs for the current connection, if possible
* *
* @return array * @return array
*/ */
public function getDbs(); public function getDbs(): ?array;
/** /**
* Return list of views for the current database * Return list of views for the current database
* *
* @return array * @return array
*/ */
public function getViews(); public function getViews(): ?array;
/** /**
* Return list of sequences for the current database, if they exist * Return list of sequences for the current database, if they exist
* *
* @return array * @return array
*/ */
public function getSequences(); public function getSequences(): ?array;
/** /**
* Return list of functions for the current database * Return list of functions for the current database
* *
* @return array * @return array
*/ */
public function getFunctions(); public function getFunctions(): ?array;
/** /**
* Return list of stored procedures for the current database * Return list of stored procedures for the current database
* *
* @return array * @return array
*/ */
public function getProcedures(); public function getProcedures(): ?array;
/** /**
* Return list of triggers for the current database * Return list of triggers for the current database
* *
* @return array * @return array
*/ */
public function getTriggers(); public function getTriggers(): ?array;
/** /**
* Surrounds the string with the databases identifier escape characters * Surrounds the string with the databases identifier escape characters
@ -148,9 +150,9 @@ interface DriverInterface {
* *
* @param string $sql * @param string $sql
* @param array $params * @param array $params
* @return \PDOStatement * @return PDOStatement
*/ */
public function prepareExecute($sql, $params); public function prepareExecute(string $sql, array $params): ?PDOStatement;
/** /**
* Method to simplify retrieving db results for meta-data queries * Method to simplify retrieving db results for meta-data queries
@ -159,14 +161,14 @@ interface DriverInterface {
* @param bool $filteredIndex * @param bool $filteredIndex
* @return array * @return array
*/ */
public function driverQuery($query, $filteredIndex=TRUE); public function driverQuery($query, $filteredIndex=TRUE): ?array;
/** /**
* Returns number of rows affected by an INSERT, UPDATE, DELETE type query * Returns number of rows affected by an INSERT, UPDATE, DELETE type query
* *
* @return int * @return int
*/ */
public function affectedRows(); public function affectedRows(): int;
/** /**
* Return the number of rows returned for a SELECT query * Return the number of rows returned for a SELECT query
@ -174,7 +176,7 @@ interface DriverInterface {
* *
* @return int * @return int
*/ */
public function numRows(); public function numRows(): ?int;
/** /**
* Prefixes a table if it is not already prefixed * Prefixes a table if it is not already prefixed
@ -182,7 +184,7 @@ interface DriverInterface {
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function prefixTable($table); public function prefixTable(string $table): string;
/** /**
* Create sql for batch insert * Create sql for batch insert
@ -191,7 +193,7 @@ interface DriverInterface {
* @param array $data * @param array $data
* @return array * @return array
*/ */
public function insertBatch($table, $data=[]); public function insertBatch(string $table, array $data=[]): array;
/** /**
* Creates a batch update, and executes it. * Creates a batch update, and executes it.
@ -202,7 +204,7 @@ interface DriverInterface {
* @param string $where * @param string $where
* @return int|null * @return int|null
*/ */
public function updateBatch($table, $data, $where); public function updateBatch(string $table, $data, $where);
/** /**
* Get the SQL class for the current driver * Get the SQL class for the current driver
@ -224,5 +226,5 @@ interface DriverInterface {
* @param string $queryString * @param string $queryString
* @return void * @return void
*/ */
public function setLastQuery(string $queryString); public function setLastQuery(string $queryString): void;
} }

View File

@ -16,12 +16,11 @@ namespace Query\Drivers\Mysql;
use PDO; use PDO;
use Query\Drivers\AbstractDriver; use Query\Drivers\AbstractDriver;
use Query\Drivers\DriverInterface;
/** /**
* MySQL specific class * MySQL specific class
*/ */
class Driver extends AbstractDriver implements DriverInterface { class Driver extends AbstractDriver {
/** /**
* Set the backtick as the MySQL escape character * Set the backtick as the MySQL escape character
@ -46,7 +45,7 @@ class Driver extends AbstractDriver implements DriverInterface {
* @param string $password * @param string $password
* @param array $options * @param array $options
*/ */
public function __construct($dsn, $username=NULL, $password=NULL, array $options=[]) public function __construct(string $dsn, string $username=NULL, string $password=NULL, array $options=[])
{ {
// Set the charset to UTF-8 // Set the charset to UTF-8
if (\defined('\\PDO::MYSQL_ATTR_INIT_COMMAND')) if (\defined('\\PDO::MYSQL_ATTR_INIT_COMMAND'))

View File

@ -29,7 +29,7 @@ class SQL extends AbstractSQL {
* @param int|boolean $offset * @param int|boolean $offset
* @return string * @return string
*/ */
public function limit($sql, $limit, $offset=FALSE) public function limit(string $sql, int $limit, $offset=FALSE): string
{ {
if ( ! is_numeric($offset)) if ( ! is_numeric($offset))
{ {
@ -45,7 +45,7 @@ class SQL extends AbstractSQL {
* @param string $sql * @param string $sql
* @return string * @return string
*/ */
public function explain($sql) public function explain(string $sql): string
{ {
return "EXPLAIN EXTENDED {$sql}"; return "EXPLAIN EXTENDED {$sql}";
} }
@ -55,7 +55,7 @@ class SQL extends AbstractSQL {
* *
* @return string * @return string
*/ */
public function random() public function random(): string
{ {
return ' RAND() DESC'; return ' RAND() DESC';
} }
@ -65,7 +65,7 @@ class SQL extends AbstractSQL {
* *
* @return string * @return string
*/ */
public function dbList() public function dbList(): string
{ {
return "SHOW DATABASES WHERE `Database` NOT IN ('information_schema','mysql')"; return "SHOW DATABASES WHERE `Database` NOT IN ('information_schema','mysql')";
} }
@ -76,12 +76,14 @@ class SQL extends AbstractSQL {
* @param string $database * @param string $database
* @return string * @return string
*/ */
public function tableList($database='') public function tableList($database=''): string
{ {
// @codeCoverageIgnoreStart
if ( ! empty($database)) if ( ! empty($database))
{ {
return "SHOW TABLES FROM `{$database}`"; return "SHOW TABLES FROM `{$database}`";
} }
// @codeCoverageIgnoreEnd
return 'SHOW TABLES'; return 'SHOW TABLES';
} }
@ -91,7 +93,7 @@ class SQL extends AbstractSQL {
* *
* @return string * @return string
*/ */
public function systemTableList() public function systemTableList(): string
{ {
return 'SELECT `TABLE_NAME` FROM `information_schema`.`TABLES` return 'SELECT `TABLE_NAME` FROM `information_schema`.`TABLES`
WHERE `TABLE_SCHEMA`=\'information_schema\''; WHERE `TABLE_SCHEMA`=\'information_schema\'';
@ -102,7 +104,7 @@ class SQL extends AbstractSQL {
* *
* @return string * @return string
*/ */
public function viewList() public function viewList(): string
{ {
return 'SELECT `table_name` FROM `information_schema`.`views`'; return 'SELECT `table_name` FROM `information_schema`.`views`';
} }
@ -112,7 +114,7 @@ class SQL extends AbstractSQL {
* *
* @return string * @return string
*/ */
public function triggerList() public function triggerList(): string
{ {
return 'SHOW TRIGGERS'; return 'SHOW TRIGGERS';
} }
@ -122,7 +124,7 @@ class SQL extends AbstractSQL {
* *
* @return string * @return string
*/ */
public function functionList() public function functionList(): string
{ {
return 'SHOW FUNCTION STATUS'; return 'SHOW FUNCTION STATUS';
} }
@ -132,7 +134,7 @@ class SQL extends AbstractSQL {
* *
* @return string * @return string
*/ */
public function procedureList() public function procedureList(): string
{ {
return 'SHOW PROCEDURE STATUS'; return 'SHOW PROCEDURE STATUS';
} }
@ -140,9 +142,9 @@ class SQL extends AbstractSQL {
/** /**
* Return sql to list sequences * Return sql to list sequences
* *
* @return NULL * @return string
*/ */
public function sequenceList() public function sequenceList(): ?string
{ {
return NULL; return NULL;
} }
@ -152,7 +154,7 @@ class SQL extends AbstractSQL {
* *
* @return string * @return string
*/ */
public function typeList() public function typeList(): string
{ {
return "SELECT DISTINCT `DATA_TYPE` FROM `information_schema`.`COLUMNS`"; return "SELECT DISTINCT `DATA_TYPE` FROM `information_schema`.`COLUMNS`";
} }
@ -163,7 +165,7 @@ class SQL extends AbstractSQL {
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function columnList($table) public function columnList(string $table): string
{ {
return "SHOW FULL COLUMNS FROM {$table}"; return "SHOW FULL COLUMNS FROM {$table}";
} }
@ -175,7 +177,7 @@ class SQL extends AbstractSQL {
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function fkList($table) public function fkList(string $table): string
{ {
return <<<SQL return <<<SQL
SELECT DISTINCT `kcu`.`COLUMN_NAME` as `child_column`, SELECT DISTINCT `kcu`.`COLUMN_NAME` as `child_column`,
@ -197,9 +199,9 @@ SQL;
* Get the list of indexes for the current table * Get the list of indexes for the current table
* *
* @param string $table * @param string $table
* @return array * @return string
*/ */
public function indexList($table) public function indexList(string $table): string
{ {
return "SHOW INDEX IN {$table}"; return "SHOW INDEX IN {$table}";
} }

View File

@ -37,10 +37,12 @@ class Util extends AbstractUtil {
foreach($dbs as &$d) foreach($dbs as &$d)
{ {
// Skip built-in dbs // Skip built-in dbs
// @codeCoverageIgnoreStart
if ($d === 'mysql') if ($d === 'mysql')
{ {
continue; continue;
} }
// @codeCoverageIgnoreEnd
// Get the list of tables // Get the list of tables
$tables = $this->getDriver()->driverQuery("SHOW TABLES FROM `{$d}`", TRUE); $tables = $this->getDriver()->driverQuery("SHOW TABLES FROM `{$d}`", TRUE);

View File

@ -1,175 +0,0 @@
<?php declare(strict_types=1);
/**
* Query
*
* SQL Query Builder / Database Abstraction Layer
*
* PHP version 7.1
*
* @package Query
* @author Timothy J. Warren <tim@timshomepage.net>
* @copyright 2012 - 2018 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query
*/
namespace Query\Drivers;
use PDO;
/**
* Interface created from official PHP Documentation
*/
interface PDOStatementInterface {
/**
* Bind a column to a PHP variable
*
* @param mixed $column Number or name of the column in the result set
* @param mixed $param Name of the PHP variable to which the column will be bound
* @param int $type Data type of the parameter, specified by the PDO::PARAM_* constants
* @param int $maxlen A hint for pre-allocation
* @param mixed $driverdata Optional parameter(s) for the driver
* @return boolean
*/
public function bindColumn($column, &$param, $type, $maxlen, $driverdata);
/**
* Binds a parameter to the specified variable name
*
* @param mixed $parameter Parameter identifier. For a prepared statement using named placeholders, this will be a
* 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 $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 $driverOptions
* @return boolean
*/
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
* prepare the statement
*
* @param mixed $parameter Parameter identifier. For a prepared statement using named placeholders, this will be a
* 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 $dataType Explicit data type for the parameter using the PDO::PARAM_* constants.
* @return boolean
*/
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
* state that enables it to be executed again
*
* @return boolean
*/
public function closeCursor();
/**
* Returns the number of columns in the result set
*
* @return int
*/
public function columnCount();
/**
* Dumps the information contained by a prepared statement directly on the output
*
* @return void
*/
public function debugDumpParams();
/**
* Fetch the SQLSTATE associated with the last operation on the statement handle
*
* @return string
*/
public function errorCode();
/**
* Fetch extended error information associated with the last operation on the statement handle
*
* @return array
*/
public function errorInfo();
/**
* Run a prepared statement query
*
* @param array $boundInputParams
* @return boolean
*/
public function execute($boundInputParams = NULL);
/**
* Fetches the next row from a result set
*
* @param int $how
* @param int $orientation
* @param int $offset
* @return mixed
*/
public function fetch($how = PDO::ATTR_DEFAULT_FETCH_MODE, $orientation = PDO::FETCH_ORI_NEXT, $offset = 0);
/**
* Returns a single column from the next row of a result set
*
* @param int $columnNumber
* @return mixed
*/
public function fetchColumn($columnNumber = 0);
/**
* Fetches the next row and returns it as an object
*
* @param string $className
* @param array $ctorArgs
* @return mixed
*/
public function fetchObject($className = "stdClass", $ctorArgs = NULL);
/**
* Retrieve a statement attribute
*
* @param int $attribute
* @return mixed
*/
public function getAttribute($attribute);
/**
* Advances to the next rowset in a multi-rowset statement handle
*
* @return boolean
*/
public function nextRowset();
/**
* Returns the number of rows affected by the last SQL statement
*
* @return int
*/
public function rowCount();
/**
* Set a statement attribute
*
* @param int $attribute
* @param mixed $value
* @return boolean
*/
public function setAttribute($attribute, $value);
/**
* Set the default fetch mode for this statement
*
* @param int $mode
* @return boolean
*/
public function setFetchMode($mode);
}

View File

@ -15,12 +15,11 @@
namespace Query\Drivers\Pgsql; namespace Query\Drivers\Pgsql;
use Query\Drivers\AbstractDriver; use Query\Drivers\AbstractDriver;
use Query\Drivers\DriverInterface;
/** /**
* PostgreSQL specific class * PostgreSQL specific class
*/ */
class Driver extends AbstractDriver implements DriverInterface { class Driver extends AbstractDriver {
/** /**
* Connect to a PosgreSQL database * Connect to a PosgreSQL database

View File

@ -27,7 +27,7 @@ class SQL extends AbstractSQL {
* @param string $sql * @param string $sql
* @return string * @return string
*/ */
public function explain($sql) public function explain(string $sql): string
{ {
return "EXPLAIN VERBOSE {$sql}"; return "EXPLAIN VERBOSE {$sql}";
} }
@ -37,7 +37,7 @@ class SQL extends AbstractSQL {
* *
* @return string * @return string
*/ */
public function random() public function random(): string
{ {
return ' RANDOM()'; return ' RANDOM()';
} }
@ -47,7 +47,7 @@ class SQL extends AbstractSQL {
* *
* @return string * @return string
*/ */
public function dbList() public function dbList(): string
{ {
return <<<SQL return <<<SQL
SELECT "datname" FROM "pg_database" SELECT "datname" FROM "pg_database"
@ -61,7 +61,7 @@ SQL;
* *
* @return string * @return string
*/ */
public function tableList() public function tableList(): string
{ {
return <<<SQL return <<<SQL
SELECT "table_name" SELECT "table_name"
@ -77,7 +77,7 @@ SQL;
* *
* @return string * @return string
*/ */
public function systemTableList() public function systemTableList(): string
{ {
return <<<SQL return <<<SQL
SELECT "table_name" SELECT "table_name"
@ -93,7 +93,7 @@ SQL;
* *
* @return string * @return string
*/ */
public function viewList() public function viewList(): string
{ {
return <<<SQL return <<<SQL
SELECT "viewname" FROM "pg_views" SELECT "viewname" FROM "pg_views"
@ -109,7 +109,7 @@ SQL;
* *
* @return string * @return string
*/ */
public function triggerList() public function triggerList(): string
{ {
return <<<SQL return <<<SQL
SELECT * SELECT *
@ -122,9 +122,9 @@ SQL;
/** /**
* Return sql to list functions * Return sql to list functions
* *
* @return NULL * @return string
*/ */
public function functionList() public function functionList(): ?string
{ {
return NULL; return NULL;
} }
@ -134,7 +134,7 @@ SQL;
* *
* @return string * @return string
*/ */
public function procedureList() public function procedureList(): string
{ {
return <<<SQL return <<<SQL
SELECT "routine_name" SELECT "routine_name"
@ -150,7 +150,7 @@ SQL;
* *
* @return string * @return string
*/ */
public function sequenceList() public function sequenceList(): string
{ {
return <<<SQL return <<<SQL
SELECT "c"."relname" SELECT "c"."relname"
@ -166,7 +166,7 @@ SQL;
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function columnList($table) public function columnList(string $table): string
{ {
return <<<SQL return <<<SQL
SELECT ordinal_position, SELECT ordinal_position,
@ -187,7 +187,7 @@ SQL;
* *
* @return string * @return string
*/ */
public function typeList() public function typeList(): string
{ {
return <<<SQL return <<<SQL
SELECT "typname" FROM "pg_catalog"."pg_type" SELECT "typname" FROM "pg_catalog"."pg_type"
@ -204,7 +204,7 @@ SQL;
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function fkList($table) public function fkList(string $table): string
{ {
return <<<SQL return <<<SQL
SELECT SELECT
@ -244,9 +244,9 @@ SQL;
* Get the list of indexes for the current table * Get the list of indexes for the current table
* *
* @param string $table * @param string $table
* @return array * @return string
*/ */
public function indexList($table) public function indexList(string $table): string
{ {
return <<<SQL return <<<SQL
SELECT SELECT

View File

@ -30,7 +30,7 @@ interface SQLInterface {
* @param int|bool $offset * @param int|bool $offset
* @return string * @return string
*/ */
public function limit($sql, $limit, $offset=FALSE); public function limit(string $sql, int $limit, $offset=FALSE): string;
/** /**
* Modify the query to get the query plan * Modify the query to get the query plan
@ -38,33 +38,33 @@ interface SQLInterface {
* @param string $sql * @param string $sql
* @return string * @return string
*/ */
public function explain($sql); public function explain(string $sql): string;
/** /**
* Get the sql for random ordering * Get the sql for random ordering
* *
* @return string * @return string
*/ */
public function random(); public function random(): string;
/** /**
* Returns sql to list other databases * Returns sql to list other databases
* *
* @return string * @return string
*/ */
public function dbList(); public function dbList(): string;
/** /**
* Returns sql to list tables * Returns sql to list tables
* *
* @return string * @return string
*/ */
public function tableList(); public function tableList(): string;
/** /**
* Returns sql to list system tables * Returns sql to list system tables
* *
* @return string * @return string|array
*/ */
public function systemTableList(); public function systemTableList();
@ -73,35 +73,35 @@ interface SQLInterface {
* *
* @return string * @return string
*/ */
public function viewList(); public function viewList(): string;
/** /**
* Returns sql to list triggers * Returns sql to list triggers
* *
* @return string * @return string
*/ */
public function triggerList(); public function triggerList(): ?string;
/** /**
* Return sql to list functions * Return sql to list functions
* *
* @return NULL * @return string
*/ */
public function functionList(); public function functionList(): ?string;
/** /**
* Return sql to list stored procedures * Return sql to list stored procedures
* *
* @return string * @return string
*/ */
public function procedureList(); public function procedureList(): ?string;
/** /**
* Return sql to list sequences * Return sql to list sequences
* *
* @return string * @return string
*/ */
public function sequenceList(); public function sequenceList(): ?string;
/** /**
* Return sql to list database field types * Return sql to list database field types
@ -117,22 +117,22 @@ interface SQLInterface {
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function columnList($table); public function columnList(string $table): string;
/** /**
* Get the list of foreign keys for the current * Get the list of foreign keys for the current
* table * table
* *
* @param string $table * @param string $table
* @return array * @return string
*/ */
public function fkList($table); public function fkList(string $table): string;
/** /**
* Get the list of indexes for the current table * Get the list of indexes for the current table
* *
* @param string $table * @param string $table
* @return array * @return string
*/ */
public function indexList($table); public function indexList(string $table): string;
} }

View File

@ -15,21 +15,12 @@
namespace Query\Drivers\Sqlite; namespace Query\Drivers\Sqlite;
use PDO; use PDO;
use PDOStatement;
use Query\Drivers\AbstractDriver; use Query\Drivers\AbstractDriver;
use Query\Drivers\DriverInterface;
/** /**
* SQLite specific class * SQLite specific class
*/ */
class Driver extends AbstractDriver implements DriverInterface { class Driver extends AbstractDriver {
/**
* Reference to the last executed sql query
*
* @var PDOStatement
*/
protected $statement;
/** /**
* SQLite has a truncate optimization, * SQLite has a truncate optimization,
@ -65,7 +56,7 @@ class Driver extends AbstractDriver implements DriverInterface {
{ {
$sql = $this->sql->tableList(); $sql = $this->sql->tableList();
$res = $this->query($sql); $res = $this->query($sql);
return db_filter($res->fetchAll(PDO::FETCH_ASSOC), 'name'); return dbFilter($res->fetchAll(PDO::FETCH_ASSOC), 'name');
} }
/** /**
@ -98,9 +89,9 @@ class Driver extends AbstractDriver implements DriverInterface {
* @codeCoverageIgnore * @codeCoverageIgnore
* @param string $table * @param string $table
* @param array $data * @param array $data
* @return string * @return array
*/ */
public function insertBatch($table, $data=[]) public function insertBatch(string $table, array $data=[]): array
{ {
// If greater than version 3.7.11, supports the same syntax as // If greater than version 3.7.11, supports the same syntax as
// MySQL and Postgres // MySQL and Postgres
@ -114,7 +105,7 @@ class Driver extends AbstractDriver implements DriverInterface {
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// Each member of the data array needs to be an array // Each member of the data array needs to be an array
if ( ! is_array(current($data))) if ( ! \is_array(current($data)))
{ {
return NULL; return NULL;
} }

View File

@ -27,7 +27,7 @@ class SQL extends AbstractSQL {
* @param string $sql * @param string $sql
* @return string * @return string
*/ */
public function explain($sql) public function explain(string $sql): string
{ {
return "EXPLAIN QUERY PLAN {$sql}"; return "EXPLAIN QUERY PLAN {$sql}";
} }
@ -37,7 +37,7 @@ class SQL extends AbstractSQL {
* *
* @return string * @return string
*/ */
public function random() public function random(): string
{ {
return ' RANDOM()'; return ' RANDOM()';
} }
@ -47,7 +47,7 @@ class SQL extends AbstractSQL {
* *
* @return string * @return string
*/ */
public function dbList() public function dbList(): string
{ {
return 'PRAGMA database_list'; return 'PRAGMA database_list';
} }
@ -57,7 +57,7 @@ class SQL extends AbstractSQL {
* *
* @return string * @return string
*/ */
public function tableList() public function tableList(): string
{ {
return <<<SQL return <<<SQL
SELECT DISTINCT "name" SELECT DISTINCT "name"
@ -73,7 +73,7 @@ SQL;
* *
* @return string[] * @return string[]
*/ */
public function systemTableList() public function systemTableList(): array
{ {
return ['sqlite_master', 'sqlite_temp_master', 'sqlite_sequence']; return ['sqlite_master', 'sqlite_temp_master', 'sqlite_sequence'];
} }
@ -83,7 +83,7 @@ SQL;
* *
* @return string * @return string
*/ */
public function viewList() public function viewList(): string
{ {
return <<<SQL return <<<SQL
SELECT "name" FROM "sqlite_master" WHERE "type" = 'view' SELECT "name" FROM "sqlite_master" WHERE "type" = 'view'
@ -95,7 +95,7 @@ SQL;
* *
* @return string * @return string
*/ */
public function triggerList() public function triggerList(): string
{ {
return 'SELECT "name" FROM "sqlite_master" WHERE "type"=\'trigger\''; return 'SELECT "name" FROM "sqlite_master" WHERE "type"=\'trigger\'';
} }
@ -103,9 +103,9 @@ SQL;
/** /**
* Return sql to list functions * Return sql to list functions
* *
* @return NULL * @return string
*/ */
public function functionList() public function functionList(): ?string
{ {
return NULL; return NULL;
} }
@ -113,9 +113,9 @@ SQL;
/** /**
* Return sql to list stored procedures * Return sql to list stored procedures
* *
* @return NULL * @return string
*/ */
public function procedureList() public function procedureList(): ?string
{ {
return NULL; return NULL;
} }
@ -123,9 +123,9 @@ SQL;
/** /**
* Return sql to list sequences * Return sql to list sequences
* *
* @return NULL * @return string
*/ */
public function sequenceList() public function sequenceList(): ?string
{ {
return NULL; return NULL;
} }
@ -135,18 +135,18 @@ SQL;
* *
* @return string[] * @return string[]
*/ */
public function typeList() public function typeList(): array
{ {
return ['INTEGER', 'REAL', 'TEXT', 'BLOB']; return ['INTEGER', 'REAL', 'TEXT', 'BLOB'];
} }
/** /**
* SQL to show infromation about columns in a table * SQL to show information about columns in a table
* *
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function columnList($table) public function columnList(string $table): string
{ {
return 'PRAGMA table_info("' . $table . '")'; return 'PRAGMA table_info("' . $table . '")';
} }
@ -158,7 +158,7 @@ SQL;
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function fkList($table) public function fkList(string $table): string
{ {
return 'PRAGMA foreign_key_list("' . $table . '")'; return 'PRAGMA foreign_key_list("' . $table . '")';
} }
@ -170,7 +170,7 @@ SQL;
* @param string $table * @param string $table
* @return string * @return string
*/ */
public function indexList($table) public function indexList(string $table): string
{ {
return 'PRAGMA index_list("' . $table . '")'; return 'PRAGMA index_list("' . $table . '")';
} }

View File

@ -120,21 +120,14 @@ class QueryBuilder implements QueryBuilderInterface {
*/ */
public function __call(string $name, array $params) public function __call(string $name, array $params)
{ {
// Alias snake_case method calls //foreach([$this, $this->driver] as $object)
$camelName = \to_camel_case($name);
foreach([$this, $this->driver] as $object)
{ {
foreach([$name, $camelName] as $methodName) if (method_exists($this->driver, $name))
{ {
if (method_exists($object, $methodName)) return \call_user_func_array([$this->driver, $name], $params);
{
return \call_user_func_array([$object, $methodName], $params);
} }
} }
}
throw new BadMethodCallException('Method does not exist'); throw new BadMethodCallException('Method does not exist');
} }
@ -1102,7 +1095,7 @@ class QueryBuilder implements QueryBuilderInterface {
// Determine the correct conjunction // Determine the correct conjunction
$conjunctionList = array_column($queryMap, 'conjunction'); $conjunctionList = array_column($queryMap, 'conjunction');
if (empty($queryMap) || ( ! regex_in_array($conjunctionList, "/^ ?\n?WHERE/i"))) if (empty($queryMap) || ( ! \regexInArray($conjunctionList, "/^ ?\n?WHERE/i")))
{ {
$conj = "\nWHERE "; $conj = "\nWHERE ";
} }

View File

@ -165,7 +165,7 @@ class State {
* @param string $fromString * @param string $fromString
* @return State * @return State
*/ */
public function setFromString(string $fromString): State public function setFromString(string $fromString): self
{ {
$this->fromString = $fromString; $this->fromString = $fromString;
return $this; return $this;
@ -183,7 +183,7 @@ class State {
* @param string $setString * @param string $setString
* @return State * @return State
*/ */
public function setSetString(string $setString): State public function setSetString(string $setString): self
{ {
$this->setString = $setString; $this->setString = $setString;
return $this; return $this;
@ -201,7 +201,7 @@ class State {
* @param string $orderString * @param string $orderString
* @return State * @return State
*/ */
public function setOrderString(string $orderString): State public function setOrderString(string $orderString): self
{ {
$this->orderString = $orderString; $this->orderString = $orderString;
return $this; return $this;
@ -219,7 +219,7 @@ class State {
* @param string $groupString * @param string $groupString
* @return State * @return State
*/ */
public function setGroupString(string $groupString): State public function setGroupString(string $groupString): self
{ {
$this->groupString = $groupString; $this->groupString = $groupString;
return $this; return $this;
@ -237,7 +237,7 @@ class State {
* @param array $setArrayKeys * @param array $setArrayKeys
* @return State * @return State
*/ */
public function appendSetArrayKeys(array $setArrayKeys): State public function appendSetArrayKeys(array $setArrayKeys): self
{ {
$this->setArrayKeys = array_merge($this->setArrayKeys, $setArrayKeys); $this->setArrayKeys = array_merge($this->setArrayKeys, $setArrayKeys);
return $this; return $this;
@ -247,7 +247,7 @@ class State {
* @param array $setArrayKeys * @param array $setArrayKeys
* @return State * @return State
*/ */
public function setSetArrayKeys(array $setArrayKeys): State public function setSetArrayKeys(array $setArrayKeys): self
{ {
$this->setArrayKeys = $setArrayKeys; $this->setArrayKeys = $setArrayKeys;
return $this; return $this;
@ -266,7 +266,7 @@ class State {
* @param mixed $orderArray * @param mixed $orderArray
* @return State * @return State
*/ */
public function setOrderArray(string $key, $orderArray): State public function setOrderArray(string $key, $orderArray): self
{ {
$this->orderArray[$key] = $orderArray; $this->orderArray[$key] = $orderArray;
return $this; return $this;
@ -284,7 +284,7 @@ class State {
* @param array $groupArray * @param array $groupArray
* @return State * @return State
*/ */
public function setGroupArray(array $groupArray): State public function setGroupArray(array $groupArray): self
{ {
$this->groupArray = $groupArray; $this->groupArray = $groupArray;
return $this; return $this;
@ -294,7 +294,7 @@ class State {
* @param string $groupArray * @param string $groupArray
* @return State * @return State
*/ */
public function appendGroupArray(string $groupArray): State public function appendGroupArray(string $groupArray): self
{ {
$this->groupArray[] = $groupArray; $this->groupArray[] = $groupArray;
return $this; return $this;
@ -312,7 +312,7 @@ class State {
* @param array $values * @param array $values
* @return State * @return State
*/ */
public function appendValues(array $values): State public function appendValues(array $values): self
{ {
$this->values = array_merge($this->values, $values); $this->values = array_merge($this->values, $values);
return $this; return $this;
@ -330,7 +330,7 @@ class State {
* @param mixed $val * @param mixed $val
* @return State * @return State
*/ */
public function appendWhereValues($val): State public function appendWhereValues($val): self
{ {
if (\is_array($val)) if (\is_array($val))
{ {
@ -358,7 +358,7 @@ class State {
* @param int $limit * @param int $limit
* @return State * @return State
*/ */
public function setLimit(int $limit): State public function setLimit(int $limit): self
{ {
$this->limit = $limit; $this->limit = $limit;
return $this; return $this;
@ -376,7 +376,7 @@ class State {
* @param string|false $offset * @param string|false $offset
* @return State * @return State
*/ */
public function setOffset($offset): State public function setOffset($offset): self
{ {
$this->offset = $offset; $this->offset = $offset;
return $this; return $this;
@ -420,7 +420,7 @@ class State {
* @param array $item * @param array $item
* @return State * @return State
*/ */
public function appendHavingMap(array $item): State public function appendHavingMap(array $item): self
{ {
$this->havingMap[] = $item; $this->havingMap[] = $item;
return $this; return $this;

View File

@ -25,33 +25,28 @@ use Query\{
* Global functions that don't really fit anywhere else * Global functions that don't really fit anywhere else
*/ */
if ( ! function_exists('mb_trim')) /**
{
/**
* Multibyte-safe trim function * Multibyte-safe trim function
* *
* @param string $string * @param string $string
* @return string * @return string
*/ */
function mb_trim(string $string): string function mb_trim(string $string): string
{ {
return preg_replace('/(^\s+)|(\s+$)/u', '', $string); return preg_replace('/(^\s+)|(\s+$)/u', '', $string);
}
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
if ( ! function_exists('db_filter')) /**
{
/**
* Filter out db rows into one array * Filter out db rows into one array
* *
* @param array $array * @param array $array
* @param mixed $index * @param mixed $index
* @return array * @return array
*/ */
function db_filter(array $array, $index): array function dbFilter(array $array, $index): array
{ {
$newArray = []; $newArray = [];
foreach($array as $a) foreach($array as $a)
@ -60,37 +55,11 @@ if ( ! function_exists('db_filter'))
} }
return $newArray; return $newArray;
}
}
if ( ! function_exists('to_camel_case'))
{
/**
* Create a camelCase string from snake_case
*
* @param string $snakeCase
* @return string
*/
function to_camel_case(string $snakeCase): string
{
$pieces = explode('_', $snakeCase);
$numPieces = count($pieces);
$pieces[0] = mb_strtolower($pieces[0]);
for($i = 1; $i < $numPieces; $i++)
{
$pieces[$i] = ucfirst(mb_strtolower($pieces[$i]));
}
return implode('', $pieces);
}
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
if ( ! function_exists('array_zipper')) /**
{
/**
* Zip a set of arrays together on common keys * Zip a set of arrays together on common keys
* *
* The $zipperInput 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
@ -99,8 +68,8 @@ if ( ! function_exists('array_zipper'))
* @param array $zipperInput * @param array $zipperInput
* @return array * @return array
*/ */
function array_zipper(array $zipperInput): array function arrayZipper(array $zipperInput): array
{ {
$output = []; $output = [];
foreach($zipperInput as $appendKey => $values) foreach($zipperInput as $appendKey => $values)
@ -116,14 +85,11 @@ if ( ! function_exists('array_zipper'))
} }
return $output; return $output;
}
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
if ( ! function_exists('regex_in_array')) /**
{
/**
* Determine whether a value in the passed array matches the pattern * Determine whether a value in the passed array matches the pattern
* passed * passed
* *
@ -131,8 +97,8 @@ if ( ! function_exists('regex_in_array'))
* @param string $pattern * @param string $pattern
* @return bool * @return bool
*/ */
function regex_in_array(array $array, string $pattern): bool function regexInArray(array $array, string $pattern): bool
{ {
if (empty($array)) if (empty($array))
{ {
return FALSE; return FALSE;
@ -147,14 +113,11 @@ if ( ! function_exists('regex_in_array'))
} }
return FALSE; return FALSE;
}
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
if ( ! function_exists('Query')) /**
{
/**
* Connection function * Connection function
* *
* Send an array or object as connection parameters to create a connection. If * Send an array or object as connection parameters to create a connection. If
@ -165,15 +128,15 @@ if ( ! function_exists('Query'))
* @param string|object|array $params * @param string|object|array $params
* @return QueryBuilderInterface|null * @return QueryBuilderInterface|null
*/ */
function Query($params = ''): ?QueryBuilderInterface function Query($params = ''): ?QueryBuilderInterface
{ {
$manager = ConnectionManager::getInstance();
if ($params === NULL) if ($params === NULL)
{ {
return NULL; return NULL;
} }
$manager = ConnectionManager::getInstance();
// If you are getting a previously created connection // If you are getting a previously created connection
if (is_scalar($params)) if (is_scalar($params))
{ {
@ -184,6 +147,6 @@ if ( ! function_exists('Query'))
// Otherwise, return a new connection // Otherwise, return a new connection
return $manager->connect($paramsObject); return $manager->connect($paramsObject);
}
} }
// End of common.php // End of common.php

View File

@ -63,4 +63,14 @@ class CoreTest extends TestCase {
$this->assertTrue($numSupported > 0); $this->assertTrue($numSupported > 0);
} }
public function testNullQuery(): void
{
$this->assertNull(\Query(NULL));
}
public function testEmptyRegexInArray(): void
{
$this->assertFalse(\regexInArray([], 'foo'));
}
} }

View File

@ -14,10 +14,10 @@
*/ */
namespace Query\Tests\Drivers\MySQL; namespace Query\Tests\Drivers\MySQL;
use InvalidArgumentException;
use PDO; use PDO;
use Query\Drivers\Mysql\Driver; use Query\Drivers\Mysql\Driver;
use Query\Tests\BaseDriverTest; use Query\Tests\BaseDriverTest;
use TypeError;
/** /**
* MySQLTest class. * MySQLTest class.
@ -132,7 +132,7 @@ SQL;
public function testBadPreparedStatement() public function testBadPreparedStatement()
{ {
$this->expectException(InvalidArgumentException::class); $this->expectException(TypeError::class);
$sql = <<<SQL $sql = <<<SQL
INSERT INTO `create_test` (`id`, `key`, `val`) INSERT INTO `create_test` (`id`, `key`, `val`)

View File

@ -20,6 +20,7 @@ use InvalidArgumentException;
use PDO; use PDO;
use Query\Drivers\Pgsql\Driver; use Query\Drivers\Pgsql\Driver;
use Query\Tests\BaseDriverTest; use Query\Tests\BaseDriverTest;
use TypeError;
/** /**
* PgTest class. * PgTest class.
@ -162,7 +163,7 @@ SQL;
public function testBadPreparedStatement() public function testBadPreparedStatement()
{ {
$this->expectException(InvalidArgumentException::class); $this->expectException(TypeError::class);
$sql = <<<SQL $sql = <<<SQL
INSERT INTO "create_test" ("id", "key", "val") INSERT INTO "create_test" ("id", "key", "val")