Skip to content

Commit 1f50048

Browse files
authored
Refactor db package (#35380)
Remove unnecessary code
1 parent aef4a35 commit 1f50048

File tree

11 files changed

+39
-54
lines changed

11 files changed

+39
-54
lines changed

models/auth/session.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ func RegenerateSession(ctx context.Context, oldKey, newKey string) (*Session, er
8686
}
8787
}
8888

89-
if _, err := db.Exec(ctx, "UPDATE "+db.TableName(&Session{})+" SET `key` = ? WHERE `key`=?", newKey, oldKey); err != nil {
89+
if _, err := db.Exec(ctx, "UPDATE `session` SET `key` = ? WHERE `key`=?", newKey, oldKey); err != nil {
9090
return nil, err
9191
}
9292

models/auth/source_test.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import (
88
"testing"
99

1010
auth_model "code.gitea.io/gitea/models/auth"
11-
"code.gitea.io/gitea/models/db"
1211
"code.gitea.io/gitea/models/unittest"
1312
"code.gitea.io/gitea/modules/json"
1413

@@ -40,7 +39,7 @@ func (source *TestSource) ToDB() ([]byte, error) {
4039
func TestDumpAuthSource(t *testing.T) {
4140
assert.NoError(t, unittest.PrepareTestDatabase())
4241

43-
authSourceSchema, err := db.TableInfo(new(auth_model.Source))
42+
authSourceSchema, err := unittest.GetXORMEngine().TableInfo(new(auth_model.Source))
4443
assert.NoError(t, err)
4544

4645
auth_model.RegisterTypeConfig(auth_model.OAuth2, new(TestSource))

models/db/context.go

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -61,17 +61,19 @@ func contextSafetyCheck(e Engine) {
6161
callerNum := runtime.Callers(3, callers) // skip 3: runtime.Callers, contextSafetyCheck, GetEngine
6262
for i := range callerNum {
6363
if slices.Contains(contextSafetyDeniedFuncPCs, callers[i]) {
64-
panic(errors.New("using database context in an iterator would cause corrupted results"))
64+
panic(errors.New("using session context in an iterator would cause corrupted results"))
6565
}
6666
}
6767
}
6868

6969
// GetEngine gets an existing db Engine/Statement or creates a new Session
70-
func GetEngine(ctx context.Context) (e Engine) {
71-
defer func() { contextSafetyCheck(e) }()
70+
func GetEngine(ctx context.Context) Engine {
7271
if engine, ok := ctx.Value(engineContextKey).(Engine); ok {
72+
// if reusing the existing session, need to do "contextSafetyCheck" because the Iterate creates a "autoResetStatement=false" session
73+
contextSafetyCheck(engine)
7374
return engine
7475
}
76+
// no need to do "contextSafetyCheck" because it's a new Session
7577
return xormEngine.Context(ctx)
7678
}
7779

@@ -301,11 +303,6 @@ func CountByBean(ctx context.Context, bean any) (int64, error) {
301303
return GetEngine(ctx).Count(bean)
302304
}
303305

304-
// TableName returns the table name according a bean object
305-
func TableName(bean any) string {
306-
return xormEngine.TableName(bean)
307-
}
308-
309306
// InTransaction returns true if the engine is in a transaction otherwise return false
310307
func InTransaction(ctx context.Context) bool {
311308
return getTransactionSession(ctx) != nil

models/db/context_test.go

Lines changed: 26 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -100,31 +100,36 @@ func TestContextSafety(t *testing.T) {
100100
assert.NoError(t, db.Insert(t.Context(), &TestModel2{ID: int64(-i)}))
101101
}
102102

103-
actualCount := 0
104-
// here: db.GetEngine(t.Context()) is a new *Session created from *Engine
105-
_ = db.WithTx(t.Context(), func(ctx context.Context) error {
106-
_ = db.GetEngine(ctx).Iterate(&TestModel1{}, func(i int, bean any) error {
107-
// here: db.GetEngine(ctx) is always the unclosed "Iterate" *Session with autoResetStatement=false,
108-
// and the internal states (including "cond" and others) are always there and not be reset in this callback.
109-
m1 := bean.(*TestModel1)
110-
assert.EqualValues(t, i+1, m1.ID)
111-
112-
// here: XORM bug, it fails because the SQL becomes "WHERE id=-1", "WHERE id=-1 AND id=-2", "WHERE id=-1 AND id=-2 AND id=-3" ...
113-
// and it conflicts with the "Iterate"'s internal states.
114-
// has, err := db.GetEngine(ctx).Get(&TestModel2{ID: -m1.ID})
115-
116-
actualCount++
103+
t.Run("Show-XORM-Bug", func(t *testing.T) {
104+
actualCount := 0
105+
// here: db.GetEngine(t.Context()) is a new *Session created from *Engine
106+
_ = db.WithTx(t.Context(), func(ctx context.Context) error {
107+
_ = db.GetEngine(ctx).Iterate(&TestModel1{}, func(i int, bean any) error {
108+
// here: db.GetEngine(ctx) is always the unclosed "Iterate" *Session with autoResetStatement=false,
109+
// and the internal states (including "cond" and others) are always there and not be reset in this callback.
110+
m1 := bean.(*TestModel1)
111+
assert.EqualValues(t, i+1, m1.ID)
112+
113+
// here: XORM bug, it fails because the SQL becomes "WHERE id=-1", "WHERE id=-1 AND id=-2", "WHERE id=-1 AND id=-2 AND id=-3" ...
114+
// and it conflicts with the "Iterate"'s internal states.
115+
// has, err := db.GetEngine(ctx).Get(&TestModel2{ID: -m1.ID})
116+
117+
actualCount++
118+
return nil
119+
})
117120
return nil
118121
})
119-
return nil
122+
assert.Equal(t, testCount, actualCount)
120123
})
121-
assert.Equal(t, testCount, actualCount)
122124

123-
// deny the bad usages
124-
assert.PanicsWithError(t, "using database context in an iterator would cause corrupted results", func() {
125-
_ = unittest.GetXORMEngine().Iterate(&TestModel1{}, func(i int, bean any) error {
126-
_ = db.GetEngine(t.Context())
127-
return nil
125+
t.Run("DenyBadUsage", func(t *testing.T) {
126+
assert.PanicsWithError(t, "using session context in an iterator would cause corrupted results", func() {
127+
_ = db.WithTx(t.Context(), func(ctx context.Context) error {
128+
return db.GetEngine(ctx).Iterate(&TestModel1{}, func(i int, bean any) error {
129+
_ = db.GetEngine(ctx)
130+
return nil
131+
})
132+
})
128133
})
129134
})
130135
}

models/db/engine.go

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ import (
1212
"strings"
1313

1414
"xorm.io/xorm"
15-
"xorm.io/xorm/schemas"
1615

1716
_ "github.com/go-sql-driver/mysql" // Needed for the MySQL driver
1817
_ "github.com/lib/pq" // Needed for the Postgresql driver
@@ -67,11 +66,6 @@ var (
6766
_ Engine = (*xorm.Session)(nil)
6867
)
6968

70-
// TableInfo returns table's information via an object
71-
func TableInfo(v any) (*schemas.Table, error) {
72-
return xormEngine.TableInfo(v)
73-
}
74-
7569
// RegisterModel registers model, if initFuncs provided, it will be invoked after data model sync
7670
func RegisterModel(bean any, initFunc ...func() error) {
7771
registeredModels = append(registeredModels, bean)

models/db/engine_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ func TestPrimaryKeys(t *testing.T) {
7070
}
7171

7272
for _, bean := range beans {
73-
table, err := db.TableInfo(bean)
73+
table, err := db.GetXORMEngineForTesting().TableInfo(bean)
7474
if err != nil {
7575
t.Fatal(err)
7676
}

models/db/index.go

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,7 @@ type ResourceIndex struct {
1919
MaxIndex int64 `xorm:"index"`
2020
}
2121

22-
var (
23-
// ErrResouceOutdated represents an error when request resource outdated
24-
ErrResouceOutdated = errors.New("resource outdated")
25-
// ErrGetResourceIndexFailed represents an error when resource index retries 3 times
26-
ErrGetResourceIndexFailed = errors.New("get resource index failed")
27-
)
22+
var ErrGetResourceIndexFailed = errors.New("get resource index failed")
2823

2924
// SyncMaxResourceIndex sync the max index with the resource
3025
func SyncMaxResourceIndex(ctx context.Context, tableName string, groupID, maxIndex int64) (err error) {

models/organization/org_list.go

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -105,11 +105,6 @@ type MinimalOrg = Organization
105105

106106
// GetUserOrgsList returns all organizations the given user has access to
107107
func GetUserOrgsList(ctx context.Context, user *user_model.User) ([]*MinimalOrg, error) {
108-
schema, err := db.TableInfo(new(user_model.User))
109-
if err != nil {
110-
return nil, err
111-
}
112-
113108
outputCols := []string{
114109
"id",
115110
"name",
@@ -122,7 +117,7 @@ func GetUserOrgsList(ctx context.Context, user *user_model.User) ([]*MinimalOrg,
122117

123118
selectColumns := &strings.Builder{}
124119
for i, col := range outputCols {
125-
fmt.Fprintf(selectColumns, "`%s`.%s", schema.Name, col)
120+
_, _ = fmt.Fprintf(selectColumns, "`user`.%s", col)
126121
if i < len(outputCols)-1 {
127122
selectColumns.WriteString(", ")
128123
}

models/unittest/consistency.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ func CheckConsistencyFor(t TestingT, beansToCheck ...any) {
4545
}
4646

4747
func checkForConsistency(t TestingT, bean any) {
48-
tb, err := db.TableInfo(bean)
48+
tb, err := GetXORMEngine().TableInfo(bean)
4949
assert.NoError(t, err)
5050
f := consistencyCheckMap[tb.Name]
5151
require.NotNil(t, f, "unknown bean type: %#v", bean)

models/unittest/fixtures_loader.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ func NewFixturesLoader(x *xorm.Engine, opts FixturesOptions) (FixturesLoader, er
218218
xormBeans, _ := db.NamesToBean()
219219
f.xormTableNames = map[string]bool{}
220220
for _, bean := range xormBeans {
221-
f.xormTableNames[db.TableName(bean)] = true
221+
f.xormTableNames[x.TableName(bean)] = true
222222
}
223223

224224
return f, nil

0 commit comments

Comments
 (0)