scope.go 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421
  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 {
  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. if scope.Search.raw {
  737. scope.Raw(scope.CombinedConditionSql())
  738. } else {
  739. scope.Raw(fmt.Sprintf("SELECT %v FROM %v %v", scope.selectSQL(), scope.QuotedTableName(), scope.CombinedConditionSql()))
  740. }
  741. return
  742. }
  743. func (scope *Scope) inlineCondition(values ...interface{}) *Scope {
  744. if len(values) > 0 {
  745. scope.Search.Where(values[0], values[1:]...)
  746. }
  747. return scope
  748. }
  749. func (scope *Scope) callCallbacks(funcs []*func(s *Scope)) *Scope {
  750. defer func() {
  751. if err := recover(); err != nil {
  752. if db, ok := scope.db.db.(sqlTx); ok {
  753. db.Rollback()
  754. }
  755. panic(err)
  756. }
  757. }()
  758. for _, f := range funcs {
  759. (*f)(scope)
  760. if scope.skipLeft {
  761. break
  762. }
  763. }
  764. return scope
  765. }
  766. func convertInterfaceToMap(values interface{}, withIgnoredField bool, db *DB) map[string]interface{} {
  767. var attrs = map[string]interface{}{}
  768. switch value := values.(type) {
  769. case map[string]interface{}:
  770. return value
  771. case []interface{}:
  772. for _, v := range value {
  773. for key, value := range convertInterfaceToMap(v, withIgnoredField, db) {
  774. attrs[key] = value
  775. }
  776. }
  777. case interface{}:
  778. reflectValue := reflect.ValueOf(values)
  779. switch reflectValue.Kind() {
  780. case reflect.Map:
  781. for _, key := range reflectValue.MapKeys() {
  782. attrs[ToColumnName(key.Interface().(string))] = reflectValue.MapIndex(key).Interface()
  783. }
  784. default:
  785. for _, field := range (&Scope{Value: values, db: db}).Fields() {
  786. if !field.IsBlank && (withIgnoredField || !field.IsIgnored) {
  787. attrs[field.DBName] = field.Field.Interface()
  788. }
  789. }
  790. }
  791. }
  792. return attrs
  793. }
  794. func (scope *Scope) updatedAttrsWithValues(value interface{}) (results map[string]interface{}, hasUpdate bool) {
  795. if scope.IndirectValue().Kind() != reflect.Struct {
  796. return convertInterfaceToMap(value, false, scope.db), true
  797. }
  798. results = map[string]interface{}{}
  799. for key, value := range convertInterfaceToMap(value, true, scope.db) {
  800. if field, ok := scope.FieldByName(key); ok && scope.changeableField(field) {
  801. if _, ok := value.(*SqlExpr); ok {
  802. hasUpdate = true
  803. results[field.DBName] = value
  804. } else {
  805. err := field.Set(value)
  806. if field.IsNormal && !field.IsIgnored {
  807. hasUpdate = true
  808. if err == ErrUnaddressable {
  809. results[field.DBName] = value
  810. } else {
  811. results[field.DBName] = field.Field.Interface()
  812. }
  813. }
  814. }
  815. }
  816. }
  817. return
  818. }
  819. func (scope *Scope) row() *sql.Row {
  820. defer scope.trace(NowFunc())
  821. result := &RowQueryResult{}
  822. scope.InstanceSet("row_query_result", result)
  823. scope.callCallbacks(scope.db.parent.callbacks.rowQueries)
  824. return result.Row
  825. }
  826. func (scope *Scope) rows() (*sql.Rows, error) {
  827. defer scope.trace(NowFunc())
  828. result := &RowsQueryResult{}
  829. scope.InstanceSet("row_query_result", result)
  830. scope.callCallbacks(scope.db.parent.callbacks.rowQueries)
  831. return result.Rows, result.Error
  832. }
  833. func (scope *Scope) initialize() *Scope {
  834. for _, clause := range scope.Search.whereConditions {
  835. scope.updatedAttrsWithValues(clause["query"])
  836. }
  837. scope.updatedAttrsWithValues(scope.Search.initAttrs)
  838. scope.updatedAttrsWithValues(scope.Search.assignAttrs)
  839. return scope
  840. }
  841. func (scope *Scope) isQueryForColumn(query interface{}, column string) bool {
  842. queryStr := strings.ToLower(fmt.Sprint(query))
  843. if queryStr == column {
  844. return true
  845. }
  846. if strings.HasSuffix(queryStr, "as "+column) {
  847. return true
  848. }
  849. if strings.HasSuffix(queryStr, "as "+scope.Quote(column)) {
  850. return true
  851. }
  852. return false
  853. }
  854. func (scope *Scope) pluck(column string, value interface{}) *Scope {
  855. dest := reflect.Indirect(reflect.ValueOf(value))
  856. if dest.Kind() != reflect.Slice {
  857. scope.Err(fmt.Errorf("results should be a slice, not %s", dest.Kind()))
  858. return scope
  859. }
  860. if dest.Len() > 0 {
  861. dest.Set(reflect.Zero(dest.Type()))
  862. }
  863. if query, ok := scope.Search.selects["query"]; !ok || !scope.isQueryForColumn(query, column) {
  864. scope.Search.Select(column)
  865. }
  866. rows, err := scope.rows()
  867. if scope.Err(err) == nil {
  868. defer rows.Close()
  869. for rows.Next() {
  870. elem := reflect.New(dest.Type().Elem()).Interface()
  871. scope.Err(rows.Scan(elem))
  872. dest.Set(reflect.Append(dest, reflect.ValueOf(elem).Elem()))
  873. }
  874. if err := rows.Err(); err != nil {
  875. scope.Err(err)
  876. }
  877. }
  878. return scope
  879. }
  880. func (scope *Scope) count(value interface{}) *Scope {
  881. if query, ok := scope.Search.selects["query"]; !ok || !countingQueryRegexp.MatchString(fmt.Sprint(query)) {
  882. if len(scope.Search.group) != 0 {
  883. if len(scope.Search.havingConditions) != 0 {
  884. scope.prepareQuerySQL()
  885. scope.Search = &search{}
  886. scope.Search.Select("count(*)")
  887. scope.Search.Table(fmt.Sprintf("( %s ) AS count_table", scope.SQL))
  888. } else {
  889. scope.Search.Select("count(*) FROM ( SELECT count(*) as name ")
  890. scope.Search.group += " ) AS count_table"
  891. }
  892. } else {
  893. scope.Search.Select("count(*)")
  894. }
  895. }
  896. scope.Search.ignoreOrderQuery = true
  897. scope.Err(scope.row().Scan(value))
  898. return scope
  899. }
  900. func (scope *Scope) typeName() string {
  901. typ := scope.IndirectValue().Type()
  902. for typ.Kind() == reflect.Slice || typ.Kind() == reflect.Ptr {
  903. typ = typ.Elem()
  904. }
  905. return typ.Name()
  906. }
  907. // trace print sql log
  908. func (scope *Scope) trace(t time.Time) {
  909. if len(scope.SQL) > 0 {
  910. scope.db.slog(scope.SQL, t, scope.SQLVars...)
  911. }
  912. }
  913. func (scope *Scope) changeableField(field *Field) bool {
  914. if selectAttrs := scope.SelectAttrs(); len(selectAttrs) > 0 {
  915. for _, attr := range selectAttrs {
  916. if field.Name == attr || field.DBName == attr {
  917. return true
  918. }
  919. }
  920. return false
  921. }
  922. for _, attr := range scope.OmitAttrs() {
  923. if field.Name == attr || field.DBName == attr {
  924. return false
  925. }
  926. }
  927. return true
  928. }
  929. func (scope *Scope) related(value interface{}, foreignKeys ...string) *Scope {
  930. toScope := scope.db.NewScope(value)
  931. tx := scope.db.Set("gorm:association:source", scope.Value)
  932. for _, foreignKey := range append(foreignKeys, toScope.typeName()+"Id", scope.typeName()+"Id") {
  933. fromField, _ := scope.FieldByName(foreignKey)
  934. toField, _ := toScope.FieldByName(foreignKey)
  935. if fromField != nil {
  936. if relationship := fromField.Relationship; relationship != nil {
  937. if relationship.Kind == "many_to_many" {
  938. joinTableHandler := relationship.JoinTableHandler
  939. scope.Err(joinTableHandler.JoinWith(joinTableHandler, tx, scope.Value).Find(value).Error)
  940. } else if relationship.Kind == "belongs_to" {
  941. for idx, foreignKey := range relationship.ForeignDBNames {
  942. if field, ok := scope.FieldByName(foreignKey); ok {
  943. tx = tx.Where(fmt.Sprintf("%v = ?", scope.Quote(relationship.AssociationForeignDBNames[idx])), field.Field.Interface())
  944. }
  945. }
  946. scope.Err(tx.Find(value).Error)
  947. } else if relationship.Kind == "has_many" || relationship.Kind == "has_one" {
  948. for idx, foreignKey := range relationship.ForeignDBNames {
  949. if field, ok := scope.FieldByName(relationship.AssociationForeignDBNames[idx]); ok {
  950. tx = tx.Where(fmt.Sprintf("%v = ?", scope.Quote(foreignKey)), field.Field.Interface())
  951. }
  952. }
  953. if relationship.PolymorphicType != "" {
  954. tx = tx.Where(fmt.Sprintf("%v = ?", scope.Quote(relationship.PolymorphicDBName)), relationship.PolymorphicValue)
  955. }
  956. scope.Err(tx.Find(value).Error)
  957. }
  958. } else {
  959. sql := fmt.Sprintf("%v = ?", scope.Quote(toScope.PrimaryKey()))
  960. scope.Err(tx.Where(sql, fromField.Field.Interface()).Find(value).Error)
  961. }
  962. return scope
  963. } else if toField != nil {
  964. sql := fmt.Sprintf("%v = ?", scope.Quote(toField.DBName))
  965. scope.Err(tx.Where(sql, scope.PrimaryKeyValue()).Find(value).Error)
  966. return scope
  967. }
  968. }
  969. scope.Err(fmt.Errorf("invalid association %v", foreignKeys))
  970. return scope
  971. }
  972. // getTableOptions return the table options string or an empty string if the table options does not exist
  973. func (scope *Scope) getTableOptions() string {
  974. tableOptions, ok := scope.Get("gorm:table_options")
  975. if !ok {
  976. return ""
  977. }
  978. return " " + tableOptions.(string)
  979. }
  980. func (scope *Scope) createJoinTable(field *StructField) {
  981. if relationship := field.Relationship; relationship != nil && relationship.JoinTableHandler != nil {
  982. joinTableHandler := relationship.JoinTableHandler
  983. joinTable := joinTableHandler.Table(scope.db)
  984. if !scope.Dialect().HasTable(joinTable) {
  985. toScope := &Scope{Value: reflect.New(field.Struct.Type).Interface()}
  986. var sqlTypes, primaryKeys []string
  987. for idx, fieldName := range relationship.ForeignFieldNames {
  988. if field, ok := scope.FieldByName(fieldName); ok {
  989. foreignKeyStruct := field.clone()
  990. foreignKeyStruct.IsPrimaryKey = false
  991. foreignKeyStruct.TagSettingsSet("IS_JOINTABLE_FOREIGNKEY", "true")
  992. foreignKeyStruct.TagSettingsDelete("AUTO_INCREMENT")
  993. sqlTypes = append(sqlTypes, scope.Quote(relationship.ForeignDBNames[idx])+" "+scope.Dialect().DataTypeOf(foreignKeyStruct))
  994. primaryKeys = append(primaryKeys, scope.Quote(relationship.ForeignDBNames[idx]))
  995. }
  996. }
  997. for idx, fieldName := range relationship.AssociationForeignFieldNames {
  998. if field, ok := toScope.FieldByName(fieldName); ok {
  999. foreignKeyStruct := field.clone()
  1000. foreignKeyStruct.IsPrimaryKey = false
  1001. foreignKeyStruct.TagSettingsSet("IS_JOINTABLE_FOREIGNKEY", "true")
  1002. foreignKeyStruct.TagSettingsDelete("AUTO_INCREMENT")
  1003. sqlTypes = append(sqlTypes, scope.Quote(relationship.AssociationForeignDBNames[idx])+" "+scope.Dialect().DataTypeOf(foreignKeyStruct))
  1004. primaryKeys = append(primaryKeys, scope.Quote(relationship.AssociationForeignDBNames[idx]))
  1005. }
  1006. }
  1007. 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)
  1008. }
  1009. scope.NewDB().Table(joinTable).AutoMigrate(joinTableHandler)
  1010. }
  1011. }
  1012. func (scope *Scope) createTable() *Scope {
  1013. var tags []string
  1014. var primaryKeys []string
  1015. var primaryKeyInColumnType = false
  1016. for _, field := range scope.GetModelStruct().StructFields {
  1017. if field.IsNormal {
  1018. sqlTag := scope.Dialect().DataTypeOf(field)
  1019. // Check if the primary key constraint was specified as
  1020. // part of the column type. If so, we can only support
  1021. // one column as the primary key.
  1022. if strings.Contains(strings.ToLower(sqlTag), "primary key") {
  1023. primaryKeyInColumnType = true
  1024. }
  1025. tags = append(tags, scope.Quote(field.DBName)+" "+sqlTag)
  1026. }
  1027. if field.IsPrimaryKey {
  1028. primaryKeys = append(primaryKeys, scope.Quote(field.DBName))
  1029. }
  1030. scope.createJoinTable(field)
  1031. }
  1032. var primaryKeyStr string
  1033. if len(primaryKeys) > 0 && !primaryKeyInColumnType {
  1034. primaryKeyStr = fmt.Sprintf(", PRIMARY KEY (%v)", strings.Join(primaryKeys, ","))
  1035. }
  1036. scope.Raw(fmt.Sprintf("CREATE TABLE %v (%v %v)%s", scope.QuotedTableName(), strings.Join(tags, ","), primaryKeyStr, scope.getTableOptions())).Exec()
  1037. scope.autoIndex()
  1038. return scope
  1039. }
  1040. func (scope *Scope) dropTable() *Scope {
  1041. scope.Raw(fmt.Sprintf("DROP TABLE %v", scope.QuotedTableName())).Exec()
  1042. return scope
  1043. }
  1044. func (scope *Scope) modifyColumn(column string, typ string) {
  1045. scope.db.AddError(scope.Dialect().ModifyColumn(scope.QuotedTableName(), scope.Quote(column), typ))
  1046. }
  1047. func (scope *Scope) dropColumn(column string) {
  1048. scope.Raw(fmt.Sprintf("ALTER TABLE %v DROP COLUMN %v", scope.QuotedTableName(), scope.Quote(column))).Exec()
  1049. }
  1050. func (scope *Scope) addIndex(unique bool, indexName string, column ...string) {
  1051. if scope.Dialect().HasIndex(scope.TableName(), indexName) {
  1052. return
  1053. }
  1054. var columns []string
  1055. for _, name := range column {
  1056. columns = append(columns, scope.quoteIfPossible(name))
  1057. }
  1058. sqlCreate := "CREATE INDEX"
  1059. if unique {
  1060. sqlCreate = "CREATE UNIQUE INDEX"
  1061. }
  1062. scope.Raw(fmt.Sprintf("%s %v ON %v(%v) %v", sqlCreate, indexName, scope.QuotedTableName(), strings.Join(columns, ", "), scope.whereSQL())).Exec()
  1063. }
  1064. func (scope *Scope) addForeignKey(field string, dest string, onDelete string, onUpdate string) {
  1065. // Compatible with old generated key
  1066. keyName := scope.Dialect().BuildKeyName(scope.TableName(), field, dest, "foreign")
  1067. if scope.Dialect().HasForeignKey(scope.TableName(), keyName) {
  1068. return
  1069. }
  1070. var query = `ALTER TABLE %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s ON DELETE %s ON UPDATE %s;`
  1071. scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), scope.quoteIfPossible(keyName), scope.quoteIfPossible(field), dest, onDelete, onUpdate)).Exec()
  1072. }
  1073. func (scope *Scope) removeForeignKey(field string, dest string) {
  1074. keyName := scope.Dialect().BuildKeyName(scope.TableName(), field, dest, "foreign")
  1075. if !scope.Dialect().HasForeignKey(scope.TableName(), keyName) {
  1076. return
  1077. }
  1078. var mysql mysql
  1079. var query string
  1080. if scope.Dialect().GetName() == mysql.GetName() {
  1081. query = `ALTER TABLE %s DROP FOREIGN KEY %s;`
  1082. } else {
  1083. query = `ALTER TABLE %s DROP CONSTRAINT %s;`
  1084. }
  1085. scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), scope.quoteIfPossible(keyName))).Exec()
  1086. }
  1087. func (scope *Scope) removeIndex(indexName string) {
  1088. scope.Dialect().RemoveIndex(scope.TableName(), indexName)
  1089. }
  1090. func (scope *Scope) autoMigrate() *Scope {
  1091. tableName := scope.TableName()
  1092. quotedTableName := scope.QuotedTableName()
  1093. if !scope.Dialect().HasTable(tableName) {
  1094. scope.createTable()
  1095. } else {
  1096. for _, field := range scope.GetModelStruct().StructFields {
  1097. if !scope.Dialect().HasColumn(tableName, field.DBName) {
  1098. if field.IsNormal {
  1099. sqlTag := scope.Dialect().DataTypeOf(field)
  1100. scope.Raw(fmt.Sprintf("ALTER TABLE %v ADD %v %v;", quotedTableName, scope.Quote(field.DBName), sqlTag)).Exec()
  1101. }
  1102. }
  1103. scope.createJoinTable(field)
  1104. }
  1105. scope.autoIndex()
  1106. }
  1107. return scope
  1108. }
  1109. func (scope *Scope) autoIndex() *Scope {
  1110. var indexes = map[string][]string{}
  1111. var uniqueIndexes = map[string][]string{}
  1112. for _, field := range scope.GetStructFields() {
  1113. if name, ok := field.TagSettingsGet("INDEX"); ok {
  1114. names := strings.Split(name, ",")
  1115. for _, name := range names {
  1116. if name == "INDEX" || name == "" {
  1117. name = scope.Dialect().BuildKeyName("idx", scope.TableName(), field.DBName)
  1118. }
  1119. name, column := scope.Dialect().NormalizeIndexAndColumn(name, field.DBName)
  1120. indexes[name] = append(indexes[name], column)
  1121. }
  1122. }
  1123. if name, ok := field.TagSettingsGet("UNIQUE_INDEX"); ok {
  1124. names := strings.Split(name, ",")
  1125. for _, name := range names {
  1126. if name == "UNIQUE_INDEX" || name == "" {
  1127. name = scope.Dialect().BuildKeyName("uix", scope.TableName(), field.DBName)
  1128. }
  1129. name, column := scope.Dialect().NormalizeIndexAndColumn(name, field.DBName)
  1130. uniqueIndexes[name] = append(uniqueIndexes[name], column)
  1131. }
  1132. }
  1133. }
  1134. for name, columns := range indexes {
  1135. if db := scope.NewDB().Table(scope.TableName()).Model(scope.Value).AddIndex(name, columns...); db.Error != nil {
  1136. scope.db.AddError(db.Error)
  1137. }
  1138. }
  1139. for name, columns := range uniqueIndexes {
  1140. if db := scope.NewDB().Table(scope.TableName()).Model(scope.Value).AddUniqueIndex(name, columns...); db.Error != nil {
  1141. scope.db.AddError(db.Error)
  1142. }
  1143. }
  1144. return scope
  1145. }
  1146. func (scope *Scope) getColumnAsArray(columns []string, values ...interface{}) (results [][]interface{}) {
  1147. resultMap := make(map[string][]interface{})
  1148. for _, value := range values {
  1149. indirectValue := indirect(reflect.ValueOf(value))
  1150. switch indirectValue.Kind() {
  1151. case reflect.Slice:
  1152. for i := 0; i < indirectValue.Len(); i++ {
  1153. var result []interface{}
  1154. var object = indirect(indirectValue.Index(i))
  1155. var hasValue = false
  1156. for _, column := range columns {
  1157. field := object.FieldByName(column)
  1158. if hasValue || !isBlank(field) {
  1159. hasValue = true
  1160. }
  1161. result = append(result, field.Interface())
  1162. }
  1163. if hasValue {
  1164. h := fmt.Sprint(result...)
  1165. if _, exist := resultMap[h]; !exist {
  1166. resultMap[h] = result
  1167. }
  1168. }
  1169. }
  1170. case reflect.Struct:
  1171. var result []interface{}
  1172. var hasValue = false
  1173. for _, column := range columns {
  1174. field := indirectValue.FieldByName(column)
  1175. if hasValue || !isBlank(field) {
  1176. hasValue = true
  1177. }
  1178. result = append(result, field.Interface())
  1179. }
  1180. if hasValue {
  1181. h := fmt.Sprint(result...)
  1182. if _, exist := resultMap[h]; !exist {
  1183. resultMap[h] = result
  1184. }
  1185. }
  1186. }
  1187. }
  1188. for _, v := range resultMap {
  1189. results = append(results, v)
  1190. }
  1191. return
  1192. }
  1193. func (scope *Scope) getColumnAsScope(column string) *Scope {
  1194. indirectScopeValue := scope.IndirectValue()
  1195. switch indirectScopeValue.Kind() {
  1196. case reflect.Slice:
  1197. if fieldStruct, ok := scope.GetModelStruct().ModelType.FieldByName(column); ok {
  1198. fieldType := fieldStruct.Type
  1199. if fieldType.Kind() == reflect.Slice || fieldType.Kind() == reflect.Ptr {
  1200. fieldType = fieldType.Elem()
  1201. }
  1202. resultsMap := map[interface{}]bool{}
  1203. results := reflect.New(reflect.SliceOf(reflect.PtrTo(fieldType))).Elem()
  1204. for i := 0; i < indirectScopeValue.Len(); i++ {
  1205. result := indirect(indirect(indirectScopeValue.Index(i)).FieldByName(column))
  1206. if result.Kind() == reflect.Slice {
  1207. for j := 0; j < result.Len(); j++ {
  1208. if elem := result.Index(j); elem.CanAddr() && resultsMap[elem.Addr()] != true {
  1209. resultsMap[elem.Addr()] = true
  1210. results = reflect.Append(results, elem.Addr())
  1211. }
  1212. }
  1213. } else if result.CanAddr() && resultsMap[result.Addr()] != true {
  1214. resultsMap[result.Addr()] = true
  1215. results = reflect.Append(results, result.Addr())
  1216. }
  1217. }
  1218. return scope.New(results.Interface())
  1219. }
  1220. case reflect.Struct:
  1221. if field := indirectScopeValue.FieldByName(column); field.CanAddr() {
  1222. return scope.New(field.Addr().Interface())
  1223. }
  1224. }
  1225. return nil
  1226. }
  1227. func (scope *Scope) hasConditions() bool {
  1228. return !scope.PrimaryKeyZero() ||
  1229. len(scope.Search.whereConditions) > 0 ||
  1230. len(scope.Search.orConditions) > 0 ||
  1231. len(scope.Search.notConditions) > 0
  1232. }