gitforge/models/unittest/fixtures.go
Mathieu Fenniak 29eddd311b chore: upgrade to https://code.forgejo.org/xorm/xorm v1.4.0 (#12639)
Upgrade Forgejo to our forked [xorm v1.4.0](https://code.forgejo.org/xorm/xorm/compare/v1.3.9-forgejo.12...v1.4.0), which is now named `code.forgejo.org/xorm/xorm` to reflect the current expectation that it is a permanent fork.  A small number of API changes were made recently in https://code.forgejo.org/xorm/xorm/issues/120 which are accounted for in this PR, in addition to the module rename.

## Checklist

The [contributor guide](https://forgejo.org/docs/next/contributor/) contains information that will be helpful to first time contributors. All work and communication must conform to Forgejo's [AI Agreement](https://codeberg.org/forgejo/governance/src/branch/main/AIAgreement.md). There also are a few [conditions for merging Pull Requests in Forgejo repositories](https://codeberg.org/forgejo/governance/src/branch/main/PullRequestsAgreement.md). You are also welcome to join the [Forgejo development chatroom](https://matrix.to/#/#forgejo-development:matrix.org).

### Documentation

- [ ] I created a pull request [to the documentation](https://codeberg.org/forgejo/docs) to explain to Forgejo users how to use this change.
- [x] I did not document these changes and I do not expect someone else to do it.

### Release notes

- [ ] This change will be noticed by a Forgejo user or admin (feature, bug fix, performance, etc.). I suggest to include a release note for this change.
- [x] This change is not visible to a Forgejo user or admin (refactor, dependency upgrade, etc.). I think there is no need to add a release note for this change.

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/12639
Reviewed-by: Otto <otto@codeberg.org>
2026-05-20 20:20:08 +02:00

157 lines
3.9 KiB
Go

// Copyright 2021 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
//nolint:forbidigo
package unittest
import (
"fmt"
"path/filepath"
"sync"
"time"
"forgejo.org/models/db"
"forgejo.org/modules/auth/password/hash"
"forgejo.org/modules/container"
"forgejo.org/modules/setting"
"code.forgejo.org/xorm/xorm"
"code.forgejo.org/xorm/xorm/schemas"
)
var fixturesLoader *loader
// GetXORMEngine gets the XORM engine
func GetXORMEngine(engine ...*xorm.Engine) (x *xorm.Engine, err error) {
if len(engine) == 1 {
return engine[0], nil
}
return db.GetMasterEngine(db.DefaultContext.(*db.Context).Engine())
}
func OverrideFixtures(dir string) func() {
old := fixturesLoader
opts := FixturesOptions{
Dir: filepath.Join(setting.AppWorkPath, "models/fixtures/"),
Base: setting.AppWorkPath,
Dirs: []string{dir},
}
if err := InitFixtures(opts); err != nil {
panic(err)
}
return func() {
fixturesLoader = old
}
}
var allTableNames = sync.OnceValue(db.GetTableNames)
// InitFixtures initialize test fixtures for a test database
func InitFixtures(opts FixturesOptions, engine ...*xorm.Engine) (err error) {
e, err := GetXORMEngine(engine...)
if err != nil {
return err
}
fixturePaths := []string{}
if opts.Dir != "" {
fixturePaths = append(fixturePaths, opts.Dir)
} else {
fixturePaths = append(fixturePaths, opts.Files...)
}
if opts.Dirs != nil {
for _, dir := range opts.Dirs {
fixturePaths = append(fixturePaths, filepath.Join(opts.Base, dir))
}
}
var dialect string
switch e.Dialect().URI().DBType {
case schemas.POSTGRES:
dialect = "postgres"
case schemas.MYSQL:
dialect = "mysql"
case schemas.SQLITE:
dialect = "sqlite3"
default:
panic("Unsupported RDBMS for test")
}
var allTables container.Set[string]
if opts.OnlyAffectModels == nil {
allTables = allTableNames().Clone()
} else {
allTables = make(container.Set[string])
for _, bean := range opts.OnlyAffectModels {
allTables.Add(e.TableName(bean))
}
}
fixturesLoader, err = newFixtureLoader(e.DB().DB, dialect, fixturePaths, allTables)
if err != nil {
return err
}
// register the dummy hash algorithm function used in the test fixtures
_ = hash.Register("dummy", hash.NewDummyHasher)
setting.PasswordHashAlgo, _ = hash.SetDefaultPasswordHashAlgorithm("dummy")
return err
}
// LoadFixtures load fixtures for a test database
func LoadFixtures(engine ...*xorm.Engine) error {
e, err := GetXORMEngine(engine...)
if err != nil {
return err
}
// (doubt) database transaction conflicts could occur and result in ROLLBACK? just try for a few times.
for range 5 {
if err = fixturesLoader.Load(); err == nil {
break
}
time.Sleep(200 * time.Millisecond)
}
if err != nil {
fmt.Printf("LoadFixtures failed after retries: %v\n", err)
}
// Now if we're running postgres we need to tell it to update the sequences
if e.Dialect().URI().DBType == schemas.POSTGRES {
results, err := e.QueryString(`SELECT 'SELECT SETVAL(' ||
quote_literal(quote_ident(PGT.schemaname) || '.' || quote_ident(S.relname)) ||
', COALESCE(MAX(' ||quote_ident(C.attname)|| '), 1) ) FROM ' ||
quote_ident(PGT.schemaname)|| '.'||quote_ident(T.relname)|| ';'
FROM pg_class AS S,
pg_depend AS D,
pg_class AS T,
pg_attribute AS C,
pg_tables AS PGT
WHERE S.relkind = 'S'
AND S.oid = D.objid
AND D.refobjid = T.oid
AND D.refobjid = C.attrelid
AND D.refobjsubid = C.attnum
AND T.relname = PGT.tablename
ORDER BY S.relname;`)
if err != nil {
fmt.Printf("Failed to generate sequence update: %v\n", err)
return err
}
for _, r := range results {
for _, value := range r {
_, err = e.Exec(value)
if err != nil {
fmt.Printf("Failed to update sequence: %s Error: %v\n", value, err)
return err
}
}
}
}
_ = hash.Register("dummy", hash.NewDummyHasher)
setting.PasswordHashAlgo, _ = hash.SetDefaultPasswordHashAlgorithm("dummy")
return err
}