scope.go 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  1. package gorm
  2. import (
  3. "database/sql"
  4. "database/sql/driver"
  5. "errors"
  6. "fmt"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "reflect"
  12. )
  13. // Scope contain current operation's information when you perform any operation on the database
  14. type Scope struct {
  15. Search *search
  16. Value interface{}
  17. SQL string
  18. SQLVars []interface{}
  19. db *DB
  20. instanceID string
  21. primaryKeyField *Field
  22. skipLeft bool
  23. fields *[]*Field
  24. selectAttrs *[]string
  25. }
  26. // IndirectValue return scope's reflect value's indirect value
  27. func (scope *Scope) IndirectValue() reflect.Value {
  28. return indirect(reflect.ValueOf(scope.Value))
  29. }
  30. // New create a new Scope without search information
  31. func (scope *Scope) New(value interface{}) *Scope {
  32. return &Scope{db: scope.NewDB(), Search: &search{}, Value: value}
  33. }
  34. ////////////////////////////////////////////////////////////////////////////////
  35. // Scope DB
  36. ////////////////////////////////////////////////////////////////////////////////
  37. // DB return scope's DB connection
  38. func (scope *Scope) DB() *DB {
  39. return scope.db
  40. }
  41. // NewDB create a new DB without search information
  42. func (scope *Scope) NewDB() *DB {
  43. if scope.db != nil {
  44. db := scope.db.clone()
  45. db.search = nil
  46. db.Value = nil
  47. return db
  48. }
  49. return nil
  50. }
  51. // SQLDB return *sql.DB
  52. func (scope *Scope) SQLDB() sqlCommon {
  53. return scope.db.db
  54. }
  55. // Dialect get dialect
  56. func (scope *Scope) Dialect() Dialect {
  57. return scope.db.parent.dialect
  58. }
  59. // Quote used to quote string to escape them for database
  60. func (scope *Scope) Quote(str string) string {
  61. if strings.Index(str, ".") != -1 {
  62. newStrs := []string{}
  63. for _, str := range strings.Split(str, ".") {
  64. newStrs = append(newStrs, scope.Dialect().Quote(str))
  65. }
  66. return strings.Join(newStrs, ".")
  67. }
  68. return scope.Dialect().Quote(str)
  69. }
  70. // Err add error to Scope
  71. func (scope *Scope) Err(err error) error {
  72. if err != nil {
  73. scope.db.AddError(err)
  74. }
  75. return err
  76. }
  77. // HasError check if there are any error
  78. func (scope *Scope) HasError() bool {
  79. return scope.db.Error != nil
  80. }
  81. // Log print log message
  82. func (scope *Scope) Log(v ...interface{}) {
  83. scope.db.log(v...)
  84. }
  85. // SkipLeft skip remaining callbacks
  86. func (scope *Scope) SkipLeft() {
  87. scope.skipLeft = true
  88. }
  89. // Fields get value's fields
  90. func (scope *Scope) Fields() []*Field {
  91. if scope.fields == nil {
  92. var (
  93. fields []*Field
  94. indirectScopeValue = scope.IndirectValue()
  95. isStruct = indirectScopeValue.Kind() == reflect.Struct
  96. )
  97. for _, structField := range scope.GetModelStruct().StructFields {
  98. if isStruct {
  99. fieldValue := indirectScopeValue
  100. for _, name := range structField.Names {
  101. fieldValue = reflect.Indirect(fieldValue).FieldByName(name)
  102. }
  103. fields = append(fields, &Field{StructField: structField, Field: fieldValue, IsBlank: isBlank(fieldValue)})
  104. } else {
  105. fields = append(fields, &Field{StructField: structField, IsBlank: true})
  106. }
  107. }
  108. scope.fields = &fields
  109. }
  110. return *scope.fields
  111. }
  112. // FieldByName find `gorm.Field` with field name or db name
  113. func (scope *Scope) FieldByName(name string) (field *Field, ok bool) {
  114. var (
  115. dbName = ToDBName(name)
  116. mostMatchedField *Field
  117. )
  118. for _, field := range scope.Fields() {
  119. if field.Name == name || field.DBName == name {
  120. return field, true
  121. }
  122. if field.DBName == dbName {
  123. mostMatchedField = field
  124. }
  125. }
  126. return mostMatchedField, mostMatchedField != nil
  127. }
  128. // PrimaryFields return scope's primary fields
  129. func (scope *Scope) PrimaryFields() (fields []*Field) {
  130. for _, field := range scope.Fields() {
  131. if field.IsPrimaryKey {
  132. fields = append(fields, field)
  133. }
  134. }
  135. return fields
  136. }
  137. // PrimaryField return scope's main primary field, if defined more that one primary fields, will return the one having column name `id` or the first one
  138. func (scope *Scope) PrimaryField() *Field {
  139. if primaryFields := scope.GetModelStruct().PrimaryFields; len(primaryFields) > 0 {
  140. if len(primaryFields) > 1 {
  141. if field, ok := scope.FieldByName("id"); ok {
  142. return field
  143. }
  144. }
  145. return scope.PrimaryFields()[0]
  146. }
  147. return nil
  148. }
  149. // PrimaryKey get main primary field's db name
  150. func (scope *Scope) PrimaryKey() string {
  151. if field := scope.PrimaryField(); field != nil {
  152. return field.DBName
  153. }
  154. return ""
  155. }
  156. // PrimaryKeyZero check main primary field's value is blank or not
  157. func (scope *Scope) PrimaryKeyZero() bool {
  158. field := scope.PrimaryField()
  159. return field == nil || field.IsBlank
  160. }
  161. // PrimaryKeyValue get the primary key's value
  162. func (scope *Scope) PrimaryKeyValue() interface{} {
  163. if field := scope.PrimaryField(); field != nil && field.Field.IsValid() {
  164. return field.Field.Interface()
  165. }
  166. return 0
  167. }
  168. // HasColumn to check if has column
  169. func (scope *Scope) HasColumn(column string) bool {
  170. for _, field := range scope.GetStructFields() {
  171. if field.IsNormal && (field.Name == column || field.DBName == column) {
  172. return true
  173. }
  174. }
  175. return false
  176. }
  177. // SetColumn to set the column's value, column could be field or field's name/dbname
  178. func (scope *Scope) SetColumn(column interface{}, value interface{}) error {
  179. var updateAttrs = map[string]interface{}{}
  180. if attrs, ok := scope.InstanceGet("gorm:update_attrs"); ok {
  181. updateAttrs = attrs.(map[string]interface{})
  182. defer scope.InstanceSet("gorm:update_attrs", updateAttrs)
  183. }
  184. if field, ok := column.(*Field); ok {
  185. updateAttrs[field.DBName] = value
  186. return field.Set(value)
  187. } else if name, ok := column.(string); ok {
  188. var (
  189. dbName = ToDBName(name)
  190. mostMatchedField *Field
  191. )
  192. for _, field := range scope.Fields() {
  193. if field.DBName == value {
  194. updateAttrs[field.DBName] = value
  195. return field.Set(value)
  196. }
  197. if (field.DBName == dbName) || (field.Name == name && mostMatchedField == nil) {
  198. mostMatchedField = field
  199. }
  200. }
  201. if mostMatchedField != nil {
  202. updateAttrs[mostMatchedField.DBName] = value
  203. return mostMatchedField.Set(value)
  204. }
  205. }
  206. return errors.New("could not convert column to field")
  207. }
  208. // CallMethod call scope value's method, if it is a slice, will call its element's method one by one
  209. func (scope *Scope) CallMethod(methodName string) {
  210. if scope.Value == nil {
  211. return
  212. }
  213. if indirectScopeValue := scope.IndirectValue(); indirectScopeValue.Kind() == reflect.Slice {
  214. for i := 0; i < indirectScopeValue.Len(); i++ {
  215. scope.callMethod(methodName, indirectScopeValue.Index(i))
  216. }
  217. } else {
  218. scope.callMethod(methodName, indirectScopeValue)
  219. }
  220. }
  221. // AddToVars add value as sql's vars, used to prevent SQL injection
  222. func (scope *Scope) AddToVars(value interface{}) string {
  223. if expr, ok := value.(*expr); ok {
  224. exp := expr.expr
  225. for _, arg := range expr.args {
  226. exp = strings.Replace(exp, "?", scope.AddToVars(arg), 1)
  227. }
  228. return exp
  229. }
  230. scope.SQLVars = append(scope.SQLVars, value)
  231. return scope.Dialect().BindVar(len(scope.SQLVars))
  232. }
  233. // SelectAttrs return selected attributes
  234. func (scope *Scope) SelectAttrs() []string {
  235. if scope.selectAttrs == nil {
  236. attrs := []string{}
  237. for _, value := range scope.Search.selects {
  238. if str, ok := value.(string); ok {
  239. attrs = append(attrs, str)
  240. } else if strs, ok := value.([]string); ok {
  241. attrs = append(attrs, strs...)
  242. } else if strs, ok := value.([]interface{}); ok {
  243. for _, str := range strs {
  244. attrs = append(attrs, fmt.Sprintf("%v", str))
  245. }
  246. }
  247. }
  248. scope.selectAttrs = &attrs
  249. }
  250. return *scope.selectAttrs
  251. }
  252. // OmitAttrs return omitted attributes
  253. func (scope *Scope) OmitAttrs() []string {
  254. return scope.Search.omits
  255. }
  256. type tabler interface {
  257. TableName() string
  258. }
  259. type dbTabler interface {
  260. TableName(*DB) string
  261. }
  262. // TableName return table name
  263. func (scope *Scope) TableName() string {
  264. if scope.Search != nil && len(scope.Search.tableName) > 0 {
  265. return scope.Search.tableName
  266. }
  267. if tabler, ok := scope.Value.(tabler); ok {
  268. return tabler.TableName()
  269. }
  270. if tabler, ok := scope.Value.(dbTabler); ok {
  271. return tabler.TableName(scope.db)
  272. }
  273. return scope.GetModelStruct().TableName(scope.db.Model(scope.Value))
  274. }
  275. // QuotedTableName return quoted table name
  276. func (scope *Scope) QuotedTableName() (name string) {
  277. if scope.Search != nil && len(scope.Search.tableName) > 0 {
  278. if strings.Index(scope.Search.tableName, " ") != -1 {
  279. return scope.Search.tableName
  280. }
  281. return scope.Quote(scope.Search.tableName)
  282. }
  283. return scope.Quote(scope.TableName())
  284. }
  285. // CombinedConditionSql return combined condition sql
  286. func (scope *Scope) CombinedConditionSql() string {
  287. joinSql := scope.joinsSQL()
  288. whereSql := scope.whereSQL()
  289. if scope.Search.raw {
  290. whereSql = strings.TrimSuffix(strings.TrimPrefix(whereSql, "WHERE ("), ")")
  291. }
  292. return joinSql + whereSql + scope.groupSQL() +
  293. scope.havingSQL() + scope.orderSQL() + scope.limitAndOffsetSQL()
  294. }
  295. // Raw set raw sql
  296. func (scope *Scope) Raw(sql string) *Scope {
  297. scope.SQL = strings.Replace(sql, "$$", "?", -1)
  298. return scope
  299. }
  300. // Exec perform generated SQL
  301. func (scope *Scope) Exec() *Scope {
  302. defer scope.trace(NowFunc())
  303. if !scope.HasError() {
  304. if result, err := scope.SQLDB().Exec(scope.SQL, scope.SQLVars...); scope.Err(err) == nil {
  305. if count, err := result.RowsAffected(); scope.Err(err) == nil {
  306. scope.db.RowsAffected = count
  307. }
  308. }
  309. }
  310. return scope
  311. }
  312. // Set set value by name
  313. func (scope *Scope) Set(name string, value interface{}) *Scope {
  314. scope.db.InstantSet(name, value)
  315. return scope
  316. }
  317. // Get get setting by name
  318. func (scope *Scope) Get(name string) (interface{}, bool) {
  319. return scope.db.Get(name)
  320. }
  321. // InstanceID get InstanceID for scope
  322. func (scope *Scope) InstanceID() string {
  323. if scope.instanceID == "" {
  324. scope.instanceID = fmt.Sprintf("%v%v", &scope, &scope.db)
  325. }
  326. return scope.instanceID
  327. }
  328. // InstanceSet set instance setting for current operation, but not for operations in callbacks, like saving associations callback
  329. func (scope *Scope) InstanceSet(name string, value interface{}) *Scope {
  330. return scope.Set(name+scope.InstanceID(), value)
  331. }
  332. // InstanceGet get instance setting from current operation
  333. func (scope *Scope) InstanceGet(name string) (interface{}, bool) {
  334. return scope.Get(name + scope.InstanceID())
  335. }
  336. // Begin start a transaction
  337. func (scope *Scope) Begin() *Scope {
  338. if db, ok := scope.SQLDB().(sqlDb); ok {
  339. if tx, err := db.Begin(); err == nil {
  340. scope.db.db = interface{}(tx).(sqlCommon)
  341. scope.InstanceSet("gorm:started_transaction", true)
  342. }
  343. }
  344. return scope
  345. }
  346. // CommitOrRollback commit current transaction if no error happened, otherwise will rollback it
  347. func (scope *Scope) CommitOrRollback() *Scope {
  348. if _, ok := scope.InstanceGet("gorm:started_transaction"); ok {
  349. if db, ok := scope.db.db.(sqlTx); ok {
  350. if scope.HasError() {
  351. db.Rollback()
  352. } else {
  353. scope.Err(db.Commit())
  354. }
  355. scope.db.db = scope.db.parent.db
  356. }
  357. }
  358. return scope
  359. }
  360. ////////////////////////////////////////////////////////////////////////////////
  361. // Private Methods For *gorm.Scope
  362. ////////////////////////////////////////////////////////////////////////////////
  363. func (scope *Scope) callMethod(methodName string, reflectValue reflect.Value) {
  364. // Only get address from non-pointer
  365. if reflectValue.CanAddr() && reflectValue.Kind() != reflect.Ptr {
  366. reflectValue = reflectValue.Addr()
  367. }
  368. if methodValue := reflectValue.MethodByName(methodName); methodValue.IsValid() {
  369. switch method := methodValue.Interface().(type) {
  370. case func():
  371. method()
  372. case func(*Scope):
  373. method(scope)
  374. case func(*DB):
  375. newDB := scope.NewDB()
  376. method(newDB)
  377. scope.Err(newDB.Error)
  378. case func() error:
  379. scope.Err(method())
  380. case func(*Scope) error:
  381. scope.Err(method(scope))
  382. case func(*DB) error:
  383. newDB := scope.NewDB()
  384. scope.Err(method(newDB))
  385. scope.Err(newDB.Error)
  386. default:
  387. scope.Err(fmt.Errorf("unsupported function %v", methodName))
  388. }
  389. }
  390. }
  391. var (
  392. columnRegexp = regexp.MustCompile("^[a-zA-Z]+(\\.[a-zA-Z]+)*$") // only match string like `name`, `users.name`
  393. isNumberRegexp = regexp.MustCompile("^\\s*\\d+\\s*$") // match if string is number
  394. comparisonRegexp = regexp.MustCompile("(?i) (=|<>|>|<|LIKE|IS|IN) ")
  395. countingQueryRegexp = regexp.MustCompile("(?i)^count(.+)$")
  396. )
  397. func (scope *Scope) quoteIfPossible(str string) string {
  398. if columnRegexp.MatchString(str) {
  399. return scope.Quote(str)
  400. }
  401. return str
  402. }
  403. func (scope *Scope) scan(rows *sql.Rows, columns []string, fields []*Field) {
  404. var (
  405. ignored interface{}
  406. values = make([]interface{}, len(columns))
  407. selectFields []*Field
  408. selectedColumnsMap = map[string]int{}
  409. resetFields = map[int]*Field{}
  410. )
  411. for index, column := range columns {
  412. values[index] = &ignored
  413. selectFields = fields
  414. if idx, ok := selectedColumnsMap[column]; ok {
  415. selectFields = selectFields[idx+1:]
  416. }
  417. for fieldIndex, field := range selectFields {
  418. if field.DBName == column {
  419. if field.Field.Kind() == reflect.Ptr {
  420. values[index] = field.Field.Addr().Interface()
  421. } else {
  422. reflectValue := reflect.New(reflect.PtrTo(field.Struct.Type))
  423. reflectValue.Elem().Set(field.Field.Addr())
  424. values[index] = reflectValue.Interface()
  425. resetFields[index] = field
  426. }
  427. selectedColumnsMap[column] = fieldIndex
  428. if field.IsNormal {
  429. break
  430. }
  431. }
  432. }
  433. }
  434. scope.Err(rows.Scan(values...))
  435. for index, field := range resetFields {
  436. if v := reflect.ValueOf(values[index]).Elem().Elem(); v.IsValid() {
  437. field.Field.Set(v)
  438. }
  439. }
  440. }
  441. func (scope *Scope) primaryCondition(value interface{}) string {
  442. return fmt.Sprintf("(%v.%v = %v)", scope.QuotedTableName(), scope.Quote(scope.PrimaryKey()), value)
  443. }
  444. func (scope *Scope) buildWhereCondition(clause map[string]interface{}) (str string) {
  445. switch value := clause["query"].(type) {
  446. case string:
  447. if isNumberRegexp.MatchString(value) {
  448. return scope.primaryCondition(scope.AddToVars(value))
  449. } else if value != "" {
  450. str = fmt.Sprintf("(%v)", value)
  451. }
  452. case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, sql.NullInt64:
  453. return scope.primaryCondition(scope.AddToVars(value))
  454. case []int, []int8, []int16, []int32, []int64, []uint, []uint8, []uint16, []uint32, []uint64, []string, []interface{}:
  455. str = fmt.Sprintf("(%v.%v IN (?))", scope.QuotedTableName(), scope.Quote(scope.PrimaryKey()))
  456. clause["args"] = []interface{}{value}
  457. case map[string]interface{}:
  458. var sqls []string
  459. for key, value := range value {
  460. if value != nil {
  461. sqls = append(sqls, fmt.Sprintf("(%v.%v = %v)", scope.QuotedTableName(), scope.Quote(key), scope.AddToVars(value)))
  462. } else {
  463. sqls = append(sqls, fmt.Sprintf("(%v.%v IS NULL)", scope.QuotedTableName(), scope.Quote(key)))
  464. }
  465. }
  466. return strings.Join(sqls, " AND ")
  467. case interface{}:
  468. var sqls []string
  469. newScope := scope.New(value)
  470. for _, field := range newScope.Fields() {
  471. if !field.IsIgnored && !field.IsBlank {
  472. sqls = append(sqls, fmt.Sprintf("(%v.%v = %v)", scope.QuotedTableName(), scope.Quote(field.DBName), scope.AddToVars(field.Field.Interface())))
  473. }
  474. }
  475. return strings.Join(sqls, " AND ")
  476. }
  477. args := clause["args"].([]interface{})
  478. for _, arg := range args {
  479. switch reflect.ValueOf(arg).Kind() {
  480. case reflect.Slice: // For where("id in (?)", []int64{1,2})
  481. if bytes, ok := arg.([]byte); ok {
  482. str = strings.Replace(str, "?", scope.AddToVars(bytes), 1)
  483. } else if values := reflect.ValueOf(arg); values.Len() > 0 {
  484. var tempMarks []string
  485. for i := 0; i < values.Len(); i++ {
  486. tempMarks = append(tempMarks, scope.AddToVars(values.Index(i).Interface()))
  487. }
  488. str = strings.Replace(str, "?", strings.Join(tempMarks, ","), 1)
  489. } else {
  490. str = strings.Replace(str, "?", scope.AddToVars(Expr("NULL")), 1)
  491. }
  492. default:
  493. if valuer, ok := interface{}(arg).(driver.Valuer); ok {
  494. arg, _ = valuer.Value()
  495. }
  496. str = strings.Replace(str, "?", scope.AddToVars(arg), 1)
  497. }
  498. }
  499. return
  500. }
  501. func (scope *Scope) buildNotCondition(clause map[string]interface{}) (str string) {
  502. var notEqualSQL string
  503. var primaryKey = scope.PrimaryKey()
  504. switch value := clause["query"].(type) {
  505. case string:
  506. if isNumberRegexp.MatchString(value) {
  507. id, _ := strconv.Atoi(value)
  508. return fmt.Sprintf("(%v <> %v)", scope.Quote(primaryKey), id)
  509. } else if comparisonRegexp.MatchString(value) {
  510. str = fmt.Sprintf(" NOT (%v) ", value)
  511. notEqualSQL = fmt.Sprintf("NOT (%v)", value)
  512. } else {
  513. str = fmt.Sprintf("(%v.%v NOT IN (?))", scope.QuotedTableName(), scope.Quote(value))
  514. notEqualSQL = fmt.Sprintf("(%v.%v <> ?)", scope.QuotedTableName(), scope.Quote(value))
  515. }
  516. case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, sql.NullInt64:
  517. return fmt.Sprintf("(%v.%v <> %v)", scope.QuotedTableName(), scope.Quote(primaryKey), value)
  518. case []int, []int8, []int16, []int32, []int64, []uint, []uint8, []uint16, []uint32, []uint64, []string:
  519. if reflect.ValueOf(value).Len() > 0 {
  520. str = fmt.Sprintf("(%v.%v NOT IN (?))", scope.QuotedTableName(), scope.Quote(primaryKey))
  521. clause["args"] = []interface{}{value}
  522. } else {
  523. return ""
  524. }
  525. case map[string]interface{}:
  526. var sqls []string
  527. for key, value := range value {
  528. if value != nil {
  529. sqls = append(sqls, fmt.Sprintf("(%v.%v <> %v)", scope.QuotedTableName(), scope.Quote(key), scope.AddToVars(value)))
  530. } else {
  531. sqls = append(sqls, fmt.Sprintf("(%v.%v IS NOT NULL)", scope.QuotedTableName(), scope.Quote(key)))
  532. }
  533. }
  534. return strings.Join(sqls, " AND ")
  535. case interface{}:
  536. var sqls []string
  537. var newScope = scope.New(value)
  538. for _, field := range newScope.Fields() {
  539. if !field.IsBlank {
  540. sqls = append(sqls, fmt.Sprintf("(%v.%v <> %v)", scope.QuotedTableName(), scope.Quote(field.DBName), scope.AddToVars(field.Field.Interface())))
  541. }
  542. }
  543. return strings.Join(sqls, " AND ")
  544. }
  545. args := clause["args"].([]interface{})
  546. for _, arg := range args {
  547. switch reflect.ValueOf(arg).Kind() {
  548. case reflect.Slice: // For where("id in (?)", []int64{1,2})
  549. if bytes, ok := arg.([]byte); ok {
  550. str = strings.Replace(str, "?", scope.AddToVars(bytes), 1)
  551. } else if values := reflect.ValueOf(arg); values.Len() > 0 {
  552. var tempMarks []string
  553. for i := 0; i < values.Len(); i++ {
  554. tempMarks = append(tempMarks, scope.AddToVars(values.Index(i).Interface()))
  555. }
  556. str = strings.Replace(str, "?", strings.Join(tempMarks, ","), 1)
  557. } else {
  558. str = strings.Replace(str, "?", scope.AddToVars(Expr("NULL")), 1)
  559. }
  560. default:
  561. if scanner, ok := interface{}(arg).(driver.Valuer); ok {
  562. arg, _ = scanner.Value()
  563. }
  564. str = strings.Replace(notEqualSQL, "?", scope.AddToVars(arg), 1)
  565. }
  566. }
  567. return
  568. }
  569. func (scope *Scope) buildSelectQuery(clause map[string]interface{}) (str string) {
  570. switch value := clause["query"].(type) {
  571. case string:
  572. str = value
  573. case []string:
  574. str = strings.Join(value, ", ")
  575. }
  576. args := clause["args"].([]interface{})
  577. for _, arg := range args {
  578. switch reflect.ValueOf(arg).Kind() {
  579. case reflect.Slice:
  580. values := reflect.ValueOf(arg)
  581. var tempMarks []string
  582. for i := 0; i < values.Len(); i++ {
  583. tempMarks = append(tempMarks, scope.AddToVars(values.Index(i).Interface()))
  584. }
  585. str = strings.Replace(str, "?", strings.Join(tempMarks, ","), 1)
  586. default:
  587. if valuer, ok := interface{}(arg).(driver.Valuer); ok {
  588. arg, _ = valuer.Value()
  589. }
  590. str = strings.Replace(str, "?", scope.AddToVars(arg), 1)
  591. }
  592. }
  593. return
  594. }
  595. func (scope *Scope) whereSQL() (sql string) {
  596. var (
  597. quotedTableName = scope.QuotedTableName()
  598. primaryConditions, andConditions, orConditions []string
  599. )
  600. if !scope.Search.Unscoped && scope.HasColumn("deleted_at") {
  601. sql := fmt.Sprintf("%v.deleted_at IS NULL", quotedTableName)
  602. primaryConditions = append(primaryConditions, sql)
  603. }
  604. if !scope.PrimaryKeyZero() {
  605. for _, field := range scope.PrimaryFields() {
  606. sql := fmt.Sprintf("%v.%v = %v", quotedTableName, scope.Quote(field.DBName), scope.AddToVars(field.Field.Interface()))
  607. primaryConditions = append(primaryConditions, sql)
  608. }
  609. }
  610. for _, clause := range scope.Search.whereConditions {
  611. if sql := scope.buildWhereCondition(clause); sql != "" {
  612. andConditions = append(andConditions, sql)
  613. }
  614. }
  615. for _, clause := range scope.Search.orConditions {
  616. if sql := scope.buildWhereCondition(clause); sql != "" {
  617. orConditions = append(orConditions, sql)
  618. }
  619. }
  620. for _, clause := range scope.Search.notConditions {
  621. if sql := scope.buildNotCondition(clause); sql != "" {
  622. andConditions = append(andConditions, sql)
  623. }
  624. }
  625. orSQL := strings.Join(orConditions, " OR ")
  626. combinedSQL := strings.Join(andConditions, " AND ")
  627. if len(combinedSQL) > 0 {
  628. if len(orSQL) > 0 {
  629. combinedSQL = combinedSQL + " OR " + orSQL
  630. }
  631. } else {
  632. combinedSQL = orSQL
  633. }
  634. if len(primaryConditions) > 0 {
  635. sql = "WHERE " + strings.Join(primaryConditions, " AND ")
  636. if len(combinedSQL) > 0 {
  637. sql = sql + " AND (" + combinedSQL + ")"
  638. }
  639. } else if len(combinedSQL) > 0 {
  640. sql = "WHERE " + combinedSQL
  641. }
  642. return
  643. }
  644. func (scope *Scope) selectSQL() string {
  645. if len(scope.Search.selects) == 0 {
  646. if len(scope.Search.joinConditions) > 0 {
  647. return fmt.Sprintf("%v.*", scope.QuotedTableName())
  648. }
  649. return "*"
  650. }
  651. return scope.buildSelectQuery(scope.Search.selects)
  652. }
  653. func (scope *Scope) orderSQL() string {
  654. if len(scope.Search.orders) == 0 || scope.Search.ignoreOrderQuery {
  655. return ""
  656. }
  657. var orders []string
  658. for _, order := range scope.Search.orders {
  659. if str, ok := order.(string); ok {
  660. orders = append(orders, scope.quoteIfPossible(str))
  661. } else if expr, ok := order.(*expr); ok {
  662. exp := expr.expr
  663. for _, arg := range expr.args {
  664. exp = strings.Replace(exp, "?", scope.AddToVars(arg), 1)
  665. }
  666. orders = append(orders, exp)
  667. }
  668. }
  669. return " ORDER BY " + strings.Join(orders, ",")
  670. }
  671. func (scope *Scope) limitAndOffsetSQL() string {
  672. return scope.Dialect().LimitAndOffsetSQL(scope.Search.limit, scope.Search.offset)
  673. }
  674. func (scope *Scope) groupSQL() string {
  675. if len(scope.Search.group) == 0 {
  676. return ""
  677. }
  678. return " GROUP BY " + scope.Search.group
  679. }
  680. func (scope *Scope) havingSQL() string {
  681. if len(scope.Search.havingConditions) == 0 {
  682. return ""
  683. }
  684. var andConditions []string
  685. for _, clause := range scope.Search.havingConditions {
  686. if sql := scope.buildWhereCondition(clause); sql != "" {
  687. andConditions = append(andConditions, sql)
  688. }
  689. }
  690. combinedSQL := strings.Join(andConditions, " AND ")
  691. if len(combinedSQL) == 0 {
  692. return ""
  693. }
  694. return " HAVING " + combinedSQL
  695. }
  696. func (scope *Scope) joinsSQL() string {
  697. var joinConditions []string
  698. for _, clause := range scope.Search.joinConditions {
  699. if sql := scope.buildWhereCondition(clause); sql != "" {
  700. joinConditions = append(joinConditions, strings.TrimSuffix(strings.TrimPrefix(sql, "("), ")"))
  701. }
  702. }
  703. return strings.Join(joinConditions, " ") + " "
  704. }
  705. func (scope *Scope) prepareQuerySQL() {
  706. if scope.Search.raw {
  707. scope.Raw(scope.CombinedConditionSql())
  708. } else {
  709. scope.Raw(fmt.Sprintf("SELECT %v FROM %v %v", scope.selectSQL(), scope.QuotedTableName(), scope.CombinedConditionSql()))
  710. }
  711. return
  712. }
  713. func (scope *Scope) inlineCondition(values ...interface{}) *Scope {
  714. if len(values) > 0 {
  715. scope.Search.Where(values[0], values[1:]...)
  716. }
  717. return scope
  718. }
  719. func (scope *Scope) callCallbacks(funcs []*func(s *Scope)) *Scope {
  720. for _, f := range funcs {
  721. (*f)(scope)
  722. if scope.skipLeft {
  723. break
  724. }
  725. }
  726. return scope
  727. }
  728. func convertInterfaceToMap(values interface{}, withIgnoredField bool) map[string]interface{} {
  729. var attrs = map[string]interface{}{}
  730. switch value := values.(type) {
  731. case map[string]interface{}:
  732. return value
  733. case []interface{}:
  734. for _, v := range value {
  735. for key, value := range convertInterfaceToMap(v, withIgnoredField) {
  736. attrs[key] = value
  737. }
  738. }
  739. case interface{}:
  740. reflectValue := reflect.ValueOf(values)
  741. switch reflectValue.Kind() {
  742. case reflect.Map:
  743. for _, key := range reflectValue.MapKeys() {
  744. attrs[ToDBName(key.Interface().(string))] = reflectValue.MapIndex(key).Interface()
  745. }
  746. default:
  747. for _, field := range (&Scope{Value: values}).Fields() {
  748. if !field.IsBlank && (withIgnoredField || !field.IsIgnored) {
  749. attrs[field.DBName] = field.Field.Interface()
  750. }
  751. }
  752. }
  753. }
  754. return attrs
  755. }
  756. func (scope *Scope) updatedAttrsWithValues(value interface{}) (results map[string]interface{}, hasUpdate bool) {
  757. if scope.IndirectValue().Kind() != reflect.Struct {
  758. return convertInterfaceToMap(value, false), true
  759. }
  760. results = map[string]interface{}{}
  761. for key, value := range convertInterfaceToMap(value, true) {
  762. if field, ok := scope.FieldByName(key); ok && scope.changeableField(field) {
  763. if _, ok := value.(*expr); ok {
  764. hasUpdate = true
  765. results[field.DBName] = value
  766. } else {
  767. err := field.Set(value)
  768. if field.IsNormal {
  769. hasUpdate = true
  770. if err == ErrUnaddressable {
  771. results[field.DBName] = value
  772. } else {
  773. results[field.DBName] = field.Field.Interface()
  774. }
  775. }
  776. }
  777. }
  778. }
  779. return
  780. }
  781. func (scope *Scope) row() *sql.Row {
  782. defer scope.trace(NowFunc())
  783. result := &RowQueryResult{}
  784. scope.InstanceSet("row_query_result", result)
  785. scope.callCallbacks(scope.db.parent.callbacks.rowQueries)
  786. return result.Row
  787. }
  788. func (scope *Scope) rows() (*sql.Rows, error) {
  789. defer scope.trace(NowFunc())
  790. result := &RowsQueryResult{}
  791. scope.InstanceSet("row_query_result", result)
  792. scope.callCallbacks(scope.db.parent.callbacks.rowQueries)
  793. return result.Rows, result.Error
  794. }
  795. func (scope *Scope) initialize() *Scope {
  796. for _, clause := range scope.Search.whereConditions {
  797. scope.updatedAttrsWithValues(clause["query"])
  798. }
  799. scope.updatedAttrsWithValues(scope.Search.initAttrs)
  800. scope.updatedAttrsWithValues(scope.Search.assignAttrs)
  801. return scope
  802. }
  803. func (scope *Scope) pluck(column string, value interface{}) *Scope {
  804. dest := reflect.Indirect(reflect.ValueOf(value))
  805. scope.Search.Select(column)
  806. if dest.Kind() != reflect.Slice {
  807. scope.Err(fmt.Errorf("results should be a slice, not %s", dest.Kind()))
  808. return scope
  809. }
  810. rows, err := scope.rows()
  811. if scope.Err(err) == nil {
  812. defer rows.Close()
  813. for rows.Next() {
  814. elem := reflect.New(dest.Type().Elem()).Interface()
  815. scope.Err(rows.Scan(elem))
  816. dest.Set(reflect.Append(dest, reflect.ValueOf(elem).Elem()))
  817. }
  818. }
  819. return scope
  820. }
  821. func (scope *Scope) count(value interface{}) *Scope {
  822. if query, ok := scope.Search.selects["query"]; !ok || !countingQueryRegexp.MatchString(fmt.Sprint(query)) {
  823. scope.Search.Select("count(*)")
  824. }
  825. scope.Search.ignoreOrderQuery = true
  826. scope.Err(scope.row().Scan(value))
  827. return scope
  828. }
  829. func (scope *Scope) typeName() string {
  830. typ := scope.IndirectValue().Type()
  831. for typ.Kind() == reflect.Slice || typ.Kind() == reflect.Ptr {
  832. typ = typ.Elem()
  833. }
  834. return typ.Name()
  835. }
  836. // trace print sql log
  837. func (scope *Scope) trace(t time.Time) {
  838. if len(scope.SQL) > 0 {
  839. scope.db.slog(scope.SQL, t, scope.SQLVars...)
  840. }
  841. }
  842. func (scope *Scope) changeableField(field *Field) bool {
  843. if selectAttrs := scope.SelectAttrs(); len(selectAttrs) > 0 {
  844. for _, attr := range selectAttrs {
  845. if field.Name == attr || field.DBName == attr {
  846. return true
  847. }
  848. }
  849. return false
  850. }
  851. for _, attr := range scope.OmitAttrs() {
  852. if field.Name == attr || field.DBName == attr {
  853. return false
  854. }
  855. }
  856. return true
  857. }
  858. func (scope *Scope) shouldSaveAssociations() bool {
  859. if saveAssociations, ok := scope.Get("gorm:save_associations"); ok {
  860. if v, ok := saveAssociations.(bool); ok && !v {
  861. return false
  862. }
  863. if v, ok := saveAssociations.(string); ok && (v != "skip") {
  864. return false
  865. }
  866. }
  867. return true && !scope.HasError()
  868. }
  869. func (scope *Scope) related(value interface{}, foreignKeys ...string) *Scope {
  870. toScope := scope.db.NewScope(value)
  871. tx := scope.db.Set("gorm:association:source", scope.Value)
  872. for _, foreignKey := range append(foreignKeys, toScope.typeName()+"Id", scope.typeName()+"Id") {
  873. fromField, _ := scope.FieldByName(foreignKey)
  874. toField, _ := toScope.FieldByName(foreignKey)
  875. if fromField != nil {
  876. if relationship := fromField.Relationship; relationship != nil {
  877. if relationship.Kind == "many_to_many" {
  878. joinTableHandler := relationship.JoinTableHandler
  879. scope.Err(joinTableHandler.JoinWith(joinTableHandler, tx, scope.Value).Find(value).Error)
  880. } else if relationship.Kind == "belongs_to" {
  881. for idx, foreignKey := range relationship.ForeignDBNames {
  882. if field, ok := scope.FieldByName(foreignKey); ok {
  883. tx = tx.Where(fmt.Sprintf("%v = ?", scope.Quote(relationship.AssociationForeignDBNames[idx])), field.Field.Interface())
  884. }
  885. }
  886. scope.Err(tx.Find(value).Error)
  887. } else if relationship.Kind == "has_many" || relationship.Kind == "has_one" {
  888. for idx, foreignKey := range relationship.ForeignDBNames {
  889. if field, ok := scope.FieldByName(relationship.AssociationForeignDBNames[idx]); ok {
  890. tx = tx.Where(fmt.Sprintf("%v = ?", scope.Quote(foreignKey)), field.Field.Interface())
  891. }
  892. }
  893. if relationship.PolymorphicType != "" {
  894. tx = tx.Where(fmt.Sprintf("%v = ?", scope.Quote(relationship.PolymorphicDBName)), relationship.PolymorphicValue)
  895. }
  896. scope.Err(tx.Find(value).Error)
  897. }
  898. } else {
  899. sql := fmt.Sprintf("%v = ?", scope.Quote(toScope.PrimaryKey()))
  900. scope.Err(tx.Where(sql, fromField.Field.Interface()).Find(value).Error)
  901. }
  902. return scope
  903. } else if toField != nil {
  904. sql := fmt.Sprintf("%v = ?", scope.Quote(toField.DBName))
  905. scope.Err(tx.Where(sql, scope.PrimaryKeyValue()).Find(value).Error)
  906. return scope
  907. }
  908. }
  909. scope.Err(fmt.Errorf("invalid association %v", foreignKeys))
  910. return scope
  911. }
  912. // getTableOptions return the table options string or an empty string if the table options does not exist
  913. func (scope *Scope) getTableOptions() string {
  914. tableOptions, ok := scope.Get("gorm:table_options")
  915. if !ok {
  916. return ""
  917. }
  918. return tableOptions.(string)
  919. }
  920. func (scope *Scope) createJoinTable(field *StructField) {
  921. if relationship := field.Relationship; relationship != nil && relationship.JoinTableHandler != nil {
  922. joinTableHandler := relationship.JoinTableHandler
  923. joinTable := joinTableHandler.Table(scope.db)
  924. if !scope.Dialect().HasTable(joinTable) {
  925. toScope := &Scope{Value: reflect.New(field.Struct.Type).Interface()}
  926. var sqlTypes, primaryKeys []string
  927. for idx, fieldName := range relationship.ForeignFieldNames {
  928. if field, ok := scope.FieldByName(fieldName); ok {
  929. foreignKeyStruct := field.clone()
  930. foreignKeyStruct.IsPrimaryKey = false
  931. foreignKeyStruct.TagSettings["IS_JOINTABLE_FOREIGNKEY"] = "true"
  932. delete(foreignKeyStruct.TagSettings, "AUTO_INCREMENT")
  933. sqlTypes = append(sqlTypes, scope.Quote(relationship.ForeignDBNames[idx])+" "+scope.Dialect().DataTypeOf(foreignKeyStruct))
  934. primaryKeys = append(primaryKeys, scope.Quote(relationship.ForeignDBNames[idx]))
  935. }
  936. }
  937. for idx, fieldName := range relationship.AssociationForeignFieldNames {
  938. if field, ok := toScope.FieldByName(fieldName); ok {
  939. foreignKeyStruct := field.clone()
  940. foreignKeyStruct.IsPrimaryKey = false
  941. foreignKeyStruct.TagSettings["IS_JOINTABLE_FOREIGNKEY"] = "true"
  942. delete(foreignKeyStruct.TagSettings, "AUTO_INCREMENT")
  943. sqlTypes = append(sqlTypes, scope.Quote(relationship.AssociationForeignDBNames[idx])+" "+scope.Dialect().DataTypeOf(foreignKeyStruct))
  944. primaryKeys = append(primaryKeys, scope.Quote(relationship.AssociationForeignDBNames[idx]))
  945. }
  946. }
  947. scope.Err(scope.NewDB().Exec(fmt.Sprintf("CREATE TABLE %v (%v, PRIMARY KEY (%v)) %s", scope.Quote(joinTable), strings.Join(sqlTypes, ","), strings.Join(primaryKeys, ","), scope.getTableOptions())).Error)
  948. }
  949. scope.NewDB().Table(joinTable).AutoMigrate(joinTableHandler)
  950. }
  951. }
  952. func (scope *Scope) createTable() *Scope {
  953. var tags []string
  954. var primaryKeys []string
  955. var primaryKeyInColumnType = false
  956. for _, field := range scope.GetModelStruct().StructFields {
  957. if field.IsNormal {
  958. sqlTag := scope.Dialect().DataTypeOf(field)
  959. // Check if the primary key constraint was specified as
  960. // part of the column type. If so, we can only support
  961. // one column as the primary key.
  962. if strings.Contains(strings.ToLower(sqlTag), "primary key") {
  963. primaryKeyInColumnType = true
  964. }
  965. tags = append(tags, scope.Quote(field.DBName)+" "+sqlTag)
  966. }
  967. if field.IsPrimaryKey {
  968. primaryKeys = append(primaryKeys, scope.Quote(field.DBName))
  969. }
  970. scope.createJoinTable(field)
  971. }
  972. var primaryKeyStr string
  973. if len(primaryKeys) > 0 && !primaryKeyInColumnType {
  974. primaryKeyStr = fmt.Sprintf(", PRIMARY KEY (%v)", strings.Join(primaryKeys, ","))
  975. }
  976. scope.Raw(fmt.Sprintf("CREATE TABLE %v (%v %v) %s", scope.QuotedTableName(), strings.Join(tags, ","), primaryKeyStr, scope.getTableOptions())).Exec()
  977. scope.autoIndex()
  978. return scope
  979. }
  980. func (scope *Scope) dropTable() *Scope {
  981. scope.Raw(fmt.Sprintf("DROP TABLE %v", scope.QuotedTableName())).Exec()
  982. return scope
  983. }
  984. func (scope *Scope) modifyColumn(column string, typ string) {
  985. scope.Raw(fmt.Sprintf("ALTER TABLE %v MODIFY %v %v", scope.QuotedTableName(), scope.Quote(column), typ)).Exec()
  986. }
  987. func (scope *Scope) dropColumn(column string) {
  988. scope.Raw(fmt.Sprintf("ALTER TABLE %v DROP COLUMN %v", scope.QuotedTableName(), scope.Quote(column))).Exec()
  989. }
  990. func (scope *Scope) addIndex(unique bool, indexName string, column ...string) {
  991. if scope.Dialect().HasIndex(scope.TableName(), indexName) {
  992. return
  993. }
  994. var columns []string
  995. for _, name := range column {
  996. columns = append(columns, scope.quoteIfPossible(name))
  997. }
  998. sqlCreate := "CREATE INDEX"
  999. if unique {
  1000. sqlCreate = "CREATE UNIQUE INDEX"
  1001. }
  1002. scope.Raw(fmt.Sprintf("%s %v ON %v(%v) %v", sqlCreate, indexName, scope.QuotedTableName(), strings.Join(columns, ", "), scope.whereSQL())).Exec()
  1003. }
  1004. func (scope *Scope) addForeignKey(field string, dest string, onDelete string, onUpdate string) {
  1005. keyName := scope.Dialect().BuildForeignKeyName(scope.TableName(), field, dest)
  1006. if scope.Dialect().HasForeignKey(scope.TableName(), keyName) {
  1007. return
  1008. }
  1009. var query = `ALTER TABLE %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s ON DELETE %s ON UPDATE %s;`
  1010. scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), scope.quoteIfPossible(keyName), scope.quoteIfPossible(field), dest, onDelete, onUpdate)).Exec()
  1011. }
  1012. func (scope *Scope) removeIndex(indexName string) {
  1013. scope.Dialect().RemoveIndex(scope.TableName(), indexName)
  1014. }
  1015. func (scope *Scope) autoMigrate() *Scope {
  1016. tableName := scope.TableName()
  1017. quotedTableName := scope.QuotedTableName()
  1018. if !scope.Dialect().HasTable(tableName) {
  1019. scope.createTable()
  1020. } else {
  1021. for _, field := range scope.GetModelStruct().StructFields {
  1022. if !scope.Dialect().HasColumn(tableName, field.DBName) {
  1023. if field.IsNormal {
  1024. sqlTag := scope.Dialect().DataTypeOf(field)
  1025. scope.Raw(fmt.Sprintf("ALTER TABLE %v ADD %v %v;", quotedTableName, scope.Quote(field.DBName), sqlTag)).Exec()
  1026. }
  1027. }
  1028. scope.createJoinTable(field)
  1029. }
  1030. scope.autoIndex()
  1031. }
  1032. return scope
  1033. }
  1034. func (scope *Scope) autoIndex() *Scope {
  1035. var indexes = map[string][]string{}
  1036. var uniqueIndexes = map[string][]string{}
  1037. for _, field := range scope.GetStructFields() {
  1038. if name, ok := field.TagSettings["INDEX"]; ok {
  1039. names := strings.Split(name, ",")
  1040. for _, name := range names {
  1041. if name == "INDEX" || name == "" {
  1042. name = fmt.Sprintf("idx_%v_%v", scope.TableName(), field.DBName)
  1043. }
  1044. indexes[name] = append(indexes[name], field.DBName)
  1045. }
  1046. }
  1047. if name, ok := field.TagSettings["UNIQUE_INDEX"]; ok {
  1048. names := strings.Split(name, ",")
  1049. for _, name := range names {
  1050. if name == "UNIQUE_INDEX" || name == "" {
  1051. name = fmt.Sprintf("uix_%v_%v", scope.TableName(), field.DBName)
  1052. }
  1053. uniqueIndexes[name] = append(uniqueIndexes[name], field.DBName)
  1054. }
  1055. }
  1056. }
  1057. for name, columns := range indexes {
  1058. scope.NewDB().Model(scope.Value).AddIndex(name, columns...)
  1059. }
  1060. for name, columns := range uniqueIndexes {
  1061. scope.NewDB().Model(scope.Value).AddUniqueIndex(name, columns...)
  1062. }
  1063. return scope
  1064. }
  1065. func (scope *Scope) getColumnAsArray(columns []string, values ...interface{}) (results [][]interface{}) {
  1066. for _, value := range values {
  1067. indirectValue := indirect(reflect.ValueOf(value))
  1068. switch indirectValue.Kind() {
  1069. case reflect.Slice:
  1070. for i := 0; i < indirectValue.Len(); i++ {
  1071. var result []interface{}
  1072. var object = indirect(indirectValue.Index(i))
  1073. var hasValue = false
  1074. for _, column := range columns {
  1075. field := object.FieldByName(column)
  1076. if hasValue || !isBlank(field) {
  1077. hasValue = true
  1078. }
  1079. result = append(result, field.Interface())
  1080. }
  1081. if hasValue {
  1082. results = append(results, result)
  1083. }
  1084. }
  1085. case reflect.Struct:
  1086. var result []interface{}
  1087. var hasValue = false
  1088. for _, column := range columns {
  1089. field := indirectValue.FieldByName(column)
  1090. if hasValue || !isBlank(field) {
  1091. hasValue = true
  1092. }
  1093. result = append(result, field.Interface())
  1094. }
  1095. if hasValue {
  1096. results = append(results, result)
  1097. }
  1098. }
  1099. }
  1100. return
  1101. }
  1102. func (scope *Scope) getColumnAsScope(column string) *Scope {
  1103. indirectScopeValue := scope.IndirectValue()
  1104. switch indirectScopeValue.Kind() {
  1105. case reflect.Slice:
  1106. if fieldStruct, ok := scope.GetModelStruct().ModelType.FieldByName(column); ok {
  1107. fieldType := fieldStruct.Type
  1108. if fieldType.Kind() == reflect.Slice || fieldType.Kind() == reflect.Ptr {
  1109. fieldType = fieldType.Elem()
  1110. }
  1111. resultsMap := map[interface{}]bool{}
  1112. results := reflect.New(reflect.SliceOf(reflect.PtrTo(fieldType))).Elem()
  1113. for i := 0; i < indirectScopeValue.Len(); i++ {
  1114. result := indirect(indirect(indirectScopeValue.Index(i)).FieldByName(column))
  1115. if result.Kind() == reflect.Slice {
  1116. for j := 0; j < result.Len(); j++ {
  1117. if elem := result.Index(j); elem.CanAddr() && resultsMap[elem.Addr()] != true {
  1118. resultsMap[elem.Addr()] = true
  1119. results = reflect.Append(results, elem.Addr())
  1120. }
  1121. }
  1122. } else if result.CanAddr() && resultsMap[result.Addr()] != true {
  1123. resultsMap[result.Addr()] = true
  1124. results = reflect.Append(results, result.Addr())
  1125. }
  1126. }
  1127. return scope.New(results.Interface())
  1128. }
  1129. case reflect.Struct:
  1130. if field := indirectScopeValue.FieldByName(column); field.CanAddr() {
  1131. return scope.New(field.Addr().Interface())
  1132. }
  1133. }
  1134. return nil
  1135. }
  1136. func (scope *Scope) hasConditions() bool {
  1137. return !scope.PrimaryKeyZero() ||
  1138. len(scope.Search.whereConditions) > 0 ||
  1139. len(scope.Search.orConditions) > 0 ||
  1140. len(scope.Search.notConditions) > 0
  1141. }