25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

686 satır
19 KiB

  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. // Drop bound_channel_id column from tokens table (deprecated field)
  238. migrateTokenDropBoundChannelId()
  239. err := DB.AutoMigrate(
  240. &Channel{},
  241. &Token{},
  242. &User{},
  243. &PasskeyCredential{},
  244. &Option{},
  245. &Redemption{},
  246. &Ability{},
  247. &Log{},
  248. &Midjourney{},
  249. &TopUp{},
  250. &QuotaData{},
  251. &Task{},
  252. &Model{},
  253. &Vendor{},
  254. &PrefillGroup{},
  255. &Setup{},
  256. &TwoFA{},
  257. &TwoFABackupCode{},
  258. &Checkin{},
  259. &SubscriptionOrder{},
  260. &UserSubscription{},
  261. &SubscriptionPreConsumeRecord{},
  262. &CustomOAuthProvider{},
  263. &UserOAuthBinding{},
  264. &ChannelPricing{},
  265. &PricingTag{},
  266. &PendingSyncRecord{},
  267. &QuotaSyncLog{},
  268. )
  269. if err != nil {
  270. return err
  271. }
  272. if common.UsingSQLite {
  273. if err := ensureSubscriptionPlanTableSQLite(); err != nil {
  274. return err
  275. }
  276. } else {
  277. if err := DB.AutoMigrate(&SubscriptionPlan{}); err != nil {
  278. return err
  279. }
  280. }
  281. return nil
  282. }
  283. func migrateDBFast() error {
  284. // Drop bound_channel_id column from tokens table (deprecated field)
  285. migrateTokenDropBoundChannelId()
  286. var wg sync.WaitGroup
  287. migrations := []struct {
  288. model interface{}
  289. name string
  290. }{
  291. {&Channel{}, "Channel"},
  292. {&Token{}, "Token"},
  293. {&User{}, "User"},
  294. {&PasskeyCredential{}, "PasskeyCredential"},
  295. {&Option{}, "Option"},
  296. {&Redemption{}, "Redemption"},
  297. {&Ability{}, "Ability"},
  298. {&Log{}, "Log"},
  299. {&Midjourney{}, "Midjourney"},
  300. {&TopUp{}, "TopUp"},
  301. {&QuotaData{}, "QuotaData"},
  302. {&Task{}, "Task"},
  303. {&Model{}, "Model"},
  304. {&Vendor{}, "Vendor"},
  305. {&PrefillGroup{}, "PrefillGroup"},
  306. {&Setup{}, "Setup"},
  307. {&TwoFA{}, "TwoFA"},
  308. {&TwoFABackupCode{}, "TwoFABackupCode"},
  309. {&Checkin{}, "Checkin"},
  310. {&SubscriptionOrder{}, "SubscriptionOrder"},
  311. {&UserSubscription{}, "UserSubscription"},
  312. {&SubscriptionPreConsumeRecord{}, "SubscriptionPreConsumeRecord"},
  313. {&CustomOAuthProvider{}, "CustomOAuthProvider"},
  314. {&UserOAuthBinding{}, "UserOAuthBinding"},
  315. {&ChannelPricing{}, "ChannelPricing"},
  316. {&PricingTag{}, "PricingTag"},
  317. {&PendingSyncRecord{}, "PendingSyncRecord"},
  318. {&QuotaSyncLog{}, "QuotaSyncLog"},
  319. }
  320. // 动态计算migration数量,确保errChan缓冲区足够大
  321. errChan := make(chan error, len(migrations))
  322. for _, m := range migrations {
  323. wg.Add(1)
  324. go func(model interface{}, name string) {
  325. defer wg.Done()
  326. if err := DB.AutoMigrate(model); err != nil {
  327. errChan <- fmt.Errorf("failed to migrate %s: %v", name, err)
  328. }
  329. }(m.model, m.name)
  330. }
  331. // Wait for all migrations to complete
  332. wg.Wait()
  333. close(errChan)
  334. // Check for any errors
  335. for err := range errChan {
  336. if err != nil {
  337. return err
  338. }
  339. }
  340. if common.UsingSQLite {
  341. if err := ensureSubscriptionPlanTableSQLite(); err != nil {
  342. return err
  343. }
  344. } else {
  345. if err := DB.AutoMigrate(&SubscriptionPlan{}); err != nil {
  346. return err
  347. }
  348. }
  349. common.SysLog("database migrated")
  350. return nil
  351. }
  352. func migrateLOGDB() error {
  353. var err error
  354. if err = LOG_DB.AutoMigrate(&Log{}); err != nil {
  355. return err
  356. }
  357. return nil
  358. }
  359. type sqliteColumnDef struct {
  360. Name string
  361. DDL string
  362. }
  363. func ensureSubscriptionPlanTableSQLite() error {
  364. if !common.UsingSQLite {
  365. return nil
  366. }
  367. tableName := "subscription_plans"
  368. if !DB.Migrator().HasTable(tableName) {
  369. createSQL := `CREATE TABLE ` + "`" + tableName + "`" + ` (
  370. ` + "`id`" + ` integer,
  371. ` + "`title`" + ` varchar(128) NOT NULL,
  372. ` + "`subtitle`" + ` varchar(255) DEFAULT '',
  373. ` + "`price_amount`" + ` decimal(10,6) NOT NULL,
  374. ` + "`currency`" + ` varchar(8) NOT NULL DEFAULT 'USD',
  375. ` + "`duration_unit`" + ` varchar(16) NOT NULL DEFAULT 'month',
  376. ` + "`duration_value`" + ` integer NOT NULL DEFAULT 1,
  377. ` + "`custom_seconds`" + ` bigint NOT NULL DEFAULT 0,
  378. ` + "`enabled`" + ` numeric DEFAULT 1,
  379. ` + "`sort_order`" + ` integer DEFAULT 0,
  380. ` + "`stripe_price_id`" + ` varchar(128) DEFAULT '',
  381. ` + "`creem_product_id`" + ` varchar(128) DEFAULT '',
  382. ` + "`max_purchase_per_user`" + ` integer DEFAULT 0,
  383. ` + "`upgrade_group`" + ` varchar(64) DEFAULT '',
  384. ` + "`total_amount`" + ` bigint NOT NULL DEFAULT 0,
  385. ` + "`quota_reset_period`" + ` varchar(16) DEFAULT 'never',
  386. ` + "`quota_reset_custom_seconds`" + ` bigint DEFAULT 0,
  387. ` + "`created_at`" + ` bigint,
  388. ` + "`updated_at`" + ` bigint,
  389. PRIMARY KEY (` + "`id`" + `)
  390. )`
  391. return DB.Exec(createSQL).Error
  392. }
  393. var cols []struct {
  394. Name string `gorm:"column:name"`
  395. }
  396. if err := DB.Raw("PRAGMA table_info(`" + tableName + "`)").Scan(&cols).Error; err != nil {
  397. return err
  398. }
  399. existing := make(map[string]struct{}, len(cols))
  400. for _, c := range cols {
  401. existing[c.Name] = struct{}{}
  402. }
  403. required := []sqliteColumnDef{
  404. {Name: "title", DDL: "`title` varchar(128) NOT NULL"},
  405. {Name: "subtitle", DDL: "`subtitle` varchar(255) DEFAULT ''"},
  406. {Name: "price_amount", DDL: "`price_amount` decimal(10,6) NOT NULL"},
  407. {Name: "currency", DDL: "`currency` varchar(8) NOT NULL DEFAULT 'USD'"},
  408. {Name: "duration_unit", DDL: "`duration_unit` varchar(16) NOT NULL DEFAULT 'month'"},
  409. {Name: "duration_value", DDL: "`duration_value` integer NOT NULL DEFAULT 1"},
  410. {Name: "custom_seconds", DDL: "`custom_seconds` bigint NOT NULL DEFAULT 0"},
  411. {Name: "enabled", DDL: "`enabled` numeric DEFAULT 1"},
  412. {Name: "sort_order", DDL: "`sort_order` integer DEFAULT 0"},
  413. {Name: "stripe_price_id", DDL: "`stripe_price_id` varchar(128) DEFAULT ''"},
  414. {Name: "creem_product_id", DDL: "`creem_product_id` varchar(128) DEFAULT ''"},
  415. {Name: "max_purchase_per_user", DDL: "`max_purchase_per_user` integer DEFAULT 0"},
  416. {Name: "upgrade_group", DDL: "`upgrade_group` varchar(64) DEFAULT ''"},
  417. {Name: "total_amount", DDL: "`total_amount` bigint NOT NULL DEFAULT 0"},
  418. {Name: "quota_reset_period", DDL: "`quota_reset_period` varchar(16) DEFAULT 'never'"},
  419. {Name: "quota_reset_custom_seconds", DDL: "`quota_reset_custom_seconds` bigint DEFAULT 0"},
  420. {Name: "created_at", DDL: "`created_at` bigint"},
  421. {Name: "updated_at", DDL: "`updated_at` bigint"},
  422. }
  423. for _, col := range required {
  424. if _, ok := existing[col.Name]; ok {
  425. continue
  426. }
  427. if err := DB.Exec("ALTER TABLE `" + tableName + "` ADD COLUMN " + col.DDL).Error; err != nil {
  428. return err
  429. }
  430. }
  431. return nil
  432. }
  433. // migrateSubscriptionPlanPriceAmount migrates price_amount column from float/double to decimal(10,6)
  434. // This is safe to run multiple times - it checks the column type first
  435. func migrateSubscriptionPlanPriceAmount() {
  436. // SQLite doesn't support ALTER COLUMN, and its type affinity handles this automatically
  437. // Skip early to avoid GORM parsing the existing table DDL which may cause issues
  438. if common.UsingSQLite {
  439. return
  440. }
  441. tableName := "subscription_plans"
  442. columnName := "price_amount"
  443. // Check if table exists first
  444. if !DB.Migrator().HasTable(tableName) {
  445. return
  446. }
  447. // Check if column exists
  448. if !DB.Migrator().HasColumn(&SubscriptionPlan{}, columnName) {
  449. return
  450. }
  451. var alterSQL string
  452. if common.UsingPostgreSQL {
  453. // PostgreSQL: Check if already decimal/numeric
  454. var dataType string
  455. DB.Raw(`SELECT data_type FROM information_schema.columns
  456. WHERE table_name = ? AND column_name = ?`, tableName, columnName).Scan(&dataType)
  457. if dataType == "numeric" {
  458. return // Already decimal/numeric
  459. }
  460. alterSQL = fmt.Sprintf(`ALTER TABLE %s ALTER COLUMN %s TYPE decimal(10,6) USING %s::decimal(10,6)`,
  461. tableName, columnName, columnName)
  462. } else if common.UsingMySQL {
  463. // MySQL: Check if already decimal
  464. var columnType string
  465. DB.Raw(`SELECT COLUMN_TYPE FROM information_schema.columns
  466. WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?`,
  467. tableName, columnName).Scan(&columnType)
  468. if strings.HasPrefix(strings.ToLower(columnType), "decimal") {
  469. return // Already decimal
  470. }
  471. alterSQL = fmt.Sprintf("ALTER TABLE %s MODIFY COLUMN %s decimal(10,6) NOT NULL DEFAULT 0",
  472. tableName, columnName)
  473. } else {
  474. return
  475. }
  476. if alterSQL != "" {
  477. if err := DB.Exec(alterSQL).Error; err != nil {
  478. common.SysLog(fmt.Sprintf("Warning: failed to migrate %s.%s to decimal: %v", tableName, columnName, err))
  479. } else {
  480. common.SysLog(fmt.Sprintf("Successfully migrated %s.%s to decimal(10,6)", tableName, columnName))
  481. }
  482. }
  483. }
  484. // migrateTokenDropBoundChannelId 删除 tokens 表中的 bound_channel_id 列(已废弃的字段)
  485. func migrateTokenDropBoundChannelId() {
  486. // SQLite 不支持 DROP COLUMN,跳过迁移
  487. if common.UsingSQLite {
  488. return
  489. }
  490. tableName := "tokens"
  491. columnName := "bound_channel_id"
  492. // 检查表是否存在
  493. if !DB.Migrator().HasTable(tableName) {
  494. return
  495. }
  496. // 检查列是否存在
  497. if !DB.Migrator().HasColumn(&Token{}, columnName) {
  498. return
  499. }
  500. // MySQL 和 PostgreSQL 都支持此语法
  501. dropSQL := fmt.Sprintf("ALTER TABLE %s DROP COLUMN %s", tableName, columnName)
  502. if err := DB.Exec(dropSQL).Error; err != nil {
  503. common.SysLog(fmt.Sprintf("Warning: failed to drop %s.%s: %v", tableName, columnName, err))
  504. } else {
  505. common.SysLog(fmt.Sprintf("Successfully dropped deprecated column %s.%s", tableName, columnName))
  506. }
  507. }
  508. func closeDB(db *gorm.DB) error {
  509. sqlDB, err := db.DB()
  510. if err != nil {
  511. return err
  512. }
  513. err = sqlDB.Close()
  514. return err
  515. }
  516. func CloseDB() error {
  517. if LOG_DB != DB {
  518. err := closeDB(LOG_DB)
  519. if err != nil {
  520. return err
  521. }
  522. }
  523. return closeDB(DB)
  524. }
  525. // checkMySQLChineseSupport ensures the MySQL connection and current schema
  526. // default charset/collation can store Chinese characters. It allows common
  527. // Chinese-capable charsets (utf8mb4, utf8, gbk, big5, gb18030) and panics otherwise.
  528. func checkMySQLChineseSupport(db *gorm.DB) error {
  529. // 仅检测:当前库默认字符集/排序规则 + 各表的排序规则(隐含字符集)
  530. // Read current schema defaults
  531. var schemaCharset, schemaCollation string
  532. err := db.Raw("SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = DATABASE()").Row().Scan(&schemaCharset, &schemaCollation)
  533. if err != nil {
  534. return fmt.Errorf("读取当前库默认字符集/排序规则失败 / Failed to read schema default charset/collation: %v", err)
  535. }
  536. toLower := func(s string) string { return strings.ToLower(s) }
  537. // Allowed charsets that can store Chinese text
  538. allowedCharsets := map[string]string{
  539. "utf8mb4": "utf8mb4_",
  540. "utf8": "utf8_",
  541. "gbk": "gbk_",
  542. "big5": "big5_",
  543. "gb18030": "gb18030_",
  544. }
  545. isChineseCapable := func(cs, cl string) bool {
  546. csLower := toLower(cs)
  547. clLower := toLower(cl)
  548. if prefix, ok := allowedCharsets[csLower]; ok {
  549. if clLower == "" {
  550. return true
  551. }
  552. return strings.HasPrefix(clLower, prefix)
  553. }
  554. // 如果仅提供了排序规则,尝试按排序规则前缀判断
  555. for _, prefix := range allowedCharsets {
  556. if strings.HasPrefix(clLower, prefix) {
  557. return true
  558. }
  559. }
  560. return false
  561. }
  562. // 1) 当前库默认值必须支持中文
  563. if !isChineseCapable(schemaCharset, schemaCollation) {
  564. 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",
  565. schemaCharset, schemaCollation, schemaCharset, schemaCollation)
  566. }
  567. // 2) 所有物理表的排序规则(隐含字符集)必须支持中文
  568. type tableInfo struct {
  569. Name string
  570. Collation *string
  571. }
  572. var tables []tableInfo
  573. 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 {
  574. return fmt.Errorf("读取表排序规则失败 / Failed to read table collations: %v", err)
  575. }
  576. var badTables []string
  577. for _, t := range tables {
  578. // NULL 或空表示继承库默认设置,已在上面校验库默认,视为通过
  579. if t.Collation == nil || *t.Collation == "" {
  580. continue
  581. }
  582. cl := *t.Collation
  583. // 仅凭排序规则判断是否中文可用
  584. ok := false
  585. lower := strings.ToLower(cl)
  586. for _, prefix := range allowedCharsets {
  587. if strings.HasPrefix(lower, prefix) {
  588. ok = true
  589. break
  590. }
  591. }
  592. if !ok {
  593. badTables = append(badTables, fmt.Sprintf("%s(%s)", t.Name, cl))
  594. }
  595. }
  596. if len(badTables) > 0 {
  597. // 限制输出数量以避免日志过长
  598. maxShow := 20
  599. shown := badTables
  600. if len(shown) > maxShow {
  601. shown = shown[:maxShow]
  602. }
  603. return fmt.Errorf(
  604. "存在不支持中文的表,请修复其排序规则/字符集。示例(最多展示 %d 项):%v / Found tables not Chinese-capable. Please fix their collation/charset. Examples (showing up to %d): %v",
  605. maxShow, shown, maxShow, shown,
  606. )
  607. }
  608. return nil
  609. }
  610. var (
  611. lastPingTime time.Time
  612. pingMutex sync.Mutex
  613. )
  614. func PingDB() error {
  615. pingMutex.Lock()
  616. defer pingMutex.Unlock()
  617. if time.Since(lastPingTime) < time.Second*10 {
  618. return nil
  619. }
  620. sqlDB, err := DB.DB()
  621. if err != nil {
  622. log.Printf("Error getting sql.DB from GORM: %v", err)
  623. return err
  624. }
  625. err = sqlDB.Ping()
  626. if err != nil {
  627. log.Printf("Error pinging DB: %v", err)
  628. return err
  629. }
  630. lastPingTime = time.Now()
  631. common.SysLog("Database pinged successfully")
  632. return nil
  633. }