MCPcopy Create free account
hub / github.com/gogs/gogs / NewConnection

Function NewConnection

internal/database/database.go:50–124  ·  view source on GitHub ↗

NewConnection returns a new database connection with the given logger.

(w logger.Writer)

Source from the content-addressed store, hash-verified

48
49// NewConnection returns a new database connection with the given logger.
50func NewConnection(w logger.Writer) (*gorm.DB, error) {
51 level := logger.Info
52 if conf.IsProdMode() {
53 level = logger.Warn
54 }
55
56 // NOTE: AutoMigrate does not respect logger passed in gorm.Config.
57 logger.Default = logger.New(w, logger.Config{
58 SlowThreshold: 100 * time.Millisecond,
59 LogLevel: level,
60 })
61
62 db, err := dbutil.OpenDB(
63 conf.Database,
64 &gorm.Config{
65 SkipDefaultTransaction: true,
66 NamingStrategy: schema.NamingStrategy{
67 SingularTable: true,
68 },
69 NowFunc: func() time.Time {
70 return time.Now().UTC().Truncate(time.Microsecond)
71 },
72 },
73 )
74 if err != nil {
75 return nil, errors.Wrap(err, "open database")
76 }
77
78 sqlDB, err := db.DB()
79 if err != nil {
80 return nil, errors.Wrap(err, "get underlying *sql.DB")
81 }
82 sqlDB.SetMaxOpenConns(conf.Database.MaxOpenConns)
83 sqlDB.SetMaxIdleConns(conf.Database.MaxIdleConns)
84 sqlDB.SetConnMaxLifetime(time.Minute)
85
86 switch conf.Database.Type {
87 case "postgres":
88 conf.UsePostgreSQL = true
89 case "mysql":
90 conf.UseMySQL = true
91 db = db.Set("gorm:table_options", "ENGINE=InnoDB").Session(&gorm.Session{})
92 case "sqlite3":
93 conf.UseSQLite3 = true
94 case "mssql":
95 conf.UseMSSQL = true
96 default:
97 panic("unreachable")
98 }
99
100 // NOTE: GORM has problem detecting existing columns, see
101 // https://github.com/gogs/gogs/issues/6091. Therefore, only use it to create new
102 // tables, and do customize migration with future changes.
103 for _, table := range Tables {
104 if db.Migrator().HasTable(table) {
105 continue
106 }
107

Callers 1

SetEngineFunction · 0.85

Calls 4

IsProdModeFunction · 0.92
OpenDBFunction · 0.92
CustomDirFunction · 0.92
loadLoginSourceFilesFunction · 0.85

Tested by

no test coverage detected