View source  
  <?php
namespace Drupal\sqlsrv\Driver\Database\sqlsrv;
use Drupal\Core\Database\Schema as DatabaseSchema;
use Drupal\Core\Database\SchemaObjectDoesNotExistException;
use Drupal\Core\Database\SchemaObjectExistsException;
class Schema extends DatabaseSchema {
  
  protected $connection;
  
  protected $defaultSchema;
  
  const COMMENT_MAX_BYTES = 7500;
  
  const PRIMARY_KEY_BYTES = 900;
  
  const CLUSTERED_INDEX_BYTES = 900;
  
  const NONCLUSTERED_INDEX_BYTES = 1700;
  
  const XML_INDEX_BYTES = 128;
  
  
  const COMPUTED_PK_COLUMN_NAME = '__pkc';
  
  const COMPUTED_PK_COLUMN_INDEX = '__ix_pkc';
  
  const TECHNICAL_PK_COLUMN_NAME = '__pk';
  
  protected $engineVersion;
  
  private $cacheSchema;
  
  private $columnInformation = [];
  
  public function getFieldTypeMap() {
    
    $utf8_string_types = [
      'varchar:normal' => 'varchar',
      'char:normal' => 'char',
      'text:tiny' => 'varchar(255)',
      'text:small' => 'varchar(255)',
      'text:medium' => 'varchar(max)',
      'text:big' => 'varchar(max)',
      'text:normal' => 'varchar(max)',
    ];
    $ucs2_string_types = [
      'varchar:normal' => 'nvarchar',
      'char:normal' => 'nchar',
      'text:tiny' => 'nvarchar(255)',
      'text:small' => 'nvarchar(255)',
      'text:medium' => 'nvarchar(max)',
      'text:big' => 'nvarchar(max)',
      'text:normal' => 'nvarchar(max)',
    ];
    $standard_types = [
      'varchar_ascii:normal' => 'varchar(255)',
      'serial:tiny' => 'smallint',
      'serial:small' => 'smallint',
      'serial:medium' => 'int',
      'serial:big' => 'bigint',
      'serial:normal' => 'int',
      'int:tiny' => 'smallint',
      'int:small' => 'smallint',
      'int:medium' => 'int',
      'int:big' => 'bigint',
      'int:normal' => 'int',
      'float:tiny' => 'real',
      'float:small' => 'real',
      'float:medium' => 'real',
      'float:big' => 'float(53)',
      'float:normal' => 'real',
      'numeric:normal' => 'numeric',
      'blob:big' => 'varbinary(max)',
      'blob:normal' => 'varbinary(max)',
      'date:normal' => 'date',
      'datetime:normal' => 'datetime2(0)',
      'time:normal' => 'time(0)',
    ];
    $standard_types += $this
      ->isUtf8() ? $utf8_string_types : $ucs2_string_types;
    return $standard_types;
  }
  
  public function renameTable($table, $new_name) {
    if (!$this
      ->tableExists($table)) {
      throw new SchemaObjectDoesNotExistException(t("Cannot rename %table to %table_new: table %table doesn't exist.", [
        '%table' => $table,
        '%table_new' => $new_name,
      ]));
    }
    if ($this
      ->tableExists($new_name)) {
      throw new SchemaObjectExistsException(t("Cannot rename %table to %table_new: table %table_new already exists.", [
        '%table' => $table,
        '%table_new' => $new_name,
      ]));
    }
    $old_table_info = $this
      ->getPrefixInfo($table);
    $new_table_info = $this
      ->getPrefixInfo($new_name);
    
    if ($old_table_info['schema'] != $new_table_info['schema']) {
      throw new \PDOException(t('Cannot rename a table across schema.'));
    }
    $this->connection
      ->queryDirect('EXEC sp_rename :old, :new', [
      ':old' => $old_table_info['schema'] . '.' . $old_table_info['table'],
      ':new' => $new_table_info['table'],
    ]);
    
    $objects = $this->connection
      ->queryDirect('SELECT name FROM sys.objects WHERE parent_object_id = OBJECT_ID(:table)', [
      ':table' => $new_table_info['schema'] . '.' . $new_table_info['table'],
    ]);
    foreach ($objects as $object) {
      if (preg_match('/^' . preg_quote($old_table_info['table']) . '_(.*)$/', $object->name, $matches)) {
        $this->connection
          ->queryDirect('EXEC sp_rename :old, :new, :type', [
          ':old' => $old_table_info['schema'] . '.' . $object->name,
          ':new' => $new_table_info['table'] . '_' . $matches[1],
          ':type' => 'OBJECT',
        ]);
      }
    }
    $this
      ->resetColumnInformation($table);
  }
  
  public function dropTable($table) {
    if (!$this
      ->tableExists($table)) {
      return FALSE;
    }
    $this->connection
      ->queryDirect('DROP TABLE {' . $table . '}');
    $this
      ->resetColumnInformation($table);
    return TRUE;
  }
  
  public function fieldExists($table, $field) {
    $prefixInfo = $this
      ->getPrefixInfo($table, TRUE);
    return $this->connection
      ->queryDirect('SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = :table AND column_name = :name', [
      ':table' => $prefixInfo['table'],
      ':name' => $field,
    ])
      ->fetchField() !== FALSE;
  }
  
  public function addField($table, $field, $spec, $keys_new = []) {
    if (!$this
      ->tableExists($table)) {
      throw new SchemaObjectDoesNotExistException(t("Cannot add field @table.@field: table doesn't exist.", [
        '@field' => $field,
        '@table' => $table,
      ]));
    }
    if ($this
      ->fieldExists($table, $field)) {
      throw new SchemaObjectExistsException(t("Cannot add field @table.@field: field already exists.", [
        '@field' => $field,
        '@table' => $table,
      ]));
    }
    
    $is_primary_key = isset($keys_new['primary key']) && in_array($field, $keys_new['primary key'], TRUE);
    if ($is_primary_key) {
      $this
        ->ensureNotNullPrimaryKey($keys_new['primary key'], [
        $field => $spec,
      ]);
    }
    $transaction = $this->connection
      ->startTransaction();
    
    $spec = $this
      ->processField($spec);
    
    $prefixInfo = $this
      ->getPrefixInfo($table, TRUE);
    $table_prefixed = $prefixInfo['table'];
    if ($this
      ->findPrimaryKeyColumns($table) !== [] && isset($keys_new['primary key']) && in_array($field, $keys_new['primary key'])) {
      $this
        ->cleanUpPrimaryKey($table);
    }
    
    $fixnull = FALSE;
    if (!empty($spec['not null'])) {
      $fixnull = TRUE;
      $spec['not null'] = FALSE;
    }
    
    $query = "ALTER TABLE {{$table}} ADD ";
    $query .= $this
      ->createFieldSql($table, $field, $spec);
    $this->connection
      ->queryDirect($query, []);
    $this
      ->resetColumnInformation($table);
    
    if (isset($spec['initial_from_field'])) {
      if (isset($spec['initial'])) {
        $expression = 'COALESCE(' . $spec['initial_from_field'] . ', :default_initial_value)';
        $arguments = [
          ':default_initial_value' => $spec['initial'],
        ];
      }
      else {
        $expression = $spec['initial_from_field'];
        $arguments = [];
      }
      $this->connection
        ->update($table)
        ->expression($field, $expression, $arguments)
        ->execute();
    }
    elseif (isset($spec['initial'])) {
      $this->connection
        ->update($table)
        ->fields([
        $field => $spec['initial'],
      ])
        ->execute();
    }
    
    if ($fixnull === TRUE) {
      
      if (isset($spec['default'])) {
        $default_expression = $this
          ->defaultValueExpression($spec['sqlsrv_type'], $spec['default']);
        $sql = "UPDATE {{$table}} SET {$field}={$default_expression} WHERE {$field} IS NULL";
        $this->connection
          ->queryDirect($sql);
      }
      
      $spec['not null'] = TRUE;
      $field_sql = $this
        ->createFieldSql($table, $field, $spec, TRUE);
      $this->connection
        ->queryDirect("ALTER TABLE {{$table}} ALTER COLUMN {$field_sql}");
      $this
        ->resetColumnInformation($table);
    }
    $this
      ->recreateTableKeys($table, $keys_new);
    if (isset($spec['description'])) {
      $this->connection
        ->queryDirect($this
        ->createCommentSql($spec['description'], $table, $field));
    }
  }
  
  public function dropField($table, $field) {
    if (!$this
      ->fieldExists($table, $field)) {
      return FALSE;
    }
    $primary_key_fields = $this
      ->findPrimaryKeyColumns($table);
    if (in_array($field, $primary_key_fields)) {
      
      $this
        ->cleanUpPrimaryKey($table);
      $this
        ->createTechnicalPrimaryColumn($table);
    }
    
    $this
      ->dropFieldRelatedObjects($table, $field);
    
    if ($this
      ->getComment($table, $field) !== FALSE) {
      $this->connection
        ->queryDirect($this
        ->deleteCommentSql($table, $field));
    }
    $this->connection
      ->query('ALTER TABLE {' . $table . '} DROP COLUMN ' . $field);
    $this
      ->resetColumnInformation($table);
    return TRUE;
  }
  
  public function fieldSetDefault($table, $field, $default) {
    @trigger_error('fieldSetDefault() is deprecated in drupal:8.7.0 and will be removed before drupal:9.0.0. Instead, call ::changeField() passing a full field specification. See https://www.drupal.org/node/2999035', E_USER_DEPRECATED);
    if (!$this
      ->fieldExists($table, $field)) {
      throw new SchemaObjectDoesNotExistException(t("Cannot set default value of field %table.%field: field doesn't exist.", [
        '%table' => $table,
        '%field' => $field,
      ]));
    }
    $default = $this
      ->escapeDefaultValue($default);
    
    try {
      $this
        ->fieldSetNoDefault($table, $field);
    } catch (\Exception $e) {
    }
    
    $this->connection
      ->query('ALTER TABLE [{' . $table . '}] ADD CONSTRAINT {' . $table . '}_' . $field . '_df DEFAULT ' . $default . ' FOR [' . $field . ']');
    $this
      ->resetColumnInformation($table);
  }
  
  public function fieldSetNoDefault($table, $field) {
    @trigger_error('fieldSetNoDefault() is deprecated in drupal:8.7.0 and will be removed before drupal:9.0.0. Instead, call ::changeField() passing a full field specification. See https://www.drupal.org/node/2999035', E_USER_DEPRECATED);
    if (!$this
      ->fieldExists($table, $field)) {
      throw new SchemaObjectDoesNotExistException(t("Cannot remove default value of field %table.%field: field doesn't exist.", [
        '%table' => $table,
        '%field' => $field,
      ]));
    }
    $prefixInfo = $this
      ->getPrefixInfo($table, TRUE);
    $constraint_name = $prefixInfo['table'] . '_' . $field . '_df';
    $this
      ->dropConstraint($table, $constraint_name, FALSE);
  }
  
  public function indexExists($table, $name) {
    $prefixInfo = $this
      ->getPrefixInfo($table, TRUE);
    return (bool) $this->connection
      ->query('SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(:table) AND name = :name', [
      ':table' => $prefixInfo['table'],
      ':name' => $name . '_idx',
    ])
      ->fetchField();
  }
  
  public function addPrimaryKey($table, $fields) {
    if (!$this
      ->tableExists($table)) {
      throw new SchemaObjectDoesNotExistException(t("Cannot add primary key to table %table: table doesn't exist.", [
        '%table' => $table,
      ]));
    }
    if ($primary_key_name = $this
      ->primaryKeyName($table)) {
      if ($this
        ->isTechnicalPrimaryKey($primary_key_name)) {
        
        $this->connection
          ->queryDirect('ALTER TABLE {' . $table . '} DROP CONSTRAINT [' . $primary_key_name . ']');
        $this
          ->resetColumnInformation($table);
        $this
          ->cleanUpTechnicalPrimaryColumn($table);
      }
      else {
        throw new SchemaObjectExistsException(t("Cannot add primary key to table %table: primary key already exists.", [
          '%table' => $table,
        ]));
      }
    }
    
    if ($this
      ->tableHasXmlIndex($table)) {
      $this
        ->createPrimaryKey($table, $fields, self::XML_INDEX_BYTES);
    }
    else {
      $this
        ->createPrimaryKey($table, $fields);
    }
    return TRUE;
  }
  
  public function dropPrimaryKey($table) {
    if (!$this
      ->primaryKeyName($table)) {
      return FALSE;
    }
    $this
      ->cleanUpPrimaryKey($table);
    return TRUE;
  }
  
  protected function findPrimaryKeyColumns($table) {
    if (!$this
      ->tableExists($table)) {
      return FALSE;
    }
    
    $prefixInfo = $this
      ->getPrefixInfo($table, TRUE);
    $query = "SELECT column_name FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC " . "INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU " . "ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND " . "TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME AND " . "KU.table_name=:table AND column_name != '__pk' AND column_name != '__pkc' " . "ORDER BY KU.ORDINAL_POSITION";
    $result = $this->connection
      ->query($query, [
      ':table' => $prefixInfo['table'],
    ])
      ->fetchAllAssoc('column_name');
    return array_keys($result);
  }
  
  public function addUniqueKey($table, $name, $fields) {
    if (!$this
      ->tableExists($table)) {
      throw new SchemaObjectDoesNotExistException(t("Cannot add unique key %name to table %table: table doesn't exist.", [
        '%table' => $table,
        '%name' => $name,
      ]));
    }
    if ($this
      ->uniqueKeyExists($table, $name)) {
      throw new SchemaObjectExistsException(t("Cannot add unique key %name to table %table: unique key already exists.", [
        '%table' => $table,
        '%name' => $name,
      ]));
    }
    $this
      ->createTechnicalPrimaryColumn($table);
    
    $column_expression = [];
    foreach ($fields as $field) {
      if (is_array($field)) {
        $column_expression[] = 'SUBSTRING(CAST(' . $field[0] . ' AS varbinary(max)),1,' . $field[1] . ')';
      }
      else {
        $column_expression[] = 'CAST(' . $field . ' AS varbinary(max))';
      }
    }
    $column_expression = implode(' + ', $column_expression);
    
    $this->connection
      ->query("ALTER TABLE {{$table}} ADD __unique_{$name} AS CAST(HashBytes('MD4', COALESCE({$column_expression}, CAST(" . self::TECHNICAL_PK_COLUMN_NAME . " AS varbinary(max)))) AS varbinary(16))");
    $this->connection
      ->query("CREATE UNIQUE INDEX {$name}_unique ON {{$table}} (__unique_{$name})");
    $this
      ->resetColumnInformation($table);
  }
  
  public function dropUniqueKey($table, $name) {
    if (!$this
      ->uniqueKeyExists($table, $name)) {
      return FALSE;
    }
    $this->connection
      ->query("DROP INDEX {$name}_unique ON {{$table}}");
    $this->connection
      ->query("ALTER TABLE {{$table}} DROP COLUMN __unique_{$name}");
    $this
      ->resetColumnInformation($table);
    
    $this
      ->cleanUpTechnicalPrimaryColumn($table);
    return TRUE;
  }
  
  public function addIndex($table, $name, $fields, array $spec = []) {
    if (!$this
      ->tableExists($table)) {
      throw new SchemaObjectDoesNotExistException(t("Cannot add index %name to table %table: table doesn't exist.", [
        '%table' => $table,
        '%name' => $name,
      ]));
    }
    if ($this
      ->indexExists($table, $name)) {
      throw new SchemaObjectExistsException(t("Cannot add index %name to table %table: index already exists.", [
        '%table' => $table,
        '%name' => $name,
      ]));
    }
    $xml_field = NULL;
    foreach ($fields as $field) {
      if (isset($info['columns'][$field]['type']) && $info['columns'][$field]['type'] == 'xml') {
        $xml_field = $field;
        break;
      }
    }
    $sql = $this
      ->createIndexSql($table, $name, $fields, $xml_field);
    $pk_fields = $this
      ->introspectPrimaryKeyFields($table);
    $size = $this
      ->calculateClusteredIndexRowSizeBytes($table, $pk_fields, TRUE);
    if (!empty($xml_field)) {
      
      if ($size > self::XML_INDEX_BYTES) {
        
        $this
          ->compressPrimaryKeyIndex($table, self::XML_INDEX_BYTES);
      }
      $this->connection
        ->query($sql);
      $this
        ->resetColumnInformation($table);
    }
    elseif ($size <= self::NONCLUSTERED_INDEX_BYTES) {
      $this->connection
        ->query($sql);
      $this
        ->resetColumnInformation($table);
    }
    
  }
  
  public function dropIndex($table, $name) {
    if (!$this
      ->indexExists($table, $name)) {
      return FALSE;
    }
    $expand = FALSE;
    if (($index = $this
      ->tableHasXmlIndex($table)) && $index == $name . '_idx') {
      $expand = TRUE;
    }
    $this->connection
      ->query('DROP INDEX ' . $name . '_idx ON [{' . $table . '}]');
    $this
      ->resetColumnInformation($table);
    
    if ($expand) {
      $this
        ->compressPrimaryKeyIndex($table);
    }
    return TRUE;
  }
  
  public function introspectIndexSchema($table) {
    if (!$this
      ->tableExists($table)) {
      throw new SchemaObjectDoesNotExistException("The table {$table} doesn't exist.");
    }
    $index_schema = [
      'primary key' => $this
        ->findPrimaryKeyColumns($table),
      'unique keys' => [],
      'indexes' => [],
    ];
    $column_information = $this
      ->queryColumnInformation($table);
    foreach ($column_information['indexes'] as $key => $values) {
      if ($values['is_primary_key'] !== 1 && $values['data_space_id'] == 1 && $values['is_unique'] == 0) {
        foreach ($values['columns'] as $num => $stats) {
          $index_schema['indexes'][substr($key, 0, -4)][] = $stats['name'];
        }
      }
    }
    foreach ($column_information['columns'] as $name => $spec) {
      if (substr($name, 0, 9) == '__unique_' && $column_information['indexes'][substr($name, 9) . '_unique']['is_unique'] == 1) {
        $definition = $spec['definition'];
        $matches = [];
        preg_match_all("/CONVERT\\(\\[varbinary\\]\\(max\\),\\[([a-zA-Z0-9_]*)\\]/", $definition, $matches);
        foreach ($matches[1] as $match) {
          if ($match != '__pk') {
            $index_schema['unique keys'][substr($name, 9)][] = $match;
          }
        }
      }
    }
    return $index_schema;
  }
  
  public function changeField($table, $field, $field_new, $spec, $keys_new = []) {
    if (!$this
      ->fieldExists($table, $field)) {
      throw new SchemaObjectDoesNotExistException(t("Cannot change the definition of field %table.%name: field doesn't exist.", [
        '%table' => $table,
        '%name' => $field,
      ]));
    }
    if ($field != $field_new && $this
      ->fieldExists($table, $field_new)) {
      throw new SchemaObjectExistsException(t("Cannot rename field %table.%name to %name_new: target field already exists.", [
        '%table' => $table,
        '%name' => $field,
        '%name_new' => $field_new,
      ]));
    }
    if (isset($keys_new['primary key']) && in_array($field_new, $keys_new['primary key'], TRUE)) {
      $this
        ->ensureNotNullPrimaryKey($keys_new['primary key'], [
        $field_new => $spec,
      ]);
    }
    
    $drop_field_comment = FALSE;
    if ($this
      ->getComment($table, $field) !== FALSE) {
      $drop_field_comment = TRUE;
    }
    
    
    $transaction = $this->connection
      ->startTransaction();
    
    $spec = $this
      ->processField($spec);
    
    $primary_key_fields = $this
      ->findPrimaryKeyColumns($table);
    if (in_array($field, $primary_key_fields)) {
      
      $this
        ->cleanUpPrimaryKey($table);
    }
    
    $unique_key = $this
      ->uniqueKeyExists($table, $field);
    
    $this
      ->dropFieldRelatedObjects($table, $field);
    if ($drop_field_comment) {
      $this->connection
        ->queryDirect($this
        ->deleteCommentSql($table, $field));
    }
    $prefixInfo = $this
      ->getPrefixInfo($table, TRUE);
    
    $this->connection
      ->queryDirect('EXEC sp_rename :old, :new, :type', [
      ':old' => $prefixInfo['table'] . '.' . $field,
      ':new' => $field . '_old',
      ':type' => 'COLUMN',
    ]);
    $this
      ->resetColumnInformation($table);
    
    $fixnull = FALSE;
    if (!empty($spec['not null'])) {
      $fixnull = TRUE;
      $spec['not null'] = FALSE;
    }
    
    $this
      ->addField($table, $field_new, $spec);
    
    if ($spec['type'] != 'serial') {
      $new_data_type = $this
        ->createDataType($table, $field_new, $spec);
      
      $sql = "UPDATE {{$table}} SET {$field_new}=CAST({$field}_old AS {$new_data_type})";
      $this->connection
        ->queryDirect($sql);
      $this
        ->resetColumnInformation($table);
    }
    
    if ($fixnull === TRUE) {
      
      if (!empty($spec['default'])) {
        $default_expression = $this
          ->defaultValueExpression($spec['sqlsrv_type'], $spec['default']);
        $sql = "UPDATE {{$table}} SET {$field_new} = {$default_expression} WHERE {$field_new} IS NULL";
        $this->connection
          ->queryDirect($sql);
        $this
          ->resetColumnInformation($table);
      }
      
      $spec['not null'] = TRUE;
      $field_sql = $this
        ->createFieldSql($table, $field_new, $spec, TRUE);
      $sql = "ALTER TABLE {{$table}} ALTER COLUMN {$field_sql}";
      $this->connection
        ->queryDirect($sql);
      $this
        ->resetColumnInformation($table);
    }
    
    if (in_array($field, $primary_key_fields) && (!isset($keys_new['primary keys']) || empty($keys_new['primary keys']))) {
      
      if ($field !== $field_new) {
        $primary_key_fields[array_search($field, $primary_key_fields)] = $field_new;
      }
      $keys_new['primary key'] = $primary_key_fields;
    }
    
    if ($unique_key && (!isset($keys_new['unique keys']) || !in_array($field_new, $keys_new['unique keys']))) {
      $keys_new['unique keys'][$field] = [
        $field_new,
      ];
    }
    
    $this
      ->dropField($table, $field . '_old');
    
    $this
      ->recreateTableKeys($table, $keys_new);
  }
  
  public function __construct($connection) {
    parent::__construct($connection);
    $options = $connection
      ->getConnectionOptions();
    if (isset($options['schema'])) {
      $this->defaultSchema = $options['schema'];
    }
    $this->cacheSchema = $options['cache_schema'] ?? FALSE;
  }
  
  public function tableExists($table) {
    if (empty($table)) {
      return FALSE;
    }
    
    $query = NULL;
    $prefixInfo = $this
      ->getPrefixInfo($table, TRUE);
    $args = [];
    if ($this->connection
      ->isTemporaryTable($table)) {
      $query = "SELECT 1 FROM tempdb.sys.tables WHERE [object_id] = OBJECT_ID(:table)";
      $args = [
        ':table' => 'tempdb.[' . $this
          ->getDefaultSchema() . '].[' . $prefixInfo['table'] . ']',
      ];
    }
    else {
      $query = "SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE [table_name] = :table";
      $args = [
        ':table' => $prefixInfo['table'],
      ];
    }
    return (bool) $this->connection
      ->queryDirect($query, $args)
      ->fetchField();
  }
  
  public function drupalSpecificFunctions() {
    $functions = [
      'SUBSTRING',
      'SUBSTRING_INDEX',
      'GREATEST',
      'MD5',
      'LPAD',
      'REGEXP',
      'IF',
      'CONNECTION_ID',
    ];
    return $functions;
  }
  
  public function getDefaultSchema() {
    if (!isset($this->defaultSchema)) {
      $result = $this->connection
        ->queryDirect("SELECT SCHEMA_NAME()")
        ->fetchField();
      $this->defaultSchema = $result;
    }
    return $this->defaultSchema;
  }
  
  public function queryColumnInformation($table) {
    if (empty($table) || !$this
      ->tableExists($table)) {
      return [];
    }
    if ($this->cacheSchema && isset($this->columnInformation[$table])) {
      return $this->columnInformation[$table];
    }
    $table_info = $this
      ->getPrefixInfo($table);
    
    if ($this->connection
      ->isTemporaryTable($table)) {
      throw new \Exception('Temporary table introspection is not supported.');
    }
    $info = [];
    
    $sql = "SELECT sysc.name, sysc.max_length, sysc.precision, sysc.collation_name,\n      sysc.is_nullable, sysc.is_ansi_padded, sysc.is_identity, sysc.is_computed, TYPE_NAME(sysc.user_type_id) as type,\n      syscc.definition, sm.[text] as default_value\n      FROM sys.columns AS sysc\n      INNER JOIN sys.syscolumns AS sysc2 ON sysc.object_id = sysc2.id and sysc.name = sysc2.name\n      LEFT JOIN sys.computed_columns AS syscc ON sysc.object_id = syscc.object_id AND sysc.name = syscc.name\n      LEFT JOIN sys.syscomments sm ON sm.id = sysc2.cdefault\n      WHERE sysc.object_id = OBJECT_ID(:table)";
    $args = [
      ':table' => $table_info['schema'] . '.' . $table_info['table'],
    ];
    $result = $this->connection
      ->queryDirect($sql, $args);
    foreach ($result as $column) {
      if ($column->type == 'varbinary') {
        $info['blobs'][$column->name] = TRUE;
      }
      $info['columns'][$column->name] = (array) $column;
      
      if (!(isset($column->name[1]) && substr($column->name, 0, 2) == "__")) {
        $info['columns_clean'][$column->name] = (array) $column;
      }
    }
    
    $column_names = array_keys($info['columns']);
    $column_regex = implode('|', $column_names);
    foreach ($info['columns'] as &$column) {
      $dependencies = [];
      if (!empty($column['definition'])) {
        $matches = [];
        if (preg_match_all("/\\[[{$column_regex}\\]]*\\]/", $column['definition'], $matches) > 0) {
          $dependencies = array_map(function ($m) {
            return trim($m, "[]");
          }, array_shift($matches));
        }
      }
      $column['dependencies'] = array_flip($dependencies);
    }
    
    $result = $this->connection
      ->queryDirect('SELECT name FROM sys.identity_columns WHERE object_id = OBJECT_ID(:table)', [
      ':table' => $table_info['schema'] . '.' . $table_info['table'],
    ]);
    unset($column);
    $info['identities'] = [];
    $info['identity'] = NULL;
    foreach ($result as $column) {
      $info['identities'][$column->name] = $column->name;
      $info['identity'] = $column->name;
    }
    
    $result = $this->connection
      ->queryDirect("select tab.[name]  as [table_name],\n         idx.[name]  as [index_name],\n         allc.[name] as [column_name],\n         idx.[type_desc],\n         idx.[is_unique],\n         idx.[data_space_id],\n         idx.[ignore_dup_key],\n         idx.[is_primary_key],\n         idx.[is_unique_constraint],\n         idx.[fill_factor],\n         idx.[is_padded],\n         idx.[is_disabled],\n         idx.[is_hypothetical],\n         idx.[allow_row_locks],\n         idx.[allow_page_locks],\n         idxc.[is_descending_key],\n         idxc.[is_included_column],\n         idxc.[index_column_id],\n         idxc.[key_ordinal]\n    FROM sys.[tables] as tab\n    INNER join sys.[indexes]       idx  ON tab.[object_id] =  idx.[object_id]\n    INNER join sys.[index_columns] idxc ON idx.[object_id] = idxc.[object_id] and  idx.[index_id]  = idxc.[index_id]\n    INNER join sys.[all_columns]   allc ON tab.[object_id] = allc.[object_id] and idxc.[column_id] = allc.[column_id]\n    WHERE tab.object_id = OBJECT_ID(:table)\n    ORDER BY tab.[name], idx.[index_id], idxc.[index_column_id]\n                    ", [
      ':table' => $table_info['schema'] . '.' . $table_info['table'],
    ]);
    foreach ($result as $index_column) {
      if (!isset($info['indexes'][$index_column->index_name])) {
        $ic = clone $index_column;
        
        unset($ic->column_name);
        unset($ic->index_column_id);
        unset($ic->is_descending_key);
        unset($ic->table_name);
        unset($ic->key_ordinal);
        $info['indexes'][$index_column->index_name] = (array) $ic;
        if ($index_column->is_primary_key) {
          $info['primary_key_index'] = $ic->index_name;
        }
      }
      $index =& $info['indexes'][$index_column->index_name];
      $index['columns'][$index_column->key_ordinal] = [
        'name' => $index_column->column_name,
        'is_descending_key' => $index_column->is_descending_key,
        'key_ordinal' => $index_column->key_ordinal,
      ];
      
      $info['columns'][$index_column->column_name]['indexes'][] = $index_column->index_name;
      if (isset($info['columns_clean'][$index_column->column_name])) {
        $info['columns_clean'][$index_column->column_name]['indexes'][] = $index_column->index_name;
      }
    }
    if ($this->cacheSchema) {
      $this->columnInformation[$table] = $info;
    }
    return $info;
  }
  
  public function resetColumnInformation($table) {
    unset($this->columnInformation[$table]);
  }
  
  public function createTable($name, $table) {
    
    $transaction = $this->connection
      ->startTransaction();
    parent::createTable($name, $table);
    
    if (!empty($table['primary key']) && is_array($table['primary key'])) {
      $this
        ->ensureNotNullPrimaryKey($table['primary key'], $table['fields']);
      $this
        ->createPrimaryKey($name, $table['primary key']);
    }
    
    if (isset($table['unique keys']) && is_array($table['unique keys'])) {
      foreach ($table['unique keys'] as $key_name => $key) {
        $this
          ->addUniqueKey($name, $key_name, $key);
      }
    }
    unset($transaction);
    
    if (isset($table['indexes']) && is_array($table['indexes'])) {
      foreach ($table['indexes'] as $key_name => $key) {
        try {
          $this
            ->addIndex($name, $key_name, $key);
        } catch (\Exception $e) {
          
          if ($this
            ->tableExists('watchdog')) {
            watchdog_exception('database', $e);
          }
        }
      }
    }
  }
  
  public function removeSqlComments($sql, &$comments = NULL) {
    $sqlComments = '@(([\'"]).*?[^\\\\]\\2)|((?:\\#|--).*?$|/\\*(?:[^/*]|/(?!\\*)|\\*(?!/)|(?R))*\\*\\/)\\s*|(?<=;)\\s+@ms';
    
    $uncommentedSQL = trim(preg_replace($sqlComments, '$1', $sql));
    if (is_array($comments)) {
      preg_match_all($sqlComments, $sql, $comments);
      $comments = array_filter($comments[3]);
    }
    return $uncommentedSQL;
  }
  
  public function userOptions() {
    $result = $this->connection
      ->queryDirect('DBCC UserOptions')
      ->fetchAllKeyed();
    return $result;
  }
  
  public function engineVersion() {
    if (!isset($this->engineVersion)) {
      $this->engineVersion = $this->connection
        ->queryDirect(<<<EOF
          SELECT CONVERT (varchar,SERVERPROPERTY('productversion')) AS VERSION,
          CONVERT (varchar,SERVERPROPERTY('productlevel')) AS LEVEL,
          CONVERT (varchar,SERVERPROPERTY('edition')) AS EDITION
EOF
)
        ->fetchAssoc();
    }
    return $this->engineVersion;
  }
  
  public function engineVersionNumber() {
    $version = $this
      ->EngineVersion();
    $start = strpos($version['VERSION'], '.');
    return intval(substr($version['VERSION'], 0, $start));
  }
  
  public function functionExists($function) {
    
    return $this->connection
      ->queryDirect("SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('" . $function . "') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT', N'AF')")
      ->fetchField() !== FALSE;
  }
  
  public function clrEnabled() {
    return $this->connection
      ->queryDirect("SELECT CONVERT(int, [value]) as [enabled] FROM sys.configurations WHERE name = 'clr enabled'")
      ->fetchField() !== 1;
  }
  
  private function isVariableLengthType($type) {
    $types = [
      'nvarchar' => TRUE,
      'ntext' => TRUE,
      'varchar' => TRUE,
      'varbinary' => TRUE,
      'image' => TRUE,
    ];
    return isset($types[$type]);
  }
  
  private function loadFieldsSpec(array $fields, $table) {
    $result = [];
    $info = $this
      ->queryColumnInformation($table);
    foreach ($fields as $field) {
      $result[$field] = $info['columns'][$field];
    }
    return $result;
  }
  
  public function calculateClusteredIndexRowSizeBytes($table, $fields, $unique = TRUE) {
    
    $info = $this
      ->queryColumnInformation($table);
    
    $num_cols = count($fields);
    $num_variable_cols = 0;
    $max_var_size = 0;
    $max_fixed_size = 0;
    foreach ($fields as $field) {
      if ($this
        ->isVariableLengthType($info['columns'][$field]['type'])) {
        $num_variable_cols++;
        $max_var_size += $info['columns'][$field]['max_length'];
      }
      else {
        $max_fixed_size += $info['columns'][$field]['max_length'];
      }
    }
    
    if (!$unique) {
      $num_cols++;
      $num_variable_cols++;
      $max_var_size += 4;
    }
    
    $null_bitmap = 2 + ($num_cols + 7) / 8;
    
    $variable_data_size = empty($num_variable_cols) ? 0 : 2 + $num_variable_cols * 2 + $max_var_size;
    
    $row_size = $max_fixed_size + $variable_data_size + $null_bitmap + 4;
    return $row_size;
  }
  
  protected function recreatePrimaryKey($table, $fields) {
    
    $this
      ->cleanUpPrimaryKey($table);
    $this
      ->createPrimaryKey($table, $fields);
  }
  
  private function createPrimaryKey($table, $fields, $limit = 900) {
    
    $csv_fields = $this
      ->createKeySql($fields);
    $size = $this
      ->calculateClusteredIndexRowSizeBytes($table, $this
      ->createKeySql($fields, TRUE));
    $result = [];
    $index = FALSE;
    
    $nullable = FALSE;
    $field_specs = $this
      ->loadFieldsSpec($fields, $table);
    foreach ($field_specs as $field) {
      if ($field['is_nullable'] == TRUE) {
        $nullable = TRUE;
        break;
      }
    }
    if ($nullable || $size >= $limit) {
      
      $result[] = self::COMPUTED_PK_COLUMN_NAME . " AS (CONVERT(VARCHAR(32), HASHBYTES('MD5', CONCAT('',{$csv_fields})), 2)) PERSISTED NOT NULL";
      $result[] = "CONSTRAINT {{$table}}_pkey PRIMARY KEY CLUSTERED (" . self::COMPUTED_PK_COLUMN_NAME . ")";
      $index = TRUE;
    }
    else {
      $result[] = "CONSTRAINT {{$table}}_pkey PRIMARY KEY CLUSTERED ({$csv_fields})";
    }
    $this->connection
      ->queryDirect('ALTER TABLE [{' . $table . '}] ADD ' . implode(' ', $result));
    $this
      ->resetColumnInformation($table);
    
    if ($index) {
      $this
        ->addIndex($table, self::COMPUTED_PK_COLUMN_INDEX, $fields);
    }
  }
  
  private function createTechnicalPrimaryKeyIndexSql($table) {
    $result = [];
    $result[] = self::TECHNICAL_PK_COLUMN_NAME . " UNIQUEIDENTIFIER DEFAULT NEWID() NOT NULL";
    $result[] = "CONSTRAINT {{$table}}_pkey_technical PRIMARY KEY CLUSTERED (" . self::TECHNICAL_PK_COLUMN_NAME . ")";
    return implode(' ', $result);
  }
  
  protected function createTableSql($name, array $table) {
    $statements = [];
    $sql_fields = [];
    foreach ($table['fields'] as $field_name => $field) {
      $sql_fields[] = $this
        ->createFieldSql($name, $field_name, $this
        ->processField($field));
      if (isset($field['description'])) {
        $statements[] = $this
          ->createCommentSQL($field['description'], $name, $field_name);
      }
    }
    $sql = "CREATE TABLE {{$name}} (" . PHP_EOL;
    $sql .= implode("," . PHP_EOL, $sql_fields);
    $sql .= PHP_EOL . ")";
    array_unshift($statements, $sql);
    if (!empty($table['description'])) {
      $statements[] = $this
        ->createCommentSql($table['description'], $name);
    }
    return $statements;
  }
  
  protected function createFieldSql($table, $name, $spec, $skip_checks = FALSE) {
    $sql = $this->connection
      ->escapeField($name) . ' ';
    $sql .= $this
      ->createDataType($table, $name, $spec);
    $sqlsrv_type = $spec['sqlsrv_type'];
    $sqlsrv_type_native = $spec['sqlsrv_type_native'];
    $is_text = in_array($sqlsrv_type_native, [
      'char',
      'varchar',
      'text',
      'nchar',
      'nvarchar',
      'ntext',
    ]);
    if ($is_text === TRUE) {
      
      if (isset($spec['binary'])) {
        $default_collation = $this
          ->getCollation();
        if ($spec['binary'] === TRUE) {
          $sql .= ' COLLATE ' . preg_replace("/_C[IS]_/", "_CS_", $default_collation);
        }
        elseif ($spec['binary'] === FALSE) {
          $sql .= ' COLLATE ' . preg_replace("/_C[IS]_/", "_CI_", $default_collation);
        }
      }
    }
    if (isset($spec['not null']) && $spec['not null']) {
      $sql .= ' NOT NULL';
    }
    if (!$skip_checks) {
      if (isset($spec['default'])) {
        $default = $this
          ->defaultValueExpression($sqlsrv_type, $spec['default']);
        $sql .= " CONSTRAINT {{$table}_{$name}_df} DEFAULT {$default}";
      }
      if (!empty($spec['identity'])) {
        $sql .= ' IDENTITY';
      }
      if (!empty($spec['unsigned'])) {
        $sql .= ' CHECK (' . $this->connection
          ->escapeField($name) . ' >= 0)';
      }
    }
    return $sql;
  }
  
  protected function createDataType($table, $name, $spec) {
    $sqlsrv_type = $spec['sqlsrv_type'];
    $sqlsrv_type_native = $spec['sqlsrv_type_native'];
    $lengthable = in_array($sqlsrv_type_native, [
      'char',
      'varchar',
      'nchar',
      'nvarchar',
    ]);
    if (!empty($spec['length']) && $lengthable) {
      $length = $spec['length'];
      if (is_int($length) && $this
        ->isUtf8()) {
        
        $length *= 3;
      }
      return $sqlsrv_type_native . '(' . $length . ')';
    }
    elseif (in_array($sqlsrv_type_native, [
      'numeric',
      'decimal',
    ]) && isset($spec['precision']) && isset($spec['scale'])) {
      
      if ($spec['precision'] > 38) {
        
        \Drupal::logger('sqlsrv')
          ->warning("Field '@field' in table '@table' has had it's precision dropped from @precision to 38", [
          '@field' => $name,
          '@table' => $table,
          '@precision' => $spec['precision'],
        ]);
        $spec['precision'] = 38;
      }
      return $sqlsrv_type_native . '(' . $spec['precision'] . ', ' . $spec['scale'] . ')';
    }
    else {
      return $sqlsrv_type;
    }
  }
  
  private function defaultValueExpression($sqlsr_type, $default) {
    
    $result = is_string($default) ? $this->connection
      ->quote($default) : $default;
    if (Utils::GetMSSQLType($sqlsr_type) == 'varbinary') {
      $default = addslashes($default);
      $result = "CONVERT({$sqlsr_type}, '{$default}')";
    }
    return $result;
  }
  
  protected function createKeySql(array $fields, $as_array = FALSE) {
    $ret = [];
    foreach ($fields as $field) {
      if (is_array($field)) {
        $ret[] = $field[0];
      }
      else {
        $ret[] = $field;
      }
    }
    if ($as_array) {
      return $ret;
    }
    return implode(', ', $ret);
  }
  
  protected function createIndexSql($table, $name, array $fields, $xml_field) {
    
    $info = $this
      ->queryColumnInformation($table);
    
    $fields = $this
      ->createKeySql($fields, TRUE);
    
    if (!empty($xml_field) && isset($fields[1])) {
      throw new \Exception("Cannot include an XML field on a multiple column index.");
    }
    
    if ($xml_field && $this
      ->tableHasXmlIndex($table)) {
      throw new \Exception("Only one primary clustered XML index is allowed per table.");
    }
    if (empty($xml_field)) {
      $fields_csv = implode(', ', $fields);
      return "CREATE INDEX {$name}_idx ON [{{$table}}] ({$fields_csv})";
    }
    else {
      return "CREATE PRIMARY XML INDEX {$name}_idx ON [{{$table}}] ({$xml_field})";
    }
  }
  
  protected function processField($field) {
    $field['size'] = $field['size'] ?? 'normal';
    if (isset($field['type']) && ($field['type'] == 'serial' || $field['type'] == 'int') && isset($field['unsigned']) && $field['unsigned'] === TRUE && $field['size'] == 'normal') {
      $field['size'] = 'big';
    }
    
    if (isset($field['sqlsrv_type'])) {
      $field['sqlsrv_type'] = mb_strtolower($field['sqlsrv_type']);
    }
    else {
      $map = $this
        ->getFieldTypeMap();
      $field['sqlsrv_type'] = $map[$field['type'] . ':' . $field['size']];
    }
    $field['sqlsrv_type_native'] = Utils::GetMSSQLType($field['sqlsrv_type']);
    if (isset($field['type']) && $field['type'] == 'serial') {
      $field['identity'] = TRUE;
    }
    return $field;
  }
  
  public function compressPrimaryKeyIndex($table, $limit = 900) {
    
    $primary_key_fields = $this
      ->introspectPrimaryKeyFields($table);
    
    $transaction = $this->connection
      ->startTransaction();
    
    $this
      ->cleanUpPrimaryKey($table);
    
    $this
      ->createPrimaryKey($table, $primary_key_fields, $limit);
  }
  
  public function getSizeInfo() {
    $sql = <<<EOF
      SELECT
    DB_NAME(db.database_id) DatabaseName,
    (CAST(mfrows.RowSize AS FLOAT)*8)/1024 RowSizeMB,
    (CAST(mflog.LogSize AS FLOAT)*8)/1024 LogSizeMB,
    (CAST(mfstream.StreamSize AS FLOAT)*8)/1024 StreamSizeMB,
    (CAST(mftext.TextIndexSize AS FLOAT)*8)/1024 TextIndexSizeMB
FROM sys.databases db
    LEFT JOIN (SELECT database_id, SUM(size) RowSize FROM sys.master_files WHERE type = 0 GROUP BY database_id, type) mfrows ON mfrows.database_id = db.database_id
    LEFT JOIN (SELECT database_id, SUM(size) LogSize FROM sys.master_files WHERE type = 1 GROUP BY database_id, type) mflog ON mflog.database_id = db.database_id
    LEFT JOIN (SELECT database_id, SUM(size) StreamSize FROM sys.master_files WHERE type = 2 GROUP BY database_id, type) mfstream ON mfstream.database_id = db.database_id
    LEFT JOIN (SELECT database_id, SUM(size) TextIndexSize FROM sys.master_files WHERE type = 4 GROUP BY database_id, type) mftext ON mftext.database_id = db.database_id
    WHERE DB_NAME(db.database_id) = :database
EOF;
    
    $options = $this->connection
      ->getConnectionOptions();
    $database = $options['database'];
    return $this->connection
      ->query($sql, [
      ':database' => $database,
    ])
      ->fetchObject();
  }
  
  public function getDatabaseInfo() {
    static $result;
    if (isset($result)) {
      return $result;
    }
    $sql = <<<EOF
      select name
        , db.snapshot_isolation_state
        , db.snapshot_isolation_state_desc
        , db.is_read_committed_snapshot_on
        , db.recovery_model
        , db.recovery_model_desc
        , db.collation_name
    from sys.databases db
    WHERE DB_NAME(db.database_id) = :database
EOF;
    
    $options = $this->connection
      ->getConnectionOptions();
    $database = $options['database'];
    $result = $this->connection
      ->queryDirect($sql, [
      ':database' => $database,
    ])
      ->fetchObject();
    return $result;
  }
  
  public function getCollation($table = NULL, $column = NULL) {
    
    if (empty($table) && empty($column)) {
      
      $options = $this->connection
        ->getConnectionOptions();
      $database = $options['database'];
      if (!empty($database)) {
        
        $sql = "SELECT CONVERT (varchar(50), DATABASEPROPERTYEX('{$database}', 'collation'))";
        return $this->connection
          ->queryDirect($sql)
          ->fetchField();
      }
      else {
        
        $sql = "SELECT SERVERPROPERTY ('collation') as collation";
        return $this->connection
          ->queryDirect($sql)
          ->fetchField();
      }
    }
    $sql = <<<EOF
      SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, COLLATION_NAME, DATA_TYPE
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = ':schema'
        AND TABLE_NAME = ':table'
        AND COLUMN_NAME = ':column'
EOF;
    $params = [];
    $params[':schema'] = $this
      ->getDefaultSchema();
    $params[':table'] = $table;
    $params[':column'] = $column;
    $result = $this->connection
      ->queryDirect($sql, $params)
      ->fetchObject();
    return $result->COLLATION_NAME;
  }
  
  public function introspectPrimaryKeyFields($table) {
    $data = $this
      ->queryColumnInformation($table);
    
    if (!isset($data['primary_key_index']) || !isset($data['indexes'][$data['primary_key_index']])) {
      return [];
    }
    $result = [];
    $index = $data['indexes'][$data['primary_key_index']];
    foreach ($index['columns'] as $column) {
      if ($column['name'] != self::COMPUTED_PK_COLUMN_NAME) {
        $result[$column['name']] = $column['name'];
      }
      
      $c = $data['columns'][$column['name']];
      
      foreach ($c['dependencies'] as $name => $order) {
        $result[$name] = $name;
      }
    }
    return $result;
  }
  
  protected function recreateTableKeys($table, $new_keys) {
    if (isset($new_keys['primary key'])) {
      $this
        ->addPrimaryKey($table, $new_keys['primary key']);
    }
    if (isset($new_keys['unique keys'])) {
      foreach ($new_keys['unique keys'] as $name => $fields) {
        $this
          ->addUniqueKey($table, $name, $fields);
      }
    }
    if (isset($new_keys['indexes'])) {
      foreach ($new_keys['indexes'] as $name => $fields) {
        $this
          ->addIndex($table, $name, $fields);
      }
    }
  }
  
  public function dropConstraint($table, $name, $check = TRUE) {
    
    if ($check) {
      
    }
    $sql = 'ALTER TABLE {' . $table . '} DROP CONSTRAINT [' . $name . ']';
    $this->connection
      ->query($sql);
    $this
      ->resetColumnInformation($table);
  }
  
  protected function dropFieldRelatedObjects($table, $field) {
    $prefixInfo = $this
      ->getPrefixInfo($table, TRUE);
    
    $sql = 'SELECT DISTINCT i.name FROM sys.columns c INNER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id INNER JOIN sys.indexes i ON i.object_id = ic.object_id AND i.index_id = ic.index_id WHERE i.is_primary_key = 0 AND i.is_unique_constraint = 0 AND c.object_id = OBJECT_ID(:table) AND c.name = :name';
    $indexes = $this->connection
      ->query($sql, [
      ':table' => $prefixInfo['table'],
      ':name' => $field,
    ]);
    foreach ($indexes as $index) {
      $this->connection
        ->query('DROP INDEX [' . $index->name . '] ON {' . $table . '}');
      $this
        ->resetColumnInformation($table);
    }
    
    $sql = 'SELECT DISTINCT cc.name FROM sys.columns c INNER JOIN sys.check_constraints cc ON cc.parent_object_id = c.object_id AND cc.parent_column_id = c.column_id WHERE c.object_id = OBJECT_ID(:table) AND c.name = :name';
    $constraints = $this->connection
      ->query($sql, [
      ':table' => $prefixInfo['table'],
      ':name' => $field,
    ]);
    foreach ($constraints as $constraint) {
      $this
        ->dropConstraint($table, $constraint->name, FALSE);
    }
    
    $sql = 'SELECT DISTINCT dc.name FROM sys.columns c INNER JOIN sys.default_constraints dc ON dc.parent_object_id = c.object_id AND dc.parent_column_id = c.column_id WHERE c.object_id = OBJECT_ID(:table) AND c.name = :name';
    $constraints = $this->connection
      ->query($sql, [
      ':table' => $prefixInfo['table'],
      ':name' => $field,
    ]);
    foreach ($constraints as $constraint) {
      $this
        ->dropConstraint($table, $constraint->name, FALSE);
    }
    
    if ($this
      ->uniqueKeyExists($table, $field)) {
      $this
        ->dropUniqueKey($table, $field);
    }
    
    $data = $this
      ->queryColumnInformation($table);
    if (isset($data['columns'][self::COMPUTED_PK_COLUMN_NAME]['dependencies'][$field])) {
      $this
        ->cleanUpPrimaryKey($table);
    }
  }
  
  protected function primaryKeyName($table) {
    $prefixInfo = $this
      ->getPrefixInfo($table, TRUE);
    $sql = 'SELECT name FROM sys.key_constraints WHERE parent_object_id = OBJECT_ID(:table) AND type = :type';
    return $this->connection
      ->query($sql, [
      ':table' => $prefixInfo['table'],
      ':type' => 'PK',
    ])
      ->fetchField();
  }
  
  protected function isTechnicalPrimaryKey($key_name) {
    return $key_name && preg_match('/_pkey_technical$/', $key_name);
  }
  
  protected function isUtf8() {
    $collation = $this
      ->getCollation();
    return stristr($collation, '_UTF8') !== FALSE;
  }
  
  protected function createTechnicalPrimaryColumn($table) {
    if (!$this
      ->fieldExists($table, self::TECHNICAL_PK_COLUMN_NAME)) {
      $this->connection
        ->query("ALTER TABLE {{$table}} ADD " . self::TECHNICAL_PK_COLUMN_NAME . " UNIQUEIDENTIFIER DEFAULT NEWID() NOT NULL");
      $this
        ->resetColumnInformation($table);
    }
  }
  
  protected function cleanUpPrimaryKey($table) {
    
    $existing_primary_key = $this
      ->primaryKeyName($table);
    if ($existing_primary_key !== FALSE) {
      $this
        ->dropConstraint($table, $existing_primary_key, FALSE);
    }
    
    if ($this
      ->fieldExists($table, self::COMPUTED_PK_COLUMN_NAME)) {
      
      $this
        ->dropIndex($table, self::COMPUTED_PK_COLUMN_INDEX);
      $this
        ->dropField($table, self::COMPUTED_PK_COLUMN_NAME);
    }
    
    $this
      ->cleanUpTechnicalPrimaryColumn($table);
  }
  
  protected function cleanUpTechnicalPrimaryColumn($table) {
    
    $prefixInfo = $this
      ->getPrefixInfo($table, TRUE);
    $sql = 'SELECT COUNT(*) FROM sys.indexes WHERE object_id = OBJECT_ID(:table) AND is_unique = 1 AND is_primary_key = 0';
    $args = [
      ':table' => $prefixInfo['table'],
    ];
    $unique_indexes = $this->connection
      ->query($sql, $args)
      ->fetchField();
    $primary_key_is_technical = $this
      ->isTechnicalPrimaryKey($this
      ->primaryKeyName($table));
    if (!$unique_indexes && !$primary_key_is_technical) {
      $this
        ->dropField($table, self::TECHNICAL_PK_COLUMN_NAME);
    }
  }
  
  protected function uniqueKeyExists($table, $name) {
    $prefixInfo = $this
      ->getPrefixInfo($table, TRUE);
    return (bool) $this->connection
      ->query('SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(:table) AND name = :name', [
      ':table' => $prefixInfo['table'],
      ':name' => $name . '_unique',
    ])
      ->fetchField();
  }
  
  public function tableHasXmlIndex($table) {
    $info = $this
      ->queryColumnInformation($table);
    if (isset($info['indexes']) && is_array($info['indexes'])) {
      foreach ($info['indexes'] as $name => $index) {
        if (strcasecmp($index['type_desc'], 'XML') == 0) {
          return $name;
        }
      }
    }
    return FALSE;
  }
  
  protected function deleteCommentSql($table = NULL, $column = NULL) {
    $schema = $this
      ->getDefaultSchema();
    $prefixInfo = $this
      ->getPrefixInfo($table, TRUE);
    $prefixed_table = $prefixInfo['table'];
    $sql = "EXEC sp_dropextendedproperty @name=N'MS_Description'";
    $sql .= ",@level0type = N'Schema', @level0name = '" . $schema . "'";
    if (isset($table)) {
      $sql .= ",@level1type = N'Table', @level1name = '{$prefixed_table}'";
      if (isset($column)) {
        $sql .= ",@level2type = N'Column', @level2name = '{$column}'";
      }
    }
    return $sql;
  }
  
  protected function createCommentSql($value, $table = NULL, $column = NULL) {
    $schema = $this
      ->getDefaultSchema();
    $value = $this
      ->prepareComment($value);
    $prefixInfo = $this
      ->getPrefixInfo($table, TRUE);
    $prefixed_table = $prefixInfo['table'];
    $sql = "EXEC sp_addextendedproperty @name=N'MS_Description', @value={$value}";
    $sql .= ",@level0type = N'Schema', @level0name = '{$schema}'";
    if (isset($table)) {
      $sql .= ",@level1type = N'Table', @level1name = '{$prefixed_table}'";
      if (isset($column)) {
        $sql .= ",@level2type = N'Column', @level2name = '{$column}'";
      }
    }
    return $sql;
  }
  
  public function getComment($table, $column = NULL) {
    $prefixInfo = $this
      ->getPrefixInfo($table, TRUE);
    $prefixed_table = $prefixInfo['table'];
    $schema = $this
      ->getDefaultSchema();
    $column_string = isset($column) ? "'Column','{$column}'" : "NULL,NULL";
    $sql = "SELECT value FROM fn_listextendedproperty ('MS_Description','Schema','{$schema}','Table','{$prefixed_table}',{$column_string})";
    $comment = $this->connection
      ->query($sql)
      ->fetchField();
    return $comment;
  }
}