define profiles::sql::postgres::grant ( String $username, String $privilege, Enum['SCHEMA', 'DATABASE'] $type = 'DATABASE', Optional[String] $dbname = undef, Optional[String] $schema = undef, ) { if $type == 'DATABASE' and $dbname == undef { fail('The dbname parameter must be provided when type is DATABASE') } if $type == 'SCHEMA' and ($dbname == undef or $schema == undef) { fail('Both dbname and schema parameters must be provided when type is SCHEMA') } $command = $type ? { 'DATABASE' => "GRANT ${privilege} ON DATABASE ${dbname} TO ${username}", 'SCHEMA' => "GRANT ${privilege} ON SCHEMA ${schema} TO ${username}", } $unless = $type ? { 'DATABASE' => "SELECT 1 FROM pg_roles r WHERE r.rolname='${username}' AND has_database_privilege('${username}', '${dbname}', '${privilege}')", # lint:ignore:140chars 'SCHEMA' => undef, } postgresql_psql { "grant_${privilege}_on_${type}_${dbname}_${schema}_to_${username}": command => $command, unless => $unless, db => $dbname, } }