Reorganize drivers

This commit is contained in:
Timothy Warren 2012-04-10 14:06:34 -04:00
parent 76b522f0bd
commit 86fe790f28
35 changed files with 2753 additions and 2029 deletions

View File

@ -14,34 +14,56 @@
/**
* Autoloader for loading available database classes
*
*/
define('BASE_PATH', dirname(__FILE__).'/');
define('DRIVER_PATH', BASE_PATH.'drivers/');
// Bulk loading wrapper workaround for PHP < 5.4
function do_include($path)
{
require_once($path);
}
// Load base classes
require_once(BASE_PATH.'db_pdo.php');
require_once(BASE_PATH.'db_sql.php');
require_once(BASE_PATH.'query_builder.php');
// Load PDO Drivers
foreach(pdo_drivers() as $d)
{
$f = DRIVER_PATH.$d.'.php';
$fsql = DRIVER_PATH.$d."_sql.php";
$dir = DRIVER_PATH.$d;
if(is_file($f) && $f !== 'firebird')
if(is_dir($dir))
{
require_once($f);
require_once($fsql);
array_map('do_include', glob($dir.'/*.php'));
}
}
// Load Firebird driver, if applicable
if (function_exists('fbird_connect'))
{
require_once(DRIVER_PATH.'firebird.php');
require_once(DRIVER_PATH.'firebird_sql.php');
array_map('do_include', glob(DRIVER_PATH.'/firebird/*.php'));
}
/**
* Filter out db rows into one array
*
* @param array $array
* @param mixed $index
* @return array
*/
function db_filter($array, $index)
{
$new_array = array();
foreach($array as $a)
{
$new_array[] = $a[$index];
}
return $new_array;
}
// End of autoload.php

View File

@ -16,11 +16,14 @@
* Base Database class
*
* Extends PDO to simplify cross-database issues
*
* @abstract
*/
abstract class DB_PDO extends PDO {
public $manip;
protected $statement;
protected $escape_char = '"';
/**
* PDO constructor wrapper
@ -28,6 +31,8 @@ abstract class DB_PDO extends PDO {
public function __construct($dsn, $username=NULL, $password=NULL, $driver_options=array())
{
parent::__construct($dsn, $username, $password, $driver_options);
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
// -------------------------------------------------------------------------
@ -132,11 +137,6 @@ abstract class DB_PDO extends PDO {
$this->statement = $statement;
}
if (empty($this->statement))
{
return FALSE;
}
// Return number of rows affected
return $this->statement->rowCount();
}
@ -173,7 +173,9 @@ abstract class DB_PDO extends PDO {
// Split each identifier by the period
$hiers = explode('.', $ident);
return '"'.implode('"."', $hiers).'"';
return $this->escape_char .
implode("{$this->escape_char}.{$this->escape_char}", $hiers) .
$this->escape_char;
}
// -------------------------------------------------------------------------
@ -195,22 +197,140 @@ abstract class DB_PDO extends PDO {
// -------------------------------------------------------------------------
/**
* Abstract public functions to override in child classes
* Return schemas for databases that list them
*
* @return array
*/
public function get_schemas()
{
return FALSE;
}
// -------------------------------------------------------------------------
/**
* Method to simplify retreiving db results for meta-data queries
*
* @param string $sql
* @param bool $filtered_index
* @return mixed
*/
protected function driver_query($sql, $filtered_index=TRUE)
{
if ($sql === FALSE)
{
return FALSE;
}
$res = $this->query($sql);
$flag = ($filtered_index) ? PDO::FETCH_NUM : PDO::FETCH_ASSOC;
$all = $res->fetchAll($flag);
return ($filtered_index) ? db_filter($all, 0) : $all;
}
// -------------------------------------------------------------------------
/**
* Return list of tables for the current database
*
* @return array
*/
abstract public function get_tables();
public function get_tables()
{
return $this->driver_query($this->sql->table_list());
}
// -------------------------------------------------------------------------
/**
* Return list of dbs for the current connection, if possible
*
* @return array
*/
abstract public function get_dbs();
public function get_dbs()
{
return $this->driver_query($this->sql->db_list());
}
// -------------------------------------------------------------------------
/**
* Return list of views for the current database
*
* @return array
*/
public function get_views()
{
return $this->driver_query($this->sql->view_list());
}
// -------------------------------------------------------------------------
/**
* Return list of sequences for the current database, if they exist
*
* @return array
*/
public function get_sequences()
{
return $this->driver_query($this->sql->sequence_list());
}
// -------------------------------------------------------------------------
/**
* Return list of function for the current database
*
* @return array
*/
public function get_functions()
{
return $this->driver_query($this->sql->function_list(), FALSE);
}
// -------------------------------------------------------------------------
/**
* Return list of stored procedures for the current database
*
* @return array
*/
public function get_procedures()
{
return $this->driver_query($this->sql->procedure_list(), FALSE);
}
// -------------------------------------------------------------------------
/**
* Return list of triggers for the current database
*
* @return array
*/
public function get_triggers()
{
return $this->driver_query($this->sql->trigger_list(), FALSE);
}
// -------------------------------------------------------------------------
/**
* Retreives an array of non-user-created tables for
* the connection/database
*
* @return array
*/
public function get_system_tables()
{
return $this->driver_query($this->sql->system_table_list());
}
// -------------------------------------------------------------------------
// ! Abstract public functions to override in child classes
// -------------------------------------------------------------------------
/**
* Empty the passed table
@ -229,69 +349,11 @@ abstract class DB_PDO extends PDO {
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
* Connect to a different database
*
* @param string $name
* @param array $columns
* @param array $constraints
* @param array $indexes
* @return string
* @return void
*/
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();
abstract public function switch_db($name);
}
// End of db_pdo.php

132
db_sql.php Normal file
View File

@ -0,0 +1,132 @@
<?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
*/
// --------------------------------------------------------------------------
/**
* Abstract parent for database manipulation subclasses
*/
abstract class DB_SQL {
/**
* Get database-specific sql to create a new table
*
* @abstract
* @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
*
* @abstract
* @param string $name
* @return string
*/
abstract public function delete_table($name);
/**
* Get database specific sql for limit clause
*
* @abstract
* @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
*
* @abstract
* @return string
*/
abstract public function random();
/**
* Return an SQL file with the database table structure
*
* @abstract
* @return string
*/
abstract public function backup_structure();
/**
* Return an SQL file with the database data as insert statements
*
* @abstract
* @return string
*/
abstract public function backup_data();
/**
* Returns sql to list other databases
*
* @return string
*/
abstract public function db_list();
/**
* Returns sql to list tables
*
* @return string
*/
abstract public function table_list();
/**
* Returns sql to list system tables
*
* @return string
*/
abstract public function system_table_list();
/**
* Returns sql to list views
*
* @return string
*/
abstract public function view_list();
/**
* Returns sql to list triggers
*
* @return string
*/
abstract public function trigger_list();
/**
* Return sql to list functions
*
* @return FALSE
*/
abstract public function function_list();
/**
* Return sql to list stored procedures
*
* @return string
*/
abstract public function procedure_list();
/**
* Return sql to list sequences
*
* @return string
*/
abstract public function sequence_list();
}
// End of db_sql.php

View File

@ -1,559 +0,0 @@
<?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 fbird_ public functions.
*/
class firebird extends DB_PDO {
protected $statement, $statement_link, $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 = @fbird_connect($dbpath, $user, $pass, 'utf-8');
// Throw an exception to make this match other pdo classes
if ( ! is_resource($this->conn))
{
throw new PDOException(fbird_errmsg());
die();
}
$class = __CLASS__."_sql";
$this->sql = new $class;
}
// --------------------------------------------------------------------------
/**
* Close the link to the database
*/
public function __destruct()
{
@fbird_close();
@fbird_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_link = @fbird_query($this->trans, $sql);
}
else
{
$this->statement_link = @fbird_query($this->conn, $sql);
}
// Throw the error as a exception
if ($this->statement_link === FALSE)
{
throw new PDOException(fbird_errmsg());
}
return new FireBird_Result($this->statement_link);
}
// --------------------------------------------------------------------------
/**
* Emulate PDO prepare
*
* @param string $query
* @return $this
*/
public function prepare($query, $options=NULL)
{
$this->statement_link = @fbird_prepare($this->conn, $query);
// Throw the error as an exception
if ($this->statement_link === FALSE)
{
throw new PDOException(fbird_errmsg());
}
return new FireBird_Result($this->statement_link);
}
// --------------------------------------------------------------------------
/**
* 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->statement->fetch(PDO::FETCH_ASSOC))
{
$tables[] = $row['RDB$RELATION_NAME'];
}
return $tables;
}
// --------------------------------------------------------------------------
/**
* Not applicable to firebird
*
* @return FALSE
*/
public function get_dbs()
{
return FALSE;
}
// --------------------------------------------------------------------------
/**
* 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->statement->fetch(PDO::FETCH_ASSOC))
{
$tables[] = $row['RDB$RELATION_NAME'];
}
return $tables;
}
// --------------------------------------------------------------------------
/**
* 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->statement->fetchAll();
return count($this->result);
}
// --------------------------------------------------------------------------
/**
* Start a database transaction
*
* @return bool
*/
public function beginTransaction()
{
if(($this->trans = fbird_trans($this->conn)) !== NULL)
{
return TRUE;
}
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Commit a database transaction
*
* @return bool
*/
public function commit()
{
return fbird_commit($this->trans);
}
// --------------------------------------------------------------------------
/**
* Rollback a transaction
*
* @return bool
*/
public function rollBack()
{
return fbird_rollback($this->trans);
}
// --------------------------------------------------------------------------
/**
* 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 $query->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 = fbird_errcode();
$msg = fbird_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;
}
}
// --------------------------------------------------------------------------
/**
* Firebird result class to emulate PDOStatement Class
*/
class Firebird_Result {
private $statement;
/**
* Create the object by passing the resource for
* the query
*
* @param resource $link
*/
public function __construct($link)
{
$this->statement = $link;
}
// --------------------------------------------------------------------------
/**
* Emulate PDO fetch public function
*
* @param int $fetch_style
* @return mixed
*/
public function fetch($fetch_style=PDO::FETCH_ASSOC, $statement=NULL)
{
if ( ! is_null($statement))
{
$this->statement = $statement;
}
switch($fetch_style)
{
case PDO::FETCH_OBJ:
return fbird_fetch_object($this->statement, IBASE_FETCH_BLOBS);
break;
case PDO::FETCH_NUM:
return fbird_fetch_row($this->statement, IBASE_FETCH_BLOBS);
break;
default:
return fbird_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, $statement=NULL)
{
$all = array();
while($row = $this->fetch($fetch_style, $statement))
{
$all[] = $row;
}
$this->result = $all;
return $all;
}
// --------------------------------------------------------------------------
/**
* 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
$this->__construct(call_user_func_array('fbird_execute', $args));
return $this;
}
// --------------------------------------------------------------------------
/**
* Return the number of rows affected by the previous query
*
* @return int
*/
public function rowCount($statement="")
{
return fbird_affected_rows();
}
// --------------------------------------------------------------------------
/**
* Method to emulate PDO->errorInfo / PDOStatement->errorInfo
*
* @return array
*/
public function errorInfo()
{
$code = fbird_errcode();
$msg = fbird_errmsg();
return array(0, $code, $msg);
}
// --------------------------------------------------------------------------
/**
* Method to emulate PDOStatement->errorCode()
*
* @return int
*/
public function errorCode()
{
return fbird_errcode();
}
// --------------------------------------------------------------------------
/**
* Method to emulate PDOStatement->debugDumpParams
*
* @return string
*/
public function debugDumpParams()
{
$params = array();
$num_params = fbird_num_params($this->statement);
for($i=0; $i < $num_params; $i++)
{
$params[] = fbird_param_info($this->statement, $i);
}
return print_r($params, TRUE);
}
}
// End of firebird-fbird.php

View File

@ -0,0 +1,257 @@
<?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 fbird_ public functions.
*/
class firebird extends DB_PDO {
protected $statement, $statement_link, $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 = fbird_connect($dbpath, $user, $pass, 'utf-8');
// Throw an exception to make this match other pdo classes
/*if ( ! is_resource($this->conn))
{
throw new PDOException(fbird_errmsg());
die();
}*/
$class = __CLASS__."_sql";
$this->sql = new $class;
}
// --------------------------------------------------------------------------
/**
* Close the link to the database and any existing results
*/
public function __destruct()
{
@fbird_close();
@fbird_free_result($this->statement);
}
// --------------------------------------------------------------------------
/**
* Doesn't apply to Firebird
*/
public function switch_db($name)
{
return FALSE;
}
// --------------------------------------------------------------------------
/**
* 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
* @return $this
*/
public function query($sql)
{
$this->count = 0;
$this->statement_link = (isset($this->trans))
? fbird_query($this->trans, $sql)
: fbird_query($this->conn, $sql);
// Throw the error as a exception
if ($this->statement_link === FALSE)
{
throw new PDOException(fbird_errmsg());
}
return new FireBird_Result($this->statement_link);
}
// --------------------------------------------------------------------------
/**
* Emulate PDO prepare
*
* @param string $query
* @return $this
*/
public function prepare($query, $options=NULL)
{
$this->statement_link = fbird_prepare($this->conn, $query);
// Throw the error as an exception
if ($this->statement_link === FALSE)
{
throw new PDOException(fbird_errmsg());
}
return new FireBird_Result($this->statement_link);
}
// --------------------------------------------------------------------------
/**
* 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->statement->fetchAll();
return count($this->result);
}
// --------------------------------------------------------------------------
/**
* Start a database transaction
*
* @return bool
*/
public function beginTransaction()
{
if(($this->trans = fbird_trans($this->conn)) !== NULL)
{
return TRUE;
}
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Commit a database transaction
*
* @return bool
*/
public function commit()
{
return fbird_commit($this->trans);
}
// --------------------------------------------------------------------------
/**
* Rollback a transaction
*
* @return bool
*/
public function rollBack()
{
return fbird_rollback($this->trans);
}
// --------------------------------------------------------------------------
/**
* 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 $query->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 = fbird_errcode();
$msg = fbird_errmsg();
return array(0, $code, $msg);
}
// --------------------------------------------------------------------------
/**
* Bind a prepared query with arguments for executing
*
* @return FALSE
*/
public function prepare_query($sql, $params)
{
// You can't bind query statements before execution with
// the firebird database
return FALSE;
}
}
// End of firebird_driver.php

View File

@ -0,0 +1,137 @@
<?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 result class to emulate PDOStatement Class - only implements
* data-fetching methods
*
* @todo Implement more of the PDOStatement Class
*/
class Firebird_Result {
private $statement;
/**
* Create the object by passing the resource for
* the query
*
* @param resource $link
*/
public function __construct($link)
{
$this->statement = $link;
}
// --------------------------------------------------------------------------
/**
* Emulate PDO fetch public function
*
* @param int $fetch_style
* @return mixed
*/
public function fetch($fetch_style=PDO::FETCH_ASSOC, $statement=NULL)
{
if ( ! is_null($statement))
{
$this->statement = $statement;
}
switch($fetch_style)
{
case PDO::FETCH_OBJ:
return fbird_fetch_object($this->statement, IBASE_FETCH_BLOBS);
break;
case PDO::FETCH_NUM:
return fbird_fetch_row($this->statement, IBASE_FETCH_BLOBS);
break;
default:
return fbird_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, $statement=NULL)
{
$all = array();
while($row = $this->fetch($fetch_style, $statement))
{
$all[] = $row;
}
$this->result = $all;
return $all;
}
// --------------------------------------------------------------------------
/**
* 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
// Then pass the resource to the constructor
$this->__construct(call_user_func_array('fbird_execute', $args));
return $this;
}
// --------------------------------------------------------------------------
/**
* Return the number of rows affected by the previous query
*
* @return int
*/
public function rowCount()
{
return fbird_affected_rows();
}
// --------------------------------------------------------------------------
/**
* Method to emulate PDO->errorInfo / PDOStatement->errorInfo
*
* @return array
*/
public function errorInfo()
{
$code = fbird_errcode();
$msg = fbird_errmsg();
return array(0, $code, $msg);
}
}
// End of firebird_result.php

View File

@ -0,0 +1,334 @@
<?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;
}
// --------------------------------------------------------------------------
/**
* Create an SQL backup file for the current database's structure
*
* @return string
*/
public function backup_structure()
{
// @todo Implement Backup structure 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;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list other databases
*
* @return FALSE
*/
public function db_list()
{
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list tables
*
* @return string
*/
public function table_list()
{
return <<<SQL
SELECT "RDB\$RELATION_NAME" FROM "RDB\$RELATIONS"
WHERE "RDB\$RELATION_NAME" NOT LIKE 'RDB$%'
AND "RDB\$RELATION_NAME" NOT LIKE 'MON$%'
AND "RDB\$VIEW_BLR" IS NOT NULL
ORDER BY "RDB\$RELATION_NAME" ASC
SQL;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list system tables
*
* @return string
*/
public function system_table_list()
{
return <<<SQL
SELECT "RDB\$RELATION_NAME" FROM "RDB\$RELATIONS"
WHERE "RDB\$RELATION_NAME" LIKE 'RDB$%'
OR "RDB\$RELATION_NAME" LIKE 'MON$%';
SQL;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list views
*
* @return string
*/
public function view_list()
{
return <<<SQL
SELECT "RDB\$RELATION_NAME"
FROM "RDB\$RELATIONS"
WHERE "RDB\$VIEW_BLR" IS NOT NULL
AND ("RDB\$SYSTEM_FLAG" IS NULL OR "RDB\$SYSTEM_FLAG" = 0)
SQL;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list triggers
*
* @return string
*/
public function trigger_list()
{
return <<<SQL
SELECT * FROM "RDB\$FUNCTIONS"
WHERE "RDB\$SYSTEM_FLAG" = 0
SQL;
}
// --------------------------------------------------------------------------
/**
* Return sql to list functions
*
* @return string
*/
public function function_list()
{
return <<<SQL
SELECT * FROM "RDB\$FUNCTIONS"
WHERE "RDB\$SYSTEM_FLAG" = 0
SQL;
}
// --------------------------------------------------------------------------
/**
* Return sql to list stored procedures
*
* @return string
*/
public function procedure_list()
{
return 'SELECT * FROM "RDB$PROCEDURES"';
}
// --------------------------------------------------------------------------
/**
* Return sql to list sequences
*
* @return string
*/
public function sequence_list()
{
return <<<SQL
SELECT "RDB\$GENERATOR_NAME"
FROM "RDB\$GENERATORS"
WHERE "RDB\$SYSTEM_FLAG" = 0
SQL;
}
}
//End of firebird_sql.php

View File

@ -1,130 +0,0 @@
<?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

View File

@ -1,166 +0,0 @@
<?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");
$vals = array_values($res->fetchAll(PDO::FETCH_ASSOC));
$return = array();
foreach($vals as $v)
{
$return[] = $v['Database'];
}
return $return;
}
// --------------------------------------------------------------------------
/**
* Returns the tables available in the current database
*
* @return array
*/
public function get_tables()
{
$res = $this->query("SHOW TABLES");
$tables = array();
$rows = $res->fetchAll(PDO::FETCH_NUM);
foreach($rows as $r)
{
$tables[] = $r[0];
}
return $tables;
}
// --------------------------------------------------------------------------
/**
* 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

View File

@ -0,0 +1,89 @@
<?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 {
protected $escape_char = '`';
/**
* 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;
}
// --------------------------------------------------------------------------
/**
* Connect to a different database
*
* @param string $name
*/
public function switch_db($name)
{
// @todo Implement
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Empty a table
*
* @param string $table
*/
public function truncate($table)
{
$this->query("TRUNCATE `{$table}`");
}
// --------------------------------------------------------------------------
/**
* Returns system tables for the current database
*
* @return array
*/
public function get_system_tables()
{
return array('information_schema');
}
// --------------------------------------------------------------------------
/**
* Return the number of rows returned for a SELECT query
*
* @return int
*/
public function num_rows()
{
return isset($this->statement) ? $this->statement->rowCount() : FALSE;
}
}
//End of mysql_driver.php

255
drivers/mysql/mysql_sql.php Normal file
View File

@ -0,0 +1,255 @@
<?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 string $name
* @param array $columns
* @param array $constraints=array()
* @param array $indexes=array()
*
* @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} ({$col})";
}
}
// Join column definitons together
$columns = array();
foreach($column_array as $n => $props)
{
$n = trim($n, '`');
$str = "`{$n}` ";
$str .= (isset($props['type'])) ? "{$props['type']} " : "";
$columns[] = $str;
}
// Add constraints
foreach($column_array as $n => $props)
{
if (isset($props['constraint']))
{
$columns[] = $props['constraint'];
}
}
// Generate the sql for the creation of the table
$sql = "CREATE TABLE IF NOT EXISTS `{$name}` (";
$sql .= implode(", ", $columns);
$sql .= ")";
return $sql;
}
// --------------------------------------------------------------------------
/**
* 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()';
}
// --------------------------------------------------------------------------
/**
* 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 '';
}
// --------------------------------------------------------------------------
/**
* Returns sql to list other databases
*
* @return string
*/
public function db_list()
{
return "SHOW DATABASES WHERE `Database` !='information_schema'";
}
// --------------------------------------------------------------------------
/**
* Returns sql to list tables
*
* @return string
*/
public function table_list()
{
return 'SHOW TABLES';
}
// --------------------------------------------------------------------------
/**
* Overridden in MySQL class
*
* @return string
*/
public function system_table_list()
{
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list views
*
* @return string
*/
public function view_list()
{
return 'SELECT `table_name` FROM `information_schema`.`views`';
}
// --------------------------------------------------------------------------
/**
* Returns sql to list triggers
*
* @return string
*/
public function trigger_list()
{
return 'SHOW TRIGGERS';
}
// --------------------------------------------------------------------------
/**
* Return sql to list functions
*
* @return string
*/
public function function_list()
{
return 'SHOW FUNCTION STATUS';
}
// --------------------------------------------------------------------------
/**
* Return sql to list stored procedures
*
* @return string
*/
public function procedure_list()
{
return 'SHOW PROCEDURE STATUS';
}
// --------------------------------------------------------------------------
/**
* Return sql to list sequences
*
* @return FALSE
*/
public function sequence_list()
{
return FALSE;
}
}
//End of mysql_sql.php

View File

@ -1,133 +0,0 @@
<?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())
{
$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} ({$col})";
}
}
// Join column definitons together
$columns = array();
foreach($column_array as $n => $props)
{
$n = trim($n, '`');
$str = "`{$n}` ";
$str .= (isset($props['type'])) ? "{$props['type']} " : "";
$columns[] = $str;
}
// Add constraints
foreach($column_array as $n => $props)
{
if (isset($props['constraint']))
{
$columns[] = $props['constraint'];
}
}
// Generate the sql for the creation of the table
$sql = "CREATE TABLE IF NOT EXISTS `{$name}` (";
$sql .= implode(", ", $columns);
$sql .= ")";
return $sql;
}
// --------------------------------------------------------------------------
/**
* 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

View File

@ -32,43 +32,15 @@ class ODBC extends DB_PDO {
// --------------------------------------------------------------------------
/**
* List tables for the current database
*
* @return mixed
* Doesn't apply to ODBC
*/
public function get_tables()
{
//Not possible reliably with this driver
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Not applicable to firebird
*
* @return FALSE
*/
public function get_dbs()
public function switch_db($name)
{
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
*
@ -89,33 +61,7 @@ class ODBC extends DB_PDO {
*/
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 '';
// @TODO: Implement
}
}
// End of odbc.php
// End of odbc_driver.php

188
drivers/odbc/odbc_sql.php Normal file
View File

@ -0,0 +1,188 @@
<?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;
}
// --------------------------------------------------------------------------
/**
* 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 '';
}
// --------------------------------------------------------------------------
/**
* Returns sql to list other databases
*
* @return FALSE
*/
public function db_list()
{
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list tables
*
* @return FALSE
*/
public function table_list()
{
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list system tables
*
* @return FALSE
*/
public function system_table_list()
{
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list views
*
* @return FALSE
*/
public function view_list()
{
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list triggers
*
* @return FALSE
*/
public function trigger_list()
{
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Return sql to list functions
*
* @return FALSE
*/
public function function_list()
{
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Return sql to list stored procedures
*
* @return FALSE
*/
public function procedure_list()
{
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Return sql to list sequences
*
* @return FALSE
*/
public function sequence_list()
{
return FALSE;
}
}
// End of odbc_sql.php

View File

@ -1,66 +0,0 @@
<?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

View File

@ -1,216 +0,0 @@
<?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);
$good_tables = array();
foreach($tables as $t)
{
$good_tables[] = $t['tablename'];
}
return $good_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

View File

@ -0,0 +1,95 @@
<?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;
}
// --------------------------------------------------------------------------
/**
* Connect to a different database
*
* @param string $name
*/
public function switch_db($name)
{
// @todo Implement
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Empty a table
*
* @param string $table
*/
public function truncate($table)
{
$sql = 'TRUNCATE "' . $table . '"';
$this->query($sql);
}
// --------------------------------------------------------------------------
/**
* Return the number of rows returned for a SELECT query
*
* @return int
*/
public function num_rows()
{
return (isset($this->statement)) ? $this->statement->rowCount : FALSE;
}
// --------------------------------------------------------------------------
/**
* Get a list of schemas for the current connection
*
* @return array
*/
public function get_schemas()
{
$sql = <<<SQL
SELECT DISTINCT "schemaname" FROM "pg_tables"
WHERE "schemaname" NOT LIKE 'pg\_%'
AND "schemaname" != 'information_schema'
SQL;
return $this->driver_query($sql);
}
}
//End of pgsql_driver.php

282
drivers/pgsql/pgsql_sql.php Normal file
View File

@ -0,0 +1,282 @@
<?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 {
/**
* Database-specific method to create a new table
*
* @param string $name
* @param array $columns
* @param array $constraints
* @param array $indexes
* @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 \"{$name}\" (";
$sql .= implode(", ", $columns);
$sql .= ")";
return $sql;
}
// --------------------------------------------------------------------------
/**
* Database-specific SQL for dropping a 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)
{
$sql .= " LIMIT {$limit}";
if(is_numeric($offset))
{
$sql .= " OFFSET {$offset}";
}
return $sql;
}
// --------------------------------------------------------------------------
/**
* Random ordering keyword
*
* @return string
*/
public function random()
{
return ' RANDOM()';
}
// --------------------------------------------------------------------------
/**
* 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 '';
}
// --------------------------------------------------------------------------
/**
* Returns sql to list other databases
*
* @return string
*/
public function db_list()
{
return <<<SQL
SELECT "datname" FROM "pg_database"
WHERE "datname" NOT IN ('template0','template1')
ORDER BY "datname" ASC
SQL;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list tables
*
* @return string
*/
public function table_list()
{
return <<<SQL
SELECT "tablename" FROM "pg_tables"
WHERE "tablename" NOT LIKE 'pg_%'
AND "tablename" NOT LIKE 'sql_%'
ORDER BY "tablename" ASC
SQL;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list system tables
*
* @return string
*/
public function system_table_list()
{
return <<<SQL
SELECT "tablename" FROM "pg_tables"
WHERE "tablename" LIKE 'pg\_%'
OR "tablename" LIKE 'sql\%'
SQL;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list views
*
* @return string
*/
public function view_list()
{
return <<<SQL
SELECT "viewname" FROM "pg_views"
WHERE "schemaname" NOT IN
('pg_catalog', 'information_schema')
AND "viewname" !~ '^pg_'
ORDER BY "viewname" ASC
SQL;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list triggers
*
* @return string
*/
public function trigger_list()
{
return <<<SQL
SELECT *
FROM "information_schema"."triggers"
WHERE "trigger_schema" NOT IN
('pg_catalog', 'information_schema')
SQL;
}
// --------------------------------------------------------------------------
/**
* Return sql to list functions
*
* @return FALSE
*/
public function function_list()
{
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Return sql to list stored procedures
*
* @return string
*/
public function procedure_list()
{
return <<<SQL
SELECT "routine_name"
FROM "information_schema"."routines"
WHERE "specific_schema" NOT IN
('pg_catalog', 'information_schema')
AND "type_udt_name" != 'trigger';
SQL;
}
// --------------------------------------------------------------------------
/**
* Return sql to list sequences
*
* @return string
*/
public function sequence_list()
{
return <<<SQL
SELECT "c"."relname"
FROM "pg_class" "c"
WHERE "c"."relkind" = 'S'
ORDER BY "relname" ASC
SQL;
}
}
//End of pgsql_manip.php

View File

@ -1,110 +0,0 @@
<?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())
{
$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 \"{$name}\" (";
$sql .= implode(", ", $columns);
$sql .= ")";
return $sql;
}
// --------------------------------------------------------------------------
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

View File

@ -37,6 +37,16 @@ class SQLite extends DB_PDO {
// --------------------------------------------------------------------------
/**
* Doesn't apply to sqlite
*/
public function switch_db($name)
{
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Empty a table
*
@ -64,32 +74,14 @@ class SQLite extends DB_PDO {
{
$tables = array();
$sql = <<<SQL
SELECT "name", "sql"
SELECT "name"
FROM "sqlite_master"
WHERE "type"='table'
ORDER BY "name" DESC
SQL;
$res = $this->query($sql);
$result = $res->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $r)
{
$tables[$r['name']] = $r['sql'];
}
return $tables;
}
// --------------------------------------------------------------------------
/**
* Not applicable to firebird
*
* @return FALSE
*/
public function get_dbs()
{
return FALSE;
return db_filter($res->fetchAll(PDO::FETCH_ASSOC), 'name');
}
// --------------------------------------------------------------------------
@ -149,96 +141,5 @@ SQL;
{
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
//End of sqlite_driver.php

View File

@ -0,0 +1,317 @@
<?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()';
}
// --------------------------------------------------------------------------
/**
* 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;
}
// --------------------------------------------------------------------------
/**
* 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;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list other databases
*
* @return FALSE
*/
public function db_list()
{
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list tables
*
* @return string
*/
public function table_list()
{
return <<<SQL
SELECT "name"
FROM "sqlite_master"
WHERE "type"='table'
ORDER BY "name" DESC
SQL;
}
// --------------------------------------------------------------------------
/**
* Overridden in SQLite class
*
* @return string
*/
public function system_table_list()
{
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list views
*
* @return string
*/
public function view_list()
{
return <<<SQL
SELECT "name" FROM "sqlite_master" WHERE "type" = 'view'
SQL;
}
// --------------------------------------------------------------------------
/**
* Returns sql to list triggers
*
* @return FALSE
*/
public function trigger_list()
{
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Return sql to list functions
*
* @return FALSE
*/
public function function_list()
{
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Return sql to list stored procedures
*
* @return FALSE
*/
public function procedure_list()
{
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Return sql to list sequences
*
* @return FALSE
*/
public function sequence_list()
{
return FALSE;
}
}
//End of sqlite_sql.php

View File

@ -1,122 +0,0 @@
<?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

View File

@ -80,7 +80,12 @@ class Query_Builder {
switch($dbtype)
{
default:
$dsn = "host={$params->host};dbname={$params->database}";
$dsn = "dbname={$params->database}";
if ( ! empty($params->host))
{
$dsn .= ";host={$params->host}";
}
if ( ! empty($params->port))
{
@ -111,25 +116,6 @@ class Query_Builder {
$this->sql =& $this->db->sql;
}
// --------------------------------------------------------------------------
/**
* Return methods from the driver object
*
* @param string $name
* @param array $params
* @return mixed
*/
public function __call($name, $params)
{
if (method_exists($this->db, $name))
{
return call_user_func_array(array($this->db, $name), $params);
}
return NULL;
}
// --------------------------------------------------------------------------
// ! Select Queries
// --------------------------------------------------------------------------
@ -958,6 +944,25 @@ class Query_Builder {
// --------------------------------------------------------------------------
/**
* Calls a function further down the inheritence chain
*
* @param string $name
* @param array $params
* @return mixed
*/
public function __call($name, $params)
{
if (method_exists($this->db, $name))
{
return call_user_func_array(array($this->db, $name), $params);
}
return NULL;
}
// --------------------------------------------------------------------------
/**
* Clear out the class variables, so the next query can be run
*/
@ -1079,8 +1084,6 @@ class Query_Builder {
break;
}
// echo $sql.'<br />';
return $sql;
}
}

View File

@ -167,4 +167,25 @@ SQL;
$table_exists = in_array('create_test', $this->tables);
$this->assertFalse($table_exists);
}*/
function TestGetSequences()
{
$this->assertTrue(is_array($this->db->get_sequences()));
}
function TestGetProcedures()
{
$this->assertTrue(is_array($this->db->get_procedures()));
}
function TestGetFunctions()
{
$this->assertTrue(is_array($this->db->get_functions()));
}
function TestGetTriggers()
{
$this->assertTrue(is_array($this->db->get_triggers()));
}
}

View File

@ -34,7 +34,7 @@ class MySQLQBTest extends QBTest {
$params = array(
'host' => '127.0.0.1',
'port' => '3306',
'database' => 'test',
'conn_db' => 'test',
'user' => 'root',
'pass' => NULL,
'type' => 'mysql'

View File

@ -84,5 +84,88 @@ class MySQLTest extends DBTest {
$this->assertTrue(in_array('create_test', $dbs));
}
function TestTruncate()
{
$this->db->truncate('create_test');
$this->db->truncate('create_join');
$ct_query = $this->db->query('SELECT * FROM create_test');
$cj_query = $this->db->query('SELECT * FROM create_join');
}
function TestPreparedStatements()
{
if (empty($this->db)) return;
$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()
{
if (empty($this->db)) return;
$sql = <<<SQL
INSERT INTO `create_test` (`id`, `key`, `val`)
VALUES (?,?,?)
SQL;
$this->db->prepare_execute($sql, array(
2, "works", 'also?'
));
}
function TestCommitTransaction()
{
if (empty($this->db)) return;
$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()
{
if (empty($this->db)) return;
$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 TestGetSchemas()
{
$this->assertFalse($this->db->get_schemas());
}
function TestGetsProcedures()
{
$this->assertTrue(is_array($this->db->get_procedures()));
}
function TestGetTriggers()
{
$this->assertTrue(is_array($this->db->get_triggers()));
}
function TestGetSequences()
{
$this->assertFalse($this->db->get_sequences());
}
}

View File

@ -12,7 +12,7 @@
// --------------------------------------------------------------------------
class ODBCQBTest extends QBTest {
class ODBCQBTest extends UnitTestCase {
function TestExists()
{

View File

@ -1,12 +1,12 @@
<?php
/**
* Query
* OpenSQLManager
*
* Free Query Builder / Database Abstraction Layer
* Free Database manager for Open Source Databases
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @link https://github.com/aviat4ion/OpenSQLManager
* @license http://philsturgeon.co.uk/code/dbad-license
*/
@ -35,7 +35,7 @@ class PgSQLQBTest extends QBTest {
$params = array(
'host' => '127.0.0.1',
'port' => '5432',
'database' => 'test',
'conn_db' => 'test',
'user' => 'postgres',
'pass' => '',
'type' => 'pgsql'

View File

@ -1,12 +1,12 @@
<?php
/**
* Query
* OpenSQLManager
*
* Free Query Builder / Database Abstraction Layer
* Free Database manager for Open Source Databases
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @link https://github.com/aviat4ion/OpenSQLManager
* @license http://philsturgeon.co.uk/code/dbad-license
*/
@ -101,4 +101,87 @@ class PgTest extends DBTest {
$this->assertTrue(in_array('create_test', $dbs));
}
function TestTruncate()
{
$this->db->truncate('create_test');
$this->db->truncate('create_join');
$ct_query = $this->db->query('SELECT * FROM create_test');
$cj_query = $this->db->query('SELECT * FROM create_join');
}
function TestPreparedStatements()
{
if (empty($this->db)) return;
$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()
{
if (empty($this->db)) return;
$sql = <<<SQL
INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?)
SQL;
$this->db->prepare_execute($sql, array(
2, "works", 'also?'
));
}
function TestCommitTransaction()
{
if (empty($this->db)) return;
$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()
{
if (empty($this->db)) return;
$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 TestGetSchemas()
{
$this->assertTrue(is_array($this->db->get_schemas()));
}
function TestGetSequences()
{
$this->assertTrue(is_array($this->db->get_sequences()));
}
function TestGetsProcedures()
{
$this->assertTrue(is_array($this->db->get_procedures()));
}
function TestGetTriggers()
{
$this->assertTrue(is_array($this->db->get_triggers()));
}
}

View File

@ -1,12 +1,12 @@
<?php
/**
* Query
* OpenSQLManager
*
* Free Query Builder / Database Abstraction Layer
* Free Database manager for Open Source Databases
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @link https://github.com/aviat4ion/OpenSQLManager
* @license http://philsturgeon.co.uk/code/dbad-license
*/

View File

@ -1,12 +1,12 @@
<?php
/**
* Query
* OpenSQLManager
*
* Free Query Builder / Database Abstraction Layer
* Free Database manager for Open Source Databases
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @link https://github.com/aviat4ion/OpenSQLManager
* @license http://philsturgeon.co.uk/code/dbad-license
*/
@ -17,7 +17,12 @@
*
* @extends UnitTestCase
*/
class SQLiteTest extends DBTest {
class SQLiteTest extends UnitTestCase {
function __construct()
{
parent::__construct();
}
function setUp()
{
@ -35,6 +40,24 @@ class SQLiteTest extends DBTest {
$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()
{
@ -66,15 +89,61 @@ class SQLiteTest extends DBTest {
//Check
$dbs = $this->db->get_tables();
$this->assertEqual($dbs['create_test'], 'CREATE TABLE "create_test" (id INTEGER PRIMARY KEY, key TEXT , val TEXT )');
$this->assertTrue(in_array('create_test', $dbs));
}
/*function TestTruncate()
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()
@ -92,4 +161,13 @@ class SQLiteTest extends DBTest {
$this->assertFalse(in_array('create_test', $dbs));
}*/
function TestGetDBs()
{
$this->assertFalse($this->db->get_dbs());
}
function TestGetSchemas()
{
$this->assertFalse($this->db->get_schemas());
}
}

View File

@ -26,17 +26,8 @@ require_once('simpletest/autorun.php');
// Require base testing classes
require_once(TEST_DIR.'/parent.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 classes
require_once(BASE_DIR.'autoload.php');
// Include db tests
// Load db classes based on capability
@ -52,12 +43,10 @@ foreach(pdo_drivers() as $d)
continue;
}
$src_file = "{$src_path}{$d}.php";
$src_dir = "{$src_path}{$d}";
if(is_file($src_file))
if(is_dir($src_dir))
{
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");
}
@ -66,8 +55,6 @@ foreach(pdo_drivers() as $d)
// Load Firebird if there is support
if(function_exists('fbird_connect'))
{
require_once("{$src_path}firebird.php");
require_once("{$src_path}firebird_sql.php");
require_once("{$test_path}firebird.php");
require_once("{$test_path}firebird-qb.php");
}

View File

@ -48,60 +48,6 @@ abstract class DBTest extends UnitTestCase {
$res = $this->db->beginTransaction();
$this->assertTrue($res);
}
function TestPreparedStatements()
{
if (empty($this->db)) return;
$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()
{
if (empty($this->db)) return;
$sql = <<<SQL
INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?)
SQL;
$this->db->prepare_execute($sql, array(
2, "works", 'also?'
));
}
function TestCommitTransaction()
{
if (empty($this->db)) return;
$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()
{
if (empty($this->db)) return;
$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);
}
}
// --------------------------------------------------------------------------
@ -236,6 +182,7 @@ abstract class QBTest extends UnitTestCase {
->where('id >', 0)
->where('id <', 9000)
->group_by('k')
->group_by('id')
->group_by('val')
->order_by('id', 'DESC')
->order_by('k', 'ASC')
@ -315,5 +262,12 @@ abstract class QBTest extends UnitTestCase {
$this->assertIsA($query, 'PDOStatement');
}
function TestGetViews()
{
if (empty($this->db)) return;
$this->assertTrue(is_array($this->db->get_views()));
}
}
// End of parent.php

Binary file not shown.

BIN
tests/test_dbs/test_sqlite.db Normal file → Executable file

Binary file not shown.