{"modulePath":"github.com/CrisisTextLine/modular/modules/database/v2","version":"v2.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 EffectiveTokenLifetime = IAMTokenTTL - TokenRefreshBuffer // 14 minutes\n\n```\nEffectiveTokenLifetime is the actual time we'll cache a token before refreshing This ensures we refresh before the token expires\n\n```go\nconst IAMTokenTTL = 15 * time.Minute\n```\nIAMTokenTTL is the lifetime of an AWS RDS IAM authentication token AWS documentation states tokens are valid for 15 minutes\n\n```go\nconst Name = \"database\"\n```\nModule name constant for service registration and dependency resolution.\n\n```go\nconst TokenRefreshBuffer = 1 * time.Minute\n```\nTokenRefreshBuffer is the buffer time before token expiration to refresh We refresh 1 minute before expiration to avoid edge cases\n\n## Variables\n\n```go\nvar (\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\tErrAWSIAMAuthNotEnabled = errors.New(\"AWS IAM auth not enabled\")\n\tErrInvalidDSNFormat     = errors.New(\"invalid DSN format\")\n\tErrMissingIAMRegion     = errors.New(\"AWS IAM auth region is required but not configured\")\n\tErrMissingIAMUsername   = errors.New(\"database username is required for IAM auth but not found in DSN or config\")\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 (e.g., \"us-east-1\")\n\t// This is required for IAM token generation\n\tRegion string `json:\"region\" yaml:\"region\" env:\"AWS_IAM_AUTH_REGION\"`\n\n\t// DBUser specifies the database username for IAM authentication.\n\t// If not specified, the username will be extracted from the DSN.\n\t// This field takes precedence over the username in the DSN if both are provided.\n\tDBUser string `json:\"db_user\" yaml:\"db_user\" env:\"AWS_IAM_AUTH_DB_USER\"`\n\n\t// ConnectionTimeout specifies the timeout for database connection tests\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```\nAWSIAMAuthConfig represents AWS IAM authentication configuration.\n\nWhen IAM authentication is enabled, the database module uses AWS RDS IAM authentication to automatically generate and refresh database authentication tokens. This provides several benefits:\n\n  - No need to manage database passwords\n  - Tokens are automatically rotated (15-minute lifetime)\n  - Uses AWS IAM for access control\n  - Audit trail through AWS CloudTrail\n\nDSN Password Handling: When IAM authentication is enabled, any password in the DSN is ignored and stripped. You can include a placeholder like $TOKEN in the DSN for clarity, but it will be removed:\n\n\tExample DSN:\n\t  postgresql://chimera_app:$TOKEN@mydb.us-east-1.rds.amazonaws.com:5432/mydb?sslmode=require\n\n\tThe module will:\n\t  1. Strip the \"$TOKEN\" placeholder from the DSN\n\t  2. Extract the username \"chimera_app\"\n\t  3. Use AWS credentials to generate an IAM auth token\n\t  4. Automatically refresh the token before it expires\n\nConfiguration Options:\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 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 TTLStore struct {\n\t// contains filtered or unexported fields\n}\n```\nTTLStore wraps a driver.Store and adds TTL-based caching to prevent using expired IAM authentication tokens.\n\nThe Problem: The awsrds.Store implementation caches credentials indefinitely, which causes PAM authentication failures after 15 minutes when tokens expire.\n\nThe Solution: This wrapper adds a TTL to the cached credentials. When Get() is called:\n\n 1. If no credentials are cached, call Refresh() to get new ones\n 2. If credentials exist but are expired (\u003e14 min old), call Refresh()\n 3. If credentials exist and are fresh (\\\u003c14 min old), return cached ones\n\nThis ensures tokens are always refreshed before they expire, preventing authentication failures while still benefiting from caching.\n\n```go\nfunc NewTTLStore(wrapped driver.Store) *TTLStore\n```\nNewTTLStore creates a new TTL-aware store wrapper\n\n```go\nfunc NewTTLStoreWithLifetime(wrapped driver.Store, lifetime time.Duration) *TTLStore\n```\nNewTTLStoreWithLifetime creates a TTL store with a custom token lifetime This is useful for testing with shorter lifetimes\n\n```go\nfunc (s *TTLStore) Get(ctx context.Context) (driver.Credentials, error)\n```\nGet implements driver.Store interface with TTL-based caching\n\n```go\nfunc (s *TTLStore) GetTokenAge() time.Duration\n```\nGetTokenAge returns how old the current cached token is Returns 0 if no token is cached\n\n```go\nfunc (s *TTLStore) IsTokenFresh() bool\n```\nIsTokenFresh returns true if cached token is still within TTL\n\n```go\nfunc (s *TTLStore) Refresh(ctx context.Context) (driver.Credentials, error)\n```\nRefresh implements driver.Store interface, always getting fresh credentials\n\n","path":"github.com/CrisisTextLine/modular/modules/database/v2","name":"database","synopsis":"Package database provides database connectivity and management for modular applications.","isRedistributable":true}
