{"modulePath":"github.com/CrisisTextLine/modular/modules/database","version":"v1.4.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package database\n\nPackage database provides database connectivity and management for modular applications. This module supports multiple database connections with different drivers and provides a unified interface for database operations.\n\nThe database module features:\n\n  - Multiple database connections with configurable drivers (MySQL, PostgreSQL, SQLite, etc.)\n  - Connection pooling and health monitoring\n  - Default connection selection for simplified usage\n  - Database service abstraction for testing and mocking\n  - Instance-aware configuration for environment-specific settings\n\nUsage:\n\n\tapp.RegisterModule(database.NewModule())\n\nThe module registers database services that provide access to sql.DB instances and higher-level database operations. Other modules can depend on these services for database access.\n\nConfiguration:\n\n\tThe module requires a \"database\" configuration section with connection details\n\tfor each database instance, including driver, DSN, and connection pool settings.\n\n## Constants\n\n```go\nconst (\n\t// Connection events\n\tEventTypeConnected       = \"com.modular.database.connected\"\n\tEventTypeDisconnected    = \"com.modular.database.disconnected\"\n\tEventTypeConnectionError = \"com.modular.database.connection.error\"\n\n\t// Query events\n\tEventTypeQueryExecuted = \"com.modular.database.query.executed\"\n\tEventTypeQueryError    = \"com.modular.database.query.error\"\n\n\t// Transaction events\n\tEventTypeTransactionStarted    = \"com.modular.database.transaction.started\"\n\tEventTypeTransactionCommitted  = \"com.modular.database.transaction.committed\"\n\tEventTypeTransactionRolledBack = \"com.modular.database.transaction.rolledback\"\n\n\t// Migration events\n\tEventTypeMigrationStarted   = \"com.modular.database.migration.started\"\n\tEventTypeMigrationCompleted = \"com.modular.database.migration.completed\"\n\tEventTypeMigrationFailed    = \"com.modular.database.migration.failed\"\n\n\t// Configuration events\n\tEventTypeConfigLoaded = \"com.modular.database.config.loaded\"\n)\n```\nEvent type constants for database module events. Following CloudEvents specification reverse domain notation.\n\n```go\nconst (\n\t// DefaultConnectionTimeout is the default timeout for database connection tests\n\tDefaultConnectionTimeout = 5 * time.Second\n)\n```\nConstants for database service\n\n```go\nconst Name = \"database\"\n```\nModule name constant for service registration and dependency resolution.\n\n## Variables\n\n```go\nvar (\n\tErrIAMAuthNotEnabled     = errors.New(\"AWS IAM auth not enabled\")\n\tErrIAMRegionRequired     = errors.New(\"AWS region is required for IAM authentication\")\n\tErrIAMDBUserRequired     = errors.New(\"database user is required for IAM authentication\")\n\tErrExtractEndpointFailed = errors.New(\"could not extract endpoint from DSN\")\n\tErrNoUserInfoInDSN       = errors.New(\"no user information in DSN to replace password\")\n)\n```\n\n```go\nvar (\n\t// ErrTransactionNil is returned when a nil transaction is passed to transaction operations\n\tErrTransactionNil = errors.New(\"transaction cannot be nil\")\n\n\t// ErrInvalidTableName is returned when an invalid table name is used\n\tErrInvalidTableName = errors.New(\"invalid table name: must start with letter/underscore and contain only alphanumeric/underscore characters\")\n\n\t// ErrMigrationServiceNotInitialized is returned when migration operations are attempted\n\t// without proper migration service initialization\n\tErrMigrationServiceNotInitialized = errors.New(\"migration service not initialized\")\n)\n```\nStatic error definitions to avoid dynamic error creation (err113 linter)\n\n```go\nvar (\n\tErrNoDefaultService          = errors.New(\"no default database service available\")\n\tErrNoSubjectForEventEmission = errors.New(\"no subject available for event emission\")\n)\n```\nStatic errors for err113 compliance\n\n```go\nvar (\n\tErrInvalidConfigType = errors.New(\"invalid config type for database module\")\n\tErrMissingDriver     = errors.New(\"database connection missing driver\")\n\tErrMissingDSN        = errors.New(\"database connection missing DSN\")\n)\n```\n\n```go\nvar (\n\tErrEmptyDriver          = errors.New(\"database driver cannot be empty\")\n\tErrEmptyDSN             = errors.New(\"database connection string (DSN) cannot be empty\")\n\tErrDatabaseNotConnected = errors.New(\"database not connected\")\n)\n```\nDefine static errors\n\n## Types\n\n```go\ntype AWSIAMAuthConfig struct {\n\t// Enabled indicates whether AWS IAM authentication is enabled\n\tEnabled bool `json:\"enabled\" yaml:\"enabled\" env:\"AWS_IAM_AUTH_ENABLED\"`\n\n\t// Region specifies the AWS region for the RDS instance\n\tRegion string `json:\"region\" yaml:\"region\" env:\"AWS_IAM_AUTH_REGION\"`\n\n\t// DBUser specifies the database username for IAM authentication\n\tDBUser string `json:\"db_user\" yaml:\"db_user\" env:\"AWS_IAM_AUTH_DB_USER\"`\n\n\t// TokenRefreshInterval specifies how often to refresh the IAM token (in seconds)\n\t// Default is 10 minutes (600 seconds), tokens expire after 15 minutes\n\tTokenRefreshInterval int `json:\"token_refresh_interval\" yaml:\"token_refresh_interval\" env:\"AWS_IAM_AUTH_TOKEN_REFRESH\" default:\"600\"`\n\n\t// ConnectionTimeout specifies the timeout for database connection tests (in seconds)\n\t// Default is 5 seconds\n\tConnectionTimeout time.Duration `json:\"connection_timeout\" yaml:\"connection_timeout\" env:\"AWS_IAM_AUTH_CONNECTION_TIMEOUT\" default:\"5s\"`\n\n\t// ConnectionCloseGracePeriod specifies the grace period to wait before closing old connections after token refresh\n\t// This allows in-flight queries to complete before the old connection pool is closed\n\t// Default is 5 seconds\n\tConnectionCloseGracePeriod time.Duration `json:\"connection_close_grace_period\" yaml:\"connection_close_grace_period\" env:\"AWS_IAM_AUTH_CONNECTION_CLOSE_GRACE_PERIOD\" default:\"5s\"`\n}\n```\nAWSIAMAuthConfig represents AWS IAM authentication configuration\n\n```go\ntype AWSIAMTokenProvider struct {\n\t// contains filtered or unexported fields\n}\n```\nAWSIAMTokenProvider manages AWS IAM authentication tokens for RDS\n\n```go\nfunc NewAWSIAMTokenProvider(authConfig *AWSIAMAuthConfig) (*AWSIAMTokenProvider, error)\n```\nNewAWSIAMTokenProvider creates a new AWS IAM token provider\n\n```go\nfunc (p *AWSIAMTokenProvider) BuildDSNWithIAMToken(ctx context.Context, originalDSN string) (string, error)\n```\nBuildDSNWithIAMToken takes a DSN and replaces the password with the IAM token\n\n```go\nfunc (p *AWSIAMTokenProvider) GetToken(ctx context.Context, endpoint string) (string, error)\n```\nGetToken returns the current valid IAM token, refreshing if necessary\n\n```go\nfunc (p *AWSIAMTokenProvider) SetTokenRefreshCallback(callback TokenRefreshCallback)\n```\nSetTokenRefreshCallback sets a callback to be notified when tokens are refreshed\n\n```go\nfunc (p *AWSIAMTokenProvider) StartTokenRefresh(ctx context.Context, endpoint string)\n```\nStartTokenRefresh starts a background goroutine to refresh tokens periodically\n\n```go\nfunc (p *AWSIAMTokenProvider) StopTokenRefresh()\n```\nStopTokenRefresh stops the background token refresh\n\n```go\ntype Config struct {\n\t// Connections contains all defined database connections\n\tConnections map[string]*ConnectionConfig `json:\"connections\" yaml:\"connections\"`\n\n\t// Default specifies the name of the default connection\n\tDefault string `json:\"default\" yaml:\"default\" env:\"DEFAULT_DB_CONNECTION\"`\n}\n```\nConfig represents database module configuration\n\n```go\nfunc (c *Config) GetInstanceConfigs() map[string]interface{}\n```\nGetInstanceConfigs returns the connections map for instance-aware configuration\n\n```go\nfunc (c *Config) Validate() error\n```\nValidate implements ConfigValidator interface\n\n```go\ntype ConnectionConfig struct {\n\t// Driver specifies the database driver to use (e.g., \"postgres\", \"mysql\")\n\tDriver string `json:\"driver\" yaml:\"driver\" env:\"DRIVER\"`\n\n\t// DSN is the database connection string\n\tDSN string `json:\"dsn\" yaml:\"dsn\" env:\"DSN\"`\n\n\t// MaxOpenConnections sets the maximum number of open connections to the database\n\tMaxOpenConnections int `json:\"max_open_connections\" yaml:\"max_open_connections\" env:\"MAX_OPEN_CONNECTIONS\"`\n\n\t// MaxIdleConnections sets the maximum number of idle connections in the pool\n\tMaxIdleConnections int `json:\"max_idle_connections\" yaml:\"max_idle_connections\" env:\"MAX_IDLE_CONNECTIONS\"`\n\n\t// ConnectionMaxLifetime sets the maximum amount of time a connection may be reused\n\tConnectionMaxLifetime time.Duration `json:\"connection_max_lifetime\" yaml:\"connection_max_lifetime\" env:\"CONNECTION_MAX_LIFETIME\"`\n\n\t// ConnectionMaxIdleTime sets the maximum amount of time a connection may be idle\n\tConnectionMaxIdleTime time.Duration `json:\"connection_max_idle_time\" yaml:\"connection_max_idle_time\" env:\"CONNECTION_MAX_IDLE_TIME\"`\n\n\t// AWSIAMAuth contains AWS IAM authentication configuration\n\tAWSIAMAuth *AWSIAMAuthConfig `json:\"aws_iam_auth,omitempty\" yaml:\"aws_iam_auth,omitempty\"`\n}\n```\nConnectionConfig represents configuration for a single database connection\n\n```go\ntype DatabaseService interface {\n\t// Connect establishes the database connection\n\tConnect() error\n\n\t// Close closes the database connection\n\tClose() error\n\n\t// DB returns the underlying database connection\n\tDB() *sql.DB\n\n\t// Ping verifies the database connection is still alive\n\tPing(ctx context.Context) error\n\n\t// Stats returns database statistics\n\tStats() sql.DBStats\n\n\t// ExecContext executes a query without returning any rows\n\tExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)\n\n\t// Exec executes a query without returning any rows (using default context)\n\tExec(query string, args ...interface{}) (sql.Result, error)\n\n\t// ExecuteContext executes a query without returning any rows (alias for ExecContext)\n\t// Kept for backwards compatibility with earlier API docs/tests\n\tExecuteContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)\n\n\t// Execute executes a query without returning any rows (alias for Exec)\n\t// Kept for backwards compatibility with earlier API docs/tests\n\tExecute(query string, args ...interface{}) (sql.Result, error)\n\n\t// PrepareContext prepares a statement for execution\n\tPrepareContext(ctx context.Context, query string) (*sql.Stmt, error)\n\n\t// Prepare prepares a statement for execution (using default context)\n\tPrepare(query string) (*sql.Stmt, error)\n\n\t// QueryContext executes a query that returns rows\n\tQueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)\n\n\t// Query executes a query that returns rows (using default context)\n\tQuery(query string, args ...interface{}) (*sql.Rows, error)\n\n\t// QueryRowContext executes a query that returns a single row\n\tQueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row\n\n\t// QueryRow executes a query that returns a single row (using default context)\n\tQueryRow(query string, args ...interface{}) *sql.Row\n\n\t// BeginTx starts a transaction\n\tBeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)\n\n\t// Begin starts a transaction with default options\n\tBegin() (*sql.Tx, error)\n\n\t// CommitTransaction commits a transaction and emits appropriate events\n\tCommitTransaction(ctx context.Context, tx *sql.Tx) error\n\n\t// RollbackTransaction rolls back a transaction and emits appropriate events\n\tRollbackTransaction(ctx context.Context, tx *sql.Tx) error\n\n\t// Migration operations\n\t// RunMigration executes a database migration\n\tRunMigration(ctx context.Context, migration Migration) error\n\n\t// GetAppliedMigrations returns a list of applied migration IDs\n\tGetAppliedMigrations(ctx context.Context) ([]string, error)\n\n\t// CreateMigrationsTable ensures the migrations tracking table exists\n\tCreateMigrationsTable(ctx context.Context) error\n\n\t// SetEventEmitter sets the event emitter for migration events\n\tSetEventEmitter(emitter EventEmitter)\n}\n```\nDatabaseService defines the operations that can be performed with a database\n\n```go\nfunc NewDatabaseService(config ConnectionConfig, logger modular.Logger) (DatabaseService, error)\n```\nNewDatabaseService creates a new database service from configuration\n\n```go\ntype EventEmitter interface {\n\t// EmitEvent emits a cloud event with the provided context\n\tEmitEvent(ctx context.Context, event cloudevents.Event) error\n}\n```\nEventEmitter interface for emitting migration events\n\n```go\ntype IAMTokenProvider interface {\n\tGetToken(ctx context.Context, endpoint string) (string, error)\n\tBuildDSNWithIAMToken(ctx context.Context, originalDSN string) (string, error)\n\tStartTokenRefresh(ctx context.Context, endpoint string)\n\tStopTokenRefresh()\n\t// SetTokenRefreshCallback sets a callback to be notified when tokens are refreshed\n\tSetTokenRefreshCallback(callback TokenRefreshCallback)\n}\n```\nIAMTokenProvider defines the interface for AWS IAM token providers\n\n```go\ntype Migration struct {\n\tID      string\n\tVersion string\n\tSQL     string\n\tUp      bool // true for up migration, false for down\n}\n```\nMigration represents a database migration\n\n```go\ntype MigrationRunner struct {\n\t// contains filtered or unexported fields\n}\n```\nMigrationRunner helps run multiple migrations\n\n```go\nfunc NewMigrationRunner(service MigrationService) *MigrationRunner\n```\nNewMigrationRunner creates a new migration runner\n\n```go\nfunc (r *MigrationRunner) RunMigrations(ctx context.Context, migrations []Migration) error\n```\nRunMigrations runs a set of migrations in order\n\n```go\ntype MigrationService interface {\n\t// RunMigration executes a single migration\n\tRunMigration(ctx context.Context, migration Migration) error\n\n\t// GetAppliedMigrations returns a list of already applied migrations\n\tGetAppliedMigrations(ctx context.Context) ([]string, error)\n\n\t// CreateMigrationsTable creates the migrations tracking table\n\tCreateMigrationsTable(ctx context.Context) error\n}\n```\nMigrationService provides migration functionality\n\n```go\nfunc NewMigrationService(db *sql.DB, eventEmitter EventEmitter) MigrationService\n```\nNewMigrationService creates a new migration service\n\n```go\ntype Module struct {\n\t// contains filtered or unexported fields\n}\n```\nModule represents the database module and implements the modular.Module interface. It manages multiple database connections and provides services for database access.\n\nThe module supports:\n\n  - Multiple named database connections\n  - Automatic connection health monitoring\n  - Default connection selection\n  - Service abstraction for easier testing\n  - Instance-aware configuration\n  - Event observation and emission for database operations\n\nThe module implements the following interfaces:\n\n  - modular.Module: Basic module lifecycle\n  - modular.Configurable: Configuration management\n  - modular.ServiceAware: Service dependency management\n  - modular.Startable: Startup logic\n  - modular.Stoppable: Shutdown logic\n  - modular.ObservableModule: Event observation and emission\n\n```go\nfunc NewModule() *Module\n```\nNewModule creates a new database module instance. The returned module must be registered with the application before use.\n\nExample:\n\n\tdbModule := database.NewModule()\n\tapp.RegisterModule(dbModule)\n\n```go\nfunc (m *Module) Constructor() modular.ModuleConstructor\n```\nConstructor provides a dependency injection constructor for the module. This allows the logger service to be properly injected during module initialization.\n\n```go\nfunc (m *Module) Dependencies() []string\n```\nDependencies returns the names of modules this module depends on. The database module has no dependencies, making it suitable as a foundation module that other modules can depend on.\n\n```go\nfunc (m *Module) EmitEvent(ctx context.Context, event cloudevents.Event) error\n```\nEmitEvent implements the ObservableModule interface. This allows the database module to emit events to registered observers.\n\n```go\nfunc (m *Module) GetConnection(name string) (*sql.DB, bool)\n```\nGetConnection returns a database connection by name. This method allows access to specific named database connections that were configured in the module's configuration.\n\nExample:\n\n\tif db, exists := dbModule.GetConnection(\"primary\"); exists {\n\t    // Use the primary database connection\n\t}\n\n```go\nfunc (m *Module) GetConnections() []string\n```\nGetConnections returns a list of all available connection names. This is useful for discovery and diagnostic purposes.\n\n```go\nfunc (m *Module) GetDefaultConnection() *sql.DB\n```\nGetDefaultConnection returns the default database connection. The default connection is determined by the \"default\" field in the configuration. If no default is configured or the named connection doesn't exist, this method will return any available connection.\n\nReturns nil if no connections are available.\n\n```go\nfunc (m *Module) GetDefaultService() DatabaseService\n```\nGetDefaultService returns the default database service. Similar to GetDefaultConnection, but returns a DatabaseService interface that provides additional functionality beyond the raw sql.DB.\n\n```go\nfunc (m *Module) GetRegisteredEventTypes() []string\n```\nGetRegisteredEventTypes implements the ObservableModule interface. Returns all event types that this database module can emit.\n\n```go\nfunc (m *Module) GetService(name string) (DatabaseService, bool)\n```\nGetService returns a database service by name. Database services provide a higher-level interface than raw database connections, including connection management and additional utilities.\n\n```go\nfunc (m *Module) Init(app modular.Application) error\n```\nInit initializes the database module and establishes database connections. This method loads the configuration, validates connection settings, and establishes connections to all configured databases.\n\nInitialization process:\n\n 1. Load configuration from the \"database\" section\n 2. Validate connection configurations\n 3. Create database services for each connection\n 4. Test initial connectivity\n\n```go\nfunc (m *Module) Name() string\n```\nName returns the name of the module. This name is used for dependency resolution and configuration section lookup.\n\n```go\nfunc (m *Module) ProvidesServices() []modular.ServiceProvider\n```\nProvidesServices declares services provided by this module. The database module provides:\n\n  - database.manager: Module instance for direct database management\n  - database.service: Default database service for convenient access\n\nOther modules can depend on these services to access database functionality.\n\n```go\nfunc (m *Module) RegisterConfig(app modular.Application) error\n```\nRegisterConfig registers the module's configuration structure. The database module uses instance-aware configuration to support environment-specific database connection settings.\n\nConfiguration structure:\n\n  - Default: name of the default connection to use\n  - Connections: map of connection names to their configurations\n\nEnvironment variables:\n\n\tDB_\u003cCONNECTION_NAME\u003e_DRIVER, DB_\u003cCONNECTION_NAME\u003e_DSN, etc.\n\n```go\nfunc (m *Module) RegisterObservers(subject modular.Subject) error\n```\nRegisterObservers implements the ObservableModule interface. This allows the database module to register as an observer for events it's interested in.\n\n```go\nfunc (m *Module) RequiresServices() []modular.ServiceDependency\n```\nRequiresServices declares services required by this module. The database module requires the logger service for structured logging.\n\n```go\nfunc (m *Module) Start(ctx context.Context) error\n```\nStart starts the database module and verifies connectivity. This method performs health checks on all database connections to ensure they are ready for use by other modules.\n\n```go\nfunc (m *Module) Stop(ctx context.Context) error\n```\nStop stops the database module and closes all connections. This method gracefully closes all database connections and services, ensuring proper cleanup during application shutdown.\n\n```go\ntype TokenRefreshCallback func(newToken string, endpoint string)\n```\nTokenRefreshCallback is called when a token is refreshed\n\n","path":"github.com/CrisisTextLine/modular/modules/database","name":"database","synopsis":"Package database provides database connectivity and management for modular applications.","isRedistributable":true}
