db.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. package service
  2. import (
  3. "crawler/config"
  4. "strings"
  5. "time"
  6. "database/sql"
  7. "fmt"
  8. "gorm.io/driver/mysql"
  9. "gorm.io/gorm"
  10. )
  11. var (
  12. DB_MOVIEW DB
  13. DB_CRAWLER DB
  14. DB_PLAYR DB
  15. )
  16. type DB struct {
  17. SQLDB *sql.DB
  18. GORMDB *gorm.DB
  19. DSN string
  20. Err error
  21. }
  22. func SetConfig() config.DBAccount {
  23. var (
  24. env = config.Env
  25. db = config.DB
  26. account = config.DBAccount{}
  27. )
  28. // DB 환경설정
  29. switch env.DeveloperEnv {
  30. case config.LOCAL:
  31. account = db.Local
  32. case config.DEV:
  33. account = db.Dev
  34. default:
  35. fmt.Println("DB 설정이 잘못되었습니다.")
  36. }
  37. //fmt.Printf("\n%#v\n", account)
  38. return account
  39. }
  40. // DB 연결
  41. func SetDatabase(dbName string) DB {
  42. var (
  43. env = config.Env
  44. db = config.DB
  45. account = SetConfig()
  46. err error
  47. )
  48. if dbName != "" {
  49. account.Name = dbName
  50. }
  51. /*
  52. * sqlDB
  53. */
  54. dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s", account.User, account.Password, account.Address, account.Name)
  55. fmt.Printf("\nEnv : %s\n", env.DeveloperEnv)
  56. fmt.Printf("%s\n", dsn)
  57. SQLConnd, err := sql.Open(account.Driver, dsn)
  58. if err != nil || SQLConnd.Ping() != nil {
  59. fmt.Printf("%s\n", account.Driver)
  60. fmt.Printf("%s\n", dsn)
  61. fmt.Printf("%v\n", SQLConnd)
  62. fmt.Printf("sqlDB에 연결에 실패하였습니다.\n %v", err.Error())
  63. fmt.Println(err)
  64. SQLConnd.Close()
  65. }
  66. SQLConnd.SetConnMaxLifetime(time.Duration(db.MaxLifetime))
  67. SQLConnd.SetConnMaxIdleTime(time.Duration(db.MaxIdleTime))
  68. SQLConnd.SetMaxIdleConns(db.MaxIdleConn)
  69. SQLConnd.SetMaxOpenConns(db.MaxOpenConn)
  70. /*
  71. * GormDB
  72. */
  73. GORMConnd, err := gorm.Open(mysql.New(mysql.Config{
  74. Conn: SQLConnd,
  75. }), &gorm.Config{})
  76. if err != nil {
  77. fmt.Printf("GormDB에 연결에 실패하였습니다.\n %v", err.Error())
  78. fmt.Println(err)
  79. }
  80. new := new(DB)
  81. new.SQLDB = SQLConnd
  82. new.GORMDB = GORMConnd
  83. new.DSN = dsn
  84. new.Err = err
  85. fmt.Println("Database was opened successfully !!")
  86. return *new
  87. }
  88. // DB 연결
  89. func (db *DB) Connection(dbName string) DB {
  90. return SetDatabase(dbName)
  91. }
  92. // gorm 커넥션 연결
  93. func (db *DB) GConnection(dbName string) DB {
  94. return SetDatabase(dbName)
  95. }
  96. // DB 오류 입력
  97. func (db *DB) SetErrorLog(err error, query string) {
  98. var (
  99. conn = DB_CRAWLER.SQLDB
  100. sql = `CALL SP_ERROR_LOG(?, ?, ?);`
  101. errorMessage = strings.TrimSpace(strings.Split(err.Error(), ":")[1])
  102. errorNo = strings.TrimSpace(strings.Replace(strings.Split(err.Error(), ":")[0], "Error ", "", 1))
  103. )
  104. conn.Exec(sql, errorNo, errorMessage, query)
  105. switch errorMessage {
  106. case "sql: no rows in result set":
  107. case "":
  108. default:
  109. fmt.Printf("DB error msg : %s\n", err.Error())
  110. }
  111. fmt.Printf("Exe error query : %s\n", query)
  112. }
  113. // DB SQL 입력
  114. func (db *DB) SetGeneralLog(action int, query, comment string) {
  115. var (
  116. conn = DB_CRAWLER.SQLDB
  117. sql = `
  118. INSERT INTO tb_general_log
  119. SET
  120. action = ?,
  121. query = ?,
  122. comment = ?,
  123. created_at = NOW();
  124. `
  125. )
  126. _, err := conn.Exec(sql, action, query, comment)
  127. if err != nil {
  128. db.SetErrorLog(err, sql)
  129. }
  130. }
  131. // DB 연결 종료
  132. func (db *DB) Close() {
  133. defer func() {
  134. if err := recover(); err != nil {
  135. fmt.Printf("Database recovered message: %s\n", err)
  136. }
  137. }()
  138. if DB_MOVIEW != (DB{}) {
  139. defer DB_MOVIEW.SQLDB.Close()
  140. DB_MOVIEW.SQLDB = nil
  141. DB_MOVIEW.GORMDB = nil
  142. DB_MOVIEW.DSN = ""
  143. DB_MOVIEW.Err = nil
  144. }
  145. if DB_CRAWLER != (DB{}) {
  146. defer DB_CRAWLER.SQLDB.Close()
  147. DB_CRAWLER.SQLDB = nil
  148. DB_CRAWLER.GORMDB = nil
  149. DB_CRAWLER.DSN = ""
  150. DB_CRAWLER.Err = nil
  151. }
  152. if DB_PLAYR != (DB{}) {
  153. defer DB_PLAYR.SQLDB.Close()
  154. DB_PLAYR.SQLDB = nil
  155. DB_PLAYR.GORMDB = nil
  156. DB_PLAYR.DSN = ""
  157. DB_PLAYR.Err = nil
  158. }
  159. fmt.Println("DB closed")
  160. }