I have a table in PostgreSQL that looks like this
create table item_counts {
item string,
view_count int}
I would like to use the table to keep track of occurrences of item, incrementing the counts as necessary. Initially the table is unpopulated, so a new value is inserted iff it is observed for the first time, otherwise the view_count is increased. Speed and multitasking are both concerns.
I know I can do
rows_affected = execute("update item_counts set view_count = view_count + 1
where item = ?")
if rows_affected == 0:
execute("insert into item_counts ...")
However, this is unsafe in a multithreaded environment, so I would have to wrap it into a transaction. This would in turn decrease the speed, since a commit would occur after each insert/update.
Any suggestions how to do it in a clean and efficient way?