From 554b6bb000d01356fda48d7f4aed606e5adf7af1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Nieto?= Date: Sun, 23 Feb 2020 22:03:31 -0600 Subject: [PATCH] fix some linter warnings --- function.go | 13 ---- internal/cache/hashstructure/hashstructure.go | 6 +- internal/sqladapter/collection.go | 4 +- internal/sqladapter/database.go | 32 +++++----- internal/sqladapter/exql/column_test.go | 10 ++-- internal/sqladapter/exql/column_value.go | 4 +- internal/sqladapter/exql/column_value_test.go | 8 +-- internal/sqladapter/exql/columns_test.go | 4 +- internal/sqladapter/exql/database_test.go | 6 +- internal/sqladapter/exql/default.go | 2 - internal/sqladapter/exql/group_by_test.go | 4 +- internal/sqladapter/exql/join_test.go | 6 +- internal/sqladapter/exql/order_by_test.go | 16 ++--- internal/sqladapter/exql/raw_test.go | 4 +- internal/sqladapter/exql/statement.go | 9 --- internal/sqladapter/exql/statement_test.go | 57 ++++++------------ internal/sqladapter/exql/table_test.go | 4 +- internal/sqladapter/exql/utilities.go | 6 -- internal/sqladapter/exql/where_test.go | 4 +- internal/sqladapter/result.go | 59 ++++++++++++------- internal/sqladapter/tx.go | 7 +-- internal/testsuite/generic_suite.go | 5 +- internal/testsuite/sql_suite.go | 21 +++---- lib/reflectx/reflect.go | 4 +- lib/sqlbuilder/builder.go | 29 +-------- lib/sqlbuilder/builder_test.go | 34 +++++------ lib/sqlbuilder/fetch.go | 5 +- lib/sqlbuilder/insert.go | 8 +-- lib/sqlbuilder/paginate.go | 7 ++- lib/sqlbuilder/select.go | 2 - lib/sqlbuilder/template_test.go | 2 - lib/sqlbuilder/update.go | 2 - logger.go | 3 +- mongo/collection.go | 16 +++-- mongo/connection.go | 2 +- mongo/helper_test.go | 11 ++-- mongo/mongo_test.go | 5 +- mongo/result.go | 9 +-- mssql/collection.go | 4 +- mssql/connection.go | 2 +- mssql/tx.go | 3 +- mysql/database.go | 5 -- mysql/helper_test.go | 9 +-- mysql/template.go | 2 - mysql/tx.go | 3 +- postgresql/connection.go | 6 -- postgresql/database.go | 4 -- postgresql/helper_test.go | 11 +--- postgresql/postgresql.go | 2 - postgresql/postgresql_test.go | 2 +- postgresql/tx.go | 3 +- ql/connection.go | 4 +- ql/helper_test.go | 6 +- ql/tx.go | 3 +- settings.go | 14 +++-- sqlite/connection.go | 4 +- sqlite/template.go | 2 - sqlite/tx.go | 3 +- 58 files changed, 211 insertions(+), 311 deletions(-) diff --git a/function.go b/function.go index b6945e4d..9fef4a31 100644 --- a/function.go +++ b/function.go @@ -21,10 +21,6 @@ package db -import ( - "reflect" -) - // Function interface defines methods for representing database functions. // This is an exported interface but it's rarely used directly, you may want to // use the `db.Func()` function instead. @@ -52,15 +48,6 @@ type Function interface { // // RTRIM("Hello ") // db.Func("RTRIM", "Hello ") func Func(name string, args ...interface{}) Function { - if len(args) == 1 { - if reflect.TypeOf(args[0]).Kind() == reflect.Slice { - iargs := make([]interface{}, len(args)) - for i := range args { - iargs[i] = args[i] - } - args = iargs - } - } return &dbFunc{name: name, args: args} } diff --git a/internal/cache/hashstructure/hashstructure.go b/internal/cache/hashstructure/hashstructure.go index 6f586fa7..9a2e9535 100644 --- a/internal/cache/hashstructure/hashstructure.go +++ b/internal/cache/hashstructure/hashstructure.go @@ -288,8 +288,6 @@ func (w *walker) visit(v reflect.Value, opts *visitOpts) (uint64, error) { default: return 0, fmt.Errorf("unknown kind to hash: %s", k) } - - return 0, nil } func hashUpdateOrdered(h hash.Hash64, a, b uint64) uint64 { @@ -321,3 +319,7 @@ const ( visitFlagInvalid visitFlag = iota visitFlagSet = iota << 1 ) + +var ( + _ = visitFlagInvalid +) diff --git a/internal/sqladapter/collection.go b/internal/sqladapter/collection.go index ddaafe28..444e440b 100644 --- a/internal/sqladapter/collection.go +++ b/internal/sqladapter/collection.go @@ -219,7 +219,7 @@ cancel: if !inTx { // This is only executed if t.Database() was **not** a transaction and if // sess was created with sess.NewTransaction(). - tx.Rollback() + _ = tx.Rollback() } return err } @@ -310,7 +310,7 @@ cancel: if !inTx { // This is only executed if t.Database() was **not** a transaction and if // sess was created with sess.NewTransaction(). - tx.Rollback() + _ = tx.Rollback() } return err } diff --git a/internal/sqladapter/database.go b/internal/sqladapter/database.go index 0d3dff09..879c9abb 100644 --- a/internal/sqladapter/database.go +++ b/internal/sqladapter/database.go @@ -350,24 +350,26 @@ func (d *database) Close() error { d.baseTx = nil d.sessMu.Unlock() }() - if d.sess != nil { - if cleaner, ok := d.PartialDatabase.(hasCleanUp); ok { - cleaner.CleanUp() - } + if d.sess == nil { + return nil + } - d.cachedCollections.Clear() - d.cachedStatements.Clear() // Closes prepared statements as well. + d.cachedCollections.Clear() + d.cachedStatements.Clear() // Closes prepared statements as well. - tx := d.Transaction() - if tx == nil { - // Not within a transaction. - return d.sess.Close() + tx := d.Transaction() + if tx == nil { + if cleaner, ok := d.PartialDatabase.(hasCleanUp); ok { + if err := cleaner.CleanUp(); err != nil { + return err + } } + // Not within a transaction. + return d.sess.Close() + } - if !tx.Committed() { - tx.Rollback() - return nil - } + if !tx.Committed() { + _ = tx.Rollback() } return nil } @@ -649,7 +651,7 @@ func (d *database) WaitForConnection(connectFn func() error) error { waitTime := time.Millisecond * 10 // Waitig 5 seconds for a successful connection. - for timeStart := time.Now(); time.Now().Sub(timeStart) < time.Second*5; { + for timeStart := time.Now(); time.Since(timeStart) < time.Second*5; { err := connectFn() if err == nil { return nil // Connected! diff --git a/internal/sqladapter/exql/column_test.go b/internal/sqladapter/exql/column_test.go index a8c2a368..f999960e 100644 --- a/internal/sqladapter/exql/column_test.go +++ b/internal/sqladapter/exql/column_test.go @@ -90,34 +90,34 @@ func BenchmarkColumnHash(b *testing.B) { func BenchmarkColumnCompile(b *testing.B) { c := Column{Name: "name"} for i := 0; i < b.N; i++ { - c.Compile(defaultTemplate) + _, _ = c.Compile(defaultTemplate) } } func BenchmarkColumnCompileNoCache(b *testing.B) { for i := 0; i < b.N; i++ { c := Column{Name: "name"} - c.Compile(defaultTemplate) + _, _ = c.Compile(defaultTemplate) } } func BenchmarkColumnWithDotCompile(b *testing.B) { c := Column{Name: "role.name"} for i := 0; i < b.N; i++ { - c.Compile(defaultTemplate) + _, _ = c.Compile(defaultTemplate) } } func BenchmarkColumnWithImplicitAsKeywordCompile(b *testing.B) { c := Column{Name: "role.name foo"} for i := 0; i < b.N; i++ { - c.Compile(defaultTemplate) + _, _ = c.Compile(defaultTemplate) } } func BenchmarkColumnWithAsKeywordCompile(b *testing.B) { c := Column{Name: "role.name AS foo"} for i := 0; i < b.N; i++ { - c.Compile(defaultTemplate) + _, _ = c.Compile(defaultTemplate) } } diff --git a/internal/sqladapter/exql/column_value.go b/internal/sqladapter/exql/column_value.go index 7b692c0d..018faa45 100644 --- a/internal/sqladapter/exql/column_value.go +++ b/internal/sqladapter/exql/column_value.go @@ -70,9 +70,7 @@ func JoinColumnValues(values ...Fragment) *ColumnValues { // Insert adds a column to the columns array. func (c *ColumnValues) Insert(values ...Fragment) *ColumnValues { - for _, f := range values { - c.ColumnValues = append(c.ColumnValues, f) - } + c.ColumnValues = append(c.ColumnValues, values...) c.hash.Reset() return c } diff --git a/internal/sqladapter/exql/column_value_test.go b/internal/sqladapter/exql/column_value_test.go index 90bf1c7d..9569fcac 100644 --- a/internal/sqladapter/exql/column_value_test.go +++ b/internal/sqladapter/exql/column_value_test.go @@ -95,14 +95,14 @@ func BenchmarkColumnValueHash(b *testing.B) { func BenchmarkColumnValueCompile(b *testing.B) { cv := &ColumnValue{Column: ColumnWithName("id"), Operator: "=", Value: NewValue(1)} for i := 0; i < b.N; i++ { - cv.Compile(defaultTemplate) + _, _ = cv.Compile(defaultTemplate) } } func BenchmarkColumnValueCompileNoCache(b *testing.B) { for i := 0; i < b.N; i++ { cv := &ColumnValue{Column: ColumnWithName("id"), Operator: "=", Value: NewValue(1)} - cv.Compile(defaultTemplate) + _, _ = cv.Compile(defaultTemplate) } } @@ -140,7 +140,7 @@ func BenchmarkColumnValuesCompile(b *testing.B) { &ColumnValue{Column: ColumnWithName("modified"), Operator: "<=", Value: NewValue(Raw{Value: "NOW()"})}, ) for i := 0; i < b.N; i++ { - cvs.Compile(defaultTemplate) + _, _ = cvs.Compile(defaultTemplate) } } @@ -153,6 +153,6 @@ func BenchmarkColumnValuesCompileNoCache(b *testing.B) { &ColumnValue{Column: ColumnWithName("created"), Operator: ">=", Value: NewValue(Raw{Value: "NOW()"})}, &ColumnValue{Column: ColumnWithName("modified"), Operator: "<=", Value: NewValue(Raw{Value: "NOW()"})}, ) - cvs.Compile(defaultTemplate) + _, _ = cvs.Compile(defaultTemplate) } } diff --git a/internal/sqladapter/exql/columns_test.go b/internal/sqladapter/exql/columns_test.go index eb121613..4c56f852 100644 --- a/internal/sqladapter/exql/columns_test.go +++ b/internal/sqladapter/exql/columns_test.go @@ -56,7 +56,7 @@ func BenchmarkColumnsCompile(b *testing.B) { &Column{Name: "role.id"}, ) for i := 0; i < b.N; i++ { - c.Compile(defaultTemplate) + _, _ = c.Compile(defaultTemplate) } } @@ -69,6 +69,6 @@ func BenchmarkColumnsCompileNoCache(b *testing.B) { &Column{Name: "role.name"}, &Column{Name: "role.id"}, ) - c.Compile(defaultTemplate) + _, _ = c.Compile(defaultTemplate) } } diff --git a/internal/sqladapter/exql/database_test.go b/internal/sqladapter/exql/database_test.go index 42dd657b..657c5b40 100644 --- a/internal/sqladapter/exql/database_test.go +++ b/internal/sqladapter/exql/database_test.go @@ -42,20 +42,20 @@ func BenchmarkDatabaseHash(b *testing.B) { func BenchmarkDatabaseCompile(b *testing.B) { c := Database{Name: "name"} for i := 0; i < b.N; i++ { - c.Compile(defaultTemplate) + _, _ = c.Compile(defaultTemplate) } } func BenchmarkDatabaseCompileNoCache(b *testing.B) { for i := 0; i < b.N; i++ { c := Database{Name: "name"} - c.Compile(defaultTemplate) + _, _ = c.Compile(defaultTemplate) } } func BenchmarkDatabaseCompileNoCache2(b *testing.B) { for i := 0; i < b.N; i++ { c := Database{Name: fmt.Sprintf("name: %v", i)} - c.Compile(defaultTemplate) + _, _ = c.Compile(defaultTemplate) } } diff --git a/internal/sqladapter/exql/default.go b/internal/sqladapter/exql/default.go index 38022166..658e57cd 100644 --- a/internal/sqladapter/exql/default.go +++ b/internal/sqladapter/exql/default.go @@ -149,8 +149,6 @@ const ( DROP TABLE {{.Table | compile}} ` - defaultGroupByColumnLayout = `{{.Column}}` - defaultGroupByLayout = ` {{if .GroupColumns}} GROUP BY {{.GroupColumns}} diff --git a/internal/sqladapter/exql/group_by_test.go b/internal/sqladapter/exql/group_by_test.go index a1c43442..f42de617 100644 --- a/internal/sqladapter/exql/group_by_test.go +++ b/internal/sqladapter/exql/group_by_test.go @@ -52,7 +52,7 @@ func BenchmarkGroupByCompile(b *testing.B) { &Column{Name: "role.id"}, ) for i := 0; i < b.N; i++ { - c.Compile(defaultTemplate) + _, _ = c.Compile(defaultTemplate) } } @@ -65,6 +65,6 @@ func BenchmarkGroupByCompileNoCache(b *testing.B) { &Column{Name: "role.name"}, &Column{Name: "role.id"}, ) - c.Compile(defaultTemplate) + _, _ = c.Compile(defaultTemplate) } } diff --git a/internal/sqladapter/exql/join_test.go b/internal/sqladapter/exql/join_test.go index 055f013d..68c603b8 100644 --- a/internal/sqladapter/exql/join_test.go +++ b/internal/sqladapter/exql/join_test.go @@ -225,7 +225,7 @@ func BenchmarkCompileJoin(b *testing.B) { ), }) for i := 0; i < b.N; i++ { - j.Compile(defaultTemplate) + _, _ = j.Compile(defaultTemplate) } } @@ -246,7 +246,7 @@ func BenchmarkCompileJoinNoCache(b *testing.B) { }, ), }) - j.Compile(defaultTemplate) + _, _ = j.Compile(defaultTemplate) } } @@ -267,6 +267,6 @@ func BenchmarkCompileJoinNoCache2(b *testing.B) { }, ), }) - j.Compile(defaultTemplate) + _, _ = j.Compile(defaultTemplate) } } diff --git a/internal/sqladapter/exql/order_by_test.go b/internal/sqladapter/exql/order_by_test.go index c6361af9..1202fef8 100644 --- a/internal/sqladapter/exql/order_by_test.go +++ b/internal/sqladapter/exql/order_by_test.go @@ -74,7 +74,7 @@ func BenchmarkCompileOrderByCompile(b *testing.B) { ), } for i := 0; i < b.N; i++ { - o.Compile(defaultTemplate) + _, _ = o.Compile(defaultTemplate) } } @@ -85,21 +85,21 @@ func BenchmarkCompileOrderByCompileNoCache(b *testing.B) { &SortColumn{Column: &Column{Name: "foo"}}, ), ) - o.Compile(defaultTemplate) + _, _ = o.Compile(defaultTemplate) } } func BenchmarkCompileOrderCompile(b *testing.B) { o := Descendent for i := 0; i < b.N; i++ { - o.Compile(defaultTemplate) + _, _ = o.Compile(defaultTemplate) } } func BenchmarkCompileOrderCompileNoCache(b *testing.B) { for i := 0; i < b.N; i++ { o := Descendent - o.Compile(defaultTemplate) + _, _ = o.Compile(defaultTemplate) } } @@ -113,14 +113,14 @@ func BenchmarkSortColumnHash(b *testing.B) { func BenchmarkSortColumnCompile(b *testing.B) { s := &SortColumn{Column: &Column{Name: "foo"}} for i := 0; i < b.N; i++ { - s.Compile(defaultTemplate) + _, _ = s.Compile(defaultTemplate) } } func BenchmarkSortColumnCompileNoCache(b *testing.B) { for i := 0; i < b.N; i++ { s := &SortColumn{Column: &Column{Name: "foo"}} - s.Compile(defaultTemplate) + _, _ = s.Compile(defaultTemplate) } } @@ -140,7 +140,7 @@ func BenchmarkSortColumnsCompile(b *testing.B) { &SortColumn{Column: &Column{Name: "bar"}}, ) for i := 0; i < b.N; i++ { - s.Compile(defaultTemplate) + _, _ = s.Compile(defaultTemplate) } } @@ -150,6 +150,6 @@ func BenchmarkSortColumnsCompileNoCache(b *testing.B) { &SortColumn{Column: &Column{Name: "foo"}}, &SortColumn{Column: &Column{Name: "bar"}}, ) - s.Compile(defaultTemplate) + _, _ = s.Compile(defaultTemplate) } } diff --git a/internal/sqladapter/exql/raw_test.go b/internal/sqladapter/exql/raw_test.go index a8f7eaab..076d574b 100644 --- a/internal/sqladapter/exql/raw_test.go +++ b/internal/sqladapter/exql/raw_test.go @@ -54,14 +54,14 @@ func BenchmarkRawCreate(b *testing.B) { func BenchmarkRawString(b *testing.B) { raw := &Raw{Value: "foo"} for i := 0; i < b.N; i++ { - raw.String() + _ = raw.String() } } func BenchmarkRawCompile(b *testing.B) { raw := &Raw{Value: "foo"} for i := 0; i < b.N; i++ { - raw.Compile(defaultTemplate) + _, _ = raw.Compile(defaultTemplate) } } diff --git a/internal/sqladapter/exql/statement.go b/internal/sqladapter/exql/statement.go index 8cf4c774..032466e2 100644 --- a/internal/sqladapter/exql/statement.go +++ b/internal/sqladapter/exql/statement.go @@ -4,8 +4,6 @@ import ( "errors" "reflect" "strings" - - "upper.io/db.v3/internal/cache" ) var errUnknownTemplateType = errors.New("Unknown template type") @@ -41,13 +39,6 @@ func (layout *Template) doCompile(c Fragment) (string, error) { return "", nil } -func getHash(h cache.Hashable) string { - if h != nil && !reflect.ValueOf(h).IsNil() { - return h.Hash() - } - return "" -} - // Hash returns a unique identifier for the struct. func (s *Statement) Hash() string { return s.hash.Hash(s) diff --git a/internal/sqladapter/exql/statement_test.go b/internal/sqladapter/exql/statement_test.go index c22f11dd..33fe21b7 100644 --- a/internal/sqladapter/exql/statement_test.go +++ b/internal/sqladapter/exql/statement_test.go @@ -22,9 +22,8 @@ func mustTrim(a string, err error) string { func TestTruncateTable(t *testing.T) { var s, e string - var stmt Statement - stmt = Statement{ + stmt := Statement{ Type: Truncate, Table: TableWithName("table_name"), } @@ -39,9 +38,8 @@ func TestTruncateTable(t *testing.T) { func TestDropTable(t *testing.T) { var s, e string - var stmt Statement - stmt = Statement{ + stmt := Statement{ Type: DropTable, Table: TableWithName("table_name"), } @@ -56,9 +54,8 @@ func TestDropTable(t *testing.T) { func TestDropDatabase(t *testing.T) { var s, e string - var stmt Statement - stmt = Statement{ + stmt := Statement{ Type: DropDatabase, Database: &Database{Name: "table_name"}, } @@ -73,9 +70,8 @@ func TestDropDatabase(t *testing.T) { func TestCount(t *testing.T) { var s, e string - var stmt Statement - stmt = Statement{ + stmt := Statement{ Type: Count, Table: TableWithName("table_name"), } @@ -90,9 +86,8 @@ func TestCount(t *testing.T) { func TestCountRelation(t *testing.T) { var s, e string - var stmt Statement - stmt = Statement{ + stmt := Statement{ Type: Count, Table: TableWithName("information_schema.tables"), } @@ -107,9 +102,8 @@ func TestCountRelation(t *testing.T) { func TestCountWhere(t *testing.T) { var s, e string - var stmt Statement - stmt = Statement{ + stmt := Statement{ Type: Count, Table: TableWithName("table_name"), Where: WhereConditions( @@ -127,9 +121,8 @@ func TestCountWhere(t *testing.T) { func TestSelectStarFrom(t *testing.T) { var s, e string - var stmt Statement - stmt = Statement{ + stmt := Statement{ Type: Select, Table: TableWithName("table_name"), } @@ -144,9 +137,8 @@ func TestSelectStarFrom(t *testing.T) { func TestSelectStarFromAlias(t *testing.T) { var s, e string - var stmt Statement - stmt = Statement{ + stmt := Statement{ Type: Select, Table: TableWithName("table.name AS foo"), } @@ -197,9 +189,8 @@ func TestSelectStarFromRawWhere(t *testing.T) { func TestSelectStarFromMany(t *testing.T) { var s, e string - var stmt Statement - stmt = Statement{ + stmt := Statement{ Type: Select, Table: TableWithName("first.table AS foo, second.table as BAR, third.table aS baz"), } @@ -214,9 +205,8 @@ func TestSelectStarFromMany(t *testing.T) { func TestSelectTableStarFromMany(t *testing.T) { var s, e string - var stmt Statement - stmt = Statement{ + stmt := Statement{ Type: Select, Columns: JoinColumns( &Column{Name: "foo.name"}, @@ -236,9 +226,8 @@ func TestSelectTableStarFromMany(t *testing.T) { func TestSelectArtistNameFrom(t *testing.T) { var s, e string - var stmt Statement - stmt = Statement{ + stmt := Statement{ Type: Select, Table: TableWithName("artist"), Columns: JoinColumns( @@ -347,9 +336,8 @@ func TestSelectNaturalJoin(t *testing.T) { func TestSelectRawFrom(t *testing.T) { var s, e string - var stmt Statement - stmt = Statement{ + stmt := Statement{ Type: Select, Table: TableWithName(`artist`), Columns: JoinColumns( @@ -368,9 +356,8 @@ func TestSelectRawFrom(t *testing.T) { func TestSelectFieldsFrom(t *testing.T) { var s, e string - var stmt Statement - stmt = Statement{ + stmt := Statement{ Type: Select, Columns: JoinColumns( &Column{Name: "foo"}, @@ -623,9 +610,8 @@ func TestSelectFieldsFromWithOrderBy(t *testing.T) { func TestSelectFieldsFromWhere(t *testing.T) { var s, e string - var stmt Statement - stmt = Statement{ + stmt := Statement{ Type: Select, Columns: JoinColumns( &Column{Name: "foo"}, @@ -648,9 +634,8 @@ func TestSelectFieldsFromWhere(t *testing.T) { func TestSelectFieldsFromWhereLimitOffset(t *testing.T) { var s, e string - var stmt Statement - stmt = Statement{ + stmt := Statement{ Type: Select, Columns: JoinColumns( &Column{Name: "foo"}, @@ -675,9 +660,8 @@ func TestSelectFieldsFromWhereLimitOffset(t *testing.T) { func TestDelete(t *testing.T) { var s, e string - var stmt Statement - stmt = Statement{ + stmt := Statement{ Type: Delete, Table: TableWithName("table_name"), Where: WhereConditions( @@ -737,9 +721,8 @@ func TestUpdate(t *testing.T) { func TestInsert(t *testing.T) { var s, e string - var stmt Statement - stmt = Statement{ + stmt := Statement{ Type: Insert, Table: TableWithName("table_name"), Columns: JoinColumns( @@ -764,9 +747,8 @@ func TestInsert(t *testing.T) { func TestInsertMultiple(t *testing.T) { var s, e string - var stmt Statement - stmt = Statement{ + stmt := Statement{ Type: Insert, Table: TableWithName("table_name"), Columns: JoinColumns( @@ -798,9 +780,8 @@ func TestInsertMultiple(t *testing.T) { func TestInsertReturning(t *testing.T) { var s, e string - var stmt Statement - stmt = Statement{ + stmt := Statement{ Type: Insert, Table: TableWithName("table_name"), Returning: ReturningColumns( diff --git a/internal/sqladapter/exql/table_test.go b/internal/sqladapter/exql/table_test.go index ea3c7e91..8f374b4a 100644 --- a/internal/sqladapter/exql/table_test.go +++ b/internal/sqladapter/exql/table_test.go @@ -124,13 +124,13 @@ func BenchmarkTableHash(b *testing.B) { func BenchmarkTableCompile(b *testing.B) { t := TableWithName("name") for i := 0; i < b.N; i++ { - t.Compile(defaultTemplate) + _, _ = t.Compile(defaultTemplate) } } func BenchmarkTableCompileNoCache(b *testing.B) { for i := 0; i < b.N; i++ { t := TableWithName("name") - t.Compile(defaultTemplate) + _, _ = t.Compile(defaultTemplate) } } diff --git a/internal/sqladapter/exql/utilities.go b/internal/sqladapter/exql/utilities.go index 67a3eac1..972ebb47 100644 --- a/internal/sqladapter/exql/utilities.go +++ b/internal/sqladapter/exql/utilities.go @@ -4,12 +4,6 @@ import ( "strings" ) -const ( - stageExpect = iota - stageCapture - stageClose -) - // isBlankSymbol returns true if the given byte is either space, tab, carriage // return or newline. func isBlankSymbol(in byte) bool { diff --git a/internal/sqladapter/exql/where_test.go b/internal/sqladapter/exql/where_test.go index 0c1b76e6..ec823bb6 100644 --- a/internal/sqladapter/exql/where_test.go +++ b/internal/sqladapter/exql/where_test.go @@ -100,7 +100,7 @@ func BenchmarkCompileWhere(b *testing.B) { &ColumnValue{Column: &Column{Name: "baz"}, Operator: "=", Value: NewValue(99)}, ) for i := 0; i < b.N; i++ { - w.Compile(defaultTemplate) + _, _ = w.Compile(defaultTemplate) } } @@ -109,6 +109,6 @@ func BenchmarkCompileWhereNoCache(b *testing.B) { w := WhereConditions( &ColumnValue{Column: &Column{Name: "baz"}, Operator: "=", Value: NewValue(99)}, ) - w.Compile(defaultTemplate) + _, _ = w.Compile(defaultTemplate) } } diff --git a/internal/sqladapter/result.go b/internal/sqladapter/result.go index b35e43f0..9070b9ef 100644 --- a/internal/sqladapter/result.go +++ b/internal/sqladapter/result.go @@ -56,7 +56,6 @@ type result struct { prevPageCursorValue interface{} fields []interface{} - columns []interface{} orderBy []interface{} groupBy []interface{} conds [][]interface{} @@ -100,12 +99,11 @@ func (r *Result) where(conds []interface{}) *Result { }) } -func (r *Result) setErr(err error) error { +func (r *Result) setErr(err error) { if err == nil { - return nil + return } r.err.Store(err) - return err } // Err returns the last error that has happened with the result set, @@ -226,20 +224,24 @@ func (r *Result) String() string { func (r *Result) All(dst interface{}) error { query, err := r.buildPaginator() if err != nil { - return r.setErr(err) + r.setErr(err) + return err } err = query.Iterator().All(dst) - return r.setErr(err) + r.setErr(err) + return err } // One fetches only one Result from the set. func (r *Result) One(dst interface{}) error { query, err := r.buildPaginator() if err != nil { - return r.setErr(err) + r.setErr(err) + return err } err = query.Iterator().One(dst) - return r.setErr(err) + r.setErr(err) + return err } // Next fetches the next Result from the set. @@ -262,6 +264,7 @@ func (r *Result) Next(dst interface{}) bool { if err := r.iter.Err(); err != db.ErrNoMoreRows { r.setErr(err) + return false } return false @@ -271,17 +274,21 @@ func (r *Result) Next(dst interface{}) bool { func (r *Result) Delete() error { query, err := r.buildDelete() if err != nil { - return r.setErr(err) + r.setErr(err) + return err } _, err = query.Exec() - return r.setErr(err) + r.setErr(err) + return err } // Close closes the Result set. func (r *Result) Close() error { if r.iter != nil { - return r.setErr(r.iter.Close()) + err := r.iter.Close() + r.setErr(err) + return err } return nil } @@ -291,22 +298,26 @@ func (r *Result) Close() error { func (r *Result) Update(values interface{}) error { query, err := r.buildUpdate(values) if err != nil { - return r.setErr(err) + r.setErr(err) + return err } _, err = query.Exec() - return r.setErr(err) + r.setErr(err) + return err } func (r *Result) TotalPages() (uint, error) { query, err := r.buildPaginator() if err != nil { - return 0, r.setErr(err) + r.setErr(err) + return 0, err } total, err := query.TotalPages() if err != nil { - return 0, r.setErr(err) + r.setErr(err) + return 0, err } return total, nil @@ -315,12 +326,14 @@ func (r *Result) TotalPages() (uint, error) { func (r *Result) TotalEntries() (uint64, error) { query, err := r.buildPaginator() if err != nil { - return 0, r.setErr(err) + r.setErr(err) + return 0, err } total, err := query.TotalEntries() if err != nil { - return 0, r.setErr(err) + r.setErr(err) + return 0, err } return total, nil @@ -330,7 +343,8 @@ func (r *Result) TotalEntries() (uint64, error) { func (r *Result) Exists() (bool, error) { query, err := r.buildCount() if err != nil { - return false, r.setErr(err) + r.setErr(err) + return false, err } query = query.Limit(1) @@ -343,7 +357,8 @@ func (r *Result) Exists() (bool, error) { if err == db.ErrNoMoreRows { return false, nil } - return false, r.setErr(err) + r.setErr(err) + return false, err } if value.Exists > 0 { @@ -357,7 +372,8 @@ func (r *Result) Exists() (bool, error) { func (r *Result) Count() (uint64, error) { query, err := r.buildCount() if err != nil { - return 0, r.setErr(err) + r.setErr(err) + return 0, err } counter := struct { @@ -367,7 +383,8 @@ func (r *Result) Count() (uint64, error) { if err == db.ErrNoMoreRows { return 0, nil } - return 0, r.setErr(err) + r.setErr(err) + return 0, err } return counter.Count, nil diff --git a/internal/sqladapter/tx.go b/internal/sqladapter/tx.go index 5897f09d..c1d2a403 100644 --- a/internal/sqladapter/tx.go +++ b/internal/sqladapter/tx.go @@ -71,10 +71,7 @@ func newBaseTx(tx *sql.Tx) BaseTx { func (b *baseTx) Committed() bool { committed := b.committed.Load() - if committed != nil { - return true - } - return false + return committed != nil } func (b *baseTx) Commit() (err error) { @@ -105,7 +102,7 @@ func RunTx(d sqlbuilder.Database, ctx context.Context, fn func(tx sqlbuilder.Tx) defer tx.Close() if err := fn(tx); err != nil { - tx.Rollback() + _ = tx.Rollback() return err } return tx.Commit() diff --git a/internal/testsuite/generic_suite.go b/internal/testsuite/generic_suite.go index 6165e240..28c806a2 100644 --- a/internal/testsuite/generic_suite.go +++ b/internal/testsuite/generic_suite.go @@ -103,10 +103,7 @@ var ( ) func even(i int) bool { - if i%2 == 0 { - return true - } - return false + return i%2 == 0 } func fib(i uint64) uint64 { diff --git a/internal/testsuite/sql_suite.go b/internal/testsuite/sql_suite.go index 5f285543..8f00bbb4 100644 --- a/internal/testsuite/sql_suite.go +++ b/internal/testsuite/sql_suite.go @@ -938,10 +938,10 @@ func (s *SQLTestSuite) TestNullableFields() { // Testing insertion of invalid nulls. test := testType{ - NullStringTest: sql.NullString{"", false}, - NullInt64Test: sql.NullInt64{0, false}, - NullFloat64Test: sql.NullFloat64{0.0, false}, - NullBoolTest: sql.NullBool{false, false}, + NullStringTest: sql.NullString{String: "", Valid: false}, + NullInt64Test: sql.NullInt64{Int64: 0, Valid: false}, + NullFloat64Test: sql.NullFloat64{Float64: 0.0, Valid: false}, + NullBoolTest: sql.NullBool{Bool: false, Valid: false}, } id, err := col.Insert(testType{}) @@ -957,10 +957,10 @@ func (s *SQLTestSuite) TestNullableFields() { // Testing insertion of valid nulls. test = testType{ - NullStringTest: sql.NullString{"", true}, - NullInt64Test: sql.NullInt64{0, true}, - NullFloat64Test: sql.NullFloat64{0.0, true}, - NullBoolTest: sql.NullBool{false, true}, + NullStringTest: sql.NullString{String: "", Valid: true}, + NullInt64Test: sql.NullInt64{Int64: 0, Valid: true}, + NullFloat64Test: sql.NullFloat64{Float64: 0.0, Valid: true}, + NullBoolTest: sql.NullBool{Bool: false, Valid: true}, } id, err = col.Insert(test) @@ -1018,6 +1018,7 @@ func (s *SQLTestSuite) TestInsertAndDelete() { total, err := res.Count() s.NoError(err) + s.Greater(total, uint64(0)) err = res.Delete() s.NoError(err) @@ -1324,7 +1325,7 @@ func (s *SQLTestSuite) TestUpdateWithNullColumn() { s.NotEqual(nil, item.Name) s.Equal(name, *item.Name) - artist.Find(id).Update(Artist{Name: nil}) + err = artist.Find(id).Update(Artist{Name: nil}) s.NoError(err) var item2 Artist @@ -1823,7 +1824,7 @@ func (s *SQLTestSuite) TestExhaustConnectionPool() { if err != nil { tFatal(err) } - tLogf("Tx %d: OK (time to connect: %v)", i, time.Now().Sub(start)) + tLogf("Tx %d: OK (time to connect: %v)", i, time.Since(start)) if !sess.LoggingEnabled() { tLogf("Expecting logging to be enabled") diff --git a/lib/reflectx/reflect.go b/lib/reflectx/reflect.go index c9faa6aa..028163fe 100644 --- a/lib/reflectx/reflect.go +++ b/lib/reflectx/reflect.go @@ -288,9 +288,7 @@ type typeQueue struct { // A copying append that creates a new slice each time. func apnd(is []int, i int) []int { x := make([]int, len(is)+1) - for p, n := range is { - x[p] = n - } + copy(x, is) x[len(x)-1] = i return x } diff --git a/lib/sqlbuilder/builder.go b/lib/sqlbuilder/builder.go index 8a621aab..91ab9a5b 100644 --- a/lib/sqlbuilder/builder.go +++ b/lib/sqlbuilder/builder.go @@ -60,14 +60,6 @@ type hasIsZero interface { IsZero() bool } -type hasArguments interface { - Arguments() []interface{} -} - -type hasStatement interface { - statement() *exql.Statement -} - type iterator struct { sess exprDB cursor *sql.Rows // This is the main query cursor. It starts as a nil value. @@ -80,8 +72,7 @@ type fieldValue struct { } var ( - reInvisibleChars = regexp.MustCompile(`[\s\r\n\t]+`) - reColumnCompareExclude = regexp.MustCompile(`[^a-zA-Z0-9]`) + reInvisibleChars = regexp.MustCompile(`[\s\r\n\t]+`) ) var ( @@ -351,18 +342,6 @@ func Map(item interface{}, options *MapOptions) ([]string, []interface{}, error) return fv.fields, fv.values, nil } -func extractArguments(fragments []interface{}) []interface{} { - args := []interface{}{} - l := len(fragments) - for i := 0; i < l; i++ { - switch v := fragments[i].(type) { - case hasArguments: // TODO: use this on other places where we want to extract arguments. - args = append(args, v.Arguments()...) - } - } - return args -} - func columnFragments(columns []interface{}) ([]exql.Fragment, []interface{}, error) { l := len(columns) f := make([]exql.Fragment, l) @@ -486,7 +465,7 @@ func (iter *iterator) Next(dst ...interface{}) bool { if err := iter.next(dst...); err != nil { // ignore db.ErrNoMoreRows, just break. if err != db.ErrNoMoreRows { - iter.setErr(err) + _ = iter.setErr(err) } return false } @@ -557,10 +536,6 @@ type exprProxy struct { t *exql.Template } -func newSqlgenProxy(db *sql.DB, t *exql.Template) *exprProxy { - return &exprProxy{db: db, t: t} -} - func (p *exprProxy) Context() context.Context { log.Printf("Missing context") return context.Background() diff --git a/lib/sqlbuilder/builder_test.go b/lib/sqlbuilder/builder_test.go index 591add40..96601c49 100644 --- a/lib/sqlbuilder/builder_test.go +++ b/lib/sqlbuilder/builder_test.go @@ -1342,49 +1342,49 @@ func TestPaginate(t *testing.T) { func BenchmarkDelete1(b *testing.B) { bt := WithTemplate(&testTemplate) for n := 0; n < b.N; n++ { - bt.DeleteFrom("artist").Where("name = ?", "Chavela Vargas").Limit(1).String() + _ = bt.DeleteFrom("artist").Where("name = ?", "Chavela Vargas").Limit(1).String() } } func BenchmarkDelete2(b *testing.B) { bt := WithTemplate(&testTemplate) for n := 0; n < b.N; n++ { - bt.DeleteFrom("artist").Where("id > 5").String() + _ = bt.DeleteFrom("artist").Where("id > 5").String() } } func BenchmarkInsert1(b *testing.B) { bt := WithTemplate(&testTemplate) for n := 0; n < b.N; n++ { - bt.InsertInto("artist").Values(10, "Ryuichi Sakamoto").Values(11, "Alondra de la Parra").Values(12, "Haruki Murakami").String() + _ = bt.InsertInto("artist").Values(10, "Ryuichi Sakamoto").Values(11, "Alondra de la Parra").Values(12, "Haruki Murakami").String() } } func BenchmarkInsert2(b *testing.B) { bt := WithTemplate(&testTemplate) for n := 0; n < b.N; n++ { - bt.InsertInto("artist").Values(map[string]string{"id": "12", "name": "Chavela Vargas"}).String() + _ = bt.InsertInto("artist").Values(map[string]string{"id": "12", "name": "Chavela Vargas"}).String() } } func BenchmarkInsert3(b *testing.B) { bt := WithTemplate(&testTemplate) for n := 0; n < b.N; n++ { - bt.InsertInto("artist").Values(map[string]string{"id": "12", "name": "Chavela Vargas"}).Returning("id").String() + _ = bt.InsertInto("artist").Values(map[string]string{"id": "12", "name": "Chavela Vargas"}).Returning("id").String() } } func BenchmarkInsert4(b *testing.B) { bt := WithTemplate(&testTemplate) for n := 0; n < b.N; n++ { - bt.InsertInto("artist").Values(map[string]interface{}{"name": "Chavela Vargas", "id": 12}).String() + _ = bt.InsertInto("artist").Values(map[string]interface{}{"name": "Chavela Vargas", "id": 12}).String() } } func BenchmarkInsert5(b *testing.B) { bt := WithTemplate(&testTemplate) for n := 0; n < b.N; n++ { - bt.InsertInto("artist").Values(struct { + _ = bt.InsertInto("artist").Values(struct { ID int `db:"id"` Name string `db:"name"` }{12, "Chavela Vargas"}).String() @@ -1394,35 +1394,35 @@ func BenchmarkInsert5(b *testing.B) { func BenchmarkSelect1(b *testing.B) { bt := WithTemplate(&testTemplate) for n := 0; n < b.N; n++ { - bt.Select().From("artist").OrderBy("name DESC").String() + _ = bt.Select().From("artist").OrderBy("name DESC").String() } } func BenchmarkSelect2(b *testing.B) { bt := WithTemplate(&testTemplate) for n := 0; n < b.N; n++ { - bt.Select("id").From("artist").Where(`name LIKE ? OR name LIKE ?`, `%Miya%`, `F%`).String() + _ = bt.Select("id").From("artist").Where(`name LIKE ? OR name LIKE ?`, `%Miya%`, `F%`).String() } } func BenchmarkSelect3(b *testing.B) { bt := WithTemplate(&testTemplate) for n := 0; n < b.N; n++ { - bt.Select().From("artist a", "publication as p").Where("p.author_id = a.id").Limit(1).String() + _ = bt.Select().From("artist a", "publication as p").Where("p.author_id = a.id").Limit(1).String() } } func BenchmarkSelect4(b *testing.B) { bt := WithTemplate(&testTemplate) for n := 0; n < b.N; n++ { - bt.SelectFrom("artist").Join("publication p").On("p.author_id = a.id").Where("a.id = 2").Limit(1).String() + _ = bt.SelectFrom("artist").Join("publication p").On("p.author_id = a.id").Where("a.id = 2").Limit(1).String() } } func BenchmarkSelect5(b *testing.B) { bt := WithTemplate(&testTemplate) for n := 0; n < b.N; n++ { - bt.SelectFrom("artist a"). + _ = bt.SelectFrom("artist a"). LeftJoin("publication p1").On("p1.id = a.id"). RightJoin("publication p2").On("p2.id = a.id"). String() @@ -1432,21 +1432,21 @@ func BenchmarkSelect5(b *testing.B) { func BenchmarkUpdate1(b *testing.B) { bt := WithTemplate(&testTemplate) for n := 0; n < b.N; n++ { - bt.Update("artist").Set("name", "Artist").String() + _ = bt.Update("artist").Set("name", "Artist").String() } } func BenchmarkUpdate2(b *testing.B) { bt := WithTemplate(&testTemplate) for n := 0; n < b.N; n++ { - bt.Update("artist").Set("name = ?", "Artist").Where("id <", 5).String() + _ = bt.Update("artist").Set("name = ?", "Artist").Where("id <", 5).String() } } func BenchmarkUpdate3(b *testing.B) { bt := WithTemplate(&testTemplate) for n := 0; n < b.N; n++ { - bt.Update("artist").Set(struct { + _ = bt.Update("artist").Set(struct { Nombre string `db:"name"` }{"Artist"}).Set(map[string]string{"last_name": "Foo"}).Where(db.Cond{"id <": 5}).String() } @@ -1455,14 +1455,14 @@ func BenchmarkUpdate3(b *testing.B) { func BenchmarkUpdate4(b *testing.B) { bt := WithTemplate(&testTemplate) for n := 0; n < b.N; n++ { - bt.Update("artist").Set(map[string]string{"name": "Artist"}).Where(db.Cond{"id <": 5}).String() + _ = bt.Update("artist").Set(map[string]string{"name": "Artist"}).Where(db.Cond{"id <": 5}).String() } } func BenchmarkUpdate5(b *testing.B) { bt := WithTemplate(&testTemplate) for n := 0; n < b.N; n++ { - bt.Update("artist").Set( + _ = bt.Update("artist").Set( "name = ? || ' ' || ? || id", "Artist", "#", "id = id + ?", 10, ).Where("id > ?", 0).String() diff --git a/lib/sqlbuilder/fetch.go b/lib/sqlbuilder/fetch.go index 1bf355a8..00e02192 100644 --- a/lib/sqlbuilder/fetch.go +++ b/lib/sqlbuilder/fetch.go @@ -58,7 +58,7 @@ func fetchRow(iter *iterator, dst interface{}) error { next := rows.Next() - if next == false { + if !next { if err = rows.Err(); err != nil { return err } @@ -214,7 +214,7 @@ func fetchResult(iter *iterator, itemT reflect.Type, columns []string) (reflect. return item, nil } -func reset(data interface{}) error { +func reset(data interface{}) { // Resetting element. v := reflect.ValueOf(data).Elem() t := v.Type() @@ -229,5 +229,4 @@ func reset(data interface{}) error { } v.Set(z) - return nil } diff --git a/lib/sqlbuilder/insert.go b/lib/sqlbuilder/insert.go index 9e9bfc79..6ebcccbe 100644 --- a/lib/sqlbuilder/insert.go +++ b/lib/sqlbuilder/insert.go @@ -15,7 +15,6 @@ type inserterQuery struct { columns []exql.Fragment values []*exql.Values arguments []interface{} - extra string amendFn func(string) string } @@ -41,9 +40,7 @@ func (iq *inserterQuery) processValues() ([]*exql.Values, []interface{}, error) values, arguments = append(values, vals), append(arguments, args...) if len(iq.columns) == 0 { - for _, c := range columns.Columns { - iq.columns = append(iq.columns, c) - } + iq.columns = append(iq.columns, columns.Columns...) } continue } @@ -276,12 +273,11 @@ func (ins *inserter) Base() interface{} { return &inserterQuery{} } -func columnsToFragments(dst *[]exql.Fragment, columns []string) error { +func columnsToFragments(dst *[]exql.Fragment, columns []string) { l := len(columns) f := make([]exql.Fragment, l) for i := 0; i < l; i++ { f[i] = exql.ColumnWithName(columns[i]) } *dst = append(*dst, f...) - return nil } diff --git a/lib/sqlbuilder/paginate.go b/lib/sqlbuilder/paginate.go index 5e1ab337..1aa9ada0 100644 --- a/lib/sqlbuilder/paginate.go +++ b/lib/sqlbuilder/paginate.go @@ -12,7 +12,6 @@ import ( ) var ( - errZeroPageSize = errors.New("Illegal page size (cannot be zero)") errMissingCursorColumn = errors.New("Missing cursor column") ) @@ -39,11 +38,15 @@ func newPaginator(sel Selector, pageSize uint) Paginator { func (pq *paginatorQuery) count() (uint64, error) { var count uint64 + row, err := pq.sel.(*selector).setColumns(db.Raw("count(1) AS _t")). Limit(0). Offset(0). OrderBy(nil). QueryRow() + if err != nil { + return 0, err + } err = row.Scan(&count) if err != nil { @@ -136,7 +139,7 @@ func (pag *paginator) TotalPages() (uint, error) { return 0, nil } - if pq.pageSize <= 0 { + if pq.pageSize < 1 { return 1, nil } diff --git a/lib/sqlbuilder/select.go b/lib/sqlbuilder/select.go index 8f2bbc15..fa0436bd 100644 --- a/lib/sqlbuilder/select.go +++ b/lib/sqlbuilder/select.go @@ -16,8 +16,6 @@ type selectorQuery struct { table *exql.Columns tableArgs []interface{} - as string - distinct bool where *exql.Where diff --git a/lib/sqlbuilder/template_test.go b/lib/sqlbuilder/template_test.go index a81db9e0..c3e175fc 100644 --- a/lib/sqlbuilder/template_test.go +++ b/lib/sqlbuilder/template_test.go @@ -150,8 +150,6 @@ const ( DROP TABLE {{.Table | compile}} ` - defaultGroupByColumnLayout = `{{.Column}}` - defaultGroupByLayout = ` {{if .GroupColumns}} GROUP BY {{.GroupColumns}} diff --git a/lib/sqlbuilder/update.go b/lib/sqlbuilder/update.go index 291b1c47..ec458107 100644 --- a/lib/sqlbuilder/update.go +++ b/lib/sqlbuilder/update.go @@ -19,8 +19,6 @@ type updaterQuery struct { where *exql.Where whereArgs []interface{} - err error - amendFn func(string) string } diff --git a/logger.go b/logger.go index 184b47ca..d5fd2f3f 100644 --- a/logger.go +++ b/logger.go @@ -43,8 +43,7 @@ const ( ) var ( - reInvisibleChars = regexp.MustCompile(`[\s\r\n\t]+`) - reColumnCompareExclude = regexp.MustCompile(`[^a-zA-Z0-9]`) + reInvisibleChars = regexp.MustCompile(`[\s\r\n\t]+`) ) // QueryStatus represents the status of a query after being executed. diff --git a/mongo/collection.go b/mongo/collection.go index 1b7796c5..17b848b8 100644 --- a/mongo/collection.go +++ b/mongo/collection.go @@ -35,7 +35,6 @@ import ( // Collection represents a mongodb collection. type Collection struct { - name string parent *Source collection *mgo.Collection } @@ -43,7 +42,7 @@ type Collection struct { var ( // idCache should be a struct if we're going to cache more than just // _id field here - idCache = make(map[reflect.Type]string, 0) + idCache = make(map[reflect.Type]string) idCacheMutex sync.RWMutex ) @@ -108,9 +107,9 @@ func compare(field string, cmp db.Comparison) (string, interface{}) { } return field, bson.M{"$ne": value} case db.ComparisonOperatorRegExp, db.ComparisonOperatorLike: - return field, bson.RegEx{value.(string), ""} + return field, bson.RegEx{Pattern: value.(string), Options: ""} case db.ComparisonOperatorNotRegExp, db.ComparisonOperatorNotLike: - return field, bson.M{"$not": bson.RegEx{value.(string), ""}} + return field, bson.M{"$not": bson.RegEx{Pattern: value.(string), Options: ""}} } if cmpOp, ok := comparisonOperators[op]; ok { @@ -284,7 +283,9 @@ func (col *Collection) Insert(item interface{}) (interface{}, error) { // Now append data the user wants to append. if err = col.collection.Update(bson.M{"_id": id}, item); err != nil { // Cleanup allocated ID - col.collection.Remove(bson.M{"_id": id}) + if err := col.collection.Remove(bson.M{"_id": id}); err != nil { + return nil, err + } return nil, err } } @@ -296,10 +297,7 @@ func (col *Collection) Insert(item interface{}) (interface{}, error) { func (col *Collection) Exists() bool { query := col.parent.database.C(`system.namespaces`).Find(map[string]string{`name`: fmt.Sprintf(`%s.%s`, col.parent.database.Name, col.collection.Name)}) count, _ := query.Count() - if count > 0 { - return true - } - return false + return count > 0 } // Fetches object _id or generates a new one if object doesn't have one or the one it has is invalid diff --git a/mongo/connection.go b/mongo/connection.go index 09bac609..98728078 100644 --- a/mongo/connection.go +++ b/mongo/connection.go @@ -83,7 +83,7 @@ func (c ConnectionURL) String() (s string) { func ParseURL(s string) (conn ConnectionURL, err error) { var u *url.URL - if strings.HasPrefix(s, connectionScheme+"://") == false { + if !strings.HasPrefix(s, connectionScheme+"://") { return conn, fmt.Errorf(`Expecting mongodb:// connection scheme.`) } diff --git a/mongo/helper_test.go b/mongo/helper_test.go index e633c976..c78fa1d2 100644 --- a/mongo/helper_test.go +++ b/mongo/helper_test.go @@ -28,8 +28,8 @@ import ( mgo "gopkg.in/mgo.v2" db "upper.io/db.v3" - "upper.io/db.v3/lib/sqlbuilder" "upper.io/db.v3/internal/testsuite" + "upper.io/db.v3/lib/sqlbuilder" ) var settings = ConnectionURL{ @@ -74,22 +74,21 @@ func (h *Helper) TearUp() error { var col *mgo.Collection col = mgod.DB(settings.Database).C("birthdays") - col.DropCollection() + _ = col.DropCollection() col = mgod.DB(settings.Database).C("fibonacci") - col.DropCollection() + _ = col.DropCollection() col = mgod.DB(settings.Database).C("is_even") - col.DropCollection() + _ = col.DropCollection() col = mgod.DB(settings.Database).C("CaSe_TesT") - col.DropCollection() + _ = col.DropCollection() // Getting a pointer to the "artist" collection. artist := h.sess.Collection("artist") _ = artist.Truncate() - for i := 0; i < 999; i++ { _, err = artist.Insert(artistType{ Name: fmt.Sprintf("artist-%d", i), diff --git a/mongo/mongo_test.go b/mongo/mongo_test.go index 0ec73201..e9718534 100644 --- a/mongo/mongo_test.go +++ b/mongo/mongo_test.go @@ -310,7 +310,7 @@ func (s *AdapterTests) TestGroup() { stats = sess.Collection("statsTest") // Truncating table. - stats.Truncate() + _ = stats.Truncate() // Adding row append. for i := 0; i < 1000; i++ { @@ -590,7 +590,8 @@ func (s *AdapterTests) TestDataTypes() { // Trying to dump the subject into an empty structure of the same type. var item testValuesStruct - res.One(&item) + err = res.One(&item) + s.NoError(err) // The original value and the test subject must match. s.Equal(testValues, item) diff --git a/mongo/result.go b/mongo/result.go index 61a1d9d3..50d7ae85 100644 --- a/mongo/result.go +++ b/mongo/result.go @@ -291,11 +291,10 @@ func (res *result) Err() error { return res.err } -func (res *result) setErr(err error) error { +func (res *result) setErr(err error) { res.errMu.Lock() defer res.errMu.Unlock() - - return err + res.err = err } func (res *result) Next(dst interface{}) bool { @@ -404,7 +403,9 @@ func (res *result) build() (*resultQuery, error) { rq := rqi.(*resultQuery) if !rq.cursorCond.Empty() { - rq.and(rq.cursorCond) + if err := rq.and(rq.cursorCond); err != nil { + return nil, err + } } if rq.cursorColumn != "" { diff --git a/mssql/collection.go b/mssql/collection.go index ceb511b4..f4fb340a 100644 --- a/mssql/collection.go +++ b/mssql/collection.go @@ -108,7 +108,9 @@ func (t *table) Insert(item interface{}) (interface{}, error) { if err != nil { return nil, err } - defer t.d.Exec("SET IDENTITY_INSERT " + t.Name() + " OFF") + defer func() { + _, _ = t.d.Exec("SET IDENTITY_INSERT " + t.Name() + " OFF") + }() } } diff --git a/mssql/connection.go b/mssql/connection.go index 766ea216..4e79e699 100644 --- a/mssql/connection.go +++ b/mssql/connection.go @@ -64,7 +64,7 @@ func (c ConnectionURL) String() (s string) { RawQuery: params.Encode(), } - u.Path, _ = c.Options["instance"] + u.Path = c.Options["instance"] if c.User != "" || c.Password != "" { u.User = url.UserPassword(c.User, c.Password) diff --git a/mssql/tx.go b/mssql/tx.go index 62e70fac..ed6067a9 100644 --- a/mssql/tx.go +++ b/mssql/tx.go @@ -37,8 +37,7 @@ var ( ) func (t *tx) WithContext(ctx context.Context) sqlbuilder.Tx { - var newTx tx - newTx = *t + newTx := *t newTx.DatabaseTx.SetContext(ctx) return &newTx } diff --git a/mysql/database.go b/mysql/database.go index a88e57ea..e7dcb2f9 100644 --- a/mysql/database.go +++ b/mysql/database.go @@ -158,11 +158,6 @@ func (d *database) ConvertValues(values []interface{}) []interface{} { switch v := values[i].(type) { case *string, *bool, *int, *uint, *int64, *uint64, *int32, *uint32, *int16, *uint16, *int8, *uint8, *float32, *float64, *[]uint8, sql.Scanner, *sql.Scanner, *time.Time: case string, bool, int, uint, int64, uint64, int32, uint32, int16, uint16, int8, uint8, float32, float64, []uint8, driver.Valuer, *driver.Valuer, time.Time: - case JSONMap, JSON: - // Already with scanner/valuer. - case *JSONMap, *JSON: - // Already with scanner/valuer. - case *map[string]interface{}: values[i] = (*JSONMap)(v) diff --git a/mysql/helper_test.go b/mysql/helper_test.go index 54819d2e..d030f8aa 100644 --- a/mysql/helper_test.go +++ b/mysql/helper_test.go @@ -29,8 +29,8 @@ import ( db "upper.io/db.v3" "upper.io/db.v3/internal/sqladapter" - "upper.io/db.v3/lib/sqlbuilder" "upper.io/db.v3/internal/testsuite" + "upper.io/db.v3/lib/sqlbuilder" ) var settings = ConnectionURL{ @@ -52,11 +52,6 @@ type Helper struct { } func cleanUp(sess sqlbuilder.Database) error { - stats, err := getStats(sess) - if err != nil { - return err - } - if activeStatements := sqladapter.NumActiveStatements(); activeStatements > 128 { return fmt.Errorf("Expecting active statements to be at most 128, got %d", activeStatements) } @@ -67,6 +62,8 @@ func cleanUp(sess sqlbuilder.Database) error { return fmt.Errorf("Expecting active statements to be 0, got %d", activeStatements) } + var err error + var stats map[string]int for i := 0; i < 10; i++ { stats, err = getStats(sess) if err != nil { diff --git a/mysql/template.go b/mysql/template.go index 265d0df9..7a0f69e9 100644 --- a/mysql/template.go +++ b/mysql/template.go @@ -34,10 +34,8 @@ const ( adapterValueQuote = `'{{.}}'` adapterAndKeyword = `AND` adapterOrKeyword = `OR` - adapterNotKeyword = `NOT` adapterDescKeyword = `DESC` adapterAscKeyword = `ASC` - adapterDefaultOperator = `=` adapterAssignmentOperator = `=` adapterClauseGroup = `({{.}})` adapterClauseOperator = ` {{.}} ` diff --git a/mysql/tx.go b/mysql/tx.go index bba938a3..c8d27cbc 100644 --- a/mysql/tx.go +++ b/mysql/tx.go @@ -37,8 +37,7 @@ var ( ) func (t *tx) WithContext(ctx context.Context) sqlbuilder.Tx { - var newTx tx - newTx = *t + newTx := *t newTx.DatabaseTx.SetContext(ctx) return &newTx } diff --git a/postgresql/connection.go b/postgresql/connection.go index 06f4b038..7f4a5520 100644 --- a/postgresql/connection.go +++ b/postgresql/connection.go @@ -72,12 +72,6 @@ func (vs values) Isset(k string) bool { return ok } -// A typical PostgreSQL connection URL looks like: -// -// "postgres://bob:secret@1.2.3.4:5432/mydb?sslmode=verify-full" - -const connectionScheme = `postgres` - // ConnectionURL represents a parsed PostgreSQL connection URL. // // You can use a ConnectionURL struct as an argument for Open: diff --git a/postgresql/database.go b/postgresql/database.go index ac7129c1..0855eb55 100644 --- a/postgresql/database.go +++ b/postgresql/database.go @@ -160,10 +160,6 @@ func (d *database) ConvertValues(values []interface{}) []interface{} { // Handled by pq. case string, bool, int, uint, int64, uint64, int32, uint32, int16, uint16, int8, uint8, float32, float64, []uint8, driver.Valuer, *driver.Valuer, time.Time: // Handled by pq. - case StringArray, Int64Array, BoolArray, GenericArray, Float64Array, JSONBMap, JSONB: - // Already with scanner/valuer. - case *StringArray, *Int64Array, *BoolArray, *GenericArray, *Float64Array, *JSONBMap, *JSONB: - // Already with scanner/valuer. case *[]int64: values[i] = (*Int64Array)(v) diff --git a/postgresql/helper_test.go b/postgresql/helper_test.go index 1d3aa29e..3a484ae9 100644 --- a/postgresql/helper_test.go +++ b/postgresql/helper_test.go @@ -28,8 +28,8 @@ import ( db "upper.io/db.v3" "upper.io/db.v3/internal/sqladapter" - "upper.io/db.v3/lib/sqlbuilder" "upper.io/db.v3/internal/testsuite" + "upper.io/db.v3/lib/sqlbuilder" ) var settings = ConnectionURL{ @@ -47,18 +47,13 @@ type Helper struct { } func cleanUp(sess sqlbuilder.Database) error { - stats, err := getStats(sess) - if err != nil { - return err - } - if activeStatements := sqladapter.NumActiveStatements(); activeStatements > 128 { - return fmt.Errorf("Expecting active statements to be at most 128, got %d", activeStatements) + return fmt.Errorf("Expecting active statements to be less than 128, got %d", activeStatements) } sess.ClearCache() - stats, err = getStats(sess) + stats, err := getStats(sess) if err != nil { return err } diff --git a/postgresql/postgresql.go b/postgresql/postgresql.go index 32a8db4b..214412ec 100644 --- a/postgresql/postgresql.go +++ b/postgresql/postgresql.go @@ -29,8 +29,6 @@ import ( "upper.io/db.v3/lib/sqlbuilder" ) -const sqlDriver = `postgres` - // Adapter is the unique name that you can use to refer to this adapter. const Adapter = `postgresql` diff --git a/postgresql/postgresql_test.go b/postgresql/postgresql_test.go index 158c7ab8..40537b18 100644 --- a/postgresql/postgresql_test.go +++ b/postgresql/postgresql_test.go @@ -1015,7 +1015,7 @@ func (s *AdapterTests) TestStringAndInt64Array() { driver := sess.Driver().(*sql.DB) defer func() { - driver.Exec(`DROP TABLE IF EXISTS array_types`) + _, _ = driver.Exec(`DROP TABLE IF EXISTS array_types`) }() if _, err := driver.Exec(` diff --git a/postgresql/tx.go b/postgresql/tx.go index e62b6626..408e9f82 100644 --- a/postgresql/tx.go +++ b/postgresql/tx.go @@ -37,8 +37,7 @@ var ( ) func (t *tx) WithContext(ctx context.Context) sqlbuilder.Tx { - var newTx tx - newTx = *t + newTx := *t newTx.DatabaseTx.SetContext(ctx) return &newTx } diff --git a/ql/connection.go b/ql/connection.go index 23fa94ad..e613b8c6 100644 --- a/ql/connection.go +++ b/ql/connection.go @@ -44,7 +44,7 @@ func (c ConnectionURL) String() (s string) { } // Does the database have an existing name? - if strings.HasPrefix(c.Database, "/") == false { + if !strings.HasPrefix(c.Database, "/") { c.Database, _ = filepath.Abs(c.Database) } @@ -72,7 +72,7 @@ func (c ConnectionURL) String() (s string) { func ParseURL(s string) (conn ConnectionURL, err error) { var u *url.URL - if strings.HasPrefix(s, connectionScheme+"://") == false { + if !strings.HasPrefix(s, connectionScheme+"://") { return conn, fmt.Errorf(`Expecting file:// connection scheme.`) } diff --git a/ql/helper_test.go b/ql/helper_test.go index 050f844b..362a95ed 100644 --- a/ql/helper_test.go +++ b/ql/helper_test.go @@ -26,8 +26,8 @@ import ( "os" db "upper.io/db.v3" - "upper.io/db.v3/lib/sqlbuilder" "upper.io/db.v3/internal/testsuite" + "upper.io/db.v3/lib/sqlbuilder" ) var settings = ConnectionURL{ @@ -157,7 +157,9 @@ func (h *Helper) TearUp() error { _ = tx.Rollback() return err } - tx.Commit() + if err := tx.Commit(); err != nil { + return err + } } return nil diff --git a/ql/tx.go b/ql/tx.go index ff837fb8..500c9e66 100644 --- a/ql/tx.go +++ b/ql/tx.go @@ -37,8 +37,7 @@ var ( ) func (t *tx) WithContext(ctx context.Context) sqlbuilder.Tx { - var newTx tx - newTx = *t + newTx := *t newTx.DatabaseTx.SetContext(ctx) return &newTx } diff --git a/settings.go b/settings.go index e427a1bd..67449421 100644 --- a/settings.go +++ b/settings.go @@ -105,10 +105,7 @@ func (c *settings) SetLogger(lg Logger) { } func (c *settings) binaryOption(opt *uint32) bool { - if atomic.LoadUint32(opt) == 1 { - return true - } - return false + return atomic.LoadUint32(opt) == 1 } func (c *settings) setBinaryOption(opt *uint32, value bool) { @@ -174,8 +171,13 @@ func (c *settings) MaxOpenConns() int { // NewSettings returns a new settings value prefilled with the current default // settings. func NewSettings() Settings { - newSettings := *(DefaultSettings.(*settings)) - return &newSettings + def := DefaultSettings.(*settings) + return &settings{ + preparedStatementCacheEnabled: def.preparedStatementCacheEnabled, + connMaxLifetime: def.connMaxLifetime, + maxIdleConns: def.maxIdleConns, + maxOpenConns: def.maxOpenConns, + } } // DefaultSettings provides default global configuration settings for database diff --git a/sqlite/connection.go b/sqlite/connection.go index aa060e49..ff0cf358 100644 --- a/sqlite/connection.go +++ b/sqlite/connection.go @@ -45,7 +45,7 @@ func (c ConnectionURL) String() (s string) { } // Did the user provided a full database path? - if strings.HasPrefix(c.Database, "/") == false { + if !strings.HasPrefix(c.Database, "/") { c.Database, _ = filepath.Abs(c.Database) if runtime.GOOS == "windows" { // Closes https://github.com/upper/db/issues/60 @@ -81,7 +81,7 @@ func (c ConnectionURL) String() (s string) { func ParseURL(s string) (conn ConnectionURL, err error) { var u *url.URL - if strings.HasPrefix(s, connectionScheme+"://") == false { + if !strings.HasPrefix(s, connectionScheme+"://") { return conn, fmt.Errorf(`Expecting file:// connection scheme.`) } diff --git a/sqlite/template.go b/sqlite/template.go index 7bb7e0d2..4354997b 100644 --- a/sqlite/template.go +++ b/sqlite/template.go @@ -34,10 +34,8 @@ const ( adapterValueQuote = `'{{.}}'` adapterAndKeyword = `AND` adapterOrKeyword = `OR` - adapterNotKeyword = `NOT` adapterDescKeyword = `DESC` adapterAscKeyword = `ASC` - adapterDefaultOperator = `=` adapterAssignmentOperator = `=` adapterClauseGroup = `({{.}})` adapterClauseOperator = ` {{.}} ` diff --git a/sqlite/tx.go b/sqlite/tx.go index 74057869..12d2e43d 100644 --- a/sqlite/tx.go +++ b/sqlite/tx.go @@ -37,8 +37,7 @@ var ( ) func (t *tx) WithContext(ctx context.Context) sqlbuilder.Tx { - var newTx tx - newTx = *t + newTx := *t newTx.DatabaseTx.SetContext(ctx) return &newTx }