PartialUpdate accepts a columns schema and a key-value map to update the record based on the given "id". Note: Trivial string, int and boolean type validations are performed here.
(ctx context.Context, id int64, schema map[string]reflect.Kind, attrs map[string]interface{})
| 161 | // update the record based on the given "id". |
| 162 | // Note: Trivial string, int and boolean type validations are performed here. |
| 163 | func (s *Service) PartialUpdate(ctx context.Context, id int64, schema map[string]reflect.Kind, attrs map[string]interface{}) (int, error) { |
| 164 | if len(schema) == 0 || len(attrs) == 0 { |
| 165 | return 0, nil |
| 166 | } |
| 167 | |
| 168 | var ( |
| 169 | keyLines []string |
| 170 | values []interface{} |
| 171 | ) |
| 172 | |
| 173 | for key, kind := range schema { |
| 174 | v, ok := attrs[key] |
| 175 | if !ok { |
| 176 | continue |
| 177 | } |
| 178 | |
| 179 | switch v.(type) { |
| 180 | case string: |
| 181 | if kind != reflect.String { |
| 182 | return 0, ErrUnprocessable |
| 183 | } |
| 184 | case int: |
| 185 | if kind != reflect.Int { |
| 186 | return 0, ErrUnprocessable |
| 187 | } |
| 188 | case bool: |
| 189 | if kind != reflect.Bool { |
| 190 | return 0, ErrUnprocessable |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | keyLines = append(keyLines, fmt.Sprintf("%s = ?", key)) |
| 195 | values = append(values, v) |
| 196 | } |
| 197 | |
| 198 | if len(values) == 0 { |
| 199 | return 0, nil |
| 200 | } |
| 201 | |
| 202 | q := fmt.Sprintf("UPDATE %s SET %s WHERE %s = ?;", |
| 203 | s.rec.TableName(), strings.Join(keyLines, ", "), s.rec.PrimaryKey()) |
| 204 | |
| 205 | res, err := s.DB().Exec(ctx, q, append(values, id)...) |
| 206 | if err != nil { |
| 207 | return 0, err |
| 208 | } |
| 209 | |
| 210 | n := GetAffectedRows(res) |
| 211 | return n, nil |
| 212 | } |
| 213 | |
| 214 | // GetAffectedRows returns the number of affected rows after |
| 215 | // a DELETE or UPDATE operation. |
nothing calls this directly
no test coverage detected