I have a table like this:
create table if not exists features (
username text not null,
feature text not null,
attributes text[] not null,
primary key(username, feature)
);
I want to insert a new feature for a user but only if they have less than 2 features currently in the table. I also want to update the feature's attributes if the user already has that feature in the table.
This is what I've got so far:
with f (username, feature, attributes, fcount) as (
values (
'bob', 'dashboard', '{"theme=dark"}'::text[],
(select count(*) from features where username = 'bob' and feature = 'dashboard')
)
)
insert into features (
username,
feature,
attributes
)
select username, feature, attributes
from f
where fcount < 2
on conflict (username, feature)
do update set attributes = excluded.attributes
;
When I run this three times with different feature names it adds three rows instead of 2.
username feature attributes
bob dashboard theme=dark
bob dashboard1 theme=dark
bob dashboard2 theme=dark
How can I achieve this? Is it possible to do this with a single insert query or do I need to use a transaction and multiple queries?