Adding PostgreSQL expression support as default value

CPgsqlColumnSchema:




--- 53,60 ----

  			$this->defaultValue=$this->typecast(str_replace("''","'",$matches[1]));

  		else if(preg_match('/^-?\d+(\.\d*)?$/',$defaultValue,$matches))

  			$this->defaultValue=$this->typecast($defaultValue);

+ 		else if(strpos($defaultValue, '(') === 0)

+ 			$this->defaultValue=$this->typecast(new CDbExpression($defaultValue));

  		// else is null

  	}

  }



CActiveRecord:




@@ -2282,17 +2282,8 @@

 

 		foreach($table->columns as $name=>$column)

 		{

-			if(!$column->isPrimaryKey && $column->defaultValue!==null)

-				$this->attributeDefaults[$name]=$column->defaultValue;

+			if(!$column->isPrimaryKey) {

+                		if ($column->defaultValue instanceof CDbExpression) {

+                    			$result = Yii::app()->db->createCommand('SELECT ' . $column->defaultValue->expression . ';')->queryColumn();

+                    

+		                	if (isset($result[0]))

+               	        		$this->attributeDefaults[$name]=$result[0];

+                		}

+                		else if ($column->defaultValue!==null)

+                    			$this->attributeDefaults[$name]=$column->defaultValue;

+            		}

 		}

 

 		foreach($model->relations() as $name=>$config)



Can you describe what exactly it allows doing and why it wasn’t possible before?

Default value is often necessary on a field. It can be an expression In PostgreSQL, example:




CREATE TABLE product."Price"

(

  id integer NOT NULL DEFAULT nextval('product."Price_id_seq"'::regclass),

  "productId" integer NOT NULL,

  "valueAddedTaxId" integer NOT NULL DEFAULT 2,

  "validityStartedDate" date NOT NULL DEFAULT ('now'::text)::date, -- today

  "validityEndedDate" date NOT NULL DEFAULT ((date_trunc('YEAR'::text, (('now'::text)::date)::timestamp with time zone) + '1 year -1 days'::interval))::date, -- 2012. 12. 31

  price double precision NOT NULL DEFAULT 0,

  "validityStartedTime" time without time zone NOT NULL DEFAULT '00:00:00'::time without time zone,

  "validityEndedTime" time without time zone NOT NULL DEFAULT '23:59:59'::time without time zone

)



It working when you insert a new tupple and validityStartedDate, validityEndedDate is null.

But, if you want to change default value, then you have to run a query before view it on user interface (etc. datepicker), because Yii doesn’t interpret these.

Can be useful. Need more opinions from developers using Postgres.