0e5b087e8326f92854914e3b994048d49a537bf0.svn-base 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  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("==============")
  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 QueryByListT(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. if(count==0){
  666. count = 1000
  667. }
  668. recordcount := int64(0)
  669. if count > 1 {
  670. tt, err := tx.SQL("SELECT COUNT(*) as count FROM ("+sqlstr+") a", params...).Query().List()
  671. if err != nil {
  672. return nil, err
  673. }
  674. switch tt[0]["count"].(type) {
  675. case int64 :
  676. recordcount = tt[0]["count"].(int64)
  677. case string :
  678. temp,_ :=strconv.Atoi(tt[0]["count"].(string))
  679. recordcount = int64(temp)
  680. }
  681. }
  682. queryData := make([]map[string]interface{},1)
  683. var err error
  684. if(count==0){
  685. queryData, err = tx.SQL(sqlstr, params...).Query().List()
  686. } else {
  687. if count > 0 && offset > 0 {
  688. offset = offset * count
  689. }
  690. queryData, err = tx.SQL(sqlstr, params...).Limit(count, offset).Query().List()
  691. }
  692. if err != nil {
  693. return nil, err
  694. }
  695. columnsname := make([]string, 0)
  696. listdata := make(map[string][]interface{})
  697. if len(queryData) > 0 {
  698. for i, _ := range queryData {
  699. if i == 0 {
  700. for i, _ := range queryData[0] {
  701. columnsname = append(columnsname, i)
  702. }
  703. }
  704. for _, v := range columnsname {
  705. listdata[v] = append(listdata[v], queryData[i][v])
  706. }
  707. }
  708. recordcount = int64(len(queryData))
  709. }
  710. data := make(map[string]interface{})
  711. data["lists"] = listdata
  712. //data["columnsname"] = columnsname
  713. data["total"] = recordcount
  714. data["code"] = 0
  715. data["message"] = "ok"
  716. if count > 0 {
  717. data["pages"] = math.Ceil(float64(recordcount) / float64(count))
  718. data["pageNum"] = math.Ceil(float64(offset+1) / float64(count))
  719. }
  720. data["pageSize"] = count
  721. return data, nil
  722. }
  723. func QueryByListListT(sqlstr string, offset, count int, params []interface{}, tx *xorm.Session) (interface{}, error) {
  724. if err := sqlCheckParam(sqlstr); err != nil {
  725. return 0, err
  726. }
  727. if(count==0){
  728. count = 1000
  729. }
  730. recordcount := int64(0)
  731. if count > 1 {
  732. tt, err := tx.SQL("SELECT COUNT(*) as count FROM ("+sqlstr+") a", params...).Query().List()
  733. if err != nil {
  734. return nil, err
  735. }
  736. switch tt[0]["count"].(type) {
  737. case int64 :
  738. recordcount = tt[0]["count"].(int64)
  739. case string :
  740. temp,_ :=strconv.Atoi(tt[0]["count"].(string))
  741. recordcount = int64(temp)
  742. }
  743. }
  744. queryData := make([]map[string]interface{},1)
  745. var err error
  746. if(count==0){
  747. queryData, err = tx.SQL(sqlstr, params...).Query().List()
  748. } else {
  749. if count > 0 && offset > 0 {
  750. offset = offset * count
  751. }
  752. queryData, err = tx.SQL(sqlstr, params...).Limit(count, offset).Query().List()
  753. }
  754. if err != nil {
  755. return nil, err
  756. }
  757. columnsname := make([]string, 0)
  758. listdata := make([]interface{}, 0)
  759. if len(queryData) > 0 {
  760. for i, _ := range queryData {
  761. if i == 0 {
  762. for i, _ := range queryData[0] {
  763. columnsname = append(columnsname, i)
  764. }
  765. }
  766. listdatarow := make([]interface{}, 0)
  767. for _, v := range columnsname {
  768. listdatarow = append(listdatarow, queryData[i][v])
  769. }
  770. listdata = append(listdata, listdatarow)
  771. }
  772. recordcount = int64(len(queryData))
  773. }
  774. data := make(map[string]interface{})
  775. data["list"] = listdata
  776. data["columnsname"] = columnsname
  777. data["total"] = recordcount
  778. data["code"] = 0
  779. data["message"] = "ok"
  780. if count > 0 {
  781. data["pages"] = math.Ceil(float64(recordcount) / float64(count))
  782. data["pageNum"] = math.Ceil(float64(offset+1) / float64(count))
  783. }
  784. data["pageSize"] = count
  785. return data, nil
  786. }
  787. func ExecQuery(sqlstr string, params []interface{}) (interface{}, error) {
  788. if err := sqlCheckParam(sqlstr); err != nil {
  789. return 0, err
  790. }
  791. rows, err := Engine.SQL(sqlstr, params...).Execute()
  792. if err != nil {
  793. return nil, err
  794. }
  795. data := make(map[string]interface{})
  796. LastInsertId, _ := rows.LastInsertId()
  797. idPointer := (*int)(unsafe.Pointer(&LastInsertId))
  798. idd16 := *idPointer
  799. RowsAffected, _ := rows.RowsAffected()
  800. _idPointer := (*int)(unsafe.Pointer(&RowsAffected))
  801. _idd16 := *_idPointer
  802. data["result"] = rows
  803. data["LastInsertId"] = idd16
  804. data["RowsAffected"] = _idd16
  805. return data, nil
  806. }
  807. func ExecQueryT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  808. if err := sqlCheckParam(sqlstr); err != nil {
  809. return 0, err
  810. }
  811. rows, err := tx.SQL(sqlstr, params...).Execute()
  812. if err != nil {
  813. fmt.Println("exe", err)
  814. return nil, err
  815. }
  816. LastInsertId, _ := rows.LastInsertId()
  817. idPointer := (*int)(unsafe.Pointer(&LastInsertId))
  818. idd16 := *idPointer
  819. data := make(map[string]interface{})
  820. RowsAffected, _ := rows.RowsAffected()
  821. _idPointer := (*int)(unsafe.Pointer(&RowsAffected))
  822. _idd16 := *_idPointer
  823. data["LastInsertId"] =strconv.Itoa(idd16)
  824. data["LastInsertIdStr"] =idd16
  825. data["RowsAffected"] = _idd16
  826. data["result"] = rows
  827. return data, nil
  828. }
  829. func ExecQuerys(sqlstr string, params []interface{}) (interface{}, error) {
  830. if err := sqlCheckParam(sqlstr); err != nil {
  831. return 0, err
  832. }
  833. /*for i, v := range params{
  834. _, err := dbs.Exec(sqlstr, v[i]...)
  835. if err != nil {
  836. return nil, err
  837. }
  838. }
  839. */
  840. data := make(map[string]interface{})
  841. data["result"] = nil
  842. return data, nil
  843. }
  844. func getValue(value interface{}, CT string) interface{} {
  845. var v interface{}
  846. val := value
  847. b, ok := val.([]byte)
  848. if ok {
  849. v1 := string(b)
  850. switch CT {
  851. case "TINYINT", "SMALLINT", "MEDIUMINT", "INT", "INTEGER", "BIGINT":
  852. {
  853. v, _ = strconv.ParseInt(v1, 10, 32)
  854. }
  855. case "FLOAT", "DOUBLE", "DECIMAL":
  856. {
  857. cindex := len(val.([]byte)) - strings.Index(v1, ".") - 1
  858. v2, _ := strconv.ParseFloat(v1, 32)
  859. v = toFixed(v2, cindex)
  860. }
  861. case "BOOL":
  862. {
  863. v, _ = strconv.ParseBool(v1)
  864. }
  865. default:
  866. {
  867. v = v1
  868. }
  869. }
  870. } else {
  871. v = val
  872. }
  873. return v
  874. }