Dragonfly2

Форк
0
77 строк · 1.8 Кб
1
/*
2
 *     Copyright 2022 The Dragonfly Authors
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16

17
package database
18

19
import (
20
	"fmt"
21

22
	"gorm.io/driver/postgres"
23
	"gorm.io/gorm"
24
	"gorm.io/gorm/schema"
25
	"moul.io/zapgorm2"
26

27
	logger "d7y.io/dragonfly/v2/internal/dflog"
28
	"d7y.io/dragonfly/v2/manager/config"
29
)
30

31
func newPostgres(cfg *config.Config) (*gorm.DB, error) {
32
	postgresCfg := &cfg.Database.Postgres
33

34
	// Format dsn string.
35
	dsn := formatPostgresDSN(postgresCfg)
36

37
	// Connect to postgres.
38
	db, err := gorm.Open(postgres.New(postgres.Config{
39
		DSN:                  dsn,
40
		PreferSimpleProtocol: cfg.Database.Postgres.PreferSimpleProtocol,
41
	}), &gorm.Config{
42
		NamingStrategy: schema.NamingStrategy{
43
			SingularTable: true,
44
		},
45
		DisableForeignKeyConstraintWhenMigrating: true,
46
		Logger:                                   zapgorm2.New(logger.CoreLogger.Desugar()),
47
	})
48
	if err != nil {
49
		return nil, err
50
	}
51

52
	// Run migration.
53
	if postgresCfg.Migrate {
54
		if err := migrate(db); err != nil {
55
			return nil, err
56
		}
57
	}
58

59
	// Run seed.
60
	if err := seed(db); err != nil {
61
		return nil, err
62
	}
63

64
	return db, nil
65
}
66

67
func formatPostgresDSN(cfg *config.PostgresConfig) string {
68
	return fmt.Sprintf("host=%v user=%v password=%v dbname=%v port=%v sslmode=%v TimeZone=%v",
69
		cfg.Host,
70
		cfg.User,
71
		cfg.Password,
72
		cfg.DBName,
73
		cfg.Port,
74
		cfg.SSLMode,
75
		cfg.Timezone,
76
	)
77
}
78

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.