Skip to content

Mapping of int8 and int16 to SQL Server types is not optimal #119

@Yunaido

Description

@Yunaido

Hello,

I've noticed an issue with the way GORM maps Go's int8 and int16 types to SQL Server types. In the current implementation, int8 is mapped to smallint and int16 is mapped to int.

sqlserver/sqlserver.go

Lines 188 to 202 in b8d91cb

case schema.Int, schema.Uint:
var sqlType string
switch {
case field.Size < 16:
sqlType = "smallint"
case field.Size < 31:
sqlType = "int"
default:
sqlType = "bigint"
}
if field.AutoIncrement {
return sqlType + " IDENTITY(1,1)"
}
return sqlType

This mapping seems odd because int8 in Go is an 8-bit integer, and SQL Server has a matching tinyint type which is also 8 bits. Mapping int8 to smallint (which is 16 bits) seems unnecessary.

Similarly, int16 in Go is a 16-bit integer, but it's being mapped to int in SQL Server, which is a 32-bit integer. SQL Server's smallint would be a better match for int16 because it's also 16 bits.

I propose that the mapping should be changed as follows:

int8 in Go should map to tinyint in SQL Server
int16 in Go should map to smallint in SQL Server

switch {
case field.Size <= 8:
  sqlType = "tinyint"
case field.Size <= 16:
  sqlType = "smallint"
case field.Size <= 32:
  sqlType = "int"
default:
  sqlType = "bigint"
}

This would make the type mapping more intuitive and efficient, and it would prevent unnecessary widening of the integer types.

Please let me know if you need any additional information about this issue.

Thank you for your consideration.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions