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.
 
 
 

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