scope.go 39 KB

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