Version 3 #1

Manually merged
timw4mail merged 47 commits from develop into master 2020-04-23 18:39:27 -04:00
20 changed files with 310 additions and 194 deletions
Showing only changes of commit 3067976cb1 - Show all commits

View File

@ -118,12 +118,13 @@ final class ConnectionManager {
/** /**
* Parse the passed parameters and return a connection * Parse the passed parameters and return a connection
* *
* @param \stdClass $params * @param object|array $params
* @throws BadDBDriverException
* @return QueryBuilderInterface * @return QueryBuilderInterface
*/ */
public function connect(\stdClass $params): QueryBuilderInterface public function connect($params): QueryBuilderInterface
{ {
list($dsn, $dbtype, $params, $options) = $this->parseParams($params); [$dsn, $dbtype, $params, $options] = $this->parseParams($params);
$dbtype = ucfirst($dbtype); $dbtype = ucfirst($dbtype);
$driver = "\\Query\\Drivers\\{$dbtype}\\Driver"; $driver = "\\Query\\Drivers\\{$dbtype}\\Driver";
@ -160,11 +161,12 @@ final class ConnectionManager {
* Parses params into a dsn and option array * Parses params into a dsn and option array
* *
* @param \stdClass $params * @param \stdClass $params
* @return array * @return object|array
* @throws BadDBDriverException * @throws BadDBDriverException
*/ */
public function parseParams(\stdClass $params): array public function parseParams($params): array
{ {
$params = (object) $params;
$params->type = strtolower($params->type); $params->type = strtolower($params->type);
$dbtype = ($params->type !== 'postgresql') ? $params->type : 'pgsql'; $dbtype = ($params->type !== 'postgresql') ? $params->type : 'pgsql';
$dbtype = ucfirst($dbtype); $dbtype = ucfirst($dbtype);
@ -202,10 +204,10 @@ final class ConnectionManager {
* *
* @codeCoverageIgnore * @codeCoverageIgnore
* @param string $dbtype * @param string $dbtype
* @param \stdClass $params * @param array|object $params
* @return string * @return string
*/ */
private function createDsn(string $dbtype, \stdClass $params): string private function createDsn(string $dbtype, $params): string
{ {
$pairs = []; $pairs = [];

View File

@ -561,15 +561,73 @@ abstract class AbstractDriver
* Creates a batch update, and executes it. * Creates a batch update, and executes it.
* Returns the number of affected rows * Returns the number of affected rows
* *
* @param string $table * @param string $table The table to update
* @param array|object $data * @param array $data an array of update values
* @param string $where * @param string $where The where key
* @return int|null * @return array<string,array,int>
*/ */
public function updateBatch(string $table, $data, $where) public function updateBatch(string $table, array $data, string $where): array
{ {
// @TODO implement $affectedRows = 0;
return NULL; $insertData = [];
$fieldLines = [];
$sql = 'UPDATE ' . $this->quoteTable($table) . ' SET ';
// Get the keys of the current set of data, except the one used to
// set the update condition
$fields = array_unique(
array_reduce($data, function ($previous, $current) use (&$affectedRows, $where) {
$affectedRows++;
$keys = array_diff(array_keys($current), [$where]);
if ($previous === NULL)
{
return $keys;
}
return array_merge($previous, $keys);
})
);
// Create the CASE blocks for each data set
foreach ($fields as $field)
{
$line = $this->quoteIdent($field) . " = CASE\n";
$cases = [];
foreach ($data as $case)
{
if (array_key_exists($field, $case))
{
$insertData[] = $case[$where];
$insertData[] = $case[$field];
$cases[] = 'WHEN ' . $this->quoteIdent($where) . ' =? '
. 'THEN ? ';
}
}
$line .= implode("\n", $cases) . "\n";
$line .= 'ELSE ' . $this->quoteIdent($field) . ' END';
$fieldLines[] = $line;
}
$sql .= implode(",\n", $fieldLines) . "\n";
$whereValues = array_column($data, $where);
foreach ($whereValues as $value)
{
$insertData[] = $value;
}
// Create the placeholders for the WHERE IN clause
$placeholders = array_fill(0, count($whereValues), '?');
$sql .= 'WHERE ' . $this->quoteIdent($where) . ' IN ';
$sql .= '(' . implode(',', $placeholders) . ')';
return [$sql, $insertData, $affectedRows];
} }
/** /**
@ -578,7 +636,7 @@ abstract class AbstractDriver
* @param string $table * @param string $table
* @return PDOStatement * @return PDOStatement
*/ */
public function truncate(string $table): PDOStatement public function truncate(string $table): ?PDOStatement
{ {
$sql = $this->hasTruncate $sql = $this->hasTruncate
? 'TRUNCATE TABLE ' ? 'TRUNCATE TABLE '

View File

@ -62,11 +62,11 @@ abstract class AbstractUtil {
$existsStr = $ifNotExists ? ' IF NOT EXISTS ' : ' '; $existsStr = $ifNotExists ? ' IF NOT EXISTS ' : ' ';
// Reorganize into an array indexed with column information // Reorganize into an array indexed with column information
// Eg $columnArray[$colname] = array( // Eg $columnArray[$colname] = [
// 'type' => ..., // 'type' => ...,
// 'constraint' => ..., // 'constraint' => ...,
// 'index' => ..., // 'index' => ...,
// ) // ]
$columnArray = \arrayZipper([ $columnArray = \arrayZipper([
'type' => $fields, 'type' => $fields,
'constraint' => $constraints 'constraint' => $constraints

View File

@ -14,6 +14,7 @@
*/ */
namespace Query\Drivers; namespace Query\Drivers;
use PDO;
use PDOStatement; use PDOStatement;
/** /**
@ -129,6 +130,15 @@ interface DriverInterface {
*/ */
public function getTriggers(): ?array; public function getTriggers(): ?array;
/**
* Quotes a string for use in a query (from native PDO)
*
* @param string $string
* @param int $parameter_type
* @return string
*/
public function quote($string, $parameter_type = NULL);
/** /**
* Surrounds the string with the databases identifier escape characters * Surrounds the string with the databases identifier escape characters
* *
@ -200,11 +210,11 @@ interface DriverInterface {
* Returns the number of affected rows * Returns the number of affected rows
* *
* @param string $table * @param string $table
* @param array|object $data * @param array $data
* @param string $where * @param string $where
* @return int|null * @return array
*/ */
public function updateBatch(string $table, $data, $where): ?int; public function updateBatch(string $table, array $data, string $where): array;
/** /**
* Get the SQL class for the current driver * Get the SQL class for the current driver

View File

@ -774,18 +774,22 @@ class QueryBuilder implements QueryBuilderInterface {
* Returns the number of affected rows * Returns the number of affected rows
* *
* @param string $table * @param string $table
* @param array|object $data * @param array $data
* @param string $where * @param string $where
* @return PDOStatement|null * @return int|null
*/ */
public function updateBatch(string $table, $data, $where): ?PDOStatement public function updateBatch(string $table, array $data, string $where): ?int
{ {
// Get the generated values and sql string if (empty($table) || empty($data) || empty($where))
list($sql, $data) = $this->driver->updateBatch($table, $data, $where); {
return NULL;
}
return $sql !== NULL // Get the generated values and sql string
? $this->_run('', $table, $sql, $data) [$sql, $data, $affectedRows] = $this->driver->updateBatch($table, $data, $where);
: NULL;
$this->_run('', $table, $sql, $data);
return $affectedRows;
} }
/** /**
@ -1158,14 +1162,14 @@ class QueryBuilder implements QueryBuilderInterface {
/** /**
* Convert the prepared statement into readable sql * Convert the prepared statement into readable sql
* *
* @param array $vals * @param array $values
* @param string $sql * @param string $sql
* @param int $totalTime * @param int $totalTime
* @return void * @return void
*/ */
protected function _appendQuery(array $vals = NULL, string $sql, int $totalTime) protected function _appendQuery(array $values = NULL, string $sql, int $totalTime)
{ {
$evals = \is_array($vals) ? $vals : []; $evals = \is_array($values) ? $values : [];
$esql = str_replace('?', "%s", $sql); $esql = str_replace('?', "%s", $sql);
// Quote string values // Quote string values

View File

@ -393,12 +393,12 @@ interface QueryBuilderInterface {
* Creates a batch update, and executes it. * Creates a batch update, and executes it.
* Returns the number of affected rows * Returns the number of affected rows
* *
* @param string $table * @param string $table The table to update
* @param array|object $data * @param array $data an array of update values
* @param string $where * @param string $where The where key
* @return PDOStatement * @return int|null
*/ */
public function updateBatch(string $table, $data, $where): ?PDOStatement; public function updateBatch(string $table, array $data, string $where): ?int;
/** /**
* Deletes data from a table * Deletes data from a table

View File

@ -108,11 +108,11 @@ class State {
* for complex select queries * for complex select queries
* *
* Format: * Format:
* array( * [
* 'type' => 'where', * 'type' => 'where',
* 'conjunction' => ' AND ', * 'conjunction' => ' AND ',
* 'string' => 'k=?' * 'string' => 'k=?'
* ) * ]
* *
* @var array * @var array
*/ */

View File

@ -35,46 +35,46 @@ abstract class BaseDriverTest extends TestCase {
public function testGetTables() public function testGetTables()
{ {
$tables = self::$db->getTables(); $tables = self::$db->getTables();
$this->assertTrue(is_array($tables)); $this->assertTrue(\is_array($tables));
$this->assertTrue( ! empty($tables)); $this->assertTrue( ! empty($tables));
} }
public function testGetSystemTables() public function testGetSystemTables()
{ {
$tables = self::$db->getSystemTables(); $tables = self::$db->getSystemTables();
$this->assertTrue(is_array($tables)); $this->assertTrue(\is_array($tables));
$this->assertTrue( ! empty($tables)); $this->assertTrue( ! empty($tables));
} }
public function testBackupData() public function testBackupData()
{ {
$this->assertTrue(is_string(self::$db->getUtil()->backupData(array('create_delete', FALSE)))); $this->assertTrue(\is_string(self::$db->getUtil()->backupData(['create_delete', FALSE])));
$this->assertTrue(is_string(self::$db->getUtil()->backupData(array('create_delete', TRUE)))); $this->assertTrue(\is_string(self::$db->getUtil()->backupData(['create_delete', TRUE])));
} }
public function testGetColumns() public function testGetColumns()
{ {
$cols = self::$db->getColumns('test'); $cols = self::$db->getColumns('test');
$this->assertTrue(is_array($cols)); $this->assertTrue(\is_array($cols));
$this->assertTrue( ! empty($cols)); $this->assertTrue( ! empty($cols));
} }
public function testGetTypes() public function testGetTypes()
{ {
$types = self::$db->getTypes(); $types = self::$db->getTypes();
$this->assertTrue(is_array($types)); $this->assertTrue(\is_array($types));
$this->assertTrue( ! empty($types)); $this->assertTrue( ! empty($types));
} }
public function testGetFKs() public function testGetFKs()
{ {
$expected = array(array( $expected = [[
'child_column' => 'ext_id', 'child_column' => 'ext_id',
'parent_table' => 'testconstraints', 'parent_table' => 'testconstraints',
'parent_column' => 'someid', 'parent_column' => 'someid',
'update' => 'CASCADE', 'update' => 'CASCADE',
'delete' => 'CASCADE' 'delete' => 'CASCADE'
)); ]];
$keys = self::$db->getFks('testconstraints2'); $keys = self::$db->getFks('testconstraints2');
$this->assertEqual($expected, $keys); $this->assertEqual($expected, $keys);
@ -83,15 +83,15 @@ abstract class BaseDriverTest extends TestCase {
public function testGetIndexes() public function testGetIndexes()
{ {
$keys = self::$db->getIndexes('test'); $keys = self::$db->getIndexes('test');
$this->assertTrue(is_array($keys)); $this->assertTrue(\is_array($keys));
} }
public function testGetViews() public function testGetViews()
{ {
$views = self::$db->getViews(); $views = self::$db->getViews();
$expected = array('numbersview', 'testview'); $expected = ['numbersview', 'testview'];
$this->assertEqual($expected, array_values($views)); $this->assertEqual($expected, array_values($views));
$this->assertTrue(is_array($views)); $this->assertTrue(\is_array($views));
} }
public function testGetTriggers() public function testGetTriggers()
@ -99,7 +99,7 @@ abstract class BaseDriverTest extends TestCase {
// @TODO standardize trigger output for different databases // @TODO standardize trigger output for different databases
$triggers = self::$db->getTriggers(); $triggers = self::$db->getTriggers();
$this->assertTrue(is_array($triggers)); $this->assertTrue(\is_array($triggers));
} }
public function testGetSequences() public function testGetSequences()
@ -109,22 +109,22 @@ abstract class BaseDriverTest extends TestCase {
// Normalize sequence names // Normalize sequence names
$seqs = array_map('strtolower', $seqs); $seqs = array_map('strtolower', $seqs);
$expected = array('newtable_seq'); $expected = ['newtable_seq'];
$this->assertTrue(is_array($seqs)); $this->assertTrue(\is_array($seqs));
$this->assertEqual($expected, $seqs); $this->assertEqual($expected, $seqs);
} }
public function testGetProcedures() public function testGetProcedures()
{ {
$procedures = self::$db->getProcedures(); $procedures = self::$db->getProcedures();
$this->assertTrue(is_array($procedures)); $this->assertTrue(\is_array($procedures));
} }
public function testGetFunctions() public function testGetFunctions()
{ {
$funcs = self::$db->getFunctions(); $funcs = self::$db->getFunctions();
$this->assertTrue(is_array($funcs)); $this->assertTrue(\is_array($funcs));
} }
} }
// End of db_test.php // End of db_test.php

View File

@ -14,7 +14,9 @@
*/ */
namespace Query\Tests; namespace Query\Tests;
use BadMethodCallException;
use PDO; use PDO;
use Query\BadDBDriverException;
/** /**
* Query builder parent test class * Query builder parent test class
@ -36,6 +38,11 @@ abstract class BaseQueryBuilderTest extends TestCase {
public static function tearDownAfterClass() public static function tearDownAfterClass()
{ {
if (PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg')
{
echo '<pre>' . print_r(self::$db->queries, TRUE) . '</pre>';
}
self::$db = NULL; self::$db = NULL;
} }
@ -100,7 +107,7 @@ abstract class BaseQueryBuilderTest extends TestCase {
public function testGetWhere() public function testGetWhere()
{ {
$query = self::$db->getWhere('test', array('id !=' => 1), 2, 1); $query = self::$db->getWhere('test', ['id !=' => 1], 2, 1);
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
} }
@ -110,7 +117,7 @@ abstract class BaseQueryBuilderTest extends TestCase {
$query = self::$db->select('id') $query = self::$db->select('id')
->from('test') ->from('test')
->groupBy('id') ->groupBy('id')
->having(array('id >' => 1)) ->having(['id >' => 1])
->having('id !=', 3) ->having('id !=', 3)
->get(); ->get();
@ -122,7 +129,7 @@ abstract class BaseQueryBuilderTest extends TestCase {
$query = self::$db->select('id') $query = self::$db->select('id')
->from('test') ->from('test')
->groupBy('id') ->groupBy('id')
->having(array('id >' => 1)) ->having(['id >' => 1])
->orHaving('id !=', 3) ->orHaving('id !=', 3)
->get(); ->get();
@ -325,7 +332,7 @@ abstract class BaseQueryBuilderTest extends TestCase {
public function testWhereIn() public function testWhereIn()
{ {
$query = self::$db->from('test') $query = self::$db->from('test')
->whereIn('id', array(0, 6, 56, 563, 341)) ->whereIn('id', [0, 6, 56, 563, 341])
->get(); ->get();
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
@ -335,7 +342,7 @@ abstract class BaseQueryBuilderTest extends TestCase {
{ {
$query = self::$db->from('test') $query = self::$db->from('test')
->where('key', 'false') ->where('key', 'false')
->orWhereIn('id', array(0, 6, 56, 563, 341)) ->orWhereIn('id', [0, 6, 56, 563, 341])
->get(); ->get();
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
@ -345,7 +352,7 @@ abstract class BaseQueryBuilderTest extends TestCase {
{ {
$query = self::$db->from('test') $query = self::$db->from('test')
->where('key', 'false') ->where('key', 'false')
->whereNotIn('id', array(0, 6, 56, 563, 341)) ->whereNotIn('id', [0, 6, 56, 563, 341])
->get(); ->get();
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
@ -355,7 +362,7 @@ abstract class BaseQueryBuilderTest extends TestCase {
{ {
$query = self::$db->from('test') $query = self::$db->from('test')
->where('key', 'false') ->where('key', 'false')
->orWhereNotIn('id', array(0, 6, 56, 563, 341)) ->orWhereNotIn('id', [0, 6, 56, 563, 341])
->get(); ->get();
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
@ -395,7 +402,7 @@ abstract class BaseQueryBuilderTest extends TestCase {
->where('id >', 0) ->where('id >', 0)
->where('id <', 9000) ->where('id <', 9000)
->groupBy('k') ->groupBy('k')
->groupBy(array('id','val')) ->groupBy(['id','val'])
->orderBy('id', 'DESC') ->orderBy('id', 'DESC')
->orderBy('k', 'ASC') ->orderBy('k', 'ASC')
->limit(5,2) ->limit(5,2)
@ -506,10 +513,10 @@ abstract class BaseQueryBuilderTest extends TestCase {
{ {
$query = self::$db->from('test ct') $query = self::$db->from('test ct')
->join('join cj', 'cj.id=ct.id', 'inner') ->join('join cj', 'cj.id=ct.id', 'inner')
->where(array( ->where([
'ct.id < ' => 3, 'ct.id < ' => 3,
'ct.key' => 'foo' 'ct.key' => 'foo'
)) ])
->get(); ->get();
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
@ -529,34 +536,34 @@ abstract class BaseQueryBuilderTest extends TestCase {
public function testInsertArray() public function testInsertArray()
{ {
$query = self::$db->insert('test', array( $query = self::$db->insert('test', [
'id' => 587, 'id' => 587,
'key' => 1, 'key' => 1,
'val' => 2, 'val' => 2,
)); ]);
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
} }
public function testInsertBatch() public function testInsertBatch()
{ {
$data = array( $data = [
array( [
'id' => 544, 'id' => 544,
'key' => 3, 'key' => 3,
'val' => 7, 'val' => 7,
), ],
array( [
'id' => 89, 'id' => 890,
'key' => 34, 'key' => 34,
'val' => "10 o'clock", 'val' => "10 o'clock",
), ],
array( [
'id' => 48, 'id' => 480,
'key' => 403, 'key' => 403,
'val' => 97, 'val' => 97,
), ],
); ];
$query = self::$db->insertBatch('test', $data); $query = self::$db->insertBatch('test', $data);
@ -566,28 +573,47 @@ abstract class BaseQueryBuilderTest extends TestCase {
public function testUpdate() public function testUpdate()
{ {
$query = self::$db->where('id', 7) $query = self::$db->where('id', 7)
->update('test', array( ->update('test', [
'id' => 7, 'id' => 7,
'key' => 'gogle', 'key' => 'gogle',
'val' => 'non-word' 'val' => 'non-word'
)); ]);
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
} }
public function testUpdateBatch() public function testUpdateBatchNull()
{ {
$query = self::$db->updateBatch('test', [], ''); $query = self::$db->updateBatch('test', [], '');
$this->assertNull($query); $this->assertNull($query);
} }
public function testDriverUpdateBatch()
{
$data = [
[
'id' => 480,
'key' => 49,
'val' => '7x7'
],
[
'id' => 890,
'key' => 100,
'val' => '10x10'
]
];
$affectedRows = self::$db->updateBatch('test', $data, 'id');
$this->assertEquals(2, $affectedRows);
}
public function testSetArrayUpdate() public function testSetArrayUpdate()
{ {
$array = array( $array = [
'id' => 22, 'id' => 22,
'key' => 'gogle', 'key' => 'gogle',
'val' => 'non-word' 'val' => 'non-word'
); ];
$query = self::$db->set($array) $query = self::$db->set($array)
->where('id', 22) ->where('id', 22)
@ -609,17 +635,17 @@ abstract class BaseQueryBuilderTest extends TestCase {
public function testDelete() public function testDelete()
{ {
$query = self::$db->delete('test', array('id' => 5)); $query = self::$db->delete('test', ['id' => 5]);
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
} }
public function testDeleteWithMultipleWhereValues() public function testDeleteWithMultipleWhereValues()
{ {
$query = self::$db->delete('test', array( $query = self::$db->delete('test', [
'id' => 5, 'id' => 5,
'key' => 'gogle' 'key' => 'gogle'
)); ]);
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
} }
@ -671,22 +697,22 @@ abstract class BaseQueryBuilderTest extends TestCase {
public function testGetCompiledUpdate() public function testGetCompiledUpdate()
{ {
$sql = self::$db->set(array( $sql = self::$db->set([
'id' => 4, 'id' => 4,
'key' => 'foo', 'key' => 'foo',
'val' => 'baz' 'val' => 'baz'
))->getCompiledUpdate('test'); ])->getCompiledUpdate('test');
$this->assertTrue(\is_string($sql)); $this->assertTrue(\is_string($sql));
} }
public function testGetCompiledInsert() public function testGetCompiledInsert()
{ {
$sql = self::$db->set(array( $sql = self::$db->set([
'id' => 4, 'id' => 4,
'key' => 'foo', 'key' => 'foo',
'val' => 'baz' 'val' => 'baz'
))->getCompiledInsert('test'); ])->getCompiledInsert('test');
$this->assertTrue(\is_string($sql)); $this->assertTrue(\is_string($sql));
} }
@ -704,34 +730,34 @@ abstract class BaseQueryBuilderTest extends TestCase {
*/ */
public function testBadDriver() public function testBadDriver()
{ {
$params = array( $params = [
'host' => '127.0.0.1', 'host' => '127.0.0.1',
'port' => '3306', 'port' => '3306',
'database' => 'test', 'database' => 'test',
'user' => 'root', 'user' => 'root',
'pass' => NULL, 'pass' => NULL,
'type' => 'QGYFHGEG' 'type' => 'QGYFHGEG'
); ];
$this->expectException('Query\BadDBDriverException'); $this->expectException(BadDBDriverException::class);
self::$db = Query($params); self::$db = Query($params);
} }
public function testBadMethod() public function testBadMethod()
{ {
$this->expectException('BadMethodCallException'); $this->expectException(BadMethodCallException::class);
self::$db->foo(); self::$db->foo();
} }
public function testBadNumRows() public function testBadNumRows()
{ {
self::$db->set(array( self::$db->set([
'id' => 999, 'id' => 999,
'key' => 'ring', 'key' => 'ring',
'val' => 'sale' 'val' => 'sale'
))->insert('test'); ])->insert('test');
$res = self::$db->numRows(); $res = self::$db->numRows();
$this->assertEqual(NULL, $res); $this->assertEqual(NULL, $res);

View File

@ -26,6 +26,11 @@ class ConnectionManagerTest extends TestCase {
self::$instance = ConnectionManager::getInstance(); self::$instance = ConnectionManager::getInstance();
} }
public static function tearDownAfterClass()
{
self::$instance = NULL;
}
public function testNoClone() public function testNoClone()
{ {
$this->expectException('DomainException'); $this->expectException('DomainException');
@ -54,34 +59,34 @@ class ConnectionManagerTest extends TestCase {
public function testParseParams() public function testParseParams()
{ {
$params = (object) array( $params = new class {
'type' => 'sqlite', public $type = 'sqlite';
'file' => ':memory:', public $file = ':memory:';
'options' => array( public $options = [
'foo' => 'bar' 'foo' => 'bar'
) ];
); };
$expected = array( $expected = [
':memory:', ':memory:',
'Sqlite', 'Sqlite',
$params, $params,
array('foo' => 'bar') ['foo' => 'bar']
); ];
$this->assertEqual($expected, self::$instance->parseParams($params)); $this->assertEqual($expected, self::$instance->parseParams($params));
} }
public function testConnect() public function testConnect()
{ {
$params = (object) array( $params = new class {
'type' => 'sqlite', public $type = 'sqlite';
'file' => ':memory:', public $file = ':memory:';
'prefix' => 'create_', public $prefix = 'create_';
'options' => array( public $options = [
'foo' => 'bar' 'foo' => 'bar'
) ];
); };
$conn = self::$instance->connect($params); $conn = self::$instance->connect($params);
$this->assertInstanceOf(QueryBuilderInterface::class, $conn); $this->assertInstanceOf(QueryBuilderInterface::class, $conn);
@ -93,15 +98,15 @@ class ConnectionManagerTest extends TestCase {
public function testGetConnection() public function testGetConnection()
{ {
$params = (object) array( $params = (object) [
'type' => 'sqlite', 'type' => 'sqlite',
'file' => ':memory:', 'file' => ':memory:',
'prefix' => 'create_', 'prefix' => 'create_',
'alias' => 'conn_manager', 'alias' => 'conn_manager',
'options' => array( 'options' => [
'foo' => 'bar' 'foo' => 'bar'
) ]
); ];
$conn = self::$instance->connect($params); $conn = self::$instance->connect($params);
$this->assertInstanceOf(QueryBuilderInterface::class, $conn); $this->assertInstanceOf(QueryBuilderInterface::class, $conn);

View File

@ -14,6 +14,10 @@
*/ */
namespace Query\Tests; namespace Query\Tests;
use function Query;
use function regexInArray;
use PDO;
/** /**
* CoreTest class - Compatibility and core functionality tests * CoreTest class - Compatibility and core functionality tests
* *
@ -29,8 +33,9 @@ class CoreTest extends TestCase {
*/ */
public function testPHPVersion(): void public function testPHPVersion(): void
{ {
//$this->assertTrue(version_compare(PHP_VERSION, '7.1', 'ge')); $this->assertTrue(PHP_VERSION_ID >= 70100);
$this->assertTrue(PHP_VERSION_ID >= 70000); $this->assertTrue(PHP_MAJOR_VERSION >= 7);
$this->assertTrue(PHP_MINOR_VERSION >= 1);
} }
/** /**
@ -52,7 +57,7 @@ class CoreTest extends TestCase {
'sqlite', 'sqlite',
]; ];
$drivers = \PDO::getAvailableDrivers(); $drivers = PDO::getAvailableDrivers();
$numSupported = count(array_intersect($drivers, $supported)); $numSupported = count(array_intersect($drivers, $supported));
@ -61,11 +66,11 @@ class CoreTest extends TestCase {
public function testNullQuery(): void public function testNullQuery(): void
{ {
$this->assertNull(\Query(NULL)); $this->assertNull(Query(NULL));
} }
public function testEmptyRegexInArray(): void public function testEmptyRegexInArray(): void
{ {
$this->assertFalse(\regexInArray([], 'foo')); $this->assertFalse(regexInArray([], 'foo'));
} }
} }

View File

@ -38,9 +38,9 @@ class MySQLDriverTest extends BaseDriverTest {
{ {
$params = $params->mysql; $params = $params->mysql;
self::$db = new 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, [
PDO::ATTR_PERSISTENT => TRUE PDO::ATTR_PERSISTENT => TRUE
)); ]);
} }
self::$db->setTablePrefix('create_'); self::$db->setTablePrefix('create_');
@ -62,28 +62,28 @@ class MySQLDriverTest extends BaseDriverTest {
//Attempt to create the table //Attempt to create the table
$sql = self::$db->getUtil()->createTable('test', $sql = self::$db->getUtil()->createTable('test',
array( [
'id' => 'int(10)', 'id' => 'int(10)',
'key' => 'TEXT', 'key' => 'TEXT',
'val' => 'TEXT', 'val' => 'TEXT',
), ],
array( [
'id' => 'PRIMARY KEY' 'id' => 'PRIMARY KEY'
) ]
); );
self::$db->query($sql); self::$db->query($sql);
//Attempt to create the table //Attempt to create the table
$sql = self::$db->getUtil()->createTable('join', $sql = self::$db->getUtil()->createTable('join',
array( [
'id' => 'int(10)', 'id' => 'int(10)',
'key' => 'TEXT', 'key' => 'TEXT',
'val' => 'TEXT', 'val' => 'TEXT',
), ],
array( [
'id' => 'PRIMARY KEY' 'id' => 'PRIMARY KEY'
) ]
); );
self::$db->query($sql); self::$db->query($sql);
@ -94,6 +94,7 @@ class MySQLDriverTest extends BaseDriverTest {
} }
public function testTruncate() public function testTruncate()
{ {
self::$db->truncate('test'); self::$db->truncate('test');
@ -109,7 +110,7 @@ class MySQLDriverTest extends BaseDriverTest {
INSERT INTO `create_test` (`id`, `key`, `val`) INSERT INTO `create_test` (`id`, `key`, `val`)
VALUES (?,?,?) VALUES (?,?,?)
SQL; SQL;
$statement = self::$db->prepareQuery($sql, array(1,"boogers", "Gross")); $statement = self::$db->prepareQuery($sql, [1,"boogers", "Gross"]);
$res = $statement->execute(); $res = $statement->execute();
@ -142,9 +143,9 @@ SQL;
INSERT INTO `create_test` (`id`, `key`, `val`) INSERT INTO `create_test` (`id`, `key`, `val`)
VALUES (?,?,?) VALUES (?,?,?)
SQL; SQL;
$res = self::$db->prepareExecute($sql, array( $res = self::$db->prepareExecute($sql, [
2, "works", 'also?' 2, "works", 'also?'
)); ]);
$this->assertInstanceOf('PDOStatement', $res); $this->assertInstanceOf('PDOStatement', $res);
@ -184,6 +185,6 @@ SQL;
public function testBackup() public function testBackup()
{ {
$this->assertTrue(is_string(self::$db->getUtil()->backupStructure())); $this->assertTrue(\is_string(self::$db->getUtil()->backupStructure()));
} }
} }

View File

@ -25,9 +25,9 @@ class MySQLQueryBuilderTest extends BaseQueryBuilderTest {
public static function setUpBeforeClass() public static function setUpBeforeClass()
{ {
$params = get_json_config(); $params = get_json_config();
if (($var = getenv('TRAVIS'))) // Travis CI Connection Info if ($var = getenv('TRAVIS')) // Travis CI Connection Info
{ {
$params = array( $params = [
'host' => '127.0.0.1', 'host' => '127.0.0.1',
'port' => '3306', 'port' => '3306',
'database' => 'test', 'database' => 'test',
@ -35,14 +35,14 @@ class MySQLQueryBuilderTest extends BaseQueryBuilderTest {
'user' => 'root', 'user' => 'root',
'pass' => NULL, 'pass' => NULL,
'type' => 'mysql' 'type' => 'mysql'
); ];
} }
// Attempt to connect, if there is a test config file // Attempt to connect, if there is a test config file
else if ($params !== FALSE) else if ($params !== FALSE)
{ {
$params = $params->mysql; $params = $params->mysql;
$params->type = "MySQL"; $params->type = 'MySQL';
$params->options = array(); $params->options = [];
$params->options[PDO::ATTR_PERSISTENT] = TRUE; $params->options[PDO::ATTR_PERSISTENT] = TRUE;
} }
@ -67,7 +67,7 @@ class MySQLQueryBuilderTest extends BaseQueryBuilderTest {
// The exact results are version dependent // The exact results are version dependent
// The important thing is that there is an array // The important thing is that there is an array
// of results returned // of results returned
$this->assertTrue(is_array($res)); $this->assertTrue(\is_array($res));
$this->assertTrue(count(array_keys($res[0])) > 1); $this->assertTrue(count(array_keys($res[0])) > 1);
$this->assertTrue(array_key_exists('table', $res[0])); $this->assertTrue(array_key_exists('table', $res[0]));
} }

View File

@ -81,28 +81,28 @@ class PgSQLDriverTest extends BaseDriverTest {
//Attempt to create the table //Attempt to create the table
$sql = self::$db->getUtil()->createTable('create_test', $sql = self::$db->getUtil()->createTable('create_test',
array( [
'id' => 'integer', 'id' => 'integer',
'key' => 'TEXT', 'key' => 'TEXT',
'val' => 'TEXT', 'val' => 'TEXT',
), ],
array( [
'id' => 'PRIMARY KEY' 'id' => 'PRIMARY KEY'
) ]
); );
self::$db->query($sql); self::$db->query($sql);
//Attempt to create the table //Attempt to create the table
$sql = self::$db->getUtil()->createTable('create_join', $sql = self::$db->getUtil()->createTable('create_join',
array( [
'id' => 'integer', 'id' => 'integer',
'key' => 'TEXT', 'key' => 'TEXT',
'val' => 'TEXT', 'val' => 'TEXT',
), ],
array( [
'id' => 'PRIMARY KEY' 'id' => 'PRIMARY KEY'
) ]
); );
self::$db->query($sql); self::$db->query($sql);
@ -133,7 +133,7 @@ class PgSQLDriverTest extends BaseDriverTest {
INSERT INTO "create_test" ("id", "key", "val") INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?) VALUES (?,?,?)
SQL; SQL;
$statement = self::$db->prepareQuery($sql, array(1,'boogers', 'Gross')); $statement = self::$db->prepareQuery($sql, [1,'boogers', 'Gross']);
$statement->execute(); $statement->execute();
@ -173,9 +173,9 @@ SQL;
INSERT INTO "create_test" ("id", "key", "val") INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?) VALUES (?,?,?)
SQL; SQL;
self::$db->prepareExecute($sql, array( self::$db->prepareExecute($sql, [
2, 'works', 'also?' 2, 'works', 'also?'
)); ]);
$res = self::$db->query('SELECT * FROM "create_test" WHERE "id"=2') $res = self::$db->query('SELECT * FROM "create_test" WHERE "id"=2')
->fetch(PDO::FETCH_ASSOC); ->fetch(PDO::FETCH_ASSOC);
@ -215,12 +215,12 @@ SQL;
public function testGetSchemas() public function testGetSchemas()
{ {
$this->assertTrue(is_array(self::$db->getSchemas())); $this->assertTrue(\is_array(self::$db->getSchemas()));
} }
public function testGetDBs() public function testGetDBs()
{ {
$this->assertTrue(is_array(self::$db->getDbs())); $this->assertTrue(\is_array(self::$db->getDbs()));
} }
public function testGetFunctions() public function testGetFunctions()

View File

@ -27,7 +27,7 @@ class PgSQLQueryBuilderTest extends BaseQueryBuilderTest {
$params = get_json_config(); $params = get_json_config();
if (getenv('TRAVIS')) // Travis CI Connection Info if (getenv('TRAVIS')) // Travis CI Connection Info
{ {
$params = array( $params = [
'host' => '127.0.0.1', 'host' => '127.0.0.1',
'port' => '5432', 'port' => '5432',
'database' => 'test', 'database' => 'test',
@ -35,7 +35,7 @@ class PgSQLQueryBuilderTest extends BaseQueryBuilderTest {
'pass' => '', 'pass' => '',
'type' => 'pgsql', 'type' => 'pgsql',
'prefix' => 'create_' 'prefix' => 'create_'
); ];
} }
// Attempt to connect, if there is a test config file // Attempt to connect, if there is a test config file
else if ($params !== FALSE) else if ($params !== FALSE)
@ -44,7 +44,7 @@ class PgSQLQueryBuilderTest extends BaseQueryBuilderTest {
$params->type = 'pgsql'; $params->type = 'pgsql';
//$params->port = 5432; //$params->port = 5432;
//$params->prefix = 'create_'; //$params->prefix = 'create_';
$params->options = array(); $params->options = [];
$params->options[PDO::ATTR_PERSISTENT] = TRUE; $params->options[PDO::ATTR_PERSISTENT] = TRUE;
} }

View File

@ -28,15 +28,15 @@ class SQLiteDriverTest extends BaseDriverTest {
public static function setupBeforeClass() public static function setupBeforeClass()
{ {
$params = array( $params = [
'type' => 'sqlite', 'type' => 'sqlite',
'file' => ':memory:', 'file' => ':memory:',
'prefix' => 'create_', 'prefix' => 'create_',
'alias' => 'test_sqlite', 'alias' => 'test_sqlite',
'options' => array( 'options' => [
PDO::ATTR_PERSISTENT => TRUE PDO::ATTR_PERSISTENT => TRUE
) ]
); ];
self::$db = Query($params); self::$db = Query($params);
self::$db->setTablePrefix('create_'); self::$db->setTablePrefix('create_');
@ -64,7 +64,7 @@ class SQLiteDriverTest extends BaseDriverTest {
/*public function testBackupData() /*public function testBackupData()
{ {
$sql = mb_trim(self::$db->getUtil()->backupData(array('create_join', 'create_test'))); $sql = mb_trim(self::$db->getUtil()->backupData(['create_join', 'create_test']));
$sqlArray = explode("\n", $sql); $sqlArray = explode("\n", $sql);
@ -192,7 +192,7 @@ SQL;
INSERT INTO "create_test" ("id", "key", "val") INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?) VALUES (?,?,?)
SQL; SQL;
$statement = self::$db->prepareQuery($sql, array(1,"boogers", "Gross")); $statement = self::$db->prepareQuery($sql, [1,"boogers", "Gross"]);
$statement->execute(); $statement->execute();
@ -212,9 +212,9 @@ SQL;
INSERT INTO "create_test" ("id", "key", "val") INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?) VALUES (?,?,?)
SQL; SQL;
self::$db->prepareExecute($sql, array( self::$db->prepareExecute($sql, [
2, "works", 'also?' 2, "works", 'also?'
)); ]);
$res = self::$db->query('SELECT * FROM "create_test" WHERE "id"=2') $res = self::$db->query('SELECT * FROM "create_test" WHERE "id"=2')
->fetch(PDO::FETCH_ASSOC); ->fetch(PDO::FETCH_ASSOC);

View File

@ -34,7 +34,7 @@ use Query\Tests\BaseQueryBuilderTest;
{ {
$db = Query('test_sqlite'); $db = Query('test_sqlite');
$this->assertTrue(self::$db === $db, "Alias passed into query function gives the original object back"); $this->assertTrue(self::$db === $db, 'Alias passed into query function gives the original object back');
} }
public function testQueryExplain() public function testQueryExplain()
@ -47,49 +47,49 @@ use Query\Tests\BaseQueryBuilderTest;
$res = $query->fetchAll(PDO::FETCH_ASSOC); $res = $query->fetchAll(PDO::FETCH_ASSOC);
$expectedPossibilities = array(); $expectedPossibilities = [];
$expectedPossibilities[] = array( $expectedPossibilities[] = [
array( [
'order' => '0', 'order' => '0',
'from' => '0', 'from' => '0',
'detail' => 'TABLE create_test USING PRIMARY KEY', 'detail' => 'TABLE create_test USING PRIMARY KEY',
) ]
); ];
$expectedPossibilities[] = array ( $expectedPossibilities[] = [
array ( [
'selectid' => '0', 'selectid' => '0',
'order' => '0', 'order' => '0',
'from' => '0', 'from' => '0',
'detail' => 'SEARCH TABLE create_test USING INTEGER PRIMARY KEY (rowid>? AND rowid<?) (~60000 rows)', 'detail' => 'SEARCH TABLE create_test USING INTEGER PRIMARY KEY (rowid>? AND rowid<?) (~60000 rows)',
), ],
); ];
$expectedPossibilities[] = array ( $expectedPossibilities[] = [
array ( [
'selectid' => '0', 'selectid' => '0',
'order' => '0', 'order' => '0',
'from' => '0', 'from' => '0',
'detail' => 'SEARCH TABLE create_test USING INTEGER PRIMARY KEY (rowid>? AND rowid<?)', 'detail' => 'SEARCH TABLE create_test USING INTEGER PRIMARY KEY (rowid>? AND rowid<?)',
), ],
); ];
$expectedPossibilities[] = array ( $expectedPossibilities[] = [
array ( [
'selectid' => '0', 'selectid' => '0',
'order' => '0', 'order' => '0',
'from' => '0', 'from' => '0',
'detail' => 'SEARCH TABLE create_test USING INTEGER PRIMARY KEY (rowid>? AND rowid<?) (~62500 rows)', 'detail' => 'SEARCH TABLE create_test USING INTEGER PRIMARY KEY (rowid>? AND rowid<?) (~62500 rows)',
), ],
); ];
$passed = FALSE; $passed = FALSE;
// Check for a matching possibility // Check for a matching possibility
foreach($expectedPossibilities as $ep) foreach($expectedPossibilities as $ep)
{ {
if ($res == $ep) if ($res === $ep)
{ {
$this->assertTrue(TRUE); $this->assertTrue(TRUE);
$passed = TRUE; $passed = TRUE;

View File

@ -35,32 +35,32 @@ class QueryParserTest extends TestCase {
public function testGeneric() public function testGeneric()
{ {
$matches = $this->parser->parseJoin('table1.field1=table2.field2'); $matches = $this->parser->parseJoin('table1.field1=table2.field2');
$this->assertEqual($matches['combined'], array( $this->assertEqual($matches['combined'], [
'table1.field1', '=', 'table2.field2' 'table1.field1', '=', 'table2.field2'
)); ]);
} }
public function testGeneric2() public function testGeneric2()
{ {
$matches = $this->parser->parseJoin('db1.table1.field1!=db2.table2.field2'); $matches = $this->parser->parseJoin('db1.table1.field1!=db2.table2.field2');
$this->assertEqual($matches['combined'], array( $this->assertEqual($matches['combined'], [
'db1.table1.field1','!=','db2.table2.field2' 'db1.table1.field1','!=','db2.table2.field2'
)); ]);
} }
public function testWUnderscore() public function testWUnderscore()
{ {
$matches = $this->parser->parseJoin('table_1.field1 = tab_le2.field_2'); $matches = $this->parser->parseJoin('table_1.field1 = tab_le2.field_2');
$this->assertEqual($matches['combined'], array( $this->assertEqual($matches['combined'], [
'table_1.field1', '=', 'tab_le2.field_2' 'table_1.field1', '=', 'tab_le2.field_2'
)); ]);
} }
public function testFunction() public function testFunction()
{ {
$matches = $this->parser->parseJoin('table1.field1 > SUM(3+5)'); $matches = $this->parser->parseJoin('table1.field1 > SUM(3+5)');
$this->assertEqual($matches['combined'], array( $this->assertEqual($matches['combined'], [
'table1.field1', '>', 'SUM(3+5)' 'table1.field1', '>', 'SUM(3+5)'
)); ]);
} }
} }

View File

@ -20,10 +20,10 @@ define('QDS', DIRECTORY_SEPARATOR);
function get_json_config() function get_json_config()
{ {
$files = array( $files = [
__DIR__ . '/settings.json', __DIR__ . '/settings.json',
__DIR__ . '/settings.json.dist' __DIR__ . '/settings.json.dist'
); ];
foreach($files as $file) foreach($files as $file)
{ {

View File

@ -87,6 +87,11 @@ namespace Query\Tests {
$this->skipUnless(FALSE, $message); $this->skipUnless(FALSE, $message);
} }
public function expectException($exception = FALSE, $message = '%s')
{
return parent::expectException(FALSE);
}
/** /**
* Alias to the method in PHPUnit * Alias to the method in PHPUnit
* *
@ -106,10 +111,10 @@ namespace Query\Tests {
namespace { namespace {
function get_json_config() function get_json_config()
{ {
$files = array( $files = [
__DIR__ . '/settings.json', __DIR__ . '/settings.json',
__DIR__ . '/settings.json.dist' __DIR__ . '/settings.json.dist'
); ];
foreach ($files as $file) { foreach ($files as $file) {
if (is_file($file)) { if (is_file($file)) {