session_exist.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright 2017 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. "errors"
  7. "fmt"
  8. "reflect"
  9. "github.com/go-xorm/builder"
  10. "github.com/go-xorm/core"
  11. )
  12. // Exist returns true if the record exist otherwise return false
  13. func (session *Session) Exist(bean ...interface{}) (bool, error) {
  14. if session.isAutoClose {
  15. defer session.Close()
  16. }
  17. var sqlStr string
  18. var args []interface{}
  19. var err error
  20. if session.statement.RawSQL == "" {
  21. if len(bean) == 0 {
  22. tableName := session.statement.TableName()
  23. if len(tableName) <= 0 {
  24. return false, ErrTableNotFound
  25. }
  26. if session.statement.cond.IsValid() {
  27. condSQL, condArgs, err := builder.ToSQL(session.statement.cond)
  28. if err != nil {
  29. return false, err
  30. }
  31. if session.engine.dialect.DBType() == core.MSSQL {
  32. sqlStr = fmt.Sprintf("SELECT top 1 * FROM %s WHERE %s", tableName, condSQL)
  33. } else {
  34. sqlStr = fmt.Sprintf("SELECT * FROM %s WHERE %s LIMIT 1", tableName, condSQL)
  35. }
  36. args = condArgs
  37. } else {
  38. if session.engine.dialect.DBType() == core.MSSQL {
  39. sqlStr = fmt.Sprintf("SELECT top 1 * FROM %s", tableName)
  40. } else {
  41. sqlStr = fmt.Sprintf("SELECT * FROM %s LIMIT 1", tableName)
  42. }
  43. args = []interface{}{}
  44. }
  45. } else {
  46. beanValue := reflect.ValueOf(bean[0])
  47. if beanValue.Kind() != reflect.Ptr {
  48. return false, errors.New("needs a pointer")
  49. }
  50. if beanValue.Elem().Kind() == reflect.Struct {
  51. if err := session.statement.setRefBean(bean[0]); err != nil {
  52. return false, err
  53. }
  54. }
  55. if len(session.statement.TableName()) <= 0 {
  56. return false, ErrTableNotFound
  57. }
  58. session.statement.Limit(1)
  59. sqlStr, args, err = session.statement.genGetSQL(bean[0])
  60. if err != nil {
  61. return false, err
  62. }
  63. }
  64. } else {
  65. sqlStr = session.statement.RawSQL
  66. args = session.statement.RawParams
  67. }
  68. rows, err := session.queryRows(sqlStr, args...)
  69. if err != nil {
  70. return false, err
  71. }
  72. defer rows.Close()
  73. return rows.Next(), nil
  74. }