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

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