Skip to content

Commit 1e86207

Browse files
committed
fix
1 parent 52b319b commit 1e86207

File tree

5 files changed

+213
-187
lines changed

5 files changed

+213
-187
lines changed

models/auth/source_test.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ import (
1313
"code.gitea.io/gitea/modules/json"
1414

1515
"github.com/stretchr/testify/assert"
16+
"github.com/stretchr/testify/require"
17+
"xorm.io/xorm"
1618
"xorm.io/xorm/schemas"
1719
)
1820

@@ -54,7 +56,8 @@ func TestDumpAuthSource(t *testing.T) {
5456

5557
sb := new(strings.Builder)
5658

57-
db.DumpTables([]*schemas.Table{authSourceSchema}, sb)
58-
59+
// TODO: this test is quite hacky, it should use a low-level "select" (without model processors) but not a database dump
60+
engine := db.GetEngine(db.DefaultContext).(*xorm.Engine)
61+
require.NoError(t, engine.DumpTables([]*schemas.Table{authSourceSchema}, sb))
5962
assert.Contains(t, sb.String(), `"Provider":"ConvertibleSourceName"`)
6063
}

models/db/engine.go

Lines changed: 1 addition & 185 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,10 @@ import (
88
"context"
99
"database/sql"
1010
"fmt"
11-
"io"
1211
"reflect"
1312
"strings"
14-
"time"
15-
16-
"code.gitea.io/gitea/modules/log"
17-
"code.gitea.io/gitea/modules/setting"
1813

1914
"xorm.io/xorm"
20-
"xorm.io/xorm/contexts"
21-
"xorm.io/xorm/names"
2215
"xorm.io/xorm/schemas"
2316

2417
_ "github.com/go-sql-driver/mysql" // Needed for the MySQL driver
@@ -73,55 +66,14 @@ func TableInfo(v any) (*schemas.Table, error) {
7366
return x.TableInfo(v)
7467
}
7568

76-
// DumpTables dump tables information
77-
func DumpTables(tables []*schemas.Table, w io.Writer, tp ...schemas.DBType) error {
78-
return x.DumpTables(tables, w, tp...)
79-
}
80-
81-
// RegisterModel registers model, if initfunc provided, it will be invoked after data model sync
69+
// RegisterModel registers model, if initFuncs provided, it will be invoked after data model sync
8270
func RegisterModel(bean any, initFunc ...func() error) {
8371
tables = append(tables, bean)
8472
if len(initFuncs) > 0 && initFunc[0] != nil {
8573
initFuncs = append(initFuncs, initFunc[0])
8674
}
8775
}
8876

89-
func init() {
90-
gonicNames := []string{"SSL", "UID"}
91-
for _, name := range gonicNames {
92-
names.LintGonicMapper[name] = true
93-
}
94-
}
95-
96-
// newXORMEngine returns a new XORM engine from the configuration
97-
func newXORMEngine() (*xorm.Engine, error) {
98-
connStr, err := setting.DBConnStr()
99-
if err != nil {
100-
return nil, err
101-
}
102-
103-
var engine *xorm.Engine
104-
105-
if setting.Database.Type.IsPostgreSQL() && len(setting.Database.Schema) > 0 {
106-
// OK whilst we sort out our schema issues - create a schema aware postgres
107-
registerPostgresSchemaDriver()
108-
engine, err = xorm.NewEngine("postgresschema", connStr)
109-
} else {
110-
engine, err = xorm.NewEngine(setting.Database.Type.String(), connStr)
111-
}
112-
113-
if err != nil {
114-
return nil, err
115-
}
116-
if setting.Database.Type == "mysql" {
117-
engine.Dialect().SetParams(map[string]string{"rowFormat": "DYNAMIC"})
118-
} else if setting.Database.Type == "mssql" {
119-
engine.Dialect().SetParams(map[string]string{"DEFAULT_VARCHAR": "nvarchar"})
120-
}
121-
engine.SetSchema(setting.Database.Schema)
122-
return engine, nil
123-
}
124-
12577
// SyncAllTables sync the schemas of all tables, is required by unit test code
12678
func SyncAllTables() error {
12779
_, err := x.StoreEngine("InnoDB").SyncWithOptions(xorm.SyncOptions{
@@ -130,94 +82,6 @@ func SyncAllTables() error {
13082
return err
13183
}
13284

133-
// InitEngine initializes the xorm.Engine and sets it as db.DefaultContext
134-
func InitEngine(ctx context.Context) error {
135-
xormEngine, err := newXORMEngine()
136-
if err != nil {
137-
if strings.Contains(err.Error(), "SQLite3 support") {
138-
return fmt.Errorf(`sqlite3 requires: -tags sqlite,sqlite_unlock_notify%s%w`, "\n", err)
139-
}
140-
return fmt.Errorf("failed to connect to database: %w", err)
141-
}
142-
143-
xormEngine.SetMapper(names.GonicMapper{})
144-
// WARNING: for serv command, MUST remove the output to os.stdout,
145-
// so use log file to instead print to stdout.
146-
xormEngine.SetLogger(NewXORMLogger(setting.Database.LogSQL))
147-
xormEngine.ShowSQL(setting.Database.LogSQL)
148-
xormEngine.SetMaxOpenConns(setting.Database.MaxOpenConns)
149-
xormEngine.SetMaxIdleConns(setting.Database.MaxIdleConns)
150-
xormEngine.SetConnMaxLifetime(setting.Database.ConnMaxLifetime)
151-
xormEngine.SetDefaultContext(ctx)
152-
153-
if setting.Database.SlowQueryThreshold > 0 {
154-
xormEngine.AddHook(&SlowQueryHook{
155-
Threshold: setting.Database.SlowQueryThreshold,
156-
Logger: log.GetLogger("xorm"),
157-
})
158-
}
159-
160-
SetDefaultEngine(ctx, xormEngine)
161-
return nil
162-
}
163-
164-
// SetDefaultEngine sets the default engine for db
165-
func SetDefaultEngine(ctx context.Context, eng *xorm.Engine) {
166-
x = eng
167-
DefaultContext = &Context{Context: ctx, engine: x}
168-
}
169-
170-
// UnsetDefaultEngine closes and unsets the default engine
171-
// We hope the SetDefaultEngine and UnsetDefaultEngine can be paired, but it's impossible now,
172-
// there are many calls to InitEngine -> SetDefaultEngine directly to overwrite the `x` and DefaultContext without close
173-
// Global database engine related functions are all racy and there is no graceful close right now.
174-
func UnsetDefaultEngine() {
175-
if x != nil {
176-
_ = x.Close()
177-
x = nil
178-
}
179-
DefaultContext = nil
180-
}
181-
182-
// InitEngineWithMigration initializes a new xorm.Engine and sets it as the db.DefaultContext
183-
// This function must never call .Sync() if the provided migration function fails.
184-
// When called from the "doctor" command, the migration function is a version check
185-
// that prevents the doctor from fixing anything in the database if the migration level
186-
// is different from the expected value.
187-
func InitEngineWithMigration(ctx context.Context, migrateFunc func(*xorm.Engine) error) (err error) {
188-
if err = InitEngine(ctx); err != nil {
189-
return err
190-
}
191-
192-
if err = x.Ping(); err != nil {
193-
return err
194-
}
195-
196-
preprocessDatabaseCollation(x)
197-
198-
// We have to run migrateFunc here in case the user is re-running installation on a previously created DB.
199-
// If we do not then table schemas will be changed and there will be conflicts when the migrations run properly.
200-
//
201-
// Installation should only be being re-run if users want to recover an old database.
202-
// However, we should think carefully about should we support re-install on an installed instance,
203-
// as there may be other problems due to secret reinitialization.
204-
if err = migrateFunc(x); err != nil {
205-
return fmt.Errorf("migrate: %w", err)
206-
}
207-
208-
if err = SyncAllTables(); err != nil {
209-
return fmt.Errorf("sync database struct error: %w", err)
210-
}
211-
212-
for _, initFunc := range initFuncs {
213-
if err := initFunc(); err != nil {
214-
return fmt.Errorf("initFunc failed: %w", err)
215-
}
216-
}
217-
218-
return nil
219-
}
220-
22185
// NamesToBean return a list of beans or an error
22286
func NamesToBean(names ...string) ([]any, error) {
22387
beans := []any{}
@@ -247,33 +111,6 @@ func NamesToBean(names ...string) ([]any, error) {
247111
return beans, nil
248112
}
249113

250-
// DumpDatabase dumps all data from database according the special database SQL syntax to file system.
251-
func DumpDatabase(filePath, dbType string) error {
252-
var tbs []*schemas.Table
253-
for _, t := range tables {
254-
t, err := x.TableInfo(t)
255-
if err != nil {
256-
return err
257-
}
258-
tbs = append(tbs, t)
259-
}
260-
261-
type Version struct {
262-
ID int64 `xorm:"pk autoincr"`
263-
Version int64
264-
}
265-
t, err := x.TableInfo(&Version{})
266-
if err != nil {
267-
return err
268-
}
269-
tbs = append(tbs, t)
270-
271-
if len(dbType) > 0 {
272-
return x.DumpTablesToFile(tbs, filePath, schemas.DBType(dbType))
273-
}
274-
return x.DumpTablesToFile(tbs, filePath)
275-
}
276-
277114
// MaxBatchInsertSize returns the table's max batch insert size
278115
func MaxBatchInsertSize(bean any) int {
279116
t, err := x.TableInfo(bean)
@@ -308,24 +145,3 @@ func SetLogSQL(ctx context.Context, on bool) {
308145
sess.Engine().ShowSQL(on)
309146
}
310147
}
311-
312-
type SlowQueryHook struct {
313-
Threshold time.Duration
314-
Logger log.Logger
315-
}
316-
317-
var _ contexts.Hook = &SlowQueryHook{}
318-
319-
func (SlowQueryHook) BeforeProcess(c *contexts.ContextHook) (context.Context, error) {
320-
return c.Ctx, nil
321-
}
322-
323-
func (h *SlowQueryHook) AfterProcess(c *contexts.ContextHook) error {
324-
if c.ExecuteTime >= h.Threshold {
325-
// 8 is the amount of skips passed to runtime.Caller, so that in the log the correct function
326-
// is being displayed (the function that ultimately wants to execute the query in the code)
327-
// instead of the function of the slow query hook being called.
328-
h.Logger.Log(8, log.WARN, "[Slow SQL Query] %s %v - %v", c.SQL, c.Args, c.ExecuteTime)
329-
}
330-
return nil
331-
}

models/db/engine_dump.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Copyright 2024 The Gitea Authors. All rights reserved.
2+
// SPDX-License-Identifier: MIT
3+
4+
package db
5+
6+
import "xorm.io/xorm/schemas"
7+
8+
// DumpDatabase dumps all data from database according the special database SQL syntax to file system.
9+
func DumpDatabase(filePath, dbType string) error {
10+
var tbs []*schemas.Table
11+
for _, t := range tables {
12+
t, err := x.TableInfo(t)
13+
if err != nil {
14+
return err
15+
}
16+
tbs = append(tbs, t)
17+
}
18+
19+
type Version struct {
20+
ID int64 `xorm:"pk autoincr"`
21+
Version int64
22+
}
23+
t, err := x.TableInfo(&Version{})
24+
if err != nil {
25+
return err
26+
}
27+
tbs = append(tbs, t)
28+
29+
if len(dbType) > 0 {
30+
return x.DumpTablesToFile(tbs, filePath, schemas.DBType(dbType))
31+
}
32+
return x.DumpTablesToFile(tbs, filePath)
33+
}

models/db/engine_hook.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Copyright 2024 The Gitea Authors. All rights reserved.
2+
// SPDX-License-Identifier: MIT
3+
4+
package db
5+
6+
import (
7+
"context"
8+
"time"
9+
10+
"code.gitea.io/gitea/modules/log"
11+
12+
"xorm.io/xorm/contexts"
13+
)
14+
15+
type SlowQueryHook struct {
16+
Threshold time.Duration
17+
Logger log.Logger
18+
}
19+
20+
var _ contexts.Hook = (*SlowQueryHook)(nil)
21+
22+
func (*SlowQueryHook) BeforeProcess(c *contexts.ContextHook) (context.Context, error) {
23+
return c.Ctx, nil
24+
}
25+
26+
func (h *SlowQueryHook) AfterProcess(c *contexts.ContextHook) error {
27+
if c.ExecuteTime >= h.Threshold {
28+
// 8 is the amount of skips passed to runtime.Caller, so that in the log the correct function
29+
// is being displayed (the function that ultimately wants to execute the query in the code)
30+
// instead of the function of the slow query hook being called.
31+
h.Logger.Log(8, log.WARN, "[Slow SQL Query] %s %v - %v", c.SQL, c.Args, c.ExecuteTime)
32+
}
33+
return nil
34+
}

0 commit comments

Comments
 (0)