From 6d9e20dc7fa32cd6898713106d9655dd5bf8b4ee Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Thu, 12 Apr 2012 14:06:00 -0400 Subject: [PATCH] Move db methods to sub-module --- .gitmodules | 3 + index.php | 35 +- sys/common/functions.php | 19 - sys/db | 1 + sys/db/db_pdo.php | 359 ------ sys/db/db_reg.php | 83 -- sys/db/db_sql.php | 132 --- sys/db/drivers/firebird/firebird_driver.php | 246 ----- sys/db/drivers/firebird/firebird_result.php | 151 --- sys/db/drivers/firebird/firebird_sql.php | 392 ------- sys/db/drivers/mysql/mysql_driver.php | 93 -- sys/db/drivers/mysql/mysql_sql.php | 255 ----- sys/db/drivers/odbc/odbc_driver.php | 67 -- sys/db/drivers/odbc/odbc_sql.php | 188 ---- sys/db/drivers/pgsql/pgsql_driver.php | 95 -- sys/db/drivers/pgsql/pgsql_sql.php | 306 ----- sys/db/drivers/sqlite/sqlite_driver.php | 145 --- sys/db/drivers/sqlite/sqlite_sql.php | 317 ------ sys/db/query_builder.php | 1103 ------------------- tests/db_files/FB_TEST_DB.FDB | Bin 933888 -> 933888 bytes tests/index.php | 10 +- 21 files changed, 15 insertions(+), 3985 deletions(-) create mode 100644 .gitmodules create mode 160000 sys/db delete mode 100644 sys/db/db_pdo.php delete mode 100644 sys/db/db_reg.php delete mode 100644 sys/db/db_sql.php delete mode 100644 sys/db/drivers/firebird/firebird_driver.php delete mode 100644 sys/db/drivers/firebird/firebird_result.php delete mode 100644 sys/db/drivers/firebird/firebird_sql.php delete mode 100644 sys/db/drivers/mysql/mysql_driver.php delete mode 100644 sys/db/drivers/mysql/mysql_sql.php delete mode 100644 sys/db/drivers/odbc/odbc_driver.php delete mode 100644 sys/db/drivers/odbc/odbc_sql.php delete mode 100644 sys/db/drivers/pgsql/pgsql_driver.php delete mode 100644 sys/db/drivers/pgsql/pgsql_sql.php delete mode 100644 sys/db/drivers/sqlite/sqlite_driver.php delete mode 100644 sys/db/drivers/sqlite/sqlite_sql.php delete mode 100644 sys/db/query_builder.php diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..3bfcdaf --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "sys/db"] + path = sys/db + url = git@github.com:aviat4ion/Query.git diff --git a/index.php b/index.php index 2fb5692..49c862a 100644 --- a/index.php +++ b/index.php @@ -101,11 +101,16 @@ set_error_handler("exception_error_handler", -1); * @param string $path * @return void */ -function do_include($path) +if ( ! function_exists('do_include')) { - require_once($path); + function do_include($path) + { + require_once($path); + } } +// -------------------------------------------------------------------------- + // Load everything so that we don't have to do requires later { array_map('do_include', glob(BASE_DIR . "/common/*.php")); @@ -116,30 +121,8 @@ function do_include($path) // -------------------------------------------------------------------------- -// Load db classes based on capability -$path = BASE_DIR . "/db/drivers/"; - -foreach(pdo_drivers() as $d) -{ - //Favor ibase/fbird over PDO firebird - if ($d === 'firebird') - { - continue; - } - - $dir = "{$path}{$d}"; - - if(is_dir($dir)) - { - array_map('do_include', glob($dir.'/*.php')); - } -} - -// Load Firebird if there is support -if (function_exists('fbird_connect')) -{ - array_map('do_include', glob($path.'firebird/*.php')); -} +// Auto-load db drivers +require_once(BASE_DIR . "/db/autoload.php"); // -------------------------------------------------------------------------- diff --git a/sys/common/functions.php b/sys/common/functions.php index 6ab1fef..96f0319 100644 --- a/sys/common/functions.php +++ b/sys/common/functions.php @@ -143,23 +143,4 @@ function about() $dlg->destroy(); } -/** - * 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 functions.php \ No newline at end of file diff --git a/sys/db b/sys/db new file mode 160000 index 0000000..74e8f99 --- /dev/null +++ b/sys/db @@ -0,0 +1 @@ +Subproject commit 74e8f99fd89d394124eb2639dfca9889c71bc39b diff --git a/sys/db/db_pdo.php b/sys/db/db_pdo.php deleted file mode 100644 index 4ffdc98..0000000 --- a/sys/db/db_pdo.php +++ /dev/null @@ -1,359 +0,0 @@ -setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - } - - // ------------------------------------------------------------------------- - - /** - * Simplifies prepared statements for database queries - * - * @param string $sql - * @param array $data - * @return mixed PDOStatement / FALSE - */ - public function prepare_query($sql, $data) - { - // Prepare the sql - $query = $this->prepare($sql); - - if( ! (is_object($query) || is_resource($query))) - { - $this->get_last_error(); - return FALSE; - } - - // Set the statement in the class variable for easy later access - $this->statement =& $query; - - - if( ! (is_array($data) || is_object($data))) - { - trigger_error("Invalid data argument"); - return FALSE; - } - - // Bind the parameters - foreach($data as $k => $value) - { - if(is_numeric($k)) - { - $k++; - } - - $res = $query->bindValue($k, $value); - - if( ! $res) - { - trigger_error("Parameter not successfully bound"); - return FALSE; - } - } - - return $query; - - } - - // ------------------------------------------------------------------------- - - /** - * Create and execute a prepared statement with the provided parameters - * - * @param string $sql - * @param array $params - * @return PDOStatement - */ - public function prepare_execute($sql, $params) - { - $this->statement = $this->prepare_query($sql, $params); - $this->statement->execute(); - - return $this->statement; - } - - // ------------------------------------------------------------------------- - - /** - * Retreives the data from a select query - * - * @param PDOStatement $statement - * @return array - */ - public function get_query_data($statement) - { - $this->statement =& $statement; - - // Execute the query - $this->statement->execute(); - - // Return the data array fetched - return $this->statement->fetchAll(PDO::FETCH_ASSOC); - } - - // ------------------------------------------------------------------------- - - /** - * Returns number of rows affected by an INSERT, UPDATE, DELETE type query - * - * @param PDOStatement $statement - * @return int - */ - public function affected_rows($statement='') - { - if ( ! empty($statement)) - { - $this->statement = $statement; - } - - // Return number of rows affected - return $this->statement->rowCount(); - } - - // -------------------------------------------------------------------------- - - /** - * Return the last error for the current database connection - * - * @return string - */ - public function get_last_error() - { - $info = $this->errorInfo(); - - echo "Error:
{$info[0]}:{$info[1]}\n{$info[2]}
"; - } - - // -------------------------------------------------------------------------- - - /** - * Surrounds the string with the databases identifier escape characters - * - * @param mixed $ident - * @return string - */ - public function quote_ident($ident) - { - if (is_array($ident)) - { - return array_map(array($this, 'quote_ident'), $ident); - } - - // Split each identifier by the period - $hiers = explode('.', $ident); - - return $this->escape_char . - implode("{$this->escape_char}.{$this->escape_char}", $hiers) . - $this->escape_char; - } - - // ------------------------------------------------------------------------- - - /** - * Deletes all the rows from a table. Does the same as the truncate - * method if the database does not support 'TRUNCATE'; - * - * @param string $table - * @return mixed - */ - public function empty_table($table) - { - $sql = 'DELETE FROM '.$this->quote_ident($table); - - return $this->query($sql); - } - - // ------------------------------------------------------------------------- - - /** - * 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 - */ - public function get_tables() - { - return $this->driver_query($this->sql->table_list()); - } - - // ------------------------------------------------------------------------- - - /** - * Return list of dbs for the current connection, if possible - * - * @return array - */ - 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(); - - /** - * Connect to a different database - * - * @param string $name - * @return void - */ - abstract public function switch_db($name); -} -// End of db_pdo.php \ No newline at end of file diff --git a/sys/db/db_reg.php b/sys/db/db_reg.php deleted file mode 100644 index 8ab347d..0000000 --- a/sys/db/db_reg.php +++ /dev/null @@ -1,83 +0,0 @@ -get_db($key); - - // Set the current key in the registry - self::$instance[$key] = new Query_Builder($db_params); - } - - // -------------------------------------------------------------------------- - - /** - * Return exiting connections - * - * @return array - */ - public static function get_connections() - { - return array_keys(self::$instance); - } - - // -------------------------------------------------------------------------- - - /** - * Remove a database connection - * - * @param string $key - * @return void - */ - public static function remove_db($key) - { - unset(self::$instance[$key]); - } -} -// End of dbreg.php \ No newline at end of file diff --git a/sys/db/db_sql.php b/sys/db/db_sql.php deleted file mode 100644 index 0801e17..0000000 --- a/sys/db/db_sql.php +++ /dev/null @@ -1,132 +0,0 @@ -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; - } - - // -------------------------------------------------------------------------- - - /** - * 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/sys/db/drivers/firebird/firebird_result.php b/sys/db/drivers/firebird/firebird_result.php deleted file mode 100644 index 7d9cc6e..0000000 --- a/sys/db/drivers/firebird/firebird_result.php +++ /dev/null @@ -1,151 +0,0 @@ -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, F_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; - } - - // -------------------------------------------------------------------------- - - /** - * Emulate PDOStatement::fetchColumn - * - * @param int $colum_num - * @return mixed - */ - public function fetchColumn($column_num=0) - { - $row = $this->fetch(PDO::FETCH_NUM); - return $row[$column_num]; - } - - // -------------------------------------------------------------------------- - - /** - * 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/sys/db/drivers/firebird/firebird_sql.php b/sys/db/drivers/firebird/firebird_sql.php deleted file mode 100644 index 4b4acab..0000000 --- a/sys/db/drivers/firebird/firebird_sql.php +++ /dev/null @@ -1,392 +0,0 @@ - ..., - // '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 << "SET NAMES UTF-8 COLLATE 'UTF-8'", - )); - - 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 \ No newline at end of file diff --git a/sys/db/drivers/mysql/mysql_sql.php b/sys/db/drivers/mysql/mysql_sql.php deleted file mode 100644 index 0465845..0000000 --- a/sys/db/drivers/mysql/mysql_sql.php +++ /dev/null @@ -1,255 +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()'; - } - - // -------------------------------------------------------------------------- - - /** - * 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/sys/db/drivers/odbc/odbc_driver.php b/sys/db/drivers/odbc/odbc_driver.php deleted file mode 100644 index b00b1e8..0000000 --- a/sys/db/drivers/odbc/odbc_driver.php +++ /dev/null @@ -1,67 +0,0 @@ -sql = new $class; - } - - // -------------------------------------------------------------------------- - - /** - * Doesn't apply to ODBC - */ - public function switch_db($name) - { - return FALSE; - } - - // -------------------------------------------------------------------------- - - /** - * Empty the current database - * - * @return void - */ - public function truncate($table) - { - $sql = "DELETE FROM {$table}"; - $this->query($sql); - } - - // -------------------------------------------------------------------------- - - /** - * Return the number of rows returned for a SELECT query - * - * @return int - */ - public function num_rows() - { - // @TODO: Implement - } -} -// End of odbc_driver.php \ No newline at end of file diff --git a/sys/db/drivers/odbc/odbc_sql.php b/sys/db/drivers/odbc/odbc_sql.php deleted file mode 100644 index 9df54dd..0000000 --- a/sys/db/drivers/odbc/odbc_sql.php +++ /dev/null @@ -1,188 +0,0 @@ -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/sys/db/drivers/pgsql/pgsql_sql.php b/sys/db/drivers/pgsql/pgsql_sql.php deleted file mode 100644 index 65cd5e1..0000000 --- a/sys/db/drivers/pgsql/pgsql_sql.php +++ /dev/null @@ -1,306 +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; - } - } - - // 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 = new $class; - } - - // -------------------------------------------------------------------------- - - /** - * Doesn't apply to sqlite - */ - public function switch_db($name) - { - return FALSE; - } - - // -------------------------------------------------------------------------- - - /** - * Empty a table - * - * @param string $table - */ - public function truncate($table) - { - // SQLite has a TRUNCATE optimization, - // but no support for the actual command. - $sql = 'DELETE FROM "'.$table.'"'; - - $this->statement = $this->query($sql); - - return $this->statement; - } - - // -------------------------------------------------------------------------- - - /** - * List tables for the current database - * - * @return mixed - */ - public function get_tables() - { - $tables = array(); - $sql = <<query($sql); - return db_filter($res->fetchAll(PDO::FETCH_ASSOC), 'name'); - } - - // -------------------------------------------------------------------------- - - /** - * List system tables for the current database - * - * @return array - */ - public function get_system_tables() - { - //SQLite only has the sqlite_master table - // that is of any importance. - return array('sqlite_master'); - } - - // -------------------------------------------------------------------------- - - /** - * Load a database for the current connection - * - * @param string $db - * @param string $name - */ - public function load_database($db, $name) - { - $sql = 'ATTACH DATABASE "'.$db.'" AS "'.$name.'"'; - $this->query($sql); - } - - // -------------------------------------------------------------------------- - - /** - * Unload a database from the current connection - * - * @param string $name - */ - public function unload_database($name) - { - $sql = 'DETACH DATABASE ":name"'; - - $this->prepare_query($sql, array( - ':name' => $name, - )); - - $this->statement->execute(); - } - - // -------------------------------------------------------------------------- - - /** - * Return the number of rows returned for a SELECT query - * - * @return int - */ - public function num_rows() - { - return (isset($this->statement)) ? $this->statement->rowCount : FALSE; - } -} -//End of sqlite_driver.php \ No newline at end of file diff --git a/sys/db/drivers/sqlite/sqlite_sql.php b/sys/db/drivers/sqlite/sqlite_sql.php deleted file mode 100644 index 2d853c8..0000000 --- a/sys/db/drivers/sqlite/sqlite_sql.php +++ /dev/null @@ -1,317 +0,0 @@ - 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 <<db->sql - private $sql; - - // Query component order mapping - // for complex select queries - // - // Format: - // - // array( - // 'type' => 'where', - // 'conjunction' => ' AND ', - // 'string' => 'k=?' - // ) - private $query_map; - - // Convenience property for connection management - public $conn_name = ""; - - /** - * Constructor - * - * @param object $conn_name - the name of the connection/parameters - */ - public function __construct($params) - { - // Convert array to object - if (is_array($params)) - { - $p = new StdClass(); - - foreach($params as $key => $val) - { - $p->$key = $val; - } - - $params = $p; - } - - $params->type = strtolower($params->type); - $dbtype = ($params->type !== 'postgresql') ? $params->type : 'pgsql'; - - // Create the dsn for the database to connect to - switch($dbtype) - { - default: - $dsn = "dbname={$params->conn_db}"; - - if ( ! empty($params->host)) - { - $dsn .= ";host={$params->host}"; - } - - if ( ! empty($params->port)) - { - $dsn .= ";port={$params->port}"; - } - - break; - - case "sqlite": - $dsn = $params->file; - break; - - case "firebird": - $dsn = "{$params->host}:{$params->file}"; - break; - } - - // Set the charset - //$dsn .= ";charset=utf-8"; - - // Create the database connection - if ( ! empty($params->user)) - { - $this->db = new $dbtype($dsn, $params->user, $params->pass); - } - else - { - $this->db = new $dbtype($dsn); - } - - if (isset($params->name)) - { - $this->conn_name = $params->name; - } - - - // Make things just slightly shorter - $this->sql =& $this->db->sql; - } - - // -------------------------------------------------------------------------- - // ! Select Queries - // -------------------------------------------------------------------------- - - /** - * Specifies rows to select in a query - * - * @param string $fields - * @return $this - */ - public function select($fields) - { - // Split fields by comma - $fields_array = explode(",", $fields); - $fields_array = array_map('trim', $fields_array); - - // Split on 'As' - foreach ($fields_array as $key => $field) - { - if (stripos($field, 'as') !== FALSE) - { - $fields_array[$key] = preg_split('`as`i', $field); - $fields_array[$key] = array_map('trim', $fields_array[$key]); - } - } - - // Quote the identifiers - $safe_array = array_map(array($this->db, 'quote_ident'), $fields_array); - - unset($fields_array); - - // Join the strings back together - for($i = 0, $c = count($safe_array); $i < $c; $i++) - { - if (is_array($safe_array[$i])) - { - $safe_array[$i] = implode(' AS ', $safe_array[$i]); - } - } - - $this->select_string = implode(', ', $safe_array); - - unset($safe_array); - - return $this; - } - - // -------------------------------------------------------------------------- - - /** - * Specify the database table to select from - * - * @param string $dbname - * @return $this - */ - public function from($dbname) - { - // Split identifiers on spaces - $ident_array = explode(' ', trim($dbname)); - $ident_array = array_map('trim', $ident_array); - - // Quote the identifiers - $ident_array = array_map(array($this->db, 'quote_ident'), $ident_array); - - // Paste it back together - $this->from_string = implode(' ', $ident_array); - - return $this; - } - - // -------------------------------------------------------------------------- - // ! 'Like' methods - // -------------------------------------------------------------------------- - - /** - * Creates a Like clause in the sql statement - * - * @param string $field - * @param mixed $val - * @param string $pos - * @return $this - */ - public function like($field, $val, $pos='both') - { - $field = $this->db->quote_ident($field); - - // Add the like string into the order map - $l = $field. ' LIKE ?'; - - if ($pos == 'before') - { - $val = "%{$val}"; - } - elseif ($pos == 'after') - { - $val = "{$val}%"; - } - else - { - $val = "%{$val}%"; - } - - $this->query_map[] = array( - 'type' => 'like', - 'conjunction' => (empty($this->query_map)) ? 'WHERE ' : ' AND ', - 'string' => $l - ); - - // Add to the values array - $this->values[] = $val; - - return $this; - } - - // -------------------------------------------------------------------------- - - /** - * Generates an OR Like clause - * - * @param string $field - * @param mixed $val - * @param string $pos - * @return $this - */ - public function or_like($field, $val, $pos='both') - { - $field = $this->db->quote_ident($field); - - // Add the like string into the order map - $l = $field. ' LIKE ?'; - - if ($pos == 'before') - { - $val = "%{$val}"; - } - elseif ($pos == 'after') - { - $val = "{$val}%"; - } - else - { - $val = "%{$val}%"; - } - - $this->query_map[] = array( - 'type' => 'like', - 'conjunction' => (empty($this->query_map)) ? 'WHERE ' : ' OR ', - 'string' => $l - ); - - // Add to the values array - $this->values[] = $val; - - return $this; - } - - // -------------------------------------------------------------------------- - - /** - * Generates a NOT LIKE clause - * - * @param string $field - * @param mixed $val - * @param string $pos - * @return $this - */ - public function not_like($field, $val, $pos='both') - { - $field = $this->db->quote_ident($field); - - // Add the like string into the order map - $l = $field. ' NOT LIKE ?'; - - if ($pos == 'before') - { - $val = "%{$val}"; - } - elseif ($pos == 'after') - { - $val = "{$val}%"; - } - else - { - $val = "%{$val}%"; - } - - $this->query_map[] = array( - 'type' => 'like', - 'conjunction' => (empty($this->query_map)) ? ' WHERE ' : ' AND ', - 'string' => $l - ); - - // Add to the values array - $this->values[] = $val; - - return $this; - } - - // -------------------------------------------------------------------------- - - /** - * Generates a OR NOT LIKE clause - * - * @param string $field - * @param mixed $val - * @param string $pos - * @return $this; - */ - public function or_not_like($field, $val, $pos='both') - { - $field = $this->db->quote_ident($field); - - // Add the like string into the order map - $l = $field. ' NOT LIKE ?'; - - if ($pos == 'before') - { - $val = "%{$val}"; - } - elseif ($pos == 'after') - { - $val = "{$val}%"; - } - else - { - $val = "%{$val}%"; - } - - $this->query_map[] = array( - 'type' => 'like', - 'conjunction' => (empty($this->query_map)) ? ' WHERE ' : ' OR ', - 'string' => $l - ); - - // Add to the values array - $this->values[] = $val; - - return $this; - } - - // -------------------------------------------------------------------------- - // ! 'Where' methods - // -------------------------------------------------------------------------- - - /** - * Do all the repeditive stuff for where type methods - * - * @param mixed $key - * @param mixed $val - * @return array - */ - private function _where($key, $val=array()) - { - $where = array(); - - // Key and value passed? Add them to the where array - if (is_scalar($key) && is_scalar($val)) - { - $where[$key] = $val; - $this->values[] = $val; - } - // Array or object, loop through and add to the where array - elseif ( ! is_scalar($key)) - { - foreach($key as $k => $v) - { - $where[$k] = $v; - $this->values[] = $v; - } - } - - return $where; - } - - // -------------------------------------------------------------------------- - - /** - * Specify condition(s) in the where clause of a query - * Note: this function works with key / value, or a - * passed array with key / value pairs - * - * @param mixed $key - * @param mixed $val - * @return $this - */ - public function where($key, $val=array()) - { - $where = $this->_where($key, $val); - - // Create key/value placeholders - foreach($where as $f => $val) - { - // Split each key by spaces, in case there - // is an operator such as >, <, !=, etc. - $f_array = explode(' ', trim($f)); - - $item = $this->db->quote_ident($f_array[0]); - - // Simple key value, or an operator - $item .= (count($f_array === 1)) ? '= ?' : " {$f_array[1]} ?"; - - // Put in the query map for select statements - $this->query_map[] = array( - 'type' => 'where', - 'conjunction' => ( ! empty($this->query_map)) ? ' AND ' : ' WHERE ', - 'string' => $item - ); - } - - return $this; - } - - // -------------------------------------------------------------------------- - - /** - * Where clause prefixed with "OR" - * - * @param string $field - * @param mixed $val - * @return $this - */ - public function or_where($field, $val=array()) - { - $where = $this->_where($field, $val); - - // Create key/value placeholders - foreach($where as $f => $val) - { - // Split each key by spaces, incase there - // is an operator such as >, <, !=, etc. - $f_array = explode(' ', trim($f)); - - // Simple key = val - if (count($f_array) === 1) - { - $item = $this->db->quote_ident($f_array[0]) . '= ?'; - } - else // Other operators - { - $item = $this->db->quote_ident($f_array[0]) . " {$f_array[1]} ?"; - } - - // Put in the query map for select statements - $this->query_map[] = array( - 'type' => 'where', - 'conjunction' => ( ! empty($this->query_map)) ? ' OR ' : ' WHERE ', - 'string' => $item - ); - } - - return $this; - } - - // -------------------------------------------------------------------------- - - /** - * Where clause with 'IN' statement - * - * @param mixed $field - * @param mixed $val - * @return $this - */ - public function where_in($field, $val=array()) - { - $field = $this->db->quote_ident($field); - $params = array_fill(0, count($val), '?'); - - foreach($val as $v) - { - $this->values[] = $v; - } - - $string = $field . ' IN ('.implode(',', $params).') '; - - $this->query_map[] = array( - 'type' => 'where_in', - 'conjunction' => ( ! empty($this->query_map)) ? ' AND ' : ' WHERE ', - 'string' => $string - ); - - return $this; - } - - // -------------------------------------------------------------------------- - - /** - * Where in statement prefixed with "or" - * - * @param string $field - * @param mixed $val - * @return $this - */ - public function or_where_in($field, $val=array()) - { - $field = $this->db->quote_ident($field); - $params = array_fill(0, count($val), '?'); - - foreach($val as $v) - { - $this->values[] = $v; - } - - $string = $field . ' IN ('.implode(',', $params).') '; - - $this->query_map[] = array( - 'type' => 'where_in', - 'conjunction' => ( ! empty($this->query_map)) ? ' OR ' : ' WHERE ', - 'string' => $string - ); - - return $this; - } - - // -------------------------------------------------------------------------- - - /** - * WHERE NOT IN (FOO) clause - * - * @param string $field - * @param mixed $val - * @return $this - */ - public function where_not_in($field, $val=array()) - { - $field = $this->db->quote_ident($field); - $params = array_fill(0, count($val), '?'); - - foreach($val as $v) - { - $this->values[] = $v; - } - - $string = $field.' NOT IN ('.implode(',', $params).') '; - - $this->query_map[] = array( - 'type' => 'where_in', - 'conjunction' => ( ! empty($this->query_map)) ? ' AND ' : ' WHERE ', - 'string' => $string - ); - - return $this; - } - - // -------------------------------------------------------------------------- - - /** - * OR WHERE NOT IN (FOO) clause - * - * @param string $field - * @param mixed $val - * @return $this - */ - public function or_where_not_in($field, $val=array()) - { - $field = $this->db->quote_ident($field); - $params = array_fill(0, count($val), '?'); - - foreach($val as $v) - { - $this->values[] = $v; - } - - $string = $field.' NOT IN ('.implode(',', $params).') '; - - $this->query_map[] = array( - 'type' => 'where_in', - 'conjunction' => ( ! empty($this->query_map)) ? ' OR ' : ' WHERE ', - 'string' => $string - ); - - return $this; - } - - // -------------------------------------------------------------------------- - // ! Other Query Modifier methods - // -------------------------------------------------------------------------- - - /** - * Creates a join phrase in a compiled query - * - * @param string $table - * @param string $condition - * @param string $type - * @return $this - */ - public function join($table, $condition, $type='') - { - // Paste it back together - $table = implode(" ", array_map(array($this->db, 'quote_ident'), explode(' ', trim($table)))); - //$condition = preg_replace('`(\W)`', " $1 ", $condition); - $cond_array = explode(' ', trim($condition)); - $cond_array = array_map('trim', $cond_array); - - $condition = $table . ' ON ' . $this->db->quote_ident($cond_array[0]) . $cond_array[1] . - ' ' . $this->db->quote_ident($cond_array[2]); - - $this->query_map[] = array( - 'type' => 'join', - 'conjunction' => strtoupper($type).' JOIN ', - 'string' => $condition, - ); - - return $this; - } - - // -------------------------------------------------------------------------- - - /** - * Group the results by the selected field(s) - * - * @param mixed $field - * @return $this - */ - public function group_by($field) - { - if ( ! is_scalar($field)) - { - $this->group_array = array_map(array($this->db, 'quote_ident'), $field); - } - else - { - $this->group_array[] = $this->db->quote_ident($field); - } - - $this->group_string = ' GROUP BY ' . implode(', ', $this->group_array); - - return $this; - } - - // -------------------------------------------------------------------------- - - /** - * Order the results by the selected field(s) - * - * @param string $field - * @param string $type - * @return $this - */ - public function order_by($field, $type="") - { - // Random case - if (stripos($type, 'rand') !== FALSE) - { - $type = (($rand = $this->sql->random()) !== FALSE ) ? $rand : 'ASC'; - } - - // Set fields for later manipulation - $field = $this->db->quote_ident($field); - $this->order_array[$field] = $type; - - $order_clauses = array(); - - // Flatten key/val pairs into an array of space-separated pairs - foreach($this->order_array as $k => $v) - { - $order_clauses[] = $k . ' ' . strtoupper($v); - } - - // Set the final string - $this->order_string = (empty($rand)) - ? ' ORDER BY '.implode(',', $order_clauses) - : ' ORDER BY'.$rand; - - return $this; - } - - // -------------------------------------------------------------------------- - - /** - * Set a limit on the current sql statement - * - * @param int $limit - * @param int $offset - * @return string - */ - public function limit($limit, $offset=FALSE) - { - $this->limit = $limit; - $this->offset = $offset; - - return $this; - } - - // -------------------------------------------------------------------------- - // ! Query execution methods - // -------------------------------------------------------------------------- - - /** - * Select and retrieve all records from the current table, and/or - * execute current compiled query - * - * @param $table - * @param int $limit - * @param int $offset - * @return object - */ - public function get($table='', $limit=FALSE, $offset=FALSE) - { - // Set the table - if ( ! empty($table)) - { - $this->from($table); - } - - // Set the limit, if it exists - if ($limit !== FALSE) - { - $this->limit($limit, $offset); - } - - $sql = $this->_compile(); - - // Do prepared statements for anything involving a "where" clause - if ( ! empty($this->query_map)) - { - $result = $this->db->prepare_execute($sql, $this->values); - } - else - { - // Otherwise, a simple query will do. - $result = $this->db->query($sql); - } - - // Reset for next query - $this->_reset(); - - return $result; - } - - // -------------------------------------------------------------------------- - - /** - * Creates an insert clause, and executes it - * - * @param string $table - * @param mixed $data - * @return mixed - */ - public function insert($table, $data=array()) - { - // No use duplicating logic! - if ( ! empty($data)) - { - $this->set($data); - } - - $sql = $this->_compile("insert", $table); - - $res = $this->db->prepare_execute($sql, $this->values); - - $this->_reset(); - - return $res; - } - - // -------------------------------------------------------------------------- - - /** - * Creates an update clause, and executes it - * - * @param string $table - * @param mixed $data - * @return mixed - */ - public function update($table, $data=array()) - { - // No use duplicating logic! - if ( ! empty($data)) - { - $this->set($data); - } - - $sql = $this->_compile('update', $table); - - $res = $this->db->prepare_execute($sql, $this->values); - - $this->_reset(); - - // Run the query - return $res; - } - - // -------------------------------------------------------------------------- - - /** - * Deletes data from a table - * - * @param string $table - * @param mixed $where - * @return mixed - */ - public function delete($table, $where='') - { - // Set the where clause - if ( ! empty($where)) - { - $this->where($where); - } - - // Create the SQL and parameters - $sql = $this->_compile("delete", $table); - - $res = $this->db->prepare_execute($sql, $this->values); - - $this->_reset(); - - // Delete the table rows, and return the result - return $res; - } - - // -------------------------------------------------------------------------- - // ! Query Grouping Methods - // -------------------------------------------------------------------------- - - /** - * Adds a paren to the current query for query grouping - * - * @return $this - */ - public function group_start() - { - $this->query_map[] = array( - 'type' => 'group_start', - 'conjunction' => '', - 'string' => ' (' - ); - - return $this; - } - - // -------------------------------------------------------------------------- - - /** - * Adds a paren to the current query for query grouping, - * prefixed with 'OR' - * - * @return $this - */ - public function or_group_start() - { - $this->query_map[] = array( - 'type' => 'group_start', - 'conjunction' => '', - 'string' => ' OR (' - ); - - return $this; - } - - // -------------------------------------------------------------------------- - - /** - * Adds a paren to the current query for query grouping, - * prefixed with 'OR NOT' - * - * @return $this - */ - public function or_not_group_start() - { - $this->query_map[] = array( - 'type' => 'group_start', - 'conjunction' => '', - 'string' => ' OR NOT (' - ); - - return $this; - } - - // -------------------------------------------------------------------------- - - /** - * Ends a query group - * - * @return $this - */ - public function group_end() - { - $this->query_map[] = array( - 'type' => 'group_end', - 'conjunction' => '', - 'string' => ' ) ' - ); - - return $this; - } - - // -------------------------------------------------------------------------- - // ! Miscellaneous Methods - // -------------------------------------------------------------------------- - - /** - * Sets values for inserts / updates / deletes - * - * @param mixed $key - * @param mixed $val - * @return $this - */ - public function set($key, $val) - { - // Plain key, value pair - if (is_scalar($key) && is_scalar($val)) - { - $this->set_array[$key] = $val; - $this->values[] = $val; - } - // Object or array - elseif ( ! is_scalar($key)) - { - foreach($key as $k => $v) - { - $this->set_array[$k] = $v; - $this->values[] = $val; - } - } - - // Use the keys of the array to make the insert/update string - // Escape the field names - $this->set_array_keys = array_map(array($this->db, 'quote_ident'), array_keys($this->set_array)); - - // Generate the "set" string - $this->set_string = implode('=?, ', $this->set_array_keys); - $this->set_string .= '=?'; - - return $this; - } - - // -------------------------------------------------------------------------- - - /** - * 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 - */ - private function _reset() - { - // Only unset class variables that - // are not callable. Otherwise, we'll - // delete class methods! - foreach($this as $name => $var) - { - // Skip properties that are needed for every query - $save_properties = array( - 'db', - 'sql' - ); - - if (in_array($name, $save_properties)) - { - continue; - } - - // Nothing query-generation related is safe! - if ( ! is_callable($this->$name)) - { - unset($this->$name); - } - - // Set values as an empty array - $this->values = array(); - } - } - - // -------------------------------------------------------------------------- - - /** - * String together the sql statements for sending to the db - * - * @param string $type - * @param string $table - * @return $string - */ - private function _compile($type='', $table="") - { - $sql = ''; - - switch($type) - { - default: - $sql = 'SELECT * FROM '.$this->from_string; - - // Set the select string - if ( ! empty($this->select_string)) - { - // Replace the star with the selected fields - $sql = str_replace('*', $this->select_string, $sql); - } - - // Set the where string - if ( ! empty($this->query_map)) - { - foreach($this->query_map as $q) - { - $sql .= $q['conjunction'] . $q['string']; - } - } - - // Set the group_by string - if ( ! empty($this->group_string)) - { - $sql .= $this->group_string; - } - - // Set the order_by string - if ( ! empty($this->order_string)) - { - $sql .= $this->order_string; - } - - // Set the limit via the class variables - if (isset($this->limit) && is_numeric($this->limit)) - { - $sql = $this->sql->limit($sql, $this->limit, $this->offset); - } - break; - - case "insert": - $param_count = count($this->set_array); - $params = array_fill(0, $param_count, '?'); - $sql = 'INSERT INTO '. $this->db->quote_ident($table) . - ' (' . implode(', ', $this->set_array_keys) . - ') VALUES ('.implode(', ', $params).')'; - break; - - case "update": - $sql = 'UPDATE '.$this->db->quote_ident($table). ' SET '. $this->set_string; - - // Set the where string - if ( ! empty($this->query_map)) - { - foreach($this->query_map as $q) - { - $sql .= $q['conjunction'] . $q['string']; - } - } - break; - - case "delete": - $sql = 'DELETE FROM '.$this->db->quote_ident($table); - - // Set the where string - if ( ! empty($this->query_map)) - { - foreach($this->query_map as $q) - { - $sql .= $q['conjunction'] . $q['string']; - } - } - - break; - } - - return $sql; - } -} -// End of query_builder.php \ No newline at end of file diff --git a/tests/db_files/FB_TEST_DB.FDB b/tests/db_files/FB_TEST_DB.FDB index efca51afe19d46b1f6bba3a74a5e2deea6bd3754..7e64312fbe0b7a3a600cedf3ce8b3b94d350235e 100755 GIT binary patch delta 2879 zcmbW3O=uKZ5XY-~rjyRROy;RXg}6(1X7h1SNn%t2f*uy!lL#yBVP!EP8qpyw6Hy83 z3?BL>2p;<2-J>jv7`!YfdhxQCJ&A__a|tXu$31MrR@Hko-IGjY@P(dEb-%8z`gOhk zt7dbd*<3j1z{1Syama>N&4RV)ydDDF#{X@0J!NtGJY&iJ49&Uu^ zoj)oMb*!COyRk0Bx)^IO)&sE~jI|%@p_jT;)XswqFDU)uKRKfhY+RZyJsON>N-t+r z@%P3d&p4Ogi_SjyTTQ^JkqP*r9KhpB0L$evv`3}^%HwdbQiTg>e;lsDi{WW_jOS~^ z6R-V|qdhR?5CipYhJhdHlCtMtS&0J)LD zp?gJ~GymE|uDg68Bc4h=>_LcfJ}~&?)utLPsuW6jU>MxzPe^fyE>60)!sO^D^qV*3&oZlLK5W$-O!jQ5&`Q!(%ZjUL(!FL`^`$+M zJH=0|#AbGwk=UX=OWRnHZAQ<6Ay$FRAU-4`v-3Gtcr9aMpJ2-35uDkSt>`01-*Gq%Z49Y*|lYGtTHV{1)Z}2_=JUGj_#gm6m21TxaVP z#ZEygv3KLGPh0_K!da0|Qt+;bSiujYAaT;hwMPNnSbIkg&@OGxycy!dW|dm0x|~Us zd6s_7t~WbJ&*gVLK_jbDY(^VE2OXnDn|hLtwp$xr;^>KT04oopPA+Y!v7hq`G9^bc zddm39m3rs?&V7%mt#fM-44`b`W}h7XqQ(@`F;ws-w+Lp(YuwxZzU~$QCGAcm?=!F# zac}L0CCT%$#Q4M(cw&pBNy~tr3tNP>HELU^MaTsF(6RY! zZQZ+c2Gl&EuuJo_Uz#WL4S9K>+9d6k`hK+go>iXYOG{0-=!LfdBW-h%mZ*_Lyjy2= k*A(PbUs8yT3T;I`H83f*7X0SIPzrHd#qHr|?eh8m0c$?DTL1t6 delta 2647 zcmb7`Pe>F|9LIlecSqfMitkW#5ZSkGrb3Z_b_p>OA*oX+iC#J=ArwdpEg{sQC1N5- z$kR{@b?Xv=b6P>td((PP zSb|w1W{J2Z5|%J5(O`*2OEg&`xh%|tU>z%lG^d(Y3f<;H(bL<|G~j#rP1VaHH!9JJbLtxq`k3=^oFKya_ApQ`^GMp6aQy?AnO@P6C-J2yd&*%J3P}9 zlJ2%k=XmSV&1<^$sZb`~@&S@2K+*(wT?5Jp4qgj#a5l7qSABq_36L}aPDOKYGRVQp zQ5+oi0g@&_(gZjf*}?Nc4vvI&aM%Y(ngB@?;6OA7`-2=j9mT;@K0wk0NSXlCksXvl z4z`DOu+0ZZngB@?V5{R`F2pL{cS}3B#$aFC%UfI;YVitt=m+n*xK~kwsOhvc5*Sk1 z4^CLJ3e;ZLVb+&bVOH%q_^SijS-4b7#hr@2`MetGMqh=3d(RDSC;Hsr{v)e52LyK< zvAuRsaQ~Jyp_l?7t?k5MC+*q^KXJScZrS72J{)~JXik2wnUh|fgBZ7DJtJviBu$Lp zYUU((?J#@42F=MYG$*|h2LZ0jdO*?yNSXjY(yI0{ad-cq_8QrjwSf4Yv