Merge remote-tracking branch 'origin/1.2'

# Conflicts:
#	code/PostgreSQLSchemaManager.php
#	composer.json
This commit is contained in:
Damian Mooyman 2016-01-21 09:30:15 +13:00
commit 24caacbf3b

View File

@ -58,7 +58,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
public function createDatabase($name) public function createDatabase($name)
{ {
if (PostgreSQLDatabase::model_schema_as_database()) { if(PostgreSQLDatabase::model_schema_as_database()) {
$schemaName = $this->database->databaseToSchemaName($name); $schemaName = $this->database->databaseToSchemaName($name);
return $this->createSchema($schemaName); return $this->createSchema($schemaName);
} }
@ -79,7 +79,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
public function databaseExists($name) public function databaseExists($name)
{ {
if (PostgreSQLDatabase::model_schema_as_database()) { if(PostgreSQLDatabase::model_schema_as_database()) {
$schemaName = $this->database->databaseToSchemaName($name); $schemaName = $this->database->databaseToSchemaName($name);
return $this->schemaExists($schemaName); return $this->schemaExists($schemaName);
} }
@ -98,10 +98,10 @@ class PostgreSQLSchemaManager extends DBSchemaManager
public function databaseList() public function databaseList()
{ {
if (PostgreSQLDatabase::model_schema_as_database()) { if(PostgreSQLDatabase::model_schema_as_database()) {
$schemas = $this->schemaList(); $schemas = $this->schemaList();
$names = array(); $names = array();
foreach ($schemas as $schema) { foreach($schemas as $schema) {
$names[] = $this->database->schemaToDatabaseName($schema); $names[] = $this->database->schemaToDatabaseName($schema);
} }
return array_unique($names); return array_unique($names);
@ -121,7 +121,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
public function dropDatabase($name) public function dropDatabase($name)
{ {
if (PostgreSQLDatabase::model_schema_as_database()) { if(PostgreSQLDatabase::model_schema_as_database()) {
$schemaName = $this->database->databaseToSchemaName($name); $schemaName = $this->database->databaseToSchemaName($name);
return $this->dropSchema($schemaName); return $this->dropSchema($schemaName);
} }
@ -186,7 +186,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
$fieldSchemas .= "\"$k\" $v,\n"; $fieldSchemas .= "\"$k\" $v,\n";
} }
} }
if (!empty($options[self::ID])) { if(!empty($options[self::ID])) {
$addOptions = $options[self::ID]; $addOptions = $options[self::ID];
} elseif (!empty($options[get_class($this)])) { } elseif (!empty($options[get_class($this)])) {
Deprecation::notice('3.2', 'Use PostgreSQLSchemaManager::ID for referencing postgres-specific table creation options'); Deprecation::notice('3.2', 'Use PostgreSQLSchemaManager::ID for referencing postgres-specific table creation options');
@ -197,7 +197,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
//First of all, does this table already exist //First of all, does this table already exist
$doesExist = $this->hasTable($table); $doesExist = $this->hasTable($table);
if ($doesExist) { if($doesExist) {
// Table already exists, just return the name, in line with baseclass documentation. // Table already exists, just return the name, in line with baseclass documentation.
return $table; return $table;
} }
@ -206,9 +206,9 @@ class PostgreSQLSchemaManager extends DBSchemaManager
//for GiST searches //for GiST searches
$fulltexts = ''; $fulltexts = '';
$triggers = ''; $triggers = '';
if ($indexes) { if($indexes) {
foreach ($indexes as $name => $this_index) { foreach($indexes as $name => $this_index){
if (is_array($this_index) && $this_index['type'] == 'fulltext') { if(is_array($this_index) && $this_index['type'] == 'fulltext') {
$ts_details = $this->fulltext($this_index, $table, $name); $ts_details = $this->fulltext($this_index, $table, $name);
$fulltexts .= $ts_details['fulltexts'] . ', '; $fulltexts .= $ts_details['fulltexts'] . ', ';
$triggers .= $ts_details['triggers']; $triggers .= $ts_details['triggers'];
@ -223,7 +223,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
} }
//Do we need to create a tablespace for this item? //Do we need to create a tablespace for this item?
if ($advancedOptions && isset($advancedOptions['tablespace'])) { if($advancedOptions && isset($advancedOptions['tablespace'])){
$this->createOrReplaceTablespace( $this->createOrReplaceTablespace(
$advancedOptions['tablespace']['name'], $advancedOptions['tablespace']['name'],
$advancedOptions['tablespace']['location'] $advancedOptions['tablespace']['location']
@ -239,17 +239,17 @@ class PostgreSQLSchemaManager extends DBSchemaManager
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']}\";");
} }
@ -312,7 +312,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
} }
//Do we need to do anything with the tablespaces? //Do we need to do anything with the tablespaces?
if ($alteredOptions && isset($advancedOptions['tablespace'])) { if($alteredOptions && isset($advancedOptions['tablespace'])){
$this->createOrReplaceTablespace($advancedOptions['tablespace']['name'], $advancedOptions['tablespace']['location']); $this->createOrReplaceTablespace($advancedOptions['tablespace']['name'], $advancedOptions['tablespace']['location']);
$this->query("ALTER TABLE \"$table\" SET TABLESPACE {$advancedOptions['tablespace']['name']};"); $this->query("ALTER TABLE \"$table\" SET TABLESPACE {$advancedOptions['tablespace']['name']};");
} }
@ -330,7 +330,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
$indexSpec = $this->parseIndexSpec($indexName, $indexSpec); $indexSpec = $this->parseIndexSpec($indexName, $indexSpec);
$indexNamePG = $this->buildPostgresIndexName($table, $indexName); $indexNamePG = $this->buildPostgresIndexName($table, $indexName);
if ($indexSpec['type']=='fulltext') { if($indexSpec['type']=='fulltext') {
//For full text indexes, we need to drop the trigger, drop the index, AND drop the column //For full text indexes, we need to drop the trigger, drop the index, AND drop the column
//Go and get the tsearch details: //Go and get the tsearch details:
@ -339,7 +339,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
//Drop this column if it already exists: //Drop this column if it already exists:
//No IF EXISTS option is available for Postgres <9.0 //No IF EXISTS option is available for Postgres <9.0
if (array_key_exists($ts_details['ts_name'], $fieldList)) { if(array_key_exists($ts_details['ts_name'], $fieldList)){
$fulltexts.="ALTER TABLE \"{$table}\" DROP COLUMN \"{$ts_details['ts_name']}\";"; $fulltexts.="ALTER TABLE \"{$table}\" DROP COLUMN \"{$ts_details['ts_name']}\";";
} }
@ -367,9 +367,9 @@ class PostgreSQLSchemaManager extends DBSchemaManager
//If we have a fulltext search request, then we need to create a special column //If we have a fulltext search request, then we need to create a special column
//for GiST searches //for GiST searches
//Pick up the new indexes here: //Pick up the new indexes here:
if ($indexSpec['type']=='fulltext') { if($indexSpec['type']=='fulltext') {
$ts_details=$this->fulltext($indexSpec, $table, $indexName); $ts_details=$this->fulltext($indexSpec, $table, $indexName);
if (!isset($fieldList[$ts_details['ts_name']])) { if(!isset($fieldList[$ts_details['ts_name']])){
$fulltexts.="ALTER TABLE \"{$table}\" ADD COLUMN {$ts_details['fulltexts']};"; $fulltexts.="ALTER TABLE \"{$table}\" ADD COLUMN {$ts_details['fulltexts']};";
$triggers.=$ts_details['triggers']; $triggers.=$ts_details['triggers'];
} }
@ -377,7 +377,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
//Check that this index doesn't already exist: //Check that this index doesn't already exist:
$indexes=$this->indexList($table); $indexes=$this->indexList($table);
if (isset($indexes[$indexName])) { if(isset($indexes[$indexName])){
$alterIndexList[] = "DROP INDEX IF EXISTS \"$indexNamePG\";"; $alterIndexList[] = "DROP INDEX IF EXISTS \"$indexNamePG\";";
} }
@ -388,18 +388,18 @@ class PostgreSQLSchemaManager extends DBSchemaManager
} }
} }
if ($alterList) { if($alterList) {
$alterations = implode(",\n", $alterList); $alterations = implode(",\n", $alterList);
$this->query("ALTER TABLE \"$table\" " . $alterations); $this->query("ALTER TABLE \"$table\" " . $alterations);
} }
//Do we need to create a tablespace for this item? //Do we need to create a tablespace for this item?
if ($advancedOptions && isset($advancedOptions['extensions']['tablespace'])) { if($advancedOptions && isset($advancedOptions['extensions']['tablespace'])){
$extensions=$advancedOptions['extensions']; $extensions=$advancedOptions['extensions'];
$this->createOrReplaceTablespace($extensions['tablespace']['name'], $extensions['tablespace']['location']); $this->createOrReplaceTablespace($extensions['tablespace']['name'], $extensions['tablespace']['location']);
} }
if ($alteredOptions && isset($this->class) && isset($alteredOptions[$this->class])) { if($alteredOptions && isset($this->class) && isset($alteredOptions[$this->class])) {
$this->query(sprintf("ALTER TABLE \"%s\" %s", $table, $alteredOptions[$this->class])); $this->query(sprintf("ALTER TABLE \"%s\" %s", $table, $alteredOptions[$this->class]));
Database::alteration_message( Database::alteration_message(
sprintf("Table %s options changed: %s", $table, $alteredOptions[$this->class]), sprintf("Table %s options changed: %s", $table, $alteredOptions[$this->class]),
@ -415,14 +415,14 @@ class PostgreSQLSchemaManager extends DBSchemaManager
$this->query($drop_triggers); $this->query($drop_triggers);
} }
if ($triggers) { if($triggers) {
$this->query($triggers); $this->query($triggers);
$triggerbits=explode(';', $triggers); $triggerbits=explode(';', $triggers);
foreach ($triggerbits as $trigger) { foreach($triggerbits as $trigger){
$trigger_fields=$this->triggerFieldsFromTrigger($trigger); $trigger_fields=$this->triggerFieldsFromTrigger($trigger);
if ($trigger_fields) { if($trigger_fields){
//We need to run a simple query to force the database to update the triggered columns //We need to run a simple query to force the database to update the triggered columns
$this->query("UPDATE \"{$table}\" SET \"{$trigger_fields[0]}\"=\"$trigger_fields[0]\";"); $this->query("UPDATE \"{$table}\" SET \"{$trigger_fields[0]}\"=\"$trigger_fields[0]\";");
} }
@ -434,7 +434,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
} }
//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']); $this->createOrReplacePartition($table, $advancedOptions['partitions']);
} }
@ -461,7 +461,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
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;");
} }
} }
@ -481,7 +481,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
// TODO: this returns an empty array for the following string: int(11) not null auto_increment // TODO: this returns an empty array for the following string: int(11) not null auto_increment
// on second thoughts, why is an auto_increment field being passed through? // on second thoughts, why is an auto_increment field being passed through?
$pattern = '/^([\w()]+)\s?((?:not\s)?null)?\s?(default\s[\w\']+)?\s?(check\s[\w()\'",\s]+)?$/i'; $pattern = '/^([\w(\,)]+)\s?((?:not\s)?null)?\s?(default\s[\w\.\']+)?\s?(check\s[\w()\'",\s]+)?$/i';
preg_match($pattern, $colSpec, $matches); preg_match($pattern, $colSpec, $matches);
if (sizeof($matches)==0) { if (sizeof($matches)==0) {
@ -492,23 +492,23 @@ class PostgreSQLSchemaManager extends DBSchemaManager
return ''; return '';
} }
if (isset($matches[1])) { if(isset($matches[1])) {
$alterCol = "ALTER COLUMN \"$colName\" TYPE $matches[1]\n"; $alterCol = "ALTER COLUMN \"$colName\" TYPE $matches[1]\n";
// SET null / not null // SET null / not null
if (!empty($matches[2])) { 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], ')');
@ -519,10 +519,10 @@ class PostgreSQLSchemaManager extends DBSchemaManager
//We have to run this as a query, not as part of the alteration queries due to the way they are constructed. //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);";
} }
@ -530,12 +530,12 @@ class PostgreSQLSchemaManager extends DBSchemaManager
} }
//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]";
} }
} }
@ -576,7 +576,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
public function renameField($tableName, $oldName, $newName) public function renameField($tableName, $oldName, $newName)
{ {
$fieldList = $this->fieldList($tableName); $fieldList = $this->fieldList($tableName);
if (array_key_exists($oldName, $fieldList)) { if(array_key_exists($oldName, $fieldList)) {
$this->query("ALTER TABLE \"$tableName\" RENAME COLUMN \"$oldName\" TO \"$newName\""); $this->query("ALTER TABLE \"$tableName\" RENAME COLUMN \"$oldName\" TO \"$newName\"");
//Remove this from the cached list: //Remove this from the cached list:
@ -601,12 +601,12 @@ class PostgreSQLSchemaManager extends DBSchemaManager
$output = array(); $output = array();
if ($fields) { if ($fields) {
foreach ($fields as $field) { foreach ($fields as $field) {
switch ($field['data_type']) { switch($field['data_type']){
case 'character varying': case 'character varying':
//Check to see if there's a constraint attached to this column: //Check to see if there's a constraint attached to this column:
//$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->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'); $constraint = $this->constraintExists($table . '_' . $field['column_name'] . '_check');
if ($constraint) { if($constraint){
//Now we need to break this constraint text into bits so we can see what we have: //Now we need to break this constraint text into bits so we can see what we have:
//Examples: //Examples:
//CHECK ("CanEditType"::text = ANY (ARRAY['LoggedInUsers'::character varying, 'OnlyTheseUsers'::character varying, 'Inherit'::character varying]::text[])) //CHECK ("CanEditType"::text = ANY (ARRAY['LoggedInUsers'::character varying, 'OnlyTheseUsers'::character varying, 'Inherit'::character varying]::text[]))
@ -614,19 +614,19 @@ class PostgreSQLSchemaManager extends DBSchemaManager
//TODO: replace all this with a regular expression! //TODO: replace all this with a regular expression!
$value=$constraint['pg_get_constraintdef']; $value=$constraint['pg_get_constraintdef'];
$value=substr($value, strpos($value, '=')); $value=substr($value, strpos($value,'='));
$value=str_replace("''", "'", $value); $value=str_replace("''", "'", $value);
$in_value=false; $in_value=false;
$constraints=array(); $constraints=array();
$current_value=''; $current_value='';
for ($i=0; $i<strlen($value); $i++) { for($i=0; $i<strlen($value); $i++){
$char=substr($value, $i, 1); $char=substr($value, $i, 1);
if ($in_value) { if ($in_value) {
$current_value.=$char; $current_value.=$char;
} }
if ($char=="'") { if($char=="'"){
if (!$in_value) { if (!$in_value) {
$in_value=true; $in_value=true;
} else { } else {
@ -637,18 +637,18 @@ class PostgreSQLSchemaManager extends DBSchemaManager
} }
} }
if (sizeof($constraints)>0) { if(sizeof($constraints)>0){
//Get the default: //Get the default:
$default=trim(substr($field['column_default'], 0, strpos($field['column_default'], '::')), "'"); $default=trim(substr($field['column_default'], 0, strpos($field['column_default'], '::')), "'");
$output[$field['column_name']]=$this->enum(array('default'=>$default, 'name'=>$field['column_name'], 'enums'=>$constraints)); $output[$field['column_name']]=$this->enum(array('default'=>$default, 'name'=>$field['column_name'], 'enums'=>$constraints));
} }
} else { } else{
$output[$field['column_name']]='varchar(' . $field['character_maximum_length'] . ')'; $output[$field['column_name']]='varchar(' . $field['character_maximum_length'] . ')';
} }
break; break;
case 'numeric': case 'numeric':
$output[$field['column_name']]='decimal(' . $field['numeric_precision'] . ',' . $field['numeric_scale'] . ') default ' . (int)$field['column_default']; $output[$field['column_name']]='decimal(' . $field['numeric_precision'] . ',' . $field['numeric_scale'] . ') default ' . floatval($field['column_default']);
break; break;
case 'integer': case 'integer':
@ -751,7 +751,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
//This is techically a bug, since new tables will not be indexed. //This is techically a bug, since new tables will not be indexed.
// If requesting the definition rather than the DDL // If requesting the definition rather than the DDL
if ($asDbValue) { if($asDbValue) {
$indexName=trim($indexName, '()'); $indexName=trim($indexName, '()');
return $indexName; return $indexName;
} }
@ -805,13 +805,13 @@ class PostgreSQLSchemaManager extends DBSchemaManager
public function alterIndex($tableName, $indexName, $indexSpec) public function alterIndex($tableName, $indexName, $indexSpec)
{ {
$indexSpec = trim($indexSpec); $indexSpec = trim($indexSpec);
if ($indexSpec[0] != '(') { if($indexSpec[0] != '(') {
list($indexType, $indexFields) = explode(' ', $indexSpec, 2); list($indexType, $indexFields) = explode(' ',$indexSpec,2);
} else { } else {
$indexFields = $indexSpec; $indexFields = $indexSpec;
} }
if (!$indexType) { if(!$indexType) {
$indexType = "index"; $indexType = "index";
} }
@ -833,17 +833,17 @@ class PostgreSQLSchemaManager extends DBSchemaManager
)->first(); )->first();
// Option 1: output as a string // Option 1: output as a string
if (strpos($trigger['tgargs'], '\000') !== false) { if(strpos($trigger['tgargs'],'\000') !== false) {
$argList = explode('\000', $trigger['tgargs']); $argList = explode('\000', $trigger['tgargs']);
array_pop($argList); array_pop($argList);
// Option 2: hex-encoded (not sure why this happens, depends on PGSQL config) // Option 2: hex-encoded (not sure why this happens, depends on PGSQL config)
} else { } else {
$bytes = str_split($trigger['tgargs'], 2); $bytes = str_split($trigger['tgargs'],2);
$argList = array(); $argList = array();
$nextArg = ""; $nextArg = "";
foreach ($bytes as $byte) { foreach($bytes as $byte) {
if ($byte == "00") { if($byte == "00") {
$argList[] = $nextArg; $argList[] = $nextArg;
$nextArg = ""; $nextArg = "";
} else { } else {
@ -867,7 +867,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
); );
$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'];
@ -876,12 +876,12 @@ class PostgreSQLSchemaManager extends DBSchemaManager
$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';
} }
@ -889,7 +889,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
//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';
} }
@ -921,7 +921,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
"SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = ? AND tablename NOT ILIKE 'pg\\\_%' AND tablename NOT ILIKE 'sql\\\_%'", "SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = ? AND tablename NOT ILIKE 'pg\\\_%' AND tablename NOT ILIKE 'sql\\\_%'",
array($this->database->currentSchema()) array($this->database->currentSchema())
); );
foreach ($result as $record) { foreach($result as $record) {
$table = reset($record); $table = reset($record);
$tables[strtolower($table)] = $table; $tables[strtolower($table)] = $table;
} }
@ -937,7 +937,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
*/ */
protected function constraintExists($constraint) protected function constraintExists($constraint)
{ {
if (!isset(self::$cached_constraints[$constraint])) { if(!isset(self::$cached_constraints[$constraint])){
$exists = $this->preparedQuery(" $exists = $this->preparedQuery("
SELECT conname,pg_catalog.pg_get_constraintdef(r.oid, true) SELECT conname,pg_catalog.pg_get_constraintdef(r.oid, true)
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;",
@ -969,7 +969,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
$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']
@ -994,7 +994,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
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\";");
} }
} }
@ -1007,7 +1007,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
*/ */
protected function triggerFieldsFromTrigger($trigger) protected function triggerFieldsFromTrigger($trigger)
{ {
if ($trigger) { if($trigger){
$tsvector='tsvector_update_trigger'; $tsvector='tsvector_update_trigger';
$ts_pos=strpos($trigger, $tsvector); $ts_pos=strpos($trigger, $tsvector);
$details=trim(substr($trigger, $ts_pos+strlen($tsvector)), '();'); $details=trim(substr($trigger, $ts_pos+strlen($tsvector)), '();');
@ -1040,15 +1040,15 @@ class PostgreSQLSchemaManager extends DBSchemaManager
//Annoyingly, we need to do a good ol' fashioned switch here: //Annoyingly, we need to do a good ol' fashioned switch here:
$default = $values['default'] ? '1' : '0'; $default = $values['default'] ? '1' : '0';
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'];
@ -1064,7 +1064,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
*/ */
public function date($values) public function date($values)
{ {
if (!isset($values['arrayValue'])) { if(!isset($values['arrayValue'])) {
$values['arrayValue']=''; $values['arrayValue']='';
} }
@ -1080,23 +1080,23 @@ class PostgreSQLSchemaManager extends DBSchemaManager
*/ */
public function decimal($values, $asDbValue=false) public function decimal($values, $asDbValue=false)
{ {
if (!isset($values['arrayValue'])) { if(!isset($values['arrayValue'])) {
$values['arrayValue']=''; $values['arrayValue']='';
} }
// Avoid empty strings being put in the db // Avoid empty strings being put in the db
if ($values['precision'] == '') { if($values['precision'] == '') {
$precision = 1; $precision = 1;
} else { } else {
$precision = $values['precision']; $precision = $values['precision'];
} }
$defaultValue = ''; $defaultValue = '';
if (isset($values['default']) && is_numeric($values['default'])) { if(isset($values['default']) && is_numeric($values['default'])) {
$defaultValue = ' default ' . $values['default']; $defaultValue = ' default ' . floatval($values['default']);
} }
if ($asDbValue) { if($asDbValue) {
return array('data_type' => 'numeric', 'precision' => $precision); return array('data_type' => 'numeric', 'precision' => $precision);
} else { } else {
return "decimal($precision){$values['arrayValue']}$defaultValue"; return "decimal($precision){$values['arrayValue']}$defaultValue";
@ -1113,11 +1113,11 @@ class PostgreSQLSchemaManager extends DBSchemaManager
{ {
//Enums are a bit different. We'll be creating a varchar(255) with a constraint of all the usual enum options. //Enums are a bit different. We'll be creating a varchar(255) with a constraint of all the usual enum options.
//NOTE: In this one instance, we are including the table name in the values array //NOTE: In this one instance, we are including the table name in the values array
if (!isset($values['arrayValue'])) { if(!isset($values['arrayValue'])) {
$values['arrayValue']=''; $values['arrayValue']='';
} }
if ($values['arrayValue']!='') { if($values['arrayValue']!='') {
$default = ''; $default = '';
} else { } else {
$default = " default '{$values['default']}'"; $default = " default '{$values['default']}'";
@ -1135,11 +1135,11 @@ class PostgreSQLSchemaManager extends DBSchemaManager
*/ */
public function float($values, $asDbValue = false) public function float($values, $asDbValue = false)
{ {
if (!isset($values['arrayValue'])) { if(!isset($values['arrayValue'])) {
$values['arrayValue']=''; $values['arrayValue']='';
} }
if ($asDbValue) { if($asDbValue) {
return array('data_type' => 'double precision'); return array('data_type' => 'double precision');
} else { } else {
return "float{$values['arrayValue']}"; return "float{$values['arrayValue']}";
@ -1167,15 +1167,15 @@ class PostgreSQLSchemaManager extends DBSchemaManager
*/ */
public function int($values, $asDbValue = false) public function int($values, $asDbValue = false)
{ {
if (!isset($values['arrayValue'])) { if(!isset($values['arrayValue'])) {
$values['arrayValue']=''; $values['arrayValue']='';
} }
if ($asDbValue) { if($asDbValue) {
return array('data_type'=>'integer', 'precision'=>'32'); return array('data_type'=>'integer', 'precision'=>'32');
} }
if ($values['arrayValue']!='') { if($values['arrayValue']!='') {
$default=''; $default='';
} else { } else {
$default=' default ' . (int)$values['default']; $default=' default ' . (int)$values['default'];
@ -1193,15 +1193,15 @@ class PostgreSQLSchemaManager extends DBSchemaManager
*/ */
public function bigint($values, $asDbValue = false) public function bigint($values, $asDbValue = false)
{ {
if (!isset($values['arrayValue'])) { if(!isset($values['arrayValue'])) {
$values['arrayValue']=''; $values['arrayValue']='';
} }
if ($asDbValue) { if($asDbValue) {
return array('data_type'=>'bigint', 'precision'=>'64'); return array('data_type'=>'bigint', 'precision'=>'64');
} }
if ($values['arrayValue']!='') { if($values['arrayValue']!='') {
$default=''; $default='';
} else { } else {
$default=' default ' . (int)$values['default']; $default=' default ' . (int)$values['default'];
@ -1220,11 +1220,11 @@ class PostgreSQLSchemaManager extends DBSchemaManager
*/ */
public function SS_Datetime($values, $asDbValue = false) public function SS_Datetime($values, $asDbValue = false)
{ {
if (!isset($values['arrayValue'])) { if(!isset($values['arrayValue'])) {
$values['arrayValue']=''; $values['arrayValue']='';
} }
if ($asDbValue) { if($asDbValue) {
return array('data_type'=>'timestamp without time zone'); return array('data_type'=>'timestamp without time zone');
} else { } else {
return "timestamp{$values['arrayValue']}"; return "timestamp{$values['arrayValue']}";
@ -1240,11 +1240,11 @@ class PostgreSQLSchemaManager extends DBSchemaManager
*/ */
public function text($values, $asDbValue = false) public function text($values, $asDbValue = false)
{ {
if (!isset($values['arrayValue'])) { if(!isset($values['arrayValue'])) {
$values['arrayValue'] = ''; $values['arrayValue'] = '';
} }
if ($asDbValue) { if($asDbValue) {
return array('data_type'=>'text'); return array('data_type'=>'text');
} else { } else {
return "text{$values['arrayValue']}"; return "text{$values['arrayValue']}";
@ -1259,7 +1259,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
*/ */
public function time($values) public function time($values)
{ {
if (!isset($values['arrayValue'])) { if(!isset($values['arrayValue'])) {
$values['arrayValue'] = ''; $values['arrayValue'] = '';
} }
@ -1275,15 +1275,15 @@ class PostgreSQLSchemaManager extends DBSchemaManager
*/ */
public function varchar($values, $asDbValue=false) public function varchar($values, $asDbValue=false)
{ {
if (!isset($values['arrayValue'])) { if(!isset($values['arrayValue'])) {
$values['arrayValue'] = ''; $values['arrayValue'] = '';
} }
if (!isset($values['precision'])) { if(!isset($values['precision'])) {
$values['precision'] = 255; $values['precision'] = 255;
} }
if ($asDbValue) { if($asDbValue) {
return array('data_type'=>'varchar', 'precision'=>$values['precision']); return array('data_type'=>'varchar', 'precision'=>$values['precision']);
} else { } else {
return "varchar({$values['precision']}){$values['arrayValue']}"; return "varchar({$values['precision']}){$values['arrayValue']}";
@ -1300,12 +1300,12 @@ class PostgreSQLSchemaManager extends DBSchemaManager
*/ */
public function year($values, $asDbValue = false) public function year($values, $asDbValue = false)
{ {
if (!isset($values['arrayValue'])) { if(!isset($values['arrayValue'])) {
$values['arrayValue'] = ''; $values['arrayValue'] = '';
} }
//TODO: the DbValue result does not include the numeric_scale option (ie, the ,0 value in 4,0) //TODO: the DbValue result does not include the numeric_scale option (ie, the ,0 value in 4,0)
if ($asDbValue) { if($asDbValue) {
return array('data_type'=>'decimal', 'precision'=>'4'); return array('data_type'=>'decimal', 'precision'=>'4');
} else { } else {
return "decimal(4,0){$values['arrayValue']}"; return "decimal(4,0){$values['arrayValue']}";
@ -1376,7 +1376,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
{ {
//return array('SiteTree','Page'); //return array('SiteTree','Page');
$constraints = $this->constraintExists("{$tableName}_{$fieldName}_check"); $constraints = $this->constraintExists("{$tableName}_{$fieldName}_check");
if ($constraints) { if($constraints) {
return $this->enumValuesFromConstraint($constraints['pg_get_constraintdef']); return $this->enumValuesFromConstraint($constraints['pg_get_constraintdef']);
} else { } else {
return array(); return array();
@ -1395,7 +1395,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
$constraint = substr($constraint, 0, -11); $constraint = substr($constraint, 0, -11);
$constraints = array(); $constraints = array();
$segments = explode(',', $constraint); $segments = explode(',', $constraint);
foreach ($segments as $this_segment) { foreach($segments as $this_segment){
$bits = preg_split('/ *:: */', $this_segment); $bits = preg_split('/ *:: */', $this_segment);
array_unshift($constraints, trim($bits[0], " '")); array_unshift($constraints, trim($bits[0], " '"));
} }
@ -1437,7 +1437,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
// 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';");
} }
} }
@ -1459,16 +1459,16 @@ class PostgreSQLSchemaManager extends DBSchemaManager
$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
@ -1476,7 +1476,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
"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);
@ -1484,7 +1484,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
$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 {
@ -1493,16 +1493,16 @@ class PostgreSQLSchemaManager extends DBSchemaManager
$trigger .= " ($partition_value) THEN INSERT INTO \"$partition_name\" VALUES (NEW.*);"; $trigger .= " ($partition_value) THEN INSERT INTO \"$partition_name\" VALUES (NEW.*);";
if ($indexes) { if($indexes){
// We need to propogate the indexes through to the child pages. // We need to propogate the indexes through to the child pages.
// Some of this code is duplicated, and could be tidied up // Some of this code is duplicated, and could be tidied up
foreach ($indexes as $name => $this_index) { foreach($indexes as $name => $this_index){
if ($this_index['type']=='fulltext') { if($this_index['type']=='fulltext'){
$fillfactor = $where = ''; $fillfactor = $where = '';
if (isset($this_index['fillfactor'])) { if(isset($this_index['fillfactor'])) {
$fillfactor = 'WITH (FILLFACTOR = ' . $this_index['fillfactor'] . ')'; $fillfactor = 'WITH (FILLFACTOR = ' . $this_index['fillfactor'] . ')';
} }
if (isset($this_index['where'])) { if(isset($this_index['where'])) {
$where = 'WHERE ' . $this_index['where']; $where = 'WHERE ' . $this_index['where'];
} }
$clusterMethod = PostgreSQLDatabase::default_fts_cluster_method(); $clusterMethod = PostgreSQLDatabase::default_fts_cluster_method();
@ -1510,14 +1510,14 @@ class PostgreSQLSchemaManager extends DBSchemaManager
$ts_details = $this->fulltext($this_index, $partition_name, $name); $ts_details = $this->fulltext($this_index, $partition_name, $name);
$this->query($ts_details['triggers']); $this->query($ts_details['triggers']);
} else { } else {
if (is_array($this_index)) { if(is_array($this_index)) {
$index_name = $this_index['name']; $index_name = $this_index['name'];
} else { } else {
$index_name = trim($this_index, '()'); $index_name = trim($this_index, '()');
} }
$createIndex = $this->getIndexSqlDefinition($partition_name, $index_name, $this_index); $createIndex = $this->getIndexSqlDefinition($partition_name, $index_name, $this_index);
if ($createIndex !== false) { if($createIndex !== false) {
$this->query($createIndex); $this->query($createIndex);
} }
} }
@ -1525,7 +1525,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
} }
//Lastly, clustering goes here: //Lastly, clustering goes here:
if ($extensions && isset($extensions['cluster'])) { if($extensions && isset($extensions['cluster'])){
$this->query("CLUSTER \"$partition_name\" USING \"{$extensions['cluster']}\";"); $this->query("CLUSTER \"$partition_name\" USING \"{$extensions['cluster']}\";");
} }
} }
@ -1549,7 +1549,7 @@ class PostgreSQLSchemaManager extends DBSchemaManager
array($language) array($language)
)->first(); )->first();
if (!$result) { if(!$result) {
$this->query("CREATE LANGUAGE $language;"); $this->query("CREATE LANGUAGE $language;");
} }
} }