Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment column value using Slick for postgres

I need to add 1 to column value for a record in postgres table based on some filter. Suppose I have two fields id and count and I want to increment count value by 1.

So far I have

MyTable.filter(_.id === someId).map(_.count).update(??)

Not sure how if it is possible to use update to do so. Any suggestion?

like image 284
αƞjiβ Avatar asked Jan 20 '16 23:01

αƞjiβ


People also ask

How do I increment a column in PostgreSQL?

First, create a sequence object and set the next value generated by the sequence as the default value for the column. Second, add a NOT NULL constraint to the id column because a sequence always generates an integer, which is a non-null value.

Does PostgreSQL have auto increment?

PostgreSQL has the data types smallserial, serial and bigserial; these are not true types, but merely a notational convenience for creating unique identifier columns. These are similar to AUTO_INCREMENT property supported by some other databases.


1 Answers

Currently, this is not supported in Slick - https://github.com/slick/slick/issues/497. You could:

  1. Use a plain SQL query; or
  2. Retrieve the current "count" value in a separate query, increment, then do the update, using the transactionally modifier to force the use of one transaction. Though, depending on the level of transaction isolation in your database, the use of a transaction might not be enough to avoid race conditions.
like image 77
Morgan Avatar answered Sep 28 '22 06:09

Morgan