Merge pull request #46 from helpfulrobot/convert-to-psr-2

Converted to PSR-2
This commit is contained in:
Damian Mooyman 2015-12-18 10:06:49 +13:00
commit 934fa61433
8 changed files with 2485 additions and 2297 deletions

View File

@ -10,7 +10,8 @@
* @package sapphire
* @subpackage model
*/
class PostgreSQLConnector extends DBConnector {
class PostgreSQLConnector extends DBConnector
{
/**
* Connection to the PG Database database
@ -51,9 +52,12 @@ class PostgreSQLConnector extends DBConnector {
* @param mixed $default The default value, or null if optional
* @return string The completed fragment in the form name=value
*/
protected function escapeParameter($parameters, $key, $name, $default = null) {
protected function escapeParameter($parameters, $key, $name, $default = null)
{
if (empty($parameters[$key])) {
if($default === null) return '';
if ($default === null) {
return '';
}
$value = $default;
} else {
$value = $parameters[$key];
@ -61,7 +65,8 @@ class PostgreSQLConnector extends DBConnector {
return "$name='" . addslashes($value) . "'";
}
public function connect($parameters, $selectDB = false) {
public function connect($parameters, $selectDB = false)
{
$this->lastParameters = $parameters;
// Note: Postgres always behaves as though $selectDB = true, ignoring
@ -78,7 +83,9 @@ class PostgreSQLConnector extends DBConnector {
);
// Close the old connection
if($this->dbConn) pg_close($this->dbConn);
if ($this->dbConn) {
pg_close($this->dbConn);
}
// Connect
$this->dbConn = @pg_connect(implode(' ', $arguments));
@ -98,30 +105,39 @@ class PostgreSQLConnector extends DBConnector {
$this->databaseName = empty($parameters['database']) ? PostgreSQLDatabase::MASTER_DATABASE : $parameters['database'];
}
public function affectedRows() {
public function affectedRows()
{
return $this->lastRows;
}
public function getGeneratedID($table) {
public function getGeneratedID($table)
{
$result = $this->query("SELECT last_value FROM \"{$table}_ID_seq\";")->first();
return $result['last_value'];
}
public function getLastError() {
public function getLastError()
{
return pg_last_error($this->dbConn);
}
public function getSelectedDatabase() {
public function getSelectedDatabase()
{
return $this->databaseName;
}
public function getVersion() {
public function getVersion()
{
$version = pg_version($this->dbConn);
if(isset($version['server'])) return $version['server'];
else return false;
if (isset($version['server'])) {
return $version['server'];
} else {
return false;
}
}
public function isActive() {
public function isActive()
{
return $this->databaseName && $this->dbConn;
}
@ -138,7 +154,8 @@ class PostgreSQLConnector extends DBConnector {
* @param string $input The SQL fragment
* @return boolean True if the string breaks into or out of a string literal
*/
public function checkStringTogglesLiteral($input) {
public function checkStringTogglesLiteral($input)
{
// Remove escaped backslashes, count them!
$input = preg_replace('/\\\\\\\\/', '', $input);
@ -157,7 +174,8 @@ class PostgreSQLConnector extends DBConnector {
* @param string $sql Paramaterised query using question mark placeholders
* @return string Paramaterised query using numeric placeholders
*/
public function replacePlaceholders($sql) {
public function replacePlaceholders($sql)
{
$segments = preg_split('/\?/', $sql);
$joined = '';
$inString = false;
@ -167,7 +185,9 @@ class PostgreSQLConnector extends DBConnector {
$joined .= $segments[$i];
// Don't add placeholder after last segment
if($i === count($segments) - 1) break;
if ($i === count($segments) - 1) {
break;
}
// check string escape on previous fragment
if ($this->checkStringTogglesLiteral($segments[$i])) {
@ -184,7 +204,8 @@ class PostgreSQLConnector extends DBConnector {
return $joined;
}
public function preparedQuery($sql, $parameters, $errorLevel = E_USER_ERROR) {
public function preparedQuery($sql, $parameters, $errorLevel = E_USER_ERROR)
{
// Reset state
$this->lastQuery = null;
$this->lastRows = 0;
@ -214,11 +235,13 @@ class PostgreSQLConnector extends DBConnector {
return new PostgreSQLQuery($result);
}
public function query($sql, $errorLevel = E_USER_ERROR) {
public function query($sql, $errorLevel = E_USER_ERROR)
{
return $this->preparedQuery($sql, array(), $errorLevel);
}
public function quoteString($value) {
public function quoteString($value)
{
if (function_exists('pg_escape_literal')) {
return pg_escape_literal($this->dbConn, $value);
} else {
@ -226,11 +249,13 @@ class PostgreSQLConnector extends DBConnector {
}
}
public function escapeString($value) {
public function escapeString($value)
{
return pg_escape_string($this->dbConn, $value);
}
public function escapeIdentifier($value, $separator = '.') {
public function escapeIdentifier($value, $separator = '.')
{
if (empty($separator) && function_exists('pg_escape_identifier')) {
return pg_escape_identifier($this->dbConn, $value);
}
@ -239,14 +264,16 @@ class PostgreSQLConnector extends DBConnector {
return parent::escapeIdentifier($value, $separator);
}
public function selectDatabase($name) {
public function selectDatabase($name)
{
if ($name !== $this->databaseName) {
user_error("PostgreSQLConnector can't change databases. Please create a new database connection", E_USER_ERROR);
}
return true;
}
public function unloadDatabase() {
public function unloadDatabase()
{
$this->databaseName = null;
}
}

View File

@ -6,7 +6,8 @@
* @package sapphire
* @subpackage model
*/
class PostgreSQLDatabase extends SS_Database {
class PostgreSQLDatabase extends SS_Database
{
/**
* Database schema manager object
@ -33,7 +34,8 @@ class PostgreSQLDatabase extends SS_Database {
*
* @return string
*/
public static function default_fts_cluster_method() {
public static function default_fts_cluster_method()
{
return Config::inst()->get('PostgreSQLDatabase', 'default_fts_cluster_method');
}
@ -42,7 +44,8 @@ class PostgreSQLDatabase extends SS_Database {
*
* @return string
*/
public static function default_fts_search_method() {
public static function default_fts_search_method()
{
return Config::inst()->get('PostgreSQLDatabase', 'default_fts_search_method');
}
@ -57,7 +60,8 @@ class PostgreSQLDatabase extends SS_Database {
* then attempts to create or check databases beyond the initial connection will
* result in a runtime error.
*/
public static function allow_query_master_postgres() {
public static function allow_query_master_postgres()
{
return Config::inst()->get('PostgreSQLDatabase', 'allow_query_master_postgres');
}
@ -71,7 +75,8 @@ class PostgreSQLDatabase extends SS_Database {
* If this is true then the database will only be set during the initial connection,
* and attempts to change to this database will use the 'public' schema instead
*/
public static function model_schema_as_database() {
public static function model_schema_as_database()
{
return Config::inst()->get('PostgreSQLDatabase', 'model_schema_as_database');
}
@ -82,7 +87,8 @@ class PostgreSQLDatabase extends SS_Database {
*
* @var string
*/
public static function search_language() {
public static function search_language()
{
return Config::inst()->get('PostgreSQLDatabase', 'search_language');
}
@ -109,7 +115,8 @@ class PostgreSQLDatabase extends SS_Database {
*/
protected $parameters = array();
public function connect($parameters) {
public function connect($parameters)
{
// Check database name
if (empty($parameters['database'])) {
// Check if we can use the master database
@ -161,13 +168,15 @@ class PostgreSQLDatabase extends SS_Database {
}
}
protected function connectMaster() {
protected function connectMaster()
{
$parameters = $this->parameters;
$parameters['database'] = self::MASTER_DATABASE;
$this->connector->connect($parameters, true);
}
protected function connectDefault() {
protected function connectDefault()
{
$parameters = $this->parameters;
$parameters['database'] = $this->databaseOriginal;
$this->connector->connect($parameters, true);
@ -178,20 +187,26 @@ class PostgreSQLDatabase extends SS_Database {
*
* @param string $timezone
*/
public function selectTimezone($timezone) {
if (empty($timezone)) return;
public function selectTimezone($timezone)
{
if (empty($timezone)) {
return;
}
$this->query("SET SESSION TIME ZONE '$timezone';");
}
public function supportsCollations() {
public function supportsCollations()
{
return true;
}
public function supportsTimezoneOverride() {
public function supportsTimezoneOverride()
{
return true;
}
public function getDatabaseServer() {
public function getDatabaseServer()
{
return "postgresql";
}
@ -200,7 +215,8 @@ class PostgreSQLDatabase extends SS_Database {
*
* @return string Name of current schema
*/
public function currentSchema() {
public function currentSchema()
{
return $this->schema;
}
@ -216,7 +232,8 @@ class PostgreSQLDatabase extends SS_Database {
* the query, or false if no error should be raised
* @return boolean Flag indicating success
*/
public function setSchema($schema, $create = false, $errorLevel = E_USER_ERROR) {
public function setSchema($schema, $create = false, $errorLevel = E_USER_ERROR)
{
if (!$this->schemaManager->schemaExists($schema)) {
// Check DB creation permisson
if (!$create) {
@ -245,7 +262,8 @@ class PostgreSQLDatabase extends SS_Database {
* @param string $arg2 Second schema to use
* @param string $argN Nth schema to use
*/
public function setSchemaSearchPath() {
public function setSchemaSearchPath()
{
if (func_num_args() == 0) {
user_error('At least one Schema must be supplied to set a search path.', E_USER_ERROR);
}
@ -260,7 +278,8 @@ class PostgreSQLDatabase extends SS_Database {
* @param string $keywords Keywords as a space separated string
* @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:
//Spaces must have pipes
//@TODO: properly handle boolean operators here.
@ -279,7 +298,9 @@ class PostgreSQLDatabase extends SS_Database {
WHERE data_type='tsvector' AND table_name in ($classesPlaceholders);",
$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();
$tableParameters = array();
@ -347,8 +368,11 @@ class PostgreSQLDatabase extends SS_Database {
$limit = $pageLength;
$offset = $start;
if($keywords) $orderBy = " ORDER BY $sortBy";
else $orderBy='';
if ($keywords) {
$orderBy = " ORDER BY $sortBy";
} else {
$orderBy='';
}
$fullQuery = "SELECT * FROM (" . implode(" UNION ", $tables) . ") AS q1 $orderBy LIMIT $limit OFFSET $offset";
@ -360,8 +384,11 @@ class PostgreSQLDatabase extends SS_Database {
$totalCount++;
}
if(isset($objects)) $results = new ArrayList($objects);
else $results = new ArrayList();
if (isset($objects)) {
$results = new ArrayList($objects);
} else {
$results = new ArrayList();
}
$list = new PaginatedList($results);
$list->setLimitItems(false);
$list->setPageStart($start);
@ -370,21 +397,29 @@ class PostgreSQLDatabase extends SS_Database {
return $list;
}
public function supportsTransactions() {
public function supportsTransactions()
{
return $this->supportsTransactions;
}
/*
* This is a quick lookup to discover if the database supports particular extensions
*/
public function supportsExtensions($extensions=Array('partitions', 'tablespaces', 'clustering')){
if(isset($extensions['partitions'])) return true;
elseif(isset($extensions['tablespaces'])) return true;
elseif(isset($extensions['clustering'])) return true;
else return false;
public function supportsExtensions($extensions=array('partitions', 'tablespaces', 'clustering'))
{
if (isset($extensions['partitions'])) {
return true;
} elseif (isset($extensions['tablespaces'])) {
return true;
} elseif (isset($extensions['clustering'])) {
return true;
} else {
return false;
}
}
public function transactionStart($transaction_mode = false, $session_characteristics = false){
public function transactionStart($transaction_mode = false, $session_characteristics = false)
{
$this->query('BEGIN;');
if ($transaction_mode) {
@ -396,11 +431,13 @@ class PostgreSQLDatabase extends SS_Database {
}
}
public function transactionSavepoint($savepoint){
public function transactionSavepoint($savepoint)
{
$this->query("SAVEPOINT {$savepoint};");
}
public function transactionRollback($savepoint = false){
public function transactionRollback($savepoint = false)
{
if ($savepoint) {
$this->query("ROLLBACK TO {$savepoint};");
} else {
@ -408,16 +445,20 @@ class PostgreSQLDatabase extends SS_Database {
}
}
public function transactionEnd($chain = false){
public function transactionEnd($chain = false)
{
$this->query('COMMIT;');
}
public function comparisonClause($field, $value, $exact = false, $negate = false, $caseSensitive = null, $parameterised = false) {
public function comparisonClause($field, $value, $exact = false, $negate = false, $caseSensitive = null, $parameterised = false)
{
if ($exact && $caseSensitive === null) {
$comp = ($negate) ? '!=' : '=';
} else {
$comp = ($caseSensitive === true) ? 'LIKE' : 'ILIKE';
if($negate) $comp = 'NOT ' . $comp;
if ($negate) {
$comp = 'NOT ' . $comp;
}
$field.='::text';
}
@ -442,7 +483,8 @@ class PostgreSQLDatabase extends SS_Database {
* %U = unix timestamp, can only be used on it's own
* @return string SQL datetime expression to query for a formatted datetime
*/
public function formattedDatetimeClause($date, $format) {
public function formattedDatetimeClause($date, $format)
{
preg_match_all('/%(.)/', $format, $matches);
foreach ($matches[1] as $match) {
if (array_search($match, array('Y', 'm', 'd', 'H', 'i', 's', 'U')) === false) {
@ -466,10 +508,11 @@ class PostgreSQLDatabase extends SS_Database {
$date = "TIMESTAMP '$date'";
}
if($format == '%U') return "FLOOR(EXTRACT(epoch FROM $date))";
if ($format == '%U') {
return "FLOOR(EXTRACT(epoch FROM $date))";
}
return "to_char($date, TEXT '$format')";
}
/**
@ -487,7 +530,8 @@ class PostgreSQLDatabase extends SS_Database {
* This includes the singular forms as well
* @return string SQL datetime expression to query for a datetime (YYYY-MM-DD hh:mm:ss) which is the result of the addition
*/
public function datetimeIntervalClause($date, $interval) {
public function datetimeIntervalClause($date, $interval)
{
if (preg_match('/^now$/i', $date)) {
$date = "NOW()";
} elseif (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date)) {
@ -506,7 +550,8 @@ class PostgreSQLDatabase extends SS_Database {
* @param string $date2 to be substracted of $date1, can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"'
* @return string SQL datetime expression to query for the interval between $date1 and $date2 in seconds which is the result of the substraction
*/
public function datetimeDifferenceClause($date1, $date2) {
public function datetimeDifferenceClause($date1, $date2)
{
if (preg_match('/^now$/i', $date1)) {
$date1 = "NOW()";
} elseif (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date1)) {
@ -522,11 +567,13 @@ class PostgreSQLDatabase extends SS_Database {
return "(FLOOR(EXTRACT(epoch FROM $date1)) - FLOOR(EXTRACT(epoch from $date2)))";
}
function now(){
public function now()
{
return 'NOW()';
}
function random(){
public function random()
{
return 'RANDOM()';
}
@ -538,7 +585,8 @@ class PostgreSQLDatabase extends SS_Database {
* @param string $schema Name of the schema
* @return string Name of the database to report
*/
public function schemaToDatabaseName($schema) {
public function schemaToDatabaseName($schema)
{
switch ($schema) {
case $this->schemaOriginal: return $this->databaseOriginal;
default: return $schema;
@ -552,18 +600,22 @@ class PostgreSQLDatabase extends SS_Database {
* @param string $database Name of the database
* @return string Name of the schema to use for this database internally
*/
public function databaseToSchemaName($database) {
public function databaseToSchemaName($database)
{
switch ($database) {
case $this->databaseOriginal: return $this->schemaOriginal;
default: return $database;
}
}
public function dropSelectedDatabase() {
public function dropSelectedDatabase()
{
if (self::model_schema_as_database()) {
// Check current schema is valid
$oldSchema = $this->schema;
if(empty($oldSchema)) return true; // Nothing selected to drop
if (empty($oldSchema)) {
return true;
} // Nothing selected to drop
// Select another schema
if ($oldSchema !== $this->schemaOriginal) {
@ -581,14 +633,16 @@ class PostgreSQLDatabase extends SS_Database {
}
}
public function getSelectedDatabase() {
public function getSelectedDatabase()
{
if (self::model_schema_as_database()) {
return $this->schemaToDatabaseName($this->schema);
}
return parent::getSelectedDatabase();
}
public function selectDatabase($name, $create = false, $errorLevel = E_USER_ERROR) {
public function selectDatabase($name, $create = false, $errorLevel = E_USER_ERROR)
{
// Substitute schema here as appropriate
if (self::model_schema_as_database()) {
// Selecting the database itself should be treated as selecting the public schema
@ -626,7 +680,8 @@ class PostgreSQLDatabase extends SS_Database {
*
* @param string $table
*/
public function clearTable($table) {
public function clearTable($table)
{
$this->query('DELETE FROM "'.$table.'";');
}
}

View File

@ -7,7 +7,8 @@
*
* @package postgresql
*/
class PostgreSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper {
class PostgreSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper
{
/**
* Create a connection of the appropriate type
@ -16,7 +17,8 @@ class PostgreSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelp
* @param string $error Error message passed by value
* @return mixed|null Either the connection object, or null if error
*/
protected function createConnection($databaseConfig, &$error) {
protected function createConnection($databaseConfig, &$error)
{
$error = null;
$username = empty($databaseConfig['username']) ? '' : $databaseConfig['username'];
$password = empty($databaseConfig['password']) ? '' : $databaseConfig['password'];
@ -50,12 +52,14 @@ class PostgreSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelp
}
}
public function requireDatabaseFunctions($databaseConfig) {
public function requireDatabaseFunctions($databaseConfig)
{
$data = DatabaseAdapterRegistry::get_adapter($databaseConfig['type']);
return !empty($data['supported']);
}
public function requireDatabaseServer($databaseConfig) {
public function requireDatabaseServer($databaseConfig)
{
$conn = $this->createConnection($databaseConfig, $error);
$success = !empty($conn);
return array(
@ -64,7 +68,8 @@ class PostgreSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelp
);
}
public function requireDatabaseConnection($databaseConfig) {
public function requireDatabaseConnection($databaseConfig)
{
$conn = $this->createConnection($databaseConfig, $error);
$success = !empty($conn);
return array(
@ -74,7 +79,8 @@ class PostgreSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelp
);
}
public function getDatabaseVersion($databaseConfig) {
public function getDatabaseVersion($databaseConfig)
{
$conn = $this->createConnection($databaseConfig, $error);
if (!$conn) {
return false;
@ -94,7 +100,8 @@ class PostgreSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelp
* @param array $databaseConfig Associative array of db configuration, e.g. "server", "username" etc
* @return array Result - e.g. array('success' => true, 'error' => 'details of error')
*/
public function requireDatabaseVersion($databaseConfig) {
public function requireDatabaseVersion($databaseConfig)
{
$success = false;
$error = '';
$version = $this->getDatabaseVersion($databaseConfig);
@ -121,7 +128,8 @@ class PostgreSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelp
* @param string $value Value to quote
* @return string Quoted strieng
*/
protected function quote($conn, $value) {
protected function quote($conn, $value)
{
if ($conn instanceof PDO) {
return $conn->quote($value);
} elseif (is_resource($conn)) {
@ -138,7 +146,8 @@ class PostgreSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelp
* @param string $sql SQL string to execute
* @return array List of first value from each resulting row
*/
protected function query($conn, $sql) {
protected function query($conn, $sql)
{
$items = array();
if ($conn instanceof PDO) {
foreach ($conn->query($sql) as $row) {
@ -153,7 +162,8 @@ class PostgreSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelp
return $items;
}
public function requireDatabaseOrCreatePermissions($databaseConfig) {
public function requireDatabaseOrCreatePermissions($databaseConfig)
{
$success = false;
$alreadyExists = false;
$conn = $this->createConnection($databaseConfig, $error);
@ -176,7 +186,8 @@ class PostgreSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelp
);
}
public function requireDatabaseAlterPermissions($databaseConfig) {
public function requireDatabaseAlterPermissions($databaseConfig)
{
$conn = $this->createConnection($databaseConfig, $error);
if ($conn) {
// if the account can even log in, it can alter tables

View File

@ -6,7 +6,8 @@
* @package sapphire
* @subpackage model
*/
class PostgreSQLQuery extends SS_Query {
class PostgreSQLQuery extends SS_Query
{
/**
* The internal Postgres handle that points to the result set.
@ -19,23 +20,30 @@ class PostgreSQLQuery extends SS_Query {
* @param database The database object that created this query.
* @param handle the internal Postgres handle that is points to the resultset.
*/
public function __construct($handle) {
public function __construct($handle)
{
$this->handle = $handle;
}
public function __destruct() {
if(is_resource($this->handle)) pg_free_result($this->handle);
public function __destruct()
{
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);
}
public function numRecords() {
public function numRecords()
{
return pg_num_rows($this->handle);
}
public function nextRecord() {
public function nextRecord()
{
return pg_fetch_assoc($this->handle);
}
}

View File

@ -1,6 +1,7 @@
<?php
class PostgreSQLQueryBuilder extends DBQueryBuilder {
class PostgreSQLQueryBuilder extends DBQueryBuilder
{
/**
* Return the LIMIT clause ready for inserting into a query.
@ -9,12 +10,15 @@ class PostgreSQLQueryBuilder extends DBQueryBuilder {
* @param array $parameters Out parameter for the resulting query parameters
* @return string The finalised limit SQL fragment
*/
public function buildLimitFragment(SQLSelect $query, array &$parameters) {
public function buildLimitFragment(SQLSelect $query, array &$parameters)
{
$nl = $this->getSeparator();
// Ensure limit is given
$limit = $query->getLimit();
if(empty($limit)) return '';
if (empty($limit)) {
return '';
}
// For literal values return this as the limit SQL
if (! is_array($limit)) {
@ -38,5 +42,4 @@ class PostgreSQLQueryBuilder extends DBQueryBuilder {
}
return $clause;
}
}

View File

@ -6,7 +6,8 @@
* @package sapphire
* @subpackage model
*/
class PostgreSQLSchemaManager extends DBSchemaManager {
class PostgreSQLSchemaManager extends DBSchemaManager
{
/**
* Identifier for this schema, used for configuring schema-specific table
@ -40,7 +41,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
*/
protected static $cached_fieldlists = array();
protected function indexKey($table, $index, $spec) {
protected function indexKey($table, $index, $spec)
{
return $this->buildPostgresIndexName($table, $index);
}
@ -49,11 +51,13 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
*
* @param string $name
*/
public function createPostgresDatabase($name) {
public function createPostgresDatabase($name)
{
$this->query("CREATE DATABASE \"$name\";");
}
public function createDatabase($name) {
public function createDatabase($name)
{
if (PostgreSQLDatabase::model_schema_as_database()) {
$schemaName = $this->database->databaseToSchemaName($name);
return $this->createSchema($schemaName);
@ -67,12 +71,14 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param string $name
* @return boolean
*/
public function postgresDatabaseExists($name) {
public function postgresDatabaseExists($name)
{
$result = $this->preparedQuery("SELECT datname FROM pg_database WHERE datname = ?;", array($name));
return $result->first() ? true : false;
}
public function databaseExists($name) {
public function databaseExists($name)
{
if (PostgreSQLDatabase::model_schema_as_database()) {
$schemaName = $this->database->databaseToSchemaName($name);
return $this->schemaExists($schemaName);
@ -85,11 +91,13 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
*
* @return array
*/
public function postgresDatabaseList() {
public function postgresDatabaseList()
{
return $this->query("SELECT datname FROM pg_database WHERE datistemplate=false;")->column();
}
public function databaseList() {
public function databaseList()
{
if (PostgreSQLDatabase::model_schema_as_database()) {
$schemas = $this->schemaList();
$names = array();
@ -105,12 +113,14 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
*
* @param string $name
*/
public function dropPostgresDatabase($name) {
public function dropPostgresDatabase($name)
{
$nameSQL = $this->database->escapeIdentifier($name);
$this->query("DROP DATABASE $nameSQL;");
}
public function dropDatabase($name) {
public function dropDatabase($name)
{
if (PostgreSQLDatabase::model_schema_as_database()) {
$schemaName = $this->database->databaseToSchemaName($name);
return $this->dropSchema($schemaName);
@ -124,7 +134,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param string $name
* @return boolean
*/
public function schemaExists($name) {
public function schemaExists($name)
{
return $this->preparedQuery(
"SELECT nspname FROM pg_catalog.pg_namespace WHERE nspname = ?;",
array($name)
@ -136,7 +147,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
*
* @param string $name
*/
public function createSchema($name) {
public function createSchema($name)
{
$nameSQL = $this->database->escapeIdentifier($name);
$this->query("CREATE SCHEMA $nameSQL;");
}
@ -146,7 +158,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
*
* @param string $name
*/
public function dropSchema($name) {
public function dropSchema($name)
{
$nameSQL = $this->database->escapeIdentifier($name);
$this->query("DROP SCHEMA $nameSQL CASCADE;");
}
@ -156,7 +169,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
*
* @return array
*/
public function schemaList() {
public function schemaList()
{
return $this->query("
SELECT nspname
FROM pg_catalog.pg_namespace
@ -164,12 +178,14 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
)->column();
}
public function createTable($table, $fields = null, $indexes = null, $options = null, $advancedOptions = null) {
public function createTable($table, $fields = null, $indexes = null, $options = null, $advancedOptions = null)
{
$fieldSchemas = $indexSchemas = "";
if($fields) foreach($fields as $k => $v) {
if ($fields) {
foreach ($fields as $k => $v) {
$fieldSchemas .= "\"$k\" $v,\n";
}
}
if (!empty($options[self::ID])) {
$addOptions = $options[self::ID];
} elseif (!empty($options[get_class($this)])) {
@ -200,9 +216,11 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
}
}
if($indexes) foreach($indexes as $k => $v) {
if ($indexes) {
foreach ($indexes as $k => $v) {
$indexSchemas .= $this->getIndexSqlDefinition($table, $k, $v) . "\n";
}
}
//Do we need to create a tablespace for this item?
if ($advancedOptions && isset($advancedOptions['tablespace'])) {
@ -211,8 +229,9 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
$advancedOptions['tablespace']['location']
);
$tableSpace = ' TABLESPACE ' . $advancedOptions['tablespace']['name'];
} else
} else {
$tableSpace = '';
}
$this->query("CREATE TABLE \"$table\" (
$fieldSchemas
@ -245,7 +264,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param string $prefix The optional prefix for the index. Defaults to "ix" for indexes.
* @return string The postgres name of the index
*/
protected function buildPostgresIndexName($tableName, $indexName, $prefix = 'ix') {
protected function buildPostgresIndexName($tableName, $indexName, $prefix = 'ix')
{
// Assume all indexes also contain the table name
// MD5 the table/index name combo to keep it to a fixed length.
@ -267,21 +287,28 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param string $triggerName
* @return string The postgres name of the trigger
*/
function buildPostgresTriggerName($tableName, $triggerName) {
public function buildPostgresTriggerName($tableName, $triggerName)
{
// Kind of cheating, but behaves the same way as indexes
return $this->buildPostgresIndexName($tableName, $triggerName, 'ts');
}
public function alterTable($table, $newFields = null, $newIndexes = null, $alteredFields = null, $alteredIndexes = null, $alteredOptions = null, $advancedOptions = null) {
public function alterTable($table, $newFields = null, $newIndexes = null, $alteredFields = null, $alteredIndexes = null, $alteredOptions = null, $advancedOptions = null)
{
$alterList = array();
if($newFields) foreach($newFields as $fieldName => $fieldSpec) {
if ($newFields) {
foreach ($newFields as $fieldName => $fieldSpec) {
$alterList[] = "ADD \"$fieldName\" $fieldSpec";
}
}
if ($alteredFields) foreach ($alteredFields as $indexName => $indexSpec) {
if ($alteredFields) {
foreach ($alteredFields as $indexName => $indexSpec) {
$val = $this->alterTableAlterColumn($table, $indexName, $indexSpec);
if (!empty($val)) $alterList[] = $val;
if (!empty($val)) {
$alterList[] = $val;
}
}
}
//Do we need to do anything with the tablespaces?
@ -298,8 +325,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
$fulltexts = false;
$drop_triggers = false;
$triggers = false;
if($alteredIndexes) foreach($alteredIndexes as $indexName=>$indexSpec) {
if ($alteredIndexes) {
foreach ($alteredIndexes as $indexName=>$indexSpec) {
$indexSpec = $this->parseIndexSpec($indexName, $indexSpec);
$indexNamePG = $this->buildPostgresIndexName($table, $indexName);
@ -326,12 +353,15 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
// Create index action (including fulltext)
$alterIndexList[] = "DROP INDEX IF EXISTS \"$indexNamePG\";";
$createIndex = $this->getIndexSqlDefinition($table, $indexName, $indexSpec);
if($createIndex!==false) $alterIndexList[] = $createIndex;
if ($createIndex!==false) {
$alterIndexList[] = $createIndex;
}
}
}
//Add the new indexes:
if($newIndexes) foreach($newIndexes as $indexName => $indexSpec){
if ($newIndexes) {
foreach ($newIndexes as $indexName => $indexSpec) {
$indexSpec = $this->parseIndexSpec($indexName, $indexSpec);
$indexNamePG = $this->buildPostgresIndexName($table, $indexName);
//If we have a fulltext search request, then we need to create a special column
@ -352,9 +382,11 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
}
$createIndex=$this->getIndexSqlDefinition($table, $indexName, $indexSpec);
if($createIndex!==false)
if ($createIndex!==false) {
$alterIndexList[] = $createIndex;
}
}
}
if ($alterList) {
$alterations = implode(",\n", $alterList);
@ -376,8 +408,12 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
}
//Create any fulltext columns and triggers here:
if($fulltexts) $this->query($fulltexts);
if($drop_triggers) $this->query($drop_triggers);
if ($fulltexts) {
$this->query($fulltexts);
}
if ($drop_triggers) {
$this->query($drop_triggers);
}
if ($triggers) {
$this->query($triggers);
@ -393,7 +429,9 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
}
}
foreach($alterIndexList as $alteration) $this->query($alteration);
foreach ($alterIndexList as $alteration) {
$this->query($alteration);
}
//If we have a partitioning requirement, we do that here:
if ($advancedOptions && isset($advancedOptions['partitions'])) {
@ -437,7 +475,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param $colSpec String which contains conditions for a column
* @return string
*/
private function alterTableAlterColumn($tableName, $colName, $colSpec){
private function alterTableAlterColumn($tableName, $colName, $colSpec)
{
// First, we split the column specifications into parts
// 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?
@ -445,9 +484,13 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
$pattern = '/^([\w()]+)\s?((?:not\s)?null)?\s?(default\s[\w\']+)?\s?(check\s[\w()\'",\s]+)?$/i';
preg_match($pattern, $colSpec, $matches);
if(sizeof($matches)==0) return '';
if (sizeof($matches)==0) {
return '';
}
if($matches[1]=='serial8') return '';
if ($matches[1]=='serial8') {
return '';
}
if (isset($matches[1])) {
$alterCol = "ALTER COLUMN \"$colName\" TYPE $matches[1]\n";
@ -500,18 +543,21 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
return isset($alterCol) ? $alterCol : '';
}
public function renameTable($oldTableName, $newTableName) {
public function renameTable($oldTableName, $newTableName)
{
$this->query("ALTER TABLE \"$oldTableName\" RENAME TO \"$newTableName\"");
unset(self::$cached_fieldlists[$oldTableName]);
}
public function checkAndRepairTable($tableName) {
public function checkAndRepairTable($tableName)
{
$this->query("VACUUM FULL ANALYZE \"$tableName\"");
$this->query("REINDEX TABLE \"$tableName\"");
return true;
}
public function createField($table, $field, $spec) {
public function createField($table, $field, $spec)
{
$this->query("ALTER TABLE \"$table\" ADD \"$field\" $spec");
}
@ -522,11 +568,13 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param string $fieldName The name of the field to change.
* @param string $fieldSpec The new field specification
*/
public function alterField($tableName, $fieldName, $fieldSpec) {
public function alterField($tableName, $fieldName, $fieldSpec)
{
$this->query("ALTER TABLE \"$tableName\" CHANGE \"$fieldName\" \"$fieldName\" $fieldSpec");
}
public function renameField($tableName, $oldName, $newName) {
public function renameField($tableName, $oldName, $newName)
{
$fieldList = $this->fieldList($tableName);
if (array_key_exists($oldName, $fieldList)) {
$this->query("ALTER TABLE \"$tableName\" RENAME COLUMN \"$oldName\" TO \"$newName\"");
@ -536,7 +584,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
}
}
public function fieldList($table) {
public function fieldList($table)
{
//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....
@ -550,8 +599,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
);
$output = array();
if($fields) foreach($fields as $field) {
if ($fields) {
foreach ($fields as $field) {
switch ($field['data_type']) {
case 'character varying':
//Check to see if there's a constraint attached to this column:
@ -569,17 +618,18 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
$value=str_replace("''", "'", $value);
$in_value=false;
$constraints=Array();
$constraints=array();
$current_value='';
for ($i=0; $i<strlen($value); $i++) {
$char=substr($value, $i, 1);
if($in_value)
if ($in_value) {
$current_value.=$char;
}
if ($char=="'") {
if(!$in_value)
if (!$in_value) {
$in_value=true;
else {
} else {
$in_value=false;
$constraints[]=substr($current_value, 0, -1);
$current_value='';
@ -590,7 +640,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
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));
$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'] . ')';
@ -624,7 +674,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
default:
$output[$field['column_name']] = $field;
}
}
}
// self::$cached_fieldlists[$table]=$output;
@ -635,9 +685,13 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
return $output;
}
function clearCachedFieldlist($tableName=false){
if($tableName) unset(self::$cached_fieldlists[$tableName]);
else self::$cached_fieldlists=array();
public function clearCachedFieldlist($tableName=false)
{
if ($tableName) {
unset(self::$cached_fieldlists[$tableName]);
} else {
self::$cached_fieldlists=array();
}
return true;
}
@ -648,9 +702,12 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param string $indexName The name of the index.
* @param string $indexSpec The specification of the index, see Database::requireIndex() for more details.
*/
public function createIndex($tableName, $indexName, $indexSpec) {
public function createIndex($tableName, $indexName, $indexSpec)
{
$createIndex = $this->getIndexSqlDefinition($tableName, $indexName, $indexSpec);
if($createIndex !== false) $this->query($createIndex);
if ($createIndex !== false) {
$this->query($createIndex);
}
}
/*
@ -683,7 +740,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
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 clustering options
@ -744,7 +802,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
return trim($spec) . ';';
}
public function alterIndex($tableName, $indexName, $indexSpec) {
public function alterIndex($tableName, $indexName, $indexSpec)
{
$indexSpec = trim($indexSpec);
if ($indexSpec[0] != '(') {
list($indexType, $indexFields) = explode(' ', $indexSpec, 2);
@ -766,7 +825,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param string $triggerName Postgres trigger name
* @return array List of columns
*/
protected function extractTriggerColumns($triggerName) {
protected function extractTriggerColumns($triggerName)
{
$trigger = $this->preparedQuery(
"SELECT tgargs FROM pg_catalog.pg_trigger WHERE tgname = ?",
array($triggerName)
@ -796,7 +856,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
return array_slice($argList, 2);
}
public function indexList($table) {
public function indexList($table)
{
//Retrieve a list of indexes for the specified table
$indexes = $this->preparedQuery("
SELECT tablename, indexname, indexdef
@ -851,10 +912,10 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
}
return $indexList;
}
public function tableList() {
public function tableList()
{
$tables = array();
$result = $this->preparedQuery(
"SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = ? AND tablename NOT ILIKE 'pg\\\_%' AND tablename NOT ILIKE 'sql\\\_%'",
@ -874,7 +935,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
*
* @param string $constraint
*/
protected function constraintExists($constraint){
protected function constraintExists($constraint)
{
if (!isset(self::$cached_constraints[$constraint])) {
$exists = $this->preparedQuery("
SELECT conname,pg_catalog.pg_get_constraintdef(r.oid, true)
@ -893,7 +955,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param string $tableName
* @return array List of columns an an associative array with the keys Column and DataType
*/
public function tableDetails($tableName) {
public function tableDetails($tableName)
{
$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 = (
@ -923,7 +986,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param string $triggerName Name of the trigger
* @param string $tableName Name of the table
*/
protected function dropTrigger($triggerName, $tableName){
protected function dropTrigger($triggerName, $tableName)
{
$exists = $this->preparedQuery("
SELECT trigger_name
FROM information_schema.triggers
@ -941,7 +1005,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param string $trigger Name of the trigger
* @return array
*/
protected function triggerFieldsFromTrigger($trigger) {
protected function triggerFieldsFromTrigger($trigger)
{
if ($trigger) {
$tsvector='tsvector_update_trigger';
$ts_pos=strpos($trigger, $tsvector);
@ -953,8 +1018,9 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
$field_bits=explode(',', str_replace('"', '', $fields));
$result=array();
foreach($field_bits as $field_bit)
foreach ($field_bits as $field_bit) {
$result[]=trim($field_bit);
}
return $result;
} else {
@ -969,7 +1035,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param boolean $asDbValue
* @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:
$default = $values['default'] ? '1' : '0';
@ -995,8 +1062,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param array $values Contains a tokenised list of info about this data type
* @return string
*/
public function date($values){
public function date($values)
{
if (!isset($values['arrayValue'])) {
$values['arrayValue']='';
}
@ -1011,8 +1078,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param boolean $asDbValue
* @return string
*/
public function decimal($values, $asDbValue=false){
public function decimal($values, $asDbValue=false)
{
if (!isset($values['arrayValue'])) {
$values['arrayValue']='';
}
@ -1042,7 +1109,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param array $values Contains a tokenised list of info about this data type
* @return string
*/
public function enum($values){
public function enum($values)
{
//Enums are a bit different. We'll be creating a varchar(255) with a constraint of all the usual enum options.
//NOTE: In this one instance, we are including the table name in the values array
if (!isset($values['arrayValue'])) {
@ -1056,7 +1124,6 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
}
return "varchar(255){$values['arrayValue']}" . $default . " check (\"" . $values['name'] . "\" in ('" . implode('\', \'', $values['enums']) . "'))";
}
/**
@ -1066,7 +1133,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param boolean $asDbValue
* @return string
*/
public function float($values, $asDbValue = false){
public function float($values, $asDbValue = false)
{
if (!isset($values['arrayValue'])) {
$values['arrayValue']='';
}
@ -1085,7 +1153,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param boolean $asDbValue
* @return string
*/
public function double($values, $asDbValue=false){
public function double($values, $asDbValue=false)
{
return $this->float($values, $asDbValue);
}
@ -1096,14 +1165,14 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param boolean $asDbValue
* @return string
*/
public function int($values, $asDbValue = false){
public function int($values, $asDbValue = false)
{
if (!isset($values['arrayValue'])) {
$values['arrayValue']='';
}
if ($asDbValue) {
return Array('data_type'=>'integer', 'precision'=>'32');
return array('data_type'=>'integer', 'precision'=>'32');
}
if ($values['arrayValue']!='') {
@ -1122,14 +1191,14 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param boolean $asDbValue
* @return string
*/
public function bigint($values, $asDbValue = false){
public function bigint($values, $asDbValue = false)
{
if (!isset($values['arrayValue'])) {
$values['arrayValue']='';
}
if ($asDbValue) {
return Array('data_type'=>'bigint', 'precision'=>'64');
return array('data_type'=>'bigint', 'precision'=>'64');
}
if ($values['arrayValue']!='') {
@ -1149,8 +1218,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param boolean $asDbValue
* @return string
*/
public function SS_Datetime($values, $asDbValue = false){
public function SS_Datetime($values, $asDbValue = false)
{
if (!isset($values['arrayValue'])) {
$values['arrayValue']='';
}
@ -1169,8 +1238,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param boolean $asDbValue
* @return string
*/
public function text($values, $asDbValue = false){
public function text($values, $asDbValue = false)
{
if (!isset($values['arrayValue'])) {
$values['arrayValue'] = '';
}
@ -1188,7 +1257,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param array $values Contains a tokenised list of info about this data type
* @return string
*/
public function time($values){
public function time($values)
{
if (!isset($values['arrayValue'])) {
$values['arrayValue'] = '';
}
@ -1203,8 +1273,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param boolean $asDbValue
* @return string
*/
public function varchar($values, $asDbValue=false){
public function varchar($values, $asDbValue=false)
{
if (!isset($values['arrayValue'])) {
$values['arrayValue'] = '';
}
@ -1228,8 +1298,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param boolean $asDbValue
* @return string
*/
public function year($values, $asDbValue = false){
public function year($values, $asDbValue = false)
{
if (!isset($values['arrayValue'])) {
$values['arrayValue'] = '';
}
@ -1253,7 +1323,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param string $name
* @param array $spec
*/
protected function fulltext($this_index, $tableName, $name){
protected function fulltext($this_index, $tableName, $name)
{
//For full text search, we need to create a column for the index
$columns = $this->quoteColumnSpecString($this_index['value']);
@ -1274,12 +1345,17 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
);
}
public function IdColumn($asDbValue = false, $hasAutoIncPK = true){
if($asDbValue) return 'bigint';
else return 'serial8 not null';
public function IdColumn($asDbValue = false, $hasAutoIncPK = true)
{
if ($asDbValue) {
return 'bigint';
} else {
return 'serial8 not null';
}
}
public function hasTable($tableName) {
public function hasTable($tableName)
{
$result = $this->preparedQuery(
"SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = ? AND tablename = ?;",
array($this->database->currentSchema(), $tableName)
@ -1296,7 +1372,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param string $fieldName name of enum field to check
* @return array List of enum values
*/
public function enumValuesForField($tableName, $fieldName) {
public function enumValuesForField($tableName, $fieldName)
{
//return array('SiteTree','Page');
$constraints = $this->constraintExists("{$tableName}_{$fieldName}_check");
if ($constraints) {
@ -1312,7 +1389,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param string $constraint
* @return array
*/
protected function enumValuesFromConstraint($constraint){
protected function enumValuesFromConstraint($constraint)
{
$constraint = substr($constraint, strpos($constraint, 'ANY (ARRAY[')+11);
$constraint = substr($constraint, 0, -11);
$constraints = array();
@ -1324,13 +1402,17 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
return $constraints;
}
public function dbDataType($type){
public function dbDataType($type)
{
$values = array(
'unsigned integer' => 'INT'
);
if(isset($values[$type])) return $values[$type];
else return '';
if (isset($values[$type])) {
return $values[$type];
} else {
return '';
}
}
/*
@ -1340,7 +1422,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param string $name
* @param string $location
*/
public function createOrReplaceTablespace($name, $location){
public function createOrReplaceTablespace($name, $location)
{
$existing = $this->preparedQuery(
"SELECT spcname, spclocation FROM pg_tablespace WHERE spcname = ?;",
array($name)
@ -1366,7 +1449,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param array $indexes
* @param array $extensions
*/
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:
$this->createLanguage('plpgsql');
@ -1413,7 +1497,6 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
// We need to propogate the indexes through to the child pages.
// Some of this code is duplicated, and could be tidied up
foreach ($indexes as $name => $this_index) {
if ($this_index['type']=='fulltext') {
$fillfactor = $where = '';
if (isset($this_index['fillfactor'])) {
@ -1427,7 +1510,6 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
$ts_details = $this->fulltext($this_index, $partition_name, $name);
$this->query($ts_details['triggers']);
} else {
if (is_array($this_index)) {
$index_name = $this_index['name'];
} else {
@ -1460,7 +1542,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
*
* @param string $language Language name
*/
public function createLanguage($language){
public function createLanguage($language)
{
$result = $this->preparedQuery(
"SELECT lanname FROM pg_language WHERE lanname = ?;",
array($language)
@ -1480,7 +1563,8 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
* @param array $values Contains a tokenised list of info about this data type
* @return string
*/
public function set($values){
public function set($values)
{
user_error("PostGreSQL does not support multi-enum", E_USER_ERROR);
return "int";
}

View File

@ -5,9 +5,11 @@
*
* @author Damian
*/
class PostgreSQLConnectorTest extends SapphireTest {
class PostgreSQLConnectorTest extends SapphireTest
{
public function testSubstitutesPlaceholders() {
public function testSubstitutesPlaceholders()
{
$connector = new PostgreSQLConnector();
// basic case

View File

@ -3,14 +3,14 @@
* @package postgresql
* @subpackage tests
*/
class PostgreSQLDatabaseTest extends SapphireTest {
function testReadOnlyTransaction(){
class PostgreSQLDatabaseTest extends SapphireTest
{
public function testReadOnlyTransaction()
{
if (
DB::get_conn()->supportsTransactions() == true
&& DB::get_conn() instanceof PostgreSQLDatabase
) {
$page=new Page();
$page->Title='Read only success';
$page->write();
@ -39,10 +39,8 @@ class PostgreSQLDatabaseTest extends SapphireTest {
//This page should NOT exist, we had 'read only' permissions
$this->assertFalse(is_object($fail) && $fail->exists());
} else {
$this->markTestSkipped('Current database is not PostgreSQL');
}
}
}