Normalize database table listing

This commit is contained in:
Timothy Warren 2012-04-02 10:23:27 -04:00
parent 59e167c064
commit fdc37f8819
5 changed files with 126 additions and 106 deletions

View File

@ -7,7 +7,7 @@
* @author Timothy J. Warren * @author Timothy J. Warren
* @copyright Copyright (c) 2012 * @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/OpenSQLManager * @link https://github.com/aviat4ion/OpenSQLManager
* @license http://philsturgeon.co.uk/code/dbad-license * @license http://philsturgeon.co.uk/code/dbad-license
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -21,7 +21,7 @@ class pgSQL extends DB_PDO {
/** /**
* Connect to a PosgreSQL database * Connect to a PosgreSQL database
* *
* @param string $dsn * @param string $dsn
* @param string $username=null * @param string $username=null
* @param string $password=null * @param string $password=null
@ -35,7 +35,7 @@ class pgSQL extends DB_PDO {
$class = __CLASS__.'_sql'; $class = __CLASS__.'_sql';
$this->sql = new $class; $this->sql = new $class;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/** /**
@ -46,21 +46,21 @@ class pgSQL extends DB_PDO {
public function truncate($table) public function truncate($table)
{ {
$sql = 'TRUNCATE "' . $table . '"'; $sql = 'TRUNCATE "' . $table . '"';
$this->query($sql); $this->query($sql);
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/** /**
* Get list of databases for the current connection * Get list of databases for the current connection
* *
* @return array * @return array
*/ */
public function get_dbs() public function get_dbs()
{ {
$sql = <<<SQL $sql = <<<SQL
SELECT "datname" FROM "pg_database" SELECT "datname" FROM "pg_database"
WHERE "datname" NOT IN ('template0','template1') WHERE "datname" NOT IN ('template0','template1')
ORDER BY 1 ORDER BY 1
SQL; SQL;
@ -70,28 +70,28 @@ SQL;
return $dbs; return $dbs;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/** /**
* Get the list of tables for the current db * Get the list of tables for the current db
* *
* @return array * @return array
*/ */
public function get_tables() public function get_tables()
{ {
$sql = <<<SQL $sql = <<<SQL
SELECT "tablename" FROM "pg_tables" SELECT "tablename" FROM "pg_tables"
WHERE "tablename" NOT LIKE 'pg\_%' WHERE "tablename" NOT LIKE 'pg_%'
AND "tablename" NOT LIKE 'sql\%' AND "tablename" NOT LIKE 'sql_%'
SQL; SQL;
$res = $this->query($sql); $res = $this->query($sql);
$tables = $res->fetchAll(PDO::FETCH_ASSOC); $tables = $res->fetchAll(PDO::FETCH_ASSOC);
$good_tables = array(); $good_tables = array();
foreach($tables as $t) foreach($tables as $t)
{ {
$good_tables[] = $t['tablename']; $good_tables[] = $t['tablename'];
@ -99,12 +99,12 @@ SQL;
return $good_tables; return $good_tables;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/** /**
* Get the list of system tables * Get the list of system tables
* *
* @return array * @return array
*/ */
public function get_system_tables() public function get_system_tables()
@ -114,21 +114,21 @@ SQL;
WHERE "tablename" LIKE 'pg\_%' WHERE "tablename" LIKE 'pg\_%'
OR "tablename" LIKE 'sql\%' OR "tablename" LIKE 'sql\%'
SQL; SQL;
$res = $this->query($sql); $res = $this->query($sql);
$tables = $res->fetchAll(PDO::FETCH_ASSOC); $tables = $res->fetchAll(PDO::FETCH_ASSOC);
return $tables; return $tables;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/** /**
* Get a list of schemas, either for the current connection, or * Get a list of schemas, either for the current connection, or
* for the current datbase, if specified. * for the current datbase, if specified.
* *
* @param string $database="" * @param string $database=""
* @return array * @return array
*/ */
@ -137,7 +137,7 @@ SQL;
if($database === "") if($database === "")
{ {
$sql = <<<SQL $sql = <<<SQL
SELECT DISTINCT "schemaname" FROM "pg_tables" SELECT DISTINCT "schemaname" FROM "pg_tables"
WHERE "schemaname" NOT LIKE 'pg\_%' WHERE "schemaname" NOT LIKE 'pg\_%'
SQL; SQL;
@ -153,18 +153,18 @@ SQL;
return $schemas; return $schemas;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/** /**
* Get a list of views for the current db * Get a list of views for the current db
* *
* @return array * @return array
*/ */
public function get_views() public function get_views()
{ {
$sql = <<<SQL $sql = <<<SQL
SELECT "viewname" FROM "pg_views" SELECT "viewname" FROM "pg_views"
WHERE "viewname" NOT LIKE 'pg\_%'; WHERE "viewname" NOT LIKE 'pg\_%';
SQL; SQL;
@ -174,21 +174,21 @@ SQL;
return $views; return $views;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/** /**
* Return the number of rows returned for a SELECT query * Return the number of rows returned for a SELECT query
* *
* @return int * @return int
*/ */
public function num_rows() public function num_rows()
{ {
return (isset($this->statement)) ? $this->statement->rowCount : FALSE; return (isset($this->statement)) ? $this->statement->rowCount : FALSE;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/** /**
* Create an SQL backup file for the current database's structure * Create an SQL backup file for the current database's structure
* *
@ -197,11 +197,11 @@ SQL;
public function backup_structure() public function backup_structure()
{ {
// @todo Implement Backup function // @todo Implement Backup function
return ''; return '';
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/** /**
* Create an SQL backup file for the current database's data * Create an SQL backup file for the current database's data
* *

View File

@ -7,13 +7,13 @@
* @author Timothy J. Warren * @author Timothy J. Warren
* @copyright Copyright (c) 2012 * @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/OpenSQLManager * @link https://github.com/aviat4ion/OpenSQLManager
* @license http://philsturgeon.co.uk/code/dbad-license * @license http://philsturgeon.co.uk/code/dbad-license
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/** /**
* SQLite specific class * SQLite specific class
* *
* @extends DB_PDO * @extends DB_PDO
*/ */
@ -23,8 +23,8 @@ class SQLite extends DB_PDO {
/** /**
* Open SQLite Database * Open SQLite Database
* *
* @param string $dsn * @param string $dsn
*/ */
public function __construct($dsn, $user=NULL, $pass=NULL) public function __construct($dsn, $user=NULL, $pass=NULL)
{ {
@ -34,7 +34,7 @@ class SQLite extends DB_PDO {
$class = __CLASS__."_sql"; $class = __CLASS__."_sql";
$this->sql = new $class; $this->sql = new $class;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/** /**
@ -49,42 +49,42 @@ class SQLite extends DB_PDO {
$sql = 'DELETE FROM "'.$table.'"'; $sql = 'DELETE FROM "'.$table.'"';
$this->statement = $this->query($sql); $this->statement = $this->query($sql);
return $this->statement; return $this->statement;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/** /**
* List tables for the current database * List tables for the current database
* *
* @return mixed * @return mixed
*/ */
public function get_tables() public function get_tables()
{ {
$tables = array(); $tables = array();
$sql = <<<SQL $sql = <<<SQL
SELECT "name", "sql" SELECT "name", "sql"
FROM "sqlite_master" FROM "sqlite_master"
WHERE "type"='table' WHERE "type"='table'
SQL; SQL;
$res = $this->query($sql); $res = $this->query($sql);
$result = $res->fetchAll(PDO::FETCH_ASSOC); $result = $res->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $r) foreach($result as $r)
{ {
$tables[$r['name']] = $r['sql']; $tables[] = $r['name'];
} }
return $tables; return $tables;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/** /**
* List system tables for the current database * List system tables for the current database
* *
* @return array * @return array
*/ */
public function get_system_tables() public function get_system_tables()
@ -93,53 +93,53 @@ SQL;
// that is of any importance. // that is of any importance.
return array('sqlite_master'); return array('sqlite_master');
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/** /**
* Load a database for the current connection * Load a database for the current connection
* *
* @param string $db * @param string $db
* @param string $name * @param string $name
*/ */
public function load_database($db, $name) public function load_database($db, $name)
{ {
$sql = 'ATTACH DATABASE "'.$db.'" AS "'.$name.'"'; $sql = 'ATTACH DATABASE "'.$db.'" AS "'.$name.'"';
$this->query($sql); $this->query($sql);
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/** /**
* Unload a database from the current connection * Unload a database from the current connection
* *
* @param string $name * @param string $name
*/ */
public function unload_database($name) public function unload_database($name)
{ {
$sql = 'DETACH DATABASE ":name"'; $sql = 'DETACH DATABASE ":name"';
$this->prepare_query($sql, array( $this->prepare_query($sql, array(
':name' => $name, ':name' => $name,
)); ));
$this->statement->execute(); $this->statement->execute();
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/** /**
* Return the number of rows returned for a SELECT query * Return the number of rows returned for a SELECT query
* *
* @return int * @return int
*/ */
public function num_rows() public function num_rows()
{ {
return (isset($this->statement)) ? $this->statement->rowCount : FALSE; return (isset($this->statement)) ? $this->statement->rowCount : FALSE;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/** /**
* Create an SQL backup file for the current database's structure * Create an SQL backup file for the current database's structure
* *
@ -160,12 +160,12 @@ SQL;
} }
$sql_structure = implode("\n\n", $sql_array); $sql_structure = implode("\n\n", $sql_array);
return $sql_structure; return $sql_structure;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/** /**
* Create an SQL backup file for the current database's data * Create an SQL backup file for the current database's data
* *
@ -184,48 +184,48 @@ SQL;
$res = $this->query($sql); $res = $this->query($sql);
$result = $res->fetchAll(PDO::FETCH_ASSOC); $result = $res->fetchAll(PDO::FETCH_ASSOC);
unset($res); unset($res);
$output_sql = ''; $output_sql = '';
// Get the data for each object // Get the data for each object
foreach($result as $r) foreach($result as $r)
{ {
$sql = 'SELECT * FROM "'.$r['name'].'"'; $sql = 'SELECT * FROM "'.$r['name'].'"';
$res = $this->query($sql); $res = $this->query($sql);
$obj_res = $res->fetchAll(PDO::FETCH_ASSOC); $obj_res = $res->fetchAll(PDO::FETCH_ASSOC);
unset($res); unset($res);
// Nab the column names by getting the keys of the first row // Nab the column names by getting the keys of the first row
$columns = array_keys($obj_res[0]); $columns = array_keys($obj_res[0]);
$insert_rows = array(); $insert_rows = array();
// Create the insert statements // Create the insert statements
foreach($obj_res as $row) foreach($obj_res as $row)
{ {
$row = array_values($row); $row = array_values($row);
// Quote values as needed by type // Quote values as needed by type
for($i=0, $icount=count($row); $i<$icount; $i++) for($i=0, $icount=count($row); $i<$icount; $i++)
{ {
$row[$i] = (is_numeric($row[$i])) ? $row[$i] : $this->quote($row[$i]); $row[$i] = (is_numeric($row[$i])) ? $row[$i] : $this->quote($row[$i]);
} }
$row_string = 'INSERT INTO "'.$r['name'].'" ("'.implode('","', $columns).'") VALUES ('.implode(',', $row).');'; $row_string = 'INSERT INTO "'.$r['name'].'" ("'.implode('","', $columns).'") VALUES ('.implode(',', $row).');';
unset($row); unset($row);
$insert_rows[] = $row_string; $insert_rows[] = $row_string;
} }
unset($obj_res); unset($obj_res);
$output_sql .= "\n\n".implode("\n", $insert_rows); $output_sql .= "\n\n".implode("\n", $insert_rows);
} }
return $output_sql; return $output_sql;
} }
} }

View File

@ -80,7 +80,7 @@ class Query_Builder {
switch($dbtype) switch($dbtype)
{ {
default: default:
$dsn = "host={$params->host};dbname={$params->database}"; $dsn = "host={$params->host};dbname={$params->conn_db}";
if ( ! empty($params->port)) if ( ! empty($params->port))
{ {

View File

@ -116,6 +116,10 @@ class Connection_Sidebar extends GtkVBox {
// Label column // Label column
$cell_renderer = new GtkCellRendererText(); $cell_renderer = new GtkCellRendererText();
$this->treeview->insert_column_with_data_func(1, 'Connection name', $cell_renderer, array($this, 'set_label')); $this->treeview->insert_column_with_data_func(1, 'Connection name', $cell_renderer, array($this, 'set_label'));
// Status column
$cell_renderer = new GtkCellRendererPixbuf();
$this->treeview->insert_column_with_data_func(2, 'Status', $cell_renderer, array($this, 'set_status_icon'));
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -166,6 +170,21 @@ class Connection_Sidebar extends GtkVBox {
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/**
* Sets the status icon of the current db connection
*
* @param GtkTreeViewColumn $col
* @param GtkCellRenderer $cell
* @param GtkTreeModel $model
* @param GtkTreeIter $iter
*/
public function set_status_icon($col, $cell, $model, $iter)
{
}
// --------------------------------------------------------------------------
/** /**
* Returns window for creating a new database connection * Returns window for creating a new database connection
* *

View File

@ -7,29 +7,29 @@
* @author Timothy J. Warren * @author Timothy J. Warren
* @copyright Copyright (c) 2012 * @copyright Copyright (c) 2012
* @link https://github.com/aviat4ion/OpenSQLManager * @link https://github.com/aviat4ion/OpenSQLManager
* @license http://philsturgeon.co.uk/code/dbad-license * @license http://philsturgeon.co.uk/code/dbad-license
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/** /**
* SQLiteTest class. * SQLiteTest class.
* *
* @extends UnitTestCase * @extends UnitTestCase
*/ */
class SQLiteTest extends UnitTestCase { class SQLiteTest extends UnitTestCase {
function __construct() function __construct()
{ {
parent::__construct(); parent::__construct();
} }
function setUp() function setUp()
{ {
$path = TEST_DIR.DS.'test_dbs'.DS.'test_sqlite.db'; $path = TEST_DIR.DS.'test_dbs'.DS.'test_sqlite.db';
$this->db = new SQLite($path); $this->db = new SQLite($path);
} }
function tearDown() function tearDown()
{ {
unset($this->db); unset($this->db);
@ -39,20 +39,20 @@ class SQLiteTest extends UnitTestCase {
{ {
$this->assertIsA($this->db, 'SQLite'); $this->assertIsA($this->db, 'SQLite');
} }
function TestGetTables() function TestGetTables()
{ {
$tables = $this->db->get_tables(); $tables = $this->db->get_tables();
$this->assertTrue(is_array($tables)); $this->assertTrue(is_array($tables));
} }
function TestGetSystemTables() function TestGetSystemTables()
{ {
$tables = $this->db->get_system_tables(); $tables = $this->db->get_system_tables();
$this->assertTrue(is_array($tables)); $this->assertTrue(is_array($tables));
} }
function TestCreateTransaction() function TestCreateTransaction()
{ {
$res = $this->db->beginTransaction(); $res = $this->db->beginTransaction();
@ -62,25 +62,25 @@ class SQLiteTest extends UnitTestCase {
function TestCreateTable() function TestCreateTable()
{ {
//Attempt to create the table //Attempt to create the table
$sql = $this->db->sql->create_table('create_test', $sql = $this->db->sql->create_table('create_test',
array( array(
'id' => 'INTEGER', 'id' => 'INTEGER',
'key' => 'TEXT', 'key' => 'TEXT',
'val' => 'TEXT', 'val' => 'TEXT',
), ),
array( array(
'id' => 'PRIMARY KEY' 'id' => 'PRIMARY KEY'
) )
); );
$this->db->query($sql); $this->db->query($sql);
//Attempt to create the table //Attempt to create the table
$sql = $this->db->sql->create_table('create_join', $sql = $this->db->sql->create_table('create_join',
array( array(
'id' => 'INTEGER', 'id' => 'INTEGER',
'key' => 'TEXT', 'key' => 'TEXT',
'val' => 'TEXT', 'val' => 'TEXT',
), ),
array( array(
'id' => 'PRIMARY KEY' 'id' => 'PRIMARY KEY'
) )
@ -89,61 +89,62 @@ class SQLiteTest extends UnitTestCase {
//Check //Check
$dbs = $this->db->get_tables(); $dbs = $this->db->get_tables();
$this->assertEqual($dbs['create_test'], 'CREATE TABLE "create_test" (id INTEGER PRIMARY KEY, key TEXT , val TEXT )');
$this->assertTrue(in_array('create_test', $dbs));
} }
function TestTruncate() function TestTruncate()
{ {
$this->db->truncate('create_test'); $this->db->truncate('create_test');
$this->assertIsA($this->db->affected_rows(), 'int'); $this->assertIsA($this->db->affected_rows(), 'int');
} }
function TestPreparedStatements() function TestPreparedStatements()
{ {
$sql = <<<SQL $sql = <<<SQL
INSERT INTO "create_test" ("id", "key", "val") INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?) VALUES (?,?,?)
SQL; SQL;
$statement = $this->db->prepare_query($sql, array(1,"boogers", "Gross")); $statement = $this->db->prepare_query($sql, array(1,"boogers", "Gross"));
$statement->execute(); $statement->execute();
} }
function TestPrepareExecute() function TestPrepareExecute()
{ {
$sql = <<<SQL $sql = <<<SQL
INSERT INTO "create_test" ("id", "key", "val") INSERT INTO "create_test" ("id", "key", "val")
VALUES (?,?,?) VALUES (?,?,?)
SQL; SQL;
$this->db->prepare_execute($sql, array( $this->db->prepare_execute($sql, array(
2, "works", 'also?' 2, "works", 'also?'
)); ));
} }
function TestCommitTransaction() function TestCommitTransaction()
{ {
$res = $this->db->beginTransaction(); $res = $this->db->beginTransaction();
$sql = 'INSERT INTO "create_test" ("id", "key", "val") VALUES (10, 12, 14)'; $sql = 'INSERT INTO "create_test" ("id", "key", "val") VALUES (10, 12, 14)';
$this->db->query($sql); $this->db->query($sql);
$res = $this->db->commit(); $res = $this->db->commit();
$this->assertTrue($res); $this->assertTrue($res);
} }
function TestRollbackTransaction() function TestRollbackTransaction()
{ {
$res = $this->db->beginTransaction(); $res = $this->db->beginTransaction();
$sql = 'INSERT INTO "create_test" ("id", "key", "val") VALUES (182, 96, 43)'; $sql = 'INSERT INTO "create_test" ("id", "key", "val") VALUES (182, 96, 43)';
$this->db->query($sql); $this->db->query($sql);
$res = $this->db->rollback(); $res = $this->db->rollback();
$this->assertTrue($res); $this->assertTrue($res);
} }
// This is really time intensive ! Run only when needed // This is really time intensive ! Run only when needed
/*function TestDeleteTable() /*function TestDeleteTable()
{ {
@ -157,7 +158,7 @@ SQL;
//Check //Check
$dbs = $this->db->get_tables(); $dbs = $this->db->get_tables();
$this->assertFalse(in_array('create_test', $dbs)); $this->assertFalse(in_array('create_test', $dbs));
}*/ }*/
} }