go-gorm / sqlserver

GORM sqlserver driver
MIT License
56 stars 39 forks source link

fixed int data type selection based on size #53

Closed rafiulgits closed 2 years ago

rafiulgits commented 2 years ago

Pull request title integer data type selection by sizing should be fixed


Conventions


Pull request reason Fix sql server integer type selection based on go lang int value memory size


User Case Description

https://github.com/go-gorm/sqlserver/blob/3c1621020dc4503717a93f7e7b9eb38c623aaa12/sqlserver.go#L158

SQL Server datatype selection based on int value data size is not appropriate. Here is the condition


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

Golang integers

The condition should be


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

)

jinzhu commented 2 years ago

reverted, tinyint equals int8, but size 15 will choose tinyint which will overflow?

rafiulgits commented 2 years ago

but one more issue still happening,

when I define a model like this

ProductID       int       `gorm:"type:int;not null"`

sql server database migration make it bigint automatically.

Whereas for type:tinyint, type:smallint, type:bigint are working perfectly. Can you describe this?

rafiulgits commented 2 years ago

reverted, tinyint equals int8, but size 15 will choose tinyint which will overflow?

but size 15 will never come, golang will select 8bit, 16bit, 32bit or 64bit.

If I am wrong then please correct my view.

Thanks @jinzhu

jinzhu commented 2 years ago

You can set with gorm size tag

On Sun, Feb 20, 2022 at 12:43 PM Rafiul @.***> wrote:

reverted, tinyint equals int8, but size 15 will choose tinyint which will overflow?

but size 15 will never come, golang will select 8bit, 16bit, 32bit or 64bit

— Reply to this email directly, view it on GitHub https://github.com/go-gorm/sqlserver/pull/53#issuecomment-1046162124, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAABVO3IMYVZNQUV37FN3L3U4BWPJANCNFSM5O2CXSMQ . You are receiving this because you modified the open/close state.Message ID: @.***>

-- Best regards


Jinzhu github.com/jinzhu

iTanken commented 1 month ago

reverted, tinyint equals int8, but size 15 will choose tinyint which will overflow?

Could we prevent overflow by using different types based on whether field.DataType is schema.Int or schema.Uint, for example, in #129:

https://github.com/go-gorm/sqlserver/commit/e01b9fffad2c446d49b407ac52d9e05a420bc1aa#diff-d4f96c05ed87dd1db12826d078654e8cb281186d30b116ba5ced4832c414a234R190