mirror of
https://github.com/silverstripe/silverstripe-postgresql
synced 2024-10-22 17:05:45 +02:00
Merge pull request #46 from helpfulrobot/convert-to-psr-2
Converted to PSR-2
This commit is contained in:
commit
934fa61433
@ -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) {
|
||||
if(empty($parameters[$key])) {
|
||||
if($default === null) return '';
|
||||
protected function escapeParameter($parameters, $key, $name, $default = null)
|
||||
{
|
||||
if (empty($parameters[$key])) {
|
||||
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,19 +83,21 @@ 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));
|
||||
if($this->dbConn === false) {
|
||||
if ($this->dbConn === false) {
|
||||
// Extract error details from PHP error handling
|
||||
$error = error_get_last();
|
||||
if($error && preg_match('/function\\.pg-connect\\<\\/a\\>\\]\\: (?<message>.*)/', $error['message'], $matches)) {
|
||||
if ($error && preg_match('/function\\.pg-connect\\<\\/a\\>\\]\\: (?<message>.*)/', $error['message'], $matches)) {
|
||||
$this->databaseError(html_entity_decode($matches['message']));
|
||||
} else {
|
||||
$this->databaseError("Couldn't connect to PostgreSQL database.");
|
||||
}
|
||||
} elseif(pg_connection_status($this->dbConn) != PGSQL_CONNECTION_OK) {
|
||||
} elseif (pg_connection_status($this->dbConn) != PGSQL_CONNECTION_OK) {
|
||||
throw new ErrorException($this->getLastError());
|
||||
}
|
||||
|
||||
@ -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,25 +174,28 @@ 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;
|
||||
$num = 0;
|
||||
for($i = 0; $i < count($segments); $i++) {
|
||||
for ($i = 0; $i < count($segments); $i++) {
|
||||
// Append next segment
|
||||
$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])) {
|
||||
if ($this->checkStringTogglesLiteral($segments[$i])) {
|
||||
$inString = !$inString;
|
||||
}
|
||||
|
||||
// Append placeholder replacement
|
||||
if($inString) {
|
||||
if ($inString) {
|
||||
$joined .= "?";
|
||||
} else {
|
||||
$joined .= '$' . ++$num;
|
||||
@ -184,19 +204,20 @@ 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;
|
||||
|
||||
// Replace question mark placeholders with numeric placeholders
|
||||
if(!empty($parameters)) {
|
||||
if (!empty($parameters)) {
|
||||
$sql = $this->replacePlaceholders($sql);
|
||||
$parameters = $this->parameterValues($parameters);
|
||||
}
|
||||
|
||||
// Execute query
|
||||
if(!empty($parameters)) {
|
||||
if (!empty($parameters)) {
|
||||
$result = pg_query_params($this->dbConn, $sql, $parameters);
|
||||
} else {
|
||||
$result = pg_query($this->dbConn, $sql);
|
||||
@ -214,39 +235,45 @@ 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) {
|
||||
if(function_exists('pg_escape_literal')) {
|
||||
public function quoteString($value)
|
||||
{
|
||||
if (function_exists('pg_escape_literal')) {
|
||||
return pg_escape_literal($this->dbConn, $value);
|
||||
} else {
|
||||
return "'" . $this->escapeString($value) . "'";
|
||||
}
|
||||
}
|
||||
|
||||
public function escapeString($value) {
|
||||
public function escapeString($value)
|
||||
{
|
||||
return pg_escape_string($this->dbConn, $value);
|
||||
}
|
||||
|
||||
public function escapeIdentifier($value, $separator = '.') {
|
||||
if(empty($separator) && function_exists('pg_escape_identifier')) {
|
||||
public function escapeIdentifier($value, $separator = '.')
|
||||
{
|
||||
if (empty($separator) && function_exists('pg_escape_identifier')) {
|
||||
return pg_escape_identifier($this->dbConn, $value);
|
||||
}
|
||||
|
||||
// Let parent function handle recursive calls
|
||||
return parent::escapeIdentifier ($value, $separator);
|
||||
return parent::escapeIdentifier($value, $separator);
|
||||
}
|
||||
|
||||
public function selectDatabase($name) {
|
||||
if($name !== $this->databaseName) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
@ -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,11 +115,12 @@ class PostgreSQLDatabase extends SS_Database {
|
||||
*/
|
||||
protected $parameters = array();
|
||||
|
||||
public function connect($parameters) {
|
||||
public function connect($parameters)
|
||||
{
|
||||
// Check database name
|
||||
if(empty($parameters['database'])) {
|
||||
if (empty($parameters['database'])) {
|
||||
// Check if we can use the master database
|
||||
if(!self::allow_query_master_postgres()) {
|
||||
if (!self::allow_query_master_postgres()) {
|
||||
throw new ErrorException('PostegreSQLDatabase::connect called without a database name specified');
|
||||
}
|
||||
// Fallback to master database connection if permission allows
|
||||
@ -122,18 +129,18 @@ class PostgreSQLDatabase extends SS_Database {
|
||||
$this->databaseOriginal = $parameters['database'];
|
||||
|
||||
// check schema name
|
||||
if(empty($parameters['schema'])) {
|
||||
if (empty($parameters['schema'])) {
|
||||
$parameters['schema'] = self::MASTER_SCHEMA;
|
||||
}
|
||||
$this->schemaOriginal = $parameters['schema'];
|
||||
|
||||
// Ensure that driver is available (required by PDO)
|
||||
if(empty($parameters['driver'])) {
|
||||
if (empty($parameters['driver'])) {
|
||||
$parameters['driver'] = $this->getDatabaseServer();
|
||||
}
|
||||
|
||||
// Ensure port number is set (required by postgres)
|
||||
if(empty($parameters['port'])) {
|
||||
if (empty($parameters['port'])) {
|
||||
$parameters['port'] = 5432;
|
||||
}
|
||||
|
||||
@ -141,10 +148,10 @@ class PostgreSQLDatabase extends SS_Database {
|
||||
|
||||
// If allowed, check that the database exists. Otherwise naively assume
|
||||
// that the original database exists
|
||||
if(self::allow_query_master_postgres()) {
|
||||
if (self::allow_query_master_postgres()) {
|
||||
// Use master connection to setup initial schema
|
||||
$this->connectMaster();
|
||||
if(!$this->schemaManager->postgresDatabaseExists($this->databaseOriginal)) {
|
||||
if (!$this->schemaManager->postgresDatabaseExists($this->databaseOriginal)) {
|
||||
$this->schemaManager->createPostgresDatabase($this->databaseOriginal);
|
||||
}
|
||||
}
|
||||
@ -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,8 +232,9 @@ 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) {
|
||||
if(!$this->schemaManager->schemaExists($schema)) {
|
||||
public function setSchema($schema, $create = false, $errorLevel = E_USER_ERROR)
|
||||
{
|
||||
if (!$this->schemaManager->schemaExists($schema)) {
|
||||
// Check DB creation permisson
|
||||
if (!$create) {
|
||||
if ($errorLevel !== false) {
|
||||
@ -245,8 +262,9 @@ class PostgreSQLDatabase extends SS_Database {
|
||||
* @param string $arg2 Second schema to use
|
||||
* @param string $argN Nth schema to use
|
||||
*/
|
||||
public function setSchemaSearchPath() {
|
||||
if(func_num_args() == 0) {
|
||||
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);
|
||||
}
|
||||
$schemas = array_values(func_get_args());
|
||||
@ -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();
|
||||
@ -312,9 +333,9 @@ class PostgreSQLDatabase extends SS_Database {
|
||||
)
|
||||
);
|
||||
|
||||
foreach($result as $row){
|
||||
foreach ($result as $row) {
|
||||
$conditions = array();
|
||||
if($row['table_name'] === 'SiteTree' || $row['table_name'] === 'File') {
|
||||
if ($row['table_name'] === 'SiteTree' || $row['table_name'] === 'File') {
|
||||
$conditions[] = array('"ShowInSearch"' => 1);
|
||||
}
|
||||
|
||||
@ -328,8 +349,8 @@ class PostgreSQLDatabase extends SS_Database {
|
||||
));
|
||||
$query->setSelect(array());
|
||||
|
||||
foreach($select[$row['table_name']] as $clause) {
|
||||
if(preg_match('/^(.*) +AS +"?([^"]*)"?/i', $clause, $matches)) {
|
||||
foreach ($select[$row['table_name']] as $clause) {
|
||||
if (preg_match('/^(.*) +AS +"?([^"]*)"?/i', $clause, $matches)) {
|
||||
$query->selectField($matches[1], $matches[2]);
|
||||
} else {
|
||||
$query->selectField($clause);
|
||||
@ -347,21 +368,27 @@ 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";
|
||||
|
||||
// Get records
|
||||
$records = $this->preparedQuery($fullQuery, $tableParameters);
|
||||
$totalCount=0;
|
||||
foreach($records as $record){
|
||||
foreach ($records as $record) {
|
||||
$objects[] = new $record['ClassName']($record);
|
||||
$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,58 +397,72 @@ 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) {
|
||||
if ($transaction_mode) {
|
||||
$this->query("SET TRANSACTION {$transaction_mode};");
|
||||
}
|
||||
|
||||
if($session_characteristics) {
|
||||
if ($session_characteristics) {
|
||||
$this->query("SET SESSION CHARACTERISTICS AS TRANSACTION {$session_characteristics};");
|
||||
}
|
||||
}
|
||||
|
||||
public function transactionSavepoint($savepoint){
|
||||
public function transactionSavepoint($savepoint)
|
||||
{
|
||||
$this->query("SAVEPOINT {$savepoint};");
|
||||
}
|
||||
|
||||
public function transactionRollback($savepoint = false){
|
||||
if($savepoint) {
|
||||
public function transactionRollback($savepoint = false)
|
||||
{
|
||||
if ($savepoint) {
|
||||
$this->query("ROLLBACK TO {$savepoint};");
|
||||
} else {
|
||||
$this->query('ROLLBACK;');
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
if($exact && $caseSensitive === null) {
|
||||
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';
|
||||
}
|
||||
|
||||
if($parameterised) {
|
||||
if ($parameterised) {
|
||||
return sprintf("%s %s ?", $field, $comp);
|
||||
} else {
|
||||
return sprintf("%s %s '%s'", $field, $comp, $value);
|
||||
@ -442,10 +483,11 @@ 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) {
|
||||
foreach ($matches[1] as $match) {
|
||||
if (array_search($match, array('Y', 'm', 'd', 'H', 'i', 's', 'U')) === false) {
|
||||
user_error('formattedDatetimeClause(): unsupported format character %' . $match, E_USER_WARNING);
|
||||
}
|
||||
}
|
||||
@ -460,16 +502,17 @@ class PostgreSQLDatabase extends SS_Database {
|
||||
);
|
||||
$format = preg_replace(array_keys($translate), array_values($translate), $format);
|
||||
|
||||
if(preg_match('/^now$/i', $date)) {
|
||||
if (preg_match('/^now$/i', $date)) {
|
||||
$date = "NOW()";
|
||||
} else if(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)) {
|
||||
$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,10 +530,11 @@ 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) {
|
||||
if(preg_match('/^now$/i', $date)) {
|
||||
public function datetimeIntervalClause($date, $interval)
|
||||
{
|
||||
if (preg_match('/^now$/i', $date)) {
|
||||
$date = "NOW()";
|
||||
} else if(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)) {
|
||||
$date = "TIMESTAMP '$date'";
|
||||
}
|
||||
|
||||
@ -506,27 +550,30 @@ 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) {
|
||||
if(preg_match('/^now$/i', $date1)) {
|
||||
public function datetimeDifferenceClause($date1, $date2)
|
||||
{
|
||||
if (preg_match('/^now$/i', $date1)) {
|
||||
$date1 = "NOW()";
|
||||
} else if(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)) {
|
||||
$date1 = "TIMESTAMP '$date1'";
|
||||
}
|
||||
|
||||
if(preg_match('/^now$/i', $date2)) {
|
||||
if (preg_match('/^now$/i', $date2)) {
|
||||
$date2 = "NOW()";
|
||||
} else if(preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date2)) {
|
||||
} elseif (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date2)) {
|
||||
$date2 = "TIMESTAMP '$date2'";
|
||||
}
|
||||
|
||||
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,8 +585,9 @@ class PostgreSQLDatabase extends SS_Database {
|
||||
* @param string $schema Name of the schema
|
||||
* @return string Name of the database to report
|
||||
*/
|
||||
public function schemaToDatabaseName($schema) {
|
||||
switch($schema) {
|
||||
public function schemaToDatabaseName($schema)
|
||||
{
|
||||
switch ($schema) {
|
||||
case $this->schemaOriginal: return $this->databaseOriginal;
|
||||
default: return $schema;
|
||||
}
|
||||
@ -552,23 +600,27 @@ 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) {
|
||||
switch($database) {
|
||||
public function databaseToSchemaName($database)
|
||||
{
|
||||
switch ($database) {
|
||||
case $this->databaseOriginal: return $this->schemaOriginal;
|
||||
default: return $database;
|
||||
}
|
||||
}
|
||||
|
||||
public function dropSelectedDatabase() {
|
||||
if(self::model_schema_as_database()) {
|
||||
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) {
|
||||
if ($oldSchema !== $this->schemaOriginal) {
|
||||
$this->setSchema($this->schemaOriginal);
|
||||
} elseif($oldSchema !== self::MASTER_SCHEMA) {
|
||||
} elseif ($oldSchema !== self::MASTER_SCHEMA) {
|
||||
$this->setSchema(self::MASTER_SCHEMA);
|
||||
} else {
|
||||
$this->schema = null;
|
||||
@ -581,16 +633,18 @@ class PostgreSQLDatabase extends SS_Database {
|
||||
}
|
||||
}
|
||||
|
||||
public function getSelectedDatabase() {
|
||||
if(self::model_schema_as_database()) {
|
||||
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()) {
|
||||
if (self::model_schema_as_database()) {
|
||||
// Selecting the database itself should be treated as selecting the public schema
|
||||
$schemaName = $this->databaseToSchemaName($name);
|
||||
return $this->setSchema($schemaName, $create, $errorLevel);
|
||||
@ -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.'";');
|
||||
}
|
||||
}
|
||||
|
@ -7,7 +7,8 @@
|
||||
*
|
||||
* @package postgresql
|
||||
*/
|
||||
class PostgreSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper {
|
||||
class PostgreSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper
|
||||
{
|
||||
|
||||
/**
|
||||
* Create a connection of the appropriate type
|
||||
@ -16,14 +17,15 @@ 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'];
|
||||
$server = $databaseConfig['server'];
|
||||
|
||||
try {
|
||||
switch($databaseConfig['type']) {
|
||||
switch ($databaseConfig['type']) {
|
||||
case 'PostgreSQLDatabase':
|
||||
$userPart = $username ? " user=$username" : '';
|
||||
$passwordPart = $password ? " password=$password" : '';
|
||||
@ -38,11 +40,11 @@ class PostgreSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelp
|
||||
$error = 'Invalid connection type';
|
||||
return null;
|
||||
}
|
||||
} catch(Exception $ex) {
|
||||
} catch (Exception $ex) {
|
||||
$error = $ex->getMessage();
|
||||
return null;
|
||||
}
|
||||
if($conn) {
|
||||
if ($conn) {
|
||||
return $conn;
|
||||
} else {
|
||||
$error = 'PostgreSQL requires a valid username and password to determine if the server exists.';
|
||||
@ -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,13 +79,14 @@ class PostgreSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelp
|
||||
);
|
||||
}
|
||||
|
||||
public function getDatabaseVersion($databaseConfig) {
|
||||
public function getDatabaseVersion($databaseConfig)
|
||||
{
|
||||
$conn = $this->createConnection($databaseConfig, $error);
|
||||
if(!$conn) {
|
||||
if (!$conn) {
|
||||
return false;
|
||||
} elseif($conn instanceof PDO) {
|
||||
} elseif ($conn instanceof PDO) {
|
||||
return $conn->getAttribute(PDO::ATTR_SERVER_VERSION);
|
||||
} elseif(is_resource($conn)) {
|
||||
} elseif (is_resource($conn)) {
|
||||
$info = pg_version($conn);
|
||||
return $info['server'];
|
||||
} else {
|
||||
@ -94,14 +100,15 @@ 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);
|
||||
|
||||
if($version) {
|
||||
if ($version) {
|
||||
$success = version_compare($version, '8.3', '>=');
|
||||
if(!$success) {
|
||||
if (!$success) {
|
||||
$error = "Your PostgreSQL version is $version. It's recommended you use at least 8.3.";
|
||||
}
|
||||
} else {
|
||||
@ -121,10 +128,11 @@ class PostgreSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelp
|
||||
* @param string $value Value to quote
|
||||
* @return string Quoted strieng
|
||||
*/
|
||||
protected function quote($conn, $value) {
|
||||
if($conn instanceof PDO) {
|
||||
protected function quote($conn, $value)
|
||||
{
|
||||
if ($conn instanceof PDO) {
|
||||
return $conn->quote($value);
|
||||
} elseif(is_resource($conn)) {
|
||||
} elseif (is_resource($conn)) {
|
||||
return "'".pg_escape_string($conn, $value)."'";
|
||||
} else {
|
||||
user_error('Invalid database connection', E_USER_ERROR);
|
||||
@ -138,13 +146,14 @@ 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) {
|
||||
if ($conn instanceof PDO) {
|
||||
foreach ($conn->query($sql) as $row) {
|
||||
$items[] = $row[0];
|
||||
}
|
||||
} elseif(is_resource($conn)) {
|
||||
} elseif (is_resource($conn)) {
|
||||
$result = pg_query($conn, $sql);
|
||||
while ($row = pg_fetch_row($result)) {
|
||||
$items[] = $row[0];
|
||||
@ -153,15 +162,16 @@ class PostgreSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelp
|
||||
return $items;
|
||||
}
|
||||
|
||||
public function requireDatabaseOrCreatePermissions($databaseConfig) {
|
||||
public function requireDatabaseOrCreatePermissions($databaseConfig)
|
||||
{
|
||||
$success = false;
|
||||
$alreadyExists = false;
|
||||
$conn = $this->createConnection($databaseConfig, $error);
|
||||
if($conn) {
|
||||
if ($conn) {
|
||||
// Check if db already exists
|
||||
$existingDatabases = $this->query($conn, "SELECT datname FROM pg_database");
|
||||
$alreadyExists = in_array($databaseConfig['database'], $existingDatabases);
|
||||
if($alreadyExists) {
|
||||
if ($alreadyExists) {
|
||||
$success = true;
|
||||
} else {
|
||||
// Check if this user has create privileges
|
||||
@ -176,9 +186,10 @@ class PostgreSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelp
|
||||
);
|
||||
}
|
||||
|
||||
public function requireDatabaseAlterPermissions($databaseConfig) {
|
||||
public function requireDatabaseAlterPermissions($databaseConfig)
|
||||
{
|
||||
$conn = $this->createConnection($databaseConfig, $error);
|
||||
if($conn) {
|
||||
if ($conn) {
|
||||
// if the account can even log in, it can alter tables
|
||||
return array(
|
||||
'success' => true,
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
@ -1,6 +1,7 @@
|
||||
<?php
|
||||
|
||||
class PostgreSQLQueryBuilder extends DBQueryBuilder {
|
||||
class PostgreSQLQueryBuilder extends DBQueryBuilder
|
||||
{
|
||||
|
||||
/**
|
||||
* Return the LIMIT clause ready for inserting into a query.
|
||||
@ -9,34 +10,36 @@ 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)) {
|
||||
if (! is_array($limit)) {
|
||||
return "{$nl}LIMIT $limit";
|
||||
}
|
||||
|
||||
// Assert that the array version provides the 'limit' key
|
||||
if( ! array_key_exists('limit', $limit) || ($limit['limit'] !== null && ! is_numeric($limit['limit']))) {
|
||||
if (! array_key_exists('limit', $limit) || ($limit['limit'] !== null && ! is_numeric($limit['limit']))) {
|
||||
throw new InvalidArgumentException(
|
||||
'DBQueryBuilder::buildLimitSQL(): Wrong format for $limit: '. var_export($limit, true)
|
||||
);
|
||||
}
|
||||
|
||||
if($limit['limit'] === null) {
|
||||
if ($limit['limit'] === null) {
|
||||
$limit['limit'] = 'ALL';
|
||||
}
|
||||
|
||||
$clause = "{$nl}LIMIT {$limit['limit']}";
|
||||
if(isset($limit['start']) && is_numeric($limit['start']) && $limit['start'] !== 0) {
|
||||
if (isset($limit['start']) && is_numeric($limit['start']) && $limit['start'] !== 0) {
|
||||
$clause .= " OFFSET {$limit['start']}";
|
||||
}
|
||||
return $clause;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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,12 +51,14 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
*
|
||||
* @param string $name
|
||||
*/
|
||||
public function createPostgresDatabase($name) {
|
||||
public function createPostgresDatabase($name)
|
||||
{
|
||||
$this->query("CREATE DATABASE \"$name\";");
|
||||
}
|
||||
|
||||
public function createDatabase($name) {
|
||||
if(PostgreSQLDatabase::model_schema_as_database()) {
|
||||
public function createDatabase($name)
|
||||
{
|
||||
if (PostgreSQLDatabase::model_schema_as_database()) {
|
||||
$schemaName = $this->database->databaseToSchemaName($name);
|
||||
return $this->createSchema($schemaName);
|
||||
}
|
||||
@ -67,13 +71,15 @@ 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) {
|
||||
if(PostgreSQLDatabase::model_schema_as_database()) {
|
||||
public function databaseExists($name)
|
||||
{
|
||||
if (PostgreSQLDatabase::model_schema_as_database()) {
|
||||
$schemaName = $this->database->databaseToSchemaName($name);
|
||||
return $this->schemaExists($schemaName);
|
||||
}
|
||||
@ -85,15 +91,17 @@ 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() {
|
||||
if(PostgreSQLDatabase::model_schema_as_database()) {
|
||||
public function databaseList()
|
||||
{
|
||||
if (PostgreSQLDatabase::model_schema_as_database()) {
|
||||
$schemas = $this->schemaList();
|
||||
$names = array();
|
||||
foreach($schemas as $schema) {
|
||||
foreach ($schemas as $schema) {
|
||||
$names[] = $this->database->schemaToDatabaseName($schema);
|
||||
}
|
||||
return array_unique($names);
|
||||
@ -105,13 +113,15 @@ 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) {
|
||||
if(PostgreSQLDatabase::model_schema_as_database()) {
|
||||
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,13 +178,15 @@ 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])) {
|
||||
}
|
||||
if (!empty($options[self::ID])) {
|
||||
$addOptions = $options[self::ID];
|
||||
} elseif (!empty($options[get_class($this)])) {
|
||||
Deprecation::notice('3.2', 'Use PostgreSQLSchemaManager::ID for referencing postgres-specific table creation options');
|
||||
@ -181,7 +197,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
|
||||
//First of all, does this table already exist
|
||||
$doesExist = $this->hasTable($table);
|
||||
if($doesExist) {
|
||||
if ($doesExist) {
|
||||
// Table already exists, just return the name, in line with baseclass documentation.
|
||||
return $table;
|
||||
}
|
||||
@ -190,9 +206,9 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
//for GiST searches
|
||||
$fulltexts = '';
|
||||
$triggers = '';
|
||||
if($indexes) {
|
||||
foreach($indexes as $name => $this_index){
|
||||
if(is_array($this_index) && $this_index['type'] == 'fulltext') {
|
||||
if ($indexes) {
|
||||
foreach ($indexes as $name => $this_index) {
|
||||
if (is_array($this_index) && $this_index['type'] == 'fulltext') {
|
||||
$ts_details = $this->fulltext($this_index, $table, $name);
|
||||
$fulltexts .= $ts_details['fulltexts'] . ', ';
|
||||
$triggers .= $ts_details['triggers'];
|
||||
@ -200,19 +216,22 @@ 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'])){
|
||||
if ($advancedOptions && isset($advancedOptions['tablespace'])) {
|
||||
$this->createOrReplaceTablespace(
|
||||
$advancedOptions['tablespace']['name'],
|
||||
$advancedOptions['tablespace']['location']
|
||||
);
|
||||
$tableSpace = ' TABLESPACE ' . $advancedOptions['tablespace']['name'];
|
||||
} else
|
||||
} else {
|
||||
$tableSpace = '';
|
||||
}
|
||||
|
||||
$this->query("CREATE TABLE \"$table\" (
|
||||
$fieldSchemas
|
||||
@ -220,17 +239,17 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
primary key (\"ID\")
|
||||
)$tableSpace; $indexSchemas $addOptions");
|
||||
|
||||
if($triggers!=''){
|
||||
if ($triggers!='') {
|
||||
$this->query($triggers);
|
||||
}
|
||||
|
||||
//If we have a partitioning requirement, we do that here:
|
||||
if($advancedOptions && isset($advancedOptions['partitions'])){
|
||||
if ($advancedOptions && isset($advancedOptions['partitions'])) {
|
||||
$this->createOrReplacePartition($table, $advancedOptions['partitions'], $indexes, $advancedOptions);
|
||||
}
|
||||
|
||||
//Lastly, clustering goes here:
|
||||
if($advancedOptions && isset($advancedOptions['cluster'])){
|
||||
if ($advancedOptions && isset($advancedOptions['cluster'])) {
|
||||
$this->query("CLUSTER \"$table\" USING \"{$advancedOptions['cluster']}\";");
|
||||
}
|
||||
|
||||
@ -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,25 +287,32 @@ 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?
|
||||
if($alteredOptions && isset($advancedOptions['tablespace'])){
|
||||
if ($alteredOptions && isset($advancedOptions['tablespace'])) {
|
||||
$this->createOrReplaceTablespace($advancedOptions['tablespace']['name'], $advancedOptions['tablespace']['location']);
|
||||
$this->query("ALTER TABLE \"$table\" SET TABLESPACE {$advancedOptions['tablespace']['name']};");
|
||||
}
|
||||
@ -298,12 +325,12 @@ 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);
|
||||
|
||||
if($indexSpec['type']=='fulltext') {
|
||||
if ($indexSpec['type']=='fulltext') {
|
||||
//For full text indexes, we need to drop the trigger, drop the index, AND drop the column
|
||||
|
||||
//Go and get the tsearch details:
|
||||
@ -312,7 +339,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
//Drop this column if it already exists:
|
||||
|
||||
//No IF EXISTS option is available for Postgres <9.0
|
||||
if(array_key_exists($ts_details['ts_name'], $fieldList)){
|
||||
if (array_key_exists($ts_details['ts_name'], $fieldList)) {
|
||||
$fulltexts.="ALTER TABLE \"{$table}\" DROP COLUMN \"{$ts_details['ts_name']}\";";
|
||||
}
|
||||
|
||||
@ -326,20 +353,23 @@ 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
|
||||
//for GiST searches
|
||||
//Pick up the new indexes here:
|
||||
if($indexSpec['type']=='fulltext') {
|
||||
if ($indexSpec['type']=='fulltext') {
|
||||
$ts_details=$this->fulltext($indexSpec, $table, $indexName);
|
||||
if(!isset($fieldList[$ts_details['ts_name']])){
|
||||
if (!isset($fieldList[$ts_details['ts_name']])) {
|
||||
$fulltexts.="ALTER TABLE \"{$table}\" ADD COLUMN {$ts_details['fulltexts']};";
|
||||
$triggers.=$ts_details['triggers'];
|
||||
}
|
||||
@ -347,27 +377,29 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
|
||||
//Check that this index doesn't already exist:
|
||||
$indexes=$this->indexList($table);
|
||||
if(isset($indexes[$indexName])){
|
||||
if (isset($indexes[$indexName])) {
|
||||
$alterIndexList[] = "DROP INDEX IF EXISTS \"$indexNamePG\";";
|
||||
}
|
||||
|
||||
$createIndex=$this->getIndexSqlDefinition($table, $indexName, $indexSpec);
|
||||
if($createIndex!==false)
|
||||
if ($createIndex!==false) {
|
||||
$alterIndexList[] = $createIndex;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if($alterList) {
|
||||
if ($alterList) {
|
||||
$alterations = implode(",\n", $alterList);
|
||||
$this->query("ALTER TABLE \"$table\" " . $alterations);
|
||||
}
|
||||
|
||||
//Do we need to create a tablespace for this item?
|
||||
if($advancedOptions && isset($advancedOptions['extensions']['tablespace'])){
|
||||
if ($advancedOptions && isset($advancedOptions['extensions']['tablespace'])) {
|
||||
$extensions=$advancedOptions['extensions'];
|
||||
$this->createOrReplaceTablespace($extensions['tablespace']['name'], $extensions['tablespace']['location']);
|
||||
}
|
||||
|
||||
if($alteredOptions && isset($this->class) && isset($alteredOptions[$this->class])) {
|
||||
if ($alteredOptions && isset($this->class) && isset($alteredOptions[$this->class])) {
|
||||
$this->query(sprintf("ALTER TABLE \"%s\" %s", $table, $alteredOptions[$this->class]));
|
||||
Database::alteration_message(
|
||||
sprintf("Table %s options changed: %s", $table, $alteredOptions[$this->class]),
|
||||
@ -376,27 +408,33 @@ 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) {
|
||||
if ($triggers) {
|
||||
$this->query($triggers);
|
||||
|
||||
$triggerbits=explode(';', $triggers);
|
||||
foreach($triggerbits as $trigger){
|
||||
foreach ($triggerbits as $trigger) {
|
||||
$trigger_fields=$this->triggerFieldsFromTrigger($trigger);
|
||||
|
||||
if($trigger_fields){
|
||||
if ($trigger_fields) {
|
||||
//We need to run a simple query to force the database to update the triggered columns
|
||||
$this->query("UPDATE \"{$table}\" SET \"{$trigger_fields[0]}\"=\"$trigger_fields[0]\";");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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'])){
|
||||
if ($advancedOptions && isset($advancedOptions['partitions'])) {
|
||||
$this->createOrReplacePartition($table, $advancedOptions['partitions']);
|
||||
}
|
||||
|
||||
@ -423,7 +461,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
array($oid)
|
||||
)->first();
|
||||
|
||||
if($clustered) {
|
||||
if ($clustered) {
|
||||
$this->query("ALTER TABLE \"$table\" SET WITHOUT CLUSTER;");
|
||||
}
|
||||
}
|
||||
@ -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,27 +484,31 @@ 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])) {
|
||||
if (isset($matches[1])) {
|
||||
$alterCol = "ALTER COLUMN \"$colName\" TYPE $matches[1]\n";
|
||||
|
||||
// SET null / not null
|
||||
if(!empty($matches[2])) {
|
||||
if (!empty($matches[2])) {
|
||||
$alterCol .= ",\nALTER COLUMN \"$colName\" SET $matches[2]";
|
||||
}
|
||||
|
||||
// SET default (we drop it first, for reasons of precaution)
|
||||
if(!empty($matches[3])) {
|
||||
if (!empty($matches[3])) {
|
||||
$alterCol .= ",\nALTER COLUMN \"$colName\" DROP DEFAULT";
|
||||
$alterCol .= ",\nALTER COLUMN \"$colName\" SET $matches[3]";
|
||||
}
|
||||
|
||||
// SET check constraint (The constraint HAS to be dropped)
|
||||
$existing_constraint=$this->query("SELECT conname FROM pg_constraint WHERE conname='{$tableName}_{$colName}_check';")->value();
|
||||
if(isset($matches[4])) {
|
||||
if (isset($matches[4])) {
|
||||
//Take this new constraint and see what's outstanding from the target table:
|
||||
$constraint_bits=explode('(', $matches[4]);
|
||||
$constraint_values=trim($constraint_bits[2], ')');
|
||||
@ -476,10 +519,10 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
//We have to run this as a query, not as part of the alteration queries due to the way they are constructed.
|
||||
$updateConstraint='';
|
||||
$updateConstraint.="UPDATE \"{$tableName}\" SET \"$colName\"='$default' WHERE \"$colName\" NOT IN ($constraint_values);";
|
||||
if($this->hasTable("{$tableName}_Live")) {
|
||||
if ($this->hasTable("{$tableName}_Live")) {
|
||||
$updateConstraint.="UPDATE \"{$tableName}_Live\" SET \"$colName\"='$default' WHERE \"$colName\" NOT IN ($constraint_values);";
|
||||
}
|
||||
if($this->hasTable("{$tableName}_versions")) {
|
||||
if ($this->hasTable("{$tableName}_versions")) {
|
||||
$updateConstraint.="UPDATE \"{$tableName}_versions\" SET \"$colName\"='$default' WHERE \"$colName\" NOT IN ($constraint_values);";
|
||||
}
|
||||
|
||||
@ -487,12 +530,12 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
}
|
||||
|
||||
//First, delete any existing constraint on this column, even if it's no longer an enum
|
||||
if($existing_constraint) {
|
||||
if ($existing_constraint) {
|
||||
$alterCol .= ",\nDROP CONSTRAINT \"{$tableName}_{$colName}_check\"";
|
||||
}
|
||||
|
||||
//Now create the constraint (if we've asked for one)
|
||||
if(!empty($matches[4])) {
|
||||
if (!empty($matches[4])) {
|
||||
$alterCol .= ",\nADD CONSTRAINT \"{$tableName}_{$colName}_check\" $matches[4]";
|
||||
}
|
||||
}
|
||||
@ -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,13 +568,15 @@ 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)) {
|
||||
if (array_key_exists($oldName, $fieldList)) {
|
||||
$this->query("ALTER TABLE \"$tableName\" RENAME COLUMN \"$oldName\" TO \"$newName\"");
|
||||
|
||||
//Remove this from the cached list:
|
||||
@ -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,14 +599,14 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
);
|
||||
|
||||
$output = array();
|
||||
if($fields) foreach($fields as $field) {
|
||||
|
||||
switch($field['data_type']){
|
||||
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:
|
||||
//$constraint=$this->query("SELECT conname,pg_catalog.pg_get_constraintdef(r.oid, true) FROM pg_catalog.pg_constraint r WHERE r.contype = 'c' AND conname='" . $table . '_' . $field['column_name'] . "_check' ORDER BY 1;")->first();
|
||||
$constraint = $this->constraintExists($table . '_' . $field['column_name'] . '_check');
|
||||
if($constraint){
|
||||
if ($constraint) {
|
||||
//Now we need to break this constraint text into bits so we can see what we have:
|
||||
//Examples:
|
||||
//CHECK ("CanEditType"::text = ANY (ARRAY['LoggedInUsers'::character varying, 'OnlyTheseUsers'::character varying, 'Inherit'::character varying]::text[]))
|
||||
@ -565,21 +614,22 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
|
||||
//TODO: replace all this with a regular expression!
|
||||
$value=$constraint['pg_get_constraintdef'];
|
||||
$value=substr($value, strpos($value,'='));
|
||||
$value=substr($value, strpos($value, '='));
|
||||
$value=str_replace("''", "'", $value);
|
||||
|
||||
$in_value=false;
|
||||
$constraints=Array();
|
||||
$constraints=array();
|
||||
$current_value='';
|
||||
for($i=0; $i<strlen($value); $i++){
|
||||
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 ($char=="'") {
|
||||
if (!$in_value) {
|
||||
$in_value=true;
|
||||
else {
|
||||
} else {
|
||||
$in_value=false;
|
||||
$constraints[]=substr($current_value, 0, -1);
|
||||
$current_value='';
|
||||
@ -587,12 +637,12 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
}
|
||||
}
|
||||
|
||||
if(sizeof($constraints)>0){
|
||||
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{
|
||||
} else {
|
||||
$output[$field['column_name']]='varchar(' . $field['character_maximum_length'] . ')';
|
||||
}
|
||||
break;
|
||||
@ -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
|
||||
@ -693,7 +751,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
//This is techically a bug, since new tables will not be indexed.
|
||||
|
||||
// If requesting the definition rather than the DDL
|
||||
if($asDbValue) {
|
||||
if ($asDbValue) {
|
||||
$indexName=trim($indexName, '()');
|
||||
return $indexName;
|
||||
}
|
||||
@ -744,15 +802,16 @@ 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);
|
||||
if ($indexSpec[0] != '(') {
|
||||
list($indexType, $indexFields) = explode(' ', $indexSpec, 2);
|
||||
} else {
|
||||
$indexFields = $indexSpec;
|
||||
}
|
||||
|
||||
if(!$indexType) {
|
||||
if (!$indexType) {
|
||||
$indexType = "index";
|
||||
}
|
||||
|
||||
@ -766,24 +825,25 @@ 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)
|
||||
)->first();
|
||||
|
||||
// Option 1: output as a string
|
||||
if(strpos($trigger['tgargs'],'\000') !== false) {
|
||||
if (strpos($trigger['tgargs'], '\000') !== false) {
|
||||
$argList = explode('\000', $trigger['tgargs']);
|
||||
array_pop($argList);
|
||||
|
||||
// Option 2: hex-encoded (not sure why this happens, depends on PGSQL config)
|
||||
} else {
|
||||
$bytes = str_split($trigger['tgargs'],2);
|
||||
$bytes = str_split($trigger['tgargs'], 2);
|
||||
$argList = array();
|
||||
$nextArg = "";
|
||||
foreach($bytes as $byte) {
|
||||
if($byte == "00") {
|
||||
foreach ($bytes as $byte) {
|
||||
if ($byte == "00") {
|
||||
$argList[] = $nextArg;
|
||||
$nextArg = "";
|
||||
} else {
|
||||
@ -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
|
||||
@ -806,7 +867,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
);
|
||||
|
||||
$indexList = array();
|
||||
foreach($indexes as $index) {
|
||||
foreach ($indexes as $index) {
|
||||
// Key for the indexList array. Differs from other DB implementations, which is why
|
||||
// requireIndex() needed to be overridden
|
||||
$indexName = $index['indexname'];
|
||||
@ -815,12 +876,12 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
$type = '';
|
||||
|
||||
//Check for uniques:
|
||||
if(substr($index['indexdef'], 0, 13)=='CREATE UNIQUE') {
|
||||
if (substr($index['indexdef'], 0, 13)=='CREATE UNIQUE') {
|
||||
$type = 'unique';
|
||||
}
|
||||
|
||||
//check for hashes, btrees etc:
|
||||
if(strpos(strtolower($index['indexdef']), 'using hash ')!==false) {
|
||||
if (strpos(strtolower($index['indexdef']), 'using hash ')!==false) {
|
||||
$type = 'hash';
|
||||
}
|
||||
|
||||
@ -828,7 +889,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
//if(strpos(strtolower($index['indexdef']), 'using btree ')!==false)
|
||||
// $prefix='using btree ';
|
||||
|
||||
if(strpos(strtolower($index['indexdef']), 'using rtree ')!==false) {
|
||||
if (strpos(strtolower($index['indexdef']), 'using rtree ')!==false) {
|
||||
$type = 'rtree';
|
||||
}
|
||||
|
||||
@ -851,16 +912,16 @@ 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\\\_%'",
|
||||
array($this->database->currentSchema())
|
||||
);
|
||||
foreach($result as $record) {
|
||||
foreach ($result as $record) {
|
||||
$table = reset($record);
|
||||
$tables[strtolower($table)] = $table;
|
||||
}
|
||||
@ -874,8 +935,9 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
*
|
||||
* @param string $constraint
|
||||
*/
|
||||
protected function constraintExists($constraint){
|
||||
if(!isset(self::$cached_constraints[$constraint])){
|
||||
protected function constraintExists($constraint)
|
||||
{
|
||||
if (!isset(self::$cached_constraints[$constraint])) {
|
||||
$exists = $this->preparedQuery("
|
||||
SELECT conname,pg_catalog.pg_get_constraintdef(r.oid, true)
|
||||
FROM pg_catalog.pg_constraint r WHERE r.contype = 'c' AND conname = ? ORDER BY 1;",
|
||||
@ -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 = (
|
||||
@ -906,7 +969,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
$result = $this->preparedQuery($query, $tableName, $this->database->currentSchema());
|
||||
|
||||
$table = array();
|
||||
while($row = pg_fetch_assoc($result)) {
|
||||
while ($row = pg_fetch_assoc($result)) {
|
||||
$table[] = array(
|
||||
'Column' => $row['Column'],
|
||||
'DataType' => $row['DataType']
|
||||
@ -923,14 +986,15 @@ 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
|
||||
WHERE trigger_name = ? AND trigger_schema = ?;",
|
||||
array($triggerName, $this->database->currentSchema())
|
||||
)->first();
|
||||
if($exists){
|
||||
if ($exists) {
|
||||
$this->query("DROP trigger IF EXISTS $triggerName ON \"$tableName\";");
|
||||
}
|
||||
}
|
||||
@ -941,8 +1005,9 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
* @param string $trigger Name of the trigger
|
||||
* @return array
|
||||
*/
|
||||
protected function triggerFieldsFromTrigger($trigger) {
|
||||
if($trigger){
|
||||
protected function triggerFieldsFromTrigger($trigger)
|
||||
{
|
||||
if ($trigger) {
|
||||
$tsvector='tsvector_update_trigger';
|
||||
$ts_pos=strpos($trigger, $tsvector);
|
||||
$details=trim(substr($trigger, $ts_pos+strlen($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,19 +1035,20 @@ 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';
|
||||
|
||||
if(!isset($values['arrayValue'])) {
|
||||
if (!isset($values['arrayValue'])) {
|
||||
$values['arrayValue']='';
|
||||
}
|
||||
|
||||
if($asDbValue) {
|
||||
if ($asDbValue) {
|
||||
return array('data_type'=>'smallint');
|
||||
}
|
||||
|
||||
if($values['arrayValue'] != '') {
|
||||
if ($values['arrayValue'] != '') {
|
||||
$default = '';
|
||||
} else {
|
||||
$default = ' default ' . (int)$values['default'];
|
||||
@ -995,9 +1062,9 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
* @param array $values Contains a tokenised list of info about this data type
|
||||
* @return string
|
||||
*/
|
||||
public function date($values){
|
||||
|
||||
if(!isset($values['arrayValue'])) {
|
||||
public function date($values)
|
||||
{
|
||||
if (!isset($values['arrayValue'])) {
|
||||
$values['arrayValue']='';
|
||||
}
|
||||
|
||||
@ -1011,25 +1078,25 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
* @param boolean $asDbValue
|
||||
* @return string
|
||||
*/
|
||||
public function decimal($values, $asDbValue=false){
|
||||
|
||||
if(!isset($values['arrayValue'])) {
|
||||
public function decimal($values, $asDbValue=false)
|
||||
{
|
||||
if (!isset($values['arrayValue'])) {
|
||||
$values['arrayValue']='';
|
||||
}
|
||||
|
||||
// Avoid empty strings being put in the db
|
||||
if($values['precision'] == '') {
|
||||
if ($values['precision'] == '') {
|
||||
$precision = 1;
|
||||
} else {
|
||||
$precision = $values['precision'];
|
||||
}
|
||||
|
||||
$defaultValue = '';
|
||||
if(isset($values['default']) && is_numeric($values['default'])) {
|
||||
if (isset($values['default']) && is_numeric($values['default'])) {
|
||||
$defaultValue = ' default ' . $values['default'];
|
||||
}
|
||||
|
||||
if($asDbValue) {
|
||||
if ($asDbValue) {
|
||||
return array('data_type' => 'numeric', 'precision' => $precision);
|
||||
} else {
|
||||
return "decimal($precision){$values['arrayValue']}$defaultValue";
|
||||
@ -1042,21 +1109,21 @@ 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'])) {
|
||||
if (!isset($values['arrayValue'])) {
|
||||
$values['arrayValue']='';
|
||||
}
|
||||
|
||||
if($values['arrayValue']!='') {
|
||||
if ($values['arrayValue']!='') {
|
||||
$default = '';
|
||||
} else {
|
||||
$default = " default '{$values['default']}'";
|
||||
}
|
||||
|
||||
return "varchar(255){$values['arrayValue']}" . $default . " check (\"" . $values['name'] . "\" in ('" . implode('\', \'', $values['enums']) . "'))";
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
@ -1066,12 +1133,13 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
* @param boolean $asDbValue
|
||||
* @return string
|
||||
*/
|
||||
public function float($values, $asDbValue = false){
|
||||
if(!isset($values['arrayValue'])) {
|
||||
public function float($values, $asDbValue = false)
|
||||
{
|
||||
if (!isset($values['arrayValue'])) {
|
||||
$values['arrayValue']='';
|
||||
}
|
||||
|
||||
if($asDbValue) {
|
||||
if ($asDbValue) {
|
||||
return array('data_type' => 'double precision');
|
||||
} else {
|
||||
return "float{$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,17 +1165,17 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
* @param boolean $asDbValue
|
||||
* @return string
|
||||
*/
|
||||
public function int($values, $asDbValue = false){
|
||||
|
||||
if(!isset($values['arrayValue'])) {
|
||||
public function int($values, $asDbValue = false)
|
||||
{
|
||||
if (!isset($values['arrayValue'])) {
|
||||
$values['arrayValue']='';
|
||||
}
|
||||
|
||||
if($asDbValue) {
|
||||
return Array('data_type'=>'integer', 'precision'=>'32');
|
||||
if ($asDbValue) {
|
||||
return array('data_type'=>'integer', 'precision'=>'32');
|
||||
}
|
||||
|
||||
if($values['arrayValue']!='') {
|
||||
if ($values['arrayValue']!='') {
|
||||
$default='';
|
||||
} else {
|
||||
$default=' default ' . (int)$values['default'];
|
||||
@ -1122,17 +1191,17 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
* @param boolean $asDbValue
|
||||
* @return string
|
||||
*/
|
||||
public function bigint($values, $asDbValue = false){
|
||||
|
||||
if(!isset($values['arrayValue'])) {
|
||||
public function bigint($values, $asDbValue = false)
|
||||
{
|
||||
if (!isset($values['arrayValue'])) {
|
||||
$values['arrayValue']='';
|
||||
}
|
||||
|
||||
if($asDbValue) {
|
||||
return Array('data_type'=>'bigint', 'precision'=>'64');
|
||||
if ($asDbValue) {
|
||||
return array('data_type'=>'bigint', 'precision'=>'64');
|
||||
}
|
||||
|
||||
if($values['arrayValue']!='') {
|
||||
if ($values['arrayValue']!='') {
|
||||
$default='';
|
||||
} else {
|
||||
$default=' default ' . (int)$values['default'];
|
||||
@ -1149,13 +1218,13 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
* @param boolean $asDbValue
|
||||
* @return string
|
||||
*/
|
||||
public function SS_Datetime($values, $asDbValue = false){
|
||||
|
||||
if(!isset($values['arrayValue'])) {
|
||||
public function SS_Datetime($values, $asDbValue = false)
|
||||
{
|
||||
if (!isset($values['arrayValue'])) {
|
||||
$values['arrayValue']='';
|
||||
}
|
||||
|
||||
if($asDbValue) {
|
||||
if ($asDbValue) {
|
||||
return array('data_type'=>'timestamp without time zone');
|
||||
} else {
|
||||
return "timestamp{$values['arrayValue']}";
|
||||
@ -1169,13 +1238,13 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
* @param boolean $asDbValue
|
||||
* @return string
|
||||
*/
|
||||
public function text($values, $asDbValue = false){
|
||||
|
||||
if(!isset($values['arrayValue'])) {
|
||||
public function text($values, $asDbValue = false)
|
||||
{
|
||||
if (!isset($values['arrayValue'])) {
|
||||
$values['arrayValue'] = '';
|
||||
}
|
||||
|
||||
if($asDbValue) {
|
||||
if ($asDbValue) {
|
||||
return array('data_type'=>'text');
|
||||
} else {
|
||||
return "text{$values['arrayValue']}";
|
||||
@ -1188,8 +1257,9 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
* @param array $values Contains a tokenised list of info about this data type
|
||||
* @return string
|
||||
*/
|
||||
public function time($values){
|
||||
if(!isset($values['arrayValue'])) {
|
||||
public function time($values)
|
||||
{
|
||||
if (!isset($values['arrayValue'])) {
|
||||
$values['arrayValue'] = '';
|
||||
}
|
||||
|
||||
@ -1203,17 +1273,17 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
* @param boolean $asDbValue
|
||||
* @return string
|
||||
*/
|
||||
public function varchar($values, $asDbValue=false){
|
||||
|
||||
if(!isset($values['arrayValue'])) {
|
||||
public function varchar($values, $asDbValue=false)
|
||||
{
|
||||
if (!isset($values['arrayValue'])) {
|
||||
$values['arrayValue'] = '';
|
||||
}
|
||||
|
||||
if(!isset($values['precision'])) {
|
||||
if (!isset($values['precision'])) {
|
||||
$values['precision'] = 255;
|
||||
}
|
||||
|
||||
if($asDbValue) {
|
||||
if ($asDbValue) {
|
||||
return array('data_type'=>'varchar', 'precision'=>$values['precision']);
|
||||
} else {
|
||||
return "varchar({$values['precision']}){$values['arrayValue']}";
|
||||
@ -1228,14 +1298,14 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
* @param boolean $asDbValue
|
||||
* @return string
|
||||
*/
|
||||
public function year($values, $asDbValue = false){
|
||||
|
||||
if(!isset($values['arrayValue'])) {
|
||||
public function year($values, $asDbValue = false)
|
||||
{
|
||||
if (!isset($values['arrayValue'])) {
|
||||
$values['arrayValue'] = '';
|
||||
}
|
||||
|
||||
//TODO: the DbValue result does not include the numeric_scale option (ie, the ,0 value in 4,0)
|
||||
if($asDbValue) {
|
||||
if ($asDbValue) {
|
||||
return array('data_type'=>'decimal', 'precision'=>'4');
|
||||
} else {
|
||||
return "decimal(4,0){$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,10 +1372,11 @@ 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) {
|
||||
if ($constraints) {
|
||||
return $this->enumValuesFromConstraint($constraints['pg_get_constraintdef']);
|
||||
} else {
|
||||
return array();
|
||||
@ -1312,25 +1389,30 @@ 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();
|
||||
$segments = explode(',', $constraint);
|
||||
foreach($segments as $this_segment){
|
||||
foreach ($segments as $this_segment) {
|
||||
$bits = preg_split('/ *:: */', $this_segment);
|
||||
array_unshift($constraints, trim($bits[0], " '"));
|
||||
}
|
||||
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)
|
||||
@ -1354,7 +1437,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
// DB::query("DROP TABLESPACE $name;");
|
||||
|
||||
//If this is a new tablespace, or we have dropped the current one:
|
||||
if(!$existing || ($existing && $location != $existing['spclocation'])) {
|
||||
if (!$existing || ($existing && $location != $existing['spclocation'])) {
|
||||
$this->query("CREATE TABLESPACE $name LOCATION '$location';");
|
||||
}
|
||||
}
|
||||
@ -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');
|
||||
@ -1375,16 +1459,16 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
$first=true;
|
||||
|
||||
//Do we need to create a tablespace for this item?
|
||||
if($extensions && isset($extensions['tablespace'])){
|
||||
if ($extensions && isset($extensions['tablespace'])) {
|
||||
$this->createOrReplaceTablespace($extensions['tablespace']['name'], $extensions['tablespace']['location']);
|
||||
$tableSpace=' TABLESPACE ' . $extensions['tablespace']['name'];
|
||||
} else {
|
||||
$tableSpace='';
|
||||
}
|
||||
|
||||
foreach($partitions as $partition_name => $partition_value){
|
||||
foreach ($partitions as $partition_name => $partition_value) {
|
||||
//Check that this child table does not already exist:
|
||||
if(!$this->hasTable($partition_name)){
|
||||
if (!$this->hasTable($partition_name)) {
|
||||
$this->query("CREATE TABLE \"$partition_name\" (CHECK (" . str_replace('NEW.', '', $partition_value) . ")) INHERITS (\"$tableName\")$tableSpace;");
|
||||
} else {
|
||||
//Drop the constraint, we will recreate in in the next line
|
||||
@ -1392,7 +1476,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
"SELECT conname FROM pg_constraint WHERE conname = ?;",
|
||||
array("{$partition_name}_pkey")
|
||||
);
|
||||
if($existing_constraint){
|
||||
if ($existing_constraint) {
|
||||
$this->query("ALTER TABLE \"$partition_name\" DROP CONSTRAINT \"{$partition_name}_pkey\";");
|
||||
}
|
||||
$this->dropTrigger(strtolower('trigger_' . $tableName . '_insert'), $tableName);
|
||||
@ -1400,7 +1484,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
|
||||
$this->query("ALTER TABLE \"$partition_name\" ADD CONSTRAINT \"{$partition_name}_pkey\" PRIMARY KEY (\"ID\");");
|
||||
|
||||
if($first){
|
||||
if ($first) {
|
||||
$trigger.='IF';
|
||||
$first=false;
|
||||
} else {
|
||||
@ -1409,17 +1493,16 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
|
||||
$trigger .= " ($partition_value) THEN INSERT INTO \"$partition_name\" VALUES (NEW.*);";
|
||||
|
||||
if($indexes){
|
||||
if ($indexes) {
|
||||
// We need to propogate the indexes through to the child pages.
|
||||
// Some of this code is duplicated, and could be tidied up
|
||||
foreach($indexes as $name => $this_index){
|
||||
|
||||
if($this_index['type']=='fulltext'){
|
||||
foreach ($indexes as $name => $this_index) {
|
||||
if ($this_index['type']=='fulltext') {
|
||||
$fillfactor = $where = '';
|
||||
if(isset($this_index['fillfactor'])) {
|
||||
if (isset($this_index['fillfactor'])) {
|
||||
$fillfactor = 'WITH (FILLFACTOR = ' . $this_index['fillfactor'] . ')';
|
||||
}
|
||||
if(isset($this_index['where'])) {
|
||||
if (isset($this_index['where'])) {
|
||||
$where = 'WHERE ' . $this_index['where'];
|
||||
}
|
||||
$clusterMethod = PostgreSQLDatabase::default_fts_cluster_method();
|
||||
@ -1427,15 +1510,14 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
$ts_details = $this->fulltext($this_index, $partition_name, $name);
|
||||
$this->query($ts_details['triggers']);
|
||||
} else {
|
||||
|
||||
if(is_array($this_index)) {
|
||||
if (is_array($this_index)) {
|
||||
$index_name = $this_index['name'];
|
||||
} else {
|
||||
$index_name = trim($this_index, '()');
|
||||
}
|
||||
|
||||
$createIndex = $this->getIndexSqlDefinition($partition_name, $index_name, $this_index);
|
||||
if($createIndex !== false) {
|
||||
if ($createIndex !== false) {
|
||||
$this->query($createIndex);
|
||||
}
|
||||
}
|
||||
@ -1443,7 +1525,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
||||
}
|
||||
|
||||
//Lastly, clustering goes here:
|
||||
if($extensions && isset($extensions['cluster'])){
|
||||
if ($extensions && isset($extensions['cluster'])) {
|
||||
$this->query("CLUSTER \"$partition_name\" USING \"{$extensions['cluster']}\";");
|
||||
}
|
||||
}
|
||||
@ -1460,13 +1542,14 @@ 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)
|
||||
)->first();
|
||||
|
||||
if(!$result) {
|
||||
if (!$result) {
|
||||
$this->query("CREATE LANGUAGE $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";
|
||||
}
|
||||
|
@ -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
|
||||
|
@ -3,14 +3,14 @@
|
||||
* @package postgresql
|
||||
* @subpackage tests
|
||||
*/
|
||||
class PostgreSQLDatabaseTest extends SapphireTest {
|
||||
function testReadOnlyTransaction(){
|
||||
|
||||
if(
|
||||
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');
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user