Validate SQLiteDate (#2052)

* Reject invalid SQLiteDate strings
* Add unit tests
* Handle null values
This commit is contained in:
WithoutPants 2021-11-23 08:18:43 +11:00 committed by GitHub
parent f2903d4dcf
commit c98ad7a62c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 95 additions and 4 deletions

View File

@ -2,9 +2,10 @@ package models
import (
"database/sql/driver"
"fmt"
"strings"
"time"
"github.com/stashapp/stash/pkg/logger"
"github.com/stashapp/stash/pkg/utils"
)
@ -33,14 +34,19 @@ func (t *SQLiteDate) Scan(value interface{}) error {
// Value implements the driver Valuer interface.
func (t SQLiteDate) Value() (driver.Value, error) {
if !t.Valid {
return nil, nil
}
s := strings.TrimSpace(t.String)
// handle empty string
if t.String == "" {
if s == "" {
return "", nil
}
result, err := utils.ParseDateStringAsFormat(t.String, "2006-01-02")
result, err := utils.ParseDateStringAsFormat(s, "2006-01-02")
if err != nil {
logger.Debugf("sqlite date conversion error: %s", err.Error())
return nil, fmt.Errorf("converting sqlite date %q: %w", s, err)
}
return result, nil
}

View File

@ -0,0 +1,84 @@
package models
import (
"database/sql/driver"
"reflect"
"testing"
)
func TestSQLiteDate_Value(t *testing.T) {
tests := []struct {
name string
tr SQLiteDate
want driver.Value
wantErr bool
}{
{
"empty string",
SQLiteDate{"", true},
"",
false,
},
{
"whitespace",
SQLiteDate{" ", true},
"",
false,
},
{
"RFC3339",
SQLiteDate{"2021-11-22T17:11:55+11:00", true},
"2021-11-22",
false,
},
{
"date",
SQLiteDate{"2021-11-22", true},
"2021-11-22",
false,
},
{
"date and time",
SQLiteDate{"2021-11-22 17:12:05", true},
"2021-11-22",
false,
},
{
"date, time and zone",
SQLiteDate{"2021-11-22 17:33:05 AEST", true},
"2021-11-22",
false,
},
{
"whitespaced date",
SQLiteDate{" 2021-11-22 ", true},
"2021-11-22",
false,
},
{
"bad format",
SQLiteDate{"foo", true},
nil,
true,
},
{
"invalid",
SQLiteDate{"null", false},
nil,
false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := tt.tr.Value()
if (err != nil) != tt.wantErr {
t.Errorf("SQLiteDate.Value() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("SQLiteDate.Value() = %v, want %v", got, tt.want)
}
})
}
}

View File

@ -6,5 +6,6 @@
* Added plugin hook for Tag merge operation. ([#2010](https://github.com/stashapp/stash/pull/2010))
### 🐛 Bug fixes
* Reject dates with invalid format. ([#2052](https://github.com/stashapp/stash/pull/2052))
* Fix Autostart Video on Play Selected and Continue Playlist default settings not working. ([#2050](https://github.com/stashapp/stash/pull/2050))
* Fix "Custom Performer Images" feature picking up non-image files. ([#2017](https://github.com/stashapp/stash/pull/2017))