scope.go 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429
  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.dialect
  58. }
  59. // Quote used to quote string to escape them for database
  60. func (scope *Scope) Quote(str string) string {
  61. if strings.Contains(str, ".") {
  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 = ToColumnName(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.IsIgnored && ((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.(*SqlExpr); 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.Contains(scope.Search.tableName, " ") {
  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(); scope.Err(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. offset := 0
  426. if idx, ok := selectedColumnsMap[column]; ok {
  427. offset = idx + 1
  428. selectFields = selectFields[offset:]
  429. }
  430. for fieldIndex, field := range selectFields {
  431. if field.DBName == column {
  432. if field.Field.Kind() == reflect.Ptr {
  433. values[index] = field.Field.Addr().Interface()
  434. } else {
  435. reflectValue := reflect.New(reflect.PtrTo(field.Struct.Type))
  436. reflectValue.Elem().Set(field.Field.Addr())
  437. values[index] = reflectValue.Interface()
  438. resetFields[index] = field
  439. }
  440. selectedColumnsMap[column] = offset + fieldIndex
  441. if field.IsNormal {
  442. break
  443. }
  444. }
  445. }
  446. }
  447. scope.Err(rows.Scan(values...))
  448. for index, field := range resetFields {
  449. if v := reflect.ValueOf(values[index]).Elem().Elem(); v.IsValid() {
  450. field.Field.Set(v)
  451. }
  452. }
  453. }
  454. func (scope *Scope) primaryCondition(value interface{}) string {
  455. return fmt.Sprintf("(%v.%v = %v)", scope.QuotedTableName(), scope.Quote(scope.PrimaryKey()), value)
  456. }
  457. func (scope *Scope) buildCondition(clause map[string]interface{}, include bool) (str string) {
  458. var (
  459. quotedTableName = scope.QuotedTableName()
  460. quotedPrimaryKey = scope.Quote(scope.PrimaryKey())
  461. equalSQL = "="
  462. inSQL = "IN"
  463. )
  464. // If building not conditions
  465. if !include {
  466. equalSQL = "<>"
  467. inSQL = "NOT IN"
  468. }
  469. switch value := clause["query"].(type) {
  470. case sql.NullInt64:
  471. return fmt.Sprintf("(%v.%v %s %v)", quotedTableName, quotedPrimaryKey, equalSQL, value.Int64)
  472. case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
  473. return fmt.Sprintf("(%v.%v %s %v)", quotedTableName, quotedPrimaryKey, equalSQL, value)
  474. case []int, []int8, []int16, []int32, []int64, []uint, []uint8, []uint16, []uint32, []uint64, []string, []interface{}:
  475. if !include && reflect.ValueOf(value).Len() == 0 {
  476. return
  477. }
  478. str = fmt.Sprintf("(%v.%v %s (?))", quotedTableName, quotedPrimaryKey, inSQL)
  479. clause["args"] = []interface{}{value}
  480. case string:
  481. if isNumberRegexp.MatchString(value) {
  482. return fmt.Sprintf("(%v.%v %s %v)", quotedTableName, quotedPrimaryKey, equalSQL, scope.AddToVars(value))
  483. }
  484. if value != "" {
  485. if !include {
  486. if comparisonRegexp.MatchString(value) {
  487. str = fmt.Sprintf("NOT (%v)", value)
  488. } else {
  489. str = fmt.Sprintf("(%v.%v NOT IN (?))", quotedTableName, scope.Quote(value))
  490. }
  491. } else {
  492. str = fmt.Sprintf("(%v)", value)
  493. }
  494. }
  495. case map[string]interface{}:
  496. var sqls []string
  497. for key, value := range value {
  498. if value != nil {
  499. sqls = append(sqls, fmt.Sprintf("(%v.%v %s %v)", quotedTableName, scope.Quote(key), equalSQL, scope.AddToVars(value)))
  500. } else {
  501. if !include {
  502. sqls = append(sqls, fmt.Sprintf("(%v.%v IS NOT NULL)", quotedTableName, scope.Quote(key)))
  503. } else {
  504. sqls = append(sqls, fmt.Sprintf("(%v.%v IS NULL)", quotedTableName, scope.Quote(key)))
  505. }
  506. }
  507. }
  508. return strings.Join(sqls, " AND ")
  509. case interface{}:
  510. var sqls []string
  511. newScope := scope.New(value)
  512. if len(newScope.Fields()) == 0 {
  513. scope.Err(fmt.Errorf("invalid query condition: %v", value))
  514. return
  515. }
  516. scopeQuotedTableName := newScope.QuotedTableName()
  517. for _, field := range newScope.Fields() {
  518. if !field.IsIgnored && !field.IsBlank && field.Relationship == nil {
  519. sqls = append(sqls, fmt.Sprintf("(%v.%v %s %v)", scopeQuotedTableName, scope.Quote(field.DBName), equalSQL, scope.AddToVars(field.Field.Interface())))
  520. }
  521. }
  522. return strings.Join(sqls, " AND ")
  523. default:
  524. scope.Err(fmt.Errorf("invalid query condition: %v", value))
  525. return
  526. }
  527. replacements := []string{}
  528. args := clause["args"].([]interface{})
  529. for _, arg := range args {
  530. var err error
  531. switch reflect.ValueOf(arg).Kind() {
  532. case reflect.Slice: // For where("id in (?)", []int64{1,2})
  533. if scanner, ok := interface{}(arg).(driver.Valuer); ok {
  534. arg, err = scanner.Value()
  535. replacements = append(replacements, scope.AddToVars(arg))
  536. } else if b, ok := arg.([]byte); ok {
  537. replacements = append(replacements, scope.AddToVars(b))
  538. } else if as, ok := arg.([][]interface{}); ok {
  539. var tempMarks []string
  540. for _, a := range as {
  541. var arrayMarks []string
  542. for _, v := range a {
  543. arrayMarks = append(arrayMarks, scope.AddToVars(v))
  544. }
  545. if len(arrayMarks) > 0 {
  546. tempMarks = append(tempMarks, fmt.Sprintf("(%v)", strings.Join(arrayMarks, ",")))
  547. }
  548. }
  549. if len(tempMarks) > 0 {
  550. replacements = append(replacements, strings.Join(tempMarks, ","))
  551. }
  552. } else if values := reflect.ValueOf(arg); values.Len() > 0 {
  553. var tempMarks []string
  554. for i := 0; i < values.Len(); i++ {
  555. tempMarks = append(tempMarks, scope.AddToVars(values.Index(i).Interface()))
  556. }
  557. replacements = append(replacements, strings.Join(tempMarks, ","))
  558. } else {
  559. replacements = append(replacements, scope.AddToVars(Expr("NULL")))
  560. }
  561. default:
  562. if valuer, ok := interface{}(arg).(driver.Valuer); ok {
  563. arg, err = valuer.Value()
  564. }
  565. replacements = append(replacements, scope.AddToVars(arg))
  566. }
  567. if err != nil {
  568. scope.Err(err)
  569. }
  570. }
  571. buff := bytes.NewBuffer([]byte{})
  572. i := 0
  573. for _, s := range str {
  574. if s == '?' && len(replacements) > i {
  575. buff.WriteString(replacements[i])
  576. i++
  577. } else {
  578. buff.WriteRune(s)
  579. }
  580. }
  581. str = buff.String()
  582. return
  583. }
  584. func (scope *Scope) buildSelectQuery(clause map[string]interface{}) (str string) {
  585. switch value := clause["query"].(type) {
  586. case string:
  587. str = value
  588. case []string:
  589. str = strings.Join(value, ", ")
  590. }
  591. args := clause["args"].([]interface{})
  592. replacements := []string{}
  593. for _, arg := range args {
  594. switch reflect.ValueOf(arg).Kind() {
  595. case reflect.Slice:
  596. values := reflect.ValueOf(arg)
  597. var tempMarks []string
  598. for i := 0; i < values.Len(); i++ {
  599. tempMarks = append(tempMarks, scope.AddToVars(values.Index(i).Interface()))
  600. }
  601. replacements = append(replacements, strings.Join(tempMarks, ","))
  602. default:
  603. if valuer, ok := interface{}(arg).(driver.Valuer); ok {
  604. arg, _ = valuer.Value()
  605. }
  606. replacements = append(replacements, scope.AddToVars(arg))
  607. }
  608. }
  609. buff := bytes.NewBuffer([]byte{})
  610. i := 0
  611. for pos, char := range str {
  612. if str[pos] == '?' {
  613. buff.WriteString(replacements[i])
  614. i++
  615. } else {
  616. buff.WriteRune(char)
  617. }
  618. }
  619. str = buff.String()
  620. return
  621. }
  622. func (scope *Scope) whereSQL() (sql string) {
  623. var (
  624. quotedTableName = scope.QuotedTableName()
  625. deletedAtField, hasDeletedAtField = scope.FieldByName("DeletedAt")
  626. primaryConditions, andConditions, orConditions []string
  627. )
  628. if !scope.Search.Unscoped && hasDeletedAtField {
  629. sql := fmt.Sprintf("%v.%v IS NULL", quotedTableName, scope.Quote(deletedAtField.DBName))
  630. primaryConditions = append(primaryConditions, sql)
  631. }
  632. if !scope.PrimaryKeyZero() {
  633. for _, field := range scope.PrimaryFields() {
  634. sql := fmt.Sprintf("%v.%v = %v", quotedTableName, scope.Quote(field.DBName), scope.AddToVars(field.Field.Interface()))
  635. primaryConditions = append(primaryConditions, sql)
  636. }
  637. }
  638. for _, clause := range scope.Search.whereConditions {
  639. if sql := scope.buildCondition(clause, true); sql != "" {
  640. andConditions = append(andConditions, sql)
  641. }
  642. }
  643. for _, clause := range scope.Search.orConditions {
  644. if sql := scope.buildCondition(clause, true); sql != "" {
  645. orConditions = append(orConditions, sql)
  646. }
  647. }
  648. for _, clause := range scope.Search.notConditions {
  649. if sql := scope.buildCondition(clause, false); sql != "" {
  650. andConditions = append(andConditions, sql)
  651. }
  652. }
  653. orSQL := strings.Join(orConditions, " OR ")
  654. combinedSQL := strings.Join(andConditions, " AND ")
  655. if len(combinedSQL) > 0 {
  656. if len(orSQL) > 0 {
  657. combinedSQL = combinedSQL + " OR " + orSQL
  658. }
  659. } else {
  660. combinedSQL = orSQL
  661. }
  662. if len(primaryConditions) > 0 {
  663. sql = "WHERE " + strings.Join(primaryConditions, " AND ")
  664. if len(combinedSQL) > 0 {
  665. sql = sql + " AND (" + combinedSQL + ")"
  666. }
  667. } else if len(combinedSQL) > 0 {
  668. sql = "WHERE " + combinedSQL
  669. }
  670. return
  671. }
  672. func (scope *Scope) selectSQL() string {
  673. if len(scope.Search.selects) == 0 {
  674. if len(scope.Search.joinConditions) > 0 {
  675. return fmt.Sprintf("%v.*", scope.QuotedTableName())
  676. }
  677. return "*"
  678. }
  679. return scope.buildSelectQuery(scope.Search.selects)
  680. }
  681. func (scope *Scope) orderSQL() string {
  682. if len(scope.Search.orders) == 0 || scope.Search.ignoreOrderQuery {
  683. return ""
  684. }
  685. var orders []string
  686. for _, order := range scope.Search.orders {
  687. if str, ok := order.(string); ok {
  688. orders = append(orders, scope.quoteIfPossible(str))
  689. } else if expr, ok := order.(*SqlExpr); ok {
  690. exp := expr.expr
  691. for _, arg := range expr.args {
  692. exp = strings.Replace(exp, "?", scope.AddToVars(arg), 1)
  693. }
  694. orders = append(orders, exp)
  695. }
  696. }
  697. return " ORDER BY " + strings.Join(orders, ",")
  698. }
  699. func (scope *Scope) limitAndOffsetSQL() string {
  700. sql, err := scope.Dialect().LimitAndOffsetSQL(scope.Search.limit, scope.Search.offset)
  701. scope.Err(err)
  702. return sql
  703. }
  704. func (scope *Scope) groupSQL() string {
  705. if len(scope.Search.group) == 0 {
  706. return ""
  707. }
  708. return " GROUP BY " + scope.Search.group
  709. }
  710. func (scope *Scope) havingSQL() string {
  711. if len(scope.Search.havingConditions) == 0 {
  712. return ""
  713. }
  714. var andConditions []string
  715. for _, clause := range scope.Search.havingConditions {
  716. if sql := scope.buildCondition(clause, true); sql != "" {
  717. andConditions = append(andConditions, sql)
  718. }
  719. }
  720. combinedSQL := strings.Join(andConditions, " AND ")
  721. if len(combinedSQL) == 0 {
  722. return ""
  723. }
  724. return " HAVING " + combinedSQL
  725. }
  726. func (scope *Scope) joinsSQL() string {
  727. var joinConditions []string
  728. for _, clause := range scope.Search.joinConditions {
  729. if sql := scope.buildCondition(clause, true); sql != "" {
  730. joinConditions = append(joinConditions, strings.TrimSuffix(strings.TrimPrefix(sql, "("), ")"))
  731. }
  732. }
  733. return strings.Join(joinConditions, " ") + " "
  734. }
  735. func (scope *Scope) prepareQuerySQL() {
  736. var sql string
  737. if scope.Search.raw {
  738. sql = scope.CombinedConditionSql()
  739. } else {
  740. sql = fmt.Sprintf("SELECT %v FROM %v %v", scope.selectSQL(), scope.QuotedTableName(), scope.CombinedConditionSql())
  741. }
  742. if str, ok := scope.Get("gorm:query_option"); ok {
  743. sql += addExtraSpaceIfExist(fmt.Sprint(str))
  744. }
  745. scope.Raw(sql)
  746. }
  747. func (scope *Scope) inlineCondition(values ...interface{}) *Scope {
  748. if len(values) > 0 {
  749. scope.Search.Where(values[0], values[1:]...)
  750. }
  751. return scope
  752. }
  753. func (scope *Scope) callCallbacks(funcs []*func(s *Scope)) *Scope {
  754. defer func() {
  755. if err := recover(); err != nil {
  756. if db, ok := scope.db.db.(sqlTx); ok {
  757. db.Rollback()
  758. }
  759. panic(err)
  760. }
  761. }()
  762. for _, f := range funcs {
  763. (*f)(scope)
  764. if scope.skipLeft {
  765. break
  766. }
  767. }
  768. return scope
  769. }
  770. func convertInterfaceToMap(values interface{}, withIgnoredField bool, db *DB) map[string]interface{} {
  771. var attrs = map[string]interface{}{}
  772. switch value := values.(type) {
  773. case map[string]interface{}:
  774. return value
  775. case []interface{}:
  776. for _, v := range value {
  777. for key, value := range convertInterfaceToMap(v, withIgnoredField, db) {
  778. attrs[key] = value
  779. }
  780. }
  781. case interface{}:
  782. reflectValue := reflect.ValueOf(values)
  783. switch reflectValue.Kind() {
  784. case reflect.Map:
  785. for _, key := range reflectValue.MapKeys() {
  786. attrs[ToColumnName(key.Interface().(string))] = reflectValue.MapIndex(key).Interface()
  787. }
  788. default:
  789. for _, field := range (&Scope{Value: values, db: db}).Fields() {
  790. if !field.IsBlank && (withIgnoredField || !field.IsIgnored) {
  791. attrs[field.DBName] = field.Field.Interface()
  792. }
  793. }
  794. }
  795. }
  796. return attrs
  797. }
  798. func (scope *Scope) updatedAttrsWithValues(value interface{}) (results map[string]interface{}, hasUpdate bool) {
  799. if scope.IndirectValue().Kind() != reflect.Struct {
  800. return convertInterfaceToMap(value, false, scope.db), true
  801. }
  802. results = map[string]interface{}{}
  803. for key, value := range convertInterfaceToMap(value, true, scope.db) {
  804. if field, ok := scope.FieldByName(key); ok {
  805. if scope.changeableField(field) {
  806. if _, ok := value.(*SqlExpr); ok {
  807. hasUpdate = true
  808. results[field.DBName] = value
  809. } else {
  810. err := field.Set(value)
  811. if field.IsNormal && !field.IsIgnored {
  812. hasUpdate = true
  813. if err == ErrUnaddressable {
  814. results[field.DBName] = value
  815. } else {
  816. results[field.DBName] = field.Field.Interface()
  817. }
  818. }
  819. }
  820. }
  821. } else {
  822. results[key] = value
  823. }
  824. }
  825. return
  826. }
  827. func (scope *Scope) row() *sql.Row {
  828. defer scope.trace(NowFunc())
  829. result := &RowQueryResult{}
  830. scope.InstanceSet("row_query_result", result)
  831. scope.callCallbacks(scope.db.parent.callbacks.rowQueries)
  832. return result.Row
  833. }
  834. func (scope *Scope) rows() (*sql.Rows, error) {
  835. defer scope.trace(NowFunc())
  836. result := &RowsQueryResult{}
  837. scope.InstanceSet("row_query_result", result)
  838. scope.callCallbacks(scope.db.parent.callbacks.rowQueries)
  839. return result.Rows, result.Error
  840. }
  841. func (scope *Scope) initialize() *Scope {
  842. for _, clause := range scope.Search.whereConditions {
  843. scope.updatedAttrsWithValues(clause["query"])
  844. }
  845. scope.updatedAttrsWithValues(scope.Search.initAttrs)
  846. scope.updatedAttrsWithValues(scope.Search.assignAttrs)
  847. return scope
  848. }
  849. func (scope *Scope) isQueryForColumn(query interface{}, column string) bool {
  850. queryStr := strings.ToLower(fmt.Sprint(query))
  851. if queryStr == column {
  852. return true
  853. }
  854. if strings.HasSuffix(queryStr, "as "+column) {
  855. return true
  856. }
  857. if strings.HasSuffix(queryStr, "as "+scope.Quote(column)) {
  858. return true
  859. }
  860. return false
  861. }
  862. func (scope *Scope) pluck(column string, value interface{}) *Scope {
  863. dest := reflect.Indirect(reflect.ValueOf(value))
  864. if dest.Kind() != reflect.Slice {
  865. scope.Err(fmt.Errorf("results should be a slice, not %s", dest.Kind()))
  866. return scope
  867. }
  868. if dest.Len() > 0 {
  869. dest.Set(reflect.Zero(dest.Type()))
  870. }
  871. if query, ok := scope.Search.selects["query"]; !ok || !scope.isQueryForColumn(query, column) {
  872. scope.Search.Select(column)
  873. }
  874. rows, err := scope.rows()
  875. if scope.Err(err) == nil {
  876. defer rows.Close()
  877. for rows.Next() {
  878. elem := reflect.New(dest.Type().Elem()).Interface()
  879. scope.Err(rows.Scan(elem))
  880. dest.Set(reflect.Append(dest, reflect.ValueOf(elem).Elem()))
  881. }
  882. if err := rows.Err(); err != nil {
  883. scope.Err(err)
  884. }
  885. }
  886. return scope
  887. }
  888. func (scope *Scope) count(value interface{}) *Scope {
  889. if query, ok := scope.Search.selects["query"]; !ok || !countingQueryRegexp.MatchString(fmt.Sprint(query)) {
  890. if len(scope.Search.group) != 0 {
  891. if len(scope.Search.havingConditions) != 0 {
  892. scope.prepareQuerySQL()
  893. scope.Search = &search{}
  894. scope.Search.Select("count(*)")
  895. scope.Search.Table(fmt.Sprintf("( %s ) AS count_table", scope.SQL))
  896. } else {
  897. scope.Search.Select("count(*) FROM ( SELECT count(*) as name ")
  898. scope.Search.group += " ) AS count_table"
  899. }
  900. } else {
  901. scope.Search.Select("count(*)")
  902. }
  903. }
  904. scope.Search.ignoreOrderQuery = true
  905. scope.Err(scope.row().Scan(value))
  906. return scope
  907. }
  908. func (scope *Scope) typeName() string {
  909. typ := scope.IndirectValue().Type()
  910. for typ.Kind() == reflect.Slice || typ.Kind() == reflect.Ptr {
  911. typ = typ.Elem()
  912. }
  913. return typ.Name()
  914. }
  915. // trace print sql log
  916. func (scope *Scope) trace(t time.Time) {
  917. if len(scope.SQL) > 0 {
  918. scope.db.slog(scope.SQL, t, scope.SQLVars...)
  919. }
  920. }
  921. func (scope *Scope) changeableField(field *Field) bool {
  922. if selectAttrs := scope.SelectAttrs(); len(selectAttrs) > 0 {
  923. for _, attr := range selectAttrs {
  924. if field.Name == attr || field.DBName == attr {
  925. return true
  926. }
  927. }
  928. return false
  929. }
  930. for _, attr := range scope.OmitAttrs() {
  931. if field.Name == attr || field.DBName == attr {
  932. return false
  933. }
  934. }
  935. return true
  936. }
  937. func (scope *Scope) related(value interface{}, foreignKeys ...string) *Scope {
  938. toScope := scope.db.NewScope(value)
  939. tx := scope.db.Set("gorm:association:source", scope.Value)
  940. for _, foreignKey := range append(foreignKeys, toScope.typeName()+"Id", scope.typeName()+"Id") {
  941. fromField, _ := scope.FieldByName(foreignKey)
  942. toField, _ := toScope.FieldByName(foreignKey)
  943. if fromField != nil {
  944. if relationship := fromField.Relationship; relationship != nil {
  945. if relationship.Kind == "many_to_many" {
  946. joinTableHandler := relationship.JoinTableHandler
  947. scope.Err(joinTableHandler.JoinWith(joinTableHandler, tx, scope.Value).Find(value).Error)
  948. } else if relationship.Kind == "belongs_to" {
  949. for idx, foreignKey := range relationship.ForeignDBNames {
  950. if field, ok := scope.FieldByName(foreignKey); ok {
  951. tx = tx.Where(fmt.Sprintf("%v = ?", scope.Quote(relationship.AssociationForeignDBNames[idx])), field.Field.Interface())
  952. }
  953. }
  954. scope.Err(tx.Find(value).Error)
  955. } else if relationship.Kind == "has_many" || relationship.Kind == "has_one" {
  956. for idx, foreignKey := range relationship.ForeignDBNames {
  957. if field, ok := scope.FieldByName(relationship.AssociationForeignDBNames[idx]); ok {
  958. tx = tx.Where(fmt.Sprintf("%v = ?", scope.Quote(foreignKey)), field.Field.Interface())
  959. }
  960. }
  961. if relationship.PolymorphicType != "" {
  962. tx = tx.Where(fmt.Sprintf("%v = ?", scope.Quote(relationship.PolymorphicDBName)), relationship.PolymorphicValue)
  963. }
  964. scope.Err(tx.Find(value).Error)
  965. }
  966. } else {
  967. sql := fmt.Sprintf("%v = ?", scope.Quote(toScope.PrimaryKey()))
  968. scope.Err(tx.Where(sql, fromField.Field.Interface()).Find(value).Error)
  969. }
  970. return scope
  971. } else if toField != nil {
  972. sql := fmt.Sprintf("%v = ?", scope.Quote(toField.DBName))
  973. scope.Err(tx.Where(sql, scope.PrimaryKeyValue()).Find(value).Error)
  974. return scope
  975. }
  976. }
  977. scope.Err(fmt.Errorf("invalid association %v", foreignKeys))
  978. return scope
  979. }
  980. // getTableOptions return the table options string or an empty string if the table options does not exist
  981. func (scope *Scope) getTableOptions() string {
  982. tableOptions, ok := scope.Get("gorm:table_options")
  983. if !ok {
  984. return ""
  985. }
  986. return " " + tableOptions.(string)
  987. }
  988. func (scope *Scope) createJoinTable(field *StructField) {
  989. if relationship := field.Relationship; relationship != nil && relationship.JoinTableHandler != nil {
  990. joinTableHandler := relationship.JoinTableHandler
  991. joinTable := joinTableHandler.Table(scope.db)
  992. if !scope.Dialect().HasTable(joinTable) {
  993. toScope := &Scope{Value: reflect.New(field.Struct.Type).Interface()}
  994. var sqlTypes, primaryKeys []string
  995. for idx, fieldName := range relationship.ForeignFieldNames {
  996. if field, ok := scope.FieldByName(fieldName); ok {
  997. foreignKeyStruct := field.clone()
  998. foreignKeyStruct.IsPrimaryKey = false
  999. foreignKeyStruct.TagSettingsSet("IS_JOINTABLE_FOREIGNKEY", "true")
  1000. foreignKeyStruct.TagSettingsDelete("AUTO_INCREMENT")
  1001. sqlTypes = append(sqlTypes, scope.Quote(relationship.ForeignDBNames[idx])+" "+scope.Dialect().DataTypeOf(foreignKeyStruct))
  1002. primaryKeys = append(primaryKeys, scope.Quote(relationship.ForeignDBNames[idx]))
  1003. }
  1004. }
  1005. for idx, fieldName := range relationship.AssociationForeignFieldNames {
  1006. if field, ok := toScope.FieldByName(fieldName); ok {
  1007. foreignKeyStruct := field.clone()
  1008. foreignKeyStruct.IsPrimaryKey = false
  1009. foreignKeyStruct.TagSettingsSet("IS_JOINTABLE_FOREIGNKEY", "true")
  1010. foreignKeyStruct.TagSettingsDelete("AUTO_INCREMENT")
  1011. sqlTypes = append(sqlTypes, scope.Quote(relationship.AssociationForeignDBNames[idx])+" "+scope.Dialect().DataTypeOf(foreignKeyStruct))
  1012. primaryKeys = append(primaryKeys, scope.Quote(relationship.AssociationForeignDBNames[idx]))
  1013. }
  1014. }
  1015. 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)
  1016. }
  1017. scope.NewDB().Table(joinTable).AutoMigrate(joinTableHandler)
  1018. }
  1019. }
  1020. func (scope *Scope) createTable() *Scope {
  1021. var tags []string
  1022. var primaryKeys []string
  1023. var primaryKeyInColumnType = false
  1024. for _, field := range scope.GetModelStruct().StructFields {
  1025. if field.IsNormal {
  1026. sqlTag := scope.Dialect().DataTypeOf(field)
  1027. // Check if the primary key constraint was specified as
  1028. // part of the column type. If so, we can only support
  1029. // one column as the primary key.
  1030. if strings.Contains(strings.ToLower(sqlTag), "primary key") {
  1031. primaryKeyInColumnType = true
  1032. }
  1033. tags = append(tags, scope.Quote(field.DBName)+" "+sqlTag)
  1034. }
  1035. if field.IsPrimaryKey {
  1036. primaryKeys = append(primaryKeys, scope.Quote(field.DBName))
  1037. }
  1038. scope.createJoinTable(field)
  1039. }
  1040. var primaryKeyStr string
  1041. if len(primaryKeys) > 0 && !primaryKeyInColumnType {
  1042. primaryKeyStr = fmt.Sprintf(", PRIMARY KEY (%v)", strings.Join(primaryKeys, ","))
  1043. }
  1044. scope.Raw(fmt.Sprintf("CREATE TABLE %v (%v %v)%s", scope.QuotedTableName(), strings.Join(tags, ","), primaryKeyStr, scope.getTableOptions())).Exec()
  1045. scope.autoIndex()
  1046. return scope
  1047. }
  1048. func (scope *Scope) dropTable() *Scope {
  1049. scope.Raw(fmt.Sprintf("DROP TABLE %v", scope.QuotedTableName())).Exec()
  1050. return scope
  1051. }
  1052. func (scope *Scope) modifyColumn(column string, typ string) {
  1053. scope.db.AddError(scope.Dialect().ModifyColumn(scope.QuotedTableName(), scope.Quote(column), typ))
  1054. }
  1055. func (scope *Scope) dropColumn(column string) {
  1056. scope.Raw(fmt.Sprintf("ALTER TABLE %v DROP COLUMN %v", scope.QuotedTableName(), scope.Quote(column))).Exec()
  1057. }
  1058. func (scope *Scope) addIndex(unique bool, indexName string, column ...string) {
  1059. if scope.Dialect().HasIndex(scope.TableName(), indexName) {
  1060. return
  1061. }
  1062. var columns []string
  1063. for _, name := range column {
  1064. columns = append(columns, scope.quoteIfPossible(name))
  1065. }
  1066. sqlCreate := "CREATE INDEX"
  1067. if unique {
  1068. sqlCreate = "CREATE UNIQUE INDEX"
  1069. }
  1070. scope.Raw(fmt.Sprintf("%s %v ON %v(%v) %v", sqlCreate, indexName, scope.QuotedTableName(), strings.Join(columns, ", "), scope.whereSQL())).Exec()
  1071. }
  1072. func (scope *Scope) addForeignKey(field string, dest string, onDelete string, onUpdate string) {
  1073. // Compatible with old generated key
  1074. keyName := scope.Dialect().BuildKeyName(scope.TableName(), field, dest, "foreign")
  1075. if scope.Dialect().HasForeignKey(scope.TableName(), keyName) {
  1076. return
  1077. }
  1078. var query = `ALTER TABLE %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s ON DELETE %s ON UPDATE %s;`
  1079. scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), scope.quoteIfPossible(keyName), scope.quoteIfPossible(field), dest, onDelete, onUpdate)).Exec()
  1080. }
  1081. func (scope *Scope) removeForeignKey(field string, dest string) {
  1082. keyName := scope.Dialect().BuildKeyName(scope.TableName(), field, dest, "foreign")
  1083. if !scope.Dialect().HasForeignKey(scope.TableName(), keyName) {
  1084. return
  1085. }
  1086. var mysql mysql
  1087. var query string
  1088. if scope.Dialect().GetName() == mysql.GetName() {
  1089. query = `ALTER TABLE %s DROP FOREIGN KEY %s;`
  1090. } else {
  1091. query = `ALTER TABLE %s DROP CONSTRAINT %s;`
  1092. }
  1093. scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), scope.quoteIfPossible(keyName))).Exec()
  1094. }
  1095. func (scope *Scope) removeIndex(indexName string) {
  1096. scope.Dialect().RemoveIndex(scope.TableName(), indexName)
  1097. }
  1098. func (scope *Scope) autoMigrate() *Scope {
  1099. tableName := scope.TableName()
  1100. quotedTableName := scope.QuotedTableName()
  1101. if !scope.Dialect().HasTable(tableName) {
  1102. scope.createTable()
  1103. } else {
  1104. for _, field := range scope.GetModelStruct().StructFields {
  1105. if !scope.Dialect().HasColumn(tableName, field.DBName) {
  1106. if field.IsNormal {
  1107. sqlTag := scope.Dialect().DataTypeOf(field)
  1108. scope.Raw(fmt.Sprintf("ALTER TABLE %v ADD %v %v;", quotedTableName, scope.Quote(field.DBName), sqlTag)).Exec()
  1109. }
  1110. }
  1111. scope.createJoinTable(field)
  1112. }
  1113. scope.autoIndex()
  1114. }
  1115. return scope
  1116. }
  1117. func (scope *Scope) autoIndex() *Scope {
  1118. var indexes = map[string][]string{}
  1119. var uniqueIndexes = map[string][]string{}
  1120. for _, field := range scope.GetStructFields() {
  1121. if name, ok := field.TagSettingsGet("INDEX"); ok {
  1122. names := strings.Split(name, ",")
  1123. for _, name := range names {
  1124. if name == "INDEX" || name == "" {
  1125. name = scope.Dialect().BuildKeyName("idx", scope.TableName(), field.DBName)
  1126. }
  1127. name, column := scope.Dialect().NormalizeIndexAndColumn(name, field.DBName)
  1128. indexes[name] = append(indexes[name], column)
  1129. }
  1130. }
  1131. if name, ok := field.TagSettingsGet("UNIQUE_INDEX"); ok {
  1132. names := strings.Split(name, ",")
  1133. for _, name := range names {
  1134. if name == "UNIQUE_INDEX" || name == "" {
  1135. name = scope.Dialect().BuildKeyName("uix", scope.TableName(), field.DBName)
  1136. }
  1137. name, column := scope.Dialect().NormalizeIndexAndColumn(name, field.DBName)
  1138. uniqueIndexes[name] = append(uniqueIndexes[name], column)
  1139. }
  1140. }
  1141. }
  1142. for name, columns := range indexes {
  1143. if db := scope.NewDB().Table(scope.TableName()).Model(scope.Value).AddIndex(name, columns...); db.Error != nil {
  1144. scope.db.AddError(db.Error)
  1145. }
  1146. }
  1147. for name, columns := range uniqueIndexes {
  1148. if db := scope.NewDB().Table(scope.TableName()).Model(scope.Value).AddUniqueIndex(name, columns...); db.Error != nil {
  1149. scope.db.AddError(db.Error)
  1150. }
  1151. }
  1152. return scope
  1153. }
  1154. func (scope *Scope) getColumnAsArray(columns []string, values ...interface{}) (results [][]interface{}) {
  1155. resultMap := make(map[string][]interface{})
  1156. for _, value := range values {
  1157. indirectValue := indirect(reflect.ValueOf(value))
  1158. switch indirectValue.Kind() {
  1159. case reflect.Slice:
  1160. for i := 0; i < indirectValue.Len(); i++ {
  1161. var result []interface{}
  1162. var object = indirect(indirectValue.Index(i))
  1163. var hasValue = false
  1164. for _, column := range columns {
  1165. field := object.FieldByName(column)
  1166. if hasValue || !isBlank(field) {
  1167. hasValue = true
  1168. }
  1169. result = append(result, field.Interface())
  1170. }
  1171. if hasValue {
  1172. h := fmt.Sprint(result...)
  1173. if _, exist := resultMap[h]; !exist {
  1174. resultMap[h] = result
  1175. }
  1176. }
  1177. }
  1178. case reflect.Struct:
  1179. var result []interface{}
  1180. var hasValue = false
  1181. for _, column := range columns {
  1182. field := indirectValue.FieldByName(column)
  1183. if hasValue || !isBlank(field) {
  1184. hasValue = true
  1185. }
  1186. result = append(result, field.Interface())
  1187. }
  1188. if hasValue {
  1189. h := fmt.Sprint(result...)
  1190. if _, exist := resultMap[h]; !exist {
  1191. resultMap[h] = result
  1192. }
  1193. }
  1194. }
  1195. }
  1196. for _, v := range resultMap {
  1197. results = append(results, v)
  1198. }
  1199. return
  1200. }
  1201. func (scope *Scope) getColumnAsScope(column string) *Scope {
  1202. indirectScopeValue := scope.IndirectValue()
  1203. switch indirectScopeValue.Kind() {
  1204. case reflect.Slice:
  1205. if fieldStruct, ok := scope.GetModelStruct().ModelType.FieldByName(column); ok {
  1206. fieldType := fieldStruct.Type
  1207. if fieldType.Kind() == reflect.Slice || fieldType.Kind() == reflect.Ptr {
  1208. fieldType = fieldType.Elem()
  1209. }
  1210. resultsMap := map[interface{}]bool{}
  1211. results := reflect.New(reflect.SliceOf(reflect.PtrTo(fieldType))).Elem()
  1212. for i := 0; i < indirectScopeValue.Len(); i++ {
  1213. result := indirect(indirect(indirectScopeValue.Index(i)).FieldByName(column))
  1214. if result.Kind() == reflect.Slice {
  1215. for j := 0; j < result.Len(); j++ {
  1216. if elem := result.Index(j); elem.CanAddr() && resultsMap[elem.Addr()] != true {
  1217. resultsMap[elem.Addr()] = true
  1218. results = reflect.Append(results, elem.Addr())
  1219. }
  1220. }
  1221. } else if result.CanAddr() && resultsMap[result.Addr()] != true {
  1222. resultsMap[result.Addr()] = true
  1223. results = reflect.Append(results, result.Addr())
  1224. }
  1225. }
  1226. return scope.New(results.Interface())
  1227. }
  1228. case reflect.Struct:
  1229. if field := indirectScopeValue.FieldByName(column); field.CanAddr() {
  1230. return scope.New(field.Addr().Interface())
  1231. }
  1232. }
  1233. return nil
  1234. }
  1235. func (scope *Scope) hasConditions() bool {
  1236. return !scope.PrimaryKeyZero() ||
  1237. len(scope.Search.whereConditions) > 0 ||
  1238. len(scope.Search.orConditions) > 0 ||
  1239. len(scope.Search.notConditions) > 0
  1240. }