(kiteProt *protocol.Kite, value *kontrolprotocol.RegisterValue)
| 241 | } |
| 242 | |
| 243 | func (p *Postgres) Upsert(kiteProt *protocol.Kite, value *kontrolprotocol.RegisterValue) (err error) { |
| 244 | // check that the incoming URL is valid to prevent malformed input |
| 245 | _, err = url.Parse(value.URL) |
| 246 | if err != nil { |
| 247 | return err |
| 248 | } |
| 249 | |
| 250 | if value.KeyID == "" { |
| 251 | return errors.New("postgres: keyId is empty. Aborting upsert") |
| 252 | } |
| 253 | |
| 254 | // we are going to try an UPDATE, if it's not successful we are going to |
| 255 | // INSERT the document, all ine one single transaction |
| 256 | tx, err := p.DB.Begin() |
| 257 | if err != nil { |
| 258 | return err |
| 259 | } |
| 260 | |
| 261 | defer func() { |
| 262 | if err != nil { |
| 263 | err = tx.Rollback() |
| 264 | } else { |
| 265 | // it calls Rollback inside if it fails again :) |
| 266 | err = tx.Commit() |
| 267 | } |
| 268 | }() |
| 269 | |
| 270 | res, err := tx.Exec(`UPDATE kite.kite SET url = $1, key_id = $3, updated_at = (now() at time zone 'utc') WHERE id = $2`, |
| 271 | value.URL, kiteProt.ID, value.KeyID) |
| 272 | if err != nil { |
| 273 | return err |
| 274 | } |
| 275 | |
| 276 | rowAffected, err := res.RowsAffected() |
| 277 | if err != nil { |
| 278 | return err |
| 279 | } |
| 280 | |
| 281 | // we got an update! so this was successful, just return without an error |
| 282 | if rowAffected != 0 { |
| 283 | return nil |
| 284 | } |
| 285 | |
| 286 | insertSQL, args, err := insertKiteQuery(kiteProt, value.URL, value.KeyID) |
| 287 | if err != nil { |
| 288 | return err |
| 289 | } |
| 290 | |
| 291 | _, err = tx.Exec(insertSQL, args...) |
| 292 | return err |
| 293 | } |
| 294 | |
| 295 | func (p *Postgres) Add(kiteProt *protocol.Kite, value *kontrolprotocol.RegisterValue) error { |
| 296 | // check that the incoming URL is valid to prevent malformed input |
nothing calls this directly
no test coverage detected