GormConvertString creates correct gorm.Queries for field + string value
(db *gorm.DB, neq bool, field string, values ...string)
| 29 | |
| 30 | // GormConvertString creates correct gorm.Queries for field + string value |
| 31 | func GormConvertString(db *gorm.DB, neq bool, field string, values ...string) *gorm.DB { |
| 32 | |
| 33 | if len(values) > 1 { |
| 34 | var dedup []interface{} |
| 35 | already := make(map[string]struct{}) |
| 36 | |
| 37 | for _, s := range values { |
| 38 | if _, f := already[s]; f { |
| 39 | continue |
| 40 | } |
| 41 | dedup = append(dedup, s) |
| 42 | already[s] = struct{}{} |
| 43 | } |
| 44 | |
| 45 | if len(dedup) == 1 { |
| 46 | if neq { |
| 47 | db = db.Not(map[string]interface{}{field: dedup[0]}) |
| 48 | } else { |
| 49 | db = db.Where(map[string]interface{}{field: dedup[0]}) |
| 50 | } |
| 51 | } else { |
| 52 | cl := clause.IN{Column: field, Values: dedup} |
| 53 | if neq { |
| 54 | db = db.Not(cl) |
| 55 | } else { |
| 56 | db = db.Where(cl) |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | } else if len(values) == 1 { |
| 61 | v := values[0] |
| 62 | var cl interface{} |
| 63 | if strings.Contains(v, "*") { |
| 64 | val := strings.Replace(v, "*", "%", -1) |
| 65 | if db.Name() == "postgres" { |
| 66 | cl = ILike{Column: field, Value: val} |
| 67 | } else { |
| 68 | cl = clause.Like{Column: field, Value: val} |
| 69 | } |
| 70 | } else { |
| 71 | cl = clause.Eq{Column: field, Value: v} |
| 72 | } |
| 73 | if neq { |
| 74 | db = db.Not(cl) |
| 75 | } else { |
| 76 | db = db.Where(cl) |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | return db |
| 81 | } |
| 82 | |
| 83 | type ILike struct { |
| 84 | Column interface{} |