sql_utils.go 27 KB

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