sql_utils.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359
  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 MapInterList(sql string, param ...interface{}) ([]map[string]interface{}, error) {
  1112. ress := make([]map[string]interface{}, 0, 0)
  1113. rows, err := Dbs.Queryx(sql, param...)
  1114. if err != nil {
  1115. log.Default().Printf("MapInterList Queryx: %v", err)
  1116. return ress, err
  1117. }
  1118. col, err := rows.Columns()
  1119. if err != nil {
  1120. log.Default().Printf("BigpartUse clolumns: %v", err)
  1121. return ress, err
  1122. }
  1123. for rows.Next() {
  1124. m := make(map[string]interface{})
  1125. rs, err := rows.SliceScan()
  1126. if err != nil {
  1127. log.Default().Printf("BigpartUse SliceScan: %v", err)
  1128. return ress, err
  1129. }
  1130. for i, r := range rs {
  1131. switch r.(type) {
  1132. case []uint8:
  1133. m[col[i]] = string(r.([]uint8))
  1134. case int64:
  1135. m[col[i]] = r.(int64)
  1136. }
  1137. }
  1138. ress = append(ress, m)
  1139. }
  1140. defer func() {
  1141. if err := rows.Close(); err != nil {
  1142. log.Default().Printf("sqlx row close:%v", err)
  1143. }
  1144. }()
  1145. return ress, nil
  1146. }
  1147. func BasicList(sql string, params []interface{}, res ...interface{}) error {
  1148. // fmt.Printf("%s\n", sql)
  1149. if params == nil {
  1150. params = make([]interface{}, 0)
  1151. }
  1152. // var count int
  1153. tt, err := Dbs.Queryx(sql, params...)
  1154. if err != nil {
  1155. fmt.Println("s1", err)
  1156. return err
  1157. }
  1158. if tt.Next() {
  1159. tt.Scan(res...)
  1160. // tt.Scan(&count)
  1161. }
  1162. defer func() {
  1163. if err := tt.Close(); err != nil {
  1164. log.Default().Printf("sqlx row close:%v", err)
  1165. }
  1166. }()
  1167. return nil
  1168. }
  1169. func MapStr(sql string, param ...interface{}) (map[string]string, error) {
  1170. m := make(map[string]string)
  1171. rows, err := Dbs.Queryx(sql, param...)
  1172. if err != nil {
  1173. log.Default().Printf("MapStr Queryx: %v", err)
  1174. return m, err
  1175. }
  1176. col, err := rows.Columns()
  1177. if err != nil {
  1178. log.Default().Printf("BigpartUse clolumns: %v", err)
  1179. return m, err
  1180. }
  1181. if rows.Next() {
  1182. rs, err := rows.SliceScan()
  1183. if err != nil {
  1184. log.Default().Printf("BigpartUse SliceScan: %v", err)
  1185. return m, err
  1186. }
  1187. for i, r := range rs {
  1188. switch r.(type) {
  1189. case []uint8:
  1190. m[col[i]] = string(r.([]uint8))
  1191. case int64:
  1192. m[col[i]] = strconv.FormatInt(r.(int64), 10)
  1193. }
  1194. }
  1195. }
  1196. defer func() {
  1197. if err := rows.Close(); err != nil {
  1198. log.Default().Printf("sqlx row close:%v", err)
  1199. }
  1200. }()
  1201. return m, nil
  1202. }
  1203. func MapStrListTx(tx *sqlx.Tx, sql string, param ...interface{}) ([]map[string]string, error) {
  1204. ress := make([]map[string]string, 0, 0)
  1205. rows, err := tx.Queryx(sql, param...)
  1206. if err != nil {
  1207. log.Default().Printf("MapStrListTx Queryx: %v", err)
  1208. return ress, err
  1209. }
  1210. col, err := rows.Columns()
  1211. if err != nil {
  1212. log.Default().Printf("BigpartUse clolumns: %v", err)
  1213. return ress, err
  1214. }
  1215. for rows.Next() {
  1216. m := make(map[string]string)
  1217. rs, err := rows.SliceScan()
  1218. if err != nil {
  1219. log.Default().Printf("BigpartUse SliceScan: %v", err)
  1220. return ress, err
  1221. }
  1222. for i, r := range rs {
  1223. switch r.(type) {
  1224. case []uint8:
  1225. m[col[i]] = string(r.([]uint8))
  1226. case int64:
  1227. m[col[i]] = strconv.FormatInt(r.(int64), 10)
  1228. }
  1229. }
  1230. ress = append(ress, m)
  1231. }
  1232. defer func() {
  1233. if err := rows.Close(); err != nil {
  1234. log.Default().Printf("sqlx row close:%v", err)
  1235. }
  1236. }()
  1237. return ress, nil
  1238. }