Skip to content

Commit

Permalink
Explicitly cast varbinary to work around MSSQL PDO bug
Browse files Browse the repository at this point in the history
  • Loading branch information
samdark committed Jan 22, 2017
1 parent 6c54d1c commit cc56e9e
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions framework/db/mssql/QueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

use yii\base\InvalidParamException;
use yii\base\NotSupportedException;
use yii\db\Expression;

/**
* QueryBuilder is the query builder for MS SQL Server databases (version 2008 and above).
Expand Down Expand Up @@ -312,4 +313,41 @@ public function selectExists($rawSql)
{
return 'SELECT CASE WHEN EXISTS(' . $rawSql . ') THEN 1 ELSE 0 END';
}

/**
* Normalizes data to be saved into the table, performing extra preparations and type converting, if necessary.
* @param string $table the table that data will be saved into.
* @param array $columns the column data (name => value) to be saved into the table.
* @return array normalized columns
*/
private function normalizeTableRowData($table, $columns, &$params)
{
if (($tableSchema = $this->db->getSchema()->getTableSchema($table)) !== null) {
$columnSchemas = $tableSchema->columns;
foreach ($columns as $name => $value) {
// @see https://github.com/yiisoft/yii2/issues/12599
if (isset($columnSchemas[$name]) && $columnSchemas[$name]->type === Schema::TYPE_BINARY && $columnSchemas[$name]->dbType === 'varbinary' && is_string($value)) {
$phName = self::PARAM_PREFIX . count($params);
$columns[$name] = new Expression("CONVERT(VARBINARY, $phName)", [$phName => $value]);
}
}
}
return $columns;
}

/**
* @inheritdoc
*/
public function insert($table, $columns, &$params)
{
return parent::insert($table, $this->normalizeTableRowData($table, $columns, $params), $params);
}

/**
* @inheritdoc
*/
public function update($table, $columns, $condition, &$params)
{
return parent::update($table, $this->normalizeTableRowData($table, $columns, $params), $condition, $params);
}
}

0 comments on commit cc56e9e

Please sign in to comment.