gdb_model_select.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gdb
  7. import (
  8. "fmt"
  9. "github.com/gogf/gf/errors/gcode"
  10. "github.com/gogf/gf/errors/gerror"
  11. "reflect"
  12. "github.com/gogf/gf/container/gset"
  13. "github.com/gogf/gf/container/gvar"
  14. "github.com/gogf/gf/internal/intlog"
  15. "github.com/gogf/gf/internal/json"
  16. "github.com/gogf/gf/text/gstr"
  17. "github.com/gogf/gf/util/gconv"
  18. )
  19. // Select is alias of Model.All.
  20. // See Model.All.
  21. // Deprecated, use All instead.
  22. func (m *Model) Select(where ...interface{}) (Result, error) {
  23. return m.All(where...)
  24. }
  25. // All does "SELECT FROM ..." statement for the model.
  26. // It retrieves the records from table and returns the result as slice type.
  27. // It returns nil if there's no record retrieved with the given conditions from table.
  28. //
  29. // The optional parameter `where` is the same as the parameter of Model.Where function,
  30. // see Model.Where.
  31. func (m *Model) All(where ...interface{}) (Result, error) {
  32. return m.doGetAll(false, where...)
  33. }
  34. // doGetAll does "SELECT FROM ..." statement for the model.
  35. // It retrieves the records from table and returns the result as slice type.
  36. // It returns nil if there's no record retrieved with the given conditions from table.
  37. //
  38. // The parameter `limit1` specifies whether limits querying only one record if m.limit is not set.
  39. // The optional parameter `where` is the same as the parameter of Model.Where function,
  40. // see Model.Where.
  41. func (m *Model) doGetAll(limit1 bool, where ...interface{}) (Result, error) {
  42. if len(where) > 0 {
  43. return m.Where(where[0], where[1:]...).All()
  44. }
  45. sqlWithHolder, holderArgs := m.getFormattedSqlAndArgs(queryTypeNormal, limit1)
  46. return m.doGetAllBySql(sqlWithHolder, holderArgs...)
  47. }
  48. // getFieldsFiltered checks the fields and fieldsEx attributes, filters and returns the fields that will
  49. // really be committed to underlying database driver.
  50. func (m *Model) getFieldsFiltered() string {
  51. if m.fieldsEx == "" {
  52. // No filtering.
  53. if !gstr.Contains(m.fields, ".") && !gstr.Contains(m.fields, " ") {
  54. return m.db.GetCore().QuoteString(m.fields)
  55. }
  56. return m.fields
  57. }
  58. var (
  59. fieldsArray []string
  60. fieldsExSet = gset.NewStrSetFrom(gstr.SplitAndTrim(m.fieldsEx, ","))
  61. )
  62. if m.fields != "*" {
  63. // Filter custom fields with fieldEx.
  64. fieldsArray = make([]string, 0, 8)
  65. for _, v := range gstr.SplitAndTrim(m.fields, ",") {
  66. fieldsArray = append(fieldsArray, v[gstr.PosR(v, "-")+1:])
  67. }
  68. } else {
  69. if gstr.Contains(m.tables, " ") {
  70. panic("function FieldsEx supports only single table operations")
  71. }
  72. // Filter table fields with fieldEx.
  73. tableFields, err := m.TableFields(m.tablesInit)
  74. if err != nil {
  75. panic(err)
  76. }
  77. if len(tableFields) == 0 {
  78. panic(fmt.Sprintf(`empty table fields for table "%s"`, m.tables))
  79. }
  80. fieldsArray = make([]string, len(tableFields))
  81. for k, v := range tableFields {
  82. fieldsArray[v.Index] = k
  83. }
  84. }
  85. newFields := ""
  86. for _, k := range fieldsArray {
  87. if fieldsExSet.Contains(k) {
  88. continue
  89. }
  90. if len(newFields) > 0 {
  91. newFields += ","
  92. }
  93. newFields += m.db.GetCore().QuoteWord(k)
  94. }
  95. return newFields
  96. }
  97. // Chunk iterates the query result with given `size` and `handler` function.
  98. func (m *Model) Chunk(size int, handler ChunkHandler) {
  99. page := m.start
  100. if page <= 0 {
  101. page = 1
  102. }
  103. model := m
  104. for {
  105. model = model.Page(page, size)
  106. data, err := model.All()
  107. if err != nil {
  108. handler(nil, err)
  109. break
  110. }
  111. if len(data) == 0 {
  112. break
  113. }
  114. if handler(data, err) == false {
  115. break
  116. }
  117. if len(data) < size {
  118. break
  119. }
  120. page++
  121. }
  122. }
  123. // One retrieves one record from table and returns the result as map type.
  124. // It returns nil if there's no record retrieved with the given conditions from table.
  125. //
  126. // The optional parameter `where` is the same as the parameter of Model.Where function,
  127. // see Model.Where.
  128. func (m *Model) One(where ...interface{}) (Record, error) {
  129. if len(where) > 0 {
  130. return m.Where(where[0], where[1:]...).One()
  131. }
  132. all, err := m.doGetAll(true)
  133. if err != nil {
  134. return nil, err
  135. }
  136. if len(all) > 0 {
  137. return all[0], nil
  138. }
  139. return nil, nil
  140. }
  141. // Value retrieves a specified record value from table and returns the result as interface type.
  142. // It returns nil if there's no record found with the given conditions from table.
  143. //
  144. // If the optional parameter `fieldsAndWhere` is given, the fieldsAndWhere[0] is the selected fields
  145. // and fieldsAndWhere[1:] is treated as where condition fields.
  146. // Also see Model.Fields and Model.Where functions.
  147. func (m *Model) Value(fieldsAndWhere ...interface{}) (Value, error) {
  148. if len(fieldsAndWhere) > 0 {
  149. if len(fieldsAndWhere) > 2 {
  150. return m.Fields(gconv.String(fieldsAndWhere[0])).Where(fieldsAndWhere[1], fieldsAndWhere[2:]...).Value()
  151. } else if len(fieldsAndWhere) == 2 {
  152. return m.Fields(gconv.String(fieldsAndWhere[0])).Where(fieldsAndWhere[1]).Value()
  153. } else {
  154. return m.Fields(gconv.String(fieldsAndWhere[0])).Value()
  155. }
  156. }
  157. one, err := m.One()
  158. if err != nil {
  159. return gvar.New(nil), err
  160. }
  161. for _, v := range one {
  162. return v, nil
  163. }
  164. return gvar.New(nil), nil
  165. }
  166. // Array queries and returns data values as slice from database.
  167. // Note that if there are multiple columns in the result, it returns just one column values randomly.
  168. //
  169. // If the optional parameter `fieldsAndWhere` is given, the fieldsAndWhere[0] is the selected fields
  170. // and fieldsAndWhere[1:] is treated as where condition fields.
  171. // Also see Model.Fields and Model.Where functions.
  172. func (m *Model) Array(fieldsAndWhere ...interface{}) ([]Value, error) {
  173. if len(fieldsAndWhere) > 0 {
  174. if len(fieldsAndWhere) > 2 {
  175. return m.Fields(gconv.String(fieldsAndWhere[0])).Where(fieldsAndWhere[1], fieldsAndWhere[2:]...).Array()
  176. } else if len(fieldsAndWhere) == 2 {
  177. return m.Fields(gconv.String(fieldsAndWhere[0])).Where(fieldsAndWhere[1]).Array()
  178. } else {
  179. return m.Fields(gconv.String(fieldsAndWhere[0])).Array()
  180. }
  181. }
  182. all, err := m.All()
  183. if err != nil {
  184. return nil, err
  185. }
  186. return all.Array(), nil
  187. }
  188. // Struct retrieves one record from table and converts it into given struct.
  189. // The parameter `pointer` should be type of *struct/**struct. If type **struct is given,
  190. // it can create the struct internally during converting.
  191. //
  192. // Deprecated, use Scan instead.
  193. func (m *Model) Struct(pointer interface{}, where ...interface{}) error {
  194. return m.doStruct(pointer, where...)
  195. }
  196. // Struct retrieves one record from table and converts it into given struct.
  197. // The parameter `pointer` should be type of *struct/**struct. If type **struct is given,
  198. // it can create the struct internally during converting.
  199. //
  200. // The optional parameter `where` is the same as the parameter of Model.Where function,
  201. // see Model.Where.
  202. //
  203. // Note that it returns sql.ErrNoRows if the given parameter `pointer` pointed to a variable that has
  204. // default value and there's no record retrieved with the given conditions from table.
  205. //
  206. // Example:
  207. // user := new(User)
  208. // err := db.Model("user").Where("id", 1).Scan(user)
  209. //
  210. // user := (*User)(nil)
  211. // err := db.Model("user").Where("id", 1).Scan(&user)
  212. func (m *Model) doStruct(pointer interface{}, where ...interface{}) error {
  213. model := m
  214. // Auto selecting fields by struct attributes.
  215. if model.fieldsEx == "" && (model.fields == "" || model.fields == "*") {
  216. model = m.Fields(pointer)
  217. }
  218. one, err := model.One(where...)
  219. if err != nil {
  220. return err
  221. }
  222. if err = one.Struct(pointer); err != nil {
  223. return err
  224. }
  225. return model.doWithScanStruct(pointer)
  226. }
  227. // Structs retrieves records from table and converts them into given struct slice.
  228. // The parameter `pointer` should be type of *[]struct/*[]*struct. It can create and fill the struct
  229. // slice internally during converting.
  230. //
  231. // Deprecated, use Scan instead.
  232. func (m *Model) Structs(pointer interface{}, where ...interface{}) error {
  233. return m.doStructs(pointer, where...)
  234. }
  235. // Structs retrieves records from table and converts them into given struct slice.
  236. // The parameter `pointer` should be type of *[]struct/*[]*struct. It can create and fill the struct
  237. // slice internally during converting.
  238. //
  239. // The optional parameter `where` is the same as the parameter of Model.Where function,
  240. // see Model.Where.
  241. //
  242. // Note that it returns sql.ErrNoRows if the given parameter `pointer` pointed to a variable that has
  243. // default value and there's no record retrieved with the given conditions from table.
  244. //
  245. // Example:
  246. // users := ([]User)(nil)
  247. // err := db.Model("user").Scan(&users)
  248. //
  249. // users := ([]*User)(nil)
  250. // err := db.Model("user").Scan(&users)
  251. func (m *Model) doStructs(pointer interface{}, where ...interface{}) error {
  252. model := m
  253. // Auto selecting fields by struct attributes.
  254. if model.fieldsEx == "" && (model.fields == "" || model.fields == "*") {
  255. model = m.Fields(
  256. reflect.New(
  257. reflect.ValueOf(pointer).Elem().Type().Elem(),
  258. ).Interface(),
  259. )
  260. }
  261. all, err := model.All(where...)
  262. if err != nil {
  263. return err
  264. }
  265. if err = all.Structs(pointer); err != nil {
  266. return err
  267. }
  268. return model.doWithScanStructs(pointer)
  269. }
  270. // Scan automatically calls Struct or Structs function according to the type of parameter `pointer`.
  271. // It calls function doStruct if `pointer` is type of *struct/**struct.
  272. // It calls function doStructs if `pointer` is type of *[]struct/*[]*struct.
  273. //
  274. // The optional parameter `where` is the same as the parameter of Model.Where function, see Model.Where.
  275. //
  276. // Note that it returns sql.ErrNoRows if the given parameter `pointer` pointed to a variable that has
  277. // default value and there's no record retrieved with the given conditions from table.
  278. //
  279. // Example:
  280. // user := new(User)
  281. // err := db.Model("user").Where("id", 1).Scan(user)
  282. //
  283. // user := (*User)(nil)
  284. // err := db.Model("user").Where("id", 1).Scan(&user)
  285. //
  286. // users := ([]User)(nil)
  287. // err := db.Model("user").Scan(&users)
  288. //
  289. // users := ([]*User)(nil)
  290. // err := db.Model("user").Scan(&users)
  291. func (m *Model) Scan(pointer interface{}, where ...interface{}) error {
  292. var (
  293. reflectValue reflect.Value
  294. reflectKind reflect.Kind
  295. )
  296. if v, ok := pointer.(reflect.Value); ok {
  297. reflectValue = v
  298. } else {
  299. reflectValue = reflect.ValueOf(pointer)
  300. }
  301. reflectKind = reflectValue.Kind()
  302. if reflectKind != reflect.Ptr {
  303. return gerror.NewCode(gcode.CodeInvalidParameter, `the parameter "pointer" for function Scan should type of pointer`)
  304. }
  305. for reflectKind == reflect.Ptr {
  306. reflectValue = reflectValue.Elem()
  307. reflectKind = reflectValue.Kind()
  308. }
  309. switch reflectKind {
  310. case reflect.Slice, reflect.Array:
  311. return m.doStructs(pointer, where...)
  312. case reflect.Struct, reflect.Invalid:
  313. return m.doStruct(pointer, where...)
  314. default:
  315. return gerror.NewCode(
  316. gcode.CodeInvalidParameter,
  317. `element of parameter "pointer" for function Scan should type of struct/*struct/[]struct/[]*struct`,
  318. )
  319. }
  320. }
  321. // ScanList converts `r` to struct slice which contains other complex struct attributes.
  322. // Note that the parameter `listPointer` should be type of *[]struct/*[]*struct.
  323. // Usage example:
  324. //
  325. // type Entity struct {
  326. // User *EntityUser
  327. // UserDetail *EntityUserDetail
  328. // UserScores []*EntityUserScores
  329. // }
  330. // var users []*Entity
  331. // or
  332. // var users []Entity
  333. //
  334. // ScanList(&users, "User")
  335. // ScanList(&users, "UserDetail", "User", "uid:Uid")
  336. // ScanList(&users, "UserScores", "User", "uid:Uid")
  337. // The parameters "User"/"UserDetail"/"UserScores" in the example codes specify the target attribute struct
  338. // that current result will be bound to.
  339. // The "uid" in the example codes is the table field name of the result, and the "Uid" is the relational
  340. // struct attribute name. It automatically calculates the HasOne/HasMany relationship with given `relation`
  341. // parameter.
  342. // See the example or unit testing cases for clear understanding for this function.
  343. func (m *Model) ScanList(listPointer interface{}, attributeName string, relation ...string) (err error) {
  344. result, err := m.All()
  345. if err != nil {
  346. return err
  347. }
  348. return doScanList(m, result, listPointer, attributeName, relation...)
  349. }
  350. // Count does "SELECT COUNT(x) FROM ..." statement for the model.
  351. // The optional parameter `where` is the same as the parameter of Model.Where function,
  352. // see Model.Where.
  353. func (m *Model) Count(where ...interface{}) (int, error) {
  354. if len(where) > 0 {
  355. return m.Where(where[0], where[1:]...).Count()
  356. }
  357. var (
  358. sqlWithHolder, holderArgs = m.getFormattedSqlAndArgs(queryTypeCount, false)
  359. list, err = m.doGetAllBySql(sqlWithHolder, holderArgs...)
  360. )
  361. if err != nil {
  362. return 0, err
  363. }
  364. if len(list) > 0 {
  365. for _, v := range list[0] {
  366. return v.Int(), nil
  367. }
  368. }
  369. return 0, nil
  370. }
  371. // CountColumn does "SELECT COUNT(x) FROM ..." statement for the model.
  372. func (m *Model) CountColumn(column string) (int, error) {
  373. if len(column) == 0 {
  374. return 0, nil
  375. }
  376. return m.Fields(column).Count()
  377. }
  378. // Min does "SELECT MIN(x) FROM ..." statement for the model.
  379. func (m *Model) Min(column string) (float64, error) {
  380. if len(column) == 0 {
  381. return 0, nil
  382. }
  383. value, err := m.Fields(fmt.Sprintf(`MIN(%s)`, m.db.GetCore().QuoteWord(column))).Value()
  384. if err != nil {
  385. return 0, err
  386. }
  387. return value.Float64(), err
  388. }
  389. // Max does "SELECT MAX(x) FROM ..." statement for the model.
  390. func (m *Model) Max(column string) (float64, error) {
  391. if len(column) == 0 {
  392. return 0, nil
  393. }
  394. value, err := m.Fields(fmt.Sprintf(`MAX(%s)`, m.db.GetCore().QuoteWord(column))).Value()
  395. if err != nil {
  396. return 0, err
  397. }
  398. return value.Float64(), err
  399. }
  400. // Avg does "SELECT AVG(x) FROM ..." statement for the model.
  401. func (m *Model) Avg(column string) (float64, error) {
  402. if len(column) == 0 {
  403. return 0, nil
  404. }
  405. value, err := m.Fields(fmt.Sprintf(`AVG(%s)`, m.db.GetCore().QuoteWord(column))).Value()
  406. if err != nil {
  407. return 0, err
  408. }
  409. return value.Float64(), err
  410. }
  411. // Sum does "SELECT SUM(x) FROM ..." statement for the model.
  412. func (m *Model) Sum(column string) (float64, error) {
  413. if len(column) == 0 {
  414. return 0, nil
  415. }
  416. value, err := m.Fields(fmt.Sprintf(`SUM(%s)`, m.db.GetCore().QuoteWord(column))).Value()
  417. if err != nil {
  418. return 0, err
  419. }
  420. return value.Float64(), err
  421. }
  422. // FindOne retrieves and returns a single Record by Model.WherePri and Model.One.
  423. // Also see Model.WherePri and Model.One.
  424. func (m *Model) FindOne(where ...interface{}) (Record, error) {
  425. if len(where) > 0 {
  426. return m.WherePri(where[0], where[1:]...).One()
  427. }
  428. return m.One()
  429. }
  430. // FindAll retrieves and returns Result by by Model.WherePri and Model.All.
  431. // Also see Model.WherePri and Model.All.
  432. func (m *Model) FindAll(where ...interface{}) (Result, error) {
  433. if len(where) > 0 {
  434. return m.WherePri(where[0], where[1:]...).All()
  435. }
  436. return m.All()
  437. }
  438. // FindValue retrieves and returns single field value by Model.WherePri and Model.Value.
  439. // Also see Model.WherePri and Model.Value.
  440. func (m *Model) FindValue(fieldsAndWhere ...interface{}) (Value, error) {
  441. if len(fieldsAndWhere) >= 2 {
  442. return m.WherePri(fieldsAndWhere[1], fieldsAndWhere[2:]...).Fields(gconv.String(fieldsAndWhere[0])).Value()
  443. }
  444. if len(fieldsAndWhere) == 1 {
  445. return m.Fields(gconv.String(fieldsAndWhere[0])).Value()
  446. }
  447. return m.Value()
  448. }
  449. // FindArray queries and returns data values as slice from database.
  450. // Note that if there are multiple columns in the result, it returns just one column values randomly.
  451. // Also see Model.WherePri and Model.Value.
  452. func (m *Model) FindArray(fieldsAndWhere ...interface{}) ([]Value, error) {
  453. if len(fieldsAndWhere) >= 2 {
  454. return m.WherePri(fieldsAndWhere[1], fieldsAndWhere[2:]...).Fields(gconv.String(fieldsAndWhere[0])).Array()
  455. }
  456. if len(fieldsAndWhere) == 1 {
  457. return m.Fields(gconv.String(fieldsAndWhere[0])).Array()
  458. }
  459. return m.Array()
  460. }
  461. // FindCount retrieves and returns the record number by Model.WherePri and Model.Count.
  462. // Also see Model.WherePri and Model.Count.
  463. func (m *Model) FindCount(where ...interface{}) (int, error) {
  464. if len(where) > 0 {
  465. return m.WherePri(where[0], where[1:]...).Count()
  466. }
  467. return m.Count()
  468. }
  469. // FindScan retrieves and returns the record/records by Model.WherePri and Model.Scan.
  470. // Also see Model.WherePri and Model.Scan.
  471. func (m *Model) FindScan(pointer interface{}, where ...interface{}) error {
  472. if len(where) > 0 {
  473. return m.WherePri(where[0], where[1:]...).Scan(pointer)
  474. }
  475. return m.Scan(pointer)
  476. }
  477. // Union does "(SELECT xxx FROM xxx) UNION (SELECT xxx FROM xxx) ..." statement for the model.
  478. func (m *Model) Union(unions ...*Model) *Model {
  479. return m.db.Union(unions...)
  480. }
  481. // UnionAll does "(SELECT xxx FROM xxx) UNION ALL (SELECT xxx FROM xxx) ..." statement for the model.
  482. func (m *Model) UnionAll(unions ...*Model) *Model {
  483. return m.db.UnionAll(unions...)
  484. }
  485. // doGetAllBySql does the select statement on the database.
  486. func (m *Model) doGetAllBySql(sql string, args ...interface{}) (result Result, err error) {
  487. cacheKey := ""
  488. cacheObj := m.db.GetCache().Ctx(m.GetCtx())
  489. // Retrieve from cache.
  490. if m.cacheEnabled && m.tx == nil {
  491. cacheKey = m.cacheName
  492. if len(cacheKey) == 0 {
  493. cacheKey = sql + ", @PARAMS:" + gconv.String(args)
  494. }
  495. if v, _ := cacheObj.GetVar(cacheKey); !v.IsNil() {
  496. if result, ok := v.Val().(Result); ok {
  497. // In-memory cache.
  498. return result, nil
  499. } else {
  500. // Other cache, it needs conversion.
  501. var result Result
  502. if err = json.UnmarshalUseNumber(v.Bytes(), &result); err != nil {
  503. return nil, err
  504. } else {
  505. return result, nil
  506. }
  507. }
  508. }
  509. }
  510. result, err = m.db.DoGetAll(
  511. m.GetCtx(), m.getLink(false), sql, m.mergeArguments(args)...,
  512. )
  513. // Cache the result.
  514. if cacheKey != "" && err == nil {
  515. if m.cacheDuration < 0 {
  516. if _, err := cacheObj.Remove(cacheKey); err != nil {
  517. intlog.Error(m.GetCtx(), err)
  518. }
  519. } else {
  520. // In case of Cache Penetration.
  521. if result == nil {
  522. result = Result{}
  523. }
  524. if err := cacheObj.Set(cacheKey, result, m.cacheDuration); err != nil {
  525. intlog.Error(m.GetCtx(), err)
  526. }
  527. }
  528. }
  529. return result, err
  530. }
  531. func (m *Model) getFormattedSqlAndArgs(queryType int, limit1 bool) (sqlWithHolder string, holderArgs []interface{}) {
  532. switch queryType {
  533. case queryTypeCount:
  534. countFields := "COUNT(1)"
  535. if m.fields != "" && m.fields != "*" {
  536. // DO NOT quote the m.fields here, in case of fields like:
  537. // DISTINCT t.user_id uid
  538. countFields = fmt.Sprintf(`COUNT(%s%s)`, m.distinct, m.fields)
  539. }
  540. // Raw SQL Model.
  541. if m.rawSql != "" {
  542. sqlWithHolder = fmt.Sprintf("SELECT %s FROM (%s) AS T", countFields, m.rawSql)
  543. return sqlWithHolder, nil
  544. }
  545. conditionWhere, conditionExtra, conditionArgs := m.formatCondition(false, true)
  546. sqlWithHolder = fmt.Sprintf("SELECT %s FROM %s%s", countFields, m.tables, conditionWhere+conditionExtra)
  547. if len(m.groupBy) > 0 {
  548. sqlWithHolder = fmt.Sprintf("SELECT COUNT(1) FROM (%s) count_alias", sqlWithHolder)
  549. }
  550. return sqlWithHolder, conditionArgs
  551. default:
  552. conditionWhere, conditionExtra, conditionArgs := m.formatCondition(limit1, false)
  553. // Raw SQL Model, especially for UNION/UNION ALL featured SQL.
  554. if m.rawSql != "" {
  555. sqlWithHolder = fmt.Sprintf(
  556. "%s%s",
  557. m.rawSql,
  558. conditionWhere+conditionExtra,
  559. )
  560. return sqlWithHolder, conditionArgs
  561. }
  562. // DO NOT quote the m.fields where, in case of fields like:
  563. // DISTINCT t.user_id uid
  564. sqlWithHolder = fmt.Sprintf(
  565. "SELECT %s%s FROM %s%s",
  566. m.distinct,
  567. m.getFieldsFiltered(),
  568. m.tables,
  569. conditionWhere+conditionExtra,
  570. )
  571. return sqlWithHolder, conditionArgs
  572. }
  573. }