sql_utils.go 35 KB

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