model_struct.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. package gorm
  2. import (
  3. "database/sql"
  4. "errors"
  5. "go/ast"
  6. "reflect"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/jinzhu/inflection"
  11. )
  12. // DefaultTableNameHandler default table name handler
  13. var DefaultTableNameHandler = func(db *DB, defaultTableName string) string {
  14. return defaultTableName
  15. }
  16. // lock for mutating global cached model metadata
  17. var structsLock sync.Mutex
  18. // global cache of model metadata
  19. var modelStructsMap sync.Map
  20. // ModelStruct model definition
  21. type ModelStruct struct {
  22. PrimaryFields []*StructField
  23. StructFields []*StructField
  24. ModelType reflect.Type
  25. defaultTableName string
  26. l sync.Mutex
  27. }
  28. // TableName returns model's table name
  29. func (s *ModelStruct) TableName(db *DB) string {
  30. s.l.Lock()
  31. defer s.l.Unlock()
  32. if s.defaultTableName == "" && db != nil && s.ModelType != nil {
  33. // Set default table name
  34. if tabler, ok := reflect.New(s.ModelType).Interface().(tabler); ok {
  35. s.defaultTableName = tabler.TableName()
  36. } else {
  37. tableName := ToTableName(s.ModelType.Name())
  38. db.parent.RLock()
  39. if db == nil || (db.parent != nil && !db.parent.singularTable) {
  40. tableName = inflection.Plural(tableName)
  41. }
  42. db.parent.RUnlock()
  43. s.defaultTableName = tableName
  44. }
  45. }
  46. return DefaultTableNameHandler(db, s.defaultTableName)
  47. }
  48. // StructField model field's struct definition
  49. type StructField struct {
  50. DBName string
  51. Name string
  52. Names []string
  53. IsPrimaryKey bool
  54. IsNormal bool
  55. IsIgnored bool
  56. IsScanner bool
  57. HasDefaultValue bool
  58. Tag reflect.StructTag
  59. TagSettings map[string]string
  60. Struct reflect.StructField
  61. IsForeignKey bool
  62. Relationship *Relationship
  63. tagSettingsLock sync.RWMutex
  64. }
  65. // TagSettingsSet Sets a tag in the tag settings map
  66. func (sf *StructField) TagSettingsSet(key, val string) {
  67. sf.tagSettingsLock.Lock()
  68. defer sf.tagSettingsLock.Unlock()
  69. sf.TagSettings[key] = val
  70. }
  71. // TagSettingsGet returns a tag from the tag settings
  72. func (sf *StructField) TagSettingsGet(key string) (string, bool) {
  73. sf.tagSettingsLock.RLock()
  74. defer sf.tagSettingsLock.RUnlock()
  75. val, ok := sf.TagSettings[key]
  76. return val, ok
  77. }
  78. // TagSettingsDelete deletes a tag
  79. func (sf *StructField) TagSettingsDelete(key string) {
  80. sf.tagSettingsLock.Lock()
  81. defer sf.tagSettingsLock.Unlock()
  82. delete(sf.TagSettings, key)
  83. }
  84. func (sf *StructField) clone() *StructField {
  85. clone := &StructField{
  86. DBName: sf.DBName,
  87. Name: sf.Name,
  88. Names: sf.Names,
  89. IsPrimaryKey: sf.IsPrimaryKey,
  90. IsNormal: sf.IsNormal,
  91. IsIgnored: sf.IsIgnored,
  92. IsScanner: sf.IsScanner,
  93. HasDefaultValue: sf.HasDefaultValue,
  94. Tag: sf.Tag,
  95. TagSettings: map[string]string{},
  96. Struct: sf.Struct,
  97. IsForeignKey: sf.IsForeignKey,
  98. }
  99. if sf.Relationship != nil {
  100. relationship := *sf.Relationship
  101. clone.Relationship = &relationship
  102. }
  103. // copy the struct field tagSettings, they should be read-locked while they are copied
  104. sf.tagSettingsLock.Lock()
  105. defer sf.tagSettingsLock.Unlock()
  106. for key, value := range sf.TagSettings {
  107. clone.TagSettings[key] = value
  108. }
  109. return clone
  110. }
  111. // Relationship described the relationship between models
  112. type Relationship struct {
  113. Kind string
  114. PolymorphicType string
  115. PolymorphicDBName string
  116. PolymorphicValue string
  117. ForeignFieldNames []string
  118. ForeignDBNames []string
  119. AssociationForeignFieldNames []string
  120. AssociationForeignDBNames []string
  121. JoinTableHandler JoinTableHandlerInterface
  122. }
  123. func getForeignField(column string, fields []*StructField) *StructField {
  124. for _, field := range fields {
  125. if field.Name == column || field.DBName == column || field.DBName == ToColumnName(column) {
  126. return field
  127. }
  128. }
  129. return nil
  130. }
  131. // GetModelStruct get value's model struct, relationships based on struct and tag definition
  132. func (scope *Scope) GetModelStruct() *ModelStruct {
  133. var modelStruct ModelStruct
  134. // Scope value can't be nil
  135. if scope.Value == nil {
  136. return &modelStruct
  137. }
  138. reflectType := reflect.ValueOf(scope.Value).Type()
  139. for reflectType.Kind() == reflect.Slice || reflectType.Kind() == reflect.Ptr {
  140. reflectType = reflectType.Elem()
  141. }
  142. // Scope value need to be a struct
  143. if reflectType.Kind() != reflect.Struct {
  144. return &modelStruct
  145. }
  146. // Get Cached model struct
  147. isSingularTable := false
  148. if scope.db != nil && scope.db.parent != nil {
  149. scope.db.parent.RLock()
  150. isSingularTable = scope.db.parent.singularTable
  151. scope.db.parent.RUnlock()
  152. }
  153. hashKey := struct {
  154. singularTable bool
  155. reflectType reflect.Type
  156. }{isSingularTable, reflectType}
  157. if value, ok := modelStructsMap.Load(hashKey); ok && value != nil {
  158. return value.(*ModelStruct)
  159. }
  160. modelStruct.ModelType = reflectType
  161. // Get all fields
  162. for i := 0; i < reflectType.NumField(); i++ {
  163. if fieldStruct := reflectType.Field(i); ast.IsExported(fieldStruct.Name) {
  164. field := &StructField{
  165. Struct: fieldStruct,
  166. Name: fieldStruct.Name,
  167. Names: []string{fieldStruct.Name},
  168. Tag: fieldStruct.Tag,
  169. TagSettings: parseTagSetting(fieldStruct.Tag),
  170. }
  171. // is ignored field
  172. if _, ok := field.TagSettingsGet("-"); ok {
  173. field.IsIgnored = true
  174. } else {
  175. if _, ok := field.TagSettingsGet("PRIMARY_KEY"); ok {
  176. field.IsPrimaryKey = true
  177. modelStruct.PrimaryFields = append(modelStruct.PrimaryFields, field)
  178. }
  179. if _, ok := field.TagSettingsGet("DEFAULT"); ok && !field.IsPrimaryKey {
  180. field.HasDefaultValue = true
  181. }
  182. if _, ok := field.TagSettingsGet("AUTO_INCREMENT"); ok && !field.IsPrimaryKey {
  183. field.HasDefaultValue = true
  184. }
  185. indirectType := fieldStruct.Type
  186. for indirectType.Kind() == reflect.Ptr {
  187. indirectType = indirectType.Elem()
  188. }
  189. fieldValue := reflect.New(indirectType).Interface()
  190. if _, isScanner := fieldValue.(sql.Scanner); isScanner {
  191. // is scanner
  192. field.IsScanner, field.IsNormal = true, true
  193. if indirectType.Kind() == reflect.Struct {
  194. for i := 0; i < indirectType.NumField(); i++ {
  195. for key, value := range parseTagSetting(indirectType.Field(i).Tag) {
  196. if _, ok := field.TagSettingsGet(key); !ok {
  197. field.TagSettingsSet(key, value)
  198. }
  199. }
  200. }
  201. }
  202. } else if _, isTime := fieldValue.(*time.Time); isTime {
  203. // is time
  204. field.IsNormal = true
  205. } else if _, ok := field.TagSettingsGet("EMBEDDED"); ok || fieldStruct.Anonymous {
  206. // is embedded struct
  207. for _, subField := range scope.New(fieldValue).GetModelStruct().StructFields {
  208. subField = subField.clone()
  209. subField.Names = append([]string{fieldStruct.Name}, subField.Names...)
  210. if prefix, ok := field.TagSettingsGet("EMBEDDED_PREFIX"); ok {
  211. subField.DBName = prefix + subField.DBName
  212. }
  213. if subField.IsPrimaryKey {
  214. if _, ok := subField.TagSettingsGet("PRIMARY_KEY"); ok {
  215. modelStruct.PrimaryFields = append(modelStruct.PrimaryFields, subField)
  216. } else {
  217. subField.IsPrimaryKey = false
  218. }
  219. }
  220. if subField.Relationship != nil && subField.Relationship.JoinTableHandler != nil {
  221. if joinTableHandler, ok := subField.Relationship.JoinTableHandler.(*JoinTableHandler); ok {
  222. newJoinTableHandler := &JoinTableHandler{}
  223. newJoinTableHandler.Setup(subField.Relationship, joinTableHandler.TableName, reflectType, joinTableHandler.Destination.ModelType)
  224. subField.Relationship.JoinTableHandler = newJoinTableHandler
  225. }
  226. }
  227. modelStruct.StructFields = append(modelStruct.StructFields, subField)
  228. }
  229. continue
  230. } else {
  231. // build relationships
  232. switch indirectType.Kind() {
  233. case reflect.Slice:
  234. defer func(field *StructField) {
  235. var (
  236. relationship = &Relationship{}
  237. toScope = scope.New(reflect.New(field.Struct.Type).Interface())
  238. foreignKeys []string
  239. associationForeignKeys []string
  240. elemType = field.Struct.Type
  241. )
  242. if foreignKey, _ := field.TagSettingsGet("FOREIGNKEY"); foreignKey != "" {
  243. foreignKeys = strings.Split(foreignKey, ",")
  244. }
  245. if foreignKey, _ := field.TagSettingsGet("ASSOCIATION_FOREIGNKEY"); foreignKey != "" {
  246. associationForeignKeys = strings.Split(foreignKey, ",")
  247. } else if foreignKey, _ := field.TagSettingsGet("ASSOCIATIONFOREIGNKEY"); foreignKey != "" {
  248. associationForeignKeys = strings.Split(foreignKey, ",")
  249. }
  250. for elemType.Kind() == reflect.Slice || elemType.Kind() == reflect.Ptr {
  251. elemType = elemType.Elem()
  252. }
  253. if elemType.Kind() == reflect.Struct {
  254. if many2many, _ := field.TagSettingsGet("MANY2MANY"); many2many != "" {
  255. relationship.Kind = "many_to_many"
  256. { // Foreign Keys for Source
  257. joinTableDBNames := []string{}
  258. if foreignKey, _ := field.TagSettingsGet("JOINTABLE_FOREIGNKEY"); foreignKey != "" {
  259. joinTableDBNames = strings.Split(foreignKey, ",")
  260. }
  261. // if no foreign keys defined with tag
  262. if len(foreignKeys) == 0 {
  263. for _, field := range modelStruct.PrimaryFields {
  264. foreignKeys = append(foreignKeys, field.DBName)
  265. }
  266. }
  267. for idx, foreignKey := range foreignKeys {
  268. if foreignField := getForeignField(foreignKey, modelStruct.StructFields); foreignField != nil {
  269. // source foreign keys (db names)
  270. relationship.ForeignFieldNames = append(relationship.ForeignFieldNames, foreignField.DBName)
  271. // setup join table foreign keys for source
  272. if len(joinTableDBNames) > idx {
  273. // if defined join table's foreign key
  274. relationship.ForeignDBNames = append(relationship.ForeignDBNames, joinTableDBNames[idx])
  275. } else {
  276. defaultJointableForeignKey := ToColumnName(reflectType.Name()) + "_" + foreignField.DBName
  277. relationship.ForeignDBNames = append(relationship.ForeignDBNames, defaultJointableForeignKey)
  278. }
  279. }
  280. }
  281. }
  282. { // Foreign Keys for Association (Destination)
  283. associationJoinTableDBNames := []string{}
  284. if foreignKey, _ := field.TagSettingsGet("ASSOCIATION_JOINTABLE_FOREIGNKEY"); foreignKey != "" {
  285. associationJoinTableDBNames = strings.Split(foreignKey, ",")
  286. }
  287. // if no association foreign keys defined with tag
  288. if len(associationForeignKeys) == 0 {
  289. for _, field := range toScope.PrimaryFields() {
  290. associationForeignKeys = append(associationForeignKeys, field.DBName)
  291. }
  292. }
  293. for idx, name := range associationForeignKeys {
  294. if field, ok := toScope.FieldByName(name); ok {
  295. // association foreign keys (db names)
  296. relationship.AssociationForeignFieldNames = append(relationship.AssociationForeignFieldNames, field.DBName)
  297. // setup join table foreign keys for association
  298. if len(associationJoinTableDBNames) > idx {
  299. relationship.AssociationForeignDBNames = append(relationship.AssociationForeignDBNames, associationJoinTableDBNames[idx])
  300. } else {
  301. // join table foreign keys for association
  302. joinTableDBName := ToColumnName(elemType.Name()) + "_" + field.DBName
  303. relationship.AssociationForeignDBNames = append(relationship.AssociationForeignDBNames, joinTableDBName)
  304. }
  305. }
  306. }
  307. }
  308. joinTableHandler := JoinTableHandler{}
  309. joinTableHandler.Setup(relationship, many2many, reflectType, elemType)
  310. relationship.JoinTableHandler = &joinTableHandler
  311. field.Relationship = relationship
  312. } else {
  313. // User has many comments, associationType is User, comment use UserID as foreign key
  314. var associationType = reflectType.Name()
  315. var toFields = toScope.GetStructFields()
  316. relationship.Kind = "has_many"
  317. if polymorphic, _ := field.TagSettingsGet("POLYMORPHIC"); polymorphic != "" {
  318. // Dog has many toys, tag polymorphic is Owner, then associationType is Owner
  319. // Toy use OwnerID, OwnerType ('dogs') as foreign key
  320. if polymorphicType := getForeignField(polymorphic+"Type", toFields); polymorphicType != nil {
  321. associationType = polymorphic
  322. relationship.PolymorphicType = polymorphicType.Name
  323. relationship.PolymorphicDBName = polymorphicType.DBName
  324. // if Dog has multiple set of toys set name of the set (instead of default 'dogs')
  325. if value, ok := field.TagSettingsGet("POLYMORPHIC_VALUE"); ok {
  326. relationship.PolymorphicValue = value
  327. } else {
  328. relationship.PolymorphicValue = scope.TableName()
  329. }
  330. polymorphicType.IsForeignKey = true
  331. }
  332. }
  333. // if no foreign keys defined with tag
  334. if len(foreignKeys) == 0 {
  335. // if no association foreign keys defined with tag
  336. if len(associationForeignKeys) == 0 {
  337. for _, field := range modelStruct.PrimaryFields {
  338. foreignKeys = append(foreignKeys, associationType+field.Name)
  339. associationForeignKeys = append(associationForeignKeys, field.Name)
  340. }
  341. } else {
  342. // generate foreign keys from defined association foreign keys
  343. for _, scopeFieldName := range associationForeignKeys {
  344. if foreignField := getForeignField(scopeFieldName, modelStruct.StructFields); foreignField != nil {
  345. foreignKeys = append(foreignKeys, associationType+foreignField.Name)
  346. associationForeignKeys = append(associationForeignKeys, foreignField.Name)
  347. }
  348. }
  349. }
  350. } else {
  351. // generate association foreign keys from foreign keys
  352. if len(associationForeignKeys) == 0 {
  353. for _, foreignKey := range foreignKeys {
  354. if strings.HasPrefix(foreignKey, associationType) {
  355. associationForeignKey := strings.TrimPrefix(foreignKey, associationType)
  356. if foreignField := getForeignField(associationForeignKey, modelStruct.StructFields); foreignField != nil {
  357. associationForeignKeys = append(associationForeignKeys, associationForeignKey)
  358. }
  359. }
  360. }
  361. if len(associationForeignKeys) == 0 && len(foreignKeys) == 1 {
  362. associationForeignKeys = []string{scope.PrimaryKey()}
  363. }
  364. } else if len(foreignKeys) != len(associationForeignKeys) {
  365. scope.Err(errors.New("invalid foreign keys, should have same length"))
  366. return
  367. }
  368. }
  369. for idx, foreignKey := range foreignKeys {
  370. if foreignField := getForeignField(foreignKey, toFields); foreignField != nil {
  371. if associationField := getForeignField(associationForeignKeys[idx], modelStruct.StructFields); associationField != nil {
  372. // mark field as foreignkey, use global lock to avoid race
  373. structsLock.Lock()
  374. foreignField.IsForeignKey = true
  375. structsLock.Unlock()
  376. // association foreign keys
  377. relationship.AssociationForeignFieldNames = append(relationship.AssociationForeignFieldNames, associationField.Name)
  378. relationship.AssociationForeignDBNames = append(relationship.AssociationForeignDBNames, associationField.DBName)
  379. // association foreign keys
  380. relationship.ForeignFieldNames = append(relationship.ForeignFieldNames, foreignField.Name)
  381. relationship.ForeignDBNames = append(relationship.ForeignDBNames, foreignField.DBName)
  382. }
  383. }
  384. }
  385. if len(relationship.ForeignFieldNames) != 0 {
  386. field.Relationship = relationship
  387. }
  388. }
  389. } else {
  390. field.IsNormal = true
  391. }
  392. }(field)
  393. case reflect.Struct:
  394. defer func(field *StructField) {
  395. var (
  396. // user has one profile, associationType is User, profile use UserID as foreign key
  397. // user belongs to profile, associationType is Profile, user use ProfileID as foreign key
  398. associationType = reflectType.Name()
  399. relationship = &Relationship{}
  400. toScope = scope.New(reflect.New(field.Struct.Type).Interface())
  401. toFields = toScope.GetStructFields()
  402. tagForeignKeys []string
  403. tagAssociationForeignKeys []string
  404. )
  405. if foreignKey, _ := field.TagSettingsGet("FOREIGNKEY"); foreignKey != "" {
  406. tagForeignKeys = strings.Split(foreignKey, ",")
  407. }
  408. if foreignKey, _ := field.TagSettingsGet("ASSOCIATION_FOREIGNKEY"); foreignKey != "" {
  409. tagAssociationForeignKeys = strings.Split(foreignKey, ",")
  410. } else if foreignKey, _ := field.TagSettingsGet("ASSOCIATIONFOREIGNKEY"); foreignKey != "" {
  411. tagAssociationForeignKeys = strings.Split(foreignKey, ",")
  412. }
  413. if polymorphic, _ := field.TagSettingsGet("POLYMORPHIC"); polymorphic != "" {
  414. // Cat has one toy, tag polymorphic is Owner, then associationType is Owner
  415. // Toy use OwnerID, OwnerType ('cats') as foreign key
  416. if polymorphicType := getForeignField(polymorphic+"Type", toFields); polymorphicType != nil {
  417. associationType = polymorphic
  418. relationship.PolymorphicType = polymorphicType.Name
  419. relationship.PolymorphicDBName = polymorphicType.DBName
  420. // if Cat has several different types of toys set name for each (instead of default 'cats')
  421. if value, ok := field.TagSettingsGet("POLYMORPHIC_VALUE"); ok {
  422. relationship.PolymorphicValue = value
  423. } else {
  424. relationship.PolymorphicValue = scope.TableName()
  425. }
  426. polymorphicType.IsForeignKey = true
  427. }
  428. }
  429. // Has One
  430. {
  431. var foreignKeys = tagForeignKeys
  432. var associationForeignKeys = tagAssociationForeignKeys
  433. // if no foreign keys defined with tag
  434. if len(foreignKeys) == 0 {
  435. // if no association foreign keys defined with tag
  436. if len(associationForeignKeys) == 0 {
  437. for _, primaryField := range modelStruct.PrimaryFields {
  438. foreignKeys = append(foreignKeys, associationType+primaryField.Name)
  439. associationForeignKeys = append(associationForeignKeys, primaryField.Name)
  440. }
  441. } else {
  442. // generate foreign keys form association foreign keys
  443. for _, associationForeignKey := range tagAssociationForeignKeys {
  444. if foreignField := getForeignField(associationForeignKey, modelStruct.StructFields); foreignField != nil {
  445. foreignKeys = append(foreignKeys, associationType+foreignField.Name)
  446. associationForeignKeys = append(associationForeignKeys, foreignField.Name)
  447. }
  448. }
  449. }
  450. } else {
  451. // generate association foreign keys from foreign keys
  452. if len(associationForeignKeys) == 0 {
  453. for _, foreignKey := range foreignKeys {
  454. if strings.HasPrefix(foreignKey, associationType) {
  455. associationForeignKey := strings.TrimPrefix(foreignKey, associationType)
  456. if foreignField := getForeignField(associationForeignKey, modelStruct.StructFields); foreignField != nil {
  457. associationForeignKeys = append(associationForeignKeys, associationForeignKey)
  458. }
  459. }
  460. }
  461. if len(associationForeignKeys) == 0 && len(foreignKeys) == 1 {
  462. associationForeignKeys = []string{scope.PrimaryKey()}
  463. }
  464. } else if len(foreignKeys) != len(associationForeignKeys) {
  465. scope.Err(errors.New("invalid foreign keys, should have same length"))
  466. return
  467. }
  468. }
  469. for idx, foreignKey := range foreignKeys {
  470. if foreignField := getForeignField(foreignKey, toFields); foreignField != nil {
  471. if scopeField := getForeignField(associationForeignKeys[idx], modelStruct.StructFields); scopeField != nil {
  472. // mark field as foreignkey, use global lock to avoid race
  473. structsLock.Lock()
  474. foreignField.IsForeignKey = true
  475. structsLock.Unlock()
  476. // association foreign keys
  477. relationship.AssociationForeignFieldNames = append(relationship.AssociationForeignFieldNames, scopeField.Name)
  478. relationship.AssociationForeignDBNames = append(relationship.AssociationForeignDBNames, scopeField.DBName)
  479. // association foreign keys
  480. relationship.ForeignFieldNames = append(relationship.ForeignFieldNames, foreignField.Name)
  481. relationship.ForeignDBNames = append(relationship.ForeignDBNames, foreignField.DBName)
  482. }
  483. }
  484. }
  485. }
  486. if len(relationship.ForeignFieldNames) != 0 {
  487. relationship.Kind = "has_one"
  488. field.Relationship = relationship
  489. } else {
  490. var foreignKeys = tagForeignKeys
  491. var associationForeignKeys = tagAssociationForeignKeys
  492. if len(foreignKeys) == 0 {
  493. // generate foreign keys & association foreign keys
  494. if len(associationForeignKeys) == 0 {
  495. for _, primaryField := range toScope.PrimaryFields() {
  496. foreignKeys = append(foreignKeys, field.Name+primaryField.Name)
  497. associationForeignKeys = append(associationForeignKeys, primaryField.Name)
  498. }
  499. } else {
  500. // generate foreign keys with association foreign keys
  501. for _, associationForeignKey := range associationForeignKeys {
  502. if foreignField := getForeignField(associationForeignKey, toFields); foreignField != nil {
  503. foreignKeys = append(foreignKeys, field.Name+foreignField.Name)
  504. associationForeignKeys = append(associationForeignKeys, foreignField.Name)
  505. }
  506. }
  507. }
  508. } else {
  509. // generate foreign keys & association foreign keys
  510. if len(associationForeignKeys) == 0 {
  511. for _, foreignKey := range foreignKeys {
  512. if strings.HasPrefix(foreignKey, field.Name) {
  513. associationForeignKey := strings.TrimPrefix(foreignKey, field.Name)
  514. if foreignField := getForeignField(associationForeignKey, toFields); foreignField != nil {
  515. associationForeignKeys = append(associationForeignKeys, associationForeignKey)
  516. }
  517. }
  518. }
  519. if len(associationForeignKeys) == 0 && len(foreignKeys) == 1 {
  520. associationForeignKeys = []string{toScope.PrimaryKey()}
  521. }
  522. } else if len(foreignKeys) != len(associationForeignKeys) {
  523. scope.Err(errors.New("invalid foreign keys, should have same length"))
  524. return
  525. }
  526. }
  527. for idx, foreignKey := range foreignKeys {
  528. if foreignField := getForeignField(foreignKey, modelStruct.StructFields); foreignField != nil {
  529. if associationField := getForeignField(associationForeignKeys[idx], toFields); associationField != nil {
  530. // mark field as foreignkey, use global lock to avoid race
  531. structsLock.Lock()
  532. foreignField.IsForeignKey = true
  533. structsLock.Unlock()
  534. // association foreign keys
  535. relationship.AssociationForeignFieldNames = append(relationship.AssociationForeignFieldNames, associationField.Name)
  536. relationship.AssociationForeignDBNames = append(relationship.AssociationForeignDBNames, associationField.DBName)
  537. // source foreign keys
  538. relationship.ForeignFieldNames = append(relationship.ForeignFieldNames, foreignField.Name)
  539. relationship.ForeignDBNames = append(relationship.ForeignDBNames, foreignField.DBName)
  540. }
  541. }
  542. }
  543. if len(relationship.ForeignFieldNames) != 0 {
  544. relationship.Kind = "belongs_to"
  545. field.Relationship = relationship
  546. }
  547. }
  548. }(field)
  549. default:
  550. field.IsNormal = true
  551. }
  552. }
  553. }
  554. // Even it is ignored, also possible to decode db value into the field
  555. if value, ok := field.TagSettingsGet("COLUMN"); ok {
  556. field.DBName = value
  557. } else {
  558. field.DBName = ToColumnName(fieldStruct.Name)
  559. }
  560. modelStruct.StructFields = append(modelStruct.StructFields, field)
  561. }
  562. }
  563. if len(modelStruct.PrimaryFields) == 0 {
  564. if field := getForeignField("id", modelStruct.StructFields); field != nil {
  565. field.IsPrimaryKey = true
  566. modelStruct.PrimaryFields = append(modelStruct.PrimaryFields, field)
  567. }
  568. }
  569. modelStructsMap.Store(hashKey, &modelStruct)
  570. return &modelStruct
  571. }
  572. // GetStructFields get model's field structs
  573. func (scope *Scope) GetStructFields() (fields []*StructField) {
  574. return scope.GetModelStruct().StructFields
  575. }
  576. func parseTagSetting(tags reflect.StructTag) map[string]string {
  577. setting := map[string]string{}
  578. for _, str := range []string{tags.Get("sql"), tags.Get("gorm")} {
  579. if str == "" {
  580. continue
  581. }
  582. tags := strings.Split(str, ";")
  583. for _, value := range tags {
  584. v := strings.Split(value, ":")
  585. k := strings.TrimSpace(strings.ToUpper(v[0]))
  586. if len(v) >= 2 {
  587. setting[k] = strings.Join(v[1:], ":")
  588. } else {
  589. setting[k] = k
  590. }
  591. }
  592. }
  593. return setting
  594. }