Skip to content

Commit c0faf36

Browse files
committed
fix(gdb): handle empty string in Fields() gracefully
When Fields("") is called with empty string parameter, it now ignores the empty string and behaves as if Fields() was not called, resulting in SELECT * instead of invalid SQL "SELECT FROM table". Also handles mixed cases like Fields("", "id") and Fields("id", "", "nickname") by filtering out empty strings while keeping valid field names. Fixes gogf#4697
1 parent 063264e commit c0faf36

2 files changed

Lines changed: 46 additions & 1 deletion

File tree

contrib/drivers/mysql/mysql_z_unit_issue_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1949,3 +1949,37 @@ func Test_Issue4500(t *testing.T) {
19491949
t.Assert(len(all), 3)
19501950
})
19511951
}
1952+
1953+
// https://github.com/gogf/gf/issues/4697
1954+
func Test_Issue4697(t *testing.T) {
1955+
table := createInitTable()
1956+
defer dropTable(table)
1957+
1958+
gtest.C(t, func(t *gtest.T) {
1959+
// Fields("") should be treated as Fields() and select all fields
1960+
result, err := db.Model(table).Fields("").Limit(1).All()
1961+
t.AssertNil(err)
1962+
t.AssertGT(len(result), 0)
1963+
// Should have all fields (id, passport, password, nickname, create_time, create_date)
1964+
t.Assert(len(result[0]), 6)
1965+
})
1966+
1967+
gtest.C(t, func(t *gtest.T) {
1968+
// Fields("", "id") should ignore empty string and only select "id"
1969+
result, err := db.Model(table).Fields("", "id").Limit(1).All()
1970+
t.AssertNil(err)
1971+
t.AssertGT(len(result), 0)
1972+
t.Assert(len(result[0]), 1)
1973+
t.AssertNE(result[0]["id"], nil)
1974+
})
1975+
1976+
gtest.C(t, func(t *gtest.T) {
1977+
// Fields("id", "", "nickname") should ignore empty string
1978+
result, err := db.Model(table).Fields("id", "", "nickname").Limit(1).All()
1979+
t.AssertNil(err)
1980+
t.AssertGT(len(result), 0)
1981+
t.Assert(len(result[0]), 2)
1982+
t.AssertNE(result[0]["id"], nil)
1983+
t.AssertNE(result[0]["nickname"], nil)
1984+
})
1985+
}

database/gdb/gdb_model_fields.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,18 @@ func (m *Model) Fields(fieldNamesOrMapStruct ...any) *Model {
2828
if length == 0 {
2929
return m
3030
}
31-
fields := m.filterFieldsFrom(m.tablesInit, fieldNamesOrMapStruct...)
31+
// Filter out empty string fields.
32+
filtered := make([]any, 0, length)
33+
for _, field := range fieldNamesOrMapStruct {
34+
if s, ok := field.(string); ok && s == "" {
35+
continue
36+
}
37+
filtered = append(filtered, field)
38+
}
39+
if len(filtered) == 0 {
40+
return m
41+
}
42+
fields := m.filterFieldsFrom(m.tablesInit, filtered...)
3243
if len(fields) == 0 {
3344
return m
3445
}

0 commit comments

Comments
 (0)