main.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. package model
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. "strings"
  7. "sync"
  8. "time"
  9. "github.com/QuantumNous/new-api/common"
  10. "github.com/QuantumNous/new-api/constant"
  11. "github.com/glebarez/sqlite"
  12. "gorm.io/driver/mysql"
  13. "gorm.io/driver/postgres"
  14. "gorm.io/gorm"
  15. )
  16. var commonGroupCol string
  17. var commonKeyCol string
  18. var commonTrueVal string
  19. var commonFalseVal string
  20. var logKeyCol string
  21. var logGroupCol string
  22. func initCol() {
  23. // init common column names
  24. if common.UsingPostgreSQL {
  25. commonGroupCol = `"group"`
  26. commonKeyCol = `"key"`
  27. commonTrueVal = "true"
  28. commonFalseVal = "false"
  29. } else {
  30. commonGroupCol = "`group`"
  31. commonKeyCol = "`key`"
  32. commonTrueVal = "1"
  33. commonFalseVal = "0"
  34. }
  35. if os.Getenv("LOG_SQL_DSN") != "" {
  36. switch common.LogSqlType {
  37. case common.DatabaseTypePostgreSQL:
  38. logGroupCol = `"group"`
  39. logKeyCol = `"key"`
  40. default:
  41. logGroupCol = commonGroupCol
  42. logKeyCol = commonKeyCol
  43. }
  44. } else {
  45. // LOG_SQL_DSN 为空时,日志数据库与主数据库相同
  46. if common.UsingPostgreSQL {
  47. logGroupCol = `"group"`
  48. logKeyCol = `"key"`
  49. } else {
  50. logGroupCol = commonGroupCol
  51. logKeyCol = commonKeyCol
  52. }
  53. }
  54. // log sql type and database type
  55. //common.SysLog("Using Log SQL Type: " + common.LogSqlType)
  56. }
  57. var DB *gorm.DB
  58. var LOG_DB *gorm.DB
  59. func createRootAccountIfNeed() error {
  60. var user User
  61. //if user.Status != common.UserStatusEnabled {
  62. if err := DB.First(&user).Error; err != nil {
  63. common.SysLog("no user exists, create a root user for you: username is root, password is 123456")
  64. hashedPassword, err := common.Password2Hash("123456")
  65. if err != nil {
  66. return err
  67. }
  68. rootUser := User{
  69. Username: "root",
  70. Password: hashedPassword,
  71. Role: common.RoleRootUser,
  72. Status: common.UserStatusEnabled,
  73. DisplayName: "Root User",
  74. AccessToken: nil,
  75. Quota: 100000000,
  76. }
  77. DB.Create(&rootUser)
  78. }
  79. return nil
  80. }
  81. func CheckSetup() {
  82. setup := GetSetup()
  83. if setup == nil {
  84. // No setup record exists, check if we have a root user
  85. if RootUserExists() {
  86. common.SysLog("system is not initialized, but root user exists")
  87. // Create setup record
  88. newSetup := Setup{
  89. Version: common.Version,
  90. InitializedAt: time.Now().Unix(),
  91. }
  92. err := DB.Create(&newSetup).Error
  93. if err != nil {
  94. common.SysLog("failed to create setup record: " + err.Error())
  95. }
  96. constant.Setup = true
  97. } else {
  98. common.SysLog("system is not initialized and no root user exists")
  99. constant.Setup = false
  100. }
  101. } else {
  102. // Setup record exists, system is initialized
  103. common.SysLog("system is already initialized at: " + time.Unix(setup.InitializedAt, 0).String())
  104. constant.Setup = true
  105. }
  106. }
  107. func chooseDB(envName string, isLog bool) (*gorm.DB, error) {
  108. defer func() {
  109. initCol()
  110. }()
  111. dsn := os.Getenv(envName)
  112. if dsn != "" {
  113. if strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://") {
  114. // Use PostgreSQL
  115. common.SysLog("using PostgreSQL as database")
  116. if !isLog {
  117. common.UsingPostgreSQL = true
  118. } else {
  119. common.LogSqlType = common.DatabaseTypePostgreSQL
  120. }
  121. return gorm.Open(postgres.New(postgres.Config{
  122. DSN: dsn,
  123. PreferSimpleProtocol: true, // disables implicit prepared statement usage
  124. }), &gorm.Config{
  125. PrepareStmt: true, // precompile SQL
  126. })
  127. }
  128. if strings.HasPrefix(dsn, "local") {
  129. common.SysLog("SQL_DSN not set, using SQLite as database")
  130. if !isLog {
  131. common.UsingSQLite = true
  132. } else {
  133. common.LogSqlType = common.DatabaseTypeSQLite
  134. }
  135. return gorm.Open(sqlite.Open(common.SQLitePath), &gorm.Config{
  136. PrepareStmt: true, // precompile SQL
  137. })
  138. }
  139. // Use MySQL
  140. common.SysLog("using MySQL as database")
  141. // check parseTime
  142. if !strings.Contains(dsn, "parseTime") {
  143. if strings.Contains(dsn, "?") {
  144. dsn += "&parseTime=true"
  145. } else {
  146. dsn += "?parseTime=true"
  147. }
  148. }
  149. if !isLog {
  150. common.UsingMySQL = true
  151. } else {
  152. common.LogSqlType = common.DatabaseTypeMySQL
  153. }
  154. return gorm.Open(mysql.Open(dsn), &gorm.Config{
  155. PrepareStmt: true, // precompile SQL
  156. })
  157. }
  158. // Use SQLite
  159. common.SysLog("SQL_DSN not set, using SQLite as database")
  160. common.UsingSQLite = true
  161. return gorm.Open(sqlite.Open(common.SQLitePath), &gorm.Config{
  162. PrepareStmt: true, // precompile SQL
  163. })
  164. }
  165. func InitDB() (err error) {
  166. db, err := chooseDB("SQL_DSN", false)
  167. if err == nil {
  168. if common.DebugEnabled {
  169. db = db.Debug()
  170. }
  171. DB = db
  172. // MySQL charset/collation startup check: ensure Chinese-capable charset
  173. if common.UsingMySQL {
  174. if err := checkMySQLChineseSupport(DB); err != nil {
  175. panic(err)
  176. }
  177. }
  178. sqlDB, err := DB.DB()
  179. if err != nil {
  180. return err
  181. }
  182. sqlDB.SetMaxIdleConns(common.GetEnvOrDefault("SQL_MAX_IDLE_CONNS", 100))
  183. sqlDB.SetMaxOpenConns(common.GetEnvOrDefault("SQL_MAX_OPEN_CONNS", 1000))
  184. sqlDB.SetConnMaxLifetime(time.Second * time.Duration(common.GetEnvOrDefault("SQL_MAX_LIFETIME", 60)))
  185. if !common.IsMasterNode {
  186. return nil
  187. }
  188. if common.UsingMySQL {
  189. //_, _ = sqlDB.Exec("ALTER TABLE channels MODIFY model_mapping TEXT;") // TODO: delete this line when most users have upgraded
  190. }
  191. common.SysLog("database migration started")
  192. err = migrateDB()
  193. return err
  194. } else {
  195. common.FatalLog(err)
  196. }
  197. return err
  198. }
  199. func InitLogDB() (err error) {
  200. if os.Getenv("LOG_SQL_DSN") == "" {
  201. LOG_DB = DB
  202. return
  203. }
  204. db, err := chooseDB("LOG_SQL_DSN", true)
  205. if err == nil {
  206. if common.DebugEnabled {
  207. db = db.Debug()
  208. }
  209. LOG_DB = db
  210. // If log DB is MySQL, also ensure Chinese-capable charset
  211. if common.LogSqlType == common.DatabaseTypeMySQL {
  212. if err := checkMySQLChineseSupport(LOG_DB); err != nil {
  213. panic(err)
  214. }
  215. }
  216. sqlDB, err := LOG_DB.DB()
  217. if err != nil {
  218. return err
  219. }
  220. sqlDB.SetMaxIdleConns(common.GetEnvOrDefault("SQL_MAX_IDLE_CONNS", 100))
  221. sqlDB.SetMaxOpenConns(common.GetEnvOrDefault("SQL_MAX_OPEN_CONNS", 1000))
  222. sqlDB.SetConnMaxLifetime(time.Second * time.Duration(common.GetEnvOrDefault("SQL_MAX_LIFETIME", 60)))
  223. if !common.IsMasterNode {
  224. return nil
  225. }
  226. common.SysLog("database migration started")
  227. err = migrateLOGDB()
  228. return err
  229. } else {
  230. common.FatalLog(err)
  231. }
  232. return err
  233. }
  234. func migrateDB() error {
  235. // Migrate price_amount column from float/double to decimal for existing tables
  236. migrateSubscriptionPlanPriceAmount()
  237. // Migrate model_limits column from varchar to text for existing tables
  238. if err := migrateTokenModelLimitsToText(); err != nil {
  239. return err
  240. }
  241. err := DB.AutoMigrate(
  242. &Channel{},
  243. &Token{},
  244. &User{},
  245. &PasskeyCredential{},
  246. &Option{},
  247. &Redemption{},
  248. &Ability{},
  249. &Log{},
  250. &Midjourney{},
  251. &TopUp{},
  252. &QuotaData{},
  253. &Task{},
  254. &Model{},
  255. &Vendor{},
  256. &PrefillGroup{},
  257. &Setup{},
  258. &TwoFA{},
  259. &TwoFABackupCode{},
  260. &Checkin{},
  261. &SubscriptionOrder{},
  262. &UserSubscription{},
  263. &SubscriptionPreConsumeRecord{},
  264. &CustomOAuthProvider{},
  265. &UserOAuthBinding{},
  266. &PerfMetric{},
  267. )
  268. if err != nil {
  269. return err
  270. }
  271. if common.UsingSQLite {
  272. if err := ensureSubscriptionPlanTableSQLite(); err != nil {
  273. return err
  274. }
  275. } else {
  276. if err := DB.AutoMigrate(&SubscriptionPlan{}); err != nil {
  277. return err
  278. }
  279. }
  280. return nil
  281. }
  282. func migrateDBFast() error {
  283. var wg sync.WaitGroup
  284. migrations := []struct {
  285. model interface{}
  286. name string
  287. }{
  288. {&Channel{}, "Channel"},
  289. {&Token{}, "Token"},
  290. {&User{}, "User"},
  291. {&PasskeyCredential{}, "PasskeyCredential"},
  292. {&Option{}, "Option"},
  293. {&Redemption{}, "Redemption"},
  294. {&Ability{}, "Ability"},
  295. {&Log{}, "Log"},
  296. {&Midjourney{}, "Midjourney"},
  297. {&TopUp{}, "TopUp"},
  298. {&QuotaData{}, "QuotaData"},
  299. {&Task{}, "Task"},
  300. {&Model{}, "Model"},
  301. {&Vendor{}, "Vendor"},
  302. {&PrefillGroup{}, "PrefillGroup"},
  303. {&Setup{}, "Setup"},
  304. {&TwoFA{}, "TwoFA"},
  305. {&TwoFABackupCode{}, "TwoFABackupCode"},
  306. {&Checkin{}, "Checkin"},
  307. {&SubscriptionOrder{}, "SubscriptionOrder"},
  308. {&UserSubscription{}, "UserSubscription"},
  309. {&SubscriptionPreConsumeRecord{}, "SubscriptionPreConsumeRecord"},
  310. {&CustomOAuthProvider{}, "CustomOAuthProvider"},
  311. {&UserOAuthBinding{}, "UserOAuthBinding"},
  312. {&PerfMetric{}, "PerfMetric"},
  313. }
  314. // 动态计算migration数量,确保errChan缓冲区足够大
  315. errChan := make(chan error, len(migrations))
  316. for _, m := range migrations {
  317. wg.Add(1)
  318. go func(model interface{}, name string) {
  319. defer wg.Done()
  320. if err := DB.AutoMigrate(model); err != nil {
  321. errChan <- fmt.Errorf("failed to migrate %s: %v", name, err)
  322. }
  323. }(m.model, m.name)
  324. }
  325. // Wait for all migrations to complete
  326. wg.Wait()
  327. close(errChan)
  328. // Check for any errors
  329. for err := range errChan {
  330. if err != nil {
  331. return err
  332. }
  333. }
  334. if common.UsingSQLite {
  335. if err := ensureSubscriptionPlanTableSQLite(); err != nil {
  336. return err
  337. }
  338. } else {
  339. if err := DB.AutoMigrate(&SubscriptionPlan{}); err != nil {
  340. return err
  341. }
  342. }
  343. common.SysLog("database migrated")
  344. return nil
  345. }
  346. func migrateLOGDB() error {
  347. var err error
  348. if err = LOG_DB.AutoMigrate(&Log{}); err != nil {
  349. return err
  350. }
  351. return nil
  352. }
  353. type sqliteColumnDef struct {
  354. Name string
  355. DDL string
  356. }
  357. func ensureSubscriptionPlanTableSQLite() error {
  358. if !common.UsingSQLite {
  359. return nil
  360. }
  361. tableName := "subscription_plans"
  362. if !DB.Migrator().HasTable(tableName) {
  363. createSQL := `CREATE TABLE ` + "`" + tableName + "`" + ` (
  364. ` + "`id`" + ` integer,
  365. ` + "`title`" + ` varchar(128) NOT NULL,
  366. ` + "`subtitle`" + ` varchar(255) DEFAULT '',
  367. ` + "`price_amount`" + ` decimal(10,6) NOT NULL,
  368. ` + "`currency`" + ` varchar(8) NOT NULL DEFAULT 'USD',
  369. ` + "`duration_unit`" + ` varchar(16) NOT NULL DEFAULT 'month',
  370. ` + "`duration_value`" + ` integer NOT NULL DEFAULT 1,
  371. ` + "`custom_seconds`" + ` bigint NOT NULL DEFAULT 0,
  372. ` + "`enabled`" + ` numeric DEFAULT 1,
  373. ` + "`sort_order`" + ` integer DEFAULT 0,
  374. ` + "`stripe_price_id`" + ` varchar(128) DEFAULT '',
  375. ` + "`creem_product_id`" + ` varchar(128) DEFAULT '',
  376. ` + "`max_purchase_per_user`" + ` integer DEFAULT 0,
  377. ` + "`upgrade_group`" + ` varchar(64) DEFAULT '',
  378. ` + "`total_amount`" + ` bigint NOT NULL DEFAULT 0,
  379. ` + "`quota_reset_period`" + ` varchar(16) DEFAULT 'never',
  380. ` + "`quota_reset_custom_seconds`" + ` bigint DEFAULT 0,
  381. ` + "`created_at`" + ` bigint,
  382. ` + "`updated_at`" + ` bigint,
  383. PRIMARY KEY (` + "`id`" + `)
  384. )`
  385. return DB.Exec(createSQL).Error
  386. }
  387. var cols []struct {
  388. Name string `gorm:"column:name"`
  389. }
  390. if err := DB.Raw("PRAGMA table_info(`" + tableName + "`)").Scan(&cols).Error; err != nil {
  391. return err
  392. }
  393. existing := make(map[string]struct{}, len(cols))
  394. for _, c := range cols {
  395. existing[c.Name] = struct{}{}
  396. }
  397. required := []sqliteColumnDef{
  398. {Name: "title", DDL: "`title` varchar(128) NOT NULL"},
  399. {Name: "subtitle", DDL: "`subtitle` varchar(255) DEFAULT ''"},
  400. {Name: "price_amount", DDL: "`price_amount` decimal(10,6) NOT NULL"},
  401. {Name: "currency", DDL: "`currency` varchar(8) NOT NULL DEFAULT 'USD'"},
  402. {Name: "duration_unit", DDL: "`duration_unit` varchar(16) NOT NULL DEFAULT 'month'"},
  403. {Name: "duration_value", DDL: "`duration_value` integer NOT NULL DEFAULT 1"},
  404. {Name: "custom_seconds", DDL: "`custom_seconds` bigint NOT NULL DEFAULT 0"},
  405. {Name: "enabled", DDL: "`enabled` numeric DEFAULT 1"},
  406. {Name: "sort_order", DDL: "`sort_order` integer DEFAULT 0"},
  407. {Name: "stripe_price_id", DDL: "`stripe_price_id` varchar(128) DEFAULT ''"},
  408. {Name: "creem_product_id", DDL: "`creem_product_id` varchar(128) DEFAULT ''"},
  409. {Name: "max_purchase_per_user", DDL: "`max_purchase_per_user` integer DEFAULT 0"},
  410. {Name: "upgrade_group", DDL: "`upgrade_group` varchar(64) DEFAULT ''"},
  411. {Name: "total_amount", DDL: "`total_amount` bigint NOT NULL DEFAULT 0"},
  412. {Name: "quota_reset_period", DDL: "`quota_reset_period` varchar(16) DEFAULT 'never'"},
  413. {Name: "quota_reset_custom_seconds", DDL: "`quota_reset_custom_seconds` bigint DEFAULT 0"},
  414. {Name: "created_at", DDL: "`created_at` bigint"},
  415. {Name: "updated_at", DDL: "`updated_at` bigint"},
  416. }
  417. for _, col := range required {
  418. if _, ok := existing[col.Name]; ok {
  419. continue
  420. }
  421. if err := DB.Exec("ALTER TABLE `" + tableName + "` ADD COLUMN " + col.DDL).Error; err != nil {
  422. return err
  423. }
  424. }
  425. return nil
  426. }
  427. // migrateTokenModelLimitsToText migrates model_limits column from varchar(1024) to text
  428. // This is safe to run multiple times - it checks the column type first
  429. func migrateTokenModelLimitsToText() error {
  430. // SQLite uses type affinity, so TEXT and VARCHAR are effectively the same — no migration needed
  431. if common.UsingSQLite {
  432. return nil
  433. }
  434. tableName := "tokens"
  435. columnName := "model_limits"
  436. if !DB.Migrator().HasTable(tableName) {
  437. return nil
  438. }
  439. if !DB.Migrator().HasColumn(&Token{}, columnName) {
  440. return nil
  441. }
  442. var alterSQL string
  443. if common.UsingPostgreSQL {
  444. var dataType string
  445. if err := DB.Raw(`SELECT data_type FROM information_schema.columns
  446. WHERE table_schema = current_schema() AND table_name = ? AND column_name = ?`,
  447. tableName, columnName).Scan(&dataType).Error; err != nil {
  448. common.SysLog(fmt.Sprintf("Warning: failed to query metadata for %s.%s: %v", tableName, columnName, err))
  449. } else if dataType == "text" {
  450. return nil
  451. }
  452. alterSQL = fmt.Sprintf(`ALTER TABLE %s ALTER COLUMN %s TYPE text`, tableName, columnName)
  453. } else if common.UsingMySQL {
  454. var columnType string
  455. if err := DB.Raw(`SELECT COLUMN_TYPE FROM information_schema.columns
  456. WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?`,
  457. tableName, columnName).Scan(&columnType).Error; err != nil {
  458. common.SysLog(fmt.Sprintf("Warning: failed to query metadata for %s.%s: %v", tableName, columnName, err))
  459. } else if strings.ToLower(columnType) == "text" {
  460. return nil
  461. }
  462. alterSQL = fmt.Sprintf("ALTER TABLE %s MODIFY COLUMN %s text", tableName, columnName)
  463. } else {
  464. return nil
  465. }
  466. if alterSQL != "" {
  467. if err := DB.Exec(alterSQL).Error; err != nil {
  468. return fmt.Errorf("failed to migrate %s.%s to text: %w", tableName, columnName, err)
  469. }
  470. common.SysLog(fmt.Sprintf("Successfully migrated %s.%s to text", tableName, columnName))
  471. }
  472. return nil
  473. }
  474. // migrateSubscriptionPlanPriceAmount migrates price_amount column from float/double to decimal(10,6)
  475. // This is safe to run multiple times - it checks the column type first
  476. func migrateSubscriptionPlanPriceAmount() {
  477. // SQLite doesn't support ALTER COLUMN, and its type affinity handles this automatically
  478. // Skip early to avoid GORM parsing the existing table DDL which may cause issues
  479. if common.UsingSQLite {
  480. return
  481. }
  482. tableName := "subscription_plans"
  483. columnName := "price_amount"
  484. // Check if table exists first
  485. if !DB.Migrator().HasTable(tableName) {
  486. return
  487. }
  488. // Check if column exists
  489. if !DB.Migrator().HasColumn(&SubscriptionPlan{}, columnName) {
  490. return
  491. }
  492. var alterSQL string
  493. if common.UsingPostgreSQL {
  494. // PostgreSQL: Check if already decimal/numeric
  495. var dataType string
  496. if err := DB.Raw(`SELECT data_type FROM information_schema.columns
  497. WHERE table_schema = current_schema() AND table_name = ? AND column_name = ?`,
  498. tableName, columnName).Scan(&dataType).Error; err != nil {
  499. common.SysLog(fmt.Sprintf("Warning: failed to query metadata for %s.%s: %v", tableName, columnName, err))
  500. } else if dataType == "numeric" {
  501. return // Already decimal/numeric
  502. }
  503. alterSQL = fmt.Sprintf(`ALTER TABLE %s ALTER COLUMN %s TYPE decimal(10,6) USING %s::decimal(10,6)`,
  504. tableName, columnName, columnName)
  505. } else if common.UsingMySQL {
  506. // MySQL: Check if already decimal
  507. var columnType string
  508. if err := DB.Raw(`SELECT COLUMN_TYPE FROM information_schema.columns
  509. WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?`,
  510. tableName, columnName).Scan(&columnType).Error; err != nil {
  511. common.SysLog(fmt.Sprintf("Warning: failed to query metadata for %s.%s: %v", tableName, columnName, err))
  512. } else if strings.HasPrefix(strings.ToLower(columnType), "decimal") {
  513. return // Already decimal
  514. }
  515. alterSQL = fmt.Sprintf("ALTER TABLE %s MODIFY COLUMN %s decimal(10,6) NOT NULL DEFAULT 0",
  516. tableName, columnName)
  517. } else {
  518. return
  519. }
  520. if alterSQL != "" {
  521. if err := DB.Exec(alterSQL).Error; err != nil {
  522. common.SysLog(fmt.Sprintf("Warning: failed to migrate %s.%s to decimal: %v", tableName, columnName, err))
  523. } else {
  524. common.SysLog(fmt.Sprintf("Successfully migrated %s.%s to decimal(10,6)", tableName, columnName))
  525. }
  526. }
  527. }
  528. func closeDB(db *gorm.DB) error {
  529. sqlDB, err := db.DB()
  530. if err != nil {
  531. return err
  532. }
  533. err = sqlDB.Close()
  534. return err
  535. }
  536. func CloseDB() error {
  537. if LOG_DB != DB {
  538. err := closeDB(LOG_DB)
  539. if err != nil {
  540. return err
  541. }
  542. }
  543. return closeDB(DB)
  544. }
  545. // checkMySQLChineseSupport ensures the MySQL connection and current schema
  546. // default charset/collation can store Chinese characters. It allows common
  547. // Chinese-capable charsets (utf8mb4, utf8, gbk, big5, gb18030) and panics otherwise.
  548. func checkMySQLChineseSupport(db *gorm.DB) error {
  549. // 仅检测:当前库默认字符集/排序规则 + 各表的排序规则(隐含字符集)
  550. // Read current schema defaults
  551. var schemaCharset, schemaCollation string
  552. err := db.Raw("SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = DATABASE()").Row().Scan(&schemaCharset, &schemaCollation)
  553. if err != nil {
  554. return fmt.Errorf("读取当前库默认字符集/排序规则失败 / Failed to read schema default charset/collation: %v", err)
  555. }
  556. toLower := func(s string) string { return strings.ToLower(s) }
  557. // Allowed charsets that can store Chinese text
  558. allowedCharsets := map[string]string{
  559. "utf8mb4": "utf8mb4_",
  560. "utf8": "utf8_",
  561. "gbk": "gbk_",
  562. "big5": "big5_",
  563. "gb18030": "gb18030_",
  564. }
  565. isChineseCapable := func(cs, cl string) bool {
  566. csLower := toLower(cs)
  567. clLower := toLower(cl)
  568. if prefix, ok := allowedCharsets[csLower]; ok {
  569. if clLower == "" {
  570. return true
  571. }
  572. return strings.HasPrefix(clLower, prefix)
  573. }
  574. // 如果仅提供了排序规则,尝试按排序规则前缀判断
  575. for _, prefix := range allowedCharsets {
  576. if strings.HasPrefix(clLower, prefix) {
  577. return true
  578. }
  579. }
  580. return false
  581. }
  582. // 1) 当前库默认值必须支持中文
  583. if !isChineseCapable(schemaCharset, schemaCollation) {
  584. return fmt.Errorf("当前库默认字符集/排序规则不支持中文:schema(%s/%s)。请将库设置为 utf8mb4/utf8/gbk/big5/gb18030 / Schema default charset/collation is not Chinese-capable: schema(%s/%s). Please set to utf8mb4/utf8/gbk/big5/gb18030",
  585. schemaCharset, schemaCollation, schemaCharset, schemaCollation)
  586. }
  587. // 2) 所有物理表的排序规则(隐含字符集)必须支持中文
  588. type tableInfo struct {
  589. Name string
  590. Collation *string
  591. }
  592. var tables []tableInfo
  593. if err := db.Raw("SELECT TABLE_NAME, TABLE_COLLATION FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_TYPE = 'BASE TABLE'").Scan(&tables).Error; err != nil {
  594. return fmt.Errorf("读取表排序规则失败 / Failed to read table collations: %v", err)
  595. }
  596. var badTables []string
  597. for _, t := range tables {
  598. // NULL 或空表示继承库默认设置,已在上面校验库默认,视为通过
  599. if t.Collation == nil || *t.Collation == "" {
  600. continue
  601. }
  602. cl := *t.Collation
  603. // 仅凭排序规则判断是否中文可用
  604. ok := false
  605. lower := strings.ToLower(cl)
  606. for _, prefix := range allowedCharsets {
  607. if strings.HasPrefix(lower, prefix) {
  608. ok = true
  609. break
  610. }
  611. }
  612. if !ok {
  613. badTables = append(badTables, fmt.Sprintf("%s(%s)", t.Name, cl))
  614. }
  615. }
  616. if len(badTables) > 0 {
  617. // 限制输出数量以避免日志过长
  618. maxShow := 20
  619. shown := badTables
  620. if len(shown) > maxShow {
  621. shown = shown[:maxShow]
  622. }
  623. return fmt.Errorf(
  624. "存在不支持中文的表,请修复其排序规则/字符集。示例(最多展示 %d 项):%v / Found tables not Chinese-capable. Please fix their collation/charset. Examples (showing up to %d): %v",
  625. maxShow, shown, maxShow, shown,
  626. )
  627. }
  628. return nil
  629. }
  630. var (
  631. lastPingTime time.Time
  632. pingMutex sync.Mutex
  633. )
  634. func PingDB() error {
  635. pingMutex.Lock()
  636. defer pingMutex.Unlock()
  637. if time.Since(lastPingTime) < time.Second*10 {
  638. return nil
  639. }
  640. sqlDB, err := DB.DB()
  641. if err != nil {
  642. log.Printf("Error getting sql.DB from GORM: %v", err)
  643. return err
  644. }
  645. err = sqlDB.Ping()
  646. if err != nil {
  647. log.Printf("Error pinging DB: %v", err)
  648. return err
  649. }
  650. lastPingTime = time.Now()
  651. common.SysLog("Database pinged successfully")
  652. return nil
  653. }