session_plus.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  1. // Copyright 2015 The Xorm Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package xorm
  5. import (
  6. "database/sql"
  7. "encoding/json"
  8. "fmt"
  9. "os"
  10. "reflect"
  11. "regexp"
  12. "strings"
  13. "time"
  14. "github.com/Chronokeeper/anyxml"
  15. "github.com/xormplus/core"
  16. )
  17. type Record map[string]Value
  18. type Result []Record
  19. type ResultValue struct {
  20. Result Result
  21. Error error
  22. }
  23. func (resultValue *ResultValue) List() (Result, error) {
  24. return resultValue.Result, resultValue.Error
  25. }
  26. func (resultValue *ResultValue) Count() (int, error) {
  27. if resultValue.Error != nil {
  28. return 0, resultValue.Error
  29. }
  30. if resultValue.Result == nil {
  31. return 0, nil
  32. }
  33. return len(resultValue.Result), nil
  34. }
  35. func (resultValue *ResultValue) ListPage(firstResult int, maxResults int) (Result, error) {
  36. if resultValue.Error != nil {
  37. return nil, resultValue.Error
  38. }
  39. if resultValue.Result == nil {
  40. return nil, nil
  41. }
  42. if firstResult > maxResults {
  43. return nil, ErrParamsFormat
  44. }
  45. if firstResult < 0 {
  46. return nil, ErrParamsFormat
  47. }
  48. if maxResults < 0 {
  49. return nil, ErrParamsFormat
  50. }
  51. if maxResults > len(resultValue.Result) {
  52. return nil, ErrParamsFormat
  53. }
  54. return resultValue.Result[(firstResult - 1):maxResults], resultValue.Error
  55. }
  56. type ResultBean struct {
  57. Has bool
  58. Result interface{}
  59. Error error
  60. }
  61. func (resultBean *ResultBean) Json() (bool, string, error) {
  62. if resultBean.Error != nil {
  63. return resultBean.Has, "", resultBean.Error
  64. }
  65. if !resultBean.Has {
  66. return resultBean.Has, "", nil
  67. }
  68. result, err := JSONString(resultBean.Result, true)
  69. return resultBean.Has, result, err
  70. }
  71. func (resultBean *ResultBean) GetResult() (bool, interface{}, error) {
  72. return resultBean.Has, resultBean.Result, resultBean.Error
  73. }
  74. func (session *Session) GetFirst(bean interface{}) *ResultBean {
  75. has, err := session.Get(bean)
  76. r := &ResultBean{Has: has, Result: bean, Error: err}
  77. return r
  78. }
  79. func (resultBean *ResultBean) Xml() (bool, string, error) {
  80. if resultBean.Error != nil {
  81. return false, "", resultBean.Error
  82. }
  83. if !resultBean.Has {
  84. return resultBean.Has, "", nil
  85. }
  86. has, result, err := resultBean.Json()
  87. if err != nil {
  88. return false, "", err
  89. }
  90. if !has {
  91. return has, "", nil
  92. }
  93. var anydata = []byte(result)
  94. var i interface{}
  95. err = json.Unmarshal(anydata, &i)
  96. if err != nil {
  97. return false, "", err
  98. }
  99. resultByte, err := anyxml.Xml(i)
  100. if err != nil {
  101. return false, "", err
  102. }
  103. return resultBean.Has, string(resultByte), err
  104. }
  105. func (resultBean *ResultBean) XmlIndent(prefix string, indent string, recordTag string) (bool, string, error) {
  106. if resultBean.Error != nil {
  107. return false, "", resultBean.Error
  108. }
  109. if !resultBean.Has {
  110. return resultBean.Has, "", nil
  111. }
  112. has, result, err := resultBean.Json()
  113. if err != nil {
  114. return false, "", err
  115. }
  116. if !has {
  117. return has, "", nil
  118. }
  119. var anydata = []byte(result)
  120. var i interface{}
  121. err = json.Unmarshal(anydata, &i)
  122. if err != nil {
  123. return false, "", err
  124. }
  125. resultByte, err := anyxml.XmlIndent(i, prefix, indent, recordTag)
  126. if err != nil {
  127. return false, "", err
  128. }
  129. return resultBean.Has, string(resultByte), err
  130. }
  131. type ResultMap struct {
  132. Result []map[string]interface{}
  133. Error error
  134. }
  135. func (resultMap *ResultMap) List() ([]map[string]interface{}, error) {
  136. return resultMap.Result, resultMap.Error
  137. }
  138. func (resultMap *ResultMap) Count() (int, error) {
  139. if resultMap.Error != nil {
  140. return 0, resultMap.Error
  141. }
  142. if resultMap.Result == nil {
  143. return 0, nil
  144. }
  145. return len(resultMap.Result), nil
  146. }
  147. func (resultMap *ResultMap) ListPage(firstResult int, maxResults int) ([]map[string]interface{}, error) {
  148. if resultMap.Error != nil {
  149. return nil, resultMap.Error
  150. }
  151. if resultMap.Result == nil {
  152. return nil, nil
  153. }
  154. if firstResult > maxResults {
  155. return nil, ErrParamsFormat
  156. }
  157. if firstResult < 0 {
  158. return nil, ErrParamsFormat
  159. }
  160. if maxResults < 0 {
  161. return nil, ErrParamsFormat
  162. }
  163. if maxResults > len(resultMap.Result) {
  164. return nil, ErrParamsFormat
  165. }
  166. return resultMap.Result[(firstResult - 1):maxResults], resultMap.Error
  167. }
  168. func (resultMap *ResultMap) Json() (string, error) {
  169. if resultMap.Error != nil {
  170. return "", resultMap.Error
  171. }
  172. return JSONString(resultMap.Result, true)
  173. }
  174. func (resultMap *ResultMap) Xml() (string, error) {
  175. if resultMap.Error != nil {
  176. return "", resultMap.Error
  177. }
  178. results, err := anyxml.Xml(resultMap.Result)
  179. if err != nil {
  180. return "", err
  181. }
  182. return string(results), nil
  183. }
  184. func (resultMap *ResultMap) XmlIndent(prefix string, indent string, recordTag string) (string, error) {
  185. if resultMap.Error != nil {
  186. return "", resultMap.Error
  187. }
  188. results, err := anyxml.XmlIndent(resultMap.Result, prefix, indent, recordTag)
  189. if err != nil {
  190. return "", err
  191. }
  192. return string(results), nil
  193. }
  194. func (resultMap *ResultMap) SaveAsCSV(filename string, headers []string, perm os.FileMode) error {
  195. if resultMap.Error != nil {
  196. return resultMap.Error
  197. }
  198. dataset, err := NewDatasetWithData(headers, resultMap.Result, true)
  199. if err != nil {
  200. return err
  201. }
  202. csv, err := dataset.CSV()
  203. if err != nil {
  204. return err
  205. }
  206. return csv.WriteFile(filename, perm)
  207. }
  208. func (resultMap *ResultMap) SaveAsTSV(filename string, headers []string, perm os.FileMode) error {
  209. if resultMap.Error != nil {
  210. return resultMap.Error
  211. }
  212. dataset, err := NewDatasetWithData(headers, resultMap.Result, true)
  213. if err != nil {
  214. return err
  215. }
  216. tsv, err := dataset.TSV()
  217. if err != nil {
  218. return err
  219. }
  220. return tsv.WriteFile(filename, perm)
  221. }
  222. func (resultMap *ResultMap) SaveAsHTML(filename string, headers []string, perm os.FileMode) error {
  223. if resultMap.Error != nil {
  224. return resultMap.Error
  225. }
  226. dataset, err := NewDatasetWithData(headers, resultMap.Result, true)
  227. if err != nil {
  228. return err
  229. }
  230. html := dataset.HTML()
  231. return html.WriteFile(filename, perm)
  232. }
  233. func (resultMap *ResultMap) SaveAsXML(filename string, headers []string, perm os.FileMode) error {
  234. if resultMap.Error != nil {
  235. return resultMap.Error
  236. }
  237. dataset, err := NewDatasetWithData(headers, resultMap.Result, false)
  238. if err != nil {
  239. return err
  240. }
  241. xml, err := dataset.XML()
  242. if err != nil {
  243. return err
  244. }
  245. return xml.WriteFile(filename, perm)
  246. }
  247. func (resultMap *ResultMap) SaveAsXMLWithTagNamePrefixIndent(tagName string, prifix string, indent string, filename string, headers []string, perm os.FileMode) error {
  248. if resultMap.Error != nil {
  249. return resultMap.Error
  250. }
  251. dataset, err := NewDatasetWithData(headers, resultMap.Result, false)
  252. if err != nil {
  253. return err
  254. }
  255. xml, err := dataset.XMLWithTagNamePrefixIndent(tagName, prifix, indent)
  256. if err != nil {
  257. return err
  258. }
  259. return xml.WriteFile(filename, perm)
  260. }
  261. func (resultMap *ResultMap) SaveAsYAML(filename string, headers []string, perm os.FileMode) error {
  262. if resultMap.Error != nil {
  263. return resultMap.Error
  264. }
  265. dataset, err := NewDatasetWithData(headers, resultMap.Result, false)
  266. if err != nil {
  267. return err
  268. }
  269. yaml, err := dataset.YAML()
  270. if err != nil {
  271. return err
  272. }
  273. return yaml.WriteFile(filename, perm)
  274. }
  275. func (resultMap *ResultMap) SaveAsJSON(filename string, headers []string, perm os.FileMode) error {
  276. if resultMap.Error != nil {
  277. return resultMap.Error
  278. }
  279. dataset, err := NewDatasetWithData(headers, resultMap.Result, false)
  280. if err != nil {
  281. return err
  282. }
  283. json, err := dataset.JSON()
  284. if err != nil {
  285. return err
  286. }
  287. return json.WriteFile(filename, perm)
  288. }
  289. func (resultMap *ResultMap) SaveAsXLSX(filename string, headers []string, perm os.FileMode) error {
  290. if resultMap.Error != nil {
  291. return resultMap.Error
  292. }
  293. dataset, err := NewDatasetWithData(headers, resultMap.Result, true)
  294. if err != nil {
  295. return err
  296. }
  297. xlsx, err := dataset.XLSX()
  298. if err != nil {
  299. return err
  300. }
  301. return xlsx.WriteFile(filename, perm)
  302. }
  303. type ResultStructs struct {
  304. Result interface{}
  305. Error error
  306. }
  307. func (resultStructs *ResultStructs) Json() (string, error) {
  308. if resultStructs.Error != nil {
  309. return "", resultStructs.Error
  310. }
  311. return JSONString(resultStructs.Result, true)
  312. }
  313. func (resultStructs *ResultStructs) Xml() (string, error) {
  314. if resultStructs.Error != nil {
  315. return "", resultStructs.Error
  316. }
  317. result, err := resultStructs.Json()
  318. if err != nil {
  319. return "", err
  320. }
  321. var anydata = []byte(result)
  322. var i interface{}
  323. err = json.Unmarshal(anydata, &i)
  324. if err != nil {
  325. return "", err
  326. }
  327. resultByte, err := anyxml.Xml(i)
  328. if err != nil {
  329. return "", err
  330. }
  331. return string(resultByte), nil
  332. }
  333. func (resultStructs *ResultStructs) XmlIndent(prefix string, indent string, recordTag string) (string, error) {
  334. if resultStructs.Error != nil {
  335. return "", resultStructs.Error
  336. }
  337. result, err := resultStructs.Json()
  338. if err != nil {
  339. return "", err
  340. }
  341. var anydata = []byte(result)
  342. var i interface{}
  343. err = json.Unmarshal(anydata, &i)
  344. if err != nil {
  345. return "", err
  346. }
  347. resultByte, err := anyxml.XmlIndent(i, prefix, indent, recordTag)
  348. if err != nil {
  349. return "", err
  350. }
  351. return string(resultByte), nil
  352. }
  353. func (session *Session) SqlMapClient(sqlTagName string, args ...interface{}) *Session {
  354. return session.Sql(session.engine.SqlMap.Sql[sqlTagName], args...)
  355. }
  356. func (session *Session) SqlTemplateClient(sqlTagName string, args ...interface{}) *Session {
  357. session.isSqlFunc = true
  358. sql, err := session.engine.SqlTemplate.Execute(sqlTagName, args...)
  359. if err != nil {
  360. session.engine.logger.Error(err)
  361. }
  362. if len(args) == 0 {
  363. return session.Sql(sql)
  364. } else {
  365. map1 := args[0].(*map[string]interface{})
  366. return session.Sql(sql, map1)
  367. }
  368. }
  369. func (session *Session) Search(rowsSlicePtr interface{}, condiBean ...interface{}) *ResultStructs {
  370. err := session.Find(rowsSlicePtr, condiBean...)
  371. r := &ResultStructs{Result: rowsSlicePtr, Error: err}
  372. return r
  373. }
  374. func (session *Session) genSelectSql(dialect core.Dialect, rownumber string) string {
  375. var sql = session.statement.RawSQL
  376. var orderBys = session.statement.OrderStr
  377. if dialect.DBType() != core.MSSQL && dialect.DBType() != core.ORACLE {
  378. if session.statement.Start > 0 {
  379. sql = fmt.Sprintf("%v LIMIT %v OFFSET %v", sql, session.statement.LimitN, session.statement.Start)
  380. } else if session.statement.LimitN > 0 {
  381. sql = fmt.Sprintf("%v LIMIT %v", sql, session.statement.LimitN)
  382. }
  383. } else if dialect.DBType() == core.ORACLE {
  384. if session.statement.Start != 0 || session.statement.LimitN != 0 {
  385. sql = fmt.Sprintf("SELECT aat.* FROM (SELECT at.*,ROWNUM %v FROM (%v) at WHERE ROWNUM <= %d) aat WHERE %v > %d",
  386. rownumber, sql, session.statement.Start+session.statement.LimitN, rownumber, session.statement.Start)
  387. }
  388. } else {
  389. keepSelect := false
  390. var fullQuery string
  391. if session.statement.Start > 0 {
  392. fullQuery = fmt.Sprintf("SELECT sq.* FROM (SELECT ROW_NUMBER() OVER (ORDER BY %v) AS %v,", orderBys, rownumber)
  393. } else if session.statement.LimitN > 0 {
  394. fullQuery = fmt.Sprintf("SELECT TOP %d", session.statement.LimitN)
  395. } else {
  396. keepSelect = true
  397. }
  398. if !keepSelect {
  399. expr := `^\s*SELECT\s*`
  400. reg, err := regexp.Compile(expr)
  401. if err != nil {
  402. fmt.Println(err)
  403. }
  404. sql = strings.ToUpper(sql)
  405. if reg.MatchString(sql) {
  406. str := reg.FindAllString(sql, -1)
  407. fullQuery = fmt.Sprintf("%v %v", fullQuery, sql[len(str[0]):])
  408. }
  409. }
  410. if session.statement.Start > 0 {
  411. // T-SQL offset starts with 1, not like MySQL with 0;
  412. if session.statement.LimitN > 0 {
  413. fullQuery = fmt.Sprintf("%v) AS sq WHERE %v BETWEEN %d AND %d", fullQuery, rownumber, session.statement.Start+1, session.statement.Start+session.statement.LimitN)
  414. } else {
  415. fullQuery = fmt.Sprintf("%v) AS sq WHERE %v >= %d", fullQuery, rownumber, session.statement.Start+1)
  416. }
  417. } else {
  418. fullQuery = fmt.Sprintf("%v ORDER BY %v", fullQuery, orderBys)
  419. }
  420. if keepSelect {
  421. if len(orderBys) > 0 {
  422. sql = fmt.Sprintf("%v ORDER BY %v", sql, orderBys)
  423. }
  424. } else {
  425. sql = fullQuery
  426. }
  427. }
  428. return sql
  429. }
  430. // Exec a raw sql and return records as ResultMap
  431. func (session *Session) Query() *ResultMap {
  432. defer session.resetStatement()
  433. if session.isAutoClose {
  434. defer session.Close()
  435. }
  436. var dialect = session.statement.Engine.Dialect()
  437. rownumber := "xorm" + NewShortUUID().String()
  438. sql := session.genSelectSql(dialect, rownumber)
  439. params := session.statement.RawParams
  440. i := len(params)
  441. var result []map[string]interface{}
  442. var err error
  443. if i == 1 {
  444. vv := reflect.ValueOf(params[0])
  445. if vv.Kind() != reflect.Ptr || vv.Elem().Kind() != reflect.Map {
  446. result, err = session.queryAll(sql, params...)
  447. } else {
  448. result, err = session.queryAllByMap(sql, params[0])
  449. }
  450. } else {
  451. result, err = session.queryAll(sql, params...)
  452. }
  453. if dialect.DBType() == core.MSSQL {
  454. if session.statement.Start > 0 {
  455. for i, _ := range result {
  456. delete(result[i], rownumber)
  457. }
  458. }
  459. } else if dialect.DBType() == core.ORACLE {
  460. if session.statement.Start != 0 || session.statement.LimitN != 0 {
  461. for i, _ := range result {
  462. delete(result[i], rownumber)
  463. }
  464. }
  465. }
  466. r := &ResultMap{Result: result, Error: err}
  467. return r
  468. }
  469. // Exec a raw sql and return records as ResultMap
  470. func (session *Session) QueryWithDateFormat(dateFormat string) *ResultMap {
  471. defer session.resetStatement()
  472. if session.isAutoClose {
  473. defer session.Close()
  474. }
  475. var dialect = session.statement.Engine.Dialect()
  476. rownumber := "xorm" + NewShortUUID().String()
  477. sql := session.genSelectSql(dialect, rownumber)
  478. params := session.statement.RawParams
  479. i := len(params)
  480. var result []map[string]interface{}
  481. var err error
  482. if i == 1 {
  483. vv := reflect.ValueOf(params[0])
  484. if vv.Kind() != reflect.Ptr || vv.Elem().Kind() != reflect.Map {
  485. result, err = session.queryAllWithDateFormat(dateFormat, sql, params...)
  486. } else {
  487. result, err = session.queryAllByMapWithDateFormat(dateFormat, sql, params[0])
  488. }
  489. } else {
  490. result, err = session.queryAllWithDateFormat(dateFormat, sql, params...)
  491. }
  492. if dialect.DBType() == core.MSSQL {
  493. if session.statement.Start > 0 {
  494. for i, _ := range result {
  495. delete(result[i], rownumber)
  496. }
  497. }
  498. } else if dialect.DBType() == core.ORACLE {
  499. if session.statement.Start != 0 || session.statement.LimitN != 0 {
  500. for i, _ := range result {
  501. delete(result[i], rownumber)
  502. }
  503. }
  504. }
  505. r := &ResultMap{Result: result, Error: err}
  506. return r
  507. }
  508. // Execute raw sql
  509. func (session *Session) Execute() (sql.Result, error) {
  510. defer session.resetStatement()
  511. if session.isAutoClose {
  512. defer session.Close()
  513. }
  514. sqlStr := session.statement.RawSQL
  515. params := session.statement.RawParams
  516. i := len(params)
  517. if i == 1 {
  518. vv := reflect.ValueOf(params[0])
  519. if vv.Kind() != reflect.Ptr || vv.Elem().Kind() != reflect.Map {
  520. return session.exec(sqlStr, params...)
  521. } else {
  522. sqlStr1, args, _ := core.MapToSlice(sqlStr, params[0])
  523. return session.exec(sqlStr1, args...)
  524. }
  525. } else {
  526. return session.exec(sqlStr, params...)
  527. }
  528. }
  529. // =============================
  530. // for Object
  531. // =============================
  532. func (session *Session) queryAll(sqlStr string, paramStr ...interface{}) (resultsSlice []map[string]interface{}, err error) {
  533. session.queryPreprocess(&sqlStr, paramStr...)
  534. if session.engine.showSQL {
  535. if session.engine.showExecTime {
  536. b4ExecTime := time.Now()
  537. defer func() {
  538. execDuration := time.Since(b4ExecTime)
  539. if len(paramStr) > 0 {
  540. session.engine.logger.Infof("[SQL][%p] %s %#v - took: %v", session, sqlStr, paramStr, execDuration)
  541. } else {
  542. session.engine.logger.Infof("[SQL][%p] %s - took: %v", session, sqlStr, execDuration)
  543. }
  544. }()
  545. } else {
  546. if len(paramStr) > 0 {
  547. session.engine.logger.Infof("[SQL][%p] %v %#v", session, sqlStr, paramStr)
  548. } else {
  549. session.engine.logger.Infof("[SQL][%p] %v", session, sqlStr)
  550. }
  551. }
  552. }
  553. if session.isAutoCommit {
  554. return query3(session.DB(), sqlStr, paramStr...)
  555. }
  556. return txQuery3(session.tx, sqlStr, paramStr...)
  557. }
  558. func (session *Session) queryAllByMap(sqlStr string, paramMap interface{}) (resultsSlice []map[string]interface{}, err error) {
  559. sqlStr1, param, _ := core.MapToSlice(sqlStr, paramMap)
  560. session.queryPreprocess(&sqlStr1, param...)
  561. if session.engine.showSQL {
  562. if session.engine.showExecTime {
  563. b4ExecTime := time.Now()
  564. defer func() {
  565. execDuration := time.Since(b4ExecTime)
  566. if len(param) > 0 {
  567. session.engine.logger.Infof("[SQL][%p] %s %#v - took: %v", session, sqlStr1, param, execDuration)
  568. } else {
  569. session.engine.logger.Infof("[SQL][%p] %s - took: %v", session, sqlStr1, execDuration)
  570. }
  571. }()
  572. } else {
  573. if len(param) > 0 {
  574. session.engine.logger.Infof("[SQL][%p] %v %#v", session, sqlStr1, param)
  575. } else {
  576. session.engine.logger.Infof("[SQL][%p] %v", session, sqlStr1)
  577. }
  578. }
  579. }
  580. if session.isAutoCommit {
  581. return query3(session.DB(), sqlStr1, param...)
  582. }
  583. return txQuery3(session.tx, sqlStr1, param...)
  584. }
  585. func (session *Session) queryAllByMapWithDateFormat(dateFormat string, sqlStr string, paramMap interface{}) (resultsSlice []map[string]interface{}, err error) {
  586. sqlStr1, param, _ := core.MapToSlice(sqlStr, paramMap)
  587. session.queryPreprocess(&sqlStr1, param...)
  588. if session.engine.showSQL {
  589. if session.engine.showExecTime {
  590. b4ExecTime := time.Now()
  591. defer func() {
  592. execDuration := time.Since(b4ExecTime)
  593. if len(param) > 0 {
  594. session.engine.logger.Infof("[SQL][%p] %s %#v - took: %v", session, sqlStr1, param, execDuration)
  595. } else {
  596. session.engine.logger.Infof("[SQL][%p] %s - took: %v", session, sqlStr1, execDuration)
  597. }
  598. }()
  599. } else {
  600. if len(param) > 0 {
  601. session.engine.logger.Infof("[SQL][%p] %v %#v", session, sqlStr1, param)
  602. } else {
  603. session.engine.logger.Infof("[SQL][%p] %v", session, sqlStr1)
  604. }
  605. }
  606. }
  607. if session.isAutoCommit {
  608. return query3WithDateFormat(session.DB(), dateFormat, sqlStr1, param...)
  609. }
  610. return txQuery3WithDateFormat(session.tx, dateFormat, sqlStr1, param...)
  611. }
  612. func (session *Session) queryAllWithDateFormat(dateFormat string, sqlStr string, paramStr ...interface{}) (resultsSlice []map[string]interface{}, err error) {
  613. session.queryPreprocess(&sqlStr, paramStr...)
  614. if session.engine.showSQL {
  615. if session.engine.showExecTime {
  616. b4ExecTime := time.Now()
  617. defer func() {
  618. execDuration := time.Since(b4ExecTime)
  619. if len(paramStr) > 0 {
  620. session.engine.logger.Infof("[SQL][%p] %s %#v - took: %v", session, sqlStr, paramStr, execDuration)
  621. } else {
  622. session.engine.logger.Infof("[SQL][%p] %s - took: %v", session, sqlStr, execDuration)
  623. }
  624. }()
  625. } else {
  626. if len(paramStr) > 0 {
  627. session.engine.logger.Infof("[SQL][%p] %v %#v", session, sqlStr, paramStr)
  628. } else {
  629. session.engine.logger.Infof("[SQL][%p] %v", session, sqlStr)
  630. }
  631. }
  632. }
  633. if session.isAutoCommit {
  634. return query3WithDateFormat(session.DB(), dateFormat, sqlStr, paramStr...)
  635. }
  636. return txQuery3WithDateFormat(session.tx, dateFormat, sqlStr, paramStr...)
  637. }
  638. func (session *Session) queryAllToJsonString(sql string, paramStr ...interface{}) (string, error) {
  639. results, err := session.queryAll(sql, paramStr...)
  640. if err != nil {
  641. return "", err
  642. }
  643. return JSONString(results, true)
  644. }
  645. func (session *Session) queryAllToXmlString(sql string, paramStr ...interface{}) (string, error) {
  646. resultMap, err := session.queryAll(sql, paramStr...)
  647. if err != nil {
  648. return "", err
  649. }
  650. results, err := anyxml.Xml(resultMap)
  651. if err != nil {
  652. return "", err
  653. }
  654. return string(results), nil
  655. }
  656. func (session *Session) queryAllToXmlIndentString(sql string, prefix string, indent string, paramStr ...interface{}) (string, error) {
  657. resultSlice, err := session.queryAll(sql, paramStr...)
  658. if err != nil {
  659. return "", err
  660. }
  661. results, err := anyxml.XmlIndent(resultSlice, prefix, indent, "result")
  662. if err != nil {
  663. return "", err
  664. }
  665. return string(results), nil
  666. }
  667. func (session *Session) queryAllToXmlStringWithDateFormat(dateFormat string, sql string, paramStr ...interface{}) (string, error) {
  668. resultSlice, err := session.queryAll(sql, paramStr...)
  669. if err != nil {
  670. return "", err
  671. }
  672. results, err := anyxml.XmlWithDateFormat(dateFormat, resultSlice)
  673. if err != nil {
  674. return "", err
  675. }
  676. return string(results), nil
  677. }
  678. func (session *Session) queryAllToXmlIndentStringWithDateFormat(dateFormat string, sql string, prefix string, indent string, paramStr ...interface{}) (string, error) {
  679. resultSlice, err := session.queryAll(sql, paramStr...)
  680. if err != nil {
  681. return "", err
  682. }
  683. results, err := anyxml.XmlIndentWithDateFormat(dateFormat, resultSlice, prefix, indent, "results")
  684. if err != nil {
  685. return "", err
  686. }
  687. return string(results), nil
  688. }
  689. func (session *Session) queryAllByMapToJsonString(sql string, paramMap interface{}) (string, error) {
  690. results, err := session.queryAllByMap(sql, paramMap)
  691. if err != nil {
  692. return "", err
  693. }
  694. return JSONString(results, true)
  695. }
  696. func (session *Session) queryAllByMapToJsonStringWithDateFormat(dateFormat string, sql string, paramMap interface{}) (string, error) {
  697. results, err := session.queryAllByMapWithDateFormat(dateFormat, sql, paramMap)
  698. if err != nil {
  699. return "", err
  700. }
  701. return JSONString(results, true)
  702. }
  703. func (session *Session) queryAllToJsonStringWithDateFormat(dateFormat string, sql string, paramStr ...interface{}) (string, error) {
  704. results, err := session.queryAllWithDateFormat(dateFormat, sql, paramStr...)
  705. if err != nil {
  706. return "", err
  707. }
  708. return JSONString(results, true)
  709. }
  710. func (session *Session) queryPreprocessByMap(sqlStr *string, paramMap interface{}) {
  711. re := regexp.MustCompile(`[?](\w+)`)
  712. query := *sqlStr
  713. names := make(map[string]int)
  714. var i int
  715. query = re.ReplaceAllStringFunc(query, func(src string) string {
  716. names[src[1:]] = i
  717. i += 1
  718. return "?"
  719. })
  720. for _, filter := range session.engine.dialect.Filters() {
  721. query = filter.Do(query, session.engine.dialect, session.statement.RefTable)
  722. }
  723. *sqlStr = query
  724. session.engine.logSQL(session, *sqlStr, paramMap)
  725. }
  726. func (session *Session) Sqls(sqls interface{}, parmas ...interface{}) *SqlsExecutor {
  727. sqlsExecutor := new(SqlsExecutor)
  728. switch sqls.(type) {
  729. case string:
  730. sqlsExecutor.sqls = sqls.(string)
  731. case []string:
  732. sqlsExecutor.sqls = sqls.([]string)
  733. case map[string]string:
  734. sqlsExecutor.sqls = sqls.(map[string]string)
  735. default:
  736. sqlsExecutor.sqls = nil
  737. sqlsExecutor.err = ErrParamsType
  738. }
  739. if len(parmas) == 0 {
  740. sqlsExecutor.parmas = nil
  741. }
  742. if len(parmas) > 1 {
  743. sqlsExecutor.parmas = nil
  744. sqlsExecutor.err = ErrParamsType
  745. }
  746. if len(parmas) == 1 {
  747. switch parmas[0].(type) {
  748. case map[string]interface{}:
  749. sqlsExecutor.parmas = parmas[0].(map[string]interface{})
  750. case []map[string]interface{}:
  751. sqlsExecutor.parmas = parmas[0].([]map[string]interface{})
  752. case map[string]map[string]interface{}:
  753. sqlsExecutor.parmas = parmas[0].(map[string]map[string]interface{})
  754. default:
  755. sqlsExecutor.parmas = nil
  756. sqlsExecutor.err = ErrParamsType
  757. }
  758. }
  759. sqlsExecutor.session = session
  760. return sqlsExecutor
  761. }
  762. func (session *Session) SqlMapsClient(sqlkeys interface{}, parmas ...interface{}) *SqlMapsExecutor {
  763. sqlMapsExecutor := new(SqlMapsExecutor)
  764. switch sqlkeys.(type) {
  765. case string:
  766. sqlMapsExecutor.sqlkeys = sqlkeys.(string)
  767. case []string:
  768. sqlMapsExecutor.sqlkeys = sqlkeys.([]string)
  769. case map[string]string:
  770. sqlMapsExecutor.sqlkeys = sqlkeys.(map[string]string)
  771. default:
  772. sqlMapsExecutor.sqlkeys = nil
  773. sqlMapsExecutor.err = ErrParamsType
  774. }
  775. if len(parmas) == 0 {
  776. sqlMapsExecutor.parmas = nil
  777. }
  778. if len(parmas) > 1 {
  779. sqlMapsExecutor.parmas = nil
  780. sqlMapsExecutor.err = ErrParamsType
  781. }
  782. if len(parmas) == 1 {
  783. switch parmas[0].(type) {
  784. case map[string]interface{}:
  785. sqlMapsExecutor.parmas = parmas[0].(map[string]interface{})
  786. case []map[string]interface{}:
  787. sqlMapsExecutor.parmas = parmas[0].([]map[string]interface{})
  788. case map[string]map[string]interface{}:
  789. sqlMapsExecutor.parmas = parmas[0].(map[string]map[string]interface{})
  790. default:
  791. sqlMapsExecutor.parmas = nil
  792. sqlMapsExecutor.err = ErrParamsType
  793. }
  794. }
  795. sqlMapsExecutor.session = session
  796. return sqlMapsExecutor
  797. }
  798. func (session *Session) SqlTemplatesClient(sqlkeys interface{}, parmas ...interface{}) *SqlTemplatesExecutor {
  799. sqlTemplatesExecutor := new(SqlTemplatesExecutor)
  800. switch sqlkeys.(type) {
  801. case string:
  802. sqlTemplatesExecutor.sqlkeys = sqlkeys.(string)
  803. case []string:
  804. sqlTemplatesExecutor.sqlkeys = sqlkeys.([]string)
  805. case map[string]string:
  806. sqlTemplatesExecutor.sqlkeys = sqlkeys.(map[string]string)
  807. default:
  808. sqlTemplatesExecutor.sqlkeys = nil
  809. sqlTemplatesExecutor.err = ErrParamsType
  810. }
  811. if len(parmas) == 0 {
  812. sqlTemplatesExecutor.parmas = nil
  813. }
  814. if len(parmas) > 1 {
  815. sqlTemplatesExecutor.parmas = nil
  816. sqlTemplatesExecutor.err = ErrParamsType
  817. }
  818. if len(parmas) == 1 {
  819. switch parmas[0].(type) {
  820. case map[string]interface{}:
  821. sqlTemplatesExecutor.parmas = parmas[0].(map[string]interface{})
  822. case []map[string]interface{}:
  823. sqlTemplatesExecutor.parmas = parmas[0].([]map[string]interface{})
  824. case map[string]map[string]interface{}:
  825. sqlTemplatesExecutor.parmas = parmas[0].(map[string]map[string]interface{})
  826. default:
  827. sqlTemplatesExecutor.parmas = nil
  828. sqlTemplatesExecutor.err = ErrParamsType
  829. }
  830. }
  831. sqlTemplatesExecutor.session = session
  832. return sqlTemplatesExecutor
  833. }