Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

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