Skip to content

Commit 2467355

Browse files
committed
Address github codescanning
1 parent 1c080e0 commit 2467355

File tree

1 file changed

+43
-4
lines changed

1 file changed

+43
-4
lines changed

sql/yeartype.go

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,26 @@ func (t yearType) Compare(a interface{}, b interface{}) (int, error) {
5757
if err != nil {
5858
return 0, err
5959
}
60-
ai := as.(int16)
61-
bi := bs.(int16)
60+
61+
// Handle nil values that might have been returned by Convert
62+
if as == nil {
63+
if bs == nil {
64+
return 0, nil
65+
}
66+
return -1, nil
67+
} else if bs == nil {
68+
return 1, nil
69+
}
70+
71+
// Safe type assertion with validation
72+
ai, ok := as.(int16)
73+
if !ok {
74+
return 0, ErrConvertingToYear.New(a)
75+
}
76+
bi, ok := bs.(int16)
77+
if !ok {
78+
return 0, ErrConvertingToYear.New(b)
79+
}
6280

6381
if ai == bi {
6482
return 0, nil
@@ -97,12 +115,21 @@ func (t yearType) Convert(v interface{}) (interface{}, error) {
97115
return int16(0), nil
98116
}
99117
if value >= 1 && value <= 69 {
118+
if value+2000 > math.MaxInt16 {
119+
return nil, ErrConvertingToYear.New(value)
120+
}
100121
return int16(value + 2000), nil
101122
}
102123
if value >= 70 && value <= 99 {
124+
if value+1900 > math.MaxInt16 {
125+
return nil, ErrConvertingToYear.New(value)
126+
}
103127
return int16(value + 1900), nil
104128
}
105129
if value >= 1901 && value <= 2155 {
130+
if value > math.MaxInt16 {
131+
return nil, ErrConvertingToYear.New(value)
132+
}
106133
return int16(value), nil
107134
}
108135
case uint64:
@@ -140,7 +167,7 @@ func (t yearType) Convert(v interface{}) (interface{}, error) {
140167
if valueLength == 1 || valueLength == 2 || valueLength == 4 {
141168
i, err := strconv.ParseInt(value, 10, 64)
142169
if err != nil {
143-
return nil, err
170+
return nil, ErrConvertingToYear.New(err)
144171
}
145172
if i == 0 {
146173
return int16(2000), nil
@@ -150,6 +177,9 @@ func (t yearType) Convert(v interface{}) (interface{}, error) {
150177
case time.Time:
151178
year := value.Year()
152179
if year == 0 || (year >= 1901 && year <= 2155) {
180+
if year > math.MaxInt16 || year < math.MinInt16 {
181+
return nil, ErrConvertingToYear.New(year)
182+
}
153183
return int16(year), nil
154184
}
155185
}
@@ -193,8 +223,17 @@ func (t yearType) SQL(ctx *Context, dest []byte, v interface{}) (sqltypes.Value,
193223
return sqltypes.Value{}, err
194224
}
195225

226+
if v == nil {
227+
return sqltypes.NULL, nil
228+
}
229+
230+
year, ok := v.(int16)
231+
if !ok {
232+
return sqltypes.Value{}, ErrConvertingToYear.New(v)
233+
}
234+
196235
stop := len(dest)
197-
dest = strconv.AppendInt(dest, int64(v.(int16)), 10)
236+
dest = strconv.AppendInt(dest, int64(year), 10)
198237
val := dest[stop:]
199238

200239
return sqltypes.MakeTrusted(sqltypes.Year, val), nil

0 commit comments

Comments
 (0)