Initial Commit

This commit is contained in:
Timothy Warren 2012-03-15 09:25:18 -04:00
commit da107cf6e3
26 changed files with 3990 additions and 0 deletions

3
README.md Normal file
View File

@ -0,0 +1,3 @@
# Query
A query builder/abstraction layer.

293
db_pdo.php Normal file
View File

@ -0,0 +1,293 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* Base Database class
*
* Extends PDO to simplify cross-database issues
*/
abstract class DB_PDO extends PDO {
public $manip;
protected $statement;
/**
* PDO constructor wrapper
*/
public function __construct($dsn, $username=NULL, $password=NULL, $driver_options=array())
{
parent::__construct($dsn, $username, $password, $driver_options);
}
// -------------------------------------------------------------------------
/**
* Simplifies prepared statements for database queries
*
* @param string $sql
* @param array $data
* @return mixed PDOStatement / FALSE
*/
public function prepare_query($sql, $data)
{
// Prepare the sql
$query = $this->prepare($sql);
if( ! (is_object($query) || is_resource($query)))
{
$this->get_last_error();
return FALSE;
}
// Set the statement in the class variable for easy later access
$this->statement =& $query;
if( ! (is_array($data) || is_object($data)))
{
trigger_error("Invalid data argument");
return FALSE;
}
// Bind the parameters
foreach($data as $k => $value)
{
if(is_numeric($k))
{
$k++;
}
$res = $query->bindValue($k, $value);
if( ! $res)
{
trigger_error("Parameter not successfully bound");
return FALSE;
}
}
return $query;
}
// -------------------------------------------------------------------------
/**
* Create and execute a prepared statement with the provided parameters
*
* @param string $sql
* @param array $params
* @return PDOStatement
*/
public function prepare_execute($sql, $params)
{
$this->statement = $this->prepare_query($sql, $params);
$this->statement->execute();
return $this->statement;
}
// -------------------------------------------------------------------------
/**
* Retreives the data from a select query
*
* @param PDOStatement $statement
* @return array
*/
public function get_query_data($statement)
{
$this->statement =& $statement;
// Execute the query
$this->statement->execute();
// Return the data array fetched
return $this->statement->fetchAll(PDO::FETCH_ASSOC);
}
// -------------------------------------------------------------------------
/**
* Returns number of rows affected by an INSERT, UPDATE, DELETE type query
*
* @param PDOStatement $statement
* @return int
*/
public function affected_rows($statement='')
{
if ( ! empty($statement))
{
$this->statement = $statement;
}
if (empty($this->statement))
{
return FALSE;
}
// Execute the query
$this->statement->execute();
// Return number of rows affected
return $this->statement->rowCount();
}
// --------------------------------------------------------------------------
/**
* Return the last error for the current database connection
*
* @return string
*/
public function get_last_error()
{
$info = $this->errorInfo();
echo "Error: <pre>{$info[0]}:{$info[1]}\n{$info[2]}</pre>";
}
// --------------------------------------------------------------------------
/**
* Surrounds the string with the databases identifier escape characters
*
* @param mixed $ident
* @return string
*/
public function quote_ident($ident)
{
if (is_array($ident))
{
return array_map(array($this, 'quote_ident'), $ident);
}
// Split each identifier by the period
$hiers = explode('.', $ident);
return '"'.implode('"."', $hiers).'"';
}
// -------------------------------------------------------------------------
/**
* Deletes all the rows from a table. Does the same as the truncate
* method if the database does not support 'TRUNCATE';
*
* @param string $table
* @return mixed
*/
public function empty_table($table)
{
$sql = 'DELETE FROM '.$this->quote_ident($table);
return $this->query($sql);
}
// -------------------------------------------------------------------------
/**
* Abstract public functions to override in child classes
*/
/**
* Return list of tables for the current database
*
* @return array
*/
abstract public function get_tables();
/**
* Empty the passed table
*
* @param string $table
*
* @return void
*/
abstract public function truncate($table);
/**
* Return the number of rows for the last SELECT query
*
* @return int
*/
abstract public function num_rows();
/**
* Retreives an array of non-user-created tables for
* the connection/database
*
* @return array
*/
abstract public function get_system_tables();
/**
* Return an SQL file with the database table structure
*
* @return string
*/
abstract public function backup_structure();
/**
* Return an SQL file with the database data as insert statements
*
* @return string
*/
abstract public function backup_data();
}
// -------------------------------------------------------------------------
/**
* Abstract parent for database manipulation subclasses
*/
abstract class DB_SQL {
/**
* Get database-specific sql to create a new table
*
* @param string $name
* @param array $columns
* @param array $constraints
* @param array $indexes
* @return string
*/
abstract public function create_table($name, $columns, array $constraints=array(), array $indexes=array());
/**
* Get database-specific sql to drop a table
*
* @param string $name
* @return string
*/
abstract public function delete_table($name);
/**
* Get database specific sql for limit clause
*
* @param string $sql
* @param int $limiit
* @param int $offset
* @return string
*/
abstract public function limit($sql, $limit, $offset=FALSE);
/**
* Get the sql for random ordering
*
* @return string
*/
abstract public function random();
}
// End of db_pdo.php

468
drivers/firebird-ibase.php Normal file
View File

@ -0,0 +1,468 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* Firebird Database class
*
* PDO-firebird isn't stable, so this is a wrapper of the ibase_ public functions.
*/
class firebird extends DB_PDO {
protected $statement, $trans, $count, $result, $conn;
/**
* Open the link to the database
*
* @param string $db
* @param string $user
* @param string $pass
*/
public function __construct($dbpath, $user='sysdba', $pass='masterkey')
{
$this->conn = @ibase_connect($dbpath, $user, $pass, 'utf-8');
// Throw an exception to make this match other pdo classes
if ( ! is_resource($this->conn))
{
throw new PDOException(ibase_errmsg());
die();
}
$class = __CLASS__."_sql";
$this->sql = new $class;
}
// --------------------------------------------------------------------------
/**
* Close the link to the database
*/
public function __destruct()
{
@ibase_close();
@ibase_free_result($this->statement);
}
// --------------------------------------------------------------------------
/**
* Empty a database table
*
* @param string $table
*/
public function truncate($table)
{
// Firebird lacka a truncate command
$sql = 'DELETE FROM "'.$table.'"';
$this->statement = $this->query($sql);
}
// --------------------------------------------------------------------------
/**
* Wrapper public function to better match PDO
*
* @param string $sql
* @param array $params
* @return $this
*/
public function query($sql)
{
$this->count = 0;
if (isset($this->trans))
{
$this->statement = @ibase_query($this->trans, $sql);
}
else
{
$this->statement = @ibase_query($this->conn, $sql);
}
// Throw the error as a exception
if ($this->statement === FALSE)
{
throw new PDOException(ibase_errmsg());
}
return $this->statement;
}
// --------------------------------------------------------------------------
/**
* Emulate PDO fetch public function
*
* @param int $fetch_style
* @return mixed
*/
public function fetch($fetch_style=PDO::FETCH_ASSOC)
{
switch($fetch_style)
{
case PDO::FETCH_OBJ:
return ibase_fetch_object($this->statement, IBASE_FETCH_BLOBS);
break;
case PDO::FETCH_NUM:
return ibase_fetch_row($this->statement, IBASE_FETCH_BLOBS);
break;
default:
return ibase_fetch_assoc($this->statement, IBASE_FETCH_BLOBS);
break;
}
}
// --------------------------------------------------------------------------
/**
* Emulate PDO fetchAll public function
*
* @param int $fetch_style
* @return mixed
*/
public function fetchAll($fetch_style=PDO::FETCH_ASSOC)
{
$all = array();
while($row = $this->fetch($fetch_style))
{
$all[] = $row;
}
$this->result = $all;
return $all;
}
// --------------------------------------------------------------------------
/**
* Emulate PDO prepare
*
* @param string $query
* @return $this
*/
public function prepare($query, $options=NULL)
{
$this->statement = @ibase_prepare($this->conn, $query);
// Throw the error as an exception
if ($this->statement === FALSE)
{
throw new PDOException(ibase_errmsg());
}
return $this->statement;
}
// --------------------------------------------------------------------------
/**
* List tables for the current database
*
* @return array
*/
public function get_tables()
{
$sql = <<<SQL
SELECT "RDB\$RELATION_NAME" FROM "RDB\$RELATIONS"
WHERE "RDB\$RELATION_NAME" NOT LIKE 'RDB$%'
AND "RDB\$RELATION_NAME" NOT LIKE 'MON$%'
SQL;
$this->statement = $this->query($sql);
$tables = array();
while($row = $this->fetch(PDO::FETCH_ASSOC))
{
$tables[] = $row['RDB$RELATION_NAME'];
}
return $tables;
}
// --------------------------------------------------------------------------
/**
* List system tables for the current database
*
* @return array
*/
public function get_system_tables()
{
$sql = <<<SQL
SELECT "RDB\$RELATION_NAME" FROM "RDB\$RELATIONS"
WHERE "RDB\$RELATION_NAME" LIKE 'RDB$%'
OR "RDB\$RELATION_NAME" LIKE 'MON$%';
SQL;
$this->statement = $this->query($sql);
$tables = array();
while($row = $this->fetch(PDO::FETCH_ASSOC))
{
$tables[] = $row['RDB$RELATION_NAME'];
}
return $tables;
}
// --------------------------------------------------------------------------
/**
* Return the number of rows affected by the previous query
*
* @return int
*/
public function affected_rows($statement="")
{
return ibase_affected_rows();
}
// --------------------------------------------------------------------------
/**
* Return the number of rows returned for a SELECT query
*
* @return int
*/
public function num_rows()
{
// @todo: Redo this similar to the codeigniter driver
if(isset($this->result))
{
return count($this->result);
}
//Fetch all the rows for the result
$this->result = $this->fetchAll();
return count($this->result);
}
// --------------------------------------------------------------------------
/**
* Start a database transaction
*
* @return bool
*/
public function beginTransaction()
{
if(($this->trans = ibase_trans($this->conn)) !== NULL)
{
return TRUE;
}
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Commit a database transaction
*
* @return bool
*/
public function commit()
{
return ibase_commit($this->trans);
}
// --------------------------------------------------------------------------
/**
* Rollback a transaction
*
* @return bool
*/
public function rollBack()
{
return ibase_rollback($this->trans);
}
// --------------------------------------------------------------------------
/**
* Run a prepared statement query
*
* @param array $args
* @return bool
*/
public function execute($args)
{
//Add the prepared statement as the first parameter
array_unshift($args, $this->statement);
// Let php do all the hard stuff in converting
// the array of arguments into a list of arguments
return call_user_func_array('ibase_execute', $args);
}
// --------------------------------------------------------------------------
/**
* Prepare and execute a query
*
* @param string $sql
* @param array $args
* @return resource
*/
public function prepare_execute($sql, $args)
{
$query = $this->prepare($sql);
// Set the statement in the class variable for easy later access
$this->statement =& $query;
return $this->execute($args);
}
// --------------------------------------------------------------------------
/**
* Method to emulate PDO->quote
*
* @param string $str
* @return string
*/
public function quote($str, $param_type=NULL)
{
if(is_numeric($str))
{
return $str;
}
return "'".str_replace("'", "''", $str)."'";
}
// --------------------------------------------------------------------------
/**
* Method to emulate PDO->errorInfo / PDOStatement->errorInfo
*
* @return array
*/
public function errorInfo()
{
$code = ibase_errcode();
$msg = ibase_errmsg();
return array(0, $code, $msg);
}
// --------------------------------------------------------------------------
/**
* Bind a prepared query with arguments for executing
*
* @param string $sql
* @param mixed $args
* @return FALSE
*/
public function prepare_query($sql, $args)
{
// You can't bind query statements before execution with
// the firebird database
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Create an SQL backup file for the current database's structure
*
* @return string
*/
public function backup_structure()
{
// @todo Implement Backup function
return '';
}
// --------------------------------------------------------------------------
/**
* Create an SQL backup file for the current database's data
*
* @param array $exclude
* @param bool $system_tables
* @return string
*/
public function backup_data($exclude=array(), $system_tables=FALSE)
{
// Determine which tables to use
if($system_tables == TRUE)
{
$tables = array_merge($this->get_system_tables(), $this->get_tables());
}
else
{
$tables = $this->get_tables();
}
// Filter out the tables you don't want
if( ! empty($exclude))
{
$tables = array_diff($tables, $exclude);
}
$output_sql = '';
// Get the data for each object
foreach($tables as $t)
{
$sql = 'SELECT * FROM "'.trim($t).'"';
$res = $this->query($sql);
$obj_res = $this->fetchAll(PDO::FETCH_ASSOC);
unset($res);
// Nab the column names by getting the keys of the first row
$columns = @array_keys($obj_res[0]);
$insert_rows = array();
// Create the insert statements
foreach($obj_res as $row)
{
$row = array_values($row);
// Quote values as needed by type
if(stripos($t, 'RDB$') === FALSE)
{
$row = array_map(array(&$this, 'quote'), $row);
$row = array_map('trim', $row);
}
$row_string = 'INSERT INTO "'.trim($t).'" ("'.implode('","', $columns).'") VALUES ('.implode(',', $row).');';
unset($row);
$insert_rows[] = $row_string;
}
unset($obj_res);
$output_sql .= "\n\nSET TRANSACTION;\n".implode("\n", $insert_rows)."\nCOMMIT;";
}
return $output_sql;
}
}
// End of firebird-ibase.php

130
drivers/firebird_sql.php Normal file
View File

@ -0,0 +1,130 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* Firebird Specific SQL
*/
class Firebird_SQL extends DB_SQL {
/**
* Convienience public function to generate sql for creating a db table
*
* @param string $name
* @param array $fields
* @param array $constraints=array()
* @param array $indexes=array()
*
* @return string
*/
public function create_table($name, $fields, array $constraints=array(), array $indexes=array())
{
$column_array = array();
// Reorganize into an array indexed with column information
// Eg $column_array[$colname] = array(
// 'type' => ...,
// 'constraint' => ...,
// 'index' => ...,
// )
foreach($fields as $colname => $type)
{
if(is_numeric($colname))
{
$colname = $type;
}
$column_array[$colname] = array();
$column_array[$colname]['type'] = ($type !== $colname) ? $type : '';
}
if( ! empty($constraints))
{
foreach($constraints as $col => $const)
{
$column_array[$col]['constraint'] = $const;
}
}
// Join column definitons together
$columns = array();
foreach($column_array as $n => $props)
{
$str = '"'.$n.'" ';
$str .= (isset($props['type'])) ? "{$props['type']} " : "";
$str .= (isset($props['constraint'])) ? "{$props['constraint']} " : "";
$columns[] = $str;
}
// Generate the sql for the creation of the table
$sql = 'CREATE TABLE "'.$name.'" (';
$sql .= implode(',', $columns);
$sql .= ')';
return $sql;
}
// --------------------------------------------------------------------------
/**
* Drop the selected table
*
* @param string $name
* @return string
*/
public function delete_table($name)
{
return 'DROP TABLE "'.$name.'"';
}
// --------------------------------------------------------------------------
/**
* Limit clause
*
* @param string $sql
* @param int $limit
* @param int $offset
* @return string
*/
public function limit($sql, $limit, $offset=FALSE)
{
// Keep the current sql string safe for a moment
$orig_sql = $sql;
$sql = 'FIRST '. (int) $limit;
if ($offset > 0)
{
$sql .= ' SKIP '. (int) $offset;
}
$sql = preg_replace("`SELECT`i", "SELECT {$sql}", $orig_sql);
return $sql;
}
// --------------------------------------------------------------------------
/**
* Random ordering keyword
*
* @return string
*/
public function random()
{
return FALSE;
}
}
//End of firebird_sql.php

148
drivers/mysql.php Normal file
View File

@ -0,0 +1,148 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* MySQL specific class
*
* @extends DB_PDO
*/
class MySQL extends DB_PDO {
/**
* Connect to MySQL Database
*
* @param string $dsn
* @param string $username=null
* @param string $password=null
* @param array $options=array()
*/
public function __construct($dsn, $username=null, $password=null, $options=array())
{
parent::__construct("mysql:$dsn", $username, $password, $options);
$class = __CLASS__.'_sql';
$this->sql = new $class;
}
// --------------------------------------------------------------------------
/**
* Empty a table
*
* @param string $table
*/
public function truncate($table)
{
$this->query("TRUNCATE `{$table}`");
}
// --------------------------------------------------------------------------
/**
* Get databases for the current connection
*
* @return array
*/
public function get_dbs()
{
$res = $this->query("SHOW DATABASES");
return $this->fetchAll(PDO::FETCH_ASSOC);
}
// --------------------------------------------------------------------------
/**
* Returns the tables available in the current database
*
* @return array
*/
public function get_tables()
{
$res = $this->query("SHOW TABLES");
return $res->fetchAll(PDO::FETCH_ASSOC);
}
// --------------------------------------------------------------------------
/**
* Returns system tables for the current database
*
* @return array
*/
public function get_system_tables()
{
//MySQL doesn't have system tables
return array();
}
// --------------------------------------------------------------------------
/**
* Return the number of rows returned for a SELECT query
*
* @return int
*/
public function num_rows()
{
return isset($this->statement) ? $this->statement->rowCount() : FALSE;
}
// --------------------------------------------------------------------------
/**
* Create an SQL backup file for the current database's structure
*
* @return string
*/
public function backup_structure()
{
// @todo Implement Backup function
return '';
}
// --------------------------------------------------------------------------
/**
* Create an SQL backup file for the current database's data
*
* @return string
*/
public function backup_data()
{
// @todo Implement Backup function
return '';
}
// --------------------------------------------------------------------------
/**
* Surrounds the string with the databases identifier escape characters
*
* @param string $ident
* @return string
*/
public function quote_ident($ident)
{
if (is_array($ident))
{
return array_map(array($this, 'quote_ident'), $ident);
}
// Split each identifier by the period
$hiers = explode('.', $ident);
return '`'.implode('`.`', $hiers).'`';
}
}
//End of mysql.php

80
drivers/mysql_sql.php Normal file
View File

@ -0,0 +1,80 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* MySQL specifc SQL
*/
class MySQL_SQL extends DB_SQL{
/**
* Convienience public function for creating a new MySQL table
*
* @param [type] $name [description]
* @param [type] $columns [description]
* @param array $constraints=array() [description]
* @param array $indexes=array() [description]
*
* @return [type]
*/
public function create_table($name, $columns, array $constraints=array(), array $indexes=array())
{
//TODO: implement
}
// --------------------------------------------------------------------------
/**
* Convience public function for droping a MySQL table
*
* @param string $name
* @return string
*/
public function delete_table($name)
{
return "DROP TABLE `{$name}`";
}
// --------------------------------------------------------------------------
/**
* Limit clause
*
* @param string $sql
* @param int $limit
* @param int $offset
* @return string
*/
public function limit($sql, $limit, $offset=FALSE)
{
if ( ! is_numeric($offset))
{
return $sql." LIMIT {$limit}";
}
return $sql." LIMIT {$offset}, {$limit}";
}
// --------------------------------------------------------------------------
/**
* Random ordering keyword
*
* @return string
*/
public function random()
{
return ' RAND()';
}
}
//End of mysql_sql.php

109
drivers/odbc.php Normal file
View File

@ -0,0 +1,109 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* ODBC Database Driver
*
* For general database access for databases not specified by the main drivers
*
* @extends DB_PDO
*/
class ODBC extends DB_PDO {
public function __construct($dsn, $username=null, $password=null, $options=array())
{
parent::__construct("odbc:$dsn", $username, $password, $options);
$class = __CLASS__.'_sql';
$this->sql = new $class;
}
// --------------------------------------------------------------------------
/**
* List tables for the current database
*
* @return mixed
*/
public function get_tables()
{
//Not possible reliably with this driver
return FALSE;
}
// --------------------------------------------------------------------------
/**
* List system tables for the current database/connection
*
* @return array
*/
public function get_system_tables()
{
//No way of determining for ODBC
return array();
}
// --------------------------------------------------------------------------
/**
* Empty the current database
*
* @return void
*/
public function truncate($table)
{
$sql = "DELETE FROM {$table}";
$this->query($sql);
}
// --------------------------------------------------------------------------
/**
* Return the number of rows returned for a SELECT query
*
* @return int
*/
public function num_rows()
{
// TODO: Implement
}
// --------------------------------------------------------------------------
/**
* Create an SQL backup file for the current database's structure
*
* @return string
*/
public function backup_structure()
{
// Not applicable to ODBC
return '';
}
// --------------------------------------------------------------------------
/**
* Create an SQL backup file for the current database's data
*
* @return string
*/
public function backup_data()
{
// Not applicable to ODBC
return '';
}
}
// End of odbc.php

66
drivers/odbc_sql.php Normal file
View File

@ -0,0 +1,66 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* ODBC SQL Class
*/
class ODBC_SQL extends DB_SQL {
public function create_table($name, $columns, array $constraints=array(), array $indexes=array())
{
//ODBC can't know how to create a table
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Remove a table from the database
*
* @param string $name
* @return string
*/
public function delete_table($name)
{
return "DROP TABLE {$name}";
}
// --------------------------------------------------------------------------
/**
* Limit clause
*
* @param string $sql
* @param int $limit
* @param int $offset
* @return string
*/
public function limit($sql, $limit, $offset=FALSE)
{
return $sql;
}
// --------------------------------------------------------------------------
/**
* Random ordering keyword
*
* @return string
*/
public function random()
{
return FALSE;
}
}
// End of odbc_sql.php

209
drivers/pgsql.php Normal file
View File

@ -0,0 +1,209 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* PostgreSQL specifc class
*
* @extends DB_PDO
*/
class pgSQL extends DB_PDO {
/**
* Connect to a PosgreSQL database
*
* @param string $dsn
* @param string $username=null
* @param string $password=null
* @param array $options=array()
*/
public function __construct($dsn, $username=null, $password=null, $options=array())
{
parent::__construct("pgsql:$dsn", $username, $password, $options);
//Get db manip class
$class = __CLASS__.'_sql';
$this->sql = new $class;
}
// --------------------------------------------------------------------------
/**
* Empty a table
*
* @param string $table
*/
public function truncate($table)
{
$sql = 'TRUNCATE "' . $table . '"';
$this->query($sql);
}
// --------------------------------------------------------------------------
/**
* Get list of databases for the current connection
*
* @return array
*/
public function get_dbs()
{
$sql = <<<SQL
SELECT "datname" FROM "pg_database"
WHERE "datname" NOT IN ('template0','template1')
ORDER BY 1
SQL;
$res = $this->query($sql);
$dbs = $res->fetchAll(PDO::FETCH_ASSOC);
return $dbs;
}
// --------------------------------------------------------------------------
/**
* Get the list of tables for the current db
*
* @return array
*/
public function get_tables()
{
$sql = <<<SQL
SELECT "tablename" FROM "pg_tables"
WHERE "tablename" NOT LIKE 'pg\_%'
AND "tablename" NOT LIKE 'sql\%'
SQL;
$res = $this->query($sql);
$tables = $res->fetchAll(PDO::FETCH_ASSOC);
return $tables;
}
// --------------------------------------------------------------------------
/**
* Get the list of system tables
*
* @return array
*/
public function get_system_tables()
{
$sql = <<<SQL
SELECT "tablename" FROM "pg_tables"
WHERE "tablename" LIKE 'pg\_%'
OR "tablename" LIKE 'sql\%'
SQL;
$res = $this->query($sql);
$tables = $res->fetchAll(PDO::FETCH_ASSOC);
return $tables;
}
// --------------------------------------------------------------------------
/**
* Get a list of schemas, either for the current connection, or
* for the current datbase, if specified.
*
* @param string $database=""
* @return array
*/
public function get_schemas($database="")
{
if($database === "")
{
$sql = <<<SQL
SELECT DISTINCT "schemaname" FROM "pg_tables"
WHERE "schemaname" NOT LIKE 'pg\_%'
SQL;
}
$sql = <<<SQL
SELECT "nspname" FROM pg_namespace
WHERE "nspname" NOT LIKE 'pg\_%'
SQL;
$res = $this->query($sql);
$schemas = $res->fetchAll(PDO::FETCH_ASSOC);
return $schemas;
}
// --------------------------------------------------------------------------
/**
* Get a list of views for the current db
*
* @return array
*/
public function get_views()
{
$sql = <<<SQL
SELECT "viewname" FROM "pg_views"
WHERE "viewname" NOT LIKE 'pg\_%';
SQL;
$res = $this->query($sql);
$views = $res->fetchAll(PDO::FETCH_ASSOC);
return $views;
}
// --------------------------------------------------------------------------
/**
* Return the number of rows returned for a SELECT query
*
* @return int
*/
public function num_rows()
{
return (isset($this->statement)) ? $this->statement->rowCount : FALSE;
}
// --------------------------------------------------------------------------
/**
* Create an SQL backup file for the current database's structure
*
* @return string
*/
public function backup_structure()
{
// @todo Implement Backup function
return '';
}
// --------------------------------------------------------------------------
/**
* Create an SQL backup file for the current database's data
*
* @return string
*/
public function backup_data()
{
// @todo Implement Backup function
return '';
}
}
//End of pgsql.php

67
drivers/pgsql_sql.php Normal file
View File

@ -0,0 +1,67 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* PostgreSQL specifc SQL
*/
class pgSQL_SQL extends DB_SQL {
public function create_table($name, $columns, array $constraints=array(), array $indexes=array())
{
//TODO: implement
}
// --------------------------------------------------------------------------
public function delete_table($name)
{
return 'DROP TABLE "'.$name.'"';
}
// --------------------------------------------------------------------------
/**
* Limit clause
*
* @param string $sql
* @param int $limit
* @param int $offset
* @return string
*/
public function limit($sql, $limit, $offset=FALSE)
{
$sql .= " LIMIT {$limit}";
if(is_numeric($offset))
{
$sql .= " OFFSET {$offset}";
}
return $sql;
}
// --------------------------------------------------------------------------
/**
* Random ordering keyword
*
* @return string
*/
public function random()
{
return ' RANDOM()';
}
}
//End of pgsql_manip.php

232
drivers/sqlite.php Normal file
View File

@ -0,0 +1,232 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* SQLite specific class
*
* @extends DB_PDO
*/
class SQLite extends DB_PDO {
protected $statement;
/**
* Open SQLite Database
*
* @param string $dsn
*/
public function __construct($dsn, $user=NULL, $pass=NULL)
{
// DSN is simply `sqlite:/path/to/db`
parent::__construct("sqlite:{$dsn}", $user, $pass);
$class = __CLASS__."_sql";
$this->sql = new $class;
}
// --------------------------------------------------------------------------
/**
* Empty a table
*
* @param string $table
*/
public function truncate($table)
{
// SQLite has a TRUNCATE optimization,
// but no support for the actual command.
$sql = 'DELETE FROM "'.$table.'"';
$this->statement = $this->query($sql);
return $this->statement;
}
// --------------------------------------------------------------------------
/**
* List tables for the current database
*
* @return mixed
*/
public function get_tables()
{
$tables = array();
$sql = <<<SQL
SELECT "name", "sql"
FROM "sqlite_master"
WHERE "type"='table'
SQL;
$res = $this->query($sql);
$result = $res->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $r)
{
$tables[$r['name']] = $r['sql'];
}
return $tables;
}
// --------------------------------------------------------------------------
/**
* List system tables for the current database
*
* @return array
*/
public function get_system_tables()
{
//SQLite only has the sqlite_master table
// that is of any importance.
return array('sqlite_master');
}
// --------------------------------------------------------------------------
/**
* Load a database for the current connection
*
* @param string $db
* @param string $name
*/
public function load_database($db, $name)
{
$sql = 'ATTACH DATABASE "'.$db.'" AS "'.$name.'"';
$this->query($sql);
}
// --------------------------------------------------------------------------
/**
* Unload a database from the current connection
*
* @param string $name
*/
public function unload_database($name)
{
$sql = 'DETACH DATABASE ":name"';
$this->prepare_query($sql, array(
':name' => $name,
));
$this->statement->execute();
}
// --------------------------------------------------------------------------
/**
* Return the number of rows returned for a SELECT query
*
* @return int
*/
public function num_rows()
{
return (isset($this->statement)) ? $this->statement->rowCount : FALSE;
}
// --------------------------------------------------------------------------
/**
* Create an SQL backup file for the current database's structure
*
* @return string
*/
public function backup_structure()
{
// Fairly easy for SQLite...just query the master table
$sql = 'SELECT "sql" FROM "sqlite_master"';
$res = $this->query($sql);
$result = $res->fetchAll(PDO::FETCH_ASSOC);
$sql_array = array();
foreach($result as $r)
{
$sql_array[] = $r['sql'];
}
$sql_structure = implode("\n\n", $sql_array);
return $sql_structure;
}
// --------------------------------------------------------------------------
/**
* Create an SQL backup file for the current database's data
*
* @param array $excluded
* @return string
*/
public function backup_data($excluded=array())
{
// Get a list of all the objects
$sql = 'SELECT "name" FROM "sqlite_master"';
if( ! empty($excluded))
{
$sql .= ' WHERE NOT IN("'.implode('","', $excluded).'")';
}
$res = $this->query($sql);
$result = $res->fetchAll(PDO::FETCH_ASSOC);
unset($res);
$output_sql = '';
// Get the data for each object
foreach($result as $r)
{
$sql = 'SELECT * FROM "'.$r['name'].'"';
$res = $this->query($sql);
$obj_res = $res->fetchAll(PDO::FETCH_ASSOC);
unset($res);
// Nab the column names by getting the keys of the first row
$columns = array_keys($obj_res[0]);
$insert_rows = array();
// Create the insert statements
foreach($obj_res as $row)
{
$row = array_values($row);
// Quote values as needed by type
for($i=0, $icount=count($row); $i<$icount; $i++)
{
$row[$i] = (is_numeric($row[$i])) ? $row[$i] : $this->quote($row[$i]);
}
$row_string = 'INSERT INTO "'.$r['name'].'" ("'.implode('","', $columns).'") VALUES ('.implode(',', $row).');';
unset($row);
$insert_rows[] = $row_string;
}
unset($obj_res);
$output_sql .= "\n\n".implode("\n", $insert_rows);
}
return $output_sql;
}
}
//End of sqlite.php

122
drivers/sqlite_sql.php Normal file
View File

@ -0,0 +1,122 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* SQLite Specific SQL
*/
class SQLite_SQL extends DB_SQL {
/**
* Convenience public function to create a new table
*
* @param string $name //Name of the table
* @param array $columns //columns as straight array and/or column => type pairs
* @param array $constraints // column => constraint pairs
* @param array $indexes // column => index pairs
* @return string
*/
public function create_table($name, $columns, array $constraints=array(), array $indexes=array())
{
$column_array = array();
// Reorganize into an array indexed with column information
// Eg $column_array[$colname] = array(
// 'type' => ...,
// 'constraint' => ...,
// 'index' => ...,
// )
foreach($columns as $colname => $type)
{
if(is_numeric($colname))
{
$colname = $type;
}
$column_array[$colname] = array();
$column_array[$colname]['type'] = ($type !== $colname) ? $type : '';
}
if( ! empty($constraints))
{
foreach($constraints as $col => $const)
{
$column_array[$col]['constraint'] = $const;
}
}
// Join column definitons together
$columns = array();
foreach($column_array as $n => $props)
{
$str = "{$n} ";
$str .= (isset($props['type'])) ? "{$props['type']} " : "";
$str .= (isset($props['constraint'])) ? $props['constraint'] : "";
$columns[] = $str;
}
// Generate the sql for the creation of the table
$sql = "CREATE TABLE IF NOT EXISTS \"{$name}\" (";
$sql .= implode(", ", $columns);
$sql .= ")";
return $sql;
}
// --------------------------------------------------------------------------
/**
* SQL to drop the specified table
*
* @param string $name
* @return string
*/
public function delete_table($name)
{
return 'DROP TABLE IF EXISTS "'.$name.'"';
}
// --------------------------------------------------------------------------
/**
* Limit clause
*
* @param string $sql
* @param int $limit
* @param int $offset
* @return string
*/
public function limit($sql, $limit, $offset=FALSE)
{
if ( ! is_numeric($offset))
{
return $sql." LIMIT {$limit}";
}
return $sql." LIMIT {$offset}, {$limit}";
}
// --------------------------------------------------------------------------
/**
* Random ordering keyword
*
* @return string
*/
public function random()
{
return ' RANDOM()';
}
}
//End of sqlite_sql.php

1049
query_builder.php Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,219 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* Firebird Query Builder Tests
*/
class FirebirdQBTest extends UnitTestCase {
function __construct()
{
parent::__construct();
$dbpath = TEST_DIR.DS.'test_dbs'.DS.'FB_TEST_DB.FDB';
// Test the query builder
$params = new Stdclass();
$params->type = 'firebird';
$params->file = $dbpath;
$params->host = 'localhost';
$params->user = 'sysdba';
$params->pass = 'masterkey';
$this->db = new Query_Builder($params);
echo '<hr /> Firebird Queries <hr />';
}
function TestGet()
{
$query = $this->db->get('create_test ct');
$this->assertTrue(is_resource($query));
}
function TestGetLimit()
{
$query = $this->db->get('create_test', 2);
$this->assertTrue(is_resource($query));
}
function TestGetLimitSkip()
{
$query = $this->db->get('create_test', 2, 1);
$this->assertTrue(is_resource($query));
}
function TestSelectWhereGet()
{
$query = $this->db->select('id, key as k, val')
->where('id >', 1)
->where('id <', 800)
->get('create_test', 2, 1);
$this->assertTrue(is_resource($query));
}
function TestSelectWhereGet2()
{
$query = $this->db->select('id, key as k, val')
->where(' id ', 1)
->get('create_test', 2, 1);
$this->assertTrue(is_resource($query));
}
function TestSelectGet()
{
$query = $this->db->select('id, key as k, val')
->get('create_test', 2, 1);
$this->assertTrue(is_resource($query));
}
function TestSelectFromGet()
{
$query = $this->db->select('id, key as k, val')
->from('create_test ct')
->where('id >', 1)
->get();
$this->assertTrue(is_resource($query));
}
function TestSelectFromLimitGet()
{
$query = $this->db->select('id, key as k, val')
->from('create_test ct')
->where('id >', 1)
->limit(3)
->get();
$this->assertTrue(is_resource($query));
}
function TestOrderBy()
{
$query = $this->db->select('id, key as k, val')
->from('create_test')
->where('id >', 0)
->where('id <', 9000)
->order_by('id', 'DESC')
->order_by('k', 'ASC')
->limit(5,2)
->get();
$this->assertTrue(is_resource($query));
}
function TestOrderByRand()
{
$query = $this->db->select('id, key as k, val')
->from('create_test')
->where('id >', 0)
->where('id <', 9000)
->order_by('id', 'rand')
->limit(5,2)
->get();
$this->assertTrue(is_resource($query));
}
function TestOrWhere()
{
$query = $this->db->select('id, key as k, val')
->from('create_test')
->where(' id ', 1)
->or_where('key >', 0)
->limit(2, 1)
->get();
$this->assertTrue(is_resource($query));
}
/*function TestGroupBy()
{
$query = $this->db->select('id, key as k, val')
->from('create_test')
->where('id >', 0)
->where('id <', 9000)
->group_by('k')
->group_by('val')
->order_by('id', 'DESC')
->order_by('k', 'ASC')
->limit(5,2)
->get();
$this->assertTrue(is_resource($query));
}*/
function TestLike()
{
$query = $this->db->from('create_test')
->like('key', 'og')
->get();
$this->assertTrue(is_resource($query));
}
function TestWhereIn()
{
$query = $this->db->from('create_test')
->where_in('key', array(12, 96, "works"))
->get();
$this->assertTrue(is_resource($query));
}
function TestJoin()
{
$query = $this->db->from('create_test')
->join('create_join cj', 'cj.id = create_test.id')
->get();
$this->assertTrue(is_resource($query));
}
function TestInsert()
{
$query = $this->db->set('id', 4)
->set('key', 4)
->set('val', 5)
->insert('create_test');
$this->assertTrue($query);
}
function TestUpdate()
{
$query = $this->db->set('id', 4)
->set('key', 'gogle')
->set('val', 'non-word')
->where('id', 4)
->update('create_test');
$this->assertTrue($query);
}
function TestDelete()
{
$query = $this->db->where('id', 4)->delete('create_test');
$this->assertTrue($query);
}
}

View File

@ -0,0 +1,181 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* FirebirdTest class.
*
* @extends UnitTestCase
*/
class FirebirdTest extends UnitTestCase {
/**
* __construct function.
*
* @access public
* @return void
*/
function __construct()
{
parent::__construct();
}
function setUp()
{
$dbpath = TEST_DIR.DS.'test_dbs'.DS.'FB_TEST_DB.FDB';
// Test the db driver directly
$this->db = new Firebird('localhost:'.$dbpath);
$this->tables = $this->db->get_tables();
}
function tearDown()
{
unset($this->db);
unset($this->tables);
}
function TestConnection()
{
$this->assertIsA($this->db, 'Firebird');
}
function TestGetTables()
{
$tables = $this->tables;
$this->assertTrue(is_array($tables));
}
function TestGetSystemTables()
{
$only_system = TRUE;
$tables = $this->db->get_system_tables();
foreach($tables as $t)
{
if(stripos($t, 'rdb$') !== 0 && stripos($t, 'mon$') !== 0)
{
$only_system = FALSE;
break;
}
}
$this->assertTrue($only_system);
}
function TestCreateTransaction()
{
$res = $this->db->beginTransaction();
$this->assertTrue($res);
}
/*function TestCreateTable()
{
//Attempt to create the table
$sql = $this->db->sql->create_table('create_join', array(
'id' => 'SMALLINT',
'key' => 'VARCHAR(64)',
'val' => 'BLOB SUB_TYPE TEXT'
));
$this->db->query($sql);
//This test fails for an unknown reason, when clearly the table exists
//Reset
$this->tearDown();
$this->setUp();
//Check
$table_exists = (bool)in_array('create_test', $this->tables);
echo "create_test exists :".(int)$table_exists.'<br />';
$this->assertTrue($table_exists);
}*/
function TestTruncate()
{
$this->db->truncate('create_test');
$this->assertTrue($this->db->affected_rows() > 0);
}
function TestCommitTransaction()
{
$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);
}
function TestRollbackTransaction()
{
$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);
}
function TestPreparedStatements()
{
$sql = <<<SQL
INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?)
SQL;
$this->db->prepare($sql);
$this->db->execute(array(1,"booger's", "Gross"));
}
function TestPrepareExecute()
{
$sql = <<<SQL
INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?)
SQL;
$this->db->prepare_execute($sql, array(
2, "works", 'also?'
));
}
function TestPrepareQuery()
{
$this->assertFalse($this->db->prepare_query('', array()));
}
/*function TestDeleteTable()
{
//Attempt to delete the table
$sql = $this->db->sql->delete_table('create_test');
$this->db->query($sql);
//Reset
$this->tearDown();
$this->setUp();
//Check
$table_exists = in_array('create_test', $this->tables);
$this->assertFalse($table_exists);
}*/
}

View File

@ -0,0 +1,26 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
class MySQLQBTest extends UnitTestCase {
function __construct()
{
}
function TestExists()
{
$this->assertTrue(in_array('mysql', pdo_drivers()));
}
}

32
tests/databases/mysql.php Normal file
View File

@ -0,0 +1,32 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* MySQLTest class.
*
* @extends UnitTestCase
*/
class MySQLTest extends UnitTestCase {
function __construct()
{
}
function TestExists()
{
$this->assertTrue(in_array('mysql', pdo_drivers()));
}
}

View File

@ -0,0 +1,26 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
class ODBCQBTest extends UnitTestCase {
function __construct()
{
}
function TestExists()
{
$this->assertTrue(in_array('odbc', pdo_drivers()));
}
}

31
tests/databases/odbc.php Normal file
View File

@ -0,0 +1,31 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* ODBCTest class.
*
* @extends UnitTestCase
*/
class ODBCTest extends UnitTestCase {
function __construct()
{
}
function TestExists()
{
$this->assertTrue(in_array('odbc', pdo_drivers()));
}
}

View File

@ -0,0 +1,26 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
class PgSQLQBTest extends UnitTestCase {
function __construct()
{
}
function TestExists()
{
$this->assertTrue(in_array('pgsql', pdo_drivers()));
}
}

37
tests/databases/pgsql.php Normal file
View File

@ -0,0 +1,37 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* PgTest class.
*
* @extends UnitTestCase
*/
class PgTest extends UnitTestCase {
/**
* __construct function.
*
* @access public
* @return void
*/
function __construct()
{
parent::__construct();
}
function TestExists()
{
$this->assertTrue(in_array('pgsql', pdo_drivers()));
}
}

View File

@ -0,0 +1,203 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* Class for testing Query Builder with SQLite
*/
class SQLiteQBTest extends UnitTestCase {
function __construct()
{
parent::__construct();
$path = TEST_DIR.DS.'test_dbs'.DS.'test_sqlite.db';
$params = new Stdclass();
$params->type = 'sqlite';
$params->file = $path;
$params->host = 'localhost';
$this->db = new Query_Builder($params);
echo '<hr /> SQLite Queries <hr />';
}
function TestGet()
{
$query = $this->db->get('create_test ct');
$this->assertIsA($query, 'PDOStatement');
}
function TestGetLimit()
{
$query = $this->db->get('create_test', 2);
$this->assertIsA($query, 'PDOStatement');
}
function TestGetLimitSkip()
{
$query = $this->db->get('create_test', 2, 1);
$this->assertIsA($query, 'PDOStatement');
}
function TestSelectWhereGet()
{
$query = $this->db->select('id, key as k, val')
->where('id >', 1)
->where('id <', 900)
->get('create_test', 2, 1);
$this->assertIsA($query, 'PDOStatement');
}
function TestSelectWhereGet2()
{
$query = $this->db->select('id, key as k, val')
->where('id !=', 1)
->get('create_test', 2, 1);
$this->assertIsA($query, 'PDOStatement');
}
function TestSelectGet()
{
$query = $this->db->select('id, key as k, val')
->get('create_test', 2, 1);
$this->assertIsA($query, 'PDOStatement');
}
function TestSelectFromGet()
{
$query = $this->db->select('id, key as k, val')
->from('create_test ct')
->where('id >', 1)
->get();
$this->assertIsA($query, 'PDOStatement');
}
function TestSelectFromLimitGet()
{
$query = $this->db->select('id, key as k, val')
->from('create_test ct')
->where('id >', 1)
->limit(3)
->get();
$this->assertIsA($query, 'PDOStatement');
}
function TestOrderBy()
{
$query = $this->db->select('id, key as k, val')
->from('create_test')
->where('id >', 0)
->where('id <', 9000)
->order_by('id', 'DESC')
->order_by('k', 'ASC')
->limit(5,2)
->get();
$this->assertIsA($query, 'PDOStatement');
}
function TestOrderByRandom()
{
$query = $this->db->select('id, key as k, val')
->from('create_test')
->where('id >', 0)
->where('id <', 9000)
->order_by('id', 'rand')
->limit(5,2)
->get();
$this->assertIsA($query, 'PDOStatement');
}
function TestGroupBy()
{
$query = $this->db->select('id, key as k, val')
->from('create_test')
->where('id >', 0)
->where('id <', 9000)
->group_by('k')
->group_by('val')
->order_by('id', 'DESC')
->order_by('k', 'ASC')
->limit(5,2)
->get();
$this->assertIsA($query, 'PDOStatement');
}
function TestOrWhere()
{
$query = $this->db->select('id, key as k, val')
->from('create_test')
->where(' id ', 1)
->or_where('key >', 0)
->limit(2, 1)
->get();
$this->assertIsA($query, 'PDOStatement');
}
function TestLike()
{
$query = $this->db->from('create_test')
->like('key', 'og')
->get();
$this->assertIsA($query, 'PDOStatement');
}
function TestJoin()
{
$query = $this->db->from('create_test')
->join('create_join cj', 'cj.id = create_test.id')
->get();
$this->assertIsA($query, 'PDOStatement');
}
function TestInsert()
{
$query = $this->db->set('id', 4)
->set('key', 4)
->set('val', 5)
->insert('create_test');
$this->assertIsA($query, 'PDOStatement');
}
function TestUpdate()
{
$query = $this->db->set('id', 4)
->set('key', 'gogle')
->set('val', 'non-word')
->where('id', 4)
->update('create_test');
$this->assertIsA($query, 'PDOStatement');
}
function TestDelete()
{
$query = $this->db->where('id', 4)->delete('create_test');
$this->assertIsA($query, 'PDOStatement');
}
}

163
tests/databases/sqlite.php Normal file
View File

@ -0,0 +1,163 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* SQLiteTest class.
*
* @extends UnitTestCase
*/
class SQLiteTest extends UnitTestCase {
function __construct()
{
parent::__construct();
}
function setUp()
{
$path = TEST_DIR.DS.'test_dbs'.DS.'test_sqlite.db';
$this->db = new SQLite($path);
}
function tearDown()
{
unset($this->db);
}
function TestConnection()
{
$this->assertIsA($this->db, 'SQLite');
}
function TestGetTables()
{
$tables = $this->db->get_tables();
$this->assertTrue(is_array($tables));
}
function TestGetSystemTables()
{
$tables = $this->db->get_system_tables();
$this->assertTrue(is_array($tables));
}
function TestCreateTransaction()
{
$res = $this->db->beginTransaction();
$this->assertTrue($res);
}
function TestCreateTable()
{
//Attempt to create the table
$sql = $this->db->sql->create_table('create_test',
array(
'id' => 'INTEGER',
'key' => 'TEXT',
'val' => 'TEXT',
),
array(
'id' => 'PRIMARY KEY'
)
);
$this->db->query($sql);
//Attempt to create the table
$sql = $this->db->sql->create_table('create_join',
array(
'id' => 'INTEGER',
'key' => 'TEXT',
'val' => 'TEXT',
),
array(
'id' => 'PRIMARY KEY'
)
);
$this->db->query($sql);
//Check
$dbs = $this->db->get_tables();
$this->assertEqual($dbs['create_test'], 'CREATE TABLE "create_test" (id INTEGER PRIMARY KEY, key TEXT , val TEXT )');
}
function TestTruncate()
{
$this->db->truncate('create_test');
$this->assertIsA($this->db->affected_rows(), 'int');
}
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();
}
function TestPrepareExecute()
{
$sql = <<<SQL
INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?)
SQL;
$this->db->prepare_execute($sql, array(
2, "works", 'also?'
));
}
function TestCommitTransaction()
{
$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);
}
function TestRollbackTransaction()
{
$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);
}
// This is really time intensive ! Run only when needed
/*function TestDeleteTable()
{
//Make sure the table exists to delete
$dbs = $this->db->get_tables();
$this->assertTrue(isset($dbs['create_test']));
//Attempt to delete the table
$sql = $this->db->sql->delete_table('create_test');
$this->db->query($sql);
//Check
$dbs = $this->db->get_tables();
$this->assertFalse(in_array('create_test', $dbs));
}*/
}

70
tests/index.php Normal file
View File

@ -0,0 +1,70 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* Unit test bootstrap - Using php simpletest
*/
define('BASE_DIR', '../');
define('TEST_DIR', dirname(__FILE__));
define('DS', DIRECTORY_SEPARATOR);
// Include simpletest
// it has to be set in your php path, or put in the tests folder
require_once('simpletest/autorun.php');
// Bulk loading wrapper workaround for PHP < 5.4
function do_include($path)
{
require_once($path);
}
// Include core tests;
require_once(BASE_DIR.'db_pdo.php');
require_once(BASE_DIR.'query_builder.php');
// Include db tests
// Load db classes based on capability
$src_path = BASE_DIR.'drivers/';
$test_path = './databases/';
foreach(pdo_drivers() as $d)
{
// PDO firebird isn't stable enough to
// bother, so skip it.
if ($d === 'firebird')
{
continue;
}
$src_file = "{$src_path}{$d}.php";
if(is_file($src_file))
{
require_once("{$src_path}{$d}.php");
require_once("{$src_path}{$d}_sql.php");
require_once("{$test_path}{$d}.php");
require_once("{$test_path}{$d}-qb.php");
}
}
// Load Firebird if there is support
if(function_exists('ibase_connect'))
{
require_once("{$src_path}firebird-ibase.php");
require_once("{$src_path}firebird_sql.php");
require_once("{$test_path}firebird.php");
require_once("{$test_path}firebird-qb.php");
}

BIN
tests/test_dbs/FB_TEST_DB.FDB Executable file

Binary file not shown.

Binary file not shown.