{"record":{"id":"6877f2ee0fec8eab","repo":"flipped-aurora/gin-vue-admin","slug":"panic-err-mysql-database-connection-failed","errorCode":null,"errorMessage":"panic(err) — MySQL database connection failed","messagePattern":"panic\\(err\\) — MySQL database connection failed","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"critical","filePath":"server/initialize/gorm_mysql.go","lineNumber":42,"sourceCode":"func GormMysqlByConfig(m config.Mysql) *gorm.DB {\n\treturn initMysqlDatabase(m)\n}\n\n// initMysqlDatabase 初始化Mysql数据库的辅助函数\nfunc initMysqlDatabase(m config.Mysql) *gorm.DB {\n\tif m.Dbname == \"\" {\n\t\treturn nil\n\t}\n\n\tmysqlConfig := mysql.Config{\n\t\tDSN:                       m.Dsn(), // DSN data source name\n\t\tDefaultStringSize:         191,     // string 类型字段的默认长度\n\t\tSkipInitializeWithVersion: false,   // 根据版本自动配置\n\t}\n\t// 数据库配置\n\tgeneral := m.GeneralDB\n\tif db, err := gorm.Open(mysql.New(mysqlConfig), internal.Gorm.Config(general)); err != nil {\n\t\tpanic(err)\n\t} else {\n\t\tdb.InstanceSet(\"gorm:table_options\", \"ENGINE=\"+m.Engine)\n\t\tsqlDB, _ := db.DB()\n\t\tsqlDB.SetMaxIdleConns(m.MaxIdleConns)\n\t\tsqlDB.SetMaxOpenConns(m.MaxOpenConns)\n\t\tsqlDB.SetConnMaxLifetime(time.Duration(m.ConnMaxLifetime) * time.Second)\n\t\treturn db\n\t}\n}\n","sourceCodeStart":24,"sourceCodeEnd":52,"githubUrl":"https://github.com/flipped-aurora/gin-vue-admin/blob/3136500ef380842b0eb6c4daa87c3f8a47fcf9e0/server/initialize/gorm_mysql.go#L24-L52","documentation":"initMysqlDatabase calls gorm.Open to establish the MySQL connection using the configured DSN; if gorm.Open returns an error (driver missing, bad DSN, unreachable server, auth failure), the initializer calls panic(err), crashing the server at startup. This is an intentional fail-fast: the app cannot serve without its primary database. The panic aborts GormMysql/GormMysqlByConfig and therefore the whole GVA initialization.","triggerScenarios":"gorm.Open(mysql.New(mysqlConfig), internal.Gorm.Config(general)) returns err at startup — e.g. mysql.go:/bin/sh-missing driver registration (blank import absent), malformed host/port/user/password/dbname in config.yaml (system.db-mysql), MySQL server down or firewall-blocked, wrong credentials, or TLS/charset params invalid in the DSN.","commonSituations":"Deploying without the MySQL container/service up (docker-compose ordering); typos in config.yaml db host/path (e.g. wrong parseTime/loc params); MySQL 8 caching_sha2_password with an old driver; database user lacking connect grants; k8s pod starting before the DB service is ready.","solutions":["Verify MySQL is reachable from the server host: mysql -h <host> -P <port> -u <user> -p and check docker/k8s service ordering/healthchecks.","Check the db-mysql block in config.yaml: path, port, config (charset/parseTime/loc), username, password, dbname; fix typos and special characters in the password.","Confirm the mysql driver is registered (the gorm.io/driver/mysql blank import in gorm_mysql.go) and go.mod is in sync (go mod tidy).","If the DB may start after the app, add retry/backoff around gorm.Open or a readiness gate instead of instant panic.","Inspect the wrapped err text — MySQL driver errors (1045 access denied, 2003 can't connect) identify auth vs network directly."],"exampleFix":"// before\nif db, err := gorm.Open(mysql.New(mysqlConfig), internal.Gorm.Config(general)); err != nil {\n    panic(err)\n}\n// after\nif db, err := gorm.Open(mysql.New(mysqlConfig), internal.Gorm.Config(general)); err != nil {\n    // log the underlying driver reason before failing fast\n    global.GVA_LOG.Error(\"mysql connect failed\", zap.Error(err))\n    panic(fmt.Sprintf(\"mysql connect failed: %v\", err))\n}","handlingStrategy":"validation","validationCode":"// before starting the app, verify connectivity\nnet.DialTimeout(\"tcp\", fmt.Sprintf(\"%s:%s\", cfg.Path, cfg.Port), 3*time.Second)\n// and preflight the DSN:\ndb, err := sql.Open(\"mysql\", dsn); if err == nil { err = db.Ping() }; db.Close()","typeGuard":null,"tryCatchPattern":"// fail fast with context instead of bare panic\nif db, err := gorm.Open(mysql.New(mysqlConfig), internal.Gorm.Config(general)); err != nil {\n    log.Fatalf(\"mysql init failed: %v\", err) // preserves stack + message\n}","preventionTips":["Ping the DB in CI/deployment healthchecks before launching the app","Keep DB config in one config.yaml section and validate it at boot (host/port/user/dbname non-empty)","Add readiness ordering in docker-compose/k8s (depends_on with healthcheck, init containers)","Never commit credentials; use env overrides so environment drift is explicit","Watch the panic message's driver error code (1045 auth vs 2003 network) to triage fast"],"tags":["mysql","gorm","startup","panic","database"],"backgroundTag":"database-connection-failed","analyzedSha":"3136500ef380842b0eb6c4daa87c3f8a47fcf9e0","analyzedAt":"2026-08-31T13:50:02.721Z","schemaVersion":2},"datasetVersion":"2026-08-31T19:17:28.585Z"}