You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

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