Chuỗi bài: Go
go
48 dòng
· Cập nhật 2026-04-18
postgres.go
Go/Baasid/internal/database/postgres.go
// Package database opens the PostgreSQL connection pool and runs GORM
// AutoMigrate so developers can bootstrap quickly from an empty database.
//
// For production, prefer versioned SQL migrations (see /scripts) applied by
// your CI/CD pipeline; AutoMigrate is convenient but does not manage indexes
// renames or destructive changes as safely as explicit migrations.
package database
import (
"fmt"
"log"
"baasid/internal/models"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// Connect opens a GORM DB handle using the given PostgreSQL DSN.
//
// The DSN format is documented at https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING
// and accepted by the pgx driver underneath GORM's postgres dialector.
func Connect(dsn string) (*gorm.DB, error) {
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
// Logger prints SQL in development; switch to logger.Silent in prod.
Logger: logger.Default.LogMode(logger.Info),
})
if err != nil {
return nil, fmt.Errorf("gorm open: %w", err)
}
sqlDB, err := db.DB()
if err != nil {
return nil, fmt.Errorf("gorm sql.DB: %w", err)
}
// Reasonable defaults for a small REST service; tune for your load test.
sqlDB.SetMaxIdleConns(5)
sqlDB.SetMaxOpenConns(20)
if err := db.AutoMigrate(&models.SystemUser{}, &models.Goods{}); err != nil {
return nil, fmt.Errorf("auto migrate: %w", err)
}
log.Println("database: connected and AutoMigrate completed")
return db, nil
}
Bài viết liên quan
Go
go
Cập nhật 2026-04-18
main.go
main.go — go source code from the Go learning materials (Go/Baasid/cmd/hashpw/main.go).
Đọc bài viết →
Go
go
Cập nhật 2026-04-18
main.go
main.go — go source code from the Go learning materials (Go/Baasid/cmd/server/main.go).
Đọc bài viết →
Go
go
Cập nhật 2026-04-18
docs.go
docs.go — go source code from the Go learning materials (Go/Baasid/docs/docs.go).
Đọc bài viết →
Go
go
Cập nhật 2026-04-18
jwt.go
jwt.go — go source code from the Go learning materials (Go/Baasid/internal/auth/jwt.go).
Đọc bài viết →
Go
go
Cập nhật 2026-04-18
password.go
password.go — go source code from the Go learning materials (Go/Baasid/internal/auth/password.go).
Đọc bài viết →
Go
go
Cập nhật 2026-04-18
password_test.go
password_test.go — go source code from the Go learning materials (Go/Baasid/internal/auth/password_test.go).
Đọc bài viết →