Skip to content

SqlsrvDriver: column types are not detected #449

@jan-kratochvil

Description

@jan-kratochvil

I use SqlsrvDriver and column types are not detected.
I found the problem is in SqlsrvResult.php function getResultColumns(). It calls sqlsrv_field_metadata() which returns numbers, they are not parsed correctly by function Helpers::detectType() that expects some kind of string describing the column.
I made a simple fix in SqlsrvResult.php adding translating array according to MS doc https://learn.microsoft.com/en-us/sql/connect/php/sqlsrv-field-metadata?view=sql-server-ver16&redirectedfrom=MSDN

private $sqlTypes = array(
-5=>'SQL_BIGINT',
-2=>'SQL_BINARY',
-7=>'SQL_BIT',
1=>'SQL_CHAR',
91=>'SQL_TYPE_DATE',
93=>'SQL_TYPE_TIMESTAMP',
93=>'SQL_TYPE_TIMESTAMP',
-155=>'SQL_SS_TIMESTAMPOFFSET',
3=>'SQL_DECIMAL',
6=>'SQL_FLOAT',
-4=>'SQL_LONGVARBINARY',
4=>'SQL_INTEGER',
3=>'SQL_DECIMAL',
-8=>'SQL_WCHAR',
-10=>'SQL_WLONGVARCHAR',
2=>'SQL_NUMERIC',
-9=>'SQL_WVARCHAR',
7=>'SQL_REAL',
93=>'SQL_TYPE_TIMESTAMP',
5=>'SQL_SMALLINT',
3=>'SQL_DECIMAL',
-150=>'SQL_SS_VARIANT',
-1=>'SQL_LONGVARCHAR',
-154=>'SQL_SS_TIME2',
-2=>'SQL_BINARY',
-6=>'SQL_TINYINT',
-151=>'SQL_SS_UDT',
-11=>'SQL_GUID',
-3=>'SQL_VARBINARY',
12=>'SQL_VARCHAR',
-152=>'SQL_SS_XML',
);

and using this array in the function getResultColumns() as this:

public function getResultColumns(): array
  {
    $columns = [];
    foreach ((array) sqlsrv_field_metadata($this->resultSet) as $fieldMetadata) {
      $columns[] = [
        'name' => $fieldMetadata['Name'],
        'fullname' => $fieldMetadata['Name'],
        'nativetype' => $this->sqlTypes[$fieldMetadata['Type']] ?? null,
      ];
    }
    return $columns;
  }

Another problem is, that sqlsrvDriver is doing some type detection by itself (int, date), so in this setup, dibi fails and special driver option ReturnDatesAsStrings: 1 has to be in connection string.

Is this the correct aproach?
Is someone else having similar problem?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions