Skip to content

Commit

Permalink
database/gdb: fix confusing error message in Insert/Update operations…
Browse files Browse the repository at this point in the history
… when table not exist or the table contains no fields (#3553)
  • Loading branch information
wln32 committed May 22, 2024
1 parent 23df83c commit 17385ee
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
56 changes: 56 additions & 0 deletions contrib/drivers/pgsql/pgsql_z_unit_db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ package pgsql_test

import (
"fmt"
"strings"
"testing"

"github.com/gogf/gf/v2/frame/g"
Expand Down Expand Up @@ -327,3 +328,58 @@ func Test_DB_TableFields(t *testing.T) {
}
})
}

func Test_NoFields_Error(t *testing.T) {
createSql := `CREATE TABLE IF NOT EXISTS %s (
id bigint PRIMARY KEY,
int_col INT);`

type Data struct {
Id int64
IntCol int64
}
// pgsql converts table names to lowercase
tableName := "Error_table"
errStr := fmt.Sprintf(`The table "%s" may not exist, or the table contains no fields`, tableName)
_, err := db.Exec(ctx, fmt.Sprintf(createSql, tableName))
gtest.AssertNil(err)
defer dropTable(tableName)

gtest.C(t, func(t *gtest.T) {
var data = Data{
Id: 2,
IntCol: 2,
}
_, err = db.Model(tableName).Data(data).Insert()
t.Assert(err, errStr)

// Insert a piece of test data using lowercase
_, err = db.Model(strings.ToLower(tableName)).Data(data).Insert()
t.AssertNil(err)

_, err = db.Model(tableName).Where("id", 1).Data(g.Map{
"int_col": 9999,
}).Update()
t.Assert(err, errStr)

})
// The inserted field does not exist in the table
gtest.C(t, func(t *gtest.T) {
data := map[string]any{
"id1": 22,
"int_col_22": 11111,
}
_, err = db.Model(tableName).Data(data).Insert()
t.Assert(err, errStr)

lowerTableName := strings.ToLower(tableName)
_, err = db.Model(lowerTableName).Data(data).Insert()
t.Assert(err, fmt.Errorf(`input data match no fields in table "%s"`, lowerTableName))

_, err = db.Model(lowerTableName).Where("id", 1).Data(g.Map{
"int_col-2": 9999,
}).Update()
t.Assert(err, fmt.Errorf(`input data match no fields in table "%s"`, lowerTableName))
})

}
6 changes: 6 additions & 0 deletions database/gdb/gdb_core_structure.go
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,9 @@ func (c *Core) mappingAndFilterData(ctx context.Context, schema, table string, d
if err != nil {
return nil, err
}
if len(fieldsMap) == 0 {
return nil, gerror.Newf(`The table %s may not exist, or the table contains no fields`, table)
}
fieldsKeyMap := make(map[string]interface{}, len(fieldsMap))
for k := range fieldsMap {
fieldsKeyMap[k] = nil
Expand All @@ -406,6 +409,9 @@ func (c *Core) mappingAndFilterData(ctx context.Context, schema, table string, d
delete(data, dataKey)
}
}
if len(data) == 0 {
return nil, gerror.Newf(`input data match no fields in table %s`, table)
}
}
return data, nil
}

0 comments on commit 17385ee

Please sign in to comment.