Add NewMysqlBackendWithDB constructor to accept existing database connections
This PR adds support for creating MySQL backend instances with an existing *sql.DB connection, addressing the need for better database connection management and integration with existing applications.
Changes
Added a new constructor NewMysqlBackendWithDB(db *sql.DB, opts ...option) that allows users to provide their own configured database connection instead of having the backend create one internally.
Key Benefits
-
Better connection pool control: Users can configure
MaxOpenConns,MaxIdleConns,ConnMaxLifetime, etc. - Shared connections: Database connections can be shared across multiple components
- Advanced configurations: Support for connection parameters not easily expressed through the original DSN-based constructor
- Integration flexibility: Easier integration with existing database management strategies
Usage Examples
Original constructor (unchanged):
backend := mysql.NewMysqlBackend("localhost", 3306, "user", "password", "dbname")
New constructor:
dsn := "user:password@tcp(localhost:3306)/dbname?parseTime=true&multiStatements=true"
db, err := sql.Open("mysql", dsn)
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(10)
db.SetConnMaxLifetime(time.Hour)
backend := mysql.NewMysqlBackendWithDB(db)
Implementation Details
- Refactored common logic into shared
newMysqlBackendinternal function - Updated migration logic to handle both DSN-based and existing DB scenarios
- Maintained full backward compatibility with existing
NewMysqlBackend - Added comprehensive test coverage including integration tests
- Updated documentation with usage examples and important notes
Note: When using NewMysqlBackendWithDB, ensure your connection string includes multiStatements=true if you plan to use automatic migrations (enabled by default).
Fixes #412.
💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.