Files
Gogs/internal/database/models.go

249 lines
6.8 KiB
Go
Raw Normal View History

2014-02-12 12:49:46 -05:00
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
2014-02-18 17:48:02 -05:00
import (
"context"
2014-10-19 01:35:24 -04:00
"database/sql"
2014-02-18 17:48:02 -05:00
"fmt"
"os"
2014-03-21 01:09:22 -04:00
"path"
"path/filepath"
2014-04-14 14:49:50 +08:00
"strings"
"time"
2014-02-18 17:48:02 -05:00
"github.com/pkg/errors"
2020-09-06 10:11:08 +08:00
"gorm.io/gorm"
"gorm.io/gorm/logger"
log "unknwon.dev/clog/v2"
"xorm.io/core"
"xorm.io/xorm"
2014-02-18 17:48:02 -05:00
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database/migrations"
"gogs.io/gogs/internal/dbutil"
2014-02-18 17:48:02 -05:00
)
2017-04-06 00:14:30 -04:00
// Engine represents a XORM engine or session.
2014-10-19 01:35:24 -04:00
type Engine interface {
Delete(any) (int64, error)
Exec(...any) (sql.Result, error)
Find(any, ...any) error
Get(any) (bool, error)
ID(any) *xorm.Session
In(string, ...any) *xorm.Session
Insert(...any) (int64, error)
InsertOne(any) (int64, error)
Iterate(any, xorm.IterFunc) error
Sql(string, ...any) *xorm.Session
Table(any) *xorm.Session
Where(any, ...any) *xorm.Session
2014-10-19 01:35:24 -04:00
}
2014-03-21 01:48:10 -04:00
var (
x *xorm.Engine
legacyTables []any
HasEngine bool
2014-03-21 01:48:10 -04:00
)
2014-04-05 22:46:32 +08:00
func init() {
legacyTables = append(legacyTables,
new(User), new(PublicKey), new(TwoFactor), new(TwoFactorRecoveryCode),
new(Repository), new(DeployKey), new(Collaboration), new(Upload),
new(Watch), new(Star),
new(Issue), new(PullRequest), new(Comment), new(Attachment), new(IssueUser),
new(Label), new(IssueLabel), new(Milestone),
new(Mirror), new(Release), new(Webhook), new(HookTask),
new(ProtectBranch), new(ProtectBranchWhitelist),
new(Team), new(OrgUser), new(TeamUser), new(TeamRepo),
)
2015-08-27 23:06:14 +08:00
2015-11-07 00:39:45 -05:00
gonicNames := []string{"SSL"}
2015-08-27 23:06:14 +08:00
for _, name := range gonicNames {
core.LintGonicMapper[name] = true
}
2014-04-05 22:46:32 +08:00
}
func getEngine() (*xorm.Engine, error) {
2020-02-22 18:58:16 +08:00
Param := "?"
if strings.Contains(conf.Database.Name, Param) {
2016-07-24 14:32:46 +08:00
Param = "&"
}
2020-02-22 18:58:16 +08:00
2020-09-06 10:11:08 +08:00
driver := conf.Database.Type
2020-02-22 18:58:16 +08:00
connStr := ""
switch conf.Database.Type {
2014-03-30 10:47:08 -04:00
case "mysql":
2020-02-22 18:58:16 +08:00
conf.UseMySQL = true
if conf.Database.Host[0] == '/' { // looks like a unix socket
connStr = fmt.Sprintf("%s:%s@unix(%s)/%s%scharset=utf8mb4&parseTime=true",
2020-02-22 18:58:16 +08:00
conf.Database.User, conf.Database.Password, conf.Database.Host, conf.Database.Name, Param)
} else {
connStr = fmt.Sprintf("%s:%s@tcp(%s)/%s%scharset=utf8mb4&parseTime=true",
2020-02-22 18:58:16 +08:00
conf.Database.User, conf.Database.Password, conf.Database.Host, conf.Database.Name, Param)
}
engineParams := map[string]string{"rowFormat": "DYNAMIC"}
2020-02-22 18:58:16 +08:00
return xorm.NewEngineWithParams(conf.Database.Type, connStr, engineParams)
2014-03-30 10:47:08 -04:00
case "postgres":
2020-02-22 18:58:16 +08:00
conf.UsePostgreSQL = true
host, port := dbutil.ParsePostgreSQLHostPort(conf.Database.Host)
connStr = fmt.Sprintf("user='%s' password='%s' host='%s' port='%s' dbname='%s' sslmode='%s' search_path='%s'",
conf.Database.User, conf.Database.Password, host, port, conf.Database.Name, conf.Database.SSLMode, conf.Database.Schema)
2020-09-06 10:11:08 +08:00
driver = "pgx"
2020-02-22 18:58:16 +08:00
2017-02-14 02:50:00 +01:00
case "mssql":
2020-02-22 18:58:16 +08:00
conf.UseMSSQL = true
host, port := dbutil.ParseMSSQLHostPort(conf.Database.Host)
connStr = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, conf.Database.Name, conf.Database.User, conf.Database.Password)
2020-02-22 18:58:16 +08:00
case "sqlite3":
2020-02-22 18:58:16 +08:00
if err := os.MkdirAll(path.Dir(conf.Database.Path), os.ModePerm); err != nil {
return nil, fmt.Errorf("create directories: %v", err)
2015-08-24 21:01:23 +08:00
}
2020-02-22 18:58:16 +08:00
conf.UseSQLite3 = true
connStr = "file:" + conf.Database.Path + "?cache=shared&mode=rwc"
2014-03-30 10:47:08 -04:00
default:
2020-02-22 18:58:16 +08:00
return nil, fmt.Errorf("unknown database type: %s", conf.Database.Type)
2014-03-30 10:47:08 -04:00
}
2020-09-06 10:11:08 +08:00
return xorm.NewEngine(driver, connStr)
}
func NewTestEngine() error {
x, err := getEngine()
2014-03-30 10:47:08 -04:00
if err != nil {
return fmt.Errorf("connect to database: %v", err)
2014-03-30 10:47:08 -04:00
}
if conf.UsePostgreSQL {
x.SetSchema(conf.Database.Schema)
}
2015-01-23 09:54:16 +02:00
x.SetMapper(core.GonicMapper{})
return x.StoreEngine("InnoDB").Sync2(legacyTables...)
2014-03-30 10:47:08 -04:00
}
func SetEngine() (*gorm.DB, error) {
var err error
x, err = getEngine()
2014-02-18 17:48:02 -05:00
if err != nil {
return nil, fmt.Errorf("connect to database: %v", err)
2014-02-18 17:48:02 -05:00
}
if conf.UsePostgreSQL {
x.SetSchema(conf.Database.Schema)
}
2015-01-23 09:54:16 +02:00
x.SetMapper(core.GonicMapper{})
var logPath string
if conf.HookMode {
logPath = filepath.Join(conf.Log.RootPath, "hooks", "xorm.log")
} else {
logPath = filepath.Join(conf.Log.RootPath, "xorm.log")
}
sec := conf.File.Section("log.xorm")
fileWriter, err := log.NewFileWriter(logPath,
log.FileRotationConfig{
Rotate: sec.Key("ROTATE").MustBool(true),
Daily: sec.Key("ROTATE_DAILY").MustBool(true),
MaxSize: sec.Key("MAX_SIZE").MustInt64(100) * 1024 * 1024,
MaxDays: sec.Key("MAX_DAYS").MustInt64(3),
},
)
if err != nil {
return nil, fmt.Errorf("create 'xorm.log': %v", err)
}
x.SetMaxOpenConns(conf.Database.MaxOpenConns)
x.SetMaxIdleConns(conf.Database.MaxIdleConns)
x.SetConnMaxLifetime(time.Second)
if conf.IsProdMode() {
x.SetLogger(xorm.NewSimpleLogger3(fileWriter, xorm.DEFAULT_LOG_PREFIX, xorm.DEFAULT_LOG_FLAG, core.LOG_ERR))
} else {
x.SetLogger(xorm.NewSimpleLogger(fileWriter))
}
x.ShowSQL(true)
var gormLogger logger.Writer
if conf.HookMode {
gormLogger = &dbutil.Logger{Writer: fileWriter}
} else {
gormLogger, err = newLogWriter()
if err != nil {
return nil, errors.Wrap(err, "new log writer")
}
}
return Init(gormLogger)
2014-02-18 17:48:02 -05:00
}
func NewEngine() (err error) {
db, err := SetEngine()
if err != nil {
return err
2014-04-05 22:46:32 +08:00
}
2015-01-22 14:49:52 +02:00
if err = migrations.Migrate(db); err != nil {
2015-02-11 21:58:37 -05:00
return fmt.Errorf("migrate: %v", err)
2015-01-22 14:49:52 +02:00
}
if err = x.StoreEngine("InnoDB").Sync2(legacyTables...); err != nil {
return errors.Wrap(err, "sync tables")
2014-02-19 17:50:53 +08:00
}
2015-01-23 09:54:16 +02:00
return nil
2014-02-18 17:48:02 -05:00
}
2014-03-20 16:04:56 -04:00
type Statistic struct {
Counter struct {
2014-08-28 22:29:00 +08:00
User, Org, PublicKey,
Repo, Watch, Star, Action, Access,
Issue, Comment, Oauth, Follow,
Mirror, Release, LoginSource, Webhook,
Milestone, Label, HookTask,
Team, UpdateTask, Attachment int64
2014-03-20 16:04:56 -04:00
}
}
func GetStatistic(ctx context.Context) (stats Statistic) {
stats.Counter.User = Users.Count(ctx)
2014-08-28 22:29:00 +08:00
stats.Counter.Org = CountOrganizations()
2014-06-21 00:51:41 -04:00
stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
2016-07-24 14:32:46 +08:00
stats.Counter.Repo = CountRepositories(true)
2014-06-21 00:51:41 -04:00
stats.Counter.Watch, _ = x.Count(new(Watch))
2014-08-28 22:29:00 +08:00
stats.Counter.Star, _ = x.Count(new(Star))
2014-06-21 00:51:41 -04:00
stats.Counter.Action, _ = x.Count(new(Action))
stats.Counter.Access, _ = x.Count(new(Access))
stats.Counter.Issue, _ = x.Count(new(Issue))
stats.Counter.Comment, _ = x.Count(new(Comment))
2015-09-17 16:11:44 -04:00
stats.Counter.Oauth = 0
2014-08-28 22:29:00 +08:00
stats.Counter.Follow, _ = x.Count(new(Follow))
stats.Counter.Mirror, _ = x.Count(new(Mirror))
2014-06-21 00:51:41 -04:00
stats.Counter.Release, _ = x.Count(new(Release))
stats.Counter.LoginSource = LoginSources.Count(ctx)
2014-06-21 00:51:41 -04:00
stats.Counter.Webhook, _ = x.Count(new(Webhook))
stats.Counter.Milestone, _ = x.Count(new(Milestone))
2014-08-28 22:29:00 +08:00
stats.Counter.Label, _ = x.Count(new(Label))
stats.Counter.HookTask, _ = x.Count(new(HookTask))
stats.Counter.Team, _ = x.Count(new(Team))
stats.Counter.Attachment, _ = x.Count(new(Attachment))
return stats
2014-03-20 16:04:56 -04:00
}
2014-05-05 00:55:17 -04:00
2014-08-06 17:21:24 -04:00
func Ping() error {
if x == nil {
return errors.New("database not available")
}
2014-08-06 17:21:24 -04:00
return x.Ping()
}
// The version table. Should have only one row with id==1
type Version struct {
ID int64
Version int64
}