-- Get dataset from access key and user account key
DELIMITER \\
DROP PROCEDURE IF EXISTS dataset_get_by_access_key\\
CREATE PROCEDURE dataset_get_by_access_key(in i_user_account_key char(32), in i_access_key char(32))
BEGIN

select
    ds.*
from
    dataset ds 
        join dataset_permissions p on p.dataset_access_key = ds.access_key
where
    ds.access_key = i_access_key and
    (p.user_access_key = i_account_key or p.group_access_key = i_account_key) and
    p.can_read = true
union
select
    ds.*
from
    dataset ds
        join dataset_permissions p on p.dataset_access_key = ds.access_key
            join users_groups_jct jct on jct.group_key = p.group_access_key
where
    jct.user_account_key = i_account_key and
    ds.access_key = i_access_key and
    p.can_read = true;


END\\
DELIMITER ;