I have a SQL function that is supposed to return 0 or 1 depending on whether a user activation was successful or not. I have the following two tables I need to interact with:
users {user_id, unique email, ...}
user_activation {activation_hash, unique email, ...}
The function is supposed to evaluate:
- Does the incoming hash match a row in user_activation?
- And does the corresponding email not already exist in the users table?
- Then insert a new user into users and delete the activation row and return 1, else return 0
Here is my function:
delimiter #
create function activate_user
(
p_activation_hash char(32)
)
returns int
deterministic
begin
if not exists (
select 1 from users u
inner join (
select email from user_activation where activation_hash = p_activation_hash
) ua
on u.email = ua.email
)
then
-- hash exists but email doesnt so add
insert into users (email, password_hash, first_name, last_name, company_name)
select email, password_hash, first_name, last_name, company_name
from user_activation
where activation_hash = p_activation_hash
and expiry_date > now();
-- delete the activation row(s)
delete low_priority from user_activation where activation_hash = p_activation_hash;
return 1;
end if;
return 0;
end #
delimiter ;
My problem is that the conditional always evaluates to true (although only 1 row is ever inserted into the user table even without the unique keyword).
Thanks.