MINOR: transaction functions renamed for consistency, field list lookups now cached for speed improvements

This commit is contained in:
Geoff Munn 2011-01-11 21:17:17 +00:00
parent 99f2cb179e
commit 2bd6e9fb8e

View File

@ -11,44 +11,44 @@
* @subpackage model * @subpackage model
*/ */
class PostgreSQLDatabase extends SS_Database { class PostgreSQLDatabase extends SS_Database {
/** /**
* Connection to the DBMS. * Connection to the DBMS.
* @var resource * @var resource
*/ */
private $dbConn; private $dbConn;
/** /**
* True if we are connected to a database. * True if we are connected to a database.
* @var boolean * @var boolean
*/ */
private $active; private $active;
/** /**
* The name of the database. * The name of the database.
* @var string * @var string
*/ */
private $database; private $database;
/* /*
* This holds the name of the original database * This holds the name of the original database
* So if you switch to another for unit tests, you * So if you switch to another for unit tests, you
* can then switch back in order to drop the temp database * can then switch back in order to drop the temp database
*/ */
private $database_original; private $database_original;
/** /**
* The database schema name. * The database schema name.
* @var string * @var string
*/ */
private $schema; private $schema;
/* /*
* This holds the parameters that the original connection was created with, * This holds the parameters that the original connection was created with,
* so we can switch back to it if necessary (used for unit tests) * so we can switch back to it if necessary (used for unit tests)
*/ */
private $parameters; private $parameters;
/* /*
* These two values describe how T-search will work. * These two values describe how T-search will work.
* You can use either GiST or GIN, and '@@' (gist) or '@@@' (gin) * You can use either GiST or GIN, and '@@' (gist) or '@@@' (gin)
@ -57,46 +57,55 @@ class PostgreSQLDatabase extends SS_Database {
*/ */
public $default_fts_cluster_method='GIN'; public $default_fts_cluster_method='GIN';
public $default_fts_search_method='@@@'; public $default_fts_search_method='@@@';
private $supportsTransactions=true; private $supportsTransactions=true;
/** /**
* Determines whether to check a database exists on the host by * Determines whether to check a database exists on the host by
* querying the 'postgres' database and running createDatabase. * querying the 'postgres' database and running createDatabase.
* *
* Some locked down systems prevent access to the 'postgres' table in * Some locked down systems prevent access to the 'postgres' table in
* which case you need to set this to false. * which case you need to set this to false.
*/ */
public static $check_database_exists = true; public static $check_database_exists = true;
/** /**
* This holds a copy of all the constraint results that are returned * This holds a copy of all the constraint results that are returned
* via the function constraintExists(). This is a bit faster than * via the function constraintExists(). This is a bit faster than
* repeatedly querying this column, and should allow the database * repeatedly querying this column, and should allow the database
* to use it's built-in caching features for better queries. * to use it's built-in caching features for better queries.
* *
* @var array * @var array
*/ */
private static $cached_constraints=array(); private static $cached_constraints=array();
/** /**
* *
* This holds a copy of all the queries that run through the function orderMoreSpecifically() * This holds a copy of all the queries that run through the function orderMoreSpecifically()
* It appears to be a performance bottleneck at times. * It appears to be a performance bottleneck at times.
* *
* @var array * @var array
*/ */
private static $cached_ordered_specifically=array(); private static $cached_ordered_specifically=array();
/**
*
* This holds a copy of all the queries that run through the function fieldList()
* This is one of the most-often called functions, and repeats itself a great deal in the unit tests.
*
* @var array
*/
private static $cached_fieldlists=array();
/** /**
* Override the language that tsearch uses. By default it is 'english, but * Override the language that tsearch uses. By default it is 'english, but
* could be any of the supported languages that can be found in the * could be any of the supported languages that can be found in the
* pg_catalog.pg_ts_config table. * pg_catalog.pg_ts_config table.
* *
* @var string * @var string
*/ */
private $search_language='english'; private $search_language='english';
/** /**
* Connect to a PostgreSQL database. * Connect to a PostgreSQL database.
* @param array $parameters An map of parameters, which should include: * @param array $parameters An map of parameters, which should include:
@ -106,64 +115,64 @@ class PostgreSQLDatabase extends SS_Database {
* - database: The database to connect to * - database: The database to connect to
*/ */
public function __construct($parameters) { public function __construct($parameters) {
//We will store these connection parameters for use elsewhere (ie, unit tests) //We will store these connection parameters for use elsewhere (ie, unit tests)
$this->parameters=$parameters; $this->parameters=$parameters;
$this->connectDatabase(); $this->connectDatabase();
$this->database_original=$this->database; $this->database_original=$this->database;
} }
/* /*
* Uses whatever connection details are in the $parameters array to connect to a database of a given name * Uses whatever connection details are in the $parameters array to connect to a database of a given name
*/ */
function connectDatabase(){ function connectDatabase(){
$parameters=$this->parameters; $parameters=$this->parameters;
if(!$parameters) if(!$parameters)
return false; return false;
($parameters['username']!='') ? $username=' user=' . $parameters['username'] : $username=''; ($parameters['username']!='') ? $username=' user=' . $parameters['username'] : $username='';
($parameters['password']!='') ? $password=' password=' . $parameters['password'] : $password=''; ($parameters['password']!='') ? $password=' password=' . $parameters['password'] : $password='';
if(!isset($this->database)) if(!isset($this->database))
$dbName=$parameters['database']; $dbName=$parameters['database'];
else $dbName=$this->database; else $dbName=$this->database;
$port = empty($parameters['port']) ? 5432 : $parameters['port']; $port = empty($parameters['port']) ? 5432 : $parameters['port'];
// First, we need to check that this database exists. To do this, we will connect to the 'postgres' database first // First, we need to check that this database exists. To do this, we will connect to the 'postgres' database first
// some setups prevent access to this database so set PostgreSQLDatabase::$check_database_exists = false // some setups prevent access to this database so set PostgreSQLDatabase::$check_database_exists = false
if(self::$check_database_exists) { if(self::$check_database_exists) {
$this->dbConn = pg_connect('host=' . $parameters['server'] . ' port=' . $port . ' dbname=postgres' . $username . $password); $this->dbConn = pg_connect('host=' . $parameters['server'] . ' port=' . $port . ' dbname=postgres' . $username . $password);
if(!$this->databaseExists($dbName)) if(!$this->databaseExists($dbName))
$this->createDatabase($dbName); $this->createDatabase($dbName);
} }
//Now we can be sure that this database exists, so we can connect to it //Now we can be sure that this database exists, so we can connect to it
$this->dbConn = pg_connect('host=' . $parameters['server'] . ' port=' . $port . ' dbname=' . $dbName . $username . $password); $this->dbConn = pg_connect('host=' . $parameters['server'] . ' port=' . $port . ' dbname=' . $dbName . $username . $password);
//By virtue of getting here, the connection is active: //By virtue of getting here, the connection is active:
$this->active=true; $this->active=true;
$this->database = $dbName; $this->database = $dbName;
if(!$this->dbConn) { if(!$this->dbConn) {
$this->databaseError("Couldn't connect to PostgreSQL database"); $this->databaseError("Couldn't connect to PostgreSQL database");
return false; return false;
} }
// Set up the schema if required // Set up the schema if required
$schema = isset($parameters['schema']) ? $parameters['schema'] : $this->currentSchema(); $schema = isset($parameters['schema']) ? $parameters['schema'] : $this->currentSchema();
// Edge-case - database with no schemas: // Edge-case - database with no schemas:
if(!$schema) $schema = "public"; if(!$schema) $schema = "public";
if(!$this->schemaExists($schema)) if(!$this->schemaExists($schema))
$this->createSchema($schema); $this->createSchema($schema);
$this->setSchema($schema); $this->setSchema($schema);
return true; return true;
} }
/** /**
@ -172,14 +181,14 @@ class PostgreSQLDatabase extends SS_Database {
public function getConnect($parameters) { public function getConnect($parameters) {
return null; return null;
} }
/** /**
* Return the parameters used to construct this database connection * Return the parameters used to construct this database connection
*/ */
public function getParameters() { public function getParameters() {
return $this->parameters; return $this->parameters;
} }
/** /**
* Returns true if this database supports collations * Returns true if this database supports collations
* TODO: get rid of this? * TODO: get rid of this?
@ -188,7 +197,7 @@ class PostgreSQLDatabase extends SS_Database {
public function supportsCollations() { public function supportsCollations() {
return true; return true;
} }
/** /**
* Get the version of PostgreSQL. * Get the version of PostgreSQL.
* @return string * @return string
@ -198,7 +207,7 @@ class PostgreSQLDatabase extends SS_Database {
if(isset($version['server'])) return $version['server']; if(isset($version['server'])) return $version['server'];
else return false; else return false;
} }
/** /**
* Get the database server, namely PostgreSQL. * Get the database server, namely PostgreSQL.
* @return string * @return string
@ -206,41 +215,41 @@ class PostgreSQLDatabase extends SS_Database {
public function getDatabaseServer() { public function getDatabaseServer() {
return "postgresql"; return "postgresql";
} }
public function query($sql, $errorLevel = E_USER_ERROR) { public function query($sql, $errorLevel = E_USER_ERROR) {
if(isset($_REQUEST['previewwrite']) && in_array(strtolower(substr($sql,0,strpos($sql,' '))), array('insert','update','delete','replace'))) { if(isset($_REQUEST['previewwrite']) && in_array(strtolower(substr($sql,0,strpos($sql,' '))), array('insert','update','delete','replace'))) {
Debug::message("Will execute: $sql"); Debug::message("Will execute: $sql");
return; return;
} }
if(isset($_REQUEST['showqueries'])) { if(isset($_REQUEST['showqueries'])) {
$starttime = microtime(true); $starttime = microtime(true);
} }
$handle = pg_query($this->dbConn, $sql); $handle = pg_query($this->dbConn, $sql);
if(isset($_REQUEST['showqueries'])) { if(isset($_REQUEST['showqueries'])) {
$endtime = round(microtime(true) - $starttime * 1000, 1); $endtime = round(microtime(true) - $starttime * 1000, 1);
Debug::message("\n$sql\n{$endtime}ms\n", false); Debug::message("\n$sql\n{$endtime}ms\n", false);
} }
DB::$lastQuery=$handle; DB::$lastQuery=$handle;
if(!$handle && $errorLevel) $this->databaseError("Couldn't run query: $sql | " . pg_last_error($this->dbConn), $errorLevel); if(!$handle && $errorLevel) $this->databaseError("Couldn't run query: $sql | " . pg_last_error($this->dbConn), $errorLevel);
return new PostgreSQLQuery($this, $handle); return new PostgreSQLQuery($this, $handle);
} }
public function getGeneratedID($table) { public function getGeneratedID($table) {
$result=DB::query("SELECT last_value FROM \"{$table}_ID_seq\";"); $result=DB::query("SELECT last_value FROM \"{$table}_ID_seq\";");
$row=$result->first(); $row=$result->first();
return $row['last_value']; return $row['last_value'];
} }
/** /**
* OBSOLETE: Get the ID for the next new record for the table. * OBSOLETE: Get the ID for the next new record for the table.
* *
* @var string $table The name od the table. * @var string $table The name od the table.
* @return int * @return int
*/ */
@ -249,22 +258,22 @@ class PostgreSQLDatabase extends SS_Database {
$result = $this->query("SELECT MAX(ID)+1 FROM \"$table\"")->value(); $result = $this->query("SELECT MAX(ID)+1 FROM \"$table\"")->value();
return $result ? $result : 1; return $result ? $result : 1;
} }
public function isActive() { public function isActive() {
return $this->active ? true : false; return $this->active ? true : false;
} }
/* /*
* You can create a database based either on a supplied name, or from whatever is in the $this->database value * You can create a database based either on a supplied name, or from whatever is in the $this->database value
*/ */
public function createDatabase($name=false) { public function createDatabase($name=false) {
if(!$name) if(!$name)
$name=$this->database; $name=$this->database;
$this->query("CREATE DATABASE \"$name\";"); $this->query("CREATE DATABASE \"$name\";");
$this->connectDatabase(); $this->connectDatabase();
} }
/** /**
@ -272,15 +281,15 @@ class PostgreSQLDatabase extends SS_Database {
* Use with caution. * Use with caution.
*/ */
public function dropDatabase() { public function dropDatabase() {
//First, we need to switch back to the original database so we can drop the current one //First, we need to switch back to the original database so we can drop the current one
$db_to_drop=$this->database; $db_to_drop=$this->database;
$this->selectDatabase($this->database_original); $this->selectDatabase($this->database_original);
$this->connectDatabase(); $this->connectDatabase();
$this->query("DROP DATABASE $db_to_drop"); $this->query("DROP DATABASE \"$db_to_drop\"");
} }
/** /**
* Drop the database that this object is currently connected to. * Drop the database that this object is currently connected to.
* Use with caution. * Use with caution.
@ -289,127 +298,127 @@ class PostgreSQLDatabase extends SS_Database {
if($dbName!=$this->database) if($dbName!=$this->database)
$this->query("DROP DATABASE \"$dbName\";"); $this->query("DROP DATABASE \"$dbName\";");
} }
/** /**
* Returns the name of the currently selected database * Returns the name of the currently selected database
*/ */
public function currentDatabase() { public function currentDatabase() {
return $this->database; return $this->database;
} }
/** /**
* Switches to the given database. * Switches to the given database.
* If the database doesn't exist, you should call createDatabase() after calling selectDatabase() * If the database doesn't exist, you should call createDatabase() after calling selectDatabase()
*/ */
public function selectDatabase($dbname) { public function selectDatabase($dbname) {
$this->database=$dbname; $this->database=$dbname;
$this->tableList = $this->fieldList = $this->indexList = null; $this->tableList = $this->fieldList = $this->indexList = null;
return true; return true;
} }
/** /**
* Returns true if the named database exists. * Returns true if the named database exists.
*/ */
public function databaseExists($name) { public function databaseExists($name) {
// We have to use addslashes here, since there may not be a database connection to base the Convert::raw2sql // We have to use addslashes here, since there may not be a database connection to base the Convert::raw2sql
// function off. // function off.
$SQL_name=addslashes($name); $SQL_name=addslashes($name);
return $this->query("SELECT datname FROM pg_database WHERE datname='$SQL_name';")->first() ? true : false; return $this->query("SELECT datname FROM pg_database WHERE datname='$SQL_name';")->first() ? true : false;
} }
/** /**
* Returns a column * Returns a column
*/ */
public function allDatabaseNames() { public function allDatabaseNames() {
return $this->query("SELECT datname FROM pg_database WHERE datistemplate=false;")->column(); return $this->query("SELECT datname FROM pg_database WHERE datistemplate=false;")->column();
} }
/** /**
* Returns true if the schema exists in the current database * Returns true if the schema exists in the current database
* @param string $name * @param string $name
* @return boolean * @return boolean
*/ */
public function schemaExists($name) { public function schemaExists($name) {
$SQL_name = pg_escape_string($this->dbConn, $name); $SQL_name = pg_escape_string($this->dbConn, $name);
return $this->query("SELECT nspname FROM pg_catalog.pg_namespace WHERE nspname = '{$SQL_name}';")->first() ? true : false; return $this->query("SELECT nspname FROM pg_catalog.pg_namespace WHERE nspname = '{$SQL_name}';")->first() ? true : false;
} }
/** /**
* Creates a schema in the current database * Creates a schema in the current database
* @param string $name * @param string $name
*/ */
public function createSchema($name) { public function createSchema($name) {
$SQL_name = pg_escape_string($this->dbConn, $name); $SQL_name = pg_escape_string($this->dbConn, $name);
$this->query("CREATE SCHEMA \"{$SQL_name}\";"); $this->query("CREATE SCHEMA \"{$SQL_name}\";");
} }
/** /**
* Drops a schema from the database. Use carefully! * Drops a schema from the database. Use carefully!
* @param string $name * @param string $name
*/ */
public function dropSchema($name) { public function dropSchema($name) {
$SQL_name = pg_escape_string($this->dbConn, $name); $SQL_name = pg_escape_string($this->dbConn, $name);
$this->query("DROP SCHEMA \"{$SQL_name}\" CASCADE;"); $this->query("DROP SCHEMA \"{$SQL_name}\" CASCADE;");
} }
/** /**
* Returns the name of the current schema in use * Returns the name of the current schema in use
*/ */
public function currentSchema() { public function currentSchema() {
return $this->query('SELECT current_schema()')->value(); return $this->query('SELECT current_schema()')->value();
} }
/** /**
* Utility method to manually set the schema to an alternative * Utility method to manually set the schema to an alternative
* Check existance & sets search path to the supplied schema name * Check existance & sets search path to the supplied schema name
* @param string $schema * @param string $schema
*/ */
public function setSchema($schema) { public function setSchema($schema) {
if(!$this->schemaExists($schema)) if(!$this->schemaExists($schema))
$this->databaseError("Schema $schema does not exist"); $this->databaseError("Schema $schema does not exist");
$this->setSchemaSearchPath($schema); $this->setSchemaSearchPath($schema);
$this->schema = $schema; $this->schema = $schema;
} }
/** /**
* Override the schema search path. Search using the arguments supplied. * Override the schema search path. Search using the arguments supplied.
* NOTE: The search path is normally set through setSchema() and only * NOTE: The search path is normally set through setSchema() and only
* one schema is selected. The facility to add more than one schema to * one schema is selected. The facility to add more than one schema to
* the search path is provided as an advanced PostgreSQL feature for raw * the search path is provided as an advanced PostgreSQL feature for raw
* SQL queries. Sapphire cannot search for datamodel tables in alternate * SQL queries. Sapphire cannot search for datamodel tables in alternate
* schemas, so be wary of using alternate schemas within the ORM environment. * schemas, so be wary of using alternate schemas within the ORM environment.
* @param string $arg1 First schema to use * @param string $arg1 First schema to use
* @param string $arg2 Second schema to use * @param string $arg2 Second schema to use
* @param string $argN Nth schema to use * @param string $argN Nth schema to use
*/ */
public function setSchemaSearchPath() { public function setSchemaSearchPath() {
if(func_num_args() == 0) if(func_num_args() == 0)
$this->databaseError('At least one Schema must be supplied to set a search path.'); $this->databaseError('At least one Schema must be supplied to set a search path.');
$args = array_values(func_get_args()); $args = array_values(func_get_args());
foreach($args as $key => $schema) foreach($args as $key => $schema)
$args[$key] = '"' . pg_escape_string($this->dbConn, $schema) . '"'; $args[$key] = '"' . pg_escape_string($this->dbConn, $schema) . '"';
$args_SQL =implode(",", $args); $args_SQL =implode(",", $args);
$this->query("SET search_path TO {$args_SQL}"); $this->query("SET search_path TO {$args_SQL}");
} }
public function createTable($tableName, $fields = null, $indexes = null, $options = null, $extensions = null) { public function createTable($tableName, $fields = null, $indexes = null, $options = null, $extensions = null) {
$fieldSchemas = $indexSchemas = ""; $fieldSchemas = $indexSchemas = "";
if($fields) foreach($fields as $k => $v) $fieldSchemas .= "\"$k\" $v,\n"; if($fields) foreach($fields as $k => $v) $fieldSchemas .= "\"$k\" $v,\n";
if(isset($this->class)){ if(isset($this->class)){
$addOptions = (isset($options[$this->class])) ? $options[$this->class] : null; $addOptions = (isset($options[$this->class])) ? $options[$this->class] : null;
} else $addOptions=null; } else $addOptions=null;
//First of all, does this table already exist //First of all, does this table already exist
$doesExist=$this->TableExists($tableName); $doesExist=$this->TableExists($tableName);
if($doesExist) { if($doesExist) {
// Table already exists, just return the name, in line with baseclass documentation. // Table already exists, just return the name, in line with baseclass documentation.
return $tableName; return $tableName;
} }
//If we have a fulltext search request, then we need to create a special column //If we have a fulltext search request, then we need to create a special column
//for GiST searches //for GiST searches
$fulltexts=''; $fulltexts='';
@ -424,35 +433,35 @@ class PostgreSQLDatabase extends SS_Database {
} }
} }
if($indexes) foreach($indexes as $k => $v) $indexSchemas .= $this->getIndexSqlDefinition($tableName, $k, $v) . "\n"; if($indexes) foreach($indexes as $k => $v) $indexSchemas .= $this->getIndexSqlDefinition($tableName, $k, $v) . "\n";
//Do we need to create a tablespace for this item? //Do we need to create a tablespace for this item?
if($extensions && isset($extensions['tablespace'])){ if($extensions && isset($extensions['tablespace'])){
$this->createOrReplaceTablespace($extensions['tablespace']['name'], $extensions['tablespace']['location']); $this->createOrReplaceTablespace($extensions['tablespace']['name'], $extensions['tablespace']['location']);
$tableSpace=' TABLESPACE ' . $extensions['tablespace']['name']; $tableSpace=' TABLESPACE ' . $extensions['tablespace']['name'];
} else } else
$tableSpace=''; $tableSpace='';
$this->query("CREATE TABLE \"$tableName\" ( $this->query("CREATE TABLE \"$tableName\" (
$fieldSchemas $fieldSchemas
$fulltexts $fulltexts
primary key (\"ID\") primary key (\"ID\")
)$tableSpace; $indexSchemas $addOptions"); )$tableSpace; $indexSchemas $addOptions");
if($triggers!=''){ if($triggers!=''){
$this->query($triggers); $this->query($triggers);
} }
//If we have a partitioning requirement, we do that here: //If we have a partitioning requirement, we do that here:
if($extensions && isset($extensions['partitions'])){ if($extensions && isset($extensions['partitions'])){
$this->createOrReplacePartition($tableName, $extensions['partitions'], $indexes, $extensions); $this->createOrReplacePartition($tableName, $extensions['partitions'], $indexes, $extensions);
} }
//Lastly, clustering goes here: //Lastly, clustering goes here:
if($extensions && isset($extensions['cluster'])){ if($extensions && isset($extensions['cluster'])){
DB::query("CLUSTER \"$tableName\" USING \"{$extensions['cluster']}\";"); DB::query("CLUSTER \"$tableName\" USING \"{$extensions['cluster']}\";");
} }
return $tableName; return $tableName;
} }
@ -465,26 +474,26 @@ class PostgreSQLDatabase extends SS_Database {
* @param $alteredIndexes Updated indexes, a map of index name => index type * @param $alteredIndexes Updated indexes, a map of index name => index type
*/ */
public function alterTable($tableName, $newFields = null, $newIndexes = null, $alteredFields = null, $alteredIndexes = null, $alteredOptions = null, $advancedOptions = null) { public function alterTable($tableName, $newFields = null, $newIndexes = null, $alteredFields = null, $alteredIndexes = null, $alteredOptions = null, $advancedOptions = null) {
$fieldSchemas = $indexSchemas = ""; $fieldSchemas = $indexSchemas = "";
$alterList = array(); $alterList = array();
if($newFields) foreach($newFields as $k => $v) $alterList[] .= "ADD \"$k\" $v"; if($newFields) foreach($newFields as $k => $v) $alterList[] .= "ADD \"$k\" $v";
if($alteredFields) { if($alteredFields) {
foreach($alteredFields as $k => $v) { foreach($alteredFields as $k => $v) {
$val=$this->alterTableAlterColumn($tableName, $k, $v); $val=$this->alterTableAlterColumn($tableName, $k, $v);
if($val!='') if($val!='')
$alterList[] .= $val; $alterList[] .= $val;
} }
} }
//Do we need to do anything with the tablespaces? //Do we need to do anything with the tablespaces?
if($alteredOptions && isset($advancedOptions['tablespace'])){ if($alteredOptions && isset($advancedOptions['tablespace'])){
$this->createOrReplaceTablespace($advancedOptions['tablespace']['name'], $advancedOptions['tablespace']['location']); $this->createOrReplaceTablespace($advancedOptions['tablespace']['name'], $advancedOptions['tablespace']['location']);
$this->query("ALTER TABLE \"$tableName\" SET TABLESPACE {$advancedOptions['tablespace']['name']};"); $this->query("ALTER TABLE \"$tableName\" SET TABLESPACE {$advancedOptions['tablespace']['name']};");
} }
//DB ABSTRACTION: we need to change the constraints to be a separate 'add' command, //DB ABSTRACTION: we need to change the constraints to be a separate 'add' command,
//see http://www.postgresql.org/docs/8.1/static/sql-altertable.html //see http://www.postgresql.org/docs/8.1/static/sql-altertable.html
$alterIndexList=Array(); $alterIndexList=Array();
@ -496,23 +505,23 @@ class PostgreSQLDatabase extends SS_Database {
if($alteredIndexes) foreach($alteredIndexes as $key=>$v) { if($alteredIndexes) foreach($alteredIndexes as $key=>$v) {
//We are only going to delete indexes which exist //We are only going to delete indexes which exist
$indexes=$this->indexList($tableName); $indexes=$this->indexList($tableName);
if($v['type']=='fulltext'){ if($v['type']=='fulltext'){
//For full text indexes, we need to drop the trigger, drop the index, AND drop the column //For full text indexes, we need to drop the trigger, drop the index, AND drop the column
//Go and get the tsearch details: //Go and get the tsearch details:
$ts_details=$this->fulltext($v, $tableName, $key); $ts_details=$this->fulltext($v, $tableName, $key);
//Drop this column if it already exists: //Drop this column if it already exists:
//No IF EXISTS option is available for Postgres <9.0 //No IF EXISTS option is available for Postgres <9.0
if(array_key_exists($ts_details['ts_name'], $fieldList)){ if(array_key_exists($ts_details['ts_name'], $fieldList)){
$fulltexts.="ALTER TABLE \"{$tableName}\" DROP COLUMN \"{$ts_details['ts_name']}\";"; $fulltexts.="ALTER TABLE \"{$tableName}\" DROP COLUMN \"{$ts_details['ts_name']}\";";
} }
$drop_triggers.= 'DROP TRIGGER IF EXISTS ts_' . strtolower($tableName) . '_' . strtolower($key) . ' ON "' . $tableName . '";'; $drop_triggers.= 'DROP TRIGGER IF EXISTS ts_' . strtolower($tableName) . '_' . strtolower($key) . ' ON "' . $tableName . '";';
$alterIndexList[] = 'DROP INDEX IF EXISTS ix_' . strtolower($tableName) . '_' . strtolower($v['value']) . ';'; $alterIndexList[] = 'DROP INDEX IF EXISTS ix_' . strtolower($tableName) . '_' . strtolower($v['value']) . ';';
//We'll execute these later: //We'll execute these later:
$fulltexts.="ALTER TABLE \"{$tableName}\" ADD COLUMN {$ts_details['fulltexts']};"; $fulltexts.="ALTER TABLE \"{$tableName}\" ADD COLUMN {$ts_details['fulltexts']};";
$triggers.=$ts_details['triggers']; $triggers.=$ts_details['triggers'];
@ -522,7 +531,7 @@ class PostgreSQLDatabase extends SS_Database {
$alterIndexList[] = 'DROP INDEX IF EXISTS ix_' . strtolower($tableName) . '_' . strtolower($v['value']) . ';'; $alterIndexList[] = 'DROP INDEX IF EXISTS ix_' . strtolower($tableName) . '_' . strtolower($v['value']) . ';';
else else
$alterIndexList[] = 'DROP INDEX IF EXISTS ix_' . strtolower($tableName) . '_' . strtolower(trim($v, '()')) . ';'; $alterIndexList[] = 'DROP INDEX IF EXISTS ix_' . strtolower($tableName) . '_' . strtolower(trim($v, '()')) . ';';
$k=$v['value']; $k=$v['value'];
$createIndex=$this->getIndexSqlDefinition($tableName, $k, $v); $createIndex=$this->getIndexSqlDefinition($tableName, $k, $v);
if($createIndex!==false) if($createIndex!==false)
@ -545,7 +554,7 @@ class PostgreSQLDatabase extends SS_Database {
} }
} }
} }
//Add the new indexes: //Add the new indexes:
if($newIndexes) foreach($newIndexes as $k=>$v){ if($newIndexes) foreach($newIndexes as $k=>$v){
//Check that this index doesn't already exist: //Check that this index doesn't already exist:
@ -562,23 +571,23 @@ class PostgreSQLDatabase extends SS_Database {
$alterIndexList[] = 'DROP INDEX IF EXISTS ' . $indexes[$name]['indexname'] . ';'; $alterIndexList[] = 'DROP INDEX IF EXISTS ' . $indexes[$name]['indexname'] . ';';
} }
} }
$createIndex=$this->getIndexSqlDefinition($tableName, $k, $v); $createIndex=$this->getIndexSqlDefinition($tableName, $k, $v);
if($createIndex!==false) if($createIndex!==false)
$alterIndexList[] = $createIndex; $alterIndexList[] = $createIndex;
} }
if($alterList) { if($alterList) {
$alterations = implode(",\n", $alterList); $alterations = implode(",\n", $alterList);
$this->query("ALTER TABLE \"$tableName\" " . $alterations); $this->query("ALTER TABLE \"$tableName\" " . $alterations);
} }
//Do we need to create a tablespace for this item? //Do we need to create a tablespace for this item?
if($advancedOptions && isset($advancedOptions['extensions']['tablespace'])){ if($advancedOptions && isset($advancedOptions['extensions']['tablespace'])){
$extensions=$advancedOptions['extensions']; $extensions=$advancedOptions['extensions'];
$this->createOrReplaceTablespace($extensions['tablespace']['name'], $extensions['tablespace']['location']); $this->createOrReplaceTablespace($extensions['tablespace']['name'], $extensions['tablespace']['location']);
} }
if($alteredOptions && isset($this->class) && isset($alteredOptions[$this->class])) { if($alteredOptions && isset($this->class) && isset($alteredOptions[$this->class])) {
$this->query(sprintf("ALTER TABLE \"%s\" %s", $tableName, $alteredOptions[$this->class])); $this->query(sprintf("ALTER TABLE \"%s\" %s", $tableName, $alteredOptions[$this->class]));
Database::alteration_message( Database::alteration_message(
@ -586,30 +595,30 @@ class PostgreSQLDatabase extends SS_Database {
"changed" "changed"
); );
} }
//Create any fulltext columns and triggers here: //Create any fulltext columns and triggers here:
if($fulltexts) if($fulltexts)
$this->query($fulltexts); $this->query($fulltexts);
if($drop_triggers) if($drop_triggers)
$this->query($drop_triggers); $this->query($drop_triggers);
if($triggers) { if($triggers) {
$this->query($triggers); $this->query($triggers);
$triggerbits=explode(';', $triggers); $triggerbits=explode(';', $triggers);
foreach($triggerbits as $trigger){ foreach($triggerbits as $trigger){
$trigger_fields=$this->triggerFieldsFromTrigger($trigger); $trigger_fields=$this->triggerFieldsFromTrigger($trigger);
if($trigger_fields){ if($trigger_fields){
//We need to run a simple query to force the database to update the triggered columns //We need to run a simple query to force the database to update the triggered columns
$this->query("UPDATE \"{$tableName}\" SET \"{$trigger_fields[0]}\"=\"$trigger_fields[0]\";"); $this->query("UPDATE \"{$tableName}\" SET \"{$trigger_fields[0]}\"=\"$trigger_fields[0]\";");
} }
} }
} }
foreach($alterIndexList as $alteration) foreach($alterIndexList as $alteration)
$this->query($alteration); $this->query($alteration);
//If we have a partitioning requirement, we do that here: //If we have a partitioning requirement, we do that here:
if($advancedOptions && isset($advancedOptions['partitions'])){ if($advancedOptions && isset($advancedOptions['partitions'])){
$this->createOrReplacePartition($tableName, $advancedOptions['partitions']); $this->createOrReplacePartition($tableName, $advancedOptions['partitions']);
@ -617,27 +626,27 @@ class PostgreSQLDatabase extends SS_Database {
//Lastly, clustering goes here: //Lastly, clustering goes here:
if($advancedOptions && isset($advancedOptions['cluster'])){ if($advancedOptions && isset($advancedOptions['cluster'])){
DB::query("CLUSTER \"$tableName\" USING ix_{$tableName}_{$advancedOptions['cluster']};"); DB::query("CLUSTER \"$tableName\" USING ix_{$tableName}_{$advancedOptions['cluster']};");
} else { } else {
//Check that clustering is not on this table, and if it is, remove it: //Check that clustering is not on this table, and if it is, remove it:
//This is really annoying. We need the oid of this table: //This is really annoying. We need the oid of this table:
$stats=DB::query("SELECT relid FROM pg_stat_user_tables WHERE relname='$tableName';")->first(); $stats=DB::query("SELECT relid FROM pg_stat_user_tables WHERE relname='$tableName';")->first();
$oid=$stats['relid']; $oid=$stats['relid'];
//Now we can run a long query to get the clustered status: //Now we can run a long query to get the clustered status:
//If anyone knows a better way to get the clustered status, then feel free to replace this! //If anyone knows a better way to get the clustered status, then feel free to replace this!
$clustered=DB::query("SELECT c2.relname, i.indisclustered FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i WHERE c.oid = '$oid' AND c.oid = i.indrelid AND i.indexrelid = c2.oid AND indisclustered='t';")->first(); $clustered=DB::query("SELECT c2.relname, i.indisclustered FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i WHERE c.oid = '$oid' AND c.oid = i.indrelid AND i.indexrelid = c2.oid AND indisclustered='t';")->first();
if($clustered) if($clustered)
DB::query("ALTER TABLE \"$tableName\" SET WITHOUT CLUSTER;"); DB::query("ALTER TABLE \"$tableName\" SET WITHOUT CLUSTER;");
} }
} }
/* /*
* Creates an ALTER expression for a column in PostgreSQL * Creates an ALTER expression for a column in PostgreSQL
* *
* @param $tableName Name of the table to be altered * @param $tableName Name of the table to be altered
* @param $colName Name of the column to be altered * @param $colName Name of the column to be altered
* @param $colSpec String which contains conditions for a column * @param $colSpec String which contains conditions for a column
@ -647,27 +656,28 @@ class PostgreSQLDatabase extends SS_Database {
// First, we split the column specifications into parts // First, we split the column specifications into parts
// TODO: this returns an empty array for the following string: int(11) not null auto_increment // TODO: this returns an empty array for the following string: int(11) not null auto_increment
// on second thoughts, why is an auto_increment field being passed through? // on second thoughts, why is an auto_increment field being passed through?
$pattern = '/^([\w()]+)\s?((?:not\s)?null)?\s?(default\s[\w\']+)?\s?(check\s[\w()\'",\s]+)?$/i'; $pattern = '/^([\w()]+)\s?((?:not\s)?null)?\s?(default\s[\w\']+)?\s?(check\s[\w()\'",\s]+)?$/i';
preg_match($pattern, $colSpec, $matches); preg_match($pattern, $colSpec, $matches);
if(sizeof($matches)==0) if(sizeof($matches)==0)
return ''; return '';
if($matches[1]=='serial8') if($matches[1]=='serial8')
return ''; return '';
if(isset($matches[1])) { if(isset($matches[1])) {
$alterCol = "ALTER COLUMN \"$colName\" TYPE $matches[1]\n"; $alterCol = "ALTER COLUMN \"$colName\" TYPE $matches[1]\n";
// SET null / not null // SET null / not null
if(!empty($matches[2])) $alterCol .= ",\nALTER COLUMN \"$colName\" SET $matches[2]"; if(!empty($matches[2])) $alterCol .= ",\nALTER COLUMN \"$colName\" SET $matches[2]";
// SET default (we drop it first, for reasons of precaution) // SET default (we drop it first, for reasons of precaution)
if(!empty($matches[3])) { if(!empty($matches[3])) {
$alterCol .= ",\nALTER COLUMN \"$colName\" DROP DEFAULT"; $alterCol .= ",\nALTER COLUMN \"$colName\" DROP DEFAULT";
$alterCol .= ",\nALTER COLUMN \"$colName\" SET $matches[3]"; $alterCol .= ",\nALTER COLUMN \"$colName\" SET $matches[3]";
} }
// SET check constraint (The constraint HAS to be dropped) // SET check constraint (The constraint HAS to be dropped)
$existing_constraint=$this->query("SELECT conname FROM pg_constraint WHERE conname='{$tableName}_{$colName}_check';")->value(); $existing_constraint=$this->query("SELECT conname FROM pg_constraint WHERE conname='{$tableName}_{$colName}_check';")->value();
if(isset($matches[4])) { if(isset($matches[4])) {
@ -688,23 +698,23 @@ class PostgreSQLDatabase extends SS_Database {
DB::query($updateConstraint); DB::query($updateConstraint);
} }
//First, delete any existing constraint on this column, even if it's no longer an enum //First, delete any existing constraint on this column, even if it's no longer an enum
if($existing_constraint) if($existing_constraint)
$alterCol .= ",\nDROP CONSTRAINT \"{$tableName}_{$colName}_check\""; $alterCol .= ",\nDROP CONSTRAINT \"{$tableName}_{$colName}_check\"";
//Now create the constraint (if we've asked for one) //Now create the constraint (if we've asked for one)
if(!empty($matches[4])) if(!empty($matches[4]))
$alterCol .= ",\nADD CONSTRAINT \"{$tableName}_{$colName}_check\" $matches[4]"; $alterCol .= ",\nADD CONSTRAINT \"{$tableName}_{$colName}_check\" $matches[4]";
} }
return isset($alterCol) ? $alterCol : ''; return isset($alterCol) ? $alterCol : '';
} }
public function renameTable($oldTableName, $newTableName) { public function renameTable($oldTableName, $newTableName) {
$this->query("ALTER TABLE \"$oldTableName\" RENAME TO \"$newTableName\""); $this->query("ALTER TABLE \"$oldTableName\" RENAME TO \"$newTableName\"");
} }
/** /**
* Repairs and reindexes the table. This might take a long time on a very large table. * Repairs and reindexes the table. This might take a long time on a very large table.
* @var string $tableName The name of the table. * @var string $tableName The name of the table.
@ -715,7 +725,7 @@ class PostgreSQLDatabase extends SS_Database {
$this->runTableCheckCommand("REINDEX TABLE \"$tableName\""); $this->runTableCheckCommand("REINDEX TABLE \"$tableName\"");
return true; return true;
} }
/** /**
* Helper function used by checkAndRepairTable. * Helper function used by checkAndRepairTable.
* @param string $sql Query to run. * @param string $sql Query to run.
@ -725,11 +735,11 @@ class PostgreSQLDatabase extends SS_Database {
$testResults = $this->query($sql); $testResults = $this->query($sql);
return true; return true;
} }
public function createField($tableName, $fieldName, $fieldSpec) { public function createField($tableName, $fieldName, $fieldSpec) {
$this->query("ALTER TABLE \"$tableName\" ADD \"$fieldName\" $fieldSpec"); $this->query("ALTER TABLE \"$tableName\" ADD \"$fieldName\" $fieldSpec");
} }
/** /**
* Change the database type of the given field. * Change the database type of the given field.
* @param string $tableName The name of the tbale the field is in. * @param string $tableName The name of the tbale the field is in.
@ -742,7 +752,7 @@ class PostgreSQLDatabase extends SS_Database {
/** /**
* Change the database column name of the given field. * Change the database column name of the given field.
* *
* @param string $tableName The name of the tbale the field is in. * @param string $tableName The name of the tbale the field is in.
* @param string $oldName The name of the field to change. * @param string $oldName The name of the field to change.
* @param string $newName The new name of the field * @param string $newName The new name of the field
@ -753,94 +763,98 @@ class PostgreSQLDatabase extends SS_Database {
$this->query("ALTER TABLE \"$tableName\" RENAME COLUMN \"$oldName\" TO \"$newName\""); $this->query("ALTER TABLE \"$tableName\" RENAME COLUMN \"$oldName\" TO \"$newName\"");
} }
} }
public function fieldList($table) { public function fieldList($table) {
//Query from http://www.alberton.info/postgresql_meta_info.html //Query from http://www.alberton.info/postgresql_meta_info.html
//This gets us more information than we need, but I've included it all for the moment.... //This gets us more information than we need, but I've included it all for the moment....
$fields = $this->query("SELECT ordinal_position, column_name, data_type, column_default, is_nullable, character_maximum_length, numeric_precision, numeric_scale FROM information_schema.columns WHERE table_name = '$table' ORDER BY ordinal_position;");
if(!isset(self::$cached_fieldlists[$table])){
$output = array(); $fields = $this->query("SELECT ordinal_position, column_name, data_type, column_default, is_nullable, character_maximum_length, numeric_precision, numeric_scale FROM information_schema.columns WHERE table_name = '$table' ORDER BY ordinal_position;");
if($fields) foreach($fields as $field) {
$output = array();
switch($field['data_type']){ if($fields) foreach($fields as $field) {
case 'character varying':
//Check to see if there's a constraint attached to this column: switch($field['data_type']){
//$constraint=$this->query("SELECT conname,pg_catalog.pg_get_constraintdef(r.oid, true) FROM pg_catalog.pg_constraint r WHERE r.contype = 'c' AND conname='" . $table . '_' . $field['column_name'] . "_check' ORDER BY 1;")->first(); case 'character varying':
$constraint=$this->constraintExists($table . '_' . $field['column_name'] . '_check'); //Check to see if there's a constraint attached to this column:
$enum=''; //$constraint=$this->query("SELECT conname,pg_catalog.pg_get_constraintdef(r.oid, true) FROM pg_catalog.pg_constraint r WHERE r.contype = 'c' AND conname='" . $table . '_' . $field['column_name'] . "_check' ORDER BY 1;")->first();
if($constraint){ $constraint=$this->constraintExists($table . '_' . $field['column_name'] . '_check');
//Now we need to break this constraint text into bits so we can see what we have: $enum='';
//Examples: if($constraint){
//CHECK ("CanEditType"::text = ANY (ARRAY['LoggedInUsers'::character varying, 'OnlyTheseUsers'::character varying, 'Inherit'::character varying]::text[])) //Now we need to break this constraint text into bits so we can see what we have:
//CHECK ("ClassName"::text = 'PageComment'::text) //Examples:
//CHECK ("CanEditType"::text = ANY (ARRAY['LoggedInUsers'::character varying, 'OnlyTheseUsers'::character varying, 'Inherit'::character varying]::text[]))
//TODO: replace all this with a regular expression! //CHECK ("ClassName"::text = 'PageComment'::text)
$value=$constraint['pg_get_constraintdef'];
$value=substr($value, strpos($value,'=')); //TODO: replace all this with a regular expression!
$value=str_replace("''", "'", $value); $value=$constraint['pg_get_constraintdef'];
$value=substr($value, strpos($value,'='));
$in_value=false; $value=str_replace("''", "'", $value);
$constraints=Array();
$current_value=''; $in_value=false;
for($i=0; $i<strlen($value); $i++){ $constraints=Array();
$char=substr($value, $i, 1); $current_value='';
if($in_value) for($i=0; $i<strlen($value); $i++){
$current_value.=$char; $char=substr($value, $i, 1);
if($in_value)
if($char=="'"){ $current_value.=$char;
if(!$in_value)
$in_value=true; if($char=="'"){
else { if(!$in_value)
$in_value=false; $in_value=true;
$constraints[]=substr($current_value, 0, -1); else {
$current_value=''; $in_value=false;
$constraints[]=substr($current_value, 0, -1);
$current_value='';
}
} }
} }
if(sizeof($constraints)>0){
//Get the default:
$default=trim(substr($field['column_default'], 0, strpos($field['column_default'], '::')), "'");
$output[$field['column_name']]=$this->enum(Array('default'=>$default, 'name'=>$field['column_name'], 'enums'=>$constraints));
}
} else{
$output[$field['column_name']]='varchar(' . $field['character_maximum_length'] . ')';
} }
break;
if(sizeof($constraints)>0){
//Get the default: case 'numeric':
$default=trim(substr($field['column_default'], 0, strpos($field['column_default'], '::')), "'"); $output[$field['column_name']]='decimal(' . $field['numeric_precision'] . ',' . $field['numeric_scale'] . ') default ' . (int)$field['column_default'];
$output[$field['column_name']]=$this->enum(Array('default'=>$default, 'name'=>$field['column_name'], 'enums'=>$constraints)); break;
}
} else{ case 'integer':
$output[$field['column_name']]='varchar(' . $field['character_maximum_length'] . ')'; $output[$field['column_name']]='integer default ' . (int)$field['column_default'];
} break;
break;
case 'timestamp without time zone':
case 'numeric': $output[$field['column_name']]='timestamp';
$output[$field['column_name']]='decimal(' . $field['numeric_precision'] . ',' . $field['numeric_scale'] . ') default ' . (int)$field['column_default']; break;
break;
case 'smallint':
case 'integer': $output[$field['column_name']]='smallint default ' . (int)$field['column_default'];
$output[$field['column_name']]='integer default ' . (int)$field['column_default']; break;
break;
case 'time without time zone':
case 'timestamp without time zone': $output[$field['column_name']]='time';
$output[$field['column_name']]='timestamp'; break;
break;
case 'double precision':
case 'smallint': $output[$field['column_name']]='float';
$output[$field['column_name']]='smallint default ' . (int)$field['column_default']; break;
break;
default:
case 'time without time zone': $output[$field['column_name']] = $field;
$output[$field['column_name']]='time'; }
break;
case 'double precision':
$output[$field['column_name']]='float';
break;
default:
$output[$field['column_name']] = $field;
} }
self::$cached_fieldlists[$table]=$output;
} }
return self::$cached_fieldlists[$table];
return $output;
} }
/** /**
* Create an index on a table. * Create an index on a table.
* @param string $tableName The name of the table. * @param string $tableName The name of the table.
@ -852,7 +866,7 @@ class PostgreSQLDatabase extends SS_Database {
if($createIndex!==false) if($createIndex!==false)
$this->query(); $this->query();
} }
/* /*
* This takes the index spec which has been provided by a class (ie static $indexes = blah blah) * This takes the index spec which has been provided by a class (ie static $indexes = blah blah)
* and turns it into a proper string. * and turns it into a proper string.
@ -860,7 +874,7 @@ class PostgreSQLDatabase extends SS_Database {
* arrays to be created. * arrays to be created.
*/ */
public function convertIndexSpec($indexSpec, $asDbValue=false, $table=''){ public function convertIndexSpec($indexSpec, $asDbValue=false, $table=''){
if(!$asDbValue){ if(!$asDbValue){
if(is_array($indexSpec)){ if(is_array($indexSpec)){
//Here we create a db-specific version of whatever index we need to create. //Here we create a db-specific version of whatever index we need to create.
@ -888,24 +902,24 @@ class PostgreSQLDatabase extends SS_Database {
} }
return $indexSpec; return $indexSpec;
} }
protected function getIndexSqlDefinition($tableName, $indexName, $indexSpec, $asDbValue=false) { protected function getIndexSqlDefinition($tableName, $indexName, $indexSpec, $asDbValue=false) {
//TODO: create table partition support //TODO: create table partition support
//TODO: create clustering options //TODO: create clustering options
//NOTE: it is possible for *_renamed tables to have indexes whose names are not updates //NOTE: it is possible for *_renamed tables to have indexes whose names are not updates
//Therefore, we now check for the existance of indexes before we create them. //Therefore, we now check for the existance of indexes before we create them.
//This is techically a bug, since new tables will not be indexed. //This is techically a bug, since new tables will not be indexed.
if(!$asDbValue){ if(!$asDbValue){
$tableCol= 'ix_' . $tableName . '_' . $indexName; $tableCol= 'ix_' . $tableName . '_' . $indexName;
if(strlen($tableCol)>64){ if(strlen($tableCol)>64){
$tableCol=substr($indexName, 0, 59) . rand(1000, 9999); $tableCol=substr($indexName, 0, 59) . rand(1000, 9999);
} }
//It is possible to specify indexes through strings: //It is possible to specify indexes through strings:
if(!is_array($indexSpec)){ if(!is_array($indexSpec)){
$indexSpec=trim($indexSpec, '()'); $indexSpec=trim($indexSpec, '()');
$bits=explode(',', $indexSpec); $bits=explode(',', $indexSpec);
@ -918,16 +932,16 @@ class PostgreSQLDatabase extends SS_Database {
else else
return false; return false;
} else { } else {
//Arrays offer much more flexibility and many more options: //Arrays offer much more flexibility and many more options:
//Misc options first: //Misc options first:
$fillfactor=$where=''; $fillfactor=$where='';
if(isset($indexSpec['fillfactor'])) if(isset($indexSpec['fillfactor']))
$fillfactor='WITH (FILLFACTOR = ' . $indexSpec['fillfactor'] . ')'; $fillfactor='WITH (FILLFACTOR = ' . $indexSpec['fillfactor'] . ')';
if(isset($indexSpec['where'])) if(isset($indexSpec['where']))
$where='WHERE ' . $indexSpec['where']; $where='WHERE ' . $indexSpec['where'];
//Fix up the value entry to be quoted: //Fix up the value entry to be quoted:
$value_bits=explode(',', $indexSpec['value']); $value_bits=explode(',', $indexSpec['value']);
$new_values=Array(); $new_values=Array();
@ -935,39 +949,39 @@ class PostgreSQLDatabase extends SS_Database {
$new_values[]="\"" . trim($value, ' "') . "\""; $new_values[]="\"" . trim($value, ' "') . "\"";
} }
$indexSpec['value']=implode(',', $new_values); $indexSpec['value']=implode(',', $new_values);
//One last check: //One last check:
$existing=DB::query("SELECT tablename FROM pg_indexes WHERE indexname='" . strtolower($tableCol) . "';"); $existing=DB::query("SELECT tablename FROM pg_indexes WHERE indexname='" . strtolower($tableCol) . "';");
if(!$existing->first()){ if(!$existing->first()){
//create a type-specific index //create a type-specific index
//NOTE: hash should be removed. This is only here to demonstrate how other indexes can be made //NOTE: hash should be removed. This is only here to demonstrate how other indexes can be made
switch($indexSpec['type']){ switch($indexSpec['type']){
case 'fulltext': case 'fulltext':
$spec="create index $tableCol ON \"" . $tableName . "\" USING " . $this->default_fts_cluster_method . "(\"ts_" . $indexName . "\") $fillfactor $where"; $spec="create index $tableCol ON \"" . $tableName . "\" USING " . $this->default_fts_cluster_method . "(\"ts_" . $indexName . "\") $fillfactor $where";
break; break;
case 'unique': case 'unique':
$spec="create unique index $tableCol ON \"" . $tableName . "\" (" . $indexSpec['value'] . ") $fillfactor $where"; $spec="create unique index $tableCol ON \"" . $tableName . "\" (" . $indexSpec['value'] . ") $fillfactor $where";
break; break;
case 'btree': case 'btree':
$spec="create index $tableCol ON \"" . $tableName . "\" USING btree (" . $indexSpec['value'] . ") $fillfactor $where"; $spec="create index $tableCol ON \"" . $tableName . "\" USING btree (" . $indexSpec['value'] . ") $fillfactor $where";
break; break;
case 'hash': case 'hash':
//NOTE: this is not a recommended index type //NOTE: this is not a recommended index type
$spec="create index $tableCol ON \"" . $tableName . "\" USING hash (" . $indexSpec['value'] . ") $fillfactor $where"; $spec="create index $tableCol ON \"" . $tableName . "\" USING hash (" . $indexSpec['value'] . ") $fillfactor $where";
break; break;
case 'index': case 'index':
//'index' is the same as default, just a normal index with the default type decided by the database. //'index' is the same as default, just a normal index with the default type decided by the database.
default: default:
$spec="create index $tableCol ON \"" . $tableName . "\" (" . $indexSpec['value'] . ") $fillfactor $where"; $spec="create index $tableCol ON \"" . $tableName . "\" (" . $indexSpec['value'] . ") $fillfactor $where";
} }
return trim($spec) . ';'; return trim($spec) . ';';
} else { } else {
return false; return false;
} }
} }
@ -976,11 +990,11 @@ class PostgreSQLDatabase extends SS_Database {
return $indexName; return $indexName;
} }
} }
function getDbSqlDefinition($tableName, $indexName, $indexSpec){ function getDbSqlDefinition($tableName, $indexName, $indexSpec){
return $this->getIndexSqlDefinition($tableName, $indexName, $indexSpec, true); return $this->getIndexSqlDefinition($tableName, $indexName, $indexSpec, true);
} }
/** /**
* Alter an index on a table. * Alter an index on a table.
* @param string $tableName The name of the table. * @param string $tableName The name of the table.
@ -994,35 +1008,35 @@ class PostgreSQLDatabase extends SS_Database {
} else { } else {
$indexFields = $indexSpec; $indexFields = $indexSpec;
} }
if(!$indexType) { if(!$indexType) {
$indexType = "index"; $indexType = "index";
} }
$this->query("DROP INDEX $indexName"); $this->query("DROP INDEX $indexName");
$this->query("ALTER TABLE \"$tableName\" ADD $indexType \"$indexName\" $indexFields"); $this->query("ALTER TABLE \"$tableName\" ADD $indexType \"$indexName\" $indexFields");
} }
/** /**
* Return the list of indexes in a table. * Return the list of indexes in a table.
* @param string $table The table name. * @param string $table The table name.
* @return array * @return array
*/ */
public function indexList($table) { public function indexList($table) {
//Retrieve a list of indexes for the specified table //Retrieve a list of indexes for the specified table
$schema_SQL = pg_escape_string($this->dbConn, $this->schema); $schema_SQL = pg_escape_string($this->dbConn, $this->schema);
$indexes=DB::query("SELECT tablename, indexname, indexdef FROM pg_catalog.pg_indexes WHERE tablename='$table' AND schemaname = '{$schema_SQL}';"); $indexes=DB::query("SELECT tablename, indexname, indexdef FROM pg_catalog.pg_indexes WHERE tablename='$table' AND schemaname = '{$schema_SQL}';");
$indexList=Array(); $indexList=Array();
foreach($indexes as $index) { foreach($indexes as $index) {
//We don't actually need the entire created command, just a few bits: //We don't actually need the entire created command, just a few bits:
$prefix=''; $prefix='';
//Check for uniques: //Check for uniques:
if(substr($index['indexdef'], 0, 13)=='CREATE UNIQUE') if(substr($index['indexdef'], 0, 13)=='CREATE UNIQUE')
$prefix='unique '; $prefix='unique ';
//check for hashes, btrees etc: //check for hashes, btrees etc:
if(strpos(strtolower($index['indexdef']), 'using hash ')!==false) if(strpos(strtolower($index['indexdef']), 'using hash ')!==false)
$prefix='using hash '; $prefix='using hash ';
@ -1030,26 +1044,26 @@ class PostgreSQLDatabase extends SS_Database {
//TODO: Fix me: btree is the default index type: //TODO: Fix me: btree is the default index type:
//if(strpos(strtolower($index['indexdef']), 'using btree ')!==false) //if(strpos(strtolower($index['indexdef']), 'using btree ')!==false)
// $prefix='using btree '; // $prefix='using btree ';
if(strpos(strtolower($index['indexdef']), 'using rtree ')!==false) if(strpos(strtolower($index['indexdef']), 'using rtree ')!==false)
$prefix='using rtree '; $prefix='using rtree ';
$value=explode(' ', substr($index['indexdef'], strpos($index['indexdef'], ' USING ')+7)); $value=explode(' ', substr($index['indexdef'], strpos($index['indexdef'], ' USING ')+7));
if(sizeof($value)>2){ if(sizeof($value)>2){
for($i=2; $i<sizeof($value); $i++) for($i=2; $i<sizeof($value); $i++)
$value[1].=$value[$i]; $value[1].=$value[$i];
} }
$key=substr($value[1], 0, strpos($value[1], ')')); $key=substr($value[1], 0, strpos($value[1], ')'));
$key=trim(trim(str_replace("\"", '', $key), '()')); $key=trim(trim(str_replace("\"", '', $key), '()'));
$indexList[$key]['indexname']=$index['indexname']; $indexList[$key]['indexname']=$index['indexname'];
$indexList[$key]['spec']=$prefix . '(' . $key . ')'; $indexList[$key]['spec']=$prefix . '(' . $key . ')';
} }
return isset($indexList) ? $indexList : null; return isset($indexList) ? $indexList : null;
} }
/** /**
@ -1058,33 +1072,34 @@ class PostgreSQLDatabase extends SS_Database {
* @return array * @return array
*/ */
public function tableList() { public function tableList() {
$schema_SQL = pg_escape_string($this->dbConn, $this->schema); $schema_SQL = pg_escape_string($this->dbConn, $this->schema);
foreach($this->query("SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = '{$schema_SQL}' AND tablename NOT ILIKE 'pg_%' AND tablename NOT ILIKE 'sql_%'") as $record) { $tables=array();
foreach($this->query("SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = '{$schema_SQL}' AND tablename NOT ILIKE 'pg_%' AND tablename NOT ILIKE 'sql_%'") as $record) {
//$table = strtolower(reset($record)); //$table = strtolower(reset($record));
$table = reset($record); $table = reset($record);
$tables[$table] = $table; $tables[$table] = $table;
} }
//Return an empty array if there's nothing in this database //Return an empty array if there's nothing in this database
return isset($tables) ? $tables : Array(); return $tables;
} }
function TableExists($tableName){ function TableExists($tableName){
$schema_SQL = pg_escape_string($this->dbConn, $this->schema); $schema_SQL = pg_escape_string($this->dbConn, $this->schema);
$result=$this->query("SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = '{$schema_SQL}' AND tablename='$tableName';")->first(); $result=$this->query("SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = '{$schema_SQL}' AND tablename='$tableName';")->first();
if($result) if($result)
return true; return true;
else else
return false; return false;
} }
/** /**
* Find out what the constraint information is, given a constraint name. * Find out what the constraint information is, given a constraint name.
* We also cache this result, so the next time we don't need to do a * We also cache this result, so the next time we don't need to do a
* query all over again. * query all over again.
* *
* @param string $constraint * @param string $constraint
*/ */
function constraintExists($constraint){ function constraintExists($constraint){
@ -1092,10 +1107,10 @@ class PostgreSQLDatabase extends SS_Database {
$exists=DB::query("SELECT conname,pg_catalog.pg_get_constraintdef(r.oid, true) FROM pg_catalog.pg_constraint r WHERE r.contype = 'c' AND conname='$constraint' ORDER BY 1;")->first(); $exists=DB::query("SELECT conname,pg_catalog.pg_get_constraintdef(r.oid, true) FROM pg_catalog.pg_constraint r WHERE r.contype = 'c' AND conname='$constraint' ORDER BY 1;")->first();
self::$cached_constraints[$constraint]=$exists; self::$cached_constraints[$constraint]=$exists;
} }
return self::$cached_constraints[$constraint]; return self::$cached_constraints[$constraint];
} }
/** /**
* Return the number of rows affected by the previous operation. * Return the number of rows affected by the previous operation.
* @return int * @return int
@ -1103,24 +1118,24 @@ class PostgreSQLDatabase extends SS_Database {
public function affectedRows() { public function affectedRows() {
return pg_affected_rows(DB::$lastQuery); return pg_affected_rows(DB::$lastQuery);
} }
/** /**
* A function to return the field names and datatypes for the particular table * A function to return the field names and datatypes for the particular table
*/ */
public function tableDetails($tableName){ public function tableDetails($tableName){
$schema_SQL = pg_escape_string($this->dbConn, $this->schema); $schema_SQL = pg_escape_string($this->dbConn, $this->schema);
$query="SELECT a.attname as \"Column\", pg_catalog.format_type(a.atttypid, a.atttypmod) as \"Datatype\" FROM pg_catalog.pg_attribute a WHERE a.attnum > 0 AND NOT a.attisdropped AND a.attrelid = ( SELECT c.oid FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relname ~ '^($tableName)$' AND pg_catalog.pg_table_is_visible(c.oid) AND n.nspname = '{$schema_SQL}');"; $query="SELECT a.attname as \"Column\", pg_catalog.format_type(a.atttypid, a.atttypmod) as \"Datatype\" FROM pg_catalog.pg_attribute a WHERE a.attnum > 0 AND NOT a.attisdropped AND a.attrelid = ( SELECT c.oid FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relname ~ '^($tableName)$' AND pg_catalog.pg_table_is_visible(c.oid) AND n.nspname = '{$schema_SQL}');";
$result=DB::query($query); $result=DB::query($query);
$table=Array(); $table=Array();
while($row=pg_fetch_assoc($result)){ while($row=pg_fetch_assoc($result)){
$table[]=Array('Column'=>$row['Column'], 'DataType'=>$row['DataType']); $table[]=Array('Column'=>$row['Column'], 'DataType'=>$row['DataType']);
} }
return $table; return $table;
} }
/** /**
* Pass a legit trigger name and it will be dropped * Pass a legit trigger name and it will be dropped
* This assumes that the trigger has been named in a unique fashion * This assumes that the trigger has been named in a unique fashion
@ -1131,47 +1146,47 @@ class PostgreSQLDatabase extends SS_Database {
DB::query("DROP trigger $triggerName ON \"$tableName\";"); DB::query("DROP trigger $triggerName ON \"$tableName\";");
} }
} }
/** /**
* This will return the fields that the trigger is monitoring * This will return the fields that the trigger is monitoring
* @param string $trigger * @param string $trigger
* *
* @return array * @return array
*/ */
function triggerFieldsFromTrigger($trigger){ function triggerFieldsFromTrigger($trigger){
if($trigger){ if($trigger){
$tsvector='tsvector_update_trigger'; $tsvector='tsvector_update_trigger';
$ts_pos=strpos($trigger, $tsvector); $ts_pos=strpos($trigger, $tsvector);
$details=trim(substr($trigger, $ts_pos+strlen($tsvector)), '();'); $details=trim(substr($trigger, $ts_pos+strlen($tsvector)), '();');
//Now split this into bits: //Now split this into bits:
$bits=explode(',', $details); $bits=explode(',', $details);
$fields=$bits[2]; $fields=$bits[2];
$field_bits=explode(',', str_replace('"', '', $fields)); $field_bits=explode(',', str_replace('"', '', $fields));
$result=array(); $result=array();
foreach($field_bits as $field_bit) foreach($field_bits as $field_bit)
$result[]=trim($field_bit); $result[]=trim($field_bit);
return $result; return $result;
} else } else
return false; return false;
} }
/** /**
* Return a boolean type-formatted string * Return a boolean type-formatted string
* *
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function boolean($values, $asDbValue=false){ public function boolean($values, $asDbValue=false){
//Annoyingly, we need to do a good ol' fashioned switch here: //Annoyingly, we need to do a good ol' fashioned switch here:
($values['default']) ? $default='1' : $default='0'; ($values['default']) ? $default='1' : $default='0';
if(!isset($values['arrayValue'])) if(!isset($values['arrayValue']))
$values['arrayValue']=''; $values['arrayValue']='';
if($asDbValue) if($asDbValue)
return Array('data_type'=>'smallint'); return Array('data_type'=>'smallint');
else { else {
@ -1179,57 +1194,57 @@ class PostgreSQLDatabase extends SS_Database {
$default=''; $default='';
else else
$default=' default ' . (int)$values['default']; $default=' default ' . (int)$values['default'];
return "smallint{$values['arrayValue']}" . $default; return "smallint{$values['arrayValue']}" . $default;
} }
} }
/** /**
* Return a date type-formatted string * Return a date type-formatted string
* *
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function date($values){ public function date($values){
if(!isset($values['arrayValue'])) if(!isset($values['arrayValue']))
$values['arrayValue']=''; $values['arrayValue']='';
return "date{$values['arrayValue']}"; return "date{$values['arrayValue']}";
} }
/** /**
* Return a decimal type-formatted string * Return a decimal type-formatted string
* *
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function decimal($values, $asDbValue=false){ public function decimal($values, $asDbValue=false){
if(!isset($values['arrayValue'])) if(!isset($values['arrayValue']))
$values['arrayValue']=''; $values['arrayValue']='';
// Avoid empty strings being put in the db // Avoid empty strings being put in the db
if($values['precision'] == '') { if($values['precision'] == '') {
$precision = 1; $precision = 1;
} else { } else {
$precision = $values['precision']; $precision = $values['precision'];
} }
$defaultValue = ''; $defaultValue = '';
if(isset($values['default']) && is_numeric($values['default'])) { if(isset($values['default']) && is_numeric($values['default'])) {
$defaultValue = ' default ' . $values['default']; $defaultValue = ' default ' . $values['default'];
} }
if($asDbValue) if($asDbValue)
return Array('data_type'=>'numeric', 'precision'=>$precision); return Array('data_type'=>'numeric', 'precision'=>$precision);
else return "decimal($precision){$values['arrayValue']}$defaultValue"; else return "decimal($precision){$values['arrayValue']}$defaultValue";
} }
/** /**
* Return a enum type-formatted string * Return a enum type-formatted string
* *
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
@ -1238,52 +1253,52 @@ class PostgreSQLDatabase extends SS_Database {
//NOTE: In this one instance, we are including the table name in the values array //NOTE: In this one instance, we are including the table name in the values array
if(!isset($values['arrayValue'])) if(!isset($values['arrayValue']))
$values['arrayValue']=''; $values['arrayValue']='';
if($values['arrayValue']!='') if($values['arrayValue']!='')
$default=''; $default='';
else else
$default=" default '{$values['default']}'"; $default=" default '{$values['default']}'";
return "varchar(255){$values['arrayValue']}" . $default . " check (\"" . $values['name'] . "\" in ('" . implode('\', \'', $values['enums']) . "'))"; return "varchar(255){$values['arrayValue']}" . $default . " check (\"" . $values['name'] . "\" in ('" . implode('\', \'', $values['enums']) . "'))";
} }
/** /**
* Return a float type-formatted string * Return a float type-formatted string
* *
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function float($values, $asDbValue=false){ public function float($values, $asDbValue=false){
if(!isset($values['arrayValue'])) if(!isset($values['arrayValue']))
$values['arrayValue']=''; $values['arrayValue']='';
if($asDbValue) if($asDbValue)
return Array('data_type'=>'double precision'); return Array('data_type'=>'double precision');
else return "float{$values['arrayValue']}"; else return "float{$values['arrayValue']}";
} }
/** /**
* Return a float type-formatted string cause double is not supported * Return a float type-formatted string cause double is not supported
* *
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function double($values, $asDbValue=false){ public function double($values, $asDbValue=false){
return $this->float($values, $asDbValue); return $this->float($values, $asDbValue);
} }
/** /**
* Return a int type-formatted string * Return a int type-formatted string
* *
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function int($values, $asDbValue=false){ public function int($values, $asDbValue=false){
if(!isset($values['arrayValue'])) if(!isset($values['arrayValue']))
$values['arrayValue']=''; $values['arrayValue']='';
if($asDbValue) if($asDbValue)
return Array('data_type'=>'integer', 'precision'=>'32'); return Array('data_type'=>'integer', 'precision'=>'32');
else { else {
@ -1291,105 +1306,106 @@ class PostgreSQLDatabase extends SS_Database {
$default=''; $default='';
else else
$default=' default ' . (int)$values['default']; $default=' default ' . (int)$values['default'];
return "integer{$values['arrayValue']}" . $default; return "integer{$values['arrayValue']}" . $default;
} }
} }
/** /**
* Return a datetime type-formatted string * Return a datetime type-formatted string
* For PostgreSQL, we simply return the word 'timestamp', no other parameters are necessary * For PostgreSQL, we simply return the word 'timestamp', no other parameters are necessary
* *
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function SS_Datetime($values, $asDbValue=false){ public function SS_Datetime($values, $asDbValue=false){
if(!isset($values['arrayValue'])) if(!isset($values['arrayValue']))
$values['arrayValue']=''; $values['arrayValue']='';
if($asDbValue) if($asDbValue)
return Array('data_type'=>'timestamp without time zone'); return Array('data_type'=>'timestamp without time zone');
else else
return "timestamp{$values['arrayValue']}"; return "timestamp{$values['arrayValue']}";
} }
/** /**
* Return a text type-formatted string * Return a text type-formatted string
* *
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function text($values, $asDbValue=false){ public function text($values, $asDbValue=false){
if(!isset($values['arrayValue'])) if(!isset($values['arrayValue']))
$values['arrayValue']=''; $values['arrayValue']='';
if($asDbValue) if($asDbValue)
return Array('data_type'=>'text'); return Array('data_type'=>'text');
else else
return "text{$values['arrayValue']}"; return "text{$values['arrayValue']}";
} }
/** /**
* Return a time type-formatted string * Return a time type-formatted string
* *
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function time($values){ public function time($values){
if(!isset($values['arrayValue'])) if(!isset($values['arrayValue']))
$values['arrayValue']=''; $values['arrayValue']='';
return "time{$values['arrayValue']}"; return "time{$values['arrayValue']}";
} }
/** /**
* Return a varchar type-formatted string * Return a varchar type-formatted string
* *
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function varchar($values, $asDbValue=false){ public function varchar($values, $asDbValue=false){
if(!isset($values['arrayValue'])) if(!isset($values['arrayValue']))
$values['arrayValue']=''; $values['arrayValue']='';
if(!isset($values['precision'])) if(!isset($values['precision']))
$values['precision']=255; $values['precision']=255;
if($asDbValue) if($asDbValue)
return Array('data_type'=>'varchar', 'precision'=>$values['precision']); return Array('data_type'=>'varchar', 'precision'=>$values['precision']);
else else
return "varchar({$values['precision']}){$values['arrayValue']}"; return "varchar({$values['precision']}){$values['arrayValue']}";
} }
/* /*
* Return a 4 digit numeric type. MySQL has a proprietary 'Year' type. * Return a 4 digit numeric type. MySQL has a proprietary 'Year' type.
* For Postgres, we'll use a 4 digit numeric * For Postgres, we'll use a 4 digit numeric
*/ */
public function year($values, $asDbValue=false){ public function year($values, $asDbValue=false){
if(!isset($values['arrayValue'])) if(!isset($values['arrayValue']))
$values['arrayValue']=''; $values['arrayValue']='';
//TODO: the DbValue result does not include the numeric_scale option (ie, the ,0 value in 4,0) //TODO: the DbValue result does not include the numeric_scale option (ie, the ,0 value in 4,0)
if($asDbValue) if($asDbValue)
return Array('data_type'=>'decimal', 'precision'=>'4', 'default'=> (int)$values['default']); return Array('data_type'=>'decimal', 'precision'=>'4');
else return "decimal(4,0){$values['arrayValue']}"; else
return "decimal(4,0){$values['arrayValue']}";
} }
function escape_character($escape=false){ function escape_character($escape=false){
if($escape) if($escape)
return "\\\""; return "\\\"";
else else
return "\""; return "\"";
} }
/** /**
* Create a fulltext search datatype for PostgreSQL * Create a fulltext search datatype for PostgreSQL
* This will also return a trigger to be applied to this table * This will also return a trigger to be applied to this table
* *
* @todo: create custom functions to allow weighted searches * @todo: create custom functions to allow weighted searches
* *
* @param array $spec * @param array $spec
@ -1401,19 +1417,19 @@ class PostgreSQLDatabase extends SS_Database {
$columns[$i]="\"" . trim($columns[$i]) . "\""; $columns[$i]="\"" . trim($columns[$i]) . "\"";
$columns=implode(', ', $columns); $columns=implode(', ', $columns);
$fulltexts="\"ts_$name\" tsvector"; $fulltexts="\"ts_$name\" tsvector";
$triggerName="ts_{$tableName}_{$name}"; $triggerName="ts_{$tableName}_{$name}";
$language=$this->get_search_language(); $language=$this->get_search_language();
$this->dropTrigger($triggerName, $tableName); $this->dropTrigger($triggerName, $tableName);
$triggers="CREATE TRIGGER $triggerName BEFORE INSERT OR UPDATE $triggers="CREATE TRIGGER $triggerName BEFORE INSERT OR UPDATE
ON \"$tableName\" FOR EACH ROW EXECUTE PROCEDURE ON \"$tableName\" FOR EACH ROW EXECUTE PROCEDURE
tsvector_update_trigger(\"ts_$name\", 'pg_catalog.$language', $columns);"; tsvector_update_trigger(\"ts_$name\", 'pg_catalog.$language', $columns);";
return Array('name'=>$name, 'ts_name'=>"ts_{$name}", 'fulltexts'=>$fulltexts, 'triggers'=>$triggers); return Array('name'=>$name, 'ts_name'=>"ts_{$name}", 'fulltexts'=>$fulltexts, 'triggers'=>$triggers);
} }
/** /**
* This returns the column which is the primary key for each table * This returns the column which is the primary key for each table
* In Postgres, it is a SERIAL8, which is the equivalent of an auto_increment * In Postgres, it is a SERIAL8, which is the equivalent of an auto_increment
@ -1425,26 +1441,26 @@ class PostgreSQLDatabase extends SS_Database {
return 'bigint'; return 'bigint';
else return 'serial8 not null'; else return 'serial8 not null';
} }
/** /**
* Returns true if this table exists * Returns true if this table exists
*/ */
function hasTable($tableName) { function hasTable($tableName) {
$schema_SQL = pg_escape_string($this->dbConn, $this->schema); $schema_SQL = pg_escape_string($this->dbConn, $this->schema);
$result = $this->query("SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = '{$schema_SQL}' AND tablename = '$tableName'"); $result = $this->query("SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = '{$schema_SQL}' AND tablename = '$tableName'");
if ($result->numRecords() > 0) return true; if ($result->numRecords() > 0) return true;
else return false; else return false;
} }
/** /**
* Returns the SQL command to get all the tables in this database * Returns the SQL command to get all the tables in this database
*/ */
function allTablesSQL(){ function allTablesSQL(){
$schema_SQL = pg_escape_string($this->dbConn, $this->schema); $schema_SQL = pg_escape_string($this->dbConn, $this->schema);
return "SELECT table_name FROM information_schema.tables WHERE table_schema='{$schema_SQL}' AND table_type='BASE TABLE';"; return "SELECT table_name FROM information_schema.tables WHERE table_schema='{$schema_SQL}' AND table_type='BASE TABLE';";
} }
/** /**
* Return enum values for the given field * Return enum values for the given field
* @todo Make a proper implementation * @todo Make a proper implementation
@ -1455,7 +1471,7 @@ class PostgreSQLDatabase extends SS_Database {
$classes=Array(); $classes=Array();
if($constraints) if($constraints)
$classes=$this->EnumValuesFromConstraint($constraints['pg_get_constraintdef']); $classes=$this->EnumValuesFromConstraint($constraints['pg_get_constraintdef']);
return $classes; return $classes;
} }
@ -1471,10 +1487,10 @@ class PostgreSQLDatabase extends SS_Database {
$bits=preg_split('/ *:: */', $this_segment); $bits=preg_split('/ *:: */', $this_segment);
array_unshift($constraints, trim($bits[0], " '")); array_unshift($constraints, trim($bits[0], " '"));
} }
return $constraints; return $constraints;
} }
/** /**
* Because NOW() doesn't always work... * Because NOW() doesn't always work...
* MSSQL, I'm looking at you * MSSQL, I'm looking at you
@ -1483,14 +1499,14 @@ class PostgreSQLDatabase extends SS_Database {
function now(){ function now(){
return 'NOW()'; return 'NOW()';
} }
/* /*
* Returns the database-specific version of the random() function * Returns the database-specific version of the random() function
*/ */
function random(){ function random(){
return 'RANDOM()'; return 'RANDOM()';
} }
/* /*
* This is a lookup table for data types. * This is a lookup table for data types.
* For instance, Postgres uses 'INT', while MySQL uses 'UNSIGNED' * For instance, Postgres uses 'INT', while MySQL uses 'UNSIGNED'
@ -1500,12 +1516,12 @@ class PostgreSQLDatabase extends SS_Database {
$values=Array( $values=Array(
'unsigned integer'=>'INT' 'unsigned integer'=>'INT'
); );
if(isset($values[$type])) if(isset($values[$type]))
return $values[$type]; return $values[$type];
else return ''; else return '';
} }
/** /**
* Convert a SQLQuery object into a SQL statement * Convert a SQLQuery object into a SQL statement
* @todo There is a lot of duplication between this and MySQLDatabase::sqlQueryToString(). Perhaps they could both call a common * @todo There is a lot of duplication between this and MySQLDatabase::sqlQueryToString(). Perhaps they could both call a common
@ -1528,15 +1544,15 @@ class PostgreSQLDatabase extends SS_Database {
if($sqlQuery->limit) { if($sqlQuery->limit) {
$limit = $sqlQuery->limit; $limit = $sqlQuery->limit;
// Pass limit as array or SQL string value // Pass limit as array or SQL string value
if(is_array($limit)) { if(is_array($limit)) {
if(isset($limit['start']) && $limit['start']!='') if(isset($limit['start']) && $limit['start']!='')
$text.=' OFFSET ' . $limit['start']; $text.=' OFFSET ' . $limit['start'];
if(isset($limit['limit']) && $limit['limit']!='') if(isset($limit['limit']) && $limit['limit']!='')
$text.=' LIMIT ' . $limit['limit']; $text.=' LIMIT ' . $limit['limit'];
} else { } else {
if(strpos($sqlQuery->limit, ',')){ if(strpos($sqlQuery->limit, ',')){
$limit=str_replace(',', ' LIMIT ', $sqlQuery->limit); $limit=str_replace(',', ' LIMIT ', $sqlQuery->limit);
@ -1546,17 +1562,17 @@ class PostgreSQLDatabase extends SS_Database {
} }
} }
} }
return $text; return $text;
} }
protected function orderMoreSpecifically($select,$order) { protected function orderMoreSpecifically($select,$order) {
//create a key so we can cache this result and quickly return it if we've done it before //create a key so we can cache this result and quickly return it if we've done it before
$cache_key=serialize($select) . $order; $cache_key=serialize($select) . $order;
if(isset(self::$cached_ordered_specifically[$cache_key])) if(isset(self::$cached_ordered_specifically[$cache_key]))
return self::$cached_ordered_specifically[$cache_key]; return self::$cached_ordered_specifically[$cache_key];
$altered = false; $altered = false;
// split expression into order terms // split expression into order terms
@ -1584,7 +1600,7 @@ class PostgreSQLDatabase extends SS_Database {
//Hold this result in the cache //Hold this result in the cache
$result=implode(',', $terms); $result=implode(',', $terms);
self::$cached_ordered_specifically[$cache_key]=$result; self::$cached_ordered_specifically[$cache_key]=$result;
return $result; return $result;
} }
@ -1595,82 +1611,82 @@ class PostgreSQLDatabase extends SS_Database {
function addslashes($value){ function addslashes($value){
return pg_escape_string($value); return pg_escape_string($value);
} }
/* /*
* This changes the index name depending on database requirements. * This changes the index name depending on database requirements.
*/ */
function modifyIndex($index, $spec){ function modifyIndex($index, $spec){
if(is_array($spec) && $spec['type']=='fulltext') if(is_array($spec) && $spec['type']=='fulltext')
return 'ts_' . str_replace(',', '_', $index); return 'ts_' . str_replace(',', '_', $index);
else else
return str_replace('_', ',', $index); return str_replace('_', ',', $index);
} }
/** /**
* The core search engine configuration. * The core search engine configuration.
* @todo Properly extract the search functions out of the core. * @todo Properly extract the search functions out of the core.
* *
* @param string $keywords Keywords as a space separated string * @param string $keywords Keywords as a space separated string
* @return object DataObjectSet of result pages * @return object DataObjectSet of result pages
*/ */
public function searchEngine($classesToSearch, $keywords, $start, $pageLength, $sortBy = "ts_rank DESC", $extraFilter = "", $booleanSearch = false, $alternativeFileFilter = "", $invertedMatch = false) { public function searchEngine($classesToSearch, $keywords, $start, $pageLength, $sortBy = "ts_rank DESC", $extraFilter = "", $booleanSearch = false, $alternativeFileFilter = "", $invertedMatch = false) {
//Fix the keywords to be ts_query compatitble: //Fix the keywords to be ts_query compatitble:
//Spaces must have pipes //Spaces must have pipes
//@TODO: properly handle boolean operators here. //@TODO: properly handle boolean operators here.
$keywords=trim($keywords); $keywords=trim($keywords);
$keywords=str_replace(' ', ' | ', $keywords); $keywords=str_replace(' ', ' | ', $keywords);
$keywords=str_replace('"', "'", $keywords); $keywords=str_replace('"', "'", $keywords);
$keywords = Convert::raw2sql(trim($keywords)); $keywords = Convert::raw2sql(trim($keywords));
$htmlEntityKeywords = htmlentities($keywords, ENT_NOQUOTES); $htmlEntityKeywords = htmlentities($keywords, ENT_NOQUOTES);
//We can get a list of all the tsvector columns though this query: //We can get a list of all the tsvector columns though this query:
//We know what tables to search in based on the $classesToSearch variable: //We know what tables to search in based on the $classesToSearch variable:
$result=DB::query("SELECT table_name, column_name, data_type FROM information_schema.columns WHERE data_type='tsvector' AND table_name in ('" . implode("', '", $classesToSearch) . "');"); $result=DB::query("SELECT table_name, column_name, data_type FROM information_schema.columns WHERE data_type='tsvector' AND table_name in ('" . implode("', '", $classesToSearch) . "');");
if (!$result->numRecords()) throw new Exception('there are no full text columns to search'); if (!$result->numRecords()) throw new Exception('there are no full text columns to search');
$tables=Array(); $tables=Array();
// Make column selection lists // Make column selection lists
$select = array( $select = array(
'SiteTree' => array("\"ClassName\"","\"SiteTree\".\"ID\"","\"ParentID\"","\"Title\"","\"URLSegment\"","\"Content\"","\"LastEdited\"","\"Created\"","NULL AS \"Filename\"", "NULL AS \"Name\"", "\"CanViewType\""), 'SiteTree' => array("\"ClassName\"","\"SiteTree\".\"ID\"","\"ParentID\"","\"Title\"","\"URLSegment\"","\"Content\"","\"LastEdited\"","\"Created\"","NULL AS \"Filename\"", "NULL AS \"Name\"", "\"CanViewType\""),
'File' => array("\"ClassName\"","\"File\".\"ID\"","NULL AS \"ParentID\"","\"Title\"","NULL AS \"URLSegment\"","\"Content\"","\"LastEdited\"","\"Created\"","\"Filename\"","\"Name\"", "NULL AS \"CanViewType\""), 'File' => array("\"ClassName\"","\"File\".\"ID\"","NULL AS \"ParentID\"","\"Title\"","NULL AS \"URLSegment\"","\"Content\"","\"LastEdited\"","\"Created\"","\"Filename\"","\"Name\"", "NULL AS \"CanViewType\""),
); );
foreach($result as $row){ foreach($result as $row){
if($row['table_name']=='SiteTree') if($row['table_name']=='SiteTree')
$showInSearch="AND \"ShowInSearch\"=1 "; $showInSearch="AND \"ShowInSearch\"=1 ";
else else
$showInSearch=''; $showInSearch='';
//public function extendedSQL($filter = "", $sort = "", $limit = "", $join = "", $having = ""){ //public function extendedSQL($filter = "", $sort = "", $limit = "", $join = "", $having = ""){
$query=singleton($row['table_name'])->extendedSql("\"" . $row['table_name'] . "\".\"" . $row['column_name'] . "\" " . $this->default_fts_search_method . ' q ' . $showInSearch, ''); $query=singleton($row['table_name'])->extendedSql("\"" . $row['table_name'] . "\".\"" . $row['column_name'] . "\" " . $this->default_fts_search_method . ' q ' . $showInSearch, '');
$query->select=$select[$row['table_name']]; $query->select=$select[$row['table_name']];
$query->from['tsearch']=", to_tsquery('" . $this->get_search_language() . "', '$keywords') AS q"; $query->from['tsearch']=", to_tsquery('" . $this->get_search_language() . "', '$keywords') AS q";
$query->select[]="ts_rank(\"{$row['table_name']}\".\"{$row['column_name']}\", q) AS \"Relevance\""; $query->select[]="ts_rank(\"{$row['table_name']}\".\"{$row['column_name']}\", q) AS \"Relevance\"";
$query->orderby=null; $query->orderby=null;
//Add this query to the collection //Add this query to the collection
$tables[] = $query->sql(); $tables[] = $query->sql();
} }
$doSet=new DataObjectSet(); $doSet=new DataObjectSet();
$limit=$pageLength; $limit=$pageLength;
$offset=$start; $offset=$start;
if($keywords) if($keywords)
$orderBy=" ORDER BY $sortBy"; $orderBy=" ORDER BY $sortBy";
else $orderBy=''; else $orderBy='';
$fullQuery = "SELECT * FROM (" . implode(" UNION ", $tables) . ") AS q1 $orderBy LIMIT $limit OFFSET $offset"; $fullQuery = "SELECT * FROM (" . implode(" UNION ", $tables) . ") AS q1 $orderBy LIMIT $limit OFFSET $offset";
// Get records // Get records
$records = DB::query($fullQuery); $records = DB::query($fullQuery);
$totalCount=0; $totalCount=0;
@ -1680,20 +1696,20 @@ class PostgreSQLDatabase extends SS_Database {
} }
if(isset($objects)) $doSet = new DataObjectSet($objects); if(isset($objects)) $doSet = new DataObjectSet($objects);
else $doSet = new DataObjectSet(); else $doSet = new DataObjectSet();
$doSet->setPageLimits($start, $pageLength, $totalCount); $doSet->setPageLimits($start, $pageLength, $totalCount);
return $doSet; return $doSet;
} }
/* /*
* Does this database support transactions? * Does this database support transactions?
*/ */
public function supportsTransactions(){ public function supportsTransactions(){
return $this->supportsTransactions; return $this->supportsTransactions;
} }
/* /*
* This is a quick lookup to discover if the database supports particular extensions * This is a quick lookup to discover if the database supports particular extensions
*/ */
@ -1707,83 +1723,83 @@ class PostgreSQLDatabase extends SS_Database {
else else
return false; return false;
} }
/* /*
* Start a prepared transaction * Start a prepared transaction
* See http://developer.postgresql.org/pgdocs/postgres/sql-set-transaction.html for details on transaction isolation options * See http://developer.postgresql.org/pgdocs/postgres/sql-set-transaction.html for details on transaction isolation options
*/ */
public function startTransaction($transaction_mode=false, $session_characteristics=false){ public function transactionStart($transaction_mode=false, $session_characteristics=false){
DB::query('BEGIN;'); DB::query('BEGIN;');
if($transaction_mode) if($transaction_mode)
DB::query('SET TRANSACTION ' . $transaction_mode . ';'); DB::query('SET TRANSACTION ' . $transaction_mode . ';');
if($session_characteristics) if($session_characteristics)
DB::query('SET SESSION CHARACTERISTICS AS TRANSACTION ' . $session_characteristics . ';'); DB::query('SET SESSION CHARACTERISTICS AS TRANSACTION ' . $session_characteristics . ';');
} }
/* /*
* Create a savepoint that you can jump back to if you encounter problems * Create a savepoint that you can jump back to if you encounter problems
*/ */
public function transactionSavepoint($savepoint){ public function transactionSavepoint($savepoint){
DB::query("SAVEPOINT $savepoint;"); DB::query("SAVEPOINT $savepoint;");
} }
/* /*
* Rollback or revert to a savepoint if your queries encounter problems * Rollback or revert to a savepoint if your queries encounter problems
* If you encounter a problem at any point during a transaction, you may * If you encounter a problem at any point during a transaction, you may
* need to rollback that particular query, or return to a savepoint * need to rollback that particular query, or return to a savepoint
*/ */
public function transactionRollback($savepoint=false){ public function transactionRollback($savepoint=false){
if($savepoint) if($savepoint)
DB::query("ROLLBACK TO $savepoint;"); DB::query("ROLLBACK TO $savepoint;");
else else
DB::query('ROLLBACK;'); DB::query('ROLLBACK;');
} }
/* /*
* Commit everything inside this transaction so far * Commit everything inside this transaction so far
*/ */
public function endTransaction(){ public function transactionEnd(){
DB::query('COMMIT;'); DB::query('COMMIT;');
} }
/* /*
* Given a tablespace and and location, either create a new one * Given a tablespace and and location, either create a new one
* or update the existing one * or update the existing one
*/ */
public function createOrReplaceTablespace($name, $location){ public function createOrReplaceTablespace($name, $location){
$existing=DB::query("SELECT spcname, spclocation FROM pg_tablespace WHERE spcname='$name';")->first(); $existing=DB::query("SELECT spcname, spclocation FROM pg_tablespace WHERE spcname='$name';")->first();
//NOTE: this location must be empty for this to work //NOTE: this location must be empty for this to work
//We can't seem to change the location of the tablespace through any ALTER commands :( //We can't seem to change the location of the tablespace through any ALTER commands :(
//If a tablespace with this name exists, but the location has changed, then drop the current one //If a tablespace with this name exists, but the location has changed, then drop the current one
//if($existing && $location!=$existing['spclocation']) //if($existing && $location!=$existing['spclocation'])
// DB::query("DROP TABLESPACE $name;"); // DB::query("DROP TABLESPACE $name;");
//If this is a new tablespace, or we have dropped the current one: //If this is a new tablespace, or we have dropped the current one:
if(!$existing || ($existing && $location!=$existing['spclocation'])) if(!$existing || ($existing && $location!=$existing['spclocation']))
DB::query("CREATE TABLESPACE $name LOCATION '$location';"); DB::query("CREATE TABLESPACE $name LOCATION '$location';");
} }
public function createOrReplacePartition($tableName, $partitions, $indexes, $extensions){ public function createOrReplacePartition($tableName, $partitions, $indexes, $extensions){
//We need the plpgsql language to be installed for this to work: //We need the plpgsql language to be installed for this to work:
$this->createLanguage('plpgsql'); $this->createLanguage('plpgsql');
$trigger='CREATE OR REPLACE FUNCTION ' . $tableName . '_insert_trigger() RETURNS TRIGGER AS $$ BEGIN '; $trigger='CREATE OR REPLACE FUNCTION ' . $tableName . '_insert_trigger() RETURNS TRIGGER AS $$ BEGIN ';
$first=true; $first=true;
//Do we need to create a tablespace for this item? //Do we need to create a tablespace for this item?
if($extensions && isset($extensions['tablespace'])){ if($extensions && isset($extensions['tablespace'])){
$this->createOrReplaceTablespace($extensions['tablespace']['name'], $extensions['tablespace']['location']); $this->createOrReplaceTablespace($extensions['tablespace']['name'], $extensions['tablespace']['location']);
$tableSpace=' TABLESPACE ' . $extensions['tablespace']['name']; $tableSpace=' TABLESPACE ' . $extensions['tablespace']['name'];
} else } else
$tableSpace=''; $tableSpace='';
foreach($partitions as $partition_name=>$partition_value){ foreach($partitions as $partition_name=>$partition_value){
//Check that this child table does not already exist: //Check that this child table does not already exist:
if(!$this->TableExists($partition_name)){ if(!$this->TableExists($partition_name)){
@ -1796,65 +1812,65 @@ class PostgreSQLDatabase extends SS_Database {
} }
$this->dropTrigger(strtolower('trigger_' . $tableName . '_insert'), $tableName); $this->dropTrigger(strtolower('trigger_' . $tableName . '_insert'), $tableName);
} }
DB::query("ALTER TABLE \"$partition_name\" ADD CONSTRAINT \"{$partition_name}_pkey\" PRIMARY KEY (\"ID\");"); DB::query("ALTER TABLE \"$partition_name\" ADD CONSTRAINT \"{$partition_name}_pkey\" PRIMARY KEY (\"ID\");");
if($first){ if($first){
$trigger.='IF'; $trigger.='IF';
$first=false; $first=false;
} else } else
$trigger.='ELSIF'; $trigger.='ELSIF';
$trigger.=" ($partition_value) THEN INSERT INTO \"$partition_name\" VALUES (NEW.*);"; $trigger.=" ($partition_value) THEN INSERT INTO \"$partition_name\" VALUES (NEW.*);";
if($indexes){ if($indexes){
// We need to propogate the indexes through to the child pages. // We need to propogate the indexes through to the child pages.
// Some of this code is duplicated, and could be tidied up // Some of this code is duplicated, and could be tidied up
foreach($indexes as $name=>$this_index){ foreach($indexes as $name=>$this_index){
if($this_index['type']=='fulltext'){ if($this_index['type']=='fulltext'){
$fillfactor=$where=''; $fillfactor=$where='';
if(isset($this_index['fillfactor'])) if(isset($this_index['fillfactor']))
$fillfactor='WITH (FILLFACTOR = ' . $this_index['fillfactor'] . ')'; $fillfactor='WITH (FILLFACTOR = ' . $this_index['fillfactor'] . ')';
if(isset($this_index['where'])) if(isset($this_index['where']))
$where='WHERE ' . $this_index['where']; $where='WHERE ' . $this_index['where'];
DB::query("CREATE INDEX \"ix_{$partition_name}_{$this_index['name']}\" ON \"" . $partition_name . "\" USING " . $this->default_fts_cluster_method . "(\"ts_" . $name . "\") $fillfactor $where"); DB::query("CREATE INDEX \"ix_{$partition_name}_{$this_index['name']}\" ON \"" . $partition_name . "\" USING " . $this->default_fts_cluster_method . "(\"ts_" . $name . "\") $fillfactor $where");
$ts_details=$this->fulltext($this_index, $partition_name, $name); $ts_details=$this->fulltext($this_index, $partition_name, $name);
DB::query($ts_details['triggers']); DB::query($ts_details['triggers']);
} else { } else {
if(is_array($this_index)) if(is_array($this_index))
$index_name=$this_index['name']; $index_name=$this_index['name'];
else $index_name=trim($this_index, '()'); else $index_name=trim($this_index, '()');
$createIndex=$this->getIndexSqlDefinition($partition_name, $index_name, $this_index); $createIndex=$this->getIndexSqlDefinition($partition_name, $index_name, $this_index);
if($createIndex!==false) if($createIndex!==false)
DB::query($createIndex); DB::query($createIndex);
} }
} }
} }
//Lastly, clustering goes here: //Lastly, clustering goes here:
if($extensions && isset($extensions['cluster'])){ if($extensions && isset($extensions['cluster'])){
DB::query("CLUSTER \"$partition_name\" USING \"{$extensions['cluster']}\";"); DB::query("CLUSTER \"$partition_name\" USING \"{$extensions['cluster']}\";");
} }
} }
$trigger.='ELSE RAISE EXCEPTION \'Value id out of range. Fix the ' . $tableName . '_insert_trigger() function!\'; END IF; RETURN NULL; END; $$ LANGUAGE plpgsql;'; $trigger.='ELSE RAISE EXCEPTION \'Value id out of range. Fix the ' . $tableName . '_insert_trigger() function!\'; END IF; RETURN NULL; END; $$ LANGUAGE plpgsql;';
$trigger.='CREATE TRIGGER trigger_' . $tableName . '_insert BEFORE INSERT ON "' . $tableName . '" FOR EACH ROW EXECUTE PROCEDURE ' . $tableName . '_insert_trigger();'; $trigger.='CREATE TRIGGER trigger_' . $tableName . '_insert BEFORE INSERT ON "' . $tableName . '" FOR EACH ROW EXECUTE PROCEDURE ' . $tableName . '_insert_trigger();';
DB::query($trigger); DB::query($trigger);
} }
/* /*
* This will create a language if it doesn't already exist. * This will create a language if it doesn't already exist.
* This is used by the createOrReplacePartition function, which needs plpgsql * This is used by the createOrReplacePartition function, which needs plpgsql
*/ */
public function createLanguage($language){ public function createLanguage($language){
$result=DB::query("SELECT lanname FROM pg_language WHERE lanname='$language';")->first(); $result=DB::query("SELECT lanname FROM pg_language WHERE lanname='$language';")->first();
if(!$result){ if(!$result){
DB::query("CREATE LANGUAGE $language;"); DB::query("CREATE LANGUAGE $language;");
} }
@ -1896,11 +1912,11 @@ class PostgreSQLDatabase extends SS_Database {
} }
if($format == '%U') return "FLOOR(EXTRACT(epoch FROM $date))"; if($format == '%U') return "FLOOR(EXTRACT(epoch FROM $date))";
return "to_char($date, TEXT '$format')"; return "to_char($date, TEXT '$format')";
} }
/** /**
* Function to return an SQL datetime expression that can be used with Postgres * Function to return an SQL datetime expression that can be used with Postgres
* used for querying a datetime addition * used for querying a datetime addition
@ -1952,13 +1968,13 @@ class PostgreSQLDatabase extends SS_Database {
return "(FLOOR(EXTRACT(epoch FROM $date1)) - FLOOR(EXTRACT(epoch from $date2)))"; return "(FLOOR(EXTRACT(epoch FROM $date1)) - FLOOR(EXTRACT(epoch from $date2)))";
} }
/** /**
* Return a set type-formatted string * Return a set type-formatted string
* This is used for Multi-enum support, which isn't actually supported by Postgres. * This is used for Multi-enum support, which isn't actually supported by Postgres.
* Throws a user error to show our lack of support, and return an "int", specifically for sapphire * Throws a user error to show our lack of support, and return an "int", specifically for sapphire
* tests that test multi-enums. This results in a test failure, but not crashing the test run. * tests that test multi-enums. This results in a test failure, but not crashing the test run.
* *
* @param array $values Contains a tokenised list of info about this data type * @param array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
@ -1966,21 +1982,21 @@ class PostgreSQLDatabase extends SS_Database {
user_error("PostGreSQL does not support multi-enum"); user_error("PostGreSQL does not support multi-enum");
return "int"; return "int";
} }
/** /**
* Set the current language for the tsearch functions * Set the current language for the tsearch functions
* *
* @todo: somehow link this to the locale options? * @todo: somehow link this to the locale options?
* *
* @param string $lang * @param string $lang
*/ */
public function set_search_language($lang){ public function set_search_language($lang){
$this->search_language=$lang; $this->search_language=$lang;
} }
/** /**
* Returns the current language for the tsearch functions * Returns the current language for the tsearch functions
* *
* @param string $lang * @param string $lang
*/ */
public function get_search_language(){ public function get_search_language(){
@ -1999,7 +2015,7 @@ class PostgreSQLQuery extends SS_Query {
* @var PostgreSQLDatabase * @var PostgreSQLDatabase
*/ */
private $database; private $database;
/** /**
* The internal Postgres handle that points to the result set. * The internal Postgres handle that points to the result set.
* @var resource * @var resource
@ -2015,19 +2031,19 @@ class PostgreSQLQuery extends SS_Query {
$this->database = $database; $this->database = $database;
$this->handle = $handle; $this->handle = $handle;
} }
public function __destruct() { public function __destruct() {
if(is_resource($this->handle)) pg_free_result($this->handle); if(is_resource($this->handle)) pg_free_result($this->handle);
} }
public function seek($row) { public function seek($row) {
return pg_result_seek($this->handle, $row); return pg_result_seek($this->handle, $row);
} }
public function numRecords() { public function numRecords() {
return pg_num_rows($this->handle); return pg_num_rows($this->handle);
} }
public function nextRecord() { public function nextRecord() {
// Coalesce rather than replace common fields. // Coalesce rather than replace common fields.
if($data = pg_fetch_row($this->handle)) { if($data = pg_fetch_row($this->handle)) {
@ -2044,8 +2060,8 @@ class PostgreSQLQuery extends SS_Query {
return false; return false;
} }
} }
} }
?> ?>