Skip to content

Default expression is not loaded into ColumnSchema #19747

Open
@SOHELAHMED7

Description

@SOHELAHMED7

When column schema is loaded from DB, for columns having default value as expression but not constant, I get expression as string as default value instead of object of \yii\db\Expression.

Example:

What steps will reproduce the problem?

  • create a new table with at least one column that have default expression. Example:
$mysqlColumns = [
            'ts' => 'datetime DEFAULT \'2011-11-11 00:00:00\'',
            'ts2' => 'datetime DEFAULT CURRENT_TIMESTAMP',
            'ts3' => 'datetime DEFAULT CURRENT_TIMESTAMP',
            'ts4' => 'timestamp DEFAULT CURRENT_TIMESTAMP',
            'ts5' => 'timestamp DEFAULT \'2011-11-11 00:00:00\'',
            'ts6' => 'timestamp DEFAULT CURRENT_TIMESTAMP',
            'd' => 'date DEFAULT \'2011-11-11\'',
            'd2' => 'text', // DEFAULT "2011-11-11"
            'd3' => 'text', // DEFAULT CURRENT_DATE + INTERVAL 1 YEAR
            'ts7' => 'date DEFAULT (CURRENT_DATE + INTERVAL 2 YEAR)',
        ];
        if (DB::isPostgres()) {
            $pgsqlColumns = $mysqlColumns;
            $pgsqlColumns['ts7'] = 'date DEFAULT (CURRENT_DATE + INTERVAL \'2 YEAR\')';
            Yii::$app->db->createCommand()->createTable('{{%fruits}}', $pgsqlColumns)->execute();
            return;
        }

        Yii::$app->db->createCommand()->createTable('{{%fruits}}', $mysqlColumns)->execute();
  • now get columns schema from yii\db\TableSchema::$columns
  • say for e.g. lets take ts7 column from example $ts7ColumnSchema = (object of yii\db\TableSchema)::$columns['ts7']

What is the expected result?

Now I expect $ts7ColumnSchema->defaultValue should be equal to object of \yii\db\Expression('(CURRENT_DATE + INTERVAL 2 YEAR)'') for Mysql

What do you get instead?

I get $ts7ColumnSchema->defaultValue as '(CURRENT_DATE + INTERVAL 2 YEAR)' as string

Hint for solution

For MySQL we get DEFAULT_GENERATED in Extra column, we can use that when we loadColumnSchema()

mysql-def-expr

For PgSQL for default constant, its value is suffixed by ::data_type e.g. ::text

pgsql-def-exp

Additional info

Q A
Yii version 2.0.*
PHP version
Operating system

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions