scope.go 38 KB

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