Attempting some Quercus compatibility, test-suite runs with simpletest as well as PHPUnit

This commit is contained in:
Timothy Warren 2014-06-09 17:02:14 -04:00
parent 6a38213a62
commit 1abd835f47
23 changed files with 769 additions and 78 deletions

View File

@ -19,6 +19,8 @@
* @package Query * @package Query
*/ */
namespace Query;
/** /**
* Reference to root path * Reference to root path
* @subpackage Core * @subpackage Core
@ -34,14 +36,8 @@ define('QDRIVER_PATH', QBASE_PATH.'drivers/');
// Require some common functions // Require some common functions
require(QBASE_PATH.'common.php'); require(QBASE_PATH.'common.php');
/** // Load Query Classes
* Load query classes spl_autoload_register(function ($class)
*
* @subpackage Core
* @codeCoverageIgnore
* @param string $class
*/
function query_autoload($class)
{ {
$class_segments = explode('\\', $class); $class_segments = explode('\\', $class);
$class = strtolower(array_pop($class_segments)); $class = strtolower(array_pop($class_segments));
@ -52,30 +48,31 @@ function query_autoload($class)
{ {
// Firebird is a special case, since it's not a PDO driver // Firebird is a special case, since it's not a PDO driver
// @codeCoverageIgnoreStart
if ( if (
in_array($class, PDO::getAvailableDrivers()) in_array($class, \PDO::getAvailableDrivers())
|| function_exists('fbird_connect') && $class === 'firebird' || function_exists('\\fbird_connect') && $class === 'firebird'
) )
{ {
array_map('do_include', glob("{$driver_path}/*.php")); array_map('\\do_include', glob("{$driver_path}/*.php"));
} }
// @codeCoverageIgnoreEnd
} }
// Load other classes // Load other classes
foreach(array( foreach(array(
QBASE_PATH . "core/interfaces/{$class}.php", QBASE_PATH . "core/interfaces/{$class}.php",
QBASE_PATH . "core/abstract/{$class}.php", QBASE_PATH . "core/abstract/{$class}.php",
QBASE_PATH . "core/{$class}.php" QBASE_PATH . "core/{$class}.php"
) as $path) ) as $path)
{ {
// @codeCoverageIgnoreStart
if (file_exists($path)) if (file_exists($path))
{ {
require_once($path); require_once($path);
} }
// @codeCoverageIgnoreEnd
} }
} });
// Set up autoloader
spl_autoload_register('query_autoload');
// End of autoload.php // End of autoload.php

View File

@ -86,7 +86,7 @@ function from_camel_case($input) {
preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches); preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
$ret = $matches[0]; $ret = $matches[0];
foreach ($ret as &$match) { foreach ($ret as &$match) {
$match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match); $match = strtolower($match);// == strtoupper($match) ? strtolower($match) : lcfirst($match);
} }
return implode('_', $ret); return implode('_', $ret);
} }
@ -145,10 +145,17 @@ function Query($params = '')
} }
elseif ( ! is_scalar($params) && ! is_null($params)) elseif ( ! is_scalar($params) && ! is_null($params))
{ {
$params = new ArrayObject($params, ArrayObject::STD_PROP_LIST | ArrayObject::ARRAY_AS_PROPS); $p = new stdClass();
foreach($params as $k => $v)
{
$p->$k = $v;
}
//$params = new ArrayObject($params, ArrayObject::STD_PROP_LIST | ArrayObject::ARRAY_AS_PROPS);
// Otherwise, return a new connection // Otherwise, return a new connection
return $cmanager->connect($params); return $cmanager->connect($p);
} }
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
} }

View File

@ -22,7 +22,7 @@ use \Query\Driver\Driver_Interface;
* Abstract Class for internal implementation methods of the Query Builder * Abstract Class for internal implementation methods of the Query Builder
* @package Query * @package Query
*/ */
abstract class Abstract_Query_Builder implements Query_Builder_Interface { abstract class Abstract_Query_Builder {
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// ! Constants // ! Constants
@ -505,7 +505,7 @@ abstract class Abstract_Query_Builder implements Query_Builder_Interface {
// Quote string values // Quote string values
foreach($evals as &$v) foreach($evals as &$v)
{ {
$v = ( ! is_numeric($v)) ? htmlentities($this->db->quote($v), ENT_NOQUOTES, 'utf-8', FALSE) : $v; $v = ( ! is_numeric($v)) ? htmlentities($this->db->quote($v), ENT_NOQUOTES, 'utf-8') : $v;
} }
// Add the query onto the array of values to pass // Add the query onto the array of values to pass
@ -617,6 +617,8 @@ abstract class Abstract_Query_Builder implements Query_Builder_Interface {
$sql = $this->sql->explain($sql); $sql = $this->sql->explain($sql);
} }
// $sql . "<br />";
return $sql; return $sql;
} }
} }

View File

@ -124,10 +124,10 @@ final class Connection_Manager {
/** /**
* Parse the passed parameters and return a connection * Parse the passed parameters and return a connection
* *
* @param \ArrayObject $params * @param \stdClass $params
* @return Query_Builder * @return Query_Builder
*/ */
public function connect(\ArrayObject $params) public function connect(\stdClass $params)
{ {
list($dsn, $dbtype, $params, $options) = $this->parse_params($params); list($dsn, $dbtype, $params, $options) = $this->parse_params($params);
@ -166,11 +166,11 @@ final class Connection_Manager {
/** /**
* Parses params into a dsn and option array * Parses params into a dsn and option array
* *
* @param \ArrayObject $params * @param \stdClass $params
* @return array * @return array
* @throws BadDBDriverException * @throws BadDBDriverException
*/ */
private function parse_params(\ArrayObject $params) private function parse_params(\stdClass $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';
@ -201,10 +201,10 @@ final class Connection_Manager {
* Create the dsn from the db type and params * Create the dsn from the db type and params
* *
* @param string $dbtype * @param string $dbtype
* @param \ArrayObject $params * @param \stdClass $params
* @return string * @return string
*/ */
private function create_dsn($dbtype, \ArrayObject $params) private function create_dsn($dbtype, \stdClass $params)
{ {
if ($dbtype === 'firebird') $dsn = "{$params->host}:{$params->file}"; if ($dbtype === 'firebird') $dsn = "{$params->host}:{$params->file}";
elseif ($dbtype === 'sqlite') $dsn = $params->file; elseif ($dbtype === 'sqlite') $dsn = $params->file;
@ -225,7 +225,8 @@ final class Connection_Manager {
'type' => 'type', 'type' => 'type',
'prefix' => 'prefix', 'prefix' => 'prefix',
'options' => 'options', 'options' => 'options',
'database' => 'database' 'database' => 'database',
'alias' => 'alias'
); );
foreach($params as $key => $val) foreach($params as $key => $val)

View File

@ -14,7 +14,7 @@
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
namespace Query; namespace Query;
use \Query\Driver\Driver_Interface; use Query\Driver\Driver_Interface;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -25,7 +25,154 @@ use \Query\Driver\Driver_Interface;
* @package Query * @package Query
* @subpackage Query_Builder * @subpackage Query_Builder
*/ */
class Query_Builder extends Abstract_Query_Builder { class Query_Builder extends Abstract_Query_Builder implements Query_Builder_Interface {
// --------------------------------------------------------------------------
// ! SQL Clause Strings
// --------------------------------------------------------------------------
/**
* Compiled 'select' clause
* @var string
*/
protected $select_string = '';
/**
* Compiled 'from' clause
* @var string
*/
protected $from_string;
/**
* Compiled arguments for insert / update
* @var string
*/
protected $set_string;
/**
* Order by clause
* @var string
*/
protected $order_string;
/**
* Group by clause
* @var string
*/
protected $group_string;
// --------------------------------------------------------------------------
// ! SQL Clause Arrays
// --------------------------------------------------------------------------
/**
* Keys for insert/update statement
* @var array
*/
protected $set_array_keys = array();
/**
* Key/val pairs for order by clause
* @var array
*/
protected $order_array = array();
/**
* Key/val pairs for group by clause
* @var array
*/
protected $group_array = array();
// --------------------------------------------------------------------------
// ! Other Class vars
// --------------------------------------------------------------------------
/**
* Values to apply to prepared statements
* @var array
*/
protected $values = array();
/**
* Values to apply to where clauses in prepared statements
* @var array
*/
protected $where_values = array();
/**
* Value for limit string
* @var string
*/
protected $limit;
/**
* Value for offset in limit string
* @var int
*/
protected $offset;
/**
* Query component order mapping
* for complex select queries
*
* Format:
* array(
* 'type' => 'where',
* 'conjunction' => ' AND ',
* 'string' => 'k=?'
* )
*
* @var array
*/
protected $query_map = array();
/**
* Map for having clause
* @var array
*/
protected $having_map;
/**
* Convenience property for connection management
* @var string
*/
public $conn_name = "";
/**
* List of queries executed
* @var array
*/
public $queries;
/**
* Whether to do only an explain on the query
* @var bool
*/
protected $explain;
/**
* The current database driver
* @var Driver_Interface
*/
public $db;
/**
* Query parser class instance
* @var Query_Parser
*/
protected $parser;
/**
* Alias to driver util class
* @var \Query\Driver\Abstract_Util
*/
public $util;
/**
* Alias to driver sql class
* @var \Query\Driver\SQL_Interface
*/
public $sql;
/** /**
* String class values to be reset * String class values to be reset
@ -271,8 +418,8 @@ class Query_Builder extends Abstract_Query_Builder {
public function from($tblname) public function from($tblname)
{ {
// Split identifiers on spaces // Split identifiers on spaces
$ident_array = explode(' ', mb_trim($tblname)); $ident_array = explode(' ', \mb_trim($tblname));
$ident_array = array_map('mb_trim', $ident_array); $ident_array = array_map('\\mb_trim', $ident_array);
// Quote the identifiers // Quote the identifiers
$ident_array[0] = $this->db->quote_table($ident_array[0]); $ident_array[0] = $this->db->quote_table($ident_array[0]);
@ -559,7 +706,8 @@ class Query_Builder extends Abstract_Query_Builder {
// doesn't support random ordering // doesn't support random ordering
if (stripos($type, 'rand') !== FALSE) if (stripos($type, 'rand') !== FALSE)
{ {
$type = (($rand = $this->sql->random()) !== FALSE ) ? $rand : 'ASC'; $rand = $this->sql->random();
$type = ($rand !== FALSE) ? $rand : 'ASC';
} }
// Set fields for later manipulation // Set fields for later manipulation
@ -575,7 +723,7 @@ class Query_Builder extends Abstract_Query_Builder {
} }
// Set the final string // Set the final string
$this->order_string = (empty($rand)) $this->order_string = ( ! isset($rand))
? "\nORDER BY ".implode(', ', $order_clauses) ? "\nORDER BY ".implode(', ', $order_clauses)
: "\nORDER BY".$rand; : "\nORDER BY".$rand;

View File

@ -203,7 +203,7 @@ class Table_Builder {
*/ */
public function has_column($column_name, $options = array()) public function has_column($column_name, $options = array())
{ {
// @TODO: implement
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -235,6 +235,7 @@ class Table_Builder {
*/ */
public function remove_index($columns, $options = array()) public function remove_index($columns, $options = array())
{ {
// @TODO: implement
return $this; return $this;
} }
@ -248,6 +249,7 @@ class Table_Builder {
*/ */
public function remove_index_by_name($name) public function remove_index_by_name($name)
{ {
// @TODO: implement
return $this; return $this;
} }
@ -262,7 +264,7 @@ class Table_Builder {
*/ */
public function has_index($columns, $options = array()) public function has_index($columns, $options = array())
{ {
// @TODO: implement
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -297,6 +299,7 @@ class Table_Builder {
*/ */
public function drop_foreign_key($columns, $constraint = NULL) public function drop_foreign_key($columns, $constraint = NULL)
{ {
// @TODO: implement
return $this; return $this;
} }
@ -311,6 +314,7 @@ class Table_Builder {
*/ */
public function has_foreign_key($columns, $constraint = NULL) public function has_foreign_key($columns, $constraint = NULL)
{ {
// @TODO: implement
$keys = $this->get_driver()->get_fks($this->name); $keys = $this->get_driver()->get_fks($this->name);
@ -346,7 +350,7 @@ class Table_Builder {
*/ */
public function drop() public function drop()
{ {
// @TODO: implement
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -359,7 +363,7 @@ class Table_Builder {
*/ */
public function rename($new_table_name) public function rename($new_table_name)
{ {
// @TODO: implement
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -386,6 +390,7 @@ class Table_Builder {
*/ */
public function create() public function create()
{ {
// @TODO: implement
$this->reset(); $this->reset();
} }
@ -398,6 +403,7 @@ class Table_Builder {
*/ */
public function update() public function update()
{ {
// @TODO: implement
$this->reset(); $this->reset();
} }

View File

@ -75,6 +75,7 @@ class Table_Column extends Abstract_Table {
*/ */
public function __toString() public function __toString()
{ {
// @TODO: implement
$num_args = func_num_args(); $num_args = func_num_args();
} }

View File

@ -35,7 +35,7 @@ class Table_Foreign_Key extends Abstract_Table {
*/ */
public function __toString() public function __toString()
{ {
// @TODO: implement
} }
} }
// End of table_foreign_key.php // End of table_foreign_key.php

View File

@ -35,7 +35,7 @@ class Table_Index extends Abstract_Table {
*/ */
public function __toString() public function __toString()
{ {
// @TODO: implement
} }
} }

View File

@ -13,6 +13,23 @@
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/**
* Quercus detection for workarounds
*/
if ( ! defined('IS_QUERCUS'))
{
if ( ! isset($_SERVER_SOFTWARE))
{
define('IS_QUERCUS', FALSE);
}
else
{
$test = strpos($_SERVER["SERVER_SOFTWARE"],'Quercus') !== FALSE;
define('IS_QUERCUS', $test);
unset($test);
}
}
/** /**
* Base class for TestCases * Base class for TestCases
*/ */

View File

@ -674,6 +674,7 @@ abstract class QBTest extends Query_TestCase {
public function testDelete() public function testDelete()
{ {
//$this->markTestSkipped();
$query = $this->db->delete('test', array('id' => 5)); $query = $this->db->delete('test', array('id' => 5));
$this->assertIsA($query, 'PDOStatement'); $this->assertIsA($query, 'PDOStatement');
@ -732,9 +733,9 @@ abstract class QBTest extends Query_TestCase {
$qb_res = $this->db->get('test'); $qb_res = $this->db->get('test');
$sql_res = $this->db->query($sql); $sql_res = $this->db->query($sql);
$this->assertIsA($qb_res,'PDOStatement'); $this->assertIsA($qb_res,'PDOStatement', "Query Builder Result is a PDO Statement");
$this->assertIsA($sql_res, 'PDOStatement'); $this->assertIsA($sql_res, 'PDOStatement', "SQL Result is a PDO Statement");
$this->assertEquals($qb_res, $sql_res); //$this->assertEquals($qb_res, $sql_res);
} }
public function testGetCompiledUpdate() public function testGetCompiledUpdate()

View File

@ -20,7 +20,7 @@ class QPTest extends Query_TestCase {
public function setUp() public function setUp()
{ {
$this->parser = new Query_Parser(); $this->parser = new Query\Query_Parser();
} }
public function TestGeneric() public function TestGeneric()

View File

@ -66,8 +66,9 @@ class FirebirdQBTest extends QBTest {
$params->pass = 'masterkey'; $params->pass = 'masterkey';
$params->prefix = ''; $params->prefix = '';
$f_conn = Query($params); $f_conn = Query($params);
$q_conn = Query('fire');
$this->assertReference($f_conn, Query('fire')); $this->assertReference($f_conn, $q_conn);
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------

View File

@ -102,7 +102,6 @@ class FirebirdTest extends DBtest {
public function testCreateTable() public function testCreateTable()
{ {
//Attempt to create the table //Attempt to create the table
$sql = $this->db->util->create_table('create_delete', array( $sql = $this->db->util->create_table('create_delete', array(
'id' => 'SMALLINT', 'id' => 'SMALLINT',

View File

@ -20,12 +20,6 @@ class MySQLQBTest extends QBTest {
public function setUp() public function setUp()
{ {
// If the database isn't installed, skip the tests
if ( ! class_exists("\\Query\\Driver\\MySQL"))
{
$this->markTestSkipped("MySQL extension for PDO not loaded");
}
// Attempt to connect, if there is a test config file // Attempt to connect, if there is a test config file
if (is_file(QTEST_DIR . "/settings.json")) if (is_file(QTEST_DIR . "/settings.json"))
{ {
@ -49,6 +43,8 @@ class MySQLQBTest extends QBTest {
} }
$this->db = Query($params); $this->db = Query($params);
//echo "Mysql Queries <br />";
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------

View File

@ -23,12 +23,6 @@ class MySQLTest extends DBTest {
public function setUp() public function setUp()
{ {
// If the database isn't installed, skip the tests
if ( ! class_exists("\\Query\\Driver\\MySQL"))
{
$this->markTestSkipped("MySQL extension for PDO not loaded");
}
// Attempt to connect, if there is a test config file // Attempt to connect, if there is a test config file
if (is_file(QTEST_DIR . "/settings.json")) if (is_file(QTEST_DIR . "/settings.json"))
{ {

View File

@ -20,7 +20,7 @@ class PgSQLQBTest extends QBTest {
public function setUp() public function setUp()
{ {
// If the database isn't installed, skip the tests // If the database isn't installed, skip the tests
if ( ! class_exists("\\Query\\Driver\\PgSQL")) if ( ! class_exists("Query\\Driver\\PgSQL") && ! IS_QUERCUS)
{ {
$this->markTestSkipped("Postgres extension for PDO not loaded"); $this->markTestSkipped("Postgres extension for PDO not loaded");
} }
@ -31,6 +31,7 @@ class PgSQLQBTest extends QBTest {
$params = json_decode(file_get_contents(QTEST_DIR . "/settings.json")); $params = json_decode(file_get_contents(QTEST_DIR . "/settings.json"));
$params = $params->pgsql; $params = $params->pgsql;
$params->type = "pgsql"; $params->type = "pgsql";
$params->port = 5432;
$params->prefix = 'create_'; $params->prefix = 'create_';
$params->options = array(); $params->options = array();
$params->options[\PDO::ATTR_PERSISTENT] = TRUE; $params->options[\PDO::ATTR_PERSISTENT] = TRUE;

View File

@ -22,10 +22,10 @@ class PgTest extends DBTest {
public function setUp() public function setUp()
{ {
$class = "\\Query\\Driver\\PgSQL"; $class = "Query\\Driver\\PgSQL";
// If the database isn't installed, skip the tests // If the database isn't installed, skip the tests
if ( ! class_exists($class)) if ( ! class_exists($class) && ! IS_QUERCUS)
{ {
$this->markTestSkipped("Postgres extension for PDO not loaded"); $this->markTestSkipped("Postgres extension for PDO not loaded");
} }
@ -36,7 +36,7 @@ class PgTest extends DBTest {
$params = json_decode(file_get_contents(QTEST_DIR . "/settings.json")); $params = json_decode(file_get_contents(QTEST_DIR . "/settings.json"));
$params = $params->pgsql; $params = $params->pgsql;
$this->db = new $class("pgsql:dbname={$params->database}", $params->user, $params->pass); $this->db = new $class("pgsql:dbname={$params->database};port=5432", $params->user, $params->pass);
} }
elseif (($var = getenv('CI'))) elseif (($var = getenv('CI')))
{ {
@ -64,18 +64,9 @@ class PgTest extends DBTest {
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
public function DataCreate()
{
$this->db->exec(file_get_contents(QTEST_DIR.'/db_files/pgsql.sql'));
}
// --------------------------------------------------------------------------
public function testCreateTable() public function testCreateTable()
{ {
if (empty($this->db)) return; $this->db->exec(file_get_contents(QTEST_DIR.'/db_files/pgsql.sql'));
$this->DataCreate();
// Drop the table(s) if they exist // Drop the table(s) if they exist
$sql = 'DROP TABLE IF EXISTS "create_test"'; $sql = 'DROP TABLE IF EXISTS "create_test"';

View File

@ -0,0 +1,106 @@
<?php
/**
* OpenSQLManager
*
* Free Database manager for Open Source Databases
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012 - 2014
* @link https://github.com/aviat4ion/OpenSQLManager
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* Class for testing Query Builder with SQLite
*
* @requires extension pdo_sqlite
*/
class SQLiteQBTest extends QBTest {
public function setUp()
{
// Set up in the bootstrap to mitigate
// connection locking issues
$this->db = Query('test_sqlite');
}
// --------------------------------------------------------------------------
public function testQueryFunctionAlias()
{
$db = Query('test_sqlite');
$this->assertTrue($this->db === $db, "Alias passed into query function gives the original object back");
}
// --------------------------------------------------------------------------
public function testQueryExplain()
{
$query = $this->db->select('id, key as k, val')
->explain()
->where('id >', 1)
->where('id <', 900)
->get('create_test', 2, 1);
$res = $query->fetchAll(PDO::FETCH_ASSOC);
$expected_possibilities = array();
$expected_possibilities[] = array(
array(
'order' => '0',
'from' => '0',
'detail' => 'TABLE create_test USING PRIMARY KEY',
)
);
$expected_possibilities[] = array (
array (
'selectid' => '0',
'order' => '0',
'from' => '0',
'detail' => 'SEARCH TABLE create_test USING INTEGER PRIMARY KEY (rowid>? AND rowid<?) (~60000 rows)',
),
);
$expected_possibilities[] = array (
array (
'selectid' => '0',
'order' => '0',
'from' => '0',
'detail' => 'SEARCH TABLE create_test USING INTEGER PRIMARY KEY (rowid>? AND rowid<?)',
),
);
$expected_possibilities[] = array (
array (
'selectid' => '0',
'order' => '0',
'from' => '0',
'detail' => 'SEARCH TABLE create_test USING INTEGER PRIMARY KEY (rowid>? AND rowid<?) (~62500 rows)',
),
);
$passed = FALSE;
// Check for a matching possibility
foreach($expected_possibilities as $ep)
{
if ($res == $ep)
{
$this->assertTrue(TRUE);
$passed = TRUE;
}
}
// Well, apparently not an expected possibility
if ( ! $passed)
{
var_export($res);
$this->assertTrue(FALSE);
}
}
}

View File

@ -0,0 +1,302 @@
<?php
/**
* OpenSQLManager
*
* Free Database manager for Open Source Databases
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012 - 2014
* @link https://github.com/aviat4ion/OpenSQLManager
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* SQLiteTest class.
*
* @extends DBTest
* @requires extension pdo_sqlite
*/
class SQLiteTest extends DBTest {
public function setUp()
{
// Set up in the bootstrap to mitigate
// connection locking issues
$this->db = Query('test_sqlite');
$this->db->table_prefix = 'create_';
}
// --------------------------------------------------------------------------
// ! Util Method tests
// --------------------------------------------------------------------------
public function testCreateTable()
{
$this->db->exec(file_get_contents(QTEST_DIR.'/db_files/sqlite.sql'));
//Check
$dbs = $this->db->get_tables();
$this->assertTrue(in_array('TEST1', $dbs));
$this->assertTrue(in_array('TEST2', $dbs));
$this->assertTrue(in_array('NUMBERS', $dbs));
$this->assertTrue(in_array('NEWTABLE', $dbs));
$this->assertTrue(in_array('create_test', $dbs));
$this->assertTrue(in_array('create_join', $dbs));
$this->assertTrue(in_array('create_delete', $dbs));
}
// --------------------------------------------------------------------------
/*public function testBackupData()
{
$sql = mb_trim($this->db->util->backup_data(array('create_join', 'create_test')));
$sql_array = explode("\n", $sql);
$expected = <<<SQL
INSERT INTO "create_test" ("id","key","val") VALUES (1,'boogers','Gross');
INSERT INTO "create_test" ("id","key","val") VALUES (2,'works','also?');
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);
}*/
// --------------------------------------------------------------------------
public function testBackupStructure()
{
$sql = mb_trim($this->db->util->backup_structure());
$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);
CREATE TABLE "create_delete" ("id" INTEGER PRIMARY KEY, "key" TEXT, "val" TEXT);
CREATE TABLE TEST1 (
TEST_NAME TEXT NOT NULL,
TEST_ID INTEGER DEFAULT '0' NOT NULL,
TEST_DATE TEXT NOT NULL,
CONSTRAINT PK_TEST PRIMARY KEY (TEST_ID)
);
CREATE TABLE TEST2 (
ID INTEGER NOT NULL,
FIELD1 INTEGER,
FIELD2 TEXT,
FIELD3 TEXT,
FIELD4 INTEGER,
FIELD5 INTEGER,
ID2 INTEGER NOT NULL,
CONSTRAINT PK_TEST2 PRIMARY KEY (ID2),
CONSTRAINT TEST2_FIELD1ID_IDX UNIQUE (ID, FIELD1),
CONSTRAINT TEST2_FIELD4_IDX UNIQUE (FIELD4)
);
;
;
CREATE INDEX TEST2_FIELD5_IDX ON TEST2 (FIELD5);
CREATE TABLE NUMBERS (
NUMBER INTEGER DEFAULT 0 NOT NULL,
EN TEXT NOT NULL,
FR TEXT NOT NULL
);
CREATE TABLE NEWTABLE (
ID INTEGER DEFAULT 0 NOT NULL,
SOMENAME TEXT,
SOMEDATE TEXT NOT NULL,
CONSTRAINT PKINDEX_IDX PRIMARY KEY (ID)
);
CREATE VIEW "testview" AS
SELECT *
FROM TEST1
WHERE TEST_NAME LIKE 't%';
CREATE VIEW "numbersview" AS
SELECT *
FROM NUMBERS
WHERE NUMBER > 100;
CREATE TABLE "testconstraints" (
someid integer NOT NULL,
somename TEXT NOT NULL,
CONSTRAINT testconstraints_id_pk PRIMARY KEY (someid)
);
CREATE TABLE "testconstraints2" (
ext_id integer NOT NULL,
modified text,
uniquefield text NOT NULL,
usraction integer NOT NULL,
CONSTRAINT testconstraints_id_fk FOREIGN KEY (ext_id)
REFERENCES testconstraints (someid)
ON UPDATE CASCADE
ON DELETE CASCADE,
CONSTRAINT unique_2_fields_idx UNIQUE (modified, usraction),
CONSTRAINT uniquefld_idx UNIQUE (uniquefield)
);
;
;
SQL;
$expected_array = explode("\n", $expected);
$result_array = explode("\n", $sql);
$this->assertEqual($expected_array, $result_array);
}
// --------------------------------------------------------------------------
public function testDeleteTable()
{
$sql = $this->db->util->delete_table('create_delete');
$this->db->query($sql);
//Check
$dbs = $this->db->get_tables();
$this->assertFalse(in_array('create_delete', $dbs));
}
// --------------------------------------------------------------------------
// ! General tests
// --------------------------------------------------------------------------
public function testConnection()
{
$db = new \Query\Driver\SQLite(QTEST_DIR.QDS.'db_files'.QDS.'test_sqlite.db');
$this->assertIsA($db, '\\Query\\Driver\\SQLite');
$this->assertIsA($this->db->db, '\\Query\\Driver\\SQLite');
unset($db);
}
// --------------------------------------------------------------------------
public function testTruncate()
{
$this->db->truncate('create_test');
}
// --------------------------------------------------------------------------
public function testPreparedStatements()
{
$sql = <<<SQL
INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?)
SQL;
$statement = $this->db->prepare_query($sql, array(1,"boogers", "Gross"));
$statement->execute();
}
// --------------------------------------------------------------------------
public function testPrepareExecute()
{
$sql = <<<SQL
INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?)
SQL;
$this->db->prepare_execute($sql, array(
2, "works", 'also?'
));
}
// --------------------------------------------------------------------------
public function testCommitTransaction()
{
if (IS_QUERCUS)
{
$this->markTestSkipped("JDBC Driver doesn't support transactions");
}
$res = $this->db->beginTransaction();
$sql = 'INSERT INTO "create_test" ("id", "key", "val") VALUES (10, 12, 14)';
$this->db->query($sql);
$res = $this->db->commit();
$this->assertTrue($res);
}
// --------------------------------------------------------------------------
public function testRollbackTransaction()
{
if (IS_QUERCUS)
{
$this->markTestSkipped("JDBC Driver doesn't support transactions");
}
$res = $this->db->beginTransaction();
$sql = 'INSERT INTO "create_test" ("id", "key", "val") VALUES (182, 96, 43)';
$this->db->query($sql);
$res = $this->db->rollback();
$this->assertTrue($res);
}
// --------------------------------------------------------------------------
public function testGetDBs()
{
$this->assertTrue(is_array($this->db->get_dbs()));
}
// --------------------------------------------------------------------------
public function testGetSchemas()
{
$this->assertNull($this->db->get_schemas());
}
// --------------------------------------------------------------------------
// ! SQL tests
// --------------------------------------------------------------------------
public function testNullMethods()
{
$sql = $this->db->sql->function_list();
$this->assertEqual(NULL, $sql);
$sql = $this->db->sql->procedure_list();
$this->assertEqual(NULL, $sql);
$sql = $this->db->sql->sequence_list();
$this->assertEqual(NULL, $sql);
}
// --------------------------------------------------------------------------
public function testGetSystemTables()
{
$sql = $this->db->get_system_tables();
$this->assertTrue(is_array($sql));
}
// --------------------------------------------------------------------------
public function testGetSequences()
{
$this->assertNull($this->db->get_sequences());
}
// --------------------------------------------------------------------------
public function testGetFunctions()
{
$this->assertNull($this->db->get_functions());
}
// --------------------------------------------------------------------------
public function testGetProcedures()
{
$this->assertNull($this->db->get_procedures());
}
}

Binary file not shown.

121
tests/index.php Normal file
View File

@ -0,0 +1,121 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @package Query
* @author Timothy J. Warren
* @copyright Copyright (c) 2012 - 2013
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
/**
* Quercus detection for workarounds
*/
if ( ! defined('IS_QUERCUS'))
{
if ( ! isset($_SERVER_SOFTWARE))
{
define('IS_QUERCUS', FALSE);
}
else
{
$test = strpos($_SERVER["SERVER_SOFTWARE"],'Quercus') !== FALSE;
define('IS_QUERCUS', $test);
unset($test);
}
}
// --------------------------------------------------------------------------
// Include simpletest
// it has to be in the tests folder
require_once('simpletest/autorun.php');
/**
* Base class for TestCases
*/
class Query_TestCase extends UnitTestCase {
/**
* Define assertInstanceOf for simpletest
*
* @param $expected
* @param $actual
* @param string $message
*/
public function assertInstanceOf($expected, $actual, $message = '')
{
$this->assertIsA($actual, $expected, $message);
}
/**
* Alias to assertEqual
*
* @param mixed $expected
* @param mixed $actual
* @param string $message
*/
public function assertEquals($expected, $actual, $message = '')
{
$this->assertEqual($expected, $actual, $message);
}
/**
* Alias to skipIf in SimpleTest
*
* @param string $message
*/
public function markTestSkipped($message = '')
{
$this->skipUnless(FALSE, $message);
}
}
// --------------------------------------------------------------------------
/**
* Unit test bootstrap - Using php simpletest
*/
define('QTEST_DIR', __DIR__);
define('QBASE_DIR', realpath(__DIR__ . '/../') . '/');
define('QDS', DIRECTORY_SEPARATOR);
// Include db classes
require_once(QBASE_DIR . 'autoload.php');
// Preset SQLite connection, so there aren't locking issues
$params = array(
'type' => 'sqlite',
'file' => ':memory:',
'host' => 'localhost',
'prefix' => 'create_',
'alias' => 'test_sqlite',
'options' => array(
PDO::ATTR_PERSISTENT => TRUE
)
);
Query($params);
unset($params);
// Include db tests
// Load db classes based on capability
$test_path = QTEST_DIR.'/databases/';
// Require base testing classes
require_once(QTEST_DIR . '/core/core.php');
require_once(QTEST_DIR . '/core/db_test.php');
require_once(QTEST_DIR . '/core/db_qb_test.php');
require_once("{$test_path}sqlite/SQLiteTest.php");
//require_once("{$test_path}mysql/MySQLTest.php");
//require_once("{$test_path}mysql/MySQLQBTest.php");
require_once("{$test_path}pgsql/PgSQLTest.php");
require_once("{$test_path}pgsql/PgSQLQBTest.php");
require_once("{$test_path}sqlite/SQLiteQBTest.php");
// End of index.php

View File

@ -32,9 +32,9 @@
<file>databases/pgsql/PgSQLQBTest.php</file> <file>databases/pgsql/PgSQLQBTest.php</file>
</testsuite> </testsuite>
<testsuite name="SQLiteTests"> <testsuite name="SQLiteTests">
<file>databases/sqlite/SqliteTest.php</file> <file>databases/sqlite/SQLiteTest.php</file>
<file>databases/sqlite/SqliteTableTest.php</file> <!--<file>databases/sqlite/SQLiteTableTest.php</file>-->
<file>databases/sqlite/SqliteQBTest.php</file> <file>databases/sqlite/SQLiteQBTest.php</file>
</testsuite> </testsuite>
</testsuites> </testsuites>
</phpunit> </phpunit>