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

View File

@ -6,7 +6,8 @@
* @package sapphire * @package sapphire
* @subpackage model * @subpackage model
*/ */
class PostgreSQLDatabase extends SS_Database { class PostgreSQLDatabase extends SS_Database
{
/** /**
* Database schema manager object * Database schema manager object
@ -33,7 +34,8 @@ class PostgreSQLDatabase extends SS_Database {
* *
* @return string * @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'); return Config::inst()->get('PostgreSQLDatabase', 'default_fts_cluster_method');
} }
@ -42,7 +44,8 @@ class PostgreSQLDatabase extends SS_Database {
* *
* @return string * @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'); 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 * then attempts to create or check databases beyond the initial connection will
* result in a runtime error. * 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'); 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, * 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 * 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'); return Config::inst()->get('PostgreSQLDatabase', 'model_schema_as_database');
} }
@ -82,7 +87,8 @@ class PostgreSQLDatabase extends SS_Database {
* *
* @var string * @var string
*/ */
public static function search_language() { public static function search_language()
{
return Config::inst()->get('PostgreSQLDatabase', 'search_language'); return Config::inst()->get('PostgreSQLDatabase', 'search_language');
} }
@ -109,7 +115,8 @@ class PostgreSQLDatabase extends SS_Database {
*/ */
protected $parameters = array(); protected $parameters = array();
public function connect($parameters) { public function connect($parameters)
{
// Check database name // Check database name
if (empty($parameters['database'])) { if (empty($parameters['database'])) {
// Check if we can use the master 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 = $this->parameters;
$parameters['database'] = self::MASTER_DATABASE; $parameters['database'] = self::MASTER_DATABASE;
$this->connector->connect($parameters, true); $this->connector->connect($parameters, true);
} }
protected function connectDefault() { protected function connectDefault()
{
$parameters = $this->parameters; $parameters = $this->parameters;
$parameters['database'] = $this->databaseOriginal; $parameters['database'] = $this->databaseOriginal;
$this->connector->connect($parameters, true); $this->connector->connect($parameters, true);
@ -178,20 +187,26 @@ class PostgreSQLDatabase extends SS_Database {
* *
* @param string $timezone * @param string $timezone
*/ */
public function selectTimezone($timezone) { public function selectTimezone($timezone)
if (empty($timezone)) return; {
if (empty($timezone)) {
return;
}
$this->query("SET SESSION TIME ZONE '$timezone';"); $this->query("SET SESSION TIME ZONE '$timezone';");
} }
public function supportsCollations() { public function supportsCollations()
{
return true; return true;
} }
public function supportsTimezoneOverride() { public function supportsTimezoneOverride()
{
return true; return true;
} }
public function getDatabaseServer() { public function getDatabaseServer()
{
return "postgresql"; return "postgresql";
} }
@ -200,7 +215,8 @@ class PostgreSQLDatabase extends SS_Database {
* *
* @return string Name of current schema * @return string Name of current schema
*/ */
public function currentSchema() { public function currentSchema()
{
return $this->schema; return $this->schema;
} }
@ -216,7 +232,8 @@ class PostgreSQLDatabase extends SS_Database {
* the query, or false if no error should be raised * the query, or false if no error should be raised
* @return boolean Flag indicating success * @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)) { if (!$this->schemaManager->schemaExists($schema)) {
// Check DB creation permisson // Check DB creation permisson
if (!$create) { if (!$create) {
@ -245,7 +262,8 @@ class PostgreSQLDatabase extends SS_Database {
* @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) {
user_error('At least one Schema must be supplied to set a search path.', E_USER_ERROR); 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 * @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.
@ -279,7 +298,9 @@ class PostgreSQLDatabase extends SS_Database {
WHERE data_type='tsvector' AND table_name in ($classesPlaceholders);", WHERE data_type='tsvector' AND table_name in ($classesPlaceholders);",
$classesToSearch $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();
$tableParameters = array(); $tableParameters = array();
@ -347,8 +368,11 @@ class PostgreSQLDatabase extends SS_Database {
$limit = $pageLength; $limit = $pageLength;
$offset = $start; $offset = $start;
if($keywords) $orderBy = " ORDER BY $sortBy"; if ($keywords) {
else $orderBy=''; $orderBy = " ORDER BY $sortBy";
} 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";
@ -360,8 +384,11 @@ class PostgreSQLDatabase extends SS_Database {
$totalCount++; $totalCount++;
} }
if(isset($objects)) $results = new ArrayList($objects); if (isset($objects)) {
else $results = new ArrayList(); $results = new ArrayList($objects);
} else {
$results = new ArrayList();
}
$list = new PaginatedList($results); $list = new PaginatedList($results);
$list->setLimitItems(false); $list->setLimitItems(false);
$list->setPageStart($start); $list->setPageStart($start);
@ -370,21 +397,29 @@ class PostgreSQLDatabase extends SS_Database {
return $list; return $list;
} }
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
*/ */
public function supportsExtensions($extensions=Array('partitions', 'tablespaces', 'clustering')){ public function supportsExtensions($extensions=array('partitions', 'tablespaces', 'clustering'))
if(isset($extensions['partitions'])) return true; {
elseif(isset($extensions['tablespaces'])) return true; if (isset($extensions['partitions'])) {
elseif(isset($extensions['clustering'])) return true; return true;
else return false; } 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;'); $this->query('BEGIN;');
if ($transaction_mode) { if ($transaction_mode) {
@ -396,11 +431,13 @@ class PostgreSQLDatabase extends SS_Database {
} }
} }
public function transactionSavepoint($savepoint){ public function transactionSavepoint($savepoint)
{
$this->query("SAVEPOINT {$savepoint};"); $this->query("SAVEPOINT {$savepoint};");
} }
public function transactionRollback($savepoint = false){ public function transactionRollback($savepoint = false)
{
if ($savepoint) { if ($savepoint) {
$this->query("ROLLBACK TO {$savepoint};"); $this->query("ROLLBACK TO {$savepoint};");
} else { } else {
@ -408,16 +445,20 @@ class PostgreSQLDatabase extends SS_Database {
} }
} }
public function transactionEnd($chain = false){ public function transactionEnd($chain = false)
{
$this->query('COMMIT;'); $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) { if ($exact && $caseSensitive === null) {
$comp = ($negate) ? '!=' : '='; $comp = ($negate) ? '!=' : '=';
} else { } else {
$comp = ($caseSensitive === true) ? 'LIKE' : 'ILIKE'; $comp = ($caseSensitive === true) ? 'LIKE' : 'ILIKE';
if($negate) $comp = 'NOT ' . $comp; if ($negate) {
$comp = 'NOT ' . $comp;
}
$field.='::text'; $field.='::text';
} }
@ -442,7 +483,8 @@ class PostgreSQLDatabase extends SS_Database {
* %U = unix timestamp, can only be used on it's own * %U = unix timestamp, can only be used on it's own
* @return string SQL datetime expression to query for a formatted datetime * @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); preg_match_all('/%(.)/', $format, $matches);
foreach ($matches[1] as $match) { foreach ($matches[1] as $match) {
if (array_search($match, array('Y', 'm', 'd', 'H', 'i', 's', 'U')) === false) { 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'"; $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')"; return "to_char($date, TEXT '$format')";
} }
/** /**
@ -487,7 +530,8 @@ class PostgreSQLDatabase extends SS_Database {
* This includes the singular forms as well * 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 * @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)) { if (preg_match('/^now$/i', $date)) {
$date = "NOW()"; $date = "NOW()";
} elseif (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date)) { } 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"' * @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 * @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)) { if (preg_match('/^now$/i', $date1)) {
$date1 = "NOW()"; $date1 = "NOW()";
} elseif (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date1)) { } 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)))"; return "(FLOOR(EXTRACT(epoch FROM $date1)) - FLOOR(EXTRACT(epoch from $date2)))";
} }
function now(){ public function now()
{
return 'NOW()'; return 'NOW()';
} }
function random(){ public function random()
{
return 'RANDOM()'; return 'RANDOM()';
} }
@ -538,7 +585,8 @@ class PostgreSQLDatabase extends SS_Database {
* @param string $schema Name of the schema * @param string $schema Name of the schema
* @return string Name of the database to report * @return string Name of the database to report
*/ */
public function schemaToDatabaseName($schema) { public function schemaToDatabaseName($schema)
{
switch ($schema) { switch ($schema) {
case $this->schemaOriginal: return $this->databaseOriginal; case $this->schemaOriginal: return $this->databaseOriginal;
default: return $schema; default: return $schema;
@ -552,18 +600,22 @@ class PostgreSQLDatabase extends SS_Database {
* @param string $database Name of the database * @param string $database Name of the database
* @return string Name of the schema to use for this database internally * @return string Name of the schema to use for this database internally
*/ */
public function databaseToSchemaName($database) { public function databaseToSchemaName($database)
{
switch ($database) { switch ($database) {
case $this->databaseOriginal: return $this->schemaOriginal; case $this->databaseOriginal: return $this->schemaOriginal;
default: return $database; default: return $database;
} }
} }
public function dropSelectedDatabase() { public function dropSelectedDatabase()
{
if (self::model_schema_as_database()) { if (self::model_schema_as_database()) {
// Check current schema is valid // Check current schema is valid
$oldSchema = $this->schema; $oldSchema = $this->schema;
if(empty($oldSchema)) return true; // Nothing selected to drop if (empty($oldSchema)) {
return true;
} // Nothing selected to drop
// Select another schema // Select another schema
if ($oldSchema !== $this->schemaOriginal) { 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()) { if (self::model_schema_as_database()) {
return $this->schemaToDatabaseName($this->schema); return $this->schemaToDatabaseName($this->schema);
} }
return parent::getSelectedDatabase(); 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 // Substitute schema here as appropriate
if (self::model_schema_as_database()) { if (self::model_schema_as_database()) {
// Selecting the database itself should be treated as selecting the public schema // Selecting the database itself should be treated as selecting the public schema
@ -626,7 +680,8 @@ class PostgreSQLDatabase extends SS_Database {
* *
* @param string $table * @param string $table
*/ */
public function clearTable($table) { public function clearTable($table)
{
$this->query('DELETE FROM "'.$table.'";'); $this->query('DELETE FROM "'.$table.'";');
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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