mirror of
https://github.com/silverstripe/silverstripe-postgresql
synced 2024-10-22 17:05:45 +02:00
Converted to PSR-2
This commit is contained in:
parent
091c4d8a1c
commit
605ba3eeff
@ -10,243 +10,270 @@
|
|||||||
* @package sapphire
|
* @package sapphire
|
||||||
* @subpackage model
|
* @subpackage model
|
||||||
*/
|
*/
|
||||||
class PostgreSQLConnector extends DBConnector {
|
class PostgreSQLConnector extends DBConnector
|
||||||
|
{
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Connection to the PG Database database
|
* Connection to the PG Database database
|
||||||
*
|
*
|
||||||
* @var resource
|
* @var resource
|
||||||
*/
|
*/
|
||||||
protected $dbConn = null;
|
protected $dbConn = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Name of the currently selected database
|
* Name of the currently selected database
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
protected $databaseName = null;
|
protected $databaseName = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reference to the last query result (for pg_affected_rows)
|
* Reference to the last query result (for pg_affected_rows)
|
||||||
*
|
*
|
||||||
* @var resource
|
* @var resource
|
||||||
*/
|
*/
|
||||||
protected $lastQuery = null;
|
protected $lastQuery = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Last parameters used to connect
|
* Last parameters used to connect
|
||||||
*
|
*
|
||||||
* @var array
|
* @var array
|
||||||
*/
|
*/
|
||||||
protected $lastParameters = null;
|
protected $lastParameters = null;
|
||||||
|
|
||||||
protected $lastRows = 0;
|
protected $lastRows = 0;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Escape a parameter to be used in the connection string
|
* Escape a parameter to be used in the connection string
|
||||||
*
|
*
|
||||||
* @param array $parameters All parameters
|
* @param array $parameters All parameters
|
||||||
* @param string $key The key in $parameters to pull from
|
* @param string $key The key in $parameters to pull from
|
||||||
* @param string $name The connection string parameter name
|
* @param string $name The connection string parameter name
|
||||||
* @param mixed $default The default value, or null if optional
|
* @param mixed $default The default value, or null if optional
|
||||||
* @return string The completed fragment in the form name=value
|
* @return string The completed fragment in the form name=value
|
||||||
*/
|
*/
|
||||||
protected function escapeParameter($parameters, $key, $name, $default = null) {
|
protected function escapeParameter($parameters, $key, $name, $default = null)
|
||||||
if(empty($parameters[$key])) {
|
{
|
||||||
if($default === null) return '';
|
if (empty($parameters[$key])) {
|
||||||
$value = $default;
|
if ($default === null) {
|
||||||
} else {
|
return '';
|
||||||
$value = $parameters[$key];
|
}
|
||||||
}
|
$value = $default;
|
||||||
return "$name='" . addslashes($value) . "'";
|
} else {
|
||||||
}
|
$value = $parameters[$key];
|
||||||
|
}
|
||||||
|
return "$name='" . addslashes($value) . "'";
|
||||||
|
}
|
||||||
|
|
||||||
public function connect($parameters, $selectDB = false) {
|
public function connect($parameters, $selectDB = false)
|
||||||
$this->lastParameters = $parameters;
|
{
|
||||||
|
$this->lastParameters = $parameters;
|
||||||
|
|
||||||
// Note: Postgres always behaves as though $selectDB = true, ignoring
|
// Note: Postgres always behaves as though $selectDB = true, ignoring
|
||||||
// any value actually passed in. The controller passes in true for other
|
// any value actually passed in. The controller passes in true for other
|
||||||
// connectors such as PDOConnector.
|
// connectors such as PDOConnector.
|
||||||
|
|
||||||
// Escape parameters
|
// Escape parameters
|
||||||
$arguments = array(
|
$arguments = array(
|
||||||
$this->escapeParameter($parameters, 'server', 'host', 'localhost'),
|
$this->escapeParameter($parameters, 'server', 'host', 'localhost'),
|
||||||
$this->escapeParameter($parameters, 'port', 'port', 5432),
|
$this->escapeParameter($parameters, 'port', 'port', 5432),
|
||||||
$this->escapeParameter($parameters, 'database', 'dbname', 'postgres'),
|
$this->escapeParameter($parameters, 'database', 'dbname', 'postgres'),
|
||||||
$this->escapeParameter($parameters, 'username', 'user'),
|
$this->escapeParameter($parameters, 'username', 'user'),
|
||||||
$this->escapeParameter($parameters, 'password', 'password')
|
$this->escapeParameter($parameters, 'password', 'password')
|
||||||
);
|
);
|
||||||
|
|
||||||
// Close the old connection
|
// 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) {
|
// Connect
|
||||||
// Extract error details from PHP error handling
|
$this->dbConn = @pg_connect(implode(' ', $arguments));
|
||||||
$error = error_get_last();
|
if ($this->dbConn === false) {
|
||||||
if($error && preg_match('/function\\.pg-connect\\<\\/a\\>\\]\\: (?<message>.*)/', $error['message'], $matches)) {
|
// Extract error details from PHP error handling
|
||||||
$this->databaseError(html_entity_decode($matches['message']));
|
$error = error_get_last();
|
||||||
} else {
|
if ($error && preg_match('/function\\.pg-connect\\<\\/a\\>\\]\\: (?<message>.*)/', $error['message'], $matches)) {
|
||||||
$this->databaseError("Couldn't connect to PostgreSQL database.");
|
$this->databaseError(html_entity_decode($matches['message']));
|
||||||
}
|
} else {
|
||||||
} elseif(pg_connection_status($this->dbConn) != PGSQL_CONNECTION_OK) {
|
$this->databaseError("Couldn't connect to PostgreSQL database.");
|
||||||
throw new ErrorException($this->getLastError());
|
}
|
||||||
}
|
} elseif (pg_connection_status($this->dbConn) != PGSQL_CONNECTION_OK) {
|
||||||
|
throw new ErrorException($this->getLastError());
|
||||||
|
}
|
||||||
|
|
||||||
//By virtue of getting here, the connection is active:
|
//By virtue of getting here, the connection is active:
|
||||||
$this->databaseName = empty($parameters['database']) ? PostgreSQLDatabase::MASTER_DATABASE : $parameters['database'];
|
$this->databaseName = empty($parameters['database']) ? PostgreSQLDatabase::MASTER_DATABASE : $parameters['database'];
|
||||||
}
|
}
|
||||||
|
|
||||||
public function affectedRows() {
|
public function affectedRows()
|
||||||
return $this->lastRows;
|
{
|
||||||
}
|
return $this->lastRows;
|
||||||
|
}
|
||||||
|
|
||||||
public function getGeneratedID($table) {
|
public function getGeneratedID($table)
|
||||||
$result = $this->query("SELECT last_value FROM \"{$table}_ID_seq\";")->first();
|
{
|
||||||
return $result['last_value'];
|
$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);
|
{
|
||||||
}
|
return pg_last_error($this->dbConn);
|
||||||
|
}
|
||||||
|
|
||||||
public function getSelectedDatabase() {
|
public function getSelectedDatabase()
|
||||||
return $this->databaseName;
|
{
|
||||||
}
|
return $this->databaseName;
|
||||||
|
}
|
||||||
|
|
||||||
public function getVersion() {
|
public function getVersion()
|
||||||
$version = pg_version($this->dbConn);
|
{
|
||||||
if(isset($version['server'])) return $version['server'];
|
$version = pg_version($this->dbConn);
|
||||||
else return false;
|
if (isset($version['server'])) {
|
||||||
}
|
return $version['server'];
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public function isActive() {
|
public function isActive()
|
||||||
return $this->databaseName && $this->dbConn;
|
{
|
||||||
}
|
return $this->databaseName && $this->dbConn;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determines if the SQL fragment either breaks into or out of a string literal
|
* Determines if the SQL fragment either breaks into or out of a string literal
|
||||||
* by counting single quotes
|
* by counting single quotes
|
||||||
*
|
*
|
||||||
* Handles double-quote escaped quotes as well as slash escaped quotes
|
* Handles double-quote escaped quotes as well as slash escaped quotes
|
||||||
*
|
*
|
||||||
* @todo Test this!
|
* @todo Test this!
|
||||||
*
|
*
|
||||||
* @see http://www.postgresql.org/docs/8.3/interactive/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS
|
* @see http://www.postgresql.org/docs/8.3/interactive/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS
|
||||||
*
|
*
|
||||||
* @param string $input The SQL fragment
|
* @param string $input The SQL fragment
|
||||||
* @return boolean True if the string breaks into or out of a string literal
|
* @return boolean True if the string breaks into or out of a string literal
|
||||||
*/
|
*/
|
||||||
public function checkStringTogglesLiteral($input) {
|
public function checkStringTogglesLiteral($input)
|
||||||
// Remove escaped backslashes, count them!
|
{
|
||||||
$input = preg_replace('/\\\\\\\\/', '', $input);
|
// Remove escaped backslashes, count them!
|
||||||
|
$input = preg_replace('/\\\\\\\\/', '', $input);
|
||||||
|
|
||||||
// Count quotes
|
// Count quotes
|
||||||
$totalQuotes = substr_count($input, "'"); // Includes double quote escaped quotes
|
$totalQuotes = substr_count($input, "'"); // Includes double quote escaped quotes
|
||||||
$escapedQuotes = substr_count($input, "\\'");
|
$escapedQuotes = substr_count($input, "\\'");
|
||||||
return (($totalQuotes - $escapedQuotes) % 2) !== 0;
|
return (($totalQuotes - $escapedQuotes) % 2) !== 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Iteratively replaces all question marks with numerical placeholders
|
* Iteratively replaces all question marks with numerical placeholders
|
||||||
* E.g. "Title = ? AND Name = ?" becomes "Title = $1 AND Name = $2"
|
* E.g. "Title = ? AND Name = ?" becomes "Title = $1 AND Name = $2"
|
||||||
*
|
*
|
||||||
* @todo Better consider question marks in string literals
|
* @todo Better consider question marks in string literals
|
||||||
*
|
*
|
||||||
* @param string $sql Paramaterised query using question mark placeholders
|
* @param string $sql Paramaterised query using question mark placeholders
|
||||||
* @return string Paramaterised query using numeric placeholders
|
* @return string Paramaterised query using numeric placeholders
|
||||||
*/
|
*/
|
||||||
public function replacePlaceholders($sql) {
|
public function replacePlaceholders($sql)
|
||||||
$segments = preg_split('/\?/', $sql);
|
{
|
||||||
$joined = '';
|
$segments = preg_split('/\?/', $sql);
|
||||||
$inString = false;
|
$joined = '';
|
||||||
$num = 0;
|
$inString = false;
|
||||||
for($i = 0; $i < count($segments); $i++) {
|
$num = 0;
|
||||||
// Append next segment
|
for ($i = 0; $i < count($segments); $i++) {
|
||||||
$joined .= $segments[$i];
|
// Append next segment
|
||||||
|
$joined .= $segments[$i];
|
||||||
|
|
||||||
// Don't add placeholder after last segment
|
// Don't add placeholder after last segment
|
||||||
if($i === count($segments) - 1) break;
|
if ($i === count($segments) - 1) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
// check string escape on previous fragment
|
// check string escape on previous fragment
|
||||||
if($this->checkStringTogglesLiteral($segments[$i])) {
|
if ($this->checkStringTogglesLiteral($segments[$i])) {
|
||||||
$inString = !$inString;
|
$inString = !$inString;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Append placeholder replacement
|
// Append placeholder replacement
|
||||||
if($inString) {
|
if ($inString) {
|
||||||
$joined .= "?";
|
$joined .= "?";
|
||||||
} else {
|
} else {
|
||||||
$joined .= '$' . ++$num;
|
$joined .= '$' . ++$num;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return $joined;
|
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;
|
// Reset state
|
||||||
$this->lastRows = 0;
|
$this->lastQuery = null;
|
||||||
|
$this->lastRows = 0;
|
||||||
|
|
||||||
// Replace question mark placeholders with numeric placeholders
|
// Replace question mark placeholders with numeric placeholders
|
||||||
if(!empty($parameters)) {
|
if (!empty($parameters)) {
|
||||||
$sql = $this->replacePlaceholders($sql);
|
$sql = $this->replacePlaceholders($sql);
|
||||||
$parameters = $this->parameterValues($parameters);
|
$parameters = $this->parameterValues($parameters);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Execute query
|
// Execute query
|
||||||
if(!empty($parameters)) {
|
if (!empty($parameters)) {
|
||||||
$result = pg_query_params($this->dbConn, $sql, $parameters);
|
$result = pg_query_params($this->dbConn, $sql, $parameters);
|
||||||
} else {
|
} else {
|
||||||
$result = pg_query($this->dbConn, $sql);
|
$result = pg_query($this->dbConn, $sql);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle error
|
// Handle error
|
||||||
if ($result === false) {
|
if ($result === false) {
|
||||||
$this->databaseError($this->getLastError(), $errorLevel, $sql, $parameters);
|
$this->databaseError($this->getLastError(), $errorLevel, $sql, $parameters);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save and return results
|
// Save and return results
|
||||||
$this->lastQuery = $result;
|
$this->lastQuery = $result;
|
||||||
$this->lastRows = pg_affected_rows($result);
|
$this->lastRows = pg_affected_rows($result);
|
||||||
return new PostgreSQLQuery($result);
|
return new PostgreSQLQuery($result);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function query($sql, $errorLevel = E_USER_ERROR) {
|
public function query($sql, $errorLevel = E_USER_ERROR)
|
||||||
return $this->preparedQuery($sql, array(), $errorLevel);
|
{
|
||||||
}
|
return $this->preparedQuery($sql, array(), $errorLevel);
|
||||||
|
}
|
||||||
|
|
||||||
public function quoteString($value) {
|
public function quoteString($value)
|
||||||
if(function_exists('pg_escape_literal')) {
|
{
|
||||||
return pg_escape_literal($this->dbConn, $value);
|
if (function_exists('pg_escape_literal')) {
|
||||||
} else {
|
return pg_escape_literal($this->dbConn, $value);
|
||||||
return "'" . $this->escapeString($value) . "'";
|
} else {
|
||||||
}
|
return "'" . $this->escapeString($value) . "'";
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public function escapeString($value) {
|
public function escapeString($value)
|
||||||
return pg_escape_string($this->dbConn, $value);
|
{
|
||||||
}
|
return pg_escape_string($this->dbConn, $value);
|
||||||
|
}
|
||||||
|
|
||||||
public function escapeIdentifier($value, $separator = '.') {
|
public function escapeIdentifier($value, $separator = '.')
|
||||||
if(empty($separator) && function_exists('pg_escape_identifier')) {
|
{
|
||||||
return pg_escape_identifier($this->dbConn, $value);
|
if (empty($separator) && function_exists('pg_escape_identifier')) {
|
||||||
}
|
return pg_escape_identifier($this->dbConn, $value);
|
||||||
|
}
|
||||||
|
|
||||||
// Let parent function handle recursive calls
|
// Let parent function handle recursive calls
|
||||||
return parent::escapeIdentifier ($value, $separator);
|
return parent::escapeIdentifier($value, $separator);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function selectDatabase($name) {
|
public function selectDatabase($name)
|
||||||
if($name !== $this->databaseName) {
|
{
|
||||||
user_error("PostgreSQLConnector can't change databases. Please create a new database connection", E_USER_ERROR);
|
if ($name !== $this->databaseName) {
|
||||||
}
|
user_error("PostgreSQLConnector can't change databases. Please create a new database connection", E_USER_ERROR);
|
||||||
return true;
|
}
|
||||||
}
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
public function unloadDatabase() {
|
public function unloadDatabase()
|
||||||
$this->databaseName = null;
|
{
|
||||||
}
|
$this->databaseName = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,627 +6,682 @@
|
|||||||
* @package sapphire
|
* @package sapphire
|
||||||
* @subpackage model
|
* @subpackage model
|
||||||
*/
|
*/
|
||||||
class PostgreSQLDatabase extends SS_Database {
|
class PostgreSQLDatabase extends SS_Database
|
||||||
|
{
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Database schema manager object
|
* Database schema manager object
|
||||||
*
|
*
|
||||||
* @var PostgreSQLSchemaManager
|
* @var PostgreSQLSchemaManager
|
||||||
*/
|
*/
|
||||||
protected $schemaManager;
|
protected $schemaManager;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The currently selected database schema name.
|
* The currently selected database schema name.
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
protected $schema;
|
protected $schema;
|
||||||
|
|
||||||
protected $supportsTransactions = true;
|
protected $supportsTransactions = true;
|
||||||
|
|
||||||
const MASTER_DATABASE = 'postgres';
|
const MASTER_DATABASE = 'postgres';
|
||||||
|
|
||||||
const MASTER_SCHEMA = 'public';
|
const MASTER_SCHEMA = 'public';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Full text cluster method. (e.g. GIN or GiST)
|
* Full text cluster method. (e.g. GIN or GiST)
|
||||||
*
|
*
|
||||||
* @return string
|
* @return string
|
||||||
*/
|
*/
|
||||||
public static function default_fts_cluster_method() {
|
public static function default_fts_cluster_method()
|
||||||
return Config::inst()->get('PostgreSQLDatabase', 'default_fts_cluster_method');
|
{
|
||||||
}
|
return Config::inst()->get('PostgreSQLDatabase', 'default_fts_cluster_method');
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Full text search method.
|
* Full text search method.
|
||||||
*
|
*
|
||||||
* @return string
|
* @return string
|
||||||
*/
|
*/
|
||||||
public static function default_fts_search_method() {
|
public static function default_fts_search_method()
|
||||||
return Config::inst()->get('PostgreSQLDatabase', 'default_fts_search_method');
|
{
|
||||||
}
|
return Config::inst()->get('PostgreSQLDatabase', 'default_fts_search_method');
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determines whether to check a database exists on the host by
|
* Determines whether to check a database exists on the host by
|
||||||
* querying the 'postgres' database and running createDatabase.
|
* querying the 'postgres' database and running createDatabase.
|
||||||
*
|
*
|
||||||
* Some locked down systems prevent access to the 'postgres' table in
|
* Some locked down systems prevent access to the 'postgres' table in
|
||||||
* which case you need to set this to false.
|
* which case you need to set this to false.
|
||||||
*
|
*
|
||||||
* If allow_query_master_postgres is false, and model_schema_as_database is also false,
|
* If allow_query_master_postgres is false, and model_schema_as_database is also false,
|
||||||
* then attempts to create or check databases beyond the initial connection will
|
* then attempts to create or check databases beyond the initial connection will
|
||||||
* result in a runtime error.
|
* result in a runtime error.
|
||||||
*/
|
*/
|
||||||
public static function allow_query_master_postgres() {
|
public static function allow_query_master_postgres()
|
||||||
return Config::inst()->get('PostgreSQLDatabase', 'allow_query_master_postgres');
|
{
|
||||||
}
|
return Config::inst()->get('PostgreSQLDatabase', 'allow_query_master_postgres');
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* For instances where multiple databases are used beyond the initial connection
|
* For instances where multiple databases are used beyond the initial connection
|
||||||
* you may set this option to true to force database switches to switch schemas
|
* you may set this option to true to force database switches to switch schemas
|
||||||
* instead of using databases. This may be useful if the database user does not
|
* instead of using databases. This may be useful if the database user does not
|
||||||
* have cross-database permissions, and in cases where multiple databases are used
|
* have cross-database permissions, and in cases where multiple databases are used
|
||||||
* (such as in running test cases).
|
* (such as in running test cases).
|
||||||
*
|
*
|
||||||
* If this is true then the database will only be set during the initial connection,
|
* If this is true then the database will only be set during the initial connection,
|
||||||
* and attempts to change to this database will use the 'public' schema instead
|
* and attempts to change to this database will use the 'public' schema instead
|
||||||
*/
|
*/
|
||||||
public static function model_schema_as_database() {
|
public static function model_schema_as_database()
|
||||||
return Config::inst()->get('PostgreSQLDatabase', 'model_schema_as_database');
|
{
|
||||||
}
|
return Config::inst()->get('PostgreSQLDatabase', 'model_schema_as_database');
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Override the language that tsearch uses. By default it is 'english, but
|
* Override the language that tsearch uses. By default it is 'english, but
|
||||||
* could be any of the supported languages that can be found in the
|
* could be any of the supported languages that can be found in the
|
||||||
* pg_catalog.pg_ts_config table.
|
* pg_catalog.pg_ts_config table.
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
public static function search_language() {
|
public static function search_language()
|
||||||
return Config::inst()->get('PostgreSQLDatabase', 'search_language');
|
{
|
||||||
}
|
return Config::inst()->get('PostgreSQLDatabase', 'search_language');
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The database name specified at initial connection
|
* The database name specified at initial connection
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
protected $databaseOriginal = '';
|
protected $databaseOriginal = '';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The schema name specified at initial construction. When model_schema_as_database
|
* The schema name specified at initial construction. When model_schema_as_database
|
||||||
* is set to true selecting the $databaseOriginal database will instead reset
|
* is set to true selecting the $databaseOriginal database will instead reset
|
||||||
* the schema to this
|
* the schema to this
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
protected $schemaOriginal = '';
|
protected $schemaOriginal = '';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Connection parameters specified at inital connection
|
* Connection parameters specified at inital connection
|
||||||
*
|
*
|
||||||
* @var array
|
* @var array
|
||||||
*/
|
*/
|
||||||
protected $parameters = array();
|
protected $parameters = array();
|
||||||
|
|
||||||
public function connect($parameters) {
|
public function connect($parameters)
|
||||||
// Check database name
|
{
|
||||||
if(empty($parameters['database'])) {
|
// Check database name
|
||||||
// Check if we can use the master database
|
if (empty($parameters['database'])) {
|
||||||
if(!self::allow_query_master_postgres()) {
|
// Check if we can use the master database
|
||||||
throw new ErrorException('PostegreSQLDatabase::connect called without a database name specified');
|
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
|
}
|
||||||
$parameters['database'] = self::MASTER_DATABASE;
|
// Fallback to master database connection if permission allows
|
||||||
}
|
$parameters['database'] = self::MASTER_DATABASE;
|
||||||
$this->databaseOriginal = $parameters['database'];
|
}
|
||||||
|
$this->databaseOriginal = $parameters['database'];
|
||||||
|
|
||||||
// check schema name
|
// check schema name
|
||||||
if(empty($parameters['schema'])) {
|
if (empty($parameters['schema'])) {
|
||||||
$parameters['schema'] = self::MASTER_SCHEMA;
|
$parameters['schema'] = self::MASTER_SCHEMA;
|
||||||
}
|
}
|
||||||
$this->schemaOriginal = $parameters['schema'];
|
$this->schemaOriginal = $parameters['schema'];
|
||||||
|
|
||||||
// Ensure that driver is available (required by PDO)
|
// Ensure that driver is available (required by PDO)
|
||||||
if(empty($parameters['driver'])) {
|
if (empty($parameters['driver'])) {
|
||||||
$parameters['driver'] = $this->getDatabaseServer();
|
$parameters['driver'] = $this->getDatabaseServer();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ensure port number is set (required by postgres)
|
// Ensure port number is set (required by postgres)
|
||||||
if(empty($parameters['port'])) {
|
if (empty($parameters['port'])) {
|
||||||
$parameters['port'] = 5432;
|
$parameters['port'] = 5432;
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->parameters = $parameters;
|
$this->parameters = $parameters;
|
||||||
|
|
||||||
// If allowed, check that the database exists. Otherwise naively assume
|
// If allowed, check that the database exists. Otherwise naively assume
|
||||||
// that the original database exists
|
// that the original database exists
|
||||||
if(self::allow_query_master_postgres()) {
|
if (self::allow_query_master_postgres()) {
|
||||||
// Use master connection to setup initial schema
|
// Use master connection to setup initial schema
|
||||||
$this->connectMaster();
|
$this->connectMaster();
|
||||||
if(!$this->schemaManager->postgresDatabaseExists($this->databaseOriginal)) {
|
if (!$this->schemaManager->postgresDatabaseExists($this->databaseOriginal)) {
|
||||||
$this->schemaManager->createPostgresDatabase($this->databaseOriginal);
|
$this->schemaManager->createPostgresDatabase($this->databaseOriginal);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Connect to the actual database we're requesting
|
// Connect to the actual database we're requesting
|
||||||
$this->connectDefault();
|
$this->connectDefault();
|
||||||
|
|
||||||
// Set up the schema if required
|
// Set up the schema if required
|
||||||
$this->setSchema($this->schemaOriginal, true);
|
$this->setSchema($this->schemaOriginal, true);
|
||||||
|
|
||||||
// Set the timezone if required.
|
// Set the timezone if required.
|
||||||
if (isset($parameters['timezone'])) {
|
if (isset($parameters['timezone'])) {
|
||||||
$this->selectTimezone($parameters['timezone']);
|
$this->selectTimezone($parameters['timezone']);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function connectMaster() {
|
protected function connectMaster()
|
||||||
$parameters = $this->parameters;
|
{
|
||||||
$parameters['database'] = self::MASTER_DATABASE;
|
$parameters = $this->parameters;
|
||||||
$this->connector->connect($parameters, true);
|
$parameters['database'] = self::MASTER_DATABASE;
|
||||||
}
|
$this->connector->connect($parameters, true);
|
||||||
|
}
|
||||||
|
|
||||||
protected function connectDefault() {
|
protected function connectDefault()
|
||||||
$parameters = $this->parameters;
|
{
|
||||||
$parameters['database'] = $this->databaseOriginal;
|
$parameters = $this->parameters;
|
||||||
$this->connector->connect($parameters, true);
|
$parameters['database'] = $this->databaseOriginal;
|
||||||
}
|
$this->connector->connect($parameters, true);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets the system timezone for the database connection
|
* Sets the system timezone for the database connection
|
||||||
*
|
*
|
||||||
* @param string $timezone
|
* @param string $timezone
|
||||||
*/
|
*/
|
||||||
public function selectTimezone($timezone) {
|
public function selectTimezone($timezone)
|
||||||
if (empty($timezone)) return;
|
{
|
||||||
$this->query("SET SESSION TIME ZONE '$timezone';");
|
if (empty($timezone)) {
|
||||||
}
|
return;
|
||||||
|
}
|
||||||
|
$this->query("SET SESSION TIME ZONE '$timezone';");
|
||||||
|
}
|
||||||
|
|
||||||
public function supportsCollations() {
|
public function supportsCollations()
|
||||||
return true;
|
{
|
||||||
}
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
public function supportsTimezoneOverride() {
|
public function supportsTimezoneOverride()
|
||||||
return true;
|
{
|
||||||
}
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
public function getDatabaseServer() {
|
public function getDatabaseServer()
|
||||||
return "postgresql";
|
{
|
||||||
}
|
return "postgresql";
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the name of the current schema in use
|
* Returns the name of the current schema in use
|
||||||
*
|
*
|
||||||
* @return string Name of current schema
|
* @return string Name of current schema
|
||||||
*/
|
*/
|
||||||
public function currentSchema() {
|
public function currentSchema()
|
||||||
return $this->schema;
|
{
|
||||||
}
|
return $this->schema;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Utility method to manually set the schema to an alternative
|
* Utility method to manually set the schema to an alternative
|
||||||
* Check existance & sets search path to the supplied schema name
|
* Check existance & sets search path to the supplied schema name
|
||||||
*
|
*
|
||||||
* @param string $name Name of the schema
|
* @param string $name Name of the schema
|
||||||
* @param boolean $create Flag indicating whether the schema should be created
|
* @param boolean $create Flag indicating whether the schema should be created
|
||||||
* if it doesn't exist. If $create is false and the schema doesn't exist
|
* if it doesn't exist. If $create is false and the schema doesn't exist
|
||||||
* then an error will be raised
|
* then an error will be raised
|
||||||
* @param int|boolean $errorLevel The level of error reporting to enable for
|
* @param int|boolean $errorLevel The level of error reporting to enable for
|
||||||
* the query, or false if no error should be raised
|
* the query, or false if no error should be raised
|
||||||
* @return boolean Flag indicating success
|
* @return boolean Flag indicating success
|
||||||
*/
|
*/
|
||||||
public function setSchema($schema, $create = false, $errorLevel = E_USER_ERROR) {
|
public function setSchema($schema, $create = false, $errorLevel = E_USER_ERROR)
|
||||||
if(!$this->schemaManager->schemaExists($schema)) {
|
{
|
||||||
// Check DB creation permisson
|
if (!$this->schemaManager->schemaExists($schema)) {
|
||||||
if (!$create) {
|
// Check DB creation permisson
|
||||||
if ($errorLevel !== false) {
|
if (!$create) {
|
||||||
user_error("Schema $schema does not exist", $errorLevel);
|
if ($errorLevel !== false) {
|
||||||
}
|
user_error("Schema $schema does not exist", $errorLevel);
|
||||||
$this->schema = null;
|
}
|
||||||
return false;
|
$this->schema = null;
|
||||||
}
|
return false;
|
||||||
$this->schemaManager->createSchema($schema);
|
}
|
||||||
}
|
$this->schemaManager->createSchema($schema);
|
||||||
$this->setSchemaSearchPath($schema);
|
}
|
||||||
$this->schema = $schema;
|
$this->setSchemaSearchPath($schema);
|
||||||
return true;
|
$this->schema = $schema;
|
||||||
}
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Override the schema search path. Search using the arguments supplied.
|
* Override the schema search path. Search using the arguments supplied.
|
||||||
* NOTE: The search path is normally set through setSchema() and only
|
* NOTE: The search path is normally set through setSchema() and only
|
||||||
* one schema is selected. The facility to add more than one schema to
|
* one schema is selected. The facility to add more than one schema to
|
||||||
* the search path is provided as an advanced PostgreSQL feature for raw
|
* the search path is provided as an advanced PostgreSQL feature for raw
|
||||||
* SQL queries. Sapphire cannot search for datamodel tables in alternate
|
* SQL queries. Sapphire cannot search for datamodel tables in alternate
|
||||||
* schemas, so be wary of using alternate schemas within the ORM environment.
|
* schemas, so be wary of using alternate schemas within the ORM environment.
|
||||||
*
|
*
|
||||||
* @param string $arg1 First schema to use
|
* @param string $arg1 First schema to use
|
||||||
* @param string $arg2 Second schema to use
|
* @param string $arg2 Second schema to use
|
||||||
* @param string $argN Nth schema to use
|
* @param string $argN Nth schema to use
|
||||||
*/
|
*/
|
||||||
public function setSchemaSearchPath() {
|
public function setSchemaSearchPath()
|
||||||
if(func_num_args() == 0) {
|
{
|
||||||
user_error('At least one Schema must be supplied to set a search path.', E_USER_ERROR);
|
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());
|
}
|
||||||
$this->query("SET search_path TO \"" . implode("\",\"", $schemas) . "\"");
|
$schemas = array_values(func_get_args());
|
||||||
}
|
$this->query("SET search_path TO \"" . implode("\",\"", $schemas) . "\"");
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The core search engine configuration.
|
* The core search engine configuration.
|
||||||
* @todo Properly extract the search functions out of the core.
|
* @todo Properly extract the search functions out of the core.
|
||||||
*
|
*
|
||||||
* @param string $keywords Keywords as a space separated string
|
* @param string $keywords Keywords as a space separated string
|
||||||
* @return object DataObjectSet of result pages
|
* @return object DataObjectSet of result pages
|
||||||
*/
|
*/
|
||||||
public function searchEngine($classesToSearch, $keywords, $start, $pageLength, $sortBy = "ts_rank DESC", $extraFilter = "", $booleanSearch = false, $alternativeFileFilter = "", $invertedMatch = false) {
|
public function searchEngine($classesToSearch, $keywords, $start, $pageLength, $sortBy = "ts_rank DESC", $extraFilter = "", $booleanSearch = false, $alternativeFileFilter = "", $invertedMatch = false)
|
||||||
//Fix the keywords to be ts_query compatitble:
|
{
|
||||||
//Spaces must have pipes
|
//Fix the keywords to be ts_query compatitble:
|
||||||
//@TODO: properly handle boolean operators here.
|
//Spaces must have pipes
|
||||||
$keywords= trim($keywords);
|
//@TODO: properly handle boolean operators here.
|
||||||
$keywords= str_replace(' ', ' | ', $keywords);
|
$keywords= trim($keywords);
|
||||||
$keywords= str_replace('"', "'", $keywords);
|
$keywords= str_replace(' ', ' | ', $keywords);
|
||||||
|
$keywords= str_replace('"', "'", $keywords);
|
||||||
|
|
||||||
$keywords = $this->quoteString(trim($keywords));
|
$keywords = $this->quoteString(trim($keywords));
|
||||||
|
|
||||||
//We can get a list of all the tsvector columns though this query:
|
//We can get a list of all the tsvector columns though this query:
|
||||||
//We know what tables to search in based on the $classesToSearch variable:
|
//We know what tables to search in based on the $classesToSearch variable:
|
||||||
$classesPlaceholders = DB::placeholders($classesToSearch);
|
$classesPlaceholders = DB::placeholders($classesToSearch);
|
||||||
$result = $this->preparedQuery("
|
$result = $this->preparedQuery("
|
||||||
SELECT table_name, column_name, data_type
|
SELECT table_name, column_name, data_type
|
||||||
FROM information_schema.columns
|
FROM information_schema.columns
|
||||||
WHERE data_type='tsvector' AND table_name in ($classesPlaceholders);",
|
WHERE data_type='tsvector' AND table_name in ($classesPlaceholders);",
|
||||||
$classesToSearch
|
$classesToSearch
|
||||||
);
|
);
|
||||||
if (!$result->numRecords()) throw new Exception('there are no full text columns to search');
|
if (!$result->numRecords()) {
|
||||||
|
throw new Exception('there are no full text columns to search');
|
||||||
|
}
|
||||||
|
|
||||||
$tables = array();
|
$tables = array();
|
||||||
$tableParameters = array();
|
$tableParameters = array();
|
||||||
|
|
||||||
// Make column selection lists
|
// Make column selection lists
|
||||||
$select = array(
|
$select = array(
|
||||||
'SiteTree' => array(
|
'SiteTree' => array(
|
||||||
'"ClassName"',
|
'"ClassName"',
|
||||||
'"SiteTree"."ID"',
|
'"SiteTree"."ID"',
|
||||||
'"ParentID"',
|
'"ParentID"',
|
||||||
'"Title"',
|
'"Title"',
|
||||||
'"URLSegment"',
|
'"URLSegment"',
|
||||||
'"Content"',
|
'"Content"',
|
||||||
'"LastEdited"',
|
'"LastEdited"',
|
||||||
'"Created"',
|
'"Created"',
|
||||||
'NULL AS "Name"',
|
'NULL AS "Name"',
|
||||||
'"CanViewType"'
|
'"CanViewType"'
|
||||||
),
|
),
|
||||||
'File' => array(
|
'File' => array(
|
||||||
'"ClassName"',
|
'"ClassName"',
|
||||||
'"File"."ID"',
|
'"File"."ID"',
|
||||||
'0 AS "ParentID"',
|
'0 AS "ParentID"',
|
||||||
'"Title"',
|
'"Title"',
|
||||||
'NULL AS "URLSegment"',
|
'NULL AS "URLSegment"',
|
||||||
'NULL AS "Content"',
|
'NULL AS "Content"',
|
||||||
'"LastEdited"',
|
'"LastEdited"',
|
||||||
'"Created"',
|
'"Created"',
|
||||||
'"Name"',
|
'"Name"',
|
||||||
'NULL AS "CanViewType"'
|
'NULL AS "CanViewType"'
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
foreach($result as $row){
|
foreach ($result as $row) {
|
||||||
$conditions = array();
|
$conditions = array();
|
||||||
if($row['table_name'] === 'SiteTree' || $row['table_name'] === 'File') {
|
if ($row['table_name'] === 'SiteTree' || $row['table_name'] === 'File') {
|
||||||
$conditions[] = array('"ShowInSearch"' => 1);
|
$conditions[] = array('"ShowInSearch"' => 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
$method = self::default_fts_search_method();
|
$method = self::default_fts_search_method();
|
||||||
$conditions[] = "\"{$row['table_name']}\".\"{$row['column_name']}\" $method q ";
|
$conditions[] = "\"{$row['table_name']}\".\"{$row['column_name']}\" $method q ";
|
||||||
$query = DataObject::get($row['table_name'], $conditions)->dataQuery()->query();
|
$query = DataObject::get($row['table_name'], $conditions)->dataQuery()->query();
|
||||||
|
|
||||||
// Could parameterise this, but convention is only to to so for where conditions
|
// Could parameterise this, but convention is only to to so for where conditions
|
||||||
$query->addFrom(array(
|
$query->addFrom(array(
|
||||||
'tsearch' => ", to_tsquery('" . self::search_language() . "', $keywords) AS q"
|
'tsearch' => ", to_tsquery('" . self::search_language() . "', $keywords) AS q"
|
||||||
));
|
));
|
||||||
$query->setSelect(array());
|
$query->setSelect(array());
|
||||||
|
|
||||||
foreach($select[$row['table_name']] as $clause) {
|
foreach ($select[$row['table_name']] as $clause) {
|
||||||
if(preg_match('/^(.*) +AS +"?([^"]*)"?/i', $clause, $matches)) {
|
if (preg_match('/^(.*) +AS +"?([^"]*)"?/i', $clause, $matches)) {
|
||||||
$query->selectField($matches[1], $matches[2]);
|
$query->selectField($matches[1], $matches[2]);
|
||||||
} else {
|
} else {
|
||||||
$query->selectField($clause);
|
$query->selectField($clause);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$query->selectField("ts_rank(\"{$row['table_name']}\".\"{$row['column_name']}\", q)", 'Relevance');
|
$query->selectField("ts_rank(\"{$row['table_name']}\".\"{$row['column_name']}\", q)", 'Relevance');
|
||||||
$query->setOrderBy(array());
|
$query->setOrderBy(array());
|
||||||
|
|
||||||
//Add this query to the collection
|
//Add this query to the collection
|
||||||
$tables[] = $query->sql($parameters);
|
$tables[] = $query->sql($parameters);
|
||||||
$tableParameters = array_merge($tableParameters, $parameters);
|
$tableParameters = array_merge($tableParameters, $parameters);
|
||||||
}
|
}
|
||||||
|
|
||||||
$limit = $pageLength;
|
$limit = $pageLength;
|
||||||
$offset = $start;
|
$offset = $start;
|
||||||
|
|
||||||
if($keywords) $orderBy = " ORDER BY $sortBy";
|
if ($keywords) {
|
||||||
else $orderBy='';
|
$orderBy = " ORDER BY $sortBy";
|
||||||
|
} else {
|
||||||
|
$orderBy='';
|
||||||
|
}
|
||||||
|
|
||||||
$fullQuery = "SELECT * FROM (" . implode(" UNION ", $tables) . ") AS q1 $orderBy LIMIT $limit OFFSET $offset";
|
$fullQuery = "SELECT * FROM (" . implode(" UNION ", $tables) . ") AS q1 $orderBy LIMIT $limit OFFSET $offset";
|
||||||
|
|
||||||
// Get records
|
// Get records
|
||||||
$records = $this->preparedQuery($fullQuery, $tableParameters);
|
$records = $this->preparedQuery($fullQuery, $tableParameters);
|
||||||
$totalCount=0;
|
$totalCount=0;
|
||||||
foreach($records as $record){
|
foreach ($records as $record) {
|
||||||
$objects[] = new $record['ClassName']($record);
|
$objects[] = new $record['ClassName']($record);
|
||||||
$totalCount++;
|
$totalCount++;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(isset($objects)) $results = new ArrayList($objects);
|
if (isset($objects)) {
|
||||||
else $results = new ArrayList();
|
$results = new ArrayList($objects);
|
||||||
$list = new PaginatedList($results);
|
} else {
|
||||||
$list->setLimitItems(false);
|
$results = new ArrayList();
|
||||||
$list->setPageStart($start);
|
}
|
||||||
$list->setPageLength($pageLength);
|
$list = new PaginatedList($results);
|
||||||
$list->setTotalItems($totalCount);
|
$list->setLimitItems(false);
|
||||||
return $list;
|
$list->setPageStart($start);
|
||||||
}
|
$list->setPageLength($pageLength);
|
||||||
|
$list->setTotalItems($totalCount);
|
||||||
|
return $list;
|
||||||
|
}
|
||||||
|
|
||||||
public function supportsTransactions() {
|
public function supportsTransactions()
|
||||||
return $this->supportsTransactions;
|
{
|
||||||
}
|
return $this->supportsTransactions;
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* This is a quick lookup to discover if the database supports particular extensions
|
* This is a quick lookup to discover if the database supports particular extensions
|
||||||
*/
|
*/
|
||||||
public function supportsExtensions($extensions=Array('partitions', 'tablespaces', 'clustering')){
|
public function supportsExtensions($extensions=array('partitions', 'tablespaces', 'clustering'))
|
||||||
if(isset($extensions['partitions'])) return true;
|
{
|
||||||
elseif(isset($extensions['tablespaces'])) return true;
|
if (isset($extensions['partitions'])) {
|
||||||
elseif(isset($extensions['clustering'])) return true;
|
return true;
|
||||||
else return false;
|
} elseif (isset($extensions['tablespaces'])) {
|
||||||
}
|
return true;
|
||||||
|
} elseif (isset($extensions['clustering'])) {
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public function transactionStart($transaction_mode = false, $session_characteristics = false){
|
public function transactionStart($transaction_mode = false, $session_characteristics = false)
|
||||||
$this->query('BEGIN;');
|
{
|
||||||
|
$this->query('BEGIN;');
|
||||||
|
|
||||||
if($transaction_mode) {
|
if ($transaction_mode) {
|
||||||
$this->query("SET TRANSACTION {$transaction_mode};");
|
$this->query("SET TRANSACTION {$transaction_mode};");
|
||||||
}
|
}
|
||||||
|
|
||||||
if($session_characteristics) {
|
if ($session_characteristics) {
|
||||||
$this->query("SET SESSION CHARACTERISTICS AS TRANSACTION {$session_characteristics};");
|
$this->query("SET SESSION CHARACTERISTICS AS TRANSACTION {$session_characteristics};");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public function transactionSavepoint($savepoint){
|
public function transactionSavepoint($savepoint)
|
||||||
$this->query("SAVEPOINT {$savepoint};");
|
{
|
||||||
}
|
$this->query("SAVEPOINT {$savepoint};");
|
||||||
|
}
|
||||||
|
|
||||||
public function transactionRollback($savepoint = false){
|
public function transactionRollback($savepoint = false)
|
||||||
if($savepoint) {
|
{
|
||||||
$this->query("ROLLBACK TO {$savepoint};");
|
if ($savepoint) {
|
||||||
} else {
|
$this->query("ROLLBACK TO {$savepoint};");
|
||||||
$this->query('ROLLBACK;');
|
} else {
|
||||||
}
|
$this->query('ROLLBACK;');
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public function transactionEnd($chain = false){
|
public function transactionEnd($chain = false)
|
||||||
$this->query('COMMIT;');
|
{
|
||||||
}
|
$this->query('COMMIT;');
|
||||||
|
}
|
||||||
|
|
||||||
public function comparisonClause($field, $value, $exact = false, $negate = false, $caseSensitive = null, $parameterised = false) {
|
public function comparisonClause($field, $value, $exact = false, $negate = false, $caseSensitive = null, $parameterised = false)
|
||||||
if($exact && $caseSensitive === null) {
|
{
|
||||||
$comp = ($negate) ? '!=' : '=';
|
if ($exact && $caseSensitive === null) {
|
||||||
} else {
|
$comp = ($negate) ? '!=' : '=';
|
||||||
$comp = ($caseSensitive === true) ? 'LIKE' : 'ILIKE';
|
} else {
|
||||||
if($negate) $comp = 'NOT ' . $comp;
|
$comp = ($caseSensitive === true) ? 'LIKE' : 'ILIKE';
|
||||||
$field.='::text';
|
if ($negate) {
|
||||||
}
|
$comp = 'NOT ' . $comp;
|
||||||
|
}
|
||||||
|
$field.='::text';
|
||||||
|
}
|
||||||
|
|
||||||
if($parameterised) {
|
if ($parameterised) {
|
||||||
return sprintf("%s %s ?", $field, $comp);
|
return sprintf("%s %s ?", $field, $comp);
|
||||||
} else {
|
} else {
|
||||||
return sprintf("%s %s '%s'", $field, $comp, $value);
|
return sprintf("%s %s '%s'", $field, $comp, $value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Function to return an SQL datetime expression that can be used with Postgres
|
* Function to return an SQL datetime expression that can be used with Postgres
|
||||||
* used for querying a datetime in a certain format
|
* used for querying a datetime in a certain format
|
||||||
* @param string $date to be formated, can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"'
|
* @param string $date to be formated, can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"'
|
||||||
* @param string $format to be used, supported specifiers:
|
* @param string $format to be used, supported specifiers:
|
||||||
* %Y = Year (four digits)
|
* %Y = Year (four digits)
|
||||||
* %m = Month (01..12)
|
* %m = Month (01..12)
|
||||||
* %d = Day (01..31)
|
* %d = Day (01..31)
|
||||||
* %H = Hour (00..23)
|
* %H = Hour (00..23)
|
||||||
* %i = Minutes (00..59)
|
* %i = Minutes (00..59)
|
||||||
* %s = Seconds (00..59)
|
* %s = Seconds (00..59)
|
||||||
* %U = unix timestamp, can only be used on it's own
|
* %U = unix timestamp, can only be used on it's own
|
||||||
* @return string SQL datetime expression to query for a formatted datetime
|
* @return string SQL datetime expression to query for a formatted datetime
|
||||||
*/
|
*/
|
||||||
public function formattedDatetimeClause($date, $format) {
|
public function formattedDatetimeClause($date, $format)
|
||||||
preg_match_all('/%(.)/', $format, $matches);
|
{
|
||||||
foreach($matches[1] as $match) {
|
preg_match_all('/%(.)/', $format, $matches);
|
||||||
if(array_search($match, array('Y','m','d','H','i','s','U')) === false) {
|
foreach ($matches[1] as $match) {
|
||||||
user_error('formattedDatetimeClause(): unsupported format character %' . $match, E_USER_WARNING);
|
if (array_search($match, array('Y', 'm', 'd', 'H', 'i', 's', 'U')) === false) {
|
||||||
}
|
user_error('formattedDatetimeClause(): unsupported format character %' . $match, E_USER_WARNING);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
$translate = array(
|
$translate = array(
|
||||||
'/%Y/' => 'YYYY',
|
'/%Y/' => 'YYYY',
|
||||||
'/%m/' => 'MM',
|
'/%m/' => 'MM',
|
||||||
'/%d/' => 'DD',
|
'/%d/' => 'DD',
|
||||||
'/%H/' => 'HH24',
|
'/%H/' => 'HH24',
|
||||||
'/%i/' => 'MI',
|
'/%i/' => 'MI',
|
||||||
'/%s/' => 'SS',
|
'/%s/' => 'SS',
|
||||||
);
|
);
|
||||||
$format = preg_replace(array_keys($translate), array_values($translate), $format);
|
$format = preg_replace(array_keys($translate), array_values($translate), $format);
|
||||||
|
|
||||||
if(preg_match('/^now$/i', $date)) {
|
if (preg_match('/^now$/i', $date)) {
|
||||||
$date = "NOW()";
|
$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'";
|
$date = "TIMESTAMP '$date'";
|
||||||
}
|
}
|
||||||
|
|
||||||
if($format == '%U') return "FLOOR(EXTRACT(epoch FROM $date))";
|
if ($format == '%U') {
|
||||||
|
return "FLOOR(EXTRACT(epoch FROM $date))";
|
||||||
|
}
|
||||||
|
|
||||||
return "to_char($date, TEXT '$format')";
|
return "to_char($date, TEXT '$format')";
|
||||||
|
}
|
||||||
|
|
||||||
}
|
/**
|
||||||
|
* Function to return an SQL datetime expression that can be used with Postgres
|
||||||
|
* used for querying a datetime addition
|
||||||
|
* @param string $date, can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"'
|
||||||
|
* @param string $interval to be added, use the format [sign][integer] [qualifier], e.g. -1 Day, +15 minutes, +1 YEAR
|
||||||
|
* supported qualifiers:
|
||||||
|
* - years
|
||||||
|
* - months
|
||||||
|
* - days
|
||||||
|
* - hours
|
||||||
|
* - minutes
|
||||||
|
* - seconds
|
||||||
|
* 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)) {
|
||||||
|
$date = "NOW()";
|
||||||
|
} elseif (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date)) {
|
||||||
|
$date = "TIMESTAMP '$date'";
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
// ... when being too precise becomes a pain. we need to cut of the fractions.
|
||||||
* Function to return an SQL datetime expression that can be used with Postgres
|
// TIMESTAMP(0) doesn't work because it rounds instead flooring
|
||||||
* used for querying a datetime addition
|
return "CAST(SUBSTRING(CAST($date + INTERVAL '$interval' AS VARCHAR) FROM 1 FOR 19) AS TIMESTAMP)";
|
||||||
* @param string $date, can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"'
|
}
|
||||||
* @param string $interval to be added, use the format [sign][integer] [qualifier], e.g. -1 Day, +15 minutes, +1 YEAR
|
|
||||||
* supported qualifiers:
|
|
||||||
* - years
|
|
||||||
* - months
|
|
||||||
* - days
|
|
||||||
* - hours
|
|
||||||
* - minutes
|
|
||||||
* - seconds
|
|
||||||
* 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)) {
|
|
||||||
$date = "NOW()";
|
|
||||||
} else if(preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date)) {
|
|
||||||
$date = "TIMESTAMP '$date'";
|
|
||||||
}
|
|
||||||
|
|
||||||
// ... when being too precise becomes a pain. we need to cut of the fractions.
|
/**
|
||||||
// TIMESTAMP(0) doesn't work because it rounds instead flooring
|
* Function to return an SQL datetime expression that can be used with Postgres
|
||||||
return "CAST(SUBSTRING(CAST($date + INTERVAL '$interval' AS VARCHAR) FROM 1 FOR 19) AS TIMESTAMP)";
|
* used for querying a datetime substraction
|
||||||
}
|
* @param string $date1, can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"'
|
||||||
|
* @param string $date2 to be substracted of $date1, can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"'
|
||||||
|
* @return string SQL datetime expression to query for the interval between $date1 and $date2 in seconds which is the result of the substraction
|
||||||
|
*/
|
||||||
|
public function datetimeDifferenceClause($date1, $date2)
|
||||||
|
{
|
||||||
|
if (preg_match('/^now$/i', $date1)) {
|
||||||
|
$date1 = "NOW()";
|
||||||
|
} elseif (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date1)) {
|
||||||
|
$date1 = "TIMESTAMP '$date1'";
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
if (preg_match('/^now$/i', $date2)) {
|
||||||
* Function to return an SQL datetime expression that can be used with Postgres
|
$date2 = "NOW()";
|
||||||
* used for querying a datetime substraction
|
} elseif (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date2)) {
|
||||||
* @param string $date1, can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"'
|
$date2 = "TIMESTAMP '$date2'";
|
||||||
* @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)) {
|
|
||||||
$date1 = "NOW()";
|
|
||||||
} else if(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)) {
|
return "(FLOOR(EXTRACT(epoch FROM $date1)) - FLOOR(EXTRACT(epoch from $date2)))";
|
||||||
$date2 = "NOW()";
|
}
|
||||||
} else if(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)))";
|
public function now()
|
||||||
}
|
{
|
||||||
|
return 'NOW()';
|
||||||
|
}
|
||||||
|
|
||||||
function now(){
|
public function random()
|
||||||
return 'NOW()';
|
{
|
||||||
}
|
return 'RANDOM()';
|
||||||
|
}
|
||||||
|
|
||||||
function random(){
|
/**
|
||||||
return 'RANDOM()';
|
* Determines the name of the current database to be reported externally
|
||||||
}
|
* by substituting the schema name for the database name.
|
||||||
|
* Should only be used when model_schema_as_database is true
|
||||||
|
*
|
||||||
|
* @param string $schema Name of the schema
|
||||||
|
* @return string Name of the database to report
|
||||||
|
*/
|
||||||
|
public function schemaToDatabaseName($schema)
|
||||||
|
{
|
||||||
|
switch ($schema) {
|
||||||
|
case $this->schemaOriginal: return $this->databaseOriginal;
|
||||||
|
default: return $schema;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determines the name of the current database to be reported externally
|
* Translates a requested database name to a schema name to substitute internally.
|
||||||
* by substituting the schema name for the database name.
|
* Should only be used when model_schema_as_database is true
|
||||||
* Should only be used when model_schema_as_database is true
|
*
|
||||||
*
|
* @param string $database Name of the database
|
||||||
* @param string $schema Name of the schema
|
* @return string Name of the schema to use for this database internally
|
||||||
* @return string Name of the database to report
|
*/
|
||||||
*/
|
public function databaseToSchemaName($database)
|
||||||
public function schemaToDatabaseName($schema) {
|
{
|
||||||
switch($schema) {
|
switch ($database) {
|
||||||
case $this->schemaOriginal: return $this->databaseOriginal;
|
case $this->databaseOriginal: return $this->schemaOriginal;
|
||||||
default: return $schema;
|
default: return $database;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
public function dropSelectedDatabase()
|
||||||
* Translates a requested database name to a schema name to substitute internally.
|
{
|
||||||
* Should only be used when model_schema_as_database is true
|
if (self::model_schema_as_database()) {
|
||||||
*
|
// Check current schema is valid
|
||||||
* @param string $database Name of the database
|
$oldSchema = $this->schema;
|
||||||
* @return string Name of the schema to use for this database internally
|
if (empty($oldSchema)) {
|
||||||
*/
|
return true;
|
||||||
public function databaseToSchemaName($database) {
|
} // Nothing selected to drop
|
||||||
switch($database) {
|
|
||||||
case $this->databaseOriginal: return $this->schemaOriginal;
|
|
||||||
default: return $database;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function dropSelectedDatabase() {
|
// Select another schema
|
||||||
if(self::model_schema_as_database()) {
|
if ($oldSchema !== $this->schemaOriginal) {
|
||||||
// Check current schema is valid
|
$this->setSchema($this->schemaOriginal);
|
||||||
$oldSchema = $this->schema;
|
} elseif ($oldSchema !== self::MASTER_SCHEMA) {
|
||||||
if(empty($oldSchema)) return true; // Nothing selected to drop
|
$this->setSchema(self::MASTER_SCHEMA);
|
||||||
|
} else {
|
||||||
|
$this->schema = null;
|
||||||
|
}
|
||||||
|
|
||||||
// Select another schema
|
// Remove this schema
|
||||||
if($oldSchema !== $this->schemaOriginal) {
|
$this->schemaManager->dropSchema($oldSchema);
|
||||||
$this->setSchema($this->schemaOriginal);
|
} else {
|
||||||
} elseif($oldSchema !== self::MASTER_SCHEMA) {
|
parent::dropSelectedDatabase();
|
||||||
$this->setSchema(self::MASTER_SCHEMA);
|
}
|
||||||
} else {
|
}
|
||||||
$this->schema = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remove this schema
|
public function getSelectedDatabase()
|
||||||
$this->schemaManager->dropSchema($oldSchema);
|
{
|
||||||
} else {
|
if (self::model_schema_as_database()) {
|
||||||
parent::dropSelectedDatabase();
|
return $this->schemaToDatabaseName($this->schema);
|
||||||
}
|
}
|
||||||
}
|
return parent::getSelectedDatabase();
|
||||||
|
}
|
||||||
|
|
||||||
public function getSelectedDatabase() {
|
public function selectDatabase($name, $create = false, $errorLevel = E_USER_ERROR)
|
||||||
if(self::model_schema_as_database()) {
|
{
|
||||||
return $this->schemaToDatabaseName($this->schema);
|
// Substitute schema here as appropriate
|
||||||
}
|
if (self::model_schema_as_database()) {
|
||||||
return parent::getSelectedDatabase();
|
// Selecting the database itself should be treated as selecting the public schema
|
||||||
}
|
$schemaName = $this->databaseToSchemaName($name);
|
||||||
|
return $this->setSchema($schemaName, $create, $errorLevel);
|
||||||
|
}
|
||||||
|
|
||||||
public function selectDatabase($name, $create = false, $errorLevel = E_USER_ERROR) {
|
// Database selection requires that a new connection is established.
|
||||||
// Substitute schema here as appropriate
|
// This is not ideal postgres practise
|
||||||
if(self::model_schema_as_database()) {
|
if (!$this->schemaManager->databaseExists($name)) {
|
||||||
// Selecting the database itself should be treated as selecting the public schema
|
// Check DB creation permisson
|
||||||
$schemaName = $this->databaseToSchemaName($name);
|
if (!$create) {
|
||||||
return $this->setSchema($schemaName, $create, $errorLevel);
|
if ($errorLevel !== false) {
|
||||||
}
|
user_error("Attempted to connect to non-existing database \"$name\"", $errorLevel);
|
||||||
|
}
|
||||||
|
// Unselect database
|
||||||
|
$this->connector->unloadDatabase();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
$this->schemaManager->createDatabase($name);
|
||||||
|
}
|
||||||
|
|
||||||
// Database selection requires that a new connection is established.
|
// New connection made here, treating the new database name as the new original
|
||||||
// This is not ideal postgres practise
|
$this->databaseOriginal = $name;
|
||||||
if (!$this->schemaManager->databaseExists($name)) {
|
$this->connectDefault();
|
||||||
// Check DB creation permisson
|
}
|
||||||
if (!$create) {
|
|
||||||
if ($errorLevel !== false) {
|
|
||||||
user_error("Attempted to connect to non-existing database \"$name\"", $errorLevel);
|
|
||||||
}
|
|
||||||
// Unselect database
|
|
||||||
$this->connector->unloadDatabase();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
$this->schemaManager->createDatabase($name);
|
|
||||||
}
|
|
||||||
|
|
||||||
// New connection made here, treating the new database name as the new original
|
/**
|
||||||
$this->databaseOriginal = $name;
|
* Delete all entries from the table instead of truncating it.
|
||||||
$this->connectDefault();
|
*
|
||||||
}
|
* This gives a massive speed improvement compared to using TRUNCATE, with
|
||||||
|
* the caveat that primary keys are not reset etc.
|
||||||
/**
|
*
|
||||||
* Delete all entries from the table instead of truncating it.
|
* @see DatabaseAdmin::clearAllData()
|
||||||
*
|
*
|
||||||
* This gives a massive speed improvement compared to using TRUNCATE, with
|
* @param string $table
|
||||||
* the caveat that primary keys are not reset etc.
|
*/
|
||||||
*
|
public function clearTable($table)
|
||||||
* @see DatabaseAdmin::clearAllData()
|
{
|
||||||
*
|
$this->query('DELETE FROM "'.$table.'";');
|
||||||
* @param string $table
|
}
|
||||||
*/
|
|
||||||
public function clearTable($table) {
|
|
||||||
$this->query('DELETE FROM "'.$table.'";');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -7,187 +7,198 @@
|
|||||||
*
|
*
|
||||||
* @package postgresql
|
* @package postgresql
|
||||||
*/
|
*/
|
||||||
class PostgreSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper {
|
class PostgreSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper
|
||||||
|
{
|
||||||
/**
|
|
||||||
* Create a connection of the appropriate type
|
/**
|
||||||
*
|
* Create a connection of the appropriate type
|
||||||
* @param array $databaseConfig
|
*
|
||||||
* @param string $error Error message passed by value
|
* @param array $databaseConfig
|
||||||
* @return mixed|null Either the connection object, or null if error
|
* @param string $error Error message passed by value
|
||||||
*/
|
* @return mixed|null Either the connection object, or null if error
|
||||||
protected function createConnection($databaseConfig, &$error) {
|
*/
|
||||||
$error = null;
|
protected function createConnection($databaseConfig, &$error)
|
||||||
$username = empty($databaseConfig['username']) ? '' : $databaseConfig['username'];
|
{
|
||||||
$password = empty($databaseConfig['password']) ? '' : $databaseConfig['password'];
|
$error = null;
|
||||||
$server = $databaseConfig['server'];
|
$username = empty($databaseConfig['username']) ? '' : $databaseConfig['username'];
|
||||||
|
$password = empty($databaseConfig['password']) ? '' : $databaseConfig['password'];
|
||||||
try {
|
$server = $databaseConfig['server'];
|
||||||
switch($databaseConfig['type']) {
|
|
||||||
case 'PostgreSQLDatabase':
|
try {
|
||||||
$userPart = $username ? " user=$username" : '';
|
switch ($databaseConfig['type']) {
|
||||||
$passwordPart = $password ? " password=$password" : '';
|
case 'PostgreSQLDatabase':
|
||||||
$connstring = "host=$server port=5432 dbname=postgres{$userPart}{$passwordPart}";
|
$userPart = $username ? " user=$username" : '';
|
||||||
$conn = pg_connect($connstring);
|
$passwordPart = $password ? " password=$password" : '';
|
||||||
break;
|
$connstring = "host=$server port=5432 dbname=postgres{$userPart}{$passwordPart}";
|
||||||
case 'PostgrePDODatabase':
|
$conn = pg_connect($connstring);
|
||||||
// May throw a PDOException if fails
|
break;
|
||||||
$conn = @new PDO('postgresql:host='.$server.';dbname=postgres;port=5432', $username, $password);
|
case 'PostgrePDODatabase':
|
||||||
break;
|
// May throw a PDOException if fails
|
||||||
default:
|
$conn = @new PDO('postgresql:host='.$server.';dbname=postgres;port=5432', $username, $password);
|
||||||
$error = 'Invalid connection type';
|
break;
|
||||||
return null;
|
default:
|
||||||
}
|
$error = 'Invalid connection type';
|
||||||
} catch(Exception $ex) {
|
return null;
|
||||||
$error = $ex->getMessage();
|
}
|
||||||
return null;
|
} catch (Exception $ex) {
|
||||||
}
|
$error = $ex->getMessage();
|
||||||
if($conn) {
|
return null;
|
||||||
return $conn;
|
}
|
||||||
} else {
|
if ($conn) {
|
||||||
$error = 'PostgreSQL requires a valid username and password to determine if the server exists.';
|
return $conn;
|
||||||
return null;
|
} else {
|
||||||
}
|
$error = 'PostgreSQL requires a valid username and password to determine if the server exists.';
|
||||||
}
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public function requireDatabaseFunctions($databaseConfig) {
|
public function requireDatabaseFunctions($databaseConfig)
|
||||||
$data = DatabaseAdapterRegistry::get_adapter($databaseConfig['type']);
|
{
|
||||||
return !empty($data['supported']);
|
$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);
|
$conn = $this->createConnection($databaseConfig, $error);
|
||||||
return array(
|
$success = !empty($conn);
|
||||||
'success' => $success,
|
return array(
|
||||||
'error' => $error
|
'success' => $success,
|
||||||
);
|
'error' => $error
|
||||||
}
|
);
|
||||||
|
}
|
||||||
|
|
||||||
public function requireDatabaseConnection($databaseConfig) {
|
public function requireDatabaseConnection($databaseConfig)
|
||||||
$conn = $this->createConnection($databaseConfig, $error);
|
{
|
||||||
$success = !empty($conn);
|
$conn = $this->createConnection($databaseConfig, $error);
|
||||||
return array(
|
$success = !empty($conn);
|
||||||
'success' => $success,
|
return array(
|
||||||
'connection' => $conn,
|
'success' => $success,
|
||||||
'error' => $error
|
'connection' => $conn,
|
||||||
);
|
'error' => $error
|
||||||
}
|
);
|
||||||
|
}
|
||||||
|
|
||||||
public function getDatabaseVersion($databaseConfig) {
|
public function getDatabaseVersion($databaseConfig)
|
||||||
$conn = $this->createConnection($databaseConfig, $error);
|
{
|
||||||
if(!$conn) {
|
$conn = $this->createConnection($databaseConfig, $error);
|
||||||
return false;
|
if (!$conn) {
|
||||||
} elseif($conn instanceof PDO) {
|
return false;
|
||||||
return $conn->getAttribute(PDO::ATTR_SERVER_VERSION);
|
} elseif ($conn instanceof PDO) {
|
||||||
} elseif(is_resource($conn)) {
|
return $conn->getAttribute(PDO::ATTR_SERVER_VERSION);
|
||||||
$info = pg_version($conn);
|
} elseif (is_resource($conn)) {
|
||||||
return $info['server'];
|
$info = pg_version($conn);
|
||||||
} else {
|
return $info['server'];
|
||||||
return false;
|
} else {
|
||||||
}
|
return false;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ensure that the PostgreSQL version is at least 8.3.
|
* Ensure that the PostgreSQL version is at least 8.3.
|
||||||
*
|
*
|
||||||
* @param array $databaseConfig Associative array of db configuration, e.g. "server", "username" etc
|
* @param array $databaseConfig Associative array of db configuration, e.g. "server", "username" etc
|
||||||
* @return array Result - e.g. array('success' => true, 'error' => 'details of error')
|
* @return array Result - e.g. array('success' => true, 'error' => 'details of error')
|
||||||
*/
|
*/
|
||||||
public function requireDatabaseVersion($databaseConfig) {
|
public function requireDatabaseVersion($databaseConfig)
|
||||||
$success = false;
|
{
|
||||||
$error = '';
|
$success = false;
|
||||||
$version = $this->getDatabaseVersion($databaseConfig);
|
$error = '';
|
||||||
|
$version = $this->getDatabaseVersion($databaseConfig);
|
||||||
|
|
||||||
if($version) {
|
if ($version) {
|
||||||
$success = version_compare($version, '8.3', '>=');
|
$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.";
|
$error = "Your PostgreSQL version is $version. It's recommended you use at least 8.3.";
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
$error = "Your PostgreSQL version could not be determined.";
|
$error = "Your PostgreSQL version could not be determined.";
|
||||||
}
|
}
|
||||||
|
|
||||||
return array(
|
return array(
|
||||||
'success' => $success,
|
'success' => $success,
|
||||||
'error' => $error
|
'error' => $error
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Helper function to quote a string value
|
* Helper function to quote a string value
|
||||||
*
|
*
|
||||||
* @param mixed $conn Connection object/resource
|
* @param mixed $conn Connection object/resource
|
||||||
* @param string $value Value to quote
|
* @param string $value Value to quote
|
||||||
* @return string Quoted strieng
|
* @return string Quoted strieng
|
||||||
*/
|
*/
|
||||||
protected function quote($conn, $value) {
|
protected function quote($conn, $value)
|
||||||
if($conn instanceof PDO) {
|
{
|
||||||
return $conn->quote($value);
|
if ($conn instanceof PDO) {
|
||||||
} elseif(is_resource($conn)) {
|
return $conn->quote($value);
|
||||||
return "'".pg_escape_string($conn, $value)."'";
|
} elseif (is_resource($conn)) {
|
||||||
} else {
|
return "'".pg_escape_string($conn, $value)."'";
|
||||||
user_error('Invalid database connection', E_USER_ERROR);
|
} else {
|
||||||
}
|
user_error('Invalid database connection', E_USER_ERROR);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
/**
|
|
||||||
* Helper function to execute a query
|
/**
|
||||||
*
|
* Helper function to execute a query
|
||||||
* @param mixed $conn Connection object/resource
|
*
|
||||||
* @param string $sql SQL string to execute
|
* @param mixed $conn Connection object/resource
|
||||||
* @return array List of first value from each resulting row
|
* @param string $sql SQL string to execute
|
||||||
*/
|
* @return array List of first value from each resulting row
|
||||||
protected function query($conn, $sql) {
|
*/
|
||||||
$items = array();
|
protected function query($conn, $sql)
|
||||||
if($conn instanceof PDO) {
|
{
|
||||||
foreach($conn->query($sql) as $row) {
|
$items = array();
|
||||||
$items[] = $row[0];
|
if ($conn instanceof PDO) {
|
||||||
}
|
foreach ($conn->query($sql) as $row) {
|
||||||
} elseif(is_resource($conn)) {
|
$items[] = $row[0];
|
||||||
$result = pg_query($conn, $sql);
|
}
|
||||||
while ($row = pg_fetch_row($result)) {
|
} elseif (is_resource($conn)) {
|
||||||
$items[] = $row[0];
|
$result = pg_query($conn, $sql);
|
||||||
}
|
while ($row = pg_fetch_row($result)) {
|
||||||
}
|
$items[] = $row[0];
|
||||||
return $items;
|
}
|
||||||
}
|
}
|
||||||
|
return $items;
|
||||||
|
}
|
||||||
|
|
||||||
public function requireDatabaseOrCreatePermissions($databaseConfig) {
|
public function requireDatabaseOrCreatePermissions($databaseConfig)
|
||||||
$success = false;
|
{
|
||||||
$alreadyExists = false;
|
$success = false;
|
||||||
$conn = $this->createConnection($databaseConfig, $error);
|
$alreadyExists = false;
|
||||||
if($conn) {
|
$conn = $this->createConnection($databaseConfig, $error);
|
||||||
// Check if db already exists
|
if ($conn) {
|
||||||
$existingDatabases = $this->query($conn, "SELECT datname FROM pg_database");
|
// Check if db already exists
|
||||||
$alreadyExists = in_array($databaseConfig['database'], $existingDatabases);
|
$existingDatabases = $this->query($conn, "SELECT datname FROM pg_database");
|
||||||
if($alreadyExists) {
|
$alreadyExists = in_array($databaseConfig['database'], $existingDatabases);
|
||||||
$success = true;
|
if ($alreadyExists) {
|
||||||
} else {
|
$success = true;
|
||||||
// Check if this user has create privileges
|
} else {
|
||||||
$allowedUsers = $this->query($conn, "select rolname from pg_authid where rolcreatedb = true;");
|
// Check if this user has create privileges
|
||||||
$success = in_array($databaseConfig['username'], $allowedUsers);
|
$allowedUsers = $this->query($conn, "select rolname from pg_authid where rolcreatedb = true;");
|
||||||
}
|
$success = in_array($databaseConfig['username'], $allowedUsers);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
return array(
|
|
||||||
'success' => $success,
|
return array(
|
||||||
'alreadyExists' => $alreadyExists
|
'success' => $success,
|
||||||
);
|
'alreadyExists' => $alreadyExists
|
||||||
}
|
);
|
||||||
|
}
|
||||||
|
|
||||||
public function requireDatabaseAlterPermissions($databaseConfig) {
|
public function requireDatabaseAlterPermissions($databaseConfig)
|
||||||
$conn = $this->createConnection($databaseConfig, $error);
|
{
|
||||||
if($conn) {
|
$conn = $this->createConnection($databaseConfig, $error);
|
||||||
// if the account can even log in, it can alter tables
|
if ($conn) {
|
||||||
return array(
|
// if the account can even log in, it can alter tables
|
||||||
'success' => true,
|
return array(
|
||||||
'applies' => true
|
'success' => true,
|
||||||
);
|
'applies' => true
|
||||||
}
|
);
|
||||||
return array(
|
}
|
||||||
'success' => false,
|
return array(
|
||||||
'applies' => true
|
'success' => false,
|
||||||
);
|
'applies' => true
|
||||||
}
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,36 +6,44 @@
|
|||||||
* @package sapphire
|
* @package sapphire
|
||||||
* @subpackage model
|
* @subpackage model
|
||||||
*/
|
*/
|
||||||
class PostgreSQLQuery extends SS_Query {
|
class PostgreSQLQuery extends SS_Query
|
||||||
|
{
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The internal Postgres handle that points to the result set.
|
* The internal Postgres handle that points to the result set.
|
||||||
* @var resource
|
* @var resource
|
||||||
*/
|
*/
|
||||||
private $handle;
|
private $handle;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Hook the result-set given into a Query class, suitable for use by sapphire.
|
* Hook the result-set given into a Query class, suitable for use by sapphire.
|
||||||
* @param database The database object that created this query.
|
* @param database The database object that created this query.
|
||||||
* @param handle the internal Postgres handle that is points to the resultset.
|
* @param handle the internal Postgres handle that is points to the resultset.
|
||||||
*/
|
*/
|
||||||
public function __construct($handle) {
|
public function __construct($handle)
|
||||||
$this->handle = $handle;
|
{
|
||||||
}
|
$this->handle = $handle;
|
||||||
|
}
|
||||||
|
|
||||||
public function __destruct() {
|
public function __destruct()
|
||||||
if(is_resource($this->handle)) pg_free_result($this->handle);
|
{
|
||||||
}
|
if (is_resource($this->handle)) {
|
||||||
|
pg_free_result($this->handle);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public function seek($row) {
|
public function seek($row)
|
||||||
return pg_result_seek($this->handle, $row);
|
{
|
||||||
}
|
return pg_result_seek($this->handle, $row);
|
||||||
|
}
|
||||||
|
|
||||||
public function numRecords() {
|
public function numRecords()
|
||||||
return pg_num_rows($this->handle);
|
{
|
||||||
}
|
return pg_num_rows($this->handle);
|
||||||
|
}
|
||||||
|
|
||||||
public function nextRecord() {
|
public function nextRecord()
|
||||||
return pg_fetch_assoc($this->handle);
|
{
|
||||||
}
|
return pg_fetch_assoc($this->handle);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,42 +1,45 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
class PostgreSQLQueryBuilder extends DBQueryBuilder {
|
class PostgreSQLQueryBuilder extends DBQueryBuilder
|
||||||
|
{
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Return the LIMIT clause ready for inserting into a query.
|
* Return the LIMIT clause ready for inserting into a query.
|
||||||
*
|
*
|
||||||
* @param SQLSelect $query The expression object to build from
|
* @param SQLSelect $query The expression object to build from
|
||||||
* @param array $parameters Out parameter for the resulting query parameters
|
* @param array $parameters Out parameter for the resulting query parameters
|
||||||
* @return string The finalised limit SQL fragment
|
* @return string The finalised limit SQL fragment
|
||||||
*/
|
*/
|
||||||
public function buildLimitFragment(SQLSelect $query, array &$parameters) {
|
public function buildLimitFragment(SQLSelect $query, array &$parameters)
|
||||||
$nl = $this->getSeparator();
|
{
|
||||||
|
$nl = $this->getSeparator();
|
||||||
|
|
||||||
// Ensure limit is given
|
// Ensure limit is given
|
||||||
$limit = $query->getLimit();
|
$limit = $query->getLimit();
|
||||||
if(empty($limit)) return '';
|
if (empty($limit)) {
|
||||||
|
return '';
|
||||||
// For literal values return this as the limit SQL
|
}
|
||||||
if( ! is_array($limit)) {
|
|
||||||
return "{$nl}LIMIT $limit";
|
// For literal values return this as the limit SQL
|
||||||
}
|
if (! is_array($limit)) {
|
||||||
|
return "{$nl}LIMIT $limit";
|
||||||
|
}
|
||||||
|
|
||||||
// Assert that the array version provides the 'limit' key
|
// 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(
|
throw new InvalidArgumentException(
|
||||||
'DBQueryBuilder::buildLimitSQL(): Wrong format for $limit: '. var_export($limit, true)
|
'DBQueryBuilder::buildLimitSQL(): Wrong format for $limit: '. var_export($limit, true)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if($limit['limit'] === null) {
|
|
||||||
$limit['limit'] = 'ALL';
|
|
||||||
}
|
|
||||||
|
|
||||||
$clause = "{$nl}LIMIT {$limit['limit']}";
|
|
||||||
if(isset($limit['start']) && is_numeric($limit['start']) && $limit['start'] !== 0) {
|
|
||||||
$clause .= " OFFSET {$limit['start']}";
|
|
||||||
}
|
|
||||||
return $clause;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
if ($limit['limit'] === null) {
|
||||||
|
$limit['limit'] = 'ALL';
|
||||||
|
}
|
||||||
|
|
||||||
|
$clause = "{$nl}LIMIT {$limit['limit']}";
|
||||||
|
if (isset($limit['start']) && is_numeric($limit['start']) && $limit['start'] !== 0) {
|
||||||
|
$clause .= " OFFSET {$limit['start']}";
|
||||||
|
}
|
||||||
|
return $clause;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,895 +6,958 @@
|
|||||||
* @package sapphire
|
* @package sapphire
|
||||||
* @subpackage model
|
* @subpackage model
|
||||||
*/
|
*/
|
||||||
class PostgreSQLSchemaManager extends DBSchemaManager {
|
class PostgreSQLSchemaManager extends DBSchemaManager
|
||||||
|
{
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Identifier for this schema, used for configuring schema-specific table
|
* Identifier for this schema, used for configuring schema-specific table
|
||||||
* creation options
|
* creation options
|
||||||
*/
|
*/
|
||||||
const ID = 'PostgreSQL';
|
const ID = 'PostgreSQL';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Instance of the database controller this schema belongs to
|
* Instance of the database controller this schema belongs to
|
||||||
*
|
*
|
||||||
* @var PostgreSQLDatabase
|
* @var PostgreSQLDatabase
|
||||||
*/
|
*/
|
||||||
protected $database = null;
|
protected $database = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This holds a copy of all the constraint results that are returned
|
* This holds a copy of all the constraint results that are returned
|
||||||
* via the function constraintExists(). This is a bit faster than
|
* via the function constraintExists(). This is a bit faster than
|
||||||
* repeatedly querying this column, and should allow the database
|
* repeatedly querying this column, and should allow the database
|
||||||
* to use it's built-in caching features for better queries.
|
* to use it's built-in caching features for better queries.
|
||||||
*
|
*
|
||||||
* @var array
|
* @var array
|
||||||
*/
|
*/
|
||||||
protected static $cached_constraints = array();
|
protected static $cached_constraints = array();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* This holds a copy of all the queries that run through the function fieldList()
|
* This holds a copy of all the queries that run through the function fieldList()
|
||||||
* This is one of the most-often called functions, and repeats itself a great deal in the unit tests.
|
* This is one of the most-often called functions, and repeats itself a great deal in the unit tests.
|
||||||
*
|
*
|
||||||
* @var array
|
* @var array
|
||||||
*/
|
*/
|
||||||
protected static $cached_fieldlists = array();
|
protected static $cached_fieldlists = array();
|
||||||
|
|
||||||
protected function indexKey($table, $index, $spec) {
|
protected function indexKey($table, $index, $spec)
|
||||||
return $this->buildPostgresIndexName($table, $index);
|
{
|
||||||
}
|
return $this->buildPostgresIndexName($table, $index);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a postgres database, ignoring model_schema_as_database
|
* Creates a postgres database, ignoring model_schema_as_database
|
||||||
*
|
*
|
||||||
* @param string $name
|
* @param string $name
|
||||||
*/
|
*/
|
||||||
public function createPostgresDatabase($name) {
|
public function createPostgresDatabase($name)
|
||||||
$this->query("CREATE DATABASE \"$name\";");
|
{
|
||||||
}
|
$this->query("CREATE DATABASE \"$name\";");
|
||||||
|
}
|
||||||
|
|
||||||
public function createDatabase($name) {
|
public function createDatabase($name)
|
||||||
if(PostgreSQLDatabase::model_schema_as_database()) {
|
{
|
||||||
$schemaName = $this->database->databaseToSchemaName($name);
|
if (PostgreSQLDatabase::model_schema_as_database()) {
|
||||||
return $this->createSchema($schemaName);
|
$schemaName = $this->database->databaseToSchemaName($name);
|
||||||
}
|
return $this->createSchema($schemaName);
|
||||||
return $this->createPostgresDatabase($name);
|
}
|
||||||
}
|
return $this->createPostgresDatabase($name);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determines if a postgres database exists, ignoring model_schema_as_database
|
* Determines if a postgres database exists, ignoring model_schema_as_database
|
||||||
*
|
*
|
||||||
* @param string $name
|
* @param string $name
|
||||||
* @return boolean
|
* @return boolean
|
||||||
*/
|
*/
|
||||||
public function postgresDatabaseExists($name) {
|
public function postgresDatabaseExists($name)
|
||||||
$result = $this->preparedQuery("SELECT datname FROM pg_database WHERE datname = ?;", array($name));
|
{
|
||||||
return $result->first() ? true : false;
|
$result = $this->preparedQuery("SELECT datname FROM pg_database WHERE datname = ?;", array($name));
|
||||||
}
|
return $result->first() ? true : false;
|
||||||
|
}
|
||||||
|
|
||||||
public function databaseExists($name) {
|
public function databaseExists($name)
|
||||||
if(PostgreSQLDatabase::model_schema_as_database()) {
|
{
|
||||||
$schemaName = $this->database->databaseToSchemaName($name);
|
if (PostgreSQLDatabase::model_schema_as_database()) {
|
||||||
return $this->schemaExists($schemaName);
|
$schemaName = $this->database->databaseToSchemaName($name);
|
||||||
}
|
return $this->schemaExists($schemaName);
|
||||||
return $this->postgresDatabaseExists($name);
|
}
|
||||||
}
|
return $this->postgresDatabaseExists($name);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determines the list of all postgres databases, ignoring model_schema_as_database
|
* Determines the list of all postgres databases, ignoring model_schema_as_database
|
||||||
*
|
*
|
||||||
* @return array
|
* @return array
|
||||||
*/
|
*/
|
||||||
public function postgresDatabaseList() {
|
public function postgresDatabaseList()
|
||||||
return $this->query("SELECT datname FROM pg_database WHERE datistemplate=false;")->column();
|
{
|
||||||
}
|
return $this->query("SELECT datname FROM pg_database WHERE datistemplate=false;")->column();
|
||||||
|
}
|
||||||
|
|
||||||
public function databaseList() {
|
public function databaseList()
|
||||||
if(PostgreSQLDatabase::model_schema_as_database()) {
|
{
|
||||||
$schemas = $this->schemaList();
|
if (PostgreSQLDatabase::model_schema_as_database()) {
|
||||||
$names = array();
|
$schemas = $this->schemaList();
|
||||||
foreach($schemas as $schema) {
|
$names = array();
|
||||||
$names[] = $this->database->schemaToDatabaseName($schema);
|
foreach ($schemas as $schema) {
|
||||||
}
|
$names[] = $this->database->schemaToDatabaseName($schema);
|
||||||
return array_unique($names);
|
}
|
||||||
}
|
return array_unique($names);
|
||||||
return $this->postgresDatabaseList();
|
}
|
||||||
}
|
return $this->postgresDatabaseList();
|
||||||
/**
|
}
|
||||||
* Drops a postgres database, ignoring model_schema_as_database
|
/**
|
||||||
*
|
* Drops a postgres database, ignoring model_schema_as_database
|
||||||
* @param string $name
|
*
|
||||||
*/
|
* @param string $name
|
||||||
public function dropPostgresDatabase($name) {
|
*/
|
||||||
$nameSQL = $this->database->escapeIdentifier($name);
|
public function dropPostgresDatabase($name)
|
||||||
$this->query("DROP DATABASE $nameSQL;");
|
{
|
||||||
}
|
$nameSQL = $this->database->escapeIdentifier($name);
|
||||||
|
$this->query("DROP DATABASE $nameSQL;");
|
||||||
|
}
|
||||||
|
|
||||||
public function dropDatabase($name) {
|
public function dropDatabase($name)
|
||||||
if(PostgreSQLDatabase::model_schema_as_database()) {
|
{
|
||||||
$schemaName = $this->database->databaseToSchemaName($name);
|
if (PostgreSQLDatabase::model_schema_as_database()) {
|
||||||
return $this->dropSchema($schemaName);
|
$schemaName = $this->database->databaseToSchemaName($name);
|
||||||
}
|
return $this->dropSchema($schemaName);
|
||||||
$this->dropPostgresDatabase($name);
|
}
|
||||||
}
|
$this->dropPostgresDatabase($name);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns true if the schema exists in the current database
|
* Returns true if the schema exists in the current database
|
||||||
*
|
*
|
||||||
* @param string $name
|
* @param string $name
|
||||||
* @return boolean
|
* @return boolean
|
||||||
*/
|
*/
|
||||||
public function schemaExists($name) {
|
public function schemaExists($name)
|
||||||
return $this->preparedQuery(
|
{
|
||||||
"SELECT nspname FROM pg_catalog.pg_namespace WHERE nspname = ?;",
|
return $this->preparedQuery(
|
||||||
array($name)
|
"SELECT nspname FROM pg_catalog.pg_namespace WHERE nspname = ?;",
|
||||||
)->first() ? true : false;
|
array($name)
|
||||||
}
|
)->first() ? true : false;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a schema in the current database
|
* Creates a schema in the current database
|
||||||
*
|
*
|
||||||
* @param string $name
|
* @param string $name
|
||||||
*/
|
*/
|
||||||
public function createSchema($name) {
|
public function createSchema($name)
|
||||||
$nameSQL = $this->database->escapeIdentifier($name);
|
{
|
||||||
$this->query("CREATE SCHEMA $nameSQL;");
|
$nameSQL = $this->database->escapeIdentifier($name);
|
||||||
}
|
$this->query("CREATE SCHEMA $nameSQL;");
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Drops a schema from the database. Use carefully!
|
* Drops a schema from the database. Use carefully!
|
||||||
*
|
*
|
||||||
* @param string $name
|
* @param string $name
|
||||||
*/
|
*/
|
||||||
public function dropSchema($name) {
|
public function dropSchema($name)
|
||||||
$nameSQL = $this->database->escapeIdentifier($name);
|
{
|
||||||
$this->query("DROP SCHEMA $nameSQL CASCADE;");
|
$nameSQL = $this->database->escapeIdentifier($name);
|
||||||
}
|
$this->query("DROP SCHEMA $nameSQL CASCADE;");
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the list of all available schemas on the current database
|
* Returns the list of all available schemas on the current database
|
||||||
*
|
*
|
||||||
* @return array
|
* @return array
|
||||||
*/
|
*/
|
||||||
public function schemaList() {
|
public function schemaList()
|
||||||
return $this->query("
|
{
|
||||||
|
return $this->query("
|
||||||
SELECT nspname
|
SELECT nspname
|
||||||
FROM pg_catalog.pg_namespace
|
FROM pg_catalog.pg_namespace
|
||||||
WHERE nspname <> 'information_schema' AND nspname !~ E'^pg_'"
|
WHERE nspname <> 'information_schema' AND nspname !~ E'^pg_'"
|
||||||
)->column();
|
)->column();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function createTable($table, $fields = null, $indexes = null, $options = null, $advancedOptions = null) {
|
public function createTable($table, $fields = null, $indexes = null, $options = null, $advancedOptions = null)
|
||||||
|
{
|
||||||
|
$fieldSchemas = $indexSchemas = "";
|
||||||
|
if ($fields) {
|
||||||
|
foreach ($fields as $k => $v) {
|
||||||
|
$fieldSchemas .= "\"$k\" $v,\n";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!empty($options[self::ID])) {
|
||||||
|
$addOptions = $options[self::ID];
|
||||||
|
} elseif (!empty($options[get_class($this)])) {
|
||||||
|
Deprecation::notice('3.2', 'Use PostgreSQLSchemaManager::ID for referencing postgres-specific table creation options');
|
||||||
|
$addOptions = $options[get_class($this)];
|
||||||
|
} else {
|
||||||
|
$addOptions = null;
|
||||||
|
}
|
||||||
|
|
||||||
$fieldSchemas = $indexSchemas = "";
|
//First of all, does this table already exist
|
||||||
if($fields) foreach($fields as $k => $v) {
|
$doesExist = $this->hasTable($table);
|
||||||
$fieldSchemas .= "\"$k\" $v,\n";
|
if ($doesExist) {
|
||||||
}
|
// Table already exists, just return the name, in line with baseclass documentation.
|
||||||
if(!empty($options[self::ID])) {
|
return $table;
|
||||||
$addOptions = $options[self::ID];
|
}
|
||||||
} elseif (!empty($options[get_class($this)])) {
|
|
||||||
Deprecation::notice('3.2', 'Use PostgreSQLSchemaManager::ID for referencing postgres-specific table creation options');
|
|
||||||
$addOptions = $options[get_class($this)];
|
|
||||||
} else {
|
|
||||||
$addOptions = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
//First of all, does this table already exist
|
//If we have a fulltext search request, then we need to create a special column
|
||||||
$doesExist = $this->hasTable($table);
|
//for GiST searches
|
||||||
if($doesExist) {
|
$fulltexts = '';
|
||||||
// Table already exists, just return the name, in line with baseclass documentation.
|
$triggers = '';
|
||||||
return $table;
|
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'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
//If we have a fulltext search request, then we need to create a special column
|
if ($indexes) {
|
||||||
//for GiST searches
|
foreach ($indexes as $k => $v) {
|
||||||
$fulltexts = '';
|
$indexSchemas .= $this->getIndexSqlDefinition($table, $k, $v) . "\n";
|
||||||
$triggers = '';
|
}
|
||||||
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'];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if($indexes) foreach($indexes as $k => $v) {
|
//Do we need to create a tablespace for this item?
|
||||||
$indexSchemas .= $this->getIndexSqlDefinition($table, $k, $v) . "\n";
|
if ($advancedOptions && isset($advancedOptions['tablespace'])) {
|
||||||
}
|
$this->createOrReplaceTablespace(
|
||||||
|
$advancedOptions['tablespace']['name'],
|
||||||
|
$advancedOptions['tablespace']['location']
|
||||||
|
);
|
||||||
|
$tableSpace = ' TABLESPACE ' . $advancedOptions['tablespace']['name'];
|
||||||
|
} else {
|
||||||
|
$tableSpace = '';
|
||||||
|
}
|
||||||
|
|
||||||
//Do we need to create a tablespace for this item?
|
$this->query("CREATE TABLE \"$table\" (
|
||||||
if($advancedOptions && isset($advancedOptions['tablespace'])){
|
|
||||||
$this->createOrReplaceTablespace(
|
|
||||||
$advancedOptions['tablespace']['name'],
|
|
||||||
$advancedOptions['tablespace']['location']
|
|
||||||
);
|
|
||||||
$tableSpace = ' TABLESPACE ' . $advancedOptions['tablespace']['name'];
|
|
||||||
} else
|
|
||||||
$tableSpace = '';
|
|
||||||
|
|
||||||
$this->query("CREATE TABLE \"$table\" (
|
|
||||||
$fieldSchemas
|
$fieldSchemas
|
||||||
$fulltexts
|
$fulltexts
|
||||||
primary key (\"ID\")
|
primary key (\"ID\")
|
||||||
)$tableSpace; $indexSchemas $addOptions");
|
)$tableSpace; $indexSchemas $addOptions");
|
||||||
|
|
||||||
if($triggers!=''){
|
if ($triggers!='') {
|
||||||
$this->query($triggers);
|
$this->query($triggers);
|
||||||
}
|
}
|
||||||
|
|
||||||
//If we have a partitioning requirement, we do that here:
|
//If we have a partitioning requirement, we do that here:
|
||||||
if($advancedOptions && isset($advancedOptions['partitions'])){
|
if ($advancedOptions && isset($advancedOptions['partitions'])) {
|
||||||
$this->createOrReplacePartition($table, $advancedOptions['partitions'], $indexes, $advancedOptions);
|
$this->createOrReplacePartition($table, $advancedOptions['partitions'], $indexes, $advancedOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
//Lastly, clustering goes here:
|
//Lastly, clustering goes here:
|
||||||
if($advancedOptions && isset($advancedOptions['cluster'])){
|
if ($advancedOptions && isset($advancedOptions['cluster'])) {
|
||||||
$this->query("CLUSTER \"$table\" USING \"{$advancedOptions['cluster']}\";");
|
$this->query("CLUSTER \"$table\" USING \"{$advancedOptions['cluster']}\";");
|
||||||
}
|
}
|
||||||
|
|
||||||
return $table;
|
return $table;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Builds the internal Postgres index name given the silverstripe table and index name
|
* Builds the internal Postgres index name given the silverstripe table and index name
|
||||||
*
|
*
|
||||||
* @param string $tableName
|
* @param string $tableName
|
||||||
* @param string $indexName
|
* @param string $indexName
|
||||||
* @param string $prefix The optional prefix for the index. Defaults to "ix" for indexes.
|
* @param string $prefix The optional prefix for the index. Defaults to "ix" for indexes.
|
||||||
* @return string The postgres name of the index
|
* @return string The postgres name of the index
|
||||||
*/
|
*/
|
||||||
protected function buildPostgresIndexName($tableName, $indexName, $prefix = 'ix') {
|
protected function buildPostgresIndexName($tableName, $indexName, $prefix = 'ix')
|
||||||
|
{
|
||||||
|
|
||||||
// Assume all indexes also contain the table name
|
// Assume all indexes also contain the table name
|
||||||
// MD5 the table/index name combo to keep it to a fixed length.
|
// MD5 the table/index name combo to keep it to a fixed length.
|
||||||
// Exclude the prefix so that the trigger name can be easily generated from the index name
|
// Exclude the prefix so that the trigger name can be easily generated from the index name
|
||||||
$indexNamePG = "{$prefix}_" . md5("{$tableName}_{$indexName}");
|
$indexNamePG = "{$prefix}_" . md5("{$tableName}_{$indexName}");
|
||||||
|
|
||||||
// Limit to 63 characters
|
// Limit to 63 characters
|
||||||
if (strlen($indexNamePG) > 63) {
|
if (strlen($indexNamePG) > 63) {
|
||||||
return substr($indexNamePG, 0, 63);
|
return substr($indexNamePG, 0, 63);
|
||||||
} else {
|
} else {
|
||||||
return $indexNamePG;
|
return $indexNamePG;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Builds the internal Postgres trigger name given the silverstripe table and trigger name
|
* Builds the internal Postgres trigger name given the silverstripe table and trigger name
|
||||||
*
|
*
|
||||||
* @param string $tableName
|
* @param string $tableName
|
||||||
* @param string $triggerName
|
* @param string $triggerName
|
||||||
* @return string The postgres name of the trigger
|
* @return string The postgres name of the trigger
|
||||||
*/
|
*/
|
||||||
function buildPostgresTriggerName($tableName, $triggerName) {
|
public function buildPostgresTriggerName($tableName, $triggerName)
|
||||||
// Kind of cheating, but behaves the same way as indexes
|
{
|
||||||
return $this->buildPostgresIndexName($tableName, $triggerName, 'ts');
|
// 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) {
|
||||||
|
$alterList[] = "ADD \"$fieldName\" $fieldSpec";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
$alterList = array();
|
if ($alteredFields) {
|
||||||
if($newFields) foreach($newFields as $fieldName => $fieldSpec) {
|
foreach ($alteredFields as $indexName => $indexSpec) {
|
||||||
$alterList[] = "ADD \"$fieldName\" $fieldSpec";
|
$val = $this->alterTableAlterColumn($table, $indexName, $indexSpec);
|
||||||
}
|
if (!empty($val)) {
|
||||||
|
$alterList[] = $val;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if ($alteredFields) foreach ($alteredFields as $indexName => $indexSpec) {
|
//Do we need to do anything with the tablespaces?
|
||||||
$val = $this->alterTableAlterColumn($table, $indexName, $indexSpec);
|
if ($alteredOptions && isset($advancedOptions['tablespace'])) {
|
||||||
if (!empty($val)) $alterList[] = $val;
|
$this->createOrReplaceTablespace($advancedOptions['tablespace']['name'], $advancedOptions['tablespace']['location']);
|
||||||
}
|
$this->query("ALTER TABLE \"$table\" SET TABLESPACE {$advancedOptions['tablespace']['name']};");
|
||||||
|
}
|
||||||
|
|
||||||
//Do we need to do anything with the tablespaces?
|
//DB ABSTRACTION: we need to change the constraints to be a separate 'add' command,
|
||||||
if($alteredOptions && isset($advancedOptions['tablespace'])){
|
//see http://www.postgresql.org/docs/8.1/static/sql-altertable.html
|
||||||
$this->createOrReplaceTablespace($advancedOptions['tablespace']['name'], $advancedOptions['tablespace']['location']);
|
$alterIndexList = array();
|
||||||
$this->query("ALTER TABLE \"$table\" SET TABLESPACE {$advancedOptions['tablespace']['name']};");
|
//Pick up the altered indexes here:
|
||||||
}
|
$fieldList = $this->fieldList($table);
|
||||||
|
$fulltexts = false;
|
||||||
|
$drop_triggers = false;
|
||||||
|
$triggers = false;
|
||||||
|
if ($alteredIndexes) {
|
||||||
|
foreach ($alteredIndexes as $indexName=>$indexSpec) {
|
||||||
|
$indexSpec = $this->parseIndexSpec($indexName, $indexSpec);
|
||||||
|
$indexNamePG = $this->buildPostgresIndexName($table, $indexName);
|
||||||
|
|
||||||
//DB ABSTRACTION: we need to change the constraints to be a separate 'add' command,
|
if ($indexSpec['type']=='fulltext') {
|
||||||
//see http://www.postgresql.org/docs/8.1/static/sql-altertable.html
|
//For full text indexes, we need to drop the trigger, drop the index, AND drop the column
|
||||||
$alterIndexList = array();
|
|
||||||
//Pick up the altered indexes here:
|
|
||||||
$fieldList = $this->fieldList($table);
|
|
||||||
$fulltexts = false;
|
|
||||||
$drop_triggers = false;
|
|
||||||
$triggers = false;
|
|
||||||
if($alteredIndexes) foreach($alteredIndexes as $indexName=>$indexSpec) {
|
|
||||||
|
|
||||||
$indexSpec = $this->parseIndexSpec($indexName, $indexSpec);
|
//Go and get the tsearch details:
|
||||||
$indexNamePG = $this->buildPostgresIndexName($table, $indexName);
|
$ts_details = $this->fulltext($indexSpec, $table, $indexName);
|
||||||
|
|
||||||
if($indexSpec['type']=='fulltext') {
|
//Drop this column if it already exists:
|
||||||
//For full text indexes, we need to drop the trigger, drop the index, AND drop the column
|
|
||||||
|
|
||||||
//Go and get the tsearch details:
|
//No IF EXISTS option is available for Postgres <9.0
|
||||||
$ts_details = $this->fulltext($indexSpec, $table, $indexName);
|
if (array_key_exists($ts_details['ts_name'], $fieldList)) {
|
||||||
|
$fulltexts.="ALTER TABLE \"{$table}\" DROP COLUMN \"{$ts_details['ts_name']}\";";
|
||||||
|
}
|
||||||
|
|
||||||
//Drop this column if it already exists:
|
// We'll execute these later:
|
||||||
|
$triggerNamePG = $this->buildPostgresTriggerName($table, $indexName);
|
||||||
|
$drop_triggers.= "DROP TRIGGER IF EXISTS \"$triggerNamePG\" ON \"$table\";";
|
||||||
|
$fulltexts .= "ALTER TABLE \"{$table}\" ADD COLUMN {$ts_details['fulltexts']};";
|
||||||
|
$triggers .= $ts_details['triggers'];
|
||||||
|
}
|
||||||
|
|
||||||
//No IF EXISTS option is available for Postgres <9.0
|
// Create index action (including fulltext)
|
||||||
if(array_key_exists($ts_details['ts_name'], $fieldList)){
|
$alterIndexList[] = "DROP INDEX IF EXISTS \"$indexNamePG\";";
|
||||||
$fulltexts.="ALTER TABLE \"{$table}\" DROP COLUMN \"{$ts_details['ts_name']}\";";
|
$createIndex = $this->getIndexSqlDefinition($table, $indexName, $indexSpec);
|
||||||
}
|
if ($createIndex!==false) {
|
||||||
|
$alterIndexList[] = $createIndex;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// We'll execute these later:
|
//Add the new indexes:
|
||||||
$triggerNamePG = $this->buildPostgresTriggerName($table, $indexName);
|
if ($newIndexes) {
|
||||||
$drop_triggers.= "DROP TRIGGER IF EXISTS \"$triggerNamePG\" ON \"$table\";";
|
foreach ($newIndexes as $indexName => $indexSpec) {
|
||||||
$fulltexts .= "ALTER TABLE \"{$table}\" ADD COLUMN {$ts_details['fulltexts']};";
|
$indexSpec = $this->parseIndexSpec($indexName, $indexSpec);
|
||||||
$triggers .= $ts_details['triggers'];
|
$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') {
|
||||||
|
$ts_details=$this->fulltext($indexSpec, $table, $indexName);
|
||||||
|
if (!isset($fieldList[$ts_details['ts_name']])) {
|
||||||
|
$fulltexts.="ALTER TABLE \"{$table}\" ADD COLUMN {$ts_details['fulltexts']};";
|
||||||
|
$triggers.=$ts_details['triggers'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Create index action (including fulltext)
|
//Check that this index doesn't already exist:
|
||||||
$alterIndexList[] = "DROP INDEX IF EXISTS \"$indexNamePG\";";
|
$indexes=$this->indexList($table);
|
||||||
$createIndex = $this->getIndexSqlDefinition($table, $indexName, $indexSpec);
|
if (isset($indexes[$indexName])) {
|
||||||
if($createIndex!==false) $alterIndexList[] = $createIndex;
|
$alterIndexList[] = "DROP INDEX IF EXISTS \"$indexNamePG\";";
|
||||||
}
|
}
|
||||||
|
|
||||||
//Add the new indexes:
|
$createIndex=$this->getIndexSqlDefinition($table, $indexName, $indexSpec);
|
||||||
if($newIndexes) foreach($newIndexes as $indexName => $indexSpec){
|
if ($createIndex!==false) {
|
||||||
|
$alterIndexList[] = $createIndex;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
$indexSpec = $this->parseIndexSpec($indexName, $indexSpec);
|
if ($alterList) {
|
||||||
$indexNamePG = $this->buildPostgresIndexName($table, $indexName);
|
$alterations = implode(",\n", $alterList);
|
||||||
//If we have a fulltext search request, then we need to create a special column
|
$this->query("ALTER TABLE \"$table\" " . $alterations);
|
||||||
//for GiST searches
|
}
|
||||||
//Pick up the new indexes here:
|
|
||||||
if($indexSpec['type']=='fulltext') {
|
|
||||||
$ts_details=$this->fulltext($indexSpec, $table, $indexName);
|
|
||||||
if(!isset($fieldList[$ts_details['ts_name']])){
|
|
||||||
$fulltexts.="ALTER TABLE \"{$table}\" ADD COLUMN {$ts_details['fulltexts']};";
|
|
||||||
$triggers.=$ts_details['triggers'];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//Check that this index doesn't already exist:
|
//Do we need to create a tablespace for this item?
|
||||||
$indexes=$this->indexList($table);
|
if ($advancedOptions && isset($advancedOptions['extensions']['tablespace'])) {
|
||||||
if(isset($indexes[$indexName])){
|
$extensions=$advancedOptions['extensions'];
|
||||||
$alterIndexList[] = "DROP INDEX IF EXISTS \"$indexNamePG\";";
|
$this->createOrReplaceTablespace($extensions['tablespace']['name'], $extensions['tablespace']['location']);
|
||||||
}
|
}
|
||||||
|
|
||||||
$createIndex=$this->getIndexSqlDefinition($table, $indexName, $indexSpec);
|
if ($alteredOptions && isset($this->class) && isset($alteredOptions[$this->class])) {
|
||||||
if($createIndex!==false)
|
$this->query(sprintf("ALTER TABLE \"%s\" %s", $table, $alteredOptions[$this->class]));
|
||||||
$alterIndexList[] = $createIndex;
|
Database::alteration_message(
|
||||||
}
|
sprintf("Table %s options changed: %s", $table, $alteredOptions[$this->class]),
|
||||||
|
"changed"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if($alterList) {
|
//Create any fulltext columns and triggers here:
|
||||||
$alterations = implode(",\n", $alterList);
|
if ($fulltexts) {
|
||||||
$this->query("ALTER TABLE \"$table\" " . $alterations);
|
$this->query($fulltexts);
|
||||||
}
|
}
|
||||||
|
if ($drop_triggers) {
|
||||||
|
$this->query($drop_triggers);
|
||||||
|
}
|
||||||
|
|
||||||
//Do we need to create a tablespace for this item?
|
if ($triggers) {
|
||||||
if($advancedOptions && isset($advancedOptions['extensions']['tablespace'])){
|
$this->query($triggers);
|
||||||
$extensions=$advancedOptions['extensions'];
|
|
||||||
$this->createOrReplaceTablespace($extensions['tablespace']['name'], $extensions['tablespace']['location']);
|
|
||||||
}
|
|
||||||
|
|
||||||
if($alteredOptions && isset($this->class) && isset($alteredOptions[$this->class])) {
|
$triggerbits=explode(';', $triggers);
|
||||||
$this->query(sprintf("ALTER TABLE \"%s\" %s", $table, $alteredOptions[$this->class]));
|
foreach ($triggerbits as $trigger) {
|
||||||
Database::alteration_message(
|
$trigger_fields=$this->triggerFieldsFromTrigger($trigger);
|
||||||
sprintf("Table %s options changed: %s", $table, $alteredOptions[$this->class]),
|
|
||||||
"changed"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
//Create any fulltext columns and triggers here:
|
if ($trigger_fields) {
|
||||||
if($fulltexts) $this->query($fulltexts);
|
//We need to run a simple query to force the database to update the triggered columns
|
||||||
if($drop_triggers) $this->query($drop_triggers);
|
$this->query("UPDATE \"{$table}\" SET \"{$trigger_fields[0]}\"=\"$trigger_fields[0]\";");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if($triggers) {
|
foreach ($alterIndexList as $alteration) {
|
||||||
$this->query($triggers);
|
$this->query($alteration);
|
||||||
|
}
|
||||||
|
|
||||||
$triggerbits=explode(';', $triggers);
|
//If we have a partitioning requirement, we do that here:
|
||||||
foreach($triggerbits as $trigger){
|
if ($advancedOptions && isset($advancedOptions['partitions'])) {
|
||||||
$trigger_fields=$this->triggerFieldsFromTrigger($trigger);
|
$this->createOrReplacePartition($table, $advancedOptions['partitions']);
|
||||||
|
}
|
||||||
|
|
||||||
if($trigger_fields){
|
//Lastly, clustering goes here:
|
||||||
//We need to run a simple query to force the database to update the triggered columns
|
if ($advancedOptions && isset($advancedOptions['cluster'])) {
|
||||||
$this->query("UPDATE \"{$table}\" SET \"{$trigger_fields[0]}\"=\"$trigger_fields[0]\";");
|
$clusterIndex = $this->buildPostgresIndexName($table, $advancedOptions['cluster']);
|
||||||
}
|
$this->query("CLUSTER \"$table\" USING \"$clusterIndex\";");
|
||||||
}
|
} else {
|
||||||
}
|
//Check that clustering is not on this table, and if it is, remove it:
|
||||||
|
|
||||||
foreach($alterIndexList as $alteration) $this->query($alteration);
|
//This is really annoying. We need the oid of this table:
|
||||||
|
$stats = $this->preparedQuery(
|
||||||
|
"SELECT relid FROM pg_stat_user_tables WHERE relname = ?;",
|
||||||
|
array($table)
|
||||||
|
)->first();
|
||||||
|
$oid=$stats['relid'];
|
||||||
|
|
||||||
//If we have a partitioning requirement, we do that here:
|
//Now we can run a long query to get the clustered status:
|
||||||
if($advancedOptions && isset($advancedOptions['partitions'])){
|
//If anyone knows a better way to get the clustered status, then feel free to replace this!
|
||||||
$this->createOrReplacePartition($table, $advancedOptions['partitions']);
|
$clustered = $this->preparedQuery("
|
||||||
}
|
|
||||||
|
|
||||||
//Lastly, clustering goes here:
|
|
||||||
if ($advancedOptions && isset($advancedOptions['cluster'])) {
|
|
||||||
$clusterIndex = $this->buildPostgresIndexName($table, $advancedOptions['cluster']);
|
|
||||||
$this->query("CLUSTER \"$table\" USING \"$clusterIndex\";");
|
|
||||||
} else {
|
|
||||||
//Check that clustering is not on this table, and if it is, remove it:
|
|
||||||
|
|
||||||
//This is really annoying. We need the oid of this table:
|
|
||||||
$stats = $this->preparedQuery(
|
|
||||||
"SELECT relid FROM pg_stat_user_tables WHERE relname = ?;",
|
|
||||||
array($table)
|
|
||||||
)->first();
|
|
||||||
$oid=$stats['relid'];
|
|
||||||
|
|
||||||
//Now we can run a long query to get the clustered status:
|
|
||||||
//If anyone knows a better way to get the clustered status, then feel free to replace this!
|
|
||||||
$clustered = $this->preparedQuery("
|
|
||||||
SELECT c2.relname, i.indisclustered
|
SELECT c2.relname, i.indisclustered
|
||||||
FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i
|
FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i
|
||||||
WHERE c.oid = ? AND c.oid = i.indrelid AND i.indexrelid = c2.oid AND indisclustered='t';",
|
WHERE c.oid = ? AND c.oid = i.indrelid AND i.indexrelid = c2.oid AND indisclustered='t';",
|
||||||
array($oid)
|
array($oid)
|
||||||
)->first();
|
)->first();
|
||||||
|
|
||||||
if($clustered) {
|
if ($clustered) {
|
||||||
$this->query("ALTER TABLE \"$table\" SET WITHOUT CLUSTER;");
|
$this->query("ALTER TABLE \"$table\" SET WITHOUT CLUSTER;");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Creates an ALTER expression for a column in PostgreSQL
|
* Creates an ALTER expression for a column in PostgreSQL
|
||||||
*
|
*
|
||||||
* @param $tableName Name of the table to be altered
|
* @param $tableName Name of the table to be altered
|
||||||
* @param $colName Name of the column to be altered
|
* @param $colName Name of the column to be altered
|
||||||
* @param $colSpec String which contains conditions for a column
|
* @param $colSpec String which contains conditions for a column
|
||||||
* @return string
|
* @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
|
// First, we split the column specifications into parts
|
||||||
// on second thoughts, why is an auto_increment field being passed through?
|
// 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?
|
||||||
|
|
||||||
$pattern = '/^([\w()]+)\s?((?:not\s)?null)?\s?(default\s[\w\']+)?\s?(check\s[\w()\'",\s]+)?$/i';
|
$pattern = '/^([\w()]+)\s?((?:not\s)?null)?\s?(default\s[\w\']+)?\s?(check\s[\w()\'",\s]+)?$/i';
|
||||||
preg_match($pattern, $colSpec, $matches);
|
preg_match($pattern, $colSpec, $matches);
|
||||||
|
|
||||||
if(sizeof($matches)==0) return '';
|
if (sizeof($matches)==0) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
if($matches[1]=='serial8') return '';
|
if ($matches[1]=='serial8') {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
if(isset($matches[1])) {
|
if (isset($matches[1])) {
|
||||||
$alterCol = "ALTER COLUMN \"$colName\" TYPE $matches[1]\n";
|
$alterCol = "ALTER COLUMN \"$colName\" TYPE $matches[1]\n";
|
||||||
|
|
||||||
// SET null / not null
|
// SET null / not null
|
||||||
if(!empty($matches[2])) {
|
if (!empty($matches[2])) {
|
||||||
$alterCol .= ",\nALTER COLUMN \"$colName\" SET $matches[2]";
|
$alterCol .= ",\nALTER COLUMN \"$colName\" SET $matches[2]";
|
||||||
}
|
}
|
||||||
|
|
||||||
// SET default (we drop it first, for reasons of precaution)
|
// SET default (we drop it first, for reasons of precaution)
|
||||||
if(!empty($matches[3])) {
|
if (!empty($matches[3])) {
|
||||||
$alterCol .= ",\nALTER COLUMN \"$colName\" DROP DEFAULT";
|
$alterCol .= ",\nALTER COLUMN \"$colName\" DROP DEFAULT";
|
||||||
$alterCol .= ",\nALTER COLUMN \"$colName\" SET $matches[3]";
|
$alterCol .= ",\nALTER COLUMN \"$colName\" SET $matches[3]";
|
||||||
}
|
}
|
||||||
|
|
||||||
// SET check constraint (The constraint HAS to be dropped)
|
// SET check constraint (The constraint HAS to be dropped)
|
||||||
$existing_constraint=$this->query("SELECT conname FROM pg_constraint WHERE conname='{$tableName}_{$colName}_check';")->value();
|
$existing_constraint=$this->query("SELECT conname FROM pg_constraint WHERE conname='{$tableName}_{$colName}_check';")->value();
|
||||||
if(isset($matches[4])) {
|
if (isset($matches[4])) {
|
||||||
//Take this new constraint and see what's outstanding from the target table:
|
//Take this new constraint and see what's outstanding from the target table:
|
||||||
$constraint_bits=explode('(', $matches[4]);
|
$constraint_bits=explode('(', $matches[4]);
|
||||||
$constraint_values=trim($constraint_bits[2], ')');
|
$constraint_values=trim($constraint_bits[2], ')');
|
||||||
$constraint_values_bits=explode(',', $constraint_values);
|
$constraint_values_bits=explode(',', $constraint_values);
|
||||||
$default=trim($constraint_values_bits[0], " '");
|
$default=trim($constraint_values_bits[0], " '");
|
||||||
|
|
||||||
//Now go and convert anything that's not in this list to 'Page'
|
//Now go and convert anything that's not in this list to 'Page'
|
||||||
//We have to run this as a query, not as part of the alteration queries due to the way they are constructed.
|
//We have to run this as a query, not as part of the alteration queries due to the way they are constructed.
|
||||||
$updateConstraint='';
|
$updateConstraint='';
|
||||||
$updateConstraint.="UPDATE \"{$tableName}\" SET \"$colName\"='$default' WHERE \"$colName\" NOT IN ($constraint_values);";
|
$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);";
|
$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);";
|
$updateConstraint.="UPDATE \"{$tableName}_versions\" SET \"$colName\"='$default' WHERE \"$colName\" NOT IN ($constraint_values);";
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->query($updateConstraint);
|
$this->query($updateConstraint);
|
||||||
}
|
}
|
||||||
|
|
||||||
//First, delete any existing constraint on this column, even if it's no longer an enum
|
//First, delete any existing constraint on this column, even if it's no longer an enum
|
||||||
if($existing_constraint) {
|
if ($existing_constraint) {
|
||||||
$alterCol .= ",\nDROP CONSTRAINT \"{$tableName}_{$colName}_check\"";
|
$alterCol .= ",\nDROP CONSTRAINT \"{$tableName}_{$colName}_check\"";
|
||||||
}
|
}
|
||||||
|
|
||||||
//Now create the constraint (if we've asked for one)
|
//Now create the constraint (if we've asked for one)
|
||||||
if(!empty($matches[4])) {
|
if (!empty($matches[4])) {
|
||||||
$alterCol .= ",\nADD CONSTRAINT \"{$tableName}_{$colName}_check\" $matches[4]";
|
$alterCol .= ",\nADD CONSTRAINT \"{$tableName}_{$colName}_check\" $matches[4]";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return isset($alterCol) ? $alterCol : '';
|
return isset($alterCol) ? $alterCol : '';
|
||||||
}
|
}
|
||||||
|
|
||||||
public function renameTable($oldTableName, $newTableName) {
|
public function renameTable($oldTableName, $newTableName)
|
||||||
$this->query("ALTER TABLE \"$oldTableName\" RENAME TO \"$newTableName\"");
|
{
|
||||||
unset(self::$cached_fieldlists[$oldTableName]);
|
$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\"");
|
$this->query("VACUUM FULL ANALYZE \"$tableName\"");
|
||||||
return true;
|
$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");
|
{
|
||||||
}
|
$this->query("ALTER TABLE \"$table\" ADD \"$field\" $spec");
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Change the database type of the given field.
|
* Change the database type of the given field.
|
||||||
*
|
*
|
||||||
* @param string $tableName The name of the tbale the field is in.
|
* @param string $tableName The name of the tbale the field is in.
|
||||||
* @param string $fieldName The name of the field to change.
|
* @param string $fieldName The name of the field to change.
|
||||||
* @param string $fieldSpec The new field specification
|
* @param string $fieldSpec The new field specification
|
||||||
*/
|
*/
|
||||||
public function alterField($tableName, $fieldName, $fieldSpec) {
|
public function alterField($tableName, $fieldName, $fieldSpec)
|
||||||
$this->query("ALTER TABLE \"$tableName\" CHANGE \"$fieldName\" \"$fieldName\" $fieldSpec");
|
{
|
||||||
}
|
$this->query("ALTER TABLE \"$tableName\" CHANGE \"$fieldName\" \"$fieldName\" $fieldSpec");
|
||||||
|
}
|
||||||
|
|
||||||
public function renameField($tableName, $oldName, $newName) {
|
public function renameField($tableName, $oldName, $newName)
|
||||||
$fieldList = $this->fieldList($tableName);
|
{
|
||||||
if(array_key_exists($oldName, $fieldList)) {
|
$fieldList = $this->fieldList($tableName);
|
||||||
$this->query("ALTER TABLE \"$tableName\" RENAME COLUMN \"$oldName\" TO \"$newName\"");
|
if (array_key_exists($oldName, $fieldList)) {
|
||||||
|
$this->query("ALTER TABLE \"$tableName\" RENAME COLUMN \"$oldName\" TO \"$newName\"");
|
||||||
|
|
||||||
//Remove this from the cached list:
|
//Remove this from the cached list:
|
||||||
unset(self::$cached_fieldlists[$tableName]);
|
unset(self::$cached_fieldlists[$tableName]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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....
|
//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....
|
||||||
|
|
||||||
//if(!isset(self::$cached_fieldlists[$table])){
|
//if(!isset(self::$cached_fieldlists[$table])){
|
||||||
$fields = $this->preparedQuery("
|
$fields = $this->preparedQuery("
|
||||||
SELECT ordinal_position, column_name, data_type, column_default,
|
SELECT ordinal_position, column_name, data_type, column_default,
|
||||||
is_nullable, character_maximum_length, numeric_precision, numeric_scale
|
is_nullable, character_maximum_length, numeric_precision, numeric_scale
|
||||||
FROM information_schema.columns WHERE table_name = ? and table_schema = ?
|
FROM information_schema.columns WHERE table_name = ? and table_schema = ?
|
||||||
ORDER BY ordinal_position;",
|
ORDER BY ordinal_position;",
|
||||||
array($table, $this->database->currentSchema())
|
array($table, $this->database->currentSchema())
|
||||||
);
|
);
|
||||||
|
|
||||||
$output = array();
|
$output = array();
|
||||||
if($fields) foreach($fields as $field) {
|
if ($fields) {
|
||||||
|
foreach ($fields as $field) {
|
||||||
|
switch ($field['data_type']) {
|
||||||
|
case 'character varying':
|
||||||
|
//Check to see if there's a constraint attached to this column:
|
||||||
|
//$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) {
|
||||||
|
//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[]))
|
||||||
|
//CHECK ("ClassName"::text = 'PageComment'::text)
|
||||||
|
|
||||||
switch($field['data_type']){
|
//TODO: replace all this with a regular expression!
|
||||||
case 'character varying':
|
$value=$constraint['pg_get_constraintdef'];
|
||||||
//Check to see if there's a constraint attached to this column:
|
$value=substr($value, strpos($value, '='));
|
||||||
//$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();
|
$value=str_replace("''", "'", $value);
|
||||||
$constraint = $this->constraintExists($table . '_' . $field['column_name'] . '_check');
|
|
||||||
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[]))
|
|
||||||
//CHECK ("ClassName"::text = 'PageComment'::text)
|
|
||||||
|
|
||||||
//TODO: replace all this with a regular expression!
|
$in_value=false;
|
||||||
$value=$constraint['pg_get_constraintdef'];
|
$constraints=array();
|
||||||
$value=substr($value, strpos($value,'='));
|
$current_value='';
|
||||||
$value=str_replace("''", "'", $value);
|
for ($i=0; $i<strlen($value); $i++) {
|
||||||
|
$char=substr($value, $i, 1);
|
||||||
|
if ($in_value) {
|
||||||
|
$current_value.=$char;
|
||||||
|
}
|
||||||
|
|
||||||
$in_value=false;
|
if ($char=="'") {
|
||||||
$constraints=Array();
|
if (!$in_value) {
|
||||||
$current_value='';
|
$in_value=true;
|
||||||
for($i=0; $i<strlen($value); $i++){
|
} else {
|
||||||
$char=substr($value, $i, 1);
|
$in_value=false;
|
||||||
if($in_value)
|
$constraints[]=substr($current_value, 0, -1);
|
||||||
$current_value.=$char;
|
$current_value='';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if($char=="'"){
|
if (sizeof($constraints)>0) {
|
||||||
if(!$in_value)
|
//Get the default:
|
||||||
$in_value=true;
|
$default=trim(substr($field['column_default'], 0, strpos($field['column_default'], '::')), "'");
|
||||||
else {
|
$output[$field['column_name']]=$this->enum(array('default'=>$default, 'name'=>$field['column_name'], 'enums'=>$constraints));
|
||||||
$in_value=false;
|
}
|
||||||
$constraints[]=substr($current_value, 0, -1);
|
} else {
|
||||||
$current_value='';
|
$output[$field['column_name']]='varchar(' . $field['character_maximum_length'] . ')';
|
||||||
}
|
}
|
||||||
}
|
break;
|
||||||
}
|
|
||||||
|
|
||||||
if(sizeof($constraints)>0){
|
case 'numeric':
|
||||||
//Get the default:
|
$output[$field['column_name']]='decimal(' . $field['numeric_precision'] . ',' . $field['numeric_scale'] . ') default ' . (int)$field['column_default'];
|
||||||
$default=trim(substr($field['column_default'], 0, strpos($field['column_default'], '::')), "'");
|
break;
|
||||||
$output[$field['column_name']]=$this->enum(Array('default'=>$default, 'name'=>$field['column_name'], 'enums'=>$constraints));
|
|
||||||
}
|
|
||||||
} else{
|
|
||||||
$output[$field['column_name']]='varchar(' . $field['character_maximum_length'] . ')';
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'numeric':
|
case 'integer':
|
||||||
$output[$field['column_name']]='decimal(' . $field['numeric_precision'] . ',' . $field['numeric_scale'] . ') default ' . (int)$field['column_default'];
|
$output[$field['column_name']]='integer default ' . (int)$field['column_default'];
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'integer':
|
case 'timestamp without time zone':
|
||||||
$output[$field['column_name']]='integer default ' . (int)$field['column_default'];
|
$output[$field['column_name']]='timestamp';
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'timestamp without time zone':
|
case 'smallint':
|
||||||
$output[$field['column_name']]='timestamp';
|
$output[$field['column_name']]='smallint default ' . (int)$field['column_default'];
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'smallint':
|
case 'time without time zone':
|
||||||
$output[$field['column_name']]='smallint default ' . (int)$field['column_default'];
|
$output[$field['column_name']]='time';
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'time without time zone':
|
case 'double precision':
|
||||||
$output[$field['column_name']]='time';
|
$output[$field['column_name']]='float';
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'double precision':
|
default:
|
||||||
$output[$field['column_name']]='float';
|
$output[$field['column_name']] = $field;
|
||||||
break;
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
default:
|
// self::$cached_fieldlists[$table]=$output;
|
||||||
$output[$field['column_name']] = $field;
|
//}
|
||||||
}
|
|
||||||
|
|
||||||
}
|
//return self::$cached_fieldlists[$table];
|
||||||
|
|
||||||
// self::$cached_fieldlists[$table]=$output;
|
return $output;
|
||||||
//}
|
}
|
||||||
|
|
||||||
//return self::$cached_fieldlists[$table];
|
public function clearCachedFieldlist($tableName=false)
|
||||||
|
{
|
||||||
|
if ($tableName) {
|
||||||
|
unset(self::$cached_fieldlists[$tableName]);
|
||||||
|
} else {
|
||||||
|
self::$cached_fieldlists=array();
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
return $output;
|
/**
|
||||||
}
|
* Create an index on a table.
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table.
|
||||||
|
* @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)
|
||||||
|
{
|
||||||
|
$createIndex = $this->getIndexSqlDefinition($tableName, $indexName, $indexSpec);
|
||||||
|
if ($createIndex !== false) {
|
||||||
|
$this->query($createIndex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function clearCachedFieldlist($tableName=false){
|
/*
|
||||||
if($tableName) unset(self::$cached_fieldlists[$tableName]);
|
* @todo - factor out? Is DBSchemaManager::convertIndexSpec sufficient?
|
||||||
else self::$cached_fieldlists=array();
|
public function convertIndexSpec($indexSpec, $asDbValue=false, $table=''){
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
if(!$asDbValue){
|
||||||
* Create an index on a table.
|
if(is_array($indexSpec)){
|
||||||
*
|
//Here we create a db-specific version of whatever index we need to create.
|
||||||
* @param string $tableName The name of the table.
|
switch($indexSpec['type']){
|
||||||
* @param string $indexName The name of the index.
|
case 'fulltext':
|
||||||
* @param string $indexSpec The specification of the index, see Database::requireIndex() for more details.
|
$indexSpec='fulltext (' . $indexSpec['value'] . ')';
|
||||||
*/
|
break;
|
||||||
public function createIndex($tableName, $indexName, $indexSpec) {
|
case 'unique':
|
||||||
$createIndex = $this->getIndexSqlDefinition($tableName, $indexName, $indexSpec);
|
$indexSpec='unique (' . $indexSpec['value'] . ')';
|
||||||
if($createIndex !== false) $this->query($createIndex);
|
break;
|
||||||
}
|
case 'hash':
|
||||||
|
$indexSpec='using hash (' . $indexSpec['value'] . ')';
|
||||||
|
break;
|
||||||
|
case 'index':
|
||||||
|
//The default index is 'btree', which we'll use by default (below):
|
||||||
|
default:
|
||||||
|
$indexSpec='using btree (' . $indexSpec['value'] . ')';
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$indexSpec = $this->buildPostgresIndexName($table, $indexSpec);
|
||||||
|
}
|
||||||
|
return $indexSpec;
|
||||||
|
}*/
|
||||||
|
|
||||||
/*
|
protected function getIndexSqlDefinition($tableName, $indexName, $indexSpec, $asDbValue=false)
|
||||||
* @todo - factor out? Is DBSchemaManager::convertIndexSpec sufficient?
|
{
|
||||||
public function convertIndexSpec($indexSpec, $asDbValue=false, $table=''){
|
|
||||||
|
|
||||||
if(!$asDbValue){
|
//TODO: create table partition support
|
||||||
if(is_array($indexSpec)){
|
//TODO: create clustering options
|
||||||
//Here we create a db-specific version of whatever index we need to create.
|
|
||||||
switch($indexSpec['type']){
|
|
||||||
case 'fulltext':
|
|
||||||
$indexSpec='fulltext (' . $indexSpec['value'] . ')';
|
|
||||||
break;
|
|
||||||
case 'unique':
|
|
||||||
$indexSpec='unique (' . $indexSpec['value'] . ')';
|
|
||||||
break;
|
|
||||||
case 'hash':
|
|
||||||
$indexSpec='using hash (' . $indexSpec['value'] . ')';
|
|
||||||
break;
|
|
||||||
case 'index':
|
|
||||||
//The default index is 'btree', which we'll use by default (below):
|
|
||||||
default:
|
|
||||||
$indexSpec='using btree (' . $indexSpec['value'] . ')';
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
$indexSpec = $this->buildPostgresIndexName($table, $indexSpec);
|
|
||||||
}
|
|
||||||
return $indexSpec;
|
|
||||||
}*/
|
|
||||||
|
|
||||||
protected function getIndexSqlDefinition($tableName, $indexName, $indexSpec, $asDbValue=false) {
|
//NOTE: it is possible for *_renamed tables to have indexes whose names are not updates
|
||||||
|
//Therefore, we now check for the existance of indexes before we create them.
|
||||||
|
//This is techically a bug, since new tables will not be indexed.
|
||||||
|
|
||||||
//TODO: create table partition support
|
// If requesting the definition rather than the DDL
|
||||||
//TODO: create clustering options
|
if ($asDbValue) {
|
||||||
|
$indexName=trim($indexName, '()');
|
||||||
|
return $indexName;
|
||||||
|
}
|
||||||
|
|
||||||
//NOTE: it is possible for *_renamed tables to have indexes whose names are not updates
|
// Determine index name
|
||||||
//Therefore, we now check for the existance of indexes before we create them.
|
$tableCol = $this->buildPostgresIndexName($tableName, $indexName);
|
||||||
//This is techically a bug, since new tables will not be indexed.
|
|
||||||
|
|
||||||
// If requesting the definition rather than the DDL
|
// Consolidate/Cleanup spec into array format
|
||||||
if($asDbValue) {
|
$indexSpec = $this->parseIndexSpec($indexName, $indexSpec);
|
||||||
$indexName=trim($indexName, '()');
|
|
||||||
return $indexName;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Determine index name
|
//Misc options first:
|
||||||
$tableCol = $this->buildPostgresIndexName($tableName, $indexName);
|
$fillfactor = $where = '';
|
||||||
|
if (isset($indexSpec['fillfactor'])) {
|
||||||
|
$fillfactor = 'WITH (FILLFACTOR = ' . $indexSpec['fillfactor'] . ')';
|
||||||
|
}
|
||||||
|
if (isset($indexSpec['where'])) {
|
||||||
|
$where = 'WHERE ' . $indexSpec['where'];
|
||||||
|
}
|
||||||
|
|
||||||
// Consolidate/Cleanup spec into array format
|
//create a type-specific index
|
||||||
$indexSpec = $this->parseIndexSpec($indexName, $indexSpec);
|
// NOTE: hash should be removed. This is only here to demonstrate how other indexes can be made
|
||||||
|
// NOTE: Quote the index name to preserve case sensitivity
|
||||||
|
switch ($indexSpec['type']) {
|
||||||
|
case 'fulltext':
|
||||||
|
// @see fulltext() for the definition of the trigger that ts_$IndexName uses for fulltext searching
|
||||||
|
$clusterMethod = PostgreSQLDatabase::default_fts_cluster_method();
|
||||||
|
$spec = "create index \"$tableCol\" ON \"$tableName\" USING $clusterMethod(\"ts_" . $indexName . "\") $fillfactor $where";
|
||||||
|
break;
|
||||||
|
|
||||||
//Misc options first:
|
case 'unique':
|
||||||
$fillfactor = $where = '';
|
$spec = "create unique index \"$tableCol\" ON \"$tableName\" (" . $indexSpec['value'] . ") $fillfactor $where";
|
||||||
if (isset($indexSpec['fillfactor'])) {
|
break;
|
||||||
$fillfactor = 'WITH (FILLFACTOR = ' . $indexSpec['fillfactor'] . ')';
|
|
||||||
}
|
|
||||||
if (isset($indexSpec['where'])) {
|
|
||||||
$where = 'WHERE ' . $indexSpec['where'];
|
|
||||||
}
|
|
||||||
|
|
||||||
//create a type-specific index
|
case 'btree':
|
||||||
// NOTE: hash should be removed. This is only here to demonstrate how other indexes can be made
|
$spec = "create index \"$tableCol\" ON \"$tableName\" USING btree (" . $indexSpec['value'] . ") $fillfactor $where";
|
||||||
// NOTE: Quote the index name to preserve case sensitivity
|
break;
|
||||||
switch ($indexSpec['type']) {
|
|
||||||
case 'fulltext':
|
|
||||||
// @see fulltext() for the definition of the trigger that ts_$IndexName uses for fulltext searching
|
|
||||||
$clusterMethod = PostgreSQLDatabase::default_fts_cluster_method();
|
|
||||||
$spec = "create index \"$tableCol\" ON \"$tableName\" USING $clusterMethod(\"ts_" . $indexName . "\") $fillfactor $where";
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'unique':
|
case 'hash':
|
||||||
$spec = "create unique index \"$tableCol\" ON \"$tableName\" (" . $indexSpec['value'] . ") $fillfactor $where";
|
//NOTE: this is not a recommended index type
|
||||||
break;
|
$spec = "create index \"$tableCol\" ON \"$tableName\" USING hash (" . $indexSpec['value'] . ") $fillfactor $where";
|
||||||
|
break;
|
||||||
|
|
||||||
case 'btree':
|
case 'index':
|
||||||
$spec = "create index \"$tableCol\" ON \"$tableName\" USING btree (" . $indexSpec['value'] . ") $fillfactor $where";
|
//'index' is the same as default, just a normal index with the default type decided by the database.
|
||||||
break;
|
default:
|
||||||
|
$spec = "create index \"$tableCol\" ON \"$tableName\" (" . $indexSpec['value'] . ") $fillfactor $where";
|
||||||
|
}
|
||||||
|
return trim($spec) . ';';
|
||||||
|
}
|
||||||
|
|
||||||
case 'hash':
|
public function alterIndex($tableName, $indexName, $indexSpec)
|
||||||
//NOTE: this is not a recommended index type
|
{
|
||||||
$spec = "create index \"$tableCol\" ON \"$tableName\" USING hash (" . $indexSpec['value'] . ") $fillfactor $where";
|
$indexSpec = trim($indexSpec);
|
||||||
break;
|
if ($indexSpec[0] != '(') {
|
||||||
|
list($indexType, $indexFields) = explode(' ', $indexSpec, 2);
|
||||||
|
} else {
|
||||||
|
$indexFields = $indexSpec;
|
||||||
|
}
|
||||||
|
|
||||||
case 'index':
|
if (!$indexType) {
|
||||||
//'index' is the same as default, just a normal index with the default type decided by the database.
|
$indexType = "index";
|
||||||
default:
|
}
|
||||||
$spec = "create index \"$tableCol\" ON \"$tableName\" (" . $indexSpec['value'] . ") $fillfactor $where";
|
|
||||||
}
|
|
||||||
return trim($spec) . ';';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function alterIndex($tableName, $indexName, $indexSpec) {
|
$this->query("DROP INDEX \"$indexName\"");
|
||||||
$indexSpec = trim($indexSpec);
|
$this->query("ALTER TABLE \"$tableName\" ADD $indexType \"$indexName\" $indexFields");
|
||||||
if($indexSpec[0] != '(') {
|
}
|
||||||
list($indexType, $indexFields) = explode(' ',$indexSpec,2);
|
|
||||||
} else {
|
|
||||||
$indexFields = $indexSpec;
|
|
||||||
}
|
|
||||||
|
|
||||||
if(!$indexType) {
|
/**
|
||||||
$indexType = "index";
|
* Given a trigger name attempt to determine the columns upon which it acts
|
||||||
}
|
*
|
||||||
|
* @param string $triggerName Postgres trigger name
|
||||||
|
* @return array List of columns
|
||||||
|
*/
|
||||||
|
protected function extractTriggerColumns($triggerName)
|
||||||
|
{
|
||||||
|
$trigger = $this->preparedQuery(
|
||||||
|
"SELECT tgargs FROM pg_catalog.pg_trigger WHERE tgname = ?",
|
||||||
|
array($triggerName)
|
||||||
|
)->first();
|
||||||
|
|
||||||
$this->query("DROP INDEX \"$indexName\"");
|
// Option 1: output as a string
|
||||||
$this->query("ALTER TABLE \"$tableName\" ADD $indexType \"$indexName\" $indexFields");
|
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)
|
||||||
* Given a trigger name attempt to determine the columns upon which it acts
|
} else {
|
||||||
*
|
$bytes = str_split($trigger['tgargs'], 2);
|
||||||
* @param string $triggerName Postgres trigger name
|
$argList = array();
|
||||||
* @return array List of columns
|
$nextArg = "";
|
||||||
*/
|
foreach ($bytes as $byte) {
|
||||||
protected function extractTriggerColumns($triggerName) {
|
if ($byte == "00") {
|
||||||
$trigger = $this->preparedQuery(
|
$argList[] = $nextArg;
|
||||||
"SELECT tgargs FROM pg_catalog.pg_trigger WHERE tgname = ?",
|
$nextArg = "";
|
||||||
array($triggerName)
|
} else {
|
||||||
)->first();
|
$nextArg .= chr(hexdec($byte));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Option 1: output as a string
|
// Drop first two arguments (trigger name and config name) and implode into nice list
|
||||||
if(strpos($trigger['tgargs'],'\000') !== false) {
|
return array_slice($argList, 2);
|
||||||
$argList = explode('\000', $trigger['tgargs']);
|
}
|
||||||
array_pop($argList);
|
|
||||||
|
|
||||||
// Option 2: hex-encoded (not sure why this happens, depends on PGSQL config)
|
public function indexList($table)
|
||||||
} else {
|
{
|
||||||
$bytes = str_split($trigger['tgargs'],2);
|
//Retrieve a list of indexes for the specified table
|
||||||
$argList = array();
|
$indexes = $this->preparedQuery("
|
||||||
$nextArg = "";
|
|
||||||
foreach($bytes as $byte) {
|
|
||||||
if($byte == "00") {
|
|
||||||
$argList[] = $nextArg;
|
|
||||||
$nextArg = "";
|
|
||||||
} else {
|
|
||||||
$nextArg .= chr(hexdec($byte));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Drop first two arguments (trigger name and config name) and implode into nice list
|
|
||||||
return array_slice($argList, 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function indexList($table) {
|
|
||||||
//Retrieve a list of indexes for the specified table
|
|
||||||
$indexes = $this->preparedQuery("
|
|
||||||
SELECT tablename, indexname, indexdef
|
SELECT tablename, indexname, indexdef
|
||||||
FROM pg_catalog.pg_indexes
|
FROM pg_catalog.pg_indexes
|
||||||
WHERE tablename = ? AND schemaname = ?;",
|
WHERE tablename = ? AND schemaname = ?;",
|
||||||
array($table, $this->database->currentSchema())
|
array($table, $this->database->currentSchema())
|
||||||
);
|
);
|
||||||
|
|
||||||
$indexList = array();
|
$indexList = array();
|
||||||
foreach($indexes as $index) {
|
foreach ($indexes as $index) {
|
||||||
// Key for the indexList array. Differs from other DB implementations, which is why
|
// Key for the indexList array. Differs from other DB implementations, which is why
|
||||||
// requireIndex() needed to be overridden
|
// requireIndex() needed to be overridden
|
||||||
$indexName = $index['indexname'];
|
$indexName = $index['indexname'];
|
||||||
|
|
||||||
//We don't actually need the entire created command, just a few bits:
|
//We don't actually need the entire created command, just a few bits:
|
||||||
$type = '';
|
$type = '';
|
||||||
|
|
||||||
//Check for uniques:
|
//Check for uniques:
|
||||||
if(substr($index['indexdef'], 0, 13)=='CREATE UNIQUE') {
|
if (substr($index['indexdef'], 0, 13)=='CREATE UNIQUE') {
|
||||||
$type = 'unique';
|
$type = 'unique';
|
||||||
}
|
}
|
||||||
|
|
||||||
//check for hashes, btrees etc:
|
//check for hashes, btrees etc:
|
||||||
if(strpos(strtolower($index['indexdef']), 'using hash ')!==false) {
|
if (strpos(strtolower($index['indexdef']), 'using hash ')!==false) {
|
||||||
$type = 'hash';
|
$type = 'hash';
|
||||||
}
|
}
|
||||||
|
|
||||||
//TODO: Fix me: btree is the default index type:
|
//TODO: Fix me: btree is the default index type:
|
||||||
//if(strpos(strtolower($index['indexdef']), 'using btree ')!==false)
|
//if(strpos(strtolower($index['indexdef']), 'using btree ')!==false)
|
||||||
// $prefix='using btree ';
|
// $prefix='using btree ';
|
||||||
|
|
||||||
if(strpos(strtolower($index['indexdef']), 'using rtree ')!==false) {
|
if (strpos(strtolower($index['indexdef']), 'using rtree ')!==false) {
|
||||||
$type = 'rtree';
|
$type = 'rtree';
|
||||||
}
|
}
|
||||||
|
|
||||||
// For fulltext indexes we need to extract the columns from another source
|
// For fulltext indexes we need to extract the columns from another source
|
||||||
if (stristr($index['indexdef'], 'using gin')) {
|
if (stristr($index['indexdef'], 'using gin')) {
|
||||||
$type = 'fulltext';
|
$type = 'fulltext';
|
||||||
// Extract trigger information from postgres
|
// Extract trigger information from postgres
|
||||||
$triggerName = preg_replace('/^ix_/', 'ts_', $index['indexname']);
|
$triggerName = preg_replace('/^ix_/', 'ts_', $index['indexname']);
|
||||||
$columns = $this->extractTriggerColumns($triggerName);
|
$columns = $this->extractTriggerColumns($triggerName);
|
||||||
$columnString = $this->implodeColumnList($columns);
|
$columnString = $this->implodeColumnList($columns);
|
||||||
} else {
|
} else {
|
||||||
$columnString = $this->quoteColumnSpecString($index['indexdef']);
|
$columnString = $this->quoteColumnSpecString($index['indexdef']);
|
||||||
}
|
}
|
||||||
|
|
||||||
$indexList[$indexName] = $this->parseIndexSpec($index, array(
|
$indexList[$indexName] = $this->parseIndexSpec($index, array(
|
||||||
'name' => $indexName, // Not the correct name in the PHP, as this will be a mangled postgres-unique code
|
'name' => $indexName, // Not the correct name in the PHP, as this will be a mangled postgres-unique code
|
||||||
'value' => $columnString,
|
'value' => $columnString,
|
||||||
'type' => $type
|
'type' => $type
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
return $indexList;
|
return $indexList;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
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) {
|
||||||
|
$table = reset($record);
|
||||||
|
$tables[strtolower($table)] = $table;
|
||||||
|
}
|
||||||
|
return $tables;
|
||||||
|
}
|
||||||
|
|
||||||
public function tableList() {
|
/**
|
||||||
$tables = array();
|
* Find out what the constraint information is, given a constraint name.
|
||||||
$result = $this->preparedQuery(
|
* We also cache this result, so the next time we don't need to do a
|
||||||
"SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = ? AND tablename NOT ILIKE 'pg\\\_%' AND tablename NOT ILIKE 'sql\\\_%'",
|
* query all over again.
|
||||||
array($this->database->currentSchema())
|
*
|
||||||
);
|
* @param string $constraint
|
||||||
foreach($result as $record) {
|
*/
|
||||||
$table = reset($record);
|
protected function constraintExists($constraint)
|
||||||
$tables[strtolower($table)] = $table;
|
{
|
||||||
}
|
if (!isset(self::$cached_constraints[$constraint])) {
|
||||||
return $tables;
|
$exists = $this->preparedQuery("
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Find out what the constraint information is, given a constraint name.
|
|
||||||
* We also cache this result, so the next time we don't need to do a
|
|
||||||
* query all over again.
|
|
||||||
*
|
|
||||||
* @param string $constraint
|
|
||||||
*/
|
|
||||||
protected function constraintExists($constraint){
|
|
||||||
if(!isset(self::$cached_constraints[$constraint])){
|
|
||||||
$exists = $this->preparedQuery("
|
|
||||||
SELECT conname,pg_catalog.pg_get_constraintdef(r.oid, true)
|
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;",
|
FROM pg_catalog.pg_constraint r WHERE r.contype = 'c' AND conname = ? ORDER BY 1;",
|
||||||
array($constraint)
|
array($constraint)
|
||||||
)->first();
|
)->first();
|
||||||
self::$cached_constraints[$constraint]=$exists;
|
self::$cached_constraints[$constraint]=$exists;
|
||||||
}
|
}
|
||||||
|
|
||||||
return self::$cached_constraints[$constraint];
|
return self::$cached_constraints[$constraint];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A function to return the field names and datatypes for the particular table
|
* A function to return the field names and datatypes for the particular table
|
||||||
*
|
*
|
||||||
* @param string $tableName
|
* @param string $tableName
|
||||||
* @return array List of columns an an associative array with the keys Column and DataType
|
* @return array List of columns an an associative array with the keys Column and DataType
|
||||||
*/
|
*/
|
||||||
public function tableDetails($tableName) {
|
public function tableDetails($tableName)
|
||||||
$query = "SELECT a.attname as \"Column\", pg_catalog.format_type(a.atttypid, a.atttypmod) as \"Datatype\"
|
{
|
||||||
|
$query = "SELECT a.attname as \"Column\", pg_catalog.format_type(a.atttypid, a.atttypmod) as \"Datatype\"
|
||||||
FROM pg_catalog.pg_attribute a
|
FROM pg_catalog.pg_attribute a
|
||||||
WHERE a.attnum > 0 AND NOT a.attisdropped AND a.attrelid = (
|
WHERE a.attnum > 0 AND NOT a.attisdropped AND a.attrelid = (
|
||||||
SELECT c.oid
|
SELECT c.oid
|
||||||
@ -903,585 +966,606 @@ class PostgreSQLSchemaManager extends DBSchemaManager {
|
|||||||
WHERE c.relname = ? AND pg_catalog.pg_table_is_visible(c.oid) AND n.nspname = ?
|
WHERE c.relname = ? AND pg_catalog.pg_table_is_visible(c.oid) AND n.nspname = ?
|
||||||
);";
|
);";
|
||||||
|
|
||||||
$result = $this->preparedQuery($query, $tableName, $this->database->currentSchema());
|
$result = $this->preparedQuery($query, $tableName, $this->database->currentSchema());
|
||||||
|
|
||||||
$table = array();
|
$table = array();
|
||||||
while($row = pg_fetch_assoc($result)) {
|
while ($row = pg_fetch_assoc($result)) {
|
||||||
$table[] = array(
|
$table[] = array(
|
||||||
'Column' => $row['Column'],
|
'Column' => $row['Column'],
|
||||||
'DataType' => $row['DataType']
|
'DataType' => $row['DataType']
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return $table;
|
return $table;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pass a legit trigger name and it will be dropped
|
* Pass a legit trigger name and it will be dropped
|
||||||
* This assumes that the trigger has been named in a unique fashion
|
* This assumes that the trigger has been named in a unique fashion
|
||||||
*
|
*
|
||||||
* @param string $triggerName Name of the trigger
|
* @param string $triggerName Name of the trigger
|
||||||
* @param string $tableName Name of the table
|
* @param string $tableName Name of the table
|
||||||
*/
|
*/
|
||||||
protected function dropTrigger($triggerName, $tableName){
|
protected function dropTrigger($triggerName, $tableName)
|
||||||
$exists = $this->preparedQuery("
|
{
|
||||||
|
$exists = $this->preparedQuery("
|
||||||
SELECT trigger_name
|
SELECT trigger_name
|
||||||
FROM information_schema.triggers
|
FROM information_schema.triggers
|
||||||
WHERE trigger_name = ? AND trigger_schema = ?;",
|
WHERE trigger_name = ? AND trigger_schema = ?;",
|
||||||
array($triggerName, $this->database->currentSchema())
|
array($triggerName, $this->database->currentSchema())
|
||||||
)->first();
|
)->first();
|
||||||
if($exists){
|
if ($exists) {
|
||||||
$this->query("DROP trigger IF EXISTS $triggerName ON \"$tableName\";");
|
$this->query("DROP trigger IF EXISTS $triggerName ON \"$tableName\";");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This will return the fields that the trigger is monitoring
|
* This will return the fields that the trigger is monitoring
|
||||||
*
|
*
|
||||||
* @param string $trigger Name of the trigger
|
* @param string $trigger Name of the trigger
|
||||||
* @return array
|
* @return array
|
||||||
*/
|
*/
|
||||||
protected function triggerFieldsFromTrigger($trigger) {
|
protected function triggerFieldsFromTrigger($trigger)
|
||||||
if($trigger){
|
{
|
||||||
$tsvector='tsvector_update_trigger';
|
if ($trigger) {
|
||||||
$ts_pos=strpos($trigger, $tsvector);
|
$tsvector='tsvector_update_trigger';
|
||||||
$details=trim(substr($trigger, $ts_pos+strlen($tsvector)), '();');
|
$ts_pos=strpos($trigger, $tsvector);
|
||||||
//Now split this into bits:
|
$details=trim(substr($trigger, $ts_pos+strlen($tsvector)), '();');
|
||||||
$bits=explode(',', $details);
|
//Now split this into bits:
|
||||||
|
$bits=explode(',', $details);
|
||||||
|
|
||||||
$fields=$bits[2];
|
$fields=$bits[2];
|
||||||
|
|
||||||
$field_bits=explode(',', str_replace('"', '', $fields));
|
$field_bits=explode(',', str_replace('"', '', $fields));
|
||||||
$result=array();
|
$result=array();
|
||||||
foreach($field_bits as $field_bit)
|
foreach ($field_bits as $field_bit) {
|
||||||
$result[]=trim($field_bit);
|
$result[]=trim($field_bit);
|
||||||
|
}
|
||||||
|
|
||||||
return $result;
|
return $result;
|
||||||
} else {
|
} else {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Return a boolean type-formatted string
|
* Return a boolean type-formatted string
|
||||||
*
|
*
|
||||||
* @param array $values Contains a tokenised list of info about this data type
|
* @param array $values Contains a tokenised list of info about this data type
|
||||||
* @param boolean $asDbValue
|
* @param boolean $asDbValue
|
||||||
* @return string
|
* @return string
|
||||||
*/
|
*/
|
||||||
public function boolean($values, $asDbValue=false){
|
public function boolean($values, $asDbValue=false)
|
||||||
//Annoyingly, we need to do a good ol' fashioned switch here:
|
{
|
||||||
$default = $values['default'] ? '1' : '0';
|
//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']='';
|
$values['arrayValue']='';
|
||||||
}
|
}
|
||||||
|
|
||||||
if($asDbValue) {
|
if ($asDbValue) {
|
||||||
return array('data_type'=>'smallint');
|
return array('data_type'=>'smallint');
|
||||||
}
|
}
|
||||||
|
|
||||||
if($values['arrayValue'] != '') {
|
if ($values['arrayValue'] != '') {
|
||||||
$default = '';
|
$default = '';
|
||||||
} else {
|
} else {
|
||||||
$default = ' default ' . (int)$values['default'];
|
$default = ' default ' . (int)$values['default'];
|
||||||
}
|
}
|
||||||
return "smallint{$values['arrayValue']}" . $default;
|
return "smallint{$values['arrayValue']}" . $default;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Return a date type-formatted string
|
* Return a date type-formatted string
|
||||||
*
|
*
|
||||||
* @param array $values Contains a tokenised list of info about this data type
|
* @param array $values Contains a tokenised list of info about this data type
|
||||||
* @return string
|
* @return string
|
||||||
*/
|
*/
|
||||||
public function date($values){
|
public function date($values)
|
||||||
|
{
|
||||||
|
if (!isset($values['arrayValue'])) {
|
||||||
|
$values['arrayValue']='';
|
||||||
|
}
|
||||||
|
|
||||||
if(!isset($values['arrayValue'])) {
|
return "date{$values['arrayValue']}";
|
||||||
$values['arrayValue']='';
|
}
|
||||||
}
|
|
||||||
|
|
||||||
return "date{$values['arrayValue']}";
|
/**
|
||||||
}
|
* Return a decimal type-formatted string
|
||||||
|
*
|
||||||
|
* @param array $values Contains a tokenised list of info about this data type
|
||||||
|
* @param boolean $asDbValue
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function decimal($values, $asDbValue=false)
|
||||||
|
{
|
||||||
|
if (!isset($values['arrayValue'])) {
|
||||||
|
$values['arrayValue']='';
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
// Avoid empty strings being put in the db
|
||||||
* Return a decimal type-formatted string
|
if ($values['precision'] == '') {
|
||||||
*
|
$precision = 1;
|
||||||
* @param array $values Contains a tokenised list of info about this data type
|
} else {
|
||||||
* @param boolean $asDbValue
|
$precision = $values['precision'];
|
||||||
* @return string
|
}
|
||||||
*/
|
|
||||||
public function decimal($values, $asDbValue=false){
|
|
||||||
|
|
||||||
if(!isset($values['arrayValue'])) {
|
$defaultValue = '';
|
||||||
$values['arrayValue']='';
|
if (isset($values['default']) && is_numeric($values['default'])) {
|
||||||
}
|
$defaultValue = ' default ' . $values['default'];
|
||||||
|
}
|
||||||
|
|
||||||
// Avoid empty strings being put in the db
|
if ($asDbValue) {
|
||||||
if($values['precision'] == '') {
|
return array('data_type' => 'numeric', 'precision' => $precision);
|
||||||
$precision = 1;
|
} else {
|
||||||
} else {
|
return "decimal($precision){$values['arrayValue']}$defaultValue";
|
||||||
$precision = $values['precision'];
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$defaultValue = '';
|
/**
|
||||||
if(isset($values['default']) && is_numeric($values['default'])) {
|
* Return a enum type-formatted string
|
||||||
$defaultValue = ' default ' . $values['default'];
|
*
|
||||||
}
|
* @param array $values Contains a tokenised list of info about this data type
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
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'])) {
|
||||||
|
$values['arrayValue']='';
|
||||||
|
}
|
||||||
|
|
||||||
if($asDbValue) {
|
if ($values['arrayValue']!='') {
|
||||||
return array('data_type' => 'numeric', 'precision' => $precision);
|
$default = '';
|
||||||
} else {
|
} else {
|
||||||
return "decimal($precision){$values['arrayValue']}$defaultValue";
|
$default = " default '{$values['default']}'";
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
return "varchar(255){$values['arrayValue']}" . $default . " check (\"" . $values['name'] . "\" in ('" . implode('\', \'', $values['enums']) . "'))";
|
||||||
* Return a enum type-formatted string
|
}
|
||||||
*
|
|
||||||
* @param array $values Contains a tokenised list of info about this data type
|
|
||||||
* @return string
|
|
||||||
*/
|
|
||||||
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'])) {
|
|
||||||
$values['arrayValue']='';
|
|
||||||
}
|
|
||||||
|
|
||||||
if($values['arrayValue']!='') {
|
/**
|
||||||
$default = '';
|
* Return a float type-formatted string
|
||||||
} else {
|
*
|
||||||
$default = " default '{$values['default']}'";
|
* @param array $values Contains a tokenised list of info about this data type
|
||||||
}
|
* @param boolean $asDbValue
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function float($values, $asDbValue = false)
|
||||||
|
{
|
||||||
|
if (!isset($values['arrayValue'])) {
|
||||||
|
$values['arrayValue']='';
|
||||||
|
}
|
||||||
|
|
||||||
return "varchar(255){$values['arrayValue']}" . $default . " check (\"" . $values['name'] . "\" in ('" . implode('\', \'', $values['enums']) . "'))";
|
if ($asDbValue) {
|
||||||
|
return array('data_type' => 'double precision');
|
||||||
|
} else {
|
||||||
|
return "float{$values['arrayValue']}";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
/**
|
||||||
|
* Return a float type-formatted string cause double is not supported
|
||||||
|
*
|
||||||
|
* @param array $values Contains a tokenised list of info about this data type
|
||||||
|
* @param boolean $asDbValue
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function double($values, $asDbValue=false)
|
||||||
|
{
|
||||||
|
return $this->float($values, $asDbValue);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Return a float type-formatted string
|
* Return a int type-formatted string
|
||||||
*
|
*
|
||||||
* @param array $values Contains a tokenised list of info about this data type
|
* @param array $values Contains a tokenised list of info about this data type
|
||||||
* @param boolean $asDbValue
|
* @param boolean $asDbValue
|
||||||
* @return string
|
* @return string
|
||||||
*/
|
*/
|
||||||
public function float($values, $asDbValue = false){
|
public function int($values, $asDbValue = false)
|
||||||
if(!isset($values['arrayValue'])) {
|
{
|
||||||
$values['arrayValue']='';
|
if (!isset($values['arrayValue'])) {
|
||||||
}
|
$values['arrayValue']='';
|
||||||
|
}
|
||||||
|
|
||||||
if($asDbValue) {
|
if ($asDbValue) {
|
||||||
return array('data_type' => 'double precision');
|
return array('data_type'=>'integer', 'precision'=>'32');
|
||||||
} else {
|
}
|
||||||
return "float{$values['arrayValue']}";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
if ($values['arrayValue']!='') {
|
||||||
* Return a float type-formatted string cause double is not supported
|
$default='';
|
||||||
*
|
} else {
|
||||||
* @param array $values Contains a tokenised list of info about this data type
|
$default=' default ' . (int)$values['default'];
|
||||||
* @param boolean $asDbValue
|
}
|
||||||
* @return string
|
|
||||||
*/
|
|
||||||
public function double($values, $asDbValue=false){
|
|
||||||
return $this->float($values, $asDbValue);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
return "integer{$values['arrayValue']}" . $default;
|
||||||
* Return a int type-formatted string
|
}
|
||||||
*
|
|
||||||
* @param array $values Contains a tokenised list of info about this data type
|
|
||||||
* @param boolean $asDbValue
|
|
||||||
* @return string
|
|
||||||
*/
|
|
||||||
public function int($values, $asDbValue = false){
|
|
||||||
|
|
||||||
if(!isset($values['arrayValue'])) {
|
/**
|
||||||
$values['arrayValue']='';
|
* Return a bigint type-formatted string
|
||||||
}
|
*
|
||||||
|
* @param array $values Contains a tokenised list of info about this data type
|
||||||
|
* @param boolean $asDbValue
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function bigint($values, $asDbValue = false)
|
||||||
|
{
|
||||||
|
if (!isset($values['arrayValue'])) {
|
||||||
|
$values['arrayValue']='';
|
||||||
|
}
|
||||||
|
|
||||||
if($asDbValue) {
|
if ($asDbValue) {
|
||||||
return Array('data_type'=>'integer', 'precision'=>'32');
|
return array('data_type'=>'bigint', 'precision'=>'64');
|
||||||
}
|
}
|
||||||
|
|
||||||
if($values['arrayValue']!='') {
|
if ($values['arrayValue']!='') {
|
||||||
$default='';
|
$default='';
|
||||||
} else {
|
} else {
|
||||||
$default=' default ' . (int)$values['default'];
|
$default=' default ' . (int)$values['default'];
|
||||||
}
|
}
|
||||||
|
|
||||||
return "integer{$values['arrayValue']}" . $default;
|
return "bigint{$values['arrayValue']}" . $default;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Return a bigint type-formatted string
|
* Return a datetime type-formatted string
|
||||||
*
|
* For PostgreSQL, we simply return the word 'timestamp', no other parameters are necessary
|
||||||
* @param array $values Contains a tokenised list of info about this data type
|
*
|
||||||
* @param boolean $asDbValue
|
* @param array $values Contains a tokenised list of info about this data type
|
||||||
* @return string
|
* @param boolean $asDbValue
|
||||||
*/
|
* @return string
|
||||||
public function bigint($values, $asDbValue = false){
|
*/
|
||||||
|
public function SS_Datetime($values, $asDbValue = false)
|
||||||
|
{
|
||||||
|
if (!isset($values['arrayValue'])) {
|
||||||
|
$values['arrayValue']='';
|
||||||
|
}
|
||||||
|
|
||||||
if(!isset($values['arrayValue'])) {
|
if ($asDbValue) {
|
||||||
$values['arrayValue']='';
|
return array('data_type'=>'timestamp without time zone');
|
||||||
}
|
} else {
|
||||||
|
return "timestamp{$values['arrayValue']}";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if($asDbValue) {
|
/**
|
||||||
return Array('data_type'=>'bigint', 'precision'=>'64');
|
* Return a text type-formatted string
|
||||||
}
|
*
|
||||||
|
* @param array $values Contains a tokenised list of info about this data type
|
||||||
|
* @param boolean $asDbValue
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function text($values, $asDbValue = false)
|
||||||
|
{
|
||||||
|
if (!isset($values['arrayValue'])) {
|
||||||
|
$values['arrayValue'] = '';
|
||||||
|
}
|
||||||
|
|
||||||
if($values['arrayValue']!='') {
|
if ($asDbValue) {
|
||||||
$default='';
|
return array('data_type'=>'text');
|
||||||
} else {
|
} else {
|
||||||
$default=' default ' . (int)$values['default'];
|
return "text{$values['arrayValue']}";
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return "bigint{$values['arrayValue']}" . $default;
|
/**
|
||||||
}
|
* Return a time type-formatted string
|
||||||
|
*
|
||||||
|
* @param array $values Contains a tokenised list of info about this data type
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function time($values)
|
||||||
|
{
|
||||||
|
if (!isset($values['arrayValue'])) {
|
||||||
|
$values['arrayValue'] = '';
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
return "time{$values['arrayValue']}";
|
||||||
* Return a datetime type-formatted string
|
}
|
||||||
* For PostgreSQL, we simply return the word 'timestamp', no other parameters are necessary
|
|
||||||
*
|
|
||||||
* @param array $values Contains a tokenised list of info about this data type
|
|
||||||
* @param boolean $asDbValue
|
|
||||||
* @return string
|
|
||||||
*/
|
|
||||||
public function SS_Datetime($values, $asDbValue = false){
|
|
||||||
|
|
||||||
if(!isset($values['arrayValue'])) {
|
/**
|
||||||
$values['arrayValue']='';
|
* Return a varchar type-formatted string
|
||||||
}
|
*
|
||||||
|
* @param array $values Contains a tokenised list of info about this data type
|
||||||
|
* @param boolean $asDbValue
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function varchar($values, $asDbValue=false)
|
||||||
|
{
|
||||||
|
if (!isset($values['arrayValue'])) {
|
||||||
|
$values['arrayValue'] = '';
|
||||||
|
}
|
||||||
|
|
||||||
if($asDbValue) {
|
if (!isset($values['precision'])) {
|
||||||
return array('data_type'=>'timestamp without time zone');
|
$values['precision'] = 255;
|
||||||
} else {
|
}
|
||||||
return "timestamp{$values['arrayValue']}";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
if ($asDbValue) {
|
||||||
* Return a text type-formatted string
|
return array('data_type'=>'varchar', 'precision'=>$values['precision']);
|
||||||
*
|
} else {
|
||||||
* @param array $values Contains a tokenised list of info about this data type
|
return "varchar({$values['precision']}){$values['arrayValue']}";
|
||||||
* @param boolean $asDbValue
|
}
|
||||||
* @return string
|
}
|
||||||
*/
|
|
||||||
public function text($values, $asDbValue = false){
|
|
||||||
|
|
||||||
if(!isset($values['arrayValue'])) {
|
/*
|
||||||
$values['arrayValue'] = '';
|
* Return a 4 digit numeric type. MySQL has a proprietary 'Year' type.
|
||||||
}
|
* For Postgres, we'll use a 4 digit numeric
|
||||||
|
*
|
||||||
|
* @param array $values Contains a tokenised list of info about this data type
|
||||||
|
* @param boolean $asDbValue
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function year($values, $asDbValue = false)
|
||||||
|
{
|
||||||
|
if (!isset($values['arrayValue'])) {
|
||||||
|
$values['arrayValue'] = '';
|
||||||
|
}
|
||||||
|
|
||||||
if($asDbValue) {
|
//TODO: the DbValue result does not include the numeric_scale option (ie, the ,0 value in 4,0)
|
||||||
return array('data_type'=>'text');
|
if ($asDbValue) {
|
||||||
} else {
|
return array('data_type'=>'decimal', 'precision'=>'4');
|
||||||
return "text{$values['arrayValue']}";
|
} else {
|
||||||
}
|
return "decimal(4,0){$values['arrayValue']}";
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Return a time type-formatted string
|
* Create a fulltext search datatype for PostgreSQL
|
||||||
*
|
* This will also return a trigger to be applied to this table
|
||||||
* @param array $values Contains a tokenised list of info about this data type
|
*
|
||||||
* @return string
|
* @todo: create custom functions to allow weighted searches
|
||||||
*/
|
*
|
||||||
public function time($values){
|
* @param array $this_index Index specification for the fulltext index
|
||||||
if(!isset($values['arrayValue'])) {
|
* @param string $tableName
|
||||||
$values['arrayValue'] = '';
|
* @param string $name
|
||||||
}
|
* @param array $spec
|
||||||
|
*/
|
||||||
|
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']);
|
||||||
|
|
||||||
return "time{$values['arrayValue']}";
|
$fulltexts = "\"ts_$name\" tsvector";
|
||||||
}
|
$triggerName = $this->buildPostgresTriggerName($tableName, $name);
|
||||||
|
$language = PostgreSQLDatabase::search_language();
|
||||||
|
|
||||||
/**
|
$this->dropTrigger($triggerName, $tableName);
|
||||||
* Return a varchar type-formatted string
|
$triggers = "CREATE TRIGGER \"$triggerName\" BEFORE INSERT OR UPDATE
|
||||||
*
|
|
||||||
* @param array $values Contains a tokenised list of info about this data type
|
|
||||||
* @param boolean $asDbValue
|
|
||||||
* @return string
|
|
||||||
*/
|
|
||||||
public function varchar($values, $asDbValue=false){
|
|
||||||
|
|
||||||
if(!isset($values['arrayValue'])) {
|
|
||||||
$values['arrayValue'] = '';
|
|
||||||
}
|
|
||||||
|
|
||||||
if(!isset($values['precision'])) {
|
|
||||||
$values['precision'] = 255;
|
|
||||||
}
|
|
||||||
|
|
||||||
if($asDbValue) {
|
|
||||||
return array('data_type'=>'varchar', 'precision'=>$values['precision']);
|
|
||||||
} else {
|
|
||||||
return "varchar({$values['precision']}){$values['arrayValue']}";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Return a 4 digit numeric type. MySQL has a proprietary 'Year' type.
|
|
||||||
* For Postgres, we'll use a 4 digit numeric
|
|
||||||
*
|
|
||||||
* @param array $values Contains a tokenised list of info about this data type
|
|
||||||
* @param boolean $asDbValue
|
|
||||||
* @return string
|
|
||||||
*/
|
|
||||||
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) {
|
|
||||||
return array('data_type'=>'decimal', 'precision'=>'4');
|
|
||||||
} else {
|
|
||||||
return "decimal(4,0){$values['arrayValue']}";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create a fulltext search datatype for PostgreSQL
|
|
||||||
* This will also return a trigger to be applied to this table
|
|
||||||
*
|
|
||||||
* @todo: create custom functions to allow weighted searches
|
|
||||||
*
|
|
||||||
* @param array $this_index Index specification for the fulltext index
|
|
||||||
* @param string $tableName
|
|
||||||
* @param string $name
|
|
||||||
* @param array $spec
|
|
||||||
*/
|
|
||||||
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']);
|
|
||||||
|
|
||||||
$fulltexts = "\"ts_$name\" tsvector";
|
|
||||||
$triggerName = $this->buildPostgresTriggerName($tableName, $name);
|
|
||||||
$language = PostgreSQLDatabase::search_language();
|
|
||||||
|
|
||||||
$this->dropTrigger($triggerName, $tableName);
|
|
||||||
$triggers = "CREATE TRIGGER \"$triggerName\" BEFORE INSERT OR UPDATE
|
|
||||||
ON \"$tableName\" FOR EACH ROW EXECUTE PROCEDURE
|
ON \"$tableName\" FOR EACH ROW EXECUTE PROCEDURE
|
||||||
tsvector_update_trigger(\"ts_$name\", 'pg_catalog.$language', $columns);";
|
tsvector_update_trigger(\"ts_$name\", 'pg_catalog.$language', $columns);";
|
||||||
|
|
||||||
return array(
|
return array(
|
||||||
'name' => $name,
|
'name' => $name,
|
||||||
'ts_name' => "ts_{$name}",
|
'ts_name' => "ts_{$name}",
|
||||||
'fulltexts' => $fulltexts,
|
'fulltexts' => $fulltexts,
|
||||||
'triggers' => $triggers
|
'triggers' => $triggers
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function IdColumn($asDbValue = false, $hasAutoIncPK = true){
|
public function IdColumn($asDbValue = false, $hasAutoIncPK = true)
|
||||||
if($asDbValue) return 'bigint';
|
{
|
||||||
else return 'serial8 not null';
|
if ($asDbValue) {
|
||||||
}
|
return 'bigint';
|
||||||
|
} else {
|
||||||
|
return 'serial8 not null';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public function hasTable($tableName) {
|
public function hasTable($tableName)
|
||||||
$result = $this->preparedQuery(
|
{
|
||||||
"SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = ? AND tablename = ?;",
|
$result = $this->preparedQuery(
|
||||||
array($this->database->currentSchema(), $tableName)
|
"SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = ? AND tablename = ?;",
|
||||||
);
|
array($this->database->currentSchema(), $tableName)
|
||||||
return ($result->numRecords() > 0);
|
);
|
||||||
}
|
return ($result->numRecords() > 0);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the values of the given enum field
|
* Returns the values of the given enum field
|
||||||
*
|
*
|
||||||
* @todo Make a proper implementation
|
* @todo Make a proper implementation
|
||||||
*
|
*
|
||||||
* @param string $tableName Name of table to check
|
* @param string $tableName Name of table to check
|
||||||
* @param string $fieldName name of enum field to check
|
* @param string $fieldName name of enum field to check
|
||||||
* @return array List of enum values
|
* @return array List of enum values
|
||||||
*/
|
*/
|
||||||
public function enumValuesForField($tableName, $fieldName) {
|
public function enumValuesForField($tableName, $fieldName)
|
||||||
//return array('SiteTree','Page');
|
{
|
||||||
$constraints = $this->constraintExists("{$tableName}_{$fieldName}_check");
|
//return array('SiteTree','Page');
|
||||||
if($constraints) {
|
$constraints = $this->constraintExists("{$tableName}_{$fieldName}_check");
|
||||||
return $this->enumValuesFromConstraint($constraints['pg_get_constraintdef']);
|
if ($constraints) {
|
||||||
} else {
|
return $this->enumValuesFromConstraint($constraints['pg_get_constraintdef']);
|
||||||
return array();
|
} else {
|
||||||
}
|
return array();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the actual enum fields from the constraint value:
|
* Get the actual enum fields from the constraint value:
|
||||||
*
|
*
|
||||||
* @param string $constraint
|
* @param string $constraint
|
||||||
* @return array
|
* @return array
|
||||||
*/
|
*/
|
||||||
protected function enumValuesFromConstraint($constraint){
|
protected function enumValuesFromConstraint($constraint)
|
||||||
$constraint = substr($constraint, strpos($constraint, 'ANY (ARRAY[')+11);
|
{
|
||||||
$constraint = substr($constraint, 0, -11);
|
$constraint = substr($constraint, strpos($constraint, 'ANY (ARRAY[')+11);
|
||||||
$constraints = array();
|
$constraint = substr($constraint, 0, -11);
|
||||||
$segments = explode(',', $constraint);
|
$constraints = array();
|
||||||
foreach($segments as $this_segment){
|
$segments = explode(',', $constraint);
|
||||||
$bits = preg_split('/ *:: */', $this_segment);
|
foreach ($segments as $this_segment) {
|
||||||
array_unshift($constraints, trim($bits[0], " '"));
|
$bits = preg_split('/ *:: */', $this_segment);
|
||||||
}
|
array_unshift($constraints, trim($bits[0], " '"));
|
||||||
return $constraints;
|
}
|
||||||
}
|
return $constraints;
|
||||||
|
}
|
||||||
|
|
||||||
public function dbDataType($type){
|
public function dbDataType($type)
|
||||||
$values = array(
|
{
|
||||||
'unsigned integer' => 'INT'
|
$values = array(
|
||||||
);
|
'unsigned integer' => 'INT'
|
||||||
|
);
|
||||||
|
|
||||||
if(isset($values[$type])) return $values[$type];
|
if (isset($values[$type])) {
|
||||||
else return '';
|
return $values[$type];
|
||||||
}
|
} else {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Given a tablespace and and location, either create a new one
|
* Given a tablespace and and location, either create a new one
|
||||||
* or update the existing one
|
* or update the existing one
|
||||||
*
|
*
|
||||||
* @param string $name
|
* @param string $name
|
||||||
* @param string $location
|
* @param string $location
|
||||||
*/
|
*/
|
||||||
public function createOrReplaceTablespace($name, $location){
|
public function createOrReplaceTablespace($name, $location)
|
||||||
$existing = $this->preparedQuery(
|
{
|
||||||
"SELECT spcname, spclocation FROM pg_tablespace WHERE spcname = ?;",
|
$existing = $this->preparedQuery(
|
||||||
array($name)
|
"SELECT spcname, spclocation FROM pg_tablespace WHERE spcname = ?;",
|
||||||
)->first();
|
array($name)
|
||||||
|
)->first();
|
||||||
|
|
||||||
//NOTE: this location must be empty for this to work
|
//NOTE: this location must be empty for this to work
|
||||||
//We can't seem to change the location of the tablespace through any ALTER commands :(
|
//We can't seem to change the location of the tablespace through any ALTER commands :(
|
||||||
|
|
||||||
//If a tablespace with this name exists, but the location has changed, then drop the current one
|
//If a tablespace with this name exists, but the location has changed, then drop the current one
|
||||||
//if($existing && $location!=$existing['spclocation'])
|
//if($existing && $location!=$existing['spclocation'])
|
||||||
// DB::query("DROP TABLESPACE $name;");
|
// DB::query("DROP TABLESPACE $name;");
|
||||||
|
|
||||||
//If this is a new tablespace, or we have dropped the current one:
|
//If this is a new tablespace, or we have dropped the current one:
|
||||||
if(!$existing || ($existing && $location != $existing['spclocation'])) {
|
if (!$existing || ($existing && $location != $existing['spclocation'])) {
|
||||||
$this->query("CREATE TABLESPACE $name LOCATION '$location';");
|
$this->query("CREATE TABLESPACE $name LOCATION '$location';");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @param string $tableName
|
* @param string $tableName
|
||||||
* @param array $partitions
|
* @param array $partitions
|
||||||
* @param array $indexes
|
* @param array $indexes
|
||||||
* @param array $extensions
|
* @param array $extensions
|
||||||
*/
|
*/
|
||||||
public function createOrReplacePartition($tableName, $partitions, $indexes, $extensions){
|
public function createOrReplacePartition($tableName, $partitions, $indexes, $extensions)
|
||||||
|
{
|
||||||
|
|
||||||
//We need the plpgsql language to be installed for this to work:
|
//We need the plpgsql language to be installed for this to work:
|
||||||
$this->createLanguage('plpgsql');
|
$this->createLanguage('plpgsql');
|
||||||
|
|
||||||
$trigger='CREATE OR REPLACE FUNCTION ' . $tableName . '_insert_trigger() RETURNS TRIGGER AS $$ BEGIN ';
|
$trigger='CREATE OR REPLACE FUNCTION ' . $tableName . '_insert_trigger() RETURNS TRIGGER AS $$ BEGIN ';
|
||||||
$first=true;
|
$first=true;
|
||||||
|
|
||||||
//Do we need to create a tablespace for this item?
|
//Do we need to create a tablespace for this item?
|
||||||
if($extensions && isset($extensions['tablespace'])){
|
if ($extensions && isset($extensions['tablespace'])) {
|
||||||
$this->createOrReplaceTablespace($extensions['tablespace']['name'], $extensions['tablespace']['location']);
|
$this->createOrReplaceTablespace($extensions['tablespace']['name'], $extensions['tablespace']['location']);
|
||||||
$tableSpace=' TABLESPACE ' . $extensions['tablespace']['name'];
|
$tableSpace=' TABLESPACE ' . $extensions['tablespace']['name'];
|
||||||
} else {
|
} else {
|
||||||
$tableSpace='';
|
$tableSpace='';
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach($partitions as $partition_name => $partition_value){
|
foreach ($partitions as $partition_name => $partition_value) {
|
||||||
//Check that this child table does not already exist:
|
//Check that this child table does not already exist:
|
||||||
if(!$this->hasTable($partition_name)){
|
if (!$this->hasTable($partition_name)) {
|
||||||
$this->query("CREATE TABLE \"$partition_name\" (CHECK (" . str_replace('NEW.', '', $partition_value) . ")) INHERITS (\"$tableName\")$tableSpace;");
|
$this->query("CREATE TABLE \"$partition_name\" (CHECK (" . str_replace('NEW.', '', $partition_value) . ")) INHERITS (\"$tableName\")$tableSpace;");
|
||||||
} else {
|
} else {
|
||||||
//Drop the constraint, we will recreate in in the next line
|
//Drop the constraint, we will recreate in in the next line
|
||||||
$existing_constraint = $this->preparedQuery(
|
$existing_constraint = $this->preparedQuery(
|
||||||
"SELECT conname FROM pg_constraint WHERE conname = ?;",
|
"SELECT conname FROM pg_constraint WHERE conname = ?;",
|
||||||
array("{$partition_name}_pkey")
|
array("{$partition_name}_pkey")
|
||||||
);
|
);
|
||||||
if($existing_constraint){
|
if ($existing_constraint) {
|
||||||
$this->query("ALTER TABLE \"$partition_name\" DROP CONSTRAINT \"{$partition_name}_pkey\";");
|
$this->query("ALTER TABLE \"$partition_name\" DROP CONSTRAINT \"{$partition_name}_pkey\";");
|
||||||
}
|
}
|
||||||
$this->dropTrigger(strtolower('trigger_' . $tableName . '_insert'), $tableName);
|
$this->dropTrigger(strtolower('trigger_' . $tableName . '_insert'), $tableName);
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->query("ALTER TABLE \"$partition_name\" ADD CONSTRAINT \"{$partition_name}_pkey\" PRIMARY KEY (\"ID\");");
|
$this->query("ALTER TABLE \"$partition_name\" ADD CONSTRAINT \"{$partition_name}_pkey\" PRIMARY KEY (\"ID\");");
|
||||||
|
|
||||||
if($first){
|
if ($first) {
|
||||||
$trigger.='IF';
|
$trigger.='IF';
|
||||||
$first=false;
|
$first=false;
|
||||||
} else {
|
} else {
|
||||||
$trigger.='ELSIF';
|
$trigger.='ELSIF';
|
||||||
}
|
}
|
||||||
|
|
||||||
$trigger .= " ($partition_value) THEN INSERT INTO \"$partition_name\" VALUES (NEW.*);";
|
$trigger .= " ($partition_value) THEN INSERT INTO \"$partition_name\" VALUES (NEW.*);";
|
||||||
|
|
||||||
if($indexes){
|
if ($indexes) {
|
||||||
// We need to propogate the indexes through to the child pages.
|
// We need to propogate the indexes through to the child pages.
|
||||||
// Some of this code is duplicated, and could be tidied up
|
// Some of this code is duplicated, and could be tidied up
|
||||||
foreach($indexes as $name => $this_index){
|
foreach ($indexes as $name => $this_index) {
|
||||||
|
if ($this_index['type']=='fulltext') {
|
||||||
|
$fillfactor = $where = '';
|
||||||
|
if (isset($this_index['fillfactor'])) {
|
||||||
|
$fillfactor = 'WITH (FILLFACTOR = ' . $this_index['fillfactor'] . ')';
|
||||||
|
}
|
||||||
|
if (isset($this_index['where'])) {
|
||||||
|
$where = 'WHERE ' . $this_index['where'];
|
||||||
|
}
|
||||||
|
$clusterMethod = PostgreSQLDatabase::default_fts_cluster_method();
|
||||||
|
$this->query("CREATE INDEX \"" . $this->buildPostgresIndexName($partition_name, $this_index['name']) . "\" ON \"" . $partition_name . "\" USING $clusterMethod(\"ts_" . $name . "\") $fillfactor $where");
|
||||||
|
$ts_details = $this->fulltext($this_index, $partition_name, $name);
|
||||||
|
$this->query($ts_details['triggers']);
|
||||||
|
} else {
|
||||||
|
if (is_array($this_index)) {
|
||||||
|
$index_name = $this_index['name'];
|
||||||
|
} else {
|
||||||
|
$index_name = trim($this_index, '()');
|
||||||
|
}
|
||||||
|
|
||||||
if($this_index['type']=='fulltext'){
|
$createIndex = $this->getIndexSqlDefinition($partition_name, $index_name, $this_index);
|
||||||
$fillfactor = $where = '';
|
if ($createIndex !== false) {
|
||||||
if(isset($this_index['fillfactor'])) {
|
$this->query($createIndex);
|
||||||
$fillfactor = 'WITH (FILLFACTOR = ' . $this_index['fillfactor'] . ')';
|
}
|
||||||
}
|
}
|
||||||
if(isset($this_index['where'])) {
|
}
|
||||||
$where = 'WHERE ' . $this_index['where'];
|
}
|
||||||
}
|
|
||||||
$clusterMethod = PostgreSQLDatabase::default_fts_cluster_method();
|
|
||||||
$this->query("CREATE INDEX \"" . $this->buildPostgresIndexName($partition_name, $this_index['name']) . "\" ON \"" . $partition_name . "\" USING $clusterMethod(\"ts_" . $name . "\") $fillfactor $where");
|
|
||||||
$ts_details = $this->fulltext($this_index, $partition_name, $name);
|
|
||||||
$this->query($ts_details['triggers']);
|
|
||||||
} else {
|
|
||||||
|
|
||||||
if(is_array($this_index)) {
|
//Lastly, clustering goes here:
|
||||||
$index_name = $this_index['name'];
|
if ($extensions && isset($extensions['cluster'])) {
|
||||||
} else {
|
$this->query("CLUSTER \"$partition_name\" USING \"{$extensions['cluster']}\";");
|
||||||
$index_name = trim($this_index, '()');
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$createIndex = $this->getIndexSqlDefinition($partition_name, $index_name, $this_index);
|
$trigger .= 'ELSE RAISE EXCEPTION \'Value id out of range. Fix the ' . $tableName . '_insert_trigger() function!\'; END IF; RETURN NULL; END; $$ LANGUAGE plpgsql;';
|
||||||
if($createIndex !== false) {
|
$trigger .= 'CREATE TRIGGER trigger_' . $tableName . '_insert BEFORE INSERT ON "' . $tableName . '" FOR EACH ROW EXECUTE PROCEDURE ' . $tableName . '_insert_trigger();';
|
||||||
$this->query($createIndex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//Lastly, clustering goes here:
|
$this->query($trigger);
|
||||||
if($extensions && isset($extensions['cluster'])){
|
}
|
||||||
$this->query("CLUSTER \"$partition_name\" USING \"{$extensions['cluster']}\";");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$trigger .= 'ELSE RAISE EXCEPTION \'Value id out of range. Fix the ' . $tableName . '_insert_trigger() function!\'; END IF; RETURN NULL; END; $$ LANGUAGE plpgsql;';
|
/*
|
||||||
$trigger .= 'CREATE TRIGGER trigger_' . $tableName . '_insert BEFORE INSERT ON "' . $tableName . '" FOR EACH ROW EXECUTE PROCEDURE ' . $tableName . '_insert_trigger();';
|
* This will create a language if it doesn't already exist.
|
||||||
|
* This is used by the createOrReplacePartition function, which needs plpgsql
|
||||||
|
*
|
||||||
|
* @param string $language Language name
|
||||||
|
*/
|
||||||
|
public function createLanguage($language)
|
||||||
|
{
|
||||||
|
$result = $this->preparedQuery(
|
||||||
|
"SELECT lanname FROM pg_language WHERE lanname = ?;",
|
||||||
|
array($language)
|
||||||
|
)->first();
|
||||||
|
|
||||||
$this->query($trigger);
|
if (!$result) {
|
||||||
}
|
$this->query("CREATE LANGUAGE $language;");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/**
|
||||||
* This will create a language if it doesn't already exist.
|
* Return a set type-formatted string
|
||||||
* This is used by the createOrReplacePartition function, which needs plpgsql
|
* This is used for Multi-enum support, which isn't actually supported by Postgres.
|
||||||
*
|
* Throws a user error to show our lack of support, and return an "int", specifically for sapphire
|
||||||
* @param string $language Language name
|
* tests that test multi-enums. This results in a test failure, but not crashing the test run.
|
||||||
*/
|
*
|
||||||
public function createLanguage($language){
|
* @param array $values Contains a tokenised list of info about this data type
|
||||||
$result = $this->preparedQuery(
|
* @return string
|
||||||
"SELECT lanname FROM pg_language WHERE lanname = ?;",
|
*/
|
||||||
array($language)
|
public function set($values)
|
||||||
)->first();
|
{
|
||||||
|
user_error("PostGreSQL does not support multi-enum", E_USER_ERROR);
|
||||||
if(!$result) {
|
return "int";
|
||||||
$this->query("CREATE LANGUAGE $language;");
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Return a set type-formatted string
|
|
||||||
* This is used for Multi-enum support, which isn't actually supported by Postgres.
|
|
||||||
* Throws a user error to show our lack of support, and return an "int", specifically for sapphire
|
|
||||||
* tests that test multi-enums. This results in a test failure, but not crashing the test run.
|
|
||||||
*
|
|
||||||
* @param array $values Contains a tokenised list of info about this data type
|
|
||||||
* @return string
|
|
||||||
*/
|
|
||||||
public function set($values){
|
|
||||||
user_error("PostGreSQL does not support multi-enum", E_USER_ERROR);
|
|
||||||
return "int";
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -5,45 +5,47 @@
|
|||||||
*
|
*
|
||||||
* @author Damian
|
* @author Damian
|
||||||
*/
|
*/
|
||||||
class PostgreSQLConnectorTest extends SapphireTest {
|
class PostgreSQLConnectorTest extends SapphireTest
|
||||||
|
{
|
||||||
|
|
||||||
public function testSubstitutesPlaceholders() {
|
public function testSubstitutesPlaceholders()
|
||||||
$connector = new PostgreSQLConnector();
|
{
|
||||||
|
$connector = new PostgreSQLConnector();
|
||||||
|
|
||||||
// basic case
|
// basic case
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
"SELECT * FROM Table WHERE ID = $1",
|
"SELECT * FROM Table WHERE ID = $1",
|
||||||
$connector->replacePlaceholders("SELECT * FROM Table WHERE ID = ?")
|
$connector->replacePlaceholders("SELECT * FROM Table WHERE ID = ?")
|
||||||
);
|
);
|
||||||
|
|
||||||
// Multiple variables
|
// Multiple variables
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
"SELECT * FROM Table WHERE ID = $1 AND Name = $2",
|
"SELECT * FROM Table WHERE ID = $1 AND Name = $2",
|
||||||
$connector->replacePlaceholders("SELECT * FROM Table WHERE ID = ? AND Name = ?")
|
$connector->replacePlaceholders("SELECT * FROM Table WHERE ID = ? AND Name = ?")
|
||||||
);
|
);
|
||||||
|
|
||||||
// Ignoring question mark placeholders within string literals
|
// Ignoring question mark placeholders within string literals
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
"SELECT * FROM Table WHERE ID = $1 AND Name = $2 AND Content = '<p>What is love?</p>'",
|
"SELECT * FROM Table WHERE ID = $1 AND Name = $2 AND Content = '<p>What is love?</p>'",
|
||||||
$connector->replacePlaceholders(
|
$connector->replacePlaceholders(
|
||||||
"SELECT * FROM Table WHERE ID = ? AND Name = ? AND Content = '<p>What is love?</p>'"
|
"SELECT * FROM Table WHERE ID = ? AND Name = ? AND Content = '<p>What is love?</p>'"
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
// Ignoring question mark placeholders within string literals with escaped slashes
|
// Ignoring question mark placeholders within string literals with escaped slashes
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
"SELECT * FROM Table WHERE ID = $1 AND Title = '\\'' AND Content = '<p>What is love?</p>' AND Name = $2",
|
"SELECT * FROM Table WHERE ID = $1 AND Title = '\\'' AND Content = '<p>What is love?</p>' AND Name = $2",
|
||||||
$connector->replacePlaceholders(
|
$connector->replacePlaceholders(
|
||||||
"SELECT * FROM Table WHERE ID = ? AND Title = '\\'' AND Content = '<p>What is love?</p>' AND Name = ?"
|
"SELECT * FROM Table WHERE ID = ? AND Title = '\\'' AND Content = '<p>What is love?</p>' AND Name = ?"
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
// same as above, but use double single quote escape syntax
|
// same as above, but use double single quote escape syntax
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
"SELECT * FROM Table WHERE ID = $1 AND Title = '''' AND Content = '<p>What is love?</p>' AND Name = $2",
|
"SELECT * FROM Table WHERE ID = $1 AND Title = '''' AND Content = '<p>What is love?</p>' AND Name = $2",
|
||||||
$connector->replacePlaceholders(
|
$connector->replacePlaceholders(
|
||||||
"SELECT * FROM Table WHERE ID = ? AND Title = '''' AND Content = '<p>What is love?</p>' AND Name = ?"
|
"SELECT * FROM Table WHERE ID = ? AND Title = '''' AND Content = '<p>What is love?</p>' AND Name = ?"
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -3,46 +3,44 @@
|
|||||||
* @package postgresql
|
* @package postgresql
|
||||||
* @subpackage tests
|
* @subpackage tests
|
||||||
*/
|
*/
|
||||||
class PostgreSQLDatabaseTest extends SapphireTest {
|
class PostgreSQLDatabaseTest extends SapphireTest
|
||||||
function testReadOnlyTransaction(){
|
{
|
||||||
|
public function testReadOnlyTransaction()
|
||||||
|
{
|
||||||
|
if (
|
||||||
|
DB::get_conn()->supportsTransactions() == true
|
||||||
|
&& DB::get_conn() instanceof PostgreSQLDatabase
|
||||||
|
) {
|
||||||
|
$page=new Page();
|
||||||
|
$page->Title='Read only success';
|
||||||
|
$page->write();
|
||||||
|
|
||||||
if(
|
DB::get_conn()->transactionStart('READ ONLY');
|
||||||
DB::get_conn()->supportsTransactions() == true
|
|
||||||
&& DB::get_conn() instanceof PostgreSQLDatabase
|
|
||||||
){
|
|
||||||
|
|
||||||
$page=new Page();
|
try {
|
||||||
$page->Title='Read only success';
|
$page=new Page();
|
||||||
$page->write();
|
$page->Title='Read only page failed';
|
||||||
|
$page->write();
|
||||||
|
} catch (Exception $e) {
|
||||||
|
//could not write this record
|
||||||
|
//We need to do a rollback or a commit otherwise we'll get error messages
|
||||||
|
DB::get_conn()->transactionRollback();
|
||||||
|
}
|
||||||
|
|
||||||
DB::get_conn()->transactionStart('READ ONLY');
|
DB::get_conn()->transactionEnd();
|
||||||
|
|
||||||
try {
|
DataObject::flush_and_destroy_cache();
|
||||||
$page=new Page();
|
|
||||||
$page->Title='Read only page failed';
|
|
||||||
$page->write();
|
|
||||||
} catch (Exception $e) {
|
|
||||||
//could not write this record
|
|
||||||
//We need to do a rollback or a commit otherwise we'll get error messages
|
|
||||||
DB::get_conn()->transactionRollback();
|
|
||||||
}
|
|
||||||
|
|
||||||
DB::get_conn()->transactionEnd();
|
$success=DataObject::get('Page', "\"Title\"='Read only success'");
|
||||||
|
$fail=DataObject::get('Page', "\"Title\"='Read only page failed'");
|
||||||
|
|
||||||
DataObject::flush_and_destroy_cache();
|
//This page should be in the system
|
||||||
|
$this->assertTrue(is_object($success) && $success->exists());
|
||||||
|
|
||||||
$success=DataObject::get('Page', "\"Title\"='Read only success'");
|
//This page should NOT exist, we had 'read only' permissions
|
||||||
$fail=DataObject::get('Page', "\"Title\"='Read only page failed'");
|
$this->assertFalse(is_object($fail) && $fail->exists());
|
||||||
|
} else {
|
||||||
//This page should be in the system
|
$this->markTestSkipped('Current database is not PostgreSQL');
|
||||||
$this->assertTrue(is_object($success) && $success->exists());
|
}
|
||||||
|
}
|
||||||
//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