d27fa538b3e7bd48979dd96c806693c53951ecda.svn-base 25 KB

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