sql_utils.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. package restful
  2. import (
  3. "database/sql"
  4. "errors"
  5. "fmt"
  6. "math"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "unsafe"
  11. "../../pkg/setting"
  12. _ "github.com/go-sql-driver/mysql"
  13. "github.com/patrickmn/go-cache"
  14. "github.com/tealeg/xlsx"
  15. "github.com/xormplus/xorm"
  16. )
  17. var (
  18. Engine *xorm.Engine
  19. Apisql_cache *cache.Cache
  20. )
  21. func SQLT() *xorm.Session {
  22. tx := Engine.NewSession()
  23. return tx
  24. }
  25. // SQLInit 初始化数据库操作句柄,这里要提供:
  26. // driverName string: 数据库类型,例如mysql、sqlite等,参考github.com/go-sql-driver/mysql官方介绍
  27. // dataSourceName string: 数据库地址,参考github.com/go-sql-driver/mysql官方介绍
  28. // MaxOpenConns int: 最大缓存连接数,这个数值包含了MaxIdleConns
  29. // MaxIdleConns int:预备的最大空闲连接数
  30. func SQLInit(driverName, dataSourceName string, maxOpenConns, maxIdleConns int, showlog bool) error {
  31. if Engine == nil {
  32. var err error
  33. if Engine, err = xorm.NewEngine(driverName, dataSourceName); err != nil {
  34. return err
  35. }
  36. if showlog {
  37. Engine.ShowSQL(true)
  38. }
  39. Engine.SetMaxIdleConns(maxIdleConns)
  40. Engine.SetMaxOpenConns(maxOpenConns)
  41. }
  42. if Apisql_cache == nil {
  43. Apisql_cache = cache.New(600*time.Second, 10*time.Second)
  44. SetCacheSql()
  45. }
  46. return nil
  47. }
  48. func SetCacheSql() {
  49. valuesMap, err := Engine.SQL("SELECT sqlname, CONCAT(sqlstr,'|',IFNULL(params,'')) AS sqlstr FROM apisql WHERE ENABLE>0 ").QueryString()
  50. if err == nil && len(valuesMap) > 0 {
  51. for _, v := range valuesMap {
  52. Apisql_cache.Set(v["sqlname"], v["sqlstr"], cache.DefaultExpiration)
  53. }
  54. }
  55. }
  56. func sqlCheckParam(param string) error {
  57. /*if strings.Contains(param, "where") {
  58. return errors.New("can not have where")
  59. }
  60. if strings.Contains(param, "and") {
  61. return errors.New("can not have and")
  62. }
  63. if strings.Contains(param, "or") {
  64. return errors.New("can not have or")
  65. }
  66. if strings.Contains(param, "=") {
  67. return errors.New("can not have =")
  68. }*/
  69. if strings.Contains(param, ";") {
  70. return errors.New("can not have ;")
  71. }
  72. return nil
  73. }
  74. func GetSqlByName(name string, tx *xorm.Session) (string, string) {
  75. sqls := ""
  76. param := ""
  77. if sql, ok := Apisql_cache.Get(name); ok {
  78. tempstrb := strings.IndexAny(sql.(string), "|")
  79. sqls = sql.(string)[0:tempstrb]
  80. param = sql.(string)[tempstrb+1:]
  81. } else {
  82. valuesMap, err := tx.SQL("SELECT sqlstr, params FROM apisql WHERE sqlname = ? AND ENABLE>0 ", name).QueryString()
  83. if err == nil && len(valuesMap) > 0 {
  84. sqls = valuesMap[0]["sqlstr"]
  85. param = valuesMap[0]["params"]
  86. Apisql_cache.Set(name, (sqls + "|" + param), cache.DefaultExpiration)
  87. }
  88. }
  89. if setting.DatabaseSetting.ShowGetSqllog {
  90. fmt.Println("==============")
  91. fmt.Println("apisql:" + sqls)
  92. fmt.Println("--------------")
  93. fmt.Println("param:" + param)
  94. fmt.Println("==============")
  95. }
  96. return sqls, param
  97. }
  98. func GetSqlByNameDB(name string) (string, string) {
  99. sqls := ""
  100. param := ""
  101. if sql, ok := Apisql_cache.Get(name); ok && setting.DatabaseSetting.CacheApiSql {
  102. tempstrb := strings.IndexAny(sql.(string), "|")
  103. sqls = sql.(string)[0:tempstrb]
  104. param = sql.(string)[tempstrb+1:]
  105. } else {
  106. valuesMap, err := Engine.SQL("SELECT sqlstr,params FROM apisql WHERE sqlname = ? AND ENABLE>0 ", name).QueryString()
  107. if err == nil && len(valuesMap) > 0 {
  108. sqls = valuesMap[0]["sqlstr"]
  109. param = valuesMap[0]["params"]
  110. Apisql_cache.Set(name, (sqls + "|" + param), cache.DefaultExpiration)
  111. }
  112. }
  113. if setting.DatabaseSetting.ShowGetSqllog {
  114. fmt.Println("==============")
  115. fmt.Println("apisql:" + sqls)
  116. fmt.Println("--------------")
  117. fmt.Println("param:" + param)
  118. fmt.Println("==============")
  119. }
  120. return sqls, param
  121. }
  122. func GetSqlByNameDBT(name string, tx *xorm.Session) (string, string) {
  123. sqls := ""
  124. param := ""
  125. if sql, ok := Apisql_cache.Get(name); ok && setting.DatabaseSetting.CacheApiSql {
  126. tempstrb := strings.IndexAny(sql.(string), "|")
  127. sqls = sql.(string)[0:tempstrb]
  128. param = sql.(string)[tempstrb+1:]
  129. } else {
  130. valuesMap, err := tx.SQL("SELECT sqlstr,params FROM apisql WHERE sqlname = ? AND ENABLE>0 ", name).QueryString()
  131. if err == nil && len(valuesMap) > 0 {
  132. sqls = valuesMap[0]["sqlstr"]
  133. param = valuesMap[0]["params"]
  134. Apisql_cache.Set(name, (sqls + "|" + param), cache.DefaultExpiration)
  135. }
  136. }
  137. if setting.DatabaseSetting.ShowGetSqllog {
  138. fmt.Println("==============")
  139. fmt.Println("apisql:" + sqls)
  140. fmt.Println("--------------")
  141. fmt.Println("param:" + param)
  142. fmt.Println("==============")
  143. }
  144. return sqls, param
  145. }
  146. // sqlGetValues 根据结构体中指向实际数据的指针获取出数据,并存储到另一张表中返回
  147. func sqlGetValues(pvs []interface{}, columnsType []*sql.ColumnType, columnsLen int) map[string]interface{} {
  148. result := make(map[string]interface{}, columnsLen)
  149. for a := 0; a < columnsLen; a++ {
  150. switch s := pvs[a].(type) {
  151. case *int8:
  152. result[columnsType[a].Name()] = *s
  153. case *int16:
  154. result[columnsType[a].Name()] = *s
  155. case *int32:
  156. result[columnsType[a].Name()] = *s
  157. case *int64:
  158. result[columnsType[a].Name()] = *s
  159. case *float32:
  160. result[columnsType[a].Name()] = *s
  161. case *float64:
  162. result[columnsType[a].Name()] = *s
  163. case *string:
  164. result[columnsType[a].Name()] = *s
  165. case *sql.NullInt64:
  166. result[columnsType[a].Name()] = *s
  167. case *sql.NullString:
  168. result[columnsType[a].Name()] = *s
  169. }
  170. }
  171. return result
  172. }
  173. // 这里返回的是原始数组的基础上加上了字段名标识
  174. func sqlQuery(columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) ([]map[string]interface{}, error) {
  175. jsondata := make([]map[string]interface{}, queryCount)
  176. for k1, v1 := range queryData {
  177. if k1 >= queryCount {
  178. break
  179. }
  180. jsondata[k1] = sqlGetValues(v1, columnsType, columnsLen)
  181. }
  182. return jsondata, nil
  183. }
  184. func sqlQueryByTinyIntMap(columnName string, columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) (map[int8]map[string]interface{}, error) {
  185. jsondata := make(map[int8]map[string]interface{}, queryCount)
  186. for k1, v1 := range queryData {
  187. if k1 >= queryCount {
  188. break
  189. }
  190. for a := 0; a < columnsLen; a++ {
  191. if columnsType[a].Name() == columnName {
  192. if value, ok := v1[a].(*int8); ok {
  193. jsondata[*value] = sqlGetValues(v1, columnsType, columnsLen)
  194. }
  195. break
  196. }
  197. }
  198. }
  199. return jsondata, nil
  200. }
  201. func sqlQueryBySmallIntMap(columnName string, columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) (map[int16]map[string]interface{}, error) {
  202. jsondata := make(map[int16]map[string]interface{}, queryCount)
  203. for k1, v1 := range queryData {
  204. if k1 >= queryCount {
  205. break
  206. }
  207. for a := 0; a < columnsLen; a++ {
  208. if columnsType[a].Name() == columnName {
  209. if value, ok := v1[a].(*int16); ok {
  210. jsondata[*value] = sqlGetValues(v1, columnsType, columnsLen)
  211. }
  212. break
  213. }
  214. }
  215. }
  216. return jsondata, nil
  217. }
  218. func sqlQueryByIntMap(columnName string, columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) (map[int32]map[string]interface{}, error) {
  219. jsondata := make(map[int32]map[string]interface{}, queryCount)
  220. for k1, v1 := range queryData {
  221. if k1 >= queryCount {
  222. break
  223. }
  224. for a := 0; a < columnsLen; a++ {
  225. if columnsType[a].Name() == columnName {
  226. if value, ok := v1[a].(*int32); ok {
  227. jsondata[*value] = sqlGetValues(v1, columnsType, columnsLen)
  228. }
  229. break
  230. }
  231. }
  232. }
  233. return jsondata, nil
  234. }
  235. func sqlQueryByBigIntMap(columnName string, columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) (map[int64]map[string]interface{}, error) {
  236. jsondata := make(map[int64]map[string]interface{}, queryCount)
  237. for k1, v1 := range queryData {
  238. if k1 >= queryCount {
  239. break
  240. }
  241. for a := 0; a < columnsLen; a++ {
  242. if columnsType[a].Name() == columnName {
  243. if value, ok := v1[a].(*int64); ok {
  244. jsondata[*value] = sqlGetValues(v1, columnsType, columnsLen)
  245. }
  246. break
  247. }
  248. }
  249. }
  250. return jsondata, nil
  251. }
  252. func sqlQueryByFloatIntMap(columnName string, columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) (map[float32]map[string]interface{}, error) {
  253. jsondata := make(map[float32]map[string]interface{}, queryCount)
  254. for k1, v1 := range queryData {
  255. if k1 >= queryCount {
  256. break
  257. }
  258. for a := 0; a < columnsLen; a++ {
  259. if columnsType[a].Name() == columnName {
  260. if value, ok := v1[a].(*float32); ok {
  261. jsondata[*value] = sqlGetValues(v1, columnsType, columnsLen)
  262. }
  263. break
  264. }
  265. }
  266. }
  267. return jsondata, nil
  268. }
  269. func sqlQueryByDoubleMap(columnName string, columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) (map[float64]map[string]interface{}, error) {
  270. jsondata := make(map[float64]map[string]interface{}, queryCount)
  271. for k1, v1 := range queryData {
  272. if k1 >= queryCount {
  273. break
  274. }
  275. for a := 0; a < columnsLen; a++ {
  276. if columnsType[a].Name() == columnName {
  277. if value, ok := v1[a].(*float64); ok {
  278. jsondata[*value] = sqlGetValues(v1, columnsType, columnsLen)
  279. }
  280. break
  281. }
  282. }
  283. }
  284. return jsondata, nil
  285. }
  286. func sqlQueryByStringMap(columnName string, columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) (map[string]map[string]interface{}, error) {
  287. jsondata := make(map[string]map[string]interface{}, queryCount)
  288. for k1, v1 := range queryData {
  289. if k1 >= queryCount {
  290. break
  291. }
  292. for a := 0; a < columnsLen; a++ {
  293. if columnsType[a].Name() == columnName {
  294. if value, ok := v1[a].(*string); ok {
  295. jsondata[*value] = sqlGetValues(v1, columnsType, columnsLen)
  296. }
  297. break
  298. }
  299. }
  300. }
  301. return jsondata, nil
  302. }
  303. func sqlGetColumnType(columnsType []*sql.ColumnType, columnsLen int, valueName string) string {
  304. for a := 0; a < columnsLen; a++ {
  305. if columnsType[a].Name() == valueName {
  306. return columnsType[a].DatabaseTypeName()
  307. }
  308. }
  309. return ""
  310. }
  311. func round(num float64) int {
  312. return int(num + math.Copysign(0.5, num))
  313. }
  314. func toFixed(num float64, precision int) float64 {
  315. output := math.Pow(10, float64(precision))
  316. return float64(round(num*output)) / output
  317. }
  318. // QueryByMap 将查询到的数据,按照指定字段的值做为索引构建map并返回
  319. // columnName string: 作为索引的字段名称
  320. // sql string: 查询需要获取哪些字段的值,就是select后面跟着的部分,一般用"*"
  321. // where string: 过滤条件,就是where后面跟着的部分
  322. // order string: 排序条件,就是order by后面跟着的部分。默认是ASC排序,除非"-"开头则DESC排序
  323. // offset string: limit后面逗号相隔的两个数值,前者就是offset,后者就是count
  324. // count string: limit后面逗号相隔的两个数值,前者就是offset,后者就是count
  325. func QueryByMap(sqlstr string, offset, count int, params []interface{}) (interface{}, error) {
  326. if err := sqlCheckParam(sqlstr); err != nil {
  327. return 0, err
  328. }
  329. recordcount := int64(0)
  330. if count > 1 {
  331. tt, err := Engine.SQL("SELECT COUNT(*) as count FROM ("+sqlstr+") a", params...).Query().List()
  332. if err != nil {
  333. fmt.Println("s1", err)
  334. return nil, err
  335. }
  336. if tt == nil {
  337. recordcount = 0
  338. } else {
  339. recordcount = tt[0]["count"].(int64)
  340. }
  341. }
  342. queryData := make([]map[string]interface{}, 1)
  343. var err error
  344. if count == 0 {
  345. queryData, err = Engine.SQL(sqlstr, params...).Query().List()
  346. } else {
  347. if count > 0 && offset > 0 {
  348. offset = offset * count
  349. }
  350. queryData, err = Engine.SQL(sqlstr, params...).Limit(count, offset).Query().List()
  351. }
  352. //fmt.Println("count, offset==================",count, offset)
  353. if err != nil {
  354. return nil, err
  355. }
  356. if recordcount == 0 {
  357. recordcount = int64(len(queryData))
  358. }
  359. data := make(map[string]interface{})
  360. data["list"] = queryData
  361. data["total"] = recordcount
  362. data["code"] = 0
  363. data["message"] = "ok"
  364. if count > 0 {
  365. data["pages"] = math.Ceil(float64(recordcount) / float64(count))
  366. data["pageNum"] = math.Ceil(float64(offset+1) / float64(count))
  367. }
  368. data["pageSize"] = count
  369. return data, nil
  370. }
  371. func QueryByMapT(sqlstr string, offset, count int, params []interface{}, tx *xorm.Session) (interface{}, error) {
  372. if err := sqlCheckParam(sqlstr); err != nil {
  373. return 0, err
  374. }
  375. recordcount := int64(0)
  376. if count > 1 {
  377. tt, err := tx.SQL("SELECT COUNT(*) as count FROM ("+sqlstr+") a", params...).Query().List()
  378. if err != nil {
  379. fmt.Println("s1", err)
  380. return nil, err
  381. }
  382. if tt == nil {
  383. recordcount = 0
  384. } else {
  385. switch tt[0]["count"].(type) {
  386. case int64:
  387. recordcount = tt[0]["count"].(int64)
  388. case string:
  389. temp, _ := strconv.Atoi(tt[0]["count"].(string))
  390. recordcount = int64(temp)
  391. }
  392. }
  393. }
  394. queryData := make([]map[string]interface{}, 1)
  395. var err error
  396. if count == 0 {
  397. queryData, err = tx.SQL(sqlstr, params...).Query().List()
  398. } else {
  399. if count > 0 && offset > 0 {
  400. offset = offset * count
  401. }
  402. queryData, err = tx.SQL(sqlstr, params...).Limit(count, offset).Query().List()
  403. }
  404. //fmt.Println("count, offset==================",count, offset)
  405. if err != nil {
  406. return nil, err
  407. }
  408. if recordcount == 0 {
  409. recordcount = int64(len(queryData))
  410. }
  411. data := make(map[string]interface{})
  412. data["list"] = queryData
  413. data["total"] = recordcount
  414. data["code"] = 0
  415. data["message"] = "ok"
  416. if count > 0 {
  417. data["pages"] = math.Ceil(float64(recordcount) / float64(count))
  418. data["pageNum"] = math.Ceil(float64(offset+1) / float64(count))
  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 := Engine.SQL(sqlstr, params...).QueryRows()
  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 := Engine.SQL(sqlstr, params...).QueryRows()
  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. //return Engine.SQL(sqlstr, params...).Query().List()
  546. }
  547. func QueryByList(sqlstr string, offset, count int, params []interface{}) (interface{}, error) {
  548. if err := sqlCheckParam(sqlstr); err != nil {
  549. return 0, err
  550. }
  551. if count == 0 {
  552. count = 1000
  553. }
  554. recordcount := int64(0)
  555. if count > 1 {
  556. tt, err := Engine.SQL("SELECT COUNT(*) as count FROM ("+sqlstr+") a", params...).Query().List()
  557. if err != nil {
  558. return nil, err
  559. }
  560. recordcount = tt[0]["count"].(int64)
  561. }
  562. queryData := make([]map[string]interface{}, 1)
  563. var err error
  564. if count == 0 {
  565. queryData, err = Engine.SQL(sqlstr, params...).Query().List()
  566. } else {
  567. if count > 0 && offset > 0 {
  568. offset = offset * count
  569. }
  570. queryData, err = Engine.SQL(sqlstr, params...).Limit(count, offset).Query().List()
  571. }
  572. if err != nil {
  573. return nil, err
  574. }
  575. columnsname := make([]string, 0)
  576. listdata := make(map[string][]interface{})
  577. if len(queryData) > 0 {
  578. for i, _ := range queryData {
  579. if i == 0 {
  580. for i, _ := range queryData[0] {
  581. columnsname = append(columnsname, i)
  582. }
  583. }
  584. for _, v := range columnsname {
  585. listdata[v] = append(listdata[v], queryData[i][v])
  586. }
  587. }
  588. recordcount = int64(len(queryData))
  589. }
  590. data := make(map[string]interface{})
  591. data["lists"] = listdata
  592. //data["columnsname"] = columnsname
  593. data["total"] = recordcount
  594. data["code"] = 0
  595. data["message"] = "ok"
  596. if count > 0 {
  597. data["pages"] = math.Ceil(float64(recordcount) / float64(count))
  598. data["pageNum"] = math.Ceil(float64(offset+1) / float64(count))
  599. }
  600. data["pageSize"] = count
  601. return data, nil
  602. }
  603. func QueryByListList(sqlstr string, offset, count int, params []interface{}) (interface{}, error) {
  604. if err := sqlCheckParam(sqlstr); err != nil {
  605. return 0, err
  606. }
  607. if count == 0 {
  608. count = 1000
  609. }
  610. recordcount := int64(0)
  611. if count > 1 {
  612. tt, err := Engine.SQL("SELECT COUNT(*) as count FROM ("+sqlstr+") a", params...).Query().List()
  613. if err != nil {
  614. return nil, err
  615. }
  616. recordcount = tt[0]["count"].(int64)
  617. }
  618. queryData := make([]map[string]interface{}, 1)
  619. var err error
  620. if count == 0 {
  621. queryData, err = Engine.SQL(sqlstr, params...).Query().List()
  622. } else {
  623. if count > 0 && offset > 0 {
  624. offset = offset * count
  625. }
  626. queryData, err = Engine.SQL(sqlstr, params...).Limit(count, offset).Query().List()
  627. }
  628. if err != nil {
  629. return nil, err
  630. }
  631. columnsname := make([]string, 0)
  632. listdata := make([]interface{}, 0)
  633. if len(queryData) > 0 {
  634. for i, _ := range queryData {
  635. if i == 0 {
  636. for i, _ := range queryData[0] {
  637. columnsname = append(columnsname, i)
  638. }
  639. }
  640. listdatarow := make([]interface{}, 0)
  641. for _, v := range columnsname {
  642. listdatarow = append(listdatarow, queryData[i][v])
  643. }
  644. listdata = append(listdata, listdatarow)
  645. }
  646. recordcount = int64(len(queryData))
  647. }
  648. data := make(map[string]interface{})
  649. data["list"] = listdata
  650. data["columnsname"] = columnsname
  651. data["total"] = recordcount
  652. data["code"] = 0
  653. data["message"] = "ok"
  654. if count > 0 {
  655. data["pages"] = math.Ceil(float64(recordcount) / float64(count))
  656. data["pageNum"] = math.Ceil(float64(offset+1) / float64(count))
  657. }
  658. data["pageSize"] = count
  659. return data, nil
  660. }
  661. func QueryByLineChart(sqlstr string, offset, count int, params []interface{}, tx *xorm.Session) (interface{}, error) {
  662. if err := sqlCheckParam(sqlstr); err != nil {
  663. return 0, err
  664. }
  665. queryData := make([]map[string]interface{}, 1)
  666. var err error
  667. queryData, err = tx.SQL(sqlstr, params...).Query().List()
  668. //fmt.Println("sql========\n", queryData)
  669. if err != nil {
  670. return nil, err
  671. }
  672. var arr1 []interface{}
  673. var arr2 []interface{}
  674. for i := 0; i < len(queryData); i++ {
  675. if queryData[i]["type"] == "1" {
  676. arr1 = append(arr1, queryData[i]["cost"])
  677. } else {
  678. arr2 = append(arr2, queryData[i]["cost"])
  679. }
  680. }
  681. chartline1_data := make(map[string]interface{})
  682. data := make(map[string]interface{})
  683. chartline1_data["arr1"] = arr1
  684. chartline1_data["arr2"] = arr2
  685. data["chartline1_data"] = chartline1_data
  686. data["code"] = 0
  687. data["message"] = "ok"
  688. return data, nil
  689. }
  690. func QueryByListT(sqlstr string, offset, count int, params []interface{}, tx *xorm.Session) (interface{}, error) {
  691. if err := sqlCheckParam(sqlstr); err != nil {
  692. return 0, err
  693. }
  694. if count == 0 {
  695. count = 1000
  696. }
  697. recordcount := int64(0)
  698. if count > 1 {
  699. tt, err := tx.SQL("SELECT COUNT(*) as count FROM ("+sqlstr+") a", params...).Query().List()
  700. if err != nil {
  701. return nil, err
  702. }
  703. switch tt[0]["count"].(type) {
  704. case int64:
  705. recordcount = tt[0]["count"].(int64)
  706. case string:
  707. temp, _ := strconv.Atoi(tt[0]["count"].(string))
  708. recordcount = int64(temp)
  709. }
  710. }
  711. queryData := make([]map[string]interface{}, 1)
  712. var err error
  713. if count == 0 {
  714. queryData, err = tx.SQL(sqlstr, params...).Query().List()
  715. } else {
  716. if count > 0 && offset > 0 {
  717. offset = offset * count
  718. }
  719. queryData, err = tx.SQL(sqlstr, params...).Limit(count, offset).Query().List()
  720. }
  721. if err != nil {
  722. return nil, err
  723. }
  724. columnsname := make([]string, 0)
  725. listdata := make(map[string][]interface{})
  726. if len(queryData) > 0 {
  727. for i, _ := range queryData {
  728. if i == 0 {
  729. for i, _ := range queryData[0] {
  730. columnsname = append(columnsname, i)
  731. }
  732. }
  733. for _, v := range columnsname {
  734. listdata[v] = append(listdata[v], queryData[i][v])
  735. }
  736. }
  737. recordcount = int64(len(queryData))
  738. }
  739. data := make(map[string]interface{})
  740. data["lists"] = listdata
  741. //data["columnsname"] = columnsname
  742. data["total"] = recordcount
  743. data["code"] = 0
  744. data["message"] = "ok"
  745. if count > 0 {
  746. data["pages"] = math.Ceil(float64(recordcount) / float64(count))
  747. data["pageNum"] = math.Ceil(float64(offset+1) / float64(count))
  748. }
  749. data["pageSize"] = count
  750. return data, nil
  751. }
  752. func QueryByListListT(sqlstr string, offset, count int, params []interface{}, tx *xorm.Session) (interface{}, error) {
  753. if err := sqlCheckParam(sqlstr); err != nil {
  754. return 0, err
  755. }
  756. if count == 0 {
  757. count = 1000
  758. }
  759. recordcount := int64(0)
  760. if count > 1 {
  761. tt, err := tx.SQL("SELECT COUNT(*) as count FROM ("+sqlstr+") a", params...).Query().List()
  762. if err != nil {
  763. return nil, err
  764. }
  765. switch tt[0]["count"].(type) {
  766. case int64:
  767. recordcount = tt[0]["count"].(int64)
  768. case string:
  769. temp, _ := strconv.Atoi(tt[0]["count"].(string))
  770. recordcount = int64(temp)
  771. }
  772. }
  773. queryData := make([]map[string]interface{}, 1)
  774. var err error
  775. if count == 0 {
  776. queryData, err = tx.SQL(sqlstr, params...).Query().List()
  777. } else {
  778. if count > 0 && offset > 0 {
  779. offset = offset * count
  780. }
  781. queryData, err = tx.SQL(sqlstr, params...).Limit(count, offset).Query().List()
  782. }
  783. if err != nil {
  784. return nil, err
  785. }
  786. columnsname := make([]string, 0)
  787. listdata := make([]interface{}, 0)
  788. if len(queryData) > 0 {
  789. for i, _ := range queryData {
  790. if i == 0 {
  791. for i, _ := range queryData[0] {
  792. columnsname = append(columnsname, i)
  793. }
  794. }
  795. listdatarow := make([]interface{}, 0)
  796. for _, v := range columnsname {
  797. listdatarow = append(listdatarow, queryData[i][v])
  798. }
  799. listdata = append(listdata, listdatarow)
  800. }
  801. recordcount = int64(len(queryData))
  802. }
  803. data := make(map[string]interface{})
  804. data["list"] = listdata
  805. data["columnsname"] = columnsname
  806. data["total"] = recordcount
  807. data["code"] = 0
  808. data["message"] = "ok"
  809. if count > 0 {
  810. data["pages"] = math.Ceil(float64(recordcount) / float64(count))
  811. data["pageNum"] = math.Ceil(float64(offset+1) / float64(count))
  812. }
  813. data["pageSize"] = count
  814. return data, nil
  815. }
  816. func ExecQuery(sqlstr string, params []interface{}) (interface{}, error) {
  817. if err := sqlCheckParam(sqlstr); err != nil {
  818. return 0, err
  819. }
  820. rows, err := Engine.SQL(sqlstr, params...).Execute()
  821. if err != nil {
  822. return nil, err
  823. }
  824. data := make(map[string]interface{})
  825. LastInsertId, _ := rows.LastInsertId()
  826. idPointer := (*int)(unsafe.Pointer(&LastInsertId))
  827. idd16 := *idPointer
  828. RowsAffected, _ := rows.RowsAffected()
  829. _idPointer := (*int)(unsafe.Pointer(&RowsAffected))
  830. _idd16 := *_idPointer
  831. data["result"] = rows
  832. data["LastInsertId"] = idd16
  833. data["RowsAffected"] = _idd16
  834. return data, nil
  835. }
  836. func ExecQueryT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  837. if err := sqlCheckParam(sqlstr); err != nil {
  838. return 0, err
  839. }
  840. rows, err := tx.SQL(sqlstr, params...).Execute()
  841. if err != nil {
  842. fmt.Println("exe", err)
  843. return nil, err
  844. }
  845. LastInsertId, _ := rows.LastInsertId()
  846. idPointer := (*int)(unsafe.Pointer(&LastInsertId))
  847. idd16 := *idPointer
  848. data := make(map[string]interface{})
  849. RowsAffected, _ := rows.RowsAffected()
  850. _idPointer := (*int)(unsafe.Pointer(&RowsAffected))
  851. _idd16 := *_idPointer
  852. data["LastInsertId"] = idd16
  853. data["RowsAffected"] = _idd16
  854. data["result"] = rows
  855. return data, nil
  856. }
  857. func ExecQuerys(sqlstr string, params []interface{}) (interface{}, error) {
  858. if err := sqlCheckParam(sqlstr); err != nil {
  859. return 0, err
  860. }
  861. /*for i, v := range params{
  862. _, err := dbs.Exec(sqlstr, v[i]...)
  863. if err != nil {
  864. return nil, err
  865. }
  866. }
  867. */
  868. data := make(map[string]interface{})
  869. data["result"] = nil
  870. return data, nil
  871. }
  872. func getValue(value interface{}, CT string) interface{} {
  873. var v interface{}
  874. val := value
  875. b, ok := val.([]byte)
  876. if ok {
  877. v1 := string(b)
  878. switch CT {
  879. case "TINYINT", "SMALLINT", "MEDIUMINT", "INT", "INTEGER", "BIGINT":
  880. {
  881. v, _ = strconv.ParseInt(v1, 10, 32)
  882. }
  883. case "FLOAT", "DOUBLE", "DECIMAL":
  884. {
  885. cindex := len(val.([]byte)) - strings.Index(v1, ".") - 1
  886. v2, _ := strconv.ParseFloat(v1, 32)
  887. v = toFixed(v2, cindex)
  888. }
  889. case "BOOL":
  890. {
  891. v, _ = strconv.ParseBool(v1)
  892. }
  893. default:
  894. {
  895. v = v1
  896. }
  897. }
  898. } else {
  899. v = val
  900. }
  901. return v
  902. }