scope.go 38 KB

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