Skip to content

Commit

Permalink
README: Add gotcha with db defaults (#99)
Browse files Browse the repository at this point in the history
  • Loading branch information
sjorsbranderhorst authored and olleolleolle committed Oct 30, 2019
1 parent a3c9f2d commit c2668f7
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,37 @@ r = MyRecord.new(id: 1, name: 'bar')
r.upsert!
```

### Gotcha with database defaults

When a table is defined with a database default for a field, this gotcha can occur when trying to explicitly upsert a record _to_ the default value (from a non-default value).

**Example**: a table called `hardwares` has a `prio` column with a default value.

┌─────────┬─────────┬───────┬
│ Column │ Type │Default│
├─────────┼─────────┼───────┼
│ id │ integer │ ...
│ prio │ integer │ 999

And `hardwares` has a record with a non-default value for `prio`. Say, the record with `id` 1 has a `prio` of `998`.

In this situation, upserting like:

```ruby
hw = { id: 1, prio: 999 }
Hardware.new(prio: hw[:prio]).upsert
```

will not mention the `prio` column in the `ON CONFLICT` clause, resulting in no update.

However, upserting like so:

```ruby
Hardware.upsert(prio: hw[:prio]).id
```

will indeed update the record in the database back to its default value, `999`.

### Conflict Clauses

It's possible to specify which columns should be used for the conflict clause. **These must comprise a unique index in Postgres.**
Expand Down

0 comments on commit c2668f7

Please sign in to comment.