gorm.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. package db
  2. import (
  3. "database/sql"
  4. "errors"
  5. "fmt"
  6. "genBrief/common/log"
  7. "os"
  8. "strings"
  9. "github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/dialers/mysql"
  10. )
  11. type DB struct {
  12. Db *sql.DB
  13. }
  14. var p1 *DB
  15. func Init() {
  16. connectionName := os.Getenv("CLOUDSQL_CONNECTION_NAME")
  17. if connectionName != "" {
  18. db, err := initProxyPool()
  19. if err != nil {
  20. log.Infof("init_sql_proxy %s", err.Error())
  21. panic("init db error" + err.Error())
  22. }
  23. p1 = &DB{Db: db}
  24. } else {
  25. db, err := initTCPConnectionPool()
  26. if err != nil {
  27. log.Infof("init_sql %s", err.Error())
  28. panic("init db error" + err.Error())
  29. }
  30. p1 = &DB{Db: db}
  31. }
  32. }
  33. func initTCPConnectionPool() (*sql.DB, error) {
  34. var (
  35. dbTcpHost = os.Getenv("DB_HOST") // e.g. '127.0.0.1' ('172.17.0.1' if deployed to GAE Flex)
  36. dbPort = os.Getenv("DB_PORT") // e.g. '3306'
  37. dbName = os.Getenv("DB_NAME") // e.g. 'my-database'
  38. dbUser = os.Getenv("DB_USER") // e.g. 'my-db-user'
  39. dbPwd = os.Getenv("DB_PASS") // e.g. 'my-db-password'
  40. )
  41. log.Infof("dbTcpHost:%v\n dbPort:%v\n dbName:%v\n dbuser:%v\n dbpwd:%v\n",
  42. dbTcpHost, dbPort, dbName, dbUser, dbPwd)
  43. //var dbURI string
  44. dbURI := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true", dbUser, dbPwd, dbTcpHost, dbPort, dbName)
  45. dbPool, err := sql.Open("mysql", dbURI)
  46. if err != nil {
  47. return nil, fmt.Errorf("sql.Open: %v", err)
  48. }
  49. configureConnectionPool(dbPool)
  50. if err := dbPool.Ping(); err != nil {
  51. log.Warn("dbPing err:", err)
  52. } else {
  53. log.Warn("dbPing succ")
  54. }
  55. return dbPool, nil
  56. }
  57. func initProxyPool() (*sql.DB, error) {
  58. var (
  59. instanceConnectionName = os.Getenv("CLOUDSQL_CONNECTION_NAME")
  60. dbName = os.Getenv("DB_NAME")
  61. dbUser = os.Getenv("DB_USER")
  62. dbPwd = os.Getenv("DB_PASS")
  63. )
  64. log.Infof("connectionName:%v\n dbName:%v\n dbuser:%v\n dbpwd:%v\n",
  65. instanceConnectionName, dbName, dbUser, dbPwd)
  66. cfg := mysql.Cfg(instanceConnectionName, dbUser, dbPwd)
  67. cfg.DBName = dbName
  68. cfg.ParseTime = true
  69. dbPool, err := mysql.DialCfg(cfg)
  70. if err != nil {
  71. log.Warn(err)
  72. panic(err.Error())
  73. }
  74. configureConnectionPool(dbPool)
  75. if err := dbPool.Ping(); err != nil {
  76. log.Warn("dbPing err:", err)
  77. } else {
  78. log.Warn("dbPing succ")
  79. }
  80. return dbPool, nil
  81. }
  82. func configureConnectionPool(dbPool *sql.DB) {
  83. dbPool.SetMaxIdleConns(50)
  84. dbPool.SetMaxOpenConns(50)
  85. dbPool.SetConnMaxLifetime(1800)
  86. }
  87. func P1() *sql.DB {
  88. return p1.Db
  89. }
  90. func Pool() *DB {
  91. return p1
  92. }
  93. func NewPool(pstr string) *DB {
  94. mdb := &DB{}
  95. mdb.init(pstr)
  96. return mdb
  97. }
  98. func (p *DB) init(pstr string) {
  99. p1, err := sql.Open("mysql", pstr)
  100. if err != nil {
  101. panic("open mysql error " + err.Error())
  102. }
  103. p.Db = p1
  104. p1.SetMaxOpenConns(200)
  105. p1.SetMaxIdleConns(100)
  106. p1.Ping()
  107. }
  108. func (p *DB) Insert(tab string, data map[string]interface{}) (int, error) {
  109. var sqllist []string
  110. var seqs []string
  111. var values []interface{}
  112. for key, value := range data {
  113. sqllist = append(sqllist, key)
  114. seqs = append(seqs, "?")
  115. values = append(values, value)
  116. }
  117. newsql := "insert into " + tab + " (" + strings.Join(sqllist, ",") + ") values (" + strings.Join(seqs, ", ") + ")"
  118. res, err := p.Db.Exec(newsql, values...)
  119. if err != nil {
  120. log.Infof(" insert err=%v", err)
  121. return 0, err
  122. }
  123. id, err1 := res.LastInsertId()
  124. //log.Infof(" insert id=%v err=%v", id, err1)
  125. return int(id), err1
  126. }
  127. func (p *DB) InsertIgnore(tab string, data map[string]interface{}) (int, error) {
  128. var sqllist []string
  129. var seqs []string
  130. var values []interface{}
  131. for key, value := range data {
  132. sqllist = append(sqllist, key)
  133. seqs = append(seqs, "?")
  134. values = append(values, value)
  135. }
  136. newsql := "insert ignore into " + tab + " (" + strings.Join(sqllist, ",") + ") values (" + strings.Join(seqs, ", ") + ")"
  137. res, err := p.Db.Exec(newsql, values...)
  138. if err != nil {
  139. log.Infof(" insert err=%v", err)
  140. return 0, err
  141. }
  142. id, err1 := res.LastInsertId()
  143. log.Infof(" insert id=%v err=%v", id, err1)
  144. return int(id), err1
  145. }
  146. func (p *DB) Replace(tab string, data map[string]interface{}) (int64, error) {
  147. var sqllist []string
  148. var seqs []string
  149. var values []interface{}
  150. for key, value := range data {
  151. sqllist = append(sqllist, key)
  152. seqs = append(seqs, "?")
  153. values = append(values, value)
  154. }
  155. newsql := "replace into " + tab + " (" + strings.Join(sqllist, ",") + ") values (" + strings.Join(seqs, ", ") + ")"
  156. res, erro := p.Db.Exec(newsql, values...)
  157. if erro != nil {
  158. log.Infof(" replace err=%v", erro)
  159. return 0, erro
  160. }
  161. log.Infof("replace sql=%v %v %v", newsql, res, erro)
  162. id, err := res.LastInsertId()
  163. return id, err
  164. }
  165. func (p *DB) Excute(newsql string, args ...interface{}) (int, error) {
  166. res, erro := p.Db.Exec(newsql, args...)
  167. if erro != nil {
  168. return 0, erro
  169. }
  170. id, err := res.RowsAffected()
  171. return int(id), err
  172. }
  173. func (p *DB) ExcuteInsert(newsql string, args ...interface{}) (int, error) {
  174. res, erro := p.Db.Exec(newsql, args...)
  175. if erro != nil {
  176. return 0, erro
  177. }
  178. id, err := res.LastInsertId()
  179. return int(id), err
  180. }
  181. func (p *DB) Update(tab string, update map[string]interface{}, where map[string]interface{}) (int, error) {
  182. var setsql []string
  183. var values []interface{}
  184. var wheresql []string
  185. for key, value := range update {
  186. setsql = append(setsql, key+" = ?")
  187. values = append(values, value)
  188. }
  189. for key1, value1 := range where {
  190. if strings.Contains(key1, "?") {
  191. wheresql = append(wheresql, key1)
  192. values = append(values, value1)
  193. } else {
  194. wheresql = append(wheresql, key1+" = ?")
  195. values = append(values, value1)
  196. }
  197. }
  198. newsql := "update " + tab + " set " + strings.Join(setsql, ",") + " where " + strings.Join(wheresql, " and ")
  199. res, erro := p.Db.Exec(newsql, values...)
  200. if erro != nil {
  201. return 0, erro
  202. }
  203. id, err := res.RowsAffected()
  204. return int(id), err
  205. }
  206. func (p *DB) GetData(sqlString string, params ...interface{}) ([]map[string]interface{}, error) {
  207. // tableData := make([]map[string]interface{}, 0)
  208. rows, err := p.Db.Query(sqlString, params...)
  209. if err != nil {
  210. log.Infof("dberr = %v", err)
  211. return nil, err
  212. // return tableData, err
  213. }
  214. defer rows.Close()
  215. tableData, err := FetchData(rows)
  216. if err != nil || len(tableData) < 1 {
  217. return nil, errors.New("data null")
  218. }
  219. return tableData, nil
  220. }
  221. func (p *DB) GetRow(sqlString string, params ...interface{}) (map[string]interface{}, error) {
  222. // tableData := make([]map[string]interface{}, 0)
  223. rows, err := p.Db.Query(sqlString, params...)
  224. if err != nil {
  225. log.Infof("dberr = %v", err)
  226. return nil, err
  227. }
  228. defer rows.Close()
  229. tableData, err := FetchData(rows)
  230. if err != nil || len(tableData) < 1 {
  231. return nil, errors.New("data null")
  232. }
  233. return tableData[0], nil
  234. }
  235. func (p *DB) GetWithTotal(tab string, attr string, where map[string]interface{}, from int, to int) ([]map[string]interface{}, int) {
  236. var wheresqls []string
  237. var params []interface{}
  238. var sqlString string
  239. tableData := make([]map[string]interface{}, 0)
  240. var wheresql string
  241. for key1, value1 := range where {
  242. if strings.Contains(key1, "?") {
  243. wheresqls = append(wheresqls, key1)
  244. params = append(params, value1)
  245. } else {
  246. wheresqls = append(wheresqls, key1+" = ?")
  247. params = append(params, value1)
  248. }
  249. }
  250. wheresql = strings.Join(wheresqls, " and ")
  251. if wheresql != "" {
  252. wheresql = " where " + wheresql
  253. }
  254. sqltotal := "select count(1) from " + tab + wheresql
  255. total := 0
  256. err0 := p.Db.QueryRow(sqltotal, params...).Scan(&total)
  257. if err0 != nil {
  258. log.Infof("dberr = %v %v", sqltotal, err0)
  259. return tableData, 0
  260. }
  261. sqlString = "select " + attr + " from " + tab + wheresql + " limit ?,?"
  262. params = append(params, from, to)
  263. rows, err := p.Db.Query(sqlString, params...)
  264. if err != nil {
  265. log.Infof("dberr = %v %v", sqltotal, err)
  266. return tableData, 0
  267. }
  268. defer rows.Close()
  269. tableData, _ = FetchData(rows)
  270. return tableData, total
  271. }
  272. func FetchData(rows *sql.Rows) (tableData []map[string]interface{}, err error) {
  273. columns, err := rows.Columns()
  274. if err != nil {
  275. return
  276. }
  277. tableData = make([]map[string]interface{}, 0)
  278. count := len(columns)
  279. values := make([]interface{}, count)
  280. valuePtrs := make([]interface{}, count)
  281. for rows.Next() {
  282. for i := 0; i < count; i++ {
  283. valuePtrs[i] = &values[i]
  284. }
  285. rows.Scan(valuePtrs...)
  286. entry := make(map[string]interface{})
  287. for i, col := range columns {
  288. var v interface{}
  289. val := values[i]
  290. b, ok := val.([]byte)
  291. if ok {
  292. v = string(b)
  293. } else {
  294. v = val
  295. }
  296. entry[col] = v
  297. }
  298. tableData = append(tableData, entry)
  299. }
  300. return
  301. }
  302. func FetchOne(rows *sql.Rows) (tableData map[string]interface{}, err error) {
  303. defer rows.Close()
  304. columns, err := rows.Columns()
  305. data := map[string]interface{}{}
  306. if err != nil {
  307. return data, err
  308. }
  309. if !rows.Next() {
  310. return data, errors.New("data null")
  311. }
  312. count := len(columns)
  313. valuePtrs := make([]interface{}, count)
  314. values := make([]interface{}, count)
  315. for i := 0; i < count; i++ {
  316. valuePtrs[i] = &values[i]
  317. }
  318. if err = rows.Scan(valuePtrs...); err != nil {
  319. return data, err
  320. }
  321. for i, col := range columns {
  322. var v interface{}
  323. val := values[i]
  324. b, ok := val.([]byte)
  325. if ok {
  326. v = string(b)
  327. } else {
  328. v = val
  329. }
  330. data[col] = v
  331. }
  332. return data, nil
  333. }