sql_utils.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322
  1. package restful
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "log"
  6. "math"
  7. "reflect"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "unsafe"
  12. "github.com/pkg/errors"
  13. _ "github.com/go-sql-driver/mysql"
  14. "github.com/jmoiron/sqlx"
  15. "github.com/patrickmn/go-cache"
  16. "github.com/tealeg/xlsx"
  17. "github.com/xormplus/xorm/schemas"
  18. "kpt.xdmy/pkg/setting"
  19. )
  20. var (
  21. Dbs *sqlx.DB
  22. Apisql_cache *cache.Cache
  23. )
  24. // SQLInit 初始化数据库操作句柄,这里要提供:
  25. // driverName string: 数据库类型,例如mysql、sqlite等,参考github.com/go-sql-driver/mysql官方介绍
  26. // dataSourceName string: 数据库地址,参考github.com/go-sql-driver/mysql官方介绍
  27. // MaxOpenConns int: 最大缓存连接数,这个数值包含了MaxIdleConns
  28. // MaxIdleConns int:预备的最大空闲连接数
  29. func SQLInit(driverName, dataSourceName string, maxOpenConns, maxIdleConns int, showlog bool) error {
  30. if Dbs == nil {
  31. var err error
  32. if Dbs, err = sqlx.Open(driverName, dataSourceName); err != nil {
  33. return err
  34. }
  35. Dbs.SetMaxOpenConns(maxOpenConns)
  36. Dbs.SetMaxIdleConns(maxIdleConns)
  37. Dbs.SetConnMaxLifetime(300 * time.Second)
  38. }
  39. if Apisql_cache == nil {
  40. Apisql_cache = cache.New(600*time.Second, 10*time.Second)
  41. }
  42. // SetCacheSql()
  43. return nil
  44. }
  45. func SetCacheSql() {
  46. rows, err := Dbs.Queryx("SELECT sqlname, CONCAT(sqlstr,'|',IFNULL(params,'')) AS sqlstr FROM apisql WHERE ENABLE>0 ")
  47. if err != nil {
  48. return
  49. }
  50. valuesMap, err := Rows2Strings(rows)
  51. if err == nil && len(valuesMap) > 0 {
  52. for _, v := range valuesMap {
  53. Apisql_cache.Set(v["sqlname"], v["sqlstr"], cache.DefaultExpiration)
  54. }
  55. }
  56. }
  57. func sqlCheckParam(param string) error {
  58. if strings.Contains(param, ";") {
  59. return errors.New("can not have ;")
  60. }
  61. return nil
  62. }
  63. func GetSqlByName(name string, tx *sqlx.Tx) (string, string) {
  64. sqls := ""
  65. param := ""
  66. if sql, ok := Apisql_cache.Get(name); ok {
  67. tempstrb := strings.IndexAny(sql.(string), "|")
  68. sqls = sql.(string)[0:tempstrb]
  69. param = sql.(string)[tempstrb+1:]
  70. } else {
  71. valuesMap, err := MapStr("SELECT sqlstr, params FROM apisql WHERE sqlname = ? AND ENABLE>0 ", name)
  72. if err != nil {
  73. return err.Error(), "err"
  74. }
  75. if len(valuesMap) > 0 {
  76. sqls = valuesMap["sqlstr"]
  77. param = valuesMap["params"]
  78. // Apisql_cache.Set(name, (sqls + "|" + param), cache.DefaultExpiration)
  79. }
  80. }
  81. if setting.DatabaseSetting.ShowGetSqllog {
  82. fmt.Println("==============")
  83. fmt.Println("apisql:" + sqls)
  84. fmt.Println("--------------")
  85. fmt.Println("param:" + param)
  86. fmt.Println("==============")
  87. }
  88. return sqls, param
  89. }
  90. func GetSqlByNameDB(name string) (string, string) {
  91. var sqls, param string
  92. if sql, ok := Apisql_cache.Get(name); ok {
  93. tempstrb := strings.IndexAny(sql.(string), "|")
  94. sqls = sql.(string)[0:tempstrb]
  95. param = sql.(string)[tempstrb+1:]
  96. } else {
  97. rows, err := Dbs.Queryx("SELECT sqlstr,params FROM apisql WHERE sqlname = ? AND ENABLE>0 ", name)
  98. if err != nil {
  99. return err.Error(), "err"
  100. }
  101. valuesMap, err := Rows2Strings(rows)
  102. if err == nil && len(valuesMap) > 0 {
  103. sqls = valuesMap[0]["sqlstr"]
  104. param = valuesMap[0]["params"]
  105. // Apisql_cache.Set(name, (sqls + "|" + param), cache.DefaultExpiration)
  106. }
  107. }
  108. if setting.DatabaseSetting.ShowGetSqllog {
  109. fmt.Println("==============")
  110. fmt.Println("apisql:" + sqls)
  111. fmt.Println("--------------")
  112. fmt.Println("param:" + param)
  113. fmt.Println("==============")
  114. }
  115. return sqls, param
  116. }
  117. func GetSqlByNameDBT(name string, tx *sqlx.Tx) (string, string) {
  118. var sqls, param string
  119. if sql, ok := Apisql_cache.Get(name); ok {
  120. tempstrb := strings.IndexAny(sql.(string), "|")
  121. sqls = sql.(string)[0:tempstrb]
  122. param = sql.(string)[tempstrb+1:]
  123. } else {
  124. rows, err := Dbs.Queryx("SELECT sqlstr,params FROM apisql WHERE sqlname = ? AND ENABLE>0 ", name)
  125. if err != nil {
  126. log.Default().Printf("GetSqlByNameDBT :%v", err)
  127. return "", ""
  128. }
  129. if rows.Next() {
  130. rows.Scan(&sqls, &param)
  131. }
  132. if sqls != "" {
  133. // Apisql_cache.Set(name, (sqls + "|" + param), cache.DefaultExpiration)
  134. }
  135. }
  136. if setting.DatabaseSetting.ShowGetSqllog {
  137. fmt.Println("==============")
  138. fmt.Println("apisql:" + sqls)
  139. fmt.Println("--------------")
  140. fmt.Println("param:" + param)
  141. fmt.Println("==============")
  142. }
  143. return sqls, param
  144. }
  145. // sqlGetValues 根据结构体中指向实际数据的指针获取出数据,并存储到另一张表中返回
  146. func sqlGetValues(pvs []interface{}, columnsType []*sql.ColumnType, columnsLen int) map[string]interface{} {
  147. result := make(map[string]interface{}, columnsLen)
  148. for a := 0; a < columnsLen; a++ {
  149. switch s := pvs[a].(type) {
  150. case *int8:
  151. result[columnsType[a].Name()] = *s
  152. case *int16:
  153. result[columnsType[a].Name()] = *s
  154. case *int32:
  155. result[columnsType[a].Name()] = *s
  156. case *int64:
  157. result[columnsType[a].Name()] = *s
  158. case *float32:
  159. result[columnsType[a].Name()] = *s
  160. case *float64:
  161. result[columnsType[a].Name()] = *s
  162. case *string:
  163. result[columnsType[a].Name()] = *s
  164. case *sql.NullInt64:
  165. result[columnsType[a].Name()] = *s
  166. case *sql.NullString:
  167. result[columnsType[a].Name()] = *s
  168. }
  169. }
  170. return result
  171. }
  172. // 这里返回的是原始数组的基础上加上了字段名标识
  173. func sqlQuery(columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) ([]map[string]interface{}, error) {
  174. jsondata := make([]map[string]interface{}, queryCount)
  175. for k1, v1 := range queryData {
  176. if k1 >= queryCount {
  177. break
  178. }
  179. jsondata[k1] = sqlGetValues(v1, columnsType, columnsLen)
  180. }
  181. return jsondata, nil
  182. }
  183. func sqlQueryByTinyIntMap(columnName string, columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) (map[int8]map[string]interface{}, error) {
  184. jsondata := make(map[int8]map[string]interface{}, queryCount)
  185. for k1, v1 := range queryData {
  186. if k1 >= queryCount {
  187. break
  188. }
  189. for a := 0; a < columnsLen; a++ {
  190. if columnsType[a].Name() == columnName {
  191. if value, ok := v1[a].(*int8); ok {
  192. jsondata[*value] = sqlGetValues(v1, columnsType, columnsLen)
  193. }
  194. break
  195. }
  196. }
  197. }
  198. return jsondata, nil
  199. }
  200. func sqlQueryBySmallIntMap(columnName string, columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) (map[int16]map[string]interface{}, error) {
  201. jsondata := make(map[int16]map[string]interface{}, queryCount)
  202. for k1, v1 := range queryData {
  203. if k1 >= queryCount {
  204. break
  205. }
  206. for a := 0; a < columnsLen; a++ {
  207. if columnsType[a].Name() == columnName {
  208. if value, ok := v1[a].(*int16); ok {
  209. jsondata[*value] = sqlGetValues(v1, columnsType, columnsLen)
  210. }
  211. break
  212. }
  213. }
  214. }
  215. return jsondata, nil
  216. }
  217. func sqlQueryByIntMap(columnName string, columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) (map[int32]map[string]interface{}, error) {
  218. jsondata := make(map[int32]map[string]interface{}, queryCount)
  219. for k1, v1 := range queryData {
  220. if k1 >= queryCount {
  221. break
  222. }
  223. for a := 0; a < columnsLen; a++ {
  224. if columnsType[a].Name() == columnName {
  225. if value, ok := v1[a].(*int32); ok {
  226. jsondata[*value] = sqlGetValues(v1, columnsType, columnsLen)
  227. }
  228. break
  229. }
  230. }
  231. }
  232. return jsondata, nil
  233. }
  234. func sqlQueryByBigIntMap(columnName string, columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) (map[int64]map[string]interface{}, error) {
  235. jsondata := make(map[int64]map[string]interface{}, queryCount)
  236. for k1, v1 := range queryData {
  237. if k1 >= queryCount {
  238. break
  239. }
  240. for a := 0; a < columnsLen; a++ {
  241. if columnsType[a].Name() == columnName {
  242. if value, ok := v1[a].(*int64); ok {
  243. jsondata[*value] = sqlGetValues(v1, columnsType, columnsLen)
  244. }
  245. break
  246. }
  247. }
  248. }
  249. return jsondata, nil
  250. }
  251. func sqlQueryByFloatIntMap(columnName string, columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) (map[float32]map[string]interface{}, error) {
  252. jsondata := make(map[float32]map[string]interface{}, queryCount)
  253. for k1, v1 := range queryData {
  254. if k1 >= queryCount {
  255. break
  256. }
  257. for a := 0; a < columnsLen; a++ {
  258. if columnsType[a].Name() == columnName {
  259. if value, ok := v1[a].(*float32); ok {
  260. jsondata[*value] = sqlGetValues(v1, columnsType, columnsLen)
  261. }
  262. break
  263. }
  264. }
  265. }
  266. return jsondata, nil
  267. }
  268. func sqlQueryByDoubleMap(columnName string, columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) (map[float64]map[string]interface{}, error) {
  269. jsondata := make(map[float64]map[string]interface{}, queryCount)
  270. for k1, v1 := range queryData {
  271. if k1 >= queryCount {
  272. break
  273. }
  274. for a := 0; a < columnsLen; a++ {
  275. if columnsType[a].Name() == columnName {
  276. if value, ok := v1[a].(*float64); ok {
  277. jsondata[*value] = sqlGetValues(v1, columnsType, columnsLen)
  278. }
  279. break
  280. }
  281. }
  282. }
  283. return jsondata, nil
  284. }
  285. func sqlQueryByStringMap(columnName string, columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) (map[string]map[string]interface{}, error) {
  286. jsondata := make(map[string]map[string]interface{}, queryCount)
  287. for k1, v1 := range queryData {
  288. if k1 >= queryCount {
  289. break
  290. }
  291. for a := 0; a < columnsLen; a++ {
  292. if columnsType[a].Name() == columnName {
  293. if value, ok := v1[a].(*string); ok {
  294. jsondata[*value] = sqlGetValues(v1, columnsType, columnsLen)
  295. }
  296. break
  297. }
  298. }
  299. }
  300. return jsondata, nil
  301. }
  302. func sqlGetColumnType(columnsType []*sql.ColumnType, columnsLen int, valueName string) string {
  303. for a := 0; a < columnsLen; a++ {
  304. if columnsType[a].Name() == valueName {
  305. return columnsType[a].DatabaseTypeName()
  306. }
  307. }
  308. return ""
  309. }
  310. func round(num float64) int {
  311. return int(num + math.Copysign(0.5, num))
  312. }
  313. func toFixed(num float64, precision int) float64 {
  314. output := math.Pow(10, float64(precision))
  315. return float64(round(num*output)) / output
  316. }
  317. // QueryByMap 将查询到的数据,按照指定字段的值做为索引构建map并返回
  318. // columnName string: 作为索引的字段名称
  319. // sql string: 查询需要获取哪些字段的值,就是select后面跟着的部分,一般用"*"
  320. // where string: 过滤条件,就是where后面跟着的部分
  321. // order string: 排序条件,就是order by后面跟着的部分。默认是ASC排序,除非"-"开头则DESC排序
  322. // offset string: limit后面逗号相隔的两个数值,前者就是offset,后者就是count
  323. // count string: limit后面逗号相隔的两个数值,前者就是offset,后者就是count
  324. func QueryByMap(sqlstr string, offset, count int, params []interface{}) (interface{}, error) {
  325. if err := sqlCheckParam(sqlstr); err != nil {
  326. return 0, err
  327. }
  328. recordcount := int64(0)
  329. if count > 1 {
  330. sqlstr = fmt.Sprintf("SELECT COUNT(*) as count FROM (%s) a", sqlstr)
  331. err := BasicList(sqlstr, params, &recordcount)
  332. if err != nil {
  333. fmt.Println("s1", err)
  334. return nil, err
  335. }
  336. }
  337. queryData := make([]map[string]interface{}, 1)
  338. var err error
  339. if count == 0 {
  340. rows, err := Dbs.Queryx(sqlstr, params...)
  341. if err != nil {
  342. return err.Error(), err
  343. }
  344. queryData, err = rows2mapObjects(rows)
  345. } else {
  346. if count > 0 && offset > 0 {
  347. offset = offset * count
  348. }
  349. rows, err := Dbs.Queryx(fmt.Sprintf(sqlstr+" limit %d , %d", offset, count), params...)
  350. if err != nil {
  351. return err.Error(), err
  352. }
  353. queryData, err = rows2mapObjects(rows)
  354. }
  355. if err != nil {
  356. return nil, err
  357. }
  358. if recordcount == 0 {
  359. recordcount = int64(len(queryData))
  360. }
  361. data := make(map[string]interface{})
  362. data["list"] = queryData
  363. data["total"] = recordcount
  364. data["code"] = 0
  365. data["message"] = "ok"
  366. if count > 0 {
  367. data["pages"] = math.Ceil(float64(recordcount) / float64(count))
  368. data["pageNum"] = math.Ceil(float64(offset+1) / float64(count))
  369. }
  370. data["pageSize"] = count
  371. return data, nil
  372. }
  373. // func QueryByMapT(sqlstr string, offset, count int, params []interface{}, tx *sqlx.Tx) (interface{}, error) {
  374. func QueryByMapT(sqlstr string, offset, count int, params []interface{}) (interface{}, error) {
  375. if err := sqlCheckParam(sqlstr); err != nil {
  376. return 0, err
  377. }
  378. recordcount := int64(0)
  379. if count > 1 {
  380. sql := "SELECT COUNT(*) as count FROM (" + sqlstr + ") a"
  381. err := BasicList(sql, params, &recordcount)
  382. if err != nil {
  383. fmt.Println("s1", err)
  384. return nil, err
  385. }
  386. }
  387. queryData := make([]map[string]interface{}, 1)
  388. // queryData := make([]map[string]string, 1)
  389. var err error
  390. if count == 0 {
  391. // queryData, err = MapStrList(sqlstr, params...)
  392. queryData, err = MapInterList(sqlstr, params...)
  393. } else {
  394. // if count > 0 && offset > 0 {
  395. // offset = offset * count
  396. // }
  397. sqllist := sqlstr + fmt.Sprintf(" limit %d offset %d", count, offset*count)
  398. // queryData, err = MapStrList(sqllist, params...)
  399. queryData, err = MapInterList(sqllist, params...)
  400. }
  401. if err != nil {
  402. return nil, err
  403. }
  404. if recordcount == 0 {
  405. recordcount = int64(len(queryData))
  406. }
  407. data := make(map[string]interface{})
  408. data["list"] = queryData
  409. data["total"] = recordcount
  410. data["code"] = 0
  411. data["message"] = "ok"
  412. if count > 0 {
  413. data["pages"] = math.Ceil(float64(recordcount) / float64(count))
  414. data["pageNum"] = math.Ceil(float64(offset+1) / float64(count))
  415. }
  416. data["pageSize"] = count
  417. return data, nil
  418. }
  419. // QueryByXlsx 将查询到的数据,按照指定字段的值做为索引构建map并返回
  420. // sql string: 查询需要获取哪些字段的值,就是select后面跟着的部分,一般用"*"
  421. // params string: 过滤条件,就是where后面跟着的部分
  422. func QueryByXlsx(sqlstr string, params []interface{}) (*xlsx.File, error) {
  423. if err := sqlCheckParam(sqlstr); err != nil {
  424. return nil, err
  425. }
  426. rows, err := Dbs.Queryx(sqlstr, params...)
  427. if err != nil {
  428. return nil, err
  429. }
  430. defer rows.Close()
  431. columnsType, _ := rows.ColumnTypes()
  432. columnsLen := len(columnsType)
  433. columns, _ := rows.Columns()
  434. values := make([]interface{}, columnsLen)
  435. valuePtrs := make([]interface{}, columnsLen)
  436. var sheet *xlsx.Sheet
  437. var row *xlsx.Row
  438. var cell *xlsx.Cell
  439. file := xlsx.NewFile()
  440. sheet, err = file.AddSheet("Sheet1")
  441. if err != nil {
  442. fmt.Printf(err.Error())
  443. }
  444. row = sheet.AddRow()
  445. for _, columnname := range columns {
  446. cell = row.AddCell()
  447. cell.Value = columnname
  448. }
  449. for rows.Next() {
  450. for a := 0; a < columnsLen; a++ {
  451. valuePtrs[a] = &values[a]
  452. }
  453. rows.Scan(valuePtrs...)
  454. row = sheet.AddRow()
  455. for i := range columns {
  456. var v interface{}
  457. val := values[i]
  458. b, ok := val.([]byte)
  459. cell = row.AddCell()
  460. if ok {
  461. v1 := string(b)
  462. switch columnsType[i].DatabaseTypeName() {
  463. case "TINYINT", "SMALLINT", "MEDIUMINT", "INT", "INTEGER", "BIGINT":
  464. {
  465. v, _ = strconv.ParseInt(v1, 10, 32)
  466. cell.Value = fmt.Sprintf("%v", v)
  467. }
  468. case "FLOAT", "DOUBLE", "DECIMAL":
  469. {
  470. cindex := len(val.([]byte)) - strings.Index(v1, ".") - 1
  471. v2, _ := strconv.ParseFloat(v1, 32)
  472. v = toFixed(v2, cindex)
  473. cell.Value = fmt.Sprintf("%v", v)
  474. }
  475. case "BOOL":
  476. {
  477. v, _ = strconv.ParseBool(v1)
  478. cell.Value = fmt.Sprintf("%v", v)
  479. }
  480. default:
  481. {
  482. v = v1
  483. cell.Value = fmt.Sprintf("%v", v)
  484. }
  485. }
  486. } else {
  487. v = val
  488. cell.Value = fmt.Sprintf("%v", v)
  489. }
  490. if cell.Value == "<nil>" {
  491. cell.Value = ""
  492. }
  493. }
  494. }
  495. return file, nil
  496. }
  497. // QueryByMap 将查询到的数据,按照指定字段的值做为索引构建map并返回
  498. // columnName string: 作为索引的字段名称
  499. // sql string: 查询需要获取哪些字段的值,就是select后面跟着的部分,一般用"*"
  500. // where string: 过滤条件,就是where后面跟着的部分
  501. // order string: 排序条件,就是order by后面跟着的部分。默认是ASC排序,除非"-"开头则DESC排序
  502. // offset string: limit后面逗号相隔的两个数值,前者就是offset,后者就是count
  503. // count string: limit后面逗号相隔的两个数值,前者就是offset,后者就是count
  504. func QueryByMapMenu(sqlstr string, offset, count int, params []interface{}) ([]map[string]interface{}, error) {
  505. if err := sqlCheckParam(sqlstr); err != nil {
  506. return nil, err
  507. }
  508. if offset < 0 {
  509. offset = 0
  510. }
  511. if count <= 0 {
  512. count = 0
  513. }
  514. if count > 0 {
  515. sqlstr += " limit " + strconv.Itoa(offset) + "," + strconv.Itoa(count)
  516. }
  517. rows, err := Dbs.Query(sqlstr, params...)
  518. if err != nil {
  519. return nil, err
  520. }
  521. defer rows.Close()
  522. columnsType, _ := rows.ColumnTypes()
  523. columnsLen := len(columnsType)
  524. columns, _ := rows.Columns()
  525. queryData := make([]map[string]interface{}, 0)
  526. values := make([]interface{}, columnsLen)
  527. valuePtrs := make([]interface{}, columnsLen)
  528. for rows.Next() {
  529. for a := 0; a < columnsLen; a++ {
  530. valuePtrs[a] = &values[a]
  531. }
  532. rows.Scan(valuePtrs...)
  533. entry := make(map[string]interface{})
  534. for i, col := range columns {
  535. entry[col] = getValue(values[i], columnsType[i].DatabaseTypeName())
  536. }
  537. queryData = append(queryData, entry)
  538. }
  539. data := queryData
  540. return data, nil
  541. }
  542. func QueryByList(sqlstr string, offset, count int, params []interface{}) (interface{}, error) {
  543. if err := sqlCheckParam(sqlstr); err != nil {
  544. return 0, err
  545. }
  546. if count == 0 {
  547. count = 1000
  548. }
  549. recordcount := int64(0)
  550. if count > 1 {
  551. trow, err := Dbs.Queryx("SELECT COUNT(1) as count FROM ("+sqlstr+") a", params...)
  552. if err != nil {
  553. return nil, err
  554. }
  555. tt, err := rows2mapObjects(trow)
  556. if err != nil {
  557. return nil, err
  558. }
  559. recordcount = tt[0]["count"].(int64)
  560. }
  561. queryData := make([]map[string]interface{}, 1)
  562. var err error
  563. if count == 0 {
  564. tqueryData, err := Dbs.Queryx(sqlstr, params...)
  565. if err != nil {
  566. return nil, err
  567. }
  568. queryData, err = rows2mapObjects(tqueryData)
  569. } else {
  570. // if count > 0 && offset > 0 {
  571. // offset = offset * count
  572. // }
  573. sqlstr += fmt.Sprintf(" limit %d offset %d", count, offset*count)
  574. tqueryData, err := Dbs.Queryx(sqlstr, params...)
  575. if err != nil {
  576. return nil, err
  577. }
  578. queryData, err = rows2mapObjects(tqueryData)
  579. }
  580. if err != nil {
  581. return nil, err
  582. }
  583. columnsname := make([]string, 0)
  584. listdata := make(map[string][]interface{})
  585. if len(queryData) > 0 {
  586. for i := range queryData {
  587. if i == 0 {
  588. for i := range queryData[0] {
  589. columnsname = append(columnsname, i)
  590. }
  591. }
  592. for _, v := range columnsname {
  593. listdata[v] = append(listdata[v], queryData[i][v])
  594. }
  595. }
  596. recordcount = int64(len(queryData))
  597. }
  598. data := make(map[string]interface{})
  599. data["list"] = listdata
  600. //data["columnsname"] = columnsname
  601. data["total"] = recordcount
  602. data["code"] = 0
  603. data["message"] = "ok"
  604. if count > 0 {
  605. data["pages"] = math.Ceil(float64(recordcount) / float64(count))
  606. data["pageNum"] = math.Ceil(float64(offset+1) / float64(count))
  607. }
  608. data["pageSize"] = count
  609. return data, nil
  610. }
  611. func QueryByListList(sqlstr string, offset, count int, params []interface{}) (interface{}, error) {
  612. if err := sqlCheckParam(sqlstr); err != nil {
  613. return 0, err
  614. }
  615. if count == 0 {
  616. count = 1000
  617. }
  618. recordcount := int64(0)
  619. if count > 1 {
  620. trow, err := Dbs.Queryx("SELECT COUNT(1) as count FROM ("+sqlstr+") a", params...)
  621. if err != nil {
  622. return nil, err
  623. }
  624. tt, err := rows2mapObjects(trow)
  625. if err != nil {
  626. return nil, err
  627. }
  628. recordcount = tt[0]["count"].(int64)
  629. }
  630. queryData := make([]map[string]interface{}, 1)
  631. var err error
  632. if count == 0 {
  633. tqueryData, err := Dbs.Queryx(sqlstr, params...)
  634. if err != nil {
  635. return nil, err
  636. }
  637. queryData, err = rows2mapObjects(tqueryData)
  638. } else {
  639. if count > 0 && offset > 0 {
  640. offset = offset * count
  641. }
  642. tqueryData, err := Dbs.Queryx(fmt.Sprintf(sqlstr+" limit %d , %d", offset, count), params...)
  643. if err != nil {
  644. return nil, err
  645. }
  646. queryData, err = rows2mapObjects(tqueryData)
  647. }
  648. if err != nil {
  649. return nil, err
  650. }
  651. columnsname := make([]string, 0)
  652. listdata := make([]interface{}, 0)
  653. if len(queryData) > 0 {
  654. for i := range queryData {
  655. if i == 0 {
  656. for i := range queryData[0] {
  657. columnsname = append(columnsname, i)
  658. }
  659. }
  660. listdatarow := make([]interface{}, 0)
  661. for _, v := range columnsname {
  662. listdatarow = append(listdatarow, queryData[i][v])
  663. }
  664. listdata = append(listdata, listdatarow)
  665. }
  666. recordcount = int64(len(queryData))
  667. }
  668. data := make(map[string]interface{})
  669. data["list"] = listdata
  670. data["columnsname"] = columnsname
  671. data["total"] = recordcount
  672. data["code"] = 0
  673. data["message"] = "ok"
  674. if count > 0 {
  675. data["pages"] = math.Ceil(float64(recordcount) / float64(count))
  676. data["pageNum"] = math.Ceil(float64(offset+1) / float64(count))
  677. }
  678. data["pageSize"] = count
  679. return data, nil
  680. }
  681. // func QueryByListT(sqlstr string, offset, count int, params []interface{}, tx *sqlx.Tx) (interface{}, error) {
  682. func QueryByListT(sqlstr string, offset, count int, params []interface{}) (interface{}, error) {
  683. if err := sqlCheckParam(sqlstr); err != nil {
  684. return 0, err
  685. }
  686. if count == 0 {
  687. count = 1000
  688. }
  689. recordcount := int64(0)
  690. if count > 1 {
  691. tt, err := Dbs.Queryx("SELECT COUNT(*) as count FROM ("+sqlstr+") a", params...)
  692. if err != nil {
  693. return nil, err
  694. }
  695. tt.Next()
  696. tt.Scan(&recordcount)
  697. }
  698. var err error
  699. var sqllist string
  700. if count > 0 {
  701. sqllist = sqlstr + fmt.Sprintf(" limit %d offset %d", count, offset*count)
  702. }
  703. listdata, err := MapInterList(sqllist, params...)
  704. if err != nil {
  705. log.Default().Printf("QueryByListT MapInterList : %v", err)
  706. }
  707. data := make(map[string]interface{})
  708. data["lists"] = listdata
  709. data["total"] = recordcount
  710. data["code"] = 0
  711. data["message"] = "ok"
  712. if count > 0 {
  713. data["pages"] = math.Ceil(float64(recordcount) / float64(count))
  714. data["pageNum"] = math.Ceil(float64(offset+1) / float64(count))
  715. }
  716. data["pageSize"] = count
  717. return data, nil
  718. }
  719. // func QueryByListListT(sqlstr string, offset, count int, params []interface{}, tx *sqlx.Tx) (interface{}, error) {
  720. func QueryByListListT(sqlstr string, offset, count int, params []interface{}) (interface{}, error) {
  721. if err := sqlCheckParam(sqlstr); err != nil {
  722. return 0, err
  723. }
  724. if count == 0 {
  725. count = 1000
  726. }
  727. recordcount := int64(0)
  728. if count > 1 {
  729. sqlstr = fmt.Sprintf("SELECT COUNT(*) as count FROM (%s) a", sqlstr)
  730. err := BasicList(sqlstr, params, &recordcount)
  731. if err != nil {
  732. return nil, err
  733. }
  734. }
  735. queryData := make([]map[string]string, 1)
  736. var err error
  737. if count == 0 {
  738. queryData, err = MapStrList(sqlstr, params...)
  739. } else {
  740. // if count > 0 && offset > 0 {
  741. // offset = offset * count
  742. // }
  743. sqllist := sqlstr + fmt.Sprintf(" limit %d offset %d", count, offset*count)
  744. queryData, err = MapStrList(sqllist, params...)
  745. }
  746. if err != nil {
  747. return nil, err
  748. }
  749. columnsname := make([]string, 0)
  750. listdata := make([]interface{}, 0)
  751. if len(queryData) > 0 {
  752. for i := range queryData {
  753. if i == 0 {
  754. for i := range queryData[0] {
  755. columnsname = append(columnsname, i)
  756. }
  757. }
  758. listdatarow := make([]interface{}, 0)
  759. for _, v := range columnsname {
  760. listdatarow = append(listdatarow, queryData[i][v])
  761. }
  762. listdata = append(listdata, listdatarow)
  763. }
  764. recordcount = int64(len(queryData))
  765. }
  766. data := make(map[string]interface{})
  767. data["list"] = listdata
  768. data["columnsname"] = columnsname
  769. data["total"] = recordcount
  770. data["code"] = 0
  771. data["message"] = "ok"
  772. if count > 0 {
  773. data["pages"] = math.Ceil(float64(recordcount) / float64(count))
  774. data["pageNum"] = math.Ceil(float64(offset+1) / float64(count))
  775. }
  776. data["pageSize"] = count
  777. return data, nil
  778. }
  779. func ExecQuery(sqlstr string, params []interface{}) (interface{}, error) {
  780. if err := sqlCheckParam(sqlstr); err != nil {
  781. return 0, err
  782. }
  783. rows, err := Dbs.Exec(sqlstr, params...)
  784. if err != nil {
  785. return nil, err
  786. }
  787. data := make(map[string]interface{})
  788. LastInsertId, _ := rows.LastInsertId()
  789. idPointer := (*int)(unsafe.Pointer(&LastInsertId))
  790. idd16 := *idPointer
  791. RowsAffected, _ := rows.RowsAffected()
  792. _idPointer := (*int)(unsafe.Pointer(&RowsAffected))
  793. _idd16 := *_idPointer
  794. data["result"] = rows
  795. data["LastInsertId"] = idd16
  796. data["RowsAffected"] = _idd16
  797. return data, nil
  798. }
  799. func ExecQueryT(sqlstr string, params []interface{}, tx *sqlx.Tx) (interface{}, error) {
  800. if err := sqlCheckParam(sqlstr); err != nil {
  801. return 0, err
  802. }
  803. rows, err := tx.Exec(sqlstr, params...)
  804. if err != nil {
  805. fmt.Println("exe", err)
  806. return nil, err
  807. }
  808. LastInsertId, _ := rows.LastInsertId()
  809. idPointer := (*int)(unsafe.Pointer(&LastInsertId))
  810. idd16 := *idPointer
  811. data := make(map[string]interface{})
  812. RowsAffected, _ := rows.RowsAffected()
  813. _idPointer := (*int)(unsafe.Pointer(&RowsAffected))
  814. _idd16 := *_idPointer
  815. data["LastInsertId"] = idd16
  816. data["RowsAffected"] = _idd16
  817. data["result"] = rows
  818. return data, nil
  819. }
  820. func ExecQuerys(sqlstr string, params []interface{}) (interface{}, error) {
  821. if err := sqlCheckParam(sqlstr); err != nil {
  822. return 0, err
  823. }
  824. var res sql.Result
  825. var e error
  826. res, e = Dbs.Exec(sqlstr, params...)
  827. if e != nil {
  828. return nil, e
  829. }
  830. fmt.Printf("%#v\n", res)
  831. data := make(map[string]interface{})
  832. data["result"] = nil
  833. return data, nil
  834. }
  835. func getValue(value interface{}, CT string) interface{} {
  836. var v interface{}
  837. val := value
  838. b, ok := val.([]byte)
  839. if ok {
  840. v1 := string(b)
  841. switch CT {
  842. case "TINYINT", "SMALLINT", "MEDIUMINT", "INT", "INTEGER", "BIGINT":
  843. {
  844. v, _ = strconv.ParseInt(v1, 10, 32)
  845. }
  846. case "FLOAT", "DOUBLE", "DECIMAL":
  847. {
  848. cindex := len(val.([]byte)) - strings.Index(v1, ".") - 1
  849. v2, _ := strconv.ParseFloat(v1, 32)
  850. v = toFixed(v2, cindex)
  851. }
  852. case "BOOL":
  853. {
  854. v, _ = strconv.ParseBool(v1)
  855. }
  856. default:
  857. {
  858. v = v1
  859. }
  860. }
  861. } else {
  862. v = val
  863. }
  864. return v
  865. }
  866. func reflect2object(rawValue *reflect.Value) (value interface{}, err error) {
  867. aa := reflect.TypeOf((*rawValue).Interface())
  868. vv := reflect.ValueOf((*rawValue).Interface())
  869. switch aa.Kind() {
  870. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  871. value = vv.Int()
  872. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  873. value = vv.Uint()
  874. case reflect.Float32, reflect.Float64:
  875. value = vv.Float()
  876. case reflect.String:
  877. value = vv.String()
  878. case reflect.Array, reflect.Slice:
  879. switch aa.Elem().Kind() {
  880. case reflect.Uint8:
  881. data := rawValue.Interface().([]byte)
  882. value = string(data)
  883. default:
  884. err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name())
  885. }
  886. // time type
  887. case reflect.Struct:
  888. if aa.ConvertibleTo(schemas.TimeType) {
  889. value = vv.Convert(schemas.TimeType).Interface().(time.Time)
  890. } else {
  891. err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name())
  892. }
  893. case reflect.Bool:
  894. value = vv.Bool()
  895. case reflect.Complex128, reflect.Complex64:
  896. value = vv.Complex()
  897. /* TODO: unsupported types below
  898. case reflect.Map:
  899. case reflect.Ptr:
  900. case reflect.Uintptr:
  901. case reflect.UnsafePointer:
  902. case reflect.Chan, reflect.Func, reflect.Interface:
  903. */
  904. default:
  905. err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name())
  906. }
  907. return
  908. }
  909. func value2Object(rawValue *reflect.Value) (data interface{}, err error) {
  910. data, err = reflect2object(rawValue)
  911. if err != nil {
  912. return
  913. }
  914. return
  915. }
  916. func rows2mapObjects(rows *sqlx.Rows) (resultsSlice []map[string]interface{}, err error) {
  917. fields, err := rows.Columns()
  918. if err != nil {
  919. return nil, err
  920. }
  921. for rows.Next() {
  922. result, err := rows2mapObject(rows, fields)
  923. if err != nil {
  924. return nil, err
  925. }
  926. resultsSlice = append(resultsSlice, result)
  927. }
  928. return resultsSlice, nil
  929. }
  930. func rows2mapObject(rows *sqlx.Rows, fields []string) (resultsMap map[string]interface{}, err error) {
  931. result := make(map[string]interface{})
  932. scanResultContainers := make([]interface{}, len(fields))
  933. for i := 0; i < len(fields); i++ {
  934. var scanResultContainer interface{}
  935. scanResultContainers[i] = &scanResultContainer
  936. }
  937. if err := rows.Scan(scanResultContainers...); err != nil {
  938. return nil, err
  939. }
  940. for ii, key := range fields {
  941. rawValue := reflect.Indirect(reflect.ValueOf(scanResultContainers[ii]))
  942. //if row is null then ignore
  943. if rawValue.Interface() == nil {
  944. continue
  945. }
  946. if data, err := value2Object(&rawValue); err == nil {
  947. result[key] = data
  948. } else {
  949. return nil, err // !nashtsai! REVIEW, should return err or just error log?
  950. }
  951. }
  952. return result, nil
  953. }
  954. func row2mapStr(rows *sqlx.Rows, fields []string) (resultsMap map[string]string, err error) {
  955. result := make(map[string]string)
  956. scanResultContainers := make([]interface{}, len(fields))
  957. for i := 0; i < len(fields); i++ {
  958. var scanResultContainer interface{}
  959. scanResultContainers[i] = &scanResultContainer
  960. }
  961. if err := rows.Scan(scanResultContainers...); err != nil {
  962. return nil, err
  963. }
  964. for ii, key := range fields {
  965. rawValue := reflect.Indirect(reflect.ValueOf(scanResultContainers[ii]))
  966. // if row is null then as empty string
  967. if rawValue.Interface() == nil {
  968. result[key] = ""
  969. continue
  970. }
  971. if data, err := value2String(&rawValue); err == nil {
  972. result[key] = data
  973. } else {
  974. return nil, err
  975. }
  976. }
  977. return result, nil
  978. }
  979. func Rows2Strings(rows *sqlx.Rows) (resultsSlice []map[string]string, err error) {
  980. fields, err := rows.Columns()
  981. if err != nil {
  982. return nil, err
  983. }
  984. for rows.Next() {
  985. result, err := row2mapStr(rows, fields)
  986. if err != nil {
  987. return nil, err
  988. }
  989. resultsSlice = append(resultsSlice, result)
  990. }
  991. return resultsSlice, nil
  992. }
  993. func value2String(rawValue *reflect.Value) (str string, err error) {
  994. aa := reflect.TypeOf((*rawValue).Interface())
  995. vv := reflect.ValueOf((*rawValue).Interface())
  996. switch aa.Kind() {
  997. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  998. str = strconv.FormatInt(vv.Int(), 10)
  999. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  1000. str = strconv.FormatUint(vv.Uint(), 10)
  1001. case reflect.Float32, reflect.Float64:
  1002. str = strconv.FormatFloat(vv.Float(), 'f', -1, 64)
  1003. case reflect.String:
  1004. str = vv.String()
  1005. case reflect.Array, reflect.Slice:
  1006. switch aa.Elem().Kind() {
  1007. case reflect.Uint8:
  1008. data := rawValue.Interface().([]byte)
  1009. str = string(data)
  1010. if str == "\x00" {
  1011. str = "0"
  1012. }
  1013. default:
  1014. err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name())
  1015. }
  1016. // time type
  1017. case reflect.Struct:
  1018. if aa.ConvertibleTo(schemas.TimeType) {
  1019. str = vv.Convert(schemas.TimeType).Interface().(time.Time).Format(time.RFC3339Nano)
  1020. } else {
  1021. err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name())
  1022. }
  1023. case reflect.Bool:
  1024. str = strconv.FormatBool(vv.Bool())
  1025. case reflect.Complex128, reflect.Complex64:
  1026. str = fmt.Sprintf("%v", vv.Complex())
  1027. /* TODO: unsupported types below
  1028. case reflect.Map:
  1029. case reflect.Ptr:
  1030. case reflect.Uintptr:
  1031. case reflect.UnsafePointer:
  1032. case reflect.Chan, reflect.Func, reflect.Interface:
  1033. */
  1034. default:
  1035. err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name())
  1036. }
  1037. return
  1038. }
  1039. func MapStrList(sql string, param ...interface{}) ([]map[string]string, error) {
  1040. ress := make([]map[string]string, 0, 0)
  1041. rows, err := Dbs.Queryx(sql, param...)
  1042. if err != nil {
  1043. log.Default().Printf("MapStrList Queryx: %v", err)
  1044. return ress, err
  1045. }
  1046. col, err := rows.Columns()
  1047. if err != nil {
  1048. log.Default().Printf("BigpartUse clolumns: %v", err)
  1049. return ress, err
  1050. }
  1051. for rows.Next() {
  1052. m := make(map[string]string)
  1053. rs, err := rows.SliceScan()
  1054. if err != nil {
  1055. log.Default().Printf("BigpartUse SliceScan: %v", err)
  1056. return ress, err
  1057. }
  1058. for i, r := range rs {
  1059. switch r.(type) {
  1060. case []uint8:
  1061. m[col[i]] = string(r.([]uint8))
  1062. case int64:
  1063. m[col[i]] = strconv.FormatInt(r.(int64), 10)
  1064. }
  1065. }
  1066. ress = append(ress, m)
  1067. }
  1068. defer func() {
  1069. if err := rows.Close(); err != nil {
  1070. log.Default().Printf("sqlx row close:%v", err)
  1071. }
  1072. }()
  1073. return ress, nil
  1074. }
  1075. func MapInterList(sql string, param ...interface{}) ([]map[string]interface{}, error) {
  1076. ress := make([]map[string]interface{}, 0, 0)
  1077. rows, err := Dbs.Queryx(sql, param...)
  1078. if err != nil {
  1079. log.Default().Printf("MapInterList Queryx: %v", err)
  1080. return ress, err
  1081. }
  1082. col, err := rows.Columns()
  1083. if err != nil {
  1084. log.Default().Printf("BigpartUse clolumns: %v", err)
  1085. return ress, err
  1086. }
  1087. for rows.Next() {
  1088. m := make(map[string]interface{})
  1089. rs, err := rows.SliceScan()
  1090. if err != nil {
  1091. log.Default().Printf("BigpartUse SliceScan: %v", err)
  1092. return ress, err
  1093. }
  1094. for i, r := range rs {
  1095. switch r.(type) {
  1096. case []uint8:
  1097. m[col[i]] = string(r.([]uint8))
  1098. case int64:
  1099. m[col[i]] = r.(int64)
  1100. }
  1101. }
  1102. ress = append(ress, m)
  1103. }
  1104. defer func() {
  1105. if err := rows.Close(); err != nil {
  1106. log.Default().Printf("sqlx row close:%v", err)
  1107. }
  1108. }()
  1109. return ress, nil
  1110. }
  1111. func BasicList(sql string, params []interface{}, res ...interface{}) error {
  1112. // fmt.Printf("%s\n", sql)
  1113. if params == nil {
  1114. params = make([]interface{}, 0)
  1115. }
  1116. // var count int
  1117. tt, err := Dbs.Queryx(sql, params...)
  1118. if err != nil {
  1119. fmt.Println("s1", err)
  1120. return err
  1121. }
  1122. if tt.Next() {
  1123. tt.Scan(res...)
  1124. // tt.Scan(&count)
  1125. }
  1126. defer func() {
  1127. if err := tt.Close(); err != nil {
  1128. log.Default().Printf("sqlx row close:%v", err)
  1129. }
  1130. }()
  1131. return nil
  1132. }
  1133. func MapStr(sql string, param ...interface{}) (map[string]string, error) {
  1134. m := make(map[string]string)
  1135. rows, err := Dbs.Queryx(sql, param...)
  1136. if err != nil {
  1137. log.Default().Printf("MapStr Queryx: %v", err)
  1138. return m, err
  1139. }
  1140. col, err := rows.Columns()
  1141. if err != nil {
  1142. log.Default().Printf("BigpartUse clolumns: %v", err)
  1143. return m, err
  1144. }
  1145. if rows.Next() {
  1146. rs, err := rows.SliceScan()
  1147. if err != nil {
  1148. log.Default().Printf("BigpartUse SliceScan: %v", err)
  1149. return m, err
  1150. }
  1151. for i, r := range rs {
  1152. switch r.(type) {
  1153. case []uint8:
  1154. m[col[i]] = string(r.([]uint8))
  1155. case int64:
  1156. m[col[i]] = strconv.FormatInt(r.(int64), 10)
  1157. }
  1158. }
  1159. }
  1160. defer func() {
  1161. if err := rows.Close(); err != nil {
  1162. log.Default().Printf("sqlx row close:%v", err)
  1163. }
  1164. }()
  1165. return m, nil
  1166. }
  1167. func MapStrListTx(tx *sqlx.Tx, sql string, param ...interface{}) ([]map[string]string, error) {
  1168. ress := make([]map[string]string, 0, 0)
  1169. rows, err := tx.Queryx(sql, param...)
  1170. if err != nil {
  1171. log.Default().Printf("MapStrListTx Queryx: %v", err)
  1172. return ress, err
  1173. }
  1174. col, err := rows.Columns()
  1175. if err != nil {
  1176. log.Default().Printf("BigpartUse clolumns: %v", err)
  1177. return ress, err
  1178. }
  1179. for rows.Next() {
  1180. m := make(map[string]string)
  1181. rs, err := rows.SliceScan()
  1182. if err != nil {
  1183. log.Default().Printf("BigpartUse SliceScan: %v", err)
  1184. return ress, err
  1185. }
  1186. for i, r := range rs {
  1187. switch r.(type) {
  1188. case []uint8:
  1189. m[col[i]] = string(r.([]uint8))
  1190. case int64:
  1191. m[col[i]] = strconv.FormatInt(r.(int64), 10)
  1192. }
  1193. }
  1194. ress = append(ress, m)
  1195. }
  1196. defer func() {
  1197. if err := rows.Close(); err != nil {
  1198. log.Default().Printf("sqlx row close:%v", err)
  1199. }
  1200. }()
  1201. return ress, nil
  1202. }