In a game using PostgreSQL 9.3 as backend I am trying to limit the number of games played by a user per week.
I have prepared an SQL Fiddle, but unfortunately it doesn't work.
My (test, not production) code is here:
create table pref_users (
id varchar(32) primary key,
last_ip inet
);
create table pref_match (
id varchar(32) references pref_users on delete cascade,
completed integer default 0 check (completed >= 0),
yw char(7) default to_char(current_timestamp, 'IYYY-IW'),
primary key(id, yw)
);
And here is a stored procedure with which I try to find the number of games played this week:
create or replace function pref_get_user_info(
IN _id varchar,
IN _last_ip inet,
OUT games_this_week integer
) as $BODY$
begin
select sum(completed)
into games_this_week
from pref_match where
(id = _id or
id in (select id from pref_users where last_ip=_last_ip)) and
yw=to_char(current_timestamp, 'IYYY-IW');
end;
$BODY$ language plpgsql;
With this condition:
(id = _id or
id in (select id from pref_users where last_ip=_last_ip))
I am trying to catch users who will try to cheat and join the game with a different player id
but from the same IP-address.
But I am worried, that sometimes I will get doubled number of completed games - because in the above condition first the 1st part will match: id = _id
and then the 2nd part id in (...)
- and this will give me the number of games 2 times.
Is there please any cure for that?
I need to "detect" when an id
is used twice in the above condition.