mirror of
https://codeberg.org/forgejo/forgejo.git
synced 2025-05-31 11:52:10 +00:00
Remove GetByBean method because sometimes it's danger when query condition parameter is zero and also introduce new generic methods (#28220)
The function `GetByBean` has an obvious defect that when the fields are empty values, it will be ignored. Then users will get a wrong result which is possibly used to make a security problem. To avoid the possibility, this PR removed function `GetByBean` and all references. And some new generic functions have been introduced to be used. The recommand usage like below. ```go // if query an object according id obj, err := db.GetByID[Object](ctx, id) // query with other conditions obj, err := db.Get[Object](ctx, builder.Eq{"a": a, "b":b}) ```
This commit is contained in:
parent
beb71f5ef6
commit
dd30d9d5c0
28 changed files with 189 additions and 174 deletions
|
@ -13,6 +13,8 @@ import (
|
|||
"code.gitea.io/gitea/modules/log"
|
||||
"code.gitea.io/gitea/modules/setting/config"
|
||||
"code.gitea.io/gitea/modules/timeutil"
|
||||
|
||||
"xorm.io/builder"
|
||||
)
|
||||
|
||||
type Setting struct {
|
||||
|
@ -36,16 +38,17 @@ func init() {
|
|||
const keyRevision = "revision"
|
||||
|
||||
func GetRevision(ctx context.Context) int {
|
||||
revision := &Setting{SettingKey: keyRevision}
|
||||
if has, err := db.GetByBean(ctx, revision); err != nil {
|
||||
revision, exist, err := db.Get[Setting](ctx, builder.Eq{"setting_key": keyRevision})
|
||||
if err != nil {
|
||||
return 0
|
||||
} else if !has {
|
||||
} else if !exist {
|
||||
err = db.Insert(ctx, &Setting{SettingKey: keyRevision, Version: 1})
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return 1
|
||||
} else if revision.Version <= 0 || revision.Version >= math.MaxInt-1 {
|
||||
}
|
||||
if revision.Version <= 0 || revision.Version >= math.MaxInt-1 {
|
||||
_, err = db.Exec(ctx, "UPDATE system_setting SET version=1 WHERE setting_key=?", keyRevision)
|
||||
if err != nil {
|
||||
return 0
|
||||
|
|
|
@ -41,14 +41,11 @@ func TestSettings(t *testing.T) {
|
|||
assert.EqualValues(t, "false", settings[keyName])
|
||||
|
||||
// setting the same value should not trigger DuplicateKey error, and the "version" should be increased
|
||||
setting := &system.Setting{SettingKey: keyName}
|
||||
_, err = db.GetByBean(db.DefaultContext, setting)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 2, setting.Version)
|
||||
err = system.SetSettings(db.DefaultContext, map[string]string{keyName: "false"})
|
||||
assert.NoError(t, err)
|
||||
setting = &system.Setting{SettingKey: keyName}
|
||||
_, err = db.GetByBean(db.DefaultContext, setting)
|
||||
|
||||
rev, settings, err = system.GetAllSettings(db.DefaultContext)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 3, setting.Version)
|
||||
assert.Len(t, settings, 2)
|
||||
assert.EqualValues(t, 4, rev)
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue