diff --git a/autoload.php b/autoload.php index 5a477b8..5d8f021 100644 --- a/autoload.php +++ b/autoload.php @@ -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 \ No newline at end of file diff --git a/db_pdo.php b/db_pdo.php index a47516e..9839852 100644 --- a/db_pdo.php +++ b/db_pdo.php @@ -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,10 +31,12 @@ 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); } - + // ------------------------------------------------------------------------- - + /** * Simplifies prepared statements for database queries * @@ -43,23 +48,23 @@ abstract class DB_PDO extends PDO { { // 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) { @@ -67,18 +72,18 @@ abstract class DB_PDO extends PDO { { $k++; } - + $res = $query->bindValue($k, $value); - + if( ! $res) { trigger_error("Parameter not successfully bound"); return FALSE; } } - - return $query; - + + return $query; + } // ------------------------------------------------------------------------- @@ -91,7 +96,7 @@ abstract class DB_PDO extends PDO { * @return PDOStatement */ public function prepare_execute($sql, $params) - { + { $this->statement = $this->prepare_query($sql, $params); $this->statement->execute(); @@ -128,21 +133,16 @@ abstract class DB_PDO extends PDO { public function affected_rows($statement='') { if ( ! empty($statement)) - { - $this->statement = $statement; - } - - if (empty($this->statement)) { - return FALSE; + $this->statement = $statement; } // Return number of rows affected return $this->statement->rowCount(); } - + // -------------------------------------------------------------------------- - + /** * Return the last error for the current database connection * @@ -151,7 +151,7 @@ abstract class DB_PDO extends PDO { public function get_last_error() { $info = $this->errorInfo(); - + echo "Error:
{$info[0]}:{$info[1]}\n{$info[2]}
"; } @@ -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,103 +197,163 @@ abstract class DB_PDO extends PDO { // ------------------------------------------------------------------------- /** - * Abstract public functions to override in child classes - */ - - /** - * Return list of tables for the current database - * + * Return schemas for databases that list them + * * @return array */ - abstract public function get_tables(); - + 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 + */ + 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 - * + * * @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 + * Connect to a different database * - * @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 + * @return void */ - 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 \ No newline at end of file diff --git a/db_sql.php b/db_sql.php new file mode 100644 index 0000000..f71f4cd --- /dev/null +++ b/db_sql.php @@ -0,0 +1,132 @@ +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 = <<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 = <<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 \ No newline at end of file diff --git a/drivers/firebird/firebird_driver.php b/drivers/firebird/firebird_driver.php new file mode 100644 index 0000000..e454fff --- /dev/null +++ b/drivers/firebird/firebird_driver.php @@ -0,0 +1,257 @@ +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 \ No newline at end of file diff --git a/drivers/firebird/firebird_result.php b/drivers/firebird/firebird_result.php new file mode 100644 index 0000000..fe6994b --- /dev/null +++ b/drivers/firebird/firebird_result.php @@ -0,0 +1,137 @@ +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 \ No newline at end of file diff --git a/drivers/firebird/firebird_sql.php b/drivers/firebird/firebird_sql.php new file mode 100644 index 0000000..e632f17 --- /dev/null +++ b/drivers/firebird/firebird_sql.php @@ -0,0 +1,334 @@ + ..., + // '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 << ..., - // '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 \ No newline at end of file diff --git a/drivers/mysql.php b/drivers/mysql.php deleted file mode 100644 index a19031f..0000000 --- a/drivers/mysql.php +++ /dev/null @@ -1,166 +0,0 @@ -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 \ No newline at end of file diff --git a/drivers/mysql/mysql_driver.php b/drivers/mysql/mysql_driver.php new file mode 100644 index 0000000..49ce5b4 --- /dev/null +++ b/drivers/mysql/mysql_driver.php @@ -0,0 +1,89 @@ +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 \ No newline at end of file diff --git a/drivers/mysql/mysql_sql.php b/drivers/mysql/mysql_sql.php new file mode 100644 index 0000000..d39e540 --- /dev/null +++ b/drivers/mysql/mysql_sql.php @@ -0,0 +1,255 @@ + ..., + // '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 \ No newline at end of file diff --git a/drivers/mysql_sql.php b/drivers/mysql_sql.php deleted file mode 100644 index caa03e4..0000000 --- a/drivers/mysql_sql.php +++ /dev/null @@ -1,133 +0,0 @@ - ..., - // '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 \ No newline at end of file diff --git a/drivers/odbc.php b/drivers/odbc/odbc_driver.php similarity index 52% rename from drivers/odbc.php rename to drivers/odbc/odbc_driver.php index 7403283..26a92fa 100644 --- a/drivers/odbc.php +++ b/drivers/odbc/odbc_driver.php @@ -28,50 +28,22 @@ class ODBC extends DB_PDO { $class = __CLASS__.'_sql'; $this->sql = new $class; } - + // -------------------------------------------------------------------------- /** - * 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 - * + * * @return void */ public function truncate($table) @@ -79,43 +51,17 @@ class ODBC extends DB_PDO { $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 ''; + // @TODO: Implement } } -// End of odbc.php \ No newline at end of file +// End of odbc_driver.php \ No newline at end of file diff --git a/drivers/odbc/odbc_sql.php b/drivers/odbc/odbc_sql.php new file mode 100644 index 0000000..3713472 --- /dev/null +++ b/drivers/odbc/odbc_sql.php @@ -0,0 +1,188 @@ +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 = <<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 = <<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 = <<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 = <<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 = <<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 \ No newline at end of file diff --git a/drivers/pgsql/pgsql_driver.php b/drivers/pgsql/pgsql_driver.php new file mode 100644 index 0000000..ec1d380 --- /dev/null +++ b/drivers/pgsql/pgsql_driver.php @@ -0,0 +1,95 @@ +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 = <<driver_query($sql); + } +} +//End of pgsql_driver.php \ No newline at end of file diff --git a/drivers/pgsql/pgsql_sql.php b/drivers/pgsql/pgsql_sql.php new file mode 100644 index 0000000..4553c9c --- /dev/null +++ b/drivers/pgsql/pgsql_sql.php @@ -0,0 +1,282 @@ + ..., + // '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 << ..., - // '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 \ No newline at end of file diff --git a/drivers/sqlite.php b/drivers/sqlite/sqlite_driver.php similarity index 51% rename from drivers/sqlite.php rename to drivers/sqlite/sqlite_driver.php index b00652c..215f95b 100644 --- a/drivers/sqlite.php +++ b/drivers/sqlite/sqlite_driver.php @@ -13,7 +13,7 @@ // -------------------------------------------------------------------------- /** - * SQLite specific class + * SQLite specific class * * @extends DB_PDO */ @@ -23,8 +23,8 @@ class SQLite extends DB_PDO { /** * Open SQLite Database - * - * @param string $dsn + * + * @param string $dsn */ public function __construct($dsn, $user=NULL, $pass=NULL) { @@ -34,7 +34,17 @@ class SQLite extends DB_PDO { $class = __CLASS__."_sql"; $this->sql = new $class; } - + + // -------------------------------------------------------------------------- + + /** + * Doesn't apply to sqlite + */ + public function switch_db($name) + { + return FALSE; + } + // -------------------------------------------------------------------------- /** @@ -49,54 +59,36 @@ class SQLite extends DB_PDO { $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 = <<query($sql); - $result = $res->fetchAll(PDO::FETCH_ASSOC); - - foreach($result as $r) - { - $tables[$r['name']] = $r['sql']; - } - - return $tables; + return db_filter($res->fetchAll(PDO::FETCH_ASSOC), 'name'); } - - // -------------------------------------------------------------------------- - /** - * 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() @@ -105,140 +97,49 @@ SQL; // that is of any importance. return array('sqlite_master'); } - + // -------------------------------------------------------------------------- /** * Load a database for the current connection - * + * * @param string $db - * @param string $name + * @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 \ No newline at end of file +//End of sqlite_driver.php \ No newline at end of file diff --git a/drivers/sqlite/sqlite_sql.php b/drivers/sqlite/sqlite_sql.php new file mode 100644 index 0000000..022ea45 --- /dev/null +++ b/drivers/sqlite/sqlite_sql.php @@ -0,0 +1,317 @@ + 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 << 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 \ No newline at end of file diff --git a/query_builder.php b/query_builder.php index f9c1e36..1e19d2c 100644 --- a/query_builder.php +++ b/query_builder.php @@ -7,7 +7,7 @@ * @author Timothy J. Warren * @copyright Copyright (c) 2012 * @link https://github.com/aviat4ion/Query - * @license http://philsturgeon.co.uk/code/dbad-license + * @license http://philsturgeon.co.uk/code/dbad-license */ // -------------------------------------------------------------------------- @@ -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)) { @@ -110,25 +115,6 @@ class Query_Builder { // Make things just slightly shorter $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.'
'; - return $sql; } } diff --git a/tests/databases/firebird.php b/tests/databases/firebird.php index b836662..29c7abc 100644 --- a/tests/databases/firebird.php +++ b/tests/databases/firebird.php @@ -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())); + } + } \ No newline at end of file diff --git a/tests/databases/mysql-qb.php b/tests/databases/mysql-qb.php index 9cf74be..a2f12a4 100644 --- a/tests/databases/mysql-qb.php +++ b/tests/databases/mysql-qb.php @@ -17,34 +17,34 @@ class MySQLQBTest extends QBTest { function __construct() { parent::__construct(); - + // Attempt to connect, if there is a test config file if (is_file("../test_config.json")) { $params = json_decode(file_get_contents("../test_config.json")); $params = $params->mysql; $params->type = "mysql"; - + $this->db = new Query_Builder($params); - - // echo '
MySQL Queries
'; + + // echo '
MySQL Queries
'; } elseif (($var = getenv('CI'))) { $params = array( 'host' => '127.0.0.1', 'port' => '3306', - 'database' => 'test', + 'conn_db' => 'test', 'user' => 'root', 'pass' => NULL, 'type' => 'mysql' ); - + $this->db = new Query_Builder($params); } } - + function TestExists() { $this->assertTrue(in_array('mysql', pdo_drivers())); diff --git a/tests/databases/mysql.php b/tests/databases/mysql.php index 8443119..83ecb2a 100644 --- a/tests/databases/mysql.php +++ b/tests/databases/mysql.php @@ -14,11 +14,11 @@ /** * MySQLTest class. - * + * * @extends UnitTestCase */ class MySQLTest extends DBTest { - + function setUp() { // Attempt to connect, if there is a test config file @@ -26,7 +26,7 @@ class MySQLTest extends DBTest { { $params = json_decode(file_get_contents("../test_config.json")); $params = $params->mysql; - + $this->db = new MySQL("host={$params->host};port={$params->port};dbname={$params->database}", $params->user, $params->pass); } elseif (($var = getenv('CI'))) @@ -34,44 +34,44 @@ class MySQLTest extends DBTest { $this->db = new MySQL('host=127.0.0.1;port=3306;dbname=test', 'root'); } } - + function TestExists() { $this->assertTrue(in_array('mysql', pdo_drivers())); } - + function TestConnection() { - if (empty($this->db)) return; - + if (empty($this->db)) return; + $this->assertIsA($this->db, 'MySQL'); } function TestCreateTable() { - if (empty($this->db)) return; - + if (empty($this->db)) return; + //Attempt to create the table - $sql = $this->db->sql->create_table('create_test', + $sql = $this->db->sql->create_table('create_test', array( 'id' => 'int(10)', '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', + $sql = $this->db->sql->create_table('create_join', array( 'id' => 'int(10)', 'key' => 'TEXT', 'val' => 'TEXT', - ), + ), array( 'id' => 'PRIMARY KEY' ) @@ -80,9 +80,92 @@ class MySQLTest extends DBTest { //Check $dbs = $this->db->get_tables(); - + $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 = <<db->prepare_query($sql, array(1,"boogers", "Gross")); + + $statement->execute(); + + } + + function TestPrepareExecute() + { + if (empty($this->db)) return; + + $sql = <<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()); } } - + diff --git a/tests/databases/odbc-qb.php b/tests/databases/odbc-qb.php index c82b677..adb33c6 100644 --- a/tests/databases/odbc-qb.php +++ b/tests/databases/odbc-qb.php @@ -12,7 +12,7 @@ // -------------------------------------------------------------------------- -class ODBCQBTest extends QBTest { +class ODBCQBTest extends UnitTestCase { function TestExists() { diff --git a/tests/databases/pgsql-qb.php b/tests/databases/pgsql-qb.php index 134ab5b..d1bfb34 100644 --- a/tests/databases/pgsql-qb.php +++ b/tests/databases/pgsql-qb.php @@ -1,13 +1,13 @@ pgsql; $params->type = "pgsql"; - + $this->db = new Query_Builder($params); - - // echo '
Postgres Queries
'; - + + // echo '
Postgres Queries
'; + } elseif (($var = getenv('CI'))) { $params = array( 'host' => '127.0.0.1', 'port' => '5432', - 'database' => 'test', + 'conn_db' => 'test', 'user' => 'postgres', 'pass' => '', 'type' => 'pgsql' ); - + $this->db = new Query_Builder($params); } } - + function TestExists() { $this->assertTrue(in_array('pgsql', pdo_drivers())); diff --git a/tests/databases/pgsql.php b/tests/databases/pgsql.php index b44d36e..3537426 100644 --- a/tests/databases/pgsql.php +++ b/tests/databases/pgsql.php @@ -1,20 +1,20 @@ pgsql; - + $this->db = new PgSQL("host={$params->host};port={$params->port};dbname={$params->database}", $params->user, $params->pass); } elseif (($var = getenv('CI'))) @@ -39,59 +39,59 @@ class PgTest extends DBTest { $this->db = new PgSQL('host=127.0.0.1;port=5432;dbname=test', 'postgres'); } } - + function TestExists() { $this->assertTrue(in_array('pgsql', pdo_drivers())); } - + function TestConnection() { - if (empty($this->db)) return; - + if (empty($this->db)) return; + $this->assertIsA($this->db, 'PgSQL'); } function TestCreateTable() { - if (empty($this->db)) return; - + if (empty($this->db)) return; + // Drop the table(s) if they exist $sql = 'DROP TABLE IF EXISTS "create_test"'; $this->db->query($sql); $sql = 'DROP TABLE IF EXISTS "create_join"'; $this->db->query($sql); - - + + //Attempt to create the table - $sql = $this->db->sql->create_table('create_test', + $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', + $sql = $this->db->sql->create_table('create_join', array( 'id' => 'integer', 'key' => 'TEXT', 'val' => 'TEXT', - ), + ), array( 'id' => 'PRIMARY KEY' ) ); $this->db->query($sql); - + //echo $sql.'
'; - + //Reset unset($this->db); $this->setUp(); @@ -99,6 +99,89 @@ class PgTest extends DBTest { //Check $dbs = $this->db->get_tables(); $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 = <<db->prepare_query($sql, array(1,"boogers", "Gross")); + + $statement->execute(); + + } + + function TestPrepareExecute() + { + if (empty($this->db)) return; + + $sql = <<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())); } } \ No newline at end of file diff --git a/tests/databases/sqlite-qb.php b/tests/databases/sqlite-qb.php index e7c2b39..f262666 100644 --- a/tests/databases/sqlite-qb.php +++ b/tests/databases/sqlite-qb.php @@ -1,12 +1,12 @@ db = new SQLite($path); } - + function tearDown() { unset($this->db); @@ -34,30 +39,48 @@ 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() { //Attempt to create the table - $sql = $this->db->sql->create_table('create_test', + $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', + $sql = $this->db->sql->create_table('create_join', array( 'id' => 'INTEGER', 'key' => 'TEXT', 'val' => 'TEXT', - ), + ), array( 'id' => 'PRIMARY KEY' ) @@ -66,16 +89,62 @@ 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 = <<db->prepare_query($sql, array(1,"boogers", "Gross")); + + $statement->execute(); + + } + + function TestPrepareExecute() + { + $sql = <<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() { @@ -89,7 +158,16 @@ class SQLiteTest extends DBTest { //Check $dbs = $this->db->get_tables(); - $this->assertFalse(in_array('create_test', $dbs)); + $this->assertFalse(in_array('create_test', $dbs)); }*/ + function TestGetDBs() + { + $this->assertFalse($this->db->get_dbs()); + } + + function TestGetSchemas() + { + $this->assertFalse($this->db->get_schemas()); + } } \ No newline at end of file diff --git a/tests/index.php b/tests/index.php index 674f383..e07bb77 100644 --- a/tests/index.php +++ b/tests/index.php @@ -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"); } \ No newline at end of file diff --git a/tests/parent.php b/tests/parent.php index 9daec28..0205121 100644 --- a/tests/parent.php +++ b/tests/parent.php @@ -9,7 +9,7 @@ * @link https://github.com/aviat4ion/Query * @license http://philsturgeon.co.uk/code/dbad-license */ - + // -------------------------------------------------------------------------- /** @@ -23,7 +23,7 @@ abstract class DBTest extends UnitTestCase { { $this->db = NULL; } - + function TestGetTables() { if (empty($this->db)) return; @@ -31,16 +31,16 @@ abstract class DBTest extends UnitTestCase { $tables = $this->db->get_tables(); $this->assertTrue(is_array($tables)); } - + function TestGetSystemTables() { if (empty($this->db)) return; $tables = $this->db->get_system_tables(); - + $this->assertTrue(is_array($tables)); } - + function TestCreateTransaction() { if (empty($this->db)) return; @@ -48,60 +48,6 @@ abstract class DBTest extends UnitTestCase { $res = $this->db->beginTransaction(); $this->assertTrue($res); } - - function TestPreparedStatements() - { - if (empty($this->db)) return; - - $sql = <<db->prepare_query($sql, array(1,"boogers", "Gross")); - - $statement->execute(); - - } - - function TestPrepareExecute() - { - if (empty($this->db)) return; - - $sql = <<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); - } } // -------------------------------------------------------------------------- @@ -114,34 +60,34 @@ abstract class QBTest extends UnitTestCase { function TestGet() { if (empty($this->db)) return; - + $query = $this->db->get('create_test'); - + $this->assertIsA($query, 'PDOStatement'); } - + function TestGetLimit() { if (empty($this->db)) return; - + $query = $this->db->get('create_test', 2); - + $this->assertIsA($query, 'PDOStatement'); } - + function TestGetLimitSkip() { if (empty($this->db)) return; - + $query = $this->db->get('create_test', 2, 1); - + $this->assertIsA($query, 'PDOStatement'); } function TestSelectWhereGet() { if (empty($this->db)) return; - + $query = $this->db->select('id, key as k, val') ->where('id >', 1) ->where('id <', 900) @@ -149,11 +95,11 @@ abstract class QBTest extends UnitTestCase { $this->assertIsA($query, 'PDOStatement'); } - + function TestSelectWhereGet2() { if (empty($this->db)) return; - + $query = $this->db->select('id, key as k, val') ->where('id !=', 1) ->get('create_test', 2, 1); @@ -164,42 +110,42 @@ abstract class QBTest extends UnitTestCase { function TestSelectGet() { if (empty($this->db)) return; - + $query = $this->db->select('id, key as k, val') ->get('create_test', 2, 1); $this->assertIsA($query, 'PDOStatement'); } - + function TestSelectFromGet() { if (empty($this->db)) return; - + $query = $this->db->select('id, key as k, val') ->from('create_test ct') ->where('id >', 1) ->get(); - + $this->assertIsA($query, 'PDOStatement'); } - + function TestSelectFromLimitGet() { if (empty($this->db)) return; - + $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() { if (empty($this->db)) return; - + $query = $this->db->select('id, key as k, val') ->from('create_test') ->where('id >', 0) @@ -208,14 +154,14 @@ abstract class QBTest extends UnitTestCase { ->order_by('k', 'ASC') ->limit(5,2) ->get(); - + $this->assertIsA($query, 'PDOStatement'); } - + function TestOrderByRandom() { if (empty($this->db)) return; - + $query = $this->db->select('id, key as k, val') ->from('create_test') ->where('id >', 0) @@ -223,97 +169,105 @@ abstract class QBTest extends UnitTestCase { ->order_by('id', 'rand') ->limit(5,2) ->get(); - + $this->assertIsA($query, 'PDOStatement'); } - + function TestGroupBy() { if (empty($this->db)) return; - + $query = $this->db->select('id, key as k, val') ->from('create_test') ->where('id >', 0) ->where('id <', 9000) ->group_by('k') + ->group_by('id') ->group_by('val') ->order_by('id', 'DESC') ->order_by('k', 'ASC') ->limit(5,2) ->get(); - + $this->assertIsA($query, 'PDOStatement'); } - + function TestOrWhere() { if (empty($this->db)) return; - + $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() { if (empty($this->db)) return; - + $query = $this->db->from('create_test') ->like('key', 'og') ->get(); - + $this->assertIsA($query, 'PDOStatement'); } - + function TestJoin() { if (empty($this->db)) return; - + $query = $this->db->from('create_test') ->join('create_join cj', 'cj.id = create_test.id') ->get(); - + $this->assertIsA($query, 'PDOStatement'); } - + function TestInsert() { if (empty($this->db)) return; - + $query = $this->db->set('id', 4) ->set('key', 4) ->set('val', 5) ->insert('create_test'); - + $this->assertIsA($query, 'PDOStatement'); } - + function TestUpdate() { if (empty($this->db)) return; - + $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() { if (empty($this->db)) return; - + $query = $this->db->where('id', 4)->delete('create_test'); - + $this->assertIsA($query, 'PDOStatement'); } - + + function TestGetViews() + { + if (empty($this->db)) return; + + $this->assertTrue(is_array($this->db->get_views())); + } } +// End of parent.php \ No newline at end of file diff --git a/tests/test_dbs/FB_TEST_DB.FDB b/tests/test_dbs/FB_TEST_DB.FDB index 5193b05..5f37771 100755 Binary files a/tests/test_dbs/FB_TEST_DB.FDB and b/tests/test_dbs/FB_TEST_DB.FDB differ diff --git a/tests/test_dbs/test_sqlite.db b/tests/test_dbs/test_sqlite.db old mode 100644 new mode 100755 index 89d1be5..1a1af45 Binary files a/tests/test_dbs/test_sqlite.db and b/tests/test_dbs/test_sqlite.db differ