Proposal Details
We often need to adapt to different databases (e.g., PostgreSQL, MySQL), so we need to distinguish them using driverName. Since sql.DB or sql.Tx objects don't provide a DriverName() method, we have to pass the driverName parameter ourselves, as shown below:
func createGooseTable(db *sql.DB, driverName, gooseTable string) error {
var createSQL string
switch driverName {
case "mysql":
createSQL = fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
version_id BIGINT NOT NULL,
is_applied TINYINT DEFAULT 1 NOT NULL, -- 默认标记为已应用
tstamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
description VARCHAR(255)
)`, gooseTable)
case "postgres":
createSQL = fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s (
id SERIAL PRIMARY KEY,
version_id BIGINT NOT NULL,
is_applied BOOLEAN DEFAULT TRUE NOT NULL,
tstamp TIMESTAMPTZ DEFAULT NOW(),
description TEXT
)`, gooseTable)
default:
return fmt.Errorf("unsupported database type: %s", driver)
}
_, err := db.Exec(createSQL)
return err
}
Many such functions require this extra driverName parameter. If sql.DB and sql.Tx could provide this method, it would be much more convenient and save one parameter. This would also be a very small change.