modified: main_dc/docker-compose.yml
modified: main_dc/yalarba/api_es/.env modified: main_dc/yalarba/api_es/cmd/main.go modified: main_dc/yalarba/api_es/go.mod modified: main_dc/yalarba/api_es/go.sum new file: main_dc/yalarba/api_es/internal/config/config.go new file: main_dc/yalarba/api_es/internal/database/psql_db.go new file: main_dc/yalarba/api_es/pkg/logger/helpers.go new file: main_dc/yalarba/api_es/pkg/logger/interface.go new file: main_dc/yalarba/api_es/pkg/logger/logger.go new file: main_dc/yalarba/api_es/pkg/logger/route_logger.go add new User model for api_es add global zapLogger api_es add configs dotenv api_es sipmplify main api_es
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"api_es/internal/config"
|
||||
"api_es/internal/models"
|
||||
"api_es/pkg/logger"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func NewPostgresConnection(cfg *config.Config) (*gorm.DB, error) {
|
||||
zapLogger := logger.Get()
|
||||
zapLogger.Info("Start connect to Postgres DB")
|
||||
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=UTC",
|
||||
cfg.DBHost, cfg.DBUser, cfg.DBPassword, cfg.DBName, cfg.DBPort)
|
||||
zapLogger.Info("dsn = %s", zap.String("dsn", dsn))
|
||||
|
||||
|
||||
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to connect to database: %w", err)
|
||||
}
|
||||
|
||||
zapLogger.Info("AutoMigrate models")
|
||||
// Автомиграция
|
||||
if err := autoMigrate(db); err != nil {
|
||||
return nil, fmt.Errorf("can't migrate models, error = %s", err)
|
||||
}
|
||||
zapLogger.Info("Migrate complite successfully")
|
||||
|
||||
log.Println("Successfully connected to database")
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func autoMigrate(db *gorm.DB) error {
|
||||
// автоматические миграции GORM
|
||||
return db.AutoMigrate(
|
||||
&models.User{},
|
||||
// другие модели...
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user