2021-01-18 01:23:20 +00:00
package sqlite
import (
"database/sql"
Errorlint sweep + minor linter tweaks (#1796)
* Replace error assertions with Go 1.13 style
Use `errors.As(..)` over type assertions. This enables better use of
wrapped errors in the future, and lets us pass some errorlint checks
in the process.
The rewrite is entirely mechanical, and uses a standard idiom for
doing so.
* Use Go 1.13's errors.Is(..)
Rather than directly checking for error equality, use errors.Is(..).
This protects against error wrapping issues in the future.
Even though something like sql.ErrNoRows doesn't need the wrapping, do
so anyway, for the sake of consistency throughout the code base.
The change almost lets us pass the `errorlint` Go checker except for
a missing case in `js.go` which is to be handled separately; it isn't
mechanical, like these changes are.
* Remove goconst
goconst isn't a useful linter in many cases, because it's false positive
rate is high. It's 100% for the current code base.
* Avoid direct comparison of errors in recover()
Assert that we are catching an error from recover(). If we are,
check that the error caught matches errStop.
* Enable the "errorlint" checker
Configure the checker to avoid checking for errorf wraps. These are
often false positives since the suggestion is to blanket wrap errors
with %w, and that exposes the underlying API which you might not want
to do.
The other warnings are good however, and with the current patch stack,
the code base passes all these checks as well.
* Configure rowserrcheck
The project uses sqlx. Configure rowserrcheck to include said package.
* Mechanically rewrite a large set of errors
Mechanically search for errors that look like
fmt.Errorf("...%s", err.Error())
and rewrite those into
fmt.Errorf("...%v", err)
The `fmt` package is error-aware and knows how to call err.Error()
itself.
The rationale is that this is more idiomatic Go; it paves the
way for using error wrapping later with %w in some sites.
This patch only addresses the entirely mechanical rewriting caught by
a project-side search/replace. There are more individual sites not
addressed by this patch.
2021-10-12 03:03:08 +00:00
"errors"
2021-04-09 08:46:00 +00:00
"fmt"
2021-01-18 01:23:20 +00:00
"math/rand"
2021-04-13 00:32:52 +00:00
"regexp"
2021-01-18 01:23:20 +00:00
"strconv"
"strings"
"github.com/stashapp/stash/pkg/logger"
"github.com/stashapp/stash/pkg/models"
)
var randomSortFloat = rand . Float64 ( )
func selectAll ( tableName string ) string {
idColumn := getColumn ( tableName , "*" )
return "SELECT " + idColumn + " FROM " + tableName + " "
}
func selectDistinctIDs ( tableName string ) string {
idColumn := getColumn ( tableName , "id" )
return "SELECT DISTINCT " + idColumn + " FROM " + tableName + " "
}
func getColumn ( tableName string , columnName string ) string {
return tableName + "." + columnName
}
func getPagination ( findFilter * models . FindFilterType ) string {
if findFilter == nil {
panic ( "nil find filter for pagination" )
}
2021-02-01 20:57:56 +00:00
if findFilter . IsGetAll ( ) {
return " "
2021-01-18 01:23:20 +00:00
}
2021-02-01 20:57:56 +00:00
return getPaginationSQL ( findFilter . GetPage ( ) , findFilter . GetPageSize ( ) )
}
2021-01-18 01:23:20 +00:00
2021-02-01 20:57:56 +00:00
func getPaginationSQL ( page int , perPage int ) string {
2021-01-18 01:23:20 +00:00
page = ( page - 1 ) * perPage
return " LIMIT " + strconv . Itoa ( perPage ) + " OFFSET " + strconv . Itoa ( page ) + " "
}
2021-04-09 08:46:00 +00:00
func getSortDirection ( direction string ) string {
2021-01-18 01:23:20 +00:00
if direction != "ASC" && direction != "DESC" {
2021-04-09 08:46:00 +00:00
return "ASC"
} else {
return direction
2021-01-18 01:23:20 +00:00
}
2021-04-09 08:46:00 +00:00
}
func getSort ( sort string , direction string , tableName string ) string {
direction = getSortDirection ( direction )
2021-01-18 01:23:20 +00:00
const randomSeedPrefix = "random_"
if strings . HasSuffix ( sort , "_count" ) {
var relationTableName = strings . TrimSuffix ( sort , "_count" ) // TODO: pluralize?
colName := getColumn ( relationTableName , "id" )
return " ORDER BY COUNT(distinct " + colName + ") " + direction
} else if strings . Compare ( sort , "filesize" ) == 0 {
colName := getColumn ( tableName , "size" )
return " ORDER BY cast(" + colName + " as integer) " + direction
} else if strings . HasPrefix ( sort , randomSeedPrefix ) {
// seed as a parameter from the UI
// turn the provided seed into a float
seedStr := "0." + sort [ len ( randomSeedPrefix ) : ]
seed , err := strconv . ParseFloat ( seedStr , 32 )
if err != nil {
// fallback to default seed
seed = randomSortFloat
}
return getRandomSort ( tableName , direction , seed )
} else if strings . Compare ( sort , "random" ) == 0 {
return getRandomSort ( tableName , direction , randomSortFloat )
} else {
colName := getColumn ( tableName , sort )
var additional string
if tableName == "scenes" {
additional = ", bitrate DESC, framerate DESC, scenes.rating DESC, scenes.duration DESC"
} else if tableName == "scene_markers" {
additional = ", scene_markers.scene_id ASC, scene_markers.seconds ASC"
}
if strings . Compare ( sort , "name" ) == 0 {
return " ORDER BY " + colName + " COLLATE NOCASE " + direction + additional
}
if strings . Compare ( sort , "title" ) == 0 {
return " ORDER BY " + colName + " COLLATE NATURAL_CS " + direction + additional
}
return " ORDER BY " + colName + " " + direction + additional
}
}
func getRandomSort ( tableName string , direction string , seed float64 ) string {
// https://stackoverflow.com/a/24511461
colName := getColumn ( tableName , "id" )
randomSortString := strconv . FormatFloat ( seed , 'f' , 16 , 32 )
return " ORDER BY " + "(substr(" + colName + " * " + randomSortString + ", length(" + colName + ") + 2))" + " " + direction
}
2021-04-09 08:46:00 +00:00
func getCountSort ( primaryTable , joinTable , primaryFK , direction string ) string {
return fmt . Sprintf ( " ORDER BY (SELECT COUNT(*) FROM %s WHERE %s = %s.id) %s" , joinTable , primaryFK , primaryTable , getSortDirection ( direction ) )
}
2021-01-18 01:23:20 +00:00
func getSearchBinding ( columns [ ] string , q string , not bool ) ( string , [ ] interface { } ) {
var likeClauses [ ] string
var args [ ] interface { }
notStr := ""
binaryType := " OR "
if not {
2021-03-02 00:27:36 +00:00
notStr = " NOT"
2021-01-18 01:23:20 +00:00
binaryType = " AND "
}
2021-04-13 00:32:52 +00:00
q = strings . TrimSpace ( q )
2021-01-18 01:23:20 +00:00
trimmedQuery := strings . Trim ( q , "\"" )
2021-04-13 00:32:52 +00:00
2021-01-18 01:23:20 +00:00
if trimmedQuery == q {
2021-04-13 00:32:52 +00:00
q = regexp . MustCompile ( ` \s+ ` ) . ReplaceAllString ( q , " " )
queryWords := strings . Split ( q , " " )
2021-01-18 01:23:20 +00:00
// Search for any word
for _ , word := range queryWords {
for _ , column := range columns {
likeClauses = append ( likeClauses , column + notStr + " LIKE ?" )
args = append ( args , "%" + word + "%" )
}
}
} else {
// Search the exact query
for _ , column := range columns {
likeClauses = append ( likeClauses , column + notStr + " LIKE ?" )
args = append ( args , "%" + trimmedQuery + "%" )
}
}
likes := strings . Join ( likeClauses , binaryType )
return "(" + likes + ")" , args
}
func getInBinding ( length int ) string {
bindings := strings . Repeat ( "?, " , length )
bindings = strings . TrimRight ( bindings , ", " )
return "(" + bindings + ")"
}
func getSimpleCriterionClause ( criterionModifier models . CriterionModifier , rhs string ) ( string , int ) {
if modifier := criterionModifier . String ( ) ; criterionModifier . IsValid ( ) {
switch modifier {
case "EQUALS" :
return "= " + rhs , 1
case "NOT_EQUALS" :
return "!= " + rhs , 1
case "GREATER_THAN" :
return "> " + rhs , 1
case "LESS_THAN" :
return "< " + rhs , 1
case "IS_NULL" :
return "IS NULL" , 0
case "NOT_NULL" :
return "IS NOT NULL" , 0
2021-08-12 00:24:16 +00:00
case "BETWEEN" :
return "BETWEEN (" + rhs + ") AND (" + rhs + ")" , 2
case "NOT_BETWEEN" :
return "NOT BETWEEN (" + rhs + ") AND (" + rhs + ")" , 2
2021-01-18 01:23:20 +00:00
default :
logger . Errorf ( "todo" )
return "= ?" , 1 // TODO
}
}
return "= ?" , 1 // TODO
}
2021-08-12 00:24:16 +00:00
func getIntCriterionWhereClause ( column string , input models . IntCriterionInput ) ( string , [ ] interface { } ) {
binding , _ := getSimpleCriterionClause ( input . Modifier , "?" )
var args [ ] interface { }
switch input . Modifier {
case "EQUALS" , "NOT_EQUALS" :
args = [ ] interface { } { input . Value }
case "LESS_THAN" :
args = [ ] interface { } { input . Value }
case "GREATER_THAN" :
args = [ ] interface { } { input . Value }
case "BETWEEN" , "NOT_BETWEEN" :
upper := 0
if input . Value2 != nil {
upper = * input . Value2
}
args = [ ] interface { } { input . Value , upper }
}
return column + " " + binding , args
2021-01-18 01:23:20 +00:00
}
// returns where clause and having clause
func getMultiCriterionClause ( primaryTable , foreignTable , joinTable , primaryFK , foreignFK string , criterion * models . MultiCriterionInput ) ( string , string ) {
whereClause := ""
havingClause := ""
if criterion . Modifier == models . CriterionModifierIncludes {
// includes any of the provided ids
whereClause = foreignTable + ".id IN " + getInBinding ( len ( criterion . Value ) )
} else if criterion . Modifier == models . CriterionModifierIncludesAll {
// includes all of the provided ids
whereClause = foreignTable + ".id IN " + getInBinding ( len ( criterion . Value ) )
havingClause = "count(distinct " + foreignTable + ".id) IS " + strconv . Itoa ( len ( criterion . Value ) )
} else if criterion . Modifier == models . CriterionModifierExcludes {
// excludes all of the provided ids
if joinTable != "" {
2021-10-10 08:02:26 +00:00
whereClause = primaryTable + ".id not in (select " + joinTable + "." + primaryFK + " from " + joinTable + " where " + joinTable + "." + foreignFK + " in " + getInBinding ( len ( criterion . Value ) ) + ")"
2021-01-18 01:23:20 +00:00
} else {
whereClause = "not exists (select s.id from " + primaryTable + " as s where s.id = " + primaryTable + ".id and s." + foreignFK + " in " + getInBinding ( len ( criterion . Value ) ) + ")"
}
}
return whereClause , havingClause
}
2021-08-12 00:24:16 +00:00
func getCountCriterionClause ( primaryTable , joinTable , primaryFK string , criterion models . IntCriterionInput ) ( string , [ ] interface { } ) {
2021-04-09 08:46:00 +00:00
lhs := fmt . Sprintf ( "(SELECT COUNT(*) FROM %s s WHERE s.%s = %s.id)" , joinTable , primaryFK , primaryTable )
return getIntCriterionWhereClause ( lhs , criterion )
}
2021-01-18 01:23:20 +00:00
func getImage ( tx dbi , query string , args ... interface { } ) ( [ ] byte , error ) {
rows , err := tx . Queryx ( query , args ... )
Errorlint sweep + minor linter tweaks (#1796)
* Replace error assertions with Go 1.13 style
Use `errors.As(..)` over type assertions. This enables better use of
wrapped errors in the future, and lets us pass some errorlint checks
in the process.
The rewrite is entirely mechanical, and uses a standard idiom for
doing so.
* Use Go 1.13's errors.Is(..)
Rather than directly checking for error equality, use errors.Is(..).
This protects against error wrapping issues in the future.
Even though something like sql.ErrNoRows doesn't need the wrapping, do
so anyway, for the sake of consistency throughout the code base.
The change almost lets us pass the `errorlint` Go checker except for
a missing case in `js.go` which is to be handled separately; it isn't
mechanical, like these changes are.
* Remove goconst
goconst isn't a useful linter in many cases, because it's false positive
rate is high. It's 100% for the current code base.
* Avoid direct comparison of errors in recover()
Assert that we are catching an error from recover(). If we are,
check that the error caught matches errStop.
* Enable the "errorlint" checker
Configure the checker to avoid checking for errorf wraps. These are
often false positives since the suggestion is to blanket wrap errors
with %w, and that exposes the underlying API which you might not want
to do.
The other warnings are good however, and with the current patch stack,
the code base passes all these checks as well.
* Configure rowserrcheck
The project uses sqlx. Configure rowserrcheck to include said package.
* Mechanically rewrite a large set of errors
Mechanically search for errors that look like
fmt.Errorf("...%s", err.Error())
and rewrite those into
fmt.Errorf("...%v", err)
The `fmt` package is error-aware and knows how to call err.Error()
itself.
The rationale is that this is more idiomatic Go; it paves the
way for using error wrapping later with %w in some sites.
This patch only addresses the entirely mechanical rewriting caught by
a project-side search/replace. There are more individual sites not
addressed by this patch.
2021-10-12 03:03:08 +00:00
if err != nil && ! errors . Is ( err , sql . ErrNoRows ) {
2021-01-18 01:23:20 +00:00
return nil , err
}
defer rows . Close ( )
var ret [ ] byte
if rows . Next ( ) {
if err := rows . Scan ( & ret ) ; err != nil {
return nil , err
}
}
if err := rows . Err ( ) ; err != nil {
return nil , err
}
return ret , nil
}