# Database Platform Package This package is responsible for initializing and managing the application's database connection. It provides a centralized and consistent way to configure and access the database. ## Architecture Overview The `db` package abstracts the underlying database technology (GORM) and provides a simple function, `InitDB`, to create a new database connection based on the application's configuration. ### Key Components - **`db.go`**: Contains the `InitDB` function, which is the sole entry point for this package. It takes a `config.Config` object and a `*observability.Metrics` instance, and returns a `*gorm.DB` connection pool. ## Features - **Centralized Configuration**: All database connection settings (host, port, user, password, etc.) are read from the application's central `config` object. - **Prometheus Integration**: The package integrates with the `gorm-prometheus` plugin to expose GORM metrics (query latency, error rates, etc.) to the application's Prometheus instance. - **Connection Management**: The `InitDB` function returns a fully configured `*gorm.DB` object, which manages the connection pool. The `Close` function is provided to gracefully close the database connection on application shutdown. ## Usage The `InitDB` function is called once at the application's startup in `cmd/api/main.go`. The resulting `*gorm.DB` object is then passed down to the repository layer. ### Example: Initializing the Database ```go // In cmd/api/main.go import "tercul/internal/platform/db" // ... // Initialize database connection database, err := db.InitDB(cfg, metrics) if err != nil { // handle error } defer db.Close(database) // Pass the 'database' object to the repositories repos := sql.NewRepositories(database, cfg) // ... ``` ## Dependencies - **`internal/platform/config`**: Relies on the `Config` struct for all database connection parameters. - **`internal/observability`**: Uses the `Metrics` object to register GORM's Prometheus metrics. - **`gorm.io/driver/postgres`**: The underlying database driver for PostgreSQL. - **`gorm.io/gorm`**: The GORM library. - **`gorm.io/plugin/prometheus`**: The GORM plugin for Prometheus integration.