SET DEFAULT ROLE

SET DEFAULT ROLE 语句默认设置将特定角色应用于用户。因此,用户不必执行 SET ROLE <rolename>SET ROLE ALL 语句,也可以自动具有与角色相关联的权限。

语法图

SetDefaultRoleStmt:

SetDefaultRoleStmt

SetDefaultRoleOpt:

SetDefaultRoleOpt

RolenameList:

RolenameList

UsernameList:

UsernameList

示例

创建新角色 analyticsteam 和新用户 jennifer

  1. $ mysql -uroot
  2. CREATE ROLE analyticsteam;
  3. Query OK, 0 rows affected (0.02 sec)
  4. GRANT SELECT ON test.* TO analyticsteam;
  5. Query OK, 0 rows affected (0.02 sec)
  6. CREATE USER jennifer;
  7. Query OK, 0 rows affected (0.01 sec)
  8. GRANT analyticsteam TO jennifer;
  9. Query OK, 0 rows affected (0.01 sec)

需要注意的是,默认情况下,用户 jennifer 需要执行 SET ROLE analyticsteam 语句才能使用与角色相关联的权限:

  1. $ mysql -ujennifer
  2. SHOW GRANTS;
  3. +---------------------------------------------+
  4. | Grants for User |
  5. +---------------------------------------------+
  6. | GRANT USAGE ON *.* TO 'jennifer'@'%' |
  7. | GRANT 'analyticsteam'@'%' TO 'jennifer'@'%' |
  8. +---------------------------------------------+
  9. 2 rows in set (0.00 sec)
  10. SHOW TABLES in test;
  11. ERROR 1044 (42000): Access denied for user 'jennifer'@'%' to database 'test'
  12. SET ROLE analyticsteam;
  13. Query OK, 0 rows affected (0.00 sec)
  14. SHOW GRANTS;
  15. +---------------------------------------------+
  16. | Grants for User |
  17. +---------------------------------------------+
  18. | GRANT USAGE ON *.* TO 'jennifer'@'%' |
  19. | GRANT Select ON test.* TO 'jennifer'@'%' |
  20. | GRANT 'analyticsteam'@'%' TO 'jennifer'@'%' |
  21. +---------------------------------------------+
  22. 3 rows in set (0.00 sec)
  23. SHOW TABLES IN test;
  24. +----------------+
  25. | Tables_in_test |
  26. +----------------+
  27. | t1 |
  28. +----------------+
  29. 1 row in set (0.00 sec)

执行 SET DEFAULT ROLE 语句将用户 jennifer 与某一角色相关联,这样该用户无需执行 SET ROLE 语句就能拥有与角色相关联的权限。

  1. $ mysql -uroot
  2. SET DEFAULT ROLE analyticsteam TO jennifer;
  3. Query OK, 0 rows affected (0.02 sec)
  1. $ mysql -ujennifer
  2. SHOW GRANTS;
  3. +---------------------------------------------+
  4. | Grants for User |
  5. +---------------------------------------------+
  6. | GRANT USAGE ON *.* TO 'jennifer'@'%' |
  7. | GRANT Select ON test.* TO 'jennifer'@'%' |
  8. | GRANT 'analyticsteam'@'%' TO 'jennifer'@'%' |
  9. +---------------------------------------------+
  10. 3 rows in set (0.00 sec)
  11. SHOW TABLES IN test;
  12. +----------------+
  13. | Tables_in_test |
  14. +----------------+
  15. | t1 |
  16. +----------------+
  17. 1 row in set (0.00 sec)

SET DEFAULT ROLE 语句不会自动将相关角色授予 (GRANT) 用户。若尝试为 jennifer 尚未被授予的角色执行 SET DEFAULT ROLE 语句会导致以下错误:

  1. SET DEFAULT ROLE analyticsteam TO jennifer;
  2. ERROR 3530 (HY000): `analyticsteam`@`%` is is not granted to jennifer@%

MySQL 兼容性

SET DEFAULT ROLE 语句与 MySQL 8.0 的角色功能完全兼容。如发现任何兼容性差异,请在 GitHub 上提交 issue

另请参阅