Simple and Powerful ORM for Go, support mysql,postgres,tidb,sqlite3,mssql,oracle https://xorm.io
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

82 lines
2.3 KiB

  1. // Copyright 2016 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. "errors"
  8. "reflect"
  9. )
  10. // Count counts the records. bean's non-empty fields
  11. // are conditions.
  12. func (session *Session) Count(bean ...interface{}) (int64, error) {
  13. if session.isAutoClose {
  14. defer session.Close()
  15. }
  16. sqlStr, args, err := session.statement.GenCountSQL(bean...)
  17. if err != nil {
  18. return 0, err
  19. }
  20. var total int64
  21. err = session.queryRow(sqlStr, args...).Scan(&total)
  22. if err == sql.ErrNoRows || err == nil {
  23. return total, nil
  24. }
  25. return 0, err
  26. }
  27. // sum call sum some column. bean's non-empty fields are conditions.
  28. func (session *Session) sum(res interface{}, bean interface{}, columnNames ...string) error {
  29. if session.isAutoClose {
  30. defer session.Close()
  31. }
  32. v := reflect.ValueOf(res)
  33. if v.Kind() != reflect.Ptr {
  34. return errors.New("need a pointer to a variable")
  35. }
  36. sqlStr, args, err := session.statement.GenSumSQL(bean, columnNames...)
  37. if err != nil {
  38. return err
  39. }
  40. if v.Elem().Kind() == reflect.Slice {
  41. err = session.queryRow(sqlStr, args...).ScanSlice(res)
  42. } else {
  43. err = session.queryRow(sqlStr, args...).Scan(res)
  44. }
  45. if err == sql.ErrNoRows || err == nil {
  46. return nil
  47. }
  48. return err
  49. }
  50. // Sum call sum some column. bean's non-empty fields are conditions.
  51. func (session *Session) Sum(bean interface{}, columnName string) (res float64, err error) {
  52. return res, session.sum(&res, bean, columnName)
  53. }
  54. // SumInt call sum some column. bean's non-empty fields are conditions.
  55. func (session *Session) SumInt(bean interface{}, columnName string) (res int64, err error) {
  56. return res, session.sum(&res, bean, columnName)
  57. }
  58. // Sums call sum some columns. bean's non-empty fields are conditions.
  59. func (session *Session) Sums(bean interface{}, columnNames ...string) ([]float64, error) {
  60. var res = make([]float64, len(columnNames), len(columnNames))
  61. return res, session.sum(&res, bean, columnNames...)
  62. }
  63. // SumsInt sum specify columns and return as []int64 instead of []float64
  64. func (session *Session) SumsInt(bean interface{}, columnNames ...string) ([]int64, error) {
  65. var res = make([]int64, len(columnNames), len(columnNames))
  66. return res, session.sum(&res, bean, columnNames...)
  67. }