Split off db_util classes for each driver

This commit is contained in:
Timothy Warren 2012-04-18 15:53:06 -04:00
parent c12fcd9c09
commit 12f53c5fd5
23 changed files with 802 additions and 634 deletions

View File

@ -21,10 +21,16 @@
*/
abstract class DB_PDO extends PDO {
public $manip;
// Reference to last query
protected $statement;
// Character to escape identifiers
protected $escape_char = '"';
// References to sub-classes
public $sql,
$util;
/**
* PDO constructor wrapper
*
@ -37,6 +43,14 @@ abstract class DB_PDO extends PDO {
{
parent::__construct($dsn, $username, $password, $driver_options);
// Load the sql class for the driver
$class = get_class($this)."_sql";
$this->sql = new $class();
// Load the util class for the driver
$class = get_class($this)."_util";
$this->util = new $class($this);
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

View File

@ -83,27 +83,6 @@ abstract class DB_SQL {
// ! Abstract Methods
// --------------------------------------------------------------------------
/**
* Get database-specific sql to create a new table
*
* @abstract
* @param string $name
* @param array $columns
* @param array $constraints
* @param array $indexes
* @return string
*/
abstract public function create_table($name, $columns, array $constraints=array(), array $indexes=array());
/**
* Get database-specific sql to drop a table
*
* @abstract
* @param string $name
* @return string
*/
abstract public function delete_table($name);
/**
* Get database specific sql for limit clause
*
@ -123,22 +102,6 @@ abstract class DB_SQL {
*/
abstract public function random();
/**
* Return an SQL file with the database table structure
*
* @abstract
* @return string
*/
abstract public function backup_structure();
/**
* Return an SQL file with the database data as insert statements
*
* @abstract
* @return string
*/
abstract public function backup_data();
/**
* Returns sql to list other databases
*

71
classes/db_util.php Normal file
View File

@ -0,0 +1,71 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* Abstract class defining database / table creation methods
*/
abstract class DB_Util {
private $conn;
/**
* Save a reference to the connection object for later use
*/
public function __construct(&$conn)
{
$this->conn =& $conn;
}
// --------------------------------------------------------------------------
// ! Abstract Methods
// --------------------------------------------------------------------------
/**
* Get database-specific sql to create a new table
*
* @abstract
* @param string $name
* @param array $columns
* @param array $constraints
* @param array $indexes
* @return string
*/
abstract public function create_table($name, $columns, array $constraints=array(), array $indexes=array());
/**
* Get database-specific sql to drop a table
*
* @abstract
* @param string $name
* @return string
*/
abstract public function delete_table($name);
/**
* Return an SQL file with the database table structure
*
* @abstract
* @return string
*/
abstract public function backup_structure();
/**
* Return an SQL file with the database data as insert statements
*
* @abstract
* @return string
*/
abstract public function backup_data();
}

View File

@ -39,6 +39,8 @@ class Settings {
*/
private function __construct()
{
// For testing and use outside of OpenSQLManager,
// define a different SETTINGS_DIR
if ( ! defined('SETTINGS_DIR'))
{
define('SETTINGS_DIR', '.');

View File

@ -44,8 +44,18 @@ class Firebird extends DB_PDO {
die();
}
// Load these classes here because this
// driver does not call the constructor
// of DB_PDO, which defines these two
// class variables for the other drivers
// Load the sql class
$class = __CLASS__."_sql";
$this->sql = new $class;
$this->sql = new $class();
// Load the util class
$class = __CLASS__."_util";
$this->util = new $class($this);
}
// --------------------------------------------------------------------------

View File

@ -17,79 +17,6 @@
*/
class Firebird_SQL extends DB_SQL {
/**
* Convienience public function to generate sql for creating a db table
*
* @param string $name
* @param array $fields
* @param array $constraints=array()
* @param array $indexes=array()
*
* @return string
*/
public function create_table($name, $fields, array $constraints=array(), array $indexes=array())
{
$column_array = array();
// Reorganize into an array indexed with column information
// Eg $column_array[$colname] = array(
// 'type' => ...,
// 'constraint' => ...,
// 'index' => ...,
// )
foreach($fields as $colname => $type)
{
if(is_numeric($colname))
{
$colname = $type;
}
$column_array[$colname] = array();
$column_array[$colname]['type'] = ($type !== $colname) ? $type : '';
}
if( ! empty($constraints))
{
foreach($constraints as $col => $const)
{
$column_array[$col]['constraint'] = $const;
}
}
// Join column definitons together
$columns = array();
foreach($column_array as $n => $props)
{
$str = '"'.$n.'" ';
$str .= (isset($props['type'])) ? "{$props['type']} " : "";
$str .= (isset($props['constraint'])) ? "{$props['constraint']} " : "";
$columns[] = $str;
}
// Generate the sql for the creation of the table
$sql = 'CREATE TABLE "'.$name.'" (';
$sql .= implode(',', $columns);
$sql .= ')';
return $sql;
}
// --------------------------------------------------------------------------
/**
* Drop the selected table
*
* @param string $name
* @return string
*/
public function delete_table($name)
{
return 'DROP TABLE "'.$name.'"';
}
// --------------------------------------------------------------------------
/**
* Limit clause
*
@ -127,88 +54,6 @@ class Firebird_SQL extends DB_SQL {
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;
}
// --------------------------------------------------------------------------

View File

@ -0,0 +1,180 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* Firebird-specific backup, import and creation methods
*/
class Firebird_Util extends DB_Util {
public function __construct(&$conn)
{
parent::__construct($conn);
}
/**
* Convienience public function to generate sql for creating a db table
*
* @param string $name
* @param array $fields
* @param array $constraints=array()
* @param array $indexes=array()
*
* @return string
*/
public function create_table($name, $fields, array $constraints=array(), array $indexes=array())
{
$column_array = array();
// Reorganize into an array indexed with column information
// Eg $column_array[$colname] = array(
// 'type' => ...,
// 'constraint' => ...,
// 'index' => ...,
// )
foreach($fields as $colname => $type)
{
if(is_numeric($colname))
{
$colname = $type;
}
$column_array[$colname] = array();
$column_array[$colname]['type'] = ($type !== $colname) ? $type : '';
}
if( ! empty($constraints))
{
foreach($constraints as $col => $const)
{
$column_array[$col]['constraint'] = $const;
}
}
// Join column definitons together
$columns = array();
foreach($column_array as $n => $props)
{
$str = '"'.$n.'" ';
$str .= (isset($props['type'])) ? "{$props['type']} " : "";
$str .= (isset($props['constraint'])) ? "{$props['constraint']} " : "";
$columns[] = $str;
}
// Generate the sql for the creation of the table
$sql = 'CREATE TABLE "'.$name.'" (';
$sql .= implode(',', $columns);
$sql .= ')';
return $sql;
}
// --------------------------------------------------------------------------
/**
* Drop the selected table
*
* @param string $name
* @return string
*/
public function delete_table($name)
{
return 'DROP TABLE "'.$name.'"';
}
// --------------------------------------------------------------------------
/**
* 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;
}
}
// End of firebird_util.php

View File

@ -37,9 +37,6 @@ class MySQL extends DB_PDO {
));
parent::__construct("mysql:$dsn", $username, $password, $options);
$class = __CLASS__.'_sql';
$this->sql = new $class;
}
// --------------------------------------------------------------------------

View File

@ -17,89 +17,6 @@
*/
class MySQL_SQL extends DB_SQL {
/**
* Convienience public function for creating a new MySQL table
*
* @param string $name
* @param array $columns
* @param array $constraints=array()
* @param array $indexes=array()
*
* @return string
*/
public function create_table($name, $columns, array $constraints=array(), array $indexes=array())
{
$column_array = array();
// Reorganize into an array indexed with column information
// Eg $column_array[$colname] = array(
// 'type' => ...,
// 'constraint' => ...,
// 'index' => ...,
// )
foreach($columns as $colname => $type)
{
if(is_numeric($colname))
{
$colname = $type;
}
$column_array[$colname] = array();
$column_array[$colname]['type'] = ($type !== $colname) ? $type : '';
}
if( ! empty($constraints))
{
foreach($constraints as $col => $const)
{
$column_array[$col]['constraint'] = "{$const} ({$col})";
}
}
// Join column definitons together
$columns = array();
foreach($column_array as $n => $props)
{
$n = trim($n, '`');
$str = "`{$n}` ";
$str .= (isset($props['type'])) ? "{$props['type']} " : "";
$columns[] = $str;
}
// Add constraints
foreach($column_array as $n => $props)
{
if (isset($props['constraint']))
{
$columns[] = $props['constraint'];
}
}
// Generate the sql for the creation of the table
$sql = "CREATE TABLE IF NOT EXISTS `{$name}` (";
$sql .= implode(", ", $columns);
$sql .= ")";
return $sql;
}
// --------------------------------------------------------------------------
/**
* Convience public function for droping a MySQL table
*
* @param string $name
* @return string
*/
public function delete_table($name)
{
return "DROP TABLE `{$name}`";
}
// --------------------------------------------------------------------------
/**
* Limit clause
*
@ -132,32 +49,6 @@ class MySQL_SQL extends DB_SQL{
// --------------------------------------------------------------------------
/**
* 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
*

View File

@ -0,0 +1,132 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* MySQL-specific backup, import and creation methods
*/
class MySQL_Util extends DB_Util {
public function __construct(&$conn)
{
parent::__construct($conn);
}
/**
* Convienience public function for creating a new MySQL table
*
* @param string $name
* @param array $columns
* @param array $constraints=array()
* @param array $indexes=array()
*
* @return string
*/
public function create_table($name, $columns, array $constraints=array(), array $indexes=array())
{
$column_array = array();
// Reorganize into an array indexed with column information
// Eg $column_array[$colname] = array(
// 'type' => ...,
// 'constraint' => ...,
// 'index' => ...,
// )
foreach($columns as $colname => $type)
{
if(is_numeric($colname))
{
$colname = $type;
}
$column_array[$colname] = array();
$column_array[$colname]['type'] = ($type !== $colname) ? $type : '';
}
if( ! empty($constraints))
{
foreach($constraints as $col => $const)
{
$column_array[$col]['constraint'] = "{$const} ({$col})";
}
}
// Join column definitons together
$columns = array();
foreach($column_array as $n => $props)
{
$n = trim($n, '`');
$str = "`{$n}` ";
$str .= (isset($props['type'])) ? "{$props['type']} " : "";
$columns[] = $str;
}
// Add constraints
foreach($column_array as $n => $props)
{
if (isset($props['constraint']))
{
$columns[] = $props['constraint'];
}
}
// Generate the sql for the creation of the table
$sql = "CREATE TABLE IF NOT EXISTS `{$name}` (";
$sql .= implode(", ", $columns);
$sql .= ")";
return $sql;
}
// --------------------------------------------------------------------------
/**
* Convience public function for droping a MySQL table
*
* @param string $name
* @return string
*/
public function delete_table($name)
{
return "DROP TABLE `{$name}`";
}
// --------------------------------------------------------------------------
/**
* 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 mysql_util.php

View File

@ -35,9 +35,6 @@ class ODBC extends DB_PDO {
public function __construct($dsn, $username=null, $password=null, $options=array())
{
parent::__construct("odbc:$dsn", $username, $password, $options);
$class = __CLASS__.'_sql';
$this->sql = new $class;
}
// --------------------------------------------------------------------------

View File

@ -17,27 +17,6 @@
*/
class ODBC_SQL extends DB_SQL {
public function create_table($name, $columns, array $constraints=array(), array $indexes=array())
{
//ODBC can't know how to create a table
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Remove a table from the database
*
* @param string $name
* @return string
*/
public function delete_table($name)
{
return "DROP TABLE {$name}";
}
// --------------------------------------------------------------------------
/**
* Limit clause
*
@ -65,32 +44,6 @@ class ODBC_SQL extends DB_SQL {
// --------------------------------------------------------------------------
/**
* Create an SQL backup file for the current database's structure
*
* @return string
*/
public function backup_structure()
{
// Not applicable to ODBC
return '';
}
// --------------------------------------------------------------------------
/**
* Create an SQL backup file for the current database's data
*
* @return string
*/
public function backup_data()
{
// Not applicable to ODBC
return '';
}
// --------------------------------------------------------------------------
/**
* Returns sql to list other databases
*

View File

@ -0,0 +1,72 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* ODBC-specific backup, import and creation methods
*/
class ODBC_Util extends DB_Util {
public function __construct(&$conn)
{
parent::__construct($conn);
}
// --------------------------------------------------------------------------
public function create_table($name, $columns, array $constraints=array(), array $indexes=array())
{
//ODBC can't know how to create a table
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Remove a table from the database
*
* @param string $name
* @return string
*/
public function delete_table($name)
{
return "DROP TABLE {$name}";
}
// --------------------------------------------------------------------------
/**
* Create an SQL backup file for the current database's structure
*
* @return string
*/
public function backup_structure()
{
// Not applicable to ODBC
return '';
}
// --------------------------------------------------------------------------
/**
* Create an SQL backup file for the current database's data
*
* @return string
*/
public function backup_data()
{
// Not applicable to ODBC
return '';
}
}
// End of ODBC_util.php

View File

@ -30,10 +30,6 @@ class pgSQL extends DB_PDO {
public function __construct($dsn, $username=null, $password=null, $options=array())
{
parent::__construct("pgsql:$dsn", $username, $password, $options);
//Get db manip class
$class = __CLASS__.'_sql';
$this->sql = new $class;
}
// --------------------------------------------------------------------------

View File

@ -17,78 +17,6 @@
*/
class pgSQL_SQL extends DB_SQL {
/**
* Database-specific method to create a new table
*
* @param string $name
* @param array $columns
* @param array $constraints
* @param array $indexes
* @return string
*/
public function create_table($name, $columns, array $constraints=array(), array $indexes=array())
{
$column_array = array();
// Reorganize into an array indexed with column information
// Eg $column_array[$colname] = array(
// 'type' => ...,
// 'constraint' => ...,
// 'index' => ...,
// )
foreach($columns as $colname => $type)
{
if(is_numeric($colname))
{
$colname = $type;
}
$column_array[$colname] = array();
$column_array[$colname]['type'] = ($type !== $colname) ? $type : '';
}
if( ! empty($constraints))
{
foreach($constraints as $col => $const)
{
$column_array[$col]['constraint'] = $const;
}
}
// Join column definitons together
$columns = array();
foreach($column_array as $n => $props)
{
$str = "{$n} ";
$str .= (isset($props['type'])) ? "{$props['type']} " : "";
$str .= (isset($props['constraint'])) ? $props['constraint'] : "";
$columns[] = $str;
}
// Generate the sql for the creation of the table
$sql = "CREATE TABLE \"{$name}\" (";
$sql .= implode(", ", $columns);
$sql .= ")";
return $sql;
}
// --------------------------------------------------------------------------
/**
* Database-specific SQL for dropping a table
*
* @param string $name
* @return string
*/
public function delete_table($name)
{
return 'DROP TABLE "'.$name.'"';
}
// --------------------------------------------------------------------------
/**
* Limit clause
*
@ -123,32 +51,6 @@ class pgSQL_SQL extends DB_SQL {
// --------------------------------------------------------------------------
/**
* 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
*

View File

@ -0,0 +1,121 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* Posgres-specific backup, import and creation methods
*/
class PgSQL_Util extends DB_Util {
public function __construct(&$conn)
{
parent::__construct($conn);
}
/**
* Database-specific method to create a new table
*
* @param string $name
* @param array $columns
* @param array $constraints
* @param array $indexes
* @return string
*/
public function create_table($name, $columns, array $constraints=array(), array $indexes=array())
{
$column_array = array();
// Reorganize into an array indexed with column information
// Eg $column_array[$colname] = array(
// 'type' => ...,
// 'constraint' => ...,
// 'index' => ...,
// )
foreach($columns as $colname => $type)
{
if(is_numeric($colname))
{
$colname = $type;
}
$column_array[$colname] = array();
$column_array[$colname]['type'] = ($type !== $colname) ? $type : '';
}
if( ! empty($constraints))
{
foreach($constraints as $col => $const)
{
$column_array[$col]['constraint'] = $const;
}
}
// Join column definitons together
$columns = array();
foreach($column_array as $n => $props)
{
$str = "{$n} ";
$str .= (isset($props['type'])) ? "{$props['type']} " : "";
$str .= (isset($props['constraint'])) ? $props['constraint'] : "";
$columns[] = $str;
}
// Generate the sql for the creation of the table
$sql = "CREATE TABLE \"{$name}\" (";
$sql .= implode(", ", $columns);
$sql .= ")";
return $sql;
}
// --------------------------------------------------------------------------
/**
* Database-specific SQL for dropping a table
*
* @param string $name
* @return string
*/
public function delete_table($name)
{
return 'DROP TABLE "'.$name.'"';
}
// --------------------------------------------------------------------------
/**
* 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_util.php

View File

@ -30,9 +30,6 @@ class SQLite extends DB_PDO {
{
// DSN is simply `sqlite:/path/to/db`
parent::__construct("sqlite:{$dsn}", $user, $pass);
$class = __CLASS__."_sql";
$this->sql = new $class;
}
// --------------------------------------------------------------------------

View File

@ -17,78 +17,6 @@
*/
class SQLite_SQL extends DB_SQL {
/**
* Convenience public function to create a new table
*
* @param string $name //Name of the table
* @param array $columns //columns as straight array and/or column => type pairs
* @param array $constraints // column => constraint pairs
* @param array $indexes // column => index pairs
* @return string
*/
public function create_table($name, $columns, array $constraints=array(), array $indexes=array())
{
$column_array = array();
// Reorganize into an array indexed with column information
// Eg $column_array[$colname] = array(
// 'type' => ...,
// 'constraint' => ...,
// 'index' => ...,
// )
foreach($columns as $colname => $type)
{
if(is_numeric($colname))
{
$colname = $type;
}
$column_array[$colname] = array();
$column_array[$colname]['type'] = ($type !== $colname) ? $type : '';
}
if( ! empty($constraints))
{
foreach($constraints as $col => $const)
{
$column_array[$col]['constraint'] = $const;
}
}
// Join column definitons together
$columns = array();
foreach($column_array as $n => $props)
{
$str = "{$n} ";
$str .= (isset($props['type'])) ? "{$props['type']} " : "";
$str .= (isset($props['constraint'])) ? $props['constraint'] : "";
$columns[] = $str;
}
// Generate the sql for the creation of the table
$sql = "CREATE TABLE IF NOT EXISTS \"{$name}\" (";
$sql .= implode(", ", $columns);
$sql .= ")";
return $sql;
}
// --------------------------------------------------------------------------
/**
* SQL to drop the specified table
*
* @param string $name
* @return string
*/
public function delete_table($name)
{
return 'DROP TABLE IF EXISTS "'.$name.'"';
}
// --------------------------------------------------------------------------
/**
* Limit clause
*
@ -121,97 +49,6 @@ class SQLite_SQL extends DB_SQL {
// --------------------------------------------------------------------------
/**
* 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
*

View File

@ -0,0 +1,188 @@
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
* @author Timothy J. Warren
* @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/Query
* @license http://philsturgeon.co.uk/code/dbad-license
*/
// --------------------------------------------------------------------------
/**
* SQLite-specific backup, import and creation methods
*/
class SQLite_Util extends DB_Util {
public function __construct(&$conn)
{
parent::__construct($conn);
}
// --------------------------------------------------------------------------
/**
* Convenience public function to create a new table
*
* @param string $name //Name of the table
* @param array $columns //columns as straight array and/or column => type pairs
* @param array $constraints // column => constraint pairs
* @param array $indexes // column => index pairs
* @return string
*/
public function create_table($name, $columns, array $constraints=array(), array $indexes=array())
{
$column_array = array();
// Reorganize into an array indexed with column information
// Eg $column_array[$colname] = array(
// 'type' => ...,
// 'constraint' => ...,
// 'index' => ...,
// )
foreach($columns as $colname => $type)
{
if(is_numeric($colname))
{
$colname = $type;
}
$column_array[$colname] = array();
$column_array[$colname]['type'] = ($type !== $colname) ? $type : '';
}
if( ! empty($constraints))
{
foreach($constraints as $col => $const)
{
$column_array[$col]['constraint'] = $const;
}
}
// Join column definitons together
$columns = array();
foreach($column_array as $n => $props)
{
$str = "{$n} ";
$str .= (isset($props['type'])) ? "{$props['type']} " : "";
$str .= (isset($props['constraint'])) ? $props['constraint'] : "";
$columns[] = $str;
}
// Generate the sql for the creation of the table
$sql = "CREATE TABLE IF NOT EXISTS \"{$name}\" (";
$sql .= implode(", ", $columns);
$sql .= ")";
return $sql;
}
// --------------------------------------------------------------------------
/**
* SQL to drop the specified table
*
* @param string $name
* @return string
*/
public function delete_table($name)
{
return 'DROP TABLE IF EXISTS "'.$name.'"';
}
// --------------------------------------------------------------------------
/**
* 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;
}
}
// End of sqlite_util.php

View File

@ -52,7 +52,7 @@ class MySQLTest extends DBTest {
if (empty($this->db)) return;
//Attempt to create the table
$sql = $this->db->sql->create_table('create_test',
$sql = $this->db->util->create_table('create_test',
array(
'id' => 'int(10)',
'key' => 'TEXT',
@ -66,7 +66,7 @@ class MySQLTest extends DBTest {
$this->db->query($sql);
//Attempt to create the table
$sql = $this->db->sql->create_table('create_join',
$sql = $this->db->util->create_table('create_join',
array(
'id' => 'int(10)',
'key' => 'TEXT',

View File

@ -64,7 +64,7 @@ class PgTest extends DBTest {
//Attempt to create the table
$sql = $this->db->sql->create_table('create_test',
$sql = $this->db->util->create_table('create_test',
array(
'id' => 'integer',
'key' => 'TEXT',
@ -78,7 +78,7 @@ class PgTest extends DBTest {
$this->db->query($sql);
//Attempt to create the table
$sql = $this->db->sql->create_table('create_join',
$sql = $this->db->util->create_table('create_join',
array(
'id' => 'integer',
'key' => 'TEXT',

View File

@ -62,7 +62,7 @@ class SQLiteTest extends UnitTestCase {
function TestCreateTable()
{
//Attempt to create the table
$sql = $this->db->sql->create_table('create_test',
$sql = $this->db->util->create_table('create_test',
array(
'id' => 'INTEGER',
'key' => 'TEXT',
@ -75,7 +75,7 @@ class SQLiteTest extends UnitTestCase {
$this->db->query($sql);
//Attempt to create the table
$sql = $this->db->sql->create_table('create_join',
$sql = $this->db->util->create_table('create_join',
array(
'id' => 'INTEGER',
'key' => 'TEXT',

Binary file not shown.